!
! The below module was made in reference to 
! https://ufcpp.net/study/algorithm/col_heap.html
!
module heappq
  
  implicit none
  integer(8),allocatable :: hp(:)

contains 
subroutine heapinit(n)
  
  integer, intent(in) :: n

  allocate( hp(n) ); hp = 0

end subroutine heapinit

subroutine heappush( newnp, newn )
  
  integer, intent(in)    :: newn
  integer(8), intent(in)    :: newnp
  integer :: i,ln
  integer(8) :: tmp
 
  ln = newn
  hp(ln) = newnp
  
  do while ( ln /= 1 )
    i = ln/2
    if ( hp(i) < hp(ln) ) then
      tmp    = hp(ln) 
      hp(ln) = hp(i) 
      hp(i)  = tmp 
    end if
    ln = i
  end do

end subroutine heappush
  
end module heappq

program main
  
  use heappq

  implicit none

  integer    :: n, k, i, j
  integer(8),allocatable :: h(:)
  
  read(*,*) n,k
  allocate( h(n) )
  read(*,*) h

  if ( k >= n ) then 
    print*, "0"
  else if ( k == 0 ) then
    print*, sum(h)
  else

    call heapinit(n) 

    do i = 1, n
      call heappush( h(i), i )
    end do

    h = hp
    print*, h
    
    if( mod( k, 2 ) == 0 ) then
      print*, sum( h(1:k) ) 
    else
      if( h(k) >= h(k+1)) then
        print*, sum( h(1:k) ) 
      else
        print*, sum( h(1:k+1) ) - h(k) 
      end if
    end if

  end if

end program main
