Harryxun/stf_run huggingface dataset:
from collections import deque
s = input()
q = int(input())
former = deque()
latter = deque()

flg = False
for i in range(q):
    p = list(map(str, input().split()))
    if p[0] == "1":
        flg = True if flg == False else False
        continue
    else:
        if (p[1] == "1" and not flg) or (p[1] == "2" and flg):
            former.appendleft(p[2])
        else:
            latter.append(p[2])

ans = former + deque(s) + latter
ans = "".join(ans)
print(ans if not flg else ans[::-1])

### FIXED CODE ###

from collections import deque

s = deque(str(input()))
q = int(input())

t = 0
for i in range(q):
    o = list(map(str, input().split()))
    if o[0] == "1":
        t += 1
    else:
        if o[1] == "1" and t%2 == 0 or o[1] == "2" and t%2 == 1:
            s.appendleft(o[2])
        else:
            s.append(o[2])

if t%2 == 1:
    s.reverse()

print("".join(s))
n=int(input())
s=list(input())
c=0
for i in range(n//2):
    if s[i]!=s[i+n//2]:
        c+=1
if c==0:
    print('Yes'):
else:
    print('No')

### FIXED CODE ###

n=int(input())
s=list(input())
c=0
if n%2 != 0:
    print('No')
    exit()
else:
    for i in range(n//2):
        if s[i]!=s[i+n//2]:
            c+=1
    if c==0:
        print('Yes')
    else:
        print('No')
r= input()
 nr = 2*3.14*(r**2)
 ar = 2*3.14
 print int(nr/ar)

# l = []
# for i in xrange(41):
#     l.append(map(int,raw_input().split()))
# print l


### FIXED CODE ###

r= input()

print r**2
import math
def lcm(x, y):
    return (x * y) // math.gcd(x, y)

a, b, c, d = map(int, input().split())
cn = b//c + (-a//c) + 1
dn = b//d + (-a//d) + 1
cd = lcm(c, d)
cdn = b//cd + (-a//cd) + 1
#print(cn, dn, cdn)
print(b-a+1-(cn+dn-cdn))

### FIXED CODE ###

import fractions
a, b, c, d = map(int, input().split())
cn = b//c + (-a//c) + 1
dn = b//d + (-a//d) + 1
cd = (c*d)//fractions.gcd(c, d)
cdn = b//cd + (-a//cd) + 1
print(b-a+1-(cn+dn-cdn))
r,g,b,n = map(int, input().split(" "))
l = sorted([r,g,b])
count=0
for i in range(n):
    for j in range(n):
        x = l[2]*i
        y = l[1]*j
        if (n - (x + y) < 0:
            break
        if (n-(x+y))%l[0] == 0:
            count = count + 1
print(count)

### FIXED CODE ###

r,g,b,n = map(int, input().split(" "))
l = sorted([r,g,b])
count=0
for i in range(int(n/l[2])+1):
    for j in range(int(n/l[1])+1):
        x = l[2]*i
        y = l[1]*j
        if (n-x-y) >= 0 and (n-x-y)%l[0] == 0:
            count = count + 1
print(count)
N,T = map(int, input().split())
minC = 1001
flag = False
for i in range(int(N)):
    c, t = map(int, input().split())
    if int(T) >= t and minC >= int(c):
        minC = c
        frag = True

if(flag == False):
    print("TLE")
else:
    print(minC)

### FIXED CODE ###

N = int(input())
if (N == 1): 
    print("Hello World")
else:
    a = int(input())
    b = int(input())
    print(a+b)
# Function for calc
def match(n, a, b):
    if (b - a)% 2 == 0:
        print((b-a)/2)
    else:
        if (n - b) > a:
            print((a)+((b-(a+1))/2))
        else:
            x=(n-b+1)
            print(x+((n-(a+x))/2))
# Run match
in_string = input()
N = int(in_string[0])
A = int(in_string[1])
B = int(in_string[2])

match(N, A, B)

### FIXED CODE ###

# Function for calc
def match(n, a, b):
    if (b - a)% 2 == 0:
        print((b-a)/2)
    else:
        if (n - b) >= a:
            print((a)+((b-(a+1))/2))
        else:
            x=(n-b+1)
            print(x+((n-(a+x))/2))
# Run match
in_string = raw_input()
[N, A, B] = [int(v) for v in in_string.split()]
match(N, A, B)
N,M = map(int,input().split())
L = list(map(int,input().split()))
L = sorted(L)
S = []
if N >= M:
  print(0)
  exit()

for i in range(M-1):
  S.append(abs(L[i+1]-L[i]))

  S=sorted(S)
print(sum(S[0:M-N]))



### FIXED CODE ###

N = int(input())
a = list(map(int, input().split()))
ans = 0

for i in a:
    while True:
        if i % 2 == 0:
            ans += 1
            i //= 2
        else:
            break
print(ans)
from copy import copy
def gcd(a, b):
	if a%b == 0:
		return b
	else:
		return gcd(b, a%b)

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

if n==2:
	print(max(a))
	quit()

a = list(set(a))

gcds = []
for i in range(len(a)):
	temp = copy(a)
	temp.pop(i)

	num1 = temp[0]
	num2 = temp[1]
	result = gcd(num1, num2)
	for j in range(2, len(temp)):
		if result in gcds:
			break
		result = gcd(result, temp[j])
	
	if result not in gcds:
		gcds.append(result)

gcds = sorted(gcds)

if len(gcds)==1:
	print(gcds[0])
else:
	gcds = sorted(gcds)
	print(gcds[1])

### FIXED CODE ###

from copy import copy
def gcd(a, b):
	if a%b == 0:
		return b
	else:
		return gcd(b, a%b)

def factor(n):
	factors = [1, n]
	i=2
	while i*i <= n:
		if n%i==0:
			factors.append(i)
			factors.append(n//i)
		i+=1

	return factors

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

if n==2:
	print(max(A))
	quit()

gcd1 = 0
fac1 = sorted(factor(A[0]),reverse=True)
for i in range(len(fac1)):
	count = 0
	for j in range(1, n):
		if A[j]%fac1[i]!=0:
			count += 1
			if count >= 2:
				break
	if count <= 1:
		gcd1 = fac1[i]
		break

fac2 = sorted(factor(A[1]),reverse=True)
gcd2 = 0
for i in range(len(fac2)):
	count = 0
	for j in range(2, n):
		if A[j]%fac2[i]!=0:
			count += 1
			break
	if count <= 0:
		gcd2 = fac2[i]
		break

print(max(gcd1, gcd2))
A,B= input().split()
A = int(A)
B2 = int(B*1000)
#print(A*B*100000)
print(int(A*B2/1000))

### FIXED CODE ###

#C - Multiplication 3
from decimal import Decimal
A,B= map(str,input().split())
A2 = Decimal(A)
B2 = Decimal(B)
#print(A*B*100000)
print(int(A2*B2))
def main():
    from collections import defaultdict
    import sys
    sys.setrecursionlimit(20000)
    n, *rem = map(int, open(0).read().split())
    t = 3 * (n - 1)
    abc = rem[:t]
    q, k = rem[t], rem[t + 1]
    xy = rem[t + 2:]

    m = [[] for _ in range(n + 1)]
    dist = defaultdict(dict)
    for a, b, c in zip(*[iter(abc)] * 3):
        m[a].append(b)
        m[b].append(a)

        dist[a].update({b: c})
        dist[b].update({a: c})

    vis = [False] * (n + 1)
    cost = [0] * (n + 1)
    vis[k] = True

    def dfs(frm, to):
        if vis[to]:
            return
        vis[to] = True
        cost[to] = cost[frm] + dist[frm][to]
        frm = to
        for to in m[frm]:
            dfs(frm, to)

    frm = k
    for to in m[frm]:
        dfs(frm, to)

    tmp = []
    for x, y in zip(*[iter(xy)] * 2):
        tmp.append(cost[x] + cost[y])

    ans = "\n".join(map(str, tmp))
    print(ans)


if __name__ == '__main__':
    main()


### FIXED CODE ###

def main():
    from collections import defaultdict
    import sys
    sys.setrecursionlimit(1000000)
    n, *rem = map(int, open(0).read().split())
    t = 3 * (n - 1)
    abc = rem[:t]
    q, k = rem[t], rem[t + 1]
    xy = rem[t + 2:]

    m = [[] for _ in range(n + 1)]
    dist = defaultdict(dict)
    for a, b, c in zip(*[iter(abc)] * 3):
        m[a].append(b)
        m[b].append(a)

        dist[a].update({b: c})
        dist[b].update({a: c})

    vis = [False] * (n + 1)
    cost = [0] * (n + 1)
    vis[k] = True

    def dfs(frm, to):
        if vis[to]:
            return
        vis[to] = True
        cost[to] = cost[frm] + dist[frm][to]
        frm = to
        for to in m[frm]:
            dfs(frm, to)

    frm = k
    for to in m[frm]:
        dfs(frm, to)

    tmp = []
    for x, y in zip(*[iter(xy)] * 2):
        tmp.append(cost[x] + cost[y])

    ans = "\n".join(map(str, tmp))
    print(ans)


if __name__ == '__main__':
    main()
N, M = map(int, input().split())
A = [-1] * N
for i in range(M):
  t = list(map(int, input().split()))
  if t == [1, 0] and N != 1:
    print(-1)
    exit()
  elif A[t[0] - 1] == -1:
    A[t[0] - 1] = t[1]
  elif A[t[0] - 1] != t[1]:
    print(-1)
    exit()
B = [A[k] * (10 ** (M - 1 - k)) for k in range(M) if A[k] > 0]
print(sum(B))

### FIXED CODE ###

N, M = map(int, input().split())
A  = [-1] * N
for i in range(M):
  t = list(map(int, input().split()))
  if A[t[0] - 1] == -1:
    A[t[0] - 1] = t[1]
  elif A[t[0] - 1] != t[1]:
    print(-1)
    exit()
if N != 1 and A[0] == 0:
  print(-1)
  exit()
elif A.count(-1) == N and N != 1:
  print(1 * 10 ** (N - 1))
  exit()
elif A[0] == -1:
  if N == 1:
    A[0] = 0
  else:
    A[0] = 1
B = [A[j] * 10 ** (N - 1 - j) for j in range(N) if A[j] > 0]
print(sum(B))
import sys
import math
import itertools as it
def i():return int(sys.stdin.readline().replace("\n",""))
def i2():return map(int,sys.stdin.readline().replace("\n","").split())
def s():return str(sys.stdin.readline().replace("\n",""))
def l():return list(sys.stdin.readline().replace("\n",""))
def intl():return [int(k) for k in sys.stdin.readline().replace("\n","").split()]
def lx():return list(map(lambda x:int(x)*-1,sys.stdin.readline().replace("\n","").split()))
def t():return tuple(map(int,sys.stdin.readline().replace("\n","").split()))

if __name__ == "__main__":pass
n ,m = i2()
l = [0]*n
for i in range(m):
    s,c = i2()
    if l[s-1] == 0 or l[s-1] == c:
        l[s-1] = c
    else:
        print(-1)
        exit()
num = ""
for i in l:
    num = num + str(i)
num = int(num)
print(num if len(str(num)) == n else -1)

### FIXED CODE ###

import sys
import math
def i():return int(sys.stdin.readline().replace("\n",""))
def i2():return map(int,sys.stdin.readline().replace("\n","").split())
def s():return str(sys.stdin.readline().replace("\n",""))
def l():return list(sys.stdin.readline().replace("\n",""))
def intl():return [int(k) for k in sys.stdin.readline().replace("\n","").split()]
def lx():return list(map(lambda x:int(x)*-1,sys.stdin.readline().replace("\n","").split()))
def t():return tuple(map(int,sys.stdin.readline().replace("\n","").split()))

if __name__ == "__main__":pass

n = i()
print(n//2 if n%2==0 else n//2+1)
A,B = map(int,input().split())
if A+B=3:
  print(3)
elif A+B=4:
  print(2)
elif A+B=5:
  print(1)

### FIXED CODE ###

a = int(input())
b = int(input())
if a+b == 3:
  print(3)
elif a+b == 4:
  print(2)
else:
  print(1)
import math
print(math.factrial(int(input()))//(10**9+7))

### FIXED CODE ###

import math
print(math.factorial(int(input()))%(10**9+7))
import itertools

s = input()
n = [i for i in s]
ans = 0

for i in range(len(n)):
  for j in itertools.combinations(range(len(n)-1, i)):
    temp = [i for i in s]
    for k in j[::-1]:
      temp.insert(k+1, "+")
    temp = "".join(temp)
    temp = temp.split("+")
    temp = map(int, temp)
    ans += sum(temp)

print(ans)

### FIXED CODE ###

import itertools

s = input()
n = [i for i in s]
ans = 0

for i in range(len(n)):
    for j in itertools.combinations(range(len(n)-1), i):
        temp = [i for i in s]
        for k in j[::-1]:
            temp.insert(k+1, "+")
        temp = "".join(temp)
        temp = temp.split("+")
        temp = map(int, temp)
        ans += sum(temp)

print(ans)
import collections
n=int(input())
A=list(map(int,input().split()))
x=0
lst=[]
for i in range(n):
    x+=A[i]
    lst.append(x)
c=collections.Counter(lst)

 
def conv(n,m):
    if n==m or m==0:
        return 1
    else:
        return conv(n-1,m-1)+conv(n-1,m)
ans=0
for k in c.keys():
    if c[k]==1:
        if k==0:
            ans+=1
        else:
            continue
    elif k==0:
        ans+=c[k]+conv(c[k],2)
    else:
        ans+=conv(c[k],2)
print(ans)

### FIXED CODE ###

import collections
n=int(input())
A=list(map(int,input().split()))
x=0
lst=[]
for i in range(n):
    x+=A[i]
    lst.append(x)
c=collections.Counter(lst)

 
def conv(n,m):
    if n==m or m==0:
        return 1
    else:
        return conv(n-1,m-1)+conv(n-1,m)
ans=0
for k in c.keys():
    if c[k]==1:
        if k==0:
            ans+=1
        else:
            continue
    elif k==0:
        ans+=c[k]+int(c[k]*(c[k]-1)/2)
    else:
        ans+=int(c[k]*(c[k]-1)/2)
print(ans)
s=input()
n=int(s)
c=0
for i in range(len(s)-3):
  for j in range(i+4,len(s)+1):
    m=int(int(n/(10**i))%(10**j))
    if m%2019==0 and m == 0:
      c+=1
print(c)

### FIXED CODE ###

S = input()
N = len(S)
A = [int(S[i]) for i in range(N)]
A = A[::-1]

MOD = 2019

p10 = [1] * N
for i in range(1, N):
	p10[i] = (p10[i - 1] * 10) % MOD

for i in range(N):
	A[i] = (A[i] * p10[i]) % MOD

cumsum = [A[0]] * N
for i in range(1, N):
	cumsum[i] = (cumsum[i - 1] + A[i]) % MOD

cnt = [0] * MOD
cnt[0] = 1
for i in range(N):
	cnt[cumsum[i]] += 1

ans = 0
for i in range(MOD):
	ans += cnt[i] * (cnt[i] - 1) // 2

print(ans)
o,e=input(),input()
ans=[]
for i in range(len(o)):
  ans.append(o[i])
  if e:
    ans.append(e[i])
print("".join(ans))

### FIXED CODE ###

o,e=input(),input()
ans=[]
for i in range(len(o)):
  ans.append(o[i])
  if i<len(e):
    ans.append(e[i])
print("".join(ans))
#include <iostream>
#include <stdio.h>
using namespace std;

int main(void)
{
	int N , K;
	cin >> N;
	cin >> K;
	int h[N];
	long long dp[N];
	long long inf=100000000000000000;
	for(int i = 0; i<N; i++){
		cin >> h[i];
		dp[i] = inf;
	}

	dp[0] = 0;

	for(int i = 0 ; i<N;i++){
		for(int j =1 ; j<=K ; j++){
			if(i+j >= N){
				break;
			}
			
			long long cost = abs(h[i] - h[i+j]) + dp[i];
			if( dp[i+j] > cost){
				dp[i+j] = cost;
				// cout << "i : " << i << " j : " << j << endl;
			}
		}

	}

	cout << dp[N-1] << endl;
}



### FIXED CODE ###

N , K = map(int,input().split())
h = list(map(int,input().split()))

def dp(cost):
    for x in range(1,N):
        for k in range(max(x-K,0),x):
            cost[x] = min(cost[x] , cost[k] + abs( h[x] - h[k] ) )
        # cost[x] =  min( [ cost[k] + abs( h[x] - h[k] ) for k in range(max(x-K,0),x) ] ) 
    return 0

def solve():
    cost = [float('inf')] * N
    cost[0] = 0
    dp(cost)
    print(cost[N-1])
    return 0

if __name__ == "__main__":
    solve()
h, n = map(int, input().split())
a = list(map(int, input().split()))
s = sum(a)
if h <= s:
	print('YES')
else:
	print('NO')

### FIXED CODE ###

h, a = map(int, input().split())
if h % a == 0:
	print(h//a)
else:
	print(h//a + 1)
n = map(int, input())
a = map(int, input())
if n%500 < a:
  print('YES')
else
  print('NO')

### FIXED CODE ###

n = int(input())
a = int(input())
if n % 500 <= a:
  print("Yes")
else:
  print("No")
class FK:
    def __init__(self,n):
        self.table=[[0]*n for i in range(n)]
        self.n=n
    
    def add(self,x,y,f):
        self.table[x][y]=f
        
    def ford(self,s,t,f):
        self.visit[s]=True
        if s==t:
            return f
        for i in range(self.n):
            if (not self.visit[i]) and self.table[s][i]>0:
                df=self.ford(i,t,min(f,self.table[s][i]))
                if df>0:
                    self.table[s][i]-=df
                    self.table[i][s]+=df
                    return df
        return 0
    
    def flow(self,s,t):
        ans=0
        inf=10**20
        while True:
            self.visit=[False]*(self.n)
            df=self.ford(s,t,inf)
            if df==0:
                break
            ans+=df
        return ans

H,W=map(int,input().split())
C=[input() for i in range(H)]
maxflow=FK(W+H+2)
inf=10**20
for i in range(W):
    for j in range(H):
        if C[j][i]=='S':
            sx=i
            sy=j
            maxflow.add(0,i+1,inf)
            maxflow.add(0,W+1+j,inf)
            continue
        if C[j][i]=='T':
            gx=i
            gy=j
            maxflow.add(i+1,W+H+1,inf)
            maxflow.add(W+1+j,W+H+1,inf)
            continue
        if C[j][i]=='o':
            maxflow.add(i+1,W+1+j,1)
            maxflow.add(W+1+j,i+1,1)
#print(maxflow.table)
if gx==sx or gy==sy:
    print('-1')
    sys.exit()
ans=maxflow.flow(0,H+W+1)
print(ans)

### FIXED CODE ###

import sys
sys.setrecursionlimit(10**8)
class FK:
    def __init__(self,n):
        self.table=[[0]*n for i in range(n)]
        self.n=n
    
    def add(self,x,y,f):
        self.table[x][y]=f
        
    def ford(self,s,t,f):
        self.visit[s]=True
        if s==t:
            return f
        for i in range(self.n):
            if (not self.visit[i]) and self.table[s][i]>0:
                df=self.ford(i,t,min(f,self.table[s][i]))
                if df>0:
                    self.table[s][i]-=df
                    self.table[i][s]+=df
                    return df
        return 0
    
    def flow(self,s,t):
        ans=0
        inf=10**20
        while True:
            self.visit=[False]*(self.n)
            df=self.ford(s,t,inf)
            if df==0:
                break
            ans+=df
        return ans

H,W=map(int,input().split())
C=[input() for i in range(H)]
maxflow=FK(W+H+2)
inf=10**20
for i in range(W):
    for j in range(H):
        if C[j][i]=='S':
            sx=i
            sy=j
            maxflow.add(0,i+1,inf)
            maxflow.add(0,W+1+j,inf)
            continue
        if C[j][i]=='T':
            gx=i
            gy=j
            maxflow.add(i+1,W+H+1,inf)
            maxflow.add(W+1+j,W+H+1,inf)
            continue
        if C[j][i]=='o':
            maxflow.add(i+1,W+1+j,1)
            maxflow.add(W+1+j,i+1,1)
#print(maxflow.table)
if gx==sx or gy==sy:
    print('-1')
    sys.exit()
ans=maxflow.flow(0,H+W+1)
print(ans)
#!/usr/bin/env python3

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

ans = 0 
time = 0 

while time <= k:
#    print('time =', time)
#    print('a =', a)
#    print('b =', b)

    if len(a) > 0:
        if a[0] <= b[0]:
            if len(a) > 0:
                time += a[0]
                ans += 1
                a.pop(0)
            elif len(b) > 0:
                time += b[0]
                ans += 1
                b.pop(0)
        else:
            if len(b) > 0:
                time += b[0]
                ans += 1
                b.pop(0)
            elif len(a) > 0:
                time += a[0]
                ans += 1
                a.pop(0)

    elif len(b) > 0:
        time += b[0]
        ans += 1
        b.pop(0)

    if len(a) == 0 and len(b) == 0:
        break

if time == k:
    print(ans)
else:
    print(ans-1)

### FIXED CODE ###

#!/usr/bin/env python3
# binary search 1

from bisect import bisect_left, bisect_right

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

cumsum_b = [0 for _ in range(m+1)]
for i in range(1,m+1):
    cumsum_b[i] = cumsum_b[i-1] + b[i-1]
cumsum_a = [0 for _ in range(n+1)]
for i in range(1,n+1):
    cumsum_a[i] = cumsum_a[i-1] + a[i-1]

# print('cumsum_b =', cumsum_b)
ans = -1
for i in range(n+1):
    res = k-cumsum_a[i]
#    print('cumsum_a[{}] ='.format(i), cumsum_a[i])
#    print('res =', res)
    if res < 0:
        break
    bl = bisect_right(cumsum_b, res) - 1 
#    print('i =', i)
#    print('bl =', bl)
    tmp = i + bisect_right(cumsum_b, res) - 1 
    if ans <= tmp:
        ans = tmp 

print(ans)
N = int(input())
X = list(map(int, (input().split())))

distance = lambda Xi, P: (Xi - P) ** 2

X_max = max(X)

answer = None
for P in range(1, X_max + 1):
    total = 0
    for Xi in X:
        total += distance(Xi, P)
    answer = min(total, answer) if answer is not None else total

print(answer)


### FIXED CODE ###

N = int(input())
X = list(map(int, (input().split())))

distance = lambda Xi, P: (Xi - P) ** 2

X_max = max(X)

answer = 99999999999
for P in range(1, X_max + 1):
    total = 0
    for Xi in X:
        total += distance(Xi, P)
    answer = min(total, answer)

print(answer)
N = int(input())

M = int(input())

for i in range(M):
    Ai = int(input())
    N = N - Ai

if N >= 0:
    print(N)
else:
    N = -1
    print(N)

### FIXED CODE ###

import math

r = int(input())
C = 2 * math.pi * r

print(C)
N = int(input())
L = list(map(int,input().split()))
L.sort()
ans = 0
for i in range(len(L)-1):
    for j in range(i+1,len(L)-1):
        a = L[i]
        b = L[j]
        c = L[j+1]
        if c-a < b and b < c+a:
            ans += bisect.bisect_left(L,b+a)-j-1
print(ans)

### FIXED CODE ###

import bisect
N = int(input())
L = list(map(int,input().split()))
L.sort()
ans = 0
for i in range(len(L)-1):
    for j in range(i+1,len(L)-1):
        a = L[i]
        b = L[j]
        c = L[j+1]
        if c-a < b and b < c+a:
            ans += bisect.bisect_left(L,b+a)-j-1
print(ans)
N, M = map(int, raw_input().split())
 
output = 1
for i in range(1, M/N+1):
    if M % i == 0 and output < i:
        output = i
 
print(output)


### FIXED CODE ###

N, M = map(int, input().split())

output = 1
for i in range(M//N, 0, -1):
    if M % i == 0 and output < i:
        output = i
        break
print(output)
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res

def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    n = I()

    return

#B
def B():
    n = I()

    return

#C
def C():
    n = I()
    a = LI()
    b = LI()
    q = []
    for i in range(n):
        heappush(q,(-b[i],i))
    ans = 0
    while q:
        bi,i = heappop(q)
        r = (i+1)%n
        l = i-1
        k = -bi-a[i]
        s = b[l]+b[r]
        m = max(s,k)//s
        if m:
            ans += m
            update = 1
            b[i] -= m*s
            if b[i] != a[i]:
                heappush(q,(-b[i],i))
        else:
            break
    if a == b:
        print(ans)
    else:
        print(-1)
    return

#D
def D():

    return

#E
def E():
    n = I()

    return

#F
def F():
    n = I()

    return

#Solve
if __name__ == "__main__":
    C()


### FIXED CODE ###

#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res

def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    n = I()

    return

#B
def B():
    n = I()

    return

#C
def C():
    n = I()
    a = LI()
    b = LI()
    q = []
    for i in range(n):
        if b[i] > a[i]:
            heappush(q,(-b[i],i))
    ans = 0
    while q:
        bi,i = heappop(q)
        r = (i+1)%n
        l = i-1
        s = b[l]+b[r]
        if a[i] < s:
            m = b[i]//s
            if m:
                ans += m
                b[i] %= s
                if b[i] != a[i]:
                    heappush(q,(-b[i],i))
        else:
            k = -bi-a[i]
            m = k//s
            b[i] -= m*s
            ans += m
            if b[i] != a[i]:
                break
    if a == b:
        print(ans)
    else:
        print(-1)
    return

#D
def D():

    return

#E
def E():
    n = I()

    return

#F
def F():
    n = I()

    return

#Solve
if __name__ == "__main__":
    C()
import math
n = int(raw_input())
ls = [int(raw_inpu() for i in range(n)]
r = max(ls)+1
sqrt = int(math.sqrt(r))
p = [1]*r
p[0] = 0
for i in range(1,sqrt):
    if p[i]:
        p[2*i+1::i+1] = [0 for x in range(2*i+1,r,i+1)]
   
ans = 0
for i in ls:
    ans += p[i-1]
print ans

### FIXED CODE ###

def isPrime(p):
	if p == 2: return 1
	if p < 2 or p&1 == 0: return 0
	return 1 if pow(2,p-1,p) == 1 else 0
	
n = int(raw_input())
print sum(isPrime(int(raw_input())) for i in range(n))
n,k=map(int,input().split())
*a,=map(int,input().split())
print(((n-2)//(k-1)+1)

### FIXED CODE ###

n,k=map(int,input().split())
*a,=map(int,input().split())
print((n-2)//(k-1)+1)