module mod_radix_sort
  implicit none
  integer, private, parameter :: intkind = 4
  integer, private, parameter :: nbit = 8
  integer, private, parameter :: upper = lshift(1, nbit) - 1
contains
  subroutine radix_sort(a)
    integer(intkind), intent(inout) :: a(:)
    integer(intkind), allocatable :: queue(:, :)
    integer :: n, m, i, j, k, cnt(0:upper)
    n = size(a)
    m = 0
    do i = 0, 8 * intkind - 1, nbit
      cnt = 0
      do j = 1, n
        k = and(rshift(a(j), i), upper)
        cnt(k) = cnt(k) + 1
      end do
      m = max(m, maxval(cnt))
    end do
    allocate(queue(m, 0:upper))
    do i = 0, 8 * intkind - 1, nbit
      cnt = 0
      do j = 1, n
        k = and(rshift(a(j), i), upper)
        cnt(k) = cnt(k) + 1
        queue(cnt(k), k) = a(j)
      end do
      k = 0
      do j = 0, upper
        if (cnt(j) == 0) cycle
        a(k + 1:k + cnt(j)) = queue(1:cnt(j), j)
        k = k + cnt(j)
      end do
    end do
  end
end module mod_radix_sort
program chat_in_a_circle
  use mod_radix_sort
  implicit none
  integer :: n, a(200000) = 0, i
  integer(8) :: x = 0
  read(*,*) n
  read(*,*) a(1:n)
  call radix_sort(a(1:n))
  write(*,'(i0)') sum(int(a(2:n), 8))
end program chat_in_a_circle