Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

n = int(input())
p = [int(x) for x in input().split()]

ans = 0
seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
reserved = [[True for j in range(n)] for i in range(n)]

vec = [(-1, 0), (1, 0), (0, -1), (0, 1)]

for i in range(n**2):
    v = p[i]-1
    x, y = v//n, v % n
    reserved[x][y] = False
    ans += seat[x][y]
    q = [(x, y)]
    while q:
        x, y = q.pop()
        for dx, dy in vec:
            if 0 <= x+dx < n and 0 <= y+dy < n and seat[x+dx][y+dy] > seat[x][y] + reserved[x][y]:
                seat[x+dx][y+dy] = seat[x][y] + reserved[x][y]
                q.append((x+dx, y+dy))

print(ans)


### FIXED CODE ###

n = int(input())
p = [int(x) for x in input().split()]

ans = 0
seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
reserved = [[True for j in range(n)] for i in range(n)]

vec = [(-1, 0), (1, 0), (0, -1), (0, 1)]

for i in range(n**2):
    v = p[i]-1
    x, y = v//n, v % n
    reserved[x][y] = False
    ans += seat[x][y]
    q = [(x, y)]
    while q:
        x, y = q.pop()
        if 0 <= x+1 < n and 0 <= y < n and seat[x+1][y] > seat[x][y] + reserved[x][y]:
            seat[x+1][y] = seat[x][y] + reserved[x][y]
            q.append((x+1, y))
        if 0 <= x-1 < n and 0 <= y < n and seat[x-1][y] > seat[x][y] + reserved[x][y]:
            seat[x-1][y] = seat[x][y] + reserved[x][y]
            q.append((x-1, y))
        if 0 <= x < n and 0 <= y+1 < n and seat[x][y+1] > seat[x][y] + reserved[x][y]:
            seat[x][y+1] = seat[x][y] + reserved[x][y]
            q.append((x, y+1))
        if 0 <= x < n and 0 <= y-1 < n and seat[x][y-1] > seat[x][y] + reserved[x][y]:
            seat[x][y-1] = seat[x][y] + reserved[x][y]
            q.append((x, y-1))


print(ans)
### BUGGY CODE ###

R,G,B,N=map(int,input().split())
cnt=0
for r in range(0,N+1):#N//R+1):
    for g in range(0,N+1):#(N-r*R)//G+1):
        bunshi=N-r*R-g*G
        q,m=divmod(bunshi,B)
        if q<0:continue
        if m==0:cnt+=1
            
print(cnt)

### FIXED CODE ###

def main():
  r,g,b,n=map(int,input().split())
  cnt=0
  for i in range(n//r+1):
    for j in range((n-i*r)//g+1):
      tmp=r*i+g*j
      q,mod=divmod(n-tmp,b)
      if (q>=0 and mod==0):
        cnt+=1
  print(cnt)
  
main()
### BUGGY CODE ###

import sys

mod = 10**9 + 7
S = sys.stdin.readline().strip()

S = S[::-1]
ls = len(S)
dp = [0] * 13
dp[0] = 1
for i in range(ls):
    ndp = [0] * 13
    # print("S", S[i])
    for j in range(13):
        if dp[j] == 0:
            continue
        digit = pow(10, i, 13)
        if S[i] == "?":
            for k in range(10):
                r = k * digit + j
                r %= 13
                ndp[r] += dp[j]
                ndp[r] %= mod

        else:
            n = int(S[i])
            r = n * digit + j
            r %= 13
            ndp[r] += dp[j]
            ndp[r] %= mod

    # print(ndp)
    dp = ndp

print(dp[5])

### FIXED CODE ###

import sys

mod = 10**9 + 7
S = sys.stdin.readline().strip()

S = S[::-1]
ls = len(S)
dp = [0] * 13
dp[0] = 1
for i in range(ls):
    ndp = [0] * 13
    # print("S", S[i])
    for j in range(13):
        if dp[j] == 0:
            continue
        digit = pow(10, i, 13)
        if S[i] == "?":
            for k in range(10):
                r = k * digit + j
                r %= 13
                ndp[r] += dp[j]
                ndp[r] %= mod

        else:
            n = int(S[i])
            r = n * digit + j
            r %= 13
            ndp[r] += dp[j]
            ndp[r] %= mod

    # print(ndp)
    dp = ndp

print(dp[5])
### BUGGY CODE ###

def resolve():
    H = int(input())
    depth = 0
    monster = [2 ** depth]
    depth += 1

    while True:
        monster.append(2 ** depth)

        if H % 2 == 1:
            H = (H-1)/2
        else:
            H = H / 2
        depth += 1

        if H == 1:
            break

    print(sum(monster))

    return


resolve()

### FIXED CODE ###

def resolve():
    import sys
    sys.setrecursionlimit(1000000)
    H = int(input())

    def battle(n):
        if n == 1:
            return 1
        return battle(n // 2) * 2 + 1

    print(battle(H))

    return


resolve()
### BUGGY CODE ###

from collections import deque
INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))
def do():
    n,m=INTM()
    roots=[[0]*n for i in range(n)]
    visit=[0]*n
    visit[0]=1
    q=deque([0])
    for i in range(m):
        a,b=INTM()
        roots[a-1].append(b-1)
        roots[b-1].append(a-1)
    while q:
        temp=q.popleft()
        for root in roots[temp]:
            if visit[root]!=0:
                continue
            else:
                q.append(root)
                visit[root]=temp+1
    
    print('Yes')
    for i in visit[1:]:
        print(i)
        

                
if __name__ == '__main__':
    do()

### FIXED CODE ###

from collections import deque
INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))
def do():
    n,m=INTM()
    roots=[[]for i in range(n)]
    visit=[0]*n
    visit[0]=1
    q=deque([0])
    for i in range(m):
        a,b=INTM()
        roots[a-1].append(b-1)
        roots[b-1].append(a-1)
    while q:
        temp=q.popleft()
        for root in roots[temp]:
            if visit[root]!=0:
                continue
            else:
                q.append(root)
                visit[root]=temp+1
    
    print('Yes')
    for i in visit[1:]:
        print(i)
        

                
if __name__ == '__main__':
    do()
### BUGGY CODE ###

n, m = (int(i) for i in input().split())
a = [int(i) for i in input().split()]
a.sort()
for i in range(m):
    a.sort()
    a[n - 1] = a[n - 1] // 2
print(sum(a))

### FIXED CODE ###

import heapq
n, m = (int(i) for i in input().split())
a = [int(i) * (-1) for i in input().split()]
heapq.heapify(a)
for i in range(m):
    tmp_min = ((a[0] * (-1)) //2) * (-1)
    heapq.heappushpop(a,tmp_min)
print(abs(sum(a)))
### BUGGY CODE ###

n = int(input())
List = list(map(int, input().split()))
ans = 'YES'
for i in range(n - 1):
    for j in range(n - i - 1):
        if List[i] == List[i + j + 1]:
            ans = 'NO'
            break
    if ans == 'NO':
        break

print(ans)

### FIXED CODE ###

n = int(input())
List = list(map(int, input().split()))
Sorted = sorted(List)
ans = 'YES'
for i in range(n - 1):
    if Sorted[i] == Sorted[i + 1]:
        ans = 'NO'
        break

print(ans)
### BUGGY CODE ###

from heapq import heappush, heappop

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())

Ch -= 1
Cw -= 1
Dh -= 1
Dw -= 1

grid = []
for _ in range(H):
	grid.append(list(c == "." for c in input().strip()))

m = H * W + 1
smallests = [[m] * W for _ in range(H)]

queue = [(0, Cw, Ch)]
smallests[Ch][Cw] = 0

def calc():
	while queue:
		d, x, y = heappop(queue)
		if d == smallests[y][x]:
			for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
				tx = x + dx
				ty = y + dy
				if tx >= 0 and tx < W and ty >= 0 and ty < H:
					if grid[ty][tx] and d < smallests[ty][tx]:
						smallests[ty][tx] = d
						heappush(queue, (d, tx, ty))
			d += 1
			for tx in range(max(0, x - 2), min(W, x + 3)):
				for ty in range(max(0, y - 2), min(H, y + 3)):
					if grid[ty][tx] and d < smallests[ty][tx]:
						smallests[ty][tx] = d
						heappush(queue, (d, tx, ty))
	return smallests[Dh][Dw]

result = calc()
if result == m:
	print(-1)
else:
	print(result)


### FIXED CODE ###

from heapq import heappush, heappop

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())

Ch -= 1
Cw -= 1
Dh -= 1
Dw -= 1

grid = []
for _ in range(H):
	grid.append(list(c == "." for c in input().strip()))

m = H * W + 1
smallests = [[m] * W for _ in range(H)]

queue_move = [(0, Cw, Ch)]
queue_warp = [(0, Cw, Ch)]
smallests[Ch][Cw] = 0

def calc():
	while queue_move or queue_warp:
		if queue_move:
			d, x, y = heappop(queue_move)
			if d == smallests[y][x]:
				for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
					tx = x + dx
					ty = y + dy
					if tx >= 0 and tx < W and ty >= 0 and ty < H:
						if grid[ty][tx] and d < smallests[ty][tx]:
							smallests[ty][tx] = d
							heappush(queue_move, (d, tx, ty))
							heappush(queue_warp, (d, tx, ty))
		else:
			d, x, y = heappop(queue_warp)
			if d == smallests[y][x]:
				d += 1
				for tx in range(max(0, x - 2), min(W, x + 3)):
					for ty in range(max(0, y - 2), min(H, y + 3)):
						if grid[ty][tx] and d < smallests[ty][tx]:
							smallests[ty][tx] = d
							heappush(queue_move, (d, tx, ty))
							heappush(queue_warp, (d, tx, ty))
	return smallests[Dh][Dw]

result = calc()
if result == m:
	print(-1)
else:
	print(result)
### BUGGY CODE ###

n,k=map(int,input().split())
a=[1]+list(map(int,input().split()))
b=[]
for i in range(1,n):
  a[i+1]*=a[i]
for i in range(k,n+1):
  b+=[a[i]//a[i-k]]
for i in range(1,n-k+1):
  print(['No','Yes'][b[i]>b[i-1]])

### FIXED CODE ###

n,k=map(int,input().split())
a=list(map(int,input().split()))
for i in range(n-k):
  print(['No','Yes'][a[i+k]>a[i]])
### BUGGY CODE ###

from collections import deque

inf=float('inf')

h,w=map(int,input().split())
maze=[]
st=[]
for j in range(h):
  a=list(input())
  for i in range(w):
    if a[i]=='.':
      a[i]=inf
    if a[i]=='#':
      a[i]=0
      st.append([j,i])
  maze.append(a)
  
de=deque(st)

while de:
  v=de.popleft()
  sy,sx=v[0],v[1]
  for p in ([1,0],[0,1],[-1,0],[0,-1]):
    ny,nx=sy+p[0],sx+p[1]
    if 0<=ny<=h-1 and 0<=nx<=w-1 and maze[ny][nx]!=0:
      if maze[ny][nx]>maze[sy][sx]+1:
        maze[ny][nx]=maze[sy][sx]+1
        de.append([ny,nx])

ans=0
for g in range(h):
  for f in range(w):
    ans=max(maze[g][f],ans)

print(ans)

### FIXED CODE ###

from collections import deque

inf=float('inf')

h,w=map(int,input().split())
maze=[]
st=[]
for j in range(h):
  a=list(input())
  for i in range(w):
    if a[i]=='.':
      a[i]=inf
    if a[i]=='#':
      a[i]=0
      st.append([j,i])
  maze.append(a)
  
de=deque(st)

while de:
  v=de.popleft()
  sy,sx=v[0],v[1]
  for p in ([1,0],[0,1],[-1,0],[0,-1]):
    ny,nx=sy+p[0],sx+p[1]
    if 0<=ny<=h-1 and 0<=nx<=w-1 and maze[ny][nx]!=0:
      if maze[ny][nx]>maze[sy][sx]+1:
        maze[ny][nx]=maze[sy][sx]+1
        de.append([ny,nx])

ans=0
for g in range(h):
  for f in range(w):
    ans=max(maze[g][f],ans)

print(ans)
### BUGGY CODE ###

import sys
input = sys.stdin.readline

import math
def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

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

if m==0:
    cnt = 0
    steps = n
    for j in range(steps//2+1):
        if j == 0:
            cnt += 1
        else:
            seat = steps - j
            cnt += combinations_count(seat,j)
    print(cnt % (10**9+7))
    exit()

l = [-1]+[int(input())]
for i in range(m-1):
    a = int(input())
    if a == l[-1]+1:
        print(0)
        exit()
    l.append(a)
l.append(n+1)
# print(l)

ans = 1
for i in range(m+1):
    cnt = 0
    steps = l[i+1] - l[i] -2
    if steps == 0:
        continue
    for j in range(steps//2+1):
        if j == 0:
            cnt += 1
        else:
            seat = steps - j
            cnt += combinations_count(seat,j)
    ans *= cnt

print(ans % (10**9+7))

### FIXED CODE ###

import sys
input = sys.stdin.readline

n,m = map(int,input().split())
oks = [True]*(n+1)
for i in range(m):
    a = int(input())
    oks[a] = False

dp = [0]*(n+1)
dp[0] = 1
for i in range(n):
    for j in range(i+1,min(n,i+2)+1):
        if oks[j]:
            dp[j] += dp[i]
            dp[j] %= (10**9+7)
print(dp[n])
### BUGGY CODE ###

def solve():
    S = input()
    s = [c for c in S]
    Q = int(input())
    for i in range(Q):
        T = input().split()
        if T[0] == '1':
            for j in range(len(s)//2):
                tmp = s[j]
                s[j] = s[-1-j]
                s[-1-j] = tmp
        else:
            ext = [c for c in T[2]]
            if T[1] == '1':
                s = ext + s
            else:
                s = s + ext
    print(''.join(s))

if __name__ == "__main__":
    solve()

### FIXED CODE ###

def solve():
    from collections import deque
    S = input()
    s = deque(S)
    Q = int(input())
    reverse = False
    for i in range(Q):
        T = input().split()
        if T[0] == '1':
            if reverse:
                reverse = False
            else:
                reverse = True
        else:
            if T[1] == '1' and not reverse:
                s.appendleft(T[2])
            elif T[1] == '1' and reverse:
                s.append(T[2])
            elif T[1] == '2' and not reverse:
                s.append(T[2])
            else:
                s.appendleft(T[2])
    if reverse:
        print(''.join(s)[::-1])
    else:
        print(''.join(s))

if __name__ == "__main__":
    solve()
### BUGGY CODE ###

from collections import deque

h,w = map(int,input().split())
ch,cw = map(int,input().split())
dh,dw = map(int,input().split())

ch,cw,dh,dw = ch-1,cw-1,dh-1,dw-1
S = [[""]*w for i in range(h)]

for i in range(h):
    s = input()
    for j in range(w):
        S[i][j] = s[j]
        
visited = [[-1]*w for _ in range(h)]

visited[ch][cw] = 0

INF = 10**9
dist = [[INF]*w for _ in range(h)]
Q = deque([])
Q.append([ch,cw])
dist[ch][cw] = 0

while Q:
    y,x = Q.popleft()
    d = dist[y][x]
    
    for i, j in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
      nx = x + i
      ny = y + j
      if (nx < 0 or nx >= w or ny < 0 or ny >= h): 
          continue
      if S[ny][nx] == "#":
          continue
      if dist[ny][nx] <= d:
          continue
      dist[ny][nx] = d
      Q.appendleft([ny,nx])
      
    
    for ey in range(-2,3):
        for ex in range(-2,3):
            nx = x + ex
            ny = y + ey
            if (nx < 0 or nx >= w or ny < 0 or ny >= h): 
              continue
            if S[ny][nx] == "#":
              continue
            if dist[ny][nx] <= d+1:     
              continue
            dist[ny][nx] = d+1
            Q.append([ny,nx])
      
ans = dist[dh][dw]

if ans == INF:
    print(-1)
else:
    print(ans)

### FIXED CODE ###

from collections import deque

h,w = map(int,input().split())
ch,cw = map(int,input().split())
dh,dw = map(int,input().split())

ch,cw,dh,dw = ch-1,cw-1,dh-1,dw-1
S = [[""]*w for i in range(h)]

for i in range(h):
    s = input()
    for j in range(w):
        S[i][j] = s[j]
        
visited = [[-1]*w for _ in range(h)]

visited[ch][cw] = 0

INF = 10**9
dist = [[INF]*w for _ in range(h)]
Q = deque([])
Q.append([ch,cw])
dist[ch][cw] = 0

while Q:
    y,x = Q.popleft()
    d = dist[y][x]
    
    for i, j in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
      nx = x + i
      ny = y + j
      if (nx < 0 or nx >= w or ny < 0 or ny >= h): 
          continue
      if S[ny][nx] == "#":
          continue
      if dist[ny][nx] <= d:
          continue
      dist[ny][nx] = d
      Q.appendleft([ny,nx])
      
    
    for ey in range(-2,3):
        for ex in range(-2,3):
            nx = x + ex
            ny = y + ey
            if (nx < 0 or nx >= w or ny < 0 or ny >= h): 
              continue
            if S[ny][nx] == "#":
              continue
            if dist[ny][nx] <= d+1:     
              continue
            dist[ny][nx] = d+1
            Q.append([ny,nx])
      
ans = dist[dh][dw]

if ans == INF:
    print(-1)
else:
    print(ans)
### BUGGY CODE ###

[x,k,d] = [int(i) for i in input().split()]
tmp_diff = abs(x)

while tmp_diff > d and k > 0:
    tmp_diff -= d
    k -= 1

if k <= 0:
    print(tmp_diff)
else:
    if k % 2 == 0:
        print(tmp_diff)
    else:
        print(d - tmp_diff)


### FIXED CODE ###

[x,k,d] = [int(i) for i in input().split()]
x = abs(x)

if k < x//d:
    print(x - k * d)
else:
    k -= x // d
    x -= (x // d) * d
    if k % 2:
        print(abs(x-d))
    else:
        print(x)
### BUGGY CODE ###

import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def divisor(n): #nの約数を全て求める
    i = 1
    table = []
    while i * i <= n:
        if n%i == 0:
            table.append(i)
            table.append(n//i)
        i += 1
    table = list(set(table))
    return table

a, b = MAP()
kouyaku = set(divisor(a)) & set(divisor(b))
ans = 0
s = []
for k in kouyaku:
    except_one_k = divisor(k)
    # except_one_k.pop(0)
    # print(except_one_k)
    # s.append(divisor(k))
    if len(except_one_k) == 1 or len(except_one_k) == 2:
        ans += 1
print(ans)


### FIXED CODE ###

import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def divisor(n): #nの約数を全て求める
    i = 1
    table = []
    while i * i <= n:
        if n%i == 0:
            table.append(i)
            table.append(n//i)
        i += 1
    table = list(set(table))
    return table

def is_prime(n):
    for i in range(2, n + 1):
        if i * i > n:
            break
        if n % i == 0:
            return False
    return n != 1

a, b = MAP()
kouyaku = list(set(divisor(a)) & set(divisor(b)))

ans = 0
for k in kouyaku:
    if is_prime(k):
        ans += 1
print(ans+1)
### BUGGY CODE ###

n, m = map(int, input().split())
uv = [list(map(int, input().split())) for _ in range(m)]
s, t = map(int, input().split())

from collections import defaultdict, deque
g1 = defaultdict(set)
for u, v in uv:
    g1[u-1].add(v-1)

s -= 1
t -= 1

f = False
visited = set([s])
q = deque([(s, 0)])
while q:
    cur, d = q.popleft()

    if cur == t:
        f = True
        break
    for target1 in g1[cur]:
        for target2 in g1[target1]:
            for target3 in g1[target2]:
                if target3 not in visited:
                    q.append((target3, d + 1))

if f:
    print(d)
else:
    print(-1)


### FIXED CODE ###

n, m = map(int, input().split())
uv = [list(map(int, input().split())) for _ in range(m)]
s, t = map(int, input().split())

import heapq
from collections import defaultdict
g1 = defaultdict(set)
for u, v in uv:
    g1[u-1].add(v-1)

s -= 1
t -= 1

dist = [[float('inf')] * 3 for _ in range(n)]
dist[s][0] = 0

q = [(0, s, 0)] # (dist, pos, kenken)
heapq.heapify(q)

while q:
    du, u, c = heapq.heappop(q)
    if dist[u][c] < du:
        continue
    c2 = (c + 1) % 3
    for v in g1[u]:
        if du + 1 < dist[v][c2]:
            dist[v][c2] = du + 1
            heapq.heappush(q, (dist[v][c2], v, c2))

if dist[t][0] != float('inf'):
    print(dist[t][0] // 3)
else:
    print(-1)
### BUGGY CODE ###

import math
k = int(input())
su = 0
for x in range(1, k+1):
  for y in range(1, k+1):
    for z in range(1, k+1):
      lis = [x, y, z]
      ans = x
      for p in range(1,3):
        ans = math.gcd(ans, lis[p])
      su += ans
      
print(su)

### FIXED CODE ###

import math
k = int(input())
su = 0
lis = []
for x in range(1, k+1):
  for y in range(1, k+1):
    a = math.gcd(x, y)
    lis.append(a)

for z in range(1, k+1):
  for p in lis:
    ans = math.gcd(p, z)
    su += ans
  
print(su)
### BUGGY CODE ###

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

    total_T_in_A = [0] * (N+1)
    # total_T_in_B = [0] * M
    # total_T_in_B[0] = B[0]
    total_T_in_B = [0] * (M+1)

    for i in range(1, N+1):
        total_T_in_A[i] = total_T_in_A[i-1] + A[i-1]

    for i in range(1, M+1):
        # total_T_in_B[i] = total_T_in_B[i-1] + B[i]
        total_T_in_B[i] = total_T_in_B[i-1] + B[i-1]

    result = 0
    for i in range(N+1):
        # A から i 冊読むときにかかる時間
        i_A_T = total_T_in_A[i]
        
        if K < i_A_T:
            continue

        if K == i_A_T:
            result = max(result, i)
            continue

        rem_T = K - i_A_T

        # total_T_in_B は累積和を格納した、ソート済の配列
        # B_i <= rem_T < B_i+1 となるような B_i を二分探索によって探す

        total_T_in_B_with_INF = total_T_in_B + [10**18]

        first = 0
        last = M + 1
        # total_T_in_B_with_INF[first] <= rem_T < total_T_in_B_with_INF[last] となるような first を二分探索によって探す
        while first < last:
            if abs(last - first) == 1:
                break
            mid = (first + last) // 2
            if rem_T < total_T_in_B_with_INF[mid]:
                last = mid
            else:
                first = mid
        result = max(result, i + first)

    print(result)

main()


### FIXED CODE ###

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

    total_T_in_A = [0] * (N+1)
    total_T_in_A[1] = A[0]
    total_T_in_B = [0] * M
    total_T_in_B[0] = B[0]

    for i in range(2, N+1):
        total_T_in_A[i] = total_T_in_A[i-1] + A[i-1]

    for i in range(1, M):
        total_T_in_B[i] = total_T_in_B[i-1] + B[i]

    result = 0
    for i in range(N+1):
        # A から i 冊読むときにかかる時間
        i_A_T = total_T_in_A[i]
        
        if K < i_A_T:
            continue

        if K == i_A_T:
            result = max(result, i)
            continue

        rem_T = K - i_A_T

        # total_T_in_B は累積和を格納した、ソート済の配列
        # B_i <= rem_T < B_i+1 となるような B_i を二分探索によって探す
        first = total_T_in_B[0]
        last = total_T_in_B[M-1]
        if rem_T < first:
            result = max(result, i)
            continue
        if last <= rem_T:
            result = max(result, i + M)
            continue

        # assume that first <= rem_T <= last
        first_i = 0
        last_i = M - 1
        while first_i < last_i:
            if abs(last_i - first_i) == 1:
                break
            mid_i = (first_i + last_i) // 2
            if rem_T < total_T_in_B[mid_i]:
                last_i = mid_i
            else:
                first_i = mid_i
        result = max(result, i + first_i + 1)

    print(result)

main()