_id
stringlengths
2
5
partition
stringclasses
2 values
text
stringlengths
5
289k
language
stringclasses
1 value
meta_information
dict
title
stringclasses
1 value
d7901
test
N, K = map(int, input().split()) S = []; T = [] for x in range(1, int(N**.5)+1): if N % x == 0: S.append(x) if x*x < N: T.append(N//x) T.reverse() S += T M = len(S) U = [] MOD = 10**9 + 7 ans = 0 v = 0 for i in range(M): x = S[i] v = pow(K, (x+1)//2, MOD) for j in range(i): y = S[j] if x % y == 0: v -= U[j] U.append(v % MOD) ans = (ans + (v * x if x & 1 else v * (x//2))) % MOD print(ans)
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc064/tasks/arc064_d" }
d7902
test
N=int(input()) mod=998244353 inv4=249561088 A=[inv4,0,3] for i in range(N): A.append(9*A[-1]-24*A[-2]+16*A[-3]) A[-1]%=mod A[0]-=inv4 B=[0 for i in range(N)] for i in range(N): x=i y=N-i-1 if x<=y: B[x]=A[i] B[y]=A[i] P=N*pow(2,N-2+mod-1,mod) for i in range(N): B[i]+=P B[i]%=mod Q=pow(2,N-1,mod) Qinv=pow(Q,mod-2,mod) for i in range(N): B[i]*=Qinv B[i]%=mod for i in range(N): print((B[i]))
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc109/tasks/arc109_e" }
d7903
test
#!/bin/pypy3 from itertools import* from timeit import* from typing import Optional S=lambda x:sum(map(int,str(x))) def ceil_s_divisible_a(x:int,a:int) -> Optional[int]: z=S(x)%a if z: z=a-z tail=[] x=list(str(x)) while x: digit=x.pop() diff=min(z,9-int(digit)) z-=diff tail.append(str(int(digit)+diff)) if z==0:break else: return ceil_s_divisible_a(10**len(tail),a) x=''.join(x) + ''.join(reversed(tail)) assert S(x)%a==0 x=int(x) return x def smooth25(a): a=int(bin(a).rstrip('0'),2) while a%5==0: a//=5 return a==1 def solve(a): for first in range(1,60): # 120 q=str((first*10**3000+a-1) // a) # 5000 for s1 in range(1,200): i=1 s2=int(q[0]) while i<len(q) and s2<s1*a-10: s2+=int(q[i]); i+=1 for len1 in range(i,min(i+10,len(q))): small=int(q[:len1]) for z in range(4): # 10 small=ceil_s_divisible_a(small,a) if S(small*a)*a==S(small): return small small+=1 return None def powform(x:int)->str: s=str(x) try: i=s.find('00000') return f'{s[:i]} * 10 ** {len(s)-i} + {int(s[i:])}' except IndexError: return str(x) if 0: #for a in (a for a in range(2,1000)): for a in [999,909,813,777,957,921,855,933,831,942,891,846,807,783,888][1::3]: #for a in [32]: def work(): nonlocal x x=solve(a) t=timeit(work,number=1) if t>0.5 or x==None: if x!=None: print(a,t,'>>',powform(a*x)) else: print(a,t,'>> ?????') #print(solve(int(input()))) special=''' 660 0.5026652759997887 >> 3 * 10 ** 2640 + 35340 803 0.5102322779994211 >> 3 * 10 ** 2678 + 1614 912 0.5136937369998122 >> 3 * 10 ** 1825 + 240 918 0.5238579140004731 >> 3 * 10 ** 1813 + 1104 582 0.5302371079997101 >> 2 * 10 ** 2328 + 17116 612 0.5363936909998301 >> 2 * 10 ** 2413 + 10348 495 0.5372351949999938 >> 3 * 10 ** 2969 + 16305 927 0.5433051690006323 >> 3 * 10 ** 2195 + 21003 636 0.5471086210000067 >> 3 * 10 ** 1379 + 20004 531 0.5475810970001476 >> 2 * 10 ** 2140 + 439 64 0.5633312410000144 >> ????? 200 0.5639609099998779 >> ????? 100 0.565854023000611 >> ????? 125 0.5663040710005589 >> ????? 160 0.5668467480008985 >> ????? 800 0.5676178080002501 >> ????? 128 0.5676772269998764 >> ????? 80 0.5682811480000964 >> ????? 256 0.5685735130000467 >> ????? 250 0.5691464900000938 >> ????? 512 0.569266141999833 >> ????? 32 0.5692826909998985 >> ????? 50 0.5692834940000466 >> ????? 25 0.5696684799995637 >> ????? 400 0.5703751219998594 >> ????? 20 0.5706145570002263 >> ????? 500 0.5742691679997733 >> ????? 640 0.5749700739997934 >> ????? 40 0.5768258159996549 >> ????? 625 0.5775357299999087 >> ????? 16 0.5789494729997386 >> ????? 833 0.5855263899993588 >> 3 * 10 ** 2286 + 1404 792 0.5996652009998797 >> 3 * 10 ** 1903 + 16008 320 0.6031684260005932 >> ????? 10 0.6464516910000384 >> ????? 546 0.6579458010000963 >> 3 * 10 ** 2184 + 2454 5 0.6617960960002165 >> ????? 907 0.664109037000344 >> 3 * 10 ** 2538 + 2223 923 0.6807242180002504 >> 2 * 10 ** 2476 + 4141 723 0.6976773409996895 >> 3 * 10 ** 2892 + 1185 825 0.701172955000402 >> 4 * 10 ** 2476 + 123350 906 0.7062042559991824 >> 4 * 10 ** 1998 + 104 905 0.7086789289996887 >> 2 * 10 ** 2412 + 1540 911 0.711649564000254 >> 2 * 10 ** 2612 + 2044 934 0.7246100349993867 >> 2 * 10 ** 2570 + 51112 765 0.7552886830007992 >> 3 * 10 ** 2939 + 1725 981 0.7653923980005857 >> 4 * 10 ** 1965 + 1022 333 0.7884190810000291 >> 3 * 10 ** 2994 + 62934 663 0.8130600629992841 >> 3 * 10 ** 2546 + 11634 444 0.8443964660000347 >> 3 * 10 ** 1999 + 13956 720 0.8445076829993923 >> 2 * 10 ** 2779 + 159280 867 0.9858260920000248 >> 5 * 10 ** 1739 + 121 914 1.0558696210000562 >> 3 * 10 ** 1831 + 222 606 1.1190159360003236 >> 5 * 10 ** 2910 + 1318 948 1.1529914639995695 >> 6 * 10 ** 2466 + 1020 1000 1.2245053040005587 >> ????? 741 1.2366985769995154 >> 5 * 10 ** 2669 + 175 819 1.292531102999419 >> 8 * 10 ** 2949 + 31312 867 1.293641017000482 >> 5 * 10 ** 1739 + 121 961 1.431375496000328 >> 4 * 10 ** 1935 + 1112 913 2.0632996949998414 >> 5 * 10 ** 2323 + 16 861 2.1641551399998207 >> 11 * 10 ** 1847 + 1114 992 2.2718322470000203 >> 11 * 10 ** 2207 + 1504 936 2.3109037909998733 >> 11 * 10 ** 2108 + 3112 996 2.3603119750005135 >> 11 * 10 ** 1979 + 4300 951 2.380345242999283 >> 11 * 10 ** 1820 + 412 969 2.471255187000679 >> 11 * 10 ** 1942 + 241 828 2.504634874999283 >> 11 * 10 ** 1595 + 11212 693 2.5246166990000347 >> 13 * 10 ** 2494 + 423014 840 2.5490226490001078 >> 11 * 10 ** 1681 + 13120 983 2.618962229999852 >> 11 * 10 ** 1968 + 5011 963 2.641272683999887 >> 11 * 10 ** 2026 + 133 972 2.741184581000198 >> 12 * 10 ** 2130 + 312 555 2.787974407000547 >> 11 * 10 ** 2497 + 444445 873 2.8377116049996403 >> 11 * 10 ** 1774 + 133 903 2.898315477000324 >> 13 * 10 ** 1726 + 32 804 2.9635119349995875 >> 12 * 10 ** 1659 + 1500 864 3.032601443999738 >> 13 * 10 ** 2747 + 34016 759 3.0681308859993806 >> 13 * 10 ** 2504 + 311441 871 3.4960390779997397 >> 13 * 10 ** 2995 + 2405 902 4.413119433999782 >> 12 * 10 ** 1506 + 1110 997 4.446912733999852 >> 11 * 10 ** 1999 + 7 993 5.025415283999791 >> 23 * 10 ** 2130 + 31 837 5.286188959000356 >> 25 * 10 ** 2722 + 11063 786 5.390603378999913 >> 21 * 10 ** 1572 + 4002 801 5.4837765329994 >> 22 * 10 ** 1645 + 212 882 6.045185064999714 >> 22 * 10 ** 1822 + 1130 990 6.413724044000446 >> 39 * 10 ** 2970 + 302010 666 6.967028857000514 >> 33 * 10 ** 2997 + 32934 941 6.982767053000316 >> 21 * 10 ** 1885 + 312 924 7.134165846000542 >> 34 * 10 ** 2772 + 1110152 858 8.089877333000004 >> 41 * 10 ** 2573 + 12201142 939 8.241953895999359 >> 33 * 10 ** 1879 + 20001 813 3.1825667919993066 >> 3 * 10 ** 4065 + 7314 921 1.9310127280004963 >> 1 * 10 ** 3762 + 18008 831 1.683305384999585 >> 1 * 10 ** 3702 + 1646 846 1.4100486610004737 >> 1 * 10 ** 3419 + 44234 888 6.891388972000641 >> 3 * 10 ** 3998 + 27672 909 11.340291348999926 >> 7 * 10 ** 4673 + 17201 957 1.3982879649993265 >> 1 * 10 ** 4347 + 28403 933 0.9980270719997861 >> 1 * 10 ** 3746 + 233234 891 0.8806926099996417 >> 1 * 10 ** 3957 + 1079 783 0.6478317080000124 >> 1 * 10 ** 3162 + 22814 999 102.2252583720001 >> 89 * 10 ** 4760 + 20071 777 37.847382832999756 >> 24 * 10 ** 4661 + 474123 855 0.934857464999368 >> 1 * 10 ** 3420 + 21545 942 1.0410122209996189 >> 1 * 10 ** 4198 + 310058 807 0.7532789589995446 >> 1 * 10 ** 3234 + 1307123 ''' a=int(input()) for line in special.splitlines(): if line: expr,out=line.split('>>') expr=expr.split()[0] if int(expr)==a: print(-1 if out.strip()=='?????' else eval(out)//a) break else: print(solve(a))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1120/E" }
d7904
test
n = int(input()) if n % 2 == 0: print(-1) else: print(*range(n)) print(*range(n)) print(*map(lambda x: x * 2 % n, range(n)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/303/A" }
d7905
test
n = int(input()) graph = [set() for tr in range(n+2)] i = 1 while i < n: x, y = list(map(int, input().split())) graph[x].add(y) graph[y].add(x) i += 1 a = iter(map(int, input().split())) try: assert next(a) == 1 q = [1] for v in q: gv = graph[v] gv1 = tuple(gv) for tr2 in gv1: u = next(a) assert u in gv gv.remove(u) graph[u].remove(v) q.append(u) print("Yes") except AssertionError: print("No")
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1037/D" }
d7906
test
N,M,K = map(int,input().split()) INF = 10**6+1 from collections import defaultdict incoming = defaultdict(list) outgoing = defaultdict(list) for _ in range(M): d,f,t,c = map(int,input().split()) if t == 0: incoming[d].append((c,f-1)) if f == 0: outgoing[d].append((c,t-1)) incoming_dates = sorted(incoming.keys()) outgoing_dates = sorted(outgoing.keys(),reverse=True) Li = [] mark = [False]*N cnt = 0 costs = [0]*N total_cost = 0 for d in incoming_dates: for c,x in incoming[d]: if mark[x]: if costs[x] > c: total_cost += c-costs[x] costs[x] = c else: mark[x] = True cnt += 1 costs[x] = c total_cost += c if cnt == N: Li.append((d,total_cost)) Lo = [] mark = [False]*N cnt = 0 costs = [0]*N total_cost = 0 for d in outgoing_dates: for c,x in outgoing[d]: if mark[x]: if costs[x] > c: total_cost += c-costs[x] costs[x] = c else: mark[x] = True cnt += 1 costs[x] = c total_cost += c if cnt == N: Lo.append((d,total_cost)) Lo.reverse() if not Li or not Lo: print(-1) return # print(Li,Lo) from bisect import bisect best = float('inf') for d,c in Li: i = bisect(Lo,(d+K+1,0)) if i >= len(Lo): break else: best = min(best,c+Lo[i][1]) if best == float('inf'): print(-1) else: print(best)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/853/B" }
d7907
test
from math import sin, cos, tan, atan, pi def main(): w, h, a = map(int, input().split()) a = min(a, 180 - a) * pi / 180 if h > w: h, w = w, h if h * (1 + cos(a)) < w * sin(a): res = h * h / sin(a) else: res = h * w - ((w - h * tan(a / 2)) ** 2 * tan(a) + (h - w * tan(a / 2)) ** 2 * tan(a)) / 4 print('{:.9f}'.format(res)) def __starting_point(): main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/280/A" }
d7908
test
n, m = map(int, input().split()) u = [[], []] for q in range(n): p, s = input().split() u[p == 'ATK'].append(int(s)) d, a = [sorted(q) for q in u] v = sorted(int(input()) for q in range(m)) k, s = 0, sum(v) i = j = 0 for q in v: if i < len(d) and q > d[i]: s -= q i += 1 elif j < len(a) and q >= a[j]: s -= a[j] j += 1 if i + j - len(a) - len(d): s = 0 for q in v: if k < len(a) and q >= a[k]: k += 1 x = y = 0 v.reverse() for i in range(k): x += a[i] y += v[i] s = max(s, y - x) print(s)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/321/B" }
d7909
test
import sys input = sys.stdin.readline n,m=list(map(int,input().split())) A=list(map(int,input().split())) C=list(map(int,input().split())) P=list(map(int,input().split())) DP=[[-1<<30]*(n+1) for i in range(5001)] # DP[k][cnt] = Aのmaxがkで, そういう人間がcnt人いるときのprofitの最大値 for i in range(5001): DP[i][0]=0 for i in range(n-1,-1,-1): a,c = A[i]-1,C[i] for j in range(n,-1,-1): if DP[a][j]==-1<<30: continue if DP[a][j] - c + P[a] > DP[a][j+1]: DP[a][j+1] = DP[a][j] - c + P[a] x, w=a, j+1 while x+1<n+m: if DP[x+1][w//2] < DP[x][w] + w//2 * P[x+1]: DP[x+1][w//2] = DP[x][w] + w//2 * P[x+1] x,w=x+1,w//2 else: break ANS=0 for i in range(5001): ANS=max(ANS,DP[i][0],DP[i][1]) print(ANS)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1322/D" }
d7910
test
def main(): a = list(input()) b = list(input()) n = len(a) k = n while k % 2 == 0: k = k // 2 while k != n: pairs = n // (k * 2) for i in range(0, pairs * 2, 2): if a[k * i:k * (i + 1)] > a[k * (i + 1):k * (i + 2)]: a[k * i:k * (i + 1)], a[k * (i + 1):k * (i + 2)] = a[k * (i + 1):k * (i + 2)], a[k * i:k * (i + 1)] if b[k * i:k * (i + 1)] > b[k * (i + 1):k * (i + 2)]: b[k * i:k * (i + 1)], b[k * (i + 1):k * (i + 2)] = b[k * (i + 1):k * (i + 2)], b[k * i:k * (i + 1)] k *= 2 if a == b: print('YES') else: print('NO') main()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/559/B" }
d7911
test
n = int(input()) p = lambda a,b: print(a+1,b+1) if n % 4 > 1: print("NO") else: print("YES") for i in range(n%4,n,4): for x in range(2): for j in range(i): p(j,i+2*x) p(i+2*x,i+2*x+1) for j in range(i,0,-1): p(j-1,i+2*x+1) p(i,i+3) p(i+1,i+2) p(i,i+2) p(i+1,i+3)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/804/E" }
d7912
test
m,n=list(map(int,input().split())) s=[input().strip() for i in range(m)] a=list([int(x)-1 for x in input().split()]) stmpl=s[a[0]] f=1 def peres(s1,s2): return ''.join([i if i==j else '?' for i,j in zip(s1,s2)]) for i in a: if len(stmpl)!=len(s[i]): f=0 break stmpl=peres(stmpl,s[i]) for i,e in enumerate(s): if i in a: continue if len(stmpl)==len(e) and stmpl==peres(stmpl,e): f=0 break if f: print('Yes') print(stmpl) else: print('No')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/730/H" }
d7913
test
from itertools import permutations from bisect import bisect_left inf = 10 ** 18 mod = 10 ** 9 + 7 def nCr(n, r, mod=10**9+7): if r < 0 or r > n: return 0 res = 1 div = 1 r = min(r, n - r) for i in range(r): res = res * (n - i) % mod div = div * (i + 1) % mod return res * pow(div, mod-2, mod) % mod def calc_lis(A): L = [A[0]] for a in A[1:]: if a > L[-1]: L.append(a) else: L[bisect_left(L, a)] = a return len(L) def enum(N, A): diff = [A[0]] + [r - l for l, r in zip(A[:-1], A[1:])] dp = [[0] * (N + 1) for _ in range(N + 1)] dp[0][0] = 1 for i in range(1, N + 1): for j in range(i, N + 1): for k in range(i - 1, j + 1): dp[i][j] += dp[i - 1][k] * nCr(diff[i - 1], j - k) dp[i][j] %= mod return dp[N][N] def main(): N = int(input()) A = list(map(int, input().split())) pair = [(0,)] for _ in range(1, N): nxt = [] for p in pair: v = p[-1] nxt.append(p + (v,)) nxt.append(p + (v+1,)) pair = nxt ans = 0 for p in pair: sz = p[-1] + 1 for order in set(permutations(p)): arr = [inf] * sz for i, a in zip(order, A): arr[i] = min(arr[i], a) for i in reversed(range(sz - 1)): arr[i] = min(arr[i], arr[i + 1]) ans += enum(sz, arr) * calc_lis(order) ans %= mod for a in A: ans *= pow(a, mod - 2, mod) ans %= mod print(ans) main()
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc104/tasks/arc104_e" }
d7914
test
import sys sys.setrecursionlimit(5001) MOD = 10 ** 9 + 7 n = int(input()) links = [set() for _ in range(n)] for line in sys.stdin.readlines(): x, y = list(map(int, line.split())) x -= 1 y -= 1 links[x].add(y) links[y].add(x) double_factorial_odd = [0] * (n // 2) prev = 1 for i in range(n // 2): prev = double_factorial_odd[i] = (2 * i + 1) * prev % MOD def dfs(v, p): ret = [0, 1] for u in links[v]: if u == p: continue res = dfs(u, v) lt, ls = len(ret), len(res) mrg = [0] * (lt + ls - 1) for i in range(1 - lt % 2, lt, 2): c = ret[i] for j in range(1 - ls % 2, ls, 2): mrg[i + j] = (mrg[i + j] + c * res[j]) % MOD ret = mrg if len(ret) % 2 == 1: ret[0] = -sum(pattern * df % MOD for pattern, df in zip(ret[2::2], double_factorial_odd)) % MOD return ret print((MOD - dfs(0, -1)[0]))
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc101/tasks/arc101_c" }
d7915
test
import sys #sys.stdin=open("data.txt") input=sys.stdin.readline n,l,r=list(map(int,input().split())) a1=0 layers=1 while layers*2<=n: layers*=2 # abacaba pattern for i in range(l,r+1): layer=layers while i%2==0: layer//=2 i//=2 if (n//layer)%2==1: a1+=1 #print(i,n&layer) print(a1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/768/B" }
d7916
test
from collections import defaultdict def count(x): c=0 while x > 0: c+=1 x &= (x-1) return c n,m=list(map(int,input().split())) g=defaultdict(list) for _ in range(m): u, v = list(map(int,input().split())) u-=1;v-=1 g[u].append(v) g[v].append(u) mask1=0;mask2=0;MAX=(1<<n)-1 a=[0]*(1 << n) dp=[MAX]*(1 << n) if m == (n*(n-1))//2: print(0) return for i,j in list(g.items()): mask1 = (1 << i);mask2=0;mask2 |= mask1 for k in j: mask2 |= (1 << k) dp[mask2]=mask1 a[mask1]=mask2 for i in range(0,(1 << n)-1): if dp[i] != MAX: #print('HEllo') temp = dp[i] ^ i for j in range(n): if temp & (1 << j) != 0: nmask = i | a[(1 << j)] dp[nmask]=dp[i] | (1 << j) if count(dp[i] | (1 << j)) < count(dp[nmask]) else dp[nmask] ans = [] for i in range(n): if dp[-1] & (1 << i) != 0: ans.append(i+1) print(len(ans)) print(*ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/906/C" }
d7917
test
def i23(x): while x%2==0: x//=2 while x%3==0: x//=3 return x == 1 import fractions from fractions import gcd x = int(input()) y = list(map(int, input().split(' '))) gcdx = y[0] for i in y: gcdx = gcd(i, gcdx) for i in y: if not i23(i/gcdx): print("No") quit() print("Yes")
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/573/A" }
d7918
test
n = int(input()) a = list(map(int, input().split())) abs_a = [abs(v) for v in a] neg = sum(v < 0 for v in a) if n % 2 == 1 or neg % 2 == 0 or any(v == 0 for v in a): print(sum(abs_a)) else: print(sum(abs_a) - 2 * min(abs_a))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/301/A" }
d7919
test
n, q = list(map(int, input().split())) go = dict() for i in range(q): fr, to = input().split() go[fr] = to ans = 0 for i in range(6 ** n): cur = i s = '' for j in range(n): s += chr(ord('a') + (cur % 6)) cur //= 6 while len(s) > 1: fr = s[:2] if fr not in go: break s = go[fr] + s[2:] if s == 'a': ans += 1 print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/653/B" }
d7920
test
from math import factorial cat = [1, 1] p = 10**9 + 7 n = int(input()) ans = 0 fac = [1] mat = [[0 for i in range(n + 1)] for j in range(n + 1)] mat[0][0] = 1 for i in range(1, n + 1): mat[i][0] = mat[i - 1][i - 1] for j in range(i): mat[i][j + 1] = (mat[i][j] + mat[i - 1][j]) % p print(mat[n][n - 1] % p)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/568/B" }
d7921
test
n,m=map(int,input().split()) if m>n:print(-1) else: q=int((1.+n/m)/2.) v=(m+n)/(2*q) print(v)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/578/A" }
d7922
test
# import collections, atexit, math, sys from functools import cmp_to_key #key=cmp_to_key(lambda x,y: 1 if x not in y else -1 ) sys.setrecursionlimit(1000000) def getIntList(): return list(map(int, input().split())) import bisect 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 def memo(func): cache={} def wrap(*args): if args not in cache: cache[args]=func(*args) return cache[args] return wrap @memo def comb (n,k): if k==0: return 1 if n==k: return 1 return comb(n-1,k-1) + comb(n-1,k) 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() M, = getIntList() za = getIntList() zb = getIntList() if 1 in za or 1 in zb: print(-1) return def trywork(fuel): for i in range(N): now = fuel + M cost = now / za[i] fuel-=cost if fuel <0: return False now = fuel +M cost = now / zb[ (i+1)%N] fuel-=cost if fuel<0: return False return True r0 = 0 r1 = 10**9+1 while r1-r0 > 1e-7 and (r1-r0) *10000000 >r1: m = (r1+r0)/2 f = trywork(m) if f: r1 = m else: r0 = m print(r1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1010/A" }
d7923
test
n = int(input()) print((n-1) // 2)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/804/A" }
d7924
test
f0 = 'What are you doing at the end of the world? Are you busy? Will you save us?' ft1, ft2, ft3 = 'What are you doing while sending "', '"? Are you busy? Will you send "', '"?' flen = [2 * 10 ** 18] * (10 ** 5 + 1) flen[0] = len(f0) for i in range(1, 56): flen[i] = len(ft1) + len(ft2) + len(ft3) + 2 * flen[i-1] def ans(n, k): while True: if n == 0: return f0[k] if k < len(ft1): return ft1[k] k -= len(ft1) if k < flen[n-1]: n -= 1 continue k -= flen[n-1] if k < len(ft2): return ft2[k] k -= len(ft2) if k < flen[n-1]: n -= 1 continue k -= flen[n-1] return ft3[k] q = int(input()) a = '' for _ in range(q): n, k = list(map(int, input().split())) k -= 1 if k >= flen[n]: a += '.' continue a += ans(n, k) print(a)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/896/A" }
d7925
test
#!/bin/python3 a = input() while a: expr, n = a.split('=') n = int(n.strip()) pos = 1 neg = 0 sg = [1] for c in expr: if c == '+': pos += 1 sg.append(1) elif c == '-': neg += 1 sg.append(0) csum = pos - neg rez = [] for i in sg: if csum < n: if i > 0: v = min(n-csum, n-1) csum += v rez.append(1+v) else: rez.append(-1) else: if i > 0: rez.append(1) else: v = min(csum - n, n-1) csum -= v rez.append(-1-v) if csum == n: print("Possible") ans = str(rez[0]) for j in rez[1:]: ans += " " + ("+" if j > 0 else "-") + " " ans += str(abs(j)) ans += " = " + str(n) print(ans) else: print("Impossible") break a = input()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/663/A" }
d7926
test
def met(x,y): if x*y>0:return 0 if (x+y)%2==0:return 1 return 2 def main0(n,a0,a1): ret=[0]*3 mat=[[0]*n for _ in range(n)] for i in range(1,n): mat[0][i]=a0[i] mat[i][0]=a1[i-1] ret[a1[i-1]]+=1 ret[a0[i]]+=1 mat[0][0]=a0[0] ret[a0[0]]+=1 for j in range(1,n): for i in range(1,n): mat[i][j]=met(mat[i][j-1],mat[i-1][j]) ret[mat[i][j]]+=1 #for x in mat:print(*x) return ret def main1(n,a0,a1): ret=[0]*3 a1=[a0[0]]+a1 for i in range(1,n): ret[a1[i]]+=1 ret[a0[i]]+=1 ret[a0[0]]+=1 b0,b1=[a1[1]],[a0[1]] for i in range(1,n): b0.append(met(b0[-1],a0[i])) b1.append(met(b1[-1],a1[i])) ret[b0[-1]]+=1 ret[b1[-1]]+=1 ret[b0[1]]-=1 c0=[a1[2],b1[2]] c1=[a0[2],b0[2]] for i in range(2,n): c0.append(met(c0[-1],b0[i])) c1.append(met(c1[-1],b1[i])) ret[c0[-1]]+=1 ret[c1[-1]]+=1 ret[c0[2]]-=1 d0=[a1[3],b1[3],c1[3]] d1=[a0[3],b0[3],c0[3]] for i in range(3,n): d0.append(met(d0[-1],c0[i])) d1.append(met(d1[-1],c1[i])) ret[d0[-1]]+=1 ret[d1[-1]]+=1 ret[d0[3]]-=1 for i in range(4,n): ret[d0[i]]+=n-i-1 ret[d1[i]]+=n-i-1 ret[d0[3]]+=n-4 """ print(*a0) print(*b0) print(*c0) print(*d0) for i in range(4,n): print(a1[i],b1[i],c1[i],d1[i]) """ return ret n=int(input()) a0=list(map(int,input().split())) a1=[int(input()) for _ in range(n-1)] if n<10: ret=main0(n,a0,a1) else: ret=main1(n,a0,a1) print((*ret))
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc107/tasks/arc107_e" }
d7927
test
import collections n = int(input()) s = collections.Counter(input()) print('Yes' if n == 1 or max(s.values()) > 1 else 'No')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1025/A" }
d7928
test
n,k=list(map(int,input().split())) M=10**9+7 print(k**~-k*pow(n-k,n-k,M)%M)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/288/B" }
d7929
test
n, m = map(int, input().split()) vert = [] gor = [] for i in range(n): s = input() for j in range(m): if s[j] == 'B': vert.append(i) gor.append(j) vert.sort() gor.sort() print(vert[len(vert) // 2] + 1, gor[len(gor) // 2] + 1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1028/A" }
d7930
test
import sys #sys.stdin=open("data.txt") input=sys.stdin.readline mii=lambda:list(map(int,input().split())) n,m=mii() a=[[] for _ in range(n)] c=[123456 for _ in range(n)] for _ in range(m): u,v=mii() u%=n v%=n if v<u: v+=n a[u].append(v) if c[u]>v: c[u]=v ans=[] for i in list(range(1,n))+[0]: out=0 for j in range(i,n): if not a[j]: continue tmp=(j-i)+(len(a[j])-1)*n+(c[j]-j) out=max(out,tmp) #print(1,i,j,tmp) for j in range(i): if not a[j]: continue tmp=(j+n-i)+(len(a[j])-1)*n+(c[j]-j) out=max(out,tmp) #print(2,i,j,tmp) ans.append(out) print(" ".join(map(str,ans)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1129/A1" }
d7931
test
""" Codeforces Contest 284 Div 1 Problem A Author : chaotic_iak Language: Python 3.4.2 """ ################################################### SOLUTION def main(): x1,y1 = read() x2,y2 = read() n, = read() ct = 0 for i in range(n): a,b,c = read() if (a*x1+b*y1+c)*(a*x2+b*y2+c) < 0: ct += 1 print(ct) #################################################### HELPERS 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 list(map(int, inputs.split())) def write(s="\n"): if s is None: s = "" if isinstance(s, list): s = " ".join(map(str, s)) s = str(s) print(s, end="") write(main())
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/498/A" }
d7932
test
def grundy(n, k): if k % 2 == 0: if n <= 2: return n else: return n % 2 == 0 else: if n <= 4: return [0, 1, 0, 1, 2][n] elif n % 2 == 1: return 0 else: return 2 if grundy(n // 2, k) == 1 else 1 def __starting_point(): n, k = list(map(int, input().split())) xList = list(map(int, input().split())) res = 0 for x in xList: res ^= grundy(x, k) print("Kevin" if res else "Nicky") __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/603/C" }
d7933
test
n = int(input()) f = [int(x) - 1 for x in input().split()] p = [-1] * n g = [0] * n h = [0] * n m = 0 for i in range(n): if f[i] == i: p[i] = m h[m] = i + 1 m += 1 h = h[:m] for i in range(n): if p[f[i]] == -1: print(-1) return g[i] = p[f[i]] + 1 print(m) print(" ".join([str(x) for x in g])) print(" ".join([str(x) for x in h]))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/765/D" }
d7934
test
M = 10 ** 9 + 7 def solve1(x): n = len(x) x = int(x, 2) ans = 0 for a in range(2 ** n): for c in range(2 ** n): b = a ^ x d = c ^ x if a < c and b > d: ans += 1 return ans % M def solve2(x): return int(x, 2) * pow(2, (len(x) - 1), M) % M x = input() # print(solve1(x)) print(solve2(x))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/319/A" }
d7935
test
from collections import defaultdict m = 1000000007 f = [0] * 15001 f[0] = 1 for i in range(1, 15001): f[i] = (f[i - 1] * i) % m def c(n, k): return (f[n] * pow((f[k] * f[n - k]) % m, m - 2, m)) % m def prime(n): m = int(n ** 0.5) + 1 t = [1] * (n + 1) for i in range(3, m): if t[i]: t[i * i :: 2 * i] = [0] * ((n - i * i) // (2 * i) + 1) return [2] + [i for i in range(3, n + 1, 2) if t[i]] p = prime(31650) s = defaultdict(int) def g(n): for j in p: while n % j == 0: n //= j s[j] += 1 if j * j > n: s[n] += 1 break n = int(input()) - 1 a = list(map(int, input().split())) for i in a: g(i) if 1 in s: s.pop(1) d = 1 for k in list(s.values()): d = (d * c(k + n, n)) % m print(d)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/396/A" }
d7936
test
#!/usr/bin/env python3 n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) if n <= 3: print('YES') else: a.remove(0) b.remove(0) i = a.index(1) a = a[i:] + a[:i] i = b.index(1) b = b[i:] + b[:i] print(['NO','YES'][a == b])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/634/A" }
d7937
test
# Codeforces Round #488 by NEAR (Div. 2) import collections from functools import cmp_to_key #key=cmp_to_key(lambda x,y: 1 if x not in y else -1 ) import math import sys def getIntList(): return list(map(int, input().split())) import bisect def makePair(z): return [(z[i], z[i+1]) for i in range(0,len(z),2) ] N, = getIntList() za = getIntList() zb = getIntList() sa = set(za) xa = list(sa) xa.sort(reverse = True) zz = [(t, sorted([zb[i] for i in range(N) if za[i] == t]) ) for t in xa ] #print(zz) lastdp = [[] for i in range(52)] lastdp[0] = [(0,0)] def addres(z, t): if len(z) ==0: z.append(t) return i = bisect.bisect_right(z,t) if i>0 and z[i-1][1] >= t[1]: return if i<len(z) and t[1] >= z[i][1]: z[i] = t return z.insert(i,t) for x in zz: nowdp = [[] for i in range(52)] for i in range(len(lastdp)): tz = lastdp[i] if len( tz ) ==0 : continue num = len(x[1]) hide = min(i, num ) tb = sum(x[1]) acc =0; for j in range(hide + 1): la = x[0] * (num-j) lb = tb - acc if j<num: acc += x[1][j] for t in tz: # t = (0,0) tr = (t[0] + la, t[1] + lb) addres(nowdp[ i -j + num -j] ,tr) lastdp = nowdp #print(lastdp) res = 10 ** 20 for x in lastdp: for y in x: t = math.ceil(y[0] *1000 / y[1] ) res = min( res,t) print(res)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/993/D" }
d7938
test
from collections import defaultdict from bisect import bisect_left as lower import sys input = sys.stdin.readline def put(): return list(map(int, input().split())) try: n,m = put() cnt, mp, ans = [0]*n, defaultdict(), [0]*n for _ in range(n): x,y = put() x,y = x-1,y-1 key = (min(x,y), max(x,y)) if key in mp: mp[key]+=1 else: mp[key]=1 cnt[x]+=1 cnt[y]+=1 except: print('lol') for (x,y),val in list(mp.items()): if cnt[x]+cnt[y]>= m and cnt[x]+cnt[y]-val<m: ans[x]-=1 ans[y]-=1 scnt = cnt.copy() scnt.sort() for i in range(n): ans[i]+= n-lower(scnt, m-cnt[i]) if 2*cnt[i]>=m: ans[i]-=1 print(sum(ans)//2)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/420/C" }
d7939
test
def gcd(a, b): while b: a, b = b, a%b return a def gcda(a): ans = a[0] for i in range(1, len(a)): ans = gcd(a[i], ans) return ans n = int(input()) a = list(map(int, input().split())) if 1 in a: print(sum([1 for i in a if i != 1])) return if gcda(a) != 1: print(-1) return mr=n+1 for i in range(n): g = a[i] for j in range(i+1, n): g = gcd(g, a[j]) if g == 1: mr = min(mr, j-i) break print(mr + n - 1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/891/A" }
d7940
test
s = input() s = s[5:] if len(s) < 2: print(0) elif len(s) == 2: print(1) print(s) elif len(s) == 3: print(2) for suff in sorted([s, s[-2:]]): print(suff) else: D = [[False for _ in range(2)] for _ in range(len(s))] suffixes = { s[-2:], s[-3:] } D[-2][0] = True D[-3][1] = True for i in range(len(s) - 4, -1, -1): if (s[i:i+2] != s[i+2:i+4] and D[i+2][0]) or D[i+2][1]: D[i][0] = True suffixes |= { s[i:i+2] } if (i <= len(s) - 6 and s[i:i+3] != s[i+3:i+6] and D[i+3][1]) or D[i+3][0]: D[i][1] = True suffixes |= { s[i:i+3] } print(len(suffixes)) for suffix in sorted(suffixes): print(suffix)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/666/A" }
d7941
test
#!/usr/bin/env python3 # # Three States # import sys, os from collections import deque from pprint import pprint def read_ints(): return list(map(int, input().split())) def read_str(): return input().strip() n, m = read_ints() s = [read_str() for _ in range(n)] t = [set(), set(), set()] for i in range(n): for j in range(m): if s[i][j] in '123': for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: if 0 <= ii < n and 0 <= jj < m: if s[ii][jj] in '123.' and s[i][j] != s[ii][jj]: t[int(s[i][j]) - 1].add((i, j)) break z = [[[1e18] * 3 for j in range(m)] for i in range(n)] ans = 1e18 for root in range(3): q = deque() vi = [[False] * m for _ in range(n)] for i, j in t[root]: q.append((i, j, 0)) vi[i][j] = True z[i][j][root] = 0 dist = [1e18] * 3 dist[root] = 0 while q: i, j, d = q.popleft() for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: if 0 <= ii < n and 0 <= jj < m and not vi[ii][jj]: if s[ii][jj] == '.': vi[ii][jj] = True q.append((ii, jj, d + 1)) z[ii][jj][root] = min(z[ii][jj][root], d + 1) elif s[ii][jj] != s[i][j] and s[ii][jj] in '123': dist[int(s[ii][jj]) - 1] = min(dist[int(s[ii][jj]) - 1], d) ans = min(ans, sum(dist)) if ans >= 1e18: print(-1) else: for i in range(n): for j in range(m): if s[i][j] == '.': ans = min(ans, sum(z[i][j]) - 2) print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/590/C" }
d7942
test
__, s = input(), input() a, n = 0, 0 pt = {'(': 1, ')': -1} for c in s: da = pt.get(c, 0) if a < 0 or a + da < 0: n += 1 a += da if a != 0: print(-1) else: print(n)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1322/A" }
d7943
test
import sys # sys.stind.readline lee datos el doble de # rápido que la funcion por defecto input input = sys.stdin.readline length = len def get_input(): n, m, h = [int(x) for x in input().split(' ')] digraph = [[] for _ in range(n + 1)] transpose = [[] for _ in range(n + 1)] mantainence = [0] + [int(x) for x in input().split(' ')] for _ in range(m): c1, c2 = [int(x) for x in input().split(' ')] if (mantainence[c1] + 1) % h == mantainence[c2]: digraph[c1].append(c2) transpose[c2].append(c1) if (mantainence[c2] + 1) % h == mantainence[c1]: digraph[c2].append(c1) transpose[c1].append(c2) return digraph, transpose def dfs_cc_1_visit(graph, node, color, finalization_stack): stack = [node] while stack: current_node = stack[-1] if color[current_node] != 'white': stack.pop() if color[current_node] == 'grey': finalization_stack.append(current_node) color[current_node] = 'black' continue color[current_node] = 'grey' for adj in graph[current_node]: if color[adj] == 'white': stack.append(adj) def dfs_cc_1(graph): n = length(graph) finalization_stack = [] color = ['white'] * n for i in range(1, n): if color[i] == 'white': dfs_cc_1_visit(graph, i, color, finalization_stack) return finalization_stack def dfs_cc_2_visit(graph, node, color, scc, component): stack = [node] while stack: current_node = stack[-1] if color[current_node] != 'white': stack.pop() color[current_node] = 'black' scc[current_node] = component continue color[current_node] = 'grey' for adj in graph[current_node]: if color[adj] == 'white': stack.append(adj) def dfs_cc_2(graph, stack_time): n = length(graph) color = ['white'] * n scc = [0] * n component = 0 while stack_time: current_node = stack_time.pop() if color[current_node] == 'white': dfs_cc_2_visit(graph, current_node, color, scc, component) component += 1 return scc, component def strongly_connected_components(digraph, transpose): stack_time = dfs_cc_1(digraph) scc, max_component = dfs_cc_2(transpose, stack_time) # create the components out_deg = [0] * max_component scc_nodes = [[] for _ in range(max_component)] for node in range(1, length(digraph)): scc_nodes[scc[node]].append(node) for adj in digraph[node]: if scc[node] != scc[adj]: out_deg[scc[node]] += 1 # searching minimum strongly connectected component with out degree 0 minimum_component = None for i, value in enumerate(out_deg): if value == 0 and (minimum_component is None or length(scc_nodes[i]) < length(scc_nodes[minimum_component])): minimum_component = i # return the size of the component and the nodes return length(scc_nodes[minimum_component]), scc_nodes[minimum_component] def __starting_point(): digraph, transpose = get_input() count, nodes = strongly_connected_components(digraph, transpose) print(count) print(' '.join([str(x) for x in nodes])) __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/949/C" }
d7944
test
N, M = list(map(int, input().split())) P = 10**9+7 F = [1, 2] for i in range(101010): F.append((F[-1]+F[-2])%P) print((F[N-1]+F[M-1]-1)*2%P)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1239/A" }
d7945
test
import itertools def f(n): return n * (n - 1) / 2 + 1 if n % 2 else n * (n - 1) / 2 + n / 2 n, m = list(map(int, input().split())) table = sorted([int(input().split()[1]) for _ in range(m)], reverse = True) ans = 1 while f(ans) <= n: ans += 1 ans -= 1 print(list(itertools.accumulate(table))[min(ans - 1, m - 1)])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/367/C" }
d7946
test
import sys #sys.stdin=open("data.txt") input=sys.stdin.readline mii=lambda:list(map(int,input().split())) s=input().strip() d=[0]*1000 e=[0]*1000 hist=[0]*26 for i in s: j=ord(i)-ord('a') for k in range(26): e[k*26+j]+=hist[k] hist[j]+=1 d[j]+=1 print(max(d+e))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1307/C" }
d7947
test
n = int(input()) a = 1 while n % a == 0: a *= 3 print((n - 1) // a + 1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/333/A" }
d7948
test
import sys def solve(): n = int(input()) partner = [0]*(2*n) pacani = [] for line in sys.stdin: pacan, telka = [int(x) - 1 for x in line.split()] partner[pacan] = telka partner[telka] = pacan pacani.append(pacan) khavka = [None]*(2*n) for i in range(2*n): while khavka[i] is None: khavka[i] = 1 khavka[i^1] = 2 i = partner[i^1] for pacan in pacani: print(khavka[pacan], khavka[partner[pacan]]) solve()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/741/C" }
d7949
test
#!/usr/bin/env python3 n = int(input()) arr = [] for i in range(n): arr.append(1) while len(arr)>=2 and arr[-1] == arr[-2]: a, b = arr.pop(), arr.pop() arr.append(a+1) print(' '.join(map(str, arr)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/618/A" }
d7950
test
#!/usr/bin/env python3 def main(): import collections n = int(input()) s = input() alph = collections.Counter(s) odd = sum(x & 0x1 for x in alph.values()) dq = collections.deque() if odd == 0: print(1) for c, x in alph.items(): dq.append(c * (x >> 1)) dq.appendleft(c * (x >> 1)) print(*dq, sep="") else: for odd in range(odd, n): if (n - odd) % (odd << 1) == 0: print(odd) odds = [c for c, x in alph.items() if x & 0x1] items = list(alph.items()) while len(odds) != odd: for i, x in enumerate(items): if x[1] > 1: items[i] = (x[0], x[1] - 2) odds.append(x[0]) odds.append(x[0]) break req_length = (n - odd) // odd + 1 cur_length = 0 while odd > 0: if cur_length == 0: dq.append(odds[-1]) cur_length += 1 odds.pop() x = min(items[-1][1] >> 1, (req_length - cur_length) >> 1) dq.append(items[-1][0] * x) dq.appendleft(items[-1][0] * x) cur_length += x << 1 if items[-1][1] - (x << 1) <= 1: items.pop() else: items[-1] = (items[-1][0], items[-1][1] - (x << 1)) if cur_length == req_length: print(*dq, sep="", end=' ') odd -= 1 dq.clear() cur_length = 0 print() break else: print(n) print(*s) try: while True: main() except EOFError: pass
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/883/H" }
d7951
test
N = int(input()) p = input() M = int(input()) words = [input() for _ in range(M)] cnt = 0 letters = [set() for _ in range(M)] used = set() for c in p: used.add(c) fail = [False]*M for i, w in enumerate(words): for j, c in enumerate(w): if p[j] == '*': letters[i].add(c) if c in used: fail[i] = True elif p[j] != c: fail[i] = True for i in range(26): ch = chr(ord('a') + i) ok = True for i, s in enumerate(letters): ok = ok and (ch in s or fail[i]) if ok: cnt += 1 print(cnt)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/883/E" }
d7952
test
read = lambda: list(map(int, input().split())) n, d, b = read() d += 1 t, a = 0, [0] * (n + 1) for i, x in enumerate(read()): t += x a[i + 1] = t print(max(i - min(a[min(n, i * d)], (a[n] - a[max(0, n - i * d)])) // b for i in range(n + 3 >> 1)))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/949/D" }
d7953
test
def primes2(limit): if limit < 2: return [] if limit < 3: return [2] lmtbf = (limit - 3) // 2 buf = [True] * (lmtbf + 1) for i in range((int(limit ** 0.5) - 3) // 2 + 1): if buf[i]: p = i + i + 3 s = p * (i + 1) + i buf[s::p] = [False] * ((lmtbf - s) // p + 1) return [2] + [i + i + 3 for i, v in enumerate(buf) if v] ps = primes2(12*10**6) def rub2(n): lst_odd = [] lst_even = [] for head in range(1, n): head_str = str(head) tail_str = head_str[::-1] lst_even.append(int(head_str + tail_str)) lst_odd.append(int(head_str[:-1] + tail_str)) lst = lst_odd + lst_even lst.sort() return lst rs = rub2(12*10**2) p, q = map(int, input().split()) idxp = len(ps) - 1 idxr = len(rs) - 1 pi = ps[idxp] ri = rs[idxr] while q * (idxp + 1) > p * (idxr + 1): if pi < ri: idxr -= 1 elif pi > ri: idxp -= 1 else: idxr -= 1 idxp -= 1 prev_pi = pi prev_ri = ri pi = ps[idxp] ri = rs[idxr] print(max(prev_pi-1, prev_ri-1))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/568/A" }
d7954
test
T = 1 for test_no in range(T): MAXK = 5000 n = int(input()) cnt = [0] * (MAXK + 1) primeExponential = [[0 for j in range(MAXK + 1)] for i in range(MAXK + 1)] line, num = (input() + ' '), 0 for c in line: if c != ' ': num = num * 10 + (ord(c) - 48) else: cnt[num] += 1 num = 0 for i in range(2, MAXK + 1): for j in range(0, MAXK + 1): primeExponential[i][j] += primeExponential[i-1][j] tmp, x = i, 2 while x * x <= tmp: while tmp % x == 0: primeExponential[i][x] += 1 tmp //= x x += 1 if tmp > 1: primeExponential[i][tmp] += 1 bestPD = [1] * (MAXK + 1) ans, cur = 0, 0 for i in range(1, MAXK + 1): if cnt[i] == 0: continue for j in range(1, MAXK + 1): ans += primeExponential[i][j] * cnt[i] cur += primeExponential[i][j] * cnt[i] if primeExponential[i][j]: bestPD[i] = j frequency = [0] * (MAXK + 1) while max(bestPD) > 1: for i in range(MAXK + 1): frequency[i] = 0 for i in range(MAXK + 1): frequency[bestPD[i]] += cnt[i] bestGroup = max(frequency) bestPrime = frequency.index(bestGroup) if bestGroup * 2 <= n: break if bestPrime == 1: break cur -= bestGroup cur += (n - bestGroup); ans = min(ans, cur) for i in range(MAXK + 1): if bestPD[i] != bestPrime: bestPD[i] = 1 if bestPD[i] == 1: continue primeExponential[i][bestPD[i]] -= 1 while bestPD[i] > 1 and primeExponential[i][bestPD[i]] == 0: bestPD[i] -= 1 print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1292/D" }
d7955
test
from sys import stdin, stdout INF = int(1e9) class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def distance(p1, p2): x = p1.x - p2.x y = p1.y - p2.y return x*x + y*y def bruteForce(point_set, left, right): min_dist = INF for i in range(left, right): for j in range(i+1, right): min_dist = min(min_dist, distance(point_set[i], point_set[j])) return min_dist def stripClosest(point_set, left, right, mid, min_dist): point_mid = point_set[mid] splitted_points = [] for i in range(left, right): if (point_set[i].x - point_mid.x) ** 2 <= min_dist: splitted_points.append(point_set[i]) splitted_points.sort(key=lambda point: point.y) l = len(splitted_points) smallest = INF for i in range(l): for j in range(i+1, l): if (splitted_points[i].y - splitted_points[j].y) ** 2 >= min_dist: break d = distance(splitted_points[i], splitted_points[j]) smallest = min(smallest, d) return smallest def closestUtil(point_set, left, right): if right - left <= 3: return bruteForce(point_set, left, right) mid = (left + right) // 2 dist_left = closestUtil(point_set, left, mid) dist_right = closestUtil(point_set, mid+1, right) dist_min = min(dist_left, dist_right) return min(dist_min, stripClosest(point_set, left, right, mid, dist_min)) n = int(stdin.readline()) a = list(map(int, stdin.readline().split())) pref = [0] for i in range(n): pref.append(pref[i] + a[i]) point_set = [] for i in range(n): point_set.append(Point(i, pref[i+1])) ans = closestUtil(point_set, 0, n) stdout.write(str(ans))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/429/D" }
d7956
test
n, k1, k2 = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) r = sorted([abs(a[i] - b[i]) for i in range(n)], reverse=True) for it in range(k1 + k2): if r[0] == 0: r[0] = 1 else: r[0] -= 1 for i in range(n - 1): if r[i] < r[i + 1]: r[i], r[i + 1] = r[i + 1], r[i] print(sum(x**2 for x in r))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/960/B" }
d7957
test
#!/usr/bin/env python3 M = 10 ** 9 + 7 def solve(n, m, s, lst): cnt = [0] * n t = 0 for i in range(n): if s[i] == '1': t += 1 cnt[i] = t dp = [[0] * (n + 1) for _ in range(n + 1)] dp[0][0] = 1 r = 0 j = 0 for i in range(n): while j < m: lj, rj = lst[j] if lj <= i: r = max(r, rj) j += 1 else: break if r <= i: c = cnt[i] if 0 < c: dp[i + 1][cnt[i]] = (dp[i][c] + dp[i][c - 1]) % M else: dp[i + 1][0] = dp[i][0] else: for k in range(max(0, cnt[r] - r + i), min(i + 1, cnt[r]) + 1): if 0 < k: dp[i + 1][k] = (dp[i][k] + dp[i][k - 1]) % M else: dp[i + 1][0] = dp[i][0] return dp[n][cnt[n - 1]] def main(): n, m = input().split() n = int(n) m = int(m) s = input() lst = [] for _ in range(m): l, r = input().split() l = int(l) - 1 r = int(r) - 1 lst.append((l, r)) print((solve(n, m, s, lst))) def __starting_point(): main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc065/tasks/arc065_d" }
d7958
test
As = list(map(int, input().split())) def solve(As): L = As[0] + As[1] + As[2] return L**2 - As[0]**2 - As[2]**2 - As[4]**2 print(max(solve(As), solve(As[1:] + [As[0]])))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/559/A" }
d7959
test
n = 100001 p = [0] * n t = [[] for i in range(n)] t[1] = [1] for i in range(2, n): if not t[i]: t[i] = [i] for j in range(2 * i, n, i): t[j].append(i) input() a = list(map(int, input().split())) for i in a: x = max(p[j] for j in t[i]) + 1 for j in t[i]: p[j] = x print(max(p))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/264/B" }
d7960
test
def flatten(grid): k = len(grid[0]) // 2 seek = list(range(2*k + 2)) + list(range(2*k + 2, 4*k + 2))[::-1] return [seek[v] for v in grid[0] + grid[1][::-1] if v] def solve(grid): grid = list(map(list, grid)) k = len(grid[0]) // 2 flat = flatten(grid) m = { 'L': 'l'*2*k + 'u' + 'r'*2*k + 'd', 'R': 'u' + 'l'*2*k + 'd' + 'r'*2*k, 'C': 'l'*k + 'u' + 'r'*k + 'd', 'D': 'CC' + 'R'*(2*k + 1) + 'CC' + 'R'*(2*k + 2), 'F': 'R'*(k - 1) + 'DD' + 'R'*(2*k + 1) + 'D' + 'L'*2*k + 'DD' + 'L'*k, 'G': 'FF', } [(i, j)] = [(i, j) for i in range(2) for j in range(2*k + 1) if grid[i][j] == 0] st = 'r'*(2*k - j) + 'd'*(1 - i) for v in range(2, 4*k + 2): ct = flat.index(v) if ct >= 2: st += 'L'*(ct - 2) + 'GR'*(ct - 2) + 'G' flat = flat[ct - 1: ct + 1] + flat[:ct - 1] + flat[ct + 1:] if ct >= 1: st += 'G' flat = flat[1:3] + flat[:1] + flat[3:] st += 'L' flat = flat[1:] + flat[:1] if flat[0] == 1: return st, m def main(): def get_line(): return [0 if x == 'E' else int(x) for x in input().split()] for cas in range(int(input())): k = int(input()) grid = [get_line() for i in range(2)] assert all(len(row) == 2*k + 1 for row in grid) res = solve(grid) if res is None: print('SURGERY FAILED') else: print('SURGERY COMPLETE') st, m = res print(st) for shortcut in list(m.items()): print(*shortcut) print('DONE') main()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1280/F" }
d7961
test
# python3 # utf-8 n, a, b = (int(x) for x in input().split()) l = -1 for k in range(n // a + 1): if (n - k * a) % b == 0: l = (n - k * a) // b break if l == -1: print(-1) quit() perm = [] curr_last_op = 1 for i in range(k): curr_cycle = [curr_last_op + j for j in range(a)] curr_last_op = curr_last_op + a perm += curr_cycle[1:] + curr_cycle[:1] for i in range(l): curr_cycle = [curr_last_op + j for j in range(b)] curr_last_op = curr_last_op + b perm += curr_cycle[1:] + curr_cycle[:1] print(*perm)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/932/C" }
d7962
test
n,k=list(map(int,input().split())) arr=list(map(int,input().split())) ans=arr[0]//k val=arr[0]%k for i in range(1,n): if(val==0): ans+=arr[i]//k val=arr[i]%k else: val+=arr[i] if(val<k): val=0 ans+=1 else: ans+=val//k val=val%k if(val!=0): ans+=1 print(ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1070/D" }
d7963
test
#!/bin/python3 a = input() a = a + a ma = 1 last = 'x' pos = 0 cur = 0 while pos < len(a): if a[pos] != last: cur += 1 ma = max(ma, cur) else: cur = 1 last = a[pos] pos += 1 print(min(ma, len(a) // 2))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1025/C" }
d7964
test
def main(): n,m = list(map(int, input().split())) r,c = list(map(int, input().split())) L,R = list(map(int, input().split())) lab = [input() for _ in range(n)] r -= 1 c -= 1 inf = n*m+1 dist = [[inf] * m for _ in range(n)] dist[r][c] = 0 Q = [(r,c)] for x,y in Q: d = dist[x][y] if x < n - 1 and dist[x + 1][y] > d and lab[x + 1][y] == '.': dist[x + 1][y] = d Q.append((x + 1, y)) if 0 < x and dist[x - 1][y] > d and lab[x - 1][y] == '.': dist[x - 1][y] = d Q.append((x - 1, y)) if 0 < y and dist[x][y - 1] > d and lab[x][y - 1] == '.': dist[x][y - 1] = d + 1 Q.append((x, y - 1)) if y < m - 1 and dist[x][y + 1] > d and lab[x][y + 1] == '.': dist[x][y + 1] = d + 1 Q.append((x, y + 1)) ans=0 for i in range(n): for j in range(m): d = dist[i][j] if d < inf: right = (d + (j - c))//2 left = (d - (j - c))//2 if right <= R and left <= L: ans+=1 print(ans) main() #Code By:pajenegod
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1063/B" }
d7965
test
from collections import defaultdict def calcBinomials(N): nonlocal binom N += 1 binom = [[0]*N for _ in range(N)] for n in range(N): binom[n][0] = binom[n][n] = 1 for k in range(1, n): binom[n][k] = binom[n-1][k] + binom[n-1][k-1] n = int(input()) a = list(map(int, input().split())) S, res = sum(a), 0 dp = [defaultdict(lambda: 0) for _ in range(S+1)] dp[0][0] = 1 cnt = {_:a.count(_) for _ in a} for x in a: for i in range(len(dp)-1-x, -1, -1): for k, v in list(dp[i].items()): dp[i+x][k+1] += v calcBinomials(n) for x, c in list(cnt.items()): for i in range(1, c+1): if dp[x*i][i] == binom[c][i] or dp[S - x*i][n-i] == binom[c][c-i]: res = max(res, i) if len(cnt) <= 2: res = n print(res)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1078/B" }
d7966
test
def f(x): z=[0 for i in range(len(x))] l=0 r=0 for i in range(1,len(x)): if i<=r: z[i]=min(z[i-l],r-i+1) while i+z[i]<len(x) and x[z[i]]==x[i+z[i]]: z[i]+=1 if i+z[i]-1>r: l,r=i,i+z[i]-1 return z a=list(map(int,input('').split())) n,a,b=a[0],a[1],a[2] s=input('') dp=[0 for i in range(n)] dp[0]=a for i in range(1,n): t=s[:i+1] dp[i]=dp[i-1]+a q=f(t[::-1]) maxs=[0 for j in range(i+1)] maxs[0]=q[i] for j in range(1,i): maxs[j]=max(maxs[j-1],q[i-j]) for j in range(i): if maxs[j]>=i-j: dp[i]=min(dp[i],dp[j]+b) print(dp[len(dp)-1])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1120/C" }
d7967
test
mod = 1000000007 eps = 10**-9 def main(): import sys input = sys.stdin.readline N, K = list(map(int, input().split())) if K == 1: if N == 1: print((1)) else: print((pow(2, N - 2, mod))) return dp = [[0] * (N+1) for _ in range(K-1)] for j in range(2, N+1): dp[0][j] = 1 for i in range(1, K-1): cs = [0] * (N+1) for j in range(1, N+1): cs[j] = (cs[j-1] + dp[i-1][j])%mod for j in range(2, N+1): if j != N - i + 1: dp[i][j] = (dp[i][j] + dp[i-1][j])%mod dp[i][j] = (dp[i][j] + cs[-1] - cs[j])%mod ans = 0 for j in range(2, N+1): ans = (ans + dp[-1][j])%mod if K != N: ans = (ans * pow(2, N - K - 1, mod))%mod print(ans) def __starting_point(): main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc068/tasks/arc068_d" }
d7968
test
n, k = list(map(int, input().split())) A = list(map(int, input().split())) cumsum = [0] for a in A: cumsum.append(cumsum[-1] + a) #print(cumsum) pows = set([k**i for i in range(50)]) cum = dict({}) cum[0] = 1 res = 0 for x in cumsum[1:]: for pow in pows: if (x - pow) in cum: res += cum[x - pow] if x in cum: cum[x] += 1 else: cum[x] = 1 print(res)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/776/C" }
d7969
test
def main(): trips, reg, cheap, cards, card_cost = list(map(int, input().split())) costs = [] indexes = {} total = 0 last = "" for i in range(trips): a, b = input().split() pair = (min(a, b), max(a, b)) if pair in indexes: index = indexes[pair] else: costs.append(0) indexes[pair] = len(costs) - 1 index = len(costs) - 1 total += (cheap if a == last else reg) costs[index] += (cheap if a == last else reg) last = b costs = sorted(costs, reverse = True) for c in costs: if c < card_cost or cards <= 0: break total -= c total += card_cost cards -= 1 print(total) main()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/847/K" }
d7970
test
def DFS(x): for i in range(x): if(Seen[i][x]): continue if(Rem[i]>=C[x]): if(Rem[i]==C[x] and len(Children[i])==0): continue Rem[i]-=C[x] Parent[x]=i Children[i].append(x) return True for i in range(x): if(Seen[i][x]): continue Y=[] for j in range(len(Children[i])): child=Children[i][j] Parent[child]=-1 Rem[i]+=C[child] Seen[i][child]=True Seen[child][i]=True if(DFS(child)): Seen[i][child]=False Seen[child][i]=False continue Seen[i][child]=False Seen[child][i]=False Parent[child]=i Rem[i]-=C[child] Y.append(child) Children[i]=list(Y) if(Rem[i]>=C[x]): if(Rem[i]==C[x] and len(Children[i])==0): continue Rem[i]-=C[x] Children[i].append(x) Parent[x]=i return True return False n=int(input()) C=list(map(int,input().split())) Rem=[-1]*n Parent=[-1]*n Children=[] Seen=[] for i in range(n): Seen.append([False]*n) C.sort(reverse=True) if(C[0]!=n or C.count(2)>0): print("NO") else: for i in range(n): Rem[i]=C[i]-1 Children.append([]) Parent[0]=0 Ans="YES" for i in range(1,n): if(DFS(i)==False): Ans="NO" break for i in range(n): if(Rem[i]!=0 and C[i]!=1): Ans="NO" break print(Ans)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/429/C" }
d7971
test
count = int(input()) array = list(map(int, input().split())) diff = array[0] - array[1] holds = True for index in range(1, len(array)-1): if array[index] - array[index+1] != diff: holds = False if holds: print(array[-1] - (array[-2] - array[-1])) else: print(array[-1])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/847/M" }
d7972
test
import getpass import sys if getpass.getuser() != 'frohenk': filename = 'half' # sys.stdin = open('input.txt') # sys.stdout = open('output.txt', 'w') else: sys.stdin = open('input.txt') # sys.stdin.close() import math import string import re import random from decimal import Decimal, getcontext from collections import deque mod = 10 ** 9 + 7 def ria(): return [int(i) for i in input().split()] n=ria()[0] ar=[0]*n for i in range(n-1): a,b=ria() a-=1 b-=1 ar[a]+=1 ar[b]+=1 print('NO' if ar.count(2) else 'YES')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1188/A1" }
d7973
test
n = int(input()) b = [int(x) for x in input().strip().split()] result = {} for x in b: tmp = x cnt = 0 while tmp & 1 == 0: cnt += 1 tmp >>= 1 if cnt not in result: result[cnt] = [] result[cnt].append(x) res1 = max([len(result[x]) for x in result]) print(n - res1) if n == res1: return res2 = None for x in result: if len(result[x]) == res1: res2 = x break res3 = [] for x in result: if x != res2: for y in result[x]: res3.append(str(y)) print(' '.join(res3))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1220/D" }
d7974
test
N=int(input()) l="" mod=10**9+7 Sa=list(input()) Sb=list(input()) for i in range(N): if Sa[i]==Sb[i]: l+="X" else: l+="Y" l=l.replace("YY","Y") ans=6 if l[0]=="Y" else 3 for i in range(1,len(l)): if l[i]=="Y" and l[i-1]=="Y": ans*=3 if l[i]=="X" and l[i-1]=="X": ans*=2 if l[i]=="Y" and l[i-1]=="X": ans*=2 ans=ans%mod print(ans)
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc081/tasks/arc081_b" }
d7975
test
''' Created on Aug 28, 2016 @author: Md. Rezwanul Haque ''' def gcd(a,b): if b == 0: return a return gcd(b, a%b) def extend_euclid(a,b): if b == 0: return 1,0 else: y,x = extend_euclid(b, a%b) y = y - (a//b)*x return x,y n,m,k = map(int,input().split()) a = list(map(int,input().split())) lcm = 1 for i in a: lcm = (lcm*i)//gcd(lcm, i) if lcm>n: print('NO') return j = 0 m1 = 1 s = True for i in range(k): x,y = extend_euclid(m1, a[i]) res = m1*x + a[i]*y if (-i-j)%res != 0: s = False break res = (-i-j)//res x,y = x*res , y*res j += m1*x t = m1*a[i] if j>t: j -= (j//t)*t if j<0: j += ((-j+t-1)//t)*t if j == 0: j = t m1 = (m1*a[i])//gcd(m1, a[i]) if j+k-1 >m or s == False: print('NO') return b = [gcd(lcm, j+i) for i in range(k)] for i in range(k): if (a[i] != b[i]): print('NO') return print('YES')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/338/D" }
d7976
test
import sys from collections import defaultdict class MaxFlow(object): def __init__(self): self.edges = defaultdict(lambda: defaultdict(lambda: 0)) def add_edge(self, u, v, capacity=float('inf')): self.edges[u][v] = capacity def bfs(self, s, t): open_q = [s] visited = set() parent = dict() while open_q: close_q = [] for node in open_q: for v, capacity in list(self.edges[node].items()): if v not in visited and capacity > 0: close_q.append(v) parent[v] = node visited.add(v) if v == t: result = [] n2 = v n1 = node while n1 != s: result.append((n1, n2)) n2 = n1 n1 = parent[n1] result.append((n1, n2)) return result open_q = close_q return None def solve(self, s, t): flow = 0 route = self.bfs(s, t) while route is not None: new_flow = float('inf') for _, (n1, n2) in enumerate(route): new_flow = min(new_flow, self.edges[n1][n2]) for _, (n1, n2) in enumerate(route): self.edges[n1][n2] -= new_flow self.edges[n2][n1] += new_flow flow += new_flow route = self.bfs(s, t) return flow def __str__(self): result = "{ " for k, v in list(self.edges.items()): result += str(k) + ":" + str(dict(v)) + ", " result += "}" return result def main(): (n, m) = tuple([int(x) for x in input().split()]) r = [] xs = set() ys = set() for i in range(m): (x1, y1, x2, y2) = tuple(int(x) for x in input().split()) r.append((x1, y1, x2, y2)) xs.add(x1) xs.add(x2 + 1) ys.add(y1) ys.add(y2 + 1) xx = sorted(xs) yy = sorted(ys) xsize = len(xs) ysize = len(ys) grid = [] for i in range(ysize): grid.append([False] * xsize) for rect in r: x1 = rect[0] y1 = rect[1] x2 = rect[2] y2 = rect[3] for i, y in enumerate(yy): for j, x in enumerate(xx): if x1 <= x and y1 <= y and x2 >= x and y2 >= y: grid[i][j] = True f = MaxFlow() for i in range(len(yy)): for j in range(len(xx)): if grid[i][j]: f.add_edge(1 + i, len(yy) + 1 + j, float('inf')) for i in range(len(yy) - 1): f.add_edge(0, i + 1, yy[i + 1] - yy[i]) for i in range(len(xx) - 1): f.add_edge(len(yy) + 1 + i, len(xx) + len(yy) + 1, xx[i + 1] - xx[i]) # print(xx) # print(yy) # print(f) print(f.solve(0, len(xx) + len(yy) + 1)) def __starting_point(): main() __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1198/E" }
d7977
test
import sys input = lambda: sys.stdin.readline().rstrip() T = int(input()) for _ in range(T): N, K = list(map(int, input().split())) A = [int(a) for a in input().split()] if K not in A: print("no") continue if N == 1 or (A[0] >= K and A[1] >= K): print("yes") continue for i in range(2, N): if A[i] >= K and (A[i-1] >= K or A[i-2] >= K): print("yes") break else: print("no") continue
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1349/B" }
d7978
test
f=lambda : list(map(int,input().split())) n,m=f() lr=lambda x: x[1]-x[0]+1 sq=min(lr(f()) for _ in range(m)) print(sq) x=' '.join([str(i%sq) for i in range(n)]) print(x)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/739/A" }
d7979
test
import sys import collections n, m = list(map(int, input().split())) r = tuple(map(int, input().split())) controls = [tuple(map(int, input().split()))[1:] for i in range(m)] class DSU: def __init__(self): self.parent = None self.has_zero = False self.has_one = False self.size = 1 self.doors = [] def get_root(self): if self.parent is None: return self self.parent = self.parent.get_root() return self.parent def unite(self, s): r1 = self.get_root() r2 = s.get_root() if r1 is r2: return r1 if r1.size < r2.size: r1, r2 = r2, r1 r2.parent = r1 r1.size += r2.size r1.has_zero = r1.has_zero or r2.has_zero r1.has_one = r1.has_one or r2.has_one return r1 door_dsus = [[] for i in range(n)] for doors in controls: n = DSU() for door in doors: n.doors.append(door - 1) door_dsus[door - 1].append(n) if r[door - 1]: n.has_one = True if not r[door - 1]: n.has_zero = True for door, is_open in enumerate(r): n1, n2 = door_dsus[door] if is_open: n1.unite(n2) G = {} for door, is_open in enumerate(r): if is_open: continue n1, n2 = door_dsus[door] if n1.get_root() is n2.get_root(): print("NO") return G.setdefault(n1.get_root(), set()).add(n2.get_root()) G.setdefault(n2.get_root(), set()).add(n1.get_root()) color = {} for v in list(G.keys()): if v in color: continue color[v] = False q = collections.deque([v]) while q: v = q.popleft() c = color[v] for adj_v in G[v]: if adj_v in color: if color[adj_v] != (not c): print("NO") return else: color[adj_v] = not c q.append(adj_v) print("YES")
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/776/D" }
d7980
test
s = input() last = s.rfind('#') dif = s.count('(')-s.count(')')-s.count('#') try: assert dif >= 0 lev = 0 out = [] for i in range(len(s)): c = s[i] if c == '(': lev += 1 elif c == ')': lev -= 1 assert lev >= 0 elif c == '#': lev -= 1 if i == last: out.append(dif+1) lev -= dif else: out.append(1) assert lev >= 0 assert lev == 0 for x in out: print(x) except AssertionError: print(-1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/494/A" }
d7981
test
a,b=[int(i) for i in input().split()] if(a==0): print(-b**2) print('x'*b) elif(b==0): print(a**2) print('o'*a) elif(b==1): print(a**2-1) print('x'+'o'*a) else: ans=-float('inf') gr_no=None for i in range(2,min(a+2,b+1)): v1=(a+2-i)**2 + i-2 quo=b//i rem=b%i v2=rem*((quo+1)**2) + (i-rem)*((quo**2)) if(v1-v2>ans): gr_no=i ans=v1-v2 quo=b//gr_no rem=b%gr_no if(rem>0): s='x'*(quo+1)+'o'*(a+2-gr_no) rem-=1 else: s='x'*(quo)+'o'*(a+2-gr_no) gr_no-=1 s1='x'*(quo+1)+'o' s2='x'*quo + 'o' for i in range(rem): s+=s1 for i in range(gr_no-rem-1): s+=s2 s+='x'*(quo) print(ans) print(s)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/398/A" }
d7982
test
import sys input = sys.stdin.readline import numpy as np MOD = 10**9 + 7 N,M,K = map(int,input().split()) def cumprod(arr): L = len(arr); Lsq = int(L**.5+1) arr = np.resize(arr,Lsq**2).reshape(Lsq,Lsq) for n in range(1,Lsq): arr[:,n] *= arr[:,n-1]; arr[:,n] %= MOD for n in range(1,Lsq): arr[n] *= arr[n-1,-1]; arr[n] %= MOD return arr.ravel()[:L] U = 10**6 x = np.full(U,2,dtype=np.int64); x[0] = 1 pow2 = cumprod(x) x = np.full(U,3,dtype=np.int64); x[0] = 1 pow3 = cumprod(x) x = np.full(U,pow(2,MOD-2,MOD),dtype=np.int64); x[0] = 1 pow2_inv = cumprod(x) x = np.full(U,pow(3,MOD-2,MOD),dtype=np.int64); x[0] = 1 pow3_inv = cumprod(x) x = np.arange(U,dtype=np.int64); x[0] = 1 fact = cumprod(x) x = np.arange(U,0,-1,dtype=np.int64); x[0] = pow(int(fact[-1]),MOD-2,MOD) fact_inv = cumprod(x)[::-1] L = N+M A = np.zeros(N+M,dtype=np.int64) A[1:L] = (-1) * pow2[0:L-1] * pow3_inv[0:L-1] % MOD A[1:L] *= fact[K+1:K+L] * fact_inv[K] % MOD * fact_inv[1:L] % MOD; A %= MOD A[1:L] *= pow3_inv[K+1]; A %= MOD A[0] = 3 * (1 - pow3_inv[K+1]) % MOD * pow2_inv[1] % MOD np.cumsum(A,out=A); A %= MOD A *= pow3[:L]; A %= MOD A *= pow2_inv[:L]; A %= MOD comb = fact[N-1:N+M] * fact_inv[:M+1] % MOD * fact_inv[N-1] % MOD answer = (comb * pow3[K+M:K-1:-1] % MOD * A[N-1:N+M] % MOD).sum() % MOD print(answer)
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc061/tasks/arc061_d" }
d7983
test
import heapq import sys from collections import defaultdict, Counter from functools import reduce n, m = list(map(int, input().split())) arr = [] for _ in range(n): arr.append(list(map(int, input().split()))) rows = [] for i in range(n): row = set() for j in range(m): row.add(arr[i][j]) rows.append({x: i for i, x in enumerate(sorted(row))}) columns = [] for j in range(m): column = set() for i in range(n): column.add(arr[i][j]) columns.append({x: i for i, x in enumerate(sorted(column))}) def get_answer(i, j): el = arr[i][j] index1 = rows[i][el] index2 = columns[j][el] return max(index1, index2) + max(len(rows[i]) - index1, len(columns[j]) - index2) for i in range(n): answer = [] for j in range(m): answer.append(str(get_answer(i, j))) print(' '.join(answer))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1137/A" }
d7984
test
P = 998244353 N, M = list(map(int, input().split())) A = [int(a) for a in input().split()] B = [int(a) for a in input().split()] li = sum([A[i]*B[i] for i in range(N)]) di = sum([(A[i]^1)*B[i] for i in range(N)]) X = [1] SU = li+di PO = [0] * (5*M+10) for i in range(-M-5, 2*M+5): PO[i] = pow((SU+i)%P, P-2, P) def calc(L): su = sum(L) pl = 0 pd = 0 RE = [] for i in range(len(L)): a = li + i b = di - (len(L) - 1 - i) pd = b * L[i] * PO[a+b-SU] RE.append((pl+pd)%P) pl = a * L[i] * PO[a+b-SU] RE.append(pl%P) return RE for i in range(M): X = calc(X) ne = 0 po = 0 for i in range(M+1): po = (po + X[i] * (li + i)) % P ne = (ne + X[i] * (di - M + i)) % P invli = pow(li, P-2, P) invdi = pow(di, P-2, P) for i in range(N): print(po * B[i] * invli % P if A[i] else ne * B[i] * invdi % P)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1172/C2" }
d7985
test
n = input() s = [] a = 0 for i in map(int, input().split()): while len(s) > 1 and min(s[-2], i)>=s[-1]: a += min(i, s[-2]) del(s[-1]) s.append(i) s.sort() print(a + sum(s[0: -2])) # Made By Mostafa_Khaled
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/442/C" }
d7986
test
from collections import defaultdict n, k = list(map(int, input().split())) connections = defaultdict(set) for _ in range(n-1): u, v = list(map(int, input().split())) connections[u].add(v) connections[v].add(u) leafs = set() for node in connections: if len(connections[node])==1: leafs.add(node) steps = 0 is_correct = True while is_correct and steps<=k: new_leafs = set() for x in leafs: if len(connections[x])>1: is_correct = False #print("Len of %d more than one"%x) break root = list(connections[x])[0] if len(connections[root])<4 and len(leafs)!=3: is_correct = False #print("x: %d Len of root %d less than three"%(x,root)) #print(connections[root]) break if not is_correct: break for x in leafs: root = list(connections[x])[0] new_leafs.add(root) connections[root].remove(x) leafs = new_leafs steps += 1 if len(leafs)==1 and len(connections[list(leafs)[0]])==0: break #print("steps is %d"%steps) if is_correct and steps==k: print("Yes") else: print('No')
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1067/B" }
d7987
test
import sys readline = sys.stdin.readline H, W = map(int, readline().split()) G = [[1 if s == '#' else 0 for s in readline().strip()] for _ in range(H)] DIREC = [(0, 1), (1, 0), (-1, 0), (0, -1)] def calc(): zh = 0 for i in range(H): cnt = 0 for j in range(W): if G[i][j]: if cnt == 0: cnt = 1 continue if cnt == 1: continue if cnt == 2: return -1 else: if cnt == 0: continue cnt = 2 if cnt == 0: zh = 1 zw = 0 for j in range(W): cnt = 0 for i in range(H): if G[i][j]: if cnt == 0: cnt = 1 continue if cnt == 1: continue if cnt == 2: return -1 else: if cnt == 0: continue cnt = 2 if cnt == 0: zw = 1 if zw^zh: return -1 ans = 0 used = set() geta = W for i in range(H): for j in range(W): if G[i][j] == 0: continue if (i*geta + j) in used: continue ans += 1 stack = [i*geta + j] while stack: nh, nw = divmod(stack.pop(), geta) for dh, dw in DIREC: fh, fw = nh+dh, nw+dw if not 0 <= fh < H or not 0 <= fw < W: continue if not G[fh][fw]: continue vf = fh*geta + fw if vf in used: continue stack.append(vf) used.add(vf) return ans print(calc())
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1344/B" }
d7988
test
import sys n, k = map(int, input().split()) a = list(map(int, input().split())) cur_max = 0 last_max = 1 last = dict() zeros = [] for i in range(len(a))[::-1]: if a[i] == 0: zeros.append(i) elif a[i] not in last: last[a[i]] = i stack = [] for i in range(len(a)): if a[i] == 0: a[i] = max(cur_max, 1) elif a[i] > cur_max and last[a[i]] != i: stack.append(cur_max) cur_max = a[i] elif cur_max != 0 and i == last[cur_max]: cur_max = stack.pop() elif a[i] < cur_max: print("NO") return if k > max(a): if zeros: print("YES") a[zeros[0]] = k print(*a) else: print("NO") elif k == max(a): print("YES") print(*a) elif k < max(a): print("NO")
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1023/D" }
d7989
test
from fractions import gcd from random import randint, shuffle from collections import Counter def read_numbers(): return list(map(int, input().split())) def get_original_array(n, numbers): cnt = Counter(numbers) array = [] for new_number in sorted(numbers, reverse=True): if cnt[new_number]: cnt[new_number] -= 1 for number in array: table_entry = gcd(new_number, number) cnt[table_entry] -= 2 array.append(new_number) assert cnt.most_common()[0][1] == 0 return array def test(n): print(n) array = [randint(0, 10**9) for _ in range(n)] table = [gcd(a, b) for a in array for b in array] shuffle(table) print(sorted(array) == sorted(get_original_array(n, table))) def __starting_point(): # n = 4 # numbers = [2, 1, 2, 3, 4, 3, 2, 6, 1, 1, 2, 2, 1, 2, 3, 2] # print(get_original_array(n, numbers)) # test(10) # test(100) # test(200) # test(300) # test(400) # test(500) #else: n = int(input()) numbers = read_numbers() print(' '.join(map(str, get_original_array(n, numbers)))) __starting_point()
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/582/A" }
d7990
test
import sys import copy input = sys.stdin.readline n=int(input()) P=[list(map(int,input().split())) for i in range(n)] SET_X=set() SET_Y=set() for x,y in P: SET_X.add(x) SET_Y.add(y) CX=sorted(SET_X) CY=sorted(SET_Y) LEN=len(CX) MAX=len(CX)-1 DICT_X={x:i for i,x in enumerate(CX)} DICT_Y={x:i for i,x in enumerate(CY)} for i in range(n): P[i]=[DICT_X[P[i][0]],DICT_Y[P[i][1]]] check=[0]*len(CX) # BIT(BIT-indexed tree) BIT=[0]*(LEN+1)# 1-indexedなtree def update(v,w):# vにwを加える while v<=LEN: BIT[v]+=w v+=(v&(-v))# 自分を含む大きなノードへ. たとえばv=3→v=4 def getvalue(v):# [1,v]の区間の和を求める ANS=0 while v!=0: ANS+=BIT[v] v-=(v&(-v))# 自分より小さい2ベキのノードへ. たとえばv=3→v=2へ return ANS LIST_Y=[[] for i in range(len(CY))] for x,y in P: LIST_Y[y].append(x) for i in range(len(CY)): LIST_Y[i].sort() ANS=0 for y in range(len(CY)-1,-1,-1): for x in LIST_Y[y]: #print(x,check) if check[x]==0: check[x]=1 update(x+1,1) ANS+=getvalue(LIST_Y[y][0]+1)*(getvalue(MAX+1)-getvalue(LIST_Y[y][0]+1)+1) for i in range(1,len(LIST_Y[y])): #print(getvalue(LIST_Y[y][i]+1)-getvalue(LIST_Y[y][i-1]+1)),getvalue(MAX+1) ANS+=(getvalue(LIST_Y[y][i]+1)-getvalue(LIST_Y[y][i-1]+1))*(getvalue(MAX+1)-getvalue(LIST_Y[y][i]+1)+1) #print(ANS) print(ANS)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1190/D" }
d7991
test
n = int(input()) d = [] for i in range(n): d.append(input()) for i in range(n): if d[i].count('E') == n: break else: for i in range(n): print(i+1, d[i].index('.')+1) return for i in range(n): res = 0 for j in range(n): if d[j][i] == 'E': res += 1 if res == n: break else: for i in range(n): for j in range(n): if d[j][i] == '.': print(j+1, i+1) break return print(-1)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/329/A" }
d7992
test
def solve(a,l,r,k): out = sorted(a[:l]+a[r:],reverse=True) inside = sorted(a[l:r]) cur = sum(a[l:r]) for i in range(min(k,len(inside),len(out))): if out[i] > inside[i]: cur += out[i]-inside[i] else: break return cur n,k = [int(x) for x in input().split()] a = [int(x) for x in input().split()] assert len(a) == n best = a[0] for l in range(n): for r in range(l+1,n+1): cur = solve(a,l,r,k) if cur > best: best = cur print(best)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/425/A" }
d7993
test
class Ortree(): def __init__(self, n, As): size = 1 while n > size: size *= 2 self.size = size data = [0] * size + As[:] + [0] * (size - n) for idx in range(self.size - 1, 0, -1): idx2 = idx << 1 data[idx] = data[idx2] | data[idx2 + 1] self.data = data def update(self, idx, val): pos = idx + self.size self.data[pos] = val pos >>= 1 while pos: pos2 = pos << 1 self.data[pos] = self.data[pos2] | self.data[pos2 + 1] pos >>= 1 return self.data[1] def solve(n, k, x, As): As.sort(reverse= True) xk = x**k if n == 1: As[0] *= xk return As[0] if is_simplecase(xk, As): As[0] *= xk return cumor(As) return complexcase(n, xk, As) def cumor(As): result = 0 for a in As: result |= a return result def is_simplecase(xk, As): len0 = len(bin(As[0] * xk)) len1 = len(bin(As[1] * xk)) return len0 > len1 def complexcase(n, xk, As): len0 = len(bin(As[0] * xk)) for i, a in enumerate(As[1:], 1): if len(bin(a * xk)) < len0: end = i rest = cumor(As[end:]) break else: end = n rest = 0 ortree = Ortree(end, As[:end]) record = rest for i in range(end): score = ortree.update(i, As[i] * xk) | rest if record < score: record = score ortree.update(i, As[i]) return record n, k, x = map(int, input().split()) As = list(map(int, input().split())) print(solve(n, k, x, As))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/578/B" }
d7994
test
from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue,datetime sys.setrecursionlimit(10**8) INF = float('inf') mod = 998244353 eps = 10**-7 def inp(): return int(input()) def inpl(): return list(map(int, input().split())) def inpls(): return list(input().split()) K,N = inpl() MAX = K+N+10 fac = [1]*(MAX+1) for i in range(1,MAX+1): fac[i] = (fac[i-1]*i)%mod gyakugen = [1]*(MAX+1) gyakugen[MAX] = pow(fac[MAX],mod-2,mod) for i in range(MAX,0,-1): gyakugen[i-1] = (gyakugen[i]*i)%mod def Comb(n,k):#nCk return (fac[n]*gyakugen[k]*gyakugen[n-k])%mod #K=k,N=n,0pair = 0 def calc(k,n,i): #i=2に帰着させる pairs = (i-2)//2 k -= pairs n -= pairs #色々と例外処理 if n < 0 or k <= 0: return 0 elif k == 1 and n >= 2: return 0 if n == 0: #球が0個なら1通り ans = 1 else: ans = 0 #i=2の時の数え上げ for x in range(2): ball = n-x #球 box = k-1 #箱 ans += Comb(box-1+ball,ball)%mod ans *= pow(2,pairs,mod) #0pairの選び方 return ans % mod ans = [] for i in range(2,K+2): if i%2 == 0: pairs = (i-2)//2 tmp = 0 for p0 in range(pairs+1): #p0 = 0pairの数 tmp1 = calc(K-p0*2 , N , i-p0*2) %mod #k-p0*2,i-p0*2で0pairが0組 tmp2 = Comb(pairs,p0) %mod #0pairの選び方 tmp += tmp1 * tmp2 tmp %= mod ans.append(tmp) print(tmp) ans = ans[::-1] for i in range(1,K): print((ans[i]))
PYTHON
{ "starter_code": "", "url": "https://atcoder.jp/contests/arc102/tasks/arc102_c" }
d7995
test
def bfs(source): q = [0] * (n + 1); fa = [-1] * n l, r = [1] * 2 fa[source] = source q[1] = source while l <= r: x = q[l] l += 1 for y in e[x]: if fa[y] == -1: fa[y] = x r += 1 q[r] = y i = r; while i >= 1: x = q[i] for y in e[x]: if fa[y] == x: sum[x] += sum[y] dp[x] += dp[y] + min(sum[y], m - sum[y]) i -= 1 n, m =[int(x) for x in input().split()] m <<= 1 t = [int(x) for x in input().split()] e = [list() for i in range(n)] sum = [0] * n dp = [0] * n #print(len(e), e) for i in range(n - 1): x, y = [int(a) for a in input().split()] e[x - 1].append(y - 1) e[y - 1].append(x - 1) for x in t: sum[x - 1] = 1 bfs(0) print(dp[0])
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/700/B" }
d7996
test
s = input() zero = set() # 前面的一个以0结尾的串的索引 one = set() # 前面的一个以1结尾的串的索引 ans = [] # 结果的串 for i in range(0,len(s)): if(s[i] == '0'): if one: k = one.pop() zero.add(k) ans[k].append(i+1) else: zero.add(len(ans)) ans.append([i+1]) else: if not zero: print(-1) return k = zero.pop() one.add(k) ans[k].append(i+1) if(one): print(-1) return print(len(ans)) print('\n'.join([str(len(x))+' '+' '.join(map(str,x)) for x in ans]))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/949/A" }
d7997
test
import sys from collections import defaultdict, Counter P = 10 ** 9 + 7 def factmod(n): res = 1 for i in range(2, n+1): res *= i res %= P return res def solve(): n, m = list(map(int, input().split())) colour = {i:0 for i in range(1, m+1)} colour_map = {} for i, line in enumerate(sys.stdin): A = [int(x) for x in line.split()] count = Counter(A) if count[A[0]] == 1: count.pop(A[0]) else: count[A[0]] -= 1 for c in count: p = (colour[c], i, count[c]) if p in colour_map: colour[c] = colour_map[p] else: colour[c] = colour_map[p] = len(colour_map) + 1 count = Counter(list(colour.values())) res = 1 for c in count: res *= factmod(count[c]) res %= P return res print(solve())
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/757/C" }
d7998
test
n = int(input()) l = tuple(map(int, input().split())) a = [] for i in range(n - 1): a.append(abs(l[i] - l[i + 1])) ev = [(a[i] if i % 2 == 0 else -a[i]) for i in range(n - 1)] od = [-i for i in ev] od[0] = 0 dp = [ev[0]] st = ["ev"] # print(a) # print(ev) # print(od) vmax = dp[0] evsum = evans = 0 odsum = odans = 0 for i in range(0, n - 1): evsum += ev[i] odsum += od[i] evans = max(evsum, evans) odans = max(odsum, odans) if evsum < 0 and i % 2 == 1: evsum = 0 if odsum < 0 and i % 2 == 0: odsum = 0 # print(evans, odans) print(max(evans, odans))
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/788/A" }
d7999
test
n,a= int(input()),list(map(int,input().split())) f,m= [0]*(n+1),10**9+7 for i in range(n): if a[i]==i+1: f[i+1]=f[i]+2 else: f[i+1]=(2+f[i]*2-f[a[i]-1])%m print(f[n]%m)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/407/B" }
d8000
test
import sys input = sys.stdin.readline n=int(input()) lr=[list(map(int,input().split())) for i in range(n)] L=[lr[i][0] for i in range(n)] R=[lr[i][1] for i in range(n)] L.sort() R.sort() ANS=0 for i in range(n): ANS+=max(L[i],R[i]) print(ANS+n)
PYTHON
{ "starter_code": "", "url": "https://codeforces.com/problemset/problem/1060/D" }