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
|
---|---|---|---|---|---|---|
import math
import itertools
n = int(input())
d =list(map(int,input().split()))
p = list(itertools.combinations(d, 2))
ans = 0
for i in range(len(p)):
d = p[i][0] * p[i][1]
ans = ans + d
print(ans) | a, b, c = map(int, input().split())
if a*a + b*b + c*c -2*(a*b + b*c + c*a) > 0 and c-a-b > 0:
print("Yes")
else:
print("No") | 0 | null | 110,345,693,882,908 | 292 | 197 |
from collections import defaultdict
def main():
N = int(input())
dd = defaultdict(int)
for _ in range(N):
si = input()
dd[si] += 1
maxv = max(dd.items(), key = lambda item: item[1])[-1]
strings = [key for key, val in dd.items() if val == maxv]
strings = sorted(strings)
for string in strings:
print(string)
if __name__ == '__main__':
main()
| n = int(input())
d = dict()
for i in range(n):
s = input()
if(s not in d.keys()):
d[s] = 1
else:
d[s] +=1
max = max(d.values())
ans = []
for i in d.keys():
if(d[i] == max):
ans.append(i)
for i in sorted(ans):
print(i)
| 1 | 70,099,145,932,448 | null | 218 | 218 |
from sys import stdin, setrecursionlimit
def main():
input = stdin.buffer.readline
n, r = map(int, input().split())
if n >= 10:
print(r)
else:
print(r + 100 * (10 - n))
if __name__ == "__main__":
setrecursionlimit(10000)
main()
| x = input().split()
n = int(x[0])
r = int(x[1])
if n >= 10:
pass
else:
r = r + 100 *(10-n)
print(r) | 1 | 63,475,854,856,484 | null | 211 | 211 |
x , y = map(int,input().split())
def GCD(x,y):
while y > 0:
x ,y = y , x %y
else:
return x
ans = GCD(x,y)
print(ans) |
x,y=map(int,input().split())
a=1
while a!=0:
if x>y:
a=x%y
else:
a=y%x
x=y
y=a
print(x)
| 1 | 7,735,229,110 | null | 11 | 11 |
N, K = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(K)]
# dpの高速化 => 累積和によって、O(N)で解く
dp = [0] * N
acc = [0]* (N+1)
dp[0], acc[1] = 1, 1
# acc[0] = 0
# acc[1] = dp[0]
# acc[2] = dp[0] + dp[1]
# acc[n] = dp[0] + dp[1] + dp[n-1]
# dp[0] = acc[1] - acc[0]
# dp[1] = acc[2] - acc[1]
# dp[n-1] = acc[n] - acc[n-1]
mod = 998244353
for i in range(1, N):
# acc[i] = dp[0] + ... + dp[i-1] が既知
# 貰うdp
for j in range(K):
r = i - X[j][0]
l = i - X[j][1]
if r < 0: continue
l = max(l, 0)
dp[i] += acc[r+1] - acc[l] # s = dp[L] + ... + dp[R]
dp[i] %= mod
acc[i+1] = acc[i] + dp[i] # acc[i+1] = dp[0] + ... + dp[i]
print(dp[N-1]) | mod = 998244353
N, K = map(int, input().split())
LR = [list(map(int, input().split())) for _ in range(K)]
dp = [0] * (N+1)
dpsum = [0] * (N+1)
dp[1] = 1
dpsum[1] = 1
for i in range(2, N+1):
for l, r in LR:
li = i-r
ri = i-l
if ri < 0: continue
li = max(1, li)
dp[i] += dpsum[ri] - dpsum[li-1]
dp[i] = dp[i] % mod
dpsum[i] = dpsum[i-1] + dp[i]
dpsum[i] = dpsum[i] % mod
print(dp[N]) | 1 | 2,706,633,004,770 | null | 74 | 74 |
n = int(input())
d = [list(map(int, input().split())) for _ in range(n)]
cnt = 0
for i in range(n):
d1, d2 = d[i]
if d1 == d2:
cnt += 1
if cnt == 3:
print("Yes")
exit(0)
else:
cnt = 0
print("No") | import sys
n = int(sys.stdin.readline().strip())
S = map(int, sys.stdin.readline().strip().split(" "))
n = int(sys.stdin.readline().strip())
T = map(int, sys.stdin.readline().strip().split(" "))
res = []
for t in T:
res.append(int(S.count(t) != 0))
print sum(res) | 0 | null | 1,298,002,121,120 | 72 | 22 |
N = int(input())
As = list(map(int,input().split()))
As.sort()
M = 1000001
array = [0]*M
for a in As:
if array[a] != 0:
array[a] = 2
continue
for i in range(a,M,a):
array[i] += 1
ans = 0
for a in As:
if array[a] == 1:
ans += 1
print(ans)
| import heapq
n = int(input())
a = list(map(int, input().split()))
dp = [0] * (pow(10, 6) + 5)
heapq.heapify(a)
heapq.heappush(a, 1000003)
ans = -1
y = 0
for _ in range(n + 1):
x = heapq.heappop(a)
if x == y and dp[x] == 2:
dp[x] = 1
ans -= 1
continue
elif dp[x] == 0:
ans += 1
dp[x] = 2
i = 2
while i * x <= 1000000:
dp[i * x] = 1
i += 1
y = x
print(ans) | 1 | 14,430,053,823,228 | null | 129 | 129 |
S,W = map(int,input().split())
if S<=W:
print('unsafe')
else: print('safe') | from sys import stdin, stdout
n, m = map(int, stdin.readline().strip().split())
if m>=n:
print('unsafe')
else:
print('safe') | 1 | 29,130,689,541,690 | null | 163 | 163 |
k=int(input())
a=0
cnt=-1
for i in range(1,k+1):
a=(10*a+7)%k
if a==0:
cnt=i
break
print(cnt) | K = int(input())
mod = 7
number = 1
for i in range(K):
if mod % K == 0:
break
number += 1
mod = (mod * 10 + 7) % K
if mod % K == 0:
print(number)
else:
print(-1) | 1 | 6,109,874,514,560 | null | 97 | 97 |
import sys
i=1
for line in sys.stdin:
a=int(line)
if a == 0:
break
else:
print 'Case {0}: {1}'.format(i, a)
i+=1 | s=0
while True:
i=input()
if i == '0': break
s+=1
print("Case {}: {}".format(s,i)) | 1 | 471,145,757,504 | null | 42 | 42 |
s="ACL"*int(input())
print(s) | n = int(input())
print("".join(["ACL" for i in range(n)]))
| 1 | 2,191,039,553,714 | null | 69 | 69 |
from math import floor,ceil,sqrt,factorial,log
from collections import Counter, deque
from functools import reduce
import numpy as np
import itertools
def S(): return input()
def I(): return int(input())
def MS(): return map(str,input().split())
def MI(): return map(int,input().split())
def FLI(): return [int(i) for i in input().split()]
def LS(): return list(MS())
def LI(): return list(MI())
def LLS(): return [list(map(str, l.split() )) for l in input()]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def LLSN(n: int): return [LS() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
s = S()
cnt = 0
max = 0
for i in s:
if i == "R":
cnt += 1
else:
if max < cnt:
max = cnt
cnt = 0
if max < cnt:
max = cnt
print(max) | N = int(input())
*A, = map(int, input().split())
dic = {}
ans = 0
for i in range(N):
if A[i] + i in dic:
dic[A[i] + i] += 1
if A[i] + i not in dic:
dic[A[i] + i] = 1
if i - A[i] in dic:
ans += dic[i - A[i]]
print(ans) | 0 | null | 15,489,076,074,592 | 90 | 157 |
from collections import deque, defaultdict
def main():
N, X, Y = map(int, input().split())
g = [[] for _ in range(N)]
for i in range(N-1):
g[i].append(i+1)
g[i+1].append(i)
g[X-1].append(Y-1)
g[Y-1].append(X-1)
ans = defaultdict(int)
for i in range(N):
q = deque()
q.append(i)
visit_time = [0 for _ in range(N)]
while len(q):
v = q.popleft()
time = visit_time[v]
for j in g[v]:
if visit_time[j] == 0 and j != i:
q.append(j)
visit_time[j] = time + 1
else:
visit_time[j] = min(time + 1, visit_time[j])
for v in visit_time:
ans[v] += 1
for i in range(1, N):
print(ans[i] // 2)
if __name__ == '__main__':
main()
| s = input()
n = int(input())
for _ in range(n):
O = list(map(str, input().split()))
i = int(O[1])
j = int(O[2])
if O[0] == 'print':
print(s[i:j + 1])
elif O[0] == 'reverse':
ss = s[i:j + 1]
s = s[:i] + ss[::-1] + s[j + 1:]
else:
p = O[3]
s = s[:i] + p + s[j + 1:]
| 0 | null | 23,259,168,731,682 | 187 | 68 |
M1,D1 = map(int,input().split())
M2,D2 = map(int,input().split())
print(1) if(M1 != M2) else print(0) | m1, _ = [int(i) for i in input().split()]
m2, _ = [int(i) for i in input().split()]
if m1 == m2:
print(0)
else:
print(1) | 1 | 124,109,088,042,760 | null | 264 | 264 |
S = input()
Q = int(input())
b = "" #reversed
a = ""
f = 0
for i in range(Q):
q = input()
if q == "1":
f+=1
else:
_,F,C = q.split()
if (f+int(F))%2==1:
b+=C
else:
a+=C
if f%2==0:
print(b[::-1]+S+a)
else:
print(a[::-1]+S[::-1]+b) | s=input()
q=int(input())
cnt=0
front=[]
rear=[]
for qq in range(q):
l=list(input().split())
if l[0]=='1':
cnt+=1
else:
if (cnt+int(l[1]))%2==1:
front.append(l[2])
else:
rear.append(l[2])
front=''.join(front[::-1])
rear=''.join(rear)
s=front+s+rear
print(s if cnt%2==0 else s[::-1]) | 1 | 57,302,605,201,222 | null | 204 | 204 |
N = int(input())
S = list(input())
alp = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
S_a = ""
for s in S:
n = alp.index(s)+N
if(alp.index(s)+N>=26):
n -= 26
S_a += alp[n]
print(S_a) | N = int(input())
S_ord = [ord(i) for i in input()]
S_ord_change = []
for i in S_ord:
i += N
if i >= 91:
i = i - 26
S_ord_change.append(i)
S_change_chr = [chr(i) for i in S_ord_change]
result = ''.join(S_change_chr)
print(result) | 1 | 134,684,304,903,990 | null | 271 | 271 |
from collections import Counter
word = input()
count = 0
while True:
text = input()
if text == 'END_OF_TEXT':
break
count += Counter(text.lower().split())[word.lower()]
print(count) | n=int(input())
p=10**9+7
A=list(map(int,input().split()))
binA=[]
for i in range(n):
binA.append(format(A[i],"060b"))
lis=[0 for i in range(60)]
for binAi in binA:
for j in range(60):
lis[j]+=int(binAi[j])
binary=[0 for i in range(60)]
for i in range(n):
for j in range(60):
if binA[i][j]=="0":
binary[j]+=lis[j]
else:
binary[j]+=n-lis[j]
binary[58]+=binary[59]//2
binary[59]=0
explis=[1]
for i in range(60):
explis.append((explis[i]*2)%p)
ans=0
for i in range(59):
ans=(ans+binary[i]*explis[58-i])%p
print(ans)
| 0 | null | 62,263,582,220,450 | 65 | 263 |
n, m, x = map(int,input().split())
c = [0] *(n)
a = [[0] for _ in range(n)]
ans = 10**10
for i in range(n):
ca = list(map(int,input().split()))
c[i] = ca[0]
a[i] = ca[1:]
for i in range(1 << n):
skill = [0] * m
total_cost = 0
for j in range(n):
if (i>>j) & 1:
total_cost += c[j]
skill = [skill[t] + a[j][t] for t in range(m)]
if all (y >= x for y in skill):
ans = min(ans, total_cost)
if ans == 10**10:
print(-1)
else:
print(ans) | import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *
a, b, c = MAP()
if Decimal(a)**Decimal("0.5") + Decimal(b)**Decimal("0.5") < Decimal(c)**Decimal("0.5"):
print("Yes")
else:
print("No") | 0 | null | 36,902,382,171,450 | 149 | 197 |
H = int(input())
ans,attack = 1,0
while(H > 1):
attack += 1
H //= 2
for i in range(1,attack+1):
ans += 2**i
print(ans) | n = int(input())
total = 0
out = 1
for _ in range(n):
a, b = map(int, input().split())
if a == b:
total += 1
else:
if total >= 3:
out = 0
else:
total = 0
if total >= 3:
out = 0
if out:
print("No")
else:
print("Yes") | 0 | null | 40,992,227,887,190 | 228 | 72 |
n,m=map(int,input().split())
for i in range(m):
if n%2==0 and 2*m-i-i-1>=n//2:
print(i+1,2*m-i+1)
else:
print(i+1,2*m-i) | S = input()
T = input()
s = len(S)
t = len(T)
ans1 = 10000000
for i in range(s - t + 1):
ans = 0
for j in range(t):
if T[j] != S[i + j]:
ans += 1
ans1 = min(ans, ans1)
print(ans1)
| 0 | null | 16,123,362,124,282 | 162 | 82 |
n = int(input())
A = list(map(int,input().split()))
m = int(input())
B = list(input().split())
for i in range(m):
B[i] = int(B[i])
def solve(x,y):
if x==n:
S[y] = 1
else:
solve(x+1,y)
if y+A[x] < 2001:
solve(x+1,y+A[x])
S = [0 for i in range(2001)]
solve(0,0)
for i in range(m):
if S[B[i]] == 1:
print("yes")
else:
print("no")
| def main():
input()
array_a = list(map(int, input().split()))
input()
array_q = map(int, input().split())
def can_construct_q (q, i, sum_sofar):
if sum_sofar == q or sum_sofar + array_a[i] == q:
return True
elif sum_sofar > q or i >= len (array_a) - 1:
return False
if can_construct_q(q, i + 1, sum_sofar + array_a[i]):
return True
if can_construct_q(q, i + 1, sum_sofar):
return True
sum_array_a = sum(array_a)
for q in array_q:
#print(q)
if sum_array_a < q:
print('no')
elif can_construct_q(q, 0, 0):
print('yes')
else:
print('no')
return
main()
| 1 | 104,424,449,350 | null | 25 | 25 |
import sys
from collections import deque
def main():
h, w = map(int, input().split())
area = [[s for s in sys.stdin.readline().strip()] for _ in range(h)]
start_point = {0:set(), 1:set(), 2:set(), 3:set(), 4:set()}
min_neighbor = 4
for i in range(h):
for j in range(w):
if area[i][j] == '#':
continue
roads = 0
if i > 0 and area[i - 1][j] == '.':
roads += 1
if i < h - 1 and area[i + 1][j] == '.':
roads += 1
if j > 0 and area[i][j - 1] == '.':
roads += 1
if j < w - 1 and area[i][j + 1] == '.':
roads += 1
min_neighbor = min(min_neighbor, roads)
start_point[roads].add((i, j))
max_cost = 0
for start in start_point[min_neighbor]:
queue = deque()
queue.append(start)
cost = 0
visited = set()
while len(queue) > 0:
roads = len(queue)
found = False
for i in range(roads):
s = queue.popleft()
if s in visited:
continue
found = True
visited.add(s)
i = s[0]
j = s[1]
if i > 0 and area[i - 1][j] == '.':
queue.append((i - 1, j))
if i < h - 1 and area[i + 1][j] == '.':
queue.append((i + 1, j))
if j > 0 and area[i][j - 1] == '.':
queue.append((i, j - 1))
if j < w - 1 and area[i][j + 1] == '.':
queue.append((i, j + 1))
if not found:
cost -= 1
max_cost = max(cost, max_cost)
if found:
cost += 1
print(max_cost)
if __name__ == '__main__':
main() | H,W = list(map(int,input().split()))
N=H*W
#壁のノード
wall=[]
for h in range(H):
for w_idx,w in enumerate(list(input())):
if w == '#':
wall.append(W*h+w_idx+1)
#道のノード
path=[_ for _ in range(1,N+1) if _ not in wall]
#隣接リスト
ad = {}
for n in range(N):
ad[n+1]=[]
for n in range(N):
n=n+1
if n not in wall:
up = n-W
if up > 0 and up not in wall:
ad[n].append(up)
down = n+W
if down <= N and down not in wall:
ad[n].append(down)
left = n-1
if n % W != 1 and left not in wall and left > 0:
ad[n].append(left)
right = n+1
if n % W != 0 and right not in wall:
ad[n].append(right)
from collections import deque
def BFS(start):
que = deque([start])
visit = deque([])
color = {}
for n in range(N):
color[n+1] = -1
color[start] = 0
depth = {}
for n in range(N):
depth[n+1] = -1
depth[start] = 0
while len(que) > 0:
start = que[0]
for v in ad[start]:
if color[v] == -1:
que.append(v)
color[v] = 0
depth[v] = depth[start]+1
color[start] = 1
visit.append(que.popleft())
return depth[start]
ans=-1
for start in path:
ans_=BFS(start)
if ans < BFS(start):
ans = ans_
# print(start,ans_)
print(ans) | 1 | 94,467,851,507,680 | null | 241 | 241 |
import sys
str = ""
for line in sys.stdin:
str = line
numbers = str.split()
answer = 0
stackList = []
for number in numbers :
if number == '+' :
answer = int(stackList.pop()) + int(stackList.pop())
stackList.append(answer)
elif number == '-' :
x = int(stackList.pop())
y = int(stackList.pop())
answer = y - x
stackList.append(answer)
elif number == '*' :
answer = int(stackList.pop()) * int(stackList.pop())
stackList.append(answer)
else :
stackList.append(number)
print(answer)
| inputs = input().split(" ")
stack = []
for str in inputs:
if str.isdigit():
stack.append(int(str))
else:
b = stack.pop()
a = stack.pop()
if str == '+':
stack.append(a + b)
elif str == '-':
stack.append(a - b)
elif str == '*':
stack.append(a * b)
print(stack.pop())
| 1 | 39,170,962,872 | null | 18 | 18 |
k = int(input())
def test_case(k):
ans,cnt = 7,1
if k % 2 == 0 or k % 5 == 0:
return -1
if k == 1 or k == 7:
return 1
while (1):
ans = (ans * 10 + 7) % k
cnt += 1
if ans == 0:
return cnt
print(test_case(k))
| a = list(input())
if a[-1] == 's':
a.append('e')
a.append('s')
else:
a.append('s')
print(''.join(a)) | 0 | null | 4,286,071,239,880 | 97 | 71 |
text = ''
while(True):
try:
text += input().lower()
except:
break
count = [0 for i in range(26)]
for c in text:
if c < 'a' or c > 'z':
continue
count[ord(c) - ord('a')] += 1
for i, c in enumerate(count):
print('{0} : {1}'.format(chr(i + ord('a')), c)) | n = int(input())
lis = list(map(int, input().split()))
m = 0
for a in lis:
m = m ^ a
for a in lis:
print(m ^ a, end=" ")
| 0 | null | 7,036,623,206,416 | 63 | 123 |
S = list(map(str,input()))
if S[0] != S[1] or S[1] != S[2]:
print("Yes")
else:
print("No") | import sys
def input(): return sys.stdin.readline().strip()
def resolve():
n=int(input())
l=[list(input().split()) for i in range(n)]
x=input()
cnt=0
for s,t in l:
if s!=x:
cnt+=int(t)
elif s==x:
cnt+=int(t)
break
suml=0
for i in range(n):
suml+=int(l[i][1])
print(suml-cnt)
resolve() | 0 | null | 76,016,824,951,820 | 201 | 243 |
dic = {}
for s in range(int(input())):
i = input().split()
if i[0] == "insert":
dic[i[1]] = None
else:
print("yes" if i[1] in dic else "no") | # -*- coding: utf-8 -*-
from sys import stdin
Dic = {}
n = int(stdin.readline().rstrip())
for i in range(n):
line = stdin.readline().rstrip()
if line[0] == 'i':
Dic[line[7:]] = 0
else:
print('yes' if line[5:] in Dic else 'no')
| 1 | 80,261,588,438 | null | 23 | 23 |
#!/usr/bin/env python3
# Generated by https://github.com/kyuridenamida/atcoder-tools
from typing import *
import collections
import functools as fts
import itertools as its
import math
import sys
INF = float('inf')
def solve(N: int):
def manhattan_distance(x1, y1, x2, y2):
return abs(x1-x2) + abs(y1-y2)
return min(manhattan_distance(1, 1, i, N//i) for i in range(1, int(math.sqrt(N))+1) if N % i == 0)
def main():
sys.setrecursionlimit(10 ** 6)
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
print(f'{solve(N)}')
if __name__ == '__main__':
main()
| n = int(input())
m = 10**13
for x in range(1,1000001):
y = n / x
if y % 1 == 0:
v = x + y -2
m = min(m, v)
print(int(m)) | 1 | 161,669,017,351,868 | null | 288 | 288 |
import sys
from itertools import product
sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7
def resolve():
H, W, K = map(int, input().split())
grid = [list(input()) for _ in range(H)]
R = [[0] * (W + 1) for _ in range(H + 1)]
for h in range(H):
for w in range(W):
R[h + 1][w + 1] = R[h][w + 1] + R[h + 1][w] - R[h][w] + int(grid[h][w])
res = f_inf
for pattern in product([0, 1], repeat=H-1):
cut_H = [idx + 1 for idx, p in enumerate(pattern) if p == 1] + [H]
cnt_cut = sum(pattern)
left = 0
right = 1
flg = 1
while right <= W:
if not flg:
break
up = 0
for bottom in cut_H:
cnt_w = R[bottom][right] - R[bottom][left] - R[up][right] + R[up][left]
if cnt_w > K:
if right - left == 1:
flg = False
cnt_cut += 1
left = right - 1
break
else:
up = bottom
else:
right += 1
else:
res = min(res, cnt_cut)
print(res)
if __name__ == '__main__':
resolve()
| x = raw_input()
a = int (x)**3
print a | 0 | null | 24,309,893,254,328 | 193 | 35 |
def solve():
for i in range(1,10):
for j in range(1,10):
print("{0}x{1}={2}".format(i,j,i*j))
solve() | import math
H = int(input())
l = math.log(H,2)
ll = math.floor(l)+1
ans = 2 ** ll -1
print(ans) | 0 | null | 40,071,909,083,950 | 1 | 228 |
import numpy as np
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
N, u, v = map(int, input().split())
E = [[] for _ in range(N+1)]
for _ in range(N-1):
ta, tb = map(int, input().split())
E[ta].append(tb)
E[tb].append(ta)
E = np.array(E)
inf = 10**9
taka = np.full(N+1, inf, dtype = np.int64)
ao = np.full(N+1, inf, dtype = np.int64)
taka[u] = 0
ao[v] = 0
def solve(dist, start):
q = [start]
while q:
cp = q.pop()
for nep in E[cp]:
if dist[nep] != inf:
continue
else:
dist[nep] = dist[cp] + 1
q.append(nep)
solve(taka, u)
solve(ao, v)
ind = taka < ao
ao_max = np.max(ao[ind])
print(ao_max - 1) | N, u, v = map(int, input().split())
u, v = u-1, v-1
ABs = [list(map(lambda x:int(x)-1, input().split())) for _ in range(N-1)]
#%%
roots = [[] for _ in range(N)]
for AB in ABs:
roots[AB[0]].append(AB[1])
roots[AB[1]].append(AB[0])
#BFS
def BFS(roots, start):
from collections import deque
seen = [-1 for _ in range(N)]
seen[start] = 0
todo = deque([start])
while len(todo) > 0:
checking = todo.pop()
for root in roots[checking]:
if seen[root] == -1:
seen[root] = seen[checking] +1
todo.append(root)
return seen
from_u = BFS(roots, u)
from_v = BFS(roots, v)
from collections import deque
todo = deque([u])
max_distance = from_v[u]
position = u
seen = [False for _ in range(N)]
seen[u] = True
while len(todo) > 0:
checking = todo.pop()
for root in roots[checking]:
if from_u[root] < from_v[root] and seen[root] == False:
seen[root] = True
todo.append(root)
if max_distance < from_v[root]:
max_distance = from_v[root]
position = root
print(max_distance-1) | 1 | 117,736,987,724,178 | null | 259 | 259 |
import sys
#import time
#from collections import deque, Counter, defaultdict
#from fractions import gcd
import bisect
#import heapq
#import math
import itertools
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
inf = 10**18
MOD = 1000000007
ri = lambda : int(input())
rs = lambda : input().strip()
rl = lambda : list(map(int, input().split()))
n = ri()
ans=0
for i in range(1,n+1):
ans+=(n//i)*(n//i+1)*i//2
print(ans) | X, Y = map(int, input().split())
mod = 10**9 + 7
def permute(n, m):
ret = 1
while n >= m:
ret *= n
# ret %= mod
n -= 1
return ret
def count_combinations(n, m):
fact = [1] * (n + 1)
inv = [i for i in range(n+1)]
fact_inv = [1] * (n + 1)
for i in range(2, n+1):
fact[i] = fact[i-1] * i % mod
inv[i] = (-inv[mod%i]*(mod//i))%mod
# inv[i] = mod - inv[mod % i] * (mod // i) % mod
fact_inv[i] = fact_inv[i-1] * inv[i] % mod
ret = (fact[n] * fact_inv[m] * fact_inv[n-m]) % mod
return ret
def count_comb2(n, m):
fact = [1, 1] # fact[n] = (n! mod p)
factinv = [1, 1] # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1] # factinv 計算用
for i in range(2, n + 1):
fact.append((fact[-1] * i) % mod)
inv.append((-inv[mod % i] * (mod // i)) % mod)
factinv.append((factinv[-1] * inv[-1]) % mod)
if (m < 0) or (n < m):
return 0
m = min(m, n - m)
return fact[n] * factinv[m] * factinv[n-m] % mod
ret = 0
if (X+Y)%3 == 0:
m = (2*X - Y) // 3
n = (2*Y - X) // 3
if m >= 0 and n >= 0:
ret = count_combinations(n+m, m)
# ret = count_comb2(n+m, m)
print(ret)
| 0 | null | 80,570,167,429,698 | 118 | 281 |
i = 0
while 1:
i += 1
x = input()
if x == '0': break
print(f"Case {i}: {x}")
| a = int(input())
if a < 2:
print(0)
elif a % 2 == 0:
print(int(a / 2 - 1) )
else:
print(int(a/2)) | 0 | null | 76,785,226,323,468 | 42 | 283 |
T1,T2 = map(int,input().split())
A1,A2 = map(int,input().split())
B1,B2 = map(int,input().split())
if T1*A1+T2*A2==T1*B1+T2*B2:
cnt="infinity"
elif T1*A1+T2*A2>T1*B1+T2*B2:
L = T1*(B1-A1)
d = T1*A1+T2*A2-(T1*B1+T2*B2)
if L<0:
cnt = 0
elif L==0:
cnt = 1
else:
cnt = 1
n = L//d
r = L%d
if r>0:
cnt += 2*n
else:
cnt += 2*(n-1)+1
elif T1*A1+T2*A2<T1*B1+T2*B2:
L = T1*(A1-B1)
d = (T1*B1+T2*B2)-(T1*A1+T2*A2)
if L<0:
cnt = 0
elif L==0:
cnt = 1
else:
cnt = 1
n = L//d
r = L%d
if r>0:
cnt += 2*n
else:
cnt += 2*(n-1)+1
print(cnt) | from collections import defaultdict, deque
import sys, heapq, bisect, math, itertools, string, queue, copy, time
from fractions import gcd
import numpy as np
sys.setrecursionlimit(10**8)
INF = float('inf')
MOD = 10**9+7
EPS = 10**-7
h, w = map(int, input().split())
ini_grid = []
ans = 0
for i in range(h):
s = list(input())
ini_grid.append(s)
dd = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(h):
for j in range(w):
if ini_grid[i][j] == '.':
temp_grid = [row[:] for row in ini_grid]
dis_grid = [[-1]*w for i in range(h)]
dis_grid[i][j] = 0
dq = deque([(i, j, 0)])
temp_grid[i][j] = '#'
while dq:
curr = dq.popleft()
for di, dj in dd:
ni = curr[0] + di
nj = curr[1] + dj
if (0 <= ni <= h-1) and (0 <= nj <= w-1) and temp_grid[ni][nj] == '.':
temp_grid[ni][nj] = '#'
dis_grid[ni][nj] = curr[2] + 1
dq.append((ni, nj, curr[2] + 1))
if curr[2] + 1 > ans:
ans = curr[2] + 1
print(ans) | 0 | null | 112,613,236,832,262 | 269 | 241 |
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions import gcd
#input=sys.stdin.readline
#import bisect
n,m=map(int,input().split())
a=list(map(int,input().split()))
def lcm(a,b):
g=math.gcd(a,b)
return b*(a//g)
l=a[0]//2
for i in range(n):
r=a[i]//2
l=lcm(l,r)
for i in range(n):
if (l//(a[i]//2))%2==0:
print(0)
exit()
res=m//l
print((res+1)//2) | from functools import reduce
import math
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)
n,m = map(int, input().split())
a = list(map(int, input().split()))
a = [i//2 for i in list(set(a))]
nothing = False
cnt_common = -1
for i in a:
cnt = 0
while i % 2 == 0:
i = i//2
cnt += 1
if cnt_common == -1:
cnt_common = cnt
continue
if cnt_common != cnt:
nothing = True
break
b=lcm_list(a)
if nothing:
print(0)
else:
ans = (m-b)//(2*b) + 1
print(max(ans,0)) | 1 | 101,701,121,883,328 | null | 247 | 247 |
import copy
import itertools
h, w, k = map(int, input().split())
#s= list(input())
s = []
min = 100000
for i in range(h):
s.append( [int(s) for s in list(input())])
#s.append([1]*w)
dbg_cnt = 0
l = list(range(h-1))
for i in range(h):
p = list(itertools.combinations(l, i))
for j in p:
tmp = list(j)
tmps = []
q = 0
tmps.append([])
#print(dbg_cnt)
#dbg_cnt += 1
for r in range(h):
tmps[q].append(copy.copy(s[r]))
if(q < len(tmp) and r==tmp[q]):
tmps.append([])
q += 1
#print(tmps)
count = i
sums = [0] * len(tmps)
precut = 1
exitflg = 0
for r in range(w): #550000
for q in range(len(tmps)):
for t in tmps[q]:
sums[q] += t[r] #5500000
cutflg = 0
for q in range(len(tmps)):
if sums[q] > k : #5500000
cutflg = 1
if cutflg == 1:
#print('cut')
count += 1
sums = [0] * len(tmps)
for q in range(len(tmps)):
for t in tmps[q]:
sums[q] += t[r] #5500000
for q in range(len(tmps)): #5500000
if sums[q] > k :
exitflg = 1
#print('exit')
#print(exitflg)
if exitflg == 0:
if min > count:
min = count
print(min) | from sys import stdin
def main():
#入力
readline=stdin.readline
h,w,k=map(int,readline().split())
grid=[readline().strip() for _ in range(h)]
ans=float("inf")
for i in range(1<<(h-1)):
div=[(i>>j)&1 for j in range(h-1)]
l=len([0 for i in range(h-1) if div[i]])+1
cnt=[0]*l
tmp=0
for j in range(w):
now=0
flag=False
for i_2 in range(h):
if grid[i_2][j]=="1":
cnt[now]+=1
if cnt[now]>k:
flag=True
break
if i_2<h-1 and div[i_2]==1: now+=1
if flag:
tmp+=1
cnt=[0]*l
now=0
flag=False
for i_2 in range(h):
if grid[i_2][j]=="1":
cnt[now]+=1
if cnt[now]>k:
flag=True
break
if i_2<h-1 and div[i_2]==1: now+=1
if flag: break
else:
tmp+=l-1
ans=min(ans,tmp)
print(ans)
if __name__=="__main__":
main() | 1 | 48,531,166,375,900 | null | 193 | 193 |
N = int(input())
print(N**3/27) | x = [int(s) for s in input().split()]
print('Yes' if x[0] < x[1] and x[1] < x[2] else 'No') | 0 | null | 23,770,066,965,360 | 191 | 39 |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import numpy as np
N,T = map(int,readline().split())
m = map(int,read().split())
AB = sorted(zip(m,m))
can_add = [0] * N
for n in range(N-1,0,-1):
x = can_add[n]
y = AB[n][1]
can_add[n-1] = x if x > y else y
dp = np.zeros(T,np.int64)
answer = 0
for i,(a,b) in enumerate(AB):
np.maximum(dp[a:], dp[:-a] + b, out = dp[a:])
x = dp.max() + can_add[i]
if answer < x:
answer = x
print(answer)
| def check_weather(weathers: str) -> int:
count = 0
l_n = [0]
for index, i in enumerate(weathers):
if weathers[-1] == 'R' and index == len(weathers) - 1:
count += 1
l_n.append(count)
break
if i == 'R':
count += 1
else:
if max(l_n) <= count:
l_n.append(count)
count = 0
return max(l_n)
if __name__ == '__main__':
print(check_weather(input())) | 0 | null | 78,375,390,543,100 | 282 | 90 |
n = int(input())
S = input()
a = ord('A')
z = ord('Z')
ans = ''
for s in S:
if ord(s) + n <= 90:
ans += chr(ord(s) + n)
else:
ans += chr(a + ord(s) + n - z - 1)
print(ans)
| def i():
return int(input())
def i2():
return map(int,input().split())
def s():
return str(input())
def l():
return list(input())
def intl():
return list(int(k) for k in input().split())
n = i()
s = s()
alf = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(len(s)):
for j in range(26):
if s[i] == alf[j]:
print(alf[j+n],end="")
continue | 1 | 134,565,440,328,660 | null | 271 | 271 |
x=int(input())
X=x
k=1
while X%360!=0:
k+=1
X+=x
print(k) | import sys
import math
a = []
for l in sys.stdin:
a.append(int(l))
h = a[0]
n = 0
while h > 1:
h = math.floor(h / 2)
n = n + 1
print(2 ** (n + 1) - 1) | 0 | null | 46,519,122,857,636 | 125 | 228 |
N = int(input())
tot = 0
for i in range(1, N+1):
m = N//i
tot += i * (m * (m+1)) // 2
print(tot) | import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
import bisect
con = 10 ** 9 + 7; INF = float("inf")
def getlist():
return list(map(int, input().split()))
def Binary_Search(A, N, M):
#初期化
left = 0
right = 10 ** 7
ans = 0
#累積和
Asum = [0]
for i in range(N):
Asum.append(Asum[i] + A[-1 - i])
leftj = [INF, INF]
rightj = [0, 0]
#二分探索
while left <= right:
mid = (left + right) // 2
var = 0
happiness = 0
for i in range(N):
ind = bisect.bisect_left(A, mid - A[i])
ind = N - ind
var += ind
happiness += ind * A[i] + Asum[ind]
# print(var, happiness)
if var == M:
return happiness
elif var > M:
leftj = min(leftj, [var, -mid])
left = mid + 1
else:
ans = max(ans, happiness)
rightj = max(rightj, [var, -mid])
right = mid - 1
# print(ans)
# print(leftj)
# print(rightj)
ans = ans + (M - rightj[0]) * (-leftj[1])
return ans
#処理内容
def main():
N, M = getlist()
A = getlist()
A.sort()
ans = Binary_Search(A, N, M)
print(ans)
if __name__ == '__main__':
main() | 0 | null | 59,337,714,320,382 | 118 | 252 |
# coding=utf-8
from math import floor, ceil, sqrt, factorial, log, gcd
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from heapq import heappop, heappush, heappushpop, heapify
import copy
import sys
INF = float('inf')
mod = 10**9+7
sys.setrecursionlimit(10 ** 6)
def lcm(a, b): return a * b / gcd(a, b)
# 1 2 3
# a, b, c = LI()
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
# a = I()
def I(): return int(sys.stdin.buffer.readline())
# abc def
# a, b = LS()
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
# a = S()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
# 2
# 1
# 2
# [1, 2]
def IR(n): return [I() for i in range(n)]
# 2
# 1 2 3
# 4 5 6
# [[1,2,3], [4,5,6]]
def LIR(n): return [LI() for i in range(n)]
# 2
# abc
# def
# [abc, def]
def SR(n): return [S() for i in range(n)]
# 2
# abc def
# ghi jkl
# [[abc,def], [ghi,jkl]]
def LSR(n): return [LS() for i in range(n)]
# 2
# abcd
# efgh
# [[a,b,c,d], [e,f,g,h]]
def SRL(n): return [list(S()) for i in range(n)]
n = I()
ans = 0
for a in range(1, n):
ans += (n-1)//a
print(ans)
| ma = lambda :map(int,input().split())
ni = lambda:int(input())
import collections
import math
import itertools
import fractions
gcd = fractions.gcd
a,b = ma()
print(a*b//gcd(a,b))
| 0 | null | 57,843,365,947,360 | 73 | 256 |
a, b, c, k = map(int, input().split())
ans = 0
if a >= k:
print(k)
exit()
ans += a
k -= a
if b >= k:
print(ans)
exit()
k -= b
ans -= k
print(ans)
| S = input()
ans = [0]*(len(S)+1)
for i in range(len(S)):
if S[i] == "<":
ans[i+1] = max(ans[i+1], ans[i]+1)
for i in range(len(S)):
i = len(S)-1 - i
if S[i] == ">":
ans[i] = max(ans[i],ans[i+1]+1)
print(sum(ans)) | 0 | null | 89,386,944,207,890 | 148 | 285 |
import math
import collections
import fractions
import itertools
import functools
import operator
import bisect
def solve():
n = int(input())
l = list(map(int, input().split()))
l.sort()
res = 0
for i in range(n):
for j in range(i+1, n):
k = bisect.bisect_left(l, l[i]+l[j])
res += max(k-(j+1), 0)
print(res)
return 0
if __name__ == "__main__":
solve() | from collections import deque
h, w = map(int, input().split())
S = [list(input()) for _ in range(h)]
DP = [[10000]*w for _ in range(h)]
DP[0][0] = 0 if S[0][0]=='.' else 1
directs = [[0,1], [1,0]]
for hi in range(h):
for wi in range(w):
for dh,dw in directs:
if not (0<=hi+dh<h and 0<=wi+dw<w): continue
if S[hi][wi]=='.' and S[hi+dh][wi+dw]=='#':
DP[hi+dh][wi+dw] = min(DP[hi+dh][wi+dw], DP[hi][wi]+1)
else:
DP[hi+dh][wi+dw] = min(DP[hi+dh][wi+dw], DP[hi][wi])
print(DP[-1][-1]) | 0 | null | 110,207,756,699,140 | 294 | 194 |
word = input()
counter = 0
while 1:
s = input()
if s == 'END_OF_TEXT':
break
else:
s = list(s.lower().split())
counter += s.count(word)
counter += s.count(word + '.')
print(counter) | W = input()
num = 0
while True:
line = input()
if line == 'END_OF_TEXT':
break
for word in line.split():
if word.lower() == W.lower():
num += 1
print(num) | 1 | 1,834,112,142,792 | null | 65 | 65 |
X,Y=map(int,input().split())
MOD=10**9+7
def modinv(a):
return pow(a,MOD-2,MOD)
x=(2*Y-X)//3
y=(2*X-Y)//3
if (2*Y-X)%3!=0 or (2*X-Y)%3!=0 or x<0 or y<0:
print(0)
else:
r=1
n=x+y
k=min(x,y)
for i in range(k):
r*=(n-i)
r*=modinv(i+1)
r%=MOD
print(r)
| from sys import stdin
input = stdin.readline
def solve():
n = int(input())
r = n % 1000
res = 0 if r == 0 else 1000 - r
print(res)
if __name__ == '__main__':
solve()
| 0 | null | 79,635,463,355,940 | 281 | 108 |
from sys import stdin
def main():
readline = stdin.readline
n = int(readline())
s = tuple(readline().strip() for _ in range(n))
plus, minus = [], []
for c in s:
if 2 * c.count('(') - len(c) > 0:
plus.append(c)
else:
minus.append(c)
plus.sort(key = lambda x: x.count(')'))
minus.sort(key = lambda x: x.count('('), reverse = True)
plus.extend(minus)
sum = 0
for v in plus:
for vv in v:
sum = sum + (1 if vv == '(' else -1)
if sum < 0 : return print('No')
if sum != 0:
return print('No')
return print('Yes')
if __name__ == '__main__':
main()
| import sys
input=sys.stdin.readline
def count(s):
m=0
e=0
for t in s:
if t=='(':
e+=1
else:
e-=1
m=min(m,e)
return (e,m)
def count_reverse(s):
m=0
e=0
for t in s[::-1]:
if t==')':
e+=1
else:
e-=1
m=min(m,e)
return (e,m)
def main():
n=int(input())
S=[input().strip() for _ in range(n)]
P,M=[],[]
Z=[0]
for s in S:
e,m=count(s)
if e>0:
P.append((m,e))
elif e<0:
e,m=count_reverse(s)
M.append((m,e))
else:
Z.append(m)
P.sort(reverse=True); M.sort(reverse=True)
s_p,s_m=0,0
for m,e in P:
if s_p+m<0:
return 'No'
s_p+=e
for m,e in M:
if s_m+m<0:
return 'No'
s_m+=e
if s_p==s_m and s_p+min(Z)>=0:
return 'Yes'
return 'No'
if __name__=='__main__':
print(main()) | 1 | 23,726,872,587,142 | null | 152 | 152 |
from itertools import product
for i, j in product(range(1, 10), repeat=2):
print('{}x{}={}'.format(i, j, i * j)) | # coding: utf-8
# Stable Sort 2018/3/12
class Card(object):
def __init__(self, card):
self.value = int(card[1])
self.card = card
def __repr__(self):
return self.card
def BubbleSort(C, N):
for i in range(N):
for j in reversed(range(i+1, N)):
if C[j].value < C[j-1].value:
C[j], C[j-1] = C[j-1], C[j]
return C
def SelectionSort(C, N):
for i in range(N):
minj = i
for j in range(i, N):
if C[j].value < C[minj].value:
minj = j
C[i], C[minj] = C[minj], C[i]
return C
def isStable(inl, out):
n = len(inl)
for i in range(n):
for j in range(i+1, n):
for a in range(n):
for b in range(a+1, n):
if inl[i].value == inl[j].value and inl[i] == out[b] and inl[j] == out[a]:
return False
return True
def print_stable(inl, out):
if isStable(inl, out):
print "Stable"
else:
print "Not stable"
if __name__ == "__main__":
N = int(raw_input())
inputs = raw_input().split()
C = []
for i in inputs:
C.append(Card(i))
Cb = BubbleSort(list(C), N)
print " ".join([i.card for i in Cb])
print_stable(C, Cb)
Cs = SelectionSort(list(C), N)
print " ".join([i.card for i in Cs])
print_stable(C, Cs)
| 0 | null | 12,815,053,158 | 1 | 16 |
import collections
#https://note.nkmk.me/python-prime-factorization/
def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
def f(n):
for i in range(1,20):
if n<(i*(i+1))//2:
return i-1
n = int(input())
c = collections.Counter(prime_factorize(n))
ans = 0
for i in c.keys():
ans += f(c[i])
print(ans) | def main():
n = int(input())
ans = 0
for k in range(2,int(n**0.5)+1):
if n%k==0:
cnt,mx = 0,0
while n%k==0:
n = n//k
cnt += 1
if cnt > mx:
ans += 1
mx += 1
cnt = 0
if n!=1:
ans += 1
print(ans)
if __name__ == "__main__":
main()
| 1 | 16,797,777,678,470 | null | 136 | 136 |
N = int(input())
A = [int(i) for i in input().split()]
if N == 0 and A[0] != 1:
print(-1)
exit()
nodes = [0] * (N+1)
nodes[0] = 1
for i in range(1, N+1):
node = (nodes[i-1]-A[i-1])*2
if node < A[i]:
print(-1)
exit()
nodes[i] = node
#print(nodes)
nodes[-1] = A[-1]
for i in range(N-1, -1, -1):
nodes[i] = min(nodes[i], nodes[i+1]+A[i])
#print(nodes)
print(sum(nodes)) | from sys import stdin
N = int(stdin.readline().rstrip())
A = [int(x) for x in stdin.readline().rstrip().split()]
max_node = [0] * (N+1)
for i in range(N-1,-1,-1):
max_node[i] = max_node[i+1]+A[i+1]
ans = 1
node = 1
for i in range(N+1):
node -= A[i]
if (i < N and node <= 0) or node < 0:
print(-1)
exit(0)
node = min(node*2,max_node[i])
ans += node
print(ans) | 1 | 18,819,935,902,768 | null | 141 | 141 |
import sys
r,g,b=map(int,input().split())
k=int(input())
for i in range(k+1):
if r<g<b:
print("Yes")
sys.exit()
else:
if r<=b<=g:
b*=2
elif b<=r<=g:
b*=2
elif b<=g<=r:
b*=2
elif g<=r<=b:
g*=2
elif g<=b<=r:
b*=2
print("No")
| import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
t1,t2 = map(int, input().split())
a1,a2 = map(int, input().split())
b1,b2 = map(int, input().split())
a1 *= t1
a2 *= t2
b1 *= t1
b2 *= t2
if a1+a2==b1+b2:
ans = "infinity"
else:
if a1+a2 < b1+b2:
a1,a2,b1,b2 = b1,b2,a1,a2
# a1+a2が大きい
if a1>b1:
ans = 0
else:
ans = ((b1-a1) // (a1+a2-b1-b2)) * 2 + 1
if (b1-a1) % (a1+a2-b1-b2) ==0:
ans -= 1
print(ans) | 0 | null | 69,273,065,843,378 | 101 | 269 |
X,Y = list(map(int,input().split()))
MAXN = 2*(10**6)+10
p = 10**9+7
f = [1]
for i in range(MAXN):
f.append(f[-1] * (i+1) % p)
def nCr(n, r, mod=p):
return f[n] * pow(f[r], mod-2, mod) * pow(f[n-r], mod-2, mod) % mod
Z = (X+Y)//3
if Z*3!=X+Y:
print(0)
else:
P,Q = X-Z, Y-Z
if P<0 or Q<0:
print(0)
else:
print(nCr(Z,P))
| def cmb(n, r, p):
if (r < 0) or (n < r):
return 0
r = min(r, n - r)
return fac[n]*finv[r]*finv[n-r]%p
N = pow(10,6)
MOD = pow(10,9)+7
fac = [-1]*(N+1); fac[0] = 1; fac[1] = 1 #階乗
finv = [-1]*(N+1); finv[0] = 1; finv[1] = 1 #階乗の逆元
inv = [-1]*(N+1); inv[0] = 0; inv[1] = 1 #逆元
for i in range(2,N+1):
fac[i] = fac[i-1]*i%MOD
inv[i] = MOD - inv[MOD%i]*(MOD//i)%MOD
finv[i] = finv[i-1]*inv[i]%MOD
X,Y = map(int,input().split())
if (X+Y)%3 != 0:
print(0)
exit()
n = (X+Y)//3
if min(X,Y) < n:
print(0)
exit()
ans = cmb(n,min(X,Y)-n,MOD)
print(ans) | 1 | 150,500,733,571,294 | null | 281 | 281 |
from collections import deque
def bfs(maze, visited, x):
queue = deque([x])
visited[x] = 1
ans_list[x] = 0
while queue:
#queueには訪れた地点が入っている。そこから、移動できるか考え、queueから消す。
y = queue.popleft()#queueに入っていたものを消す。
r = maze[y - 1][2:]
for i in r:
if visited[i] == 0:
if ans_list[i] >= 10 ** 10:
ans_list[i] = ans_list[y] + 1
queue.append(i)
return 0
if __name__ == "__main__":
N = int(input())
A = [0] * N
for i in range(N):
A[i] = list(map(int, input().split()))
visited = [0] * (N + 1)
ans_list = [float("inf")] * (N + 1)
bfs(A, visited, 1)
#print(bfs(A, visited, 1))
for i in range(1, N + 1):
if ans_list[i] >= 10 ** 10:
print(i, -1)
else:
print(i, ans_list[i])
| from collections import deque
n = int(input())
G = [[] for _ in range(n)]
for i in range(n):
u, k, *vs = map(int, input().split())
u -= 1
vs = list(map(lambda x: x - 1, vs))
for v in vs:
G[u].append(v)
dist = [-1] * n
dist[0] = 0
que = deque([0])
while len(que) > 0:
now_v = que.popleft()
now_dist = dist[now_v]
next_vs = G[now_v]
for next_v in next_vs:
if dist[next_v] == -1:
dist[next_v] = now_dist + 1
que.append(next_v)
for i, x in enumerate(dist):
print(i + 1, x)
| 1 | 4,190,239,668 | null | 9 | 9 |
import math
K = int(input())
A, B = map(int, input().split())
largest = math.floor(B/K)*K
print("OK") if largest >= A else print("NG") | k=int(input())
a,b=map(int,input().split())
print("OK" if (a-1)//k!=b//k else"NG") | 1 | 26,651,076,411,488 | null | 158 | 158 |
l = map(int,raw_input().split())
l.sort()
print "%d %d %d" %(l[0] ,l[1], l[2]) | D, T, S = map(int, input().split())
if (D / S) <= T:
print('Yes')
else:
print('No') | 0 | null | 1,985,750,857,660 | 40 | 81 |
from math import gcd
def main():
N = int(input())
A = list([int(x) for x in input().split()])
max_a = max(A)
before = 0
result = [0 for _ in range(max_a + 1)]
for i in A:
before = gcd(before, i)
result[i] += 1
is_pairwise = True
for i in range(2, max_a + 1):
cnt = 0
for j in range(i, max_a + 1, i):
cnt += result[j]
if cnt > 1:
is_pairwise = False
break
if is_pairwise:
print('pairwise coprime')
exit()
if before == 1:
print('setwise coprime')
else:
print('not coprime')
if __name__ == '__main__':
main()
| n,k = map(int,input().split())
p = list(map(int,input().split()))
c = list(map(int,input().split()))
for i in range(n):
p[i] -= 1
v = [False] * n
roop = []
for i in range(n):
if not v[i]:
tmp = [i]
while True:
t = p[tmp[-1]]
v[t] = True
if tmp[0] == t:
break
else:
tmp.append(t)
roop.append(tmp)
s = []
for li in roop:
s1 = 0
for i in li:
s1 += c[i]
s.append(s1)
s2 = []
for li in roop:
tmp = [0]
for i in li:
tmp.append(tmp[-1] + c[i])
for i in li:
tmp.append(tmp[-1] + c[i])
s2.append(tmp)
v2 = [-1] * n
for i,li in enumerate(roop):
for j in li:
v2[j] = i
ans = -10**20
for i,li in enumerate(roop):
t = -10**20
if s[i] <= 0:
for j in range(len(li)):
for k1 in range(j+1, j + 1 + min(k, len(li))):
t = max(t, s2[i][k1] - s2[i][j])
ans = max(ans, t)
else:
for cnt in range(min(len(li), k)+1):
for j in range(len(li)):
if k >= cnt:
t = max(t, s2[i][cnt+j] - s2[i][j] + s[i] * ((k - cnt) // len(li)))
ans = max(ans, t)
print(ans)
| 0 | null | 4,769,977,090,538 | 85 | 93 |
n,m = input().split()
n=int(n)
m=float(m)*100+0.5
m=int(m)
ans = int(n*m//100)
print(ans) | def input_int():
return map(int, input().split())
def one_int():
return int(input())
def one_str():
return input()
def many_int():
return list(map(int, input().split()))
import math
from decimal import Decimal
A, B = input().split()
# A=int(A)
# B=float(B)
temp = Decimal(A)*Decimal(B)
print(int(math.floor(temp))) | 1 | 16,519,482,045,216 | null | 135 | 135 |
while True:
i = input().split()
result = 0
if i[1] == '+':
result = int(i[0]) + int(i[2])
elif i[1] == '-':
result = int(i[0]) - int(i[2])
elif i[1] == '*':
result = int(i[0]) * int(i[2])
elif i[1] == '/':
result = int(i[0]) // int(i[2])
elif i[1] == '?':
break
print(result) | n = int(input())
lst = list(input())
count = 0
for i in range(0, len(lst)):
if lst[i - 2] == 'A' and lst[i - 1] == 'B' and lst[i] == 'C':
count += 1
print(count)
| 0 | null | 49,935,749,181,138 | 47 | 245 |
from itertools import product
import copy
H,W,K = list(map(int, input().split()))
A = []
for i in range(H):
A.append(list(map(int, input())))
#SM = [np.cumsum(A[i]) for i in range(H)]
ANS = []
for pat in product(['0','1'], repeat = H-1):
res = []
cnt = 0
now = copy.copy(A[0])
for i in range(1,H):
p = pat[i-1]
if p == '1':
res.append(now)
now = copy.copy(A[i])
cnt += 1
else:
for j in range(W):
now[j] += A[i][j]
res.append(now)
"""
print("---")
print(pat)
print(res)
print(cnt)
"""
wk2 = [0] * len(res)
cnt2 = 0
flg = True
for x in range(W):
for j in range(len(res)):
if res[j][x] > K:
# 横に割った段階で、すでに最小単位がKを超えてたら実現不可能
flg = False
break
if wk2[j] + res[j][x] > K:
cnt2 += 1
wk2 = [0] * len(res)
break
for j in range(len(res)):
wk2[j] += res[j][x]
if not flg:
break
if flg:
ANS.append(cnt + cnt2)
#print(pat, cnt, cnt2)
print(min(ANS))
| class Dice:
def __init__(self,l1,l2,l3,l4,l5,l6):
self.l1 = l1
self.l2 = l2
self.l3 = l3
self.l4 = l4
self.l5 = l5
self.l6 = l6
self.top = 1
self.front = 2
self.right = 3
def get_top(self):
return eval("self." + 'l' + str(self.top))
def move(self, order):
if order == 'S':
pretop = self.top
self.top = 7 - self.front
self.front = pretop
elif order == 'E':
pretop = self.top
self.top = 7 - self.right
self.right = pretop
elif order == 'N':
pretop = self.top
self.top = self.front
self.front = 7 - pretop
elif order == 'W':
pretop = self.top
self.top = self.right
self.right = 7 - pretop
l = list(map(int,input().split()))
orders = input()
d = Dice(l[0],l[1],l[2],l[3],l[4],l[5])
for order in orders:
d.move(order)
print(d.get_top()) | 0 | null | 24,347,343,076,842 | 193 | 33 |
mountains = []
for x in range(10):
mountains.append(int(raw_input()))
mountains.sort()
mountains.reverse()
print mountains[0]
print mountains[1]
print mountains[2] | n = int(input())
nums = list(map(int, input().split()))
q = int(input())
m = list(map(int, input().split()))
li = []
for i in range(2**n):
an = format(i, 'b').zfill(n)
li.append(an)
ans = []
for lis in li:
num = 0
for i in range(n):
if lis[i] == '1':
num += nums[i]
ans.append(num)
for j in m:
if j in ans:
print('yes')
else:
print('no')
| 0 | null | 49,437,725,860 | 2 | 25 |
N = int(input())
n = 0
if not N%2:
s = 5
N = N//2
while N>=s:
n += N//s
s *= 5
print(n)
| n = int(input())
a = list(map(int, input().split()))
mod = 10**9+7
cur = 0
res = 0
for i in range(n-1):
cur = (cur + a[n-1-i]) % mod
tmp = (a[n-2-i] * cur) % mod
res = (res + tmp) % mod
print(res) | 0 | null | 59,636,031,822,230 | 258 | 83 |
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = input()
ans = 0
for i in range(n):
if((i - k) < 0):
if(t[i] == 'r'):ans += p
elif(t[i] == 's'):ans += r
else:ans += s
continue
else:
if(t[i-k] == t[i]):t = t[:i] + 'n' + t[i+1:]
else:
if(t[i] == 'r'):ans += p
elif(t[i] == 's'):ans += r
else:ans += s
print(ans)
| import os
import sys
import numpy as np
def solve(N, K, S, P, R, T):
dp = np.zeros((N+1, 3), dtype=np.int64)
for i in range(1, N+1):
c = T[i]
dp[i, 0] = max(dp[i-K, 1], dp[i-K, 2]) + (c == "r") * R
dp[i, 1] = max(dp[i-K, 0], dp[i-K, 2]) + (c == "s") * S
dp[i, 2] = max(dp[i-K, 0], dp[i-K, 1]) + (c == "p") * P
#d = dp.max(1)
d = np.zeros(N+1, dtype=np.int64)
for i in range(N+1):
d[i] = dp[i].max()
ans = d[-K:].sum()
return ans
# >>> numba compile >>>
numba_config = [
[solve, "i8(i8,i8,i8,i8,i8,string)"],
]
if sys.argv[-1] == "ONLINE_JUDGE":
from numba import njit
from numba.pycc import CC
cc = CC("my_module")
for func, signature in numba_config:
vars()[func.__name__] = njit(signature)(func)
cc.export(func.__name__, signature)(func)
cc.compile()
exit()
elif os.name == "posix":
exec(f"from my_module import {','.join(func.__name__ for func, _ in numba_config)}")
else:
from numba import njit
for func, signature in numba_config:
vars()[func.__name__] = njit(signature, cache=True)(func)
print("compiled!", file=sys.stderr)
# <<< numba compile <<<
def main():
N, K = map(int, input().split())
S, P, R = map(int, input().split())
T = "_" + input()
ans = solve(N, K, S, P, R, T)
print(ans)
main()
| 1 | 106,582,177,137,400 | null | 251 | 251 |
n,m = map(int,input().split())
wa = [0] * 10**6
ac = [0] * 10**6
ans = 0
for i in range(m):
str_p,str_m = map(str,input().split())
p = int(str_p)
if str_m =='WA':
if ac[p] == 0:
wa[p] += 1
else:
if ac[p] == 0:
ac[p] = 1
ans += wa[p]
print(sum(ac),ans) | n = int(input())
S, T = input().split()
ans = ""
for i in range(n):
ans += S[i]+T[i]
print(ans) | 0 | null | 102,660,423,180,238 | 240 | 255 |
from itertools import groupby
N = int(input())
S = input()
g = groupby(S)
print(len(list(g))) |
n = int(input())
s = input()
count = 1
for h in range(len(s)-1):
if s[h] != s[h+1]:
count += 1
print(count)
| 1 | 170,774,915,543,230 | null | 293 | 293 |
N,K = map(int,input().split())
MOD = 998244353
interval = []
for i in range(K):
intv = [int(x) for x in input().split()]
interval.append(intv)
dp = [0]*N
diff = [0]*(N-1)
dp[0] = 1
diff[0] = -1
for i in range(N-1):
for L,R in interval:
if L <= N-1 - i:
diff[i+L-1] += dp[i]
if R+1 <= N-1 - i:
diff[i+R] -= dp[i]
dp[i+1] = dp[i] + diff[i]
dp[i+1] %= MOD
print(dp[N-1]) | MOD = 998244353
N, K = list(map(int, input().split()))
dp = [0] * (N+1)
dp[1] = 1
LR = []
for i in range(K):
l, r = list(map(int, input().split()))
LR.append([l, r])
for i in range(2, N+1):
dp[i] = dp[i-1]
for j in range(K):
l, r = LR[j]
dp[i] += dp[max(i-l, 0)] - dp[max(i-r-1, 0)]
dp[i] %= MOD
print((dp[N]-dp[N-1]) % MOD) | 1 | 2,705,642,928,042 | null | 74 | 74 |
# coding=utf-8
from math import pi
r = float(raw_input().strip())
print "{0:f} {1:f}".format(pi * r * r, 2 * pi * r) | import math
x = float(input())
print("%.6f %.6f"%(x*x*math.pi, x*2*math.pi))
| 1 | 654,183,782,720 | null | 46 | 46 |
S=input();
if(S=="hi" or S=="hihi" or S=="hihihi" or S=="hihihihi" or S=="hihihihihi"):
print("Yes");
else:
print("No"); | n=int(input())
ans=0
if n%2==0:
for i in range(1,26):
ans+=(n//(2*5**i))
print(ans) | 0 | null | 84,769,402,724,578 | 199 | 258 |
# import sys
# input = sys.stdin.readline
import collections
def main():
n = int(input())
s = input()
a_list = []
for i in range(n):
if s[i] == "W":
a_list.append(0)
else:
a_list.append(1)
r_count = sum(a_list)
print(r_count - sum(a_list[0:r_count]))
def input_list():
return list(map(int, input().split()))
def input_list_str():
return list(map(str, input().split()))
if __name__ == "__main__":
main()
| n,m,k=map(int,input().split())
par = [-1]*n
num = [0]*n
def find(x):
if par[x]<0:
return x
else:
par[x] = find(par[x])
return par[x]
def union(x, y):
p,q=find(x), find(y)
if p==q:
return
if p>q:
p,q = q,p
par[p] += par[q]
par[q] = p
def size(x):
return -par[find(x)]
def same(x,y):
return find(x)==find(y)
for i in range(m):
a,b=map(int,input().split())
a-=1
b-=1
union(a,b)
num[a]+=1
num[b]+=1
for i in range(k):
c,d=map(int,input().split())
c-=1
d-=1
if same(c,d):
num[c]+=1
num[d]+=1
for i in range(n):
print(size(i)-1-num[i], end=" ") | 0 | null | 34,089,219,847,180 | 98 | 209 |
import sys
from collections import deque
def test():
EleList = deque()
sublist = []
output = []
areas_from_left = list(sys.stdin.readline())
sum = 0
depth = 0
for element in areas_from_left:
if element == '\\':
depth += 1
EleList.append(element)
elif element == '_':
if EleList:
EleList.append(element)
elif element == '/':
depth -= 1
if EleList:
for pop_count in range(len(EleList)):
pop_ele = EleList.pop()
if pop_ele == '\\' and EleList:
for i in range(pop_count+2):
EleList.append('_')
break
lake = pop_count + 1
sum += lake
if len(EleList) == 0:
if len(sublist) == 0:
output.append(lake)
else:
tmp = 0
for i in sublist:
tmp += i[0]
output.append(tmp + lake)
sublist.clear()
else:
if not sublist or sublist[len(sublist)-1][1] < depth:
sublist_element = [0,0]
sublist_element[0] = lake
sublist_element[1] = depth
sublist.append(sublist_element)
else:
sublist_element = [lake,depth]
while True:
if not sublist:
break
tmp = sublist.pop()
if tmp[1] > depth:
sublist_element[0] += tmp[0]
else:
sublist.append(tmp)
break
sublist.append(sublist_element)
#print(f"{output}{sublist}")
output_sublist = []
for tmp in sublist:
output_sublist.append(tmp[0])
output = output + output_sublist
length = len(output)
print(sum)
if length != 0:
print(f"{length} ",end='')
else:
print(length)
for i in range(length - 1):
print(f"{output[i]} ",end='')
if output:
print(output[length-1])
if __name__ == "__main__":
test()
| S1 = []
S2= []
sum = 0
for i, s in enumerate(input()):
if s == "\\":
S1.append(i)
elif s == "/" and len(S1) > 0:
j = S1.pop()
sum += i - j
a = i - j
while len(S2) > 0 and S2[-1][0] > j:
a += S2.pop()[1]
S2.append((j, a))
print(sum)
sum2 = [str(len(S2))]
for s in S2:
sum2.append(str(s[1]))
print(" ".join(sum2))
| 1 | 61,481,427,140 | null | 21 | 21 |
while True:
m, f, r = (int(x) for x in input().split())
if (m, f, r) == (-1, -1, -1):
break
sum_score = m + f
if m == -1 or f == -1:
print("F")
elif sum_score >= 80:
print("A")
elif 65 <= sum_score < 80:
print("B")
elif 50 <= sum_score < 65:
print("C")
elif 30 <= sum_score < 50:
print("C") if r >= 50 else print("D")
else:
print("F") | # ABC143
# B Tkoyaki Festival 2019
n = int(input())
D = list(map(int, input().split()))
ct = 0
for i in range(n):
for j in range(n):
if i != j:
if i < j:
ct += D[i] * D[j]
print(ct)
| 0 | null | 85,002,306,659,270 | 57 | 292 |
N = int(input())
AB = [list(map(int, input().split())) for _ in range(N)]
A = [a for a, b in AB]
B = [b for a, b in AB]
A.sort()
B.sort()
if N % 2:
ma = B[N // 2]
mi = A[N // 2]
else:
ma = B[N // 2 - 1] + B[N // 2]
mi = A[N // 2 - 1] + A[N // 2]
print(ma - mi + 1) | from collections import deque
import sys
input = sys.stdin.readline
n = int(input())
a = [0]*n
b = [0]*n
for i in range(n):
a[i], b[i] = map(int, input().split())
a.sort()
b.sort()
if n%2!=0 :
l = a[int(n/2)]
u = b[int(n/2)]
ans = u - l + 1
else:
l = a[int(n/2-1)] + a[int(n/2)]
u = b[int(n/2-1)] + b[int(n/2)]
ans = u - l +1
print(ans)
| 1 | 17,262,077,516,850 | null | 137 | 137 |
def A():
n, x, t = map(int, input().split())
print(t * ((n+x-1)//x))
def B():
n = list(input())
s = 0
for e in n:
s += int(e)
print("Yes" if s % 9 == 0 else "No")
def C():
int(input())
a = list(map(int, input().split()))
l = 0
ans = 0
for e in a:
if e < l: ans += l - e
l = max(l, e)
print(ans)
def E():
h, w, m = map(int, input().split())
row = [0] * h
col = [0] * w
exist = set([])
th = 1000000000
for i in range(m):
x, y = map(int, input().split())
x -= 1
y -= 1
row[x] += 1
col[y] += 1
exist.add(x*th + y)
max_row = max(row)
max_col = max(col)
candi_row = []
candi_col = []
for i in range(h):
if row[i] == max_row: candi_row.append(i)
for i in range(w):
if col[i] == max_col: candi_col.append(i)
ans = max_row + max_col
for x in candi_row:
for y in candi_col:
if x*th + y in exist: continue
print(ans)
return
print(ans - 1)
E()
| h,w,m = map(int,input().split())
x = {}
y = {}
dic = {}
for _ in range(m):
a,b = map(int,input().split())
dic[(a,b)] = 1
x[a] = x.get(a,0) + 1
y[b] = y.get(b,0) + 1
p = max(x.values())
q = max(y.values())
cnt = 1
a = [i for i in x if x[i] == p]
b = [j for j in y if y[j] == q]
for i in a:
for j in b:
if dic.get((i,j),-1) == -1:
cnt = 0
break
if not cnt:
break
print(p+q-cnt) | 1 | 4,769,244,142,720 | null | 89 | 89 |
M = 10 ** 6
d = [0] * (M+1)
for a in range(1, M+1):
for b in range(a, M+1):
n = a * b
if n > M:
break
d[n] += 2 - (a==b)
N = int(input())
ans = 0
for c in range(1, N):
ans += d[N - c]
print(ans) | n = int(input())
cnt = 0
for a in range(1, n):
for b in range(1, ((n-1)//a)+1):
c = n - a*b
if c <= 0: break
if a*b + c == n: cnt += 1
print(cnt)
| 1 | 2,612,271,010,268 | null | 73 | 73 |
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1:
arr.append([temp, 1])
if arr==[]:
arr.append([n, 1])
return arr
N = int(input())
if N == 1:
print("0")
exit()
factors = factorization(N)
ans = 0
for factor in factors:
num = factor[1]
x = 1
for i in range(num+1):
if i**2 + i > 2*num:
x = i-1
break
# print(num,x)
ans += x
print(ans)
| import math
import numpy as np
n = int(input())
s = math.sqrt(n)
i = 2
f = {}
while i <= s:
while n % i == 0:
f[i] = f.get(i,0)+1
n = n // i
i += 1
ans = 0
for x in f.values():
e = 0
cumsum = 0
while e + cumsum + 1 <= x:
e += 1
cumsum += e
ans += e
print(ans+(n>1)) | 1 | 16,842,506,280,860 | null | 136 | 136 |
h, w = map(int, input().split())
sheet = []
for j in range(h):
lista = list(map(int, input().split()))
lista.append(sum(lista))
sheet.append(lista)
lista = []
for i in range(w+1):
sum = 0
for j in range(h):
sum += sheet[j][i]
lista.append(sum)
sheet.append(lista)
for i in range(h+1):
text = ""
for j in range(w+1):
text += str(sheet[i][j]) + " "
print(text[:-1]) | # 降順にしたものを考え、最大のやつは1回、あとのやつは2回ずつ使える
n = int(input())
a = sorted(list(map(int, input().split())), reverse=True)
ans = a[0]
count = n - 2
idx = 1
while count > 0:
count_of_count = 2
while count_of_count > 0 and count > 0:
count -= 1
count_of_count -= 1
ans += a[idx]
idx += 1
print(ans) | 0 | null | 5,246,670,586,482 | 59 | 111 |
n = int(input())
s = [list(input()) for i in range(n)]
r = []
l = []
ans = 0
for i in s:
now = 0
c = 0
for j in i:
if j =="(":
now += 1
else:
now -= 1
c = min(c,now)
if c == 0:
ans += now
elif now >= 0:
l.append([c,now])
else:
r.append([c-now,now])
l.sort(reverse =True)
r.sort()
for i,j in l:
if ans + i < 0:
print("No")
exit()
else:
ans += j
for i,j in r:
if ans +i+j < 0:
print("No")
exit()
else:
ans += j
if ans == 0:
print("Yes")
else:
print("No")
| n = input()
card = []
for i in range(n):
card.append(raw_input())
for a in ['S','H','C','D']:
for b in range(1,14):
check = a + " " + str(b)
for c in card:
if check == c:
flg = 0
break
else:
flg = 1
if flg == 1:
print check | 0 | null | 12,404,078,352,710 | 152 | 54 |
from bisect import bisect_left
n, m = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
A_r = sorted(A, reverse = True)
cumsumA = [0]
total = 0
for i in range(n):
total += A_r[i]
cumsumA.append(total)
def func(x):
ans = 0
for i in range(n):
kazu = x - A[i]
idx = bisect_left(A, kazu)
cou = n - idx
ans += cou
if ans >= m:
return True
else:
return False
mi = 0
ma = 2 * 10 ** 5 + 1
while ma - mi > 1:
mid = (mi + ma) // 2
if func(mid):
mi = mid
else:
ma = mid
ans = 0
count = 0
for ai in A_r:
idx = bisect_left(A, mi - ai)
ans += ai * (n - idx) + cumsumA[n - idx]
count += n - idx
print(ans - (count-m) * mi)
| #!/usr/bin/env python3
import sys
input = sys.stdin.readline
import cmath
pi = cmath.pi
exp = cmath.exp
def fft(a, inverse=False):
n = len(a)
h = n.bit_length() - 1
# Swap
for i in range(n):
j = 0
for k in range(h):
j |= (i >> k & 1) << (h - 1 - k)
if i < j:
a[i], a[j] = a[j], a[i]
# Butterfly calculation
if inverse:
sign = 1.0
else:
sign = -1.0
b = 1
while b < n:
for j in range(b):
w = exp(sign * 2.0j * pi / (2.0 * b) * j)
for k in range(0, n, b*2):
s = a[j + k]
t = a[j + k + b] * w
a[j + k] = s + t
a[j + k + b] = s - t
b *= 2
if inverse:
for i in range(n):
a[i] /= n
return a
def ifft(a):
return fft(a, inverse=True)
def convolve(f, g):
n = 2**((len(f) + len(g) - 1).bit_length())
f += [0] * (n - len(f))
g += [0] * (n - len(g))
F = fft(f)
G = fft(g)
FG = [Fi * Gi for Fi, Gi in zip(F, G)]
fg = [int(item.real + 0.5) for item in ifft(FG)]
return fg
if __name__ == "__main__":
n, m = map(int, input().split())
a = [int(item) for item in input().split()]
max_a = max(a)
freq = [0] * (max_a + 1)
for item in a:
freq[item] += 1
f = freq[:]; g = freq[:]
fg = convolve(f, g)
total = sum(a) * n * 2
cnt = n * n - m
for i, item in enumerate(fg):
use = min(cnt, item)
total -= i * use
cnt -= use
if cnt == 0:
break
print(total) | 1 | 108,359,328,618,170 | null | 252 | 252 |
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from collections import deque
from functools import lru_cache
import bisect
import re
import queue
import copy
import decimal
class Scanner():
@staticmethod
def int():
return int(sys.stdin.readline().rstrip())
@staticmethod
def string():
return sys.stdin.readline().rstrip()
@staticmethod
def map_int():
return [int(x) for x in Scanner.string().split()]
@staticmethod
def string_list(n):
return [Scanner.string() for i in range(n)]
@staticmethod
def int_list_list(n):
return [Scanner.map_int() for i in range(n)]
@staticmethod
def int_cols_list(n):
return [Scanner.int() for i in range(n)]
def solve():
X = Scanner.int()
X -= 400
print(8 - X // 200)
def main():
# sys.setrecursionlimit(1000000)
# sys.stdin = open("sample.txt")
solve()
if __name__ == "__main__":
main()
| # get input from user and convert in to int
current_temp = int(input())
# Check that the restriction per task instruction is met
if (current_temp <= 40) and (current_temp >= -40):
# Check if current_temp is greater than or equal to 30
if current_temp >= 30:
print("Yes")
else:
print("No") | 0 | null | 6,171,478,985,828 | 100 | 95 |
N = int(input())
A = N%10
B = [2,4,5,7,9]
C = [0,1,6,8]
if A in B:
print('hon')
elif A in C:
print('pon')
else:
print('bon') | N = input()
if (N[-1] == str(3)):
print('bon')
elif(int(N[-1]) == 0 or int(N[-1]) == 1 or int(N[-1]) == 6 or int(N[-1]) == 8 ):
print('pon')
else:
print('hon') | 1 | 19,332,761,661,152 | null | 142 | 142 |
import math
N = int(input())
MOD_VALUE = math.pow(10, 9) + 7
def pow_mod(value, pow):
ret = 1
for _ in range(pow):
ret = ret * value % MOD_VALUE
return ret
result = pow_mod(10, N) - pow_mod(9, N) * 2 + pow_mod(8, N)
print(int(result % MOD_VALUE))
| N = int(input())
MOD = 10**9 + 7
a1, a2, a3 = 1, 1, 1
for _ in range(N):
a1 *= 10
a1 %= MOD
for _ in range(N):
a2 *= 9
a2 %= MOD
a2 *= 2
a2 %= MOD
for _ in range(N):
a3 *= 8
a3 %= MOD
ans = a1 - a2 + a3
ans %= MOD
print(ans)
| 1 | 3,174,565,102,570 | null | 78 | 78 |
K = int(input())
[A,B] = list(map(int,input().split()))
flag=0
for i in range(A,B+1):
if i%K==0:
flag=1
if flag==1:
print('OK')
else:
print('NG') | K = int(input())
A, B = [int(x) for x in input().split(" ")]
i = 1
while 1:
if A <= i * K <= B:
print("OK")
break
elif i * K > B:
print("NG")
break
i += 1 | 1 | 26,562,088,484,392 | null | 158 | 158 |
import math
x1,y1,x2,y2=map(float,input().split())
print(round(math.sqrt((x1-x2)**2+(y1-y2)**2),7))
| data = list(map(float, input().split()))
print(((data[2]-data[0])**2+(data[3]-data[1])**2)**0.5)
| 1 | 151,379,652,960 | null | 29 | 29 |
n = input()
if "7" in n:
print('Yes')
else:
print('No') | a,b,c= (int(x) for x in input().split())
A = int(a)
B = int(b)
C = int(c)
if A+B+C >= 22:
print("bust")
else:
print("win") | 0 | null | 76,456,652,953,212 | 172 | 260 |
count = input()
Ss = []
Hs = []
Cs = []
Ds = []
for i in range(int(count)):
mark, num = input().split()
if mark is 'S':
Ss.append(num)
elif mark is 'H':
Hs.append(num)
elif mark is 'C':
Cs.append(num)
elif mark is 'D':
Ds.append(num)
for i in range(1,14):
if not(str(i) in Ss):
print("S {0}".format(str(i)))
for i in range(1,14):
if not(str(i) in Hs):
print("H {0}".format(str(i)))
for i in range(1,14):
if not(str(i) in Cs):
print("C {0}".format(str(i)))
for i in range(1,14):
if not(str(i) in Ds):
print("D {0}".format(str(i))) | def main():
n = input()
A = []
s = []
B = [[0,0] for i in xrange(n)]
for i in xrange(n):
A.append(map(int,raw_input().split()))
color = [-1]*n
d = [0]*n
f = [0]*n
t = 0
for i in xrange(n):
if color[i] == -1:
t = dfs(i,t,color,d,f,A,n)
for i in xrange(n):
print i+1, d[i], f[i]
def dfs(u,t,color,d,f,A,n):
t += 1
color[u] = 0
d[u] = t
for i in A[u][2:]:
if (color[i-1] == -1):
t = dfs(i-1,t,color,d,f,A,n)
color[u] = 1
t += 1
f[u] = t
return t
if __name__ == '__main__':
main() | 0 | null | 512,167,754,058 | 54 | 8 |
n,m=map(int,input().split())
a=list(map(int,input().split()))
h=sum(a)
if n<h:
print('-1')
else:
print(n-h) | s=input()
sl=len(s)
a=[]
count=1
for i in range(sl-1):
if s[i+1]==s[i]:
count+=1
else:
a.append(count)
count=1
a.append(count)
ans=0
al=len(a)
if s[0]=="<":
for i in range(0,al-1,2):
m,n=max(a[i],a[i+1]),min(a[i],a[i+1])
ans+=(m*(m+1)+n*(n-1))/2
if al%2==1:
ans+=a[-1]*(a[-1]+1)/2
elif s[0]==">":
ans+=a[0]*(a[0]+1)/2
for i in range(1,al-1,2):
m,n=max(a[i],a[i+1]),min(a[i],a[i+1])
ans+=(m*(m+1)+n*(n-1))/2
if al%2==0:
ans+=a[-1]*(a[-1]+1)/2
print(int(ans)) | 0 | null | 94,021,550,155,820 | 168 | 285 |
def gcd(a,b):
if a > b:
x = a
y = b
else:
x = b
y = a
while y > 0:
r = x % y
x = y
y = r
return x
def lcm(a,b,c):
return int(a*b/c)
while 1:
try:
a,b = [int(x) for x in input().split()]
res_gcd = gcd(a,b)
res_lcm = lcm(a,b,res_gcd)
print('{} {}'.format(res_gcd,res_lcm))
except:
break | import sys
a=[map(int,i.split())for i in sys.stdin]
for i,j in a:
c,d=i,j
while d:
if c > d:c,d = d,c
d%=c
print(c,i//c*j) | 1 | 511,003,458 | null | 5 | 5 |
n = int(input())
h = [[[0 for i in range(10)] for j in range(3)] for k in range(4)]
for _ in range(n):
b, f, r, v = [int(e) for e in input().split()]
h[b-1][f-1][r-1] += v
for i, b in enumerate(h):
if i != 0:
print('#'*20)
for f in b:
print(' ', end='')
print(*f) | build = range(1, 5)
floor = range(1, 4)
dic = {b: {f: [0]*10 for f in floor} for b in build}
n = input()
for i in range(n):
info = map(int, raw_input().split())
dic[info[0]][info[1]][info[2]-1] += info[3]
if dic[info[0]][info[1]][info[2]-1] > 9:
print 'error'
for b in build:
for f in floor:
print '',
print ' '.join(map(str, dic[b][f]))
if b != 4:
print "#"*20 | 1 | 1,076,124,255,008 | null | 55 | 55 |
import sys
n = sys.stdin.readline()
s = sys.stdin.readline().split()
q = sys.stdin.readline()
t = sys.stdin.readline().split()
cnt = 0
for i in t:
if i in s:
cnt += 1
print(cnt) | h,n = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(n)]
dp = [float("inf") for i in range(10**5)]
dp[0] = 0
for a,b in ab:
for k in range(a+1):
dp[k] = min(dp[k], b)
for k in range(a+1,h+1):
dp[k] = min(dp[k], dp[k-a] + b)
print(dp[h]) | 0 | null | 40,339,656,659,810 | 22 | 229 |
n = int(input())
low = [0]*n
high = [0]*n
for i in range(n):
a, b = [int(x) for x in input().split(" ")]
low[i] = a
high[i] = b
low.sort()
high.sort()
if n%2 == 1:
print(high[n//2]-low[n//2]+1)
else:
x = (low[(n-1)//2] + low[n//2])/2
y = (high[(n-1)//2] + high[n//2])/2
print(int(2*y - 2*x + 1))
| from statistics import median
n = int(input())
a = [None] * n
b = [None] * n
for i in range(n):
a[i], b[i] = map(int, input().split())
if n % 2 == 1:
print(median(b) - median(a) + 1)
else:
print(int((median(b) - median(a)) * 2) + 1) | 1 | 17,229,022,807,682 | null | 137 | 137 |
from sys import stdin
n = int(stdin.readline())
q = []
bottom = 0
for i in range(n):
cmd = stdin.readline()[:-1]
if cmd[0] == 'i':
q.append(cmd[7:])
elif cmd[6] == ' ':
try:
q.pop(~q[::-1].index(cmd[7:]))
except:
pass
elif cmd[6] == 'F':
q.pop()
else:
bottom += 1
print(' '.join(q[bottom:][::-1])) | n=int(input())
cnt=0
ans=0
for i in range(1,n+1):
cnt+=1
if i%2==1:
ans+=1
print(ans/cnt) | 0 | null | 88,166,029,580,060 | 20 | 297 |
# -*- coding: utf-8 -*-
def main():
A, B = map(int, input().split())
ans = A - 2 * B
if ans < 0:
ans = 0
print(ans)
if __name__ == "__main__":
main() | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
a, b = map(int, readline().split())
ans = a - b * 2
if ans < 0:
print(0)
else:
print(ans)
| 1 | 166,706,483,668,240 | null | 291 | 291 |
x, y = map(int, input().split())
def gcd(x, y):
if x % y == 0:
return y
elif x % y == 1:
return 1
else:
return gcd(y, x % y)
if x >= y:
n = gcd(x, y)
print(n)
else:
n = gcd(y, x)
print(n) | def getResult(a,b):
if a<b:
a,b=b,a
while b!=0:
r = a%b
a = b
b = r
return a
a,b = map(int,input().strip().split())
print(getResult(a,b)) | 1 | 7,448,683,100 | null | 11 | 11 |
from functools import lru_cache
MOD = 10**9+7
x,y = map(int, input().split())
summ = x+y
@lru_cache(maxsize=None)
def inv(n):
return pow(n,-1,MOD)
if summ%3 == 0 and summ//3 <= x and summ//3 <= y:
mn = min(x,y)
n = mn - summ//3
a = summ//3
b = 1
ans = 1
for i in range(n):
ans *= a
ans *= inv(b)
ans %= MOD
a -= 1
b += 1
print(ans)
else:
print(0) | import sys
from collections import OrderedDict
input = sys.stdin.readline
sys.setrecursionlimit(2 * 10**6)
def inpl():
return list(map(int, input().split()))
def main():
MOD = 998244353
N, S = inpl()
A = sorted(inpl())
dp = {}
dp[0] = 1
for i, a in enumerate(A):
# print(i, dp)
ks = sorted(dp.keys())
for k in ks[::-1]:
# print(k)
if k + a <= S:
if k + a in dp:
dp[k + a] = (dp[k] + dp[k + a]) % MOD
else:
dp[k + a] = dp[k]
dp[k] = (dp[k] * 2) % MOD
# print(dp)
print(0 if S not in dp else dp[S])
return
if __name__ == '__main__':
main()
| 0 | null | 84,203,838,061,698 | 281 | 138 |
N, M = map(int, input().split())
print('Yes' if N <= M else 'No')
| N_dict = {i:0 for i in list(map(str,input().split()))}
N_List = list(map(int,input().split()))
ct = 0
for i in N_dict.keys():
N_dict[i] = N_List[ct]
ct += 1
N_dict[str(input())] -= 1
print(" ".join(list(map(str,N_dict.values()))))
| 0 | null | 77,161,661,073,472 | 231 | 220 |
import numpy as np
def solve(H, W, M, h, w):
f = [0] * (H+1)
g = [0] * (W+1)
for r, c in zip(h, w):
f[r] += 1
g[c] += 1
p = np.max(f)
q = np.max(g)
num = len(list(filter(p.__eq__, f))) * len(list(filter(q.__eq__, g)))
for r, c in zip(h, w):
if (f[r] == p) and (g[c] == q):
num -= 1
return p + q - (num <= 0)
H, W, M = map(int, input().split())
h, w = zip(*[map(int, input().split()) for i in range(M)])
print(solve(H, W, M, h, w)) | def main():
from sys import setrecursionlimit, stdin, stderr
from os import environ
from collections import defaultdict, deque, Counter
from math import ceil, floor
from itertools import accumulate, combinations, combinations_with_replacement
setrecursionlimit(10**6)
dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
input = lambda: stdin.readline().rstrip()
LMIIS = lambda: list(map(int,input().split()))
II = lambda: int(input())
P = 10**9+7
INF = 10**18+10
H,W,M = LMIIS()
targets_row = []
targets_column = []
targets = []
for i in range(M):
column,row = LMIIS()
targets_row.append(row)
targets_column.append(column)
targets.append((column,row))
common_columns = Counter(targets_column).most_common()
common_rows = Counter(targets_row).most_common()
max_columns = defaultdict(bool)
num_max_column = common_columns[0][1]
for k,v in common_columns:
if v < num_max_column:
break
max_columns[k] = True
max_rows = defaultdict(bool)
num_max_row = common_rows[0][1]
for k,v in common_rows:
if v < num_max_row:
break
max_rows[k] = True
dbg(max_columns)
dbg(max_rows)
num_candidates = len(max_columns)*len(max_rows)
num_target_on_intersection = 0
for column, row in targets:
if max_columns[column] and max_rows[row]:
num_target_on_intersection += 1
ans = common_columns[0][1] + common_rows[0][1]
dbg(num_target_on_intersection)
dbg(num_candidates)
print(ans if num_target_on_intersection < num_candidates else ans - 1)
main() | 1 | 4,689,915,896,118 | null | 89 | 89 |
import sys
input = sys.stdin.readline
N = [int(x) for x in input().rstrip()][::-1] + [0]
L = len(N)
dp = [[10 ** 18, 10 ** 18] for _ in range(L)]
dp[0] = [N[0], 10 - N[0]]
for i in range(1, L):
n = N[i]
dp[i][0] = min(dp[i - 1][0] + n, dp[i - 1][1] + (n + 1))
dp[i][1] = min(dp[i - 1][0] + (10 - n), dp[i - 1][1] + (10 - (n + 1)))
print(dp[-1][0]) | #!/usr/bin/env python3
import sys
input = sys.stdin.readline
def main():
N = [0] + list(map(int, tuple(input().rstrip("\n"))))
Ncopy = N.copy()
ans = 0
flag = False
for i in range(len(N)-1, 0, -1):
if (Ncopy[i] <= 4) or (Ncopy[i] == 5 and N[i-1] <= 4):
ans += Ncopy[i]
flag = False
else:
Ncopy[i-1] += 1
if not flag:
ans += 10 - N[i]
else:
ans += 9 - N[i]
Ncopy[i] = 0
flag = True
if Ncopy[0] == 1:
ans += 1
print(ans)
if __name__ == "__main__":
main()
| 1 | 70,847,055,679,060 | null | 219 | 219 |
n = int(input())
a = map(int,input().split())
ans = "APPROVED"
for i in a:
if i%2 == 0:
if not(i%3==0 or i%5==0):
ans = "DENIED"
print(ans) | a,b=map(str,input().split())
c,d=map(int,input().split())
k=input()
if k==a:
c-=1
else:
d-=1
print(c,d) | 0 | null | 70,212,175,124,840 | 217 | 220 |
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
def main():
MOD = 1000000007
N, *A = map(int, read().split())
ans = 1
C = [0] * (N + 1)
C[0] = 3
for a in A:
ans = ans * C[a] % MOD
C[a] -= 1
C[a + 1] += 1
print(ans)
return
if __name__ == '__main__':
main()
| from collections import defaultdict
d=defaultdict(int)
n=int(input())
a=list(map(int,input().split()))
ans=1
mod=10**9+7
d[-1]=3
for i in a:
ans*=d[i-1]
ans%=mod
d[i-1]-=1
d[i]+=1
print(ans) | 1 | 130,128,906,000,508 | null | 268 | 268 |
N = input()
print("Yes" if N.count("7") > 0 else "No") | n=str(input())
if '7' in n:
print('Yes')
else:
print('No') | 1 | 34,315,737,064,960 | null | 172 | 172 |
A=map(int,raw_input().split(" "))
vec=A[0]
col=A[1]
def zero(n):
zerolist=list()
for i in range(n):
zerolist+=[0]
return(zerolist)
A=list()
for i in range(vec):
A+=[zero(col)]
for i in range(vec):
k=map(int,raw_input().split(" "))
for j in range(col):
A[i][j]=k[j]
#ok
v=zero(col)
for i in range(col):
v[i]=int(raw_input())
k=0
for i in range(vec):
for j in range(col):
k+=A[i][j]*v[j]
print k
k=0 | n,m = map(int,input().split())
a = []
b = []
c = []
for i in range(n):
a.append([int(j) for j in input().split()])
for k in range(m):
b.append(int(input()))
for x in range(n):
z = 0
for y in range(m):
z += a[x][y] * b[y]
c.append(z)
for i in c:
print(i)
| 1 | 1,148,957,652,828 | null | 56 | 56 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.