code1
stringlengths 17
427k
| code2
stringlengths 17
427k
| similar
int64 0
1
| pair_id
int64 2
181,637B
⌀ | question_pair_id
float64 3.7M
180,677B
⌀ | code1_group
int64 1
299
| code2_group
int64 1
299
|
---|---|---|---|---|---|---|
import string
L = string.split(raw_input())
a = int(L[0])
b = int(L[1])
if a == b:
print "a == b"
elif a > b:
print "a > b"
elif a < b:
print "a < b" | a, b = [int(x) for x in raw_input().split(" ")]
if a > b:
print("a > b")
elif a < b:
print("a < b")
else:
print("a == b") | 1 | 366,502,102,240 | null | 38 | 38 |
# -*- coding: utf-8 -*-
"""
D - Knight
https://atcoder.jp/contests/abc145/tasks/abc145_d
"""
import sys
def modinv(a, m):
b, u, v = m, 1, 0
while b:
t = a // b
a -= t * b
a, b = b, a
u -= t * v
u, v = v, u
u %= m
return u if u >= 0 else u + m
def solve(X, Y):
MOD = 10**9 + 7
if (X + Y) % 3:
return 0
n = (X - 2 * Y) / -3.0
m = (Y - 2 * X) / -3.0
if not n.is_integer() or not m.is_integer() or n < 0 or m < 0:
return 0
n, m = int(n), int(m)
x1 = 1
for i in range(2, n + m + 1):
x1 = (x1 * i) % MOD
x2 = 1
for i in range(2, n+1):
x2 = (x2 * i) % MOD
for i in range(2, m+1):
x2 = (x2 * i) % MOD
ans = (x1 * modinv(x2, MOD)) % MOD
return ans
def main(args):
X, Y = map(int, input().split())
ans = solve(X, Y)
print(ans)
if __name__ == '__main__':
main(sys.argv[1:])
| def nCr(n, r, mod):
x, y = 1, 1
for i in range(1, r+1):
x = x*(n+1-i)%mod
y = y*i%mod
return x*pow(y, mod-2, mod)%mod
a,b = map(int,input().split())
s=2*a-b
t=2*b-a
if s%3!=0 or s<0 or t%3!=0 or t<0:
print(0)
else:
print(nCr((s+t)//3,(t//3),10**9+7)) | 1 | 150,062,638,744,490 | null | 281 | 281 |
import numpy as np
H,N= map(int, input().split())
m = np.array([list(map(int, input().split())) for _ in range(N)])
max_a = np.max(m[:,0])
dp = np.zeros(H+max_a+1, dtype='i8')
for i in range(max_a+1, H+max_a+1):
dp[i] = np.min(dp[i-m[:,0]] + m[:,1])
print(dp[H+max_a]) | H, N = map(int, input().split())
dp = [10 ** 9] * (H + 1)
dp[0] = 0
for _ in range(N):
a, b = map(int, input().split())
for i in range(H):
idx = min(H, i + a)
dp[idx] = min(dp[idx], dp[i] + b)
print(dp[H])
| 1 | 81,216,538,561,288 | null | 229 | 229 |
week=int(input())
money=100000
for i in range(week):
money=money*1.05
if money%1000!=0:
money=1000*(money//1000+1)
print(int(money)) | # coding: utf-8
import math
n = int(raw_input())
ans = 100000
for i in range(n):
ans = ans * 1.05
q = math.ceil(ans / 1000)
ans = q * 1000
print int(ans) | 1 | 984,874,348 | null | 6 | 6 |
import sys
readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)
def main():
S = input()
l = len(S)
print("x" * l)
if __name__ == '__main__':
main()
|
def main():
S = input()
print("x"*len(S))
if __name__ == "__main__":
main() | 1 | 72,753,434,252,876 | null | 221 | 221 |
MOD = 2019
def solve(S):
N = len(S)
dp = [0 for _ in range(MOD)]
tmp = 0
ret = 0
for i in range(N - 1, -1, -1):
m = (tmp + int(S[i]) * pow(10, N - i - 1, MOD)) % MOD
ret += dp[m]
dp[m] += 1
tmp = m
ret += dp[0]
return ret
if __name__ == "__main__":
S = input()
print(solve(S)) | s = input()
t = s[::-1]
n = len(s)
resid = [0] * 2019
resid[0] = 1
csum = 0
powoften = 1
for i in range(n):
csum = (csum + int(t[i]) * powoften) % 2019
powoften = (10 * powoften) % 2019
resid[csum] += 1
ans = 0
for i in range(2019):
ans += resid[i] * (resid[i] - 1) // 2
print(ans) | 1 | 30,833,841,982,580 | null | 166 | 166 |
import os, sys, re, math
N = (int(input()))
S = input()
T = S.replace('ABC', '')
print((len(S) - len(T)) // 3)
| x = int(input())
n = input()
t = "ABC"
c = 0;
for i in range(x-2):
if n[i] == 'A' and n[i+1] =='B' and n[i+2] == 'C':
c+=1
print(c)
| 1 | 99,526,304,940,812 | null | 245 | 245 |
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()
def resolve():
N, X, M = LI()
A = []
seen = set()
tmp = X
head_idx = -1
while True:
A.append(tmp)
seen.add(tmp)
tmp = pow(tmp, 2, M)
if tmp in seen:
head_idx = A.index(tmp)
break
# print(A, head_idx)
cnt = [0] * len(A)
for i in range(len(A)):
if i < head_idx:
if i <= N:
cnt[i] = 1
else:
l = len(A) - head_idx
cnt[i] = (N - head_idx) // l
for i in range(head_idx, head_idx + (N - head_idx) % l):
cnt[i] += 1
# print(cnt)
ans = sum([a * c for a, c in zip(A, cnt)])
print(ans)
if __name__ == '__main__':
resolve()
| n = int(input())
a = []
for i in range(1, n+1):
if i%3 == 0 or i%5 == 0:
continue
else:
a.append(i)
print(sum(a)) | 0 | null | 18,748,238,757,942 | 75 | 173 |
a, b, c = map(int, input().split())
a, b = b, a
a, c = c, a
print(f'{a} {b} {c}') | x,y,z=map(int,input().split())
li=[z,x,y]
print(" ".join(map(str,li))) | 1 | 38,286,906,760,230 | null | 178 | 178 |
N=int(input())
import math
print(360//math.gcd(360,N))
| X = int(input())
i = 1
while (360*i) % X != 0:
i += 1
ans = 360*i//X
print(ans)
| 1 | 13,098,353,238,042 | null | 125 | 125 |
N = input()
S = 0
for m in N:
S += int(m)
S %= 9
if S == 0:
print('Yes')
else:
print('No') | count = input()
#print(len(count))
num = 0
for i in range(len(count)):
num += int(count[i])
if num % 9 == 0:
print("Yes")
else:
print("No") | 1 | 4,453,123,775,840 | null | 87 | 87 |
st = input()
if(st[-1]=='s'):
out = st+"es"
else:
out=st+"s"
print(out) | N = int(input())
def S(x):
return(x*(x+1)//2)
print(S(N) - 3*S(N//3) - 5*S(N//5) + 15*S(N//15)) | 0 | null | 18,584,116,000,254 | 71 | 173 |
n = input()
print('Yes' if '7' in n else 'No') | from sys import exit
import math
import collections
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))
n,k = mi()
h = li()
h.sort()
h.reverse()
sum = 0
for i in range(k,n,1):
sum += h[i]
print(sum)
| 0 | null | 56,893,384,874,994 | 172 | 227 |
n, m = map(int, input().split())
ac = [0] * n
wa = [0] * n
for _ in range(m):
p, s = input().split()
if s == 'AC':
ac[int(p) - 1] = 1
elif ac[int(p) - 1] == 0:
wa[int(p) - 1] += 1
for i in range(n):
if ac[i] == 0:
wa[i] = 0
print(sum(ac), sum(wa)) | n, m = map(int, input().split())
submissions = [list(input().split()) for _ in range(m)]
count_penalty = [0] * (n + 1)
count_ac = [0] * (n + 1)
for i in range(m):
ploblem = int(submissions[i][0])
if submissions[i][1] == "AC":
count_ac[ploblem] = 1
elif count_ac[ploblem] != 1 and submissions[i][1] == "WA":
count_penalty[ploblem] += 1
for i in range(n + 1):
if count_ac[i] != 1:
count_penalty[i] = 0
print("{} {}".format(count_ac.count(1), sum(count_penalty)))
| 1 | 93,767,755,158,360 | null | 240 | 240 |
import math
A, B = map(str,input().split(" "))
B_ = int(B.split(".")[0])*100 + int(B.split(".")[1])
print(int(A) * B_ // 100)
| n = input()
a = int(n)
print(a**2) | 0 | null | 80,951,420,126,458 | 135 | 278 |
a=input()
print(str.swapcase(a))
| import sys
prm = sys.stdin.readline()
S = int(prm)
h = S / (60 * 60);
S = S % (60 * 60);
m = S / 60;
s = S % 60;
print str(h)+':'+str(m)+':'+str(s) | 0 | null | 937,345,556,378 | 61 | 37 |
N,K = map(int,input().split())
if N<=K :
print(0)
else :
H = list(map(int,input().split()))
H.sort()
if 0<K :
del H[-K:]
print(sum(H)) | #!/usr/bin/env python3
import sys
from itertools import chain
def solve(N: int, K: int, H: "List[int]"):
H = sorted(H, reverse=True)
return sum(H[K:])
def main():
tokens = chain(*(line.split() for line in sys.stdin))
N = int(next(tokens)) # type: int
K = int(next(tokens)) # type: int
H = [int(next(tokens)) for _ in range(N)] # type: "List[int]"
answer = solve(N, K, H)
print(answer)
if __name__ == "__main__":
main()
| 1 | 78,559,465,405,788 | null | 227 | 227 |
n = int(input())
a = list(map(int, input().split()))
count = 0
for i in range(n-1):
min_j = i
for j in range(i+1, n):
if a[j] < a[min_j]:
min_j = j
if min_j != i:
a[i], a[min_j] = a[min_j], a[i]
count += 1
print(*a)
print(count)
| #ALDS1_2-B Sort 1 - Selection Sort
def selectionSort(A,N):
c=0
for i in range(N):
minj = i
j=i
while j<N:
if(int(A[j])<int(A[minj])):
minj = j
j+=1
if(i!=minj):
A[i],A[minj]=A[minj],A[i]
c+=1
return c
N=int(input())
A=input().split()
c=selectionSort(A,N)
S=""
for i in range(N-1):
S+=A[i]+" "
S+=str(A[-1])
print(S)
print(c) | 1 | 18,774,668,132 | null | 15 | 15 |
n = int(input())
a , b = input().split()
ans = ""
for i in range(n):
ans += a[i]
ans += b[i]
print(ans)
| from sys import exit
import math
import collections
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))
n = ii()
s,t = input().split()
for i in range(len(s)):
print(s[i] + t[i] ,end = "") | 1 | 112,206,094,181,972 | null | 255 | 255 |
import collections
N=int(input())
A=list(input().split())
a=collections.Counter(A)
A=[int(i) for i in A]
S=sum(A)
Q=int(input())
for i in range(Q):
B,C=input().split()
if B in a:
b=a[B]
S-=int(B)*b
S+=int(C)*b
del a[B]
if C in a:
a[C]+=b
else:
a[C]=b
print(S)
| N = int(input())
A = list(map(int, input().split()))
Q = int(input())
sum_res = sum(A)
counter = [0 for _ in range(10 ** 5 + 1)]
for a in A:
counter[a] += 1
for _ in range(Q):
B, C = map(int, input().split())
sum_res += (C - B) * counter[B]
counter[C] += counter[B]
counter[B] = 0
print(sum_res)
| 1 | 12,167,119,385,340 | null | 122 | 122 |
N = input()
print('Yes' if '7' in N else 'No') | N, K = map(int, input().split())
LR = [tuple(map(int, input().split())) for _ in range(K)]
MOD = 998244353
class Mint:
__slots__ = ('value')
def __init__(self, value=0):
self.value = value % MOD
if self.value < 0: self.value += MOD
@staticmethod
def get_value(x): return x.value if isinstance(x, Mint) else x
def inverse(self):
a, b = self.value, MOD
u, v = 1, 0
while b:
t = a // b
b, a = a - t * b, b
v, u = u - t * v, v
if u < 0: u += MOD
return u
def __repr__(self): return str(self.value)
def __eq__(self, other): return self.value == other.value
def __neg__(self): return Mint(-self.value)
def __hash__(self): return hash(self.value)
def __bool__(self): return self.value != 0
def __iadd__(self, other):
self.value = (self.value + Mint.get_value(other)) % MOD
return self
def __add__(self, other):
new_obj = Mint(self.value)
new_obj += other
return new_obj
__radd__ = __add__
def __isub__(self, other):
self.value = (self.value - Mint.get_value(other)) % MOD
if self.value < 0: self.value += MOD
return self
def __sub__(self, other):
new_obj = Mint(self.value)
new_obj -= other
return new_obj
def __rsub__(self, other):
new_obj = Mint(Mint.get_value(other))
new_obj -= self
return new_obj
def __imul__(self, other):
self.value = self.value * Mint.get_value(other) % MOD
return self
def __mul__(self, other):
new_obj = Mint(self.value)
new_obj *= other
return new_obj
__rmul__ = __mul__
def __ifloordiv__(self, other):
other = other if isinstance(other, Mint) else Mint(other)
self *= other.inverse()
return self
def __floordiv__(self, other):
new_obj = Mint(self.value)
new_obj //= other
return new_obj
def __rfloordiv__(self, other):
new_obj = Mint(Mint.get_value(other))
new_obj //= self
return new_obj
LR.sort(key=lambda x: x[1])
pl = pr = -1
LR2 = []
for l, r in LR:
if LR2:
pl, pr = LR2.pop()
if l <= pl:
LR2.append((l, r))
elif l <= pr:
LR2.append((pl, r))
else:
LR2.append((pl, pr))
LR2.append((l, r))
else:
LR2.append((l, r))
dp = [Mint() for _ in range(N + 5)]
dp[1] += 1
dp[2] -= 1
for i in range(1, N):
dp[i] += dp[i - 1]
for l, r in LR2:
nl = min(i + l, N + 1)
nr = min(i + r, N + 1)
dp[nl] += dp[i]
dp[nr + 1] -= dp[i]
dp[N] += dp[N - 1]
print(dp[N])
| 0 | null | 18,587,450,913,670 | 172 | 74 |
import sys
from collections import deque
n,m=map(int,input().split())
s=input()
if n<=m:
print(n)
sys.exit()
lst=[0]*(n+1)
for i in range(1,m+1):
if s[i]=="0":
lst[i]=i
left=1
right=m+1
k=0
while left<n:
if s[left]=="0":
while right-left<=m:
if s[right]=="0":
lst[right]=right-left
right+=1
if right==n+1:
k=n
break
left+=1
if left==right or k==n:
break
if lst[n]==0:
print(-1)
else:
ans=deque([])
while k>0:
c=lst[k]
ans.appendleft(c)
k-=c
print(*ans) | #146_F
n, m = map(int, input().split())
s = input()[::-1]
ans = []
flg = True
cur = 0
while cur < n and flg:
for to in range(cur + m, cur, -1):
if to > n:
continue
if s[to] == '0':
ans.append(to - cur)
cur = to
break
if to == cur + 1:
flg = False
if flg:
print(*ans[::-1])
else:
print(-1) | 1 | 139,005,339,878,940 | null | 274 | 274 |
def resolve():
N, T = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]
AB.sort()
dp = [[0] * (T + 1) for _ in range(N + 1)]
for i in range(N):
t, v = AB[i]
for j in range(T + 1):
if t + j <= T:
dp[i + 1][j + t] = max(dp[i + 1][j + t], dp[i][j] + v)
dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
ans = 0
for i, (t, v) in enumerate(AB):
ans = max(ans, dp[i][T - 1] + v)
print(ans)
if __name__ == "__main__":
resolve()
| from itertools import chain
N, T = map(int, input().split())
# A = [0]*(N+1)
# B = [0]*(N+1)
AB = [(0, 0)]
for i in range(1, N+1):
a, b = map(int, input().split())
# A[i] = a
# B[i] = b
AB.append((a, b))
AB.sort()
dp = [[-1]*(6000+1) for _ in range(N+1)]
#dp[i][t]: 注文後にt秒になっている時、i番目までを考慮したとき、
#の最大
dp[0][0] = 0
for i in range(1, N+1):
a, b = AB[i]
for t in range(T):
dp[i][t+a] = max(dp[i][t+a], dp[i-1][t] + b)
dp[i][t] = max(dp[i][t], dp[i-1][t])
print(max(chain.from_iterable(dp))) | 1 | 151,536,133,241,220 | null | 282 | 282 |
n = int(input())
A = list(map(int, input().split()))
MOD = 10**9+7
ans = 0
for i in range(60):
cnt = 0
for a in A:
cnt += a>>i&1
ans += cnt*(n-cnt)*2**i
ans %= MOD
print(ans)
| import numpy as np
MOD = 10 ** 9 + 7
N = int(input())
A = np.array(input().split(), dtype=np.int64)
total = 0
for shamt in range(65):
bits = np.count_nonzero(A & 1)
total += (bits * (N - bits)) << shamt
A >>= 1
if not A.any():
break
print(total % MOD) | 1 | 123,433,023,756,448 | null | 263 | 263 |
N = int(input())
S = input()
if N<4:
print(0)
else:
a = [0] * N
R, G, B = 0, 0, 0
for i in range(N):
if S[i] == "R":
a[i] = 1
R += 1
if S[i] == "G":
a[i] = 2
G += 1
if S[i] == "B":
a[i] = 4
B += 1
rgb = R * G * B
cnt = 0
for i in range(N-2):
for d in range(1, (N-i-1) // 2+1):
if a[i] + a[i+d] + a[i+2*d] == 7:
cnt += 1
print(rgb -cnt)
| N = int(input())
S = input()
total = S.count('R') * S.count('G') * S.count('B')
cnt = 0
for i in range(N):
for j in range(i+1,N):
k = 2 * j - i
if k >= N:
break
if S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
cnt += 1
print(total-cnt) | 1 | 36,039,537,406,602 | null | 175 | 175 |
def main():
n = int(input())
cnt = 0
for i in range(n):
a, b = map(int, input().split())
if a==b: cnt += 1
else: cnt = 0
if cnt==3:
print("Yes")
return
print("No")
return
main() | from itertools import permutations as p
from math import factorial as f
from math import sqrt as s
def func(x1, x2, y1, y2): return s((x2-x1) ** 2 + (y2-y1) ** 2)
N = int(input())
xy = list(list(map(int,input().split())) for _ in range(N))
total = 0
for l in p(range(1, N+1)):
for i in range(N-1):
total += func(xy[l[i]-1][0], xy[l[i+1]-1][0], xy[l[i]-1][1], xy[l[i+1]-1][1])
print(total / f(N)) | 0 | null | 75,161,596,891,460 | 72 | 280 |
n, x, m = map(int, input().split())
lis = set()
loop_lis = []
cnt = 0
while x not in lis:
cnt += 1
lis.add(x)
loop_lis.append(x)
x = pow(x, 2) % m
if cnt == n:
print(sum(lis))
exit()
start = loop_lis.index(x)
length = len(loop_lis) - start
loop_sum = sum(loop_lis[start:])
before = sum(loop_lis[:start])
loop = loop_sum * ((n - start) // length)
remain = sum(loop_lis[start : (start + (n - start) % length)])
print(before + loop + remain)
| from collections import defaultdict
from collections import deque
from collections import Counter
import math
import itertools
def readInt():
return int(input())
def readInts():
return list(map(int, input().split()))
def readChar():
return input()
def readChars():
return input().split()
n,x,m = readInts()
an = x
ans = an
moddict = {an:1}
for i in range(2,n+1):
an = pow(an,2,m)
if an in moddict:
break
else:
moddict[an]=i
ans += an
#print(ans)
if an in moddict:
rep = (n-len(moddict))//(len(moddict)-moddict[an]+1)
rem = (n-len(moddict))%(len(moddict)-moddict[an]+1)
#print(rep,rem)
rep_sum = 0
boo = 0
for key in moddict:
if boo or key==an:
boo = 1
rep_sum+=key
ans += rep_sum*rep
for i in range(rem):
ans+=an
an=pow(an,2,m)
print(ans) | 1 | 2,786,983,482,350 | null | 75 | 75 |
import sys
N = int(input())
cc = list(map(int,input().split()))
dic = set()
for i in cc:
if i in dic:
print('NO')
sys.exit()
else:
dic.add(i)
print('YES') | n=int(input())
a=[int(i) for i in input().split()]
cnt={}
for i in range(n):
cnt[a[i]]=0
ok=1
for i in range(n):
cnt[a[i]]+=1
if cnt[a[i]]==2:
print("NO")
ok=0
break
if ok==1:
print("YES")
| 1 | 73,848,815,827,072 | null | 222 | 222 |
n,k = map(int, input().split())
sunuke = []
for i in range(n):
sunuke.append(1)
for i in range(k):
d = int(input())
a = list(map(int, input().split()))
for j in range(d):
sunuke[a[j]-1] = 0
print(sum(sunuke)) |
N,k = map(int,input().split())
A = [0] * N
#print(A)
#print(type(A))
for okashi_number in range(k):
di = int(input())
D = list(map(int,input().split()))
for x in range(di):
A[D[x]-1]= 1
#print(A)
count = 0
for i in range(N):
if A[i] == 0:
count = count + 1
print(count) | 1 | 24,566,443,209,948 | null | 154 | 154 |
x = input()
s = 0
for i in range(len(x)):
s = s + int(x[i])
if s % 9 == 0:
print("Yes")
else:
print("No") | n, m = map(int, input().split())
if n == 1 or m == 1:
print(1)
elif n*m%2 == 0:
print(n*m//2)
else:
print(n*m//2+1) | 0 | null | 27,540,656,467,392 | 87 | 196 |
import collections
N = int(input())
L = [input() for i in range(N)]
c = collections.Counter(L)
max_L = max(list(c.values()))
keys = [k for k, v in c.items() if v == max_L]
keys.sort()
for key in keys:
print(key)
| A,V=map(int,input().split())
B,W=map(int,input().split())
T=int(input())
v=V-W
l=abs(A-B)
if l<=v*T:
print("YES")
else:
print("NO")
| 0 | null | 42,590,418,382,722 | 218 | 131 |
def resolve():
H, W = list(map(int, input().split()))
S = [list(input()) for _ in range(H)]
import collections
maxdist = 0
for startx in range(H):
for starty in range(W):
if S[startx][starty] == "#":
continue
visited = [[-1 for _ in range(W)] for __ in range(H)]
visited[startx][starty] = 0
q = collections.deque([(startx, starty)])
while q:
x, y = q.pop()
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nx = x + dx
ny = y + dy
if 0 <= nx < H and 0 <= ny < W and S[nx][ny] != "#" and visited[nx][ny] == -1:
visited[nx][ny] = visited[x][y] + 1
q.appendleft((nx, ny))
maxdist = max(maxdist,max(sum(visited, [])))
print(maxdist)
if '__main__' == __name__:
resolve()
| from collections import deque
import numpy as np
# (sx, sy) から (gx, gy) への最短距離を求める
# 辿り着けないと INF
def bfs(sx, sy):
# すべての点を INF で初期化
d = [[float("-inf")] * m for i in range(n)]
# 移動4方向のベクトル
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
# スタート地点をキューに入れ、その点の距離を0にする
que = deque([])
que.append((sx, sy))
d[sx][sy] = 0
# キューが空になるまでループ
while que:
# キューの先頭を取り出す
p = que.popleft()
# 取り出してきた状態がゴールなら探索をやめる
#if p[0] == gx and p[1] == gy:
# break
# 移動4方向をループ
for i in range(4):
# 移動した後の点を (nx, ny) とする
nx = p[0] + dx[i]
ny = p[1] + dy[i]
# 移動が可能かの判定とすでに訪れたことがあるかの判定
# d[nx][ny] != INF なら訪れたことがある
if 0 <= nx < n and 0 <= ny < m and maze[nx][ny] != "#" and d[nx][ny] == float("-inf"):
# 移動できるならキューに入れ、その点の距離を p からの距離 +1 で確定する
que.append((nx, ny))
d[nx][ny] = d[p[0]][p[1]] + 1
a = np.max(d)
return a
n, m = map(int, input().split())
maze = [list(input()) for i in range(n)]
ans = 1
for x in range(n):
for y in range(m):
sx = x
sy = y
if maze[sx][sy] == "#":
continue
A = bfs(sx, sy)
ans = max(A, ans)
print(int(ans)) | 1 | 94,385,371,469,200 | null | 241 | 241 |
n, m, l = map(int, input().split())
A = [[int(num) for num in input().split()] for i in range(n)]
B = [[int(num) for num in input().split()] for i in range(m)]
B = list(zip(*B)) # 列を行に置き換える
C = [[0 for i in range(l)] for j in range(n)]
for i, A_line in enumerate(A):
for j, B_line in enumerate(B):
for A_element, B_element in zip(A_line, B_line):
C[i][j] += A_element * B_element
for line in C:
for i, element in enumerate(line):
if i == l - 1:
print(element)
else:
print(element, end=' ')
| NML = input().split()
n = int(NML[0])
m = int(NML[1])
l = int(NML[2])
A = []
B = []
for i in range(n):
A.append([])
A_r = input().split()
for j in range(m):
A[i].append(int(A_r[j]))
for i in range(m):
B.append([])
B_r= input().split()
for j in range(l):
B[i].append(int(B_r[j]))
for i in range(n):
for j in range(l):
out=0
for k in range(m):
out +=A[i][k]*B[k][j]
print(str(out),end="")
if j != l-1:
print(" ",end="")
print("") | 1 | 1,439,432,943,842 | null | 60 | 60 |
N= int(input())
S = input()
abc = "ABC"
ans = 0
j = 0
for i in range(N):
if S[i] == abc[j]:
j += 1
if S[i] == "C":
j = 0
ans += 1
elif S[i] == "A":
j = 1
else:
j = 0
print(ans) | def main():
N = int(input())
S = list(input().rstrip())
ans = 0
for i in range(N-2):
if S[i:i+3] == ["A", "B", "C"]:
ans += 1
print(ans)
if __name__ == '__main__':
main()
| 1 | 98,902,187,830,410 | null | 245 | 245 |
from collections import deque
n = int(input())
graph_W = []
for _ in range(n):
graph_W.append(list(map(int, input().split())))
num_root = [0]*n
work_queue = deque([])
visited = set()
work_queue.append(1)
visited.add(1)
cnt = 0
while work_queue:
here = work_queue.popleft() - 1
num_node = graph_W[here][1]
cnt += 1
if num_node == 0:
continue
for k in range(num_node):
num_graph = graph_W[here][k+2]
if num_graph not in visited:
work_queue.append(num_graph)
visited.add(num_graph)
num_root[num_graph-1] = num_root[here] + 1
print(1,0)
for i in range(1,n):
if num_root[i] != 0:
print(i+1,num_root[i])
else:
print(i+1,-1)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
4
1 2 2 4
2 1 4
3 0
4 1 3
output:
1 0
2 1
3 2
4 1
"""
import sys
from collections import deque
UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2
def graph_bfs(v_init):
queue = deque()
status[v_init] = VISITED_IN_QUEUE
distance[v_init] = 0
queue.appendleft(v_init)
while queue:
current = queue.popleft()
for adj in adj_table[current]:
if status[adj] is UNVISITED:
status[adj] = VISITED_IN_QUEUE
distance[adj] = distance[current] + 1
queue.append(adj)
status[current] = POPPED_OUT
return None
if __name__ == '__main__':
_input = sys.stdin.readlines()
v_num = int(_input[0])
vertices = list(map(lambda x: x.split(), _input[1:]))
# assert len(vertex_info) == vertex_num
status = [UNVISITED] * (v_num + 1)
distance = [-1] * (v_num + 1)
adj_table = tuple([] for _ in range(v_num + 1))
for v_info in vertices:
v_index, adj_num, *adj_list = map(int, v_info)
# assert len(adj_list) == adj_num
adj_table[v_index].extend(adj_list)
graph_bfs(v_init=1)
for index, v in enumerate(distance[1:], 1):
print(index, v) | 1 | 3,902,393,418 | null | 9 | 9 |
n = int(input())
p = list(map(int,input().split()))
p2 = [0]*n
for x in p:
p2[x-1] = p2[x-1] + 1
for x in p2:
print(x) | N = int(input())
A = list(map(int, input().split()))
l = [0]*N
for i in A:
l[i-1] += 1
print(*l, sep="\n") | 1 | 32,558,416,399,872 | null | 169 | 169 |
n = int(input())
a = list(map(int, input().split()))
l = []
for i in range(n):
l.append([a[i], i+1])
l = sorted(l)
ans = []
for j in range(n):
ans.append(str(l[j][1]))
print(" ".join(ans)) | n=int(input())
start=[[[0 for i in range(10)] for j in range(3)] for k in range(4)]
for i in range(n):
b,f,r,v=[int(i) for i in input().split()]
start[b-1][f-1][r-1]+=v
for i in range(4):
for j in range(3):
for k in range(10):
print(" ",end="")
print(start[i][j][k],end="")
print()
if i<=2:
for m in range(20):
print("#",end="")
print()
| 0 | null | 90,722,921,940,458 | 299 | 55 |
s=input()
lis=list(s)
n=len(lis)
X=["x" for i in range(n)]
print("".join(X)) | #!/usr/bin/env python3
S = input()
print(len(S) * 'x')
| 1 | 72,917,926,906,020 | null | 221 | 221 |
def bubble(A,N):
flag=1
cnt=0
while flag==1:
flag=0
for j in range(1,N):
if A[j]<A[j-1]:
k=A[j-1]
A[j-1]=A[j]
A[j]=k
flag=1
cnt+=1
return A,cnt
n=int(raw_input())
list=map(int,raw_input().split())
list,cnt=bubble(list,n)
for x in list:
print x,
print
print cnt, |
def print_array(A, N):
for i in xrange(N - 1):
print str(A[i]),
print A[N - 1]
def bubbleSort(A, N):
swap_num = 0
flag = 1
while flag == 1:
flag = 0
for j in xrange(N - 1, 0, -1):
if A[j] < A[j - 1]:
swap_num += 1
temp = A[j]
A[j] = A[j - 1]
A[j - 1] = temp
flag = 1
return swap_num
def main():
N = int(raw_input())
A = []
for num in raw_input().split():
A.append(int(num))
temp = bubbleSort(A, N)
print_array(A, N)
print temp
if __name__ == "__main__":
main() | 1 | 18,089,213,688 | null | 14 | 14 |
import sys
read=sys.stdin.readline
class SEGTree:
def __init__(self,n):
self.Unit=0
i=1
while(i<n):
i*=2
self.SEG=[self.Unit]*(2*i-1)
self.d=i
def update(self,i,x):
i+=self.d-1
self.SEG[i]=1<<x
while i>0:
i=(i-1)//2
self.SEG[i]=self.SEG[i*2+1]|self.SEG[i*2+2]
def find(self,a,b,k,l,r):
if r<=a or b<=l:
return self.Unit
if a<=l and r<=b:
return self.SEG[k]
else:
c1=self.find(a,b,2*k+1,l,(l+r)//2)
c2=self.find(a,b,2*k+2,(l+r)//2,r)
return c1|c2
def get(self,a,b):
return self.find(a,b,0,0,self.d)
def bitcnt(x):
res=0
while x>0:
if x&1:
res+=1
x//=2
return res
n=int(input())
s=input()
q=int(input())
seg=SEGTree(n)
for i in range(n):
seg.update(i,ord(s[i])-97)
for i in range(q):
q,x,y=read().rstrip().split()
if q=='1':
seg.update(int(x)-1,ord(y)-97)
else:
x,y=int(x)-1,int(y)
bit=seg.get(x,y)
print(bitcnt(bit)) | # simpleバージョン
class BinaryIndexedTree:
def __init__(self,size):
self.N = size
self.bit = [0]*(size+1)
def add(self,x,w): # 0-indexed
x += 1
while x <= self.N:
self.bit[x] += w
x += (x & -x)
def _sum(self,x): # 1-indexed
ret = 0
while x > 0:
ret += self.bit[x]
x -= (x & -x)
return ret
def sum(self,l,r): # [l,r)
return self._sum(r) - self._sum(l)
def __str__(self): # for debug
arr = [self.sum(i,i+1) for i in range(self.N)]
return str(arr)
class BIT:
""" 区間加算BIT(区間加算・区間合計取得) """
def __init__(self, N):
# 添字0が使えないので、内部的には全て1-indexedとして扱う
N += 1
self.N = N
self.data0 = [0] * N
self.data1 = [0] * N
def _add(self, data, k, x):
k += 1
while k < self.N:
data[k] += x
k += k & -k
def _get(self, data, k):
k += 1
s = 0
while k:
s += data[k]
k -= k & -k
return s
def add(self, l, r, x):
""" 区間[l,r)に値xを追加 """
self._add(self.data0, l, -x*(l-1))
self._add(self.data0, r, x*(r-1))
self._add(self.data1, l, x)
self._add(self.data1, r, -x)
def query(self, l, r):
""" 区間[l,r)の和を取得 """
return self._get(self.data1, r-1) * (r-1) + self._get(self.data0, r-1) \
- self._get(self.data1, l-1) * (l-1) - self._get(self.data0, l-1)
def ctoi(c):
return ord(c) - ord('a')
def main():
N = int(input())
S = input()
Q = int(input())
query = [input().split() for i in range(Q)]
bits = [BIT(N) for i in range(26)]
s = []
for i, c in enumerate(S):
bits[ctoi(c)].add(i,i+1,1)
s.append(c)
for a, b, c in query:
if a == '1':
i = int(b) - 1
bits[ctoi(s[i])].add(i,i+1,-1)
bits[ctoi(c)].add(i,i+1,1)
s[i] = c
else:
l = int(b) - 1
r = int(c)
a = 0
for i in range(26):
if bits[i].query(l,r):
a += 1
print(a)
if __name__ == "__main__":
main() | 1 | 62,208,649,870,620 | null | 210 | 210 |
r = int(input())
print(2 * r * 3.1415) | R = int(input())
print(R * 2 * 3.1415)
| 1 | 31,360,978,238,762 | null | 167 | 167 |
n, m = map(int, input().split())
ac = [0] * n
wa = [0] * n
for _ in range(m):
p, s = input().split()
if s == 'AC':
ac[int(p) - 1] = 1
elif ac[int(p) - 1] == 0:
wa[int(p) - 1] += 1
for i in range(n):
if ac[i] == 0:
wa[i] = 0
print(sum(ac), sum(wa)) | import math
member = []
score = []
while True:
num = int(raw_input())
if num == 0: break
member.append(num)
score.append(map(int, raw_input().split()))
alpha = []
for m, s in zip(member, score):
average = sum(s)/float(m)
sigma = 0
for t in s:
sigma += (t - average)**2
else:
alpha += [sigma/m]
for a in alpha:
#print '%.8f' % math.sqrt(a)
print math.sqrt(a) | 0 | null | 46,886,408,758,460 | 240 | 31 |
import bisect
n=int(input())
l=sorted(list(map(int,input().split())))
ans=0
for i in range(n):
for j in range(i+1,n):
index=bisect.bisect_left(l,l[i]+l[j])
ans+=index-j-1
print(ans) | n = int(input())
base = [mark + str(rank) for mark in ["S ", "H ", "C ", "D "] for rank in range(1,14)]
for card in [input() for i in range(n)]:
base.remove(card)
for elem in base:
print(elem) | 0 | null | 86,616,162,721,430 | 294 | 54 |
# D - Coloring Edges on Tree
import sys
sys.setrecursionlimit(10 ** 5)
N = int(input())
G = [[] for _ in range(N)]
for i in range(N - 1):
a, b = map(int, input().split())
a, b = a - 1, b - 1
G[a].append((b, i))
G[b].append((a, i))
ans = [-1] * (N - 1)
def dfs(key, color=-1, parent=-1):
k = 1
for i in range(len(G[key])):
if G[key][i][0] == parent:
continue
if color == k:
k += 1
ans[G[key][i][1]] = k
dfs(G[key][i][0], k, key)
k += 1
dfs(0)
print(max(ans))
for a in ans:
print(a)
| N = int(input())
ab = [list(map(int,input().split())) for i in range(N-1)]
graph = [[] for _ in range(N+1)]
for a,b in ab:
graph[a].append(b)
graph[b].append(a)
from collections import deque
todo = deque([1])
seen = deque([])
parent = [0] * (N+1)
# 親と子の関係を作る
while todo:
x = todo.popleft()
seen.append(x)
for y in graph[x]:
if y == parent[x]:
continue
parent[y] = x
todo.append(y)
# 根以外の頂点は、唯一の親を持つことから、
# vの親がpであるとき → color[v] に辺 pvの色を持たせると定めて色を管理
color = [-1] * (N+1)
for x in seen:
ng = color[x]
c = 1
for y in graph[x]:
if y == parent[x]:
continue
if c == ng:
c += 1
color[y] = c
c += 1
ans = []
for a,b in ab:
ans.append(color[b])
print(max(ans))
for i in ans:
print(i)
| 1 | 136,330,044,343,782 | null | 272 | 272 |
#!/usr/bin/env python
# encoding: utf-8
class Solution:
@staticmethod
def stack_polish_calc():
# write your code here
# array_length = int(input())
calc_func = ('+', '-', '*')
array = [str(x) for x in input().split()]
# print(array)
result = []
for i in range(len(array)):
if array[i] not in calc_func:
result.append(str(array[i]))
else:
calc = array[i]
arg_2 = result.pop()
arg_1 = result.pop()
result.append(str(eval(''.join((str(arg_1), calc, str(arg_2))))))
print(*result)
if __name__ == '__main__':
solution = Solution()
solution.stack_polish_calc() | s=[]
for p in input().split():
if p in "+-*":
b=s.pop()
a=s.pop()
s.append(str(eval(a+p+b)))
else:
s.append(p)
print(*s)
| 1 | 36,280,383,370 | null | 18 | 18 |
ha,sa,hb,sb = list(map(int, input().split()))
while ha>0 and hb>0:
hb -= sa
if hb<=0: break
ha -= sb
print('Yes' if ha>0 else 'No') | class monster:
def __init__(self, hp: int, ap: int):
self.hit_point = hp
self.attack_point = ap
self.status = 'healthy'
def attack(self, enemy: 'monster'):
enemy.defend(self.attack_point)
def defend(self, enemy_ap: int):
self.hit_point -= enemy_ap
if self.hit_point <= 0:
self.status = 'dead'
def is_alive(self) -> bool:
return not self.is_dead()
def is_dead(self) -> bool:
return self.status == 'dead'
def answer(t_hp: int, t_ap: int, a_hp: int, a_ap: int) -> str:
taka_monster = monster(t_hp, t_ap)
aoki_monster = monster(a_hp, a_ap)
while taka_monster.is_alive() and aoki_monster.is_alive():
taka_monster.attack(aoki_monster)
if aoki_monster.is_dead():
return 'Yes'
aoki_monster.attack(taka_monster)
if taka_monster.is_dead():
return 'No'
def main():
a, b, c, d = map(int, input().split())
print(answer(a, b, c, d))
if __name__ == '__main__':
main() | 1 | 29,723,126,539,684 | null | 164 | 164 |
def popcount(x):
c = 0
while x > 0:
if x & 1: c += 1
x //= 2
return c
def f(x):
if x==0: return 0
return f(x % popcount(x)) + 1
n = int(input())
X = input()
po = X.count('1')
pp = po + 1
pm = max(1, po - 1)
rp = rm = 0
for x in X:
rp = (rp*2 + int(x)) % pp
rm = (rm*2 + int(x)) % pm
bp = [0]*(n) # 2^i % (po+1)
bm = [0]*(n) # 2^i % (po-1)
bp[n-1] = 1 % pp
bm[n-1] = 1 % pm
for i in range(n-1, 0, -1):
bp[i-1] = bp[i]*2 % pp
bm[i-1] = bm[i]*2 % pm
for i in range(n):
if X[i] == '0': ri = (rp + bp[i]) % pp
else:
if po-1 != 0: ri = (rm - bm[i]) % pm
else:
print(0)
continue
print(f(ri) + 1)
| import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()
def resolve():
N = I()
X = SS()
# 一回の操作でnはN以下になる
# 2回目以降の操作はメモ化再帰
# 初回popcountは2種類しかない Xのpopcountから足し引きすればよい
pc_X = X.count('1')
if pc_X == 0:
for i in range(N):
print(1)
elif pc_X == 1:
for i in range(N):
if i == X.index('1'):
print(0)
else:
# 1が2つある場合、最後の位が1の場合、奇数
if i == N - 1 or X.index('1') == N - 1:
print(2)
else:
print(1)
else:
next_X_m1 = 0
next_X_p1 = 0
pc_m1 = pc_X - 1
pc_p1 = pc_X + 1
for i in range(N):
if X[i] == '1':
next_X_m1 += pow(2, N - 1 - i, pc_m1)
next_X_p1 += pow(2, N - 1 - i, pc_p1)
dp = [-1] * N
dp[0] = 0
def dfs(n):
if dp[n] == -1:
dp[n] = 1 + dfs(n % bin(n).count('1'))
return dp[n]
for i in range(N):
next = 0
if X[i] == '0':
next = (next_X_p1 + pow(2, N - 1 - i, pc_p1)) % pc_p1
else:
next = (next_X_m1 - pow(2, N - 1 - i, pc_m1)) % pc_m1
ans = dfs(next) + 1
print(ans)
# print(dp)
if __name__ == '__main__':
resolve()
| 1 | 8,254,592,016,538 | null | 107 | 107 |
import sys
input=sys.stdin.readline
inf=10**9+7
n,m,l=map(int,input().split())
D=[[inf]*(n+1) for _ in range(n+1)]
for _ in range(m):
a,b,c=map(int,input().split())
D[a][b]=c
D[b][a]=c
for k in range(1,n+1):
for i in range(1,n+1):
for j in range(1,n+1):
D[i][j]=min(D[i][j],D[i][k]+D[k][j])
DD=[[inf]*(n+1) for _ in range(n+1)]
for x in range(1,n+1):
for y in range(1,n+1):
if D[x][y]<=l:
DD[x][y]=1
for k in range(1,n+1):
for i in range(1,n+1):
for j in range(1,n+1):
DD[i][j]=min(DD[i][j],DD[i][k]+DD[k][j])
q=int(input())
for _ in range(q):
s,t=map(int,input().split())
if DD[s][t]==inf:
print(-1)
else:
print(DD[s][t]-1) | import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
n,m,L=map(int,input().split())
E=[[] for _ in range(n)]
for _ in range(m):
a,b,c=map(int,input().split())
if(c>L): continue
a-=1; b-=1
E[a].append((b,c))
E[b].append((a,c))
A=[0]*n
# pure Dijkstraを全ての始点で行う
for u in range(n):
dist=[(INF,INF)]*n # (補給回数,使用燃料)
dist[u]=(0,0)
calculated=[False]*n
for _ in range(n-1):
v=min((dist[v],v) for v in range(n) if(not calculated[v]))[1]
calculated[v]=True
now=dist[v]
for nv,w in E[v]:
if(now[1]+w<=L):
next=(now[0],now[1]+w)
else:
next=(now[0]+1,w)
if(dist[nv]>next):
dist[nv]=next
A[u]=dist
# output
Q=int(input())
for _ in range(Q):
s,t=map(int,input().split())
s-=1; t-=1
ans=A[s][t][0]
print(ans if ans!=INF else -1)
resolve() | 1 | 173,442,051,096,022 | null | 295 | 295 |
r = int(input())
print(r * 2 * 3.1415926535897932384626433) | import math
x = math.pi
r = int(input())
x = 2*x*r
print(x) | 1 | 31,248,165,924,182 | null | 167 | 167 |
import sys
a,b,c = map(int,input().split())
d = a+b+c
if(d > 21):
print("bust")
else:
print("win")
| inputs = input().split(' ')
inputs = list(map(int,inputs))
W = inputs[0]
H = inputs[1]
x = inputs[2]
y = inputs[3]
r = inputs[4]
if r <= x and x <= W-r and r <= y and y <= H-r :
print('Yes')
else :
print('No') | 0 | null | 59,940,597,936,978 | 260 | 41 |
def main():
N, M = tuple([int(_x) for _x in input().split()])
A = [int(_x) for _x in input().split()]
total = sum(A)
if total % (4*M) == 0:
min_vote = total // (4 * M)
else:
min_vote = 1 + total // (4 * M)
cnt = 0
for vot in A:
if vot >= min_vote:
cnt += 1
if (cnt >= M):
print("Yes")
else:
print("No")
main()
| n,m=map(int,input().split())
A=list(map(int,input().split()))
ans=0
for i in range(n):
if 4*m*A[i]<sum(A):
continue
else:
ans+=1
if ans<m:
print('No')
else:
print('Yes') | 1 | 38,675,073,914,538 | null | 179 | 179 |
import itertools
n, m, q = map(int, input().split())
abcd = [list(map(int, input().split())) for _ in range(q)]
v = list(itertools.combinations_with_replacement(range(1, m+1), n))
ans = 0
for i in v:
s = 0
for a, b, c, d in abcd:
if i[b-1] - i[a-1] == c:
s += d
ans = max(ans, s)
print(ans) | def mi(): return map(int,input().split())
def lmi(): return list(map(int,input().split()))
def ii(): return int(input())
def isp(): return input().split()
from itertools import combinations_with_replacement
n,m,q=mi()
ll=[i for i in range(1,m+1)]
input_list=[]
for i in range(q):
abcd=lmi()
input_list.append(abcd)
ans=0
la=list(combinations_with_replacement(ll,n))
for i in la:
suma=0
#print(i)
for j in input_list:
a=j[0]
b=j[1]
c=j[2]
d=j[3]
if (i[b-1]-i[a-1])==c:
suma+=d
#print(suma)
ans=max(ans,suma)
print(ans) | 1 | 27,651,497,809,738 | null | 160 | 160 |
R=int(input())
print((R*2)*3.14) | K = int(input())
string = "ACL"
print(string * K) | 0 | null | 16,735,995,159,780 | 167 | 69 |
n=int(input())
s,t=map(str, input().split())
a=[]
for i in range(n):
a.append(s[i]+t[i])
a = "".join(a)
print(a) | ans = 100000
n = int(raw_input())
for i in xrange(n):
ans *= 1.05
ans = int((ans+999)/1000)*1000;
print ans | 0 | null | 56,059,285,852,840 | 255 | 6 |
n=int(input())
a=sorted(list(map(int,input().split())))[::-1]
ans=a[0]
for i in range(1,(n-2)//2+1):
ans+=(a[i]*2)
if n%2:
ans+=a[(n-2)//2+1]
print(ans) | a,b = list(map(int,input().split()))
print("%d %d %f" % ((a//b),(a%b),float((a/b)))) | 0 | null | 4,906,809,872,732 | 111 | 45 |
#!/usr/bin/env python3
# Generated by https://github.com/kyuridenamida/atcoder-tools
from typing import *
import collections
import itertools
import math
import sys
INF = float('inf')
YES = "Yes" # type: str
NO = "No" # type: str
def solve(N: int, M: int, A: "List[int]"):
t = sum(A)/4/M
return [YES, NO][len([a for a in A if a >= t]) < M]
def main():
sys.setrecursionlimit(10 ** 6)
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
M = int(next(tokens)) # type: int
A = [int(next(tokens)) for _ in range(N)] # type: "List[int]"
print(f'{solve(N, M, A)}')
if __name__ == '__main__':
main()
| n = int(input())
ans = 0 if n % 1000 == 0 else 1000 - n % 1000
print(ans) | 0 | null | 23,601,243,558,340 | 179 | 108 |
# from math import sqrt
# from heapq import heappush, heappop
# from collections import deque
from functools import reduce
# a, b = [int(v) for v in input().split()]
def main():
mod = 1000000007
n, k = map(int, input().split())
fact1 = [0] * (n + 1) # 1/P!
fact1[0] = 1
for i in range(1, n + 1):
fact1[i] = (fact1[i - 1] * i) % mod
fact2 = [0] * (n + 1) # P!
fact2[n] = pow(fact1[n], mod-2, mod)
for i in range(n, 0, -1):
fact2[i - 1] = (fact2[i] * i) % mod
def cmb2(n, r, mod):
if r < 0 or r > n:
return 0
return fact1[n] * fact2[n - r] * fact2[r] % mod
ans = 0
for i in range(min(n - 1, k) + 1):
ans += cmb2(n, i, mod) * cmb2(n - 1, i, mod)
ans %= mod
print(ans)
main()
| N = int(input())
M = (N+1000-1)//1000
ans = M*1000-N
print(ans) | 0 | null | 37,691,165,606,948 | 215 | 108 |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = [int(x)-48 for x in read().rstrip()]
ans = 0
dp = [[0]*(len(N)+1) for i in range(2)]
dp[1][0] = 1
dp[0][0] = 0
for i in range(1, len(N)+1):
dp[0][i] = min(dp[0][i-1] + N[i-1],
dp[1][i-1] + (10 - N[i-1]))
dp[1][i] = min(dp[0][i-1] + N[i-1] + 1,
dp[1][i-1] + (10 - (N[i-1] + 1)))
print(dp[0][len(N)])
| s = input()
INF = float('inf')
dp = [[INF,INF] for _ in range(len(s)+1)]
dp[0][0]=0
dp[0][1]=1
for i in range(len(s)):
dp[i+1][0] = min(dp[i][0]+int(s[i]), dp[i][1]+10-int(s[i]), dp[i][1]+int(s[i])+1)
dp[i+1][1] = min(dp[i][0]+int(s[i])+1,dp[i][1]+10-int(s[i])-1)
print(dp[-1][0])
| 1 | 71,284,304,359,840 | null | 219 | 219 |
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) | #! /usr/bin/env python
# -*- coding: utf-8 -*-
''' ???????????? '''
# pop???push??¨??????????????????????????????????????????????????¨??£??\????????????????????????
# ?¨??????????O(1)
operators = {"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y}
def compute(A):
stack = []
for i in range(len(A)):
# ?????????
if isinstance(A[i], str):
op_right = stack.pop()
op_left = stack.pop()
# ?¨???????????????????????????????
stack.append(operators[A[i]](op_left, op_right))
# ???????????????
if isinstance(A[i], int):
stack.append(A[i])
return stack[-1]
if __name__ == '__main__':
A = list(input().split())
# A = list("1 2 + 3 4 - *".split())
for i in range(len(A)):
if not A[i] in ['+', '-', '*', '/']:
A[i] = int(A[i])
print(compute(A)) | 0 | null | 65,192,342,602,592 | 268 | 18 |
import sys
from io import StringIO
import unittest
import os
from operator import ixor
# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)
# 実装を行う関数
def resolve(test_def_name=""):
# 数値取得サンプル
# 1行1項目 n = int(input())
# 1行2項目 x, y = map(int, input().split())
# 1行N項目 x = [list(map(int, input().split()))]
# N行1項目 x = [int(input()) for i in range(n)]
# N行N項目 x = [list(map(int, input().split())) for i in range(n)]
# 文字取得サンプル
# 1行1項目 x = input()
# 1行1項目(1文字ずつリストに入れる場合) x = list(input())
n = int(input())
a_s = list(map(int, input().split()))
one_counts = [0 for i in range(61)]
zero_counts = [0 for i in range(61)]
# 以下、XORで便利と思われる処理。
# -------------------------------------------
# ループ回数の取得(最大の数値の桁数分、ループ処理を行うようにする)
max_num = max(a_s)
max_loop = 0
for i in range(0, 61):
if max_num < 1 << i:
break
max_loop += 1
# ループ処理にて、各桁の0と1の個数を数え上げる。
# 例:入力[1(01),2(10),3(11)] -> one_count=[2,2,0・・]とzero_counts[1,1,0・・]を得る。
for a in a_s:
for i in range(0, max_loop):
if a & 1 << i:
one_counts[i] += 1
else:
zero_counts[i] += 1
# -------------------------------------------
# 以上、XORで便利と思われる処理。
# 結果を計算する処理
ans = 0
for i in range(0, max_loop):
# 各桁の「0の個数」*「1の個数」*2^(0~桁数-1乗まで) を加算していく
ans += (one_counts[i] * zero_counts[i] * pow(2, i)) % (pow(10, 9) + 7)
ans = ans % (pow(10, 9) + 7)
# 結果を出力
print(ans)
# テストクラス
class TestClass(unittest.TestCase):
def assertIO(self, assert_input, output):
stdout, sat_in = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
resolve(sys._getframe().f_back.f_code.co_name)
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, sat_in
self.assertEqual(out, output)
def test_input_1(self):
test_input = """3
1 2 3"""
output = """6"""
self.assertIO(test_input, output)
def test_input_2(self):
test_input = """10
3 1 4 1 5 9 2 6 5 3"""
output = """237"""
self.assertIO(test_input, output)
def test_input_3(self):
test_input = """10
3 14 159 2653 58979 323846 2643383 27950288 419716939 9375105820"""
output = """103715602"""
self.assertIO(test_input, output)
# 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
def tes_t_1original_1(self):
test_input = """データ"""
output = """データ"""
self.assertIO(test_input, output)
# 実装orテストの呼び出し
if __name__ == "__main__":
if os.environ.get("USERNAME") is None:
# AtCoder提出時の場合
resolve()
else:
# 自PCの場合
unittest.main()
| n=int(input())
x, y=0, 1
for i in range(1, n+1):
x, y=y, x+y
print(y)
| 0 | null | 61,555,828,152,826 | 263 | 7 |
N=int(input())
D=[map(int, input().split()) for i in range(N)]
x, y = [list(i) for i in zip(*D)]
s=0
l=[]
for i in range(N):
if x[i]==y[i]:
s+=1
if i==N-1:
l.append(s)
elif x[i]!=y[i]:
l.append(s)
s=0
if max(l)>=3:
print("Yes")
else:
print("No") | n=int(input())
lis=[]
count=0
high=0
for _ in range(n):
lis.append(input().split())
lis.append([5,6])
for i in range(n+1):
if lis[i][0]==lis[i][1]:
count+=1
else:
if count>=high:
high=count
count=0
if high>=3:
print("Yes")
else:
print("No") | 1 | 2,480,435,907,520 | null | 72 | 72 |
d1=[0 for i in range(6)]
d1[:]=(int(x) for x in input().split())
t1=[0 for i in range(6)]
order=input()
for i in range(len(order)):
if order[i]=='N':
t1[0]=d1[1]
t1[1]=d1[5]
t1[2]=d1[2]
t1[3]=d1[3]
t1[4]=d1[0]
t1[5]=d1[4]
if order[i]=='S':
t1[0]=d1[4]
t1[1]=d1[0]
t1[2]=d1[2]
t1[3]=d1[3]
t1[4]=d1[5]
t1[5]=d1[1]
if order[i]=='E':
t1[0]=d1[3]
t1[1]=d1[1]
t1[2]=d1[0]
t1[3]=d1[5]
t1[4]=d1[4]
t1[5]=d1[2]
if order[i]=='W':
t1[0]=d1[2]
t1[1]=d1[1]
t1[2]=d1[5]
t1[3]=d1[0]
t1[4]=d1[4]
t1[5]=d1[3]
d1=list(t1)
print(d1[0])
| a,b=open(0);c=1;
for i in sorted(b.split()):
c*=int(i)
if c>10**18:c=-1;break
print(c) | 0 | null | 8,155,155,118,110 | 33 | 134 |
A = int(input())
B = int(input())
print(3 if A+B==3 else 2 if A+B==4 else 1) | import math
a,b,deg = map(float,input().split(" "))
sindeg = math.sin(math.radians(deg))
S = (a*b*sindeg)/2
cosdeg = math.cos(math.radians(deg))
z = a*a + b*b - 2*a*b*cosdeg
L = a + b + math.sqrt(z)
h = b*sindeg
print("{:.5f}".format(S))
print("{:.5f}".format(L))
print("{:.5f}".format(h))
| 0 | null | 55,312,133,960,800 | 254 | 30 |
def gcd(a, b):
if (a % b) == 0:
return b
return gcd(b, a%b)
def lcd(a, b):
return a * b // gcd(a, b)
while True:
try:
nums = list(map(int, input().split()))
print(gcd(nums[0], nums[1]), lcd(nums[0], nums[1]))
except EOFError:
break | total_stack = []
single_stack = []
def main():
input_line = input()
total = 0
for i,s in enumerate(input_line):
if s == "\\":
total_stack.append(i)
elif s == "/" and len(total_stack) != 0:
a = total_stack.pop()
total += i - a
area = 0
while len(single_stack) != 0 and a < single_stack[-1][0]:
area += single_stack.pop()[1]
single_stack.append([a, area + i - a])
print(total)
print(' '.join([str(len(single_stack))] + [str(i[1]) for i in single_stack]))
if __name__ == '__main__':
main()
| 0 | null | 28,629,056,960 | 5 | 21 |
import copy
# 約数列挙
def make_divisors(n):
lower_divisors , upper_divisors = [], []
i = 2
while i*i <= n:
if n % i == 0:
lower_divisors.append(i)
if i != n // i:
upper_divisors.append(n//i)
i += 1
return lower_divisors + upper_divisors[::-1] + [n]
# 素因数分解
def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
n = int(input())
if n == 2:
print(1)
exit()
div1 = make_divisors(n-1)
cnt = len(div1)
div2 = make_divisors(n)
for i in div2:
x = copy.deepcopy(n)
while x >= i:
if x % i == 0:
x //= i
else:
break
if x == 1 or x % i == 1:
cnt += 1
print(cnt) | def get_ints():
return map(int, input().split())
def get_list():
return list(map(int, input().split()))
l, r, d = get_ints()
c = 0
for i in range(l, r + 1):
if i % d == 0:
c += 1
print(c) | 0 | null | 24,560,481,135,132 | 183 | 104 |
# coding=utf-8
def insertionSort(A, N):
print ' '.join(map(str, 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 ' '.join(map(str, A))
return A
n = int(raw_input().rstrip())
a = map(int, raw_input().rstrip().split())
insertionSort(a, n) | x=list(map(int,input().split()))
sum=0
for i in x:
sum+=i
print(15-sum) | 0 | null | 6,744,396,529,530 | 10 | 126 |
n=int(input())
n=int(n/2+0.5-1)
print(n) | #ITP1_10-C Standard Deviation
while True:
n= int(input())
if n==0:
break
s = input().split(" ")
mean = 0.0
for i in range(n):
mean += float(s[i])
mean /= n
cov = 0.0
for i in range(n):
cov+=((float(s[i])-mean)**2)/n
print(cov**0.5) | 0 | null | 76,485,484,062,708 | 283 | 31 |
#52 大文字変換
S = str(input())
swa = S.swapcase()
print(swa)
| n=raw_input()
a=''
for i in n:
if i.islower():a+=i.upper()
else:a+=i.lower()
print a | 1 | 1,511,396,941,364 | null | 61 | 61 |
a = int(input())
print((1+a)*a//2-((3 + a//3*3)*(a//3)//2 + (5 + a//5*5)*(a//5)//2 - (15 + a//15*15)*(a//15)//2))
| ans = 0
for a in range(1, int(input())+1):
if a % 3 != 0 and a % 5 != 0:
ans += a
print(ans) | 1 | 35,101,396,499,400 | null | 173 | 173 |
def main():
""""ここに今までのコード"""
H = int(input())
Count, atk = 1,1
while H > atk * 2 - 1:
atk = atk * 2
Count = Count * 2 + 1
print(Count)
if __name__ == '__main__':
main() | N = input()
a = [input() for i in range(N)]
def smax(N,a):
smin = a[0]
smax = -10**9
for j in range(1,N):
smax = max(smax,a[j]-smin)
smin = min(smin,a[j])
return smax
print smax(N,a) | 0 | null | 40,288,919,996,710 | 228 | 13 |
n,m = map(int,input().split())
matrix = [[0 for i in range(m)] for j in range(n)]
b = [0 for i in range(m)]
c = [0 for i in range(n)]
for i in range(0,n):
matrix[i] = list(map(int,input().split()))
for i in range(0,m):
b[i] = int(input())
for i in range(0,n):
for j in range(0,m):
c[i] += matrix[i][j]*b[j]
print(c[i])
| def gcd(a,b):
while True:
# print(a,b)
if a >= b:
x = a
y = b
else:
x = b
y = a
mod = x%y
if mod == 0:
return y
else:
a = y
b = mod
A,B = list(map(int,input().split()))
ans = int(A*B / gcd(A,B))
print(ans) | 0 | null | 57,341,957,074,302 | 56 | 256 |
n = int(input())
a = list(map(int, input().split()))
l = {}
r = {}
for i, j in enumerate(a):
if i - j in l:
l[i-j] += 1
else:
l[i-j] = 1
if i + j in r:
r[i+j] += 1
else:
r[i+j] = 1
ans = 0
for i, j in l.items():
if i in r:
ans += r[i] * j
print(ans) | N ,M= input().split()
a=[]
N=int(N)
M=int(M)
for i in range(N):
a.append(list(map(int,input().split())))
b=[int(input()) for i in range(M)]
x=[0 for i in range(N)]
for i in range(N):
for j in range(M):
x[i]+=a[i][j]*b[j]
print("\n".join(map(str,x))) | 0 | null | 13,715,423,245,970 | 157 | 56 |
S = input()
K = int(input())
if S[0] != S[-1]:
ans = 0
for i in range(len(S) - 1):
if S[i] == S[i + 1]:
S = S[:i + 1] + '*' + S[i + 2:]
ans += 1
print(ans * K)
else:
# S -> s_1 s_2 ... s_k + A + t_l t_l-1 ... t_1 (s_i = t_j)と分解
k, l = 0, len(S) - 1
while k < len(S) and S[k] == S[-1]:
k += 1
while l > -1 and S[l] == S[0]:
l -= 1
# 連結に関係ない部分のカウント
A = S[k:l + 1]
ans = 0
for i in range(len(A) - 1):
if A[i + 1] == A[i]:
A = A[:i + 1] + '*' + A[i + 2:]
ans += 1
ans *= K
# 連結に関係ある部分のカウント
if l == -1 and k == len(S):
# 全部同じ
print((len(S) * K) // 2)
else:
ans += (len(S) - l + k - 1) // 2 * (K - 1)
ans += (len(S) - l - 1) // 2 + k // 2
print(ans)
|
def main():
s = list(input())
k = int(input())
lst = []
cnt = 1
flg = 0
ans = 0
prev = s[0]
for i in range(1, len(s)):
if prev == s[i]:
cnt += 1
else:
lst.append(cnt)
cnt = 1
prev = s[i]
flg = 1
lst.append(cnt)
if len(lst) == 1:
ans = len(s) * k // 2
else:
ans += sum(map(lambda x: x // 2, lst[1:len(lst)-1])) * k
# for l in lst[1: len(lst) - 1]:
# ans += l // 2 * k
if s[-1] == s[0]:
ans += (lst[0] + lst[-1]) // 2 * (k - 1)
ans += lst[0] // 2 + lst[-1] // 2
else:
ans += (lst[0] // 2 + lst[-1] // 2) * k
print(ans)
if __name__ == "__main__":
main()
| 1 | 174,684,486,917,094 | null | 296 | 296 |
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
graph = {i: deque() for i in range(1, n+1)}
for _ in range(n):
u, k, *v = [int(x) for x in input().split()]
v.sort()
for i in v:
graph[u].append(i)
#graph[i].append(u)
seen = [0]*(n+1)
stack = []
time = 0
seentime = [0]*(n+1)
donetime = [0]*(n+1)
def dfs(j):
global time
seen[j] = 1
time += 1
seentime[j] = time
stack.append(j)
while stack:
s = stack[-1]
if not graph[s]:
stack.pop()
time += 1
donetime[s] = time
continue
g_NO = graph[s].popleft()
if seen[g_NO]:
continue
seen[g_NO] = 1
stack.append(g_NO)
time += 1
seentime[g_NO] = time
for j in range(1, n+1):
if seen[j]:
continue
dfs(j)
for k, a, b in zip(range(1, n+1), seentime[1:], donetime[1:]):
print(k, a, b)
| a = input().split(" ")
l = 0
g = int(a[0])
h = int(a[1])
s = int(a[2])
i = g
while i <= h :
if i % s == 0 :
l = l + 1
i = i + 1
print(l)
| 0 | null | 3,753,437,522,016 | 8 | 104 |
def bubbleSort(A, N):
flag = 1
count = 0
while flag:
flag = 0
for j in xrange(N-1,0,-1):
if A[j] < A[j-1]:
tmp = A[j]
A[j] = A[j-1]
A[j-1] = tmp
flag += 1
count += 1
return A, count
def main():
N = int(raw_input())
A = map(int, raw_input().split())
new_A, count = bubbleSort(A, N)
print ' '.join(map(str,new_A))
print count
if __name__ == "__main__":
main() | d = {n: 'hon' for n in "24579"}
d.update({n: 'pon' for n in "0168"})
d.update({"3": 'bon'})
print(d[input()[-1]]) | 0 | null | 9,648,379,461,150 | 14 | 142 |
from itertools import combinations_with_replacement
N, M, Q = map(int, input().split())
abcds = [tuple(map(int, input().split()))for _ in range(Q)]
def cal_score(A):
score = 0
for a, b, c, d in abcds:
if A[b-1] - A[a-1] == c:
score += d
return score
ans = 0
for A in combinations_with_replacement([i for i in range(M)], N):
ans = max(ans, cal_score(A))
print(ans)
| # coding: utf-8
import itertools
def main():
n, m, q = map(int, input().split())
matrix = []
for _ in range(q):
row = list(map(int, input().split()))
matrix.append(row)
# print(matrix)
A = list(range(1, m+1))
ans = 0
for tmp_A in itertools.combinations_with_replacement(A, n):
tmp_A = sorted(list(tmp_A))
tmp_ans = 0
for row in matrix:
# print("row", row)
# print("tmp_A", tmp_A)
tmp = tmp_A[row[1] - 1] - tmp_A[row[0]- 1]
if row[2] == tmp:
tmp_ans += row[3]
if tmp_ans >= ans:
ans = tmp_ans
print(ans)
main() | 1 | 27,575,519,905,086 | null | 160 | 160 |
# Begin Header {{{
from math import gcd
from collections import Counter, deque, defaultdict
from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
from bisect import bisect_left, bisect_right, bisect, insort_left, insort_right, insort
from itertools import accumulate, product, permutations, combinations, combinations_with_replacement
# }}} End Header
# _________コーディングはここから!!___________
mod = 10**9+7
n = int(input())
ans=0
ans+=pow(10, n, mod)
ans-=pow(9, n, mod)*2
ans+=pow(8, n, mod)
print(ans%mod)
| mod = 1000000007
def fexp(x, y):
ans = 1
while y > 0:
if y % 2 == 1:
ans = ans * x % mod
x = x * x % mod
y //= 2
return ans
n = int(input())
ans = fexp(10, n) - 2 * fexp(9, n) + fexp(8, n)
ans %= mod
if ans < 0:
ans += mod
print(ans) | 1 | 3,183,556,022,304 | null | 78 | 78 |
R, C, K = map(int, input().split())
score = [[0]*C for i in range(R)]
for i in range(K):
r, c, v = map(int, input().split())
score[r-1][c-1]+=v
ans0 = [[0]*C for i in range(R)]
ans1 = [[0]*C for i in range(R)]
ans2 = [[0]*C for i in range(R)]
ans3 = [[0]*C for i in range(R)]
ans1[0][0]=score[0][0]
ans2[0][0]=score[0][0]
ans3[0][0]=score[0][0]
for i in range(R):
for j in range(C):
if i>0:
ans0[i][j]=max(ans0[i][j],ans3[i-1][j])
ans1[i][j]=max(ans1[i][j],ans3[i-1][j]+score[i][j])
ans2[i][j]=max(ans2[i][j],ans3[i-1][j]+score[i][j])
ans3[i][j]=max(ans3[i][j],ans3[i-1][j]+score[i][j])
if j>0:
ans0[i][j]=max(ans0[i][j],ans0[i][j-1])
ans1[i][j]=max(ans1[i][j],ans0[i][j-1]+score[i][j],ans1[i][j-1])
ans2[i][j]=max(ans2[i][j],ans1[i][j-1]+score[i][j],ans2[i][j-1])
ans3[i][j]=max(ans3[i][j],ans2[i][j-1]+score[i][j],ans3[i][j-1])
print(ans3[R-1][C-1]) | r, c, k = map(int, input().split())
atlas = [[0]*c for i in range(r)]
dp = [[[0]*c for i in range(r)] for j in range(4)]
for i in range(k):
x, y, v = map(int, input().split())
atlas[x-1][y-1] = v
def max_sum(r, c, atlas):
global dp
if atlas[0][0] > 0:
dp[1][0][0] = atlas[0][0]
for i in range(r):
for j in range(c):
for h in range(4):
if j+1 < c:
dp[h][i][j+1] = max(dp[h][i][j+1], dp[h][i][j])
if atlas[i][j+1] > 0 and h < 3:
dp[h+1][i][j+1] = max(dp[h+1][i][j+1], dp[h][i][j]+atlas[i][j+1])
if i+1 < r:
dp[0][i+1][j] = max(dp[0][i+1][j], dp[h][i][j])
if atlas[i+1][j] > 0:
dp[1][i+1][j] = max(dp[1][i+1][j], dp[h][i][j]+atlas[i+1][j])
return dp
max_sum(r, c, atlas)
ans = 0
for i in range(4):
ans = max(ans, dp[i][r-1][c-1])
print(ans) | 1 | 5,582,176,520,660 | null | 94 | 94 |
# -*-coding:utf-8
class Dice:
def __init__(self, diceList):
self.d1, self.d2, self.d3, self.d4, self.d5, self.d6 = diceList
def diceRoll(self, r):
if(r == 'N'):
self.d1, self.d2, self.d5, self.d6 = self.d2, self.d6, self.d1, self.d5
elif(r == 'E'):
self.d1, self.d3, self.d4, self.d6 = self.d4, self.d1, self.d6, self.d3
elif(r == 'W'):
self.d1, self.d3, self.d4, self.d6 = self.d3, self.d6, self.d1, self.d4
elif(r == 'S'):
self.d1, self.d2, self.d5, self.d6 = self.d5, self.d1, self.d6, self.d2
def main():
inputDiceList = list(map(int, input().split()))
rollList = list(input())
d = Dice(inputDiceList)
for i in rollList:
d.diceRoll(i)
print(d.d1)
if __name__ == '__main__':
main() |
import sys
input = sys.stdin.readline
class Dice:
"""
0:top, 1:south, 2:east, 3:west, 4:north, 5:bottom
"""
def __init__(self, surfaces):
self.surface = surfaces
def roll(self, direction: str):
if direction == "E":
self.surface = [self.surface[3], self.surface[1], self.surface[0],
self.surface[5], self.surface[4], self.surface[2]]
elif direction == "N":
self.surface = [self.surface[1], self.surface[5], self.surface[2],
self.surface[3], self.surface[0], self.surface[4]]
elif direction == "S":
self.surface = [self.surface[4], self.surface[0], self.surface[2],
self.surface[3], self.surface[5], self.surface[1]]
elif direction == "W":
self.surface = [self.surface[2], self.surface[1], self.surface[5],
self.surface[0], self.surface[4], self.surface[3]]
return
def get_top(self):
return self.surface[0]
def main():
surface = [int(i) for i in input().strip().split()]
spins = input().strip()
dice = Dice(surface)
for d in spins:
dice.roll(d)
print(dice.get_top())
if __name__ == "__main__":
main()
| 1 | 241,113,387,320 | null | 33 | 33 |
line = list(map(int,input().split()))
print(line[0]//line[1],line[0]%line[1],'%0.05f'%(1.0*line[0]/line[1])) | N = int(input())
S = input()
judge = [1]*N
for i in range(1,N):
if S[i-1] == S[i]:
judge[i] = 0
print(sum(judge)) | 0 | null | 85,374,347,513,210 | 45 | 293 |
a,b = input().split()
if int(a * int(b))>= int(b *int(b)):
print(b*int(a))
else:
print(a*int(b)) | T = int(input())
if T >= 30:
print("Yes")
else:
print("No") | 0 | null | 44,902,208,989,550 | 232 | 95 |
def solve(s):
dp = [0]*(s+1)
dp[0] = 1
MOD = 10**9+7
x = 0
for i in range(1,s+1):
for j in range(0,i-3+1):
dp[i] += dp[j]
dp[i] %= MOD
return dp[s]
s = int(input())
print(solve(s)) | from math import factorial as fac
def binom(a,b):
return(fac(a) // (fac(a-b) * fac(b)))
def main():
S = int(input())
count = 0
for n in range(1,S//3 + 1):
s = S - 3 * n
count += binom(s+n-1,n-1)
print(count % (10**9 + 7))
main()
| 1 | 3,322,550,902,894 | null | 79 | 79 |
# https://atcoder.jp/contests/abc163/tasks/abc163_d
def main():
n, k = map(int, input().split(" "))
# このやり方だと当然TLE
# total = 0
# for i in range(k, n + 2):
# a = 0
# b = 0
# for j in range(i):
# a += j
# b += n - j
# total += b - a + 1
# print(total)
max_num = sum(range(n - k + 1, n + 1))
min_num = sum(range(k))
c = max_num - min_num + 1
total = c
for i in range(k, n + 1):
max_num += n - i
min_num += i
c = max_num - min_num + 1
total += c
print(total % 1000000007)
if __name__ == '__main__':
main()
| N, K = map(int, input().split())
N += 1
res = 0
s = [i for i in range(N)]
if K == 1:
res += N
K = 2
if N == 0:
print(res)
exit(0)
res += 1
minimum = sum(s[:K - 1])
maximum = sum(s[-K + 1:])
for i in range(K, N):
minimum += s[i]
maximum += s[-i + 1]
res = (res + (maximum - minimum + 1)) % (10 ** 9 + 7)
print(res)
| 1 | 33,030,281,340,980 | null | 170 | 170 |
n, m = map(int, input().split())
ps = [input().split() for i in range(m)]
b = [False] * n
wa = [0] * n
for i in ps:
if b[int(i[0])-1] == False and i[1] == "AC":
b[int(i[0])-1] = True
elif b[int(i[0])-1] == False and i[1] == "WA":
wa[int(i[0])-1] += 1
print(b.count(True),end=" ")
ans = 0
for i in range(n):
if b[i]:
ans += wa[i]
print(ans) | N, M = map(int,input().split())
ans = [["",0] for i in range(N)]
for i in range(M):
p,S = map(str,input().split())
p = int(p)-1
if ans[p][0] != "AC":
if S == "AC":
ans[p][0] = "AC"
elif S == "WA":
ans[p][1] += 1
AC = 0
WA = 0
for i in ans:
if i[0] == "AC":
AC += 1
WA += i[1]
print(AC,WA) | 1 | 93,273,136,054,270 | null | 240 | 240 |
n = int(input())
ns = []
max_profit = -1000000000
min_value = 1000000000
for i in range(n):
num = int(input())
if i > 0:
max_profit = max(max_profit, num-min_value)
min_value = min(num, min_value)
print(max_profit)
| #coding: UTF-8
N = int(input())
a = [int(input()) for i in range(N)]
ans = set()
maxv = -9999999999
minv = a[0]
for i in range(1,N):
if (a[i] - minv) > maxv:
maxv = a[i] - minv
if a[i] < minv:
minv = a[i]
print(maxv) | 1 | 12,422,001,692 | null | 13 | 13 |
S = int(input())
h = S//(60*60)
m = (S%(60*60))//60
s = (S%(60*60))%60
print(h, ':', m, ':', s, sep='')
| N,K = list(map(int,input().split()))
snacker = set()
for i in range(K):
dummy=input()
for j in [int(k) for k in input().split()]:
snacker.add(j)
print(N-len(snacker))
| 0 | null | 12,372,515,180,254 | 37 | 154 |
N, K = map(int, input().split())
*P, = map(int, input().split())
*C, = map(int, input().split())
def get(pos):
used = [-1] * N
cost = [0] * (N+1)
for k in range(N+1):
if k:
cost[k] = cost[k-1] + C[pos]
if used[pos] >= 0:
loop_size = k-used[pos]
break
used[pos] = k
pos = P[pos] - 1
if cost[loop_size] <= 0:
return max(cost[1:K+1])
else:
a, b = divmod(K, loop_size)
v1 = cost[loop_size] * (a-1) + max(cost[:K+1])
v2 = cost[loop_size] * a + max(cost[:b+1])
return max(v1, v2) if a else v2
ans = max([get(i) for i in range(N)])
print(ans)
| N,K = map(int, input().split())
P = [int(p) for p in input().split()]
C = [int(c) for c in input().split()]
ans = max(C)
for i in range(N):
used = [0]*N
used[i] = 1
loop = [C[i]]
j = P[i]-1
while used[j] == 0:
used[j] = 1
loop.append(loop[-1]+C[j])
j = P[j]-1
M = len(loop)
if K >= M:
if K%M == 0:
t = 0
else:
t = max(loop[:K%M])
t = max(t, 0)
num = max(loop[-1]*(K//M)+t, max(loop), loop[-1]*(K//M-1)+max(loop))
else:
num = max(loop[:K])
ans = max(ans, num)
if max(C) <= 0:
ans = max(C)
print(ans) | 1 | 5,338,888,119,168 | null | 93 | 93 |
# エラトステネスの篩
def make_prime_table(N):
sieve = list(range(N + 1))
sieve[0] = -1
sieve[1] = -1
for i in range(2, int(N ** 0.5) + 1):
if sieve[i] != i:
continue
for j in range(i * i, N + 1, i):
if sieve[j] == j:
sieve[j] = i
return sieve
def f(X):
t = []
a = X
while a != 1:
if len(t) != 0 and t[-1][0] == prime_table[a]:
t[-1][1] += 1
else:
t.append([prime_table[a], 1])
a //= prime_table[a]
result = 1
for _, n in t:
result *= n + 1
return result
N = int(input())
prime_table = make_prime_table(N)
result = 0
for K in range(1, N + 1):
result += K * f(K)
print(result)
| n = int(input())
ans = 0
for a in range(1, n + 1):
num = n // a
ans += num * (num + 1) // 2 * a
print(ans) | 1 | 11,059,571,563,728 | null | 118 | 118 |
listset = set()
for i in range(int(input())):
listset.add(input())
print(len(listset)) | n = int(input())
s = set()
for i in range(n):
s |= {input()}
print(len(s)) | 1 | 30,208,055,162,660 | null | 165 | 165 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
N = int(input())
AB = [tuple(map(int,input().split())) for i in range(N-1)]
es = [[] for _ in range(N)]
for i,(a,b) in enumerate(AB):
a,b = a-1,b-1
es[a].append((b,i))
es[b].append((a,i))
ans = [None] * (N-1)
def dfs(v,p=-1,c=-1):
nc = 1
for to,e in es[v]:
if to==p: continue
if nc==c: nc += 1
ans[e] = nc
dfs(to,v,nc)
nc += 1
dfs(0)
print(max(ans))
print(*ans, sep='\n') | from collections import defaultdict
def main():
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
S = [0] * (N + 1) # 累積和
for i in range(1, N + 1):
S[i] = S[i - 1] + A[i - 1]
T = [(s - i) % K for i, s in enumerate(S)]
counter = defaultdict(int)
ans = 0
for j in range(N + 1):
if j >= K:
counter[T[j - K]] -= 1
ans += counter[T[j]]
counter[T[j]] += 1
print(ans)
if __name__ == '__main__':
main()
| 0 | null | 136,400,271,960,106 | 272 | 273 |
import sys
input()
numbers = map(int, input().split())
evens = [number for number in numbers if number % 2 == 0]
if len(evens) == 0:
print('APPROVED')
sys.exit()
for even in evens:
if even % 3 != 0 and even % 5 != 0:
print('DENIED')
sys.exit()
print('APPROVED')
| n = input()
l = list( map(int, input().split()))
odd = [ c for c in l if (c % 2 == 0 ) and (( c % 3 != 0) and ( c % 5 !=0 ))]
if len( odd ) == 0:
print( "APPROVED" )
else:
print( "DENIED" ) | 1 | 69,288,764,274,192 | null | 217 | 217 |
D, T, S = [int(x) for x in input().split()]
print("Yes" if D <= (T * S) else "No")
| n = int(input())
a = list(map(int, input().split()))
MAX = 10 ** 6 + 5
cnt = [0] * MAX
ok = [True] * MAX
for x in a:
cnt[x] += 1
ans = 0
for i in range(1,MAX):
if cnt[i] > 0:
for j in range(i*2, MAX, i):
ok[j] = False
if ok[i] and cnt[i] == 1:
ans += 1
print(ans) | 0 | null | 8,959,128,924,718 | 81 | 129 |
n = int(input())
tenant = [
[ [0]*10, [0]*10, [0]*10, ],
[ [0]*10, [0]*10, [0]*10, ],
[ [0]*10, [0]*10, [0]*10, ],
[ [0]*10, [0]*10, [0]*10, ]
]
for i in range(n):
b,f,r,nu = map(int, input().split())
tenant[b-1][f-1][r-1] += nu
for b in range(4):
for f in range(3):
print(' ', end='')
print(' '.join(map(str,tenant[b][f])))
if b < 3:
print('#'*20) | n = int(input())
home = [[0 for i in range(20)] for j in range(15)] #横最大20→間の#,縦最大3階*4棟+3行の空行
for i in range(n) :
b, f, r, v = map(int, input().split())
h = (b - 1) * 4 + f - 1
w = r * 2 - 1
s = v
home[h][w] += s
for y in range(15) :
for x in range(20) :
if(y % 4 == 3) :
home[y][x] = "#"
elif(x % 2 == 0) :
home[y][x] = " "
print(home[y][x], end = "")
print()
| 1 | 1,086,150,405,690 | null | 55 | 55 |
n=int(input())
if n<3:
print(0)
elif n%2==0:
print(int((n/2)-1))
else:
print(int(n//2)) | import sys
N = int(sys.stdin.readline().rstrip())
A = list(map(int, sys.stdin.readline().rstrip().split()))
mod = 10**9 + 7
ans = 1
cnt = [0] * N
for a in A:
if a > 0:
ans *= (cnt[a - 1] - cnt[a])
cnt[a] += 1
ans %= mod
for i in range(cnt[0]):
ans *= 3 - i
print(ans % mod) | 0 | null | 141,378,565,256,350 | 283 | 268 |
n, k = map(int, input().split())
p_list = list(map(lambda x: int(x) - 1, input().split()))
c_list = list(map(int, input().split()))
max_score = -(1 << 64)
cycles = []
cycled = [False] * n
for i in range(n):
if cycled[i]:
continue
cycle = [i]
cycled[i] = True
while p_list[cycle[-1]] != cycle[0]:
cycle.append(p_list[cycle[-1]])
cycled[cycle[-1]] = True
cycles.append(cycle)
for cycle in cycles:
cycle_len = len(cycle)
accum = [0]
for i in range(cycle_len * 2):
accum.append(accum[-1] + c_list[cycle[i % cycle_len]])
cycle_score = accum[cycle_len]
max_series_sums = [max([accum[i + length] - accum[i]
for i in range(cycle_len)])
for length in range(cycle_len + 1)]
if cycle_len >= k:
score = max(max_series_sums[1:k + 1])
elif cycle_score <= 0:
score = max(max_series_sums[1:])
else:
max_cycle_num, cycle_rem = divmod(k, cycle_len)
score = max(cycle_score * (max_cycle_num - 1) + max(max_series_sums),
cycle_score * max_cycle_num + max(max_series_sums[:cycle_rem + 1]))
max_score = max(max_score, score)
print(max_score)
| s = list(input())
sur_list = [0 for i in range(2019)]
sur = 0
keta = 1
ans = 0
s.reverse()
for i in range(len(s)):
keta = (keta*10)%2019
sur_list[sur] += 1
sur = (int(s[i]) * keta + sur) % 2019
ans += sur_list[sur]
print(ans)
| 0 | null | 17,982,229,659,240 | 93 | 166 |
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
# mod = 998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 1<<32-1
# INF = 10**18
def main():
ans = 0
n = input()
dp = [0,1] #0,1多く入れる
for i in n:
ni = int(i)
pdp = dp*1
dp[0] = min(pdp[0]+ni,pdp[1]+(10-ni))
dp[1] = min(pdp[0]+ni+1,pdp[1]+(10-ni-1))
print(dp[0])
return None
if __name__ == '__main__':
main()
| N = list(map(int, input()))
# print(N)
ans = 0
DP = [0] *2
DP[0] = 0
DP[1] = 1
for i in N:
a, b = DP[0] ,DP[1]
DP[0] = a + i if a+i < b +(10-i) else b +(10-i)
DP[1] = a + i+1 if a + i+1 < b + (9-i) else b + (9-i)
# print(DP)
print(DP[0] if DP[0] <= DP[1]+1 else DP[1] +1) | 1 | 70,823,915,369,930 | null | 219 | 219 |
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
MOD = 10**9+7
def main():
N,*A = map(int, read().split())
cnt = [0] * N
ans = 1
for a in A:
if a == 0:
cnt[0] += 1
continue
ans *= cnt[a - 1] - cnt[a]
ans %= MOD
cnt[a] += 1
if cnt[0] == 1:
ans *= 3
elif cnt[0] <= 3:
ans *= 6
else:
ans = 0
ans %= MOD
print(ans)
if __name__ == "__main__":
main()
| n=int(input())
mod=1000000007
l=list(map(int,input().split()))
me=[3]+[0]*2*n
ans=1
for x in l:
ans=ans*me[x]%mod
me[x]-=1
me[x+1]+=1
print(ans) | 1 | 129,890,998,014,440 | null | 268 | 268 |
import math
from functools import reduce
def gcd(*numbers):
return reduce(math.gcd, numbers)
total = 0
N = int(input())
for i in range(1,N+1):
for j in range(1,N+1):
for k in range(1,N+1):
total += gcd(i, j, k)
print(total)
| a, b, c, d = map(int,input().split())
while True:
c = c - b
a = a - d
if c <= 0:
print('Yes')
break
elif a <= 0:
print('No')
break
else:
pass | 0 | null | 32,528,727,202,048 | 174 | 164 |
#
# 10d
#
import math
def main():
n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
d1 = 0
d2 = 0
d3 = 0
dn = 0
for i in range(n):
d1 += abs(x[i] - y[i])
d2 += (x[i] - y[i])**2
d3 += abs(x[i] - y[i])**3
dn = max(dn, abs(x[i] - y[i]))
d2 = math.sqrt(d2)
d3 = math.pow(d3, 1/3)
print(f"{d1:.5f}")
print(f"{d2:.5f}")
print(f"{d3:.5f}")
print(f"{dn:.5f}")
if __name__ == '__main__':
main()
| N, K, S = map(int, input().split())
if S == 10**9:
Ans = [S for _ in range(K)] + [1 for _ in range(N-K)]
else:
Ans = [S for _ in range(K)] + [S+1 for _ in range(N-K)]
for ans in Ans:
print(ans, end=' ') | 0 | null | 45,900,949,626,742 | 32 | 238 |
n, k = map(int, input().split())
p = list(map(int, input().split()))
p = [_p-1 for _p in p]
c = list(map(int, input().split()))
ans = -float('inf')
visited = [False] * n
ss = []
for i in range(n):
if visited[i]: continue
cur = i
s = []
while not visited[cur]:
visited[cur] = True
s.append(c[cur])
cur = p[cur]
ss.append(s)
for s in ss:
m = len(s)
cumsum = [0] * (m*2+1)
for i in range(2*m):
cumsum[i+1] = cumsum[i] + s[i%m]
amari = [-float('inf')] * m
for i in range(m):
for j in range(m):
amari[j] = max(amari[j], cumsum[i+j] - cumsum[i])
for r in range(0, m):
if r > k: continue
q = (k-r)//m
if r==0 and q==0:
continue
if cumsum[m] > 0:
ans = max(ans, amari[r] + cumsum[m]*q)
elif r > 0:
ans = max(ans, amari[r])
print(ans)
| N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
lim = 60
nex = [[0] * N for _ in range(lim)]
val = [[0] * N for _ in range(lim)]
cnd = [[0] * N for _ in range(lim)]
for i in range(N):
nex[0][i] = P[i] - 1
val[0][i] = C[i]
cnd[0][i] = C[i]
for d in range(lim - 1):
for i in range(N):
nex[d + 1][i] = nex[d][nex[d][i]]
val[d + 1][i] = val[d][i] + val[d][nex[d][i]]
cnd[d + 1][i] = max(cnd[d][i], val[d][i] + cnd[d][nex[d][i]])
res = -10 ** 9
for i in range(N):
sum_ = 0
offset = i
for d in reversed(range(lim)):
if K & 1 << d:
res = max(res, sum_ + cnd[d][offset])
sum_ += val[d][offset]
offset = nex[d][offset]
print(res)
| 1 | 5,403,903,215,168 | null | 93 | 93 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.