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
|
---|---|---|---|---|---|---|
#!/usr/bin/env python
# coding: utf-8
# In[21]:
N,K = map(int, input().split())
R,S,P = map(int,input().split())
T = input()
# In[22]:
points = {}
points["r"] = P
points["s"] = R
points["p"] = S
ans = 0
mylist = []
for i in range(N):
mylist.append(T[i])
if i >= K:
if T[i] == mylist[-K-1]:
mylist[-1] = "x"
else:
ans += points[T[i]]
else:
ans += points[T[i]]
print(ans)
# In[ ]:
|
n,m = map(int, input().split())
a = list(map(int,input().split()))
sum = 0;
for i in a:
sum += i
if(sum > n):
print(-1)
else:
print(n-sum)
#print(a)
| 0 | null | 69,348,545,503,248 | 251 | 168 |
MAX = 600000
MOD = 10 ** 9 + 7
fac = [0] * MAX
ifac = [0] * MAX
fac[0] = 1
for i in range(1,MAX):
fac[i] = (fac[i-1] * i) % MOD
ifac[MAX-1] = pow(fac[MAX-1],MOD-2,MOD)
for i in reversed(range(1,MAX)):
ifac[i-1] = (ifac[i] * i) % MOD
def combinations(n, k):
if k < 0 or n < k:
return 0
else:
return (fac[n] * ifac[k] * ifac[n-k]) % MOD
N,K = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
def f(A):
ans = 0
for i in range(K-1,N):
ans += A[i]*combinations(i,K-1)
ans %= MOD
#print(A[i],combinations(i,K-1))
return ans
print((f(A) - f(list(reversed(A)))) % MOD )
#print(f(A))
|
def fibonacci(i, num_list):
if i == 0 or i == 1:
num_list[i] = 1
else:
num_list[i] = num_list[i-2] + num_list[i-1]
n = int(input()) + 1
num_list = [0 for i in range(n)]
for i in range(n):
fibonacci(i, num_list)
print(num_list[-1])
| 0 | null | 47,987,236,034,468 | 242 | 7 |
r=float(raw_input())
p=float(3.14159265358979323846264338327950288)
s=p*r**2.0
l=2.0*p*r
print"%.5f %.5f"%(float(s),float(l))
|
from collections import defaultdict, deque
import sys, heapq, bisect, math, itertools, string, queue, copy, time
from fractions import gcd
import numpy as np
sys.setrecursionlimit(10**8)
INF = float('inf')
MOD = 10**9+7
EPS = 10**-7
h, w = map(int, input().split())
ini_grid = []
ans = 0
for i in range(h):
s = list(input())
ini_grid.append(s)
dd = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(h):
for j in range(w):
if ini_grid[i][j] == '.':
temp_grid = [row[:] for row in ini_grid]
dis_grid = [[-1]*w for i in range(h)]
dis_grid[i][j] = 0
dq = deque([(i, j, 0)])
temp_grid[i][j] = '#'
while dq:
curr = dq.popleft()
for di, dj in dd:
ni = curr[0] + di
nj = curr[1] + dj
if (0 <= ni <= h-1) and (0 <= nj <= w-1) and temp_grid[ni][nj] == '.':
temp_grid[ni][nj] = '#'
dis_grid[ni][nj] = curr[2] + 1
dq.append((ni, nj, curr[2] + 1))
if curr[2] + 1 > ans:
ans = curr[2] + 1
print(ans)
| 0 | null | 47,515,848,777,760 | 46 | 241 |
# A, Can'tWait for Holiday
# 今日の曜日を表す文字列Sが与えられます。
# Sは'SUN','MON','TUE','WED','THU','FRI','SAT'のいずれかであり、それぞれ日曜日、月曜日、火曜日。水曜日、木曜日、金曜日、土曜日を表します。
# 月の日曜日(あす以降)が何日後か求めてください。
# Sは'SUN','MON','TUE','WED','THU','FRI','SAT'のいずれか。
S = input()
if S == 'MON':
print(6)
elif S == 'TUE':
print(5)
elif S == 'WED':
print(4)
elif S == 'THU':
print(3)
elif S == 'FRI':
print(2)
elif S == 'SAT':
print(1)
else:print(7)
|
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, lru_cache
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 MAP1() : return map(lambda x:int(x)-1,input().split())
def LIST() : return list(MAP())
def LIST1() : return list(MAP1())
n = INT()
k = INT()
@lru_cache(None)
def F(n, k):
# n以下で0でないものがちょうどk個ある数字の個数
if n < 10:
if k == 0:
return 1
if k == 1:
return n
return 0
q, r = divmod(n, 10)
ret = 0
if k >= 1:
ret += F(q, k-1) * r
ret += F(q-1, k-1) * (9-r)
ret += F(q, k)
return ret
print(F(n, k))
| 0 | null | 104,854,997,464,168 | 270 | 224 |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 14 11:19:14 2020
@author: ezwry
"""
n = int(input())
xy = [map(int, input().split()) for i in range(n)]
x, y = [list(i) for i in zip(*xy)]
"""
A,Bの場合
"""
maxab = x[0] + y[0]
minab = x[0] + y[0]
for i in range(n):
xi = x[i]
yi = y[i]
mini = xi+yi
maxi = xi+yi
if mini < minab:
minab = mini
if maxi > maxab:
maxab = maxi
maxatob = maxab - minab
"""
C,Dの場合
"""
maxcd = y[0]-x[0]
mincd = y[0]-x[0]
for j in range(n):
maxj = y[j] - x[j]
minj = y[j] - x[j]
if maxj > maxcd:
maxcd = maxj
if minj < mincd:
mincd = minj
maxctod = maxcd - mincd
majimax = max(maxatob, maxctod)
print(majimax)
|
import math
import sys
from functools import reduce
N, M = map(int, input().split())
A = list(map(int, input().split()))
for i in range(N):
A[i] = A[i] // 2
def lcm_base(x, y):
return (x * y) // math.gcd(x, y)
def lcm_list(numbers):
return reduce(lcm_base, numbers, 1)
C = lcm_list(A)
B = [0 for _ in range(N)]
for i in range(N):
B[i] = C // A[i]
if B[i] % 2 == 0:
print(0)
sys.exit()
print( (M // C + 1) // 2)
| 0 | null | 52,430,691,826,200 | 80 | 247 |
n = int(input())
a = list(map(int, input().split()))
ans = sum(a)
ans2 = 0
for i in range(n):
if abs((ans - a[i]) - (ans2 + a[i])) < abs(ans - ans2):
ans2 += a[i]
ans -= a[i]
else:
break
print(abs(ans - ans2))
|
T1, T2, A1, A2, B1, B2 = map(int, open(0).read().split())
P = (A1 - B1) * T1
Q = (A2 - B2) * T2
if P > 0:
P, Q = -P, -Q
if P + Q < 0:
print(0)
elif P + Q == 0:
print("infinity")
else:
S, T = divmod(-P, P + Q)
print(S * 2 + (T != 0))
| 0 | null | 136,989,804,357,072 | 276 | 269 |
a = int(input())
b = int(input())
print(6-a-b)
|
a=int(input())
b=int(input())
if a==3:
print(3-b)
elif b==3:
print(3-a)
else:
print(3)
| 1 | 110,460,419,909,420 | null | 254 | 254 |
# AOJ ITP1_10_D
import math
def intinput():
a = input().split()
for i in range(len(a)):
a[i] = int(a[i])
return a
def main():
n = int(input())
x = intinput()
y = intinput()
sum_1 = 0
sum_2 = 0
sum_3 = 0
MD_INFTY = 0
for i in range(n):
MD_INFTY = max(MD_INFTY, abs(x[i] - y[i]))
sum_1 += abs(x[i] - y[i])
sum_2 += abs(x[i] - y[i]) ** 2
sum_3 += abs(x[i] - y[i]) ** 3
MD_1 = sum_1
MD_2 = math.sqrt(sum_2)
MD_3 = sum_3 ** (1 / 3)
print(MD_1); print(MD_2); print(MD_3); print(float(MD_INFTY))
if __name__ == "__main__":
main()
|
import math
n = int(input())
x = list(map(float, input().split()))
y = list(map(float, input().split()))
for p in [1.0, 2.0, 3.0]:
a = 0
for i in range(n):
a += abs(x[i] - y[i]) ** p
D = a ** (1/p)
print(D)
inf_D = float("-inf")
for i in range(n):
if abs(x[i] - y[i]) > inf_D:
inf_D = abs(x[i] - y[i])
print(inf_D)
| 1 | 208,849,320,482 | null | 32 | 32 |
n = int(input())
x = list(input().split())
x.reverse()
print(" ".join(x))
|
import sys
n = int( sys.stdin.readline() )
nums = sys.stdin.readline().rstrip().split( " " )
nums.reverse()
output = []
for i in range( n ):
output.append( nums[i] )
if i < (n-1):
output.append( " " )
print( "".join( output ) )
| 1 | 1,007,770,871,370 | null | 53 | 53 |
H, W, K = [int(n) for n in input().split(" ")]
M = []
for _ in range(H):
a = [n for n in input()]
assert(len(a) == W)
M.append(a)
import copy
import itertools
"""
M = [[".", ".", "#"],
["#", "#", "#"]
]
W = len(M[0])
H = len(M)
K = 2
"""
def makeCombination(candidate, n, lessFlag):
if len(candidate) <= 0:
return [[]]
_candidate = [n for n in candidate]
_candidate = sorted(_candidate)
result = []
if lessFlag is False:
tmp = list(set(list(itertools.combinations(_candidate, n))))
for t in tmp:
result.append(list(t))
else:
for i in range(n):
result += makeCombination(candidate, i + 1, False)
result += [[]]
return result
def check(m, h, w):
MM = copy.deepcopy(m)
for a in h:
for i in range(W):
MM[a][i] = "R"
for a in w:
for i in range(H):
MM[i][a] = "R"
count = 0
for i in range(len(MM)):
for j in range(len(MM[i])):
if MM[i][j] == "#":
count += 1
return count
HHH = makeCombination([n for n in range(H)], H, True)
WWW = makeCombination([n for n in range(W)], W, True)
OK = 0
for i in range(len(HHH)):
for j in range(len(WWW)):
if check(M, HHH[i], WWW[j]) == K:
OK += 1
print(OK)
|
import sys
import numpy as np
from collections import Counter
# 全探索なら、 2**6 * 2**6 (4000)
# > 4000 * (6**2)
# bit全探索でOK
# ------------------------------------------
h, w, num = map(int, input().split())
data = []
for _ in range(h):
# 一文字ずつListへ格納
temp = list(input())
data.append(temp)
#data = [input() for _ in range(h)]
# print(data)
'''
count = Counter(data)
most = count.most_common()
print(most)
'''
ans = 0
# 縦の全Loop
for i in range(2 ** h):
for j in range(2 ** w):
#print(i, j)
*temp, = data
temp = np.array(temp)
for k in range(h):
if (i >> k & 1):
temp[k, :] = 'aa'
for l in range(w):
if (j >> l & 1):
temp[:, l] = 'aa'
count = np.where(temp == '#')[0]
#print(count, len(count))
if (len(count) == num):
# print('add')
ans += 1
else:
pass
print(ans)
| 1 | 8,959,897,988,580 | null | 110 | 110 |
def main():
x = int(input())
print((2000-x)//200 + 1 if x %200 != 0 else (2000-x)//200)
if __name__ == '__main__':
main()
|
x = int(input())
y = x - 400
print(8 - y//200)
| 1 | 6,721,334,778,388 | null | 100 | 100 |
if int(input()) == 1:
print(0)
else:
print(1)
|
n = int(input())
s = str(input())
w = s[0]
num = 0
for i in range(1,n):
if w[0] == s[i]:
w += s[i]
else:
num += 1
w = s[i]
num += 1
print(num)
| 0 | null | 86,113,362,196,044 | 76 | 293 |
a = list(map(int, input().split()))
kishou = a[0] * 60 + a[1]
shuusin = a[2] * 60 + a[3]
print(shuusin - kishou - a[4])
|
N = int(input())
T = [[] for _ in range(N)]
for i in range(N):
A = int(input())
for j in range(A):
x, y = map(int, input().split())
x -= 1
T[i].append((x, y))
ans = 0
for i in range(1 << N):
isPossible = True
bit = [0] * N
for k in range(N):
if (i >> k) & 1:
bit[k] = 1
for idx, b in enumerate(bit):
if b == 1:
for x, y in T[idx]:
isPossible &= (bit[x] == y)
if isPossible:
ans = max(ans, bit.count(1))
print(ans)
| 0 | null | 69,772,300,003,380 | 139 | 262 |
import time
start=time.time()
k=int(input())
ans=0
x=k
for i in range(10**9):
while x%10!=7:
x+=k
if time.time()-start>=1.9:exit(print(-1))
x//=10
if x==0:exit(print(i+1))
|
li1 = []
li2 = []
ans = 0
for i, s in enumerate(input()):
if s == "\\":
li1.append(i)
elif s == "/" and li1:
j = li1.pop()
c = i - j
ans += c
while li2 and li2[-1][0] > j:
c += li2[-1][1]
li2.pop()
li2.append((j, c))
print(ans)
if li2:
print(len(li2), *list(zip(*li2))[1])
else:
print(0)
| 0 | null | 3,061,758,534,988 | 97 | 21 |
suits = ['S', 'H', 'C', 'D']
table = [[False] * 14 for i in range(4)]
N = int(input())
for _i in range(N):
mark, num = input().split()
num = int(num)
if mark == 'S':
table[0][num] = True
if mark == 'H':
table[1][num] = True
if mark == 'C':
table[2][num] = True
if mark == 'D':
table[3][num] = True
for i in range(4):
for j in range(1, 14):
if not table[i][j]:
print(f'{suits[i]} {j}')
|
n = int(input())
cards = set()
for _ in range(n):
cards |= {input()}
for s in ["S","H","C","D"]:
for n in range(1,14):
needle = s + " " + str(n)
if not needle in cards:
print(needle)
| 1 | 1,035,736,718,060 | null | 54 | 54 |
def main():
import collections
N, P = map(int, input().split())
S = input()[::-1]
ans = 0
if P == 2 or P == 5:
for i, s in enumerate(S):
if int(s) % P == 0:
ans += N - i
else:
mod = [0] * P
mod[0] = 1
current = 0
X = 1
for s in S:
current = (current + int(s) * X) % P
ans += mod[current]
mod[current] += 1
X = X * 10 % P
print(ans)
if __name__ == '__main__':
main()
|
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()
def resolve():
N, P = map(int, input().split())
S = str(input())
def main():
if P == 2:
res = 0
for i in range(N):
if int(S[N - 1 - i]) % 2 == 0:
res += N - i
elif P == 5:
res = 0
for i in range(N):
if int(S[N - 1 - i]) == 0 or int(S[N - 1 - i]) == 5:
res += N - i
else:
mods = [0] * P # mods[i]はPで割ったあまりがiである連続部分列の個数
tenfactor = 1
mod = 0
mods[mod] += 1
for i in range(N):
mod = (mod + int(S[N - i - 1]) * tenfactor) % P
tenfactor = (tenfactor * 10) % P
mods[mod] += 1
res = 0
for p in range(P):
res += mods[p] * (mods[p] - 1) // 2
return res
print(main())
resolve()
| 1 | 58,274,177,034,392 | null | 205 | 205 |
def resolve():
N, K, C = map(int, input().split())
S = input()
left = [0]*N
i = 0
cnt = 1
while i < N:
if S[i] == "o":
left[i] = cnt
i += C
cnt += 1
i += 1
right = [0]*N
i = 0
cnt = K
T = S[::-1]
while i < N:
if T[i] == "o":
right[i] = cnt
i += C
cnt -= 1
i += 1
right = right[::-1]
for i in range(N):
if left[i] == 0:
continue
if left[i] == right[i]:
print(i+1)
if __name__ == "__main__":
resolve()
|
k = int(input())
if k % 7 == 0:
l = 9*k // 7
else:
l = 9*k
if l % 2 == 0 or l % 5 == 0:
print(-1)
else:
pmo = 1
for i in range(1, l + 1):
mo = (pmo * 10) % l
if mo == 1:
print(i)
break
else:
pmo = mo
| 0 | null | 23,460,526,593,044 | 182 | 97 |
while True:
height, width = [int(x) for x in input().split(" ")]
if height == 0 and width ==0:
break
#start line
print("{0}".format("#" * width))
for h in range(0, (height - 2)):
for w in range(width):
if w == 0 or w == (width - 1):
print ("#", end="")
else:
print (".", end="")
print("\n", end="")
#end line
print("{0}".format("#" * width))
print("\n", end="")
|
MOD = 10 ** 9 + 7
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort(key=lambda x: abs(x), reverse=True)
res = 1
if k == n:
for e in a:
res *= e
res %= MOD
elif max(a) < 0:
if k % 2 == 1:
for i in range(n - k, n):
res *= a[i]
res %= MOD
else:
for i in range(k):
res *= a[i]
res %= MOD
else:
plus_a = [e for e in a if e >= 0]
minus_a = [e for e in a if e < 0]
minus_cnt = min(k, len(minus_a))
minus_cnt -= minus_cnt % 2
plus_cnt = k - minus_cnt
minus_a = minus_a[:minus_cnt]
minus_a.reverse()
max_change_cnt = min(minus_cnt, len(plus_a) - plus_cnt)
max_change_cnt -= max_change_cnt % 2
change_cnt = 0
while change_cnt < max_change_cnt:
if plus_a[plus_cnt + change_cnt] * plus_a[plus_cnt + change_cnt + 1]\
<= minus_a[change_cnt] * minus_a[change_cnt + 1]:
break
change_cnt += 2
for i in range(change_cnt, minus_cnt):
res *= minus_a[i]
res %= MOD
for i in range(plus_cnt + change_cnt):
res *= plus_a[i]
res %= MOD
print(res)
main()
| 0 | null | 5,109,237,476,850 | 50 | 112 |
n=int(input())
l = [int(x) for x in input().split()]
p = int(sum(l)/n + 0.5)
ans = 0
for i in range(n):
ans += (p-l[i])**2
print(ans)
|
N = int(input())
Xs = list(map(int, input().split()))
ans = 10**10
for P in range(0, 102):
cost = 0
for X in Xs:
cost += (X-P)**2
ans = min(ans, cost)
print(ans)
| 1 | 65,328,039,610,240 | null | 213 | 213 |
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
# INF = float("inf")
INF = 10**18
import bisect
import statistics
mod = 10**9+7
# mod = 998244353
A, B = map(int, input().split())
# リストのlcm
def lcm_base(x, y):
return (x * y) // math.gcd(x, y)
print(lcm_base(A, B))
|
from fractions import gcd
A, B = map(int, input().split())
print(str((A * B) // gcd(A, B)))
| 1 | 113,246,376,038,400 | null | 256 | 256 |
cnt = int(input())
dif_max = -1000000000
v_min = 1000000000
for i in range(cnt):
buf = int(input())
if i > 0:
dif_max = dif_max if buf - v_min < dif_max else buf - v_min
v_min = buf if buf < v_min else v_min
print(dif_max)
|
n=int(input())
R=[int(input()) for i in range(n)]
mini=10**10
maxi=-10**10
for r in R:
maxi=max([maxi,r-mini])
mini=min([mini,r])
print(maxi)
| 1 | 12,609,689,412 | null | 13 | 13 |
input_list = [int(num) for num in input().split()]
D = input_list[0]
T = input_list[1]
S = input_list[2]
if D/S <= T:
print("Yes")
else:
print("No")
|
import math
n = int(input())
ans=0
k = [[0]*10 for i in range(10)]
for i in range(1,n+1):
j = str(i)
l = int(j[0])
r = int(j[-1])
k[l][r]+=1
for i in range(10):
for j in range(10):
if i==0 or j==0:
continue
if i==j:
ans += k[i][j]*k[i][j]
else:
ans += k[i][j]*k[j][i]
print(ans)
| 0 | null | 44,853,743,303,928 | 81 | 234 |
from collections import deque
D1 = {i:chr(i+96) for i in range(1,27)}
D2 = {val:key for key,val in D1.items()}
N = int(input())
heap = deque([(D1[1],1)])
A = []
while heap:
a,n = heap.popleft()
if n<N:
imax = 0
for i in range(len(a)):
imax = max(imax,D2[a[i]])
for i in range(1,min(imax+1,26)+1):
heap.append((a+D1[i],n+1))
if n==N:
A.append(a)
A = sorted(list(set(A)))
for i in range(len(A)):
print(A[i])
|
x = int(input())
print("Yes" if x >= 30 else "No")
| 0 | null | 28,981,516,154,932 | 198 | 95 |
S = 13 * 0
H = 13 * 1
C = 13 * 2
D = 13 * 3
#???????????????????¨??????????????????????????????????????????????????????????,???????????????:1???
#??????????????????????????????5???S(???0)+5???????????????11???D(???39)+11??§??¨??????
#?????????0???????????¨
card_count = [0 for i in range(53)]
n = int(input())
for i in range(n):
card_type, card_num = input().split()
card_count[eval(card_type)+int(card_num)] += 1 #???????????£????¨??????¨???????????????????????°???1????¶????
for s in ['S','H','C','D']:
for i in range(1, 13+1):
if card_count[eval(s)+i] == 0: #??????????????°???0??????
print("{0} {1}".format(s,i)) #?¨??????¨?????????????????????
|
def II(): return int(input())
def MI(): return map(int, input().split())
N=II()
a=[0]*N
x=[[0]*N for i in range(N)]
y=[[0]*N for i in range(N)]
for i in range(N):
a[i]=II()
for j in range(a[i]):
x[i][j],y[i][j]=MI()
x[i][j]-=1
def check(honest):
for i in range(N):
if not honest[i]:
continue
for j in range(a[i]):
if y[i][j]==0 and honest[x[i][j]]:
return False
if y[i][j]==1 and not honest[x[i][j]]:
return False
return True
def dfs(honest):
if len(honest)==N:
if check(honest):
return sum(honest)
else:
return 0
return max(dfs(honest+[True]),dfs(honest+[False]))
print(dfs([]))
| 0 | null | 61,146,763,148,440 | 54 | 262 |
x = int(input())
c = 0
bank = 100
while bank < x:
bank += bank//100
c += 1
print(c)
|
n, k = map(int, input().split())
A = list(map(lambda x: int(x) - 1, input().split()))
prev = 0
count = 0
used = {prev: count}
for _ in range(min(k, n)):
prev = A[prev]
count += 1
if prev in used:
for _ in range((k - used[prev]) % (count - used[prev])):
prev = A[prev]
break
used[prev] = count
print(prev + 1)
| 0 | null | 24,781,057,696,458 | 159 | 150 |
#
# ⋀_⋀
# (・ω・)
# ./ U ∽ U\
# │* 合 *│
# │* 格 *│
# │* 祈 *│
# │* 願 *│
# │* *│
#  ̄
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないyp
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A):
for a in A: print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
H,W=MI()
grid = [ST() for _ in range(H)]
N = H*W
edge = [[] for _ in range(N)]
def enc(h,w):
return h*W+w
# DP = [[[inf,inf] for _ in range(W)] for _ in range(H)]
# DP[0][0][0] = 0
DP = [[inf]*W for _ in range(H)]
DP[0][0] = int(grid[0][0] == "#")
for h in range(H):
for w in range(W):
if(h+1<H):
if(grid[h][w] == grid[h+1][w] or grid[h+1][w] == "."):
DP[h+1][w] = min(DP[h+1][w], DP[h][w])
else:
DP[h+1][w] = min(DP[h+1][w], DP[h][w] + 1)
if(w+1<W):
if(grid[h][w] == grid[h][w+1] or grid[h][w+1] == "."):
DP[h][w+1] = min(DP[h][w+1], DP[h][w])
else:
DP[h][w+1] = min(DP[h][w+1], DP[h][w] + 1)
print(DP[-1][-1])
if __name__ == '__main__':
main()
|
# A - Range Flip Find Route
h,w=map(int,input().split())
s=[input() for i in range(h)]
inf=10**18
dp=[[inf]*(w+1) for i in range(h+1)]
if s[0][0]=="#":
dp[0][0]=1
else:
dp[0][0]=0
for i in range(h):
for j in range(w):
for y,x in ([1,0],[0,1]):
ni,nj=i+y,j+x
if ni>=h or nj>=w:continue
c=0
if s[ni][nj]=="#" and s[i][j]==".":c=1
dp[ni][nj]=min(dp[ni][nj],dp[i][j]+c)
print(dp[h-1][w-1])
| 1 | 49,427,081,419,408 | null | 194 | 194 |
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right
sys.setrecursionlimit(10**7)
def input():
return sys.stdin.readline()[:-1]
mod = 10**9 + 7
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
if row <= 0:
return [[] for _ in range(col)]
elif col == 1:
return [I() for _ in range(row)]
else:
read_all = [LI() for _ in range(row)]
return map(list, zip(*read_all))
#################
N = I()
count = 0
for i in range(N):
val1,val2 = LI()
if val1 == val2:
count += 1
if count == 3:
print('Yes')
exit()
else:
count = 0
print('No')
|
#A
N=input()
hon=["2","4","5","7","9"]
pon=["0","1","6","8"]
if N[-1] in hon:
print('hon')
elif N[-1] in pon:
print('pon')
else:
print('bon')
| 0 | null | 10,872,659,893,962 | 72 | 142 |
result = []
def combination(n, x):
count = 0
for i in range(1, n + 1):
for j in range(1,i):
for k in range(1, j):
if i + j + k == x:
count += 1
result.append(count)
while True:
(n, x) = [int(i) for i in input().split()]
if n == x == 0:
break
combination(n, x)
[print(result[x]) for x in range(len(result))]
|
from itertools import combinations
def main():
while True:
n, x = map(int, input().split())
if (n, x) == (0, 0):
break
ans = 0
for nums in combinations(range(1, n + 1), 3):
if x == sum(nums):
ans += 1
print(ans)
if __name__ == "__main__":
main()
| 1 | 1,289,342,427,360 | null | 58 | 58 |
s = []
p = []
a = i = 0
for c in input():
if c == "\\":
s += [i]
elif c == "/" and s:
j = s.pop()
t = i-j
a += t
while p and p[-1][0] > j:
t += p[-1][1]
p.pop()
p += [(j,t)]
i += 1
print(a)
if p:
print(len(p),*list(zip(*p))[1])
else:
print(0)
|
data = input()
#data = '\\\\///\\_/\\/\\\\\\\\/_/\\\\///__\\\\\\_\\\\/_\\/_/\\'
diff = {'\\':-1, '_':0, '/':1}
height = [0]
[height.append(height[-1]+diff[i]) for i in data]
bottom = min(height)
height = [h-bottom for h in height]
m = max(height)
water = [m for h in height]
height00 = [0] + height + [0]
water00 = [0] + water + [0]
roop = True
forward = 1
while roop:
temp = water00[:]
for i in range(1,len(water00)-1)[::forward]:
water00[i] = max(height00[i],min(water00[i-1:i+2]))
roop = temp != water00
forward *= -1
water = water00[1:-1]
depth = [w-h for w,h in zip(water,height)]
paddles = [0]
for d1,d2 in zip(depth[:-1],depth[1:]):
if d1==0 and d2>0:
paddles.append(0)
paddles[-1] += min(d1,d2) + 0.5*abs(d1-d2)
paddles = [int(p) for p in paddles[1:]]
print(sum(paddles))
print(len(paddles), *paddles)
| 1 | 55,197,192,640 | null | 21 | 21 |
n, q = (int(x) for x in input().split())
process = [input().split() for _ in range(n)]
time = 0
while process:
p = process.pop(0)
if int(p[1]) <= q:
time += int(p[1])
print(p[0], time)
else:
time += q
process.append([p[0], int(p[1]) - q])
|
import time as ti
class MyQueue(object):
"""
My Queue class
Attributes:
queue: queue
head
tail
"""
def __init__(self):
"""Constructor
"""
self.length = 50010
self.queue = [0] * self.length
# counter = 0
# while counter < self.length:
# self.queue.append(Process())
# counter += 1
self.head = 0
self.tail = 0
# def enqueue(self, name, time):
def enqueue(self, process):
"""enqueue method
Args:
name: enqueued process name
time: enqueued process time
Returns:
None
"""
self.queue[self.tail] = process
# self.queue[self.tail].name = name
# self.queue[self.tail].time = time
self.tail = (self.tail + 1) % self.length
def dequeue(self):
"""dequeue method
Returns:
None
"""
# self.queue[self.head].name = ""
# self.queue[self.head].time = 0
self.queue[self.head] = 0
self.head = (self.head + 1) % self.length
def is_empty(self):
"""check queue is empty or not
Returns:
Bool
"""
if self.head == self.tail:
return True
else:
return False
def is_full(self):
"""chech whether queue is full or not"""
if self.tail - self.head >= len(self.queue):
return True
else:
return False
class Process(object):
"""process class
"""
def __init__(self, name="", time=0):
"""constructor
Args:
name: name
time: time
"""
self.name = name
self.time = time
def forward_time(self, time):
"""time forward method
Args:
time: forward time interval
Returns:
remain time
"""
self.time -= time
return self.time
def time_forward(my_queue, interval, current_time,):
"""
Args:
my_queue: queue
interval: time step interval
current_time: current time
"""
value = my_queue.queue[my_queue.head].forward_time(interval)
if value <= 0:
current_time += (interval + value)
print my_queue.queue[my_queue.head].name, current_time
my_queue.dequeue()
elif value > 0:
current_time += interval
name, time = my_queue.queue[my_queue.head].name, \
my_queue.queue[my_queue.head].time
my_queue.enqueue(my_queue.queue[my_queue.head])
my_queue.dequeue()
return current_time
my_queue = MyQueue()
n, q = [int(x) for x in raw_input().split()]
counter = 0
while counter < n:
name, time = raw_input().split()
my_queue.enqueue(Process(name, int(time)))
counter += 1
# end_time_list = []
current_time = 0
while not my_queue.is_empty():
current_time = time_forward(my_queue, q, current_time)
| 1 | 43,215,279,460 | null | 19 | 19 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
# あるbit列に対するコストの計算
def count(zerone):
one = 0
cnt = 0
for i in range(N):
flag = True
if zerone[i] == 1:
one += 1
for j in range(len(A[i])):
if A[i][j][1] != zerone[A[i][j][0]-1]:
flag = False
break
if flag:
cnt += 1
if cnt == N:
return one
else:
return 0
# bit列の列挙
def dfs(bits):
if len(bits) == N:
return count(bits)
res = 0
for i in range(2):
bits.append(i)
res = max(res, dfs(bits))
bits.pop()
return res
# main
N = int(input())
A = [[] for _ in range(N)]
for i in range(N):
a = int(input())
for _ in range(a):
A[i].append([int(x) for x in input().split()])
ans = dfs([])
print(ans)
|
# coding: utf-8
s = list(input().rstrip())
ht = []
ponds=[]
for i, ch in enumerate(s):
if ch == "\\":
ht.append(i)
elif ch == "/":
if ht:
b = ht.pop()
ap = i - b
if not ponds:
ponds.append([b, ap])
else:
while ponds:
p = ponds.pop()
if p[0] > b:
ap += p[1]
else:
ponds.append([p[0],p[1]])
break
ponds.append([b,ap])
else:
pass
ans = ""
area = 0
for point, ar in ponds:
area += ar
ans += " "
ans += str(ar)
print(area)
print(str(len(ponds)) + ans)
| 0 | null | 61,131,368,153,568 | 262 | 21 |
n = int(input())
al = list(map(int, input().split()))
num_cnt = {}
c_sum = 0
for a in al:
num_cnt.setdefault(a,0)
num_cnt[a] += 1
c_sum += a
ans = []
q = int(input())
for _ in range(q):
b,c = map(int, input().split())
num_cnt.setdefault(b,0)
num_cnt.setdefault(c,0)
diff = num_cnt[b]*c - num_cnt[b]*b
num_cnt[c] += num_cnt[b]
num_cnt[b] = 0
c_sum += diff
ans.append(c_sum)
for a in ans:
print(a)
|
N = int(input())
A = list(map(int,input().split()))
Adict = {}
for i in range(N):
Adict[A[i]] = (i+1)
ans = []
for i in range(1,N+1):
ans.append(str(Adict[i]))
print(" ".join(ans))
| 0 | null | 96,875,291,952,102 | 122 | 299 |
import sys
def resolve(in_):
mod = 1000000007 # 10 ** 9 + 7
n, k = map(int, in_.readline().split())
n += 1
# ans = 0
ans = 1
# while n >= k:
while n > k:
ans += (
((n + (n - k)) * k // 2) % mod -
((1 + k - 1) * k // 2) % mod +
1
) % mod
ans %= mod
k += 1
return ans
def main():
answer = resolve(sys.stdin.buffer)
print(answer)
if __name__ == '__main__':
main()
|
def main():
N,M = map(int,input().split())
A = list(map(int,input().split()))
cnt = 0
for i in range(M):
cnt += A[i]
if N < cnt:
return -1
else:
return N - cnt
print(main())
| 0 | null | 32,566,080,750,940 | 170 | 168 |
a=10**5;b=1000
for i in range(input()):
a*=1.05
if a%b>0: a=a-a%b+b
print int(a)
|
s = 100000
n = int(input())
for i in range(n):
s *= 1.05
if s % 1000 != 0:
s = s // 1000 * 1000 + 1000
else:
pass
print(int(s))
| 1 | 1,195,671,808 | null | 6 | 6 |
n, m, l = list(map(lambda x: int(x), input().split(" ")))
A = list()
for i in range(n):
A.extend([list(map(lambda x: int(x), input().split(" ")))])
B = list()
for i in range(m):
B.extend([list(map(lambda x: int(x), input().split(" ")))])
C = list([[0 for l_ in range(l)]for n_ in range(n)])
for i in range(n):
for j in range(l):
for k in range(m):
C[i][j] += A[i][k] * B[k][j]
for a in C:
print("%d" % a[0], end="")
for b in a[1:]:
print(" %d" % b, end="")
print()
|
n, m, l = map(int, input().split())
A = [tuple(map(int, input().split())) for _ in range(n)]
B = [tuple(map(int, input().split())) for _ in range(m)]
B_T = [tuple(r) for r in zip(*B)]
for L in ((sum((a*b for a, b in zip(ai, bj))) for bj in B_T) for ai in A):
print(*L)
| 1 | 1,418,063,697,412 | null | 60 | 60 |
def main():
L, R, d = input_ints()
print(len([True for i in range(L, R+1) if i % d == 0]))
def input_ints():
line_list = input().split()
if len(line_list) == 1:
return int(line_list[0])
else:
return map(int, line_list)
def input_int_list_in_line():
return list(map(int, input().split()))
def input_int_tuple_list(n: int):
return [tuple(map(int, input().split())) for _ in range(n)]
main()
|
import sys
input = sys.stdin.buffer.readline
#sys.setrecursionlimit(10**9)
#from functools import lru_cache
def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()
def main():
l,r,d=MI()
ans=(r-l)//d
a=l+ans*d
if r//d*d==-(-a//d)*d:
ans+=1
print(ans)
if __name__ == "__main__":
main()
| 1 | 7,572,476,304,448 | null | 104 | 104 |
def main():
n, m, l = map(int, input().split())
matrix_a = [list(map(int, input().split())) for i in range(n)]
matrix_b = [list(map(int, input().split())) for j in range(m)]
matrix_c = [[0 for i in range(l)] for j in range(n)]
for i in range(n):
for j in range(l):
matrix_c[i][j] = sum(matrix_a[i][k] * matrix_b[k][j] for k in range(m))
for row in matrix_c:
print(' '.join(map(str, row)))
main()
|
n,m,l =map(int,input().split())
a =[]
b=[]
for i in range(n):
a.append(list(map(int,input().split())))
for j in range(m):
b.append(list(map(int,input().split())))
for i in range(n):
li=[]
for j in range(l):
su =0
for k in range(m):
su += a[i][k] * b[k][j]
li.append(su)
print(" ".join(list(map(str,li))))
| 1 | 1,432,154,360,132 | null | 60 | 60 |
from collections import Counter
N = int(input())
d = list(map(int, input().split()))
MOD = 998244353
dn = Counter(d)
ans = 1
if dn[0] != 1 or d[0] != 0: ans = 0
else:
for i in range(1, max(d)+1):
ans *= (dn[i-1]**dn[i])
ans %= MOD
print(ans)
|
# import bisect
import unittest
from io import StringIO
# https://note.nkmk.me/python-scipy-connected-components/
from collections import Counter, deque
# from copy import copy, deepcopy
# from functools import reduce
# from heapq import heapify, heappop, heappush
# from itertools import accumulate, permutations, combinations, combinations_with_replacement, groupby, product
# import math
# import numpy as np # Pythonのみ!
# from operator import xor
# import re
# from scipy.sparse.csgraph import connected_components # Pythonのみ!
# ↑cf. https://note.nkmk.me/python-scipy-connected-components/
# from scipy.sparse import csr_matrix
# import string
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()
def resolve():
def main():
n = int(input())
D = list(map(int, input().split()))
cnts=[0]*(max(D)+1)
for i in D:
cnts[i]+=1
if cnts[0]!=1 or D[0]!=0: return 0
ans=1
for i in range(2,max(D)+1):
if cnts[i]==0:
return 0
ans*=cnts[i-1]**cnts[i]
return ans % 998244353
print(main())
#
resolve()
| 1 | 154,759,864,765,522 | null | 284 | 284 |
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
# ある経路をきめる.
# そのとき(白マスから黒マスに移動する回数)=(その経路がいい経路にするための操作回数)
dp = [[float("inf")]*w for _ in range(h)]
if s[0][0] == "#":
dp[0][0] = 1
else:
dp[0][0] = 0
# dp[i][j]は00からijに行くときに白マスから黒マスに移動する回数の最小値
for i in range(h):
for j in range(w):
if i+1 < h:
count1 = dp[i][j]
if s[i][j] == "." and s[i+1][j] == "#":
count1 += 1
dp[i+1][j] = min(dp[i+1][j], count1)
if j+1 < w:
count2 = dp[i][j]
if s[i][j] == "." and s[i][j+1] == "#":
count2 += 1
dp[i][j+1] = min(dp[i][j+1], count2)
print(dp[h-1][w-1])
|
H, W = map(int, input().split())
S = []
for _ in range(H):
S.append([c for c in input()])
cnts = [[0 for _ in range(W)] for _ in range(H)]
if S[0][0] == "#":
cnts[0][0] = 1
for h in range(H):
for w in range(W):
if h == 0 and w == 0:
continue
c1, c2 = float('inf'), float('inf')
if 0 <= h - 1:
c1 = cnts[h - 1][w]
if S[h][w] == "#" and S[h - 1][w] == ".":
c1 += 1
if 0 <= w - 1:
c2 = cnts[h][w - 1]
if S[h][w] == "#" and S[h][w - 1] == ".":
c2 += 1
cnts[h][w] = min(c1, c2)
print(cnts[H-1][W-1])
| 1 | 49,127,005,919,780 | null | 194 | 194 |
N = int(input())
b=[]
c=[]
for j in range(N):
a = input()
b.append(a)
c = set(b)
print(len(c))
|
import sys
input = sys.stdin.readline
n, s = int(input()), set([])
for i in range(n): s.add(input()[:-1])
print(len(s))
| 1 | 30,404,650,647,510 | null | 165 | 165 |
from collections import deque
N=int(input())
G=[{} for i in range(N+1)]
colors = []
for i in range(N-1):
a,b=map(int,input().split())
G[a][b]=[i,-1]
G[b][a]=[i,-1]
def bfs(s):
seen = [0 for i in range(N+1)]
prev = [0 for i in range(N+1)]
todo = deque([])
cmax = 0
now = s
seen[now]=1
todo.append(now)
while 1:
if len(todo)==0:break
a = todo.popleft()
if len(G[a])<50:
if prev[a] == 0:
a_color=set([])
else:
a_color=set([G[a][prev[a]][1]])
for b in G[a]:
if seen[b] == 0:
seen[b] = 1
todo.append(b)
prev[b] = a
for c in range(1,N+1):
if c not in a_color:
a_color.add(c)
colors.append((G[a][b][0],c))
G[a][b][1]=G[b][a][1]=c
if c > cmax: cmax = c
break
else:
temp = list(range(1,N))
if prev[a] != 0:
del temp[G[a][prev[a]][1]-1]
temp = deque(temp)
for i,b in enumerate(G[a]):
if seen[b] == 0:
seen[b] = 1
todo.append(b)
prev[b] = a
c = temp.popleft()
colors.append((G[a][b][0],c))
G[a][b][1]=G[b][a][1]=c
if c > cmax: cmax = c
return colors, cmax
colors,cmax = bfs(1)
colors=sorted(colors)
print(cmax)
for i in range(N-1):
print(colors[i][1])
|
n = int(input())
graph = [[] for _ in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
graph[a - 1].append((b - 1, i))
graph[b - 1].append((a - 1, i))
ans = [0] * (n - 1)
from collections import deque
d = deque()
d.append([0, -1])
while d:
point, prev = d.popleft()
color = 1 if prev != 1 else 2
for a, index in graph[point]:
if ans[index] == 0:
ans[index] = color
d.append([a, color])
color += 1 if prev != color + 1 else 2
print(max(ans))
print(*ans, sep='\n')
| 1 | 135,939,867,731,730 | null | 272 | 272 |
N=int(input())
L= list(map(int,input().split()))
L_sorted=sorted(L,reverse=False)#昇順
count=0
import bisect
for i in range(N):
for j in range(i+1,N):
a=L_sorted[i]
b=L_sorted[j]
bisect.bisect_left(L_sorted,a+b)
count+=bisect.bisect_left(L_sorted,a+b)-j-1
print(count)
|
import bisect
N = int(input())
num_list = list(map(int,input().split()))
num_list.sort()
res = 0
for a in range(N-2):
for b in range(a+1,N-1):
k = bisect.bisect_left(num_list,num_list[a]+num_list[b])
res += max(k-(b+1),0)
print(res)
| 1 | 171,900,696,640,050 | null | 294 | 294 |
def main():
import sys
input = sys.stdin.readline
n = int(input())
D = list(map(int,input().split()))
mod = 998244353
from collections import Counter
node_cnt = Counter(D)
set_d = sorted(list(set(D)))
if D[0]!=0:
print(0);exit()
if set_d[-1]!=len(set_d)-1:
print(0);exit()
ans = 0
pre = 1
if 0 in node_cnt:
if node_cnt[0]==1:
ans = 1
for k,v in sorted(node_cnt.items()):
ans*=pow(pre,v)
ans%=mod
pre = v
print(ans)
if __name__=='__main__':
main()
|
import sys,math
input = sys.stdin.readline
A,B,C,D=list(map(int,input().split()))
if math.ceil(C/B) <= math.ceil(A/D):
print('Yes')
else:
print('No')
| 0 | null | 92,419,384,479,960 | 284 | 164 |
while True:
H,W = map(int, input().split())
if H==0 and W==0: break
for y in range(0,H):
for x in range(0,W):
if y%2==1:
if x%2==1: print("#",end="")
else: print(".",end="")
else:
if x%2==1: print(".",end="")
else: print("#",end="")
print()
print()
|
n=int(input())
s=input().split()
a=s[0]
b=s[1]
ans=''
for i in range(len(a)):
ans+=a[i]
ans+=b[i]
print (ans)
| 0 | null | 56,505,396,447,150 | 51 | 255 |
n = input()
s, t = map(str, input().split())
out = [si+ti for si, ti in zip(s, t)]
print("".join(out))
|
def main():
n=int(input())
s,t= list(map(str,input().split()))
ans=""
for i in range(0,n):
ans+=s[i]+t[i]
print(ans)
main()
| 1 | 111,814,725,206,800 | null | 255 | 255 |
from sys import stdin
input = stdin.readline
def main():
N, K = list(map(int, input().split()))
surp = N % K
print(min(surp, abs(surp-K)))
if(__name__ == '__main__'):
main()
|
N = int(input())
l = []
for i in range(N+1):
if i % 5 == 0 or i % 3 == 0:
l.append(0)
else:
l.append(i)
print(sum(l))
| 0 | null | 37,237,923,097,112 | 180 | 173 |
(h,n),*t=[[*map(int,t.split())]for t in open(0)]
d=[0]*9**8
for i in range(h):d[i+1]=min(b+d[i-a+1]for a,b in t)
print(d[h])
|
def check(x,y):
for i in range(100):
for j in range(100):
if i+j==x and i*4+j*2==y :
return "Yes"
return "No"
x,y = map(int, input().split())
print( check(x,y) )
| 0 | null | 47,269,964,124,160 | 229 | 127 |
print(1&~int(input()))
|
X = int(input())
if X == 1:
print(0)
else:
print(1)
| 1 | 2,911,550,173,618 | null | 76 | 76 |
def resolve():
N, K = map(int, input().split())
D = []
A = []
for _ in range(K):
d = int(input())
a = list(map(int, input().split()))
D.append(d)
A.append(a)
ans = 0
for i in range(N):
flag = 0
for j in range(K):
if i+1 in A[j]:
flag = 1
if flag == 0:
ans += 1
print(ans)
resolve()
|
def gcd(a,b):
if a>b:
x=a
y=b
else:
x=b
y=a
if y==0:
return x
else:
return gcd(y,x%y)
p,q=[int(i) for i in input().split(" ")]
print(gcd(p,q))
| 0 | null | 12,339,552,059,224 | 154 | 11 |
import sys
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7
S, T = rs().split()
print(T+S)
|
#!/usr/bin/env python3
# Generated by https://github.com/kyuridenamida/atcoder-tools
from typing import *
import collections
import functools
import itertools
import math
import sys
INF = float('inf')
def solve(S: str, T: str):
return T+S
def main():
sys.setrecursionlimit(10 ** 6)
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
S = next(tokens) # type: str
T = next(tokens) # type: str
print(f'{solve(S, T)}')
if __name__ == '__main__':
main()
| 1 | 103,050,029,070,980 | null | 248 | 248 |
n, k = list(map(int, input().split()))
max_len = 2 * n - 1 # 適宜変更する
mod = 10**9 + 7
def modinv(x):
'''
xの逆元を求める。フェルマーの小定理より、 x の逆元は x ^ (mod - 2) に等しい。計算時間はO(log(mod))程度。
Python標準のpowは割った余りを出すことも可能。
'''
return pow(x, mod-2, mod)
# 二項係数の左側の数字の最大値を max_len とする。nとかだと他の変数と被りそうなので。
# factori_table = [1, 1, 2, 6, 24, 120, ...] 要は factori_table[n] = n!
# 計算時間はO(max_len * log(mod))
modinv_table = [-1] * (max_len + 1)
modinv_table[0] = None # 万が一使っていたときにできるだけ早期に原因特定できるようにしたいので、Noneにしておく。
factori_table = [1] * (max_len + 1)
factori_inv_table = [1] * (max_len + 1)
for i in range(1, max_len + 1):
factori_table[i] = factori_table[i-1] * (i) % mod
modinv_table[1] = 1
for i in range(2, max_len + 1):
modinv_table[i] = (-modinv_table[mod % i] * (mod // i)) % mod
factori_inv_table[i] = factori_inv_table[i-1] * modinv_table[i] % mod
def binomial_coefficients(n, k):
'''
n! / (k! * (n-k)! )
0 <= k <= nを満たさないときは変な値を返してしまうので、先にNoneを返すことにする。
場合によっては0のほうが適切かもしれない。
'''
if not 0 <= k <= n:
return None
return (factori_table[n] * factori_inv_table[k] * factori_inv_table[n-k]) % mod
def binomial_coefficients2(n, k):
'''
(n * (n-1) * ... * (n-k+1)) / (1 * 2 * ... * k)
'''
ans = 1
for i in range(k):
ans *= n-i
ans *= modinv_table[i + 1]
ans %= mod
return ans
if k >= n-1:
# nHn = 2n-1 C n
print(binomial_coefficients(2 * n - 1, n))
else:
# 移動がk回←→ 人数0の部屋がk個以下
# 人数0の部屋がちょうどj個のものは
# nCj(人数0の部屋の選び方) * jH(n-j) (余剰のj人を残りの部屋に入れる)
ans = 0
for j in range(k+1):
if j == 0:
ans += 1
else:
ans += binomial_coefficients(n, j) * binomial_coefficients(n-1, j)
ans %= mod
print(ans)
|
n, m = map(int,input().split())
par = [-1 for i in range(n + 1)]
par[0] = 0
def find(x):
if (par[x] < 0):
return x
else:
x = par[x]
return find(x)
def unit(x, y):
if (find(x) == find(y)):
pass
else:
x = find(x)
y = find(y)
if (x > y):
x, y = y, x
s = par[y]
par[y] = x
par[x] = par[x] + s
for i in range(m):
a, b = map(int,input().split())
unit(a, b)
par.sort()
print(-par[0])
| 0 | null | 35,372,135,919,552 | 215 | 84 |
k = int(input())
from collections import deque
d = deque()
c = 0
for i in range(1, 10):
d.append(i)
while True:
tmp = d.popleft()
c += 1
if c == k:
ans = tmp
break
if tmp % 10 != 0:
d.append(tmp * 10 + (tmp % 10 - 1))
d.append(tmp * 10 + tmp % 10)
if tmp % 10 != 9:
d.append(tmp * 10 + (tmp % 10 + 1))
print(ans)
|
n,k,c = map(int,input().split())
s = input()
canwork=[0]*(n+1) #canwork[i]:=i日目までに働くことができる最大日数(1-indexed)
canwork2 = [0]*(c+n+3)
for i in range(n):
if s[i] == "o":
canwork[i+1]=max(canwork[i],canwork[i-c]+1)
else:
canwork[i+1] = canwork[i]
for i in range(n)[::-1]:
if s[i] == "o":
canwork2[i]=max(canwork2[i+1],canwork2[i+c+1]+1)
else:
canwork2[i] = canwork2[i+1]
ans = []
for i in range(n):
if canwork[i]+canwork2[i+1]==k-1:
ans.append(i+1)
print(*ans)
| 0 | null | 40,320,984,777,992 | 181 | 182 |
nums = list(map(int, input().split()))
print(nums.index(0)+1)
|
n, m, k = map(int, input().split())
#Union-Find
def find(x):
if par[x] < 0:
return x
else:
par[x] = find(par[x])
return par[x]
def unite(x, y):
p = find(x)
q = find(y)
if p == q:
return None
if p > q:
p,q = q,p
par[p] += par[q]
par[q] = p
def same(x, y):
return find(x) == find(y)
def size(x):
return -par[find(x)]
par = [-1 for i in range(n)]
l = [0] * n
for i in range(m):
a, b = map(int, input().split())
unite(a-1, b-1)
l[a-1] += 1
l[b-1] += 1
for i in range(k):
c, d = map(int, input().split())
if same(c-1, d-1):
l[c-1] += 1
l[d-1] += 1
for i in range(n):
print(size(i) - l[i] - 1, end=" ")
| 0 | null | 37,713,206,908,328 | 126 | 209 |
class Dice(object):
def __init__(self):
self.number = [0 for _ in range(6)]
self.before = [0 for _ in range(6)]
def set_number(self, l):
for i in range(6):
self.number[i] = l[i]
def roll(self, loc):
d = {
'N': (1, 5, 2, 3, 0, 4),
'S': (4, 0, 2, 3, 5, 1),
'E': (3, 1, 0, 5, 4, 2),
'W': (2, 1, 5, 0, 4, 3)
}
for i in range(6):
self.before[i] = self.number[i]
for i, j in enumerate(d[loc]):
self.number[i] = self.before[j]
def get_Top(self):
return self.number[0]
if __name__ == '__main__':
l = list(map(int, input().split()))
dice = Dice()
dice.set_number(l)
s = input()
for i in s:
dice.roll(i)
print(dice.get_Top())
|
if __name__ == "__main__":
S = input()
count_right = 0
count_left = 0
prev = ""
a = []
current = 0
for i, s in enumerate(S):
if prev == ">" and s == "<":
a.append((count_left, count_right))
count_left = 0
count_right = 0
if s == ">":
count_right += 1
prev = ">"
# a.append((count_left)
else:
count_left += 1
prev = "<"
a.append((count_left, count_right))
s = 0
for x in a:
large = max(x[0], x[1])
small = min(x[0], x[1])
s += sum(range(large + 1)) + sum(range(small))
print(s)
| 0 | null | 78,096,684,854,220 | 33 | 285 |
import sys
input = sys.stdin.readline
N = int(input())
musics = []
for _ in range(N):
s, t = input().split()
musics.append((s.strip(), int(t)))
X = input().strip()
ans = 0
flag = False
for s, t in musics:
if flag:
ans += t
if s == X:
flag = True
print(ans)
|
a,b=map(int,input().split())
#a,bの最大公約数
def gcd(a, b):
while b:
a, b = b, a % b
return a
#a,bの最小公倍数
def lcm(a, b):
return a * b // gcd (a, b)
print(lcm(a,b))
| 0 | null | 104,943,128,093,790 | 243 | 256 |
S = input()
week = ['SUN','MON','TUE','WED','THU','FRI','SAT']
day = [7, 6, 5, 4, 3, 2, 1]
ans = week.index(S)
print(day[ans])
|
n = int(input())
A = list(map(int, input().split()))
A.sort()
l = [False]*(A[n-1] + 1)
fix = []
for i in A:
if l[i]:
fix.append(i)
l[i] = True
for i in range(A[n-1]+1):
if l[i]:
for j in range(i*2, A[n-1]+1, i):
l[j] = False
for i in fix:
l[i] = False
ans = [i for i in range(A[n-1] + 1) if l[i]]
print(len(ans))
| 0 | null | 73,414,291,898,958 | 270 | 129 |
a,b = map(int,input().split())
# 8% -> [a,a+1)
# 10% -> [b,b+1)
# max(a*100/8, b*10) <= 元の価格 < min((a+1)*100/8, (b+1)*10)
min8 = a*(100/8)
max8 = (a+1)*(100/8)
min10 = b*10
max10 = (b+1)*10
mi = int(max(min8, min10) - 0.001) + 1
ma = int(min(max8, max10) - 0.001)
if mi > ma:
ans = -1
else:
ans = mi
print(ans)
|
import math
A, B = map(int, input().split())
ans = -1
for a in range(math.ceil(A/0.08), math.ceil((A+1)/0.08)):
if int(a*0.1) == B:
ans = a
break
print(ans)
| 1 | 56,211,234,137,960 | null | 203 | 203 |
while True:
L = map(int,raw_input().split())
H = (L[0])
W = (L[1])
if H == 0 and W == 0:break
for x in range(0,H):
if x % 2 == 0:
if W % 2 == 1:
print "{}#".format("#."* (W / 2))
else:
print "#." * (W / 2)
else:
if W % 2 == 1:
print "{}.".format(".#"* (W / 2))
else:
print ".#" * (W / 2)
print ""
|
import sys
num = []
for i in sys.stdin:
H, W = i.split()
if H == W == '0':
break
num.append((int(H), int(W)))
for cnt in range(len(num)):
output = []
for h in range(num[cnt][0]):
before = '#'
for w in range(num[cnt][1]):
if h == 0:
if before == '.':
before = '#'
elif before == '#':
before = '.'
output.append(before)
for z in range(num[cnt][1]):
if output[z] == '#':
output[z] = '.'
elif output[z] == '.':
output[z] = '#'
for y in range(num[cnt][1]):
print(output[y],end='')
print()
print()
| 1 | 853,575,589,532 | null | 51 | 51 |
N,X,M=map(int,input().split())
i=1
A=[X]
seen=[-1]*M
seen[X]=0
while(i<N):
T=A[-1]**2%M
#seen[T]~i-1までがループになっている
if seen[T]!=-1:
Roop=i-seen[T]
Left,Right=seen[T],i
break
seen[T]=i
A.append(T)
i+=1
if i==N:
print(sum(A))
exit()
ans=sum(A)
RoopSum=0
for i in range(Left,Right):
RoopSum+=A[i]
Rest=N-len(A)
ans+=Rest//Roop*RoopSum
for i in range(Rest%Roop):
ans+=T
T=T**2%M
print(ans)
|
N,X,M=map(int, input().split())
m=[0]*M
t={}
def f(x,y):
return x*x % y
a = X
s=0
for i in range(N):
if a in t:
x = t[a]
nn = N - x
q,r = divmod(nn,i-x)
s = m[x-1] + (m[i-1] - m[x-1])*q + m[x-1+r] - m[x-1]
break
t[a]=i
s += a
m[i] = s
a = f(a,M)
print(s)
| 1 | 2,836,690,682,408 | null | 75 | 75 |
n, m = map(int, input().split())
def ark(a, b):
return min(abs(a - b), n - abs(a - b))
a, b = n, 1
S = set()
for i in range(m):
if 2 * ark(a, b) == n or ark(a, b) in S:
a -= 1
print(a, b)
S.add(ark(a, b))
a -= 1
b += 1
|
'''
N人を円周上に配置し、M本の線分で結ぶ。
このとき、線分を回転させていっても同じ人のペアが生まれないようにする。
基本的には、上から順に結べばよい。
'''
from collections import deque
def main():
N, M = map(int, input().split())
if N&1:
'''
・Nが奇数の場合
上から順に結ぶだけ。
dequeに 1,2,3,...,M*2 を突っ込んで、両端から取り出してペアにする。
'''
q = deque(range(M*2))
while q:
print(q.popleft()+1, q.pop()+1)
else:
'''
[Nが偶数の場合]
上から順に結ぶと、上下の線対称になり、同じ間隔のペアが生まれるためNG。
→ 半分以降は、1つずらしてペアを作っていく
簡単に解決するため、
・上から順に奇数間隔ペアを作る
・下から順に偶数間隔ペアを作る
この2つから、M個を順に、交互に取り出す。
'''
q1 = deque(range(N))
q2 = deque(range(N-1))
p1 = []
while q1:
p1.append((q1.popleft()+1, q1.pop()+1))
p2 = []
while len(q2)>=2:
p2.append((q2.popleft()+1, q2.pop()+1))
p2.reverse()
for _ in range(M):
print(*p1.pop())
p1, p2 = p2, p1
main()
| 1 | 28,485,852,996,480 | null | 162 | 162 |
if __name__ == '__main__':
try:
count = []
result = 0
T = int(input())
for _ in range(T):
x, y = map(int, input().split())
count.append([x, y])
for i in range(T-2):
if count[i][0] == count[i][1] and count[i+1][0] == count[i+1][1] and count[i+2][0] == count[i+2][1]:
print("Yes")
exit(0)
print("No")
except Exception:
pass
|
n, t = map(int, input().split())
dp = [0] * (t + 1)
ab = [tuple(map(int, input().split())) for _ in range(n)]
ab.sort()
max_b = [0] * n
max_b[-1] = ab[-1][1]
for i in range(n - 1, 0, -1):
max_b[i - 1] = max(ab[i - 1][1], max_b[i])
for i in range(n - 1):
a, b = ab[i]
for j in range(t - 1, a-1, -1):
dp[j] = max(dp[j - a] + b, dp[j])
dp[t] = max(dp[t], dp[t-1] + max_b[i + 1])
print(max(dp))
| 0 | null | 76,973,429,429,948 | 72 | 282 |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from collections import defaultdict
def f(x):
return (int(str(x)[0]), int(str(x)[-1]))
def main():
N = int(readline())
df = defaultdict(int)
for i in range(1, N+1):
df[f(i)] += 1
ans = 0
for i in range(1, 10):
for j in range(1, 10):
ans += df[(i, j)]*df[(j, i)]
print(ans)
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
# 入力を整数に変換して受け取る
def input_int():
return int(input())
# マイナス1した値を返却
def int1(x):
return int(x) - 1
# 半角スペース区切り入力をIntに変換してMapで受け取る
def input_to_int_map():
return map(int, input().split())
# 半角スペース区切り入力をIntに変換して受け取る
def input_to_int_tuple():
return tuple(map(int, input().split()))
# 半角スペース区切り入力をIntに変換してマイナス1した値を受け取る
def input_to_int_tuple_minus1():
return tuple(map(int1, input().split()))
def main():
n = input_int()
cnt = [[0] * 10 for i in range(10)]
for n in range(1, n + 1):
cnt[int(str(n)[0])][int(str(n)[-1])] += 1
ret = 0
for i in range(10):
for j in range(10):
ret += cnt[i][j] * cnt[j][i]
return ret
if __name__ == "__main__":
print(main())
| 1 | 86,505,627,818,290 | null | 234 | 234 |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 7 11:05:00 2020
@author: liang
"""
"""
片側を固定して、それぞれのケースに対して最適解を求める
それぞれのケースについて
index(b_i) =< index(b_i-1)
であるから、bの最大値bestを保存して探索することで重複探索を回避できる
"""
N, M, K = map(int, input().split())
A = [0] + [int(x) for x in input().split()]
B = [0] + [int(x) for x in input().split()]
s_b = 0
for i in range(M+1):
s_b += B[i]
if s_b > K:
s_b -= B[i]
best = i - 1
break
else:
best = M
res = best
#print(res)
s_a = 0
for i in range(N+1):
# print("i", i)
s_a += A[i]
if s_a > K:
break
for j in reversed(range(best+1)):
#print("j",j)
if s_b <= K - s_a:
if i + j > res:
res = i + j
best = j
#print(i, j, s_a, s_b)
break
else:
s_b -= B[j]
print(res)
|
import bisect
n, m, k = map(int, input().split())
aaa = list(map(int, input().split()))
bbb = list(map(int, input().split()))
sum_a = [0] * (n + 1)
sum_b = [0] * (m + 1)
for i in range(n):
sum_a[i + 1] = sum_a[i] + aaa[i]
for j in range(m):
sum_b[j + 1] = sum_b[j] + bbb[j]
ans = 0
for i in range(n + 1):
if sum_a[i] > k:
break
tmp = bisect.bisect_right(sum_b, k - sum_a[i])
ans = max(ans, i + tmp - 1)
print(ans)
| 1 | 10,750,094,509,218 | null | 117 | 117 |
import collections
N = int(input())
A = []
for i in range(N):
A.append(input())
dic = collections.Counter(A)
print(len(dic.keys()))
|
import sys
def input():
return sys.stdin.readline().rstrip()
def main():
n = int(input())
items = {input() for _ in range(n)}
print(len(items))
if __name__ == "__main__":
main()
| 1 | 30,419,386,030,810 | null | 165 | 165 |
A, B, C = map(int, input().split())
K = int(input())
cnt = 0
while A>=B:
cnt+=1
B*=2
while B>=C:
cnt+=1
C*=2
print("Yes" if cnt<=K else "No")
|
N,K=list(map(int,input().split()))
A=sorted(list(map(int,input().split())))
F=sorted(list(map(int,input().split())),reverse=True)
ok=10**12
ng=0
while abs(ok-ng)>0:
center=(ok+ng)//2
cnt=0
for i in range(N):
ap=center//F[i]
cnt+=max(0,A[i]-ap)
if K<cnt:
ng=center+1
break
else:
ok=center
print(ok)
| 0 | null | 86,240,612,091,290 | 101 | 290 |
S = input()
T = input()
s = len(S)
t = len(T)
ans = t
for j in range(s - t + 1):
val = 0
for i in range(t):
if S[j:j + t][i] != T[i]:
val += 1
ans = min(ans, val)
print(ans)
|
from collections import deque
slope = input()
down_slope = deque()
total_slopes = deque()
for i in range(len(slope)):
if slope[i] == '\\':
down_slope.append(i)
elif slope[i] == '/':
area = 0
if len(down_slope) > 0:
while len(total_slopes) > 0 and total_slopes[-1][0] > down_slope[-1]:
area += total_slopes[-1][1]
total_slopes.pop()
area += i-down_slope[-1]
total_slopes.append([down_slope[-1],area])
down_slope.pop()
if len(total_slopes) > 0:
total_slopes = [i[1] for i in total_slopes]
print(sum(total_slopes))
print(len(total_slopes),end=' ')
print(' '.join(map(str,total_slopes)))
else:
print(0)
print(0)
| 0 | null | 1,885,096,274,452 | 82 | 21 |
X, Y = map(int, input().split())
P = 10 ** 9 + 7
N = (X+Y) // 3
R = (2 * X - Y) // 3
fact = [1, 1]
factinv = [1, 1]
inv = [0, 1]
for i in range(2, N+1):
fact.append((fact[-1] * i) % P)
inv.append((-inv[P % i] * (P//i) % P))
factinv.append((factinv[-1] * inv[-1] % P))
def cmb_mod(n, r, p):
if (r < 0) or (n < r):
return 0
r = min(r, n-r)
return fact[n] * factinv[r] * factinv[n-r] % p
if (X+Y) % 3 != 0:
print(0)
else:
print(cmb_mod(N, R, P))
|
X,Y=map(int,input().split())
if 2*Y<X or 2*X<Y:
print(0)
exit()
if not((X%3==0 and Y%3==0) or (X%3==1 and Y%3==2) or (X%3==2 and Y%3==1)):
print(0)
exit()
P=10**9+7
A=(2*Y-X)//3
B=(2*X-Y)//3
num = 1
for i in range(A+1, A+B+1):
num=num*i%P
den = 1
for j in range(1, B+1):
den = den*j%P
den = pow(den,P-2,P)
print((num*den)%P)
| 1 | 150,105,337,392,462 | null | 281 | 281 |
from collections import deque
def main():
k = int(input())
l = list(range(1, 10))
Q = deque(l)
for _ in range(k):
q = Q.popleft()
# 基準-1
if q % 10 != 0:
Q.append(10*q+q%10-1)
# 基準
Q.append(10*q+q%10)
# 基準 + 1
if q % 10 != 9:
Q.append(10*q+q%10+1)
print(q)
if __name__ == '__main__':
main()
|
from sys import stdin
def I(): return int(stdin.readline().rstrip())
def LI(): return list(map(int,stdin.readline().rstrip().split()))
if __name__=='__main__':
mod = 10**9 + 7
n = I()
a = LI()
ans = 0
for i in range(60):
c1 = 0
for rep in a:
if (rep>>i)&1:
c1 += 1
ans += ((n-c1)*c1*(2**i)%mod)%mod
print(ans%mod)
| 0 | null | 81,638,751,915,020 | 181 | 263 |
n = int(input())
a = []
for _ in range(n):
a.append([list(map(int,input().split())) for __ in range(int(input()))])
l = []
for i in range(2**n):
flag2 = 0
for j in range(n):
if i >> j & 1 == 1:
flag1 = 0
for k in a[j]:
if i >> (k[0]-1) & 1 != k[1]:
flag1 = 1
flag2 += 1
break
if flag1 : break
if flag2 == 0 :l.append(list(bin(i)).count('1'))
print(max(l))
|
N = int(input())
A_li = list(map(int, input().split()))
is_rising = False
money = 1000
stock = 0
for i in range(N - 1):
if i == 0:
if A_li[0] < A_li[1]:
# できるだけ買う
stock = money // A_li[0]
money -= A_li[0] * stock
is_rising = True
else:
if is_rising:
if A_li[i] > A_li[i + 1]:
# 全て売る
money += A_li[i] * stock
stock = 0
is_rising = False
else:
if A_li[i] < A_li[i + 1]:
# できるだけ買う
stock = money // A_li[i]
money -= A_li[i] * stock
is_rising = True
if i + 1 == N - 1:
# 全て売って終了
money += A_li[i+1] * stock
stock = 0
print(money)
| 0 | null | 64,808,677,012,662 | 262 | 103 |
N, X, M = map(int, input().split())
I = [-1] * M
A = []
total = 0
while (I[X] == -1):
A.append(X)
I[X] = len(A)
total += X
X = (X * X) % M
# print(f'{A=}')
# print(f'{I[:20]=}')
# print(f'{total=}')
# print(f'{X=}, {I[X]=}')
c = len(A) - I[X] + 1
s = sum(A[I[X] - 1:])
# print(f'{c=}, {s=}')
ans = 0
if N < len(A):
ans += sum(A[:N])
else:
ans += total
N -= len(A)
ans += s * (N // c)
N %= c
ans += sum(A[I[X] - 1:I[X] - 1 + N])
print(ans)
|
X = int(input())
for i in range(1000):
if 100 * i <= X and X <= 105 * i:
print(1)
break
else:
print(0)
| 0 | null | 64,967,266,946,538 | 75 | 266 |
N = int(input())
c = 0
for _ in range(N):
D1, D2 = map(int, input().split())
if D1 == D2:
c += 1
if c == 3:
print('Yes')
exit()
else:
c = 0
print('No')
|
n = int(input())
f = 0
L = []
for i in range(n):
a,b = map(int, input().split())
L.append([a,b])
for i in range(2,n):
if(L[i-2][0] == L[i-2][1] and L[i-1][0] == L[i-1][1] and L[i][0] == L[i][1]):
f = 1
break
if(f):
print('Yes')
else:
print('No')
| 1 | 2,484,181,396,860 | null | 72 | 72 |
n = int(input())
while 1:
for i in range(2, int(n**0.5)+1):
if n % i < 1:
break
else:
print(n)
break
n += 1
|
def solve():
N, K = list(map(int, input().split()))
if(N >= K):
tmp = N - ((N // K) * K)
ans = min(tmp, abs(abs(tmp) - K))
elif(N < K):
if(K <= 2*N):
ans = abs(N - K)
else:
ans = abs(N)
print(ans)
if __name__ == "__main__":
solve()
| 0 | null | 72,314,075,610,880 | 250 | 180 |
class Unionfind():
def __init__(self, n):
self.n = n
self.parents = [-1] * (n+1)
def find(self, x):
if(self.parents[x] < 0):
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if(x == y):
return
if(self.parents[x] > self.parents[y]):
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}:{}'.format(r, self.members(r)) for r in self.roots())
N, M, K = map(int, input().split())
uf = Unionfind(N)
f = [0 for _ in range(N)]
n = [0 for _ in range(N)]
for _ in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
uf.union(a, b)
f[a] += 1
f[b] += 1
for _ in range(K):
c, d = map(int, input().split())
c -= 1
d -= 1
if(uf.same(c, d)):
n[c] += 1
n[d] += 1
ans = []
for i in range(N):
ans.append(uf.size(i)-f[i]-n[i]-1)
print(*ans)
|
# coding=utf-8
a, b = map(int, input().split())
if a > b:
big_num = a
sml_num = b
else:
big_num = b
sml_num = a
while True:
diviser = big_num % sml_num
if diviser == 0:
break
else:
big_num = sml_num
sml_num = diviser
print(sml_num)
| 0 | null | 30,753,141,699,808 | 209 | 11 |
rate = int(input())
rank=8-((rate-400)//200)
print((rank))
|
k,n=map(int,input().split())
a = list(map(int,input().split()))
s = []
for i in range(n-1):
s.append(abs(a[i+1] - a[i]))
s.append(k-a[-1]+a[0])
print(k-max(s))
| 0 | null | 25,198,761,136,082 | 100 | 186 |
a, b = map(int, input().split())
print(a*b)
|
def main():
a, b = map(int, input().split(" "))
print(a*b)
if __name__ == "__main__":
main()
| 1 | 15,736,262,839,822 | null | 133 | 133 |
#
# ⋀_⋀
# (・ω・)
# ./ U ∽ U\
# │* 合 *│
# │* 格 *│
# │* 祈 *│
# │* 願 *│
# │* *│
#  ̄
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないyp
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A):
for a in A: print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
# UnionFind
class UnionFind():
def __init__(self, n):
self.nodes=[-1] * n # nodes[x]: 負なら、絶対値が木の要素数
def get_root(self, x):
# nodes[x]が負ならxが根
if self.nodes[x] < 0:
return x
# 根に直接つなぎ直しつつ、親を再帰的に探す
else:
self.nodes[x]=self.get_root(self.nodes[x])
return self.nodes[x]
def unite(self, x, y):
root_x=self.get_root(x)
root_y=self.get_root(y)
# 根が同じなら変わらない
# if root_x == root_y:
# pass
if root_x != root_y:
# 大きい木の方につないだほうが計算量が減る
if self.nodes[root_x] < self.nodes[root_y]:
big_root=root_x
small_root=root_y
else:
small_root=root_x
big_root=root_y
self.nodes[big_root] += self.nodes[small_root]
self.nodes[small_root]=big_root
def main():
N,M = MI()
uf=UnionFind(N)
get_root, unite, nodes=uf.get_root, uf.unite, uf.nodes
for _ in range(M):
A,B = MI()
unite(A-1,B-1)
ans = 0
for i in range(N):
ans = max(ans, -nodes[get_root(i)])
print(ans)
if __name__ == '__main__':
main()
|
import sys
def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def main():
n = I()
A = LI()
sub = [0]*n
for a in A:
sub[a-1] += 1
for s in sub:
print(s)
if __name__ == '__main__':
main()
| 0 | null | 18,255,467,653,052 | 84 | 169 |
moji = "1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51"
moji = moji.split(",")
a = input()
print(int(moji[int(a)-1]))
|
def main():
X = [1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51]
K = int(input())
return X[K - 1]
print(main())
| 1 | 49,947,966,834,460 | null | 195 | 195 |
N, M = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]
# N, M = map(int, input().split())
# A = list(map(int, input().split()))
# print(len(A))
max_p = max(A)
X = max_p
cnt = [0 for x in range(100001)]
hpp = [0 for x in range(100001)]
# print(A)
for i in A:
# print(i)
# if cnt[i] != 0:
# continue
cnt[i] += 1
hpp[i] += i
# print(cnt[:100])
for i in range(1, 100001)[::-1]:
cnt[i - 1] += cnt[i]
hpp[i - 1] += hpp[i]
def countpair(left, x):
# return cnt[x - left + 1] if (x - left > 0) else N
if x - left <= 0:
return N
elif x - left > 100000:
return 0
else:
return cnt[x - left]
def get_hpp(left, x):
if x - left <= 0:
return hpp[0]
elif x - left > 100000:
return 0
else:
return hpp[x - left]
# print(hpp[:100])
# print(cnt[:100])
small = 0
large = max_p * 2
threshold = 0
# d_c = 0
# mems = []
while (small <= large):
# d_c += 1
# print(small, large)
X = (small + large) // 2
nums = 0
for i in range(N):
left = A[i]
# print(len(A))
nums += countpair(left, X)
if nums >= M:
threshold = X
small = X + 1
else:
large = X - 1
X = threshold
# print("X:", X)
# print("threshold:", threshold)
Y = X + 1
hpp_sum = 0
num_sum = 0
for i in range(N):
# print("-----------")
left = A[i]
cnt_num = countpair(left, Y)
num_sum += cnt_num
# print("left:", left)
# print("cnt_num:", cnt_num)
hpp_sum += left * cnt_num
# print("get_hpp:", get_hpp(left, Y))
hpp_sum += get_hpp(left, Y)
# print("hpp_sum:", hpp_sum)
hpp_sum += X * (M - num_sum) if (M - num_sum > 0) else 0
print(hpp_sum)
# print(out)
# for i in range(N):
|
n = input()
m = map(int, raw_input().split())
m2 = [0 for i in xrange(n)]
for i in xrange(n):
m2[n-i-1] = m[i]
for i in xrange(n):
print m2[i],
| 0 | null | 54,560,794,567,948 | 252 | 53 |
d = ["ABC", "ARC"]
s = input()
print(d[1 - d.index(s)])
|
n = int(input())
dp = [0 for _ in range(45)]
def fib_dp(n):
dp[0] = 1
dp[1] = 1
for i in range(2, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
print(fib_dp(n))
| 0 | null | 11,991,267,885,830 | 153 | 7 |
A, B = input().split()
C = B + A
print(C)
|
n=int(input())
a=[]
b=[]
for i in range(n):
x,y=map(int,input().split())
a.append(x+y)
b.append(x-y)
a=sorted(a)
b=sorted(b)
ans=max(a[-1]-a[0],b[-1]-b[0])
print(ans)
| 0 | null | 53,092,400,882,052 | 248 | 80 |
H, W, K = map(int, input().split())
S = [list(map(int, list(input()))) for _ in range(H)]
ans = H*W
def countWhite(ytop, ybottom, xleft, xright):
ret = sum([sum(s[xleft:xright]) for s in S[ytop:ybottom]])
return ret
for h_div in range(1 << H-1):
count = 0
cut = [0]
for i in range(H):
if h_div >> i & 1:
cut.append(i+1)
count += 1
cut.append(H)
if count > ans:
continue
left = 0
# ここどんなふうに縦に切っても条件を満たさない場合がある
for right in range(1, W+1):
white = 0
for i in range(len(cut)-1):
white = max(white, countWhite(cut[i], cut[i+1], left, right))
if white > K:
if left == right - 1: # 条件を満たす縦の切り方がなかった場合
break
left = right - 1
count += 1
if count > ans:
break
else:
if count < ans:
ans = count
print(ans)
|
input()
l = [int(i) for i in input().split()]
input()
c = 0
for i in input().split():
for j in l:
if int(i) == j:
c += 1
break
print(c)
| 0 | null | 24,180,360,939,368 | 193 | 22 |
def main():
N, A, B = map(int, input().split())
if (B - A) % 2 == 0:
print((B - A) // 2)
else:
ret = min(
A + (B - A - 1) // 2,
(N - B + 1) + (N - (A + N - B + 1)) // 2
)
print(ret)
if __name__ == '__main__':
main()
|
import sys
input=sys.stdin.readline
n,k=map(int,input().split())
INF=10**9+7
l=[0]*k
ans=0
for i in range(k-1,-1,-1):
x=i+1
temp=pow(k//x,n,INF)
for j in range(2,k//x+1):
temp=(temp-l[j*x-1])%INF
l[i]=temp
ans=(ans+x*temp)%INF
print(ans)
| 0 | null | 73,261,895,108,128 | 253 | 176 |
N, M = map(int, input().split())
route = [[] for _ in range(N)]
sign = [0]*N
#print(route)
for i in range(M):
a,b = map(int, input().split())
route[a-1].append(b-1)
route[b-1].append(a-1)
#print(route)
marked = {0}
q = [0]
for i in q:
for j in route[i]:
if j in marked:
continue
q.append(j)
marked.add(j)
sign[j] = i+1
print('Yes')
[print(i) for i in sign[1:]]
|
[X,Y] = list(map(int,input().split()))
n = (-1*X+2*Y)//3
m = (2*X-Y)//3
if (X+Y)%3 !=0:
print(0)
elif n<0 or m<0:
print(0)
else:
MAXN = (10**6)+10
MOD = 10**9 + 7
f = [1]
for i in range(MAXN):
f.append(f[-1] * (i+1) % MOD)
def nCr(n, r, mod=MOD):
return f[n] * pow(f[r], mod-2, mod) * pow(f[n-r], mod-2, mod) % mod
print(nCr(n+m,n,10**9 + 7))
| 0 | null | 85,298,163,680,250 | 145 | 281 |
from sys import setrecursionlimit
setrecursionlimit(10 ** 5)
def find(parent, i):
t = parent[i]
if t < 0:
return i
t = find(parent, t)
parent[i] = t
return t
def unite(parent, i, j):
i = find(parent, i)
j = find(parent, j)
if i == j:
return
parent[j] += parent[i]
parent[i] = j
n, m, k = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(m)]
cd = [list(map(int, input().split())) for _ in range(k)]
parent = [-1] * n
friends = [[] for _ in range(n)]
for a, b in ab:
unite(parent, a-1, b-1)
friends[a-1].append(b-1)
friends[b-1].append(a-1)
blocks = [[] for _ in range(n)]
for c, d in cd:
blocks[c-1].append(d-1)
blocks[d-1].append(c-1)
result = []
for i in range(n):
p = find(parent, i)
t = -parent[p] - 1
t -= len(friends[i])
for b in blocks[i]:
if p == find(parent, b):
t -= 1
result.append(t)
print(*result)
|
import math
def main():
R = input_int()
print(R * 2 * math.pi)
def input_int():
return int(input())
def input_ints():
return map(int, input().split())
def input_int_list_in_line():
return list(map(int, input().split()))
def input_int_tuple_list(n: int, q: int):
return [tuple(map(int, input().split())) for _ in range(n)]
main()
| 0 | null | 46,445,400,193,670 | 209 | 167 |
n = int(raw_input())
i = 0
s = []
h = []
c = []
d = []
def order_list(list):
l = len(list)
for i in xrange(l):
j = i + 1
while j < l:
if list[i] > list[j]:
temp = list[i]
list[i] = list[j]
list[j] = temp
j += 1
return list
def not_enough_cards(mark, list):
list = order_list(list)
# line = "########################################"
# print line
# print mark + ":"
# print list
# print line
i = 0
for x in xrange(1, 14):
# print "x = " + str(x) + ", i = " + str(i)
if i >= len(list):
print mark + " " + str(x)
elif x != list[i]:
print mark + " " + str(x)
else:
i += 1
while i < n:
line = raw_input().split(" ")
line[1] = int(line[1])
if line[0] == "S":
s.append(line[1])
elif line[0] == "H":
h.append(line[1])
elif line[0] == "C":
c.append(line[1])
elif line[0] == "D":
d.append(line[1])
i += 1
not_enough_cards("S", s)
not_enough_cards("H", h)
not_enough_cards("C", c)
not_enough_cards("D", d)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
??´?????????
"""
suits = {"S": 0, "H": 1, "C": 2, "D": 3}
nsuits = ["S", "H", "C", "D"]
cards = [[0 for i in range(13)] for j in range(4)]
n = int(input())
for i in range(n):
inp = input().split(" ")
s = inp[0]
c = int(inp[1]) - 1
cards[suits[s]][c] = 1
for i in range(4):
for j in range(13):
if cards[i][j] == 0:
print("{0} {1}".format(nsuits[i], j+1))
| 1 | 1,036,356,510,400 | null | 54 | 54 |
l,r,d = map(int, input().split())
var=l//d
var1=r//d
ans=var1-var
if l%d==0:
ans+=1
print(ans)
|
L, R, d = map(int,input().split())
ans = 0
while L <= R:
if L % d == 0:
ans += 1
L += 1
print(ans)
| 1 | 7,570,360,631,872 | null | 104 | 104 |
downs, ponds = [], []
for i, s in enumerate(input()):
if s == "\\":
downs.append(i)
elif s == "/" and downs:
i_down = downs.pop()
area = i - i_down
while ponds and ponds[-1][0] > i_down:
area += ponds.pop()[1]
ponds.append([i_down, area])
print(sum(p[1] for p in ponds))
print(len(ponds), *(p[1] for p in ponds))
|
# input
section = raw_input()
# map the height of the section
height = 0
heights = [0]
for p in xrange( len(section) ):
if section[p] == '/':
height += 1
elif section[p] == '\\':
height -= 1
heights.append(height)
# search the pools
pools = []
water = []
p = 0
while p < len(section):
if section[p] == '\\':
try:
pr = heights[p+1:].index( heights[p] )
pools.append([p, p+1+pr])
p = p+1+pr
except:
p+=1
else:
p+=1
# count
for pool in pools:
tp = section[pool[0]:pool[1]]
depth = 0
s = 0
for p in xrange( len(tp) ):
if tp[p] == '/':
depth -= 1
elif tp[p] == '\\':
depth += 1
s += 2*(depth-1)+1
else:
s += depth
water.append(s)
# print
print sum(water)
if len(water) == 0:
print len(water)
else:
print len(water), " ".join(map(str, water))
| 1 | 60,807,154,588 | null | 21 | 21 |
n = int(input())
s = input()
a = s[:n//2]
b = s[n//2:]
if a == b:
print('Yes')
else:
print('No')
|
import math
data = input().split()
x1 = float(data[0])
x2 = float(data[2])
y1 = float(data[1])
y2 = float(data[3])
x3 = x1 - x2 if x1 > x2 else x2 - x1
y3 = y1 - y2 if y1 > y2 else y2 - y1
print("%.8f" % math.sqrt(x3 * x3 + y3 * y3))
| 0 | null | 73,542,605,603,110 | 279 | 29 |
s = input()
print("Yes" if s[2] == s[3] and s[4] == s[5] else "No")
|
s = list(input())
if s[2] == s[3]:
if s[4] == s[5]:
print("Yes")
else:
print("No")
exit
else:
print("No")
exit
| 1 | 42,110,894,120,304 | null | 184 | 184 |
S,W=map(int,input().split())
if S<=W:
print("unsafe")
exit(0)
print("safe")
|
s,w = [int(s) for s in input().split()]
if w>=s:
print("unsafe")
else:
print("safe")
| 1 | 29,223,582,375,680 | null | 163 | 163 |
import math
class MergeSort:
cnt = 0
def merge(self, a, n, left, mid, right):
n1 = mid - left
n2 = right - mid
l = a[left:(left+n1)]
r = a[mid:(mid+n2)]
l.append(2000000000)
r.append(2000000000)
i = 0
j = 0
for k in range(left, right):
self.cnt += 1
if l[i] <= r[j]:
a[k] = l[i]
i += 1
else:
a[k] = r[j]
j += 1
return a
def mergeSort(self, a, n, left, right):
if left + 1 < right:
mid = (left + right) // 2
self.mergeSort(a, n, left, mid)
self.mergeSort(a, n, mid, right)
self.merge(a, n, left, mid, right)
return a
if __name__ == '__main__':
n = int(input().rstrip())
s = [int(i) for i in input().rstrip().split(" ")]
x = MergeSort()
print(" ".join(map(str, x.mergeSort(s, n, 0, n))))
print(x.cnt)
|
cnt=0
def mer(l,r):
global cnt
ll=len(l)
rr=len(r)
md=[]
i,j=0,0
l.append(float('inf'))
r.append(float('inf'))
for k in range(ll+rr):
cnt+=1
if l[i]<=r[j]:
md.append(l[i])
i+=1
else:
md.append(r[j])
j+=1
return md
def mergesort(a):
m=len(a)
if m<=1:
return a
m=m//2
l=mergesort(a[:m])
r=mergesort(a[m:])
return mer(l,r)
n=int(input())
a=list(map(int, input().split()))
b=mergesort(a)
for i in range(n-1):
print(b[i],end=" ")
print(b[n-1])
print(cnt)
| 1 | 109,952,075,872 | null | 26 | 26 |
N=int(input())
A=list(map(int,input().split()))
SUM=sum(A)
Q=int(input())
List=[0 for _ in range(10**5+1)]
for a in A:
List[a]+=1
for q in range(Q):
B,C=map(int,input().split())
SUM-=B*List[B]
SUM+=C*List[B]
List[C]+=List[B]
List[B]=0
print(SUM)
|
N, K = map(int,input().split())
friend = list(map(int,input().split()))
clear = []
for i in friend:
if i >= K:
clear.append(i)
print(len(clear))
| 0 | null | 95,218,288,497,320 | 122 | 298 |
a=[input() for i in range(2)]
a1=int(a[0])
a2=[int(i) for i in a[1].split()]
money=1000
kabu=0
for i in range(a1-1):
if a2[i]<a2[i+1]:
kabu=int(money/a2[i])
money+=kabu*(a2[i+1]-a2[i])
print(money)
|
n,k = map(int,input().split())
sec = []
for i in range(k):
l,r = map(int,input().split())
sec.append([l,r])
mod = 998244353
dp = [0]*(n+1)
dp[0],dp[1] = 0,1
cumsum = [0]*(n+1)
cumsum[1] = 1
for i in range(2,n+1):
for l,r in sec:
if i>l:
dp[i] += cumsum[i-l]-cumsum[max(0,i-r-1)]
cumsum[i] = (dp[i]+cumsum[i-1])%mod
print(dp[n]%mod)
| 0 | null | 5,065,615,890,116 | 103 | 74 |
s = input()
h = 'hi'
if s == h or s == h * 2 or s == h * 3 or s == h * 4 or s == h * 5:
print('Yes')
else:
print('No')
|
s=input()
t=input()
max_=0
for i in range(len(s)-len(t)+1):
c = 0
for j in range(len(t)):
if s[i+j] == t[j]:
c += 1
max_ = max(max_, c)
print(len(t)-max_)
| 0 | null | 28,442,788,618,494 | 199 | 82 |
a,b,c,d=map(int,input().split())
for i in range(1001):
if i%2==0:
c-=b
if c<=0:
print("Yes")
exit(0)
else:
a-=d
if a<=0:
print("No")
exit(0)
|
A,B,C,D=map(int,input().split())
ans=0
while 1:
C-=B
if C<=0:
ans=1
break
A-=D
if A<=0:
break
if ans==1:
print("Yes")
else:
print("No")
| 1 | 29,507,812,528,800 | null | 164 | 164 |
B=[];C=[];S=0
N=int(input())
A=list(map(int,input().split()))
Q=int(input())
for i in range(Q):
b,c=map(int,input().split())
B.append(b)
C.append(c)
X=[0]*(10**5+1)
for i in range(N):
X[A[i]]+=1
S=S+A[i]
#print(A)
#print(B)
#print(C)
for i in range(Q):
X[C[i]]+=X[B[i]]
S=S+X[B[i]]*(C[i]-B[i])
X[B[i]]=0
print(S)
|
from collections import Counter
n = int(input())
a = list(map(int, input().split()))
q = int(input())
ans = sum(a)
count = Counter(a)
for _ in range(q):
b,c = map(int, input().split())
count[c] += count[b]
ans -= b*count[b]
ans += c*count[b]
count[b] = 0
print(ans)
| 1 | 12,226,205,850,742 | null | 122 | 122 |
a = [int(i) for i in input().split()]
if(max(a) > 9):
print("-1")
else:
print(a[0] * a[1])
|
from sys import stdin, setrecursionlimit
def main():
input = stdin.buffer.readline
a, b = map(int, input().split())
if 1 <= a <= 9 and 1 <= b <= 9:
print(a * b)
else:
print(-1)
if __name__ == "__main__":
setrecursionlimit(10000)
main()
| 1 | 158,459,961,328,700 | null | 286 | 286 |
n = int(input())
s = list(map(int, input().split()))
m = 1000
stock = 0
for i in range(n-1):
if s[i+1] >= s[i]:
#buy
stock = stock + m // s[i]
m = m - s[i]*(m//s[i])
else:
#sell
m = m + stock*s[i]
stock = 0
an = m + stock*s[n-1]
print(an)
|
n = int(input())
alphabets = [chr(ord('a') + x) for x in range(26)]
tmp = []
def dfs(s, i):
if len(s) == n:
yield s
return
for j in range(i):
for k in dfs(s+alphabets[j], i):
yield k
for k in dfs(s+alphabets[i], i+1):
yield k
for w in dfs('', 0):
print(w)
| 0 | null | 29,861,619,684,664 | 103 | 198 |
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter
from operator import mul
import copy
lun = [[str(i)] for i in range(10)] + [[]]
olun =[[str(i)] for i in range(10)] + [[]]
ans = [str(i) for i in range(1,10)]
while True:
for i in range(0,10):
lun[i] = list(map(lambda x: str(i) + x, (olun[i-1]+olun[i]+olun[i+1])))
if i>= 1: ans += lun[i]
if len(ans) >= 10**5 + 5: break
olun = copy.deepcopy(lun)
k = int(input())
print(ans[k-1])
|
import sys
x,n = map(int,input().split())
p = list(map(int,input().split()))
s = 100
min_i = -1
if x not in p:
print(x)
sys.exit()
for i in range(-1,102):
if i not in p and abs(i-x) < s:
s = abs(i-x)
min_i = i
print(min_i)
| 0 | null | 26,977,192,166,620 | 181 | 128 |
K = int(input())
S = input()
M = int(10 ** 9 + 7)
fact = [1]
for i in range(1, K + len(S) + 10):
fact.append(fact[-1] * i % M)
finv = [pow(fact[-1], M - 2, M)]
for i in range(K + len(S) + 9, 0, -1):
finv.append(finv[-1] * i % M)
finv.reverse()
def comb(a, b, m):
return fact[a] * finv[b] % m * finv[a - b] % m
def hcomb(a, b, m):
return comb(a + b - 1, a - 1, m)
ans = 0
for l in range(0, K + 1):
ans += pow(26, l, M) * pow(25, K - l, M) % M * hcomb(len(S), K - l, M) % M
ans %= M
print(ans)
|
S = input()
S_len = len(S)
print("x" * S_len)
| 0 | null | 42,899,148,333,580 | 124 | 221 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.