code1
stringlengths 16
24.5k
| code2
stringlengths 16
24.5k
| similar
int64 0
1
| pair_id
int64 2
181,637B
⌀ | question_pair_id
float64 3.71M
180,628B
⌀ | code1_group
int64 1
299
| code2_group
int64 1
299
|
---|---|---|---|---|---|---|
from math import factorial
N, M = map(int, input().split())
if N <= 1:
combN = 0
else:
combN = factorial(N) // (factorial(N - 2) * factorial(2))
if M <= 1:
combM = 0
else:
combM = factorial(M) // (factorial(M - 2) * factorial(2))
print(combN + combM)
|
def main():
N, M = tuple([int(_x) for _x in input().split()])
print(N*(N-1)//2 + M*(M-1)//2)
main()
| 1 | 45,431,632,978,564 | null | 189 | 189 |
import math
a, b, C = map(int, input().split())
C = math.radians(C)
c = math.sqrt(a**2 + b**2 - 2*a*b*math.cos(C))
S = a * b * math.sin(C) / 2
print(f"{S:0.9f}")
print(f"{a+b+c:0.9f}")
print(f"{S*2/a:0.9f}")
|
n = int(input())
A = [(a, i) for i, a in enumerate(map(int, input().split()))]
A.sort(reverse=True)
dp = [[0]*(n+1) for _ in range(n+1)]
ans = 0
for L in range(n+1):
for R in range(n+1):
if n <= L+R-1:
continue
a, i = A[L+R-1]
if 0 <= R-1:
dp[L][R] = max(dp[L][R], dp[L][R-1]+abs((n-R)-i)*a)
if 0 <= L-1:
dp[L][R] = max(dp[L][R], dp[L-1][R]+abs(i-(L-1))*a)
ans = max(ans, dp[L][R])
print(ans)
| 0 | null | 17,035,044,776,198 | 30 | 171 |
input()
array = input().split()
array.reverse()
print(' '.join(array))
|
input()
print ' '.join(raw_input().split()[::-1])
| 1 | 964,335,907,750 | null | 53 | 53 |
x,k,d=list(map(int,input().split()))
if k>=abs(x)//d:
y=abs(x)//d
ans=abs(abs(x)-y*d)
ans=abs(ans-((k-y)%2)*d)
else:
ans=abs(abs(x)-k*d)
print(ans)
|
x, k, d = map(int, input().split())
x = abs(x)
if x >= k*d:
print(x-k*d)
else:
t = x//d
t -= int(t%2 ^ k%2)
print(min(x-d*t, abs(x-d*(t+2))))
| 1 | 5,248,159,617,818 | null | 92 | 92 |
s = input()
moji = len(s)
if moji % 2 == 0:
moji = int(moji/2)
else:
moji = int((moji-1)/2)
answer = 0
for i in range(moji):
if s[i] != s[len(s)-1-i]:
answer += 1
print(answer)
|
ret = []
while True:
n, x = map(int, raw_input().split())
num_arr = [i for i in range(1, n+1)]
if (n, x) == (0, 0):
break
cnt = 0
for i in range(n, 0, -1):
if x - i <= 2:
continue
#print "i : %d" % i
for j in range(i -1, 0, -1):
if x-i-j <= 0:
continue
#print "j : %d" % j
for k in range(j - 1, 0 , -1):
if x-i-j-k < 0:
continue
if x -i-j-k == 0:
cnt += 1
#print "k : %d" % k
break
ret += [cnt]
for i in ret:
print i
| 0 | null | 60,568,009,218,420 | 261 | 58 |
from fractions import Fraction
from collections import defaultdict
def resolve():
# A1*A2 + B1*B2 = 0 式変形 A1/B1 = -(B2/A2)
# a, b の0がある条件を考える
MOD = 1000000007
N = int(input())
zeroes = 0
hash1 = defaultdict(int) #
hash2 = defaultdict(str) #中の悪い相手を記入
for _ in range(N):
a, b = map(int, input().split())
if a==0 and b==0:
zeroes += 1
elif b == 0:
hash1["1/0"] += 1
hash2["1/0"] = "0/1"
elif a == 0:
hash1["0/1"] += 1
hash2["0/1"] = "1/0"
else: # a, bが0以外
rat1 = Fraction(a, b)
rat2 = Fraction(-b, a)
hash1[str(rat1)] += 1
hash2[str(rat1)] = str(rat2) # 相手を入れる
confirmed = set()
ans = 1
for k, v in hash1.items():
if k in confirmed: # 確認済みを数えないようにする
continue
bad = hash1.get(hash2[k], 0) # 中の悪い相手, キーがなかったら0を出力
cnt1 = pow(2, v, MOD) - 1
cnt2 = pow(2, bad, MOD) - 1
ans = (ans * (cnt1 + cnt2 + 1)) % MOD
# 確認済みにする
confirmed.add(k)
confirmed.add(hash2[k])
# ※ ループ中に値を変更したらエラー
# hash1[k] = -1
ans = (ans + zeroes + MOD -1) % MOD
print(ans)
if __name__ == "__main__":
resolve()
|
s = list(input())
if s[0] != s[1] or s[1] != s[2]:
print("Yes")
else:
print("No")
| 0 | null | 38,025,505,517,220 | 146 | 201 |
# https://atcoder.jp/contests/abc146/submissions/8617148
def solve(N, M, S):
from collections import namedtuple
from heapq import heappop, heappush
INF = N * 2
V = namedtuple('V', 'cnt index')
cnt_from_N = [INF] * (N + 1)
cnt_from_N[N] = 0
parent = [0] * (N + 1)
h = [V(cnt=0, index=N)]
for j in range(N - 1, -1, -1):
# S[j]に到達する最小回数とその経路を求める
if S[j]:
continue
while h:
cnt, par = h[0]
if par > j + M:
# jまで移動できない(距離>M)
heappop(h)
continue
break
# jまで最小回数で到達できる頂点par
# parまでの回数cnt
if not h:
return -1,
# jまで到達できる頂点がない
cnt_from_N[j] = cnt + 1
parent[j] = par
heappush(h, V(cnt=cnt + 1, index=j))
ret = []
curr = 0
while curr < N:
par = parent[curr]
ret.append(par - curr)
curr = par
return ret
def main():
N, M = map(int, input().split())
*S, = map(int, input())
print(*solve(N, M, S))
if __name__ == '__main__':
main()
|
n,m=map(int,input().split())
s=input()[::-1]
i=0
ans=[]
while i<n:
for j in range(min(n-i,m),0,-1):
if s[i+j]=="0":
ans.append(j)
i+=j
break
if j==1:print(-1);exit()
print(*ans[::-1])
| 1 | 139,340,178,499,680 | null | 274 | 274 |
import sys
sys.setrecursionlimit(10000000)
def dfs(s):
if len(s)==11:
return
if s!="":
a.append(int(s))
for c in "0123456789":
if s=="" and c=="0":continue
if s!="":
if abs(ord(c)-ord(s[-1]))<=1:
dfs(s+c)
else:
dfs(s+c)
k=int(input())
a=[]
dfs("")
a=list(set(a))
a.sort()
print(a[k-1])
|
N, M, K = map(int, input().split())
mod = 998244353
MAX = 510000
fac = [0]*MAX
facinv = [0]*MAX
inv = [0]*MAX
def modinv(a, mod):
b = mod
x, u = 1, 0
while b:
q = a//b
a, b = b, a-q*b
x, u = u, x-q*u
x %= mod
return x
def mod_nCr_init(n, mod):
fac[0] = fac[1] = 1
facinv[0] = facinv[1] = 1
inv[1] = 1
for i in range(2, n):
fac[i] = fac[i-1] * i % mod
inv[i] = -inv[mod % i] * (mod // i) % mod
facinv[i] = facinv[i-1] * inv[i] % mod
def mod_nCr(n, r, mod):
if n < r or n < 0 or r < 0:
return 0
return fac[n] * (facinv[r] * facinv[n-r] % mod) % mod
mod_nCr_init(MAX, mod)
ans = 0
for i in range(K+1):
ans += mod_nCr(N-1, i, mod) * M * pow(M-1, N-i-1, mod)
ans %= mod
print(ans)
| 0 | null | 31,738,053,003,492 | 181 | 151 |
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
#sys.setrecursionlimit(10**8)
def geta(fn=lambda s: s.decode()):
return map(fn, readline().split())
def gete(fn=lambda s: s.decode()):
return fn(readline().rstrip())
def main():
x = gete(int)
print('Yes' if x >= 30 else 'No')
if __name__ == "__main__":
main()
|
now = int(input())
if now >= 30:
print('Yes')
else:
print('No')
| 1 | 5,709,219,800,592 | null | 95 | 95 |
import fractions
from functools import reduce
def lcm_base(x, y):
return (x * y) // fractions.gcd(x, y)
def lcm_list(numbers):
return reduce(lcm_base, numbers, 1)
N, M = map(int, input().split())
A = list(map(int, input().split()))
for i in range(N):
A[i] = A[i] // 2
p = 0
de_2 = 0
x = A[0]
while (p == 0):
if x % 2 == 0:
x = x // 2
de_2 += 1
else:
p = 1
de = 2 ** de_2
for i in range(1, N):
if A[i] % de == 0:
if A[i] % (de * 2) != 0:
continue
else:
print("0")
quit()
else:
print("0")
quit()
lcm = lcm_list(A)
p = M // lcm
if p % 2 == 0:
ans = p // 2
else:
ans = (p + 1) // 2
print(ans)
|
h1, m1, h2, m2, k = map(int, input().split())
a1 = 60*h1 + m1
a2 = 60*h2 + m2
duration = abs(a2-a1)
ans = duration-k
if ans > 0:
print(ans)
else:
print(0)
| 0 | null | 59,928,424,805,440 | 247 | 139 |
a, b = map(int, input().split())
print(a*b if 0 < a < 10 and 0 < b < 10 else -1)
|
import sys
def solve():
input = sys.stdin.readline
A, B = map(int, input().split())
if A < 10 and B < 10: print(A * B)
else: print(-1)
return 0
if __name__ == "__main__":
solve()
| 1 | 158,753,441,340,732 | null | 286 | 286 |
class Process:
def __init__(self, name_time):
self.name = name_time[0]
self.time = int(name_time[1])
process_amount, quontam = (int(i) for i in input().split(' '))
processes = [Process(input().split(' ')) for i in range(process_amount)]
i = 0
total_time = 0
while len(processes) != 0:
process = processes[0]
if process.time <= quontam:
total_time += process.time
print('{} {}'.format(process.name, total_time))
else:
total_time += quontam
process.time -= quontam
processes.append(process)
processes.pop(0)
|
number_list=[int(i) for i in input().split()]
counter=0
for r in range(number_list[0],number_list[1]+1):
if number_list[2]%r==0:
counter+=1
print(counter)
| 0 | null | 309,315,885,312 | 19 | 44 |
# Ring
ring = input()
word = input()
doubleRing = ring * 2
ringCut = doubleRing.split(word)
# print(ringCut)
if ringCut[0] == doubleRing:
print('No')
else:
print('Yes')
|
from collections import Counter
N = int(input())
A = list(map(int, input().split()))
X, Y = [], []
for i in range(N):
X.append(i + 1 + A[i])
Y.append(i + 1 - A[i])
XL = Counter(X)
c = 0
for y in Y:
c += XL.get(y, 0)
print(c)
| 0 | null | 13,941,740,502,338 | 64 | 157 |
S = list(input())
T = list(input())
mindiff = len(S)
for i in range(len(S) - len(T) +1):
diff = 0
for j in range(len(T)):
if(S[i+j] != T[j]):
diff += 1
pass
if(diff < mindiff):
mindiff = diff
print(mindiff)
|
while True:
H, W = map(int, input().split())
if H == 0 and W == 0:
break
for j in range(H):
for i in range(W):
print("#", end="")
print()
print()
| 0 | null | 2,268,816,218,720 | 82 | 49 |
a,b=input().split()
a=int(a)
b=int(b)
e=a
d=b
c=1
if a>b:
for i in range(1,e):
if a%(e-i)==0 and b%(e-i)==0:
a=a/(e-i)
b=b/(e-i)
c=c*(e-i)
print(int(a*b*c))
if a<b:
for i in range(1,d):
if a%(d-i)==0 and b%(d-i)==0:
a=a/(d-i)
b=b/(d-i)
c=c*(d-i)
print(int(a*b*c))
|
import math
a, b = map(int, input().split())
print(int((a*b)/math.gcd(a, b)))
| 1 | 113,228,735,681,248 | null | 256 | 256 |
def isKaibun(ss):
return ss==ss[::-1]
s = input()
ans=True
n=len(s)
if not isKaibun(s):
ans=False
if not isKaibun(s[:((n-1)//2)]):
ans=False
if ans:
print("Yes")
else:
print("No")
|
n, m = [int(i) for i in input().split()]
vec = []
for i in range(n):
vec.append([int(j) for j in input().split()])
c = []
for i in range(m):
c.append(int(input()))
for i in range(n):
sum = 0
for j in range(m):
sum += vec[i][j]*c[j]
print(sum)
| 0 | null | 23,602,788,631,940 | 190 | 56 |
N,X,M = map(int, input().split())
A = [X]
S = set(A)
cnt = 0
i = 0
for i in range(1, N):
A.append(A[i-1] ** 2 % M)
if A[i] in S:
break
else:
S.add(A[i])
roup_cycle = i - A.index(A[i])
before_roup_sums = sum(A[:A.index(A[i])])
roup_sums = sum(A[A.index(A[i]):i])
if roup_cycle != 0:
roup_amount = (N - A.index(A[i])) // roup_cycle
roup_mod = (N - A.index(A[i])) % roup_cycle
print(before_roup_sums + roup_sums * roup_amount + sum(A[A.index(A[i]):(A.index(A[i]) + roup_mod)]))
else:
print(sum(A))
|
x = int(input())
i = 0
ganpon = 100
while True:
if x > ganpon:
ganpon += int(ganpon//100)
i += 1
else:
print(i)
break
| 0 | null | 15,029,353,858,820 | 75 | 159 |
import numpy as np
n = int(input())
mod = 10**9 + 7
a = np.array(list(map(int, input().split())))
ans = 0
for i in range(len(bin(max(a)))):
num_1 = np.count_nonzero((a>>i)&1)
num_0 = n - num_1
ans += (2**i)*(num_1*num_0) % mod
ans %= mod
print(ans)
|
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n = inp()
a = inpl()
ln = len(bin(max(a))) -2
cnt = [0] * ln
for x in a:
for shift in range(ln):
cnt[shift] += (x>>shift)%2
# print(cnt)
res = 0
for i in range(ln):
now = cnt[i] * (n-cnt[i])
res += now*pow(2,i)
res %= mod
print(res)
| 1 | 122,726,990,898,692 | null | 263 | 263 |
n = int(input())
fib = []
ans = 0
for i in range(n+1):
if i == 0 or i == 1:
ans = 1
fib.append(ans)
else:
ans = fib[i-1] + fib[i-2]
fib.append(ans)
print(ans)
|
n = int(input())
DP = [None] * (n + 1) # 計算結果を保存する配列
DP[0] = 1 # 定義より
DP[1] = 1 # 定義より
def fib(n):
# フィボナッチ数を2からnまで順に求めていく
for i in range(2, n + 1):
DP[i] = DP[i-1] + DP[i-2]
return DP[n]
print(fib(n))
| 1 | 1,594,621,692 | null | 7 | 7 |
while 1:
a=0
n,x=map(int,raw_input().split())
if n==0:break
for i in range(1,n-1):
for j in range(i+1,n):
c=x-i-j
if c>j and c<=n:a+=1
print a
|
while True:
n,x = map(int,input().split(" "))
if n == 0 and x == 0:
break
#データリスト作成
data = [m for m in range(1,n+1)]
data_list = []
cnt = 0
#n種類の数字があって、xになる組み合わせは?
for i in range(1,n+1):
for j in range(1+i,n+1):
for k in range(1+j,n+1):
if i+j+k == x:
cnt += 1
print(cnt)
| 1 | 1,286,180,885,306 | null | 58 | 58 |
s = input()
n = int(input())
for i in range(n):
order, a, b, *c = input().split()
a = int(a)
b = int(b)
if order == 'replace':
s = s[:a] + c[0] + s[b+1:]
elif order[0] == 'r':
s = s[:a] + s[::-1][len(s)-b-1:len(s)-a]+ s[b+1:]
else:
print(s[a:b+1])
|
def biserch(n,List):
left = 0
right = len(List)
while left < right:
mid = (left+right)//2
if n <= List[mid]:
right = mid
else:
left = mid + 1
return left
N = int(input())
L = list(map(int,input().split()))
L.sort()
ans = 0
for i in range(N):
for j in range(i+1,N):
key = L[i] + L[j]
anchor = biserch(key,L)
ans += max(anchor - (j+1),0)
print(ans)
| 0 | null | 86,777,328,818,782 | 68 | 294 |
counter=0
while True:
counter+=1
x=int(input())
if x==0:
break
print("Case "+str(counter)+": "+str(x))
|
def f():
n,k=map(int,input().split())
l=list(map(int,input().split()))
now=1
for d in range(k.bit_length()):
k,f=divmod(k,2)
if f:now=l[now-1]
l=tuple(l[i-1]for i in l)
print(now)
if __name__ == "__main__":
f()
| 0 | null | 11,708,903,292,060 | 42 | 150 |
s=input()
ans=0
if s=="SSS":
ans=0
if s=="SSR" or s=="SRS" or s=="RSS" or s=="RSR":
ans=1
if s=="RRS" or s=="SRR":
ans=2
if s=="RRR":
ans=3
print(ans)
|
s = input()
if s[0] == "S":
if s[1] == "S":
if s[2] == "S":
print("0")
else:
print("1")
if s[1] == "R":
if s[2] == "S":
print("1")
else:
print("2")
if s[0] == "R":
if s[1] == "S":
if s[2] == "S":
print("1")
else:
print("1")
if s[1] == "R":
if s[2] == "S":
print("2")
else:
print("3")
| 1 | 4,822,451,833,888 | null | 90 | 90 |
from collections import deque
def main():
inf = 1000000007
n = int(input())
e = [[] for _ in range(n)]
d = [inf]*n
for i in range(n):
m = list(map(int,input().split()))
for j in range(2,len(m)):
e[m[0]-1].append(m[j]-1)
d[0] = 0
dq = deque([])
dq.append([0,0])
while dq:
c,v = dq.popleft()
for u in e[v]:
if d[u]==inf:
d[u] = c+1
dq.append([c+1,u])
for i in range(n):
if d[i]==inf:print (i+1,-1)
else :print (i+1,d[i])
if __name__ == '__main__':
main()
|
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
N, A, B = MAP()
if abs(A-B)%2 == 0:
print(abs(A-B)//2)
else:
A, B = min(A, B), max(A, B)
print(min((N-B)-(-(B-A)//2), A-1-(-(B-A)//2)))
| 0 | null | 54,882,548,148,120 | 9 | 253 |
a = {1:300000,2:200000,3:100000}
x,y = map(int,input().split())
if x == 1 and y == 1:
print(a[x] + a[y] + 400000)
else:
if x > 3 and y <= 3:
print(a[y])
elif x <= 3 and y > 3:
print(a[x])
elif x>3 and y >3:
print(0)
else:
print(a[x] + a[y])
|
x, y = map(int, input().split(" "))
total = 0
rewards = {1: 300000, 2: 200000, 3: 100000}
x1 = rewards[x] if (x <= 3) else 0
y1 = rewards[y] if (y <= 3) else 0
if (x == 1 and y == 1):
total += 400000
if (x1 != None):
total += x1
if (y1 != None):
total += y1
print(total)
| 1 | 140,507,498,586,350 | null | 275 | 275 |
from collections import defaultdict
N=int(input())
*A,=map(int,input().split())
mod = 10**9+7
count = defaultdict(int)
count[0] = 3
ans = 1
for i in range(N):
ans *= count[A[i]]
ans %= mod
count[A[i]] -= 1
count[A[i]+1] += 1
print(ans)
|
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf,comb
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
from functools import reduce
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()
d = LIST()
mod = 998244353
if d[0] != 0:
print(0)
exit()
c = Counter(d)
counts = [0]*(max(d)+1)
for k, v in c.items():
counts[k] = v
if counts[0] > 1:
print(0)
exit()
ans = 1
for i in range(1, len(counts)):
ans *= pow(counts[i-1], counts[i])
ans %= mod
print(ans)
| 0 | null | 142,515,204,382,240 | 268 | 284 |
def bubbleSort(A, N):
ret = 0
flag = 1
while flag:
flag = 0
for j in range(N-1, 0, -1):
if A[j] < A[j-1]:
A[j], A[j-1] = A[j-1], A[j]
flag = 1
ret += 1
return ret
n = int(input())
a = list(map(int, input().split()))
count = bubbleSort(a, n)
print(" ".join(map(str, a)))
print(count)
|
def bubble_sort(A):
count = 0
for i in reversed(range(len(A))):
for j in range(i):
if A[j] > A[j+1]:
temp = A[j]
A[j] = A[j+1]
A[j+1] = temp
count += 1
return count
N = int(input())
A = list(map(int,input().split()))
count = bubble_sort(A)
print(" ".join(map(str,A)))
print(count)
| 1 | 16,731,905,020 | null | 14 | 14 |
def kougeki(H):
if H == 1:
return 1
else:
return 2 * kougeki(H//2) + 1
H = int(input())
print(kougeki(H))
|
import math
h = int(input())
x = math.floor(math.log2(h)) + 1
y = (2 ** x) - 1
print(y)
| 1 | 80,109,223,804,470 | null | 228 | 228 |
x = input()
x = x.split(" ")
width = int(x[0])
height = int(x[1])
area = width * height
perimeter = width * 2 + height * 2
print("{0} {1}".format(area, perimeter))
|
import math
H = int(input())
cnt = 0
monster = 1
while(H >= 1):
cnt += monster
H = math.floor(H/2)
monster *= 2
print(cnt)
| 0 | null | 40,056,220,134,590 | 36 | 228 |
H,W,K = map(int,input().split())
S = [input().strip() for _ in range(H)]
Ar = []
for i in range(H):
for j in range(W):
if S[i][j]=="#":
Ar.append(i)
break
Ar.append(H)
if len(Ar)==2:
Ac = []
for j in range(W):
if S[Ar[0]][j]=="#":
Ac.append(j)
A = [[1 for _ in range(W)] for _ in range(H)]
Ac.append(W)
Ac[0]=0
if len(Ac)>2:
for k in range(len(Ac)-1):
for j in range(Ac[k],Ac[k+1]):
for i in range(H):
A[i][j] = k+1
else:
Ac = {i:[] for i in range(len(Ar)-1)}
for i in range(len(Ar)-1):
for j in range(W):
if S[Ar[i]][j]=="#":
Ac[i].append(j)
A = [[1 for _ in range(W)] for _ in range(H)]
Ar[0] = 0
cnt = 1
for i in range(len(Ar)-1):
Ac[i][0] = 0
Ac[i].append(W)
for j in range(len(Ac[i])-1):
for j1 in range(Ac[i][j],Ac[i][j+1]):
for i1 in range(Ar[i],Ar[i+1]):
A[i1][j1] = cnt
cnt += 1
for i in range(H):
print(*A[i])
|
H, W, k = map(int, input().split())
a = [list(input()) for _ in range(H)]
res = [[0] * W for _ in range(H)]
cnt = 0
for h in range(H):
for w in range(W):
if a[h][w] == "#":
cnt += 1
res[h][w] = cnt
for h in range(H):
for w in range(W):
if w > 0 and res[h][w] == 0:
res[h][w] = res[h][w - 1]
for h in range(H):
for w in reversed(range(W)):
if w < W - 1 and res[h][w] == 0:
res[h][w] = res[h][w + 1]
for h in range(H):
for w in range(W):
if h > 0 and res[h][w] == 0:
res[h][w] = res[h - 1][w]
for h in reversed(range(H)):
for w in range(W):
if h < H - 1 and res[h][w] == 0:
res[h][w] = res[h + 1][w]
for i in res:
print(*i)
| 1 | 143,573,208,296,568 | null | 277 | 277 |
print(0--int(input())//2)
|
N,K=map(int,input().split())
A=list(map(int,input().split()))
A.sort()
mod=10**9+7
f=[1]
for i in range(N):
f+=[f[-1]*(i+1)%mod]
def comb(a,b):
return f[a]*pow(f[b],mod-2,mod)*pow(f[a-b],mod-2,mod)%mod
max=0
for i in range(K-1,N):
max+=comb(i,K-1)*A[i]
max%=mod
for i in range(N-K+1):
max-=comb(N-i-1,K-1)*A[i]
max%=mod
print(max)
| 0 | null | 77,035,003,787,658 | 206 | 242 |
from collections import Counter
n = int(input())
c = list(input())
count = Counter(c)
ans = float('inf')
w = 0
r = 0
if count.get('R'):
r = count['R']
ans = max(w, r)
for i in range(n):
if c[i]=='W':
w += 1
else:
r -= 1
ans =min(max(w,r), ans)
print(ans)
|
from collections import defaultdict as dict
n, p = map(int, input().split())
s = input()
a = []
for x in s:
a.append(int(x))
def solve():
l = [0]*p
ans = 0
for x in a:
l_ = [0] * p
for i in range(p):
l_[(i * 10 + x) % p] += l[i]
l, l_ = l_, l
l[x % p] += 1
ans += l[0]
print(ans)
if p <= 5:
solve()
exit()
x = 0
mem = dict(int)
mem[0] = 1
ans = 0
a.reverse()
d = 1
for y in a:
x += d*y
x %= p
d = (d * 10) % p
ans += mem[x]
mem[x] += 1
# print(mem)
print(ans)
| 0 | null | 32,051,749,488,508 | 98 | 205 |
n = int(input())
nums = [0]*n
a = int(n**0.5)+1
for x in range(1,a):
for y in range(1,a):
if x**2 + y**2 + x*y > n: break
for z in range(1,a):
s = x**2 + y**2 + z**2 + x*y + y*z + z*x
if s <= n: nums[s-1] += 1
print(*nums, sep="\n")
|
n = int(input())
ANS = [0] * (n+1)
for x in range(1, 101):
for y in range(1, 101):
for z in range(1, 101):
tmp = (x + y + z)**2 - z*(x + y) - (x*y)
if tmp > n: continue
ANS[tmp] += 1
for ans in ANS[1:]:
print(ans)
| 1 | 7,933,672,054,880 | null | 106 | 106 |
s = str(raw_input())
p = str(raw_input())
i = 0
while(1):
if i == len(s):
print "No"
break
if i+len(p) >= len(s):
str = s[i:len(s)] + s[0:len(p)-len(s[i:len(s)])]
else:
str = s[i:i+len(p)]
if str == p:
print "Yes"
break
else:
i += 1
|
from collections import*
(n,m),*c = [[*map(int,i.split())]for i in open(0)]
g = [[]for _ in range(n+1)]
for a,b in c:
g[a]+=[b]
g[b]+=[a]
q=deque([1])
r=[0]*(n+1)
while q:
v=q.popleft()
for i in g[v]:
if r[i]==0:
r[i]=v
q.append(i)
print("Yes",*r[2:],sep="\n")
| 0 | null | 11,216,521,273,792 | 64 | 145 |
import math
x1, y1, x2, y2 = map(float, raw_input().split())
x, y = x2 - x1, y2 - y1
print math.sqrt(x**2 + y**2)
|
# -*- coding: utf-8 -*-
import math
class KochCurve(object):
x = 0.0
y = 0.0
# ?§£???
def koch(self, n, a, b):
if n == 0:
return
s = KochCurve()
t = KochCurve()
u = KochCurve()
th = math.pi * 60.0 / 180.0
s.x = (2.0 * a.x + 1.0 * b.x) / 3.0
s.y = (2.0 * a.y + 1.0 * b.y) / 3.0
t.x = (1.0 * a.x + 2.0 * b.x) / 3.0
t.y = (1.0 * a.y + 2.0 * b.y) / 3.0
u.x = (t.x - s.x) * math.cos(th) - (t.y - s.y) * math.sin(th) + s.x
u.y = (t.x - s.x) * math.sin(th) + (t.y - s.y) * math.cos(th) + s.y
KochCurve().koch(n - 1, a, s)
msg = "%.8f %.8f" % (s.x, s.y)
print(msg)
KochCurve().koch(n - 1, s, u)
msg = "%.8f %.8f" % (u.x, u.y)
print(msg)
KochCurve().koch(n - 1, u, t)
msg = "%.8f %.8f" % (t.x, t.y)
print(msg)
KochCurve().koch(n - 1, t, b)
if __name__ == '__main__':
a = KochCurve()
b = KochCurve()
n = int(input())
a.x = 0
a.y = 0
b.x = 100
b.y = 0
msg = "%.8f %.8f" % (a.x, a.y)
print(msg)
KochCurve().koch(n, a, b)
msg = "%.8f %.8f" % (b.x, b.y)
print(msg)
| 0 | null | 144,949,972,738 | 29 | 27 |
while True:
i = list(map(int, input().split()))
if i[0] == 0 and i[1] == 0:
break
else:
for j in range(i[0]):
for k in range(i[1]):
if j % 2 == 0 and k % 2 == 0:
print("#", end='')
elif j % 2 == 1 and k % 2 == 1:
print("#", end='')
else:
print(".", end='')
print("\n", end='')
print("\n", end='')
|
from collections import Counter
import math
n = int(input())
pp = []
a0 = 0
b0 = 0
z = 0
for i in range(n):
a,b = map(int,input().split())
if a==0 and b==0:
z += 1
elif a==0:
a0 += 1
elif b==0:
b0 += 1
else:
gomi = math.gcd(a,b)
if a < 0:
a *= -1
b *= -1
pp.append((a//gomi,b//gomi))
mod = 10**9+7
a0 %= mod
b0 %= mod
z %= mod
p = Counter(pp)
r = 1
s = set()
for i,j in p.keys():
if (i,j) in s:
continue
ans = p[(i,j)]
if j < 0:
f = (-j,i)
else:
f = (j,-i)
chk = p[f]
r *= (pow(2,ans,mod)+pow(2,chk,mod)-1)%mod
r %= mod
s.add(f)
r *= (pow(2,a0,mod)+pow(2,b0,mod)-1)%mod
r %= mod
print((r+z-1)%mod)
| 0 | null | 10,859,763,856,068 | 51 | 146 |
def gcd(a, b):
if a < b:
return gcd(b, a)
while b > 0:
a, b = b, a % b
return a
n, m = map(int, input().split())
a = list(map(int, input().split()))
x = 1
for i in range(n):
b = a[i] // 2
x = x * b // gcd(x, b)
if any(2 * x // y % 2 == 0 for y in a):
print(0)
quit()
print((m - x) // (2 * x) + 1)
|
N, M = map(int, input().split())
a = list(map(int, input().split()))
for k in range(N):
a[k] //= 2
foo = 1
while a[0]%2 == 0:
foo *= 2
a[0] //= 2
for k in range(1, N):
if a[k] % foo == 0 and a[k]%(2*foo) !=0:
a[k] //= foo
continue
else:
print(0)
exit()
ans = 0
for odd in [3, 5, 7, 11]:
flag = False
for k in range(N):
if a[k]%odd == 0:
a[k] //= odd
flag = True
if flag:
foo *= odd
def euclid(a, b):
while b:
a, b = b, a%b
return a
lcm = a.pop()
for k in range(1, N):
b = a.pop()
lcm = lcm * b // euclid(lcm, b)
if lcm* foo > M:
print(0)
exit()
lcm *= foo
ans = int((M / lcm -1)//2 + 1)
print(ans)
| 1 | 102,014,261,096,160 | null | 247 | 247 |
def main():
n = int(input())
s = input()
if n % 2 == 0:
sl = len(s) // 2
s1 = s[:sl]
s2 = s[sl:]
if s1 == s2:
print('Yes')
else:
print('No')
else:
print('No')
if __name__ == '__main__':
main()
|
import math
X = int(input())
print(int(360 / math.gcd(360, X)))
| 0 | null | 80,245,813,468,096 | 279 | 125 |
import sys
sys.setrecursionlimit(1000000000)
import math
from math import gcd
def lcm(a, b): return a * b // gcd(a, b)
from itertools import count, permutations, chain, accumulate
from functools import lru_cache
from collections import deque, defaultdict
from pprint import pprint
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')
N1097 = 10**9 + 7
def meg(f, ok, ng):
while abs(ok-ng)>1:
mid = (ok+ng)//2
if f(mid):
ok=mid
else:
ng=mid
return ok
def get_inv(n, modp):
return pow(n, modp-2, modp)
def factorials_list(n, modp): # 10**6
fs = [1]
for i in range(1, n+1):
fs.append(fs[-1] * i % modp)
return fs
def invs_list(n, fs, modp): # 10**6
invs = [get_inv(fs[-1], modp)]
for i in range(n, 1-1, -1):
invs.append(invs[-1] * i % modp)
invs.reverse()
return invs
def comb(n, k, modp):
num = 1
for i in range(n, n-k, -1):
num = num * i % modp
den = 1
for i in range(2, k+1):
den = den * i % modp
return num * get_inv(den, modp) % modp
def comb_from_list(n, k, modp, fs, invs):
return fs[n] * invs[n-k] * invs[k] % modp
#
class UnionFindEx:
def __init__(self, size):
#正なら根の番号、負ならグループサイズ
self.roots = [-1] * size
def getRootID(self, i):
r = self.roots[i]
if r < 0: #負なら根
return i
else:
r = self.getRootID(r)
self.roots[i] = r
return r
def getGroupSize(self, i):
return -self.roots[self.getRootID(i)]
def connect(self, i, j):
r1, r2 = self.getRootID(i), self.getRootID(j)
if r1 == r2:
return False
if self.getGroupSize(r1) < self.getGroupSize(r2):
r1, r2 = r2, r1
self.roots[r1] += self.roots[r2] #サイズ更新
self.roots[r2] = r1
return True
Yes = 'Yes'
No = 'No'
def main():
N,K = mis()
A = lmis()
for _ in range(K):
l = [0]*(N+1)
for i in range(N):
a = A[i]
l[max(0, i-a)] += 1
l[min(N, i+a+1)] -= 1
A = list(accumulate(l))[:-1]
if all(a==N for a in A):
break
print(*A)
main()
|
N = int(input())
l = [1] * N
i = 0
d = {1:0,2:0,3:0}
for s in input():
n = 1
if s == "G":
n = 2
elif s == "B":
n = 3
l[i] = n
d[n] += 1
i += 1
cnt = d[1] * d[2] * d[3]
for j in range(1,(N - 1) // 2 + 1):
for k in range(N - (2 * j)):
if l[k] * l[k+j] * l[k+j+j] == 6:
cnt -= 1
print(cnt)
| 0 | null | 25,939,381,930,528 | 132 | 175 |
def warshall_floyd(edge):
e=edge
for k in range(len(e)):
for i in range(len(e)):
for j in range(len(e)):
e[i][j]=min(e[i][j],e[i][k]+e[k][j])
return e
n,m,l=map(int,input().split())
edge=[n*[10**18]for _ in range(n)]
for i in range(n):
edge[i][i]=0
for i in range(m):
a,b,c=map(int,input().split())
a-=1
b-=1
edge[a][b]=edge[b][a]=c
edge=warshall_floyd(edge)
edge2=[n*[10**18]for _ in range(n)]
for i in range(n):
edge2[i][i]=0
for j in range(n):
if edge[i][j]<=l:
edge2[i][j]=1
edge2=warshall_floyd(edge2)
q=int(input())
for i in range(q):
s,t=map(int,input().split())
s-=1
t-=1
ans=edge2[s][t]
if ans==10**18:
print(-1)
else:
print(ans-1)
|
from scipy.sparse.csgraph import floyd_warshall
# ダイクストラではなくワーシャルフロイドで解く
N, M, L = map(int, input().split())
# graph = [[] for _ in range(N)]
distant = [[float('inf')]*N for _ in range(N)]
for _ in range(M):
a, b, c = map(int, input().split())
a, b = a-1, b-1
if c > L:
continue
distant[a][b] = c
distant[b][a] = c
distant = floyd_warshall(distant)
another = [[float('inf')]*N for _ in range(N)]
for i in range(N):
for j in range(N):
if distant[i][j] <= L: # 行けるところまでいくという印象
another[i][j] = 1
another = floyd_warshall(another)
Q = int(input())
for _ in range(Q):
s, t = map(lambda x: int(x)-1, input().split())
if another[s][t] == float('inf'):
print(-1)
continue
print(int(another[s][t])-1)
# if distant[s][t] == float('inf'):
# print(-1)
# continue
# print(int(distant[s][t])//L + min(1, int(distant[s][t]) % L) - 1)
# 燃料が4で
# 1 -> 4 -> 2
# のとき、距離は7だから一見すると補給回数は1で良さそうだけど、実は2回必要
# 今、2点間の最小距離を求めておいて、もう一つのグラフは「最短距離がL以下の2点に辺(重み1)を張る」
| 1 | 173,611,971,942,440 | null | 295 | 295 |
import math
def combinations_count(n, r):
return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
N, M = map(int, input().split())
ans = 0
if N >= 2:
ans += combinations_count(N, 2)
if M >= 2:
ans += combinations_count(M, 2)
print(ans)
|
import sys,queue,math,copy,itertools,bisect,collections,heapq
def main():
sys.setrecursionlimit(10**7)
INF = 10**18
MOD = 10**9 + 7
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
_LI = lambda : [int(x)-1 for x in sys.stdin.readline().split()]
NI = lambda : int(sys.stdin.readline())
SI = lambda : sys.stdin.readline().rstrip()
N = [0] + list(map(int,SI()))
ans = 0
for i in range(len(N)-1,-1,-1):
if N[i] < 6 and not(N[i] == 5 and (i > 0 and N[i-1] >= 5)):
ans += N[i]
else:
ans += 10 - N[i]
N[i-1] += 1
print(ans)
if __name__ == '__main__':
main()
| 0 | null | 58,384,526,616,790 | 189 | 219 |
n, k, c = map(int, input().split())
S = input()
# 要素の値は何回目の働く日か(0は働いていない状態)
by_left = [0] * n
by_right = [0] * n
# 左から貪欲
rest = 0
cnt = 1
for itr, s in enumerate(S):
rest -= 1
if rest <= 0 and s == "o":
by_left[itr] = cnt
cnt += 1
rest = c + 1
# 右から貪欲
rest = 0
cnt = k
for itr, s in enumerate(S[::-1]):
rest -= 1
if rest <= 0 and s == "o":
by_right[n - itr- 1] = cnt
cnt -= 1
rest = c + 1
# 左右からの貪欲で、どちらでも同じ働く回数の値が入っている日が必ず働く日
ans = [itr + 1 for itr, (i, j) in enumerate(zip(by_left, by_right)) if i != 0 and i == j]
for a in ans:
print(a)
|
# -*- coding: utf-8 -*-
import collections
N = int(input())
all_str = []
for i in range(N):
str_temp = input()
all_str.append(str_temp)
all_str.sort()
coll_str = (collections.Counter(all_str))
count_max = 0
j = 0
max_str = coll_str.most_common()
for i in max_str:
num_of_str = i[1]
if num_of_str == count_max or j == 0:
print(i[0])
j = 1
count_max = num_of_str
if num_of_str < count_max:
break
| 0 | null | 55,286,841,062,950 | 182 | 218 |
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)))
|
i=0
while True:
a = input()
if a == 0:
break
else:
i=i+1
print "Case",str(i)+":", a
| 0 | null | 89,246,838,632,810 | 297 | 42 |
n = int(input())
a = list(map(int,input().split()))
mod = 10**9+7
ans = 0
for i in range(60):
x = 1<< i
l = len([1 for j in a if j & x])
ans += x * l * (n-l) % mod
ans %= mod
print(ans)
|
import sys
sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7
def resolve():
n = int(input())
A = list(map(int, input().split()))
res = 0
for i in range(60):
cnt = 0
for a in A:
cnt += (a >> i) & 1
res += (cnt * (n - cnt)) % mod * (1 << i) % mod
res %= mod
print(res)
if __name__ == '__main__':
resolve()
| 1 | 122,447,120,728,658 | null | 263 | 263 |
table = [[[ 0 for i in range(10)] for j in range(3)] for k in range(4)]
n = int(input())
i = 0
while i < n:
b,f,r,v = (int(x) for x in input().split())
table[b-1][f-1][r-1] += v
i += 1
for i,elem_i in enumerate(table): # building
for j,elem_j in enumerate(elem_i): # floor
for k, elem_k in enumerate(elem_j): # room
print (" " + str(elem_k), end='')
print ("")
if i != 3:
print ("####################")
|
n = int(input())
buffer = []
i = 0
while i<n:
b,f,r,v = map(int,input().split())
buffer.append([b,f,r,v])
i = i + 1
room = []
for h in range(15):
if h == 3 or h == 7 or h == 11:
room.append(['**']*10)
else:
room.append([0]*10)
for y in range(n):
if buffer[y][0] == 1:
room[buffer[y][1]-1][buffer[y][2]-1] = buffer[y][3] + room[buffer[y][1]-1][buffer[y][2]-1]
elif buffer[y][0] == 2:
room[buffer[y][1]-1+4][buffer[y][2]-1] = buffer[y][3] + room[buffer[y][1]-1+4][buffer[y][2]-1]
elif buffer[y][0] == 3:
room[buffer[y][1]-1+8][buffer[y][2]-1] = buffer[y][3] + room[buffer[y][1]-1+8][buffer[y][2]-1]
elif buffer[y][0] == 4:
room[buffer[y][1]-1+12][buffer[y][2]-1] = buffer[y][3] + room[buffer[y][1]-1+12][buffer[y][2]-1]
for x in range(15):
if x == 3 or x == 7 or x == 11:
print("####################")
else:
for y in range(10):
print(" "+str(room[x][y]), end = "")
print()
| 1 | 1,116,352,501,638 | null | 55 | 55 |
n,K=input(),int(input())
m=len(n)
DP=[[[0]*(K+2) for _ in range(2)] for _ in range(m+1)]
DP[0][0][0]=1
for i in range(1,m+1):
for flag in range(2):
num=9 if flag else int(n[i-1])
for j in range(K+1):
for k in range(num+1):
if k!=0:DP[i][flag or k<num][j+1] +=DP[i-1][flag][j]
else:DP[i][flag or k<num][j] +=DP[i-1][flag][j]
print(DP[m][0][K]+DP[m][1][K])
|
n = int(input())
print((n-1)//2)
| 0 | null | 114,809,249,812,190 | 224 | 283 |
g = list(input())
sum, d, r, p = 0, 0, 0, 0
f = 0
lake_list = []
for c in g:
if c == "\\":
if f == 0:
f, d, r = 1, 1, 1
else:
d += 1
r += (1 + (d-1))
elif c == "_":
if f == 1:
r += d
else:
if f == 1:
d -= 1
r += d
if d == 0:
f = 0
sum += r
lake_list.append([p, r])
r = 0
p += 1
d, r, p = 0, 0, len(g)-1
f = 0
g.reverse()
for c in g:
if c == "/":
if f == 0:
f, d, r = 1, 1, 1
pr = p
else:
d += 1
r += (1 + (d-1))
elif c == "_":
if f == 1:
r += d
else:
if f == 1:
d -= 1
r += d
if d == 0:
if [pr, r] not in lake_list:
sum += r
lake_list.append([pr, r])
f = 0
r = 0
p -= 1
lake_list.sort()
print(sum)
print(len(lake_list), end="")
i = 0
while i != len(lake_list):
print(" {}".format(lake_list[i][1]), end="")
i += 1
print()
|
MOD = 998244353
def solve():
if D[0] != 0 or 0 in D[1:]:
print(0)
return
tree_dict = dict()
max_dist = 0
for idx, dist in enumerate(D):
tree_dict[dist] = tree_dict.get(dist, 0) + 1
max_dist = max(max_dist, dist)
ret = 1
for dist in range(max_dist + 1):
if not dist in tree_dict:
print(0)
return
ret = (ret * pow(tree_dict.get(dist - 1, 1), tree_dict[dist])) % MOD
print(ret)
if __name__ == "__main__":
N = int(input())
D = list(map(int, input().split()))
solve()
| 0 | null | 77,429,962,215,900 | 21 | 284 |
import math
import itertools
n = int(input())
al = [0] * n
bl = [0] * n
for i in range(n):
al[i], bl[i] = map(int, input().split())
bunbo = math.factorial(n)
ans = 0
for p in itertools.permutations(list(range(n))):
for i in range(n-1):
ans += ((al[p[i+1]]-al[p[i]])**2+(bl[p[i+1]]-bl[p[i]])**2)**0.5
print(ans/bunbo)
|
S, T = input(), input()
print(sum(x != y for x, y in zip(S, T)))
| 0 | null | 79,195,696,248,128 | 280 | 116 |
# -*- coding:utf-8 -*-
n = int(input())
import sys
a = input()
a = a.split()
a = [int(i) for i in a]
a.reverse()
for i in range(n-1):
print(a[i],end = ' ')
print(a[n-1])
|
n = int(input())
given_list = list(map(int, input().split()))
for i in range(n):
if i == n-1:
print(given_list[n-i-1])
else:
print(given_list[n-i-1], end=" ")
| 1 | 986,381,406,852 | null | 53 | 53 |
n, m, l = map(int, input().split())
A = [[] for a in range(n)]
B = [[] for b in range(m)]
C = [[0 for c in range(l)] for d in range(n)]
for a in A:
a += list(map(int, input().split()))
for b in B:
b += list(map(int, input().split()))
for k,x in enumerate(C):
for y in range(l):
for z in range(m):
C[k][y] += A[k][z]*B[z][y]
for x in C:
for k,y in enumerate(x):
if k == l-1:
print(y)
else:
print(y,end=" ")
|
#!/usr/bin/env python3
import sys
INF = float("inf")
def solve(N: int, T: int, A: "List[int]", B: "List[int]"):
# DP1
# 1からi番目の料理でj分以内に完食できる美味しさの合計の最大値
DP1 = [[0 for _ in range(T+1)] for __ in range(N+1)]
for i in range(1, N+1):
for j in range(1, T+1):
if j-A[i-1] >= 0:
DP1[i][j] = max(DP1[i][j], DP1[i-1][j-A[i-1]]+B[i-1])
DP1[i][j] = max(DP1[i][j], DP1[i-1][j], DP1[i][j-1])
# DP2
# i番目からN番目の料理でj分以内に完食できる美味しさの合計の最大値
DP2 = [[0 for _ in range(T+1)] for __ in range(N+2)]
for i in range(N, 0, -1):
for j in range(1, T+1):
if j-A[i-1] >= 0:
DP2[i][j] = max(DP2[i][j], DP2[i+1][j-A[i-1]]+B[i-1])
DP2[i][j] = max(DP2[i][j], DP2[i+1][j], DP2[i][j-1])
# i番目以外の料理でT-1分以内に完食できる美味しさの合計の最大値
ans = 0
for i in range(1, N+1):
bns = 0
for j in range(T):
bns = max(bns, DP1[i-1][j] + DP2[i+1][T-j-1])
ans = max(ans, bns+B[i-1])
print(ans)
return
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
T = int(next(tokens)) # type: int
A = [int()] * (N) # type: "List[int]"
B = [int()] * (N) # type: "List[int]"
for i in range(N):
A[i] = int(next(tokens))
B[i] = int(next(tokens))
solve(N, T, A, B)
if __name__ == '__main__':
main()
| 0 | null | 76,649,815,107,908 | 60 | 282 |
import heapq
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
f = list(map(int, input().split()))
f.sort(reverse=True)
asum = sum(a)
def test(x):
t = [min(a[i], x//f[i]) for i in range(n)]
return asum - sum(t)
ng = -1
ok = 10**13
while abs(ok-ng)>1:
mid = (ok+ng)//2
if test(mid) <= k:
ok = mid
else:
ng = mid
print(ok)
|
from collections import deque
def solve(n,t):
q=deque([])
for i in range(n):
l=list(input().split())
q.append(l)
time=0
while not len(q)==0:
x=q.popleft()
if int(x[1])-t>0:
x[1]=str(int(x[1])-t)
time+=t
q.append(x)
else:
print(x[0]+" "+str(time+int(x[1])))
time+=int(x[1])
n,t=map(int,input().split())
solve(n,t)
| 0 | null | 82,840,555,663,268 | 290 | 19 |
# coding: utf-8
a , b = map(int,input().split())
c , d = map(int,input().split())
if a + 1 == c:
print(1)
else:
print(0)
|
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def popcnt(n):
return bin(n).count("1")
def mod(n, cnt):
if n == 0:
return cnt
n = n % popcnt(n)
cnt += 1
return mod(n, cnt)
n = int(readline())
x2 = list(readline().decode().rstrip())
x10 = int(''.join(x2), 2)
c = x2.count('1')
mod1 = x10 % (c + 1)
mod2 = x10 % (c - 1) if c - 1 != 0 else 0
for i in range(n):
if x2[i] == '0':
t = (mod1 + pow(2, n - i - 1, c + 1)) % (c + 1)
else:
if c - 1 != 0:
t = (mod2 - pow(2, n - i - 1, c - 1)) % (c - 1)
else:
print(0)
continue
print(mod(t, 1))
| 0 | null | 66,387,566,493,868 | 264 | 107 |
n,m=map(int,input().split())
if (n>0) and (m>0):
print(int(n*(n-1)/2+m*(m-1)/2))
else:
print(int(max(n,m)*(max(n,m)-1)/2))
|
n=int(input())
i=int(n**0.5)
while n%i:
i-=1
print(i+n//i-2)
| 0 | null | 103,527,113,182,008 | 189 | 288 |
n = int(input())
S = list(map(int, input().split(' ')))
q = int(input())
T = list(map(int, input().split(' ')))
counter = 0
for t in T:
for s in S:
if(s == t):
counter += 1
break
print(counter)
|
N = int(input())
sqrt_N = int(N ** 0.5)
dividers_for_N = set()
ans_set = set()
for i in range(1, sqrt_N + 1):
if (N - 1) % i == 0:
ans_set.add(i)
ans_set.add((N - 1) // i)
if N % i == 0:
dividers_for_N.add(i)
dividers_for_N.add(N // i)
dividers_for_N -= {1}
ans_set -= {1}
for i in dividers_for_N:
num = N
while num % i == 0:
num //= i
if num % i == 1:
ans_set.add(i)
ans = len(ans_set)
print(ans)
| 0 | null | 20,825,383,119,028 | 22 | 183 |
import sys
lines = [s.rstrip("\n") for s in sys.stdin.readlines()]
n = int(lines.pop(0))
s = lines.pop(0)
count = 0
prev_c = None
for c in s:
if c != prev_c:
count += 1
prev_c = c
print(count)
|
n = int(input())
x = list(map(float, input().split()))
y = list(map(float, input().split()))
dif = [abs(i-j) for i, j in zip(x, y)]
print(sum(dif))
print(sum([i**2 for i in dif])**0.5)
print(sum([i**3 for i in dif])**(1/3))
print(max(dif))
| 0 | null | 84,845,756,617,280 | 293 | 32 |
if __name__ == '__main__':
n = int(input())
A = list(map(int,input().split()))
cnt = 0
for i in A:
if i % 2 == 0:
if i % 3 == 0 or i % 5 == 0:
cnt += 1
else:
cnt += 1
if cnt == n:
print("APPROVED")
else:
print("DENIED")
|
import math
A, B, N = list(map(int,input().split()))
def f(x):
return math.floor(A * x / B) - A * math.floor(x / B)
if B - 1 <= N:
ans = f(B - 1)
else:
ans = f(N)
print(ans)
| 0 | null | 48,453,451,556,604 | 217 | 161 |
a, b, m = map(int, input().split())
re = list(map(int, input().split()))
de = list(map(int, input().split()))
mre = min(re)
mde = min(re)
list1 = []
for i in range(m):
x, y, c = map(int, input().split())
price = re[x-1] + de[y-1] -c
list1.append(price)
mlist = min(list1)
m1 = mre + mde
if m1 < mlist:
print(m1)
else:
print(mlist)
|
A, B, M = map(int, input().split())
la = list(map(int, input().split()))
lb = list(map(int, input().split()))
prm_min = min(la) + min(lb)
lcost = list()
for i in range(M):
x, y, c = map(int, input().split())
lcost.append(la[x-1] + lb[y-1] - c)
print(min(min(lcost), prm_min))
| 1 | 54,105,741,407,088 | null | 200 | 200 |
import sys
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
n,m,l = map(int, input().split())
d=[[sys.maxsize]*(n) for _ in range(n)]
e=[[sys.maxsize]*(n) for _ in range(n)]
for i in range(n):
d[i][i] = 0
e[i][i] = 0
for _ in range(m):
a,b,c = map(int, input().split())
d[a-1][b-1]=c
d[b-1][a-1]=c
d=floyd_warshall(csr_matrix(d))
for i in range(n):
for j in range(n):
if d[i][j] <= l:
e[i][j] = 1
e=floyd_warshall(csr_matrix(e))
q=int(input())
for _ in range(q):
s,t = map(int, input().split())
if e[s-1][t-1] == sys.maxsize:
print(-1)
else:
print(int(e[s-1][t-1]-1))
|
N=int(input())
a=[0]*10**4
for j in range(1,101):
for k in range(1,101):
for h in range(1,101):
tmp=h**2+j**2+k**2+h*j+j*k+k*h
if tmp<=10000:
a[tmp-1]+=1
for i in range(N):
print(a[i])
| 0 | null | 90,426,718,106,298 | 295 | 106 |
import math
a,b,x=map(int,input().split())
if a*a*b==x:
ans=90
elif x>((a**2)*b)/2:
ans=math.degrees(math.atan(a/(2*(b-(x/(a**2))))))
else:
ans=math.degrees(math.atan((2*x)/(a*(b**2))))
print(90-ans)
|
import math
a, b, x = map(float, input().split())
if a * a * b <= x * 2:
h = 2 * (b - x / a / a)
ret = math.degrees(math.atan2(h, a))
else:
h = 2 * x / a / b
ret = 90 - math.degrees(math.atan2(h, b))
print(ret)
| 1 | 163,606,068,826,080 | null | 289 | 289 |
def II(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
N=II()
A=LI()
cnt=[0]*((10**6)+1)
for elem in A:
cnt[elem]+=1
unique=[]
for i in range((10**6)+1):
if cnt[i]==1:
unique.append(i)
cnt=[0]*((10**6)+1)
A=list(set(A))
for elem in A:
for m in range(elem*2,10**6+1,elem):
cnt[m]=1
ans=0
for i in unique:
if cnt[i]==0:
ans+=1
print(ans)
|
N = int(input())
*A, = map(int, input().split())
# N = 5
# A = list([24, 11, 8, 3, 16])
M = max(A) + 1
cnt =[0 for _ in range(M)]
for i in A:
for j in range(i, M, i):
cnt[j] += 1
ans = 0
for k in A:
if cnt[k] == 1:
ans += 1
print(ans)
| 1 | 14,269,991,639,762 | null | 129 | 129 |
def main():
import sys
n,s,_,*t=sys.stdin.buffer.read().split()
n=int(n)
d=[0]*n+[1<<c-97for c in s]
for i in range(n-1,0,-1):d[i]=d[i+i]|d[i-~i]
r=[]
for q,a,b in zip(*[iter(t)]*3):
i,s=int(a)+n-1,0
if q<b'2':
d[i]=1<<b[0]-97
while i:
i//=2
d[i]=d[i+i]|d[i-~i]
continue
j=int(b)+n
while i<j:
if i&1:
s|=d[i]
i+=1
if j&1:
j-=1
s|=d[j]
i//=2
j//=2
r+=bin(s).count('1'),
print(' '.join(map(str,r)))
main()
|
class SegmentTree():
def segfunc(self, x, y):
return x|y #関数
def __init__(self, a): #a:リスト
n = len(a)
self.ide_ele = 0 #単位元
self.num = 2**((n-1).bit_length()) #num:n以上の最小の2のべき乗
self.seg = [self.ide_ele]*2*self.num
#set_val
for i in range(n):
self.seg[i+self.num-1] = a[i]
#built
for i in range(self.num-2,-1,-1):
self.seg[i] = self.segfunc(self.seg[2*i+1], self.seg[2*i+2])
def update(self, k, s):
x = 1<<(ord(s)-97)
k += self.num-1
self.seg[k] = x
while k:
k = (k-1)//2
self.seg[k] = self.segfunc(self.seg[k*2+1], self.seg[k*2+2])
def query(self, p, q):
if q <= p:
return self.ide_ele
p += self.num-1
q += self.num-2
res = self.ide_ele
while q - p > 1:
if p&1 == 0:
res = self.segfunc(res, self.seg[p])
if q&1 == 1:
res = self.segfunc(res, self.seg[q])
q -= 1
p = p//2
q = (q-1)//2
if p == q:
res = self.segfunc(res,self.seg[p])
else:
res = self.segfunc(self.segfunc(res,self.seg[p]),self.seg[q])
return res
def popcount(x):
'''xの立っているビット数をカウントする関数
(xは64bit整数)'''
# 2bitごとの組に分け、立っているビット数を2bitで表現する
x = x - ((x >> 1) & 0x5555555555555555)
# 4bit整数に 上位2bit + 下位2bit を計算した値を入れる
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f # 8bitごと
x = x + (x >> 8) # 16bitごと
x = x + (x >> 16) # 32bitごと
x = x + (x >> 32) # 64bitごと = 全部の合計
return x & 0x0000007f
N = int(input())
S = list(input())
for i in range(N):
S[i] = 1<<(ord(S[i])-97)
Seg = SegmentTree(S)
Q = int(input())
for i in range(Q):
x, y, z = input().split()
if int(x) == 1:
Seg.update(int(y)-1, z)
else:
print(popcount(Seg.query(int(y)-1, int(z))))
| 1 | 62,648,880,622,382 | null | 210 | 210 |
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy,bisect
from operator import itemgetter
#from heapq import heappush, heappop
#import numpy as np
#from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
#from scipy.sparse import csr_matrix
#from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7
stdin = sys.stdin
ni = lambda: int(ns())
nf = lambda: float(ns())
na = lambda: list(map(int, stdin.readline().split()))
nb = lambda: list(map(float, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip() # ignore trailing spaces
N, M = na()
print(N * (N - 1) // 2 + M * (M - 1) // 2)
|
N, M = [int(i) for i in input().split(' ')]
print((N * (N - 1) + M * (M - 1)) // 2)
| 1 | 45,552,108,455,300 | null | 189 | 189 |
n, k = map(int, input().split())
snukes = []
for _ in range(k):
okashi = int(input())
snukes += [int(v) for v in input().split()]
target = 1
cnt = 0
l = list(set(snukes))
s = [int(v) for v in range(1, n + 1)]
for p in s:
if p not in l:
cnt += 1
print(cnt)
|
n, k = map(int, input().split())
sunuke = []
for s in range(n):
sunuke.append(str(s+1))
for t in range(k):
d = int(input())
hito = input().split(" ")
for u in range(d):
for v in range(n):
if hito[u] == sunuke[v]:
sunuke[v] = 0
else:
pass
m = sunuke.count(0)
print(n-m)
| 1 | 24,502,641,107,410 | null | 154 | 154 |
N = int(input())
ans = set()
for i in range(1, N + 1):
j = N - i
if i == j or i == 0 or j == 0:
continue
ans.add((min(i, j), max(i, j)))
print(len(ans))
|
n = int(input())
a,b = divmod(n,2)
if b == 0:
a -= 1
print(a)
| 1 | 153,395,828,886,300 | null | 283 | 283 |
import re
W = input()
T = []
count = 0
while(1):
line = input()
if (line == "END_OF_TEXT"):
break
words = list(line.split())
for word in words:
T.append(word)
for word in T:
matchOB = re.fullmatch(W, word.lower())
if matchOB:
count += 1
print(count)
|
import sys
e=[list(map(int,x.split()))for x in sys.stdin];n=e[0][0]+1
[print(*x)for x in[[sum(s*t for s,t in zip(c,l))for l in zip(*e[n:])]for c in e[1:n]]]
| 0 | null | 1,618,544,963,910 | 65 | 60 |
# https://atcoder.jp/contests/abc157/tasks/abc157_e
from string import ascii_lowercase
from bisect import bisect_left, insort
from collections import defaultdict
N = int(input())
S = list(input())
Q = int(input())
locs = {c: [] for c in ascii_lowercase}
for i in range(N):
locs[S[i]].append(i + 1)
for _ in range(Q):
qt, l, r = input().split()
l = int(l)
if int(qt) == 1:
if S[l - 1] != r:
locs[S[l - 1]].remove(l)
S[l - 1] = r
insort(locs[r], l)
else:
count = 0
r = int(r)
for ch in ascii_lowercase:
if len(locs[ch]) > 0:
left = bisect_left(locs[ch], l)
if left != len(locs[ch]):
if locs[ch][left] <= r:
count += 1
print(count)
|
import bisect
n=int(input())
s=list(input())
#アルファベットの各文字に対してからのリストを持つ辞書
alpha={chr(i):[] for i in range(97,123)}
#alpha[c]で各文字ごとに出現場所をソートして保管
for i,c in enumerate(s):
bisect.insort(alpha[c],i+1)
for i in range(int(input())):
p,q,r=input().split()
if p=='1':
q=int(q)
b=s[q-1]
if b!=r:
alpha[b].pop(bisect.bisect_left(alpha[b],q))
bisect.insort(alpha[r],q)
s[q-1]=r
else:
count=0
for l in alpha.values():
pos=bisect.bisect_left(l,int(q))
if pos<len(l) and l[pos]<=int(r):
count+=1
print(count)
| 1 | 62,616,289,256,080 | null | 210 | 210 |
h,w,k = map(int,input().split())
s = [list(input()) for i in range(h)]
a = [[0]*w for i in range(h)]
num = 1
for i in range(h):
b = s[i]
if "#" in b:
t = b.count("#")
for j in range(w):
c = b[j]
# print(c)
if c=="#" and t!=1:
a[i][j] = num
num += 1
t -= 1
elif c=="#" and t==1:
a[i][j] = num
t = -1
else:
a[i][j] = num
if t==-1:
num += 1
else:
if i==0:
continue
else:
for j in range(w):
a[i][j] = a[i-1][j]
index = 0
for i in range(h):
if "#" not in s[i]:
index += 1
else:
break
for j in range(index):
for k in range(w):
a[j][k] = a[index][k]
for j in a:
print(*j)
|
from __future__ import print_function
import sys
officalhouse = [0]*4*3*10
n = int( sys.stdin.readline() )
for i in range( n ):
b, f, r, v = [ int( val ) for val in sys.stdin.readline().split( " " ) ]
bfr = (b-1)*30+(f-1)*10+(r-1)
officalhouse[bfr] = officalhouse[bfr] + v;
output = []
for b in range( 4 ):
for f in range( 3 ):
for r in range( 10 ):
output.append( " {:d}".format( officalhouse[ b*30 + f*10 + r ] ) )
output.append( "\n" )
if b < 3:
output.append( "####################\n" )
print( "".join( output ), end="" )
| 0 | null | 72,178,648,192,108 | 277 | 55 |
N,M=map(int,input().split())
H=list(map(int,input().split()))
cnt=[1 for _ in range(N)]
for _ in range(M):
A,B=map(int,input().split())
A-=1
B-=1
if H[A]>H[B]:
cnt[B]=0
elif H[A]<H[B]:
cnt[A]=0
else:
cnt[A]=0
cnt[B]=0
print(cnt.count(1))
|
N,M=map(int, input().split())
peaks=list(map(int, input().split()))
flag=[1]*N
a=0
b=0
for i in range(M):
a,b=map(int,input().split())
a-=1
b-=1
if peaks[a]<=peaks[b]:
flag[a]=0
if peaks[a]>=peaks[b]:
flag[b]=0
ans=0
for i in flag:
ans+=i
print(ans)
| 1 | 25,191,354,099,548 | null | 155 | 155 |
while True:
n = input()
if n == '0':
break
print(sum([int(x) for x in n]))
|
while True:
N=input()
if N=="0":
break
else:
print(sum([int(x) for x in list(N)]))
| 1 | 1,563,251,461,596 | null | 62 | 62 |
def f():return map(int,raw_input().split())
n,m,l=f()
A = [f() for _ in [0]*n]
B = [f() for _ in [0]*m]
C = [[0 for _ in [0]*l] for _ in [0]*n]
for i in range(n):
for j in range(l):
print sum([A[i][k]*B[k][j] for k in range(m)]),
print
|
N=int(input())
Xlist=list(map(int,input().split()))
ans=10**18
for p in range(1,101):
ans=min(ans,sum(list(map(lambda x:(p-x)**2,Xlist))))
print(ans)
| 0 | null | 33,194,396,673,692 | 60 | 213 |
from collections import Counter
s = input()
MOD = 2019
ts = [0]
cur = 0
for i, j in enumerate(s[::-1], 1):
cur = (cur + pow(10, i, MOD) * int(j)) % MOD
ts.append(cur)
ct = Counter(ts)
res = 0
for k, v in ct.items():
if v > 1:
res += v * (v-1) // 2
print(res)
|
N=int(input())
M=1000
if N%M==0:
print(0)
else:
print(M-N%M)
| 0 | null | 19,629,170,168,832 | 166 | 108 |
from collections import deque
H, W = map(int, input().split())
maze = [input() for _ in range(H)]
v = {(1,0), (-1,0), (0,1), (0,-1)}
q = deque()
ans = 0
for i in range(H):
for j in range(W):
if maze[i][j] == '.':
#bfs
dist = [[-1 for _ in range(W)] for _ in range(H)]
dist[i][j] = 0
q.append([j, i])
while len(q) > 0:
now = q.popleft()
x, y = now[0], now[1]
d = dist[y][x]
for dx, dy in v:
nx, ny = x+dx, y+dy
if 0<=nx<W and 0<=ny<H and dist[ny][nx]==-1 and maze[ny][nx]=='.':
dist[ny][nx] = d+1
q.append([nx, ny])
ans = max(ans, d)
print(ans)
|
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
#from decimal import *
H, W = MAP()
S = [input() for _ in range(H)]
dy = (1, 0, -1, 0)
dx = (0, -1, 0, 1)
def diff_max(start_y, start_x):
check = [[-1]*W for _ in range(H)]
check[start_y][start_x] = 0
q = deque([(start_y, start_x)])
while q:
y, x = q.popleft()
for i in range(4):
ny = y + dy[i]
nx = x + dx[i]
if 0 <= ny < H and 0 <= nx < W:
if check[ny][nx] == -1 and S[ny][nx] == ".":
check[ny][nx] = check[y][x] + 1
q.append((ny, nx))
return max([max(x) for x in check])
ans = -INF
for i in range(H):
for j in range(W):
if S[i][j] == ".":
ans = max(ans, diff_max(i, j))
print(ans)
| 1 | 94,428,392,856,422 | null | 241 | 241 |
import sys
for i,ws in enumerate(sys.stdin,1):
list = sorted(map(int, ws[:-1].split()))
if list[0] == 0 and list[1] == 0:
break
print(' '.join(map(str,list)))
|
while True:
ins = input().split()
x = int(ins[0])
y = int(ins[1])
if x == 0 and y == 0:
break
else:
nums = [x, y]
nums.sort()
print(" ".join(map(str, nums)))
| 1 | 510,287,588,030 | null | 43 | 43 |
n = int(input())
G = [[0]]+[list(map(int, input().split()))[2:] for _ in range(n)]
# print(G)
from collections import deque
d = deque([1])
dist = [10**10 for _ in range(n+1)]
dist[1] = 0
while len(d) != 0:
now = d.popleft()
# print(now)
for nexte in G[now]:
if dist[now] +1 < dist[nexte]:
dist[nexte] = dist[now] + 1
d.append(nexte)
for i,d in enumerate(dist[1:]):
if d != 10**10:
print(i+1,d)
else:
print(i+1,-1)
|
def main():
s=int(input())
if(s<600):
print(8)
elif(s<800):
print(7)
elif(s<1000):
print(6)
elif(s<1200):
print(5)
elif(s<1400):
print(4)
elif(s<1600):
print(3)
elif(s<1800):
print(2)
elif(s<2000):
print(1)
main()
| 0 | null | 3,308,411,703,520 | 9 | 100 |
N = int(input())
A = list(map(int, input().split()))
min = 1
check = True
count = 0
for i in range(N):
if A[i] != min:
A[i] = 0
count += 1
elif A[i] == min:
min += 1
if A == [0] * N:
print(-1)
else:
print(count)
|
import math
import numpy as np
n = int(input())
s = math.sqrt(n)
i = 2
f = {}
while i <= s:
while n % i == 0:
f[i] = f.get(i,0)+1
n = n // i
i += 1
ans = 0
for x in f.values():
e = 0
cumsum = 0
while e + cumsum + 1 <= x:
e += 1
cumsum += e
ans += e
print(ans+(n>1))
| 0 | null | 65,882,112,537,436 | 257 | 136 |
import sys
import math
while True:
line = sys.stdin.readline()
if not line:
break
token = list(map(int, line.strip().split()))
print(int(math.log10(token[0] + token[1]) + 1))
|
N = int(input())
S = []
for _ in range(N):
S.append(input())
ac = 0
wa = 0
tle = 0
re = 0
for s in S:
if s == "AC":
ac += 1
if s == "WA":
wa += 1
if s == "TLE":
tle += 1
if s == "RE":
re += 1
print("AC x ",ac)
print("WA x ",wa)
print("TLE x ",tle)
print("RE x ",re)
| 0 | null | 4,306,965,250,600 | 3 | 109 |
a, b, m = map(int, input().split())
a_list = [int(i) for i in input().split()]
b_list = [int(i) for i in input().split()]
money = []
for _ in range(m):
x, y, c = map(int, input().split())
x -= 1
y -= 1
total = a_list[x] +b_list[y] - c
money.append(total)
money.append(min(a_list) + min(b_list))
print(min(money))
|
A, B, M = map(int, input().split())
la = list(map(int, input().split()))
lb = list(map(int, input().split()))
prm_min = min(la) + min(lb)
lcost = list()
for i in range(M):
x, y, c = map(int, input().split())
lcost.append(la[x-1] + lb[y-1] - c)
print(min(min(lcost), prm_min))
| 1 | 54,049,179,290,820 | null | 200 | 200 |
n, k = [ int( val ) for val in raw_input( ).split( " " ) ]
w = [ int( raw_input( ) ) for val in range( n ) ]
sumW = sum( w )
maxW = max( w )
minP = 0
if 1 == k:
minP = sumW
elif n == k:
minP = maxW
else:
left = maxW
right = 100000*10000
while left <= right:
middle = ( left+right )//2
truckCnt = i = loadings = 0
while i < n:
loadings += w[i]
if middle < loadings:
truckCnt += 1
if k < truckCnt+1:
break
loadings = w[i]
i += 1
if truckCnt+1 <= k:
minP = middle
if k < truckCnt+1:
left = middle + 1
else:
right = middle - 1
print( minP )
|
def stackable(pack, tmp_p, k):
cur_w = 0
trucks = 1
for i in range(len(pack)):
if tmp_p < pack[i]:
return False
if cur_w + pack[i] <= tmp_p:
cur_w += pack[i]
else:
cur_w = pack[i]
trucks += 1
if k < trucks:
return False
return True
n, k = map(int, input().split())
pack = []
for i in range(n):
pack.append(int(input()))
left = int(sum(pack) / k)
right = max(pack) * n
while left < right - 1:
tmp_p = int((left + right) / 2)
if stackable(pack, tmp_p, k):
right = tmp_p
else:
left = tmp_p
if stackable(pack, left, k):
print(left)
else:
print(right)
| 1 | 89,484,658,300 | null | 24 | 24 |
W,H,x,y,r = map(int,input().split())
cr = x+r
cl = x-r
ct = y+r
cb = y-r
if ct <= H and cb >= 0 and cl >= 0 and cr <= W:
print('Yes')
else:
print('No')
|
def resolve():
l, P = map(int, input().split())
S = input()
ans = 0
# 10^r: 2^r * 5^r の為、10と同じ素数
if P == 2 or P == 5:
for i, s in enumerate(S):
if int(s) % P == 0:
ans += i + 1
return print(ans)
cnts = [0] * P
cnts[0] = 1
num, d = 0, 1
for s in S[::-1]:
s = int(s)
num = (num + (s * d)) % P
d = (10 * d) % P
cnts[num] += 1
for cnt in cnts:
ans += cnt * (cnt - 1) // 2
print(ans)
if __name__ == "__main__":
resolve()
| 0 | null | 29,503,005,688,352 | 41 | 205 |
global cnt
cnt = 0
def merge(A, left, mid, right):
L = A[left:mid] + [float("inf")]
R = A[mid:right] + [float("inf")]
i = 0
j = 0
global cnt
for k in range(left, right):
if L[i] <= R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
cnt += 1
def mergesort(A, left, right):
rsl = []
if left+1 < right:
mid = int((left+right)/2)
mergesort(A, left, mid)
mergesort(A, mid, right)
rsl = merge(A, left, mid, right)
return rsl
n = int(input())
S = list(map(int, input().split()))
mergesort(S, 0, n)
print(*S)
print(cnt)
|
n = int(input())
S = list(map(int, input().split()))
SENTINEL = 10 ** 9 + 1
count = 0
def merge(S, left, mid, right):
L = S[left:mid] + [SENTINEL]
R = S[mid:right] + [SENTINEL]
i = j = 0
global count
for k in range(left, right):
if (L[i] <= R[j]):
S[k] = L[i]
i += 1
else:
S[k] = R[j]
j += 1
count += right - left
def mergeSort(S, left, right):
if(left + 1 < right):
mid = (left + right) // 2
mergeSort(S, left, mid)
mergeSort(S, mid, right)
merge(S, left, mid, right)
mergeSort(S, 0, n)
print(*S)
print(count)
| 1 | 117,140,262,930 | null | 26 | 26 |
#!/usr/bin/env python3
# Generated by https://github.com/kyuridenamida/atcoder-tools
from typing import *
import collections
import functools as fts
import itertools as its
import math
import sys
INF = float('inf')
YES = "Yes" # type: str
NO = "No" # type: str
def solve(X: int):
return [NO, YES][X >= 30]
def main():
sys.setrecursionlimit(10 ** 6)
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
X = int(next(tokens)) # type: int
print(f'{solve(X)}')
if __name__ == '__main__':
main()
|
def ac_control(q):
if q >= 30:
print("Yes")
else:
print("No")
if __name__ == '__main__':
q = int(input())
ac_control(q)
| 1 | 5,784,847,948,048 | null | 95 | 95 |
n,k=map(int,input().split())
R,S,P=map(int,input().split())
T=input()
t=""
count=0
for i in range(n):
if i>k-1:
if T[i]=="r":
if t[i-k]!="p":
t=t+"p"
count+=P
else:
t=t+" "
if T[i]=="s":
if t[i-k]!="r":
t=t+"r"
count+=R
else:
t=t+" "
if T[i]=="p":
if t[i-k]!="s":
t=t+"s"
count+=S
else:
t=t+" "
else:
if T[i]=="r":
t=t+"p"
count+=P
if T[i]=="p":
t=t+"s"
count+=S
if T[i]=="s":
t=t+"r"
count+=R
print(count)
|
y=[1,1]
n=int(input())
for i in range(0,n):
a=y[i]+y[i+1]
y.append(a)
print(y[n])
| 0 | null | 53,222,029,649,020 | 251 | 7 |
from collections import deque
import sys
sys.setrecursionlimit(10**9)
def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))
INF=10**20
def main():
N=ii()
G = [[] for _ in range(N)]
E = []
_E = set()
for i in range(N-1):
a,b=mi()
G[a-1].append(b-1)
G[b-1].append(a-1)
E.append((a-1,b-1))
_E.add((a-1,b-1))
leaf = 0
for i in range(N):
g = G[i]
if len(g) == 1:
leaf = i
stack = deque([(leaf,1,None)])
seen = set()
path = {x:0 for x in E}
K = 0
def save(edge,color):
if edge == None: return
a,b = edge
if (a,b) in _E:
path[(a,b)] = color
else:
path[(b,a)] = color
while stack:
current,color,edge = stack.popleft()
seen.add(current)
save(edge,color)
K = max(K,color)
# print(current,color,edge)
i = 1
for next in G[current]:
if next in seen: continue
if color == i:
i += 1
stack.append((next,i,(current,next)))
i += 1
if N == 2:
print(1)
print(1)
exit()
print(K)
for i in range(N-1):
a,b = E[i]
print(path[(a,b)],sep="")
if __name__ == "__main__":
main()
|
import sys
sys.setrecursionlimit(1000000000)
input = sys.stdin.readline
N = int(input())
graph = [[] for _ in range(N)]
ab = [list(map(lambda x:int(x)-1, input().split())) for _ in range(N-1)]
d = {}
for a, b in ab:
graph[a] += [b]
graph[b] += [a]
def dfs(u, pre, c):
color = 0
for v in graph[u]:
if v != pre:
color += 1
if color == c:
color += 1
d[(u, v)] = color
d[(v, u)] = color
dfs(v, u, color)
dfs(0, -1, -1)
s = set()
for a, b in ab:
s.add(d[(a, b)])
print(len(s))
for a, b in ab:
print(d[(a, b)])
| 1 | 135,580,240,158,948 | null | 272 | 272 |
n = int(input())
s = input()
r = s.count('R')
g = s.count('G')
b = s.count('B')
ans = r * g * b
for i in range(n):
for d in range(1, n):
j = i + d
k = j + d
if k >= n:
break
if s[i] != s[j] and s[i] != s[k] and s[j] != s[k]:
ans -= 1
print(ans)
|
from collections import defaultdict
def main():
_, S = open(0).read().split()
indices, doubled_indices = defaultdict(list), defaultdict(set)
for i, c in enumerate(S):
indices[c].append(i)
doubled_indices[c].add(2 * i)
cnt = S.count("R") * S.count("G") * S.count("B")
for x, y, z in ["RGB", "GBR", "BRG"]:
cnt -= sum(i + j in doubled_indices[z] for i in indices[x] for j in indices[y])
print(cnt)
if __name__ == "__main__":
main()
| 1 | 36,242,062,406,020 | null | 175 | 175 |
a, b = map(int,input().split())
c, d = map(int,input().split())
if d == 1:
print("1")
else:
print("0")
|
#!/usr/bin python3
# -*- coding: utf-8 -*-
def main():
mod = 10**9+7
N = int(input())
A = list(map(int, input().split()))
C = [0] * 3
ret = 1
for i in range(N):
ret *= C.count(A[i])
ret %= mod
for j in range(3):
if C[j]==A[i]:
C[j]+=1
break
print(ret)
if __name__ == '__main__':
main()
| 0 | null | 127,354,199,193,220 | 264 | 268 |
N = int(input())
xyp = []
xym = []
for _ in range(N):
x, y = map(int, input().split())
xyp.append(x+y)
xym.append(x-y)
xyp.sort()
xym.sort()
print(max(xyp[-1] - xyp[0], xym[-1] - xym[0]))
|
N = int(input())
X = []
Y = []
for _ in range(N):
x, y = list(map(int, input().split()))
X.append(x)
Y.append(y)
points = []
for x, y in zip(X, Y):
points.append((
x + y,
x - y
))
print(max(max(dim) - min(dim) for dim in zip(*points)))
| 1 | 3,407,171,963,958 | null | 80 | 80 |
n, t = map(int, input().split())
dish = [list(map(int, input().split())) for _ in range(n)]
dish.sort(key=lambda x: x[0])
dp = [[0 for _ in range(3005)] for _ in range(3005)]
ans = 0
for i in range(n):
for j in range(t):
dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
nj = j + dish[i][0]
if nj < t:
dp[i + 1][nj] = max(dp[i + 1][nj], dp[i][j] + dish[i][1])
now = dp[i][t- 1] + dish[i][1]
ans = max(ans, now)
print(ans)
|
def main():
n=int(input())
lst=list(map(int,input().split()))
mod=10**9+7
sm=1
color=[0,0,0]
for x in lst:
if x not in color : sm=0;break
sm*=color.count(x)
sm%=mod
color[color.index(x)]+=1
print(sm)
main()
| 0 | null | 140,414,310,856,160 | 282 | 268 |
X = int(input())
Y = X % 500
answer = (X // 500 * 1000 + Y // 5 * 5)
print(answer)
|
from collections import deque
n = int(input())
adj = [[]]
for i in range(n):
adj.append(list(map(int, input().split()))[2:])
ans = [-1]*(n+1)
ans[1] = 0
q = deque([1])
visited = [False] * (n+1)
visited[1] = True
while q:
x = q.popleft()
for y in adj[x]:
if visited[y] == False:
q.append(y)
ans[y] = ans[x]+1
visited[y] = True
for j in range(1, n+1):
print(j, ans[j])
| 0 | null | 21,413,082,568,020 | 185 | 9 |
S,W=map(int,input().split())
if W>=S:
print('unsafe')
exit()
print('safe')
|
# ????????°??¶???????????? s ???????????????????????????????¨????????????£?¶????????????????????????????????????§???????????? p ??????????????????????????????????????°??????
# ????????°??¶????????????s????¨??????\?????????????????????
s = list(input())
# ??????????±??????????p????¨??????\?????????????????????
p = list(input())
# ?????????s??????????????????????????????????????????s?????????s?????????
s = s + s
# print(s)
# ???????????????????????????????????????????????°
flag = 0
for i in range(len(s) // 2):
if s[i] == p[0]:
for j in range(len(p)):
if s[i + j] != p[j]:
break
if j == len(p) - 1:
flag = 1
if flag == 1:
print("Yes")
else:
print("No")
| 0 | null | 15,570,454,414,592 | 163 | 64 |
N, K = map(int, input().split())
A = list(map(int, input().split()))
MOD = 10**9+7
def solve():
A.sort(key=lambda x: abs(x), reverse=True)
ans = 1
nneg = 0
a, b, c, d = -1, -1, -1, -1
for k in range(K):
ans = (ans * A[k])%MOD
if A[k] < 0:
nneg += 1
b = k
else:
a = k
if K == N or nneg%2 == 0:
return ans
for k in range(N-1, K-1, -1):
if A[k] < 0:
d = k
else:
c = k
# b must be >= 0
if a == -1 and c == -1: # all minus
ans = 1
for k in range(K):
ans = (ans * A[-1-k])%MOD
return ans
if a == -1 or d == -1:
outn = A[b]
inn = A[c]
elif c == -1:
outn = A[a]
inn = A[d]
else:
if A[a]*A[c] > A[b]*A[d]:
outn = A[b]
inn = A[c]
else:
outn = A[a]
inn = A[d]
ans = (ans * pow(outn, MOD-2, MOD))%MOD
ans = (ans * inn)%MOD
return ans
if __name__ == "__main__":
print(solve())
|
import math
a,b = [int(x) for x in input().split()]
ma = int(a//0.08)
mb = int(b//0.1)
fmindi = False
mindi = 9999999999999
for x in range(min(ma,mb),max(ma,mb)+2):
j = math.floor(x*0.08)
e = math.floor(x*0.1)
if j == a and e == b:
fmindi = True
mindi = min(mindi,x)
print(mindi if fmindi else -1)
| 0 | null | 32,849,328,984,100 | 112 | 203 |
def dfs(s,n):
if len(s) == n:
print(s)
else:
for i in range(len(set(s))+1):
dfs(''.join([s,chr(97+i)]),n)
N = int(input())
dfs('a',N)
|
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
INF = float('inf')
MOD = 998244353
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, K = LI()
LR = [LI() for _ in range(K)]
dp = [0] * (N + 1)
dp[0] = 1
a = [0] * (N + 1)
a[0] = 1
a[1] = -1
for i in range(N):
for l, r in LR:
left = min(i + l, N)
right = min(i + r + 1, N)
a[left] += dp[i]
a[right] -= dp[i]
dp[i+1] += dp[i] + a[i+1]
dp[i+1] %= MOD
# print(a)
# print(dp)
print(dp[-2])
if __name__ == '__main__':
resolve()
| 0 | null | 27,697,804,296,620 | 198 | 74 |
n=int(input())
a=list(map(int,input().split()))
ans=0
for i in range(n):
minj=i
for j in range(i,n):
if a[j]<a[minj]:
j,minj=minj,j
if i!=minj:
a[i],a[minj]=a[minj],a[i]
ans+=1
print(' '.join(map(str,a)))
print(ans)
|
def selection_sort(a,n):
count=0
for i in range(n):
ch=False
minj=i
for j in range(i,n):
if a[j] < a[minj]:
minj = j
ch = True
if(ch):
count+=1
a[i],a[minj] = a[minj],a[i]
return count
if __name__ == "__main__":
n=int(input())
a=list(map(int,input().split()))
count=selection_sort(a,n)
print(*a)
print(count)
| 1 | 20,577,815,380 | null | 15 | 15 |
list = []
while True:
a = int(input())
if(a == 0): break
else: list.append(a)
for i in range(len(list)):
print("Case %d: %d" %(i+1,list[i]))
|
S = input()
N = len(S)
if S == S[::-1]:
if S[:(N-1)//2] == S [(N+1)//2:]:
print("Yes")
else:
print("No")
else:
print("No")
| 0 | null | 23,226,772,094,848 | 42 | 190 |
n,a,b=map(int,input().split())
MOD=10**9+7
def inv(a):
return pow(a,MOD-2,MOD)
def choose(n,r):
if r==0 or r==n:
return 1
else:
A=B=1
ls_A=[1]
ls_B=[1]
for i in range(r):
A=ls_A[i]*(n-i)%MOD
ls_A.append(A)
B=ls_B[i]*(i+1)%MOD
ls_B.append(B)
return ls_A[r]*inv(ls_B[r])%MOD
def pow_k(x,n):
if n==0:
return 1
K=1
while n>1:
if n%2 != 0:
K=K*x%MOD
x=x**2%MOD
n=(n-1)//2
else:
x=x**2%MOD
n=n//2%MOD
return K*x%MOD
print((pow_k(2,n)-1-choose(n,a)-choose(n,b))%MOD)
|
import sys
sys.setrecursionlimit(4100000)
import math
INF = 10**9
def main():
n = int(input())
S = input()
if n%2 == 0:
if S[:n//2] == S[n//2:]:
print('Yes')
return
print('No')
if __name__ == '__main__':
main()
| 0 | null | 106,235,167,033,898 | 214 | 279 |
n = int(input())
ans = 0
for a in range(1,n):
b = n//a
if b*a == n:
b -= 1
ans += b
print(ans)
|
N = int(input())
cnt = 0
for a in range(1, N):
for b in range(a, N, a):
cnt += 1
print(cnt)
| 1 | 2,596,486,980,610 | null | 73 | 73 |
a,b,c=map(int,input().split())
import math
d=math.sin(math.radians(c))
print(a*b*d/2)
e=math.cos(math.radians(c))
x=math.sqrt(a**2+b**2-2*a*b*e)
print(a+b+x)
print(2*(a*b*d/2)/a)
|
import math
a, b, C=map(int, input().split())
print("{0:.5f}".format((1/2)*a*b*math.sin(C*math.pi/180.0)))
print("{0:.5f}".format(a+b+math.sqrt(a**2+b**2-2*a*b*math.cos(C*math.pi/180))))
print("{0:.5f}".format(b*math.sin(C*math.pi/180.0)))
| 1 | 170,848,291,560 | null | 30 | 30 |
#!usr/bin/env pypy3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == "\n":
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
def main():
N, X, Y = LI()
X -= 1
Y -= 1
dist = [[N] * N for _ in range(N)]
q = deque()
for i in range(N):
q.append(i)
dist[i][i] = 0
while q:
u = q.popleft()
if u < N - 1:
if dist[i][u + 1] > dist[i][u] + 1:
q.append(u + 1)
dist[i][u + 1] = dist[i][u] + 1
if u >= 1:
if dist[i][u - 1] > dist[i][u] + 1:
q.append(u - 1)
dist[i][u - 1] = dist[i][u] + 1
if u == X:
if dist[i][Y] > dist[i][u] + 1:
q.append(Y)
dist[i][Y] = dist[i][u] + 1
if u == Y:
if dist[i][X] > dist[i][u] + 1:
q.append(X)
dist[i][X] = dist[i][u] + 1
cnt = [0] * N
for i in range(N):
for j in range(i + 1, N):
cnt[dist[i][j]] += 1
for i in cnt[1:]:
print(i)
main()
|
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from collections import defaultdict
def main():
n, x, y = map(int, input().split())
x -= 1
y -= 1
dis = defaultdict(int)
for i1 in range(n):
for i2 in range(i1+1, n):
d = min(abs(i2-i1), abs(x-i1)+abs(y-i2)+1, abs(x-i2)+abs(y-i1)+1)
dis[d] += 1
for k1 in range(1, n):
print(dis[k1])
if __name__ == '__main__':
main()
| 1 | 44,267,411,407,170 | null | 187 | 187 |
x, k, d = map(int, input().split())
x = abs(x)
kk = x // d
amari = x % d
if kk >= k:
ans = (kk - k) * d + amari
elif (k - kk) % 2 == 1:
ans = abs(amari - d)
else:
ans = amari
print(ans)
|
#!/usr/bin/env python3
s = input()
l = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
if s == 'SUN':
print(7)
else:
print(6 - l.index(s))
| 0 | null | 69,500,384,869,180 | 92 | 270 |
list = []
while True:
a = int(input())
if(a == 0): break
else: list.append(a)
for i in range(len(list)):
print("Case %d: %d" %(i+1,list[i]))
|
a = []
while True:
num = int(input())
if num == 0:
break
a.append(num)
i=1
for x in a:
print('Case {}: {}'.format(i,x))
i += 1
| 1 | 489,977,936,348 | null | 42 | 42 |
import sys
input = sys.stdin.readline
def solve_K_1(N):
S = str(N)
d = len(S)
return 9 * (d - 1) + int(S[0])
def solve_K_2(N):
if N <= 99:
return N - solve_K_1(N)
S = str(N)
d = len(S)
res = 0
res += 81 * (d - 1) * (d - 2) // 2
res += 9 * (d - 1) * (int(S[0]) - 1)
x = 0
for i in range(1, d):
if S[i] != "0":
x = int(S[i])
break
i += 1
res += x + 9 * (d - i)
return res
def solve_K_3(N):
if N <= 999:
return N - solve_K_1(N) - solve_K_2(N)
S = str(N)
d = len(S)
res = 0
for n in range(3, d):
res += 729 * (n - 1) * (n - 2) // 2
res += 81 * (d - 1) * (d - 2) // 2 * (int(S[0]) - 1)
res += solve_K_2(int(S[1:]))
return res
def main():
N = int(input())
K = int(input())
if K == 1:
ans = solve_K_1(N)
elif K == 2:
ans = solve_K_2(N)
elif K == 3:
ans = solve_K_3(N)
print(ans)
if __name__ == "__main__":
main()
|
import sys
sys.setrecursionlimit(10000)
n = input()
k = int(input())
m = {}
def doit(n, k):
if len(n) == 0:
return k == 0
d = int(n[0])
if (n, k) not in m:
ret = 0
for i in range(d + 1):
if i == d:
ret += doit(n[1:], k - 1 if i > 0 else k)
else:
ret += doit('9' * (len(n) - 1), k - 1 if i > 0 else k)
m[(n, k)] = ret
return m[(n, k)]
print(doit(n, k))
| 1 | 76,235,983,339,010 | null | 224 | 224 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.