:- use_module(library(clpfd)).
:- use_module(library(yall)).
:- use_module(library(apply)).

main :-
    read_num(N),
    read_num(M),
    read_num(K),
    read_n_num_list(N, A),
    read_n_num_list(M, B),

    find_answer(N, M, K, A, B),
    halt.



find_answer(N, M, K, A, B) :-

        X in 0 .. N,
        Y in 0 .. M,
        findall([X, Y], (label([X, Y]), satisfy(X, Y, K, A, B)), XY),
        
        convlist([[X, Y], Z]>>(Z is X + Y),
                 XY,
                 Sums),
        max_member(Ans, Sums),

        write(Ans),
        nl.

satisfy(X, Y, K, A, B) :-

        length(RA, X),
        length(RB, Y),
        
        prefix(RA, A),
        prefix(RB, B),

        sum_list(RA, ReadATime),
        sum_list(RB, ReadBTime),

        0 =< ReadATime, ReadATime =< K,
        0 =< ReadBTime, ReadBTime =< K,
        K >= ReadATime + ReadBTime.


read_n_num_list(Num, List) :-
    read_n_num_list_aux(Num, [], List),
    !.
read_n_num_list_aux(0, List, List).
read_n_num_list_aux(Num, Old, Accum) :-
    read_num(NewItem),
    NewNum is Num - 1,
    append(Old, [NewItem], NewList),
    read_n_num_list_aux(NewNum, NewList, Accum).


read_str(S) :-
        read_string(current_input, ' \n', '', _, S).
 
read_num(N) :-
	read_str(S),
	number_string(N, S).


:- main.
