_id
stringlengths
2
5
partition
stringclasses
2 values
text
stringlengths
5
289k
language
stringclasses
1 value
meta_information
dict
title
stringclasses
1 value
d2001
train
import heapq n,m,a,b=map(int,input().split()) graph={i:[] for i in range(n)} for i in range(m): u,v,w=map(int,input().split()) graph[u-1].append((v-1,w)) graph[v-1].append((u-1,w)) components=[-1]*n comp=-1 for i in range(n): if components[i]==-1: comp+=1 components[i]=comp prev=[] layer=[i] while layer!=[]: newlayer=[] for guy in layer: for guy1 in graph[guy]: if guy1[1]==a and components[guy1[0]]==-1: newlayer.append(guy1[0]) components[guy1[0]]=comp prev=layer[:] layer=newlayer[:] useless=[] for guy in graph: for neigh in graph[guy]: if components[guy]==components[neigh[0]] and neigh[1]==b: useless.append((guy,neigh)) for guy in useless: graph[guy[0]].remove(guy[1]) counts=[0]*(comp+1) for i in range(n): counts[components[i]]+=1 bad=[] for i in range(comp+1): if counts[i]<=3: bad.append(i) for j in range(n): if components[j]==i: components[j]=-1 for guy in bad[::-1]: for i in range(n): if components[i]>guy: components[i]-=1 comp-=len(bad) comp+=1 dists=[[float("inf") for i in range(2**comp)] for j in range(n)] dists[0][0]=0 pq=[] heapq.heappush(pq,[0,0,0]) remaining=n visited=[0]*n while len(pq)>0 and remaining>0: dist,vert,mask=heapq.heappop(pq) if visited[vert]==0: visited[vert]=1 remaining-=1 for neigh in graph[vert]: if neigh[1]==b: if components[vert]==components[neigh[0]] and components[vert]!=-1: continue if components[neigh[0]]!=-1: if mask & (2**components[neigh[0]])>0: continue if components[vert]!=-1: maskn=mask+2**(components[vert]) else: maskn=mask else: maskn=mask if dist+neigh[1]<dists[neigh[0]][maskn]: dists[neigh[0]][maskn]=dist+neigh[1] heapq.heappush(pq,[dist+neigh[1],neigh[0],maskn]) optimal=[str(min(dists[i])) for i in range(n)] print(" ".join(optimal))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1149/D" }
d2002
train
X, D = list(map(int, input().split())) cn = 1 add0 = 1 if (X&1) else 0 ans = [] for i in range(30,0,-1): if not (X & (1<<i)): continue ans += [cn]*i add0 += 1 cn += D for i in range(add0): ans.append(cn) cn += D print(len(ans)) print(' '.join(map(str, ans)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/960/C" }
d2003
train
str = input() l = len(str) a = [0] * (2 * l) pos = [[] for i in range(26)] for i, c in enumerate(str): t = ord(c) - ord('a') a[i] = t a[i + l] = t pos[t].append(i) ans = 0 for c in range(26): cur = 0 for k in range(1, l): cnt = [0] * 26 for i in pos[c]: cnt[a[i + k]] += 1 cur = max(cur, len(list([x for x in cnt if x == 1]))) ans += cur print(ans / l)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/930/B" }
d2004
train
from bisect import * from math import * n = int(input()) a, b, c, d = list(map(int,input().replace('/',' ').split())) alpha = atan2(c,d) - atan2(a,b) tan_alpha = tan(alpha) lis = [] for x,y in sorted((y/tan_alpha - x,y) for x,y in [ (x,y) for x,y in [(b*x + a*y,-a*x + b*y) for x, y in [list(map(int,input().split())) for _ in range(n)] if a*x - b*y <= 0 and d*y - c*x <= 0]]): pos = bisect_left(lis,-y) if pos == len(lis): lis.append(-y) else: lis[pos] = -y print(len(lis))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/249/D" }
d2005
train
x = input () flag = 0 s = 0 for each_item in x: if each_item == '0': if flag == 0: flag = 1; continue else: print (each_item, end = '') else: if (s == len (x) - 1 and flag == 0) : continue print (each_item, end = '') s = s + 1
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/258/A" }
d2006
train
X = [[], ['0', '1'], ['00', '01', '10', '11'], ['001', '010', '011', '100', '101', '110'], ['0010', '0011', '0100', '0101', '0110', '1001', '1010', '1011', '1100', '1101'], ['00100', '00101', '00110', '01001', '01011', '01100', '01101', '10010', '10011', '10100', '10110', '11001', '11010', '11011'], ['001001', '001011', '001100', '001101', '010010', '010011', '010110', '011001', '011010', '011011', '100100', '100101', '100110', '101001', '101100', '101101', '110010', '110011', '110100', '110110'], ['0010011', '0011001', '0011010', '0011011', '0100101', '0101100', '0101101', '0110011', '1001100', '1010010', '1010011', '1011010', '1100100', '1100101', '1100110', '1101100'], ['00110011', '01011010', '01100110', '10011001', '10100101', '11001100']] s = input() N = len(s) ans = (N-1)*(N-2)//2 for i in range(N): for j in range(i+3, min(i+9, N+1)): if s[i:j] in X[j-i]: ans -= 1 print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1168/B" }
d2007
train
def gcd(a, b): while b > 0: a, b = b, a % b return a n = int(input()) A = list(map(int, input().split())) GCD = A[0] for x in A[1:]: GCD = gcd(GCD, x) num = max(A) // GCD - n if num % 2 == 0: print("Bob") else: print("Alice")
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/346/A" }
d2008
train
import sys from itertools import * from math import * def solve(): n, m = map(int, input().split()) h = list(map(int, input().split())) p = list(map(int, input().split())) ss, ll = 0, int(2.2e10) while ss < ll: avg = (ss + ll) // 2 works = True hidx = 0 pidx = 0 while hidx < len(h) and pidx < len(p): leftget = p[pidx] curpos = h[hidx] if curpos - leftget > avg: works = False break getbacktime = max(0, 2*(curpos - leftget)) alsotoright = max(0, avg - getbacktime) leftime = max(0, curpos - leftget) remtime = max(0, (avg - leftime) // 2) furthestright = curpos + max(alsotoright, remtime) while pidx < len(p) and p[pidx] <= furthestright: pidx += 1 hidx += 1 if pidx != len(p): works = False if works: ll = avg else: ss = avg + 1 print(ss) if sys.hexversion == 50594544 : sys.stdin = open("test.txt") solve()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/343/C" }
d2009
train
from sys import stdin #stdin = open('input.txt') n = int(stdin.readline()) seq = [int(x) for x in stdin.readline().split()] carry = seq[0] result = [carry] mark = False cur_len = 0 max_len = 0 i = 1 while i < len(seq) - 1: if mark: if seq[i] != seq[i + 1]: cur_len += 1 else: if cur_len > max_len: max_len = cur_len if seq[i] == carry: result.extend([carry]*cur_len) else: result.extend([carry]*(cur_len//2)) result.extend([seq[i]]*(cur_len//2)) result.append(seq[i]) mark = False cur_len = 0 elif seq[i] != seq[i - 1] and seq[i] != seq[i + 1]: mark = True cur_len = 1 carry = seq[i - 1] else: result.append(seq[i]) i += 1 if mark: if cur_len > max_len: max_len = cur_len if seq[i] == carry: result.extend([carry]*cur_len) else: result.extend([carry]*(cur_len//2)) result.extend([seq[i]]*(cur_len//2)) result.append(seq[i]) print((max_len + 1)//2) for x in result: print(x, end=' ')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/590/A" }
d2010
train
import random n = int(input()) v = [] a = [] for i in range(n): a.append(i) for _ in range(0, n): x, y = list(map(int, input().split())) v.append([x, y, x*x+y*y]) while 1>0: x = 0 y = 0 ans = [0]*n random.shuffle(a) for i in range(n): if (x+v[a[i]][0])**2+(y+v[a[i]][1])**2 <= (x-v[a[i]][0])**2+(y-v[a[i]][1])**2: x += v[a[i]][0] y += v[a[i]][1] ans[a[i]] = 1 else: x -= v[a[i]][0] y -= v[a[i]][1] ans[a[i]] = -1 if x*x+y*y <= 1500000**2: print(*ans) break
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/995/C" }
d2011
train
x = int(input()) y = list(map(int, input().split(' '))) y[0] = 1 y[x-1] = 1 z = y[:] for i in range(1, x): z[i] = min(z[i], z[i-1] + 1) w = y[:] for i in range(x-2, -1, -1): w[i] = min(w[i], w[i+1]+1) ans = 0 for i in range(x): ans = max(ans, min(z[i], w[i])) print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/573/B" }
d2012
train
n=int(input()) q=[] for i in range(max(0,n-100),n+1): j=i res=i while j: res+=j%10 j//=10 if res==n: q.append(i) print(len(q)) for i in q: print(i)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/875/A" }
d2013
train
n = int(input()) if n%4 > 1: print(-1) else: a = [n+1>>1]*n for i in range(n//4): j = i*2 a[j], a[j+1], a[-2-j], a[-1-j] = j+2, n-j, j+1, n-1-j print(' '.join(map(str, a)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/286/A" }
d2014
train
#!/usr/bin/env python3 import re try: while True: s = input() m = re.search(r"[^a]", s) if m is None: print(s[:-1], end="z\n") else: j = s.find('a', m.end()) if j == -1: j = len(s) print(end=s[:m.start()]) for i in range(m.start(), j): print(end=chr((ord(s[i]) - 98) % 26 + 97)) print(s[j:]) except EOFError: pass
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/708/A" }
d2015
train
mod = 1000000007 def sum(x, y, k, add) : if k < add : return 0 up = x + add if up > k : up = k add = add + 1 return y * ( ( (add + up) * (up - add + 1) // 2 ) % mod ) % mod def solve(x, y, k, add = 0) : if x == 0 or y == 0 : return 0 if x > y : x, y = y, x pw = 1 while (pw << 1) <= y : pw <<= 1 if pw <= x : return ( sum(pw, pw, k, add)\ + sum(pw, x + y - pw - pw, k, add + pw)\ + solve(x - pw, y - pw, k, add) ) % mod else : return ( sum(pw, x, k, add)\ + solve(x, y - pw, k, add + pw) ) % mod q = int(input()) for i in range(0, q) : x1, y1, x2, y2, k = list(map(int, input().split())) ans = ( solve(x2, y2, k)\ - solve(x1 - 1, y2, k)\ - solve(x2, y1 - 1, k)\ + solve(x1 - 1, y1 - 1, k) ) % mod if ans < 0 : ans += mod print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/809/C" }
d2016
train
import sys n = int(input()) v = [ list(map(int, input().split())) for i in range(n)] res = [] for i in range(n): if v[i][2] >= 0: res.append(i + 1) dec = 0 for j in range(i + 1, n): if v[j][2] >= 0: if v[i][0] > 0: v[j][2] -= v[i][0] v[i][0] -= 1 v[j][2] -= dec if v[j][2] < 0: dec += v[j][1] print(len(res)) print(" ".join(map(str, res)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/585/A" }
d2017
train
import sys input = sys.stdin.readline n,m=list(map(int,input().split())) W=[0]+list(map(int,input().split())) E=[tuple(map(int,input().split())) for i in range(m)] S=int(input()) ELIST=[[] for i in range(n+1)] EW=[0]*(n+1) for x,y in E: ELIST[x].append(y) ELIST[y].append(x) EW[x]+=1 EW[y]+=1 from collections import deque Q=deque() USED=[0]*(n+1) for i in range(1,n+1): if EW[i]==1 and i!=S: USED[i]=1 Q.append(i) EW[S]+=1<<50 USED[S]=1 while Q: x=Q.pop() EW[x]-=1 for to in ELIST[x]: if USED[to]==1: continue EW[to]-=1 if EW[to]==1 and USED[to]==0: Q.append(to) USED[to]=1 #print(EW) LOOP=[] ANS=0 for i in range(1,n+1): if EW[i]!=0: ANS+=W[i] LOOP.append(i) SCORE=[0]*(n+1) USED=[0]*(n+1) for l in LOOP: SCORE[l]=ANS USED[l]=1 Q=deque(LOOP) while Q: x=Q.pop() for to in ELIST[x]: if USED[to]==1: continue SCORE[to]=W[to]+SCORE[x] Q.append(to) USED[to]=1 print(max(SCORE))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1220/E" }
d2018
train
n = int(input()) xs = [int(x) for x in input().split()] seen = {} res = 0 while xs: j = xs.index(xs[0], 1) res += j - 1 xs = xs[1:j] + xs[j+1:] print(res)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/995/B" }
d2019
train
n,m=map(int,input().split());a=list(map(int,input().split()));p=0;t=[0]*3 for i in range(n): if(a[i]<a[p]):p=i if(n==2):print('0\n1 1\n') else: a.sort();t[0]=min(a[0]+a[1]+m,a[1]+a[2]);t[1]=max(a[0]+a[n-1]+m,a[n-2]+a[n-1]);t[2]=(a[n-2]+a[n-1])-(a[0]+a[1]) if(t[1]-t[0]>t[2]):p=n else:t[2]=t[1]-t[0] print(t[2]) for i in range(n):print(int(i==p)+1,end=' ')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/238/B" }
d2020
train
n = int(input()) a = list(map(int, input().split())) r = n-2 for d in a: r += d print(max(max(a), r//(n-1)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/348/A" }
d2021
train
import math #import fractions from functools import reduce n = int(input()) odd = -1 beads = [int(x) for x in input().split()] for i in range(n): if beads[i]%2: if odd >= 0: print(0) print(''.join(chr(ord('a') + i)*beads[i] for i in range(n))) break else: odd = i else: gcd = reduce(lambda x,y: math.gcd(x,y), beads) print(gcd) if odd >= 0: s = ''.join(chr(ord('a') + i)*(beads[i]//(2*gcd)) for i in range(n) if i != odd) p = s + chr(ord('a') + odd)*(beads[odd]//gcd) + s[::-1] print(p*gcd) else: s = ''.join(chr(ord('a') + i)*(beads[i]//gcd) for i in range(n)) p = s + s[::-1] print(p*(gcd//2))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/613/C" }
d2022
train
def main(): n, m = list(map(int, input().split())) l = [[] for _ in range(n + 1)] for _ in range(m): u, v = list(map(int, input().split())) l[u].append(v) l[v].append(u) res = [0] * (n + 1) for u, x in enumerate(res): if not x: x, nxt = -1, [u] while nxt: x, cur, nxt = -x, nxt, [] for u in cur: if l[u]: res[u] = x for v in l[u]: if not res[v]: nxt.append(v) elif res[v] == x: print(-1) return for x in -1, 1: l = [u for u in range(1, n + 1) if res[u] == x] print(len(l)) print(' '.join(map(str, l))) def __starting_point(): main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/687/A" }
d2023
train
n,m=map(int,input().split()) if n==1and m==1:print('YES\n1') elif n==3and m==3: print('YES') print(6, 1, 8) print(7,5,3) print(2,9,4) elif n<4and m<4:print('NO') elif n==1 or m==1: t=max(n,m) a=[i for i in range(2,t+1,2)] a+=[i for i in range(1,t+1,2)] print('YES') for i in a:print(i,end="");print([' ','\n'][m==1],end='') else: a=[] for j in range(n): a.append([int(i)+int(m*j) for i in range(1,m+1)]) if n<=m: for j in range(1,m,2): t=a[0][j] for i in range(1,n): a[i-1][j]=a[i][j] a[n-1][j]=t for i in range(1,n,2): r,s=a[i][0],a[i][1] for j in range(2,m): a[i][j-2]=a[i][j] a[i][m-2],a[i][m-1]=r,s else: for j in range(1,m,2): r,s=a[0][j],a[1][j] for i in range(2,n): a[i-2][j]=a[i][j] a[n-2][j], a[n-1][j] = r, s for i in range(1,n,2): t=a[i][0] for j in range(1,m): a[i][j-1]=a[i][j] a[i][m-1]=t print('YES') for i in range(n): print(*a[i])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/906/B" }
d2024
train
from math import sqrt n = int(input()) k = int(sqrt(n)) b = [] last = 0 while last < n: b.append([last + j for j in range(k)]) last = b[-1][-1] + 1 k = len(b) for i in range(k - 1, -1, -1): for j in b[i]: if j < n: print(1 + j, end=' ') print()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1017/C" }
d2025
train
n = input() read = input() p = [] for x in read.split(): p.append((float)(x)) v = 0.0 l = 0.0 for item in p: v = v*(1-item) + item*(v + 2*l + 1) l = (l + 1)*item print(v)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/235/B" }
d2026
train
def main(): n = int(input()) result = [] for i in range(2, n + 1): j = 2 while j * j <= i: if i % j == 0: break j += 1 else: j = i while j <= n: result.append(j) j *= i print(len(result)) print(' '.join(str(i) for i in result)) main()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/576/A" }
d2027
train
n, d = map(int, input().split()) a = [0] + list(map(int, input().split())) + [0] x = [] y = [] for i in range(n): xx, yy = map(int, input().split()) x += [xx] y += [yy] b = [-1] * n b[0] = 0 c = True while c: c = False for i in range(n): for j in range(1, n): if i != j and b[i] != -1: t = b[i] + (abs(x[i] - x[j]) + abs(y[i] - y[j])) * d - a[j] if b[j] == -1 or t < b[j]: b[j] = t c = True print(b[-1])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/301/B" }
d2028
train
t = input() a, b = [i for i, d in enumerate(t, 1) if d == 'l'], [i for i, d in enumerate(t, 1) if d == 'r'] a.reverse() print('\n'.join(map(str, b))) print('\n'.join(map(str, a)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/264/A" }
d2029
train
def solve(s): n = len(s) for i in range(n): s2 = s[i:] + s[:i] # print(s2) if s != s2 and s2[::-1] == s2: return 1 for i in range( (n // 2) + 1, n): if s[i] != s[0]: return 2 # print(s[i]) return "Impossible" s = input() print(solve(s))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1109/B" }
d2030
train
def main(): n = int(input()) ans = [0] * (2 * n) for i in range(n): a = 2 * i + 1 b = 2 * i + 2 if i & 1: ans[i] = a ans[i + n] = b else: ans[i] = b ans[i + n] = a ans *= 2 curr = sum(ans[:n]) mi = curr ma = curr for i in range(n, 4 * n): curr -= ans[i - n] curr += ans[i] mi = min(mi, curr) ma = max(ma, curr) if ma - mi > 1: print("NO") else: print("YES") print(*ans[:2*n]) return 0 main()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1205/A" }
d2031
train
from collections import defaultdict from collections import deque from functools import reduce n, x, y = [int(x) for x in input().split()] E = defaultdict(set) for i in range(n-1): u, v = [int(x) for x in input().split()] E[u].add(v) E[v].add(u) if x > y: for v in E: if len(E[v]) == n-1: print((n-2)*y + x) break elif len(E[v]) > 1: print((n-1)*y) break else: visited = {v : False for v in E} stack = [1] topsorted = deque() while stack: v = stack.pop() if visited[v]: continue visited[v] = True topsorted.appendleft(v) stack.extend(E[v]) chopped = set() ans = 0 for v in topsorted: ans += max(0, len(E[v])-2) if len(E[v]) > 2: S = E[v].intersection(chopped) S1 = {S.pop(), S.pop()} for u in E[v]: if not u in S1: E[u].remove(v) E[v].clear() E[v].update(S1) chopped.add(v) print(ans*y + (n-1-ans)*x)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/618/D" }
d2032
train
def main(): import sys input = sys.stdin.readline N, M = list(map(int, input().split())) L = list(map(int, input().split())) if sum(L) < N: print(-1) return ans = [0] * M left = N for i in range(M-1, -1, -1): if left - L[i] >= i: ans[i] = left - L[i] + 1 left -= L[i] else: if i+L[i]-1 >= N: print(-1) return ans[i] = i+1 left = i print(*ans) def __starting_point(): main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1329/A" }
d2033
train
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def II(): return int(input()) def LS(): return input().split() def S(): return input() def main(): n = II() d = collections.defaultdict(set) for _ in range(n-1): a,b = LI() d[a].add(b) d[b].add(a) memo = [-1] * (n+1) def path(t,s): ps = set() dt = list(d[t]) for k in dt: if memo[k] < 0: continue ps.add(memo[k]) if s == -1 and len(ps) == 2: memo[t] = sum(ps) + 2 return memo[t] if len(ps) > 1: return -t if len(ps) == 0: memo[t] = 0 return 0 memo[t] = list(ps)[0] + 1 return memo[t] def _path(tt,ss): f = [False] * (n+1) q = [(tt,ss)] tq = [] qi = 0 while len(q) > qi: t,s = q[qi] for k in d[t]: if k == s or memo[k] >= 0: continue q.append((k,t)) qi += 1 for t,s in q[::-1]: r = path(t,s) if r < 0: return r return memo[tt] t = _path(1,-1) if t < 0: t = _path(-t,-1) if t > 0: while t%2 == 0: t//=2 return t return -1 print(main())
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/765/E" }
d2034
train
h = int(input()) a = list(map(int, input().split())) w, q = [], [] p = r = 0 for i in a: for j in range(i): w.append(r) q.append(r - (j and p > 1)) p = i r += i if w == q: print('perfect') else: print('ambiguous') print(*w) print(*q)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/901/A" }
d2035
train
import sys input = sys.stdin.readline n = int(input()) x = [] y = [] for i in range(n): xi, yi = map(int, input().split()) x.append(xi) y.append(yi) min_x = min(x) max_x = max(x) min_y = min(y) max_y = max(y) answer = 0 for i in range(n): dx = max(max_x - x[i], x[i] - min_x) dy = max(max_y - y[i], y[i] - min_y) answer = max(answer, dx + dy) print(2*answer, end = ' ') for i in range(4, n + 1): print(2*(max_x - min_x + max_y - min_y), end = ' ')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1074/C" }
d2036
train
MOD = 998244353 BOUND = 19 n, m = list(map(int, input().split())) l = list(map(int,input().split())) basis = [] for p in range(m-1,-1,-1): p2 = pow(2,p) nex = -1 for i in range(n): if l[i] >= p2: nex = l[i] break if nex != -1: basis.append(nex) for i in range(n): if l[i] >= p2: l[i] ^= nex extra = n - len(basis) def add(a, b): out = [0] * (max(len(a), len(b))) for i in range(len(a)): out[i] = a[i] for i in range(len(b)): out[i] += b[i] out[i] %= MOD return out def addSh(a, b): out = [0] * (max(len(a) + 1, len(b))) for i in range(len(a)): out[i + 1] = a[i] for i in range(len(b)): out[i] += b[i] out[i] %= MOD return out i = 0 curr = dict() curr[0] = [1] for p in range(m-1,-1,-1): p2 = pow(2,p) if i < len(basis) and basis[i] >= p2: currN = dict(curr) for v in curr: if v ^ basis[i] not in currN: currN[v ^ basis[i]] = [0] currN[v ^ basis[i]] = add(curr[v], currN[v ^ basis[i]]) curr = currN i += 1 currN = dict(curr) for v in curr: if v >= p2: if v ^ p2 not in currN: currN[v ^ p2] = [0] currN[v ^ p2] = addSh(curr[v], currN[v ^ p2]) del currN[v] curr = currN out = curr[0] while len(out) < m + 1: out.append(0) for i in range(m + 1): out[i] *= pow(2, extra, MOD) out[i] %= MOD print(' '.join(map(str,out)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1336/E1" }
d2037
train
import sys input = sys.stdin.readline n,k=list(map(int,input().split())) if k==0: print(0) return A=sorted(map(int,input().split())) # DP[UL][n][left] # [left*pow(2,n),left*pow(2,n)+pow(2,n))の間のチームで, # ファンのチームが # UL=0: upperでもlowerでも勝ち残っている # UL=1: upperでのみ勝ち残っている # UL=2: lowerでのみ勝ち残っている # ときの、そこまでのファンのチームの試合数の最大値. DP=[[[0]*((1<<n)+2) for i in range(n+1)] for UL in range(3)] for i in range(k): if A[i]%2==1: DP[1][1][A[i]]=1 DP[2][1][A[i]]=1 else: DP[1][1][A[i]-1]=1 DP[2][1][A[i]-1]=1 if i<k-1 and A[i]%2==1 and A[i+1]==A[i]+1: DP[0][1][A[i]]=1 for i in range(2,n+1): for left in range(1,(1<<n)+1,1<<i): if DP[0][i-1][left]: DP[0][i][left]=max(DP[0][i-1][left] + DP[0][i-1][left+(1<<(i-1))] + 3,DP[0][i-1][left] + DP[1][i-1][left+(1<<(i-1))] + 3,\ DP[0][i-1][left] + DP[2][i-1][left+(1<<(i-1))] + 3) if DP[0][i-1][left+(1<<(i-1))]: DP[0][i][left]=max(DP[0][i][left], DP[0][i-1][left] + DP[0][i-1][left+(1<<(i-1))] + 3,\ DP[1][i-1][left] + DP[0][i-1][left+(1<<(i-1))] + 3,DP[2][i-1][left] + DP[0][i-1][left+(1<<(i-1))] + 3) if DP[1][i-1][left]: DP[1][i][left]=max(DP[1][i][left], DP[1][i-1][left] + 1) DP[2][i][left]=max(DP[2][i][left], DP[1][i-1][left] + 2) if DP[2][i-1][left]: DP[2][i][left]=max(DP[2][i][left], DP[2][i-1][left] + 2) if DP[1][i-1][left+(1<<(i-1))]: DP[1][i][left]=max(DP[1][i][left], DP[1][i-1][left+(1<<(i-1))] + 1) DP[2][i][left]=max(DP[2][i][left], DP[1][i-1][left+(1<<(i-1))] + 2) if DP[2][i-1][left+(1<<(i-1))]: DP[2][i][left]=max(DP[2][i][left], DP[2][i-1][left+(1<<(i-1))] + 2) if DP[1][i-1][left] and DP[1][i-1][left+(1<<(i-1))]: DP[0][i][left]=max(DP[0][i][left], DP[1][i-1][left] + DP[1][i-1][left+(1<<(i-1))] + 2) if DP[1][i-1][left] and DP[2][i-1][left+(1<<(i-1))]: DP[0][i][left]=max(DP[0][i][left], DP[1][i-1][left] + DP[2][i-1][left+(1<<(i-1))] + 3) if DP[2][i-1][left] and DP[1][i-1][left+(1<<(i-1))]: DP[0][i][left]=max(DP[0][i][left], DP[2][i-1][left] + DP[1][i-1][left+(1<<(i-1))] + 3) if DP[2][i-1][left] and DP[2][i-1][left+(1<<(i-1))]: DP[2][i][left]=max(DP[2][i][left], DP[2][i-1][left] + DP[2][i-1][left+(1<<(i-1))] + 2) """ for i in range(n+1): print(DP[0][i]) print() for i in range(n+1): print(DP[1][i]) print() for i in range(n+1): print(DP[2][i]) print() for i in range(n+1): print(DP[0][0][i]) """ print(max(DP[0][n][1],DP[1][n][1],DP[2][n][1])+1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1314/B" }
d2038
train
# python3 import sys from collections import namedtuple def readline(): return list(map(int, input().split())) def readlines(): for line in sys.stdin.readlines(): yield list(map(int, line.split())) class State(namedtuple('State', 'payload time floor')): def hook(self, pivot, a, b): lo, up = min(pivot, a, self.floor), max(pivot, a, self.floor) return tuple(x for x in self.payload if x < lo or up < x) + (b,), \ self.time + abs(self.floor - pivot) + abs(pivot - a) def choices_to_take_next(self, a, b): floor = self.floor payload, time = self.hook(floor, a, b) if len(payload) < 5: yield payload, time if floor > a: pivots = (x for x in self.payload if x > floor) elif floor == a: pivots = () else: pivots = (x for x in self.payload if x < floor) else: pivots = self.payload for pivot in pivots: yield self.hook(pivot, a, b) def time_to_get_free(payload, floor): if payload: lo, up = min(payload), max(payload) return abs(lo-up) + min(abs(floor-lo), abs(floor-up)) else: return 0 def main(): n, = readline() floor = 1 positions = {(): 0} # empty elevator, time = 0 for (a, b) in readlines(): max_acceptable_time = min(positions.values()) + 16 - abs(floor - a) new_positions = dict() for payload, time in list(positions.items()): state = State(payload, time, floor) for npayload, ntime in state.choices_to_take_next(a, b): if ntime <= max_acceptable_time: npayload = tuple(sorted(npayload)) if new_positions.setdefault(npayload, ntime) > ntime: new_positions[npayload] = ntime positions = new_positions floor = a return min(t + time_to_get_free(p, floor) for p, t in list(positions.items())) \ + 2 * n print(main())
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/983/C" }
d2039
train
import sys n, m = [int(x) for x in input().split()] adj_for = [[] for _ in range(n)] adj_back = [[] for _ in range(n)] for _ in range(m): a, b = [int(x) for x in sys.stdin.readline().split()] a -= 1 b -= 1 adj_for[a].append(b) adj_back[b].append(a) lens = [len(adj_back[i]) for i in range(n)] stack = [x for x in range(n) if lens[x] == 0] toposort = [x for x in range(n) if lens[x] == 0] while len(stack): cur = stack.pop() for nb in adj_for[cur]: lens[nb] -= 1 if lens[nb] == 0: toposort.append(nb) stack.append(nb) if len(toposort) != n: print(-1) return min_above = list(range(n)) min_below = list(range(n)) for i in toposort: for j in adj_back[i]: if min_above[j] < min_above[i]: min_above[i] = min_above[j] for i in reversed(toposort): for j in adj_for[i]: if min_below[j] < min_below[i]: min_below[i] = min_below[j] qt = ["A" if min_below[i] == min_above[i] == i else "E" for i in range(n)] # qt = [None for x in range(n)] # # for i in range(n): # if qt[i] is not None: # continue # qt[i] = 'A' # stack_for = [i] # while len(stack_for): # cur = stack_for.pop() # for nb in adj_for[cur]: # if qt[nb] is None: # qt[nb] = 'E' # stack_for.append(nb) # # # stack_back = [i] # while len(stack_back): # cur = stack_back.pop() # for nb in adj_back[cur]: # if qt[nb] is None: # qt[nb] = 'E' # stack_back.append(nb) # print(len([x for x in qt if x == 'A'])) print("".join(qt))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1344/C" }
d2040
train
import sys input = sys.stdin.readline n,m=list(map(int,input().split())) A=list(map(int,input().split())) MIN=0 MAX=m while MIN!=MAX: x=(MIN+MAX)//2 #print(x,MIN,MAX) #print() M=0 for a in A: #print(a,M) if a<=M and a+x>=M: continue elif a>M and a+x>=m and (a+x)%m>=M: continue elif a>M: M=a else: MIN=x+1 break else: MAX=x print(MIN)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1168/A" }
d2041
train
n, h = map(int,input().split()) unit = h*h/n for i in range(1,n): print((unit*i)**0.5, end=' ')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/794/B" }
d2042
train
def main(): n, l = int(input()), list(map(int, input().split())) if not (n & 1): l.append(0) l.append(150001) i, b, c, fails0, fails1 = 0, 0, 150001, [], [] try: while True: a, b, c = b, c, l[i] if a >= b or b <= c: if len(fails0) + len(fails1) > 5: print(0) return fails1.append(i - 1) i += 1 a, b, c = b, c, l[i] if a <= b or b >= c: if len(fails0) + len(fails1) > 5: print(0) return fails0.append(i - 1) i += 1 except IndexError: fails, res = fails0 + fails1, 0 for i in fails: a = l[i] for j in range(n): f = fails1 if j & 1 else fails0 f.append(j) l[i], l[j] = l[j], a if (all(l[b - 1] > l[b] < l[b + 1] for b in fails0) and all(l[b - 1] < l[b] > l[b + 1] for b in fails1)): res += 1 if j in fails else 2 l[j] = l[i] del f[-1] l[i] = a print(res // 2) def __starting_point(): main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/653/C" }
d2043
train
def main(): n, a, b, t = list(map(int, input().split())) a1 = a + 1 b += a1 l, res = [b if c == "w" else a1 for c in input()], [] l[0] = x = l[0] - a if t <= x: print(int(t == x)) return f = res.append for dr in 0, 1: if dr: l[1:] = l[-1:-n:-1] tot = t for hi, x in enumerate(l): tot -= x if tot < 0: break else: print(n) return f(hi) tot += x hi -= 1 tot -= hi * a lo = n while True: while lo > 0 <= tot: lo -= 1 tot -= l[lo] f(n + hi - lo) if not (lo and hi): break while tot <= 0 < hi: tot += l[hi] + a hi -= 1 print(max(res)) def __starting_point(): main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/650/B" }
d2044
train
n = int(input()) arr = [] for i in range(n): l,r = map(int, input().split()) arr.append([l,r]) lts = [] for i in range(n): if arr[i][0] == 0: l = i j = i while arr[j][1] != 0: j = arr[j][1] - 1 r = j lts.append([l,r]) for i in range(1, len(lts)): arr[lts[i-1][1]][1] = lts[i][0] + 1 arr[lts[i][0]][0] = lts[i-1][1] + 1 for i in range(n): print(arr[i][0], arr[i][1])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/847/A" }
d2045
train
from sys import stdin, stdout n,k = list(map(int,stdin.readline().rstrip().split())) print(2+(n-2)//k+(n-3)//k) connectionsList = [] # Leaf node is 1. Make this node have connections to k children for i in range(k): connectionsList.append((str(1),str(i+2))) for i in range(k+2,n+1): connectionsList.append((str(i-k),str(i))) for conn in connectionsList: print(' '.join(conn))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/827/B" }
d2046
train
n, m = map(int, input().split()) p, d = [0] * (n + 2), [0] * (n + 2) for i in range(m): l, r, x = map(int, input().split()) while l < x: if d[l]: k = d[l] d[l] = x - l l += k else: d[l], p[l] = x - l, x l += 1 l += 1 r += 1 while d[r]: r += d[r] while l < r: if d[l]: k = d[l] d[l] = r - l l += k else: d[l], p[l] = r - l, x l += 1 print(' '.join(map(str, p[1: -1])))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/356/A" }
d2047
train
n = int(input()) t = [0, 0] + list(map(int, input().split())) a, b = [0] * (n + 1), [0] * (n + 1) a[1] = b[1] = -1 def f(s, a, b, l): nonlocal t l.reverse() j, n = 0, len(l) while True: s += t[l[j]] a[l[j]] = s j += 1 if j == n: return s += t[l[j]] b[l[j]] = s j += 1 if j == n: return def g(i, k): nonlocal a, b l = [] if k: a[i] = -1 l.append(i) i += t[i] while True: if i > n: return f(0, a, b, l) if b[i] > 0: return f(b[i], a, b, l) if b[i] == -1: return b[i] = -1 l.append(i) i -= t[i] if i < 1: return f(0, b, a, l) if a[i] > 0: return f(a[i], b, a, l) if a[i] == -1: return a[i] = -1 l.append(i) i += t[i] for i in range(2, n + 1): if a[i] == 0: g(i, True) if b[i] == 0: g(i, False) for i in range(1, n): if b[i + 1] > 0: t[i] = i + b[i + 1] else: t[i] = -1 print('\n'.join(map(str, t[1: n])))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/283/B" }
d2048
train
def main(): n, k = map(int, input().split()) a, b, c, d = (list(map(int, input().split())) for _ in 'abcd') ss, tt, n2, res = [*b, *c[::-1]], [*a, *d[::-1]], n * 2, [] yx = [*[(2, i + 1) for i in range(n)], *[(3, i) for i in range(n, 0, -1)]] def park(): for i, s, t, (y, x) in zip(range(n2), ss, tt, yx): if s == t != 0: ss[i] = 0 res.append(f'{s} {(1, 4)[y == 3]} {x}') def rotate(): start = ss.index(0) for i in range(start - n2, start - 1): s = ss[i] = ss[i + 1] if s: y, x = yx[i] res.append(f'{s} {y} {x}') ss[start - 1] = 0 park() if all(ss): print(-1) return while any(ss): rotate() park() print(len(res), '\n'.join(res), sep='\n') def __starting_point(): main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/995/A" }
d2049
train
import sys n, k = map(int, sys.stdin.readline().split()) nums = list(map(int, sys.stdin.readline().split())) total = sum(nums) avg = int(total / n) def check1(nums, target, K): for x in nums: if K < 0: return False if x < target: K -= target - x return K >= 0 def check2(nums, target, K): for x in nums: if K < 0: return False if x > target: K -= x - target return K >= 0 l1, r1 = min(nums), avg + 1 while l1 + 1 < r1: mid = (l1 + r1) >> 1 if check1(nums, mid, k): l1 = mid else: r1 = mid if check2(nums, avg + (0 if total % n == 0 else 1), k): r2 = avg + (0 if total % n == 0 else 1) else: l2, r2 = avg + (0 if total % n == 0 else 1), max(nums) while l2 + 1 < r2: mid = (l2 + r2) >> 1 if check2(nums, mid, k): r2 = mid else: l2 = mid print(r2 - l1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/671/B" }
d2050
train
import sys def calc(b0, b1, q): if q == 0: return b0 ^ b1 if q == 1: return b0 | b1 if q == 2: return b0 & b1 n, m = list(map(int,sys.stdin.readline().split())) arr1 = {} opt = ['XOR', 'OR', 'AND'] arr2 = [] for j in range(n): a, b = list(map(str,sys.stdin.readline().split(" := "))) b = b.split() if len(b) == 1: s = b[0] arr1[a] = s else: c = b[0] d = b[2] q = opt.index(b[1]) arr2.append((a, c, d, q)) mins = '' maxs = '' d0 = {'?':0} d1 = {'?':1} for i in range(m): for a, b in list(arr1.items()): d0[a] = int(b[i]) d1[a] = int(b[i]) s0 = 0 s1 = 0 for a, c, d, q in arr2: b00 = d0[c] b01 = d0[d] b10 = d1[c] b11 = d1[d] c0 = calc(b00, b01, q) c1 = calc(b10, b11, q) s0 += (1 if c0 else 0) s1 += (1 if c1 else 0) d0[a] = c0 d1[a] = c1 if s1 < s0: mins += "1" else: mins += "0" if s1 > s0: maxs += "1" else: maxs += "0" sys.stdout.write("{0}\n{1}".format(mins,maxs))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/778/B" }
d2051
train
""" Codeforces Contest 260 Div 1 Problem B Author : chaotic_iak Language: Python 3.3.4 """ def main(): n,k = read() s = set() for i in range(n): s.add(read(0)) s = list(s) s.sort() s = treeify(s) res = solve(s) if res == 0: # neither: second player win print("Second") if res == 1: # odd: first player win if k is odd print("First" if k % 2 else "Second") if res == 2: # even: second player win print("Second") if res == 3: # both: first player win print("First") def treeify(s): res = [[] for _ in range(26)] for i in s: if i: res[ord(i[0]) - 97].append(i[1:]) fin = [] for i in range(26): if res[i]: fin.append(treeify(res[i])) return fin def solve(s, parity=2): for i in range(len(s)): if isinstance(s[i], list): s[i] = solve(s[i], 3-parity) if not s: return parity # no possible move: current parity if 0 in s: return 3 # any neither: both if 1 in s and 2 in s: return 3 # any odd and any even: both if 1 in s: return 1 # any odd: odd if 2 in s: return 2 # any even: even return 0 # all both: neither ################################### NON-SOLUTION STUFF BELOW def read(mode=2): # 0: String # 1: List of strings # 2: List of integers inputs = input().strip() if mode == 0: return inputs if mode == 1: return inputs.split() if mode == 2: return map(int, inputs.split()) def write(s="\n"): if isinstance(s, list): s = " ".join(map(str, s)) s = str(s) print(s, end="") main()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/455/B" }
d2052
train
from heapq import heappush,heappop,heapify n,k=map(int,input().split()) *l,=map(int,input().split()) q=[(-l[i],i)for i in range(k)];heapify(q) a=[0]*n s=0 for i in range(k,n): heappush(q,(-l[i],i)) x,j=heappop(q) s-=x*(i-j) a[j]=i+1 for i in range(n,n+k): x,j=heappop(q) s-=x*(i-j) a[j]=i+1 print(s) print(' '.join(map(str,a)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/853/A" }
d2053
train
n, m = list(map(int, input().split())) used = [1] * 2 * n for i in range(m): x, y = list(map(int, input().split())) used[x - 1] = used[n + y - 1] = 0 if n % 2 and used[n // 2]: used[n // 2 + n] = 0 res = sum(used) for i in [0, n - 1, n, 2 * n - 1]: res -= used[i] print(res)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/333/B" }
d2054
train
n,m=map(int,input().split()) b=list(map(int,input().split())) g=list(map(int,input().split())) if max(b)>min(g): print(-1) else: maxi=0 maxi2=0 for guy in b: if guy>maxi: maxi2,maxi=maxi,guy elif guy>maxi2: maxi2=guy sumi=m*sum(b)+sum(g)-m*maxi+maxi-maxi2 if maxi in g: sumi-=(maxi-maxi2) print(sumi)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1158/A" }
d2055
train
def main(): n = int(input()) edges = [] for _ in range(n - 1): u, v = list(map(int, input().split())) u -= 1 v -= 1 edges.append((u, v)) colors = list(map(int, input().split())) suspect = [(u, v) for (u, v) in edges if colors[u] != colors[v]] if len(suspect) == 0: print("YES") print(1) else: cands = set(suspect[0]) for u, v in suspect: cands &= set([u, v]) if len(cands) == 0: print("NO") else: print("YES") e = list(cands)[0] print(e + 1) main()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/763/A" }
d2056
train
MOD = 10**9+7 s = input() n = int(input()) qs = [['',s]]+[input().split('->') for i in range(n)] ds = {} for i in range(10): ds[str(i)] = (10,i) for i in range(n,-1,-1): out = 0 mul = 1 for d in qs[i][1]: out = (out * ds[d][0] + ds[d][1]) % MOD mul = (mul * ds[d][0]) % MOD ds[qs[i][0]] = (mul,out) print(ds[''][1])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/464/C" }
d2057
train
# import collections, atexit, math, sys, bisect sys.setrecursionlimit(1000000) def getIntList(): return list(map(int, input().split())) try : #raise ModuleNotFoundError import numpy def dprint(*args, **kwargs): print(*args, **kwargs, file=sys.stderr) dprint('debug mode') except ModuleNotFoundError: def dprint(*args, **kwargs): pass inId = 0 outId = 0 if inId>0: dprint('use input', inId) sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件 if outId>0: dprint('use output', outId) sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件 atexit.register(lambda :sys.stdout.close()) #idle 中不会执行 atexit N, = getIntList() s1 = input() +'0' s2 = input() +'0' res = 0 i = 0 while i<N: if s1[i] != s2[i]: if s1[i+1] == s2[i] and s2[i+1] == s1[i]: res+=1 i+=2 continue res+=1 i+=1 print(res)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1037/C" }
d2058
train
import sys #sys.stdin=open("data.txt") input=sys.stdin.readline # so the ending sequence is b...ba...a # find length of ending sequence extra=0 need=0 for ch in input().strip(): if ch=='a': need=(need*2+1)%1000000007 else: extra=(extra+need)%1000000007 print(extra)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/804/B" }
d2059
train
import heapq n = int(input()) d = list(map(int,input().split())) pq = [-d[0]] heapq.heapify(pq) ans = 0 for i in range(1,n): temp = i - d[i] heapq.heappush(pq,temp) if heapq.nsmallest(1,pq)[0] < temp: ans += temp - heapq.nsmallest(1,pq)[0] heapq.heappushpop(pq,temp) print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/713/C" }
d2060
train
n = int(input()) inp = input() seq = inp.split(' ') seq = [ abs(int(x)) for x in seq ] Max = max(seq) nxt = [0] * n cnt = [0] * n pos = [n] * (Max+1) for i in range(n-1, -1, -1): nxt[i] = pos[seq[i]] pos[seq[i]] = i for i in range(0, Max+1): j = pos[i] while(j<n): front = sum(cnt[0:j]) back = sum(cnt[j+1:n]) if(front < back): seq[j] = 0 - seq[j] j = nxt[j] j = pos[i] while(j < n): cnt[j] = 1 j = nxt[j] #for i in range(0, n-1): # print(seq[i], sep=' ') #print(seq[n-1]) inv = 0 for i in range(len(seq)): for j in range(i+1, len(seq)): if(seq[i] > seq[j]): inv += 1 print(inv)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/351/E" }
d2061
train
def f(m): nonlocal dp, sdp l = 0 for i in range(n): while l < n and v[l] < v[i] - m: l += 1 if l - 1 > i - k: dp[i] = False else: dp[i] = (sdp[i - k + 1] != sdp[l - 1]) sdp[i + 1] = sdp[i] + (1 if dp[i] else 0) return dp[n - 1] n, k = list(map(int, input().split())) dp = [False for i in range(n + 2)] sdp = [0 for i in range(n + 2)] dp[-1] = True sdp[0] = 1 v = list(map(int, input().split())) v.sort() le = -1 r = v[-1] - v[0] while r - le > 1: m = (r + le) // 2 if f(m): r = m else: le = m print(r)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/883/I" }
d2062
train
import sys input = sys.stdin.readline def solve(ax,ay,bx,by,cx,cy): x = ax+bx+cx y = ay+by+cy x -= x//3+1 y -= y//3+1 if x==y: return x if 0 <= x <= 1 else abs(x)+1 else: return max(abs(x), abs(y)) T = int(input()) for _ in range(T): ax,ay,bx,by,cx,cy = map(int,input().split()) print(solve(ax,ay,bx,by,cx,cy))
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc109/tasks/arc109_d" }
d2063
train
def main(): mod = 10**9+7 inv_n = [0]*1001 nCr = [[1]*(i+1) for i in range(1001)] for i in range(1001): inv_n[i] = pow(i, mod-2, mod) for i in range(2, 1001): for j in range(1, i): nCr[i][j] = (nCr[i-1][j-1]+nCr[i-1][j]) % mod n, a, b, c, d = list(map(int, input().split())) dp = [0]*(n+1) dp[0] = 1 for A in range(b, a-1, -1): dp2 = [i for i in dp] for N in range(n-c*A, -1, -1): e = dp[N] if e: temp = 1 for C in range(1, c): temp = temp*nCr[n-N-(C-1)*A][A]*inv_n[C] % mod for C in range(c, min(d, (n-N)//A)+1): temp = temp*nCr[n-N-(C-1)*A][A]*inv_n[C] % mod dp2[N+C*A] = (dp2[N+C*A]+temp*e) % mod dp = dp2 print((dp[-1])) main()
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc067/tasks/arc067_c" }
d2064
train
rd = lambda: list(map(int, input().split())) def root(x): if f[x]!=x: f[x] = root(f[x]) return f[x] n, m = rd() N = list(range(n)) f = list(N) lang = [0]*n for i in N: lang[i] = set(rd()[1:]) for i in N: for j in N[:i]: rj = root(j) if lang[rj].intersection(lang[i]): f[rj] = i lang[i] = lang[i].union(lang[rj]) print(sum(1 for i in N if i==root(i)) - (sum(map(len, lang))>0))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/277/A" }
d2065
train
import sys readline = sys.stdin.readline N, Q = list(map(int, readline().split())) state = [[False]*(N+2) for _ in range(2)] cnt = 0 Ans = [None]*Q for qu in range(Q): r, c = list(map(int, readline().split())) r -= 1 c -= 1 state[r][c] = not state[r][c] res = state[r-1][c-1] + state[r-1][c] + state[r-1][c+1] if state[r][c]: cnt += res else: cnt -= res Ans[qu] = 'No' if cnt else 'Yes' print('\n'.join(Ans))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1292/A" }
d2066
train
n, k = [int(c) for c in input().split()] a = [] for i in range(k): ak = [int(c) for c in input().split()] a.append(ak[1:]) total = k - 1 for ak in a: if ak[0] == 1: j = 1 while j <= len(ak) - 1: if ak[j] != ak[j-1] + 1: break j += 1 total += 2*(len(ak) - j) else: total += 2*(len(ak) - 1) print(total)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/555/A" }
d2067
train
import os import random import sys from typing import List, Dict class Int: def __init__(self, val): self.val = val def get(self): return self.val + 111 class Unique: def __init__(self): self.s = set() def add(self, val : int): self.s.add(val) def __contains__(self, item : int) -> bool: return self.s.__contains__(item) def ceil(top : int, bottom : int) -> int: return (top + bottom - 1) // bottom def concat(l : List[int]): return "".join(map(str, l)) def get(d : Dict[int, str], val : int) -> Dict[int, str]: return d[val] #guy who wants small moves first #then guy who wants large moves #so lets say we have 4 positions # 1, 2, 3, 4 #small wants to ban edges, because if he bans 2 or 3 he is fucked #so he bans 1 # and we have 2, 3, 4 # then large bans middle so we have 2, 4 and the ans is 2 # 0, 1, 2, 3, 4, 5, 6, 7 # 0, 1, 2, 3, 4, 5, 6 # 0, 1, 2, 3, 5, 6 # 0, 1, 2, 3, 5 # 0, 1, 3, 5 # 0, 1, 3 # 0, 3 # 0, 1, 2, 3, 4, 5, 6, 7 # 0, 4 # # 0, 3 #1 5 9 19 21 22 # 5 9 19 21 22 # 5 19 21 22 # 19 21 22 # 0, 1, 3, 7, 15 # 0, 1, 7, 15 # 0, 1, 7 # 0, 7 def slowsolve(a): a.sort() small = True while len(a) > 2: if small: if a[1] - a[0] > a[-1] - a[-2]: a.pop(0) else: a.pop() small = False else: a.pop(len(a) // 2) small = True return a[1] - a[0] def solve(a): a.sort() candelete = len(a) // 2 - 1 res = 10 ** 18 for leftdelete in range(0, candelete + 1): leftrem = leftdelete rightrem = leftdelete + candelete + 1 res = min(res, a[rightrem] - a[leftrem]) return res def prt(l): return print(' '.join(l)) def rv(): return map(int, input().split()) def rl(n): return [list(map(int, input().split())) for _ in range(n)] if os.path.exists("test.txt"): sys.stdin = open("test.txt") n, = rv() a, = rl(1) # a = sorted([random.randrange(10**2) for _ in range(6)]) # print(a) # print(solve(a), slowsolve(a)) print(solve(a))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/594/A" }
d2068
train
n = int(input()) t = [list(map(int, input().split())) for q in range(n)] t[0][0] = 0 n += 1 u = [-1e7] * n v = [0] * n for i, (j, a) in list(enumerate(t, 1))[::-1]: u[i] = max(u[i], v[i] + a) v[j], u[j] = max(v[j] + v[i], u[j] + u[i]), max(v[j] + u[i], u[j] + v[i]) print(u[1])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/533/B" }
d2069
train
import sys readline = sys.stdin.readline from collections import Counter def getpar(Edge, p): N = len(Edge) par = [0]*N par[0] = -1 par[p] -1 stack = [p] visited = set([p]) while stack: vn = stack.pop() for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn stack.append(vf) return par def topological_sort_tree(E, r): Q = [r] L = [] visited = set([r]) while Q: vn = Q.pop() L.append(vn) for vf in E[vn]: if vf not in visited: visited.add(vf) Q.append(vf) return L def getcld(p): res = [[] for _ in range(len(p))] for i, v in enumerate(p[1:], 1): res[v].append(i) return res N = int(readline()) We = list(map(int, readline().split())) Edge = [[] for _ in range(N)] Cost = Counter() geta = N+1 for _ in range(N-1): a, b, c = list(map(int, readline().split())) a -= 1 b -= 1 Edge[a].append(b) Edge[b].append(a) Cost[b*geta+a] = c Cost[a*geta+b] = c P = getpar(Edge, 0) L = topological_sort_tree(Edge, 0) C = getcld(P) dp = [0]*N candi = [[0, 0] for _ in range(N)] ans = 0 for l in L[::-1][:-1]: dp[l] += We[l] p = P[l] k = dp[l] - Cost[l*geta + p] if k > 0: dp[p] = max(dp[p], k) candi[p].append(k) res = max(candi[l]) candi[l].remove(res) ans = max(ans, We[l] + res + max(candi[l])) res = max(candi[0]) candi[0].remove(res) ans = max(ans, We[0] + res + max(candi[0])) print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1083/A" }
d2070
train
n=int(input()) L=list(map(int,input().split())) if n==1: print(1,1) print(0) print(1,1) print(0) print(1,1) print(-L[0]) else: print(1,n-1) for i in range(n-1):print(L[i]*(n-1),end=' ') print() print(n,n) print(-L[n-1]) print(1,n) for i in range(n-1):print(-L[i]*n,end=' ') print(0)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1396/A" }
d2071
train
#!/usr/bin/env pypy3 import math def make_nCr_mod(max_n=2*10**5 + 100, mod=10**9 + 7): fact, inv_fact = [0] * (max_n + 1), [0] * (max_n + 1) fact[0] = 1 for i in range(max_n): fact[i + 1] = fact[i] * (i + 1) % mod inv_fact[-1] = pow(fact[-1], mod - 2, mod) for i in reversed(range(max_n)): inv_fact[i] = inv_fact[i + 1] * (i + 1) % mod def nCr_mod(n, r): res = 1 while n or r: a, b = n % mod, r % mod if a < b: return 0 res = res * fact[a] % mod * inv_fact[b] % mod * inv_fact[a - b] % mod n //= mod r //= mod return res return nCr_mod nCr_mod = make_nCr_mod() MODULUS = 10**9+7 input() A = input().split(' ') A = list(map(int, A)) if len(A) == 1: print(A[0]) return if len(A) % 2 == 1: new_A = [] next_plus = True for i in range(len(A) - 1): if next_plus: new_A += [A[i] + A[i+1]] else: new_A += [A[i] - A[i+1]] next_plus = not next_plus A = new_A if len(A) % 4 == 2: new_A = [] for i in range(len(A) // 2): new_A += [A[2*i] + A[2*i+1]] A = new_A else: new_A = [] for i in range(len(A) // 2): new_A += [A[2*i] - A[2*i+1]] A = new_A # binomial sum N = len(A)-1 ret = 0 for i in range(N+1): ret += A[i]*nCr_mod(N, i) ret = ret % MODULUS print(ret)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/815/B" }
d2072
train
from collections import Counter n = int(input()) points = Counter([tuple(map(int, input().split(' '))) for i in range(n)]) x, y = Counter([k for k, v in points.elements()]), Counter([v for k, v in points.elements()]) ans = sum([v*(v-1)//2 for k, v in list(x.items())])+sum([v*(v-1)//2 for k, v in list(y.items())])-sum([v*(v-1)//2 for k, v in list(points.items())]) print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/650/A" }
d2073
train
from sys import* # def check(u, d, l, r): used = [pointsx[i][1] for i in range(l)] used += [pointsx[-1 - i][1] for i in range(r)] used += [pointsy[i][1] for i in range(u)] used += [pointsy[-1 - i][1] for i in range(d)] if len(set(used)) > k: return DOHERA dx = pointsx[-1 - r][0] - pointsx[l][0] dy = pointsy[-1 - d][0] - pointsy[u][0] dx += dx & 1 dy += dy & 1 dx = max(2, dx) dy = max(2, dy) return dx * dy # (n, k) = list(map(int, input().split())) pointsx = [] pointsy = [] DOHERA = 10 ** 228 for i in range(n): a = list(map(int, input().split())) pointsx += [(a[0] + a[2], i)] pointsy += [(a[1] + a[3], i)] (pointsx, pointsy) = (sorted(pointsx), sorted(pointsy)) ans = DOHERA for u in range(0, k + 1): for d in range(0, k + 1): for l in range(0, k + 1): for r in range(0, k + 1): if l + r <= k and u + d <= k: ans = min(ans, check(u, d, l, r)) print(ans // 4) # Made By Mostafa_Khaled
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/594/C" }
d2074
train
def maximum_xor_secondary(sequence): stack, answer = [], 0 for x in sequence: while stack: answer = max(answer, stack[-1] ^ x) if stack[-1] > x: break else: stack.pop() stack.append(x) return answer size, num = input(), [int(x) for x in input().split()] print(maximum_xor_secondary(num)) # Made By Mostafa_Khaled
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/280/B" }
d2075
train
INF = 10 ** 18 + 179 [n, k], a = [list(map(int, input().split())) for x in range(2)] a.sort() dp, l = [[0] * (k - n % k + 1) for x in range(n % k + 1)], n // k for i in range(n % k + 1): for j in range(k - n % k + 1): pos = i * (l + 1) + j * l dp[i][j] = min((dp[i - 1][j] + a[pos - 1] - a[pos - l - 1] if i else INF), \ (dp[i][j - 1] + a[pos - 1] - a[pos - l] if j else INF)) if (i or j) else 0 print(dp[n % k][k - n % k])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/571/B" }
d2076
train
rd = lambda: list(map(int, input().split())) rd() a = sorted(rd(), reverse=True) b = sorted(rd(), reverse=True) if len(a) > len(b): print("YES"); return for i in range(len(a)): if a[i] > b[i]: print("YES"); return print("NO")
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/297/B" }
d2077
train
n = int(input()) p = [tuple(map(int, input().split())) for i in range(n)] def d(a, b): return (a[0]-b[0], a[1]-b[1], a[2]-b[2], a[3]-b[3], a[4]-b[4]) def m(a, b): t = 0 for i in range(5): t += a[i] * b[i] return t good_points = [] for i in range(n): good = True for j in range(n): if j == i: continue ab = d(p[j], p[i]) for k in range(j + 1, n): if k == i: continue ac = d(p[k], p[i]) if m(ab, ac) > 0: good = False break if not good: break if good: good_points.append(i) print(len(good_points)) for i in good_points: print(i + 1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/850/A" }
d2078
train
from collections import defaultdict def solve(n, a, b, xs): group = [None] * n id_ = {x: i for i, x in enumerate(xs)} if a == b: for x in xs: if a - x not in id_: return False group = [0] * n else: for i, x in enumerate(xs): if group[i] is not None: continue y = a - x z = b - x f1 = y in id_ and group[id_[y]] is None f2 = z in id_ and group[id_[z]] is None if f1 + f2 == 0: return False elif f1 + f2 == 1: g = int(f2) # End of link link = [] t = a if f1 else b while x in id_: link.append(x) x = t - x if x + x == t: break t = a + b - t # print(link) if len(link) % 2 == 0: for i, x in enumerate(link): group[id_[x]] = g elif link[0] * 2 == (b, a)[g]: for i, x in enumerate(link): group[id_[x]] = 1 - g elif link[-1] * 2 == (a, b)[g]: for i, x in enumerate(link): group[id_[x]] = g else: # Found invalid link, answer is "NO" return False return group n, a, b = list(map(int, input().split())) xs = list(map(int, input().split())) group = solve(n, a, b, xs) if isinstance(group, list): print('YES') print(' '.join(map(str, group))) else: print('NO')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/468/B" }
d2079
train
def main(): n = int(input()) a = list(map(int, (x for x in input()))) b = list(map(int, (x for x in input()))) x = [0] * (n - 1) x[0] = b[0] - a[0] for i in range(1, n - 1): x[i] = b[i] - a[i] - x[i - 1] if a[n - 1] + x[n - 2] != b[n - 1]: print(-1) return cnt = sum(map(abs, x)) # prevbug: ftl print(cnt) cnt = min(cnt, 10 ** 5) index = 0 def handle_zero_nine(cur_zero): nonlocal cnt nxt = index + 1 # cur_zero = True prevbug: preserved this line while True: if cur_zero and a[nxt + 1] != 9: break if not cur_zero and a[nxt + 1] != 0: break nxt += 1 cur_zero = not cur_zero while nxt > index: if cnt == 0: break if cur_zero: print(nxt + 1, 1) a[nxt] += 1 a[nxt + 1] += 1 else: print(nxt + 1, -1) a[nxt] -= 1 a[nxt + 1] -= 1 nxt -= 1 cnt -= 1 # print(a) cur_zero = not cur_zero while cnt > 0: if a[index] == b[index]: index += 1 continue elif a[index] > b[index] and a[index + 1] == 0: handle_zero_nine(True) elif a[index] < b[index] and a[index + 1] == 9: handle_zero_nine(False) elif a[index] > b[index]: print(index + 1, -1) a[index] -= 1 a[index + 1] -= 1 cnt -= 1 # print(a) elif a[index] < b[index]: print(index + 1, 1) a[index] += 1 a[index + 1] += 1 cnt -= 1 # print(a) def __starting_point(): main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1120/B" }
d2080
train
q = int(input()) def full_way(u): res = set() while u >= 1: res.add(u) u //= 2 return res def get_way(u, v): res1 = full_way(u) res2 = full_way(v) m = max(res1 & res2) res = set() for x in res1 | res2: if x > m: res.add(x) return res d = {} for i in range(q): a = input().split() if a[0] == '1': v, u, w = map(int, a[1:]) for x in get_way(u, v): if x not in d: d[x] = 0 d[x] += w else: v, u = map(int, a[1:]) res = 0 for x in get_way(u, v): if x in d: res += d[x] print(res)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/696/A" }
d2081
train
import sys n_discounts = int(sys.stdin.readline()) discount_values = [int(x) for x in sys.stdin.readline().split()] n_items = int(sys.stdin.readline()) item_values = [int(x) for x in sys.stdin.readline().split()] min_discount_req = 10000000 for discount_value in discount_values: min_discount_req = min(min_discount_req, discount_value) item_values.sort(reverse=True) index = 0 overall_price = 0 while index < n_items: n_left = min(min_discount_req, n_items - index) for i in range(n_left): overall_price += item_values[index+i] index += n_left + 2 print(overall_price)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/261/A" }
d2082
train
from math import pi from cmath import exp def fft(a, lgN, rot=1): # rot=-1 for ifft N = 1<<lgN assert len(a)==N rev = [0]*N for i in range(N): rev[i] = (rev[i>>1]>>1)+(i&1)*(N>>1) A = [a[rev[i]] for i in range(N)] h = 1 while h<N: w_m = exp((0+1j) * rot * (pi / h)) for k in range(0, N, h<<1): w = 1 for j in range(h): t = w * A[k+j+h] A[k+j+h] = A[k+j]-t A[k+j] = A[k+j]+t w *= w_m h = h<<1 return A if rot==1 else [x/N for x in A] import sys ints = (int(x) for x in sys.stdin.read().split()) n, x = (next(ints) for i in range(2)) r = [next(ints) for i in range(n)] ac = [0]*(n+1) for i in range(n): ac[i+1] = (r[i]<x) + ac[i] # Multiset addition min_A, min_B = 0, -ac[-1] max_A, max_B = ac[-1], 0 N, lgN, m = 1, 0, 2*max(max_A-min_A+1, max_B-min_B+1) while N<m: N,lgN = N<<1,lgN+1 a, b = [0]*N, [0]*N for x in ac: a[x-min_A] += 1 b[-x-min_B] += 1 c = zip(fft(a, lgN), fft(b, lgN)) c = fft([x*y for x,y in c], lgN, rot=-1) c = [round(x.real) for x in c][-min_A-min_B:][:n+1] c[0] = sum((x*(x-1))//2 for x in a) print(*c, *(0 for i in range(n+1-len(c))), flush=True)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/993/E" }
d2083
train
MOD = 998244353 n = int(input()) a = list(map(int, input().split())) tot = sum(a) def inv(x): return pow(x, MOD - 2, MOD) l = [0, pow(n, tot, MOD) - 1] for i in range(1, tot): aC = i cC = (n - 1) * (tot - i) curr = (aC + cC) * l[-1] curr -= tot * (n - 1) curr -= aC * l[-2] curr *= inv(cC) curr %= MOD l.append(curr) out = 0 for v in a: out += l[tot - v] out %= MOD zero = l[tot] out -= (n - 1) * zero out *= inv(n) print(out % MOD)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1349/D" }
d2084
train
n, m = map(int, input().split()) a = [10**9 for _ in range(n)] extra = [0 for _ in range(n)] query = list() for _ in range(m): t, l, r, x = map(int, input().split()) l -= 1 r -= 1 query.append((t, l, r, x)) if t == 1: for j in range(l, r + 1): extra[j] += x else: for j in range(l, r + 1): a[j] = min(a[j], x - extra[j]) extra = a.copy() for t, l, r, x in query: if t == 1: for j in range(l, r + 1): a[j] += x else: val = -10**9 for j in range(l, r + 1): val = max(val, a[j]) if not val == x: print('NO') return print('YES') for x in extra: print(x, end=' ')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/360/A" }
d2085
train
import heapq def coor_neighbor(coor, dxs, dys): x, y = coor for dx in dxs: for dy in dys: yield x + dx, y + dy def coor_bottoms(coor): return coor_neighbor(coor, (-1, 0, 1), (-1, )) def coor_tops(coor): return coor_neighbor(coor, (-1, 0, 1), (1, )) def coor_sibs(coor): return coor_neighbor(coor, (-2, -1, 1, 2), (0, )) class Figure: def __init__(self, coors): self._coors = dict() self._stables_min = [] self._stables_max = [] self._pushed = set() self._dropped = set() cubes = dict() self._bots = dict() self._tops = dict() for idx, coor in enumerate(coors): cubes[coor] = idx self._coors[idx] = coor self._bots[idx] = set() self._tops[idx] = set() coor_set = set(coors) for idx, coor in enumerate(coors): for bottom in coor_bottoms(coor): if bottom in coor_set: self._bots[idx].add(cubes[bottom]) for top in coor_tops(coor): if top in coor_set: self._tops[idx].add(cubes[top]) for idx in self._coors: if self.isdroppable(idx): self.push(idx) def sibs(self, idx): for top_idx in self._tops[idx]: for sib_idx in self._bots[top_idx]: if sib_idx not in self._dropped: yield sib_idx def bottom_count(self, idx): return len(self._bots[idx]) def isdroppable(self, idx): return all(len(self._bots[top_idx]) > 1 for top_idx in self._tops[idx]) def push(self, idx): if idx not in self._pushed: heapq.heappush(self._stables_min, idx) heapq.heappush(self._stables_max, -idx) self._pushed.add(idx) def unpush(self, idx): if idx in self._pushed: self._pushed.remove(idx) def drop(self, idx): if idx not in self._pushed: return False self._pushed.remove(idx) self._dropped.add(idx) for bot_idx in self._bots[idx]: self._tops[bot_idx].remove(idx) for top_idx in self._tops[idx]: self._bots[top_idx].remove(idx) coor = self._coors[idx] for bot_idx in self._bots[idx]: if self.isdroppable(bot_idx): self.push(bot_idx) for sib_idx in self.sibs(idx): if not self.isdroppable(sib_idx): self.unpush(sib_idx) return True def drop_min(self): while True: if not self._stables_min: return None min_idx = heapq.heappop(self._stables_min) if self.drop(min_idx): return min_idx def drop_max(self): while True: if not self._stables_max: return None max_idx = - heapq.heappop(self._stables_max) if self.drop(max_idx): return max_idx def __bool__(self): return len(self._coors) != len(self._dropped) def input_tuple(): return tuple(map(int, input().split())) def result_add(result, base, num): return (result * base + num) % (10 ** 9 + 9) N = int(input()) coors = [input_tuple() for _ in range(N)] figure = Figure(coors) result = 0 while True: if not figure: break result = result_add(result, N, figure.drop_max()) if not figure: break result = result_add(result, N, figure.drop_min()) print(result)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/521/B" }
d2086
train
from sys import stdin, stdout K = 20 def findAllStrings(s): n = len(s) sDict = {} for i in range(1,K+1): sDict[i]=set() for x in range(n-i+1): sDict[i].add(s[x:x+i]) return sDict n = int(stdin.readline().rstrip()) stringDicts = [] stringEnd = [] stringBegin = [] for i in range(n): s = stdin.readline().rstrip() stringDicts.append(findAllStrings(s)) if len(s)<K: stringEnd.append(s) stringBegin.append(s) else: stringEnd.append(s[-20:]) stringBegin.append(s[:20]) m = int(stdin.readline().rstrip()) for _ in range(m): a,b = list(map(int,stdin.readline().rstrip().split())) a-=1 b-=1 sDict1 = findAllStrings(stringEnd[a]+stringBegin[b]) sDict2 = stringDicts[a] sDict3 = stringDicts[b] sDict={} for i in range(1,K+1): sDict[i] = sDict1[i]|sDict2[i]|sDict3[i] stringDicts.append(sDict) for i in range(1,K+1): if len(sDict[i])!=2**i: print(i-1) break if len(stringBegin[a])<K and len(stringBegin[a])+len(stringBegin[b])<K: stringBegin.append(stringBegin[a]+stringBegin[b]) elif len(stringBegin[a])<K: s = stringBegin[a]+stringBegin[b] stringBegin.append(s[:K]) else: stringBegin.append(stringBegin[a]) if len(stringEnd[b])<K and len(stringEnd[a])+len(stringEnd[b])<K: stringEnd.append(stringEnd[a]+stringEnd[b]) elif len(stringEnd[b])<K: s = stringEnd[a]+stringEnd[b] stringEnd.append(s[-K:]) else: stringEnd.append(stringEnd[b])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/868/D" }
d2087
train
import sys input = sys.stdin.readline from collections import deque N, Q = list(map(int, input().split())) que = deque([int(a) for a in input().split()]) ma = max(que) X = [] k = -1 c = 0 while c <= k+N+5: a = deque.popleft(que) b = deque.popleft(que) X.append((a, b)) c += 1 if a > b: a, b = b, a if k < 0 and b == ma: k = c deque.appendleft(que, b) deque.append(que, a) for _ in range(Q): i = int(input()) - 1 if i <= k: print(*X[i]) else: i = (i-k)%(N-1)+k print(*X[i])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1179/A" }
d2088
train
3 import sys n, l, r, ql, qr = list(map(int, sys.stdin.readline().strip().split())) w = [int(x) for x in sys.stdin.readline().strip().split()] s = [0] for i in range(0, n): s.append(s[-1] + w[i]) def cost(left): right = n - left diff = left - right bonus = 0 if diff > 0: # left part is larger bonus = ql * (diff - 1) elif diff < 0: # right part is larger bonus = qr * (-diff - 1) return bonus + l * s[left] + r * (s[n] - s[left]) best = cost(0) for left in range(1, n+1): c = cost(left) if c < best: best = c print(best)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/354/A" }
d2089
train
n = int(input()) C = list(map(int, input().split())) dp = [[0]*n for _ in range(n)] for i in range(n) : dp[i][i] = 1 for i in range(n-2, -1, -1) : for j in range(i+1, n) : dp[i][j] = 1 + dp[i+1][j] if C[i] == C[i+1] : dp[i][j] = min( dp[i][j], 1 + (dp[i+2][j] if i+2 < n else 0) ) for k in range(i+2, j) : if C[i] == C[k] : dp[i][j] = min( dp[i][j], dp[i+1][k-1] + dp[k+1][j] ) if C[i] == C[j] and j-i > 1: dp[i][j] = min( dp[i][j], dp[i+1][j-1] ) print( dp[0][n-1] )
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/607/B" }
d2090
train
from operator import __or__, __and__, __xor__ from sys import stdin, stdout n, b, c = int(stdin.readline()), 0, 1023 m = {'|': __or__, '&': __and__, '^': __xor__} for i in range(n): t, v = [i for i in stdin.readline().split()] b = m[t](b, int(v)) c = m[t](c, int(v)) x, o, a = 0, 0, 1023 for i in range(10): if ((b >> i) & 1) and ((c >> i) & 1): o |= 1 << i elif not ((b >> i) & 1) and not ((c >> i) & 1): a -= 1 << i elif ((b >> i) & 1) and not ((c >> i) & 1): x |= 1 << i stdout.write('3\n| ' + str(o) + '\n^ ' + str(x) + '\n& ' + str(a))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/878/A" }
d2091
train
from itertools import combinations_with_replacement from collections import deque #sys.stdin = open("input_py.txt","r") n, m = map(int, input().split()) G = [ [] for i in range(n)] for i in range(m): x, y = map(int, input().split()) x-=1; y-=1 G[x].append(y) G[y].append(x) def BFS(s): dist = [-1 for i in range(n)] dist[s] = 0 Q = deque() Q.append(s) while len(Q) > 0: v = Q.popleft() for to in G[v]: if dist[to] < 0: dist[to] = dist[v] + 1 Q.append(to) return dist Dist = [BFS(i) for i in range(n)] s1, t1, l1 = map(int, input(). split()) s2, t2, l2 = map(int, input(). split()) s1-=1; t1-=1; s2-=1; t2-=1 if Dist[s1][t1] > l1 or Dist[s2][t2] > l2: print(-1) return rest = Dist[s1][t1] + Dist[s2][t2] for i in range(n): for j in range(n): if Dist[i][s1] + Dist[i][j] + Dist[j][t1] <= l1 and Dist[i][s2] + Dist[i][j] + Dist[j][t2] <= l2 : rest = min(rest, Dist[i][j] + Dist[i][s1] + Dist[i][s2] + Dist[j][t1] + Dist[j][t2]) if Dist[i][s1] + Dist[i][j] + Dist[j][t1] <= l1 and Dist[j][s2] + Dist[i][j] + Dist[i][t2] <= l2 : rest = min(rest, Dist[i][j] + Dist[j][t1] + Dist[j][s2] + Dist[i][s1] + Dist[i][t2]) print(m-rest)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/543/B" }
d2092
train
import sys input = sys.stdin.readline s = input() M = int(input()) def next_pow_2(n): p = 1 while p < n: p <<= 1 return p def represented_range(node, size): l = node r = node while l < size: l = 2*l r = 2*r + 1 return l-size, r-size class SegTree: def __init__(self, size): self.size = next_pow_2(size) self.answer = [0] * (2*self.size) self.opened = [0] * (2*self.size) self.closed = [0] * (2*self.size) # O(size * (O(func) + O(init)) def build(self, s): for i in range(self.size): self.answer[self.size + i] = 0 self.opened[self.size + i] = 1 if i < len(s) and s[i] == '(' else 0 self.closed[self.size + i] = 1 if i < len(s) and s[i] == ')' else 0 for i in range(self.size - 1, 0, -1): matched = min(self.opened[2*i], self.closed[2*i+1]) self.answer[i] = self.answer[2*i] + self.answer[2*i+1] + matched self.opened[i] = self.opened[2*i] + self.opened[2*i+1] - matched self.closed[i] = self.closed[2*i] + self.closed[2*i+1] - matched # O(log(size)), [l,r] def query(self, l, r): l += self.size r += self.size eventsR = [] answer = 0 opened = 0 while l <= r: if l & 1: matched = min(self.closed[l], opened) answer += self.answer[l] + matched opened += self.opened[l] - matched l += 1 if not (r & 1): eventsR.append((self.answer[r], self.opened[r], self.closed[r])) r -= 1 l >>= 1 r >>= 1 for i in range(len(eventsR)-1, -1, -1): a, o, c = eventsR[i] matched = min(c, opened) answer += a + matched opened += o - matched return answer seg = SegTree(len(s)) seg.build(s) for i in range(M): l, r = [int(_) for _ in input().split()] print(2*seg.query(l-1, r-1))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/380/C" }
d2093
train
n = int(input()) if n % 2: print("contest") else: print("home")
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/765/A" }
d2094
train
n = int(input()) from bisect import bisect_left a = list(map(int, input().split())) ss = [] ms = [] for i in range(n): k = a[i] ind = bisect_left(ms, -k) if ind == len(ms): ss.append([]) ms.append(0) ss[ind].append(k) ms[ind] = -k for s in ss: print(' '.join([str(i) for i in s]))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/847/B" }
d2095
train
def main(): import sys input = sys.stdin.readline n = int(input()) arr = input() one = arr.count('n') zero = arr.count('z') ans = [1] * one + [0] * zero print(*ans) return 0 main()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1220/A" }
d2096
train
input() A = list(map(int, input().split(' '))) root=-1 for i,a in enumerate(A) : if i == a-1 : root = i break v = [False]*len(A) if root>-1 : v[root]=True ans= 0 for i,a in enumerate(A) : if v[i] : continue v[i]= True l=[i] a-=1 while not v[a] : l.append(a) v[a]=True a=A[a]-1 if a in l: #new cycle if root==-1: A[a]=a+1 root=a ans+=1 else : A[a]=root+1 ans+=1 print(ans) print(' '.join(map(str,A)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/698/B" }
d2097
train
import sys #sys.stdin=open("data.txt") input=sys.stdin.readline n=int(input()) b=list(map(int,input().split())) bb=sorted(b) c={bb[i]:i for i in range(n)} a=[c[b[i]] for i in range(n)] vis=[0]*n out=[] for i in range(n): if vis[i]: continue vis[i]=1 newlist=[i] while a[newlist[-1]]!=i: newlist.append(a[newlist[-1]]) vis[newlist[-1]]=1 out.append(newlist) print(len(out)) for i in out: print(" ".join([str(x+1) for x in [len(i)-1]+i]))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/843/A" }
d2098
train
n = int(input()) edges = [[int(x) for x in input().split()] for i in range(n-1)] edges = sorted(edges) use_count = [0]+[int(input()) for i in range(n)] lo,hi = 0,10000 def getpar(par,u): if par[par[u]] == par[u]: return par[u] par[u] = getpar(par,par[u]) return par[u] def unite(par,sz,use,u,v): u = getpar(par,u) v = getpar(par,v) par[u] = v sz[v] += sz[u] use[v] += use[u] def solve(fp): par = [i for i in range(n+1)] sz = [1 for i in range(n+1)] use = [use_count[i] for i in range(n+1)] for edge in edges: if edge[2] < fp: unite(par,sz,use,edge[0],edge[1]) total_use = sum(use_count) for i in range(n+1): p = getpar(par,i) if(p == i): if(total_use - use[p] < sz[p]): return False return True while lo < hi: mid = (lo+hi+1)//2 if solve(mid): lo = mid else: hi = mid-1 print(lo)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/444/E" }
d2099
train
import sys #sys.stdin=open("data.txt") input=sys.stdin.readline n,m=list(map(int,input().split())) party=[[] for _ in range(m+5)] pc=sorted([list(map(int,input().split())) for _ in range(n)],key=lambda x:x[1]) choose=[0]*n for i in range(n): party[pc[i][0]].append(i) want=10**18 for i in range(1,n+1): p1=len(party[1]) # want all other parties to have <i voters for j in range(2,m+5): if len(party[j])<i: continue for k in range(len(party[j])-i+1): p1+=1 choose[party[j][k]]=1 # want party 1 to have >=i voters want2=0 for j in range(n): if p1<i and choose[j]==0 and pc[j][0]!=1: choose[j]=1 p1+=1 if choose[j]==1: want2+=pc[j][1] if want>want2: want=want2 #print(i,want2) # reset choose=[0]*n print(want)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1019/A" }
d2100
train
3 import sys def __starting_point(): n, k = list(map(int, sys.stdin.readline().split())) l = [] i = 1 j = k + 1 while i <= j: l.append(str(i)) i += 1 if j > i: l.append(str(j)) j -= 1 for i in range(k+2, n+1): l.append(str(i)) print(' '.join(l)) __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/482/A" }