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
|
---|---|---|---|---|---|---|
inputa = input()
print(inputa.swapcase()) | str = input()
new = ''
for i in str:
if i.islower():
new += i.upper()
else:
new += i.lower()
print(new) | 1 | 1,487,120,041,468 | null | 61 | 61 |
N = int(input())
ans = 0
MOD = 10**9+7
ans = 10**N-2*9**N+8**N
ans %= MOD
print(ans) | import math
def solve():
N = int(input())
lowercase = 'abcdefghijklmnopqrstuvwxyz'
ans = ''
for i in range(len(str(N))):
if N == 0:
break
j = N % 26
N -= 1
N = N // 26
ans = lowercase[j - 1] + ans
print(ans)
if __name__ == '__main__':
solve()
| 0 | null | 7,475,765,282,550 | 78 | 121 |
ls = []
while True:
try:
n = int(raw_input())
except EOFError:
break
ls.append(n)
ls.sort(reverse=True)
print ls[0]
print ls[1]
print ls[2] | from collections import deque
H, W = map(int, input().split())
S=[]
for _ in range(H):
S.append(input())
vx = [1, 0, -1, 0]
vy = [0, 1, 0, -1]
ans = 0
def func(si, sj):
queue = deque([si, sj])
seen = [[-1]*W for _ in range(H)]
seen[si][sj] = 0
while queue:
x = queue.popleft()
y = queue.popleft()
for i in range(4):
nx = x + vx[i]
ny = y + vy[i]
if nx<0 or nx>=H or ny<0 or ny>=W:
continue
if S[nx][ny]=="#" or seen[nx][ny]>=0:
continue
seen[nx][ny]=seen[x][y]+1
queue.append(nx)
queue.append(ny)
return seen[x][y]
ans = 0
for i in range(H):
for j in range(W):
if S[i][j]==".":
ans = max(ans, func(i, j))
print(ans) | 0 | null | 47,178,953,155,616 | 2 | 241 |
alpha = "abcdefghijklmnopqrstuvwxyz"
A = [0]*26
while True :
try :
n = input()
for i in range(len(n)) :
if n[i] in alpha or n[i].lower() in alpha :
A[alpha.index(n[i].lower())] += 1
except :
break
for j in range(len(A)) :
print(alpha[j], ":", A[j])
| alphabet = 'abcdefghijklmnopqrstuvwxyz'
from collections import defaultdict
import sys
adict = defaultdict(int)
for l in sys.stdin:
for c in l.lower():
adict[c] += 1
for k in alphabet:
print('%s : %i' %(k, adict[k])) | 1 | 1,664,743,782,756 | null | 63 | 63 |
def main():
a, b, c = map(int, input().split())
if (a + b + c) >= 22:
print("bust")
else:
print("win")
main() | A,B,C=map(int, input().split())
D=A+B+C
if D>=22:
print('bust')
else :
print('win') | 1 | 118,852,670,465,260 | null | 260 | 260 |
s,t=map(str,input('').split(' '))
a,b=map(int,input('').split(' '))
u=input('')
if u==s:
a=a-1
elif u==t:
b=b-1
print(str(a)+' '+str(b)) | s,t=map(str,input().split())
a,b=map(int,input().split())
ss=input()
if ss==s:
a-=1
else:
b-=1
print(a,b) | 1 | 71,838,347,446,250 | null | 220 | 220 |
x=input().split()
y=list(map(int,x))
a=y[0]
b=y[1]
c=y[2]
if a < b and b < c:
print('Yes')
else:
print('No') | word = input()
text = []
count = 0
while True:
line = input()
if line=='END_OF_TEXT':
break
else:
text.append(line.lower().split())
for i in text:
for j in i:
if j == word:
count += 1
print(str(count)) | 0 | null | 1,109,706,193,508 | 39 | 65 |
import sys
sys.setrecursionlimit(10 ** 6)
# 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 SI(): return input().split()
def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))
INF = float('inf')
from math import ceil, floor, log2
from collections import deque
from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product
def solve():
n = II()
A = LI()
memo = {}
ans = 0
for i in range(n):
mae = (i+1) + A[i]
ima = (i+1) - A[i]
ans += memo.get(ima, 0)
memo[mae] = memo.get(mae, 0) + 1
# print(memo)
print(ans)
if __name__ == '__main__':
solve()
| import math
a,b = map(int,input().split())
print(a*b//math.gcd(a,b)) | 0 | null | 70,083,034,511,450 | 157 | 256 |
n = int(input())
s = str(input())
count = 1
for i in range(1, n):
if s[i] != s[i - 1]:
count += 1
print(count)
| N = int(input())
ans = ""
while N > 0:
N -=1
ans = chr(ord("a") + (N%26)) + ans
N //= 26
print(ans) | 0 | null | 91,381,549,157,380 | 293 | 121 |
N, M, K = map(int, input().split())
A = [0] + list(map(int, input().split()))
B = [0] + list(map(int, input().split()))
for i in range(1, N+1):
A[i] += A[i-1]
i = N
total = 0
ans = 0
for j in range(M+1):
total += B[j]
while i >= 0 and A[i]+total > K:
i -= 1
if A[i]+total <= K:
ans = max(ans, i+j)
print(ans) | import numpy as np
from numba import njit
@njit("i8[:](i8, i8[:], i8[:])", cache=True)
def cumsum(K, L, cL):
for i, a in enumerate(L):
cL[i] = cL[i - 1] + L[i]
if cL[i] > K:
cL[i] = 0
break
cL = cL[cL != 0]
cL = np.append(0, cL)
return cL
@njit("i8(i8, i8[:], i8[:])", cache=True)
def solve(K, A, cB):
ans_max = 0
for i, a in enumerate(A):
ans = 0
K -= a
ind = np.searchsorted(cB, K, side="right") - 1
ans = i + ind
if ans > ans_max:
ans_max = ans
if ind == 0 or K < 0:
break
return ans_max
N, M, K = map(int, input().split())
A = np.array(input().split(), dtype=np.int64)
B = np.array(input().split(), dtype=np.int64)
cA = np.zeros(N, dtype=np.int64)
cB = np.zeros(M, dtype=np.int64)
# np.cumsumだとoverflowする
cA = cumsum(K, A, cA)
cB = cumsum(K, B, cB)
A = np.append(0, A)
ans = solve(K, A, cB)
print(max(ans, len(cA) - 1, len(cB) - 1))
| 1 | 10,788,878,714,052 | null | 117 | 117 |
def num_divisors_table(n):
table = [0] * (n + 1)
for i in range(1, n + 1):
for j in range(i, n + 1, i):
table[j] += j
return table
n=int(input())
print(sum(num_divisors_table(n))) | n = int(input())
t = [0]*(n+1)
for i in range(1,n+1):
for j in range(i,n+1,i):
t[j] += j
print(sum(t))
| 1 | 11,057,606,307,770 | null | 118 | 118 |
def divisors(N):
U = int(N ** 0.5) + 1
L = [i for i in range(1, U) if N % i == 0]
return L + [N // i for i in reversed(L) if N != i * i]
def solve(k):
n = N
while n % k == 0:
n //= k
return (n % k == 1)
N = int(input())
K = set(divisors(N) + divisors(N - 1)) - {1}
print(sum(solve(k) for k in K)) | N = int(input())
originalN = 0 +N
if N == 2:
print(1)
exit()
ans = 0
primenum = [2]
count = [0 for _ in range(int(N**0.5)+2)]
for k in range(3, len(count), 2):
if count[k] == 0:
primenum.append(k)
for j in range(k, len(count), k):
count[j] = 1
def factorization(n):
lis = []
k = 0
while primenum[k] <= n:
if n%primenum[k] == 0:
c = 0
while n%primenum[k] == 0:
n //= primenum[k]
c += 1
lis.append([primenum[k], c])
else:
k += 1
if k > len(primenum)-1:
break
if n > 1:
lis.append([n, 1])
return lis
list1 = factorization(N-1)
#print(factorization(N-1))
ans1 = 1
for k in range(len(list1)):
ans1*= list1[k][1]+1
ans1 -= 1
ans += ans1
#print(ans1)
def operation(K):
N = originalN
while N%K == 0:
N //= K
if N%K == 1:
return True
else:
return False
list2 = factorization(N)
#print(list2)
factorlist = [1]
for l in range(len(list2)):
list3 = []
for j in range(list2[l][1]):
for k in range(len(factorlist)):
list3.append(factorlist[k]*list2[l][0]**(j+1))
factorlist += list3
factorlist = factorlist[1:-1]
#print(factorlist)
ans2 = 1
for item in factorlist:
if operation(item):
#print(item)
ans2 +=1
ans += ans2
#print(ans2)
print(ans) | 1 | 41,204,754,649,692 | null | 183 | 183 |
n, k, s = map(int, input().split())
ans = []
for i in range(k):
ans.append(s)
for i in range(n-k):
if s == 10**9:
ans.append(10**9-1)
else:
ans.append(s+1)
print(*ans, sep=' ')
| def resolve():
N = int(input())
S = str(input())
ans = 0
for pos in range(N - 2):
if S[pos:(pos + 3)] == 'ABC':
ans += 1
print(ans)
return
resolve() | 0 | null | 95,625,626,163,100 | 238 | 245 |
a, b, c, d = map(int, input().split())
T = 0
A = 0
while a > 0:
a -= d
A += 1
while c > 0:
c -= b
T += 1
if A >= T:
print("Yes")
else:
print("No") | def solve(N,K):
if N == 0:
return 1
digit_num = 0
while(1):
if N >= pow(K,digit_num):
digit_num += 1
else:
return digit_num
N, K = map(int,input().split())
ans = solve(N,K)
print(ans) | 0 | null | 46,781,120,904,850 | 164 | 212 |
import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy
def prime_factorize(n):
prime_fact = []
while n%2 == 0:
prime_fact.append(2)
n//=2
f = 3
while f * f <= n:
if n % f == 0:
prime_fact.append(f)
n //= f
else:
f += 2
if n != 1:
prime_fact.append(n)
return prime_fact
if __name__ == "__main__":
n = int(input())
a = list(map(int,input().split()))
prefix_gcd = a[0]
dp = [0]*(max(a)+1)
for i in range(n):
prefix_gcd = math.gcd(prefix_gcd,a[i])
for i in range(n):
d = prime_factorize(a[i])
d = set(d)
for j in d:
dp[j]+=1
pair = True
for i in range(len(dp)):
if dp[i] > 1:
pair = False
if pair == True and prefix_gcd == 1:
print("pairwise coprime")
elif pair == False and prefix_gcd == 1:
print("setwise coprime")
else:
print("not coprime") | import math
def GCD(a):
gcd = a[0]
N = len(a)
for i in range(1, N):
gcd = math.gcd(gcd, a[i])
return gcd
# 素因数分解
def fact(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())
A = list(map(int, input().split()))
hst = [0] * (max(A) + 1)
for a in A:
F = fact(a)
for f in F:
hst[f[0]] += 1
if hst[f[0]] > 1 and f[0] != 1:
# ここでpairwise じゃないことが確定する
if GCD(A) == 1:
print("setwise coprime")
else:
print("not coprime")
exit()
print("pairwise coprime") | 1 | 4,117,802,336,802 | null | 85 | 85 |
N,K = map(int,input().split())
A = list(map(int,input().split()))
for i in range(K,N):
if A[i] > A[i-K]:
print("Yes")
else:
print("No") | N, K = map(int, input().split())
A = list(map(int, input().split()))
result = []
for i in range(K, N):
if A[i] > A[i - K]:
result.append('Yes')
else:
result.append('No')
print(*result, sep='\n') | 1 | 7,105,868,554,876 | null | 102 | 102 |
N,M=map(int,input().split())
A=list(map(int,input().split()))
A.sort(reverse=True)
AM=A[0:M]
asum=sum(A)
rate=asum/4/M
for idx in AM:
if idx<rate:
print('No')
break
else:
print('Yes') | n = int(input())
x = input()
f = [-1] * (n+10)
f[0] = 0
for i in range(1, n+10):
# python bitcount で見つけたこれを参考に https://ameblo.jp/316228/entry-10518720149.html
f[i] = f[i % bin(i).count('1')] + 1
init_bitcount = x.count('1')
# Xを init_bitcount+1とinit_bitcount-1で割った余り
x_mod_01 = 0
for digit in x:
x_mod_01 *= 2
if digit == '1':
x_mod_01 += 1
x_mod_01 %= (init_bitcount+1)
if init_bitcount != 1:
x_mod_10 = 0
for digit in x:
x_mod_10 *= 2
if digit == '1':
x_mod_10 += 1
x_mod_10 %= (init_bitcount-1)
# print(x_mod_01, x_mod_10, init_bitcount)
power_mod_01 = [-1] * (n+10)
power_mod_01[0] = 1
for i in range(1, n+10):
power_mod_01[i] = power_mod_01[i-1] * 2 % (init_bitcount + 1)
if init_bitcount != 1:
power_mod_10 = [-1] * (n+10)
power_mod_10[0] = 1
for i in range(1, n+10):
power_mod_10[i] = power_mod_10[i-1] * 2 % (init_bitcount - 1)
for i in range(n):
if x[i] == '0':
# 0→1
first_residue = (x_mod_01 + power_mod_01[n - i - 1]) % (init_bitcount+1)
print(f[first_residue] + 1)
else:
if init_bitcount == 1:
# 立っているビットの数は0桁、つまりX_i = 0なのでf(X_i) = 0
print(0)
continue
# 1→0
first_residue = (x_mod_10 - power_mod_10[n - i - 1]) % (init_bitcount-1)
print(f[first_residue] + 1)
# https://twitter.com/kyopro_friends/status/1281949470100353024
# https://atcoder.jp/contests/aising2020/editorial 公式
# 1回の操作で桁数以下に落ちることに注意すると、操作の繰り返しで急速に値が小さくなり、少ない回数で0に到着する。
# したがってfの表を作るのは今回不要。愚直にやってもできるので。初回の高速化だけが必要。
| 0 | null | 23,387,012,950,322 | 179 | 107 |
# Binary Search
def isOK(i, key):
'''
問題に応じて返り値を設定
'''
cnt = 0
for v in a:
cnt += (v + i - 1) // i - 1
return cnt <= key
def binary_search(key):
'''
条件を満たす最小/最大のindexを求める
O(logN)
'''
ok = 10 ** 9 # 条件を満たすindexの上限値/下限値
ng = 0 # 条件を満たさないindexの下限値-1/上限値+1
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if isOK(mid, key): # midが条件を満たすか否か
ok = mid
else:
ng = mid
return ok
n, k = map(int, input().split())
a = list(map(int, input().split()))
print(binary_search(k)) | def main():
import math
n,k = map(int,input().split())
a = list(map(int,input().split()))
def f(a,l):
ans = 0
for i in range(len(a)):
ans += math.ceil(a[i]/l)-1
return ans
l,r = 1,max(a)
while r-l>1:
mid = (l+r)//2
g = f(a,mid)
if g>k:
l = mid+1
else:
r = mid
if f(a,l)<=k:
print(l)
else:
print(r)
if __name__ == "__main__":
main()
| 1 | 6,473,078,010,560 | null | 99 | 99 |
num1, num2 = map(int, input().split())
print(num1*num2) | # 問題文
# 高橋君の夏休みはN日間です。
# 夏休みの宿題が M個出されており、i番目の宿題をやるにはAi日間かかります。
# 複数の宿題を同じ日にやることはできず、また、宿題をやる日には遊ぶことができません。
# 夏休み中に全ての宿題を終わらせるとき、最大何日間遊ぶことができますか?
# ただし、夏休み中に全ての宿題を終わらせることができないときは、かわりに -1 を出力してください。
# n(夏休みの日数),m(宿題の数):標準入力
# リストの中のA(宿題日):リストを作成し、標準入力
n, m = map(int, input().split())
A = list(map(int, input(). split()))
# 最大で n −合計(A1+. . .+AM)日間遊ぶことができる
if n < sum(A): # 夏休みの日数より宿題日が多い場合:宿題をやる日数が足りない→終わらせることができない
print(-1)
else:
print(n-sum(A)) # その他→宿題は終わる→夏休みの日数-宿題日
# NameError: name 'N' is not defined | 0 | null | 23,909,376,179,282 | 133 | 168 |
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
n = int(input())
A = list(map(int,input().split()))
high = 0
ans = 0
for a in A:
if high > a:
ans += high - a
elif high < a:
high = a
print(ans)
if __name__=='__main__':
main() | n = int(input())
a = list(map(int, input().split()))
ans = [0]*n
for boss in a:
ans[boss-1] += 1
for sub in ans:
print(sub) | 0 | null | 18,600,918,410,130 | 88 | 169 |
s=input()
con=len(s)
ans=['x']*con
ANS=''
for i in ans:
ANS+=i
print(ANS) | S=input()
a=len(S)
print('x'*a) | 1 | 73,162,357,396,000 | null | 221 | 221 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def print_array(a):
print(" ".join(map(str, a)))
def insertion_sort(a, n):
print_array(a)
for i in range(1, n):
v = a[i]
j = i - 1
while j >= 0 and a[j] > v:
a[j + 1] = a[j]
j -= 1
a[j + 1] = v
print_array(a)
return a
def main():
n = int(input())
a = list(map(int, input().split()))
b = insertion_sort(a, n)
if __name__ == "__main__":
main() | N,M,K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
###Bをi冊目まで読むのにどれだけ時間がかかるか
P = [0]*M
P[0] = B[0]
for i in range(1,M):
P[i] = P[i-1] + B[i]
T = K###残り時間
ans = 0
num = M-1
for i in range(N):
T -= A[i]
if T < 0:
break
while P[num] > T and num >= 0:
num -= 1
ans = max(ans,i+num+2)
#print(i,num,ans)
###Aを1冊も読まない場合
for i in range(M):
if P[i] <= K:
ans = max(ans,i+1)
else:
break
print(ans) | 0 | null | 5,429,397,973,550 | 10 | 117 |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import numpy as np
N = int(readline())
XY = np.array(read().split(),np.int64)
X = XY[::2]; Y = XY[1::2]
dx = X[:,None] - X[None,:]
dy = Y[:,None] - Y[None,:]
dist_mat = (dx * dx + dy * dy) ** .5
answer = dist_mat.sum() / N
print(answer) | import itertools
N = int(input())
x = []
y = []
for i in range(N):
xy = list(map(int, input().split()))
x.append(xy[0])
y.append(xy[1])
l = [i for i in range(N)]
ans = 0
cnt = 0
for i in itertools.permutations(l, N):
cnt += 1
for j in range(1, N):
x1 = x[i[j]]
x2 = x[i[j-1]]
y1 = y[i[j]]
y2 = y[i[j-1]]
ans += pow((x1 - x2)**2 + (y1 - y2)**2, 0.5)
# print(i, j, x1, y1, x2, y2)
ans /= cnt
print(ans) | 1 | 148,478,053,643,250 | null | 280 | 280 |
from collections import deque
h, w = map(int, input().split())
chiz = [[] for _ in range(w)]
for _ in range(h):
tmp_list = input()
for i in range(w):
chiz[i].append(tmp_list[i])
def bfs(i,j):
ds = [[-1]*h for _ in range(w)]
dq = deque([(i,j)])
ds[i][j] = 0
res = -1
while dq:
i,j = dq.popleft()
for move in [(1,0),(-1,0),(0,-1),(0,1)]:
if i+move[0] >= 0 and i+move[0] < w and j+move[1] >= 0 and j+move[1] < h:
if chiz[i+move[0]][j+move[1]]=='.' and ds[i+move[0]][j+move[1]] == -1:
ds[i + move[0]][j + move[1]] = ds[i][j] + 1
res = max(res,ds[i + move[0]][j + move[1]])
dq.append((i + move[0],j + move[1]))
return res
res = -1
for j in range(h):
for i in range(w):
if chiz[i][j]=='.':
res = max(res, bfs(i,j))
print(res) | h,w=[int(x) for x in input().rstrip().split()]
l=[list(input()) for i in range(h)]
move=[[1,0],[-1,0],[0,-1],[0,1]]
def bfs(x,y):
stack=[[x,y]]
done=[[False]*w for i in range(h)]
dist=[[0]*w for i in range(h)]
max_val=0
while(stack):
nx,ny=stack.pop(0)
done[ny][nx]=True
for dx,dy in move:
mx=nx+dx
my=ny+dy
if not(0<=mx<=w-1) or not(0<=my<=h-1) or done[my][mx]==True or l[my][mx]=="#":
continue
done[my][mx]=True
dist[my][mx]=dist[ny][nx]+1
max_val=max(max_val,dist[my][mx])
stack.append([mx,my])
return max_val
ans=0
for i in range(w):
for j in range(h):
if l[j][i]!="#":
now=bfs(i,j)
ans=max(ans,now)
print(ans) | 1 | 94,903,417,561,720 | null | 241 | 241 |
a,b,c=[int(x) for x in input().split()]
print('Yes' if a<b<c else 'No')
| def main():
a = []
for i in range(10):
a.append(int(input()))
a.sort()
a.reverse()
for i in range(3):
print(a[i])
if __name__ == '__main__':
main() | 0 | null | 191,717,775,712 | 39 | 2 |
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)
| N = int(input())
X = input()
a = X.count("1")
ap, am = a+1, a-1
Flag = True
if am == 0:
Flag = False
am += 1
Ap = [1]
Am = [1]
for i in range(N-1):
Ap.append(Ap[-1]*2%ap)
Am.append(Am[-1]*2%am)
Aps = 0
Ams = 0
for i in range(N):
if X[-1-i] == "1":
Aps += Ap[i]
Aps %= ap
Ams += Am[i]
Ams %= am
def popcount(x):
x = x - ((x >> 1) & 0x5555555555555555)
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
x = x + (x >> 32)
return x & 0x0000007f
for i in range(N):
cnt = 0
if X[i] == "1":
if Flag:
p = Ams - Am[-1-i]
p %= am
cnt += 1
else:
p = 0
else:
p = Aps + Ap[-1-i]
p %= ap
cnt += 1
while p > 0:
p %= popcount(p)
cnt += 1
print(cnt) | 0 | null | 5,456,878,098,208 | 73 | 107 |
import math
PI = math.pi
r = input()
men = r*r * PI
sen = r*2 * PI
print('%.6f %.6f' % (men, sen)) | # -*- coding: utf-8 -*-
import sys
import os
import math
PI = math.pi
r = float(input())
s = r * r * PI
l = 2 * PI * r
print(s, l) | 1 | 635,357,173,222 | null | 46 | 46 |
while True:
try:
m,f,r = map(int,raw_input().split())
if all(k == -1 for k in [m,f,r]):
break
except EOFError:
break
if m == -1 or f == -1:
print 'F'
elif m + f >= 80:
print 'A'
elif 65 <= m + f <80:
print 'B'
elif 50 <= m + f < 65:
print 'C'
elif 30 <= m + f < 50:
if r >= 50:
print 'C'
else:
print 'D'
elif m + f < 30:
print 'F' | A,B = map(int,input().split())
if A < 10 and B < 10:
answer = A * B
print(answer)
else:
print('-1') | 0 | null | 79,736,927,740,128 | 57 | 286 |
n=int(input())
p=n
yakusu=[]
for i in range(1,int(n**0.5)+1):
if n%i==0:
yakusu.append(i)
if i!=n//i:
yakusu.append(n//i)
p-=1
yakusu_1=[]
for i in range(1,int(p**0.5)+1):
if p%i==0:
yakusu_1.append(i)
if i!=p//i:
yakusu_1.append(p//i)
ans=len(yakusu_1)-1
for x in yakusu:
r=n
if x!=1:
while r%x==0:
r//=x
if (r-1)%x==0:
ans+=1
print(ans) | while True:
n = int(input())
if n == 0:
break
s = list(map(int, input().split()))
m = sum(s) / n
b = 0
for i in range(n):
b += (s[i] - m) ** 2
ans = (b / n) ** 0.5
print(ans)
| 0 | null | 20,662,743,106,852 | 183 | 31 |
#!usr/bin/env python3
import sys
def string_to_list_spliter():
h, w = [int(i) for i in sys.stdin.readline().split()]
return h, w
def generate_ractangle(h, w):
rect = ''
for i in range(h):
for j in range(w):
rect += '#'
rect += '\n'
return rect
def main():
while True:
h, w = string_to_list_spliter()
if h == 0 and w == 0:
break
print(generate_ractangle(h, w))
if __name__ == '__main__':
main() | import copy
n = int(input())
a = list(map(int, input().split()))
k = 1 + n%2
INF = 10**18
dp = [[-INF]*4 for i in range(n+5)]
dp[0][0] = 0
for i in range(n):
for j in range(k+1):
dp[i+1][j+1] = max(dp[i+1][j+1], dp[i][j])
now = copy.deepcopy(dp[i][j])
if (i+j) % 2 == 0:
now += a[i]
dp[i+1][j] = max(dp[i+1][j], now)
print(dp[n][k])
| 0 | null | 19,219,186,549,832 | 49 | 177 |
# Merge Sort
N = int(input())
lst = list(map(int, input().split()))
INF = 10**9 + 1
cnt = 0
def merge(A, left, mid, right):
global cnt
n1 = mid - left
n2 = right - mid
L = A[left:mid]
L.append(INF) # 番兵
R = A[mid:right]
R.append(INF) # 番兵
i, j = 0, 0
for k in range(left, right):
cnt += 1
if (L[i] <= R[j]):
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
def merge_sort(A, left, right):
if (right - left > 1):
mid = (left + right) // 2
merge_sort(A, left, mid)
merge_sort(A, mid, right)
merge(A, left, mid, right)
merge_sort(lst, 0, len(lst))
print(*lst)
print(cnt)
| k = int(input())
start = 7 % k
ans = start
con = 1
if k % 2 == 0 or k % 5 == 0:
print("-1")
exit()
while True:
if ans == 0:
print(con)
break
else:
con += 1
ans = ans * 10 + 7
ans = ans % k
if ans == start:
print("-1")
break
| 0 | null | 3,115,560,660,662 | 26 | 97 |
A,B,K = map(int,input().split())
a = A-K
if a < 0:
A = 0
B = max(0, B+a)
print(max(0,a), B) | a,b,k=map(int,input().split())
c=max(0,a-k)
d=min(b,b-(k-a))
if d<0:
print(c,"0")
else:
print(c,d) | 1 | 104,015,786,468,182 | null | 249 | 249 |
#!/usr/bin/env python3
import sys
from collections import Counter
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
N, M, K = map(int, readline().split())
def graph_input(N, M):
G = [[] for _ in range(N+1)]
for _ in range(M):
a, b = map(int, readline().split())
G[a-1].append(b-1)
G[b-1].append(a-1)
return G
friend = graph_input(N, M)
block = graph_input(N, K)
seen = [0] * N
def dfs(x, group):
# DFS で頂点 x がどの group に属するかを記録していく
# 後に、各 group に対して、seen[x] = group となるがいくつあるか数えれば連結成分数もわかる
seen[x] = group
for y in friend[x]:
if seen[y]:
continue
else:
seen[y] = group
dfs(y, group)
group = 1
for x in range(N):
if seen[x] == 0:
dfs(x, group)
group += 1
counter = Counter(seen) # リストの値の出現回数を Counter で数えることで各連結成分数を得ている
res = []
for x in range(N):
# x 自身を連結成分数から除く-1 さらに friend[x] を除く
cand_n = counter[seen[x]] - len(friend[x]) - 1
# block[x]と xの連結成分の共通部分の抜くのが難しい
for a in block[x]:
if seen[a] == seen[x]:
cand_n -= 1
res.append(cand_n)
print(" ".join(map(str, res)))
if __name__ == '__main__':
print()
| n = int(input())
pr = {}
for i in range(n):
s = input()
if pr != s:
pr[s] = True
print(len(pr))
| 0 | null | 45,841,433,499,820 | 209 | 165 |
#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, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect
import heapq
#
#
#
# pythonで無理なときは、pypyでやると正解するかも!!
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
INF = float('inf')
from sys import stdin
readline = stdin.readline
def readInts():
return list(map(int,readline().split()))
def readTuples():
return tuple(map(int,readline().split()))
def I():
return int(readline())
n = I()
s = input()
C = Counter(s)
w,r = 0,0
for k,v in C.items():
if k == 'W':
w += v
else:
r += v
p = 'R' * r + 'W' * w
ans = 0
for i in range(n):
if p[i] == s[i]:
pass
else:
ans += 1
print(ans//2)
| N = int(input())
edge = [[] for _ in range(N+1)]
d = [0] * (N+1)
f = [0] * (N+1)
for i in range(N):
t = list(map(int, input().split()))
for j in range(t[1]):
edge[t[0]].append(t[j+2])
#print(1)
def dfs(v, t):
if d[v] == 0:
d[v] = t
t += 1
else:
return t
for nv in edge[v]:
t = dfs(nv, t)
if f[v] == 0:
f[v] = t
t += 1
return t
t = 1
for i in range(1,1+N):
if d[i] == 0:
t = dfs(i, t)
for i in range(1,1+N):
print(i, d[i], f[i])
| 0 | null | 3,158,778,585,480 | 98 | 8 |
i=0
while True:
i+=1
a=input()
if a==0:
break
else:
print("Case "+str(i)+": "+str(a)) | S = input()
youbi = ['SAT', 'FRI', 'THU', 'WED', 'TUE', 'MON', 'SUN']
print(youbi.index(S) + 1) | 0 | null | 66,537,953,130,308 | 42 | 270 |
import sys
sys.setrecursionlimit(10 ** 6)
# input = sys.stdin.readline ####
int1 = lambda x: 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)]
INF = float('inf')
def solve():
s, w = MI()
if w >= s:
print('unsafe')
else:
print('safe')
if __name__ == '__main__':
solve()
| # bit全探索 典型といえば典型(問題文の意味がよくわからんので読解力コンテスト)
n = int(input())
syogen = []
for i in range(n):
syogen.append([])
for _ in range(int(input())):
syogen[i].append(list(map(int, input().split())))
ans = 0
for bit in range(1 << n):
p = ["不親切"] * n
ng = False
# bitの立っているのを正直者と仮定
for i in range(n):
if bit >> i & 1 == 1:
# 上位bit = 小さいインデックス、になる(ように実装してしまった わかりづらい
p[n - i - 1] = "正直者"
for i in range(n):
if p[i] == "不親切":
# まあ不親切な人間のことなんて聞かなくていい
continue
for s in syogen[i]:
if p[s[0] - 1] == "正直者" and s[1] == 1:
# 証言と一致する
continue
elif p[s[0] - 1] == "不親切" and s[1] == 0:
# 証言と一致する
continue
else:
# 証言と一致しない
ng = True
break
if not ng:
ans = max(ans, p.count("正直者"))
print(ans)
| 0 | null | 75,343,634,315,388 | 163 | 262 |
n=int(input())
a=list(map(int,input().split()))
q=int(input())
m=list(map(int,input().split()))
l=[]
for i in range(2**n):
sub=0
for j in range(n):
if (i>>j)&1==1:
sub+=a[j]
l.append(sub)
for i in m:
if i in l:
print("yes")
else:
print("no")
| N,K = map(int,input().split())
count =0
for i in range(K,N+2):
if i ==N+1:
count+=1
else:
a = (i-1)
a = a/2
a = a*i
b = (N+N-(i-1))/2
b = b*i
count +=b-a+1
#print(i,count,a,b)
print(int(count%(10**9+7))) | 0 | null | 16,496,329,653,288 | 25 | 170 |
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT() : return int(input())
def MAP() : return map(int,input().split())
def LIST() : return list(MAP())
n = INT()
a = LIST()
ans = 1
r = 0
g = 0
b = 0
for x in a:
ans = ans * ( (r == x) + (g == x) + (b == x) ) % (10**9+7)
if r == x:
r += 1
elif g == x:
g += 1
else:
b += 1
print(ans) | A,B = input().split()
A = int(A)
x = ""
for i in range(len(B)):
if B[i]!=".":
x += B[i]
B = int(x)
C = A*B
C = C//100
print(C) | 0 | null | 73,451,458,758,368 | 268 | 135 |
def main():
x, k, d = map(int, input().split())
x = abs(x)
if k % 2 == 1:
x = abs(x-d)
k -= 1
if x > d*k:
print(x-d*k)
else:
print(min(x % (2*d), abs(x % (2*d)-2*d)))
main()
| x,k,d=map(int,input().split())
x=abs(x)
if x%d==0:
minNear = x%d + d
minFar = x%d
minTransitionToNear = (x-minNear)/d
#print(minNear)
#print(minFar)
#print(minTransitionToNear)
else:
minNear = x%d
minFar = x%d - d
minTransitionToNear = (x-minNear)/d
#print(minNear)
#print(minFar)
#print(minTransitionToNear)
if k<minTransitionToNear:
print(x-k*d)
else:
if (k-minTransitionToNear)%2==0:
print(abs(minNear))
else:
print(abs(minFar)) | 1 | 5,208,299,801,472 | null | 92 | 92 |
N=int(input())
List = list(map(int, input().split()))
Row = int(input())
QList = []
for i in range (Row):
QList.append(list(map(int, input().split())))
dictA ={}
res = 0
for i in range (N):
dictA.setdefault(List[i],0)
dictA[List[i]] += 1
res += List[i]
num = 0
for i in range(Row):
if QList[i][0] not in dictA:
pass
else:
num = dictA[QList[i][0]]
res = res - dictA[QList[i][0]] * QList[i][0]
dictA[QList[i][0]] = 0
dictA.setdefault(QList[i][1],0)
dictA[QList[i][1]] += num
res += QList[i][1] * num
print(res) | n = int(input())
al = list(map(int, input().split()))
num_cnt = {}
c_sum = 0
for a in al:
num_cnt.setdefault(a,0)
num_cnt[a] += 1
c_sum += a
ans = []
q = int(input())
for _ in range(q):
b,c = map(int, input().split())
num_cnt.setdefault(b,0)
num_cnt.setdefault(c,0)
diff = num_cnt[b]*c - num_cnt[b]*b
num_cnt[c] += num_cnt[b]
num_cnt[b] = 0
c_sum += diff
ans.append(c_sum)
for a in ans:
print(a) | 1 | 12,179,039,731,650 | null | 122 | 122 |
n = int(input())
arr = list(map(int,input().split()))
total = 0
for i in range(n):
total ^= arr[i]
arr = [i^total for i in arr]
print(*arr) | N = int(input())
A = list(map(int,input().split()))
xor = 0
for i in range(N):
xor ^= A[i]
anslis = []
for i in range(N):
answer = xor^A[i]
anslis.append(answer)
print(' '.join(map(str,anslis))) | 1 | 12,572,088,946,102 | null | 123 | 123 |
n = int(input())
s = [input() for _ in range(n)]
l = 0
r = 0
m = []
def fin():
print("No")
exit()
for word in s:
stack = []
for e in word:
if stack and stack[-1] == "(" and e == ")":
stack.pop()
else:
stack.append(e)
if stack:
if stack[0] == ")" and stack[-1] == "(":
m.append(stack)
elif stack[0] == ")":
r += len(stack)
else:
l += len(stack)
ml = []
mm = 0
mr = []
for word in m:
ll = word.index("(")
rr = len(word) - ll
if ll > rr:
mr.append([ll, rr])
elif ll < rr:
ml.append([ll, rr])
else:
mm = max(mm, ll)
ml.sort()
for ll, rr in ml:
l -= ll
if l < 0:
fin()
l += rr
mr.sort(key=lambda x: x[1])
for ll, rr in mr:
r -= rr
if r < 0:
fin()
r += ll
if mm <= l or mm <= r:
if l == r:
print("Yes")
exit()
fin()
| import sys
def input(): return sys.stdin.readline().strip()
mod = 998244353
def main():
"""
各トークンを(最下点、最終的な高さ)に分けるのはできた。
そしてそれらを最下点位置が浅い順に並べるのも悪くはなかった、増加パートに関しては。
減少パートは減少度合が小さい順に付け加えたとしても高さが負に潜り込むケースがある。
(例)高さ3から下るとして、(-1, -1), (-2, 0), (-3, -2)が各トークンとすると
この順にくっつけると(-3, -2)を加えるときにアウトだが、
(-2, 0), (-3, -2), (-1, -1)の順だったらOK
なので下る場合には増加パートとは違う方法でくっつけないといけない。
結論としては、これは左右反転させれば増加していることになるので、右からくっつけるようにすればいい。
"""
N = int(input())
S_up = []
S_down = []
for _ in range(N):
s = input()
max_depth = 0
height = 0
for c in s:
if c == '(':
height += 1
else:
height -= 1
max_depth = min(max_depth, height)
if height > 0: S_up.append((max_depth, height - max_depth))
else: S_down.append((-(height - max_depth), -max_depth))
S_up.sort(key=lambda x: (x[0], x[1]))
S_down.sort(key=lambda x: (x[0], x[1]))
height_left = 0
while S_up:
d, h = S_up.pop()
#print("({}, {})".format(d, h))
if height_left + d < 0:
print("No")
return
height_left += d+h
height_right = 0
while S_down:
d, h = S_down.pop()
#print("({}, {})".format(d, h))
if height_right + d < 0:
print("No")
return
height_right += d+h
if height_left != height_right: print("No")
else: print("Yes")
if __name__ == "__main__":
main()
| 1 | 23,845,351,754,940 | null | 152 | 152 |
N = int(input())
z = []
zz = []
for _ in range(N):
x, y = map(int, input().split())
zz.append(x-y)
z.append(x+y)
z.sort()
zz.sort()
ans = z[-1]-z[0]
ans = max(ans, zz[-1]-zz[0])
print(ans) | import sys
readline = sys.stdin.readline
N = int(readline())
A = []
B = []
for _ in range(N):
x, y = map(int, readline().split())
A.append(x-y)
B.append(x+y)
print(max(max(A) - min(A), max(B) - min(B))) | 1 | 3,410,973,830,430 | null | 80 | 80 |
k = int(input())
ans = 0
ai = 0
for i in range(k+2):
ai = ((ai * 10) + 7) % k
if ai == 0:
ans = i + 1
print(ans)
exit()
ans = -1
print(ans)
| k = int(input())
mod = 7 % k
counter = 1
memo = 1
mod_map = set()
mod_map.add(mod)
while mod != 0:
mod = ((mod * 10) % k + 7) % k
if mod not in mod_map:
mod_map.add(mod)
else:
counter = -1
break
counter += 1
if mod == 0:
break
print(counter)
| 1 | 6,137,154,774,892 | null | 97 | 97 |
print('Yes' if ['A','B'] == sorted(set(input())) else 'No') | n=int(input())
for m in range(1,n+1):
if int(m*1.08)==n:
print(m)
break
else:print(":(")
| 0 | null | 90,577,203,384,448 | 201 | 265 |
def readinput():
n=input()
return n
def main(n):
if n[0]=='7' or n[1]=='7' or n[2]=='7':
return 'Yes'
else:
return 'No'
if __name__=='__main__':
n=readinput()
ans=main(n)
print(ans)
| n = int(input())
a = list(map(int,input().split()))
flag = 1
i = 0
count = 0
while flag:
flag = 0
for j in range(n-1,i,-1):
if a[j] < a[j-1]:
a[j],a[j-1] = a[j-1],a[j]
count += 1
flag = 1
i += 1
for w in range(n):
if w != n-1:
print(a[w],end=" ")
else:
print(a[w])
print(count) | 0 | null | 17,127,158,102,560 | 172 | 14 |
n = int(input())
A = list(map(int, input().split()))
q = int(input())
m = list(map(int, input().split()))
"""
def exhaustive_search(m, i):
if i == n:
return 0
if m < 0:
return 0
if m == A[i]:
return 1
return max(exhaustive_search(m, i + 1), exhaustive_search(m - A[i], i + 1))
"""
def dp_search(m):
dp = [[1] + [0] * m for _ in range(n + 1)] # dp[i][j] i番目まででjを作れるか
for i in range(1, n+1):
for j in range(1, m+1):
if j >= A[i-1]:
dp[i][j] = max(dp[i-1][j], dp[i-1][j - A[i-1]])
else:
dp[i][j] = dp[i-1][j]
return dp[n][m]
for mi in m:
if dp_search(mi):
print("yes")
else:
print("no")
| n = int(input())
a = list(map(int,input().split()))
m = int(input())
q = list(map(int,input().split()))
cand = []
for i in range(2**n):
tmp = 0
for j in range(n):
if(i>>j)&1:
tmp += a[j]
if tmp not in cand:
cand.append(tmp)
for i in q:
print('yes' if i in cand else 'no')
| 1 | 101,931,765,670 | null | 25 | 25 |
def gcd(x, y):
if y == 0:
return x
else:
return gcd(y, x%y)
def lcm(x,y):
return x/gcd(x, y)*y
while True:
try:
x, y = map(int, raw_input().split())
except EOFError:
break
print "%d %d" % (gcd(x, y), lcm(x, y)) | import sys
def gcd(a,b):
if b != 0:
return gcd(b,a%b)
else:
return a
def lcm(a,b,g):
return b / g * a
for s in sys.stdin:
ls = map(int,s.split(' '))
print "%d %d" % (gcd(ls[0],ls[1]),lcm(ls[0],ls[1],gcd(ls[0],ls[1]))) | 1 | 632,537,360 | null | 5 | 5 |
n_max, m_max, l_max = (int(x) for x in input().split())
a = []
b = []
c = []
for n in range(n_max):
a.append([int(x) for x in input().split()])
for m in range(m_max):
b.append([int(x) for x in input().split()])
for n in range(n_max):
c.append( [sum(a[n][m] * b[m][l] for m in range(m_max)) for l in range(l_max)])
for n in range(n_max):
print(" ".join(str(c[n][l]) for l in range(l_max))) | N, K, S = map(int, input().split())
ans = [S] * K
if S != 10**9:
for i in range(N-K):
ans.append(S+1)
else:
for j in range(N-K):
ans.append(1)
print(" ".join([str(x) for x in ans])) | 0 | null | 46,413,473,038,488 | 60 | 238 |
taro = 0
hanako = 0
n = int(input())
for _ in range(n):
taro_card, hanako_card = input().split()
if taro_card > hanako_card:
taro += 3
elif taro_card < hanako_card:
hanako += 3
else:
taro += 1
hanako += 1
print(taro, hanako) | # -*- coding: utf-8 -*-
n = input()
x = y = 0
for _ in xrange(n):
a, b = raw_input().split()
if a==b:
x += 1
y += 1
elif a>b:
x += 3
else:
y += 3
print x, y | 1 | 1,984,753,380,028 | null | 67 | 67 |
x = list(map(int, input().split())) # n個の数字がリストに格納される
for i in range(5):
if x[i] is 0:
print(i+1) | #from random import randint
import numpy as np
def f(h,w,m,ins):
yp = np.zeros(h,dtype=np.int32)
xp = np.zeros(w,dtype=np.int32)
s = set()
for hi,wi in ins:
s.add((hi-1,wi-1))
yp[hi-1] += 1
xp[wi-1] += 1
ypm = yp.max()
xpm = xp.max()
yps = np.where(yp == ypm)[0].tolist()
xps = np.where(xp == xpm)[0].tolist()
ans = yp[yps[0]]+xp[xps[0]]
for ypsi in yps:
for xpsi in xps:
if not (ypsi,xpsi) in s:
return ans
return ans-1
if __name__ == "__main__":
if False:
while True:
h,w = randint(1,10**5*3),randint(10**5,10**5*3)
m = randint(1,min(h*w,10**5*3))
ins = [(randint(1,h),randint(1,w)) for i in range(m)]
ans = f(h,w,m,ins)
print(ans)
else:
h,w,m = map(int,input().split())
ans = f(h,w,m,[list(map(int,input().split())) for i in range(m)])
print(ans)
| 0 | null | 9,179,376,725,468 | 126 | 89 |
import itertools
n = int(input())
a = list(map(int, input().split()))
q = int(input())
M = list(map(int, input().split()))
able = [0] * (max(n * max(a) + 1, 2001))
for item in itertools.product([0, 1], repeat=n):
total = sum([i * j for i, j in zip(a, item)])
able[total] = 1
for m in M:
print('yes' if able[m] else 'no')
| from itertools import repeat
from itertools import combinations
def rec(s, i, total, m):
if total == m:
return 1
if len(s) == i or total > m:
return 0
return rec(s, i + 1, total, m) + rec(s, i + 1, total + s[i], m)
def makeCache(s):
cache = {}
for i in range(len(s)):
comb = list(combinations(s, i))
for c in comb:
cache[sum(c)] = 1
return cache
def loop(s, m):
for i in range(len(s)):
comb = list(combinations(s, i))
for c in comb:
if sum(c) == m:
return 1
return 0
if __name__ == "__main__":
n = int(input())
a = [int (x) for x in input().split()]
q = int(input())
m = [int (x) for x in input().split()]
s = makeCache(a)
for i in m:
#print("yes") if rec(a, 0, 0, i) > 0 else print("no")
#print("yes") if loop(a, i) > 0 else print("no")
print("yes") if i in s else print("no")
| 1 | 99,564,591,098 | null | 25 | 25 |
# -*- coding: utf-8 -*-
from collections import deque
################ DANGER ################
test = ""
#test = \
"""
9 6 1
1 2
2 3
3 4
4 5
5 6
4 7
7 8
8 9
ans 5
"""
"""
5 4 1
1 2
2 3
3 4
3 5
ans 2
"""
"""
5 4 5
1 2
1 3
1 4
1 5
ans 1
"""
########################################
test = list(reversed(test.strip().splitlines()))
if test:
def input2():
return test.pop()
else:
def input2():
return input()
########################################
n, taka, aoki = map(int, input2().split())
edges = [0] * (n-1)
for i in range(n-1):
edges[i] = tuple(map(int, input2().split()))
adjacencyL = [[] for i in range(n+1)]
for edge in edges:
adjacencyL[edge[0]].append(edge[1])
adjacencyL[edge[1]].append(edge[0])
################ DANGER ################
#print("taka", taka, "aoki", aoki)
#import matplotlib.pyplot as plt
#import networkx as nx
#G = nx.DiGraph()
#G.add_edges_from(edges)
#nx.draw_networkx(G)
#plt.show()
########################################
takaL = [None] * (n+1)
aokiL = [None] * (n+1)
takaL[taka] = 0
aokiL[aoki] = 0
takaQ = deque([taka])
aokiQ = deque([aoki])
for L, Q in ((takaL, takaQ), (aokiL, aokiQ)):
while Q:
popN = Q.popleft()
for a in adjacencyL[popN]:
if L[a] == None:
Q.append(a)
L[a] = L[popN] + 1
#print(L)
print(max(aokiL[i] for i in range(1, n+1) if takaL[i] < aokiL[i]) - 1)
| from collections import defaultdict, deque
N, u, v = map(int, input().split())
G = defaultdict(lambda: [])
for _ in range(N-1):
a,b=map(int,input().split())
G[a].append(b)
G[b].append(a)
if G[u] == [v]:
print(0)
exit()
def bfs(v):
seen = [0]*(N+1)
queue = deque()
dist = [-1]*(N+1)
dist[v] = 0
seen[v] = 1
queue.append(v)
while queue:
q = queue.popleft()
for nx in G[q]:
if seen[nx]:
continue
dist[nx] = dist[q] + 1
seen[nx] = 1
queue.append(nx)
return dist
d_u = bfs(u)
d_v = bfs(v)
ans = 0
for node in range(1, N+1):
if d_u[node] < d_v[node] and len(G[node]) == 1:
ans = max(ans, d_v[node]-1)
print(ans) | 1 | 117,487,850,196,820 | null | 259 | 259 |
import math
a, b, c = map(float, input().split())
r = math.radians(c)
S = (a * b * math.sin(r)) / 2
print(S)
d = (a**2 + b**2 - 2 * a * b * math.cos(r))
d = math.sqrt(d)
L = a + b + d
print(L)
h = 2 * S / a
print(h) | import math
a,b,C=map(float,input().split())
θ=math.radians(C)
h=b*math.sin(θ)
S=(a*h)/2
c=math.sqrt(a**2+b**2-2*a*b*math.cos(θ))
L=a+b+c
print(S,L,h,sep="\n")
| 1 | 175,769,133,228 | null | 30 | 30 |
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) | import collections
n = int(raw_input())
adj = collections.defaultdict(list)
edges = []
for _ in range(n - 1):
u,v = map(int, raw_input().split(' '))
edges.append((u,v))
adj[u].append(v)
adj[v].append(u)
root = 1
q = collections.deque([root])
h = {}
while(q):
u = q.popleft()
c = 1
used = set([h[tuple(sorted([u,v]))] for v in adj[u] if tuple(sorted([u,v])) in h])
for v in adj[u]:
t = tuple(sorted([u,v]))
if t not in h:
while(c in used): c+=1
h[t] = c
c+=1
q.append(v)
print max(h.values())
for u,v in edges:
print h[(u,v)] | 0 | null | 69,560,732,707,818 | 83 | 272 |
from collections import deque
D1 = {i:chr(i+96) for i in range(1,27)}
D2 = {val:key for key,val in D1.items()}
N = int(input())
heap = deque([(D1[1],1)])
A = []
while heap:
a,n = heap.popleft()
if n<N:
imax = 0
for i in range(len(a)):
imax = max(imax,D2[a[i]])
for i in range(1,min(imax+1,26)+1):
heap.append((a+D1[i],n+1))
if n==N:
A.append(a)
A = sorted(list(set(A)))
for i in range(len(A)):
print(A[i]) | import sys
sys.setrecursionlimit(10**7)
readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))
n = readint()
ans = [[[0],[0]]]
i = 0
while len(ans[i][0])<n:
a = ans[i]
for x in a[1]:
ans.append([a[0]+[x],a[1]])
x = a[1][-1]+1
ans.append([a[0]+[x],a[1] + [x]])
i+=1
a_ = ord('a')
for i in range(len(ans)):
a = ans[i][0]
if len(a)<n:
continue
for x in a[:-1]:
print(chr(x+a_),end='')
print(chr(a[-1]+a_))
| 1 | 52,409,533,614,790 | null | 198 | 198 |
N = int(input())
if N % 2 == 0:
result = N//2 - 1
else:
result = N//2
print(result) | a = [int(i) for i in input().split()]
if(max(a) > 9):
print("-1")
else:
print(a[0] * a[1]) | 0 | null | 155,632,070,218,392 | 283 | 286 |
def main():
N = int(input())
G = [[] for _ in range(N)]
edge = [-1] * (N-1)
for i in range(N-1):
a, b = (int(i)-1 for i in input().split())
G[a].append(b*N + i)
G[b].append(a*N + i)
max_deg = max(len(G[i]) for i in range(N))
from collections import deque
def bfs(s):
que = deque([])
par = [-1]*N
que.append(s)
while que:
pos = que.popleft()
c = -1
k = 1
for vi in G[pos]:
v, i = divmod(vi, N)
if par[pos] == v:
c = edge[i]
for vi in G[pos]:
v, i = divmod(vi, N)
if par[pos] == v:
continue
if k == c:
k += 1
par[v] = pos
edge[i] = k
k += 1
que.append(v)
bfs(0)
print(max_deg)
for i in range(N-1):
print(edge[i])
if __name__ == '__main__':
main()
| st = input().split()
S = st[0]
T = st[1]
ab = input().split()
A = int(ab[0])
B = int(ab[1])
U = input()
new_a = A - 1 if S == U else A
new_b = B-1 if T == U else B
print("{} {}".format(new_a, new_b))
| 0 | null | 103,776,576,775,452 | 272 | 220 |
N,K = map(int, input().split())
tmp=N
count=0
while tmp!=0:
tmp = tmp//K
count += 1
print(count) | N, K = map(int, input().split())
ans = 1
while N >= K:
N = N // K
ans += 1
print(ans) | 1 | 64,439,372,653,822 | null | 212 | 212 |
import numpy;x=int(input());print(numpy.lcm(360,x)//x) | Row = int(input())
List = []
for i in range (Row):
List.append(input())
s_l = set(List)
print(len(s_l)) | 0 | null | 21,779,816,496,998 | 125 | 165 |
from collections import deque
def bfs(start):
Q = deque()
Q.append(start)
dist[start] = 0
while Q:
v = Q.popleft()
for nv in G[v]:
if dist[nv] != -1:
continue
# print(Q)
dist[nv] = dist[v] + 1
Q.append(nv)
N = int(input())
G = [[]] + [list(map(int, input().split())) for _ in range(N)]
for a in range(1, N + 1):
b = G[a][2:]
G[a] = b
# print(G)
dist = [-1 for _ in range(N + 1)]
start = 1
bfs(start)
# print(dist[1:])
for i in range(1, N + 1):
print(i, dist[i])
| from collections import deque
n=int(input())
E=[0]*n
for _ in range(n):
u,k,*V=map(int,input().split())
E[u-1]=V
d=[-1]*n
d[0]=0
todo=deque([1])
while todo:
now=todo.popleft()
for v in E[now-1]:
if d[v-1]==-1:
todo.append(v)
d[v-1]=d[now-1]+1
for i in range(n):
print(i+1,d[i])
| 1 | 4,231,165,564 | null | 9 | 9 |
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7
def debug(*x):
print(*x, file=sys.stderr)
def precompute():
maxAS = 1000000
eratree = [0] * (maxAS + 10)
for p in range(2, maxAS + 1):
if eratree[p]:
continue
# p is prime
eratree[p] = p
x = p * p
while x <= maxAS:
if not eratree[x]:
eratree[x] = p
x += p
import pickle
pickle.dump(eratree, open("eratree.pickle", "wb"))
def solve(N, AS):
import pickle
eratree = pickle.load(open("eratree.pickle", "rb"))
num_division = 0
from collections import defaultdict
count = defaultdict(int)
for a in AS:
factors = []
while a > 1:
d = eratree[a]
factors.append(d)
a //= d
num_division += 1
# debug(": ", factors)
for f in set(factors):
count[f] += 1
# debug(": num_division", num_division)
if any(x == N for x in count.values()):
return "not coprime"
if any(x >= 2 for x in count.values()):
return "setwise coprime"
return "pairwise coprime"
def main():
# parse input
N = int(input())
AS = list(map(int, input().split()))
print(solve(N, AS))
# tests
T1 = """
3
3 4 5
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
pairwise coprime
"""
T2 = """
3
6 10 15
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
setwise coprime
"""
T3 = """
3
6 10 16
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
not coprime
"""
T4 = """
3
100000 100001 100003
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
pairwise coprime
"""
def _test():
import doctest
doctest.testmod()
g = globals()
for k in sorted(g):
if k.startswith("TEST_"):
doctest.run_docstring_examples(g[k], g, name=k)
def as_input(s):
"use in test, use given string as input file"
import io
f = io.StringIO(s.strip())
g = globals()
g["input"] = lambda: bytes(f.readline(), "ascii")
g["read"] = lambda: bytes(f.read(), "ascii")
input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
if sys.argv[-1] == "-t":
print("testing")
_test()
sys.exit()
if sys.argv[-1] == 'ONLINE_JUDGE':
precompute()
elif sys.argv[-1] != "DONTCALL":
import subprocess
subprocess.call("pypy3 Main.py DONTCALL", shell=True, stdin=sys.stdin, stdout=sys.stdout)
else:
main()
| n=int(input())
A=[int(x) for x in input().split()]
u=10**6+1
C=[0]*u
D=[0]*2+[1]*(u-2)
def gcd(a,b):
while a%b:
a,b=b,a%b
return b
n=4
while n<u:
D[n]=0
n+=2
i=3
while i*i<u:
if D[i]:
n=i*2
while n<u:
D[n]=0
n+=i
i+=2
for a in A:
C[a]+=1
for i in [x for x in range(2,u) if D[x]==1]:
if sum(C[i::i])>1:
break
else:
print('pairwise coprime')
exit()
c=A[0]
for a in A:
c=gcd(c,a)
if c==1:
break
else:
print('not coprime')
exit()
print('setwise coprime')
| 1 | 4,055,321,355,162 | null | 85 | 85 |
import math
x1,y1,x2,y2 = (float(x) for x in input().split())
print(round(math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2), 8))
| import math
l=input().split()
x1=float(l[0])
y1=float(l[1])
x2=float(l[2])
y2=float(l[3])
A=math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
print(A)
| 1 | 150,626,749,478 | null | 29 | 29 |
x, y = map(int, input().split())
for a in range(x+1):
for b in range(x+1-a):
if a + b == x and 2*a + 4*b == y:
print("Yes")
exit()
print("No") | x, y = map(int,input().split())
leg = 2*x
if y==leg:
print('Yes')
exit()
for i in range(1,x+1):
leg += 2
if y==leg:
print('Yes')
exit()
print('No') | 1 | 13,755,941,359,040 | null | 127 | 127 |
n,m=map(int, input().split())
roads=[]
for _ in range(m):
a,b=map(int, input().split())
roads.append([a,b])
group=[i for i in range(n)]
group2=[]
while group2!=group:
group2=list(group)
for road in roads:
if group[road[1]-1]>group[road[0]-1]:
group[road[1]-1]=group[road[0]-1]
else:
group[road[0]-1]=group[road[1]-1]
counter=1
group.sort()
for i in range(n-1):
if group[i]!=group[i+1]:
counter+=1
print(counter-1)
| import sys
input = sys.stdin.readline
n,m=map(int,input().split())
d={i+1:[] for i in range(n)}
for i in range(m):
x,y=map(int,input().split())
d[x].append(y)
d[y].append(x)
visit=set()
ans= 0
for i in range(1,n+1):
if i not in visit:
ans+=1
stack = [i]
while stack:
c=stack.pop()
visit.add(c)
for i in d[c]:
if i not in visit:
stack.append(i)
print(ans-1) | 1 | 2,268,274,252,340 | null | 70 | 70 |
x, y, z = map(int, input().split())
createNum = 0
createTime = 0
loopCnt = x//y
createNum = y*loopCnt
createTime = z*loopCnt
remain = x%y
if remain != 0:
createTime += z
print(createTime) | (r, c) = [int(i) for i in input().split()]
table = [[0 for j in range(c + 1)]for i in range(r + 1)]
for i in range(r):
tmp = [int(x) for x in input().split()]
for j in range(c + 1):
if not j == c:
table[i][j] = tmp[j]
table[i][c] += table[i][j]
table[r][j] += table[i][j]
for i in range(r + 1):
for j in range(c + 1):
if j == c:
print(table[i][j], end='')
else:
print(table[i][j], '', end='')
print() | 0 | null | 2,800,615,831,290 | 86 | 59 |
N=int(input())
Taro=0
Hanako=0
for i in range(N):
T,H=map(str,input().split())
if T<H:
Hanako+=3
elif H<T:
Taro+=3
else:
Hanako+=1
Taro+=1
print(Taro,Hanako)
| turn=int(input())
duel=[input().split(" ")for i in range(turn)]
point=[0,0]
for i in duel:
if i[0]==i[1]:
point[0],point[1]=point[0]+1,point[1]+1
if i[0]>i[1]:
point[0]+=3
if i[0]<i[1]:
point[1]+=3
print(" ".join(map(str,point)))
| 1 | 2,015,181,971,450 | null | 67 | 67 |
n = int(raw_input())
num_list = [int(raw_input()) for i in xrange(n)]
minv = num_list[0]
maxv = -1000000000
for i in xrange(1, n):
tmp = num_list[i] - minv
maxv = tmp if tmp > maxv else maxv
minv = num_list[i] if minv > num_list[i] else minv
# print "i = %d, tmp = %d, maxv = %d, minv = %d" % (i, tmp, maxv, minv)
print maxv | n = int(input())
inf = 10 ** 10
buy = inf
ans = -inf
for i in range(n):
price = int(input())
ans = max(ans, price - buy)
buy = min(buy, price)
print(ans)
| 1 | 13,517,574,092 | null | 13 | 13 |
n = int(input())
ans = ""
for i in range(1, n + 1):
if(i % 3 == 0):
ans += " " + str(i)
continue
x = i
while(x):
if(x % 10 == 3):
ans += " " + str(i)
break
x //= 10
print(ans) | count =[[[0]*10 for j in range(3)] for k in range(4)]
n = int(input())
for x in range(n):
b,f,r,v = map(int,input().split())
# 1 <= b <=4
# 1 <= f <= 3
# 1 <= r <= 10
# 1 <= v <= 9
count[b-1][f-1][r-1] += v
for i in range(4):
if i != 0:
print("#"*20)
for j in range(3):
for k in range(10):
print(f' {count[i][j][k]}',end="")
print()
| 0 | null | 1,007,188,233,910 | 52 | 55 |
N, S = map(int, input().split())
A = list(map(int, input().split()))
mod = 998244353
dp = [[0 for j in range(S+1)] for i in range(N+1)]
dp[0][0] = 1
for i in range(N):
for j in range(S+1):
dp[i+1][j] += 2*dp[i][j]
dp[i+1][j] %= mod
if j + A[i] <= S:
dp[i+1][j+A[i]] += dp[i][j]
dp[i+1][j+A[i]] %= mod
print(dp[N][S]) | ri = [int(v) for v in input().split()]
A, B, C, D = ri
f = 1
while A > 0 and C > 0:
if f:
C -= B
else:
A -= D
f ^= 1
print("Yes" if A > C else "No")
| 0 | null | 23,738,934,846,500 | 138 | 164 |
x,y,z = map(int,input().split())
temp = x
x = y
y = temp
temp = x
x = z
z = temp
print(x,y,z) | xyz = list(map(int,input().split()))
print("{} {} {}".format(xyz[2],xyz[0],xyz[1])) | 1 | 37,959,401,593,032 | null | 178 | 178 |
# 解説放送の方針
# ダメージが消える右端をキューで管理
# 右端を超えた分は、累積ダメージから引いていく
from collections import deque
N,D,A=map(int,input().split())
XH = [tuple(map(int,input().split())) for _ in range(N)]
XH = sorted(XH)
que=deque()
cum = 0
ans = 0
for i in range(N):
x,h = XH[i]
if i == 0:
r,n = x+2*D,(h+A-1)//A
d = n*A
cum += d
que.append((r,d))
ans += n
continue
while que and que[0][0]<x:
r,d = que.popleft()
cum -= d
h -= cum
if h<0:
continue
r,n = x+2*D,(h+A-1)//A
d = n*A
cum += d
que.append((r,d))
ans += n
print(ans) | import queue
N=int(input())
M=[input().split()[2:]for _ in[0]*N]
q=queue.Queue();q.put(0)
d=[-1]*N;d[0]=0
while q.qsize()>0:
u=q.get()
for v in M[u]:
v=int(v)-1
if d[v]<0:d[v]=d[u]+1;q.put(v)
for i in range(N):print(i+1,d[i])
| 0 | null | 40,955,187,908,558 | 230 | 9 |
A,B,M=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=[]
d=[]
for i in range(M):
c.append(list(map(int,input().split())))
C=min(a)+min(b)
for i in range(0,M):
d.append(a[(c[i][0]-1)]+b[(c[i][1]-1)]-c[i][2])
D=min(d)
print(min(C,D)) | A,B,M = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
x = []
y = []
c = []
for _ in range(M):
X,Y,Z = map(int,input().split())
x.append(X)
y.append(Y)
c.append(Z)
mini = min(a) + min(b)
for i in range(M):
rei = a[x[i]-1]
den = b[y[i]-1]
coop = c[i]
if rei + den - coop < mini:
mini = rei + den - coop
print(mini)
| 1 | 53,870,515,223,088 | null | 200 | 200 |
import bisect
import math
N,D,A=map(int,input().split())
tmp=[list(map(int,input().split())) for i in range(N)]
tmp.sort(key=lambda x:x[0])
monster=[];X=[]
for i in range(N):
monster.append(tmp[i][1]);X.append(tmp[i][0])
minus=[0]*(N+1)
ans=0
damage=0
for i in range(N):
damage-=minus[i]
monster[i]=max(0,monster[i]-damage)
if(monster[i]==0):
continue
cnt=math.ceil(monster[i]/A)
monster[i]=0
ans+=cnt
b=bisect.bisect_left(X,X[i]+2*D+1)
minus[b]+=cnt*A
damage+=A*cnt
print(ans) | import sys
from collections import defaultdict
from queue import deque
readline = sys.stdin.buffer.readline
def geta(fn=lambda s: s.decode()):
return map(fn, readline().split())
def gete(fn=lambda s: s.decode()):
return fn(readline().rstrip())
sys.setrecursionlimit(10**5)
def main():
n, d, a = geta(int)
mon = []
ans = 0
for _ in range(n):
x, h = geta(int)
mon.append([x, (h + a - 1) // a])
mon.sort()
bom = deque()
cur = 0
for i, mi in enumerate(mon):
while len(bom) != 0 and bom[0][0] < mi[0]:
b = bom.popleft()
cur -= b[1]
if mi[1] <= cur:
continue
else:
b1 = mi[1] - cur
bom.append((mi[0] + 2 * d, b1))
cur += b1
ans += b1
print(ans)
if __name__ == "__main__":
main() | 1 | 81,970,297,020,512 | null | 230 | 230 |
import itertools
n = int(input())
L = list(map(int, input().split()))
comb = itertools.combinations(L, 3)
ans = 0
for i in comb:
i = list(i)
i.sort()
if i[0] + i[1] > i[2] and (i[0] != i[1] and i[1] != i[2] and i[2] != i[0]):
ans += 1
print(ans) | from itertools import combinations
N = int(input())
L = list(map(int, input().split()))
ans = 0
for a, b, c in combinations(L, 3):
if a == b or b ==c or a == c:
continue
if a + b + c - max(a, b, c) > max(a, b, c):
ans += 1
print(ans) | 1 | 5,013,741,123,422 | null | 91 | 91 |
W, H, x, y, r = list(map(int, input().split()))
x_right = x + r
x_left = x - r
y_up = y + r
y_down = y - r
if x_right <= W and x_left >= 0 and y_up <= H and y_down >= 0:
print("Yes")
else:
print("No")
| import sys
def solve():
a, b = map(int, input().split())
ans = gcd(a, b)
print(ans)
def gcd(a, b):
return gcd(b, a % b) if b else a
if __name__ == '__main__':
solve() | 0 | null | 235,063,509,862 | 41 | 11 |
_, D1 = map(int, input().split())
_, D2 = map(int, input().split())
print(0 if D1 < D2 else 1) | input1 = list(map(int,input().split()))
input2 = list(map(int,input().split()))
m1 = input1[0]
d1 = input1[1]
m2 = input2[0]
d2 = input2[1]
if m1 == m2:
print(0)
else:
print(1) | 1 | 124,617,708,429,172 | null | 264 | 264 |
n = input()
vals = list(map(int, input().split()))
print(min(vals), max(vals), sum(vals)) | n = int(input())
a = [int(i) for i in input().split()]
summ = 0
for i in range(n):
summ += a[i]
a.sort()
print(str(a[0])+" "+str(a[n-1])+" "+str(summ)) | 1 | 731,997,076,228 | null | 48 | 48 |
def main():
h,w,m = map(int,input().split())
X = [0]*w
Y = [0]*h
g = set([])
for _ in range(m):
a,b = map(int,input().split())
a-=1
b-=1
X[b]+=1
Y[a]+=1
g.add((a,b))
xmax = max(X)
ymax = max(Y)
xlist = []
for i,x in enumerate(X):
if x==xmax:
xlist.append(i)
ylist = []
for i,y in enumerate(Y):
if y==ymax:
ylist.append(i)
ans = xmax+ymax
flag = True
for x in xlist:
for y in ylist:
if (y,x) not in g:
flag = False
break
if not flag:
break
if flag:
ans-=1
print(ans)
main() | input_line = input().rstrip().split()
if (input_line[0]==input_line[1]):
print("Yes")
else:
print("No") | 0 | null | 43,814,235,003,802 | 89 | 231 |
cnt = int(input())
li = list(map(int,input().split()))
re_li = li[::-1]
print(' '.join(map(str,re_li)))
| import sys
from collections import defaultdict
time = 1
def dfs(g, visited, start, ans):
global time
visited[start - 1] = True
ans[start - 1][0] = time
for e in g[start]:
if not visited[e - 1]:
time += 1
dfs(g, visited, e, ans)
time += 1
ans[start - 1][1] = time
def main():
input = sys.stdin.buffer.readline
n = int(input())
g = defaultdict(list)
for i in range(n):
line = list(map(int, input().split()))
if line[1] > 0:
g[line[0]] = line[2:]
visited = [False] * n
ans = [[1, 1] for _ in range(n)]
global time
while False in visited:
start = visited.index(False) + 1
dfs(g, visited, start, ans)
time += 1
for i in range(1, n + 1):
print(i, *ans[i - 1])
if __name__ == "__main__":
main()
| 0 | null | 505,725,146,876 | 53 | 8 |
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))
n=ni()
c = [1 if _ == 'R' else 0 for _ in input()]
b = sum(c)
w=0
r=0
for i in range(n):
if c[i] == 0 and i < b:
r+=1
if c[i] == 1 and i >= b:
w+=1
print(max(w,r))
| A, B, M = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = min(a) + min(b)
for i in range(M):
x, y, c = map(int, input().split())
p = a[x-1] + b[y-1] - c
if p < ans:
ans = p
print(ans) | 0 | null | 30,167,525,027,390 | 98 | 200 |
class Dice():
def __init__(self, spots):
self.spots = [spots[i] for i in range(6)]
def roll(self, direction):
if direction == 0:
self.spots = [self.spots[i] for i in [1, 5, 2, 3, 0, 4]]
elif direction == 1:
self.spots = [self.spots[i] for i in [3, 1, 0, 5, 4, 2]]
elif direction == 2:
self.spots = [self.spots[i] for i in [4, 0, 2, 3, 5, 1]]
elif direction == 3:
self.spots = [self.spots[i] for i in [2, 1, 5, 0, 4, 3]]
first_state = list(map(int, input().split()))
q = int(input())
for _ in range(q):
my_dice = Dice(first_state)
a, b = map(int, input().split())
if b == my_dice.spots[0]:
my_dice.roll(2)
elif b == my_dice.spots[1]:
pass
elif b == my_dice.spots[2]:
my_dice.roll(3)
my_dice.roll(2)
elif b == my_dice.spots[3]:
my_dice.roll(1)
my_dice.roll(2)
elif b == my_dice.spots[4]:
my_dice.roll(2)
my_dice.roll(2)
elif b == my_dice.spots[5]:
my_dice.roll(0)
if a == my_dice.spots[0]:
pass
elif a == my_dice.spots[2]:
my_dice.roll(3)
elif a == my_dice.spots[3]:
my_dice.roll(1)
elif a == my_dice.spots[5]:
my_dice.roll(1)
my_dice.roll(1)
print(my_dice.spots[2])
| a,b=[int(i) for i in input().split()]
c=[int(i) for i in input().split()]
if(sum(c)>=a):
print('Yes')
else:
print('No') | 0 | null | 38,925,150,375,738 | 34 | 226 |
a, v = map(int, input().split())
b, w = map(int, input().split())
t = int(input())
if (v-w)*t >= abs(a-b):
print('YES')
else:
print('NO') | n = input()
xi = map(int, raw_input().split())
print ("%d %d %d") %(min(xi), max(xi), sum(xi)) | 0 | null | 7,869,212,929,270 | 131 | 48 |
def main() -> None:
n = input()
if n[-1] in ['2', '4', '5', '7', '9']:
print('hon')
elif n[-1] in ['0', '1', '6', '8']:
print('pon')
else:
print('bon')
return
if __name__ == '__main__':
main()
| x,n = map(int,input().split())
p = list(map(int,input().split()))
i = 0
ans = -1
while True:
temp1 = x - i
temp2 = x + i
if temp1 not in p:
ans = temp1
break
if temp2 not in p:
ans = temp2
break
i += 1
print(ans) | 0 | null | 16,685,966,682,112 | 142 | 128 |
from collections import deque
H, W = map(int, input().split())
maze = [input() for _ in range(H)]
v = {(1,0), (-1,0), (0,1), (0,-1)}
q = deque()
ans = 0
for i in range(H):
for j in range(W):
if maze[i][j] == '.':
#bfs
dist = [[-1 for _ in range(W)] for _ in range(H)]
dist[i][j] = 0
q.append([j, i])
while len(q) > 0:
now = q.popleft()
x, y = now[0], now[1]
d = dist[y][x]
for dx, dy in v:
nx, ny = x+dx, y+dy
if 0<=nx<W and 0<=ny<H and dist[ny][nx]==-1 and maze[ny][nx]=='.':
dist[ny][nx] = d+1
q.append([nx, ny])
ans = max(ans, d)
print(ans) | N, M = map(int, input().split())
# 行先記憶用
rooting = [[] for _ in range(N+1)]
for _ in range(M):
A, B = map(int, input().split())
rooting[A].append(B)
rooting[B].append(A)
# グループの最大人数
max_group_num = 1
# 到達判定フラグ(到達していれば1)
visited = [0 for _ in range(N+1)]
# 幅優先探索
for i in range(1, N+1):
if visited[i] == 1:
continue
visited[i] = 1
queue = [i]
group_num = 1
while not queue == []:
h = queue.pop(0)
for n in rooting[h]:
if visited[n] != 1:
queue.append(n)
group_num += 1
visited[n] = 1
max_group_num = max(max_group_num, group_num)
print(max_group_num) | 0 | null | 49,187,139,480,970 | 241 | 84 |
#!/usr/bin/env python3
import sys
import collections as cl
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def main():
N = input()
print("No" if N[0] == N[1] == N[2] else "Yes")
main()
| N = int(input())
S = input()
ans = 0
s = 0
while True:
x = S.find('ABC', s)
if x == -1:
break
else:
s = x+1
ans +=1
print(ans) | 0 | null | 76,749,857,115,020 | 201 | 245 |
n = int(input())
a0 = 1
a1 = 1
#print(a0, a1, end='')
if n == 0 or n == 1:
a2 = 1
else:
for i in range(n-1):
a2 = a0 + a1
a0 = a1
a1 = a2
#print('',a2,end='')
print(a2)
| r, c = map(int, [int(_) for _ in input().split()])
ll = []
for _ in range(r):
l = [int(n) for n in input().split()]
l.append(sum(l))
ll.append(l)
l = [sum(_) for _ in zip(*ll)]
ll.append(l)
for l in ll:
print(" ".join([str(_) for _ in l])) | 0 | null | 666,658,810,260 | 7 | 59 |
def solve(a, b):
if a % b == 0:
return b
else:
return solve(b, a % b)
while True:
try:
a, b = map(int, input().split())
lcm = solve(a,b)
print(lcm, a * b // lcm)
except:
break
| from collections import deque
n = int(input())
que = deque()
for _ in range(n):
cmd = input()
if cmd == 'deleteFirst':
try:
que.popleft()
except:
pass
elif cmd == 'deleteLast':
try:
que.pop()
except:
pass
else:
cmd, x = cmd.split()
if cmd == 'insert':
que.appendleft(x)
elif cmd == 'delete':
try:
que.remove(x)
except:
pass
print(*que)
| 0 | null | 24,949,941,568 | 5 | 20 |
nml=input().split()
n,m,l=int(nml[0]),int(nml[1]),int(nml[2])
A_=[input() for i in range(n)]
B_=[input() for i in range(m)]
A,B=[],[]
for i in range(n):
A_[i]=A_[i].split()
for i in A_:
A.append(list(map(lambda i:int(i),i)))
for i in range(m):
B_[i]=B_[i].split()
for i in B_:
B.append(list(map(lambda i:int(i),i)))
AB=[]
for i in range(n):
AB.append([])
for i in range(n):
for j in range(l):
AB[i].append(0)
for i in range(n):
for j in range(l):
for k in range(m):
AB[i][j]+=(A[i][k]*B[k][j])
for i in AB:
print(*i)
| n,m,l=map(int,input().split())
a=[list(map(int,input().split(" "))) for i in range(n)]
b=[list(map(int,input().split(" "))) for i in range(m)]
c=[[0]*l for i in range(n)]
for i in range(n):
for j in range(l):
for k in range(m):
c[i][j]=c[i][j]+a[i][k]*b[k][j]
for d in range(n):
print(c[d][0],end="")
for e in range(1,l):
print(" %d"%c[d][e],end="")
print()
| 1 | 1,422,098,986,748 | null | 60 | 60 |
x = int(input().strip())
for i in range(120):
for j in range(120):
y = i**5 + j**5
z = i**5 - j**5
if z == x:
a = i
b = j
print("{} {}".format(a, b))
exit()
if y == x:
a = i
b = -j
print("{} {}".format(a, b))
exit()
|
n = int(input())
stack = [["",0] for i in range(10**6*4)]
stack[0] = ["a",1]
pos = 0
while(pos>=0):
if(len(stack[pos][0]) == n):
print(stack[pos][0])
pos-=1
else:
nowstr = stack[pos][0]
nowlen = stack[pos][1]
#print(nowlen)
pos-=1
for ii in range(nowlen+1):
i = nowlen-ii
pos+=1
stack[pos][0] = nowstr+chr(ord('a')+i)
if(i == nowlen):
stack[pos][1] = nowlen+1
else:
stack[pos][1] = nowlen
| 0 | null | 38,952,628,488,970 | 156 | 198 |
n, k = map(int , input().split())
hn = [int(num) for num in input().split()]
hn.sort(reverse = True)
if len(hn) > k:
print(sum(hn[k:]))
else :
print(0) | import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
r = int(readline())
print(r * r)
return
if __name__ == '__main__':
main()
| 0 | null | 112,198,181,589,380 | 227 | 278 |
s = list(input())
if s.count('A') == 3 or s.count('B') == 3:
print('No')
else:
print('Yes') | s = input()
prev = s[0]
for i in range(1, 3):
if s[i] != prev:
print('Yes')
break
else:
print('No')
| 1 | 55,027,054,935,492 | null | 201 | 201 |
m1,_ = input().split()
m2,_ = input().split()
ans = 0
if m1 != m2:
ans = 1
print(ans) | import math
import numpy as np
import sys
import os
from operator import mul
sys.setrecursionlimit(10**7)
def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))
if os.getenv("LOCAL"):
inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
sys.stdin = open(inputFile, "r")
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353
N,K = LI()
s = set()
for i in range(K):
_ = I()
s.update(LI())
print(N-len(s)) | 0 | null | 74,314,656,267,168 | 264 | 154 |
# https://note.nkmk.me/python-union-find/
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())
N, M, K = map(int, input().split())
par = [-1]*N
#直接友達になっている人数とブロックしている人数をカウント
num = [0]*N
uf = UnionFind(N)
for _ in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
#友達関係をつなげる
uf.union(a, b)
#直接友達なのでカウントする
num[a] += 1
num[b] += 1
for _ in range(K):
c, d = map(int, input().split())
c -= 1
d -= 1
# print(f"c{c}, d{d}, uf.same(c, d) {uf.same(c, d)}")
#同じグループに属している場合、size()にカウントされるのでnumを増やす
if uf.same(c, d):
num[c] += 1
num[d] += 1
# print(num)
for i in range(N):
#直接友達関係の人と同じグループでブロックしている人、自分自身を除く人数が候補となる
print(uf.size(i)-1-num[i], end=" ") | 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())
n,m,k=map(int,input().split())
friend=[[] for _ in range(n)]
block=[[] for _ in range(n)]
a=UnionFind(n)
for i in range(m):
x,y=map(int,input().split())
friend[x-1].append(y-1)
friend[y-1].append(x-1)
a.union(x-1,y-1)
for i in range(k):
x,y=map(int,input().split())
block[x-1].append(y-1)
block[y-1].append(x-1)
ans=[]
for i in range(n):
ans.append(a.size(i)-len(friend[i])-sum(a.same(i,j) for j in block[i])-1)
print(*ans) | 1 | 61,490,724,489,780 | null | 209 | 209 |
N = int(input())
#https://img.atcoder.jp/abc178/editorial-E-phcdiydzyqa.pdf
z_list = list()
w_list = list()
for i in range(N):
x,y = map(int, input().split())
z_list.append(x + y)
w_list.append(x - y)
print(max(max(z_list)-min(z_list),max(w_list)-min(w_list))) | str = input()
if '7' in str:
print("Yes")
else:
print("No") | 0 | null | 18,913,293,967,932 | 80 | 172 |
#!/usr/bin/env python3
import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
s = input()
n = len(s)
ans = 0
for i in range(n//2):
if s[i] != s[-(i+1)]:
ans += 1
print(ans)
| s = list(input())
c = 0
x = s[::-1]
for i in range(len(s)):
if s[i] != x[i]:
x[i] = s[i]
c += 1
s[::-1] = x
print(c) | 1 | 120,463,362,353,446 | null | 261 | 261 |
import math
char = str(input())
char = char.replace('?','D')
print(char)
| import math
import re
import copy
t = input()
ans = t.replace("?","D")
print(ans) | 1 | 18,485,143,919,620 | null | 140 | 140 |
from sys import stdin
import math
def isPrime(x):
if x == 2 or x == 3: return True
elif (x < 2 or x % 2 == 0 or x % 3 == 0): return False
s = int(math.sqrt(x) + 1)
for i in range(5, s + 1, 2):
if x % i == 0: return False
return True
print(sum([isPrime(int(stdin.readline())) for _ in range(int(stdin.readline()))]))
| import math
n = int(input())
count = 0
for i in range(n):
t = int(input())
a = int(t ** (1 / 2))
end = 0
for j in range(2, a + 1):
if t % j == 0:
end = 1
break
if end == 0:
count += 1
print(count)
| 1 | 11,241,796,160 | null | 12 | 12 |
s=input()
if s[0]==s[1] and s[1]==s[2] :print("No")
else: print("Yes") | import collections
n,x,m=map(int,input().split())
if n==1 or x==0:
print(x)
exit()
start,end,loopcnt=0,0,0
a={x:0}
wk=x
for i in range(1,m):
wk=(wk*wk)%m
if not wk in a:
a[wk]=i
else:
start=a[wk]
end=i
break
a=sorted(a.items(),key=lambda x:x[1])
koteiindex=min(n,start)
koteiwa=0
for i in range(koteiindex):
koteiwa+=a[i][0]
loopcnt=(n-koteiindex)//(end-start)
loopindex=start-1+(n-koteiindex)%(end-start)
loopwa=0
amariwa=0
for i in range(start,end):
if i<=loopindex:
amariwa+=a[i][0]
loopwa+=a[i][0]
ans=koteiwa+loopwa*loopcnt+amariwa
print(ans)
| 0 | null | 29,012,267,515,400 | 201 | 75 |
def resolve():
import itertools
N = int(input())
A = []
X = []
ans = [0]
for _ in range(N):
a = int(input())
xx = []
for __ in range(a):
x = list(map(int, input().split()))
xx.append(x)
X.append(xx)
A.append(a)
for i in itertools.product([0, 1], repeat=N):
flag = 0
for p in range(N):
for q in range(A[p]):
if i[p] == 1 and X[p][q][1] != i[X[p][q][0]-1]:
flag = 1
if flag == 0:
ans.append(i.count(1))
print(max(ans))
resolve() | N = int(input())
evidence = [[] for _ in range(N)]
for i in range(N):
A = int(input())
for _ in range(A):
x,y = map(int,input().split())
evidence[i].append((x-1,y))
result = 0
for i in range(1,2**N):
consistent = True
for j in range(N):
if (i>>j)&1 == 1:
for x,y in evidence[j]:
if (i>>x)&1 != y:
consistent = False
break
if not consistent:
break
if consistent:
result = max(result,bin(i)[2:].count("1"))
print(result) | 1 | 121,105,239,908,700 | null | 262 | 262 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.