input
stringlengths
20
127k
target
stringlengths
20
119k
problem_id
stringlengths
6
6
a = int(eval(input())) if a%2 == 0: print((a//2)) else: print((a//2+1))
n = int(eval(input())) if n % 2 == 0: print((n//2)) else: print(((n+1)//2))
p02759
import math n = int(eval(input())) print((math.floor((n+1)/2)))
import math N = int(eval(input())) print((math.ceil(N/2)))
p02759
def main(): N = int(eval(input())) print(((N + 1) // 2)) return main()
def main(): N = int(eval(input())) print((-(-N // 2))) return main()
p02759
print((int((int(eval(input()))+1)/2)))
print(((int(eval(input()))+1)//2))
p02759
N = int(eval(input())) ans = N // 2 + N % 2 print(ans)
N = int(eval(input())) ans = (N + 1) // 2 print(ans)
p02759
import math N = int(eval(input())) print((math.ceil(N/2)))
n = int(eval(input())) if n % 2 <= 0 : print((n//2)) elif n % 2 >= 1 : print((n//2 +1))
p02759
N = int(eval(input())) if N % 2 == 0: print((N//2)) else: print((N//2+1))
N = int(eval(input())) output = 0 for i in range(1, N+1, 2): output += 1 print(output)
p02759
import sys sys.setrecursionlimit(10**9) INF = 10**12 N = int(eval(input())) D = dict() for _ in range(N): s, c = input().split() if s in list(D.keys()): D[s] = min(D[s], int(c)) else: D[s] = int(c) def check_kaibun(s): n = len(s) return all(s[i] == s[-i-1] for i in range(n//2)) def calc_cost(use): return sum(D[s] * n for (s, n) in list(use.items())) def find_candidate(cost, use, s, is_left): if check_kaibun(s): return min(cost, calc_cost(use)) if is_left: for t in list(D.keys()): # reversed s is included in the end of t if t[::-1].find(s) == 0: use[t] += 1 c = find_candidate(cost, use, t[:-len(s):], False) cost = min(cost, c) use[t] -= 1 # reveresed t is included in the begin of s elif s.find(t[::-1]) == 0: use[t] += 1 c = find_candidate(cost, use, s[len(t):], True) cost = min(cost, c) use[t] -= 1 else: for t in list(D.keys()): # t is included in the end of reversed s if s[::-1].find(t) == 0: use[t] += 1 c = find_candidate(cost, use, s[:-len(t):], False) cost = min(cost, c) use[t] -= 1 # s is included in the begin of reveresed t elif t.find(s[::-1]) == 0: use[t] += 1 c = find_candidate(cost, use, t[len(s):], True) cost = min(cost, c) use[t] -= 1 return min(cost, INF) def solve(): ans = INF for s in list(D.keys()): use = {s: 0 for s in list(D.keys())} use[s] = 1 ans = find_candidate(ans, use, s, True) return ans if ans < INF else -1 if __name__ == "__main__": print((solve()))
import sys sys.setrecursionlimit(10**9) INF = 10**12 LIM = 20 N = int(eval(input())) D = dict() for _ in range(N): s, c = input().split() if s in list(D.keys()): D[s] = min(D[s], int(c)) else: D[s] = int(c) def check_kaibun(s): n = len(s) return all(s[i] == s[-i-1] for i in range(n//2)) def calc_cost(use): return sum(D[s] * n for (s, n) in list(use.items())) def find_candidate(cost, use, s, is_left): if check_kaibun(s): return min(cost, calc_cost(use)) if is_left: for t in list(D.keys()): # reversed s is included in the end of t if t[::-1].find(s) == 0: use[t] += 1 if use[t] > LIM: return INF c = find_candidate(cost, use, t[:-len(s):], False) cost = min(cost, c) use[t] -= 1 # reveresed t is included in the begin of s elif s.find(t[::-1]) == 0: use[t] += 1 c = find_candidate(cost, use, s[len(t):], True) cost = min(cost, c) use[t] -= 1 else: for t in list(D.keys()): # t is included in the end of reversed s if s[::-1].find(t) == 0: use[t] += 1 c = find_candidate(cost, use, s[:-len(t):], False) cost = min(cost, c) use[t] -= 1 # s is included in the begin of reveresed t elif t.find(s[::-1]) == 0: use[t] += 1 c = find_candidate(cost, use, t[len(s):], True) cost = min(cost, c) use[t] -= 1 return min(cost, INF) def solve(): ans = INF for s in list(D.keys()): use = {s: 0 for s in list(D.keys())} use[s] = 1 ans = find_candidate(ans, use, s, True) return ans if ans < INF else -1 if __name__ == "__main__": print((solve()))
p02587
# coding: utf-8 import sys #from operator import itemgetter sysread = sys.stdin.buffer.readline read = sys.stdin.buffer.read from heapq import heappop, heappush #from collections import defaultdict sys.setrecursionlimit(10**7) #import math #from itertools import product, accumulate, combinations, product #import bisect #import numpy as np #from copy import deepcopy #from collections import deque #from decimal import Decimal #from numba import jit INF = 1 << 50 def search_next(l, r, SC): ll, lc = l rr, rc = r nexts = [] if len(ll) > len(rr): part = ll[::-1] for s,c in SC: if s[-len(part):] == part: r_n = (s[:-len(ll)], rc + c) l_n = ('', lc) nexts.append((rc+c+lc, (l_n, r_n))) elif s == part[-len(s):]: l_n =(ll[len(s):], lc) r_n = ('', rc + c) nexts.append((rc + c + lc, (l_n, r_n))) else: part = rr[::-1] for s, c in SC: if s[:len(part)] == part: l_n = (s[len(rr):], lc + c) r_n = ('', rc) nexts.append((lc+rc+c, (l_n, r_n))) elif s == part[:len(s)]: r_n = (rr[:-len(s)], rc) l_n = ('', lc + c) nexts.append((lc + rc + c, (l_n, r_n))) return nexts def palindrome(l, r): if l + r == (l+r)[::-1]: return True else: return False def run(): totalL = 0 N = int(sysread()) SC = [] for i in range(N): s,c = input().split() c = int(c) SC.append((s,c)) totalL += len(s) min_val = INF for s,c in SC: queue = [] left = (s, c) right = ('', 0) heappush(queue, (c, (left, right))) done = False while queue: #print(queue) cost, (l, r) = heappop(queue) if palindrome(l[0], r[0]): done = True break nexts = search_next(l, r, SC) for n in nexts: heappush(queue, n) if done: min_val = min(min_val, cost) if min_val == INF: print((-1)) else: print(min_val) if __name__ == "__main__": run()
# coding: utf-8 import sys #from operator import itemgetter sysread = sys.stdin.buffer.readline read = sys.stdin.buffer.read from heapq import heappop, heappush #from collections import defaultdict sys.setrecursionlimit(10**7) #import math #from itertools import product, accumulate, combinations, product #import bisect #import numpy as np #from copy import deepcopy #from collections import deque #from decimal import Decimal #from numba import jit INF = 1 << 50 def search_next(l, r, SC): ll, lc = l rr, rc = r nexts = [] if len(ll) > len(rr): part = ll[::-1] for s,c in SC: if s[-len(part):] == part: r_n = (s[:-len(ll)], rc + c) l_n = ('', lc) nexts.append((rc+c+lc, (l_n, r_n))) elif s == part[-len(s):]: l_n =(ll[len(s):], lc) r_n = ('', rc + c) nexts.append((rc + c + lc, (l_n, r_n))) else: part = rr[::-1] for s, c in SC: if s[:len(part)] == part: l_n = (s[len(rr):], lc + c) r_n = ('', rc) nexts.append((lc+rc+c, (l_n, r_n))) elif s == part[:len(s)]: r_n = (rr[:-len(s)], rc) l_n = ('', lc + c) nexts.append((lc + rc + c, (l_n, r_n))) return nexts def palindrome(l, r): if l + r == (l+r)[::-1]: return True else: return False def run(): totalL = 0 N = int(sysread()) SC = [] for i in range(N): s,c = input().split() c = int(c) SC.append((s,c)) totalL += len(s) min_val = INF for s,c in SC: queue = [] left = (s, c) right = ('', 0) heappush(queue, (c, (left, right))) done = False count = 0 while queue: count += 1 if count > 200000:break #print(queue) cost, (l, r) = heappop(queue) if palindrome(l[0], r[0]): done = True #print(l, r) break nexts = search_next(l, r, SC) for n in nexts: heappush(queue, n) if done: min_val = min(min_val, cost) if min_val == INF: print((-1)) else: print(min_val) if __name__ == "__main__": run()
p02587
import sys sys.setrecursionlimit(2*10**9) from collections import defaultdict inf = 10**18 def main(): N = int(eval(input())) S1 = [] S2 = [] C = [] for i in range(N): s,c = input().split() S1.append(s) S2.append(s[::-1]) C.append(int(c)) d_l = defaultdict(lambda:inf) def left(s1): res = inf-1 if s1==s1[::-1]: return 0 if d_l[s1] != inf: return d_l[s1] for i in range(N): s2 = S2[i] c = C[i] if s1.startswith(s2): res = min(res,left(s1[len(s2):])+c) if s2.startswith(s1): res = min(res,right(s2[len(s1):])+c) d_l[s1] = res return res d_r = defaultdict(lambda:inf) def right(s2): res = inf-1 if s2==s2[::-1]: return 0 if d_r[s2] != inf: return d_r[s2] for i in range(N): s1 = S1[i] c = C[i] if s1.startswith(s2): res = min(res,left(s1[len(s2):])+c) if s2.startswith(s1): res = min(res,right(s2[len(s1):])+c) d_r[s2] = res return res ans = inf for i in range(N): ans = min(ans,left(S1[i])+C[i]) if ans == inf: ans = -1 print(ans) if __name__ == '__main__': main()
from heapq import heappush, heappop inf = float('inf') def dijkstra(graph:list, node:int, start:int) -> list: dist = [inf]*node dist[start] = 0 heap = [(0,start)] while heap: cost,thisNode = heappop(heap) for NextCost,NextNode in graph[thisNode]: dist_cand = dist[thisNode]+NextCost if dist_cand < dist[NextNode]: dist[NextNode] = dist_cand heappush(heap,(dist[NextNode],NextNode)) return dist N = int(eval(input())) S1 = [] S2 = [] C = [] for i in range(N): s,c = input().split() S1.append(s) S2.append(s[::-1]) C.append(int(c)) d_v = {('',''):0,('l',''):1,('r',''):2} idx = 3 for i in range(N): s = S1[i] for j in range(len(s)): for k in range(j,len(s)): ss_l = s[j:k+1] ss_r = ss_l[::-1] if ss_l != ss_r: if ('l',ss_l) not in d_v: d_v[('l',ss_l)] = idx idx += 1 if ('r',ss_r) not in d_v: d_v[('r',ss_r)] = idx idx += 1 edge = [[] for _ in range(len(d_v))] for i in range(N): s_l = S1[i] s_r = S2[i] c = C[i] for lr,ss in d_v: if ss == '': if lr == '': t = s_l if t==t[::-1]: t = '' edge[0].append((c,d_v[('l',t)])) else: continue if lr == 'l': if ss.startswith(s_r): t = ss[len(s_r):] if t==t[::-1]: t = '' edge[d_v[(lr,ss)]].append((c,d_v[('l',t)])) if s_r.startswith(ss): t = s_r[len(ss):] if t==t[::-1]: t = '' edge[d_v[(lr,ss)]].append((c,d_v[('r',t)])) elif lr == 'r': if ss.startswith(s_l): t = ss[len(s_l):] if t==t[::-1]: t = '' edge[d_v[(lr,ss)]].append((c,d_v[('r',t)])) if s_l.startswith(ss): t = s_l[len(ss):] if t==t[::-1]: t = '' edge[d_v[(lr,ss)]].append((c,d_v[('l',t)])) dist = dijkstra(edge,len(d_v),0) ans = min(dist[1],dist[2]) if ans == inf: ans = -1 print(ans)
p02587
# -*- coding: utf-8 -*- ############# # Libraries # ############# import sys input = sys.stdin.readline import math #from math import gcd import bisect import heapq from collections import defaultdict from collections import deque from collections import Counter from functools import lru_cache ############# # Constants # ############# MOD = 10**9+7 INF = float('inf') AZ = "abcdefghijklmnopqrstuvwxyz" ############# # Functions # ############# ######INPUT###### def I(): return int(input().strip()) def S(): return input().strip() def IL(): return list(map(int,input().split())) def SL(): return list(map(str,input().split())) def ILs(n): return list(int(eval(input())) for _ in range(n)) def SLs(n): return list(input().strip() for _ in range(n)) def ILL(n): return [list(map(int, input().split())) for _ in range(n)] def SLL(n): return [list(map(str, input().split())) for _ in range(n)] #####Shorten##### def DD(arg): return defaultdict(arg) #####Inverse##### def inv(n): return pow(n, MOD-2, MOD) ######Combination###### kaijo_memo = [] def kaijo(n): if(len(kaijo_memo) > n): return kaijo_memo[n] if(len(kaijo_memo) == 0): kaijo_memo.append(1) while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD) return kaijo_memo[n] gyaku_kaijo_memo = [] def gyaku_kaijo(n): if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n] if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1) while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD) return gyaku_kaijo_memo[n] def nCr(n,r): if n == r: return 1 if n < r or r < 0: return 0 ret = 1 ret = ret * kaijo(n) % MOD ret = ret * gyaku_kaijo(r) % MOD ret = ret * gyaku_kaijo(n-r) % MOD return ret ######Factorization###### def factorization(n): arr = [] temp = n for i in range(2, int(-(-n**0.5//1))+1): if temp%i==0: cnt=0 while temp%i==0: cnt+=1 temp //= i arr.append([i, cnt]) if temp!=1: arr.append([temp, 1]) if arr==[]: arr.append([n, 1]) return arr #####MakeDivisors###### def make_divisors(n): divisors = [] for i in range(1, int(n**0.5)+1): if n % i == 0: divisors.append(i) if i != n // i: divisors.append(n//i) return divisors #####MakePrimes###### def make_primes(N): max = int(math.sqrt(N)) seachList = [i for i in range(2,N+1)] primeNum = [] while seachList[0] <= max: primeNum.append(seachList[0]) tmp = seachList[0] seachList = [i for i in seachList if i % tmp != 0] primeNum.extend(seachList) return primeNum #####GCD##### def gcd(a, b): while b: a, b = b, a % b return a #####LCM##### def lcm(a, b): return a * b // gcd (a, b) #####BitCount##### def count_bit(n): count = 0 while n: n &= n-1 count += 1 return count #####ChangeBase##### def base_10_to_n(X, n): if X//n: return base_10_to_n(X//n, n)+[X%n] return [X%n] def base_n_to_10(X, n): return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X)))) def base_10_to_n_without_0(X, n): X -= 1 if X//n: return base_10_to_n_without_0(X//n, n)+[X%n] return [X%n] #####IntLog##### def int_log(n, a): count = 0 while n>=a: n //= a count += 1 return count ############# # Main Code # ############# N = I() data = SLL(N) words = [] costs = [] nodes = {("",0),("",1)} best = INF for d in data: word = d[0] cost = int(d[1]) if word == word[::-1]: best = min(best,cost) continue words.append(word) costs.append(cost) for j in range(len(word)): nodes.add((word[:j+1],0)) nodes.add((word[:j+1],1)) nodes.add((word[j:],0)) nodes.add((word[j:],1)) graph = {k:[] for k in nodes} graph[("",1)].append((0,("",0))) for k in nodes: amari = k[0] t = k[1] if amari == amari[::-1]: if amari: graph[k].append((0,("",0))) else: n = len(amari) for i in range(len(words)): word = words[i] cost = costs[i] if t == 0: if len(word)>n: if amari == word[::-1][:n]: graph[k].append((cost,(word[:-n],1))) else: if amari[:len(word)] == word[::-1]: graph[k].append((cost,(amari[len(word):],0))) else: if len(word)>n: if amari[::-1] == word[:n]: graph[k].append((cost,(word[n:],0))) else: if amari[::-1][:len(word)] == word: graph[k].append((cost,(amari[:-len(word)],1))) def dijkstra(graph, start,cost): N = len(graph) d = {k:INF for k in nodes} d[start] = cost f = {k:False for k in nodes} q = [(cost, start)] while q: c,u = heapq.heappop(q) if f[u]: continue d[u] = c f[u] = True for c,v in graph[u]: if not f[v]: heapq.heappush(q, (c + d[u], v)) return d for i in range(len(words)): word = words[i] cost = costs[i] best = min(best,dijkstra(graph,(word,0),cost)[("",0)]) best = min(best,dijkstra(graph,(word,1),cost)[("",0)]) if best == INF: print((-1)) else: print(best)
# -*- coding: utf-8 -*- ############# # Libraries # ############# import sys input = sys.stdin.readline import math #from math import gcd import bisect import heapq from collections import defaultdict from collections import deque from collections import Counter from functools import lru_cache ############# # Constants # ############# MOD = 10**9+7 INF = float('inf') AZ = "abcdefghijklmnopqrstuvwxyz" ############# # Functions # ############# ######INPUT###### def I(): return int(input().strip()) def S(): return input().strip() def IL(): return list(map(int,input().split())) def SL(): return list(map(str,input().split())) def ILs(n): return list(int(eval(input())) for _ in range(n)) def SLs(n): return list(input().strip() for _ in range(n)) def ILL(n): return [list(map(int, input().split())) for _ in range(n)] def SLL(n): return [list(map(str, input().split())) for _ in range(n)] #####Shorten##### def DD(arg): return defaultdict(arg) #####Inverse##### def inv(n): return pow(n, MOD-2, MOD) ######Combination###### kaijo_memo = [] def kaijo(n): if(len(kaijo_memo) > n): return kaijo_memo[n] if(len(kaijo_memo) == 0): kaijo_memo.append(1) while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD) return kaijo_memo[n] gyaku_kaijo_memo = [] def gyaku_kaijo(n): if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n] if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1) while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD) return gyaku_kaijo_memo[n] def nCr(n,r): if n == r: return 1 if n < r or r < 0: return 0 ret = 1 ret = ret * kaijo(n) % MOD ret = ret * gyaku_kaijo(r) % MOD ret = ret * gyaku_kaijo(n-r) % MOD return ret ######Factorization###### def factorization(n): arr = [] temp = n for i in range(2, int(-(-n**0.5//1))+1): if temp%i==0: cnt=0 while temp%i==0: cnt+=1 temp //= i arr.append([i, cnt]) if temp!=1: arr.append([temp, 1]) if arr==[]: arr.append([n, 1]) return arr #####MakeDivisors###### def make_divisors(n): divisors = [] for i in range(1, int(n**0.5)+1): if n % i == 0: divisors.append(i) if i != n // i: divisors.append(n//i) return divisors #####MakePrimes###### def make_primes(N): max = int(math.sqrt(N)) seachList = [i for i in range(2,N+1)] primeNum = [] while seachList[0] <= max: primeNum.append(seachList[0]) tmp = seachList[0] seachList = [i for i in seachList if i % tmp != 0] primeNum.extend(seachList) return primeNum #####GCD##### def gcd(a, b): while b: a, b = b, a % b return a #####LCM##### def lcm(a, b): return a * b // gcd (a, b) #####BitCount##### def count_bit(n): count = 0 while n: n &= n-1 count += 1 return count #####ChangeBase##### def base_10_to_n(X, n): if X//n: return base_10_to_n(X//n, n)+[X%n] return [X%n] def base_n_to_10(X, n): return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X)))) def base_10_to_n_without_0(X, n): X -= 1 if X//n: return base_10_to_n_without_0(X//n, n)+[X%n] return [X%n] #####IntLog##### def int_log(n, a): count = 0 while n>=a: n //= a count += 1 return count ############# # Main Code # ############# N = I() data = SLL(N) words = [] costs = [] nodes = {("",0),("",1)} best = INF for d in data: word = d[0] cost = int(d[1]) if word == word[::-1]: best = min(best,cost) continue words.append(word) costs.append(cost) for j in range(len(word)): nodes.add((word[:j+1],1)) nodes.add((word[j:],0)) graph = {k:[] for k in nodes} graph[("",1)].append((0,("",0))) for k in nodes: amari = k[0] t = k[1] if amari == amari[::-1]: if amari: graph[k].append((0,("",0))) else: n = len(amari) for i in range(len(words)): word = words[i] cost = costs[i] if t == 0: if len(word)>n: if amari == word[::-1][:n]: graph[k].append((cost,(word[:-n],1))) else: if amari[:len(word)] == word[::-1]: graph[k].append((cost,(amari[len(word):],0))) else: if len(word)>n: if amari[::-1] == word[:n]: graph[k].append((cost,(word[n:],0))) else: if amari[::-1][:len(word)] == word: graph[k].append((cost,(amari[:-len(word)],1))) def dijkstra(graph, start,cost): N = len(graph) d = {k:INF for k in nodes} d[start] = cost f = {k:False for k in nodes} q = [(cost, start)] while q: c,u = heapq.heappop(q) if f[u]: continue d[u] = c f[u] = True for c,v in graph[u]: if not f[v]: heapq.heappush(q, (c + d[u], v)) return d for i in range(len(words)): word = words[i] cost = costs[i] best = min(best,dijkstra(graph,(word,0),cost)[("",0)]) best = min(best,dijkstra(graph,(word,1),cost)[("",0)]) if best == INF: print((-1)) else: print(best)
p02587
#!usr/bin/env python3 from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect 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 def solve(): def dfs(pre, suf): ns = pre+suf[::-1] if ns != [] and ns == ns[::-1]: return 0 res = 0 cos = float("inf") if len(pre) <= len(suf): k = suf[len(pre):] for i in range(n): s = lis[i] m = min(len(s),len(k)) if k[:m] == s[:m]: re = dfs(pre+s,suf)+c[i] if re < cos: cos = re else: k = pre[len(suf):] for i in range(n): s = rev[i] m = min(len(s),len(k)) if k[:m] == s[:m]: re = dfs(pre,suf+s)+c[i] if re < cos: cos = re return res+cos n = I() lis = [] c = [] rev = [] for _ in range(n): a,b = input().split() b = int(b) a = list(a) lis.append(a) rev.append(a[::-1]) c.append(b) ans = dfs([],[]) res = defaultdict(lambda : float("inf")) q = [(0,[],[])] res[(tuple(),tuple())] = 0 while q: d,pre,suf = heappop(q) ns = pre+suf[::-1] if ns != [] and ns == ns[::-1]: print(d) return if len(pre) <= len(suf): k = suf[len(pre):] for i in range(n): s = lis[i] m = min(len(s),len(k)) if k[:m] == s[:m]: npre = pre+s re = d+c[i] i = tuple(npre) j = tuple(suf) if re < res[(i,j)]: res[(i,j)] = re heappush(q,(re,npre,suf)) else: k = pre[len(suf):] for i in range(n): s = rev[i] m = min(len(s),len(k)) if k[:m] == s[:m]: nsuf = suf+s re = d+c[i] i = tuple(pre) j = tuple(nsuf) if re < res[(i,j)]: res[(i,j)] = re heappush(q,(re,pre,nsuf)) print((-1)) return #Solve if __name__ == "__main__": solve()
#!usr/bin/env python3 from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect 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 def solve(): n = I() lis = [] c = [] rev = [] for _ in range(n): a,b = input().split() b = int(b) a = list(a) lis.append(a) rev.append(a[::-1]) c.append(b) res = defaultdict(lambda : float("inf")) q = [(0,[],[])] res[(tuple(),tuple())] = 0 while q: d,pre,suf = heappop(q) ns = pre+suf[::-1] if ns != [] and ns == ns[::-1]: print(d) return if len(pre) <= len(suf): k = suf[len(pre):] for i in range(n): s = lis[i] m = min(len(s),len(k)) if k[:m] == s[:m]: npre = pre+s re = d+c[i] i = tuple(npre) j = tuple(suf) if re < res[(i,j)]: res[(i,j)] = re heappush(q,(re,npre,suf)) else: k = pre[len(suf):] for i in range(n): s = rev[i] m = min(len(s),len(k)) if k[:m] == s[:m]: nsuf = suf+s re = d+c[i] i = tuple(pre) j = tuple(nsuf) if re < res[(i,j)]: res[(i,j)] = re heappush(q,(re,pre,nsuf)) print((-1)) return #Solve if __name__ == "__main__": solve()
p02587
from collections import deque def isPalindrome(s): L = len(s) return all(s[i] == s[L - 1 - i] for i in range(L // 2)) N = int(eval(input())) S = [] for _ in range(N): s, c = input().split() S.append((s, int(c))) path = [dict() for _ in range(2)] q = deque() # S.sort(key=lambda x: x[1]) for s, c in S: if s not in path[0] or path[0][s] > c: path[0][s] = c q.append((0, s, c)) INF = 10 ** 15 ans = INF while q: side, s0, c0 = q.popleft() if isPalindrome(s0): ans = min(ans, c0) else: for s1, c1 in S: if side == 0: l, r = s0, s1 else: l, r = s1, s0 L = len(l) R = len(r) isCandidate = False if L > R: if all(l[i] == r[-1 - i] for i in range(R)): ns = l[len(r):] nc = c0 + c1 nside = 0 isCandidate |= True elif L < R: if all(l[i] == r[-1 - i] for i in range(L)): ns = r[:-len(l)] nc = c0 + c1 nside = 1 isCandidate |= True else: if all(l[i] == r[-1 - i] for i in range(L)): ns = '' nc = c0 + c1 nside = 0 isCandidate |= True if isCandidate and (ns not in path[nside] or path[nside][ns] > nc): path[nside][ns] = nc q.append((nside, ns, nc)) if ans < INF: print(ans) else: print((-1))
from collections import deque def isPalindrome(s): L = len(s) return all(s[i] == s[L - 1 - i] for i in range(L // 2)) N = int(eval(input())) S = [] for _ in range(N): s, c = input().split() S.append((s, int(c))) path = [dict() for _ in range(2)] q = deque() S.sort(key=lambda x: x[1]) for s, c in S: if s not in path[0] or path[0][s] > c: path[0][s] = c q.append((0, s, c)) INF = 10 ** 15 ans = INF while q: side, s0, c0 = q.popleft() if isPalindrome(s0): ans = min(ans, c0) else: for s1, c1 in S: if side == 0: l, r = s0, s1 else: l, r = s1, s0 L = len(l) R = len(r) isCandidate = False if L > R: if all(l[i] == r[-1 - i] for i in range(R)): ns = l[len(r):] nc = c0 + c1 nside = 0 isCandidate |= True elif L < R: if all(l[i] == r[-1 - i] for i in range(L)): ns = r[:-len(l)] nc = c0 + c1 nside = 1 isCandidate |= True else: if all(l[i] == r[-1 - i] for i in range(L)): ns = '' nc = c0 + c1 nside = 0 isCandidate |= True if isCandidate and (ns not in path[nside] or path[nside][ns] > nc): path[nside][ns] = nc q.append((nside, ns, nc)) if ans < INF: print(ans) else: print((-1))
p02587
from collections import deque def isPalindrome(s): L = len(s) return all(s[i] == s[L - 1 - i] for i in range(L // 2)) N = int(eval(input())) S = [] for _ in range(N): s, c = input().split() S.append((s, int(c))) path = [dict() for _ in range(2)] q = deque() S.sort(key=lambda x: x[1]) for s, c in S: if s not in path[0] or path[0][s] > c: path[0][s] = c q.append((0, s, c)) INF = 10 ** 15 ans = INF while q: side, s0, c0 = q.popleft() if isPalindrome(s0): ans = min(ans, c0) else: for s1, c1 in S: if side == 0: l, r = s0, s1 else: l, r = s1, s0 L = len(l) R = len(r) isCandidate = False if L > R: if all(l[i] == r[-1 - i] for i in range(R)): ns = l[len(r):] nc = c0 + c1 nside = 0 isCandidate |= True elif L < R: if all(l[i] == r[-1 - i] for i in range(L)): ns = r[:-len(l)] nc = c0 + c1 nside = 1 isCandidate |= True else: if all(l[i] == r[-1 - i] for i in range(L)): ns = '' nc = c0 + c1 nside = 0 isCandidate |= True if isCandidate and (ns not in path[nside] or path[nside][ns] > nc): path[nside][ns] = nc q.append((nside, ns, nc)) if ans < INF: print(ans) else: print((-1))
from collections import deque def isPalindrome(s): ''' s: string が回文か判定する. 回文 -> True, 回文でない -> False. ''' L = len(s) return all(s[i] == s[L - 1 - i] for i in range(L // 2)) N = int(eval(input())) S = [] for _ in range(N): s, c = input().split() S.append((s, int(c))) path = [dict() for _ in range(2)] # 余り文字列へ到達するコスト, path[0]:左側余り, path[1]: 右側余り q = deque() S.sort(key=lambda x: x[1]) # コストの小さい順にソートしておくと速くなる. # 初期処理. Siを左側余り文字列と見做してキューに入れていく. for s, c in S: if s not in path[0] or path[0][s] > c: path[0][s] = c q.append((0, s, c)) INF = 10 ** 15 ans = INF while q: side, s0, c0 = q.popleft() if isPalindrome(s0): # 余り文字列自体が回文のとき ans = min(ans, c0) else: # 余り文字列が回文でないとき, 他の文字列を追加する for s1, c1 in S: if side == 0: l, r = s0, s1 else: l, r = s1, s0 L = len(l) R = len(r) isCandidate = False # s1が追加可能な文字列かどうかを示すフラグ if L > R: if all(l[i] == r[-1 - i] for i in range(R)): ns = l[R:] nc = c0 + c1 nside = 0 isCandidate |= True elif L < R: if all(l[i] == r[-1 - i] for i in range(L)): ns = r[:-L] nc = c0 + c1 nside = 1 isCandidate |= True else: if all(l[i] == r[-1 - i] for i in range(L)): ns = '' nc = c0 + c1 nside = 0 isCandidate |= True if isCandidate and (ns not in path[nside] or path[nside][ns] > nc): path[nside][ns] = nc q.append((nside, ns, nc)) if ans < INF: print(ans) else: print((-1))
p02587
n = int(eval(input())) def stairs(n): if (n == 1): return 1 elif(n == 2): return 2 elif(n == 3): return 4 return stairs(n-1) + stairs(n-2) + stairs(n-3) while (n != 0): pn = stairs(n) if (pn%10 == 0): pn //= 10 else: pn = pn//10 + 1 if (pn%365 == 0): pn //= 365 else: pn = pn//365 + 1 print(pn) n = int(eval(input()))
n = int(eval(input())) st = [1,2,4] for i in range(n-3): s = st[-1] + st[-2] + st[-3] st.append(s) while (n != 0): pn = st[n-1] if (pn%10 == 0): pn //= 10 else: pn = pn//10 + 1 if (pn%365 == 0): pn //= 365 else: pn = pn//365 + 1 print(pn) n = int(eval(input())) st = [1,2,4] for i in range(n-3): s = st[-1] + st[-2] + st[-3] st.append(s)
p00168
import functools #@functools.lru_cache(maxsize=None) def rec(i): if i <= 0: return i == 0 return rec(i-1) + rec(i-2) + rec(i-3) while True: N = int(eval(input())) if not N: break print((((rec(N)-1)//10)//365+1))
import functools @functools.lru_cache(maxsize=None) def rec(i): if i <= 0: return i == 0 return rec(i-1) + rec(i-2) + rec(i-3) while True: N = int(eval(input())) if not N: break print((rec(N)//3650+1))
p00168
def up(n): if n == 0: return 1 if n < 0: return 0 return up(n-1)+up(n-2)+up(n-3) while True: n = int(input()) if n == 0: break print((up(n)//10+1)//365+1)
def up(n): goal = [0 for i in range(n)] goal[:3] = [1,2,4] for i in range(3,n): goal[i] = sum(goal[i-3:i]) return goal[-1] while True: n = int(input()) if n == 0: break print((up(n)//10+1)//365+1)
p00168
from math import ceil dp = [1] + [0 for i in range(30)] for i in range(1,31): for step in [1,2,3]: if step <= i: dp[i] += dp[i-step] unit = 3650. while 1: n = int(input()) if n == 0: break print(int(ceil(dp[n] / unit)))
from math import ceil dp = [1] + [0 for i in range(33)] for i in range(0,30): for step in [1,2,3]: dp[i+step] += dp[i] unit = 3650. while 1: n = int(input()) if n == 0: break print(int(ceil(dp[n] / unit)))
p00168
from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor from operator import mul from functools import reduce sys.setrecursionlimit(2147483647) INF = 10 ** 13 def LI(): return list(map(int, sys.stdin.readline().split())) def I(): return int(sys.stdin.readline()) def LS(): return sys.stdin.readline().rstrip().split() def S(): return sys.stdin.readline().rstrip() 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)] def SRL(n): return [list(S()) for i in range(n)] def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)] mod = 998244353 n = I() x = S() rx=x.replace("1","2").replace("0","1").replace("2","0") D = [] for i in range(1, int(n**0.5)+1): if n % i == 0: if n // i % 2: D += [i] if i != n // i and i % 2: D += [n // i] D.sort() bx=int(x,2) cnt = [0] * len(D) ans = 0 for k in range(len(D)): t=x[:D[k]] rt=rx[:D[k]] f=(t+rt)*(n//D[k]//2)+t cnt[k]=cnt[k]+int(int(f,2)<=bx)+int(t,2) cnt[k]%=mod ans += cnt[k]*D[k]*2 for kk in range(k + 1, len(D)): if D[kk] % D[k] == 0: cnt[kk] -= cnt[k] cnt[kk]%=mod ans %= mod print((ans % mod))
from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor from operator import mul from functools import reduce sys.setrecursionlimit(2147483647) INF = 10 ** 13 def LI(): return list(map(int, sys.stdin.readline().split())) def I(): return int(sys.stdin.readline()) def LS(): return sys.stdin.readline().rstrip().split() def S(): return sys.stdin.readline().rstrip() 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)] def SRL(n): return [list(S()) for i in range(n)] def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)] mod = 998244353 n = I() x = S() rx=x.replace("1","2").replace("0","1").replace("2","0") D = [] for i in range(1, int(n**0.5)+1): if n % i == 0: if n // i % 2: D += [i] if i != n // i and i % 2: D += [n // i] D.sort() bx=int(x,2) cnt = [0] * len(D) ans = 0 for k in range(len(D)): t=x[:D[k]] rt=rx[:D[k]] f=(t+rt)*(n//D[k]//2)+t cnt[k]=cnt[k]+int(f<=x)+int(t,2) cnt[k]%=mod ans += cnt[k]*D[k]*2 for kk in range(k + 1, len(D)): if D[kk] % D[k] == 0: cnt[kk] -= cnt[k] cnt[kk]%=mod ans %= mod print((ans % mod))
p02893
N=int(eval(input())) for _ in[0]*int(eval(input())): a,b=list(map(int,input().split())) print((min(a-1,N-a,b-1,N-b)%3+1))
import sys N=int(eval(input())) eval(input()) for e in sys.stdin: a,b=list(map(int,e.split())) print((min(a-1,N-a,b-1,N-b)%3+1))
p00479
import math #import numpy as np import queue from collections import deque,defaultdict import heapq as hpq from sys import stdin,setrecursionlimit #from scipy.sparse.csgraph import dijkstra #from scipy.sparse import csr_matrix ipt = stdin.readline setrecursionlimit(10**7) def main(): n,k = list(map(int,ipt().split())) a = list(map(int,ipt().split())) # n = 2*10**5 # k = 2*10**5 # a = [i+1 for i in range(n)] nxt = [-1]*(n) pa = [-1]*(2*10**5+1) for i,ai in enumerate(a*2): pai = pa[ai] if pai == -2: continue if pai == -1: pa[ai] = i else: nxt[pai] = i-pai+1 if i <= n-1: pa[ai] = i else: pa[ai] = -2 dbl = [nxt] ni = 1 while ni <= n*k: nnxt = [0]*n pnxt = dbl[-1] for i in range(n): nnxt[i] = pnxt[i]+pnxt[(i+pnxt[i])%n] dbl.append(nnxt) if min(nnxt) > n*k: break ni *= 2 np = 0 ld = len(dbl) ni = len(dbl)-1 # print(dbl) for db in dbl[::-1]: while True: if db[np%n] < n*k-1-np: np += db[np%n] else: break # print(np) ans = [] for i in range(np%n,n): ai = a[i] if ai in ans: ans = ans[:ans.index(ai)] else: ans.append(ai) print((" ".join(map(str,ans)))) return if __name__ == '__main__': main()
import math #import numpy as np import queue from collections import deque,defaultdict import heapq as hpq from sys import stdin,setrecursionlimit #from scipy.sparse.csgraph import dijkstra #from scipy.sparse import csr_matrix ipt = stdin.readline setrecursionlimit(10**7) def main(): n,k = list(map(int,ipt().split())) a = list(map(int,ipt().split())) # n = 2*10**5 # k = 2*10**5 # a = [i+1 for i in range(n)] nxt = [-1]*(n) pa = [-1]*(2*10**5+1) for i,ai in enumerate(a*2): pai = pa[ai] if pai == -2: continue if pai == -1: pa[ai] = i else: nxt[pai] = i-pai+1 if i <= n-1: pa[ai] = i else: pa[ai] = -2 dbl = [nxt] ni = 1 while ni <= n*k: nnxt = [0]*n pnxt = dbl[-1] for i in range(n): nnxt[i] = pnxt[i]+pnxt[(i+pnxt[i])%n] dbl.append(nnxt) if min(nnxt) > n*k: break ni *= 2 np = 0 ld = len(dbl) ni = len(dbl)-1 # print(dbl) for db in dbl[::-1]: while True: if db[np%n] < n*k-1-np: np += db[np%n] else: break # print(np) ans = [] np %= n while np < n: if nxt[np]+np > n: ans.append(a[np]) np += 1 elif nxt[np]+np == n: np = n else: np = nxt[np]+np print((" ".join(map(str,ans)))) return if __name__ == '__main__': main()
p02964
import bisect n,k = list(map(int,input().split())) a = list(map(int,input().split())) ind = [[] for _ in range(2*10**5 + 1)] for i,num in enumerate(a): ind[num].append(i) for i in range(1,2*10**5 + 1): if(ind[i]): ind[i].append(ind[i][0] + n) cnt = 0 now = a[0] while(True): right = bisect.bisect_right(ind[now], cnt%n) cnt += ind[now][right] - ind[now][right-1] + 1 now = a[cnt%n] if(cnt%n == 0): break cyc = k%(cnt//n) cnt = 0 now =a[0] while(True): right = bisect.bisect_right(ind[now], cnt%n) cnt += ind[now][right] - ind[now][right-1] + 1 if(cnt//n == cyc): cnt -= ind[now][right] - ind[now][right-1] + 1 break now = a[cnt%n] cnt %= n ans = [] while(cnt < n): now = a[cnt] right = bisect.bisect_right(ind[now],cnt) if(ind[now][right] >= n): ans.append(now) cnt += 1 else: cnt = ind[now][right] + 1 print((' '.join(map(str,ans))))
import bisect n,k = list(map(int,input().split())) a = list(map(int,input().split())) ind = [[] for _ in range(2*10**5 + 1)] for i,num in enumerate(a): ind[num].append(i) for i in range(1,2*10**5 + 1): if(ind[i]): ind[i].append(ind[i][0] + n) before = [] cnt = 0 now = a[0] while(True): right = bisect.bisect_right(ind[now], cnt%n) cnt += ind[now][right] - ind[now][right-1] + 1 if(ind[now][right] >= n): before.append(ind[now][right-1]) now = a[cnt%n] if(cnt%n == 0): break if(cnt//n==1): print('') exit() cyc = k%(cnt//n) cnt = before[cyc-1] ans = [] while(cnt < n): now = a[cnt] right = bisect.bisect_right(ind[now],cnt) if(ind[now][right] >= n): ans.append(now) cnt += 1 else: cnt = ind[now][right] + 1 print((' '.join(map(str,ans))))
p02964
import sys input = sys.stdin.readline ''' 9 4 1 8 6 6 8 7 8 1 9 ''' N, K = list(map(int, input().split())) A = [int(i) for i in input().split()] last = dict() v = [-1] * N for i, a in enumerate(A + A) : if a in last and last[a] < N : v[last[a]] = i + 1 last[a] = i dist = [-1] * N cur = 0 s = 0 while dist[cur] < 0 : dist[cur] = s s += v[cur] - cur cur = v[cur] % N # d1 - ループに入るまでの長さ, d2 - ループの長さ d1 = dist[cur] d2 = s - d1 NK = N * K if NK > d1 : m = (NK-d1) % d2 cur = v[cur] % N s = 0 while m > dist[cur] - d1 > 0 : s = dist[cur] - d1 cur = v[cur] % N m -= s else : m = N ret = [] if m != 0 : last = dict() for a in A[-m:] : if a in ret : ret = ret[:ret.index(a)] else : ret.append(a) print((' '.join([str(i) for i in ret])))
import sys input = sys.stdin.readline N, K = list(map(int, input().split())) A = [int(i) for i in input().split()] last = dict() v = [-1] * N for i, a in enumerate(A + A) : if a in last and last[a] < N : v[last[a]] = i + 1 last[a] = i dist = [-1] * N cur = 0 cycle = 0 while dist[cur] < 0 : dist[cur] = cycle cycle += v[cur] - cur cur = v[cur] % N NK = N * K m = NK % cycle cur = v[cur] % N s = 0 while m > dist[cur] > 0 : s = dist[cur] cur = v[cur] % N m -= s ret = [] seen = set() for a in A[N-m:] : if a in seen : p = ret.pop() seen.remove(a) while p != a : seen.remove(p) p = ret.pop() else : ret.append(a) seen.add(a) print((' '.join([str(i) for i in ret])))
p02964
def examA(): N = DI()/dec(7) ans = N print(N) return def examB(): N, K = LI() A = LI() maxA = max(A) def function(s): stack = deque() num = [0]*(maxA+1) for i in range(s,N): a = A[i] if num[a]==0: stack.append(a) num[a] += 1 else: while(num[a]>0): num[stack.pop()] -= 1 return stack B = [-1 for _ in range(N)] que = {} for i in range(N): a = A[i] if a not in que: que[a] = i else: prev = que.pop(a) B[prev] = i - prev que[a] = i i = 0 while(que): a = A[i] if a in que: prev = que.pop(a) B[prev] = N + i - prev i += 1 #print(B) locat_doubling = [[-1]*N for _ in range(61)] for i in range(N): locat_doubling[0][i] = 0 locat_doubling[1][i] = B[i] + 1 for k in range(2,61): for i in range(N): locat_doubling[k][i] = locat_doubling[k-1][i] + locat_doubling[k-1][(i+locat_doubling[k-1][i])%N] #print(locat_doubling[:5]) now = 0 rest = K*N for i in range(61)[::-1]: if locat_doubling[i][now]<=rest: rest -= locat_doubling[i][now] now = (locat_doubling[i][now]+now)%N #print(rest,now) ans = function(now) print((" ".join(map(str,ans)))) return def examC(): ans = 0 print(ans) return def examD(): ans = 0 print(ans) return def examE(): ans = 0 print(ans) return def examF(): ans = 0 print(ans) return from decimal import getcontext,Decimal as dec import sys,bisect,itertools,heapq,math,random from copy import deepcopy from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines def I(): return int(eval(input())) def LI(): return list(map(int,sys.stdin.readline().split())) def DI(): return dec(eval(input())) def LDI(): return list(map(dec,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,mod2,inf,alphabet,_ep mod = 10**9 + 7 mod2 = 998244353 inf = 10**18 _ep = dec("0.000000000001") alphabet = [chr(ord('a') + i) for i in range(26)] alphabet_convert = {chr(ord('a') + i): i for i in range(26)} getcontext().prec = 28 sys.setrecursionlimit(10**7) if __name__ == '__main__': examB() """ 142 12 9 1445 0 1 asd dfg hj o o aidn """
def examA(): N = DI()/dec(7) ans = N print(N) return def examB(): N, K = LI() A = LI() maxA = max(A) def function(s): stack = deque() num = [0]*(maxA+1) for i in range(s,N): a = A[i] if num[a]==0: stack.append(a) num[a] += 1 else: while(num[a]>0): num[stack.pop()] -= 1 return stack B = [-1 for _ in range(N)] que = {} for i in range(N): a = A[i] if a not in que: que[a] = i else: prev = que.pop(a) B[prev] = i - prev que[a] = i i = 0 while(que): a = A[i] if a in que: prev = que.pop(a) B[prev] = N + i - prev i += 1 #print(B) locat_doubling = [[-1]*N for _ in range(51)] for i in range(N): locat_doubling[0][i] = 0 locat_doubling[1][i] = B[i] + 1 for k in range(2,51): for i in range(N): locat_doubling[k][i] = locat_doubling[k-1][i] + locat_doubling[k-1][(i+locat_doubling[k-1][i])%N] if locat_doubling[k][i]>inf: locat_doubling[k][i] = inf #print(locat_doubling[:5]) now = 0 rest = K*N for i in range(51)[::-1]: if locat_doubling[i][now]<=rest: rest -= locat_doubling[i][now] now = (locat_doubling[i][now]+now)%N #print(rest,now) ans = function(now) print((" ".join(map(str,ans)))) return def examC(): ans = 0 print(ans) return def examD(): ans = 0 print(ans) return def examE(): ans = 0 print(ans) return def examF(): ans = 0 print(ans) return from decimal import getcontext,Decimal as dec import sys,bisect,itertools,heapq,math,random from copy import deepcopy from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines def I(): return int(eval(input())) def LI(): return list(map(int,sys.stdin.readline().split())) def DI(): return dec(eval(input())) def LDI(): return list(map(dec,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,mod2,inf,alphabet,_ep mod = 10**9 + 7 mod2 = 998244353 inf = 10**18 _ep = dec("0.000000000001") alphabet = [chr(ord('a') + i) for i in range(26)] alphabet_convert = {chr(ord('a') + i): i for i in range(26)} getcontext().prec = 28 sys.setrecursionlimit(10**7) if __name__ == '__main__': examB() """ 142 12 9 1445 0 1 asd dfg hj o o aidn """
p02964
from bisect import bisect from collections import defaultdict def main(): n, k = list(map(int, input().split())) *a, = list(map(int, input().split())) idx = defaultdict(list) for i, x in enumerate(a): idx[x].append(i) m = (k * n).bit_length() dub = [[0] * n for _ in range(m)] for i, x in enumerate(a): if i == idx[x][-1]: dub[0][i] = n + idx[x][0] - i else: dub[0][i] = idx[x][bisect(idx[x], i)] - i # print(dub[0]) for i in range(m - 1): for j in range(n): dub[i + 1][j] = dub[i][j] + 1 + dub[i][(j + dub[i][j] + 1) % n] # print(dub) now = -1 for i in range(m - 1, -1, -1): if now + 1 + dub[i][(now + 1) % n] < n * k: now += 1 + dub[i][(now + 1) % n] # print(now) if now == n * k: print("") exit() b = a[(now + 1) % n:] # print(b) inQ = {x: False for x in b} Q = [] for x in b: if inQ[x]: while Q[-1] != x: inQ[Q.pop()] = False Q.pop() inQ[x] = False else: inQ[x] = True Q.append(x) print((" ".join(map(str, Q)))) if __name__ == '__main__': main()
from bisect import bisect from collections import defaultdict def main(): n, k = list(map(int, input().split())) *a, = list(map(int, input().split())) idx = defaultdict(list) for i, x in enumerate(a): idx[x].append(i) m = (k * n).bit_length() dub = [[-1] * n for _ in range(m)] for i, x in enumerate(a): if i == idx[x][-1]: dub[0][i] = n + idx[x][0] - i else: dub[0][i] = idx[x][bisect(idx[x], i)] - i # print(dub[0]) for i in range(m - 1): for j in range(n): if dub[i][j]<n*k and dub[i][j]!=-1: dub[i + 1][j] = dub[i][j] + 1 + dub[i][(j + dub[i][j] + 1) % n] # print(dub) now = -1 for i in range(m - 1, -1, -1): if dub[i][(now+1)%n]!=-1 and now + 1 + dub[i][(now + 1) % n] < n * k: now += 1 + dub[i][(now + 1) % n] # print(now) if now == n * k: print("") exit() b = a[(now + 1) % n:] # print(b) inQ = {x: False for x in b} Q = [] for x in b: if inQ[x]: while Q[-1] != x: inQ[Q.pop()] = False Q.pop() inQ[x] = False else: inQ[x] = True Q.append(x) print((" ".join(map(str, Q)))) if __name__ == '__main__': main()
p02964
N, K = list(map(int, input().split())) As = list(map(int, input().split())) M = [[] for i in range(200001)] for i, a in enumerate(As): M[a].append(i) S = [] for i, a in enumerate(As): l = M[a] index = l.index(i) if index+1 == len(l): n = l[0]+N else: n = l[index+1] S.append(n+1-i) #print(S) p = 0 while True: p = p+S[p%N] if p%N == 0: break count = p//N #print(count) K = K%count #print(K) p = 0 while True: q = p+S[p%N] if q > N*K: break p = q index = p%N #print(index, As[index:N]) s = [] for a in As[index:N]: i = -1 for j in range(len(s)): if s[j] == a: i = j if i < 0: s.append(a) else: s = s[0:i] print((" ".join(map(str, s))))
N, K = list(map(int, input().split())) As = list(map(int, input().split())) M = [[] for i in range(200001)] for i, a in enumerate(As): M[a].append(i) S = [] for i, a in enumerate(As): l = M[a] index = l.index(i) if index+1 == len(l): n = l[0]+N else: n = l[index+1] S.append(n+1-i) #print(S) p = 0 while True: p = p+S[p%N] if p%N == 0: break count = p//N #print(count) K = K%count #print(K) p = 0 s = [] while p < N*K: q = p+S[p%N] if q > N*K: s.append(As[p%N]) p = p+1 else: p = q print((" ".join(map(str, s))))
p02964
import math # input # # n = 5 # k = 10 # a = [1, 2, 3, 2, 3] n, k = list(map(int, input().split())) a = [int(ai) for ai in input().split()] # make jumpto # # 0 -> 6 (6) # 1 -> 4 (3) # 2 -> 5 (3) # 3 -> 7 (4) # 4 -> 8 (4) jumpto = [[-1] * n] la = -1 li = -1 for (ca, ci) in sorted(zip(a, list(range(n)))): if ca == la: jumpto[0][ci] = jumpto[0][li] + li - ci jumpto[0][li] = ci - li + 1 else: jumpto[0][ci] = n + 1 la = ca li = ci # doubling jumpto # # 0 -> 6 -> 9 (9) # 1 -> 4 -> 8 (7) # 2 -> 5 -> 11 (9) # 3 -> 7 -> 10 (7) # 4 -> 8 -> 12 (8) # # 0 -> 6 -> 9 -> 13 -> 17 (17) # 1 -> 4 -> 8 -> 12 -> 15 (14) # 2 -> 5 -> 11 -> 14 -> 18 (16) # 3 -> 7 -> 10 -> 16 -> 19 (16) # 4 -> 8 -> 12 -> 15 -> 21 (17) levels = int(math.log(n * k, 2)) for l in range(1, levels + 1): jumpto.append([-1] * n) for i in range(n): f = jumpto[l - 1][i] s = jumpto[l - 1][(i + f) % n] jumpto[l][i] = f + s # step1 and step2 ret = [] s = 0 while s < n * k: jumped = False for l in range(levels, -1, -1): if s + jumpto[l][s % n] <= n * k: s += jumpto[l][s % n] jumped = True break if not jumped: ret.append(str(a[s % n])) s += 1 print((' '.join(ret)))
import math # input # # n = 5 # k = 10 # a = [1, 2, 3, 2, 3] n, k = list(map(int, input().split())) a = [int(ai) for ai in input().split()] # make jumpto # # 0 -> 6 (6) # 1 -> 4 (3) # 2 -> 5 (3) # 3 -> 7 (4) # 4 -> 8 (4) jumpto = [[-1] * n] la = -1 li = -1 for (ca, ci) in sorted(zip(a, list(range(n)))): if ca == la: jumpto[0][ci] = jumpto[0][li] + li - ci jumpto[0][li] = ci - li + 1 else: jumpto[0][ci] = n + 1 la = ca li = ci # doubling jumpto # # 0 -> 6 -> 9 (9) # 1 -> 4 -> 8 (7) # 2 -> 5 -> 11 (9) # 3 -> 7 -> 10 (7) # 4 -> 8 -> 12 (8) # # 0 -> 6 -> 9 -> 13 -> 17 (17) # 1 -> 4 -> 8 -> 12 -> 15 (14) # 2 -> 5 -> 11 -> 14 -> 18 (16) # 3 -> 7 -> 10 -> 16 -> 19 (16) # 4 -> 8 -> 12 -> 15 -> 21 (17) levels = int(math.log(k, 2)) for l in range(1, levels + 1): jumpto.append([-1] * n) for i in range(n): f = jumpto[l - 1][i] s = jumpto[l - 1][(i + f) % n] jumpto[l][i] = f + s # step1 and step2 ret = [] s = 0 while s < n * k: jumped = False for l in range(levels, -1, -1): if s + jumpto[l][s % n] <= n * k: s += jumpto[l][s % n] jumped = True break if not jumped: ret.append(str(a[s % n])) s += 1 print((' '.join(ret)))
p02964
import sys sys.setrecursionlimit(1000000) n,k = list(map(int,input().split())) a = list(map(int,input().split())) count = 0 j = 0 def f(s,j,count): cho = False for t in range(j+1,n): if a[s] == a[t]: cho == True if t+1==n: return count else: return f(t+1,t+1,count) if not cho: return f(s,-1,count+1) lasta = [] if f(0,0,0) == 0: lasta = [] else: for i in range(0,min((k%f(0,0,0)+1),k)): lasta += a def lastf(s,lista): cho = False for t in range(s+1,len(lista)): if lista[s] == lista[t]: cho = True lista = lista[0:s] + lista[t+1:len(lasta)] if len(lista)==s: return lista else: return lastf(s,lista) if not cho: if s < len(lista)-1: return lastf(s+1,lista) else: return lista ans = lastf(0,lasta) print((" ".join(map(str,ans))))
import sys sys.setrecursionlimit(1000000) n,k = list(map(int,input().split())) a = list(map(int,input().split())) b = [] for i in range(0,n): p = a[i] chou = False for j in range(i+1,n): if a[i] == a[j]: chou = True b.append(j) break if not chou: for j in range(0,i+1): if a[i] == a[j]: chou = True b.append(j) break def f(s,count): if s < b[s]: if b[s]==n-1: return count else: return f(b[s]+1,count) else: count += 1 if b[s]==n-1: return count else: return f(b[s]+1,count) lasta = [] loop = f(0,0) if loop == 0: lasta = [] else: for i in range(0,min(k%(loop+1),k)): lasta += a ans = [] #listaからansをつくる. t = 0 count = 0 while len(lasta)>0: if b[t]<=t: count=count+1 if b[t]+count*n<len(lasta)-1: t = (b[t]+1)%n elif b[t]+count*n == len(lasta)-1: break else: ans.append(lasta[t]) count = count -1 if t+count*n==len(lasta)-1: break else: t = (t + 1)%n else: if b[t]+count*n<len(lasta)-1: t = (b[t]+1)%n elif b[t]+count*n == len(lasta)-1: break print((" ".join(map(str,ans))))
p02964
n=int(eval(input())) a=list(map(int,input().split())) print((max(a)-min(a)))
n=int(eval(input())) a=sorted(list(map(int,input().split()))) print((a[-1]-a[0]))
p03694
N = eval(input()) a = list(map(int, input().split())) print((max(a)-min(a)))
total_house = int(eval(input())) house_coordinate = sorted(list(map(int, input().split()))) print((house_coordinate[total_house - 1]- house_coordinate[0]))
p03694
eval(input()) a=list(map(int,input().split())) print((max(a)-min(a)))
eval(input()) a = sorted(map(int, input().split())) print((a[-1]-a[0]))
p03694
_,*a=list(map(int,open(0).read().split()));print((max(a)-min(a)))
_,t=open(0);*a,=list(map(int,t.split()));print((max(a)-min(a)))
p03694
N = int(eval(input())) a = list(map(int, input().split())) a.sort() ans = 0 for i in range(1, len(a)): ans += a[i] - a[i-1] print(ans)
N = int(eval(input())) a = list(map(int, input().split())) print((max(a) - min(a)))
p03694
N = int(eval(input())) A = sorted(list(map(int,input().split()))) print((A[-1]-A[0]))
N = int(eval(input())) A = list(map(int,input().split())) print((max(A)-min(A)))
p03694
N = int(eval(input())) A = sorted(list(map(int,input().split()))) dis = 0 for i in range(N-1): dis += abs(A[i] - A[i+1]) print(dis)
N = int(eval(input())) A = list(map(int,input().split())) print((max(A)-min(A)))
p03694
eval(input()) a=list(map(int,input().split())) print((max(a)-min(a)))
eval(input()) a=sorted(map(int,input().split())) print((a[-1]-a[0]))
p03694
times = int(eval(input())) count = 0 li = [list(map(int, input().split())) for i in range(times)] for item in li: count += 1 + item[1] - item[0] print(count)
n = int(eval(input())) lr = [list(map(int,input().split())) for _ in range(n)] ans = 0 for i in range(n): ans += lr[i][1]-lr[i][0]+1 print(ans)
p03606
n = int(eval(input())) sum = 0 for i in range(n): l, r = list(map(int, input().split())) sum += (r-l) + 1 print(sum)
n = int(eval(input())) res = 0 for i in range(n): l, r = list(map(int, input().split())) res += (r-l + 1) print(res)
p03606
china = int(eval(input())) kazu = 0 for i in range(china): a, b = [int(i) for i in input().split()] kazu = kazu + (b - a + 1) print(kazu)
num = int(eval(input())) InA = [input().split() for i in range(num)] seki_total = 0 for seki in InA: seki_total += int(seki[1]) - int(seki[0]) + 1 print (seki_total)
p03606
N = int(eval(input())) people = 0 for i in range(N): l, r = list(map(int, input().split())) people += r-l+1 print(people)
p = 0 for i in range(int(eval(input()))): l, r = list(map(int, input().split())) p += r-l+1 print(p)
p03606
print((sum([1-eval(input().replace(' ','-')) for _ in [0]*int(eval(input()))])))
N = int(eval(input())) S = 0 for i in range(N): l,r = list(map(int,input().split())) S += r - l + 1 print(S)
p03606
def resolve(): record =[] for i in range(int(eval(input()))): l,r = list(map(int,input().split())) record+=list(range(l,r+1)) print((len(set(record)))) resolve()
print((sum(1-eval(input().replace(" ","-")) for _ in range(int(eval(input()))))))
p03606
N=int(eval(input())) ans=0 for i in range(N): l,r=list(map(int,input().split())) ans+=r-l+1 print(ans)
import sys input = sys.stdin.buffer.readline N = int(eval(input())) LR = [list(map(int, input().split())) for _ in range(N)] answer = 0 for l, r in LR: answer += r - l + 1 print(answer)
p03606
N = int(eval(input())) ans = 0 for i in range(N): lr = list(map(int, input().split())) ans += lr[1] - lr[0] +1 print(ans)
N = int(eval(input())) ans = 0 for i in range(N): l, r = list(map(int, input().split())) ans += r-l+1 print(ans)
p03606
N = int(eval(input())) a = [] for i in range(N): a.append(list(map(int, input().split()))) number = 0 for i in range(N): abc = a[i-1] first = abc[0] last = abc[1] abc_number = last - first + 1 number += abc_number print((int(number)))
n = int(eval(input())) ans = 0 for i in range(n): l, r = list(map(int, input().split())) ans += r - l + 1 print(ans)
p03606
print((sum(1-eval(input().replace(" ","-")) for _ in range(int(eval(input()))))))
N=int(eval(input())) people=0 for i in range(N): l,r=list(map(int,input().split())) people+=r-l+1 print(people)
p03606
n = int(eval(input())) seat = [0] * 10 ** 6 for i in range(n): l, r = list(map(int, input().split())) for j in range(l, r + 1): seat[j - 1] = 1 res = 0 for i in range(10 ** 6): if seat[i] == 1: res += 1 print(res)
n = int(eval(input())) seat = [0] * (10 ** 5 + 1) for i in range(n): l, r = list(map(int, input().split())) seat[l - 1] += 1 seat[r] -= 1 for i in range(1, 10 ** 5): seat[i] += seat[i - 1] res = 0 for i in range(10 ** 5): if seat[i] == 1: res += 1 print(res)
p03606
n = int(eval(input())) seat = [0] * (10 ** 5 + 1) for i in range(n): l, r = list(map(int, input().split())) seat[l - 1] += 1 seat[r] -= 1 for i in range(1, 10 ** 5): seat[i] += seat[i - 1] res = 0 for i in range(10 ** 5): if seat[i] == 1: res += 1 print(res)
n = int(eval(input())) # seat = [0] * 10 ** 6 seat = [0] * 10 ** 5 for i in range(n): l, r = list(map(int, input().split())) for j in range(l, r + 1): seat[j - 1] = 1 res = 0 # for i in range(10 ** 6): for i in range(10 ** 5): if seat[i] == 1: res += 1 print(res)
p03606
n = int(eval(input())) # seat = [0] * 10 ** 6 seat = [0] * 10 ** 5 for i in range(n): l, r = list(map(int, input().split())) for j in range(l, r + 1): seat[j - 1] = 1 res = 0 # for i in range(10 ** 6): for i in range(10 ** 5): if seat[i] == 1: res += 1 print(res)
n = int(eval(input())) res = 0 for i in range(n): r, l = list(map(int, input().split())) res += l - r + 1 print(res)
p03606
print((sum(1-eval(s.replace(' ','-'))for s in open(0).readlines()[1:])))
_,*t=open(0);print((sum(1-eval(s.replace(' ','-'))for s in t)))
p03606
import collections n = int(eval(input())) l = [list(map(int, input().split())) for _ in range(n)] d = {} for i in range(len(l)): for j in range(l[i][0], l[i][1] + 1): d[j] = 1 print((len(d)))
n = int(eval(input())) t = 0 for i in range(n): l, r = list(map(int, input().split())) t += (r - l + 1) print(t)
p03606
n = int(eval(input())) l = [tuple(map(int, input().split())) for i in range(n)] cnt = 0 for i in l: cnt += (i[1] - i[0] + 1) print(cnt)
N = int(eval(input())) ans = 0 for i in range(N): l,r = list(map(int, input().split())) ans += r - l + 1 print(ans)
p03606
n = int(eval(input())) count = 0 for i in range(n): l,r = list(map(int,input().split())) count += r-l+1 print(count)
n = int(eval(input())) count = 0 for i in range(n): li,ri = list(map(int,input().split())) count += ri-li+1 print(count)
p03606
print((sum(s[1] - s[0] + 1 for s in [list(map(int, input().split())) for _ in range(int(eval(input())))])))
import sys stdin = sys.stdin def input(): return stdin.readline().strip() print((sum(s[1] - s[0] + 1 for s in [list(map(int, input().split())) for _ in range(int(eval(input())))])))
p03606
n=int(eval(input())) c=0 for i in range(n): l,r=input().split() c+=(int(r)-int(l)+1) print(c)
c=0 n=int(eval(input())) for i in range(n): l,r=list(map(int,input().split())) c+=(r-l+1) print(c)
p03606
# import bisect # import copy # import fractions # import math # import numpy as np # from collections import Counter, deque # from itertools import accumulate,permutations, combinations,combinations_with_replacement,product def resolve(): N=int(eval(input())) cnt=0 for i in range(N): l,r=list(map(int,input().split())) cnt+=r-l+1 print(cnt) resolve()
import sys sys.setrecursionlimit(10 ** 5 + 10) def input(): return sys.stdin.readline().strip() def resolve(): cnt=0 N=int(eval(input())) for i in range(N): l,r=list(map(int,input().split())) cnt+=r-l+1 print(cnt) resolve()
p03606
# 2019-11-12 22:21:08(JST) import sys # import collections # import math # from string import ascii_lowercase, ascii_uppercase, digits # from bisect import bisect_left as bi_l, bisect_right as bi_r import itertools # from functools import reduce # import operator as op # from scipy.misc import comb # float # import numpy as np def main(): s = sys.stdin.readline().rstrip() all_words = [] for i in range(1, len(s) + 1): for letters in itertools.product('ATCG', repeat=i): word = ''.join(letters) all_words.append(word) for i in range(len(all_words)-1, 0-1, -1): if all_words[i] in s: print((len(all_words[i]))) sys.exit() print((0)) if __name__ == "__main__": main()
# 2019-11-12 22:21:08(JST) import sys # import collections # import math # from string import ascii_lowercase, ascii_uppercase, digits # from bisect import bisect_left as bi_l, bisect_right as bi_r # import itertools # from functools import reduce # import operator as op # from scipy.misc import comb # float # import numpy as np def main(): s = sys.stdin.readline().rstrip() permitted = 'ACGT' continuous_count = [] count = 0 for i in range(len(s)): char = s[i] if char in permitted: count += 1 else: continuous_count.append(count) count = 0 if i == len(s) - 1: continuous_count.append(count) if not continuous_count: print((len(s))) else: print((max(continuous_count))) if __name__ == "__main__": main()
p03086
#ABC122B def main(): import sys S = sys.stdin.readline().rstrip() #print(S) L = ['A', 'C', 'G', 'T'] cnt, ans = 0, 0 for s in S: if s in L: cnt+=1 else: if ans < cnt: ans = cnt #print(ans) cnt=0 else: if ans < cnt: ans = cnt print(ans) if __name__=='__main__': main()
#ABC122B def main(): import sys S = sys.stdin.readline().rstrip() #print(S) cnt = 0 ans = 0 for s in S: if s in ['A', 'G', 'C', 'T']: cnt +=1 else: ans = max(ans, cnt) cnt=0 ans = max(ans, cnt) print(ans) if __name__=='__main__': main()
p03086
import sys from collections import deque from itertools import * def I(): return int(sys.stdin.readline().rstrip()) def LI(): return list(map(int, sys.stdin.readline().rstrip().split())) def S(): return sys.stdin.readline().rstrip() def LS(): return list(sys.stdin.readline().rstrip().split()) s = S() ans = 0 temp = 0 for s_s in s: if s_s in 'ACGT': temp += 1 else: temp = 0 ans = max(ans, temp) print(ans)
import sys def I(): return int(sys.stdin.readline().rstrip()) def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) def S(): return sys.stdin.readline().rstrip() def LS(): return list(sys.stdin.readline().rstrip().split()) s = S() temp = 0 ans = 0 for char in s: if char in 'ACGT': temp += 1 else: temp = 0 ans = max(ans,temp) print(ans)
p03086
import sys def I(): return int(sys.stdin.readline().rstrip()) def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) def S(): return sys.stdin.readline().rstrip() def LS(): return list(sys.stdin.readline().rstrip().split()) s = S() temp = 0 ans = 0 for char in s: if char in 'ACGT': temp += 1 else: temp = 0 ans = max(ans,temp) print(ans)
import sys def I(): return int(sys.stdin.readline().rstrip()) def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) def S(): return sys.stdin.readline().rstrip() def LS(): return list(sys.stdin.readline().rstrip().split()) s = S() ans = 0 temp = 0 for i in s: if i in 'ACGT': temp += 1 else: temp = 0 ans = max(ans,temp) print(ans)
p03086
from collections import deque N = int(eval(input())) A = list(map(int, input().split())) B = list(map(int, input().split())) # check reachability B -> A ? # 隣接和table P = [B[(i-1)%N] + B[(i+1)%N] for i in range(N)] D = deque(i for i in range(N) if B[i] - P[i] >= A[i]) ans = 0 nmatch = [B[i] == A[i] for i in range(N)].count(True) while D: upd = False i = D.popleft() if B[i] == A[i]: nmatch += 1 continue if B[i] <= P[i]: continue if B[i] - P[i] >= A[i]: P[(i-1)%N] -= P[i] P[(i+1)%N] -= P[i] B[i] -= P[i] upd = True ans += 1 if B[i] == A[i]: nmatch += 1 if B[(i-1)%N] - P[(i-1)%N] >= A[(i-1)%N]: D.append((i-1)%N) if B[(i+1)%N] - P[(i+1)%N] >= A[(i+1)%N]: D.append((i+1)%N) if B[i] - P[i] >= A[i]: D.append(i) if not upd: break print((ans if nmatch == N else -1))
from collections import deque N = int(eval(input())) A = list(map(int, input().split())) B = list(map(int, input().split())) # check reachability B -> A ? # 隣接和table P = [B[(i-1)%N] + B[(i+1)%N] for i in range(N)] D = deque(i for i in range(N) if B[i] - P[i] >= A[i]) ans = 0 nmatch = [B[i] == A[i] for i in range(N)].count(True) while D: upd = False i = D.popleft() if B[i] == A[i]: nmatch += 1 continue if B[i] <= P[i]: continue if B[i] - P[i] >= A[i]: n = (B[i] - A[i]) // P[i] P[(i-1)%N] -= P[i] * n P[(i+1)%N] -= P[i] * n B[i] -= P[i] * n upd = True ans += n if B[i] == A[i]: nmatch += 1 if B[(i-1)%N] - P[(i-1)%N] >= A[(i-1)%N]: D.append((i-1)%N) if B[(i+1)%N] - P[(i+1)%N] >= A[(i+1)%N]: D.append((i+1)%N) if not upd: break print((ans if nmatch == N else -1))
p02941
from pprint import pprint import queue def solve(n, a, b): state = queue.Queue() state.put((0, b[:])) while not state.empty(): count, b_tmp = state.get() # print("next:" + str(count)) # pprint(b_tmp) for i, b_i in enumerate(b_tmp): i_a = (i - 1 + n) % n i_c = (i + 1) % n b_cand = b_i - b_tmp[i_a] - b_tmp[i_c] if b_cand >= a[i]: b_next = b_tmp[:] b_next[i] = b_cand if b_next == a: return count + 1 # print(count + 1) state.put((count + 1, b_next)) return -1 if __name__ == '__main__': n = int(input().strip()) a = list(map(int, input().strip().split(" "))) b = list(map(int, input().strip().split(" "))) print((solve(n, a, b)))
from pprint import pprint import queue def solve(n, a, b): a_pq = queue.PriorityQueue() for i, a_i in enumerate(a): a_pq.put((a_i, i)) b_pq = queue.PriorityQueue() for i, b_i in enumerate(b): b_pq.put((b_i, i)) state = queue.Queue() state.put((0, b[:])) while not state.empty(): count, b_tmp = state.get() b_tmp_pq = queue.PriorityQueue() for b_tmp_i in b_tmp: b_tmp_pq.put(b_tmp_i) # print("next:" + str(count)) # pprint(b_tmp) while not b_tmp_pq.empty(): b_i = b_tmp_pq.get() i_b = b_tmp.index(b_i) # print(i_b, b_i) i_a = (i_b - 1 + n) % n i_c = (i_b + 1) % n b_cand = b_i if b_cand - b_tmp[i_a] - b_tmp[i_c] < a[i_b]: continue while b_cand - b_tmp[i_a] - b_tmp[i_c] >= a[i_b]: b_cand = b_cand - b_tmp[i_a] - b_tmp[i_c] count += 1 b_next = b_tmp[:] b_next[i_b] = b_cand if b_next == a: return count # print(count + 1) state.put((count, b_next)) return -1 if __name__ == '__main__': n = int(input().strip()) a = list(map(int, input().strip().split(" "))) b = list(map(int, input().strip().split(" "))) print((solve(n, a, b)))
p02941
from pprint import pprint import queue def solve(n, a, b): a_pq = queue.PriorityQueue() for i, a_i in enumerate(a): a_pq.put((a_i, i)) b_pq = queue.PriorityQueue() for i, b_i in enumerate(b): b_pq.put((b_i, i)) state = queue.Queue() state.put((0, b[:])) while not state.empty(): count, b_tmp = state.get() b_tmp_pq = queue.PriorityQueue() for b_tmp_i in b_tmp: b_tmp_pq.put(b_tmp_i) # print("next:" + str(count)) # pprint(b_tmp) while not b_tmp_pq.empty(): b_i = b_tmp_pq.get() i_b = b_tmp.index(b_i) # print(i_b, b_i) i_a = (i_b - 1 + n) % n i_c = (i_b + 1) % n b_cand = b_i if b_cand - b_tmp[i_a] - b_tmp[i_c] < a[i_b]: continue while b_cand - b_tmp[i_a] - b_tmp[i_c] >= a[i_b]: b_cand = b_cand - b_tmp[i_a] - b_tmp[i_c] count += 1 b_next = b_tmp[:] b_next[i_b] = b_cand if b_next == a: return count # print(count + 1) state.put((count, b_next)) return -1 if __name__ == '__main__': n = int(input().strip()) a = list(map(int, input().strip().split(" "))) b = list(map(int, input().strip().split(" "))) print((solve(n, a, b)))
from pprint import pprint import queue def solve(n, a, b): a_pq = queue.PriorityQueue() for i, a_i in enumerate(a): a_pq.put((a_i, i)) b_pq = queue.PriorityQueue() for i, b_i in enumerate(b): b_pq.put((b_i, i)) state = queue.Queue() state.put((0, b[:])) while not state.empty(): count, b_tmp = state.get() b_tmp_pq = queue.PriorityQueue() for b_tmp_i in b_tmp: b_tmp_pq.put(b_tmp_i) # print("next:" + str(count)) # pprint(b_tmp) while not b_tmp_pq.empty(): b_i = b_tmp_pq.get() i_b = b_tmp.index(b_i) # print(i_b, b_i) i_a = (i_b - 1 + n) % n i_c = (i_b + 1) % n b_cand = b_i if b_cand - b_tmp[i_a] - b_tmp[i_c] < a[i_b]: continue while b_cand - b_tmp[i_a] - b_tmp[i_c] >= a[i_b]: b_cand = b_cand - b_tmp[i_a] - b_tmp[i_c] count += 1 b_next = b_tmp[:] b_next[i_b] = b_cand if b_next == a: return count # print(count + 1) state.put((count, b_next)) break return -1 if __name__ == '__main__': n = int(input().strip()) a = list(map(int, input().strip().split(" "))) b = list(map(int, input().strip().split(" "))) print((solve(n, a, b)))
p02941
from pprint import pprint import heapq def solve(n, a, b): b_pq = [] b_rev = {} for i, b_i in enumerate(b): heapq.heappush(b_pq, (-1 * b_i, i)) count = 0 while b_pq: tmp = heapq.heappop(b_pq) # pprint(tmp) b_i = tmp[0] * -1 i_b = tmp[1] # print(i_b, b_i) i_a = (i_b - 1 + n) % n i_c = (i_b + 1) % n b_cand = b_i if b_cand - b[i_a] - b[i_c] < a[i_b]: continue #while b_cand - b[i_a] - b[i_c] >= a[i_b]: # b_cand = b_cand - b[i_a] - b[i_c] # count += 1 tmp_count = (b_cand - a[i_b]) // (b[i_a] + b[i_c]) b_cand -= (b[i_a] + b[i_c]) * tmp_count count += tmp_count b[i_b] = b_cand heapq.heappush(b_pq, (-1 * b_cand, i_b)) # print("count: ", count) # pprint(b) if b_cand == a[i_b] and b == a: return count return -1 if __name__ == '__main__': n = int(input().strip()) a = list(map(int, input().strip().split(" "))) b = list(map(int, input().strip().split(" "))) print((solve(n, a, b)))
from pprint import pprint import heapq def solve(n, a, b): b_pq = [] b_rev = {} delete = [] for i, b_i in enumerate(b): if b_i == a[i]: continue heapq.heappush(b_pq, (-1 * b_i, i)) count = 0 while b_pq: tmp = heapq.heappop(b_pq) # pprint(tmp) b_i = tmp[0] * -1 i_b = tmp[1] # print(i_b, b_i) i_a = (i_b - 1 + n) % n i_c = (i_b + 1) % n b_cand = b_i if b_cand - b[i_a] - b[i_c] < a[i_b]: continue #while b_cand - b[i_a] - b[i_c] >= a[i_b]: # b_cand = b_cand - b[i_a] - b[i_c] # count += 1 tmp_count = (b_cand - a[i_b]) // (b[i_a] + b[i_c]) b_cand -= (b[i_a] + b[i_c]) * tmp_count count += tmp_count b[i_b] = b_cand heapq.heappush(b_pq, (-1 * b_cand, i_b)) # print("count: ", count) # pprint(b) if b_cand == a[i_b] and b == a: return count return -1 if __name__ == '__main__': n = int(input().strip()) a = list(map(int, input().strip().split(" "))) b = list(map(int, input().strip().split(" "))) print((solve(n, a, b)))
p02941
from pprint import pprint import heapq def solve(n, a, b): b_pq = [] b_rev = {} delete = [] for i, b_i in enumerate(b): if b_i == a[i]: continue heapq.heappush(b_pq, (-1 * b_i, i)) count = 0 while b_pq: tmp = heapq.heappop(b_pq) # pprint(tmp) b_i = tmp[0] * -1 i_b = tmp[1] # print(i_b, b_i) i_a = (i_b - 1 + n) % n i_c = (i_b + 1) % n b_cand = b_i if b_cand - b[i_a] - b[i_c] < a[i_b]: continue #while b_cand - b[i_a] - b[i_c] >= a[i_b]: # b_cand = b_cand - b[i_a] - b[i_c] # count += 1 tmp_count = (b_cand - a[i_b]) // (b[i_a] + b[i_c]) b_cand -= (b[i_a] + b[i_c]) * tmp_count count += tmp_count b[i_b] = b_cand heapq.heappush(b_pq, (-1 * b_cand, i_b)) # print("count: ", count) # pprint(b) if b_cand == a[i_b] and b == a: return count return -1 if __name__ == '__main__': n = int(input().strip()) a = list(map(int, input().strip().split(" "))) b = list(map(int, input().strip().split(" "))) print((solve(n, a, b)))
from pprint import pprint import heapq def solve(n, a, b): b_pq = [] b_rev = {} delete = [] for i, b_i in enumerate(b): if b_i == a[i]: continue heapq.heappush(b_pq, (-1 * b_i, i)) count = 0 while b_pq: tmp = heapq.heappop(b_pq) # pprint(tmp) b_i = tmp[0] * -1 i_b = tmp[1] # print(i_b, b_i) i_a = (i_b - 1 + n) % n i_c = (i_b + 1) % n b_cand = b_i if b_cand - b[i_a] - b[i_c] < a[i_b]: continue #while b_cand - b[i_a] - b[i_c] >= a[i_b]: # b_cand = b_cand - b[i_a] - b[i_c] # count += 1 tmp_count = (b_cand - a[i_b]) // (b[i_a] + b[i_c]) b_cand -= (b[i_a] + b[i_c]) * tmp_count count += tmp_count b[i_b] = b_cand if b_cand != a[i_b]: heapq.heappush(b_pq, (-1 * b_cand, i_b)) # print("count: ", count) # pprint(b) if b_cand == a[i_b] and b == a: return count return -1 if __name__ == '__main__': n = int(input().strip()) a = list(map(int, input().strip().split(" "))) b = list(map(int, input().strip().split(" "))) print((solve(n, a, b)))
p02941
def main(): n=int(eval(input())) # for i in range(n): src = [int(item) for item in input().split()] dst = [int(item) for item in input().split()] q=set() s=set() ans=0 def SandQ(i): ri=i+1 li=i-1 if i==0:li=n-1 if i==n-1:ri=0 x=0 if dst[i]-src[i]>=dst[ri]+dst[li]: x=(dst[i]-src[i])//(dst[ri]+dst[li]) dst[i]-=(dst[ri]+dst[li])*x q.add(li) q.add(ri) if dst[i]<=src[i]: s.add(i) # print (i,dst,x) return x; # print(src) # print(dst) for i in range(n): ans+=SandQ(i) while len(q)>0: i=q.pop() ans+=SandQ(i) if len(s)!=n:print((-1)) else:print(ans) # print(dst) main()
def main(): n=int(eval(input())) src = [int(item) for item in input().split()] dst = [int(item) for item in input().split()] q=set() ans=0 def SandQ(i): ri=i+1 li=i-1 if i==0:li=n-1 if i==n-1:ri=0 x=0 if dst[i]-src[i]>=dst[ri]+dst[li]: x=(dst[i]-src[i])//(dst[ri]+dst[li]) dst[i]-=(dst[ri]+dst[li])*x q.add(li) q.add(ri) return x; for i in range(n): ans+=SandQ(i) while len(q)>0: i=q.pop() ans+=SandQ(i) for i in range(n): if src[i]!=dst[i]: print((-1)) exit() else:print(ans) main()
p02941
def main(): n=int(eval(input())) src = [int(item) for item in input().split()] dst = [int(item) for item in input().split()] q=set() ans=0 def SandQ(i): ri=i+1 li=i-1 if i==0:li=n-1 if i==n-1:ri=0 x=0 if dst[i]-src[i]>=dst[ri]+dst[li]: x=(dst[i]-src[i])//(dst[ri]+dst[li]) dst[i]-=(dst[ri]+dst[li])*x q.add(li) q.add(ri) return x; for i in range(n): ans+=SandQ(i) while len(q)>0: i=q.pop() ans+=SandQ(i) for i in range(n): if src[i]!=dst[i]: print((-1)) exit() else:print(ans) main()
def main(): n=int(eval(input())) src = [int(item) for item in input().split()] dst = [int(item) for item in input().split()] ans=0 def SandQ(i): ri=i+1 li=i-1 if i==0:li=n-1 if i==n-1:ri=0 x=0 if dst[i]-src[i]>=dst[ri]+dst[li]: x=(dst[i]-src[i])//(dst[ri]+dst[li]) dst[i]-=(dst[ri]+dst[li])*x x+=SandQ(li) x+=SandQ(ri) return x; for i in range(n): ans+=SandQ(i) for i in range(n): if src[i]!=dst[i]: print((-1)) exit() else:print(ans) main()
p02941
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) from heapq import heappop, heappush N = int(eval(input())) A = [int(x) for x in input().split()] B = [int(x) for x in input().split()] q = [] push = lambda x,i: heappush(q, (-x,i)) def pop(): x,i = heappop(q) return -x,i for i,x in enumerate(B): push(x,i) answer = 0 while q: x,i = pop() a = A[i] dx = x-a if dx<0: answer = -1 break if dx == 0: continue if i < N-1: nbd = B[i-1] + B[i+1] else: nbd = B[i-1] + B[0] t = dx // nbd if t == 0: answer = -1 break B[i] -= nbd * t answer += t push(B[i],i) print(answer)
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) from heapq import heappop, heappush N = int(eval(input())) A = [int(x) for x in input().split()] B = [int(x) for x in input().split()] q = [] push = lambda x,i: heappush(q, (-x,i)) for i,x in enumerate(B): push(x,i) answer = 0 while q: x,i = heappop(q) x = -x if x < A[i]: answer = -1 break dx = x-A[i] nbd = B[(i-1)%N] + B[(i+1)%N] t = dx // nbd if t == 0: if x == A[i]: continue answer = -1 break B[i] -= nbd * t answer += t push(B[i],i) print(answer)
p02941
import sys from heapq import heappush as hpu from heapq import heappop as hpo input = sys.stdin.readline N = int(eval(input())) a = list(map(int, input().split())) b = list(map(int, input().split())) base = 10 ** 10 sb = [(-b[i], i) for i in range(N) if a[i] != b[i]] h = [] for t in sb: hpu(h, t) res = 0 while len(h): v, i = hpo(h) v = -v if v < a[i]: print((-1)) exit(0) d = v - a[i] x = b[i - 1] + b[(i + 1) % N] t = d // x if t == 0: if v == a[i]: continue print((-1)) exit(0) b[i] -= x * (t) res += t hpu(h, (-b[i], i)) print(res)
import sys from heapq import heappush as hpu from heapq import heappop as hpo input = sys.stdin.readline N = int(eval(input())) a = list(map(int, input().split())) b = list(map(int, input().split())) base = 10 ** 6 sb = [-(b[i] * base + i) for i in range(N) if a[i] != b[i]] h = [] for t in sb: hpu(h, t) res = 0 while len(h): v = hpo(h) i = -v % base v = -v // base if v < a[i]: print((-1)) exit(0) d = v - a[i] x = b[i - 1] + b[(i + 1) % N] t = d // x if t == 0: if v == a[i]: continue print((-1)) exit(0) b[i] -= x * (t) res += t hpu(h, -(b[i] * base + i)) print(res)
p02941
from heapq import heappush, heappop import sys input = sys.stdin.readline N = int(eval(input())) A = list(map(int, input().split())) B = list(map(int, input().split())) pq = [] for i, b in enumerate(B): if A[i] != b: heappush(pq, (-b, i)) ans = 0 while pq: _, i = heappop(pq) B[i] -= B[(i-1) % N] + B[(i+1) % N] if B[i] < A[i]: ans = -1 break if B[i] > A[i]: heappush(pq, (-B[i], i)) ans += 1 print(ans)
from heapq import heappush, heappop import sys input = sys.stdin.readline N = int(eval(input())) A = list(map(int, input().split())) B = list(map(int, input().split())) pq = [] for i, b in enumerate(B): if A[i] != b: heappush(pq, (-b, i)) ans = 0 while pq: _, i = heappop(pq) s = B[(i-1) % N] + B[(i+1) % N] q, r = divmod(B[i] - A[i], s) B[i] = A[i] + r ans += q if q == 0: ans = -1 break if B[i] > A[i]: heappush(pq, (-B[i], i)) print(ans)
p02941
from collections import deque def resolve(): n = int(eval(input())) aa = list(map(int, input().split())) bb = list(map(int, input().split())) q = deque() diffs = set() for i in range(n): if bb[i] != aa[i]: diffs.add(i) bef_i = i-1 if i > 0 else n-1 aft_i = i+1 if i < n-1 else 0 if bb[i] > aa[i] and bb[i] > bb[bef_i] + bb[aft_i]: q.append(i) count = 0 while len(q) > 0: i = q.popleft() bef_i = i-1 if i > 0 else n-1 bef2_i = bef_i-1 if bef_i > 0 else n-1 aft_i = i+1 if i < n-1 else 0 aft2_i = aft_i+1 if aft_i < n-1 else 0 while bb[i] > aa[i] and bb[i] > bb[bef_i] + bb[aft_i]: bb[i] = bb[i] - bb[bef_i] - bb[aft_i] count += 1 if bb[i] == aa[i]: diffs.remove(i) if bb[bef_i] > aa[bef_i] and bb[bef_i] > bb[bef2_i] + bb[i]: q.append(bef_i) if bb[aft_i] > aa[aft_i] and bb[aft_i] > bb[aft2_i] + bb[i]: q.append(aft_i) if len(diffs) > 0: print((-1)) return print(count) resolve()
from collections import deque def resolve(): n = int(eval(input())) aa = list(map(int, input().split())) bb = list(map(int, input().split())) q = deque() diffs = set() for i in range(n): if bb[i] != aa[i]: diffs.add(i) bef_i = i-1 if i > 0 else n-1 aft_i = i+1 if i < n-1 else 0 if bb[i] > aa[i] and bb[i] > bb[bef_i] + bb[aft_i]: q.append(i) count = 0 while len(q) > 0: i = q.popleft() bef_i = i-1 if i > 0 else n-1 bef2_i = bef_i-1 if bef_i > 0 else n-1 aft_i = i+1 if i < n-1 else 0 aft2_i = aft_i+1 if aft_i < n-1 else 0 count += (bb[i] - aa[i]) // (bb[bef_i] + bb[aft_i]) bb[i] = (bb[i] - aa[i]) % (bb[bef_i] + bb[aft_i]) + aa[i] if bb[i] == aa[i]: diffs.remove(i) if bb[bef_i] > aa[bef_i] and bb[bef_i] > bb[bef2_i] + bb[i]: q.append(bef_i) if bb[aft_i] > aa[aft_i] and bb[aft_i] > bb[aft2_i] + bb[i]: q.append(aft_i) if len(diffs) > 0: print((-1)) return print(count) resolve()
p02941
import heapq n=int(eval(input())) arr1=list(map(int,input().split())) arr2=list(map(int,input().split())) q=[] for i in range(n): if arr2[i]!=arr1[i]: heapq.heappush(q,(-arr2[i],i)) cnt=0 while q: val,pos=heapq.heappop(q) val*=-1 diff=arr2[pos-1]+arr2[(pos+1)%n] move,tmp=divmod(val-arr1[pos],diff) if move==0: break cnt+=move tmp+=arr1[pos] arr2[pos]=tmp if tmp!=arr1[pos]: heapq.heappush(q,(-tmp,pos)) for i in range(n): if arr1[i]!=arr2[i]: print((-1)) break else: print(cnt)
import heapq n=int(eval(input())) arr1=list(map(int,input().split())) arr2=list(map(int,input().split())) q=[] for i in range(n): if arr2[i]!=arr1[i]: heapq.heappush(q,(-arr2[i],i)) cnt=0 while q: val,pos=heapq.heappop(q) val*=-1 diff=arr2[pos-1]+arr2[(pos+1)%n] move=(val-arr1[pos])//diff if move==0: break cnt+=move tmp=arr2[pos]-diff*move arr2[pos]=tmp if tmp!=arr1[pos]: heapq.heappush(q,(-tmp,pos)) for i in range(n): if arr1[i]!=arr2[i]: print((-1)) break else: print(cnt)
p02941
import math #import numpy as np import queue from collections import deque,defaultdict import heapq from sys import stdin,setrecursionlimit #from scipy.sparse.csgraph import dijkstra #from scipy.sparse import csr_matrix ipt = stdin.readline setrecursionlimit(10**7) def main(): n = int(ipt()) a = [int(i) for i in ipt().split()] b = [int(i) for i in ipt().split()] hq = [] ma = max(a) ans = 0 for i,bi in enumerate(b): heapq.heappush(hq,(-bi,i)) while len(hq) > 0: nbi,i = heapq.heappop(hq) if len(hq) > 0: nnbi,ni = heapq.heappop(hq) heapq.heappush(hq,(nnbi,ni)) else: nnbi = -ma if i < n-1: bp = b[i+1] else: bp = b[0] bm = b[i-1] if -nbi-bm-bp < a[i]: print((-1)) exit() else: t = math.ceil((nnbi-nbi)/(bm+bp)) b[i] -= (bm+bp)*t if b[i] > a[i]: heapq.heappush(hq,(-b[i],i)) ans += t print(ans) return if __name__ == '__main__': main()
import math #import numpy as np import queue from collections import deque,defaultdict import heapq from sys import stdin,setrecursionlimit #from scipy.sparse.csgraph import dijkstra #from scipy.sparse import csr_matrix ipt = stdin.readline setrecursionlimit(10**7) def main(): n = int(ipt()) a = [int(i) for i in ipt().split()] b = [int(i) for i in ipt().split()] hq = [] ans = 0 for i,bi in enumerate(b): if bi > a[i]: heapq.heappush(hq,(-bi,i)) while len(hq) > 0: #print(hq,b) nbi,i = heapq.heappop(hq) if i == n-1: bp = b[0] else: bp = b[i+1] bm = b[i-1] t = (-a[i]-nbi)//(bm+bp) if t == 0: print((-1)) exit() b[i] -= (bm+bp)*t if b[i] > a[i]: heapq.heappush(hq,(-b[i],i)) ans += t print(ans) return if __name__ == '__main__': main()
p02941
#!/usr/bin/env python3 #AGC37 C import sys import math import bisect sys.setrecursionlimit(1000000000) from heapq import heappush, heappop,heappushpop,heapify from collections import defaultdict from itertools import accumulate from collections import Counter from collections import deque from operator import itemgetter from itertools import permutations mod = 10**9 + 7 inf = float('inf') def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) n = I() a = LI() b = LI() h = [] for i,v in enumerate(b): heappush(h,(-v,i)) ans = 0 while h: v,i = heappop(h) v = -v tmp = b[(i+1) % n] + b[i-1] if v == a[i]: continue s = (v - a[i])//tmp if s <= 0: print((-1)) quit() ans += s v -= s*tmp b[i] = v if v != a[i]: heappush(h,(-v,i)) print(ans)
#!/usr/bin/env python3 #AGC37 C import sys import math import bisect sys.setrecursionlimit(1000000000) from heapq import heappush, heappop,heappushpop,heapify from collections import defaultdict from itertools import accumulate from collections import Counter from collections import deque from operator import itemgetter from itertools import permutations mod = 10**9 + 7 inf = float('inf') def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) n = I() a = LI() b = LI() h = [] for i in range(n): heappush(h,(-b[i],i)) ans = 0 while h: v,i = heappop(h) v = -v tmp = b[(i+1) % n] + b[i-1] if v == a[i]: continue s = (v - a[i])//tmp if s <= 0: print((-1)) quit() ans += s v -= s*tmp b[i] = v if v != a[i]: heappush(h,(-v,i)) print(ans)
p02941
""" 演算子は要素とセットでモノイドを形成するようなものでなければならない。 すなわち、結合律が成り立ち単位元が存在する必要がある。 equalityはsetを高速化するために使う。めんどい場合はNoneにしてもOK """ class SegmentTree: @classmethod def all_identity(cls, operator, equality, identity, size): return cls(operator, equality, identity, [identity]*(2 << (size-1).bit_length())) @classmethod def from_initial_data(cls, operator, equality, identity, data): size = 1 << (len(data)-1).bit_length() temp = [identity]*(2*size) temp[size:size+len(data)] = data data = temp for i in reversed(list(range(size))): data[i] = operator(data[2*i],data[2*i+1]) return cls(operator, equality, identity, data) # これ使わずファクトリーメソッド使いましょうね def __init__(self, operator, equality, identity, data): if equality is None: equality = lambda a,b: False self.op = operator self.eq = equality self.id = identity self.data = data self.size = len(data)//2 def _interval(self, a, b): a += self.size b += self.size ra = self.id rb = self.id data = self.data op = self.op while a < b: if a & 1: ra = op(ra,data[a]) a += 1 if b & 1: b -= 1 rb = op(data[b],rb) a >>= 1 b >>= 1 return op(ra,rb) def __getitem__(self, i): if isinstance(i, slice): return self._interval( 0 if i.start is None else i.start, self.size if i.stop is None else i.stop) elif isinstance(i, int): return self.data[i+self.size] def __setitem__(self, i, v): i += self.size data = self.data op = self.op eq = self.eq while i and not eq(data[i],v): data[i] = v v = op(data[i^1],v) if i & 1 else op(v,data[i^1]) i >>= 1 def __iter__(self): return self.data[self.size:] from operator import eq def solve(): N = int(eval(input())) A = list(map(int,input().split())) B = list(map(int,input().split())) max_finder = SegmentTree.from_initial_data(max, eq, (0,0), [(v,i) for i,v in enumerate(B)]) cnt = 0 while True: v,i = max_finder[:] if v == 0: print(cnt) return if B[i] == A[i]: max_finder[i] = (0,i) continue delta = B[(i-1)%N] + B[(i+1)%N] n = (B[i]-A[i])//delta if n <= 0: print((-1)) return else: max_finder[i] = (B[i]-n*delta, i) B[i] -= n*delta cnt += n solve()
""" 演算子は要素とセットでモノイドを形成するようなものでなければならない。 すなわち、結合律が成り立ち単位元が存在する必要がある。 equalityはsetを高速化するために使う。めんどい場合はNoneにしてもOK """ class SegmentTree: @classmethod def all_identity(cls, operator, equality, identity, size): return cls(operator, equality, identity, [identity]*(2 << (size-1).bit_length())) @classmethod def from_initial_data(cls, operator, equality, identity, data): size = 1 << (len(data)-1).bit_length() temp = [identity]*(2*size) temp[size:size+len(data)] = data data = temp for i in reversed(list(range(size))): data[i] = operator(data[2*i],data[2*i+1]) return cls(operator, equality, identity, data) # これ使わずファクトリーメソッド使いましょうね def __init__(self, operator, equality, identity, data): if equality is None: equality = lambda a,b: False self.op = operator self.eq = equality self.id = identity self.data = data self.size = len(data)//2 def _interval(self, a, b): a += self.size b += self.size ra = self.id rb = self.id data = self.data op = self.op while a < b: if a & 1: ra = op(ra,data[a]) a += 1 if b & 1: b -= 1 rb = op(data[b],rb) a >>= 1 b >>= 1 return op(ra,rb) def __getitem__(self, i): if isinstance(i, slice): return self._interval( 0 if i.start is None else i.start, self.size if i.stop is None else i.stop) elif isinstance(i, int): return self.data[i+self.size] def __setitem__(self, i, v): i += self.size data = self.data op = self.op eq = self.eq while i and not eq(data[i],v): data[i] = v v = op(data[i^1],v) if i & 1 else op(v,data[i^1]) i >>= 1 def __iter__(self): return self.data[self.size:] from operator import eq def solve(): N = int(eval(input())) A = list(map(int,input().split())) B = list(map(int,input().split())) max_finder = SegmentTree.from_initial_data(max, eq, (0,0), [(0 if A[i] == v else v,i) for i,v in enumerate(B)]) cnt = 0 v,i = max_finder[:] while v != 0: delta = B[i-1] + B[i-N+1] n = (B[i]-A[i])//delta if n <= 0: print((-1)) return else: B[i] -= n*delta max_finder[i] = (0 if B[i] == A[i] else B[i], i) cnt += n v,i = max_finder[:] print(cnt) solve()
p02941
def main(): from sys import exit n = int(eval(input())) a = [int(e) for e in input().split()] b = [int(e) for e in input().split()] result = 0 q = [i for i in range(n) if b[i] != a[i]] while len(q) != 0: nq = [] c = 0 for i in q: if i == 0 or i == n - 1: j = b[(n + i - 1) % n] + b[(n + i + 1) % n] else: j = b[i - 1] + b[i + 1] if j > b[i] - a[i]: nq.append(i) continue c += 1 k = (b[i] - a[i]) // j result += k b[i] -= j * k if a[i] != b[i]: nq.append(i) if c == 0 and len(nq) != 0: print((-1)) exit() q = nq print(result) main()
def main(): from sys import exit N = int(eval(input())) A = list(map(int, input().split())) B = list(map(int, input().split())) result = 0 q = [i for i in range(N) if B[i] != A[i]] while len(q) != 0: nq = [] c = 0 for i in q: if i == 0 or i == N - 1: j = B[(N + i - 1) % N] + B[(N + i + 1) % N] else: j = B[i - 1] + B[i + 1] if j > B[i] - A[i]: nq.append(i) continue c += 1 k = (B[i] - A[i]) // j result += k B[i] -= j * k if A[i] != B[i]: nq.append(i) if c == 0 and len(nq) != 0: print((-1)) exit() q = nq print(result) main()
p02941
n = int(eval(input())) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] cnt, prev_cnt = 0, -1 while cnt != prev_cnt: prev_cnt = cnt for i in range(n): adj_sum = b[i - 1] + b[(i + 1) % n] k = (b[i] - a[i]) // adj_sum if k > 0: b[i] -= k * adj_sum cnt += k print((cnt if a == b else -1))
#import sys #input = sys.stdin.readline n = int(eval(input())) a = [0]*n b = [0]*n a =[int(xi) for xi in input().split()] b =[int(yi) for yi in input().split()] cnt, prev_cnt = 0, -1 while cnt != prev_cnt: prev_cnt = cnt for i in range(n): adj_sum = b[i - 1] + b[(i + 1) % n] k = (b[i] - a[i]) // adj_sum if k > 0: b[i] -= k * adj_sum cnt += k print((cnt if a == b else -1))
p02941
import sys from heapq import heappop as hpp, heappush as hp readline = sys.stdin.readline N = int(readline()) A = list(map(int, readline().split())) B = list(map(int, readline().split())) geta = 10**6 Q = [-(B[i]*geta+i) for i in range(N)] + [0] Q.sort() ans = 0 cnt = 0 inf = 10**9+7 while cnt < N: b, idx = divmod(-hpp(Q), geta) bsec = Q[0] bsec = (-bsec)//geta a = A[idx] if b < a: ans = -1 break bside = B[(idx+1)%N] + B[(idx-1)%N] kb = (1+(b-bsec)//bside) ka = (b-a)//bside k = min(ka, kb) B[idx] -= k*bside ans += k if B[idx] == a: cnt += 1 elif k == 0: ans = -1 break else: hp(Q, -(B[idx]*geta+idx)) print(ans)
import sys from heapq import heappop as hpp, heappush as hp readline = sys.stdin.readline N = int(readline()) A = list(map(int, readline().split())) B = list(map(int, readline().split())) geta = 10**6 Q = [-(B[i]*geta+i) for i in range(N)] + [0] Q.sort() ans = 0 cnt = 0 inf = 10**9+7 while cnt < N: b, idx = divmod(-hpp(Q), geta) a = A[idx] if b < a: ans = -1 break bside = B[(idx+1)%N] + B[(idx-1)%N] kb = 1+(b-bside)//bside ka = (b-a)//bside k = min(ka, kb) B[idx] -= k*bside ans += k if B[idx] == a: cnt += 1 elif k == 0: ans = -1 break else: hp(Q, -(B[idx]*geta+idx)) print(ans)
p02941
import sys import heapq def main(): n=int(eval(input())) a=list(map(int,input().split())) b=list(map(int,input().split())) h=[] for i in range(n): if b[i]>a[i]: heapq.heappush(h,[b[i]*-1,i]) loop=0 idx=0 while(1): #print(b) if not h: break buf,idx=heapq.heappop(h) buf=-1*buf x=(buf-a[idx])//(b[(idx-1)%n]+b[(idx+1)%n]) buf-=x*(b[(idx-1)%n]+b[(idx+1)%n]) loop+=x b[idx]=buf if x==0: #print(b) print((-1)) sys.exit() elif buf>a[idx]: heapq.heappush(h,[buf*-1,idx]) print(loop) if __name__ == '__main__': main()
import sys import heapq def main(): n=int(eval(input())) a=list(map(int,input().split())) b=list(map(int,input().split())) h=[] for i in range(n): if b[i]>a[i]: heapq.heappush(h,(b[i]*-1,i)) loop=0 idx=0 while(1): #print(b) if not h: break buf,idx=heapq.heappop(h) buf=-1*buf x=(buf-a[idx])//(b[(idx-1)%n]+b[(idx+1)%n]) buf-=x*(b[(idx-1)%n]+b[(idx+1)%n]) loop+=x b[idx]=buf if x==0: #print(b) print((-1)) sys.exit() elif buf>a[idx]: heapq.heappush(h,(buf*-1,idx)) print(loop) if __name__ == '__main__': main()
p02941
N=int(eval(input())) A=tuple(map(int,input().split())) B=list(map(int,input().split())) from heapq import heappop,heappush q=[] a=0 for i,b in enumerate(B): heappush(q,(-b,i)) while len(q)>0: b,i=heappop(q) ba=-b-A[i] bb=B[i-1]+B[i+1-N] if ba<0: a=-1 break elif ba==0: continue elif -b>bb: x=ba//bb if x==0: a=-1 break B[i]-=bb*x heappush(q,(-B[i],i)) a+=x else: a=-1 break print(a)
N=int(eval(input())) A=tuple(map(int,input().split())) B=list(map(int,input().split())) from heapq import heappop,heappush q=[] a=0 for i,b in enumerate(B): heappush(q,(-b,i)) while len(q)>0: b,i=heappop(q) ba=-b-A[i] bb=B[i-1]+B[i+1-N] if ba<0: a=-1 break elif ba==0: continue elif -b>bb: x,y=divmod(ba,bb) if x==0: a=-1 break B[i]-=bb*x if y>0: heappush(q,(-B[i],i)) a+=x else: a=-1 break print(a)
p02941
from heapq import heappush, heappop N = int(eval(input())) A = [int(i) for i in input().split()] B = [int(i) for i in input().split()] def solve() : h = [] for i in range(N) : if A[i] == B[i] : continue heappush(h, (-B[i], i)) ret = 0 while len(h) > 1 : _, i = heappop(h) if B[i] > A[i] : m, M = B[(i-1)%N], B[(i+1)%N] if m > M : m, M = M, m x = (B[i] - B[h[0][1]] + m + M - 1) // (m + M) B[i] -= x * (m + M) ret += x if A[i] > B[i] : return -1 elif A[i] < B[i] : heappush(h, (-B[i], i)) _, i = heappop(h) if (B[i] - A[i]) % (B[(i-1)%N] + B[(i+1)%N]) == 0 : ret += (B[i] - A[i]) // (B[(i-1)%N] + B[(i+1)%N]) else : return -1 return ret print((solve()))
from heapq import heappush, heappop N = int(eval(input())) A = [int(i) for i in input().split()] B = [int(i) for i in input().split()] def solve() : h = [] for i in range(N) : if A[i] == B[i] : continue heappush(h, (-B[i], i)) ret = 0 while h : _, i = heappop(h) m, M = B[(i-1)%N], B[(i+1)%N] if m > M : m, M = M, m if M >= A[i] : x = (B[i] + m - 1) // (m + M) B[i] -= x * (m + M) ret += x else : if (B[i] - A[i]) % (m + M) != 0 : return -1 ret += (B[i] - A[i]) // (m + M) B[i] = A[i] if A[i] > B[i] : return -1 elif A[i] < B[i] : heappush(h, (-B[i], i)) return ret print((solve()))
p02941
n=int(eval(input())) A=list(map(int,input().split( ))) B=list(map(int,input().split( ))) count=0 prv_count=-1#人の見て追加 #flag=True while count!=prv_count: prv_count=count for i in range(-1,n-1): tonari=B[i-1]+B[i+1] tmp=(B[i]-A[i])//tonari if tmp>0: B[i]-=tonari*tmp count+=tmp #flag=True if A==B: print(count) else: print((-1))
###test n=int(eval(input())) A=list(map(int,input().split( ))) B=list(map(int,input().split( ))) count=0 flag=True while flag: flag=False for i in range(-1,n-1): tonari=B[i-1]+B[i+1] tmp=(B[i]-A[i])//tonari if tmp>0: B[i]-=tonari*tmp count+=tmp flag=True if A==B: print(count) else: print((-1))
p02941
###test n=int(eval(input())) A=list(map(int,input().split( ))) B=list(map(int,input().split( ))) count=0 flag=True while flag: flag=False for i in range(-1,n-1): tonari=B[i-1]+B[i+1] tmp=(B[i]-A[i])//tonari if tmp>0: B[i]-=tonari*tmp count+=tmp flag=True if A==B: print(count) else: print((-1))
n=int(eval(input())) A=list(map(int,input().split( ))) B=list(map(int,input().split( ))) count=0 flag=True while flag: flag=False for i in range(-1,n-1): tonari=B[i-1]+B[i+1] tmp=(B[i]-A[i])//tonari if tmp>0: B[i]-=tonari*tmp count+=tmp flag=True if A==B: print(count) else: print((-1))
p02941
def main(): from heapq import heappop as hpop from heapq import heappush as hpush n = int(eval(input())) a = list(map(int, input().split())) b = list(map(int, input().split())) visit = [False]*n h = [] for i in range(n): hpush(h, (-b[i], i)) cnt = 0 while h: i, j = hpop(h) i = -i jj = (j+1) % n if visit[j]: if a[j] != b[j]: print((-1)) return 0 visit[j-1] = True visit[jj] = True continue temp = i-a[j] temp2 = b[j-1]+b[jj] sho = temp//temp2 if sho == 0: if temp: print((-1)) return 0 visit[j-1] = True visit[jj] = True continue cnt += sho b[j] -= temp2*sho hpush(h, (-b[j], j)) print(cnt) main()
def main(): from heapq import heappop as hpop from heapq import heappush as hpush n = int(eval(input())) a = list(map(int, input().split())) b = list(map(int, input().split())) h = [] for i in range(n): hpush(h, (-b[i], i)) cnt = 0 while h: i, j = hpop(h) i = -i jj = (j+1) % n temp = i-a[j] temp2 = b[j-1]+b[jj] sho = temp//temp2 if sho == 0: if temp: print((-1)) return 0 continue cnt += sho b[j] -= temp2*sho hpush(h, (-b[j], j)) print(cnt) main()
p02941
import heapq q = [] heapq.heapify(q) n = int(eval(input())) As = list(map(int, input().split())) Bs = list(map(int, input().split())) zeros = [False]*n Cs = [Bs[(i-1)%n]+Bs[(i+1)%n] for i in range(n)] Ds = [b-(c+a) for b,c,a in zip(Bs,Cs,As)] # Dが大きい順に操作していく? # 初期値 for i,d in enumerate(Ds): if d < 0: continue heapq.heappush(q,(-d,i)) # print("init",Bs,Cs) cnt = 0 while len(q) > 0: d,i = heapq.heappop(q) # 自分と周りの影響を更新 # print(Bs,Cs,i,"before") cnt_ = (Bs[i%n]-As[i%n]) // Cs[i%n] Bs[i%n] -= cnt_*Cs[i%n] Cs[(i-1)%n] = Bs[(i-2)%n]+Bs[i%n] Cs[(i+1)%n] = Bs[(i+2)%n]+Bs[i%n] # print("bef",Bs,Cs,i) # 周りとの差 d_m = Bs[(i-1)%n]-Cs[(i-1)%n]-As[(i-1)%n] d_p = Bs[(i+1)%n]-Cs[(i+1)%n]-As[(i+1)%n] # print("pop",d,i,d_m,d_p) if d_m >= 0: heapq.heappush(q,(-d_m,i-1)) if d_p >= 0: heapq.heappush(q,(-d_p,i+1)) # print("debug",Bs,Cs) cnt += cnt_ if As == Bs: print(cnt) else: print((-1))
import heapq q = [] heapq.heapify(q) n = int(eval(input())) As = list(map(int, input().split())) Bs = list(map(int, input().split())) zeros = [False]*n Cs = [Bs[(i-1)%n]+Bs[(i+1)%n] for i in range(n)] # Dが大きい順に操作していく for i, (b,c,a) in enumerate(zip(Bs,Cs,As)): d = b-(c+a) if d < 0: continue heapq.heappush(q,(-d,i)) cnt = 0 while len(q) > 0: d,i = heapq.heappop(q) # 自分と周りの影響を更新 cnt_ = (Bs[i%n]-As[i%n]) // Cs[i%n] Bs[i%n] -= cnt_*Cs[i%n] Cs[(i-1)%n] = Bs[(i-2)%n]+Bs[i%n] Cs[(i+1)%n] = Bs[(i+2)%n]+Bs[i%n] # 周りとの差 d_m = Bs[(i-1)%n]-Cs[(i-1)%n]-As[(i-1)%n] d_p = Bs[(i+1)%n]-Cs[(i+1)%n]-As[(i+1)%n] if d_m >= 0: heapq.heappush(q,(-d_m,i-1)) if d_p >= 0: heapq.heappush(q,(-d_p,i+1)) cnt += cnt_ if As == Bs: print(cnt) else: print((-1))
p02941
words = lambda t : list(map(t, input().split())) n = int(eval(input())) a = words(int) b = words(int) def getNext(i): if i == n-1: return 0 else: return i+1 def getPrev(i): if i == 0: return n-1 else: return i-1 import queue q = queue.Queue() def verify(i): if b[i] != a[i] and b[i] - (b[getNext(i)] + b[getPrev(i)]) >= a[i]: return True else: return False for i in range(len(b)): if b[i] >= a[i] and verify(i): q.put(i) ans = 0 succeed = True while not q.empty(): i = q.get() ni = getNext(i) pi = getPrev(i) #print(i, b) d = b[ni] + b[pi] if b[i] % d == a[i] % d: ans += b[i] // d - (a[i] // d) b[i] = a[i] else: ans += b[i] // d b[i] %= d if b[i] < a[i]: succeed = False break if verify(ni): q.put(ni) if verify(pi): q.put(pi) for i in range(len(b)): if a[i] != b[i]: succeed = False break if succeed: print(ans) else: print((-1))
words = lambda t : list(map(t, input().split())) n = int(eval(input())) a = words(int) b = words(int) def getNext(i): if i == n-1: return 0 else: return i+1 def getPrev(i): if i == 0: return n-1 else: return i-1 from collections import deque q = deque() def verify(i): if b[i] != a[i] and b[i] - (b[getNext(i)] + b[getPrev(i)]) >= a[i]: return True else: return False for i in range(len(b)): if b[i] >= a[i] and verify(i): q.append(i) ans = 0 succeed = True while not len(q) == 0: i = q.popleft() ni = getNext(i) pi = getPrev(i) #print(i, b) d = b[ni] + b[pi] if b[i] % d == a[i] % d: ans += b[i] // d - (a[i] // d) b[i] = a[i] else: ans += b[i] // d b[i] %= d if b[i] < a[i]: succeed = False break if verify(ni): q.append(ni) if verify(pi): q.append(pi) for i in range(len(b)): if a[i] != b[i]: succeed = False break if succeed: print(ans) else: print((-1))
p02941
from heapq import heappush,heappop n,*t=list(map(int,open(0).read().split())) a=t[:n] b=t[n:] B=[] for i,j in enumerate(b):heappush(B,(-j,i)) c=0 d=0 while B and d<2*10**6: d+=1 y,i=heappop(B) x,z=b[(i-1)%n],b[(i+1)%n] t=(b[i]-a[i])//(x+z) b[i]-=t*(x+z) c+=t if b[i]>a[i]: heappush(B,(-b[i],i)) print(([-1,c][a==b]))
n,*t=list(map(int,open(0).read().split()));A=t[:n];B=t[n:];r=0 while True: c=0 for i in range(n): b=B[(i-1)%n]+B[(i+1)%n] if 0<b<B[i] and A[i]<B[i]: t=(B[i]-A[i])//b c+=t B[i]-=t*b r+=c if c==0:break print(([-1,r][A==B]))
p02941
n,*t=list(map(int,open(0).read().split()));A=t[:n];B=t[n:];r=0 while 1: c=0 for i in range(n): b=B[~-i%n]+B[-~i%n] if b<B[i]and A[i]<B[i]:t=(B[i]-A[i])//b;c+=t;B[i]-=t*b r+=c if c==0:break print(([-1,r][A==B]))
n,*t=list(map(int,open(0).read().split()));A=t[:n];B=t[n:];r=0 while 1: c=0 for i in range(n): b=B[~-i%n]+B[-~i%n] if A[i]<B[i]>b:t=(B[i]-A[i])//b;c+=t;B[i]-=t*b r+=c if c==0:break print(([-1,r][A==B]))
p02941
def examA(): S = SI(); N = len(S) prev = S[0]; cur = "" k = 0; ans = 1 while(k<N-1): k +=1 cur += S[k] if cur==prev: continue prev = cur cur = "" ans +=1 print(ans) return def examB(): N = I() S = SI() return def examC(): N = I() A = LI() B = LI() ans = 0 que = [] for i in range(N): que.append((-B[i],i)) heapify(que) flag = True while(que): b,i = heappop(que) b *=(-1) if b == A[i]: continue a, c = B[(i - 1) % N], B[(i + 1) % N] if b - A[i] < a + c: flag = False break r = (b - A[i]) // (a + c) b -= (a + c) * r B[i] = b ans += r if b != A[i]: heapq.heappush(que, (-b, i)) # print(que) # print(K) if flag: print(ans) else: print((-1)) return import sys,copy,bisect,itertools,heapq,math from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,mod2,inf mod = 10**9 + 7 mod2 = 998244353 inf = 10**18 if __name__ == '__main__': examC()
def examA(): S = SI(); N = len(S) prev = S[0]; cur = "" k = 0; ans = 1 while(k<N-1): k +=1 cur += S[k] if cur==prev: continue prev = cur cur = "" ans +=1 print(ans) return def examB(): N = I() S = SI() return def examC(): N = I() A = LI() B = LI() ans = 0 que = [] for i in range(N): heappush(que,(-B[i],i)) flag = True while(que): b,i = heappop(que) b *=(-1) if b == A[i]: continue a, c = B[(i - 1) % N], B[(i + 1) % N] if b - A[i] < a + c: flag = False break r = (b - A[i]) // (a + c) b -= (a + c) * r B[i] = b ans += r if b != A[i]: heapq.heappush(que, (-b, i)) # print(que) # print(K) if flag: print(ans) else: print((-1)) return import sys,copy,bisect,itertools,heapq,math from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,mod2,inf mod = 10**9 + 7 mod2 = 998244353 inf = 10**18 if __name__ == '__main__': examC()
p02941
import sys input = sys.stdin.readline N=int(eval(input())) A=list(map(int,input().split())) B=list(map(int,input().split())) BI=[(b,i) for i,b in enumerate(B)] # Segment tree(1-indexed,再帰を使わないもの) seg_el=1<<(N.bit_length())# Segment treeの台の要素数 SEG=[(0,0)]*(2*seg_el)# 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化 for i in range(N): SEG[i+seg_el]=BI[i] for i in range(seg_el-1,0,-1):# 親の部分もupdate SEG[i]=max(SEG[i*2],SEG[i*2+1]) def update(n,x,seg_el):# A[n]をxへ更新(反映) i=n+seg_el SEG[i]=x i>>=1# 子ノードへ while i!=0: SEG[i]=max(SEG[i*2],SEG[i*2+1]) i>>=1 def getvalues(l,r):# 区間[l,r)に関するmaxを調べる L=l+seg_el R=r+seg_el ANS=(0,0) while L<R: if L & 1: ANS=max(ANS , SEG[L]) L+=1 if R & 1: R-=1 ANS=max(ANS , SEG[R]) L>>=1 R>>=1 return ANS ANS=0 while True: x,y=getvalues(0,N) if x==0: break if x<A[y]: print((-1)) sys.exit() elif x==A[y]: update(y,(0,y),seg_el) else: B[y]-=B[(y+1)%N]+B[(y-1)%N] ANS+=1 update(y,(B[y],y),seg_el) print(ANS)
import sys input = sys.stdin.readline N=int(eval(input())) A=list(map(int,input().split())) B=list(map(int,input().split())) BI=[(b,i) for i,b in enumerate(B)] # Segment tree(1-indexed,再帰を使わないもの) seg_el=1<<(N.bit_length())# Segment treeの台の要素数 SEG=[(0,0)]*(2*seg_el)# 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化 for i in range(N): SEG[i+seg_el]=BI[i] for i in range(seg_el-1,0,-1):# 親の部分もupdate SEG[i]=max(SEG[i*2],SEG[i*2+1]) def update(n,x,seg_el):# A[n]をxへ更新(反映) i=n+seg_el SEG[i]=x i>>=1# 子ノードへ while i!=0: SEG[i]=max(SEG[i*2],SEG[i*2+1]) i>>=1 def getvalues(l,r):# 区間[l,r)に関するmaxを調べる L=l+seg_el R=r+seg_el ANS=(0,0) while L<R: if L & 1: ANS=max(ANS , SEG[L]) L+=1 if R & 1: R-=1 ANS=max(ANS , SEG[R]) L>>=1 R>>=1 return ANS ANS=0 while True: x,y=getvalues(0,N) if x==0: break if x<A[y]: print((-1)) sys.exit() elif x==A[y]: update(y,(0,y),seg_el) else: t=B[(y+1)%N]+B[(y-1)%N] if B[y]<t+A[y]: print((-1)) sys.exit() q=(B[y]-A[y])//t ANS+=q B[y]-=t*q update(y,(B[y],y),seg_el) print(ANS)
p02941
from heapq import heappop,heappush def main(a,b): for i in range(n): if b[i]<=a[i]: pass else: print((-1)) exit() pq=[] [heappush(pq,[-x,i]) for i,x in enumerate(a)] ans=0 while pq: v,i=heappop(pq) v=-v vv=v v-=b[i] tmp=a[(i-1)%n]+a[(i+1)%n] ans+=v//tmp v%=tmp v+=b[i] a[i]=v if v==b[i]:continue elif vv<=v or v<b[i]: print((-1)) exit() heappush(pq,[-v,i]) print(ans) if __name__=='__main__': n=int(eval(input())) b=list(map(int,input().split())) a=list(map(int,input().split())) main(a,b)
def main(n,a,b): ans=0 while True: cnt=0 for i in range(n): m=a[(i-1)%n]+a[(i+1)%n] if m<a[i] and b[i]<a[i]: a[i]-=b[i] cnt+=a[i]//m a[i]%=m a[i]+=b[i] if cnt==0:break ans+=cnt if a==b: print(ans) else: print((-1)) if __name__=='__main__': n=int(eval(input())) b=list(map(int,input().split())) a=list(map(int,input().split())) main(n,a,b)
p02941
def p_c(): N = int(eval(input())) A = list(map(int, input().split())) B = list(map(int, input().split())) l = [-1] * N idx = set(range(N)) for i in range(N): l[i] = B[i - 1] + B[(i + 1) % N] ans = 0 while 1: f = False for i in list(idx): if A[i] <= B[i] - l[i]: f = True ans += 1 B[i] -= l[i] l[i - 1] -= l[i] l[(i + 1) % N] -= l[i] idx.add((N + i - 1) % N) idx.add((i + 1) % N) else: idx.remove(i) if not f: break if A != B: print((-1)) else: print(ans) if __name__ == '__main__': p_c()
def p_c(): N = int(eval(input())) A = list(map(int, input().split())) B = list(map(int, input().split())) l = [-1] * N for i in range(N): l[i] = B[i - 1] + B[(i + 1) % N] ans = 0 while 1: f = False for i in range(N): if A[i] <= B[i] - l[i]: f = True n = (B[i] - A[i]) // l[i] ans += n B[i] -= n * l[i] l[i - 1] -= n * l[i] l[(i + 1) % N] -= n * l[i] if not f: break if A != B: print((-1)) else: print(ans) if __name__ == '__main__': p_c()
p02941
import heapq N = int(eval(input())) A = list(map(int,input().split())) B = list(map(int,input().split())) if any(a>b for a,b in zip(A,B)): print((-1)) exit() hq = [(-a,i) for i,a in enumerate(B)] heapq.heapify(hq) ans = 0 while hq: _,i = heapq.heappop(hq) if B[i] == A[i]: continue l = B[(i-1)%N] r = B[(i+1)%N] if B[i]-l-r < A[i]: continue k = (B[i]-A[i]) // (l+r) ans += k B[i] -= k*(l+r) heapq.heappush(hq, (-B[i],i)) if all(a==b for a,b in zip(A,B)): print(ans) else: print((-1))
import heapq N = int(eval(input())) A = list(map(int,input().split())) B = list(map(int,input().split())) if any(a>b for a,b in zip(A,B)): print((-1)) exit() hq = [] for i,(a,b) in enumerate(zip(A,B)): if a <= b - B[(i-1)%N] - B[(i+1)%N]: hq.append((-b,i)) heapq.heapify(hq) ans = 0 while hq: _,i = heapq.heappop(hq) if B[i] == A[i]: continue l = B[(i-1)%N] r = B[(i+1)%N] if B[i]-l-r < A[i]: continue k = (B[i]-A[i]) // (l+r) ans += k B[i] -= k*(l+r) if A[i] <= B[i] - l - r: heapq.heappush(hq, (-B[i],i)) ll = B[(i-2)%N] rr = B[(i+2)%N] if A[(i+1)%N] <= r - B[i] - rr: heapq.heappush(hq, (-r,(i+1)%N)) if A[(i-1)%N] <= l - B[i] - ll: heapq.heappush(hq, (-l,(i-1)%N)) if all(a==b for a,b in zip(A,B)): print(ans) else: print((-1))
p02941
import heapq N = int(eval(input())) A = list(map(int,input().split())) B = list(map(int,input().split())) if any(a>b for a,b in zip(A,B)): print((-1)) exit() def pb(i): return i-1 if i-1 >= 0 else N-1 def nx(i): return i+1 if i+1 < N else 0 hq = [] for i,(a,b) in enumerate(zip(A,B)): if a <= b - B[pb(i)] - B[nx(i)]: hq.append((-b,i)) heapq.heapify(hq) ans = 0 while hq: _,i = heapq.heappop(hq) if B[i] == A[i]: continue l = B[pb(i)] r = B[nx(i)] if B[i]-l-r < A[i]: continue k = (B[i]-A[i]) // (l+r) ans += k B[i] -= k*(l+r) if A[i] <= B[i] - l - r: heapq.heappush(hq, (-B[i],i)) ll = B[pb(pb(i))] rr = B[nx(nx(i))] if A[nx(i)] <= r - B[i] - rr: heapq.heappush(hq, (-r,nx(i))) if A[pb(i)] <= l - B[i] - ll: heapq.heappush(hq, (-l,pb(i))) if all(a==b for a,b in zip(A,B)): print(ans) else: print((-1))
import heapq N = int(eval(input())) A = list(map(int,input().split())) B = list(map(int,input().split())) if any(a>b for a,b in zip(A,B)): print((-1)) exit() def pb(i): return i-1 if i-1 >= 0 else N-1 def nx(i): return i+1 if i+1 < N else 0 hq = [] for i,(a,b) in enumerate(zip(A,B)): if a <= b - B[pb(i)] - B[nx(i)]: hq.append((-b,i)) heapq.heapify(hq) ans = 0 while hq: _,i = heapq.heappop(hq) if B[i] == A[i]: continue l = B[pb(i)] r = B[nx(i)] if B[i]-l-r < A[i]: continue k = (B[i]-A[i]) // (l+r) ans += k B[i] -= k*(l+r) ll = B[pb(pb(i))] rr = B[nx(nx(i))] if A[nx(i)] <= r - B[i] - rr: heapq.heappush(hq, (-r,nx(i))) if A[pb(i)] <= l - B[i] - ll: heapq.heappush(hq, (-l,pb(i))) if all(a==b for a,b in zip(A,B)): print(ans) else: print((-1))
p02941
from collections import deque def main(): N=int(eval(input())) A=list(map(int, input().split())) B=list(map(int, input().split())) q = deque() cq = deque() q.appendleft(B) cq.appendleft(0) while len(q) > 0: b = q.pop() c = cq.pop() if b == A: print(c) break else: for i in range(N): _tmp = b[0:N] _tmp[i] = b[i] - b[i-1 if i>=1 else N-1] - b[i+1 if i<N-1 else 0] if A[i] <= _tmp[i]: #print(_tmp) q.appendleft(_tmp) cq.appendleft(c+1) else: print((-1)) if __name__ == '__main__': main()
def main(): N=int(eval(input())) A=list(map(int, input().split())) B=list(map(int, input().split())) count = 0 while A!=B: b = True for i in range(N): d = B[i-1 if i>=1 else N-1] + B[i+1 if i<N-1 else 0] if B[i] > d > 0: b = False c = (B[i]-A[i]) // d B[i] -= d * c count += c if b: if A == B: print(count) else: print((-1)) break else: if A == B: print(count) else: print((-1)) if __name__ == '__main__': main()
p02941
import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ def unable(): print((-1)) exit() n = int(eval(input())) a = list(map(int, input().split())) b = list(map(int, input().split())) from heapq import heappop, heappush done = set() heap = [] for i in range(n): if a[i] > b[i]: unable() elif a[i] == b[i]: done.add(i) elif b[i] >= b[i-1]+b[(i+1)%n]: heappush(heap, (-b[i],i)) ans = 0 while heap and len(done) != n: _, cur = heappop(heap) prv = (cur-1)%n nxt = (cur+1)%n base = b[prv]+b[nxt] cnt1, mod = divmod(b[cur], base) if cnt1 == 0: if b[cur] == a[cur]: done.add(cur) continue if mod > a[cur]: ans += cnt1 b[cur] = mod else: cnt2, mod = divmod(b[cur]-a[cur], base) if mod != 0: unable() ans += cnt2 done.add(cur) b[cur] = a[cur] if prv not in done: heappush(heap, (-b[prv], prv)) if nxt not in done: heappush(heap, (-b[nxt], nxt)) if len(done)==n: print(ans) else: unable()
import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ def unable(): print((-1)) exit() n = int(eval(input())) a = list(map(int, input().split())) b = list(map(int, input().split())) from heapq import heappush, heappop h = [] for i in range(n): if a[i]>b[i]: unable() else: heappush(h, (-b[i], i)) ans = 0 while h: _, i = heappop(h) cnt, mod = divmod(b[i]-a[i],b[i-1]+b[(i+1)%n]) if cnt == 0: if mod != 0: unable() else: ans += cnt b[i] = a[i]+mod heappush(h, (-b[i], i)) print(ans)
p02941
import sys,heapq as hq mod = 10**9+7 def l(): #intのlist return list(map(int,input().split())) def m(): #複数文字 return list(map(int,input().split())) def onem(): #Nとかの取得 return int(eval(input())) n = onem() a = l() b = l() t = [] for i in range(n): if b[i] != a[i]: hq.heappush(t,(-b[i],i)) co = 0 while t: k = hq.heappop(t) k = (-k[0],k[1]) q,w = divmod(k[0] - a[k[1]], b[(k[1] - 1) % n] + b[(k[1] + 1) % n]) co += q if q == 0: print((-1)) exit() w = a[k[1]] + w b[k[1]] = w if b[k[1]] != a[k[1]]: hq.heappush(t,(-w,k[1])) print(co)
import heapq as hq mod = 10**9+7 def l(): #intのlist return list(map(int,input().split())) def m(): #複数文字 return list(map(int,input().split())) def onem(): #Nとかの取得 return int(eval(input())) def onon(): n = onem() a = l() b = l() t = [] for i in range(n): if b[i] != a[i]: hq.heappush(t,(-b[i],i)) co = 0 while t: k = hq.heappop(t) k = (-k[0],k[1]) q,w = divmod(k[0] - a[k[1]], b[(k[1] - 1) % n] + b[(k[1] + 1) % n]) co += q if q == 0: return -1 w = a[k[1]] + w b[k[1]] = w if b[k[1]] != a[k[1]]: hq.heappush(t,(-w,k[1])) return co print((onon()))
p02941
from heapq import heappush,heappop import sys input=sys.stdin.readline N=int(eval(input())) A=list(map(int,input().split())) B=list(map(int,input().split())) lst=[] for i in range(N): heappush(lst,[-B[i],i]) count=0 while lst: h,i=heappop(lst) h=-h x,z=B[i-1],B[(i+1)%N] if (h-A[i])%(x+z)==0: num=(h-A[i])//(x+z) count+=num B[i]=A[i] continue else: num=h//(x+z) h=h%(x+z) count+=num if num==0: print((-1)) sys.exit() B[i]=h if A[i]>h: print((-1)) sys.exit() heappush(lst,[-h,i]) if A==B: print(count) else: print((-1))
from heapq import heappush,heappop import sys input=sys.stdin.readline N=int(eval(input())) A=list(map(int,input().split())) B=list(map(int,input().split())) lst=[] for i in range(N): heappush(lst,(-B[i],i)) count=0 while lst: h,i=heappop(lst) h=-h x,z=B[i-1],B[(i+1)%N] kkk=x+z if (h-A[i])%kkk==0: count+=(h-A[i])//kkk B[i]=A[i] continue elif kkk>=h: print((-1)) sys.exit() else: count+=h//kkk h=h%kkk B[i]=h if A[i]>h: print((-1)) sys.exit() heappush(lst,(-h,i)) if A==B: print(count) else: print((-1))
p02941
import sys input = sys.stdin.readline sys.setrecursionlimit(100000) def getN(): return int(eval(input())) def getList(): return list(map(int, input().split())) import math n = getN() anums = getList() bnums = getList() ans = 0 update = True while(update): update = False for i in range(n): if i == n - 1: j = 0 else: j = i + 1 h = i - 1 a,b,c = bnums[h], bnums[i], bnums[j] # print(a,b,c) if b > max(a, c): if anums[i] > bnums[i]: print((-1)) sys.exit() if anums[i] != bnums[i]: dec = math.ceil((b - (max(a, c, anums[i])) ) / (a+c)) bnums[i] -= dec * (a+c) ans += dec update = True # print(coll, anums, bnums) print(ans)
import sys input = sys.stdin.readline sys.setrecursionlimit(100000) def getN(): return int(eval(input())) def getList(): return list(map(int, input().split())) import math n = getN() anums = getList() bnums = getList() ans = 0 okay = [0 for i in range(n)] update = True while(update): update = False for i in range(n): if not okay[i]: if i == n - 1: j = 0 else: j = i + 1 h = i - 1 a,b,c, tgt = bnums[h], bnums[i], bnums[j], anums[i] # print(a,b,c) if b > max(a, c): if tgt > b: print((-1)) sys.exit() if tgt != b: dec = math.ceil((b - (max(a, c, tgt)) ) / (a+c)) bnums[i] -= dec * (a+c) ans += dec update = True if anums[i] == bnums[i]: okay[i] = 1 # print(coll, anums, bnums) print(ans)
p02941
from heapq import * N = int(eval(input())) A = [int(a) for a in input().split()] B = [int(a) for a in input().split()] h = [] for i in range(N): heappush(h, (-B[i], i)) ans = 0 while h: b, i = heappop(h) b = -b if b == A[i]: continue k = - (-(B[i] - max(B[i-1], B[(i+1)%N], A[i])) // (B[i-1] + B[(i+1)%N])) if k <= 0: print("-1") break B[i] -= (B[i-1] + B[(i+1)%N]) * k heappush(h, (-B[i], i)) ans += k else: print(ans)
N = int(eval(input())) A = [int(a) for a in input().split()] B = [int(a) for a in input().split()] if N > 10000: A = A[5050:] + A[:5050] B = B[5050:] + B[:5050] ans = -1 D = [0] * N L = [i-1 for i in range(N)] R = [i+1 for i in range(N)] def calc(): i = 0 c = 0 ans = 0 while c < N: while i < N: if B[i] == A[i]: if D[i] == 0: c += 1 D[i] = 1 if L[i] >= 0: R[L[i]] = R[i] if R[i] < N: L[R[i]] = L[i] if B[i] > A[i] and B[i] >= max(B[i-1], B[(i+1)%N]): k = - (-(B[i] - max(B[i-1], B[(i+1)%N], A[i])) // (B[i-1] + B[(i+1)%N])) B[i] -= (B[i-1] + B[(i+1)%N]) * k ans += k if k <= 0: return -1 i = R[i] i = N-1 while i >= 0: if B[i] == A[i]: if D[i] == 0: c += 1 D[i] = 1 if L[i] >= 0: R[L[i]] = R[i] if R[i] < N: L[R[i]] = L[i] if B[i] > A[i] and B[i] >= max(B[i-1], B[(i+1)%N]): k = - (-(B[i] - max(B[i-1], B[(i+1)%N], A[i])) // (B[i-1] + B[(i+1)%N])) B[i] -= (B[i-1] + B[(i+1)%N]) * k ans += k if k <= 0: return -1 i = L[i] return ans print((calc()))
p02941