get_string(String) :-
  current_input(Input),
  read_string(Input, ' \n', '', _, String).

get_number(Number) :-
  get_string(String),
  number_string(Number, String).

insert_sort(L1,L2) :-
        insert_sort(L1,[],L2).

insert_sort([],L,L).
insert_sort([A|R],L1,L) :-
        insert(A,L1,L2),
        insert_sort(R,L2,L).

insert(A,[],[A]).
insert(A,[B|R],[A,B|R]) :-
        A @=< B,!.
insert(A,[B|R1],[B|R2]) :-
        A @> B,
        insert(A,R1,R2).

get_numbers(0, []).
get_numbers(N, [X|Xs]) :-
  get_number(X),
  N1 is N - 1,
  get_numbers(N1, Xs).

get_k_nums(X, 0, 0).
get_k_nums([X|Xs], C, Sum) :-
  C1 is C - 1,
  get_k_nums(Xs, C1, Nextsum),
  Sum is Nextsum + X.

main :-
  get_number(N),
  get_number(K),
  get_numbers(N, A),
  insert_sort(A, B),
  get_k_nums(B, K, Ans),
  write(Ans).

:- main.
