Problem:


Score : 300 points

Problem Statement

We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.

It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).

Consider the following action:

Choose a desk with a book remaining, read the topmost book on that desk, and remove it from the desk.

How many books can we read at most by repeating this action so that it takes us at most K minutes in total? We ignore the time it takes to do anything other than reading.

Constraints

1 \leq N, M \leq 200000

1 \leq K \leq 10^9

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K
A_1 A_2 \ldots A_N
B_1 B_2 \ldots B_M

Output

Print an integer representing the maximum number of books that can be read.

Sample Input 1

3 4 240
60 90 120
80 150 80 150

Sample Output 1

3

In this case, it takes us 60, 90, 120 minutes to read the 1-st, 2-nd, 3-rd books from the top on Desk A, and 80, 150, 80, 150 minutes to read the 1-st, 2-nd, 3-rd, 4-th books from the top on Desk B, respectively.

We can read three books in 230 minutes, as shown below, and this is the maximum number of books we can read within 240 minutes.

Read the topmost book on Desk A in 60 minutes, and remove that book from the desk.

Read the topmost book on Desk B in 80 minutes, and remove that book from the desk.

Read the topmost book on Desk A in 90 minutes, and remove that book from the desk.

Sample Input 2

3 4 730
60 90 120
80 150 80 150

Sample Output 2

7

Sample Input 3

5 4 1
1000000000 1000000000 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000

Sample Output 3

0

Watch out for integer overflows.



Sample input:
3 4 240
60 90 120
80 150 80 150


Sample output:
3

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
import sys
import re
from collections import deque, defaultdict
from itertools import combinations, combinations_with_replacement
import bisect
from math import factorial, sqrt, log, ceil, floor
sys.setrecursionlimit(1000000)


def main():
    #N, M = map(int, input().split())
    #N, K = map(int, input().split())
    #ps = list(map(int, input().split()))

    N, M, K = map(int, input().split())
    As = list(map(int, input().split()))
    Bs = list(map(int, input().split()))

    B_sums = []
    B = 0
    for b in Bs:
        B += b
        B_sums.append(B)

    max_num = 0
    A = None
    for i in range(len(As)+1):
        if i == 0:
            A = 0
        else:
            A += As.pop(0)
        k = A
        if k > K:
            break
        num = i

        remain = K - k
        pos = bisect.bisect(B_sums, remain)
        num += pos
        max_num = max([max_num, num])

    print(max_num)



if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n,m,k = map(int, input().split())
a_lst = [int(i) for i in input().split() if int(i) <= k]
b_lst = [int(i) for i in input().split() if int(i) <= k]

sum_lst = sorted(a_lst + b_lst)
count = 0
time = 0

for i in range(len(a_lst)+len(b_lst)):
    if time >= k:
        break
    count += 1
    time += sum_lst.pop(0)
if time > k:
    print(count-1)
else:
    print(count)

Submission status: Time Limit Exceeded

Solution code:
import math
from queue import Queue

n, m, k = map(int, input().split(" "))
aLi = list(map(int, input().split(" ")))
bLi = list(map(int, input().split(" ")))

if aLi[0] > k and bLi[0] > k:
    print(0)
    exit()

q = Queue()
q.put({"s": aLi[0], "na": 1, "nb": 0})
q.put({"s": bLi[0], "na": 0, "nb": 1})

while True:
    cp = q.get()
    _sum = cp["s"]
    nextA = cp["na"]
    nextB = cp["nb"]

    if _sum >= k:
        print(nextA + nextB)
        exit()

    if nextA + 1 == n and nextB + 1 == m:
        print(n + m)
        exit()

    if n > nextA:
        q.put({"s": _sum + aLi[nextA], "na": nextA + 1, "nb": nextB})

    if m > nextB:
        q.put({"s": _sum + bLi[nextB], "na": nextA, "nb": nextB + 1})

Submission status: Time Limit Exceeded

Solution code:
n,m,k = map(int, input().split())

from collections import deque

an = list(map(int, input().split()))

bn = list(map(int, input().split()))

an = [0] + an
bn = bn

vMax = 10**9+10

import itertools

accum_a = [0]
accum_b = [0]



candidate = []


for b_i in range(0,len(bn)):
    i_ = accum_b[-1] + bn[b_i]
    if i_ > k:
        break
    accum_b.append(i_)

accum_b.reverse()

countMax = 0
for a_i in range(0,len(an)):


    sumCandidate = accum_a[-1] + an[a_i]
    if sumCandidate > k:
        break
    accum_a.append(sumCandidate)

    rest = k - sumCandidate

    bIndex = 0
    for j, accB in enumerate(accum_b):
        if accB <= rest:
            bIndex = len(accum_b) - 1 - j
            break


    countMax = max(countMax, a_i + bIndex)



print(countMax)

Submission status: Time Limit Exceeded

Solution code:
N, M, K =map(int, input().split())
A = list(map(int, input().split()))
A.insert(0,0)
B = list(map(int, input().split()))  
B.insert(0,0)
len_A = len(A)
len_B = len(B)
dp = [[0]*len_B for _ in range(len_A)]
ans = 0
for i in range(len_A):
    for j in range(len_B):
        if i == 0 and j == 0:
            dp[i][j] = 0
        elif i == 0:
            dp[i][j] = dp[i][j-1] + B[j]
            if dp[i][j] <= K and ans < i+j :
                ans = i+j
        else:
            dp[i][j] = dp[i-1][j] + A[i]
            if dp[i][j] <= K and ans < i+j :
                ans = i+j

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, M, K = map(int, input().split())

A = list(map(int, input().split()))

B = list(map(int, input().split()))

a = 0
b = 0

ans = 0

dp_a = {}
dp_b = {}

s = 0
for i, a in enumerate(A):
    s += a
    if s > K:
        break
    dp_a[s] = i+1

s = 0
for i, b in enumerate(B):
    s += b
    if s > K:
        break
    dp_b[s] = i+1

new = {}
for b, s in dp_b.items():
    for k, v in dp_a.items():
        if k+b > K:
            break
        if k+b in new:
            new[k+b] = min(new[k+b], v + s)
        else:
            new[k+b] = v +s

ans = 0

for k in range(K, -1, -1):
    if k in new:
        ans = max(ans, new[k])
        break
    if k in dp_b:
        ans = max(ans, dp_b[k])
        break
    if k in dp_a:
        ans = max(ans, dp_a[k])
        break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,m,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
atimemat=[sum(a[0:i+1]) for i in range(len(a))]
btimemat=[sum(b[0:i+1]) for i in range(len(b))]
ans=0
for i in range(len(a)):
    if atimemat[i]>k:
        break
    else:
        ans=i+1
        for j in range(len(b)):
            if atimemat[i]+btimemat[j]<=k:
                if ans<=i+j+2:
                    ans=i+j+2
            else:
                break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
k = [int(x) for x in input().split()][2]
ab = [int(x) for x in input().split()] + [int(x) for x in input().split()]

O = 0
ab.sort()

while k > 0:
    if ab:
        k -= ab[0]
        if k < 0:
            break
        ab.pop(0)
        O +=1

print(O)

Submission status: Time Limit Exceeded

Solution code:
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
i = 0
j = 0
count = 0
for i in range(N+1):
	for j in range(M+1):
		if sum(A[:i]) + sum(B[:j]) <= K:
			tmp = i + j
			count = max(tmp, count)
		else:
			break
print(count)

Submission status: Time Limit Exceeded

Solution code:
NMK = [int(i) for i in input().split(' ')]
A = [int(a) for a in input().split(' ')]
B = [int(a) for a in input().split(' ')]

# Aの最高冊数
A_max = 0
Ksum = 0
for i in range(NMK[0]):
    Ksum += A[i]
    if Ksum <= NMK[2]:
        A_max+=1
    else:
        break

# Bの最高冊数
B_max = 0
Ksum = 0
for i in range(NMK[1]):
    Ksum += B[i]
    if Ksum <= NMK[2]:
        B_max += 1
    else:
        break

books_max = max(A_max,B_max)
for i in range(A_max+1):
    Ksum = 0
    for j in range(B_max+1):
        for_s = sum(A[0:i])+sum(B[0:j])
        if i + j > books_max:
            if for_s <= NMK[2]:
                books_max = i+j

print(books_max)

Submission status: Time Limit Exceeded

Solution code:
a,b,c = map(int,input().split())
d = list(map(int,input().split()))
e = list(map(int,input().split()))
count = 0

while c > 0:
  if(len(d) > 0):
    if((c-d[0]) >= 0):
      c = c - d[0]
      del d[0]
      count += 1
  if(len(e) > 0):
    if((c-e[0]) >= 0):
      c = c - e[0]
      del e[0]
      count += 1

print(count)

Submission status: Time Limit Exceeded

Solution code:
import sys
from typing import Callable, List, NoReturn, Set, Tuple


def main() -> NoReturn:
    readline: Callable[[], str] = sys.stdin.readline

    n, m, k = map(int, readline().rstrip().split())  # type: int, int, int
    a: List[int] = []
    for a_i in readline().rstrip().split():
        a.append(int(a_i))
    b: List[int] = []
    for b_i in readline().rstrip().split():
        b.append(int(b_i))

    stack: List[Tuple] = [(0, 0, 0)]
    searched: Set[Tuple] = set()
    results: List[Tuple] = []

    while stack:
        current = stack.pop()
        result_flag = True
        if current not in searched:
            next_a, next_b, total_time = current
            if next_b < m and total_time + b[next_b] <= k:
                stack.append((next_a, next_b + 1, total_time + b[next_b]))
                result_flag = False
            if next_a < n and total_time + a[next_a] <= k:
                stack.append((next_a + 1, next_b, total_time + a[next_a]))
                result_flag = False
            if result_flag:
                results.append(current)
            searched.add(current)

    print(max(map(lambda t: t[0] + t[1], results)))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

a_depth = 0
tmp = 0
for i in range(n):
    if tmp+a[i] <= k:
        tmp += a[i]
        a_depth += 1
    else:
        break
b_depth = 0
tmp = 0
for i in range(m):
    if tmp+b[i] <= k:
        tmp += b[i]
        b_depth += 1
    else:
        break

ans = 0
total = 0
tmp_ans = 0

for i in range(a_depth):
    for j in range(a_depth-i):
        if total+a[j] <= k:
            total += a[j]
            tmp_ans += 1
    
    for j in range(b_depth):
        if total+b[j] <= k:
            total += b[j]
            tmp_ans += 1
    ans = max(ans, tmp_ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: UTF-8

import numpy as np

N, M, K = np.fromstring(input(), sep=" ", dtype=np.int64)
A = np.fromstring("0 " + input(), sep=" ", dtype=np.int64)
B = np.fromstring("0 " + input(), sep=" ", dtype=np.int64)

aa = np.add.accumulate(A)
bb = np.add.accumulate(B)

# print(aa)
# print(bb)

base = 0
for i in range(N):
    if aa[i] <= K:
        base += 1
    else:
        break

while True:
    for i in range(max(N+1,M+1)):
        if not ((base - i) < N+1 and i < M+1):
            # print("continue", base-i, i)
            continue
        # print(base-i, i,(aa[base-i] + bb[i]))
        if (aa[base-i] + bb[i]) <= K:
            base += 1
            break
    else:
        break
print(base-1)
# cc = np.add.outer(aa, bb)
# print(cc)
# print(base)
#
# dd = cc <= K
#
# num = np.add.outer(np.arange(N+1), np.arange(M+1))
# # print(dd.shape)
# # print(num.shape)
# print(np.max(num[dd]))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2147483647)
input = sys.stdin.readline

if __name__ == '__main__':
  n,m,k=map(int,input().strip("\n").split())
  A=list(map(int,input().strip("\n").split()))
  B=list(map(int,input().strip("\n").split()))
#  A.append(10**9+1)
#  B.append(10**9+1)

  def dfs(a,b,k,s):
    if k<0:
      return s-1
    if k==0:
      return s
    if a<n:
      ansA=dfs(a+1,b,k-A[a],s+1)
    else:
      ansA=s
    if b<m:
      ansB=dfs(a,b+1,k-B[b],s+1)
    else:
      ansB=s
    return max(ansA,ansB)

  ans=dfs(0,0,k,0)
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,m,k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
result=0
count= 0
List2 = []
result2=0
count2 = 0
List3 = []

if a > b:
    List = a
    L = b
else:
    List = b
    L = a
for e in List:
    result += e
    if result > k:
        result = result - e
        break
    count+=1
    List2.append(e)
for e in L:
    result2 += e
    if result2 > k:
        result2 = result2 - e
        break
    count2+=1
    List3.append(e)

if result > result2:
    List = List2
    L = List3
else:
    List = List3
    L = List2

if count2 > count:
    result = result2
    count = count2   

t = 0
for i in range(len(List)):
    t += List[i]
    t2 = 0
    for j in range(len(L)):
        t2 += L[j]
        if t+t2 >= result and t+t2 <= k and count < i+j+2:
            result = t+t2
            count = i+j+2
print(count)

Submission status: Time Limit Exceeded

Solution code:
n,m,k = list(map(int,input().split()))
a = list(map(int,input().split()))
b = list(map(int,input().split()))
a_i,b_i = 0,0
read_list =[]

if a[0]>k and b[0]>k:
  print(0)

else:
  for num_a in range(n+1):
    break_b=1
    sum_a = sum(a[0:num_a])
    if sum_a >= k:
      read_list.append(num_a)
      break_a=1
      break
    for num_b in range(m):
      sum_a += b[num_b]
      if sum_a > k:
        break_b=0
        break
    read_list.append(num_a+num_b+break_b)

  print(max(read_list))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

AA = list(reversed(A))
BB = list(reversed(B))

rest = K
ans = 0

def dfs(cost, aindex, bindex, score):

    if K == cost:
        # print("1:", score, cost)
        return score
    elif K < cost:
        # print("2:", score, cost)
        return score - 1
        # return -1
    
    if aindex == N and bindex == M:
        # print("3:", score, cost)
        return score

    if aindex >= N:
        return dfs(cost + B[bindex], aindex, bindex+1, score + 1)
    
    elif bindex >= M:
        return dfs(cost + A[aindex], aindex+1, bindex, score + 1)

    else:
        return max(dfs(cost + A[aindex], aindex+1, bindex, score + 1), dfs(cost + B[bindex], aindex, bindex + 1, score + 1))

print(max(dfs(A[0], 1, 0, 1), dfs(B[0], 0, 1, 1)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def LI():
  return list(map(int,input().split()))

N,M,K = map(int,input().split())
A = LI()
B = LI()

res = 0
for i in range(N+1):
  for j in range(M+1):
    if sum(A[:i]) + sum(B[:j]) <= K:
      res = max(res, i+j)

print(res)

Submission status: Time Limit Exceeded

Solution code:
"""
N = list(map(int,input().split()))
S = [str(input()) for _ in range(N)]
S = [list(map(int,list(input()))) for _ in range(h)] 
print(*S,sep="")
"""

import sys
sys.setrecursionlimit(10**6)
input = lambda: sys.stdin.readline().rstrip()
inf = float("inf") # 無限

n,m,k = map(int,input().split())

nm = n + m

a = list(map(int,input().split()))
b = list(map(int,input().split()))

if sum(a)+sum(b) <= k:
    print(nm)
    exit()


answer = 0

for i in range(nm**2):
    count = 0
    times = 0
    a_temp = a[:]
    b_temp = b[:]
    for j in range(nm):
        if (i>>j)&1:
            if a_temp:
                times+= a_temp.pop(0)
            else:
                times+= b_temp.pop(0)
        else:
            if b_temp:
                times+= b_temp.pop(0)
            else:
                times+= a_temp.pop(0)
        if k<times:
            if answer < count:
                answer = count
            break
        count+=1
if answer < count:
    answer = count
print(answer)

Submission status: Time Limit Exceeded

Solution code:
n,m,k = map(int,input().split())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
import sys
sys.setrecursionlimit(10**6)
maxc = 0
a_i=0
b_i=0
def dfs(a_i,b_i,t,cnt):
    global maxc
    if(a_i==n and b_i==m):
        maxc = m+n
        return
    if(a_i==n):
        if((t+B[b_i])>k):
            if(cnt > maxc):
                maxc = cnt
            return
        dfs(a_i,b_i+1,t+B[b_i],cnt+1)
        return
    if(b_i==m):
        if((t+A[a_i])>k):
            if(cnt > maxc):
                maxc = cnt
            return
        dfs(a_i+1,b_i,t+A[a_i],cnt+1)
        return
    if((A[a_i]+t)<=k):
        dfs(a_i+1,b_i,A[a_i]+t,cnt+1)
    else:
        if(maxc < cnt):
            maxc = cnt
    if((B[b_i]+t)<=k):
        dfs(a_i,b_i+1,B[b_i]+t,cnt+1)
    else:
        if(maxc < cnt):
            maxc = cnt

        
dfs(0,0,0,0)
print(maxc)

Submission status: Time Limit Exceeded

Solution code:
import math
from queue import Queue

n, m, k = map(int, input().split(" "))
aLi = list(map(int, input().split(" ")))
bLi = list(map(int, input().split(" ")))

if aLi[0] > k and bLi[0] > k:
    print(0)
    exit()

q = Queue()
q.put({"s": aLi[0], "na": 1, "nb": 0})
q.put({"s": bLi[0], "na": 0, "nb": 1})

while True:
    cp = q.get()
    _sum = cp["s"]
    nextA = cp["na"]
    nextB = cp["nb"]

    if nextA + 1 == n and nextB + 1 == m:
        print(n + m)
        exit()

    if _sum >= k:
        print(nextA + nextB)
        exit()

    if n > nextA:
        q.put({"s": _sum + aLi[nextA], "na": nextA + 1, "nb": nextB})

    if m > nextB:
        q.put({"s": _sum + bLi[nextB], "na": nextA, "nb": nextB + 1})

Submission status: Time Limit Exceeded

Solution code:
N, M, K = map(int, input().split())

A = list(map(int, input().split()))

B = list(map(int, input().split()))

a = 0
b = 0

ans = 0

dp_a = {}
dp_b = {}

s = 0
for i, a in enumerate(A):
    s += a
    if s > K:
        break
    dp_a[s] = i+1

s = 0
for i, b in enumerate(B):
    s += b
    if s > K:
        break
    dp_b[s] = i+1

new = {}
for b, s in dp_b.items():
    for k, v in dp_a.items():
        if k+b > K:
            break
        if k+b in new:
            new[k+b] = min(new[k+b], v + s)
        else:
            new[k+b] = v +s

# newa = {}
# for i, a in enumerate(A):
#     s += a
#     if s > K:
#         break
#     for k, v in dp_b.items():
#         if k+s > K:
#             break
#         if k+s in newa:
#             newa[k+s] = min(newa[k+s], v + i+1)
#         else:
#             newa[k+s] = v + i+1

ans = 0
for k in range(K, -1, -1):
    if k in new:
        ans = max(ans, new[k])
    if k in dp_b:
        ans = max(ans, dp_b[k])
    if k in dp_a:
        ans = max(ans, dp_a[k])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

N, M, K = map(int, input().split())
tempA = [int(i) for i in input().split()]
tempB = [int(i) for i in input().split()]
A = [0] * (N+1)
for i in range(1, N+1):
    A[i] = A[i-1] + tempA[i-1]
B = [0] * (M+1)
for i in range(1, M+1):
    B[i] = B[i-1] + tempB[i-1]

ans = 0
for a in range(N+1):
    if A[a] > K:
        break
    for b in range(M+1):
        if A[a] + B[b] <= K:
            ans = max(ans, a+b)
        else:
            break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

cnt = 0
cnt_max = 0

t = 0

#aの本を全部読む場合を考える
#bを1冊ずつ増やしたときに最大になるかどうかを判定する

c = []

for i in a:
  t += i
  if t <= k:
    c.append(i)
    cnt += 1
  else:
    t -= i
    break

#print(c)
cnt_max = cnt
tmp_cnt = cnt

t_max = t

for i in range(len(c) + 1):
  if i == 0:
    pass
  else:
    t_max -= c[i-1]
    tmp_cnt -= 1
    
  #print(i, t_max, tmp_cnt)
  
  t = t_max
  cnt = tmp_cnt
  
  for j in b:
    t += j
    #print('j:', j, t)
    if t <= k:
      cnt += 1
      if cnt > cnt_max:
        cnt_max = cnt
        #print('cnt', cnt, 'max', cnt_max)
    else:
      break
      
print(cnt_max)

Submission status: Time Limit Exceeded

Solution code:
N,M,K=list(map(int,input().split()))
A=list(map(int,input().split()))
B=list(map(int,input().split()))
mini=0
count=0
if A[0]>K and B[0]>K:
    print(0)

else:
    while mini<K:
        if A==[] and B==[]:
            break
        elif A==[]:
            mini+=B[0]
            B.pop(0)
            count+=1
        elif B==[]:
            mini+=A[0]
            A.pop(0)
            count+=1
        elif A[0]>=B[0]:
            mini+=A[0]
            A.pop(0)
            count+=1
        else:
            mini+=B[0]
            B.pop(0)
            count+=1
    print(count)

Submission status: Time Limit Exceeded

Solution code:

N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

sA = sum(A)
sB = sum(B)

def countmax(A, N, K):
    sA_ = 0
    for i in range(N):
        sA_ += A[i]
        if sA_ > K:
            return i
    return N

# Dont need count
if sA + sB <= K:
    print(N + M)
    exit(0)

## Aの全読み VS Bの全読みにならない？
## Aの全読み
if sA <= K: # 全読み可
    AyomiA = N
    AyomiB = countmax(B, M, K - sA)
else:
    AyomiA = countmax(A, N, K)
    AyomiB = countmax(B, M, K-sum(A[:AyomiA]))

## Bの全読み
if sB <= K: # 全読み可
    ByomiB = M
    ByomiA = countmax(A, N, K - sB)
else:
    ByomiB = countmax(B, M, K)
    ByomiA = countmax(A, N, K-sum(B[:ByomiB]))

# Bでカウントする時
if AyomiA - ByomiA > ByomiB - AyomiB:
    count = 0
    for b in range(AyomiB, ByomiB + 1):
        count = max(count, b + countmax(A, N, K - sum(B[:b])))
else:
# Aでカウントする時
    count = 0
    for a in range(ByomiA, AyomiA + 1):
        count = max(count, a + countmax(B, M, K - sum(A[:a])))
         
print(count)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, M: int, K: int, A: "List[int]", B: "List[int]"):
    candidateA = []
    weightA = 0
    tmp_A = N
    for idx, a in enumerate(A):
        if weightA + a > K:
            tmp_A = idx
            break
        else:
            weightA += a
    candidateA = A[:tmp_A]
    max_count = current_count = len(candidateA)

    #candidateB = []
    weightB = 0
    terminated = False
    for b in B:
        if terminated == True and weightA + weightB > K:
            break

        if len(candidateA)==0 and weightA + weightB + b > K:
            break

        if weightA + weightB + b <= K:
            weightB += b
            #candidateB.append(b)
            current_count += 1

        elif terminated==False:
            while weightA + weightB + b > K:
                if len(candidateA)>0:
                    weightA -= candidateA.pop()
                    current_count -= 1
                else:
                    terminated=True

            if weightA + weightB + b <= K:
                weightB += b
                #candidateB.append(b)
                current_count += 1
        max_count = max(max_count, current_count)

    print(max_count)
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    B = [int(next(tokens)) for _ in range(M)]  # type: "List[int]"
    solve(N, M, K, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import itertools

N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

aa = [0] + list(itertools.accumulate(A))
bb = [0] + list(itertools.accumulate(B))

ans = 0
for i in range(N+1):
    tmp_K = K-aa[i]
    if tmp_K == 0:
        ans = max(ans, i)
    elif tmp_K < 0:
        continue

    if tmp_K >= bb[-1]:
        ans = max(ans, i+M)
        continue

    mn = 0
    mx = M
    while True:
        if mn == mx:
            if tmp_K >= bb[mn]:
                ans = max(ans, i+mn)
            break

        mid = (mn+mx//2)
        if bb[mid] <= tmp_K:
            if mn == mid:
                mn = mid+1
            else:
                mn = mid

        else:
            if mx == mid:
                mx = mid-1
            else:
                mx = mid
            if i+mx <= ans:
                break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
nmk = input('')
n = int(nmk.split(' ')[0])
m = int(nmk.split(' ')[1])
k = int(nmk.split(' ')[2])

alist = list(map(int,input().split()))
blist = list(map(int,input().split()))

l = (n+m)
t =k

max_read=0

for i in range(2**l):
    bag = ['A']*l
    for j in range(l):
        if ((i>>j)&1):
            bag[l-1-j]='B'
    if bag.count('A') == n and bag.count('B') == m:
        time=0
        read=0
        a=0
        b=0
        bag2=[]
        for item in bag:
            if item=='A':
                t = alist[a]
                bag2.append(t)
                time+=t
                a+=1
                if k>=time:
                    read+=1
                else:
                    break
            else:
                bag2.append(t)
                t = blist[b]
                time+=t
                b+=1
                if k>=time:
                    read+=1
                else:
                    break

#        print("{} {}/{} {}".format(i,time,k,bag2))

        if max_read < read:
            max_read = read

print(max_read)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,m,k = (int(x) for x in input().split())
a =np.array([int(x) for x in input().split()])
b =np.array([int(x) for x in input().split()])

count = 0
for i in range(n+1):
    for j in range(m+1):
        if np.sum(a[:i])+np.sum(b[:j]) > k:
            break
        if i+j>count:
            count = i+j
print(count)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def resolve():
    N, M, K = list(map(int, input().split()))
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))

    read = deque()
    w = 0

    if sum(A) + sum(B) <= K:
        print(len(A) + len(B))
        return

    while w <= K:        
        if len(A) == 0 and len(B) == 0:
            break

        if len(A) == 0:
            if w + B[0] <= K:
                read.append(B[0])
                w += B[0]
            B.pop(0)
            continue

        if len(B) == 0:
            if w + A[0] <= K:
                read.append(A[0])
                w += A[0]
            A.pop(0)
            continue

        if A[0] < B[0] or len(B) == 0:
            if w + A[0] <= K:
                read.append(A[0])
                w += A[0]
            A.pop(0)
        else:
            if w + B[0] <= K:
                read.append(B[0])
                w += B[0]
            B.pop(0)

    print(len(read))


resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys
x=input()
x0=x.split()
n=int(x0[0])
m=int(x0[1])
k=int(x0[2])
a=input()
b=input()
a0=[int(i) for i in a.split()]
b0=[int(i) for i in b.split()]
a=0
b=0
al=list([0])
bl=list([0])
for i in range(n):
    a=a+a0[i]
    if a>k:
        break
    al.append(a)
for i in range(m):
    b=b+b0[i]
    if b>k:
        break
    bl.append(b)
p=0
for i in range(len(al)):
    for l in range(len(bl)):
        if al[-i-1]+bl[-l-1]<=k:
            q=len(al)+len(bl)-i-l-2
            if p<q:
                p=q
    if al[-i-1]+bl[-1]<k:
        break
print(p)

Submission status: Time Limit Exceeded

Solution code:
n, m, k = map(int, input().split())
an= list(map(int, input().split()))
bm= list(map(int, input().split()))
an.insert(0,0)
bm.insert(0,0)
ans = 0
import numpy as np
cn = np.cumsum(an)
for i in range(n+1):
    x=cn[i]
    if k <x:
        break
    for j in range(m+1):
        x += bm[j]
        if k >= x and i+j > ans:
            ans = i+j
        elif k <x:
            break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
"""
N = list(map(int,input().split()))
S = [str(input()) for _ in range(N)]
S = [list(map(int,list(input()))) for _ in range(h)] 
print(*S,sep="")
"""

import sys
sys.setrecursionlimit(10**6)
input = lambda: sys.stdin.readline().rstrip()
inf = float("inf") # 無限

n,m,k = map(int,input().split())

nm = n + m

a = list(map(int,input().split()))
b = list(map(int,input().split()))

answer = 0

for i in range(nm**2):
    count = 0
    times = 0
    a_temp = a[:]
    b_temp = b[:]
    for j in range(nm):
        if (i>>j)&1:
            if a_temp:
                times+= a_temp.pop(0)
            else:
                times+= b_temp.pop(0)
        else:
            if b_temp:
                times+= b_temp.pop(0)
            else:
                times+= a_temp.pop(0)
        if k<times:
            if answer < count:
                answer = count
            break
        count+=1
if answer < count:
    answer = count
print(answer)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
import sys
import re
from collections import deque, defaultdict
from itertools import combinations, combinations_with_replacement
import bisect
from math import factorial, sqrt, log, ceil, floor
sys.setrecursionlimit(1000000)


def main():
    #N, M = map(int, input().split())
    #N, K = map(int, input().split())
    #ps = list(map(int, input().split()))

    N, M, K = map(int, input().split())
    As = list(map(int, input().split()))
    Bs = list(map(int, input().split()))

    max_num = 0
    A = None
    b_sum = sum(Bs)
    b_num = len(Bs)
    for i in range(len(As)+1):
        if i == 0:
            A = 0
        else:
            A += As.pop(0)
        k = A
        if k > K:
            break
        num = i
        k += b_sum
        b_itr = b_num + 1
        for j in range(b_itr):
            if k <= K:
                num += b_num
                max_num = max([max_num, num])
                break
            else:
                if Bs:
                    b = Bs.pop(-1)
                    k -= b
                    b_sum -= b
                    b_num -= 1

    print(max_num)



if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N,M,K=list(map(int,input().split()))
A=list(map(int,input().split()))
B=list(map(int,input().split()))
AA=[0]*(N+1)
BB=[0]*(M+1)
A3=0
B3=0
high=0
for i in range(0,N):
    A3+=A[i]
    AA[i+1]=A3
for j in range(0,M):
    B3+=B[j]
    BB[j+1]=B3
for i in range(0,N+1):
    for j in range(0,M+1):
        if AA[i]+BB[j]<=K and high<i+j:
            high=i+j
print(high)