code1
stringlengths
17
427k
code2
stringlengths
17
427k
similar
int64
0
1
pair_id
int64
2
181,637B
question_pair_id
float64
3.7M
180,677B
code1_group
int64
1
299
code2_group
int64
1
299
P = [1 for _ in range(10**6)] P[0]=0 P[1]=0 for i in range(2,10**3): for j in range(i*i,10**6,i): P[j] = 0 Q = [] for i in range(10**6): if P[i]==1: Q.append(i) N = int(input()) C = {} for q in Q: if N%q==0: cnt = 0 while N%q==0: N = N//q cnt += 1 C[q] = cnt if N>1: C[N] = 1 cnt = 0 for q in C: n = C[q] k = 1 while n>=(k*(k+1))//2: k += 1 cnt += k-1 print(cnt)
n = list(map(int, list(input()))) count = 0 n = n[::-1] + [0] for idx, num in enumerate(n): if num == 10: n[idx+1] += 1 elif num == 5: if n[idx+1] >= 5: n[idx+1] += 1 count += 10 - num else: count += num elif num <= 4: count += num else: count += 10 - num n[idx+1] += 1 print(count)
0
null
43,996,210,524,172
136
219
from sys import stdin for line in stdin: mid, final, make = map(int, line.split()) if mid == -1 and final == -1 and make == -1: break elif mid == -1 or final == -1: print('F') elif mid + final >= 80: print('A') elif mid + final >= 65: print('B') elif mid + final >= 50: print('C') elif mid + final >= 30: if make >= 50: print('C') else: print('D') else: print('F')
n,k,s=map(int,input().split()) L=[s]*k+[min(s+1,10**9-1)]*(n-k) print(' '.join(map(str,L)))
0
null
46,253,905,984,260
57
238
import sys sys.setrecursionlimit(10**6) def solve(n,a): wa=0 for i in range(n): if(i%2==0): wa+=a[i] kotae=wa for i in range(n//2): wa+=a[(n//2-i-1)*2+1] wa-=a[(n//2-i-1)*2] if(wa>kotae): kotae=wa return kotae def dfs(n,a,k): global zen zen.append([n,k]) if(k==1): return max(a) ari=a[n-1]+dfs(n-2,a[:n-2],k-1) if(n==k*2-1): return ari nasi=dfs(n-1,a[:n-1],k) return max(ari,nasi) n=int(input()) a=list(map(int,input().split())) if(n%2==0): print(solve(n,a)) else: data=[[a[0],a[0]],[max(a[:2]),max(a[:2])]] #data.append([max(a[:3]),sum(a[:3])-min(a[:3])]) data.append([max(a[:3]),a[0]+a[2]]) for i in range(3,n): if(i%2==1): ari=a[i]+data[i-2][0] nasi=data[i-1][1] saiyo=max(ari,nasi) data.append([saiyo,saiyo]) else: ooi=a[i]+data[i-2][1] nasi=data[i-1][1] ari=a[i]+data[i-2][0] sukunai=max(ari,nasi) data.append([sukunai,ooi]) print(data[n-1][0])
import numpy as np from numba import njit @njit('i8(i8)', cache=True) def solve(x): count = np.zeros(x + 1, dtype=np.int64) for i in range(1, x + 1): for j in range(i, x + 1, i): count[j] += j return count.sum() if __name__ == "__main__": x = int(input()) print(solve(x))
0
null
24,146,613,637,120
177
118
print(input()**2)
from sys import stdin r = int(stdin.readline()) if r < 1: print(0) else: circle = r * r print(circle)
1
145,347,104,131,420
null
278
278
# coding=utf-8 from collections import deque n, q = map(int, input().split()) queue = deque() total_time = 0 for i in range(n): name, time = input().split() queue.append([name, int(time)]) while queue: poped = queue.popleft() if poped[1] > q: queue.append([poped[0], poped[1] - q]) total_time += q else: total_time += poped[1] print(poped[0], total_time)
def robin(process, q): if int(process[0][1]) - q > 0: process[0][1] = int(process[0][1]) - q process.append([process[0][0],process[0][1]]) process.pop(0) return process, q else: q = int(process[0][1]) process.pop(0) return process, q n, q = input().split() n, q = int(n), int(q) process = [] for i in range(n): process.append([i for i in input().split()]) time = 0 while len(process) != 0: length = len(process) name = process[0][0] process, process_time = robin(process, q) time += process_time if length > len(process): print(name,time)
1
40,940,204,230
null
19
19
L, R, D = map(int, input().split()) counter = 0 for i in range(L, R + 1): if i % D == 0: counter+= 1 print(counter)
L, R, d = input().split() L = int(L) R = int(R) d = int(d) cnt = 0 for t in range(L,R+1): if t % d == 0: cnt = cnt + 1 print(cnt)
1
7,554,931,483,372
null
104
104
a = list(input()) print("Yes" if len(set(a)) == 2 else "No")
S = str(input()) if S[0] == S[1] == S[2]: print('No') else: print('Yes')
1
54,756,877,097,958
null
201
201
# -*- coding: utf-8 -*- import sys N=input() bit=[ [ 0 for _ in range(N+1) ] for __ in range(27) ] def add(i,a,w): while a<=N: bit[i][a]+=w a+=a&-a def sum(i,a): ret=0 while 0<a: ret+=bit[i][a] a-=a&-a return ret S=sys.stdin.readline().strip() S=[None]+list(S) #1-indexed for j,x in enumerate(S): if j==0: continue i=ord(x)-96 add(i,j,1) Q=input() for _ in range(Q): q1,q2,q3=sys.stdin.readline().split() if q1=="1": q1=int(q1) q2=int(q2) current_s=q3 former_s=S[q2] former_s=ord(former_s)-96 #1-indexed S[q2]=current_s #文字列で更新された1文字を置き換える current_s=ord(current_s)-96 add(current_s,q2,1) add(former_s,q2,-1) if q1=="2": q2=int(q2) q3=int(q3) begin,end=q2,q3 cnt=0 for i in range(1,27): if 0<sum(i,end)-sum(i,begin-1): cnt+=1 print cnt
def main(): import bisect n = int(input()) s = list(input()) q = int(input()) d = {} for i in range(26): d[chr(ord('a')+i)] = [] for i in range(n): d[s[i]].append(i) #print(d) for i in range(q): t,a,b = input().split() if t == '1': a = int(a)-1 if s[a] == b: continue #idx = bisect.bisect_left(d[s[a]],a) #d[s[a]].pop(idx) d[s[a]].remove(a) bisect.insort_left(d[b],a) s[a] = b else: a = int(a)-1 b = int(b)-1 c = 0 for i in range(26): idx = bisect.bisect_left(d[chr(ord('a')+i)],a) if idx < len(d[chr(ord('a')+i)]) and d[chr(ord('a')+i)][idx] <= b: c += 1 print(c) main()
1
62,711,476,437,188
null
210
210
n = int(input()) a = list(map(int,input().split())) ans = {} for i in range(n): ans[a[i]] = i + 1 s = [ans[i+1] for i in range(n)] print(*s)
import numpy as np N = int(input()) A = list(map(int, input().split())) A = np.argsort(A) for a in A: print(a+1, end=" ")
1
180,717,365,947,678
null
299
299
nMonsters, nSpecial = [int(x) for x in input().split()] monst = [int(x) for x in input().split()] monst.sort() nMonsters -= nSpecial if nMonsters < 0: print(0) else: print(sum(monst[0:nMonsters]))
S = input() # 高々2^3=8通りなので、全て列挙すればよい # RRR RRS SRR RSR RSS SRS SSR SSS ans = 0 if S == 'RRR': ans = 3 elif S == 'SRR' or S == 'RRS': ans = 2 elif S == 'SSS': ans = 0 else: ans = 1 print(ans)
0
null
41,744,948,592,424
227
90
回数 = int(input()) a, b = list(map(str, input().split())) c = "" for i in range(回数): c = c + a[i] c = c + b[i] print(c)
S=list(map(int,input().split())) while True: S[2]=S[2]-S[1] S[0]=S[0]-S[3] if S[2]<=0: print("Yes") break elif S[0]<=0: print("No") break
0
null
70,763,271,006,080
255
164
from collections import deque from math import ceil # n个怪物,d杀伤半径,a杀伤值 n, d, a = map(int, input().split()) ms = [map(int, input().split()) for i in range(n)] ms = sorted([(pos, ceil(hp / a)) for pos, hp in ms]) bombs = deque() ans = 0 valid_bomb = 0 for pos, hp in ms: # 查看队列里的bomb是否对当前怪物有效 while bombs and bombs[0][0] < pos: bomb_border, bomb_cnt = bombs.popleft() valid_bomb -= bomb_cnt # 还需新加多少bomb才能灭掉当前怪物 bomb_cnt = max(0, hp - valid_bomb) valid_bomb += bomb_cnt ans += bomb_cnt # 新加的bomb放入队列 if bomb_cnt > 0: bombs.append([pos + d * 2, bomb_cnt]) print(ans)
s = input() ans = 'Yes' num = len(s) if num % 2 != 0: ans = 'No' pass else: for i in range(0, num, 2): if s[i] + s[i+1] != 'hi': ans = 'No' print(ans)
0
null
67,381,859,270,880
230
199
n = int(input()) p = list(map(int, input().split())) p.sort(reverse=True) #追加していく際に追加した数の両脇を固める s = 0 for i in range(1,n): s += p[i//2] print(s)
N = int(input()) a = list(map(int, input().split())) a.sort() arrival = 1 ans = 0 while arrival < N: score = a.pop() if arrival == 1: ans += score arrival += 1 else: ans += score*min(2, N - arrival) arrival += 2 print(ans)
1
9,295,697,098,390
null
111
111
N = int(input()) for x in range(N+1): if int(x*1.08) == N: print(x) break else: print(':(')
import math N = int(input()) for i in range(N+1): if math.floor(1.08 * i) == N: print(i) exit() print(":(")
1
125,444,599,829,472
null
265
265
s = input() n = len(s) // 2 j = -1 t = 0 for i in range(n): if s[i] != s[j]: t += 1 j -= 1 print(t)
import numpy as np import scipy as sp import math S = input() n = len(S) m = n//2 l = 0 for i in range (0,m): if(S[i] != S[n-i-1]): l = l + 1 print(l)
1
120,169,164,924,260
null
261
261
x = int(input()) a = [0]*1000 for i in range(1000): tmp = i**5 a[i] = tmp for i in range(1000): for j in range(1000): if((a[i]-x) == (a[j])): print(i,j) exit() elif(x-a[i]==a[j]): print(i,-j) exit()
S,W=map(int,input().split(" ")) if S>W: print("safe") else: print("unsafe")
0
null
27,383,006,486,538
156
163
import itertools n=int(input()) l=list(map(int,input().split())) c=itertools.combinations(l,2) ans=sum(x*y for x,y in c) print(ans)
n,x,m=map(int,input().split()) sm=[-1 for i in range(m)]+[0] w=[-1 for i in range(m)] d=[m] a=x t=0 s=0 while True: s+=a if w[a]!=-1: inter=t-w[a] fv=w[a] ls=d[(n-fv)%inter+fv] lls=d[w[a]] print(sm[lls]+(n-fv)//inter*(s-sm[a])+(sm[ls]-sm[lls])) break w[a]=t d.append(a) sm[a]=s t+=1 a=(a*a)%m
0
null
85,623,518,827,070
292
75
S = input().strip() Q = int(input()) ind = 1 x = [] y = [] for i in range(Q): q = list(input().split()) if len(q)==1: ind = ind*(-1) else: if q[1]=="1": if ind>0: x.append(q[2]) else: y.append(q[2]) else: if ind>0: y.append(q[2]) else: x.append(q[2]) if ind>0: x = x[::-1] S = "".join(x)+S+"".join(y) else: S = S[::-1] y = y[::-1] S = "".join(y)+S+"".join(x) print(S)
def main(): S = input() Q = int(input()) order = [list(input().split()) for _ in range(Q)] left_flag = 0 right_flag = 0 cnt = 0 for i in range(Q): if order[i][0] == '1': cnt += 1 else: if cnt%2 == 0: if order[i][1] == '1': if left_flag == 1: left = order[i][2] + left else: left = order[i][2] left_flag = 1 else: if right_flag == 1: right = right + order[i][2] else: right = order[i][2] right_flag = 1 else: if order[i][1] == '2': if left_flag == 1: left = order[i][2] + left else: left = order[i][2] left_flag = 1 else: if right_flag == 1: right = right + order[i][2] else: right = order[i][2] right_flag = 1 if left_flag == 1 and right_flag == 1: S = left + S + right elif left_flag == 1 and right_flag == 0: S = left + S elif left_flag == 0 and right_flag == 1: S = S + right else: S = S if cnt%2 == 0: return(S) else: S2 = S[-1] for i in range(len(S)-2,-1,-1): S2 = S2 + S[i] return S2 print(main())
1
57,437,388,949,834
null
204
204
import math def main(): n=int(input()) print(math.ceil(n/2)/n) if __name__ == '__main__': main()
count = 0 for i in range(int(input())): l = list(map(int, input().split())) if l[0] == l[1]: count += 1 elif l[0] != l[1]: count = 0 if count >= 3: print("Yes") break if count < 3: print("No")
0
null
89,412,471,154,230
297
72
#!/usr/bin/env python3 import sys, math, itertools, collections, bisect input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8') inf = float('inf') ;mod = 10**9+7 mans = inf ;ans = 0 ;count = 0 ;pro = 1 n = int(input()) for i in range(2,int(n**.5) + 1): if n % i == 0: tmp = n while tmp % i==0: tmp //= i if (tmp-1) % i == 0:ans += 1 if n//i != i: tmp = n;i = n//i while tmp % i==0: tmp //= i if (tmp-1) % i == 0:ans += 1 for i in range(2,int((n-1)**.5 )+ 1): if (n-1) % i == 0: if (n-1) // i == i: ans += 1 else: ans += 2 # print(ans) print(ans+1 + int(n != 2))
import math h,w = map(int,input().split()) if w < h: h,w = w,h if h==1: print(1) else: ans = math.ceil((h*w)/2) print(max(1,ans))
0
null
46,278,316,811,362
183
196
import math A, B = input().split() A = int(A) B = int(B.replace(".", "")) ans = (A * B) // 100 print(ans)
N = int(input()) if N%2 == 1 : print(0) exit() n = 0 i = 0 for i in range(1,26) : n += N//((5**i)*2) print(n)
0
null
66,046,374,948,372
135
258
import sys from collections import deque def main(): h, w = map(int, input().split()) maze = [input() for i in range(h)] # 行ったかどうかのフラグ visited = [[-1]*w for j in range(h)] start_yx = [] for i in range(h): for j in range(w): if maze[i][j] == '.': sy = i sx = j start_yx .append([sy, sx]) # 移動パターン mv = [[1, 0], [-1, 0], [0, 1], [0, -1]] ans = 0 for sy, sx in start_yx : visited = [[-1]*w for j in range(h)] q = deque([[sy, sx]]) visited[sy][sx] = 0 while q: y, x = q.popleft() ans = max(ans, visited[y][x]) for i, j in mv: if (0 <= y + i < h) and (0 <= x + j < w): ny = y+i nx = x+j if visited[ny][nx] != -1: continue if maze[ny][nx] == '.': visited[ny][nx] = visited[y][x] + 1 q.append([ny, nx]) else: continue print(ans) if __name__ == '__main__': main()
X = int(input()) A = X // 500 B = X % 500 C = B // 5 ans = A * 1000 + C * 5 print(ans)
0
null
68,849,931,955,090
241
185
a,b=map(int,input().split()) ans=0 if a<=3: ans+=(4-a)*10**5 if b<=3: ans+=(4-b)*10**5 if a==b==1: ans+=4*10**5 print(ans)
codePlace, implePlace = map(int, input().split(" ")) priceDict = { 1:300000, 2:200000, 3:100000 } totalPrice = priceDict[codePlace] if codePlace in priceDict.keys() else 0 totalPrice += priceDict[implePlace] if implePlace in priceDict.keys() else 0 totalPrice += 400000 if codePlace == 1 and implePlace == 1 else 0 print(totalPrice)
1
141,048,685,830,718
null
275
275
n,m=map(int,input().split()) if n%2==1: x=[f"{i+1} {n-i}" for i in range(m)] print(" ".join(x)) else: x=[f"{i+1} {n-i}" if i<m/2 else f"{i+1} {n-i-1}" for i in range(m)] print(" ".join(x))
n,m=map(int,input().split()) k=m//2 for i in range (0,k): a=i+1 b=2*k+1-i print (a,b) c=2*k+2 k=(m+1)//2 j=1 #print(c,k) for i in range (c,c+k): a=i b=c+2*k-j j+=1 print(a,b)
1
28,575,766,593,948
null
162
162
a, b, c = map(int, raw_input().split()) print sum(1 for i in xrange(a, b + 1) if c % i == 0)
l, r, d = map(int, input().split()) if (l/d).is_integer(): print(r//d-l//d+1) else: print(r//d-l//d)
0
null
4,046,167,349,344
44
104
#!/usr/bin/env python3 def main(): n, u, v = map(int, input().split()) u -= 1 v -= 1 adj = [[] for i in range(n)] for i in range(n - 1): a, b = map(int, input().split()) a -= 1 b -= 1 adj[a].append(b) adj[b].append(a) # uv間経路を求める st = [u] prev = [None for i in range(n)] while st: x = st.pop() for y in adj[x]: if y == prev[x]: continue prev[y] = x st.append(y) path = [v] while path[-1] != u: path.append(prev[path[-1]]) path = list(reversed(path)) # crossからsquareを経由しない最遠ノードstarを求める(a59p22) l = len(path) - 1 cross = path[(l - 1) // 2] square = path[(l - 1) // 2 + 1] st = [(cross, 0)] prev = [None for i in range(n)] dist = [-1 for i in range(n)] while st: x, d = st.pop() dist[x] = d for y in adj[x]: if y == prev[x]: continue if y == square: continue prev[y] = x st.append((y, d + 1)) star_square = max(dist) if l % 2 == 1: res = (l - 1) // 2 + star_square else: res = (l - 1) // 2 + star_square + 1 print(res) if __name__ == "__main__": main()
from collections import deque n = int(input()) graph = [list(map(int,input().split()))[2:] for _ in range(n)] dist = [-1]*(n+1) dist[0] = 0 dist[1] = 0 d = deque() d.append(1) while d: v = d.popleft()-1 if len(graph[v]) >= 1: for i in graph[v]: if dist[i] == -1: dist[i] = dist[v+1]+1 d.append(i) for i in range(1,n+1): print(i,dist[i])
0
null
58,589,367,009,030
259
9
s = list(input()) k = int(input()) n = len(s) if s == [s[0]]*n: print(n*k//2) else: ss = s*2 ans1 = 0 for i in range(1, n): if s[i] == s[i -1]: s[i] = "" ans1 += 1 ans2 = 0 for i in range(1, 2*n): if ss[i] == ss[i - 1]: ss[i] = "" ans2 += 1 j = ans2 - ans1 print(ans1 + j*(k - 1))
def main(): s = input() k = int(input()) count_l = [] i = 0 counter = 1 while True: if len(s) == 1: count_l.append(counter) break elif s[i] == s[i+1]: counter += 1 else: count_l.append(counter) counter = 1 i += 1 if i == len(s)-1: if counter == 1: break else: count_l.append(counter) break answer = 0 if len(count_l) >= 3 and s[0] == s[-1] and k >= 2: sub_l = [count_l[0] + count_l[-1]] + count_l[1:-1] for i in range(len(sub_l)): answer += (sub_l[i] // 2) * (k - 1) for j in range(len(count_l[:-1])): answer += count_l[j] // 2 answer += count_l[-1] // 2 elif len(count_l) == 1: answer += (count_l[0] * k) // 2 else: for i in range(len(count_l)): answer += (count_l[i] // 2) * k print(answer) if __name__ == "__main__": main()
1
175,264,090,400,830
null
296
296
import sys def resolve(in_): mod = 1000000007 # 10 ** 9 + 7 n, k = map(int, in_.readline().split()) n += 1 # ans = 0 ans = 1 # while n >= k: while n > k: ans += ( ((n + (n - k)) * k // 2) % mod - ((1 + k - 1) * k // 2) % mod + 1 ) % mod ans %= mod k += 1 return ans def main(): answer = resolve(sys.stdin.buffer) print(answer) if __name__ == '__main__': main()
N, K = map(int, input().split()) N += 1 ans = 0 p = 10 ** 9 + 7 for k in range(K, N + 1): ans += (k * (N - k) + 1) % p ans %= p print(ans)
1
33,223,260,105,002
null
170
170
a = int(input()) n = 1 while True: if a*n % 360 == 0: break else: n += 1 print(n)
#!/usr/bin/env python3 from networkx.utils import UnionFind import sys def input(): return sys.stdin.readline().rstrip() def main(): n,m=map(int, input().split()) uf = UnionFind() for i in range(1,n+1): _=uf[i] for _ in range(m): a,b=map(int, input().split()) uf.union(a, b) # aとbをマージ print(len(list(uf.to_sets()))-1) #for group in uf.to_sets(): # すべてのグループのリストを返す #print(group) if __name__ == '__main__': main()
0
null
7,708,796,452,292
125
70
#!/usr/bin/env python a, v = map(int, input().split()) b, w = map(int, input().split()) t = int(input()) if v <= w: print('NO') exit() if abs(b-a)/(v-w) > t: print('NO') exit() print('YES')
a,v = map(int,input().split()) b,w = map(int,input().split()) t = int(input()) if a > b: oni = a + (-1*v) * t nige = b + (-1*w) * t if oni <= nige: print("YES") else: print("NO") else: oni = a + v*t nige = b + w * t if oni >= nige: print("YES") else: print("NO")
1
15,074,408,665,602
null
131
131
A, B = map(int,input().split()) mult = A * B print(mult)
N, M = map(int, input().split()) A = map(int, input().split()) A_sum = sum(A) if (N - A_sum) >= 0: print(N - A_sum) else: print(-1)
0
null
23,758,889,631,260
133
168
N=int(input()) L=list(map(int,input().split())) S=[0]*N c=1 for i in L: S[i-1]=c c+=1 for i in range(N): print(S[i],end=' ')
list = input().split() stack = [] for i in list: if ( i.isdigit() ): stack.append(int(i)) elif (i == '+'): stack.append(stack.pop() + stack.pop()) elif (i == '*'): stack.append(stack.pop() * stack.pop()) elif (i == '-'): stack.append( (-1)*stack.pop() + stack.pop()) print(stack.pop())
0
null
90,568,362,952,452
299
18
N = int(input()) xy = [[] for i in range(N)] for i in range(N): A = int(input()) for j in range(A): x, y = map(int, input().split()) xy[i].append([x, y]) ans = 0 for i in range(2**N): b = format(i, "0" + str(N) + "b") t = 0 f = 0 for j in range(N): if b[j] == "1": t += 1 for k in xy[j]: if str(k[1]) != b[k[0]-1]: f = 1 break if f == 0: ans = max(ans, t) #print(b) print(ans)
from itertools import product N = int(input()) A = [None] * N lst = [[] for _ in range(N)] for i in range(N): A[i] = int(input()) lst[i] = [list(map(int, input().split())) for _ in range(A[i])] bit_lst = list(product(range(2), repeat=N)) #N桁のビット ans = 0 for bit in bit_lst: f = True #このbitの証言が無意味になったらFalse for a in range(N): #1人ずつ順番に聞く : a人目の証言 if f: for b in range(A[a]): #b個目の証言 if bit[a] == 1: #この人が正直者なとき if lst[a][b][1] != bit[lst[a][b][0]-1]: #正直者の証言と現実が食い違う f = False break else: #正直者ではないとき break if f: ans = max(ans, sum(bit)) print(ans)
1
121,675,149,655,380
null
262
262
N=int(input()) def prime_factorization(n): arr=[] temp=n for i in range(2,int(-(-n**0.5//1))+1): if temp%i==0: cnt=0 while temp%i==0: cnt+=1 temp//=i arr.append([i,cnt]) if temp!=1: arr.append([temp,1]) if arr==[]: arr.append([n,1]) return arr def solve(): if N==1: print(0) return pri_arr=prime_factorization(N) ans=0 for i in range(len(pri_arr)): e=pri_arr[i][1] temp=0 cur=1 while e>=cur: e-=cur cur+=1 temp+=1 ans+=temp print(ans) if __name__ == "__main__": solve()
# import sys input=sys.stdin.readline def main(): x,y,z=map(int,input().split()) print(z,x,y) if __name__=="__main__": main()
0
null
27,447,092,457,098
136
178
class Dice(): def __init__(self, *n): self.rolls = n def spin(self, order): if order == "N": self.rolls = [ self.rolls[1], self.rolls[5], self.rolls[2], self.rolls[3], self.rolls[0], self.rolls[4] ] if order == "E": self.rolls = [ self.rolls[3], self.rolls[1], self.rolls[0], self.rolls[5], self.rolls[4], self.rolls[2] ] if order == "S": self.rolls = [ self.rolls[4], self.rolls[0], self.rolls[2], self.rolls[3], self.rolls[5], self.rolls[1] ] if order == "W": self.rolls = [ self.rolls[2], self.rolls[1], self.rolls[5], self.rolls[0], self.rolls[4], self.rolls[3] ] return self.rolls[0] d = Dice(*[int(i) for i in input().split()]) for order in list(input()): l = d.spin(order) print(l)
i = input() print(i.swapcase())
0
null
869,573,773,718
33
61
class process: def __init__(self, name, time): self.name = name self.time = time def queue(q, ps): time = 0 while len(ps) != 0: p = ps.pop(0) if p.time > q: p.time -= q time += q ps.append(p) else: time += p.time print p.name + " " + str(time) if __name__ == "__main__": L = map(int, raw_input().split()) N = L[0] q = L[1] processes = [] for i in range(N): L = raw_input().split() processes.append(process(L[0], int(L[1]))) queue(q, processes)
# coding: UTF-8 from collections import deque queue = deque() ftime = deque() n,quantum = map(int,input().split()) for i in range(n): name,time = input().split() time = int(time) queue.append((name,time)) t = 0 while queue: name,time = queue.popleft() if time <= quantum: t += time ftime.append(name + " " + str(t)) else: t += quantum queue.append((name,time-quantum)) while ftime: print(ftime.popleft())
1
42,254,948,512
null
19
19
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) from time import time from random import randint from copy import deepcopy start_time = time() def calcScore(t, s, c): scores = [0]*26 lasts = [0]*26 for i in range(1, len(t)): scores[t[i]] += s[i][t[i]] dif = i - lasts[t[i]] scores[t[i]] -= c[t[i]] * dif * (dif-1) // 2 lasts[t[i]] = i for i in range(26): dif = len(t) - lasts[i] scores[i] -= c[i] * dif * (dif-1) // 2 return scores def greedy(c, s): day_lim = len(s) socres = [0]*26 t = [0]*day_lim lasts = [0]*26 for i in range(1, day_lim): pls = [v for v in socres] mns = [v for v in socres] for j in range(26): pls[j] += s[i][j] mns[j] -= c[j] * (i - lasts[j]) sum_mns = sum(mns) pt = sum_mns - mns[0] + pls[0] idx = 0 for j in range(1, 26): tmp = sum_mns - mns[j] + pls[j] if pt < tmp: pt = tmp idx = j t[i] = idx lasts[idx] = i for j in range(26): if j == idx: socres[j] = pls[j] else: socres[j] = mns[j] return socres, t def subGreedy(c, s, t, day): day_lim = len(s) socres = [0]*26 t = [0]*day_lim lasts = [0]*26 for i in range(1, day_lim): if day <= i: pls = [v for v in socres] mns = [v for v in socres] for j in range(26): pls[j] += s[i][j] mns[j] -= c[j] * (i - lasts[j]) sum_mns = sum(mns) pt = sum_mns - mns[0] + pls[0] idx = 0 for j in range(1, 26): tmp = sum_mns - mns[j] + pls[j] if pt < tmp: pt = tmp idx = j t[i] = idx lasts[idx] = i for j in range(26): if j == idx: socres[j] = pls[j] else: socres[j] = mns[j] else: scores[t[i]] += s[i][t[i]] lasts[t[i]] = i for j in range(26): dif = i - lasts[j] scores[j] -= c[j] * dif return socres, t D = int(input()) c = list(map(int, input().split())) s = [[0]*26 for _ in range(D+1)] for i in range(1, D+1): s[i] = list(map(int, input().split())) scores, t = greedy(c, s) sum_score = sum(scores) while time() - start_time < 1.86: typ = randint(1, 90) if typ <= 70: for _ in range(100): tmp_t = deepcopy(t) tmp_t[randint(1, D)] = randint(0, 25) tmp_scores = calcScore(tmp_t, s, c) sum_tmp_score = sum(tmp_scores) if sum_score < sum_tmp_score: sum_score = sum_tmp_score t = deepcopy(tmp_t) scores = deepcopy(tmp_scores) elif typ <= 90: for _ in range(30): tmp_t = deepcopy(t) dist = randint(1, 20) p = randint(1, D-dist) q = p + dist tmp_t[p], tmp_t[q] = tmp_t[q], tmp_t[p] tmp_scores = calcScore(tmp_t, s, c) sum_tmp_score = sum(tmp_scores) if sum_score < sum_tmp_score: sum_score = sum_tmp_score t = deepcopy(tmp_t) scores = deepcopy(tmp_scores) elif typ <= 100: tmp_t = deepcopy(t) day = randint(D//4*3, D) tmp_scores, tmp_t = subGreedy(c, s, tmp_t, day) sum_tmp_score = sum(tmp_scores) if sum_score < sum_tmp_score: sum_score = sum_tmp_score t = tmp_t scores = tmp_scores for v in t[1:]: print(v+1)
from itertools import chain import sys def main(): N = int(input()) # TLEs were caused mostly by slow input (1s+) # S = list(input() for _ in range(N)) S = sys.stdin.read().split('\n') print(solve(S)) def get_count(args): s, result = args # messy input to work with map. cum_sum = 0 for c in s: if c == ')': cum_sum -= 1 else: cum_sum += 1 result[0] = max(result[0], -cum_sum) result[1] = result[0] + cum_sum return result # Made-up name, don't remember what to call this. Radix-ish def silly_sort(array, value_min, value_max, get_value): if len(array) == 0: return cache = [None for _ in range(value_max - value_min + 1)] for elem in array: # Assume elem[0] is the value value = get_value(elem) - value_min if cache[value] is None: cache[value] = [] cache[value].append(elem) for values in cache: if values is None: continue for value in values: yield value def solve(S): counts = [[0,0] for _ in range(len(S))] counts = list(map(get_count, zip(S,counts))) first_group = [] second_group = [] min_first_group = float('inf') max_first_group = 0 min_second_group = float('inf') max_second_group = 0 for c in counts: if c[0] - c[1] <= 0: first_group.append(c) max_first_group = max(max_first_group, c[0]) min_first_group = min(min_first_group, c[0]) else: second_group.append(c) max_second_group = max(max_second_group, c[1]) min_second_group = min(min_first_group, c[1]) first_group = silly_sort(first_group, min_first_group, max_first_group, lambda c: c[0]) second_group = reversed(list(silly_sort(second_group, min_second_group, max_second_group, lambda c: c[1]))) order = chain(first_group, second_group) cum_sum = 0 for c in order: cum_sum -= c[0] if cum_sum < 0: return 'No' cum_sum += c[1] if cum_sum == 0: return 'Yes' return 'No' if __name__ == '__main__': main()
0
null
16,820,573,154,608
113
152
# coding: utf-8 import sys import collections def main(): n, quantum = map(int, raw_input().split()) processes = [x.split() for x in sys.stdin.readlines()] for p in processes: p[1] = int(p[1]) queue = collections.deque(processes) elapsed = 0 while queue: # print elapsed, queue head = queue.popleft() if head[1] > quantum: head[1] -= quantum queue.append(head) elapsed += quantum else: elapsed += head[1] print head[0], elapsed if __name__ == '__main__': main()
import math h,w = map(int,input().split()) ans = 0 if h == 1 or w ==1 : ans += 1 else: #奇数行目+偶数行目 ans += math.ceil(h/2)*math.ceil(w/2)+(h//2)*(w//2) print(ans)
0
null
25,306,866,118,452
19
196
N = int(input()) print(N//2 if N%2==0 else N//2+1)
import itertools n, m, x = map(int, input().split()) A = [] for _ in range(n): A.append(list(map(int, input().split()))) c = [ (0, 1) for _ in range(n)] min_price = float('inf') for cc in itertools.product(*c): xx = [0] * m price = 0 for i, ccc in enumerate(cc): if ccc==1: price += A[i][0] xx = [a +b for a, b in zip(xx, A[i][1:])] if min(xx) >= x: min_price = min(min_price, price) if min_price==float('inf'): print(-1) else: print(min_price)
0
null
40,482,783,182,172
206
149
N = int(input()) S, T = map(str, input().split()) result = [] for i in range(N): result.append(S[i]) result.append(T[i]) print(''.join(result))
n = int(input()) S,T = input().split() result = '' for s,t in zip(S,T): result += s result += t print(result)
1
112,038,736,524,508
null
255
255
#!/usr/bin/env python3 import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines def main(): S = readline().rstrip().decode() print('x' * len(S)) if __name__ == '__main__': main()
s = input() t = len(s) print('x'*t)
1
73,089,882,125,930
null
221
221
for i in range(1,10001): x = int(input()) if(x == 0): break print('Case ', i, ': ', x, sep='')
i=1 while True: line = int(input()) if line==0: break print('Case {i}: {line}'.format(i=i,line=line)) i+=1
1
487,146,333,410
null
42
42
a = str(input()) if a[0] == a[1] != a[2]: print("Yes") elif a[1] == a[2] != a[0]: print("Yes") elif a[0] == a[2] != a[1]: print("Yes") else: print("No")
from sys import stdin, stdout n, m = map(int, stdin.readline().strip().split()) if m>=n: print('unsafe') else: print('safe')
0
null
41,937,688,206,420
201
163
x = input() print x**3
n = int(raw_input()) i = 0 s = [] h = [] c = [] d = [] def order_list(list): l = len(list) for i in xrange(l): j = i + 1 while j < l: if list[i] > list[j]: temp = list[i] list[i] = list[j] list[j] = temp j += 1 return list def not_enough_cards(mark, list): list = order_list(list) # line = "########################################" # print line # print mark + ":" # print list # print line i = 0 for x in xrange(1, 14): # print "x = " + str(x) + ", i = " + str(i) if i >= len(list): print mark + " " + str(x) elif x != list[i]: print mark + " " + str(x) else: i += 1 while i < n: line = raw_input().split(" ") line[1] = int(line[1]) if line[0] == "S": s.append(line[1]) elif line[0] == "H": h.append(line[1]) elif line[0] == "C": c.append(line[1]) elif line[0] == "D": d.append(line[1]) i += 1 not_enough_cards("S", s) not_enough_cards("H", h) not_enough_cards("C", c) not_enough_cards("D", d)
0
null
652,576,086,122
35
54
import sys heights = [int(i) for i in sys.stdin.read().split()] heights.sort(reverse=True) print("\n".join(map(str, heights[:3])))
L=[] for i in range(0,10): x = raw_input() L.append(int(x)) L.sort() for i in range(0,3): print L.pop()
1
39,603,750
null
2
2
def main(): target_word = str(input()).lower() texts_tuple = tuple() while True: text = input() if text == 'END_OF_TEXT': break texts_tuple += tuple(text.lower().split()) print(texts_tuple.count(target_word)) main()
W = input().lower() T = "" while True: inp = input().strip() if inp == 'END_OF_TEXT': break T += inp.strip().lower()+' ' print(T.split().count(W))
1
1,836,403,651,852
null
65
65
n = int( raw_input( ) ) dic = {} output = [] for i in range( n ): cmd, word = raw_input( ).split( " " ) if "insert" == cmd: dic[ word ] = True elif "find" == cmd: if not dic.get( word ): output.append( "no" ) else: output.append( "yes" ) print( "\n".join( output ) )
n = int( raw_input( ) ) dic = {} for i in range( n ): cmd, word = raw_input( ).split( " " ) if "insert" == cmd: dic[ word ] = True elif "find" == cmd: if not dic.get( word ): print( "no" ) else: print( "yes" )
1
75,835,404,490
null
23
23
N = int(input()) G = [[-1] * N for i in range(N)] ans = 0 for i in range(N): A = int(input()) for j in range(A): x, y = map(int, input().split()) G[i][x-1] = y for bit in range(2**N): honests = [] for i in range(N): if bit & (1<<i): honests.append(i) flag = True for j in honests: for k in range(N): if (k in honests) and G[j][k] == 0: flag = False elif(k not in honests) and G[j][k] == 1: flag = False if flag: ans = max(ans, len(honests)) print(ans)
N = int(input()) W = [[-1]*N for _ in range(N)] for i in range(N): A = int(input()) for j in range(A): x, y = [int(z) for z in input().split()] x -= 1 W[i][x] = y M = 0 for b in range(2**N): d = [0] * N for i in range(N): if (b >> i) & 1: d[i] = 1 ok = True for i in range(N): if d[i] == 1: for j in range(N): if W[i][j] == -1: continue if W[i][j] != d[j]: ok =False if ok == True: M = max(M, sum(d)) print(M)
1
121,429,600,343,174
null
262
262
import sys import numpy as np from collections import defaultdict sr = lambda: sys.stdin.readline().rstrip() ir = lambda: int(sr()) lr = lambda: list(map(int, sr().split())) N, K = lr() A = np.array([1] + lr()) A = (A-1) % K N += 1 # 累積和が同じになっている箇所に注目、要素がK-1離れている組み合わせは無理 Acum = (A.cumsum() % K).tolist() answer = 0 dic = defaultdict(int) for i, cur in enumerate(Acum): answer += dic[cur] dic[cur] += 1 if i >= K-1: vanish = Acum[i-(K-1)] dic[vanish] -= 1 print(answer) # 10
from itertools import accumulate from collections import defaultdict n, k = map(int, input().split()) a = list(map(int, input().split())) acc = [0] + list(accumulate(a)) sm = [(e - i) % k for i, e in enumerate(acc)] d = defaultdict(int) ans = 0 for r in range(1, n + 1): if r - k >= 0: e = sm[r - k] d[e] -= 1 e = sm[r - 1] d[e] += 1 e = sm[r] ans += d[e] print(ans)
1
137,741,371,515,520
null
273
273
N=int(input()) A=["a"] if N==1: print("a") exit() else: S="abcdefghijklmn" slist=list(S) for i in range(2,N+1): temp=[[] for _ in range(N)] for j in range(i-1): for w in A[j]: for u in slist[:j+1]: temp[j].append(w+u) temp[j+1].append(w+slist[j+1]) A=temp B=[] for j in range(N): for t in A[j]: B.append(t) B.sort() for i in range(len(B)): print(B[i])
n = int(input()) count = 0 ans = 0 for i in range(n): s = input().split() if s[0]==s[1]: count += 1 else: count = 0 if count ==3: print('Yes') exit(0) else: print('No')
0
null
27,488,378,369,452
198
72
#! python3 # spreadsheet.py r, c = [int(x) for x in input().split(' ')] sheet = [[int(x) for x in input().split(' ')] for i in range(r)] for i in range(r): sheet[i].append(0) sheet.append([0 for i in range(c+1)]) for i in range(r): for j in range(c): sheet[i][c] += sheet[i][j] sheet[r][j] += sheet[i][j] sheet[r][c] += sheet[i][j] for i in range(r+1): print(' '.join([str(x) for x in sheet[i]]))
''' ITP-1_7-C ??¨?¨???? ??¨?¨??????????????°???????????????°??????????????????????????? ??¨????????°r??¨?????°c???r ?? c ???????´????????????¨?????????????????§???????????¨??????????¨?????????\????????°????????¨??????????????? ????????°????????????????????????????????? ???Input ???????????????r??¨c????????????????????§??????????????????????¶????r??????????????????c????????´??°????????????????????§????????????????????? ???Output (r+1) ?? (c+1) ?????°????????¨??????????????????????????????????????£???????????´??°????????????????????§????????£??????????????? ???????????????????????¨??????????????????????¨?????????????????????????????????¨??????????????????????¨?????????? ???????????????????????¨??¨??????????¨????????????\?????????????????? ''' # inputData r, c = map(int, input().split()) data = [list(map(int, input().split())) for i in range(r)] for row in data: row.append(sum(row)) print(*row) # zip ????´?????????????????????????????????¨?????§????????????????????§?????? columnSum = [sum(Column) for Column in zip(*data)] print(*columnSum)
1
1,371,378,834,292
null
59
59
n = input() for i in range(len(n)): if(n[i] == '7'): print("Yes") exit() print("No")
# -*- coding: utf-8 -*- n = int(raw_input()) num = map(int, raw_input().split()) for e in num[::-1]: if e == num[0]: print e break print e,
0
null
17,782,516,110,548
172
53
X, K, D = map(int, input().split()) X = abs(X) div, mod = divmod(X, D) if X > D * K: ans = X - D * K elif (K - div) % 2 == 0: ans = mod else: ans = D - mod print(ans)
#from statistics import median #import collections #aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0] from fractions import gcd from itertools import combinations,permutations,accumulate # (string,3) 3回 #from collections import deque from collections import deque,defaultdict,Counter import decimal import re #import bisect # # d = m - k[i] - k[j] # if kk[bisect.bisect_right(kk,d) - 1] == d: # # # # pythonで無理なときは、pypyでやると正解するかも!! # # # my_round_int = lambda x:np.round((x*2 + 1)//2) # 四捨五入 import sys sys.setrecursionlimit(10000000) mod = 10**9 + 7 #mod = 9982443453 def readInts(): return list(map(int,input().split())) def I(): return int(input()) n = I() A = readInts() nya = [] for i in range(n): nya.append((i+1,A[i])) nya = sorted(nya,key = lambda x:x[1]) ans = [] for (idx,po) in nya: ans.append(idx) print(*ans)
0
null
93,344,368,155,302
92
299
#init N = int(input()) S=[input() for i in range(N)] for word in ['AC', 'WA', 'TLE', 'RE']: print('{0} x {1}'.format(word, S.count(word)))
num = int(input()) ac = 0 wa = 0 tle = 0 re = 0 for i in range(num): k = input() if k == "AC": ac += 1 elif k == "WA": wa += 1 elif k == "TLE": tle += 1 elif k == "RE": re += 1 print("AC x " + str(ac)) print("WA x " + str(wa)) print("TLE x " + str(tle)) print("RE x " + str(re))
1
8,687,992,584,220
null
109
109
N = int(input()) def solve(N): fib = [1]*(N+1) for i in range(2,N+1): fib[i] = fib[i-1] + fib[i-2] ans = fib[N] return ans print(solve(N))
# -*- coding: utf_8 -*- n = int(input()) + 1 arr = [-1] * n arr[0] = 1 arr[1] = 1 for i in range(2, len(arr)): arr[i] = arr[i - 1] + arr[i - 2] print(arr[n - 1])
1
1,925,535,130
null
7
7
from functools import reduce from fractions import gcd import math import bisect import itertools import sys sys.setrecursionlimit(10**7) input = sys.stdin.readline INF = float("inf") MOD = 998244353 # 処理内容 def main(): N, S = map(int, input().split()) A = list(map(int, input().split())) dp = [[0]*(S+1) for _ in range(N+1)] dp[0][0] = 1 for i in range(N): for j in range(S+1): dp[i+1][j] += dp[i][j] * 2 dp[i+1][j] %= MOD if j + A[i] > S: continue dp[i+1][j+A[i]] += dp[i][j] dp[i+1][j+A[i]] %= MOD print(dp[N][S]) if __name__ == '__main__': main()
import sys from collections import defaultdict from queue import deque readline = sys.stdin.buffer.readline sys.setrecursionlimit(10**8) def geta(fn=lambda s: s.decode()): return map(fn, readline().split()) def gete(fn=lambda s: s.decode()): return fn(readline().rstrip()) def egcd(a: int, b: int): """ A solution of ax+by=gcd(a,b). Returns (gcd(a,b), (x, y)). """ if a == 0: return b, 0, 1 else: g, x, y = egcd(b % a, a) return g, y - (b // a) * x, x def modinv(a: int, mod: int = 10**9 + 7): """ Returns a^{-1} modulo m. """ g, x, y = egcd(a, mod) if g > 1: raise Exception('{}^(-1) mod {} does not exist.'.format(a, mod)) else: return x % mod def main(): N, S = geta(int) A = list(geta(int)) A.sort() mod = 998244353 inv2 = modinv(2, mod) dp = [[0] * (S + 1) for _ in range(N + 1)] for s in range(S + 1): dp[0][s] = 0 _t = pow(2, N, mod) for n in range(N + 1): dp[n][0] = _t for i in range(1, N + 1): for j in range(1, S + 1): if j >= A[i - 1]: dp[i][j] = dp[i - 1][j - A[i - 1]] * inv2 + dp[i - 1][j] else: dp[i][j] = dp[i - 1][j] dp[i][j] %= mod print(dp[N][S]) if __name__ == "__main__": main()
1
17,842,522,613,920
null
138
138
nm = input().split(" ") n = int(nm[0]) m = int(nm[1]) if n == m: print("Yes") else: print("No")
X=int(input()) MAX=2*int(X**(1/5))+1 MIN=-2*int(X**(1/5))-1 for A in range(MIN,MAX): for B in range(MIN,MAX): if A**5-B**5==X: print(A,B) exit()
0
null
54,331,533,367,160
231
156
n=int(input()) c=input() r_cnt=c.count('R') w_cnt=c.count('W') last_c='R'*r_cnt+'W'*w_cnt num=0 for i in range(n): if c[i]!=last_c[i]: num+=1 print((num+2-1)//2)
a, b, c = [int(x) for x in input().split(" ")] if a < b and b < c: ans ="Yes" else: ans ="No" print(ans)
0
null
3,341,947,188,008
98
39
from collections import deque dq=deque() n=int(input()) for i in range(n): com=input().split() if com[0]=='insert': dq.appendleft(com[1]) elif com[0]=='deleteFirst': dq.popleft() elif com[0]=='deleteLast': dq.pop() else: if com[1] in dq: dq.remove(com[1]) print(' '.join(dq))
import collections q = collections.deque() n = int(input()) for i in range(n): com = input().split() if com[0] == 'insert': q.appendleft(int(com[1])) elif com[0] == 'delete': try: q.remove(int(com[1])) except: pass elif com[0] == 'deleteFirst': q.popleft() elif com[0] == 'deleteLast': q.pop() print(*q)
1
50,748,952,860
null
20
20
n,m=map(int,raw_input().split()) A,B=[],[] c=0 for i in xrange(n): A.append(map(int,raw_input().split())) for i in xrange(m): B.append(int(raw_input())) for i in xrange(n): for j in xrange(m): c+=A[i][j]*B[j] print c c=0
a, b = map(int, input().split()) mat = [map(int, input().split()) for i in range(a)] vec = [int(input()) for i in range(b)] for row in mat: print(sum([x*y for x, y in zip(row, vec)]))
1
1,186,678,752,132
null
56
56
class unionfind(): def __init__(self,n): #親番号<0なら根 #根の場合、数値の絶対値が要素数 self.par=[-1 for i in range(n)] def root(self,x): par=self.par if par[x]<0: return x else: self.x = self.root(par[x]) return self.x def unite(self,x,y): #高いほうに低いほうをくっつける rx=self.root(x) ry=self.root(y) if rx==ry: return else: if self.par[rx]>self.par[ry]: rx,ry = ry,rx self.par[rx]+=self.par[ry] self.par[ry] = rx def same(self, x,y): return self.root(x) == self.root(y) def par_print(self): print(self.par) def count(self, x): return -self.root(x) n,m = map(int,input().split()) friend = unionfind(n) for i in range(m): a,b = map(int,input().split()) friend.unite(a-1,b-1) # print(friend.par_print()) # print(friend.par_print()) ans = -min(friend.par) print(ans)
N = int(input()) P = [input().split() for i in range(N)] M = input() chk = 0 value = 0 for i, (k, v) in enumerate(P): if k == M: chk = int(v) elif chk != 0: value += int(v) print(value)
0
null
50,214,010,822,208
84
243
from itertools import permutations n = int(input()) p = [int(i) for i in input().split()] q = [int(i) for i in input().split()] perm = list(permutations(sorted(p), n)) #; print(perm) a = perm.index(tuple(p)) b = perm.index(tuple(q)) print(abs(a-b))
import itertools N = int(input()) P = tuple(map(int,input().split())) Q = tuple(map(int,input().split())) perm = list(itertools.permutations(range(1,N+1))) for i in range(len(perm)): if P == perm[i]: a = i if Q == perm[i]: b = i print(abs(a-b))
1
100,409,607,491,398
null
246
246
from collections import deque H, W = map(int, input().split()) S_raw = [list(input()) for _ in range(H)] m = 0 def calc(h,w): S = [list(S_raw[i][j] for j in range(W)) for i in range(H)] S[h][w]=0 queue = deque([(h,w)]) while queue: q = queue.popleft() for x in ((q[0]-1, q[1]),(q[0]+1, q[1]), (q[0], q[1]-1), (q[0], q[1]+1)): if 0<=x[0]<=H-1 and 0<=x[1]<=W-1: if S[x[0]][x[1]]==".": S[x[0]][x[1]] = S[q[0]][q[1]]+1 queue.append(x) return max(S[h][w] for w in range(W) for h in range(H) \ if str(S[h][w]).isdigit()) for h in range(H): for w in range(W): if S_raw[h][w]==".": m = max(m, calc(h,w)) print(m)
def main(): H, W = [int(x) for x in input().split(" ")] S = [] S.append(["X"] * (W + 2)) h = 0 w = 0 for i in range(H): row = list(input()) S.append(["X"] + row + ["X"]) if not h and not w and row.count(".") > 0: h = i + 1 w = row.index(".") + 1 S.append(["X"] * (W + 2)) ans = [] for i in range(H): for j in range(W): ans.append(BFS(S, i + 1, j + 1, H + 2, W + 2)) print(max(ans)) def BFS(M, i, j, H, W): if M[i][j] != ".": return 0 to_visit = [{"row": i, "col": j, "step": 0}] checked = [[0] * W for x in range(H)] checked[i][j] = 1 z = [[0] * W for x in range(H)] while len(to_visit): visiting = to_visit.pop(0) r0 = visiting["row"] c0 = visiting["col"] s0 = visiting["step"] z[r0][c0] = s0 for d in [[1, 0], [-1, 0], [0, 1], [0, -1]]: r = r0 + d[0] c = c0 + d[1] s = s0 + 1 if checked[r][c] == 0 and M[r][c] == ".": to_visit.append({"row": r, "col": c, "step": s}) checked[r][c] = 1 a = 0 for i in range(len(z)): for j in range(len(z[i])): if a < z[i][j]: a = z[i][j] return a main()
1
94,487,328,385,202
null
241
241
N = int(input()) A = sorted(list(map(int,input().split())),reverse=True) ans = A[0] for i in range(1,N//2): ans += 2* A[i] if N%2 == 1: ans += A[N//2] print(ans)
n = int(input()) lis = list(map(int,input().split())) lis = sorted(lis, reverse=True) ans = lis[0] res = [] for i in range(1,n): res.append(lis[i]) res.append(lis[i]) for i in range(n - 2): ans += res[i] print(ans)
1
9,214,057,299,138
null
111
111
input = raw_input() 3 input = int(input) ans = input**3 print ans
a, b, c = [int(i) for i in input().split()] if a < b: if b < c: print('Yes') else: print('No') else: print('No')
0
null
331,268,770,840
35
39
import sys sys.setrecursionlimit(10000000) input=sys.stdin.readline n = int(input()) a = list(map(int,input().split())) def gcd(a, b): return a if b == 0 else gcd(b, a%b) def lcm(a, b): return a // gcd(a, b) * b mod = 10**9+7 x=a[0] for i in a[1:]: x=lcm(x,i) ans=0 for i in range(n): ans+= x//a[i] print(ans%mod)
N = int(input()) A = list(map(int,input().split())) mod = pow(10,9)+7 ok = 1 import math from functools import reduce def lcm_base(x, y): return (x * y) // math.gcd(x, y) def lcm(*numbers): return reduce(lcm_base, numbers, 1) def lcm_list(numbers): return reduce(lcm_base, numbers, 1) LCM = lcm_list(A) import numpy as np B = np.array(A) C = LCM//B print(sum(C)%mod)
1
87,824,569,150,080
null
235
235
def bubbleSort(A,N): count = 0 flag = 1 while flag: flag = 0 for i in range(1,N): if A[N-i] < A[N-i-1]: A[N-i] , A[N-i-1] = A[N-i-1] , A[N-i] flag = 1 count += 1 return (count) n = int(input()) data = [int(i) for i in input().split()] a = bubbleSort(data,n) print(" ".join(map(str,data))) print(a)
def bubblesort(N, A): c, flag = 0, 1 while flag: flag = False for j in range(N-1, 0, -1): if A[j] < A[j-1]: A[j], A[j-1] = A[j- 1], A[j] c += 1 flag = True return (A, c) A, c = bubblesort(int(input()), list(map(int, input().split()))) print(' '.join([str(v) for v in A])) print(c)
1
15,386,082,432
null
14
14
#from statistics import median #import collections #aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0] from fractions import gcd from itertools import combinations,permutations,accumulate # (string,3) 3回 #from collections import deque from collections import deque,defaultdict,Counter import decimal import re #import bisect # # d = m - k[i] - k[j] # if kk[bisect.bisect_right(kk,d) - 1] == d: # # # # pythonで無理なときは、pypyでやると正解するかも!! # # import sys sys.setrecursionlimit(10000000) mod = 10**9 + 7 #mod = 9982443453 def readInts(): return list(map(int,input().split())) def I(): return int(input()) n,m = readInts() A = readInts() sumA = sum(A) div = sumA * (1/(4*m)) A = sorted(A,reverse=True) for i in range(m): if A[i] < div: print('No') exit() print('Yes')
def e_yutori(): # 参考: https://drken1215.hatenablog.com/entry/2020/04/05/163400 N, K, C = [int(i) for i in input().split()] S = input() def sub_solver(string): """string が表す労働日時に対して、労働数が最大になるように働いたとき、 i 日目には何回働いているかのリストを返す""" n = len(string) current, last = 0, -C - 1 # 最初に 'o' があっても動作するように設定 ret = [0] * (n + 1) for i in range(n): if i - last > C and string[i] == 'o': current += 1 last = i ret[i + 1] = current return ret left = sub_solver(S) right = sub_solver(S[::-1]) ans = [] for i in range(N): if S[i] == 'x': continue if left[i] + right[N - i - 1] < K: ans.append(i + 1) return '\n'.join(map(str, ans)) print(e_yutori())
0
null
39,680,180,269,570
179
182
n = int(input()) a = list(map(int, input().split())) ans_list = [None for _ in range(n)] for i in range(0, n): ans_list[a[i] - 1] = str(i + 1) print(" ".join(ans_list))
r, c = list(map(int,input().split())) S = [map(int,input().split()) for i in range(r)] col_sum = [0 for i in range(c)]; for row in S: row = list(row) print(' '.join(map(str,row)) + ' {}'.format(sum(row))) col_sum = [x + y for (x,y) in zip(col_sum,row)] print(' '.join(map(str,col_sum)) + ' {}'.format(sum(col_sum)))
0
null
91,385,691,668,580
299
59
import math a,b,C = (int(x) for x in input().split()) S = a * b * math.sin(math.radians(C)) / 2 L = math.sqrt(a ** 2 + b ** 2 - 2 * a * b * math.cos(math.radians(C))) + a + b h = b * math.sin(math.radians(C)) print(round(S,8),round(L,8),round(h,8))
# coding:utf-8 cal = { "+": lambda a, b: b+a, "-": lambda a, b: b-a, "*": lambda a, b: b*a } stack = [] for i in input().split(): if i in cal: stack.append(cal[i](stack.pop(), stack.pop())) else: stack.append(int(i)) print(stack[-1])
0
null
107,345,225,840
30
18
n = input() k = int(input()) dp0 = [[0]*(k+1) for _ in range(len(n)+1)] dp1 = [[0]*(k+1) for _ in range(len(n)+1)] dp0[0][0] = 1 for i in range(len(n)): for j in range(k+1): if int(n[i]) == 0: dp0[i+1][j] += dp0[i][j] if int(n[i]) > 0: dp1[i+1][j] += dp0[i][j] if j < k: dp0[i+1][j+1] += dp0[i][j] dp1[i+1][j+1] += dp0[i][j]*(int(n[i])-1) if j < k: dp1[i+1][j+1] += dp1[i][j]*9 dp1[i+1][j] += dp1[i][j] print(dp0[len(n)][k]+dp1[len(n)][k])
x,y=map(int,input().split()) print(['No','Yes'][y%2==0 and 2*x <= y <= 4*x])
0
null
45,094,539,545,516
224
127
A=list(map(int,input().split())) B=0 B=A[0]+A[1]+A[2] if B>=22: print("bust") else: print("win")
def solve(): N, K = map(int, input().split()) H = list(map(int, input().split())) if K>=N: return 0 H.sort() ans = sum(H[:N-K]) return ans print(solve())
0
null
99,252,458,933,628
260
227
N = input()[::-1] l = len(N) dp = [[0,0] for i in range(l+1)] for i in range(l): dp[i+1][0] = min(dp[i][0] + int(N[i]), dp[i][1] + int(N[i]) + 1) if i == 0: dp[i+1][1] = 10 - int(N[i]) else: dp[i+1][1] = min(dp[i][0] + 10 - int(N[i]), dp[i][1] + 9 - int(N[i])) print(min(dp[-1][0],dp[-1][1]+1))
p1 , s1=map(int , input().split()) p2 , s2=map(int , input().split()) t=int(input()) if abs(p1-p2) > t*(s1-s2): print("NO") else: print("YES")
0
null
42,983,889,830,520
219
131
from math import ceil N,X,T = list(map(int,input().split(' '))) print(ceil(N/X)*T)
S = 0 N,X,T = map(int,input().split()) if N % X ==0: print((N // X)*T) else: print((N + X - 1)// X *T)
1
4,324,406,666,494
null
86
86
def resolve(): s, t = input().split() a, b = list(map(int, input().split())) u = input() if u == s: a -= 1 elif u == t: b -= 1 print(a, b) resolve()
def main(): s,t = input().split(" ") a, b = map(int, input().split(" ")) u = input() if u == s : a-= 1 else: b -= 1 print(f"{a} {b}") if __name__ == "__main__": main()
1
72,057,563,921,032
null
220
220
#!/usr/bin/env python # -*- coding: utf-8 -*- def main(): N = int(input()) A = [(i, v) for i, v in enumerate(map(int, input().split()))] values = [[0] * (N + 1) for _ in range(N + 1)] A.sort(key=lambda x:-x[1]) for i, (p, v) in enumerate(A): for j in range(i + 1): left = abs((p - j) * v) right = abs((N - 1 - (i - j) - p) * v) values[i + 1][j + 1] = max(values[i][j] + left, values[i + 1][j + 1]) values[i + 1][j] = max(values[i][j] + right, values[i + 1][j]) print(max(values[-1])) if __name__ == '__main__': main()
from sys import stdin, stdout import math import bisect import datetime n = int(stdin.readline().strip()) arr = list(map(int, stdin.readline().strip().split())) arr.insert(0,0) d={} for i in range(len(arr)): d[i] = arr[i] arr = sorted(d.items(), key=lambda a: a[1]) dp = [[0 for i in range(2005)] for j in range(2005)] for i in range(1, n + 1): dp[i][i]=arr[1][1]*abs(arr[1][0]-i) for l in range(2, n + 1): pos, val = arr[l] for left in range(1, n - l + 2): right = left + l - 1 dp[left][right] = max(dp[left + 1][right] + val * abs(pos - left), dp[left][right - 1] + val * abs(pos - right)) stdout.writelines(str(dp[1][n]) + '\n')
1
33,511,198,255,922
null
171
171
n,m,l = map(int,input().split()) A = [[int(i) for i in input().split()] for _ in range(n)] B = [[int(i) for i in input().split()] for _ in range(m)] res = [ [sum([ a*b for a,b in zip(A[i],list(zip(*B))[j]) ]) for j in range(l)] for i in range(n)] for r in res: print(*r)
n=int(input()) k="ACL" print(k*n)
0
null
1,798,571,929,752
60
69
S = str(input()) l = ['SUN','MON','TUE','WED','THU','FRI','SAT'] for i in range(7): if S == l[i]: print(7-i)
s = input() week = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"] ans_dic = {k: v for k, v in zip(week, range(7, 0, -1))} print(ans_dic[s])
1
132,885,013,370,290
null
270
270
N,X,M=map(int,input().split()) a=[0]*(M) A=X%M a[A]=1 ans=A Ans=[A] flag=0 for i in range(N-1): A=A*A%M if A==0: break if a[A]==1: flag=1 break a[A]=1 ans+=A Ans.append(A) if flag==1: for num in range(len(Ans)): if A==Ans[num]: break n=len(Ans)-num b=sum(Ans[:num]) x=(N-num)//n y=(N-num)%n Sum=b+(ans-b)*(x)+sum(Ans[num:y+num]) else: Sum=sum(Ans) print(Sum)
import sys sys.setrecursionlimit(10 ** 9) # input = sys.stdin.readline #### def int1(x): return int(x) - 1 def II(): return int(input()) def MI(): return map(int, input().split()) def MI1(): return map(int1, input().split()) def LI(): return list(map(int, input().split())) def LI1(): return list(map(int1, input().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def MS(): return input().split() def LS(): return list(input()) def LLS(rows_number): return [LS() for _ in range(rows_number)] def printlist(lst, k=' '): print(k.join(list(map(str, lst)))) INF = float('inf') # from math import ceil, floor, log2 # from collections import deque, defaultdict # from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations # from heapq import heapify, heappop, heappush # import numpy as np # cumsum # from bisect import bisect_left, bisect_right class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def all_group_members(self): return {r: self.members(r) for r in self.roots()} def __str__(self): return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots()) def solve(): N, M = MI() uf = UnionFind(N) for i in range(M): a, b = MI1() uf.union(a, b) print(uf.group_count()-1) if __name__ == '__main__': solve()
0
null
2,560,300,329,740
75
70
n = int(input()) a = list(map(int, input().split())) dict_diffs = dict() for i in range(1, n+1): dict_diffs[i+a[i-1]] = dict_diffs.get(i+a[i-1], 0) + 1 total = 0 for j in range(1, n+1): total += dict_diffs.get(j-a[j-1], 0) print(total)
from collections import defaultdict iim = lambda: map(int, input().rstrip().split()) def resolve(): N = int(input()) A = list(iim()) ans = 0 dp = [0]*N for i, ai in enumerate(A): x = i + ai if x < N: dp[x] += 1 x = i - ai if x >= 0: ans += dp[x] print(ans) resolve()
1
26,109,012,662,708
null
157
157
import math a,b,c = map(float,input().split()) sinc = math.sin(c*math.pi/180) cosc = math.cos(c*math.pi/180) c = math.sqrt(a**2+b**2-2*a*b*cosc) s = a*b*sinc/2.0 print(s) print(a+b+c) print(s/a*2.0)
import math e=map(float,raw_input().split()) a=e[0] b=e[1] C=math.radians(e[2]) c=(a**2+b**2-2*a*b*math.cos(C))**0.5 h=b*math.sin(C) S=h*a*0.5 L=a+b+c print S print L print h
1
172,242,900,480
null
30
30
n1 = input() A = map(int, raw_input().split()) n2 = input() q = map(int, raw_input().split()) list = set() def solve(i,m): if m == 0: return True if i >= n1 or m > sum(A): return False res = solve(i+1,m) or solve(i+1,m-A[i]) return res for m in q: if solve(0,m): print "yes" else: print "no"
n = int(input()) A = list(map(int,input().split())) q = int(input()) m = list(map(int,input().split())) sumA = sum(A) def solve(i,m): if m == 0: return 1 if i >= n: return 0 rec = solve(i+1,m) or solve(i+1, m - A[i]) return rec for i in m: if i >= sumA: print("no") else: if solve(0,i): print("yes") else: print("no")
1
99,642,626,160
null
25
25
import sys w = sys.stdin.readline().strip().lower() cnt = 0 while True: line = sys.stdin.readline().strip() if line == 'END_OF_TEXT': break words = line.split(' ') for i in words: if i.lower() == w: cnt += 1 print(cnt)
import sys write=sys.stdout.write for i in range(1,10): for j in range(1,10): write(str(i)) write('x') write(str(j)) write('=') write(str(i*j)) print()
0
null
926,290,812,018
65
1
a = int(input()) res = 0 for i in range(a+1): if i % 3 ==0 or i % 5 ==0: pass else: res += i print(res)
import itertools def check(targets): if targets[1] > targets[0] and targets[2] > targets[1]: return True else: return False if __name__ == "__main__": A, B, C = map(int, input().split()) K = int(input()) targets = [A, B, C] answer = 'No' cases = itertools.product([0, 1, 2], repeat=K) for case in cases: copy_targets = targets.copy() for i in case: copy_targets[i] = copy_targets[i] * 2 if check(copy_targets): answer = 'Yes' break print(answer)
0
null
20,715,127,029,070
173
101
s = int(input()) if(s<3): print(0) exit() l = s//3 cnt = 0 mod = 10**9+7 for i in range(l): if(i==0): cnt += 1 continue remain = s-3*(i+1) bar_remain = remain+i n = 1 for j in range(i): n*=(bar_remain-j) k = 1 for j in range(1,i+1): k*=j cnt += (n//k)%mod cnt %= mod print(cnt)
MOD = 10**9 + 7 def modinv(a, mod=10**9+7): return pow(a, mod-2, mod) def combination(n, r, mod=10**9+7): r = min(r, n-r) res = 1 for i in range(r): res = res * (n - i) * modinv(i+1, mod) % mod return res # print(combination(10,2)) s = int(input()) n = s//3 ans = 0 while n: S = s - n*3 # print(S+n-1,n-1) ans += combination(S+n-1,n-1) n-=1 print(ans%MOD)
1
3,301,678,088,940
null
79
79
# ABC162 # FizzBuzz Sum n = int(input()) ct = 0 for i in range(n + 1): if i % 3 != 0: if i % 5 != 0: ct += i else: continue print(ct)
X, N = [int(i) for i in input().split()] P = [int(i) for i in input().split()] # Xは0~101の値になる result = 0 current = 102 for i in range(102): if i not in P: if abs(X - i) < current: result = i current = abs(X - i) print(result)
0
null
24,488,169,124,288
173
128
a,b=input().split() ans=int(a)*round(float(b)*100)//100 print(int(ans))
a,b=[i for i in input().split()] a=int(a) b=round(float(b)*100) print(a*b//100)
1
16,535,529,829,940
null
135
135
# 19-String-Finding_a_Word.py # ?????????????´¢ # ??????????????? W ??¨?????? T ????????????????????????T ??????????????? W ?????°???????????????????????°????????????????????????????????? # ?????? T ????????????????????????????????????????????§????????????????????????????????? Ti ??¨???????????? # ???????????? Ti ?????????????????? W ??¨??????????????????????????°?????????????????? # ???????????§????????¨?°???????????????\??????????????? # Constraints # W????????????????????????10????¶???????????????? # T??????????????????????????????????????????1000????¶???????????????? # Input # ?????????????????? W ???????????????????????? # ?¶???????????????°????????????????????£?????????????????????????????? # END_OF_TEXT ??¨?????????????????????????????????????????????????????? # Output # ?????? W ?????°??????????????????????????? # Sample Input # computer # Nurtures computer scientists and highly-skilled computer engineers # who will create and exploit "knowledge" for the new era. # Provides an outstanding computer environment. # END_OF_TEXT # Sample Output # 3 # Note import re count=0 w = input().lower() while 1: string = input() if string=="END_OF_TEXT": break; for i in string.lower().split(): count += w==i print(count)
st = input() q = int(input()) for x in range(q): ip = list(input().split()) if ip[0] == "print": print(st[int(ip[1]):int(ip[2])+1]) elif ip[0] == "replace": ip[1] = int(ip[1]) ip[2] = int(ip[2]) temp = st[0:ip[1]] + ip[3] + st[ip[2]+1:] st = temp elif ip[0] == "reverse": ip[1] = int(ip[1]) ip[2] = int(ip[2]) temp = st[0:ip[1]] + st[ip[1]:ip[2]+1][::-1] + st[ip[2]+1:] st = temp
0
null
1,962,689,578,214
65
68
H,N = map(int,input().split()) a = list(map(int,input().split())) a.sort() reversed(a) flag = True for i in range(N): H-=a[i] if H<=0: flag = False print('Yes') break if flag == True: print('No')
h, n = map(int, input().split()) print("Yes" if sum(map(int, input().split())) >= h else "No")
1
78,175,598,277,750
null
226
226
k = int(input()) s = input() if(len(s) <= k): print(s) else: print(s[0:k]+"...")
k=int(input());s=input();print((s,s[:k]+'...')[k<len(s)])
1
19,628,486,917,280
null
143
143
_, vs, c = input(), list(map(int, input().split())), 0 for i in range(len(vs)): for j in range(len(vs)-1, i, -1): if vs[j] < vs[j-1]: vs[j], vs[j-1] = vs[j-1], vs[j] c += 1 print(' '.join(map(str, vs))) print(c)
sum = 0 while 1: x = int(raw_input()) sum = sum + 1 if x == 0: break print 'Case %s: %s' %(sum, x)
0
null
246,089,022,268
14
42
n = int(input()) S = [] T = [] for _ in range(n): s, t = input().split() S.append(s) T.append(int(t)) x = input() index = S.index(x) if index == n - 1: print(0) else: print(sum(T[index+1:]))
from collections import Counter N = int(input()) S = [input() for _ in range(N)] cntr = Counter(S) mc = cntr.most_common() n = mc[0][1] ans = [] for k, v in mc: if n!=v: break ans.append(k) ans.sort() print("\n".join(ans))
0
null
83,757,146,196,132
243
218
import math import sys import bisect import array m=10**9 + 7 sys.setrecursionlimit(1000010) (N,K) = map(int,input().split()) A = list( map(int,input().split())) # print(N,K,A) B = list( map(lambda x: x % K, A)) C = [0] x = 0 i = 0 for b in B: x = (x + b ) % K C.append((x-i-1) % K) i += 1 # print(B,C) E={} ans=0 for i in range(N+1): if C[i] in E: ans += E[C[i]] E[C[i]] = E[C[i]] + 1 else: E[C[i]] = 1 if i >= K-1: E[C[i-K+1]] = E[C[i-K+1]] - 1 if E[C[i-K+1]] == 0: E.pop(C[i-K+1]) print(ans) exit(0)
import sys def main(): input=sys.stdin.readline n,k=map(int,input().split()) a=list(map(int,input().split())) accum=[0]*n accum[0]=a[0] d=dict() ans=0 for i in range(1,n): accum[i]+=a[i]+accum[i-1] accum=[0]+accum for j in range(n+1): if j-k>=0: d[(accum[j-k]-(j-k))%k]-=1 if (accum[j]-j)%k not in d: d[(accum[j]-j)%k]=1 else: ans+=d[(accum[j]-j)%k] d[(accum[j]-j)%k]+=1 #print(d) return print(ans) if __name__=='__main__': main()
1
137,257,910,229,088
null
273
273
#!/usr/bin/env python3 # Generated by https://github.com/kyuridenamida/atcoder-tools from typing import * import itertools import math import sys INF = float('inf') def solve(K: int, S: str): return S[:K] + ['...', ''][len(S) <= K] def main(): sys.setrecursionlimit(10 ** 6) def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() K = int(next(tokens)) # type: int S = next(tokens) # type: str print(solve(K, S)) if __name__ == '__main__': main()
# Aizu Problem 0001: List of Top 3 Hills # import sys, math, os # read input: PYDEV = os.environ.get('PYDEV') if PYDEV=="True": sys.stdin = open("sample-input2.txt", "rt") for h in sorted([int(input()) for _ in range(10)], reverse=True)[:3]: print(h)
0
null
9,763,305,707,300
143
2
H, N = map(int, input().split()) N = list(map(int, input().split())) print("Yes") if(sum(N) >= H) else print("No")
a = [int(i) for i in input().split()] if a[0]+a[1]<=a[2]: print(0,0) elif a[0]>=a[2]: print(a[0]-a[2],a[1]) elif a[0]<a[2]: b = a[2]-a[0] print(0,a[1]-b)
0
null
91,388,999,767,172
226
249
n, m, k = map(int, input().split()) friendships = [[] for _ in range(n)] for _ in range(m): a, b = map(int, input().split()) friendships[a-1].append(b-1) friendships[b-1].append(a-1) blockships = [[] for _ in range(n)] for _ in range(k): c, d = map(int, input().split()) blockships[c-1].append(d-1) blockships[d-1].append(c-1) # assign users (id) for connected component, according to friendships # also increment a counter for size of each component component_id = [-1]*n component_size = dict() stack_to_visit = [(node, node) for node in range(n)] while stack_to_visit: node, parent_id = stack_to_visit.pop() if component_id[node] != -1: continue component_id[node] = parent_id component_size[parent_id] = component_size.get(parent_id, 0) + 1 for other in friendships[node]: stack_to_visit.append((other, parent_id)) # calculate number of suggestions for each node for node in range(n): suggestions = 0 current_id = component_id[node] suggestions += component_size[current_id] - 1 suggestions -= len(friendships[node]) suggestions -= sum(int(component_id[other] == current_id) for other in blockships[node]) print(suggestions, end=" ")
word = input() if word.endswith('s'): print(word+"es") else: print(word+"s")
0
null
31,909,683,309,140
209
71
from collections import defaultdict N = int(input()) *A,=map(int,input().split()) ''' 方針: - 各A_i,(i<h)ごとにf(h,j)=A_h+A_j-|h-j|の値がf(i,j)に比べてどれだけ変化するかを計算し、 リストに格納(①) - 各要素A_k,(j<k)ごとにf(i,k)=A_i+A_k-|i-k|の値がf(i,j)に比べてどれだけ変化するかを 計算し、カウントをとる(②) - 再度ループを回して①と②を照合し、値が一致する組数をansに加算 ''' ans=0 diff_list=[] #①照合用の差分リスト count=defaultdict(int) #②各要素がどれだけはみ出ているかのカウント #前処理として、最初のループで①と②を作成 for i in range(1,N): if i == A[0]+A[i]: ans += 1 d1 = A[i]-A[0] d2 = i diff_list.append(d1+d2) count[A[0]+A[i]-i] += 1 for i in range(N-1): count[A[0]+A[i+1]-(i+1)] -= 1 #その要素自身を忘れずに引く d = diff_list[i] ans += count[-d] print(ans)
from collections import defaultdict def main(): d = defaultdict(int) d2 = defaultdict(int) N = int(input()) A = list(map(int, input().split())) for i in range(N): d[i + 1 + A[i]] += 1 d2[max(0, (i + 1) - A[i])] += 1 ans = 0 for k,v in d.items(): if k == 0:continue ans += v * d2[k] print(ans) if __name__ == '__main__': main()
1
26,076,885,013,452
null
157
157
SIZE = 2**20 # 2**20 > N=500000 class SegmentTree: def __init__(self, size): self.size = size self.seg = [0] * (2 * size) def update(self, pos, ch): # update leaf i = self.size + pos - 1 self.seg[i] = 1 << (ord(ch)-ord('a')) # update tree while i > 0: i = (i - 1) // 2 self.seg[i] = self.seg[i*2+1] | self.seg[i*2+2] def _query(self, a, b, k, left, right): if right<a or b<left: return 0 if a<=left and right<=b: return self.seg[k] vl = self._query(a,b,k*2+1, left, (left+right)//2) vr = self._query(a,b,k*2+2, (left+right)//2+1, right) return vl | vr def query(self, a, b): return self._query(a,b,0,0,self.size-1) def resolve(): N = int(input()) S = input().strip() Q = int(input()) table = [[] for _ in range(26)] sg = SegmentTree(SIZE) for i,ch in enumerate(S): sg.update(i, ch) for i in range(Q): query = input().strip().split() if query[0] == '1': pos = int(query[1])-1 sg.update(pos, query[2]) else: left = int(query[1])-1 right = int(query[2])-1 bits = sg.query(left, right) count = 0 for j in range(26): count += (bits>>j) & 1 print(count) resolve()
X = int(input()) rank = -1 if X <= 599: rank = 8 elif X <= 799: rank = 7 elif X <= 999: rank = 6 elif X <= 1199: rank = 5 elif X <= 1399: rank = 4 elif X <= 1599: rank = 3 elif X <= 1799: rank = 2 else: rank = 1 print(rank)
0
null
34,750,573,083,798
210
100
import sys import bisect N = int(sys.stdin.readline().rstrip()) S = list(sys.stdin.readline().rstrip()) Q = int(sys.stdin.readline().rstrip()) idx = {chr(ord("a") + i): [] for i in range(26)} for i, s in enumerate(S): idx[s].append(i + 1) for _ in range(Q): t, i, c = sys.stdin.readline().rstrip().split() i = int(i) if t == "1": if S[i - 1] != c: idx[S[i - 1]].remove(i) bisect.insort(idx[c], i) S[i - 1] = c else: c = int(c) ans = 0 for a, id in idx.items(): x = bisect.bisect_left(id, i) y = bisect.bisect_right(id, c) if y - x: ans += 1 print(ans)
class BalancingTree: """平衡二分木のクラス Pivotを使った実装. 0以上2^n - 2以下の整数を扱う """ def __init__(self, n): """ 2の指数nで初期化 """ self.N = n self.root = self.node(1<<n, 1<<n) def debug(self): """デバッグ用の関数""" def debug_info(nd_): return (nd_.value - 1, nd_.pivot - 1, nd_.left.value - 1 if nd_.left else -1, nd_.right.value - 1 if nd_.right else -1) def debug_node(nd): re = [] if nd.left: re += debug_node(nd.left) if nd.value: re.append(debug_info(nd)) if nd.right: re += debug_node(nd.right) return re print("Debug - root =", self.root.value - 1, debug_node(self.root)[:50]) def append(self, v): """ v を追加(その時点で v はない前提) """ v += 1 nd = self.root while True: if v == nd.value: # v がすでに存在する場合に何か処理が必要ならここに書く return 0 else: mi, ma = min(v, nd.value), max(v, nd.value) if mi < nd.pivot: nd.value = ma if nd.left: nd = nd.left v = mi else: p = nd.pivot nd.left = self.node(mi, p - (p&-p)//2) break else: nd.value = mi if nd.right: nd = nd.right v = ma else: p = nd.pivot nd.right = self.node(ma, p + (p&-p)//2) break def leftmost(self, nd): if nd.left: return self.leftmost(nd.left) return nd def rightmost(self, nd): if nd.right: return self.rightmost(nd.right) return nd def find_l(self, v): """ vより真に小さいやつの中での最大値(なければ-1) """ v += 1 nd = self.root prev = 0 if nd.value < v: prev = nd.value while True: if v <= nd.value: if nd.left: nd = nd.left else: return prev - 1 else: prev = nd.value if nd.right: nd = nd.right else: return prev - 1 def find_r(self, v): """ vより真に大きいやつの中での最小値(なければRoot) """ v += 1 nd = self.root prev = 0 if nd.value > v: prev = nd.value while True: if v < nd.value: prev = nd.value if nd.left: nd = nd.left else: return prev - 1 else: if nd.right: nd = nd.right else: return prev - 1 @property def max(self): """最大値の属性""" return self.find_l((1<<self.N)-1) @property def min(self): """最小値の属性""" return self.find_r(-1) def delete(self, v, nd = None, prev = None): """ 値がvのノードがあれば削除(なければ何もしない) """ v += 1 if not nd: nd = self.root if not prev: prev = nd while v != nd.value: prev = nd if v <= nd.value: if nd.left: nd = nd.left else: return else: if nd.right: nd = nd.right else: return if (not nd.left) and (not nd.right): if nd.value < prev.value: prev.left = None else: prev.right = None elif not nd.left: if nd.value < prev.value: prev.left = nd.right else: prev.right = nd.right elif not nd.right: if nd.value < prev.value: prev.left = nd.left else: prev.right = nd.left else: nd.value = self.leftmost(nd.right).value self.delete(nd.value - 1, nd.right, nd) def __contains__(self, v: int) -> bool: return self.find_r(v - 1) == v class node: """ノードをあらわすクラス v: 値 p: ピボット値 で初期化 """ def __init__(self, v, p): self.value = v self.pivot = p self.left = None self.right = None Trees = [BalancingTree(50) for _ in range(26)] N = int(input()) S = input() Q = int(input()) alphabets = list("abcdefghijklmnopqrstuvwxyz") c2n = {c: i for i, c in enumerate(alphabets)} for i in range(N): Trees[c2n[S[i]]].append(i+1) S = list(S) for _ in range(Q): tmp = list(input().split()) if tmp[0] == "1": _, i, c = tmp i = int(i) bef = S[i-1] if bef == c: continue Trees[c2n[bef]].delete(i) Trees[c2n[c]].append(i) S[i-1] = c else: _, l, r = tmp l = int(l) r = int(r) ans = 0 for char in range(26): res = Trees[char].find_r(l-1) if l <= res <= r: ans += 1 print(ans)
1
62,580,614,715,202
null
210
210
import collections N = int(input()) hList = list(map(int, input().split())) count = 0 n_p = collections.Counter([ i + hList[i] for i in range(len(hList))]) for i in range(N): if i - hList[i] > 0: count += n_p.get(i - hList[i], 0) print(count)
num = input() lst = [] for x in num: lst.append(int(x)) total = sum(lst) if total % 9 == 0: print('Yes') else: print('No')
0
null
15,232,444,334,910
157
87