    module m_sort
    !reference
    !https://qiita.com/cure_honey/items/29944920e8aff5651e41
      implicit none
    contains  
      recursive function iqsort(ix) result(ires)
        integer(16), allocatable :: ires(:)
        integer(16), intent(in)  :: ix(:)
        integer(16) :: k
        if (size(ix) <= 1) then 
          ires = ix
        else  
          k = ix(size(ix) / 2)
          ires = [iqsort(pack(ix, ix < k)), pack(ix, ix == k), iqsort(pack(ix, ix > k))] 
        end if
      end function iqsort  
    end module m_sort
      
      PROGRAM handshake
      USE m_sort
      IMPLICIT NONE
      integer(16) :: n,m
      integer(16),allocatable :: a(:),sumPow(:)
      integer(16) :: i
      
      read*,n,m
      allocate( a(n),sumPow(n*n) )
      read*,a(:)
      
      do i = 1,n
        sumPow((i-1)*n+1:i*n) = a(i) + a(1:n)
      end do
      sumPow = iqsort( sumPow )
      
      print*,sum(sumPow(n*n-m+1:n*n))
      
      END PROGRAM