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

get_number(A, B) :-
    get_number(A),
    get_number(B).

get_number(A, B, C) :-
    get_number(A, B),
    get_number(C).

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

get_chars(Xs) :-
    get_string(S),
    string_chars(S, Xs).

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

put_numbers([]).
put_numbers([X|Xs]) :-
    writeln(X),
    put_numbers(Xs).

/* memo
    code(int)
    string_code(1, S, C), (C: code)
    char_code(X, Y) (X: char, Y: code)
    string_chars(S, S2) (S: string, S2: [char])
    to_lower(C, C2) (C: char? C2: code?)
    length(S, L),
    sub_string

    f(0, [], []).
    f(Z, [X|Xs], [Y|Ys]) :- X = Y, f(Z1, Xs, Ys), Z is Z1 + 1.
    f(Z, [_|Xs], [_|Ys]) :- f(Z, Xs, Ys).

    match: =, \=

    numeric: <,=<, >, >= (eval)
    lexicographically: @<. @=<, @>, @>=
    value?: =:=, =\= (eval)
    identical: ==, \==

    between(L,U,X): L <= X <= U
    nth0(I, Xs, Y), nth1(I, Xs, Y): (Xs,Y) -> I, (I, Xs) -> Y 

    sort(Key, Order, List, Sorted): Keyは通常0?, Orderは=なしが重複削除，=は重複保持
    \+ P(X) : not P(X)
*/

f(_, _, [], []).

f(YI, [X|Xs], [Y|Ys], [Z|Zs]) :- 
    YI = X,
    Z is Y + 1,
    YI2 is YI + 1,
    f(YI2, Xs, Ys, Zs), !.

f(YI, [X|Xs], [Y|Ys], [Z|Zs]) :-
    Z is Y,
    YI2 is YI + 1,
    f(YI2, [X|Xs], Ys, Zs).

countX([], _, 0) :- !.
countX([Y|Ys], X, N) :- Y = X, countX(Ys, X, N2), N is N2 + 1, !.
countX([_|Ys], X, N) :- countX(Ys, X, N).

g(0, Xs) :-
    countX(Xs, 0, Z),
    writeln(Z).

g(N, Xs) :-
    get_number(D),
    get_numbers(D, Ys),
    f(1, Ys, Xs, Xs2),
    N2 is N - 1,
    g(N2, Xs2).

repX(0, _, []) :- !.
repX(N, X, [Y|Ys]) :- N2 is N - 1, Y is X, repX(N2, X, Ys).

main :-
    get_number(N, K),
    repX(N, 0, Xs),
    % put_numbers(Xs).
    g(K, Xs).
