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
|
---|---|---|---|---|---|---|
def hash1(m, key):
return key % m
def hash2(m, key):
return 1 + key % (m - 1)
def hash(m, key, i):
return (hash1(m, key) + i * hash2(m, key) ) % m
def insert(T, key):
i = 0
l = len(T)
while True:
h = hash(1046527,key,i)
if (T[h] == None ):
T[h] = key
return h
elif (T[h] == key):
return h
else:
i += 1
def search(T,key):
l = len(T)
i = 0
while True:
h = hash(1046527,key,i)
if(T[h] == key):
return h
elif(T[h] is None or h >= l):
return -1
else:
i += 1
def find(T, key):
a = search(T,key)
if(a == -1):
print('no')
else:
print('yes')
dict = {'A' : '1', 'C' : '2', 'G' : '3', 'T' : '4'}
data = []
T = [None]*1046527
n = int(input())
while n > 0:
st = input()
d = list(st.split())
### convert key to num(1~4)
tmp_key = ''
for x in list(d[1]):
tmp_key += dict[x]
data.append([d[0],int(tmp_key)])
n -= 1
for com in data:
if(com[0] == 'insert'):
insert(T,com[1])
else:
find(T,com[1]) | def main():
n = int(input())
dictionary = set()
for _ in range(n):
order, code = input().split()
if order == 'insert':
dictionary.add(code)
elif order == 'find':
if code in dictionary:
print('yes')
else:
print('no')
else:
raise Exception('InputError')
if __name__ == '__main__':
main() | 1 | 78,331,626,600 | null | 23 | 23 |
k=int(input())
n=input()
x=len(n)
if(x>k):
print(n[0:k]+"...")
else:
print(n) | s = input()
week = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]
for i in range(6):
if s == week[i]:
print(6 - i)
if s == "SUN":
print("7")
| 0 | null | 76,534,721,269,380 | 143 | 270 |
A,B,C,K=map(int,input().split())
ans=1*min(A,K)
K=max(0,K-A-B)
print(ans-(1*K))
| import sys
import math
N = int(input())
def solve(num):
d = math.floor(num**(1/2))
for i in range(1,d+1):
if num % i == 0:
yield [i,num//i]
if N == 2:
print(1)
sys.exit()
cnt = 0
for a,b in solve(N-1):
if a == b:
cnt += 1
else:
cnt += 2
cnt -= 1
for s in solve(N):
if s[0] == s[1]:
s.pop()
for a in s:
if a == 1:
continue
tmp = N
while True:
tmp,m = divmod(tmp, a)
if m == 0:
continue
elif m == 1:
cnt += 1
break
print(cnt) | 0 | null | 31,559,089,966,702 | 148 | 183 |
n = int(input())
S = ['']*n
T = []
for i in range(n):
S[i] = input()
S.sort()
if n == 1:
print(S[0])
exit()
cnt = 1
mxcnt = 1
for i in range(n-1):
if S[i] == S[i+1]:
cnt += 1
else:
cnt = 1
mxcnt = max(mxcnt,cnt)
cnt = 1
for i in range(n-1):
if S[i] == S[i+1]:
cnt += 1
else:
cnt = 1
if cnt == mxcnt:
T.append(S[i])
if mxcnt == 1:
T.append(S[-1])
for t in T:
print(t) | # Common Raccoon vs Monster
H, N = map(int,input().split())
A = list(map(int, input().split()))
ans = ['No', 'Yes'][sum(A) >= H]
print(ans) | 0 | null | 73,747,522,942,338 | 218 | 226 |
# A - Curtain
def main():
a, b = map(int,input().split())
print(a - b*2 if a >= b*2 else 0)
if __name__ == "__main__":
main() | A,B = map(int,input().split())
print(A - 2*B if A > 2*B else 0) | 1 | 166,151,854,660,352 | null | 291 | 291 |
a,b = map(int, input().split())
print(f"{a//b} {a%b} {a/b:.5f}")
| 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
def f(n):
for i in range(50,-1,-1):
if n>=(i*(i+1)//2):
return i
break
n=int(input())
cnt=0
alist=factorization(n)
for i in range(len(alist)):
cnt+=f(alist[i][1])
if n==1:
cnt=0
print(cnt) | 0 | null | 8,751,318,373,820 | 45 | 136 |
from collections import defaultdict as d
n=int(input())
a=list(map(int,input().split()))
p=d(int)
l=0
for i in a:
p[i]+=1
l+=i
for i in range(int(input())):
b,c=map(int,input().split())
l+=p[b]*(c-b)
p[c]+=p[b]
p[b]=0
print(l) | import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
#======================================================#
def main():
n = II()
aa = MII()
q = II()
bc = [MII() for _ in range(q)]
sumv = sum(aa)
numbers = [0]*(10**5+1)
for a in aa:
numbers[a] += 1
for b,c in bc:
numb = numbers[b]
sumv += numb*(c-b)
print(sumv)
numbers[b] = 0
numbers[c] += numb
if __name__ == '__main__':
main() | 1 | 12,289,170,166,048 | null | 122 | 122 |
import sys; input = sys.stdin.readline
n = int(input())
if n%1000 == 0: print(0)
else: print(1000 - n%1000)
| r = int(input()) % 1000
print((1000 - r) % 1000) | 1 | 8,428,483,820,120 | null | 108 | 108 |
import math
L,R,d = map(int, input().strip().split())
x=math.ceil(L/d)
y=math.floor(R/d)
print(y-x+1)
| l,R, d = map(int, input().split())
a =0
for i in range(l,R+1):
if i % d == 0:
a = a+1
print(a)
| 1 | 7,590,047,226,652 | null | 104 | 104 |
N=1000;print(lambda f,n:f(f,n))(lambda f,n:n==0 and 100*N or(lambda x:x%N>0 and x-x%N+N or x)(f(f,n-1)*105/100),input()) | import math
n = input()
money = 100000
for i in range(0, n):
money = money*1.05
money /= 1000
money = int(math.ceil(money)*1000)
print money | 1 | 1,362,841,538 | null | 6 | 6 |
X = int(input())
c1 = X//500
X = X - c1*500
c2 = X//5
print(c1*1000 + c2*5) | X = int(input())
five_hundred = int(X / 500)
five = int((X - five_hundred*500)/5)
print(five_hundred*1000+five*5) | 1 | 42,750,021,158,320 | null | 185 | 185 |
N = int(input())
if N >=30:
print('Yes')
else :
print('No') | temp = int(input())
if temp >= 30:
print("Yes")
else:
print("No") | 1 | 5,723,127,520,252 | null | 95 | 95 |
K = int(input())
S = input().rstrip()
L = len(S)
if L <= K:
print(S)
else:
print(S[:K] + "...") | h,w,k=map(int,input().split())
ans=10**9
choco=[list(input()) for i in range(h)]
sumL=[[0 for i in range(w+1)] for j in range(h+1)]
for i in range(h):
for j in range(w):
sumL[i][j]=sumL[i-1][j]+sumL[i][j-1]-sumL[i-1][j-1]+int(choco[i][j])
for stat in range(2**(h-1)):
cnt=0;previous=-1
flg=0
cut=format(stat,"b").zfill(h-1)
cutl=[]
for hi in range(h-1):
if cut[hi]=="1":
cutl.append(hi)
cnt+=1
cutl.append(h-1)
cutl.append(-1)
for yoko in range(w):
for seg in range(len(cutl)):
if sumL[cutl[seg]][yoko]-sumL[cutl[seg]][previous]-sumL[cutl[seg-1]][yoko]+sumL[cutl[seg-1]][previous]>k and yoko-previous<=1:flg=1
elif sumL[cutl[seg]][yoko]-sumL[cutl[seg]][previous]-sumL[cutl[seg-1]][yoko]+sumL[cutl[seg-1]][previous]>k:previous=yoko-1;cnt+=1
if not flg and cnt < ans:ans=cnt
print(ans)
| 0 | null | 34,160,685,356,480 | 143 | 193 |
n,m,q = map(int,input().split())
a = [0]*q
b = [0]*q
c = [0]*q
d = [0]*q
for i in range(q):
a[i], b[i], c[i], d[i] = map(int, input().split())
a[i] -= 1 # インデックス補正
b[i] -= 1
def score(A):
x = 0
for ai,bi,ci,di in zip(a,b,c,d):
if A[bi] - A[ai] == ci:
x += di
return x
def dfs(A):
# 終端条件 --- 3 重ループまで回したら処理して打ち切り
if len(A) == n:
#print(A)
return score(A)
res = 0
# 単調増加するように制限
pre = A[-1] if len(A) > 0 else 0
for v in range(pre, m):
A.append(v) # 次のノードへの遷移
res = max(res,dfs(A)) # 再帰呼出し
A.pop() # 一回元に戻す (これが結構ポイント appendする前の状態に戻している)
return res
print(dfs([])) | 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()
| 0 | null | 78,642,171,373,916 | 160 | 268 |
n=int(input())#nはデータセットの数
for i in range(n):#n回繰り返す
edge=input().split()#入力
edge=[int(j) for j in edge]#入力
edge.sort()#ここでedge[2]が最大になる
if(edge[0]**2+edge[1]**2==edge[2]**2):#直角三角形かどうか
print("YES")
else:#そうでないなら
print("NO") | for i in range(int(input())):
a,b,c=map(lambda x:int(x)**2,input().split())
if a+b==c or b+c==a or c+a==b:
print("YES")
else:
print("NO")
| 1 | 319,861,300 | null | 4 | 4 |
import numpy as np
n,m,x = map(int,input().split())
value = []
books = []
for i in range(n):
a = list(map(int,input().split()))
value.append(a[0])
books.append(np.array(a[1:]))
if min(sum(books))<x:
print(-1)
else:
ans = 10**8
for i in range(2**n):
M = np.array([0]*m)
v = 0
for j in range(n):
if i >> j & 1:
M += books[j]
v += value[j]
if min(M)>= x:
ans = min(ans,v)
print(ans) | import sys
n,m,x=map(int,input().split())
ac=[[0]*(m+1) for i in range(n)]
a=[[0]*m for i in range(0,n)]
c=[0 for i in range(n)]
for i in range(n):
ac[i]=list(map(int,input().split()))
c[i]=ac[i][0]
a[i]=ac[i][1:m+1]#sliceは上限+1を:の右に代入
cheap=[]
kaukadouka=[0 for i in range(n)]
def kau(i):
global a,x,kaukadouka,cheap,c
rikaido=[0 for i in range(m)]#初期化
for j in range(i+1,n):
kaukadouka[j]=0
if i>=n:
sys.exit()
kaukadouka[i]=1
for j in range(n):
for k in range(m):
rikaido[k]+=kaukadouka[j]*a[j][k]
value=0
if min(rikaido)>=x:
for j in range(n):
value+=c[j]*kaukadouka[j]
cheap.append(value)
if i<n-1:
kau(i+1)
kawanai(i+1)
def kawanai(i):
global kaukadouka
for j in range(i,n):
kaukadouka[j]=0
if i>=n:
sys.exit()
#print('i=',i,'のとき買わないで')
#print('->',kaukadouka)
if i<n-1:
kau(i+1)
kawanai(i+1)
kau(0)
kawanai(0)
if len(cheap)>0:
#print(cheap)
print(min(cheap))
else:
print('-1') | 1 | 22,451,790,221,540 | null | 149 | 149 |
import math
N = int(input())
for i in range(N+1):
if math.floor(1.08 * i) == N:
print(i)
exit()
print(":(")
| import math
def lcm(a, b):
return int(a * b/ math.gcd(a, b))
a, b = map(int, input().split())
print(lcm(a,b)) | 0 | null | 119,288,325,968,214 | 265 | 256 |
import sys
N = input()
for i in range ( len ( N )):
if '7' == N[i] :
print("Yes")
sys.exit()
print("No") | n=list(map(int,input()))
if 7 in n:
print("Yes")
else:
print("No")
| 1 | 34,297,489,187,050 | null | 172 | 172 |
a,b = map(float, raw_input().split())
if b > 10**6:
f = 0.0
else:
f = a/b
d = int(a/b)
r = int(a%b)
print d, r, f | ls = map(float, raw_input().split())
d = (ls[0]/ls[1])
r = (ls[0]%ls[1])
f = ls[0]/ls[1]
print '%d %d %f' % (d, r, f) | 1 | 614,277,281,982 | null | 45 | 45 |
# -*- coding: utf-8 -*-
def main():
from math import gcd
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
max_a = 10 ** 6
numbers = [0 for _ in range(max_a + 1)]
# KeyInsight:
# 調和級数: 計算量 O(AlogA)
# ◯: 素因数分解をすればよいことには気がつけた。
# △: 4ケースWA・TLEが取れず
for ai in a:
numbers[ai] += 1
is_pairwise = True
# 素因数の判定
# 素因数の倍数の要素を数えている
for i in range(2, max_a + 1):
count = 0
for j in range(i, max_a + 1, i):
count += numbers[j]
# 2つ以上ある数の倍数があった場合は、少なくともpairwiseではない
if count > 1:
is_pairwise = False
if is_pairwise:
print("pairwise coprime")
exit()
value_gcd = 0
# 全ての要素のGCDが1かどうかを判定
for i in range(n):
value_gcd = gcd(value_gcd, a[i])
if value_gcd == 1:
print("setwise coprime")
exit()
print("not coprime")
if __name__ == '__main__':
main()
| N = int(input())
A = list(map(int, input().split()))
B = [0 for i in range(max(A)+1)]
for i in range(2, len(B)):
if B[i] != 0:
continue
for j in range(i, len(B), i):
B[j] = i
def func(X):
buf = set()
while X>1:
x = B[X]
buf.add(x)
while X%x==0:
X = X//x
#print(buf)
return buf
set1 = func(A[0])
set2 = func(A[0])
totallen = len(set1)
for a in A[1:]:
set3 = func(a)
totallen += len(set3)
#print(a, set1, set2)
set1 |= set3
set2 &= set3
#print(set1, set2, set3)
#print(totallen, set1, set2)
if len(set2)!=0:
print("not coprime")
elif len(set1)==totallen:
print("pairwise coprime")
else:
print("setwise coprime") | 1 | 4,093,962,223,012 | null | 85 | 85 |
H, N = map(int, input().split())
List = [list(map(int, input().split())) for _ in range(N)]
inf = 10 ** 9
dp = [0] + [inf] * H
for h in range(1, H + 1):
for n in range(1, N + 1):
a, b = List[n - 1]
ref = h - a
if ref < 0: ref = 0
dp[h] = min(dp[h], dp[ref] + b)
print(dp[H])
| import sys
input = sys.stdin.readline
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def main():
mod=10**9+7
H,N=MI()
A=[0]*N
B=[0]*N
for i in range(N):
A[i],B[i]=MI()
inf =10**20
dp=[[inf]*(H+1)for _ in range(N+1)]
# dp[i]はi番目の魔法まででhpをj減らす方法
dp[0][0]=0
for i in range(N):
a=A[i]
b=B[i]
for j in range(H+1):
if j-a>=0:
dp[i+1][j]=min(dp[i+1][j],
dp[i][j],
dp[i+1][j-a]+b)
else:
dp[i+1][j]=min(dp[i+1][j],
dp[i][j],
dp[i+1][0]+b)
print(dp[-1][-1])
main()
| 1 | 81,283,972,429,452 | null | 229 | 229 |
n = int(input())
dp = [1, 1]
for i in range(2, n + 1):
dp = [dp[-1], dp[-2] + dp[-1]]
print(dp[-1])
| a, b = 1, 1
for i in range(int(input())):
a, b = b, a + b
print(a) | 1 | 1,816,134,686 | null | 7 | 7 |
S = input()
if S[len(S) - 1] == 's':
print(S + 'es')
else:
print(S + 's') | palavra= input()
tam= len(palavra)
if palavra[tam-1]=='s':
print(palavra+'es')
else:
print(palavra+'s') | 1 | 2,372,606,304,800 | null | 71 | 71 |
from random import randint
import sys
input = sys.stdin.readline
INF = 9223372036854775808
def calc_score(D, C, S, T):
"""
開催日程Tを受け取ってそこまでのスコアを返す
コンテストi 0-indexed
d 0-indexed
"""
score = 0
last = [0]*26 # コンテストiを前回開催した日
for d, t in enumerate(T):
last[t] = d + 1
for i in range(26):
score -= (d + 1 - last[i]) * C[i]
score += S[d][t]
return score
def update_score(D, C, S, T, score, ct, ci):
"""
ct日目のコンテストをコンテストciに変更する
スコアを差分更新する
ct: change t 変更日 0-indexed
ci: change i 変更コンテスト 0-indexed
"""
new_score = score
last = [0]*26 # コンテストiを前回開催した日
prei = T[ct] # 変更前に開催する予定だったコンテストi
for d, t in enumerate(T, start=1):
last[t] = d
new_score += (d - last[prei])*C[prei]
new_score += (d - last[ci])*C[ci]
last = [0]*26
for d, t in enumerate(T, start=1):
if d-1 == ct:
last[ci] = d
else:
last[t] = d
new_score -= (d - last[prei])*C[prei]
new_score -= (d - last[ci])*C[ci]
new_score -= S[ct][prei]
new_score += S[ct][ci]
return new_score
def evaluate(D, C, S, T, k):
"""
d日目終了時点での満足度を計算し,
d + k日目終了時点での満足度の減少も考慮する
"""
score = 0
last = [0]*26
for d, t in enumerate(T):
last[t] = d + 1
for i in range(26):
score -= (d + 1 - last[i]) * C[i]
score += S[d][t]
for d in range(len(T), min(len(T) + k, D)):
for i in range(26):
score -= (d + 1 - last[i]) * C[i]
return score
def greedy(D, C, S):
Ts = []
for k in range(5, 13):
T = [] # 0-indexed
max_score = -INF
for d in range(D):
# d+k日目終了時点で満足度が一番高くなるようなコンテストiを開催する
max_score = -INF
best_i = 0
for i in range(26):
T.append(i)
score = evaluate(D, C, S, T, k)
if max_score < score:
max_score = score
best_i = i
T.pop()
T.append(best_i)
Ts.append((max_score, T))
return max(Ts, key=lambda pair: pair[0])
def local_search(D, C, S, score, T):
# ct 日目のコンテストをciに変更
for k in range(50000):
ct = randint(0, D-1)
ci = randint(0, 25)
ori = T[ct]
new_score = update_score(D, C, S, T, score, ct, ci)
T[ct] = ci
if score < new_score:
score = new_score
else:
T[ct] = ori
return T
if __name__ == '__main__':
D = int(input())
C = [int(i) for i in input().split()]
S = [[int(i) for i in input().split()] for j in range(D)]
init_score, T = greedy(D, C, S)
T = local_search(D, C, S, init_score, T)
for t in T:
print(t+1)
| while True:
x, y = map(int, raw_input().split())
if x==0 and y==0:
break
if x<y:
print '%d %d' %(x, y)
else:
print '%d %d' %(y, x) | 0 | null | 5,076,612,295,414 | 113 | 43 |
def g(x):
return x*(x+1)//2
n=int(input())
ans=0
for i in range(1,n+1):
ans=ans+i*g(n//i)
print(ans) | import math
class Triangle():
def __init__(self, edge1, edge2, angle):
self.edge1 = edge1
self.edge2 = edge2
self.angle = angle
self.edge3 = math.sqrt(edge1 ** 2 + edge2 ** 2 - 2 * edge1 * edge2 * math.cos(math.radians(angle)))
self.height = edge2 * math.sin(math.radians(angle))
self.area = edge1 * self.height / 2
a, b, theta = [int(i) for i in input().split()]
triangle = Triangle(a, b, theta)
print(triangle.area)
print(triangle.edge1 + triangle.edge2 + triangle.edge3)
print(triangle.height)
| 0 | null | 5,544,400,232,862 | 118 | 30 |
S=str(input())
ls = ["SAT","FRI","THU","WED","TUE","MON","SUN"]
for i in range(7):
if S == ls[i]:
print(i+1)
| from math import *
def distance (p,n,x,y):
dis = 0.0
if p == "inf":
for i in range(0,n) :
if dis < abs(x[i]-y[i]):
dis = abs(x[i]-y[i])
else :
for i in range(0,n) :
dis += abs(x[i]-y[i])**p
dis = dis ** (1.0/p)
return dis
if __name__ == '__main__' :
n = int(input())
x = map(int,raw_input().split())
y = map(int,raw_input().split())
print distance(1,n,x,y)
print distance(2,n,x,y)
print distance(3,n,x,y)
v = distance('inf',n,x,y)
print "%.6f" % v | 0 | null | 66,332,733,170,368 | 270 | 32 |
def main():
import sys
input = sys.stdin.readline
# comb init
mod = 1000000007
nmax = 4 * 10 ** 5 + 10 # change here
fac = [0] * nmax
finv = [0] * nmax
inv = [0] * nmax
fac[0] = 1
fac[1] = 1
finv[0] = 1
finv[1] = 1
inv[1] = 1
for i in range(2, nmax):
fac[i] = fac[i - 1] * i % mod
inv[i] = mod - inv[mod % i] * (mod // i) % mod
finv[i] = finv[i - 1] * inv[i] % mod
def comb(n, r):
if n < r:
return 0
else:
return (fac[n] * ((finv[r] * finv[n - r]) % mod)) % mod
N, K = map(int, input().split())
ans = 0
for m in range(min(K+1, N)):
ans = (ans + (comb(N, m) * comb(N-1, m))%mod)%mod
print(ans)
if __name__ == '__main__':
main()
| class Cmb:
def __init__(self, N, mod=10**9+7):
self.fact = [1,1]
self.fact_inv = [1,1]
self.inv = [0,1]
""" 階乗を保存する配列を作成 """
for i in range(2, N+1):
self.fact.append((self.fact[-1]*i) % mod)
self.inv.append((-self.inv[mod%i] * (mod//i))%mod)
self.fact_inv.append((self.fact_inv[-1]*self.inv[i])%mod)
""" 関数として使えるように、callで定義 """
def __call__(self, n, r, mod=10**9+7):
if (r<0) or (n<r):
return 0
r = min(r, n-r)
return self.fact[n] * self.fact_inv[r] * self.fact_inv[n-r] % mod
n,k = map(int,input().split())
mod = 10**9+7
c = Cmb(N=n)
ans = 0
for l in range(min(k+1, n)):
tmp = c(n,l)*c(n-1, n-l-1)
ans += tmp%mod
print(ans%mod) | 1 | 67,446,701,928,040 | null | 215 | 215 |
import math
n = input()
p = 0
money = 100
while p != n:
money = math.ceil(money * 1.05)
p += 1
print int(money * 1000) | def f(a,b):
if (b == 0): return a
a = a * 1.05
if (a%1000 != 0): a = a - a%1000 + 1000
return f(a,b-1)
print int(f(100000,input())) | 1 | 1,119,202,380 | null | 6 | 6 |
def nanbanme(n, x):
lst = [1 for i in range(n)]
ans = 0
for i in range(n):
a = x[i]
count = 0
for j in range(a - 1):
if (lst[j] == 1):
count = count + 1
tmp = 1
for k in range(1, n - i):
tmp = tmp*k
ans = ans + count*tmp
lst[a - 1] = 0
return (ans + 1)
n = int(input())
lst1 = list(map(int,input().split()))
lst2 = list(map(int,input().split()))
a = nanbanme(n, lst1)
b = nanbanme(n, lst2)
print(abs(a - b))
| T1, T2 = map(int,input().split())
A1, A2 = map(int,input().split())
B1, B2 = map(int,input().split())
T = T1*A1+T2*A2
A = T1*B1+T2*B2
if T == A:
print("infinity")
exit()
if T > A:
if A1 > B1:
print(0)
exit()
else:
tdif = T-A #7-5
pdif = T1*(B1-A1) #5
if pdif%tdif == 0:
ans = 2*(pdif//tdif)+1
else:
ans = 2*(1+pdif//tdif)
ans -=1 #原点の分を引く
else:
if B1 > A1:
print(0)
exit()
else:
tdif = A-T #7-5
pdif = T1*(A1-B1) #5
if pdif%tdif == 0:
ans = 2*(pdif//tdif)+1
else:
ans = 2*(1+pdif//tdif)
ans -=1 #原点の分を引く
print(ans) | 0 | null | 115,526,250,519,240 | 246 | 269 |
score = input()
scin = score.split()
ans = int(scin[0]) * int(scin[1])
print(ans) | import decimal
def main():
A, B = map(decimal.Decimal,input().split())
if A == 0:
return 0
else:
AB = A*B
return int(AB)
print(main()) | 0 | null | 16,131,082,403,552 | 133 | 135 |
N = int(input())
a_num = 97
def dfs(s, n, cnt): #s: 現在の文字列, n: 残りの文字数, cnt: 現在の文字列の最大の値
if n == 0:
print(s)
return
for i in range(cnt+2):
if i == cnt+1:
dfs(s+chr(a_num+i), n-1, cnt+1)
else:
dfs(s+chr(a_num+i), n-1, cnt)
dfs("a", N-1, 0) | #
# panasonic2020b d
#
import sys
from io import StringIO
import unittest
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, stdin
self.assertEqual(out, output)
def test_入力例_1(self):
input = """1"""
output = """a"""
self.assertIO(input, output)
def test_入力例_2(self):
input = """2"""
output = """aa
ab"""
self.assertIO(input, output)
def resolve():
global N
N = int(input())
T = []
func("a", "a", T)
for t in T:
print(t)
def func(mw, s, T):
if len(s) == N:
T.append(s)
return
for i in range(ord(mw)-ord("a")+2):
mw = max(mw, chr(ord("a")+i))
ns = s + chr(ord("a")+i)
func(mw, ns, T)
if __name__ == "__main__":
# unittest.main()
resolve()
| 1 | 52,616,154,591,550 | null | 198 | 198 |
s = input()
res = 0
cur = 0
for i in s:
if i =='S':
cur = 0
else:
cur += 1
res = max(cur, res)
print(res) | weather = list(input())
i = 0
j = 0
days = 0
consecutive = []
while i <= 2:
while i + j <= 2:
if weather[i+j] == "R":
days += 1
j += 1
else:
break
i += 1
j = 0
consecutive.append(days)
days = 0
print(max(consecutive))
| 1 | 4,947,589,446,998 | null | 90 | 90 |
import sys
sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inm = lambda: map(int, sys.stdin.readline().split())
inl = lambda: list(inm())
ins = lambda: sys.stdin.readline().rstrip()
debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw))
N = ins()
K = ini()
def solve():
M = len(N)
dp_eq = [[0 for _ in range(K + 1)] for _ in range(M)]
dp_less = [[0 for _ in range(K + 1)] for _ in range(M)]
dp_eq[0][K - 1] = 1
dp_less[0][K] = 1
dp_less[0][K - 1] = ord(N[0]) - ord("0") - 1
for i in range(1, M):
is_zero = N[i] == "0"
for k in range(K + 1):
if is_zero:
dp_eq[i][k] = dp_eq[i - 1][k]
elif k < K:
dp_eq[i][k] = dp_eq[i - 1][k + 1]
dp_less[i][k] = dp_less[i - 1][k]
if k < K:
dp_less[i][k] += dp_less[i - 1][k + 1] * 9
if not is_zero:
dp_less[i][k] += dp_eq[i - 1][k]
if k < K:
dp_less[i][k] += dp_eq[i - 1][k + 1] * (ord(N[i]) - ord("0") - 1)
return dp_eq[M - 1][0] + dp_less[M - 1][0]
print(solve())
| from decimal import Decimal, getcontext
a,b,c = input().split()
getcontext().prec = 10000
a = Decimal(a).sqrt()
b = Decimal(b).sqrt()
c = Decimal(c).sqrt()
if a+b+Decimal('0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001') < c:
print('Yes')
else:
print('No')
| 0 | null | 64,087,232,295,040 | 224 | 197 |
h,w= map(int,input().split())
tb = [input() for _ in range(h)]
st = [[0 for _ in range(w)] for _ in range(h)]
for i in range(h):
for j in range(w):
if i==0 and j==0:st[i][j]= (1 if tb[i][j]=='#' else 0)
else:
tr=td=999999999
if i!=0:
td=st[i-1][j]+(1 if (tb[i-1][j]=='.' and tb[i][j]=='#') else 0)
if j!=0:
tr=st[i][j-1]+(1 if (tb[i][j-1]=='.' and tb[i][j]=='#') else 0)
st[i][j]=min(td,tr)
print(st[h-1][w-1]) | INF = 10**9
def solve(h, w, s):
dp = [[INF] * w for r in range(h)]
dp[0][0] = int(s[0][0] == "#")
for r in range(h):
for c in range(w):
for dr, dc in [(-1, 0), (0, -1)]:
nr, nc = r+dr, c+dc
if (0 <= nr < h) and (0 <= nc < w):
dp[r][c] = min(dp[r][c], dp[nr][nc] + (s[r][c] != s[nr][nc]))
return (dp[h-1][w-1] + 1) // 2
h, w = map(int, input().split())
s = [input() for r in range(h)]
print(solve(h, w, s))
| 1 | 49,175,368,542,124 | null | 194 | 194 |
N = int(input())
S = input()
cnt = 0
post_c = ''
for i in range(len(S)):
if post_c != S[i]:
post_c = S[i]
cnt += 1
print(cnt)
| ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))
n,t = mi()
data = []
for i in range(n):
data.append(li())
data.sort()
dp = [[0]*t for i in range(n+1)]
for i in range(n):
for k in range(t):
dp[i+1][k] = max(dp[i+1][k],dp[i][k])
if k + data[i][0] <= t-1:
dp[i+1][k+data[i][0]] = max(dp[i+1][k+data[i][0]],dp[i][k] + data[i][1])
ans = 0
for i in range(n):
ans = max(ans,dp[i][t-1] + data[i][1])
print(ans)
| 0 | null | 160,944,878,595,948 | 293 | 282 |
from collections import deque
N = int(input())
A = deque(map(int, input().split()))
mod = 10**9 + 7
M = len(bin(max(A))) - 2
ans = 0
bitlist = [1]
anslist = [0 for _ in range(M)]
for k in range(M):
bitlist.append(bitlist[-1]*2%mod)
counter = [0 for _ in range(M)]
for k in range(N):
a = A.pop()
c = 0
while a:
b = a & 1
if b == 0:
anslist[c] += counter[-c-1]
else:
anslist[c] += k - counter[-c-1]
counter[-c-1] += 1
c += 1
a >>= 1
while c < M:
anslist[c] += counter[-c-1]
c += 1
for k in range(M):
ans += anslist[k]*bitlist[k]%mod
ans %= mod
print(ans)
| import sys
import math
from heapq import *
import fractions
from collections import defaultdict
stdin = sys.stdin
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))
N=int(input())
A=nl()
A.sort(reverse=True)
mod=10**9+7
keta=[0]*60
for i in range(N):
for j in range(60):
keta[j]+=((A[i]>>j)&1)
ans=0
mod_div2=[0]*60
mod_div2[0]=1
for i in range(1,60):
mod_div2[i]=(2*mod_div2[i-1])%mod
for i in range(len(A)):
keta_max=0
for j in range(60):
if((A[i]>>j)&1):
keta_max=j+1
for j in range(keta_max):
if((A[i]>>j)&1):
keta[j]-=1
ans+=mod_div2[j]*(len(A)-i-1-keta[j])
else:
ans+=mod_div2[j]*keta[j]
ans%=mod
print(ans%mod) | 1 | 122,947,616,302,680 | null | 263 | 263 |
n = int(input())
data = [int(i) for i in input().split()]
print(f'{min(data)} {max(data)} {sum(data)}')
| import sys
input = sys.stdin.readline
mod = 998244353
N, S = map(int, input().split())
A = list(map(int, input().split()))
ans = 0
dp = [0] * (S+1)
dp[0] = pow(2, N, mod)
two_inv = pow(2, mod-2, mod)
for i, a in enumerate(A):
for j in range(a, S+1)[::-1]:
dp[j] = (dp[j] + dp[j-a] * two_inv) % mod
print(dp[S])
| 0 | null | 9,157,239,468,860 | 48 | 138 |
#!/usr/bin/env python3
import math
import sys
import itertools
sys.setrecursionlimit(10**7)
MOD = 1000000007 # type: int
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1] # 階乗を求めるためのキャッシュ
self.invModulos = [0, 1] # n^-1のキャッシュ
self.invFactorial_ = [1, 1] # (n^-1)!のキャッシュ
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def choose_k_from_n(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
def pow(a,n,m):
if n == 1:
return a
elif n == 0 or a == 1:
return 1
else:
if n%2 == 0:
r = pow(a,n//2,m)
return r*r%m
else:
r = pow(a,n-1,m)
return a*r%m
def solve(N: int, K: int):
powDict = {}
def powd(a):
if a in powDict:
return powDict[a]
else:
powDict[a] = pow(a,N,MOD)
return powDict[a]
cDict = {}
sum = 0
for p in range(K,0,-1):
c = powd(K//p)
for i in range(2*p,K+1,p):
c = (c-cDict[i])%MOD
cDict[p]=c
sum = (sum + c*p)%MOD
print(sum)
# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
K = int(next(tokens)) # type: int
solve(N, K)
if __name__ == '__main__':
main()
| a, b, k = map(int, input().split())
n = min(a,k)
k -= n
print(a-n, max(0,b-k)) | 0 | null | 70,642,086,852,542 | 176 | 249 |
a, b = input().split()
print(sorted([a*int(b), b*int(a)])[0])
|
N = int(input().strip())
l = [chr(i) for i in range(97, 97+26)]
ans = ""
if N <= 26:
ans = l[N-1]
else:
for i in range(1,11):
st = 0
for k in range(i):
st = st + 26**(k+1)
nd = st + 26**(i+1)
if st < N <= nd:
N = N - st
for j in range(i+1):
r = N % 26
N = N // 26
if r != 0:
N += 1
ans = l[r-1] + ans
if r == 0:
ans = "z" + ans
break
print(ans) | 0 | null | 48,126,595,428,840 | 232 | 121 |
# ng, ok = 0, 10**9+1
n,k = map(int, input().split())
al = list(map(int, input().split()))
ng, ok = 0, 10**9+1
while abs(ok-ng) > 1:
mid = (ok+ng)//2
ok_flag = True
# ...
cnt = 0
for a in al:
cnt += (a-1)//mid
if cnt <= k:
ok = mid
else:
ng = mid
print(ok)
| n,k = map(int,input().split())
L = list(map(int,input().split()))
ok = 0
ng = 10**9
while abs(ok-ng) > 1:
mid = (ok+ng)//2
cur = 0
for i in range(n):
cur += L[i]//mid
if cur > k:
ok = mid
elif cur <= k:
ng = mid
K = [mid-1, mid, mid+1]
P = []
for i in range(3):
res = 0
if K[i] > 0:
for j in range(n):
res += (L[j]-1)//K[i]
if res <= k:
P.append(K[i])
print(min(P))
| 1 | 6,510,109,237,320 | null | 99 | 99 |
from collections import deque
n = int(input())
dll = deque()
for i in range(n):
input_line = input().split()
if input_line[0] == "insert":
dll.appendleft(input_line[1])
elif len(dll) == 0:
continue
elif input_line[0] == "delete":
try:
dll.remove(input_line[1])
except:
pass
elif input_line[0] == "deleteFirst":
dll.popleft()
else:
dll.pop()
print(*dll) | from collections import deque
import sys
n = int(sys.stdin.readline())
#lines = sys.stdin.readlines()
lines = [input() for i in range(n)]
deq = deque()
for i in range(n):
o = lines[i].split()
if o[0] == 'insert':
deq.appendleft(o[1])
elif o[0] == 'delete':
try:
deq.remove(o[1])
except:
continue
elif o[0] == 'deleteFirst':
deq.popleft()
elif o[0] == 'deleteLast':
deq.pop()
print(' '.join(deq))
| 1 | 50,980,400,028 | null | 20 | 20 |
n = int(input())
ans = [1]*n
T = [[-1]*n for _ in range(n)]
for ni in range(n):
a = int(input())
for ai in range(a):
x, y = map(int,input().split())
T[ni][x-1] = y
mx = 0
for i in range(pow(2,n)):
tmx = -1
B = bin(i)[2:].zfill(n)
S = [i for i,b in enumerate(B) if b=='1']
for s in S:
_Ts = [i for i,t in enumerate(T[s]) if t==1]
_Tf = [i for i,t in enumerate(T[s]) if t==0]
if not (set(_Ts)<=set(S) and set(_Tf)&set(S)==set()):
tmx = 0
break
if tmx==-1: tmx=len(S)
mx = max(mx, tmx)
print(mx) | n = input()
p = [0] * 2
for i in range(n):
t, h = raw_input().split()
if(t > h):
p[0] += 3
elif(t < h):
p[1] += 3
else:
p[0] += 1
p[1] += 1
print("%d %d" %(p[0], p[1])) | 0 | null | 62,051,912,560,968 | 262 | 67 |
n=int(input())
a=list(map(int,input().split()))
ans='APPROVED'
for i in range(n):
if a[i]%2==0:
if a[i]%3!=0 and a[i]%5!=0:
ans='DENIED'
print(ans) | def Base(X, n):
if (int(X/n)):
return Base(int(X/n), n)+str(X%n)
return str(X%n)
def main():
N, K = map(int, input().split())
ans1 = Base(N, K)
ans = len(ans1)
print(ans)
main() | 0 | null | 66,852,347,813,660 | 217 | 212 |
n,t=map(int,input().split())
F=[list(map(int,input().split())) for i in range(n)]
dp1=[[0]*(t+1) for i in range(n)]
for i in range(1,n):
for j in range(1,t+1):
if j-F[i-1][0]>=0:
dp1[i][j]=max(dp1[i-1][j],dp1[i][j-1],dp1[i-1][j-F[i-1][0]]+F[i-1][1])
else:
dp1[i][j]=max(dp1[i-1][j],dp1[i][j-1])
dp2=[[0]*(t+1) for i in range(n)]
for i in range(1,n):
for j in range(1,t+1):
if j-F[n-i][0]>=0:
dp2[i][j]=max(dp2[i-1][j],dp2[i][j-1],dp2[i-1][j-F[n-i][0]]+F[n-i][1])
else:
dp2[i][j]=max(dp2[i-1][j],dp2[i][j-1])
ans=0
for i in range(n):
for j in range(1,t):
a=dp1[i][j]+dp2[n-i-1][t-j-1]+F[i][1]
if a>ans:
ans=a
print(ans) | def ints():
return [int(x) for x in input().split()]
def ii():
return int(input())
N, T = ints()
dp = [[0]*T for j in range(N+1)]
F = sorted([ints() for i in range(N)])
for i in range(N):
a, b = F[i]
for t in range(T):
dp[i+1][t] = max(dp[i+1][t], dp[i][t])
nt = t+a
if nt<T:
dp[i+1][nt] = max(dp[i+1][nt], dp[i][t]+b)
w = max([F[i][1] + dp[i][T-1] for i in range(1, N)])
print(w)
| 1 | 151,830,929,960,060 | null | 282 | 282 |
S = str(input())
print(len(S) * "x") | import sys
try:
#d = int(input('D: '))
#t = int(input('T: '))
#s = int(input('S: '))
nums = [int(e) for e in input().split()]
except ValueError:
print('エラー:整数以外を入力しないでください')
sys.exit(1)
if 1 <= nums[0] <= 10000 and 1 <= nums[1] <= 10000 and 1 <= nums[2] <= 10000:
take_time = nums[0] / nums[2]
if take_time <= nums[1]:
print("Yes")
else:
print("No")
else:
print('エラー:各入力は1~10000までの整数です') | 0 | null | 38,100,738,080,578 | 221 | 81 |
class stack():
def __init__(self):
self.S = []
def push(self, x):
self.S.append(x)
def pop(self):
return self.S.pop()
def isEmpty(self):
if len(self.S) == 0:
return True
else:
return False
areas = input()
S1 = stack()
S2 = stack()
for i, info in enumerate(areas):
if info == '/':
if S1.isEmpty():
continue
left = S1.pop()
menseki = i - left
while True:
if S2.isEmpty():
S2.push([menseki, left])
break
if S2.S[-1][1] < left:
S2.push([menseki, left])
break
menseki += S2.pop()[0]
elif info == '\\':
S1.push(i)
ans = [m[0] for m in S2.S]
print(sum(ans))
if len(ans) == 0:
print(len(ans))
else:
print(len(ans), ' '.join(list(map(str, ans))))
| def bubble_sort(alist):
"""Sort alist by bubble sort.
Returns (number of swap operations, sorted list)
>>> bubble_sort([5, 3, 2, 4, 1])
([1, 2, 3, 4, 5], 8)
"""
size = len(alist)
count = 0
for i in range(size-1):
for j in reversed(range(i+1, size)):
if alist[j] < alist[j-1]:
count += 1
alist[j-1], alist[j] = alist[j], alist[j-1]
return (alist, count)
def run():
_ = int(input()) # flake8: noqa
nums = [int(i) for i in input().split()]
(sorted_list, num_swap) = bubble_sort(nums)
print(" ".join([str(i) for i in sorted_list]))
print(num_swap)
if __name__ == '__main__':
run()
| 0 | null | 36,393,167,248 | 21 | 14 |
def main():
K, X = map(int, input().split())
print('Yes' if 500 * K >= X else 'No')
if __name__ == "__main__":
main()
| from sys import stdin
import math
n, m = [int(x) for x in stdin.readline().rstrip().split()]
if n * 500 >= m:
print('Yes')
else:
print('No') | 1 | 97,762,755,176,254 | null | 244 | 244 |
while 1:
a = list(map(int, input().split()))
if a[0] or a[1]:
print(min(a), max(a))
else:
break
| while True:
line = list(map(int, input().split()))
if line==[0,0]: break
print(' '.join(map(str,sorted(line)))) | 1 | 520,694,872,810 | null | 43 | 43 |
def main():
n = int(input())
A = list(map(int,input().split()))
ans = n
A.sort()
table = [True]*(A[-1]+1)
for k,a in enumerate(A):
if table[a]:
if k+1<n and A[k+1]==a:
ans-=1
for i in range(a,A[-1]+1,a):
table[i] = False
else:
ans-=1
print(ans)
main() | 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, log
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
from decimal import Decimal
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 *
N = INT()
ab = [LIST() for _ in range(N-1)]
graph = [[] for _ in range(N)]
for a, b in ab:
graph[a-1].append(b-1)
graph[b-1].append(a-1)
length = [len(x) for x in graph]
ans = max(length)
color = defaultdict(int)
q = deque([])
cnt = 1
for x in graph[0]:
q.append((x, 0, cnt))
cnt += 1
while q:
n, previous, col = q.popleft()
cnt = 1
for x in graph[n]:
if x == previous:
color[(n, x)] = col
color[(x, n)] = col
else:
if cnt == col:
cnt += 1
color[(n, x)] = cnt
color[(x, n)] = cnt
q.append((x, n, cnt))
cnt += 1
print(ans)
for a,b in ab:
print(color[(a-1, b-1)])
| 0 | null | 75,637,995,547,488 | 129 | 272 |
K = int(input())
A, B = map(int, input().split())
if B // K * K >= A:
print('OK')
else:
print('NG')
| #0除算
import math
def popcount(x):
s=0
y=int(math.log2(x))+2
for i in range(y):
if(x>>i)&1:
s+=1
return x%s
n=int(input())
x=input()[::-1]
#1がなんこ出るのか
c=x.count("1")
#c+1とc-1だけ考えれば良い
#c=1の時場合分け
#m[i][j]:2^iまで考えたときのmod(c+j-1)
if c!=1:
m=[[1%(c-1),1%(c+1)]]
for i in range(n-1):
m.append([(2*m[-1][0])%(c-1),(2*m[-1][1])%(c+1)])
l=[0,0]
for i in range(n):
if x[i]=="1":
l[0]+=m[i][0]
l[1]+=m[i][1]
l[0]%=(c-1)
l[1]%=(c+1)
else:
m=[[1%(c+1),1%(c+1)]]
for i in range(n-1):
m.append([(2*m[-1][0])%(c+1),(2*m[-1][1])%(c+1)])
l=[0,0]
for i in range(n):
if x[i]=="1":
l[0]+=m[i][0]
l[1]+=m[i][1]
l[0]%=(c+1)
l[1]%=(c+1)
#一個だけ変えたいので全体を求める
#最初以外はpopcount使って間に合う
ans=[0]*n
for i in range(n):
if x[i]=="1":
if c-1==0:
ans[i]=0
continue
p=(l[0]+(c-1)-m[i][0])%(c-1)
ans[i]+=1
while p!=0:
p=popcount(p)
ans[i]+=1
else:
p=(l[1]+m[i][1])%(c+1)
ans[i]+=1
while p!=0:
p=popcount(p)
ans[i]+=1
ans=ans[::-1]
for i in range(n):
print(ans[i])
| 0 | null | 17,517,713,966,666 | 158 | 107 |
def selection_sort(A):
count = 0
for i in range(len(A)):
min_value = A[i]
min_value_index = i
# print('- i:', i, 'A[i]', A[i], '-')
for j in range(i, len(A)):
# print('j:', j, 'A[j]:', A[j])
if A[j] < min_value:
min_value = A[j]
min_value_index = j
# print('min_value', min_value, 'min_value_index', min_value_index)
if i != min_value_index:
count += 1
A[i], A[min_value_index] = A[min_value_index], A[i]
# print('swap!', A)
return count
n = int(input())
A = list(map(int, input().split()))
count = selection_sort(A)
print(*A)
print(count)
| x,y=map(int,input().split())
if (x+y)%3!=0:
print(0)
exit()
if x<y:
x,y=y,x
if 2*y<x:
print(0)
exit()
mod=10**9+7
a=(2*y-x)//3
b=(2*x-y)//3
mx=10**6
k=[1]*(mx+1)
def inv(n):
return pow(n,mod-2,mod)
for i in range(mx):
k[i+1]=k[i]*(i+1)%mod
ans=(k[a+b]*inv(k[a])*inv(k[b]))%mod
print(ans) | 0 | null | 74,761,012,364,932 | 15 | 281 |
u={1,2,3}
AB=[int(input()) for i in range(2)]
print(list(u-set(AB))[0]) | def main():
a, b = map(lambda x: int(x.replace('.','')), input().split())
print(a*b//100)
if __name__ == '__main__':
main() | 0 | null | 63,402,364,642,720 | 254 | 135 |
# -*- coding: utf-8 -*-
import sys
from bisect import bisect_left,bisect_right
from collections import defaultdict
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1
def main():
class SegmentTree:
def __init__(self,n,segfunc,ide_ele):
self.segfunc=segfunc
self.ide_ele=ide_ele
self.num=2**(n-1).bit_length()
self.dat=[ide_ele]*2*self.num
def init(self,iter):
for i in range(len(iter)):
self.dat[i+self.num]=iter[i]
for i in range(self.num-1,0,-1):
self.dat[i]=self.segfunc(self.dat[i*2],self.dat[i*2+1])
def update(self,k,x):
k+=self.num
self.dat[k]=x
while k:
k//=2
self.dat[k]=self.segfunc(self.dat[k*2],self.dat[k*2+1])
def query(self,p,q):
if q<=p:
return self.ide_ele
p+=self.num
q+=self.num-1
res=self.ide_ele
while q-p>1:
if p&1==1:
res=self.segfunc(res,self.dat[p])
if q&1==0:
res=self.segfunc(res,self.dat[q])
q-=1
p=(p+1)//2
q=q//2
if p==q:
res=self.segfunc(res,self.dat[p])
else:
res=self.segfunc(self.segfunc(res,self.dat[p]),self.dat[q])
return res
N=int(input())
S=[input() for i in range(N)]
P=0
M=0
c=0
Seg=SegmentTree(10**6+1,lambda a,b:max(a,b),-INF)
l_PM=defaultdict(list)
stack=defaultdict(list)
minus=set()
for i,s in enumerate(S):
p=0
m=0
for x in s:
if x=='(':
p+=1
else:
if p>0:
p-=1
else:
m+=1
if m==0 and p>0:
P+=p
elif p==0 and m>0:
M+=m
elif p>0 and m>0:
c+=1
minus.add(m)
stack[m].append(p-m)
minus=list(minus)
minus.sort()
for x in minus:
stack[x].sort()
if x<=P:
while stack[x]:
y=stack[x].pop()
if y>=0:
c-=1
P+=y
else:
Seg.update(x,y)
l_PM[y].append(x)
break
else:
y=stack[x].pop()
Seg.update(x,y)
l_PM[y].append(x)
for _ in range(c):
x=Seg.query(0,P+1)
if x==-INF or P+x<0:
print('No')
exit()
l_PM[x].sort()
res=bisect_right(l_PM[x],P)-1
index=l_PM[x][res]
del l_PM[x][res]
if stack[index]:
y=stack[index].pop()
Seg.update(index,y)
l_PM[y].append(index)
else:
Seg.update(index,-INF)
P+=x
P-=M
YesNo(P==0)
if __name__ == '__main__':
main()
| import sys
readline = sys.stdin.readline
def main():
N = int(readline())
Sp = []
Sm = []
total = 0
bm = 0
for i in range(N):
l = readline().strip()
b = 0
h = 0
for j in range(len(l)):
if l[j] == '(':
h += 1
else:
h -= 1
b = min(b, h)
if h == 0 and b != 0:
bm = min(bm, b)
elif h > 0:
Sp.append([b, h])
elif h < 0:
Sm.append([b-h, -h])
total += h
Sp.append([bm, 0])
if total != 0:
print('No')
exit()
Sp.sort(key=lambda x:x[0], reverse=True)
p = check(Sp)
if p < 0:
print('No')
exit()
Sm.sort(key=lambda x:x[0], reverse=True)
m = check(Sm)
if m < 0:
print('No')
exit()
print('Yes')
def check(S):
h = 0
for i in range(len(S)):
if h + S[i][0] < 0:
return -1
else:
h += S[i][1]
return h
if __name__ == '__main__':
main() | 1 | 23,664,420,817,988 | null | 152 | 152 |
def resolve():
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
BC = [list(map(int, input().split())) for _ in range(Q)]
a = [0] * 100001
for i in A:
a[i] += i
ans = sum(a)
for b, c in BC:
if a[b] == 0:
print(ans)
continue
move = a[b] // b
a[b] = 0
a[c] += c * move
ans += (c - b) * move
print(ans)
if __name__ == "__main__":
resolve() | N = int(input())
A = list(map(int,input().split()))
Q = int(input())
C = (10**5+1)*[0]
T = sum(A)
for a in A:
C[a]+=1
for q in range(Q):
b,c = map(int,input().split())
T+=C[b]*(c-b)
C[c]+=C[b]
C[b]=0
print(T) | 1 | 12,245,963,555,462 | null | 122 | 122 |
x,y = map(int,input().split())
def point(a):
if a == 1:
return 300000
elif a == 2:
return 200000
elif a == 3:
return 100000
else:
return 0
c = point(x)
b = point(y)
if x == 1 and y == 1:
print(1000000)
else:
print(c+b) | s = 0
a = 0
for i in map(int, input().split()):
s += max(0, (4 - i) * 100000)
if i == 1:
a += 1
if a == 2:
s += 400000
print(s) | 1 | 140,445,345,119,930 | null | 275 | 275 |
S = int(input())
MOD = 10 ** 9 + 7
DP = [0] * (S+1)
DP[0] = 1
for i in range(S):
for nex in range(i+3, S+1):
DP[nex] += DP[i]
DP[nex] %= MOD
print(DP[S] % MOD)
| N,K=map(int,input().split())
P=list(map(int,input().split()))
L=[]
M=[0]
c=0
m=0
x=0
for i in range(200100):
c+=i
L.append(c)
for i in P:
m+=L[i]/i
M.append(m)
if N!=K:
for i in range(N-K+1):
x=max(M[K+i]-M[i],x)
else:
x=M[K]-M[0]
print(x) | 0 | null | 39,120,575,530,400 | 79 | 223 |
n=int(input())
if n%2==0:
r=0
i=1
while 2*5**i<=n:
r+=n//(2*5**i)
i+=1
print(r)
else:
print(0)
| N = int(input())
ans = 0
if N%2 == 0:
five = 10
while N//five > 0:
ans += N//five
five *= 5
print(ans) | 1 | 115,517,314,643,580 | null | 258 | 258 |
from collections import deque
n, m = map(int ,input().split())
graph = [[] for _ in range(n)]
for i in range(m):
a,b = map(int, input().split())
graph[a-1].append(b-1)
graph[b-1].append(a-1)
v = [0]*n
ans = 0
for i in range(n):
if v[i] == 0:
ans += 1
q = deque()
q.append(i)
v[i] = 1
while q:
node = q.popleft()
for j in graph[node]:
if v[j] == 0:
q.append(j)
v[j] = 1
print(ans-1) | import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque, defaultdict
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np # cumsum
# from bisect import bisect_left, bisect_right
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
def solve():
N, M = MI()
uf = UnionFind(N)
for i in range(M):
a, b = MI1()
uf.union(a, b)
print(uf.group_count()-1)
if __name__ == '__main__':
solve()
| 1 | 2,264,365,751,780 | null | 70 | 70 |
class Card(object):
def __init__(self, card):
self.suit = card[:1]
self.value = int(card[1:])
def __str__(self):
return self.suit + str(self.value)
def is_stable(bs, ss):
if bs == ss:
return 'Stable'
else:
return 'Not stable'
def bubble_sort(c, n):
c = c.split()
c = [Card(card) for card in c]
for i in range(n-1):
for j in range(n-1):
if c[j].value > c[j+1].value:
c[j], c[j+1] = c[j+1], c[j]
return c
def selection_sort(c, n):
c = c.split()
c = [Card(card) for card in c]
for i in range(n):
mink = i
for v in range(i, n):
if c[v].value < c[mink].value:
mink = v
if mink != i:
c[i], c[mink] = c[mink], c[i]
return c
n = input()
nums = input()
bs = bubble_sort(nums, int(n))
bs_str = [str(card) for card in bs]
print(' '.join(bs_str))
print('Stable')
ss = selection_sort(nums, int(n))
ss_str = [str(card) for card in ss]
print(' '.join(ss_str))
print(is_stable(bs_str, ss_str))
| def selection_sort(numbers, n, key=lambda x: x):
"""selection sort method
Args:
numbers: a list of numbers to be sorted
n: len(numbers)
key: sort key
Returns:
sorted numberd, number of swapped times
"""
x = []
for data in numbers:
x.append(data)
counter = 0
for i in range(0, n):
min_j = i
for j in range(i, n):
if key(x[j]) < key(x[min_j]):
min_j = j
if min_j != i:
x[min_j], x[i] = x[i], x[min_j]
counter += 1
return x, counter
def bubble_sort(numbers, n, key=lambda x: x):
"""bubble sort method
Args:
numbers: a list of numbers to be sorted by bubble sort
n: len(list)
key: sort key
Returns:
sorted list
"""
x = []
for data in numbers:
x.append(data)
flag = True
counter = 0
while flag:
flag = False
for index in range(n - 1, 0, -1):
if key(x[index]) < key(x[index - 1]):
x[index], x[index - 1] = x[index - 1], x[index]
flag = True
counter += 1
return x, counter
def insertion_sort(numbers, n, key=lambda x: x):
"""insertion sort method
Args:
numbers: a list of numbers to be sorted
n: len(numbers)
Returns:
sorted list
"""
for i in range(1, n):
target = numbers[i]
index = i - 1
while index >= 0 and target < numbers[index]:
numbers[index + 1] = numbers[index]
index -= 1
numbers[index + 1] = target
return numbers
def is_stable(list1, list2):
"""check stablity of sorting method used in list2
Args:
list1: sorted list(bubble sort)
list2: sorted list(some sort)
Returns:
bool
"""
flag = True
for index, data in enumerate(list1):
if list2[index] != data:
flag = False
break
return flag
length = int(raw_input())
cards = raw_input().split()
bubble_sorted_card, bubble_swapped = bubble_sort(numbers=cards, n=length, key=lambda x: int(x[1]))
selection_sorted_card, selection_swapped = selection_sort(numbers=cards, n=length, key=lambda x: int(x[1]))
print(" ".join(bubble_sorted_card))
print("Stable")
print(" ".join(selection_sorted_card))
if is_stable(bubble_sorted_card, selection_sorted_card):
print("Stable")
else:
print("Not stable") | 1 | 27,015,135,862 | null | 16 | 16 |
class Stack():
def __init__(self):
self.stack = [0 for _ in range(200)]
self.top = 0
def isEmpty(self):
return self.top == 0
def isFull(self):
return self.top >= len(self.stack) - 1
def push(self, x):
if self.isFull():
print "error"
return exit()
self.top += 1
self.stack[self.top] = x
def pop(self):
if self.isEmpty():
print "error"
return exit()
a = self.stack[self.top]
del self.stack[self.top]
self.top -= 1
return a
def lol(self):
return self.stack[self.top]
def main():
st = Stack()
data = raw_input().split()
for i in data:
if i == '+':
b = int(st.pop())
a = int(st.pop())
st.push(a + b)
elif i == '-':
b = int(st.pop())
a = int(st.pop())
st.push(a - b)
elif i == '*':
b = int(st.pop())
a = int(st.pop())
st.push(a * b)
else:
st.push(i)
print st.lol()
if __name__ == '__main__':
main() | lst = raw_input().split()
lst2 = []
for v in lst:
if v == "+":
lst2[len(lst2)-2] += lst2.pop()
elif v == "-":
lst2[len(lst2)-2] -= lst2.pop()
elif v == "*":
lst2[len(lst2)-2] *= lst2.pop()
elif v == "/":
lst2[len(lst2)-2] /= lst2.pop()
else:
lst2.append(int(v))
print lst2[0] | 1 | 34,713,337,890 | null | 18 | 18 |
mod = 1000000007
ans = 0
power = [0 for i in range(2005)]
power[0] = 1
for i in range(1,2001):
power[i] = power[i-1] * i
def C(x,y):
return 0 if x < y else power[x] // power[y] // power[x-y]
def H(x,y):
return C(x+y-1,y-1)
n = int(input())
for i in range(3,n+1,3):
ans += H(n-i,i//3)
ans = (ans % mod + mod) % mod
print(ans) | s = input()
suffix = ''
if s.endswith('s'):
suffix = 'es'
else:
suffix = 's'
print(s + suffix) | 0 | null | 2,880,571,701,630 | 79 | 71 |
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7
a, v = MAP()
b, w = MAP()
t = INT()
if a == b:
YES()
exit()
if w >= v:
NO()
exit()
diff = v - w
dist = abs(a-b)
if diff*t >= dist:
YES()
else:
NO()
| input()
s=input()
t,a=s[0],1
for c in s:
if c!=t: a+=1; t=c
print(a) | 0 | null | 92,909,037,650,560 | 131 | 293 |
N,K=map(int,input().split())
mod=10**9+7
X=[0]+[pow(K//d,N,mod) for d in range(1,K+1)]
'''
Y=[[] for i in range(K+1)]
for i in range(1,K+1):
for j in range(i,K+1,i):
Y[j].append(i)
'''
#print(X)
isPrime=[1 for i in range(K+1)]
isPrime[0]=0;isPrime[1]=0
for i in range(K+1):
if isPrime[i]==0:
continue
for j in range(2*i,K+1,i):
isPrime[j]=0
Mebius=[1 for i in range(K+1)]
Mebius[0]=0
for i in range(2,K+1):
if isPrime[i]==0:
continue
for j in range(i,K+1,i):
Mebius[j]*=-1
for i in range(2,K+1):
for j in range(i*i,K+1,i*i):
Mebius[j]=0
Z=[0 for i in range(K+1)]
for i in range(1,K+1):
for j in range(i,K+1,i):
Z[i]+=X[j]*Mebius[j//i]
ans=0
for i in range(1,K+1):
ans+=Z[i]*i
ans%=mod
print(ans)
'''
P(G%d==0)
Gがd,2d,3d,...の可能性がある
P(d)-P(2d)-P(3d)-P(5d)+P(6d)-P(7d)
''' | '''
@sksshivam007 - Template 1.0
'''
import sys, re, math
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx): return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))[::-1]
toret = {}
for tup in temp:
toret[tup[0]] = tup[1]
return toret
def sortDictWithKey(passedDic):
return dict(OrderedDict(sorted(passedDic.items())))
INF = float('inf')
mod = 10 ** 9 + 7
n, k = MAP()
a = [0]*(k+1)
for i in range(k, 0, -1):
temp = pow((k//i), n, mod)
ans = temp%mod
for j in range(2, k//i + 1):
ans -= a[j*i]%mod
a[i] = ans%mod
final = 0
for i in range(len(a)):
final+=(a[i]*i)%mod
print(final%mod) | 1 | 36,812,531,557,308 | null | 176 | 176 |
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
import sys,bisect,string,math,time,functools,random
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
org_inp=[];g=[[] for i in range(n)]
for i in range(E):
inp=LI();org_inp.append(inp)
if index==0:inp[0]-=1;inp[1]-=1
if len(inp)==2:
a,b=inp;g[a].append(b)
if not Directed:g[b].append(a)
elif len(inp)==3:
a,b,c=inp;aa=(inp[0],inp[2]);bb=(inp[1],inp[2]);g[a].append(bb)
if not Directed:g[b].append(aa)
return g,org_inp
def GGI(h,w,boundary=1,search=[],replacement_of_found='.',mp_def={'#':1,'.':0}):
#h,w,g,sg=GGI(h,w,boundary=1,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage
mp=[boundary]*(w+2);found={}
for i in range(h):
s=input()
for char in search:
if char in s:
found[char]=((i+1)*(w+2)+s.index(char)+1)
mp_def[char]=mp_def[replacement_of_found]
mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
mp+=[boundary]*(w+2)
return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(k,n=2):return [[tb//(n**bt)%n for bt in range(k)] for tb in range(n**k)]
def show(*inp,end='\n'):
if show_flg:print(*inp,end=end)
def show2d(g,h,w):
for i in range(h):show(g[i*w:i*w+w])
YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()
def ran_input():
n=random.randint(4,16)
rmin,rmax=1,10
a=[random.randint(rmin,rmax) for _ in range(n)]
return n,a
show_flg=False
show_flg=True
ans=0
def gcj(t,*x):
print("Case #"+str(t)+":",*x)
return
n,t=LI()
N=6001
N=31
dp=[[0]*t for i in range(n+1)]
c=[]
for i in range(n):
a,b=LI()
c+=[(a,b)]
c.sort(key=lambda x:x[0]*4000-x[1])
for i in range(n):
a,b=c[i]
ans=max(ans,dp[i][-1]+b)
for j in range(t):
dp[i+1][j]=max(dp[i+1][j],dp[i][j])
if j+a<t:
dp[i+1][j+a]=max(dp[i][j]+b,dp[i][j+a])
print(ans) | def LinearSearch(A,n,key):
i = 0
A[n] = key
while A[i] != key:
i += 1
return i != n
N = int(input())
S = [int(x) for x in input().split(" ")]
S.append(None)
q = int(input())
T = [int(x) for x in input().split(" ")]
count = 0
for key in T:
if LinearSearch(S,N,key):
count += 1
print(count)
| 0 | null | 76,056,429,203,040 | 282 | 22 |
import math
while True:
n = int(input())
if(n == 0):
exit()
else:
s = [int(x) for x in input().split()]
m = sum(s)/len(s)
for i in range(n):
s [i] = (s[i] - m)**2
print("%.5f" % (math.sqrt(sum(s)/len(s)))) | import sys
import math
import collections
def set_debug(debug_mode=False):
if debug_mode:
fin = open('input.txt', 'r')
sys.stdin = fin
def int_input():
return list(map(int, input().split()))
def get(s):
return str(s % 9) + '9' * (s // 9)
if __name__ == '__main__':
# set_debug(True)
# t = int(input())
t = 1
for ti in range(1, t + 1):
n = int(input())
A = int_input()
cur = 0
for x in A:
cur = x ^ cur
res = []
for x in A:
res.append(cur ^ x)
print(*res)
| 0 | null | 6,283,532,012,992 | 31 | 123 |
a, b, k = list(map(int, input().split(' ')))
print(max(0, a-k), max(0, b-max(0, k-a))) | A, B, K = map(int, input().split())
A_after = 0
B_after = 0
if A - K >= 0:
A_after = A - K
B_after = B
elif A + B - K >= 0:
B_after = B - (K - A)
print(A_after, B_after) | 1 | 104,652,433,384,910 | null | 249 | 249 |
S,T = input().split()
A,B = (int(x) for x in input().split())
U = input()
if U == S:
A -= 1
print(('{} {}'.format(A,B)))
else:
B -= 1
print(('{} {}'.format(A,B))) | n, k = map(int,input().split())
p = list(map(lambda x:int(x)+1,input().split()))
s = [0]*(n+1)
for i in range(n):
s[i+1] = s[i] + p[i]
res = 0
for i in range(n-k+1):
res = max(res,s[i+k]-s[i])
print(res/2) | 0 | null | 73,526,660,588,500 | 220 | 223 |
N = input()
l = len(N)
# print(N[l-1])
k = N[l-1]
if k == '2' or k == '4' or k == '5' or k == '7' or k == '9':
print('hon')
elif k == '0' or k == '1' or k == '6' or k == '8':
print('pon')
elif k == '3':
print('bon') | N,T=map(int,input().split())
G=[list(map(int,input().split())) for _ in range(N)]
G.sort()
dp=[0]*(60000)
for g in G:
for i in range(T-1,-1,-1):
dp[i+g[0]]=max(dp[i+g[0]],dp[i]+g[1])
print(max(dp))
| 0 | null | 85,520,973,924,500 | 142 | 282 |
N = input()
n = map(int,raw_input().split(' '))
c = 0
for i in range(0,N-1):
for j in range(1,N-i):
if n[j-1] > n[j]:
temp = n[j-1]
n[j-1] = n[j]
n[j] = temp
c += 1
print " ".join(str(i) for i in n)
print c | n = int(input())
s = input().split(" ")
nums = list(map(int,s))
flag = 1
koukan = 0
while flag:
flag = 0
for i in range(n-1, 0, -1):
if nums[i] < nums[i-1]:
w = nums[i]
nums[i] = nums[i-1]
nums[i-1] = w
koukan += 1
flag = 1
for i in range(n):
if i == n-1:
print(nums[i])
else:
print(nums[i],end=" ")
print(koukan) | 1 | 15,584,741,770 | null | 14 | 14 |
a,b,c = list(map(int,input().split(" ")))
div=0
for i in range(a,b+1):
if c % i == 0:
div += 1
print(div) | a, b, m = map(int, input().split())
a_l = list(map(int, input().split()))
b_l = list(map(int, input().split()))
x_y_c = [ list(map(int, input().split())) for _ in range(m) ]
ans = min(a_l) + min(b_l)
for x,y,c in x_y_c:
ans = min(a_l[x-1]+b_l[y-1]-c, ans)
print(ans) | 0 | null | 27,310,374,486,340 | 44 | 200 |
matrix = []
vector = []
n, m = [int(x) for x in input().split()]
for i in range(n):
matrix.append([int(x) for x in input().split()])
for i in range(m):
vector.append(int(input()))
for i in range(n):
sum = 0
for j in range(m):
sum += matrix[i][j] * vector[j]
print(sum) | from collections import deque
n = int(input())
G = [[0]*n for _ in range(n)]
for _ in range(n):
u, k, *V = map(int, input().split())
if k == 0:
continue
else:
for v in V:
G[u-1][v-1] = 1
def bfs(u=0):
Q = deque([])
color = ['White']*n
d = [-1]*n
d[0] = 0
Q.append(u)
while Q:
u = Q.popleft()
for v in range(n):
if G[u][v] == 1 and color[v] == 'White':
if d[v] != -1:
continue
color[v] = 'Gray'
d[v] = d[u] + 1
Q.append(v)
color[u] = 'Black'
return d
D = bfs()
for i in range(n):
print('{} {}'.format(i+1, D[i]))
| 0 | null | 585,224,965,468 | 56 | 9 |
N = int(input())
dic = {}
for i in range (N):
s = input()
if s in dic:
dic[s] += 1
else:
dic[s] = 1
sai = max(dic.values())
for j in sorted(k for k in dic if dic[k] == sai):
print(j) | import sys
readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)
def main():
n, m = map(int, readline().split())
s = input()
t = [0] * (n + 1)
cur = n
for i in range(n, -1, -1):
if s[i] == "0":
cur = i
t[i] = cur
else:
t[i] = cur
res = []
i = n
while i > 0:
nx = max(0, i - m)
if t[nx] == i:
return print(-1)
else:
res.append(i - t[nx])
i = t[nx]
print(*res[::-1])
if __name__ == '__main__':
main()
| 0 | null | 104,253,488,584,742 | 218 | 274 |
n=int(input())#nはデータセットの数
for i in range(n):#n回繰り返す
edge=input().split()#入力
edge=[int(j) for j in edge]#入力
edge.sort()#ここでedge[2]が最大になる
if(edge[0]**2+edge[1]**2==edge[2]**2):#直角三角形かどうか
print("YES")
else:#そうでないなら
print("NO") | #!/usr/bin/python
import sys
t = raw_input()
for i in range(int(t)):
x = [int(s) for s in raw_input().split()]
x.sort()
if x[0] ** 2 + x[1] ** 2 == x[2] ** 2:
print "YES"
else:
print "NO" | 1 | 221,894,900 | null | 4 | 4 |
N = int(input())
deg = [0 for _ in range(N)]
edges = [[] for _ in range(N - 1)]
a = []
for i in range(N - 1):
in1, in2 = map(int, input().split())
a.append([in1, in2, i])
a = sorted(a, key = lambda x: x[0])
for i in range(N - 1):
edges[i] = [a[i][0] - 1, a[i][1] - 1, a[i][2]]
deg[a[i][0] - 1] += 1
deg[a[i][1] - 1] += 1
deg_max = max(deg)
print(deg_max)
co = [0 for _ in range(N)]
ans = [0 for _ in range(N - 1)]
for i in range(N - 1):
a = edges[i][0]
b = edges[i][1]
temp = 1 + (co[a] % deg_max)
co[a] = temp
co[b] = temp
ans[edges[i][2]] = temp
for i in range(N - 1): print(ans[i]) | import queue
n = int(input())
e = []
f = [{} for i in range(n)]
for i in range(n-1):
a,b = map(int, input().split())
a-=1
b-=1
e.append([a,b])
f[a][b]=0
f[b][a]=0
k = 0
for i in range(n-1):
k = max(k,len(f[i]))
q = queue.Queue()
q.put(0)
used = [[0] for i in range(n)]
while not q.empty():
p = q.get()
for key,c in f[p].items():
if c == 0:
if used[p][-1]<k:
col = used[p][-1]+1
else:
col = 1
f[p][key] = col
f[key][p] = col
used[p].append(col)
used[key].append(col)
q.put(key)
print(k)
for a,b in e:
print(max(f[a][b],f[b][a]))
| 1 | 136,484,893,029,980 | null | 272 | 272 |
n = int(input())
print(n//2 + n%2) | n = int(input())
print(int(n/2)) if n%2 == 0 else print(int(n/2+1))
| 1 | 58,950,700,446,740 | null | 206 | 206 |
S = list(map(str,input()))
if S[0] != S[1] or S[1] != S[2]:
print("Yes")
else:
print("No") | import itertools
n, m, q = map(int, input().split())
lst = []
for _ in range(q):
l = [int(i) for i in input().split()]
lst.append(l)
lists = list(itertools.combinations_with_replacement(range(1, m+1), n))
#print(lists)
max_point = 0
for each in lists:
point = 0
for i in range(q):
l = lst[i]
a = l[0] - 1
b = l[1] - 1
c = l[2]
if each[b] - each[a] == c:
point += l[3]
if point > max_point:
max_point = point
print(max_point) | 0 | null | 41,139,245,552,960 | 201 | 160 |
s = str(input())
if 1 <= s.count('AB') or 1 <= s.count('BA'):
print('Yes')
else:
print('No') | flg = len(set(input())) == 2
print('Yes' if flg else 'No')
| 1 | 54,811,367,821,618 | null | 201 | 201 |
n,k=map(int,input().split())
p=list(map(int,input().split()))
dp=[0]*(n-k+1)
dp[0]=sum(p[:k])
for i in range(n-k):
dp[i+1]=dp[i]+p[k+i]-p[i]
print((max(dp)+k)/2) | N = int(input())
for i in range(10):
pay = (i + 1) * 1000
if(pay >= N):
break
if(pay < N):
print("たりません")
else:
print(pay - N) | 0 | null | 41,738,625,777,860 | 223 | 108 |
import sys
input = sys.stdin.readline
P = 2019
def main():
S = input().rstrip()
N = len(S)
count = [0] * P
count[0] += 1
T = 0
for i in range(N):
T = (T + int(S[(N - 1) - i]) * pow(10, i, mod=P)) % P
count[T] += 1
ans = 0
for k in count:
ans = (ans + k * (k - 1) // 2)
print(ans)
if __name__ == "__main__":
main()
| N = int(input())
A = list(map(int,input().split()))
for a in A:
if a%2==0 and a%3!=0 and a%5!=0:
print("DENIED")
exit()
print("APPROVED") | 0 | null | 50,161,474,477,420 | 166 | 217 |
import numpy as np
T1, T2 = map(int, input().split())
A1, A2 = map(int, input().split())
B1, B2 = map(int, input().split())
S1 = (A1 - B1) * T1
S2 = (A2 - B2) * T2
if (S1 + S2) == 0:
print('infinity')
elif np.sign(S1) == np.sign(S2):
print(0)
elif abs(S1) > abs(S2):
print(0)
else:
z = 1 + ((abs(S1)) // abs(S1 + S2)) * 2
if (abs(S1)) % abs(S1 + S2) == 0:
z = z -1
print(z)
| import sys
def main():
i = 1
while True:
x = int(sys.stdin.readline())
if x != 0:
print("Case {0}: {1}".format(i, x))
i += 1
else:
break
return
if __name__ == '__main__':
main()
| 0 | null | 66,297,379,171,232 | 269 | 42 |
n, k = [int(x) for x in input().split()]
p_list = sorted([int(x) for x in input().split()])
print(sum(p_list[:k])) | L, R = input().split()
huga = list(map(int, input().split()))
i=0
gou=0
huga.sort()
for a in range(int(R)):
gou=gou+huga[i]
i+=1
print(gou) | 1 | 11,600,988,618,560 | null | 120 | 120 |
import decimal
def main():
A, B = map(decimal.Decimal,input().split())
if A == 0:
return 0
else:
AB = A*B
return int(AB)
print(main()) | import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)
A, B = input().split()
B = int(''.join(B.split('.')))
print(int(A)*B//100) | 1 | 16,389,531,003,484 | null | 135 | 135 |
N = int(input())
S = input()
cnt = 0
for i in range(len(S)-2):
if S[i:i+3] == "ABC":
cnt += 1
print(cnt)
| n = int(input())
s = input()
print(len(s.split('ABC')) - 1) | 1 | 99,643,729,793,400 | null | 245 | 245 |
n=int(input())
def dfs(s):
if len(s)==n:
print(s)
else:
for i in range(ord('a'),max(map(ord,list(s)))+2):
dfs(s+chr(i))
dfs('a') | 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 # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
# d = m - k[i] - k[j]
# if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも!!
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
def readInts():
return list(map(int,input().split()))
def main():
n = int(input())
# 一番大きいものは何か、それを保存してdfs
def dfs(cnt, s):
if cnt == n:
print(s)
return
biggest = 'a'
c = 0
while c < len(s):
if s[c] == biggest:
biggest = chr(ord(biggest)+1)
c += 1
else:
c += 1
for i in range(0,ord(biggest) - ord('a') + 1):
sc = chr(ord('a')+i)
s += sc
dfs(cnt + 1, s)
s = s[:-1]
dfs(0,"")
if __name__ == '__main__':
main()
| 1 | 52,536,551,416,216 | null | 198 | 198 |
a,v,b,w,t=map(int,open(0).read().split())
if (a<b and a+v*t>=b+w*t)or(b<a and b-w*t>=a-v*t):print("YES")
else:print("NO") | import sys
A,V = map(int, input().split())
B,W = map(int, input().split())
T = int(input())
#これO(1)で解けそう。
# スピードが同じ or 逃げる方のスピードが速いと無理
if V <= W:
print("NO")
sys.exit()
# 鬼の方がスピードが速い場合で場合訳
distance_AB = abs(A-B)
speed_AB = abs(V-W)
if speed_AB * T >= distance_AB:
print("YES")
else:
print("NO") | 1 | 15,104,064,227,200 | null | 131 | 131 |
# coding: utf-8
import sys
from fractions import gcd
import numpy as np
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
MOD = 10 ** 9 + 7
N = ir()
A = lr()
lcm = 1
for a in A:
lcm *= a // gcd(lcm, a)
A = np.array(A)
answer = (lcm // A).sum() % MOD
print(answer % MOD)
# np.int64とint型の違いに注意
| def main():
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
import math
#from math import gcd
#inf = 10**17
#mod = 10**9 + 7
n,k,c = map(int, input().split())
s = input().rstrip()
left = [0]*n
day = 0
temp = 0
while day < n:
if s[day] == 'o':
temp += 1
left[day] = temp
for i in range(c):
if day+i+1 < n:
left[day+i+1] = temp
day += c
else:
left[day] = temp
day += 1
right = [0]*n
day = n-1
temp = 0
while 0 <= day:
if s[day] == 'o':
temp += 1
right[day] = temp
for i in range(c):
if day-i-1 >= 0:
right[day-i-1] = temp
day -= c
else:
right[day] = temp
day -= 1
res = []
for i in range(n):
if s[i] == 'o':
if i-c-1 < 0:
pre = 0
else:
pre = left[i-c-1]
if i+c+1 >= n:
pos = 0
else:
pos = right[i+c+1]
if pre + pos == k-1:
res.append(i+1)
for i in range(len(res)):
if i-1>=0:
l = res[i-1]
else:
l = -1000000
if i+1<len(res):
r = res[i+1]
else:
r = 10000000
if res[i]-l>c and r-res[i] > c:
print(res[i])
if __name__ == '__main__':
main() | 0 | null | 63,800,731,471,640 | 235 | 182 |
import math
a, b, x = map(int, input().split())
if x == a**2*b:
print(0)
elif x >= a**2*b/2:
print(90 - math.degrees(math.atan(a**3/(2*a**2*b-2*x))))
else:
print((90 - math.degrees(math.atan(2*x/(a*b**2)))))
| N=int(input())
A=0
B=0
C=0
D=0
for i in range(N+1):
A+=i
for i in range(N+1):
if i % 3 == 0:
B+=i
for i in range(N+1):
if i % 5 == 0:
C+=i
for i in range(N+1):
if i % 15 == 0:
D+=i
print(A-B-C+D) | 0 | null | 99,180,116,794,780 | 289 | 173 |
#162D
#RGB Triplets
import collections
n=int(input())
S=input()
s=collections.Counter(S)
ans=s['R']*s['G']*s['B']
for i in range(n):
for d in range(n):
j=i+d
k=j+d
if k>n-1:
break
if S[i]!=S[j] and S[j]!=S[k] and S[k]!=S[i]:
ans-=1
print(ans) | def fibonacci(n, memo=None):
if memo==None:
memo = [None]*n
if n<=1:
return 1
else:
if memo[n-2]==None:
memo[n-2] = fibonacci(n-2, memo)
if memo[n-1]==None:
memo[n-1] = fibonacci(n-1, memo)
return memo[n-1] + memo[n-2]
n = int(input())
print(fibonacci(n)) | 0 | null | 18,209,037,712,290 | 175 | 7 |
n, m = map(int, input().split())
mat = [map(int,input().split()) for i in range(n)]
vec = [int(input()) for i in range(m)]
for row in mat:
print(sum([a*b for (a,b) in zip(row, vec)])) | N = int(input())
S = input()
A = ['']
for i in S:
if i != A[-1]:
A.append(i)
print(len(''.join(A))) | 0 | null | 85,399,925,786,248 | 56 | 293 |
import collections
N = int(input())
S = []
for i in range(N):
s = input()
S.append(s)
c = collections.Counter(S)
values, counts = zip(*c.most_common())
print(len(values)) | line = input()
words = line.split()
nums = list(map(int, words))
a = nums[0]
b = nums[1]
d = a // b
r = a % b
f = a / b
f = round(f,5)
print ("{0} {1} {2}".format(d,r,f)) | 0 | null | 15,558,080,658,492 | 165 | 45 |
il = [int(k) for k in input().split()]
K = il[0]
X = il[1]
if 500 * K >= X:
print("Yes")
else:
print("No")
| import sys
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
read = sys.stdin.buffer.read
sys.setrecursionlimit(10 ** 7)
INF = float('inf')
H, W = map(int, readline().split())
masu = []
for _ in range(H):
masu.append(readline().rstrip().decode('utf-8'))
# print(masu)
dp = [[INF]*W for _ in range(H)]
dp[0][0] = int(masu[0][0] == "#")
dd = [(1, 0), (0, 1)]
# 配るDP
for i in range(H):
for j in range(W):
for dx, dy in dd:
ni = i + dy
nj = j + dx
# はみ出す場合
if (ni >= H or nj >= W):
continue
add = 0
if masu[ni][nj] == "#" and masu[i][j] == ".":
add = 1
dp[ni][nj] = min(dp[ni][nj], dp[i][j] + add)
# print(dp)
ans = dp[H-1][W-1]
print(ans) | 0 | null | 73,766,905,006,322 | 244 | 194 |
n = int(input())
ans = ''
for i in range(13):
if n >= 26 and n%26 == 0:
ans = 'z' + ans
n -= 26
else:
ans = chr(97 -1 + n%26) + ans
n -= n%26
n = n //26
print(ans.replace("`", ""))
| N=int(input())
if N==1:
print('{:.10f}'.format(1))
elif N%2==0:
print('{:.10f}'.format(0.5))
else:
print('{:.10f}'.format((N+1)/(2*N))) | 0 | null | 94,971,437,508,198 | 121 | 297 |
n = int(input())
a_list = list(map(int, input().split()))
sum_l = sum(a_list)
ans = 0
for i in range(n-1):
sum_l -= a_list[i]
ans += sum_l * a_list[i]
print(ans % 1000000007) | def main() :
N = int(input())
A = list(map(int, input().split()))
sum = 0
t = A[0]
for i in range(1, N):
if A[i] <= t:
sum += t - A[i]
else:
t = A[i]
print(sum)
if __name__ == "__main__":
main() | 0 | null | 4,217,571,394,260 | 83 | 88 |
def main():
s = int(input())
if s < 3:
print(0)
else:
total = [0]*(s+1)
total[3] = 1
mod = 10**9+7
for i in range(4, s+1):
total[i] = (total[i-3] + 1) + total[i-1]
total[i] %= mod
print((total[s-3]+1)%mod)
if __name__ == "__main__":
main() | n, k = map(int, input().split())
enemy = list(map(int, input().split()))
enemy.sort(reverse=True)
if n <= k :
print(0)
else :
for i in range(k) :
enemy[i] = 0
print(sum(enemy))
| 0 | null | 41,041,995,902,140 | 79 | 227 |
n,k = map(int, input().split())
ans = 0
while n > 0:
n /= k
n = int(n)
ans += 1
print(ans)
| n = int(input())
m = (n + 1) // 2
print(m) | 0 | null | 61,581,983,319,184 | 212 | 206 |
from sys import stdin
n, m, l = [int(x) for x in stdin.readline().rstrip().split()]
a = [[int(x) for x in stdin.readline().rstrip().split()] for _ in range(n)]
b = [[int(x) for x in stdin.readline().rstrip().split()] for _ in range(m)]
c = [[0] *l for _ in range(n)]
for i in range(n):
for j in range(l):
for k in range(m):
c[i][j] += a[i][k]*b[k][j]
for i in range(n):
print(*c[i])
| n, m, ll = map(int, input().split())
a = []
b = []
for i in range(n):
a.append(list(map(int, input().split())))
for i in range(m):
b.append(list(map(int, input().split())))
for i in range(n):
prt = []
for j in range(ll):
s = 0
for k in range(m):
s += a[i][k] * b[k][j]
prt.append(s)
print(*prt)
| 1 | 1,436,004,546,418 | null | 60 | 60 |
x = int(raw_input())
print "%d" % x**3 | MOD = 10**9 + 7
MAX = 10**6
X, Y = map(int, input().split())
m, n = 2*Y-X, 2*X-Y
if (X+Y) % 3 != 0 or m%3!=0 or n%3!=0 or m<0 or n<0:
print(0)
exit()
m //= 3
n //= 3
fac, inv = [0]*MAX, [0]*MAX
fac[0] = 1
for i in range(1, MAX):
fac[i] = fac[i-1] * i % MOD
inv[-1] = pow(fac[-1], MOD-2, MOD)
for i in range(MAX-2, 0, -1):
inv[i] = inv[i+1] * (i+1) % MOD
def com(n, k):
if n<k:return 0
if n<0 or k<0:return 0
if n==k or k==0:return 1
return int(fac[n] * (inv[k]*inv[n-k]%MOD) % MOD)
print(com(n=m+n,k=n)) | 0 | null | 74,838,574,761,142 | 35 | 281 |
n,k = map(int,input().split(' '))
l = list(map(int,input().split(' ')))
count = 0
for i in l:
if i >= k:
count += 1
else:
continue
print(count) | import math
cnt = 0
for i in range(int(input())):
x = int(input())
flg = False # なんらかの数で割り切れるかどうか
if x == 1:
continue
if x == 2:
cnt += 1
continue
for k in range(2, math.floor(math.sqrt(x))+1):
if not(x % k):
flg = True
break
if not flg:
cnt += 1
print(cnt)
| 0 | null | 89,272,073,677,398 | 298 | 12 |
while 1:
x,y,z=raw_input().split()
x=int(x)
z=int(z)
if(y=='?'):
break
if(y=='+'):
print x+z
if(y=='-'):
print x-z
if(y=='/'):
print x/z
if(y=='%'):
print x%z
if(y=='*'):
print x*z | fib = [1]*100
for i in range(2,100):
fib[i] = fib[i-1] + fib[i-2]
print(fib[int(input())])
| 0 | null | 346,299,104,632 | 47 | 7 |
n = int(input())
A = list(map(int,input().split()))
ans = [0]*n
for i in range(n):
ans[A[i] - 1] = str(i + 1)
Ans = ' '.join(ans)
print(Ans) | N, K = map(int, input().split())
h = list(map(int, input().split()))
h = sorted(h)
if K == 0:
print(sum(h))
else:
print(sum(h[:-K])) | 0 | null | 129,603,164,284,572 | 299 | 227 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.