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
|
---|---|---|---|---|---|---|
n = int(input())
tp = 0
hp = 0
for i in range(n):
tarou, hanako = map(str,input().split())
if(tarou > hanako):
tp += 3
elif(tarou < hanako):
hp += 3
else:
tp += 1
hp += 1
print("%d %d" %(tp,hp))
|
d,t,s = map(int, input().split())
if(d-t*s>0):
print("No")
else:
print("Yes")
| 0 | null | 2,793,343,514,052 | 67 | 81 |
from itertools import permutations
n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
per = [0] + list(permutations(list(range(1,n+1))))
pnum = per.index(p)
qnum = per.index(q)
ans = abs(pnum-qnum)
print(ans)
|
from itertools import accumulate
mod = 10**9 + 7
n, k = map(int, input().split())
arr = []
for i in range(n+1):
arr.append(i)
ls = [0] + list(accumulate(arr))
ans = 0
for i in range(k, n+2):
ans += (((ls[-1] - ls[-1-i]) - ls[i]) + 1)%mod
ans %= mod
print(ans)
| 0 | null | 66,459,439,893,950 | 246 | 170 |
# B - Battle
import sys
a,b,c,d = map(int,input().split())
while True:
if c - b <= 0:
print('Yes')
sys.exit()
c = c - b
if a - d <= 0:
print('No')
sys.exit()
a = a - d
|
A, B, C, D = map(int, input().split())
is_turn_of_takahashi = True
while A > 0 and C > 0:
if is_turn_of_takahashi:
C -= B
else:
A -= D
is_turn_of_takahashi = not is_turn_of_takahashi
print("Yes" if A > 0 else "No")
| 1 | 29,639,964,297,020 | null | 164 | 164 |
s = input()
k = len(s)
ans = ''
if k % 2 == 1:
ans = 'No'
else:
if s == 'hi' * (k // 2):
ans = 'Yes'
else:
ans = 'No'
print(ans)
|
s=input()
n=len(s)
if n%2==1:
print("No")
exit()
for i in range(n-1):
if s[i]=="h":
if s[i+1]!="i":
print("No")
exit()
elif s[i]=="i":
if s[i+1]!="h":
print("No")
exit()
else:
print("No")
exit()
print("Yes")
| 1 | 53,135,573,309,092 | null | 199 | 199 |
class Node:
def __init__(self, key):
self.key = key
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.nil = Node(None)
self.nil.prev = self.nil
self.nil.next = self.nil
def insert(self,key):
new = Node(key)
new.next = self.nil.next
self.nil.next.prev = new
self.nil.next = new
new.prev = self.nil
def listSearch(self, key):
cur = self.nil.next
while cur != self.nil and cur.key != key:
cur = cur.next
return cur
def deleteNode(self, t):
if t == self.nil:
return
t.prev.next = t.next
t.next.prev = t.prev
def deleteFirst(self):
self.deleteNode(self.nil.next)
def deleteLast(self):
self.deleteNode(self.nil.prev)
def deleteKey(self, key):
self.deleteNode(self.listSearch(key))
if __name__ == '__main__':
import sys
input = sys.stdin.readline # 入力の高速化
n = int(input())
dll = DoublyLinkedList()
for _ in range(n):
'''
以下のようにcomとkeyに分けるとTimeLimitExceededになるので、comだけで処理しました
(別のいい方法があれば教えて欲しいです)
com, *key = input().split()
この場合keyがリストになるので、com[7:]をkey[0]で置き換える必要があります。
(xがない命令ではkey=[]となるだけ)
'''
com = input().rstrip()
# 以下、本と順番など多少異なります
if com[0] == 'i':
dll.insert(com[7:])
elif com[6] == 'F':
dll.deleteFirst()
elif com[6] == 'L':
dll.deleteLast()
else:
dll.deleteKey(com[7:])
cur = dll.nil.next
ans = []
while cur != dll.nil:
ans.append(cur.key)
cur = cur.next
print(' '.join(ans))
|
from math import pi
r = float(input())
print('{:.5f} {:.5f}'.format(r*r*pi,r*2*pi))
| 0 | null | 336,493,899,072 | 20 | 46 |
import sys
import numpy as np
n, k = map(int,input().split())
a = np.array(sorted(list(map(int, input().split()))))
f = np.array(sorted(list(map(int, input().split())), reverse=True))
asum = a.sum()
l,r = 0, 10**13
while l != r:
mid = (l+r)//2
can = (asum - np.minimum(mid//f, a).sum()) <= k
if can:
r = mid
else:
l = mid +1
print(l)
|
def main():
import numpy as np
import sys
input = sys.stdin.readline
N, K = map(int,input().split())
A = np.sort(list(map(int,input().split())))
F = np.sort(list(map(int,input().split())))[::-1]
if K >= np.sum(A)*N:
print(0)
exit()
ma = A[-1]*F[0]
mi = 0
A = A*F
while ma != mi:
tgt = (ma + mi)//2
tmp = np.ceil((A-tgt)/F)
if np.sum(tmp[tmp>0]) <= K:
ma = (ma + mi)//2
else:
mi = (ma + mi)//2+1
print(ma)
if __name__ == '__main__':
main()
| 1 | 165,359,380,354,308 | null | 290 | 290 |
while True:
n = input()
if n == '0':
break
sum = 0
for i in n:
sum += int(i)
print(sum)
|
N=[]
while True:
n=raw_input()
if n=='0':
break
N.append(n)
for i in range(len(N)):
print('%d'%sum(map(int,N[i])))
| 1 | 1,578,035,335,862 | null | 62 | 62 |
import math
a,b,c,d = map(int,input().split(" "))
taka = math.ceil(c/b)
aoki = math.ceil(a/d)
if taka <= aoki:
print("Yes")
else:
print("No")
|
S=list(map(int,input().split()))
while True:
S[2]=S[2]-S[1]
S[0]=S[0]-S[3]
if S[2]<=0:
print("Yes")
break
elif S[0]<=0:
print("No")
break
| 1 | 29,710,708,226,540 | null | 164 | 164 |
while 1:
x,y=sorted(map(int,raw_input().split()))
if x==y==0:break
print x,y
|
while(True):
a, b = map(int, input().split())
if(a == b == 0):
break
print('{} {}'.format(min(a, b), max(a, b)))
| 1 | 519,756,736,256 | null | 43 | 43 |
import sys
def main():
# input = sys.stdin.read()
# data = list(map(int, input.split()))
s = input()
p = input()
cnt = 0
for i in range(len(s) - len(p)+1):
mx = 0
for j in range(len(p)):
if s[i+j] == p[j]:
mx += 1
# print(i, mx)
cnt = max(cnt, mx)
# print(p,cnt)
print(len(p)-cnt)
if __name__ == '__main__':
main()
|
s=input()
t=input()
c=len(t)
for i in range(len(s)-len(t)+1):
d=0
for j in range(len(t)):
if s[i+j]!=t[j]:
d+=1
if d<c:
c=d
print(c)
| 1 | 3,656,424,491,290 | null | 82 | 82 |
def f(w, n, k, v):
# how many things in list w of length n can fill in k cars with capacity v?
i = 0
space = 0
while i < n:
if space >= w[i]:
space -= w[i]
i += 1
else:
# space < w[i]
if k == 0:
break
k -= 1
space = v
return i
if __name__ == '__main__':
n, k = map(int, raw_input().split())
w = []
maxv = -1
for i in range(n):
x = int(raw_input())
w.append(x)
maxv = max(maxv, x)
left = 0
right = n * maxv
# range: (left, right]
# loop until left + 1 = right, then right is the answer
# why? because right works, but right - 1 doesn't work
# so right is the smallest capacity
while right - left > 1:
mid = (left + right) / 2
v = f(w, n, k, mid)
if v >= n:
# range: (left, mid]
# in fact, v cannot > n
right = mid
else:
# range: (mid, right]
left = mid
print right
|
n,x,m=map(int,input().split())
sm=[-1 for i in range(m)]+[0]
w=[-1 for i in range(m)]
d=[m]
a=x
t=0
s=0
while True:
s+=a
if w[a]!=-1:
inter=t-w[a]
fv=w[a]
ls=d[(n-fv)%inter+fv]
lls=d[w[a]]
print(sm[lls]+(n-fv)//inter*(s-sm[a])+(sm[ls]-sm[lls]))
break
w[a]=t
d.append(a)
sm[a]=s
t+=1
a=(a*a)%m
| 0 | null | 1,469,530,769,710 | 24 | 75 |
A, B, M = map(int,input().split())
A = [a for a in map(int,input().split())]
B = [b for b in map(int,input().split())]
C = []
for m in range(M):
C.append([c for c in map(int,input().split())])
ans = min(A) + min(B)
for c in C:
if (A[c[0]-1]+B[c[1]-1]-c[2])<ans:
ans = A[c[0]-1]+B[c[1]-1]-c[2]
print(ans)
|
input_line=input().rstrip().split()
num1 = int(input_line[0])
num2 = int(input_line[1])
if (num1 > num2):
print(str(num2)*num1)
elif (num1 < num2):
print(str(num1)*num2)
elif (num1 == num2):
print(str(num1)*num2)
| 0 | null | 69,184,520,799,482 | 200 | 232 |
a,b = input().split()
ans = sorted( [a*int(b),b*int(a)] )[0]
print(ans)
|
N = int(input())
N += 1
print(N // 2)
| 0 | null | 71,815,919,352,982 | 232 | 206 |
def draft(A, K, N):
for _ in range(1, K+1):# 2 * 10**5
tmp = [0]*(N+1)
for i in range(N):# 2 * 10**5
L = max(0, i - A[i])
R = min(N, i + A[i]+1)
tmp[L] += 1
tmp[R] -= 1
f = True
for i in range(N):
tmp[i+1] += tmp[i]
A[i] = tmp[i]
if A[i] != N:
f = False
if f:
break
for i in range(N):
print(A[i], end=" ")
def main():
N, K = map(int, input().split())
A = list(map(int, input().split()))
draft(A, K, N)
if __name__ == "__main__":
main()
|
import numpy as np
from numba import njit
@njit('i8,i8,i8[::1]',cache=True)
def solve(N,K,A):
for i in range(K):
br = np.zeros(N+1, dtype=np.int64)
for ind, rux in enumerate(A):
br[max(ind-rux,0)] += 1
br[min(ind+rux+1,N)] -= 1
A = br.cumsum()[:-1]
if br[0] == N and br[-1] == -N:
return A
return A
if __name__ == "__main__":
n,k = map(int, input().split())
a = np.array(list(map(int, input().split())),dtype=np.int64)
ans = solve(n,k,a)
print(*ans)
| 1 | 15,454,553,353,860 | null | 132 | 132 |
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random,resource
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)
def main():
n = I()
s = S()
m = {}
m[0] = 0
def f(i):
if i in m:
return m[i]
c = 0
ii = i
while ii > 0:
c += ii % 2
ii //= 2
t = i % c
m[i] = f(t) + 1
return m[i]
c = len([_ for _ in s if _ == '1'])
t = int(s, 2)
cm = (c+1) * c * (c-1)
if c > 1:
t %= cm
r = []
k = 1
for i in range(n-1,-1,-1):
if t == k:
r.append(0)
elif s[i] == '1':
r.append(f((t - k) % (c-1)) + 1)
else:
r.append(f((t + k) % (c+1)) + 1)
k *= 2
if c > 1:
k %= cm
return JA(r[::-1], "\n")
print(main())
|
def pc(x):
return format(x, 'b').count('1')
N = int(input())
X = input()
Xo = int(X, 2)
count = 0
ans = 0
ori = pc(Xo)
X = list(X)
Xp = Xo%(ori + 1)
if ori == 1:
Xm = 0
else:
Xm = Xo % (ori - 1)
# for i in range(N-1, -1, -1):
for i in range(N):
if ori == 1 and X[i] == '1':
print(0)
continue
else:
if X[i] == '1':
# ans = Xm - pow(2, i, ori - 1)
ans = Xm - pow(2, N-1-i, ori - 1)
ans %= ori - 1
else:
# ans = Xp - pow(2, i, ori + 1)
ans = Xp + pow(2, N-1-i, ori + 1)
ans %= ori + 1
count = 1
while ans > 0:
# count += 1
# if ans == 1:
# break
ans %= pc(ans)
count += 1
print(count)
count = 1
| 1 | 8,129,212,942,982 | null | 107 | 107 |
n = input()
S = raw_input().split()
q = input()
T = raw_input().split()
s = 0
for i in T:
if i in S:
s+=1
print s
|
#!/usr/bin/env python3
import sys
import numpy as np
input = sys.stdin.readline
def ST():
return input().rstrip()
def I():
return int(input())
def MI():
return map(int, input().split())
def LI():
return list(MI())
S = ST()
cnt = np.zeros(2019)
cnt[0] = 1
res = 0
tmp = 1
for s in S[::-1]:
res += int(s) * tmp
res %= 2019
cnt[res] += 1
tmp *= 10
tmp %= 2019
ans = 0
for c in cnt[cnt >= 2]:
ans += c * (c - 1) // 2
print(int(ans))
| 0 | null | 15,489,038,389,418 | 22 | 166 |
# 連想配列
from collections import deque
N = int(input())
ab = {}
abl = []
path = [[] for _ in range(N)]
for i in range(N-1):
a,b = map(int,input().split())
path[a-1].append(b-1)
path[b-1].append(a-1)
abl.append((a-1,b-1))
ab[(a-1,b-1)] = 0
color = [0]*N
color[0] = -1
q = deque([])
q.append(0)
max = 0
while len(q)>0:
cn = q.popleft()
ccolor = color[cn]
ncolor = 1
for i in path[cn]:
if color[i] == 0:
if ccolor != ncolor:
color[i] = ncolor
ab[(cn,i)] = ncolor
ncolor += 1
else:
color[i] = ncolor+1
ab[(cn,i)] = ncolor+1
ncolor += 2
if color[i] > max:
max = color[i]
q.append(i)
print(max)
for i in abl:
print(ab[i])
|
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
def dfs(curr, pare, pare_c, k, color_dic):
curr_c = pare_c
for chi in g[curr]:
if chi == pare: continue
curr_c = curr_c%k + 1
color_dic[(curr,chi)] = curr_c
dfs(chi, curr, curr_c, k, color_dic)
n = int(input())
g = [ [] for _ in range(n+1)]
gl = []
for i in range(n-1):
a, b = map(int, input().split())
g[a].append(b)
g[b].append(a)
gl.append((a,b))
k = 0
for node in g:
k = max(len(node),k)
color_dic = {}
dfs(1, -1, 0, k, color_dic)
print(k)
for edge in gl:
print(color_dic[edge])
| 1 | 135,865,226,576,478 | null | 272 | 272 |
INF = 10**10
def merge(ary, left, mid, right):
lry = ary[left:mid]
rry = ary[mid:right]
lry.append(INF)
rry.append(INF)
i = 0
j = 0
for k in range(left, right):
if lry[i] <= rry[j]:
ary[k] = lry[i]
i += 1
else:
ary[k] = rry[j]
j += 1
return right - left
def merge_sort(ary, left, right):
cnt = 0
if left + 1 < right:
mid = (left + right) // 2
cnt += merge_sort(ary, left, mid)
cnt += merge_sort(ary, mid, right)
cnt += merge(ary, left, mid, right)
return cnt
if __name__ == '__main__':
n = int(input())
ary = [int(_) for _ in input().split()]
cnt = merge_sort(ary, 0, n)
print(*ary)
print(cnt)
|
cnt = 0
def merge(A, left, mid, right):
global cnt
L = A[left:mid]
R = A[mid:right]
L.append(10000000000)
R.append(10000000000)
i = 0
j = 0
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):
if left + 1 < right: #if block size >= 2
mid = int((left + right)/2)
mergesort(A, left, mid)
mergesort(A, mid, right)
merge(A, left, mid, right)
n = int(input())
S = list(map(int,input().split()))
mergesort(S, 0, n)
print(*S)
print(str(cnt))
| 1 | 111,398,435,070 | null | 26 | 26 |
k = int(input())
a,b = map(int,input().split())
if b//k - (a-1)//k > 0:
print("OK")
else:
print("NG")
|
#coding:UTF-8
def FN(n):
if n==0 or n==1:
F[n]=1
return F[n]
if F[n]!=None:
return F[n]
F[n]=FN(n-1)+FN(n-2)
return F[n]
if __name__=="__main__":
n=int(input())
F=[None]*(n+1)
ans=FN(n)
print(ans)
| 0 | null | 13,203,891,060,180 | 158 | 7 |
n=int(input())
a=list(map(int,input().split()))
for i in a:
if i%2==0 and i%3!=0 and i%5!=0:
print("DENIED")
exit()
print("APPROVED")
|
a=int(input())
b=list(map(int,input().split()))
c=0
for i in range(a):
if b[i]%2==0:
if b[i]%3==0 or b[i]%5==0:
c=c+1
else:
c=c+1
if c==a:
print("APPROVED")
else:
print("DENIED")
| 1 | 69,034,834,819,118 | null | 217 | 217 |
data_h = []
data_w = []
while True:
h, w = (int(i) for i in input().split())
if h == w == 0:
break
else:
data_h.append(h)
data_w.append(w)
for i in range(len(data_h)):
h = data_h[i]
w = data_w[i]
for j in range(1,h+1):
for k in range(1,w+1):
if j == 1 or j == h or k == 1 or k == w:
print('#',end='')
else:
print('.',end='')
print('')
print('')
|
n = int(input())
data = list(map(int, input().split()))
ans = 0
money = 1000
for idx in range(n-1):
today = data[idx]
tmr = data[idx+1]
if tmr > today:
money += (tmr-today) * (money//today)
print(money)
| 0 | null | 4,102,647,632,818 | 50 | 103 |
debt=100000
week=input()
for i in range(week):
debt=debt*1.05
if debt%1000!=0:
debt=int(debt/1000)*1000+1000
print debt
|
def resolve():
N, u, v = list(map(int, input().split()))
u, v = u-1, v-1
adjs = [ [] for _ in range(N)]
for _ in range(N-1):
a, b = list(map(lambda x: int(x)-1, input().split()))
adjs[a].append(b)
adjs[b].append(a)
dist_from_u = [float("inf") for _ in range(N)]
dist_from_u[u] = 0
import collections
q = collections.deque([u])
while q:
node = q.pop()
for adj in adjs[node]:
if dist_from_u[adj] > dist_from_u[node]+1:
dist_from_u[adj] = dist_from_u[node]+1
q.appendleft(adj)
#print(dist_from_u)
dist_from_v = [float("inf") for _ in range(N)]
dist_from_v[v] = 0
import collections
q = collections.deque([v])
while q:
node = q.pop()
for adj in adjs[node]:
if dist_from_v[adj] > dist_from_v[node]+1:
dist_from_v[adj] = dist_from_v[node]+1
q.appendleft(adj)
#print(dist_from_v)
length = 0
for i in range(N):
if dist_from_u[i] < dist_from_v[i] and length < dist_from_v[i]:
length = dist_from_v[i]
print(length-1)
if __name__ == "__main__":
resolve()
| 0 | null | 58,846,339,608,904 | 6 | 259 |
def main():
H, W, K = (int(i) for i in input().split())
A = [input() for i in range(H)]
ans = [[-1]*W for _ in range(H)]
p = 1
for h in range(H):
flag = False
cnt = 0
for w in range(W):
if A[h][w] == "#":
flag = True
cnt += 1
upper = p + cnt
if not(flag):
continue
for w in range(W):
ans[h][w] = p
if A[h][w] == "#":
if p + 1 < upper:
p += 1
p = upper
for h in range(H):
for w in range(W):
if ans[h][w] != -1:
continue
if h != 0:
ans[h][w] = ans[h-1][w]
for h in range(H)[::-1]:
for w in range(W):
if ans[h][w] != -1:
continue
if h != H-1:
ans[h][w] = ans[h+1][w]
for a in ans:
print(*a)
if __name__ == '__main__':
main()
|
N=int(input())
S=set()
for i in range(1,N):
x=i
y=N-i
if x<y:
S.add(x)
print(len(S))
| 0 | null | 148,228,867,856,372 | 277 | 283 |
while True:
m,f,r=map(int,input().split())
p=m+f
if m+f+r==-3:
break
if m==-1 or f==-1:
print("F")
elif p>=80:
print("A")
elif 65<=p and p<80:
print("B")
elif 50<=p and p<65:
print("C")
elif 30<=p and p<50:
if r>=50:
print("C")
else:
print("D")
else:
print("F")
|
s,t = input().split()
a,b = map(int,input().split())
u = input()
print(a if u == t else a-1, end = " ")
print(b-1 if u == t else b)
| 0 | null | 36,363,204,090,500 | 57 | 220 |
K=input()
r='ACL'
for i in range(1,int(K)):
r='ACL'+ r
print(r)
|
#! /usr/bin/python3
k = int(input())
print('ACL'*k)
| 1 | 2,148,433,070,902 | null | 69 | 69 |
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))
n=ni()
c = [1 if _ == 'R' else 0 for _ in input()]
b = sum(c)
w=0
r=0
for i in range(n):
if c[i] == 0 and i < b:
r+=1
if c[i] == 1 and i >= b:
w+=1
print(max(w,r))
|
n = int(input())
s = input()
num_r = s.count("R")
count = 0
for i in range(num_r):
if s[i] != "R":
count += 1
print(count)
| 1 | 6,293,699,332,736 | null | 98 | 98 |
a,b=map(int,input().split())
print((a//b)+1 if a%b!=0 else a//b)
|
n = input()
R = [input() for i in xrange(n)]
m = R[0]
ans = -1e10
for r in R[1:]:
ans = max(ans, r - m)
m = min(m, r)
print ans
| 0 | null | 38,354,078,881,668 | 225 | 13 |
S = int(input())
R = "ACL"
print(R * S)
|
x = int(input())
for _ in range(x):
print("ACL", end="")
| 1 | 2,207,809,269,510 | null | 69 | 69 |
import bisect
n=int(input())
l=sorted(list(map(int,input().split())))
ans=0
for i in range(n-1):
for j in range(i+1,n):
index=bisect.bisect_left(l,l[i]+l[j])
if j<index:
ans+=index-j-1
print(ans)
|
import bisect
def bisect_right_reverse(a, x):
'''
reverseにソートされたlist aに対してxを挿入できるidxを返す。
xが存在する場合には一番右側のidx+1となる。
'''
if a[0] < x:
return 0
if x <= a[-1]:
return len(a)
# 二分探索
ok = len(a) - 1
ng = 0
while (abs(ok - ng) > 1):
mid = (ok + ng) // 2
if a[mid] < x:
ok = mid
else:
ng = mid
return ok
def bisect_left_reverse(a, x):
'''
reverseにソートされたlist aに対してxを挿入できるidxを返す。
xが存在する場合には一番左側のidxとなる。
'''
if a[0] <= x:
return 0
if x < a[-1]:
return len(a)
# 二分探索
ok = len(a) - 1
ng = 0
while (abs(ok - ng) > 1):
mid = (ok + ng) // 2
if a[mid] <= x:
ok = mid
else:
ng = mid
return ok
def main2():
n = int(input())
l=[int(i) for i in input().split()]
l.sort(reverse = True)
res = 0
for i in range(n-1):
for j in range(i+1, n-1):
#index がj以降で k < c を満たすcで一番小さいc'を探す
#index(c')-j - 1が三角形の条件を満たす
nibu = l[j+1:]
k = max(l[i]-l[j],l[j]-l[i])
left=bisect_left_reverse(nibu,k)
res += left
print(res)
if __name__ == '__main__':
main2()
| 1 | 172,046,392,017,632 | null | 294 | 294 |
n = input()
list = map(int, input().split())
num = 1
a = 0
for i in list:
if i == num:
num = num +1
else:
a = a + 1
if num == 1:
print(-1)
else:
print(a)
|
N=int(input())
L=list(map(int,input().split()))
i=0
n=1
while True:
if i==N:
break
if L[i]==n:
n+=1
i+=1
if n==1:
print(-1)
else:
print(N-n+1)
| 1 | 114,895,792,698,592 | null | 257 | 257 |
from collections import deque
N, D, A = map(int, input().split())
monsters = []
for _ in range(N):
monsters.append(list(map(int, input().split())))
monsters.sort()
d = deque()
ans = 0
damage = 0
for x, h in monsters:
while d:
if d[0][0] >= x - D:
break
_, power = d.popleft()
damage -= power
h -= damage
if h <= 0:
continue
attack = (h - 1) // A + 1
ans += attack
d.append((x + D, attack * A))
damage += attack * A
print(ans)
|
ring_str=input()
key=input()
ring_str+=ring_str
if key in ring_str:
print('Yes')
else:
print('No')
| 0 | null | 42,198,003,567,188 | 230 | 64 |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def main():
S = input()
cnt = 0
mx = 0
for i in range(len(S)):
if (S[i] == 'R'):
cnt += 1
else:
cnt = 0
mx = max(mx, cnt)
print(mx)
if __name__ == '__main__':
main()
|
A=int(input())
B=int(input())
if 1 not in [A,B]:
print(1)
if 2 not in [A,B]:
print(2)
if 3 not in [A,B]:
print(3)
| 0 | null | 57,685,702,974,570 | 90 | 254 |
n, p = map(int, input().split())
s = input()
count = [0]*p
key = 0
if p%2 and p%5:
count = [0]*p
key = 0
mod = 1
for i in range(n):
key += (mod*int(s[n-1-i]))%p
key %= p
count[key] += 1
mod *= 10
mod %= p
ans = count[0]
for i in range(p):
if count[i] >= 2:
ans += (count[i])*(count[i]-1)//2
else:
ans = 0
for i in range(n):
key = int(s[n-1-i])
if key%p == 0:
ans += n-i
print(ans)
|
a, b, c, k = map(int, input().split())
ans = 0
if a >= k:
ans = k
elif a < k and a+b >= k:
ans = a
else:
ans = a - (k-(a+b))
print(ans)
| 0 | null | 39,948,865,768,630 | 205 | 148 |
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)
|
N = int(input())
S = ""
while 0<N:
N-=1
S+=chr(97+N%26)
N//=26
print(S[::-1])
| 0 | null | 37,414,763,511,410 | 210 | 121 |
"""
方針:
幸福度が一定以上のつなぎ方の数→NlogNで二分探索可能
採用するうち最小の幸福度を NlogNlogNで探索
累積和を用いて合計を算出
2 3
5 2
10 + 7 + 7 = 24
"""
import bisect
def wantover(n): #n以上の幸福度のつなぎ方の数がM以上ならTrueを返す
ret = 0
for i in range(N):
serchnum = n - A[i]
ret += (N - bisect.bisect_left(A,serchnum))
#print ("over",n,"is",ret)
if ret >= M:
return True
else:
return False
N,M = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
#print (wantover(7))
hpl = 0
hpr = A[-1] * 2 + 1
while hpr - hpl != 1:
mid = (hpr + hpl) // 2
if wantover(mid):
hpl = mid
else:
hpr = mid
#ここで最小の幸福度はhpl
#print (hpl,hpr)
B = [0] #累積和行列
for i in range(N):
B.append(B[-1] + A[-1 - i])
#print (A)
#print (B)
ans = 0
plnum = 0 #つないだ手の回数
for i in range(N):
i = N-i-1
ind = bisect.bisect_left(A,hpl - A[i])
#print (hpl,A[i],N-ind)
plnum += N - ind
ans += B[N - ind] + A[i] * (N-ind)
#print (ans,plnum)
print (ans - hpl * (plnum - M))
|
from bisect import bisect_left
def main():
n, m = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
L, R = 0, 2 * 10**5 + 1
while L+1 < R:
P = (L+R)//2
cnt = 0
for v in a:
x = P - v
cnt += n - bisect_left(a, x)
if cnt >= m:
L = P
else:
R = P
csum = [0]
for v in a:
csum.append(v)
for i in range(n):
csum[i+1] += csum[i]
ans = 0
cnt = 0
for v in a:
x = L - v
idx = bisect_left(a, x)
cnt += n-idx
ans += csum[-1] - csum[idx]
ans += v * (n - idx)
ans -= (cnt - m) * L
print(ans)
if __name__ == "__main__":
main()
| 1 | 108,115,843,929,998 | null | 252 | 252 |
import numpy as np
from numba import njit
@njit
def f(a):
n = len(a)
cnt = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if a[k] < a[i] + a[j]:
cnt += 1
return cnt
n = int(input())
a = np.array(input().split(), dtype=np.int32)
a.sort()
print(f(a))
|
while 1:
tmp = map(int, raw_input().split())
if tmp[0] == tmp[1] == 0:
break
else:
print " ".join(map(str, sorted(tmp)))
| 0 | null | 85,948,086,285,082 | 294 | 43 |
def bingo(appear):
for j in range(3):
if appear[0][j] and appear[1][j] and appear[2][j]:
return "Yes"
for i in range(3):
if appear[i][0] and appear[i][1] and appear[i][2]:
return "Yes"
if appear[0][0] and appear[1][1] and appear[2][2]:
return "Yes"
if appear[0][2] and appear[1][1] and appear[2][0]:
return "Yes"
return "No"
card = []
for _ in range(3):
arr = list(map(int, input().split()))
card.append(arr)
appear = [[False for _ in range(3)] for _ in range(3)]
n = int(input())
for _ in range(n):
a = int(input())
for i in range(3):
for j in range(3):
if a == card[i][j]:
appear[i][j] = True
print(bingo(appear))
|
A = [list(map(int,input().split())) for _ in range(3)]
N = int(input())
b = [int(input()) for _ in range(N)]
c = [[0]*3 for _ in range(3)]
for x in b:
for i in range(3):
for j in range(3):
if A[i][j] == x:
c[i][j] = 1
if c[0] == [1,1,1] or c[1] == [1,1,1] or c[2] == [1,1,1]:
print("Yes")
elif [c[0][0], c[1][0], c[2][0]] == [1,1,1] or [c[0][1], c[1][1], c[2][1]] == [1,1,1] or [c[0][2], c[1][2], c[2][2]] == [1,1,1]:
print("Yes")
elif [c[0][0], c[1][1], c[2][2]] == [1,1,1] or [c[2][0], c[1][1], c[0][2]] == [1,1,1]:
print("Yes")
else:
print("No")
| 1 | 59,688,820,763,010 | null | 207 | 207 |
N = int(input())
A_list = [0]*N
B_list = [0]*N
for i in range(N):
A_list[i],B_list[i] = map(int,input().split())
A_list.sort()
B_list.sort()
if N%2 == 1:
print(B_list[(N-1)//2] - A_list[(N-1)//2] + 1)
else:
big = (B_list[N//2] + B_list[N//2-1])/2
small = (A_list[N//2] + A_list[N//2-1])/2
print(int((big-small)*2 + 1))
|
n = int(input())
a = list(map(int, input().split()))
target = 1
broken = 0
for i in a:
if i == target:
target += 1
else:
broken += 1
if broken < n:
print(broken)
else:
print(-1)
| 0 | null | 66,224,005,317,460 | 137 | 257 |
days = ('SUN','MON','TUE','WED','THU','FRI','SAT')
Day_of_the_week = input()
for index, day in enumerate(days):
if Day_of_the_week == day:
print(7 - index)
|
weekday = ['SUN', 'SAT', 'FRI', 'THU', 'WED', 'TUE', 'MON']
val = input()
if val == 'SUN':
print("7")
else:
print(weekday.index(val))
| 1 | 133,244,628,998,172 | null | 270 | 270 |
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)
|
n = int(input())
R = []
for i in range(n):
R.append(int(input()))
minv = R[0]
maxv = R[1] - R[0]
for r in R[1:]:
maxv = max(maxv, r - minv)
minv = min(minv, r)
print(maxv)
| 0 | null | 4,457,191,182,048 | 110 | 13 |
vec1 = []
vec2 = []
n, m = map(int, input().split())
for x in range(1, n+1):
vec1.append(list(map(int, input().split())))
for y in range(m):
vec2.append(int(input()))
for j in vec1:
result = 0
for w, z in zip(j, vec2):
result += w * z
print(result)
|
n = int(input())
a = list(map(int, input().split()))
if 1 in a:
num = 1
for i in range(n):
if a[i] == num:
a[i] = 0
num += 1
else:
a[i] = 1
print(sum(a))
else:
print(-1)
| 0 | null | 58,060,451,071,520 | 56 | 257 |
N = int(input())
S = input()
if len(S) % 2 != 0:
print("No")
exit()
else:
l = len(S)
if S[0:l//2] == S[l//2:l]:
print("Yes")
else:
print("No")
|
N = int(input())
ret = False
if N % 2 == 0:
S = input()
if S[:N//2] == S[N//2:]:
ret = True
if ret:
print("Yes")
else:
print("No")
| 1 | 147,246,558,460,352 | null | 279 | 279 |
S = "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"
N = list(map(int,S.split(",")))
K = int(input())
print(N[K-1])
|
s = "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"
lst = s.split(", ")
print(lst[int(input()) - 1])
| 1 | 50,112,066,496,092 | null | 195 | 195 |
x = input()
ans = 1 if x == "0" else 0
print(ans)
|
import math
h, w = map(int, input().split())
print(math.ceil((h * w) / 2) if h != 1 and w != 1 else 1)
| 0 | null | 26,989,533,786,114 | 76 | 196 |
from collections import deque,defaultdict
import bisect
N = int(input())
S = [input() for i in range(N)]
def bend(s):
res = 0
k = 0
for th in s:
if th == '(':
k += 1
else:
k -= 1
res = min(k,res)
return res
species = [(bend(s),s.count('(')-s.count(')')) for s in S]
ups = [(b,u) for b,u in species if u > 0]
flats = [(b,u) for b,u in species if u == 0]
downs = [(b,u) for b,u in species if u < 0]
ups.sort()
high = 0
for b,u in ups[::-1] + flats:
if high + b < 0:
print('No')
exit()
high += u
rdowns = [(b-u,-u) for b,u in downs]
rdowns.sort()
high2 = 0
for b,u in rdowns[::-1]:
if high2 + b < 0:
print('No')
exit()
high2 += u
if high == high2:
print('Yes')
else:
print('No')
|
N, K = list(map(int, input().split()))
pt = list(map(int, input().split()))
T = input()
pc_hand = [0]*N
my_hand = [0]*N
for i in range(N):
if T[i] == 'r':
pc_hand[i] = 0
elif T[i] == 's':
pc_hand[i] = 1
else:
pc_hand[i] = 2
point = 0
for i in range(N):
if i >= K and T[i] == T[i - K] and (my_hand[i - K] + 1) % 3 == pc_hand[i - K]:
my_hand[i] = pc_hand[i]
else:
my_hand[i] = (pc_hand[i] - 1) % 3
point += pt[my_hand[i]]
print(point)
| 0 | null | 65,443,201,841,718 | 152 | 251 |
N=int(input());M=N//500;M*=1000;X=500*(N//500);N-=X;M+=(N//5)*5;print(M)
|
X = int(input())
happy = 0
happy += (X // 500) * 1000
X %= 500
happy += (X // 5) * 5
print(happy)
| 1 | 42,856,460,037,642 | null | 185 | 185 |
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
def gcd(*numbers): reduce(math.gcd, numbers)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
count = 0
ans = 0
N = k()
ans = N-1
for i in range(1,int(N**0.5)+1):
if N % i == 0:
b = N // i
ans = min(ans, b+i-2)
print(ans)
|
n=int(input())
result=float('inf')
for i in range(1,int(n**.5)+1):
if i*(n//i)==n:
result=min(result,abs(i+n//i)-2)
print(result)
| 1 | 161,658,825,958,498 | null | 288 | 288 |
#ITP1_10-A Distance
x1,y1,x2,y2 = input().split(" ")
x1=float(x1)
y1=float(y1)
x2=float(x2)
y2=float(y2)
print ( ((x1-x2)**2.0 + (y1-y2)**2.0 )**0.5)
|
import math
if __name__ == '__main__':
x1, y1, x2, y2 = [float(i) for i in input().split()]
d = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
print("{0:.5f}".format(d))
| 1 | 159,024,333,848 | null | 29 | 29 |
N = int(input())
G = [[] for n in range(N)]
vc = N*[0]
ec = (N-1)*[0]
h = 1
for n in range(N-1):
a,b = map(int,input().split())
G[a-1].append((b-1,n))
for v,g in enumerate(G):
t = 1
for b,i in g:
if vc[v]==t:
t+=1
vc[b] = t
ec[i] = t
h = max(h,t)
t+=1
print(h)
for n in range(N-1):
print(ec[n])
|
#!/usr/bin/env python3
from collections import deque
n = int(input())
connect_list = [[] for _ in range(n)]
ab = [list(map(int, input().split())) for i in range(n-1)]
for i in range(n-1):
a, b = ab[i]
connect_list[a-1].append(b-1)
connect_list[b-1].append(a-1)
color_list = {}
check_list = [0]*n
color_max = max(map(len, connect_list))
vertex = [0 for i in range(n)]
d = deque([0])
while(len(d) > 0):
# print(d)
index = d.pop()
check_list[index] = 1
index_list = connect_list[index]
for i in index_list:
if check_list[i] == 1:
continue
check_list[i] = 1
d.append(i)
num = vertex[index] % color_max+1
color_list[(min(index, i), max(index, i))] = num
vertex[index], vertex[i] = num, num
print(color_max)
for a, b in ab:
print(color_list[(a-1, b-1)])
| 1 | 136,635,234,723,680 | null | 272 | 272 |
import math
def isPrime(number):
for i in range(2,math.floor(math.sqrt(number))+1):
if number%(i)==0:
return False
return True
N=int(input())
numbers=[]
for i in range(N):
numbers.append(int(input()))
pass
count=0
for number in numbers:
if isPrime(number):
count+=1
print(count)
|
def getprimes(n):
primes = []
for i in xrange(2, n+1):
isprime = True
for j in xrange(len(primes)):
if i % primes[j] == 0:
isprime = False
break
if isprime:
primes.append(i)
return primes
n = int(raw_input())
primes = getprimes(10000)
count = 0
for _ in xrange(n):
x = int(raw_input())
isprime = True
for i in xrange(len(primes)):
if primes[i] >= x:
break
if x % primes[i] == 0:
isprime = False
break
if isprime:
count += 1
print count
| 1 | 9,832,378,400 | null | 12 | 12 |
mod=10**9+7
def fact(n):
ans=1
for i in range(1,n+1):
ans*=i
ans%=mod
return ans
x,y=map(int,input().split())
if (x+y)%3!=0: print(0)
else:
temp=(x+y)//3
if x<temp or x>2*temp: print(0)
else:
dx=x-temp
fc_temp=fact(temp)
fc_dx=fact(dx)
fc_temp_dx=fact(temp-dx)
fc_dx=pow(fc_dx,mod-2,mod)
fc_temp_dx=pow(fc_temp_dx,mod-2,mod)
ans=fc_temp*fc_dx%mod*fc_temp_dx%mod
print(ans)
|
x = int(input())
y = 0
z = 100
while z<x:
y+=1
z *= 101
z //= 100
print(y)
| 0 | null | 88,854,187,773,820 | 281 | 159 |
t_hp, t_atk, a_hp, a_atk = map(int, input().split())
t_count = 0
a_count = 0
while a_hp > 0:
a_hp -= t_atk
t_count += 1
while t_hp > 0:
t_hp -= a_atk
a_count += 1
if t_count <= a_count:
print('Yes')
else:
print('No')
|
# ALDS1_4_C.py
N = int(input())
dict = {}
for i in range(N):
query, s = input().split()
if query == "insert":
dict[s] = True
else:
print('yes' if s in dict else 'no')
| 0 | null | 14,986,141,431,666 | 164 | 23 |
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))
|
K = int(input())
a=[7 % K]
for i in range(1, K):
a.append((10*a[i-1] + 7) % K)
flag = False
for i in range(len(a)):
if a[i] == 0:
print(i+1)
flag = True
break
if not flag:
print(-1)
| 0 | null | 3,137,932,039,360 | 32 | 97 |
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0002
"""
while True:
try:
a = raw_input().split()
#print a
c = 0
for b in a:
c = c + int(b)
print len(str(c))
except EOFError:
break
|
import sys
for line in sys.stdin:
a = int(line.split()[0])
b = int(line.split()[1])
s = a + b
print(len(str(s)))
| 1 | 119,465,152 | null | 3 | 3 |
print(['SUN','MON','TUE','WED','THU','FRI','SAT'][::-1].index(input())+1)
|
s = input()
x = 7
if s == "SUN":
pass
elif s == "SAT":
x = x - 6
elif s == "FRI":
x = x - 5
elif s == "THU":
x = x - 4
elif s == "WED":
x = x - 3
elif s == "TUE":
x = x - 2
elif s == "MON":
x = x - 1
print(x)
| 1 | 132,899,934,928,240 | null | 270 | 270 |
N = int(input())
print(1 - N)
|
import sys
n, a, b = map(int, input().split())
mod = 10**9 + 7
sys.setrecursionlimit(10**9)
def f(x):
if x == 0:
return 1
elif x % 2 == 0:
return (f(x // 2) ** 2) % mod
else:
return (f(x - 1) * 2) % mod
def comb(n,k,p):
"""power_funcを用いて(nCk) mod p を求める"""
from math import factorial
if n<0 or k<0 or n<k: return 0
if n==0 or k==0: return 1
a=factorial(n) %p
b=factorial(k) %p
c=factorial(n-k) %p
return (a*power_func(b,p-2,p)*power_func(c,p-2,p))%p
def power_func(a,b,p):
"""a^b mod p を求める"""
if b==0: return 1
if b%2==0:
d=power_func(a,b//2,p)
return d*d %p
if b%2==1:
return (a*power_func(a,b-1,p ))%p
# 互いに素なa,bについて、a*x+b*y=1の一つの解
def extgcd(a, b):
r = [1, 0, a]
w = [0, 1, b]
while w[2] != 1:
q = r[2] // w[2]
r2 = w
w2 = [r[0] - q * w[0], r[1] - q * w[1], r[2] - q * w[2]]
r = r2
w = w2
# [x,y]
return [w[0], w[1]]
# aの逆元(mod m)を求める。(aとmは互いに素であることが前提)
def mod_inv(a, m):
x = extgcd(a, m)[0]
return (m + x % m) % m
def nCm(a):
ans = 1
for i in range(a):
ans *= n - i
ans %= mod
for i in range(1, a+1):
ans *= mod_inv(i, mod)
ans %= mod
return ans
base = f(n)
comb_a = nCm(a)
comb_b = nCm(b)
print((base - comb_a - comb_b - 1) % mod)
| 0 | null | 34,648,171,105,300 | 76 | 214 |
def main():
S = input()
print(S[0:3])
if __name__ == "__main__":
main()
|
s = input()
q = int(input())
for _ in range(q):
query = list(input().split())
l,r = map(int,query[1:3])
if query[0] == 'replace':
p = query[3]
s = s[:l] + p + s[r+1:]
elif query[0] == 'reverse':
s = s[:l] + ''.join(list(reversed(s[l:r+1]))) + s[r+1:]
else:
print(s[l:r+1])
| 0 | null | 8,421,377,994,400 | 130 | 68 |
# 154 A
s, t = input().split()
a, b = map(int, input().split())
u = input()
if u == s:
a = a - 1
elif u == t:
b = b - 1
print(a, end = " ")
print(b)
|
m=f=r=0
while 1:
m,f,r=map(int,input().split())
x=m+f
if m==f==r==-1:break
elif m==-1 or f==-1 or x<30:print('F')
elif x>=80:print('A')
elif 65<=x<80:print('B')
elif 50<=x<65 or r>=50:print('C')
else:print('D')
| 0 | null | 36,559,617,136,358 | 220 | 57 |
def division(n):
if n < 2:
return []
prime_fac = []
for i in range(2,int(n**0.5)+1):
cnt = 0
while n % i == 0:
n //= i
cnt += 1
if cnt!=0:prime_fac.append((i,cnt))
if n > 1:
prime_fac.append((n,1))
return prime_fac
n = int(input())
div = division(n)
ans = 0
for i,e in div:
b = 1
while b <= e:
e -= b
b += 1
ans += 1
print(ans)
|
N,K=map(int,input().split())
MOD=int(1e9)+7
dp=[0]*(K+1)
for i in range(K):
j=K-i
dp[j]+=pow(K//j, N, MOD)
k=2*j
while k<=K:
dp[j]=(dp[j]-dp[k]+MOD) % MOD
k+=j
ans=0
for i in range(1,K+1):
ans+=dp[i]*i
ans%=MOD
print(ans)
| 0 | null | 27,030,813,166,720 | 136 | 176 |
s = input()
p = input()
s = s * 2
for i in range(len(s) - len(p) + 1):
#print(s[i:i + len(p)])
if p == s[i:i + len(p)]:
print("Yes")
exit()
print("No")
|
s = raw_input()
p = raw_input()
slen = len(s)
plen = len(p)
flag = False
for i in xrange(len(s)):
j = 0
while(j < plen and s[(i+j)%slen] == p[j]):
j += 1
if (j == plen):
flag = True
if(flag):
print "Yes"
else:
print "No"
| 1 | 1,728,330,090,450 | null | 64 | 64 |
N, M, K = map(int, input().split())
A=list(map(int, input().split()))
B=list(map(int, input().split()))
Asum=[0]
Bsum=[0]
for i, a in enumerate(A):
Asum.append(Asum[i]+a)
for i, b in enumerate(B):
Bsum.append(Bsum[i]+b)
ans, b = 0, M
for a, asum in enumerate(Asum):
if asum > K:
break
while Bsum[b]>K - asum:
b-=1
ans = max(ans, a+b)
print(ans)
|
N,K=map(int,input().split())
ans=0
mod=10**9+7
A=[0 for i in range(K)]
for i in range(K,0,-1):
l=pow(K//i,N,mod)
a=2
while a*i<=K:
l-=A[a*i-1]
a+=1
ans+=l*i%mod
ans%=mod
A[i-1]=l
print(ans)
| 0 | null | 23,724,959,767,802 | 117 | 176 |
# -*- coding: utf-8 -*-
import sys
from collections import deque
N,D,A=map(int, sys.stdin.readline().split())
XH=[ map(int, sys.stdin.readline().split()) for _ in range(N) ]
XH.sort()
q=deque() #(攻撃が無効となる座標、攻撃によるポイント)
ans=0
cnt=0
attack_point=0
for x,h in XH:
while q:
if x<q[0][0]:break #無効となる攻撃がない場合はwhileを終了
end_x,end_point=q.popleft()
attack_point-=end_point #攻撃が無効となる座標<=現在の座標があれば、その攻撃のポイントを引く
if h<=attack_point: #モンスターの体力よりも攻撃で減らせるポイントの方が大きければ新規攻撃は不要
pass
else: #新規攻撃が必要な場合
if h%A==0:
cnt=(h-attack_point)/A #モンスターの大量をゼロ以下にするために何回攻撃が必要か
else:
cnt=(h-attack_point)/A+1
attack_point+=cnt*A
q.append((x+2*D+1,cnt*A)) #(攻撃が無効となる座標、攻撃によるポイント)をキューに入れる
ans+=cnt
print ans
|
from collections import deque
from bisect import bisect_right
n, d, a = map(int, input().split())
xh = [tuple(map(int, input().split())) for _ in range(n)]
xh.sort()
x, h = zip(*xh)
h = list(map(lambda x: -(-x//a), h))
s = [0] * (n+1)
ans = 0
for i in range(n):
add = max(0, h[i] - s[i])
j = bisect_right(x, x[i]+d*2)
if j < n: s[j] -= add
s[i] += add
ans += add
s[i+1] += s[i]
print(ans)
| 1 | 82,130,839,552,772 | null | 230 | 230 |
# C - Sum of product of pairs
N = int(input())
A = list(int(a) for a in input().split())
MOD = 10**9 + 7
csA = [0] * (N+1)
for i in range(N):
csA[i+1] = csA[i] + A[i]
ans = 0
for i in range(N-1):
ans += (A[i] * (csA[N] - csA[i+1])) % MOD
print(ans%MOD)
|
import itertools
n,k=map(int,input().split())
d=[]
a=[]
for i in range(k):
p=int(input())
d.append(p)
q=list(map(int,input().split()))
a.append(q)
c=list(itertools.chain.from_iterable(a))
c.sort()
c_set=set(c)
c=list(c_set)
print(n-len(c))
| 0 | null | 14,241,716,523,200 | 83 | 154 |
N,K=map(int,input().split())
m=N//K
print(min(abs(N-m*K),abs(N-(m+1)*K)))
|
import math
h, w, n = [int(input()) for i in range(3)]
ans = 0
if h > w:
print(math.ceil(n / h))
else:
print(math.ceil(n / w))
| 0 | null | 64,244,080,187,690 | 180 | 236 |
h, w, k = map(int, input().split())
s = []
for _ in range(h):
s.append(input())
cnt = 1
rflg = False
rcnt = 1
for r in s:
if r.count('#')>0:
if rflg:
cnt += 1
rcnt = 1
rflg = True
elif rflg:
print(*ans)
continue
else:
rcnt += 1
continue
cflg = False
ans = []
for e in r:
if e=='#':
if cflg:
cnt += 1
cflg = True
ans.append(cnt)
for _ in range(rcnt):
print(*ans)
|
from collections import deque
def BFS():
color=["white" for _ in range(h)]
D=[-1 for _ in range(h)]
M=[[] for _ in range(h)]
for i in range(h-1):
M[i].append(i+1)
M[i+1].append(i)
queue=deque([])
for i in line:
queue.append(i)
D[i]=i
color[i]="gray"
while len(queue)>0:
u=queue.popleft()
for i in M[u]:
if D[i]==-1 and color[i]=="white":
D[i]=D[u]
color[i]="gray"
queue.append(i)
return D
h,w,k=map(int,input().split())
S=[list(input()) for _ in range(h)]
M=[[0 for _ in range(w)] for _ in range(h)]
num,line=0,[]
for i in range(h):
if S[i].count("#")!=0:
p=num
for j in range(w):
if S[i][j]=="#":
num +=1
elif num==p:
M[i][j]=num+1
continue
M[i][j]=num
line.append(i)
D=BFS()
for i in range(h):
M[i]=M[D[i]]
for i in range(h):
print(*M[i])
| 1 | 144,335,939,919,876 | null | 277 | 277 |
N,K=map(int,input().split())
A=[int(x)-1 for x in input().split()]
seen={0}
town=0
while K>0:
town=A[town]
K-=1
if town in seen:
break
seen.add(town)
start=town
i=0
while K>0:
town=A[town]
i+=1
K-=1
if town is start:
break
K=K%i if i>0 else 0
while K>0:
town=A[town]
i+=1
K-=1
print(town+1)
|
n,k = map(int,input().split())
b = [bi-1 for bi in list(map(int,input().split()))]
a = 0
f = [0]*n
c = 1
for i in range(k):
if f[a]:
k %= c-f[a]
for i in range(k):
a = b[a]
print(a+1)
break
f[a] = c
k -= 1
c += 1
a = b[a]
else:
print(a+1)
| 1 | 22,799,674,897,428 | null | 150 | 150 |
import collections
N = int(input())
A = list(map(int , input().split()))
# N = 32
# A = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6, 4, 3, 3, 8, 3, 2, 7, 9, 5]
# N = 6
# A = [2, 3, 3, 1, 3, 1]
i = [k for k in range(1,N+1)]
j = [k for k in range(1,N+1)]
Li = [i[k]+A[k] for k in range(N)]
Rj = [j[k]-A[k] for k in range(N)]
Li = collections.Counter(Li)
counter = 0
for r in Rj:
counter += Li[r]
print(counter)
|
def aizu005():
cnt = 0
while True:
cnt =cnt + 1
x = int(raw_input())
if x == 0 :
break
else :
print "Case " + str(cnt) + ": " + str(x)
aizu005()
| 0 | null | 13,384,793,603,760 | 157 | 42 |
import sys
sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline
def solve():
S = rl().rstrip()
print(S[:3])
if __name__ == '__main__':
solve()
|
import random
name = input()
name_lenght = len(name)
start = random.randint(0, name_lenght - 3)
end = start + 3
print(name[start:end])
| 1 | 14,664,956,935,870 | null | 130 | 130 |
N = int(input())
A = []
xy = []
for i in range(N):
a = int(input())
A.append(a)
xy.append([list(map(int, input().split())) for j in range(a)])
ans = 0
p = [-1]*N
def dfs(i, p):
global ans
if i == N:
ans = max(ans, sum(p))
else:
p_true = p.copy()
if p_true[i] != 0:
p_true[i] = 1
ok = True
for x, y in xy[i]:
if y == p_true[x-1] or p_true[x-1] == -1:
p_true[x-1] = y
else:
ok = False
if ok:
dfs(i+1, p_true)
p_false = p.copy()
if p_false[i] != 1:
p_false[i] = 0
dfs(i+1, p_false)
dfs(0, p)
print(ans)
|
import sys
sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline
def solve():
N = int(rl())
ans = 0
for a in range(1, N):
ans += (N - 1) // a
print(ans)
if __name__ == '__main__':
solve()
| 0 | null | 61,856,569,657,860 | 262 | 73 |
s,t = input().split()
print("".join(map(str,[t,s])))
|
a, b = input().split()
s = b + a
print(s)
| 1 | 103,215,662,286,844 | null | 248 | 248 |
import random
S = input()
x = random.randrange(len(S)-2)
print(S[x] + S[x + 1] + S[x + 2])
|
import sys
input = sys.stdin.readline
S=tuple(input().strip())
N=len(S)+1
sets = []
count = 0
for c in S:
d = 1 if c == '<' else -1
if count * d < 0:
sets.append(count)
count = d
else:
count += d
sets.append(count)
sum = 0
for i in range(len(sets)):
k=sets[i]
if k > 0:
sum += (k*(k+1))//2
else:
sum += (k*(k-1))//2
if i > 0:
sum -= min(sets[i-1], -k)
print(sum)
| 0 | null | 85,286,214,933,700 | 130 | 285 |
a,b = input().split()
a=int(a)
b=int(b)
if a>=1 and a<=9 and b>=1 and b<=9:
print(a*b)
else: print("-1")
|
s = input()
cnt = 0
for i in range(len(s)//2):
if s[i] == s[-i-1]:
continue
else:
cnt += 1
print(cnt)
| 0 | null | 138,762,045,173,168 | 286 | 261 |
house = [[[0 for r in range(10)] for f in range(3)] for b in range(4)]
for i in range(int(input())):
b, f, r, v = map(int, input().split())
house[b-1][f-1][r-1] += v
for b in range(4):
for f in range(3):
house[b][f] = ' ' + ' '.join(map(str, house[b][f]))
house[b] = '\n'.join(map(str, house[b])) + '\n'
border = '#' * 20 + '\n'
house = border.join(map(str, house))
print(house.rstrip())
|
x, n = list(map(int, input().split()))
if n == 0:
inputs = []
else:
inputs = list(map(int, input().split()))
nums = [0] * 201
diff = 1000
n = 100
for i in inputs:
nums[i] = 1
for i in range(0, 201):
d = abs(i - x)
if nums[i] == 1:
continue
if d < diff:
diff = d
n = i
print(n)
| 0 | null | 7,644,044,302,652 | 55 | 128 |
T1, T2 = map(int,input().split())
A1, A2 = map(int,input().split())
B1, B2 = map(int,input().split())
if T1*A1 + T2*A2 == T1*B1 + T2*B2:
print("infinity")
else:
if T1*A1 + T2*A2 > T1*B1 + T2*B2:
A1, B1 = B1, A1
A2, B2 = B2, A2
if T1*A1 < T1*B1:
print("0")
else:
forward = T1*A1 - T1*B1
shrink = (T1*B1 + T2*B2) - (T1*A1 + T2*A2)
#print(str(forward))
#print(str(shrink))
if forward % shrink == 0:
print(str(2*forward//shrink))
else:
print(str((forward//shrink + 1)*2 - 1))
|
import sys
readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)
def main():
t1, t2 = map(int, readline().split())
a1, a2 = map(int, readline().split())
b1, b2 = map(int, readline().split())
if a1 < b1:
a1, b1 = b1, a1
a2, b2 = b2, a2
if a2 > b2:
return print(0)
else:
d1 = t1 * a1 + t2 * a2
d2 = t1 * b1 + t2 * b2
if d1 == d2:
return print("infinity")
elif d2 > d1:
ans = 1
diff = d2 - d1
x = t1 * (a1 - b1)
cnt = x // diff
ans += cnt * 2
if x % diff == 0:
ans -= 1
return print(ans)
else:
return print(0)
if __name__ == '__main__':
main()
| 1 | 131,336,053,231,628 | null | 269 | 269 |
N = int(input())
A = list(map(int,input().split()))
B = []
B_val = 0
ans = 0
for i in A[::-1]:
B.append(B_val)
B_val += i
for i in range(N):
ans += ( A[i] * B[-i-1] ) % (1000000000 + 7 )
print(ans % (1000000000 + 7 ) )
|
from sys import stdin
from itertools import accumulate
input = stdin.readline
n = int(input())
a = list(map(int,input().split()))
p = [0] + list(accumulate(a))
res = 0
for i in range(n-1,-1,-1):
res += (a[i] * p[i])%(10**9 + 7)
print(res % (10**9 + 7))
| 1 | 3,820,551,992,110 | null | 83 | 83 |
X = int(input())
money = 100
for i in range(1, 10000):
money = money * 101 // 100
if money >= X:
print(i)
exit()
|
x = int(input())
deposit = 100
year = 0
rate = 101
while(deposit < x):
deposit = deposit * rate // 100
year += 1
print(year)
| 1 | 27,057,993,102,560 | null | 159 | 159 |
import math
N = int(input())
M = []
sqr_N = math.floor(math.sqrt(N))
a = 0
for i in range(1, (sqr_N + 1)):
if N % i == 0:
a = i
a_pair = N // a
print(a + a_pair - 2)
|
#import time
count=0
def merge(A,left,mid,right):
global count
L=A[left:mid]+[2**30]
R=A[mid:right]+[2**30]
i=0
j=0
for k in range(left,right):
count+=1
if L[i]<=R[j]:
A[k]=L[i]
i+=1
else:
A[k]=R[j]
j+=1
def mergeSort(A,left,right):
if left+1 < right:
mid = int((left+right)/2)
mergeSort(A,left,mid)
mergeSort(A,mid,right)
merge(A,left,mid,right)
#start = time.time()
n=int(input())
s=list(map(int,input().split()))
count=0
mergeSort(s,0,n)
print(s[0],end='',sep='')
for i in range(1,n):
print(" ",s[i],end='',sep='')
print()
print(count)
#end=time.time()-start
#end*=1000
#print ("Time:{0}".format(end) + "[m_sec]")
| 0 | null | 81,074,776,301,050 | 288 | 26 |
n = int(input())
c=0
for i in range(1,(n//2)+1):
if((n-i) != i):
c+=1
print(c)
|
N = int(input())
if N % 2 == 0:
ans = int(N / 2) - 1
else:
ans = int(N / 2)
print(ans)
| 1 | 152,995,721,566,322 | null | 283 | 283 |
N = int(input())
def S(x):
return(x*(x+1)//2)
print(S(N) - 3*S(N//3) - 5*S(N//5) + 15*S(N//15))
|
N = int(input())
total = 0
for num in range(1, N+1):
if num % 15 == 0:
continue
if num % 3 == 0 or num % 5 == 0:
continue
total += num
print(total)
| 1 | 35,002,485,628,222 | null | 173 | 173 |
def warshall_floyd(v_count: int, matrix: list) -> list:
""" ワーシャルフロイド
v_count: 頂点数
matrix: 隣接行列(到達不能はfloat("inf"))
"""
for i in range(v_count):
for j, c2 in enumerate(row[i] for row in matrix):
for k, (c1, c3) in enumerate(zip(matrix[j], matrix[i])):
if c1 > c2+c3:
matrix[j][k] = c2+c3
return matrix
INF = 10 ** 16
n, m, l = map(int, input().split())
mat = [[INF] * n for _ in range(n)]
for i in range(n):
mat[i][i] = 0
for _ in range(m):
a, b, c = map(int, input().split())
mat[a - 1][b - 1] = c
mat[b - 1][a - 1] = c
mat = warshall_floyd(n, mat)
fuel_mat = [[INF] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if i == j:
fuel_mat[i][j] = 0
elif mat[i][j] <= l:
fuel_mat[i][j] = 1
fuel_mat = warshall_floyd(n, fuel_mat)
q = int(input())
for _ in range(q):
s, t = map(int, input().split())
d = fuel_mat[s - 1][t - 1]
if d == INF:
print(-1)
else:
print(d - 1)
|
import numpy as np
from scipy.sparse.csgraph import floyd_warshall
def main():
N, M, L = map(int, input().split())
graph = [[0] * N for _ in range(N)]
for _ in range(M):
s, t, w = map(int, input().split())
if w <= L:
graph[s-1][t-1] = graph[t-1][s-1] = w
graph = floyd_warshall(graph, directed=False)
graph = floyd_warshall(graph <= L, directed=False)
graph[np.isinf(graph)] = 0
Q = int(input())
ans = []
for _ in range(Q):
s, t = map(int, input().split())
ans.append(int(graph[s-1][t-1]) - 1)
print(*ans, sep='\n')
if __name__ == '__main__':
main()
| 1 | 173,582,458,749,700 | null | 295 | 295 |
N,M = [int(i) for i in input().split()]
if N%2 == 1:
for i in range(1,M+1):
print(i, end=" ")
print(N+1-i)
exit()
L = min(M,N//4)
for i in range(1,L+1):
print(i,end=" ")
print(N+1-i)
if L < M:
for i in range(L+1,M+1):
print(i,end=" ")
print(N-i)
|
n, m = map(int, input().split())
def check_ans(list_pairs):
dict_people = {i: i for i in range(1, n+1)}
for i in range(n):
for k in range(m):
val1 = dict_people[list_pairs[k][0]]
val2 = dict_people[list_pairs[k][1]]
if val1>val2:
print(val2, val1, end=" / ")
else:
print(val1, val2, end=" / ")
print("")
for j in range(1, n+1):
dict_people[j] = (dict_people[j]+1)%n
if dict_people[j] == 0: dict_people[j] = n
ans = list()
if n%2 == 1:
for i in range(m):
node1 = (1-i)%n
if node1 == 0: node1 = n
node2 = 2+i
ans.append((node1, node2))
else:
distance = -1
node2 = 1
for i in range(m):
node1 = (1-i)%n
if node1 == 0: node1 = n
node2 = node2+1
distance += 2
if distance == n//2 or distance == n//2 + 1:
node2 += 1
ans.append((node1, node2))
[print(str(values[0])+" "+str(values[1])) for values in ans]
# check_ans(ans)
| 1 | 28,551,159,665,378 | null | 162 | 162 |
#!/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(C: str):
return chr(ord(C)+1)
def main():
sys.setrecursionlimit(10 ** 6)
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
C = next(tokens) # type: str
print(f'{solve(C)}')
if __name__ == '__main__':
main()
|
N = int(input())
A = list(map(int,input().split()))
chk = []
for i in range(N-1):
if A[i+1] > A[i]:
chk.append(1)
else:
chk.append(0)
ans = 1000
for i in range(N-1):
if chk[i] == 1:
ans += (A[i+1] - A[i]) * (ans//A[i])
print(ans)
| 0 | null | 49,970,536,115,360 | 239 | 103 |
d=input().split()
for o in list(input()):
s={'N':(0,1,5,4),'W':(0,2,5,3),'E':(0,3,5,2),'S':(0,4,5,1)}[o]
for i in range(3):d[s[i+1]],d[s[i]]=d[s[i]],d[s[i+1]]
print(d[0])
|
class Dice(object):
def __init__(self,List):
self.face=List
def n_spin(self,List):
temp=List[0]
List[0]=List[1]
List[1]=List[5]
List[5]=List[4]
List[4]=temp
def s_spin(self,List):
temp=List[0]
List[0]=List[4]
List[4]=List[5]
List[5]=List[1]
List[1]=temp
def e_spin(self,List):
temp=List[0]
List[0]=List[3]
List[3]=List[5]
List[5]=List[2]
List[2]=temp
def w_spin(self,List):
temp=List[0]
List[0]=List[2]
List[2]=List[5]
List[5]=List[3]
List[3]=temp
dice = Dice(map(int,raw_input().split()))
command = list(raw_input())
for k in command:
if k=='N':
dice.n_spin(dice.face)
elif k=='S':
dice.s_spin(dice.face)
elif k=='E':
dice.e_spin(dice.face)
else:
dice.w_spin(dice.face)
print dice.face[0]
| 1 | 227,197,111,582 | null | 33 | 33 |
n=int(input())
a=list(map(int,input().split()))
mod=10**9+7
x=sum(a)%mod
y=0
for i in range(n):
y+=a[i]**2
y%=mod
z=pow(2,mod-2,mod)
print(((x**2-y)*z)%mod)
|
mod = 10**9 + 7
def C():
N = int(input())
ans = 10**N - 2*9**N + 8**N
print(ans%mod)
def A():
N = int(input())
if( N == 0):
print(1)
else:
print(0)
A()
| 0 | null | 3,368,590,749,060 | 83 | 76 |
N = int(input())
A = list(map(int, input().split())) # <- note that this has (N - 1) elements
#print(A)
A_0 = [x - 1 for x in A]
#print(A_0)
ans = [0] * N # <- represents number of immediate subordinates of each person
for i in range(0, N - 1):
ans[A_0[i]] += 1
for i in range(0, N):
print(ans[i])
|
N = int(input())
A = tuple(map(int, input().split()))
x = [0] * N
for i in range(N - 1):
x[A[i]-1] += 1
for a in x:
print(a)
| 1 | 32,565,613,898,948 | null | 169 | 169 |
C=str(input())
a=ord(C)
print(chr(a+1))
|
def main():
x, n = map(int, input().split())
ps = list(map(int, input().split()))
for i in range(n//2 + 2):
if x - i not in ps:
print(x-i)
return
if x + i not in ps:
print(x+i)
return
if __name__ == '__main__':
main()
| 0 | null | 53,420,290,581,310 | 239 | 128 |
n = int(input())
data = []
[data.append(int(input())) for i in range(n)]
ans = data[1] - data[0]
x = data[0]
for d in data[1:]:
ans = max(ans,d-x)
x = min(d,x)
print(ans)
|
import sys
def get_maximum_profit():
element_number = int(input())
v0 = int(input())
v1 = int(input())
min_v = min(v0, v1)
max_profit = v1-v0
for v in map(int, sys.stdin.readlines()):
max_profit = max(max_profit, v-min_v)
min_v = min(min_v, v)
print(max_profit)
if __name__ == '__main__':
get_maximum_profit()
| 1 | 12,830,105,850 | null | 13 | 13 |
from itertools import accumulate
N,K = map(int,input().split())
acc = list(accumulate(range(N+1), lambda x,y:x+y))
ans = 0
mod = 10**9+7
for i in range(K, N+1):
r = acc[N] - acc[N-i]
l = acc[i-1]
ans = (ans+r-l+1) % mod
ans += 1
print(ans % mod)
|
import math
A, B = map(str,input().split(" "))
B_ = int(B.split(".")[0])*100 + int(B.split(".")[1])
print(int(A) * B_ // 100)
| 0 | null | 24,638,688,985,270 | 170 | 135 |
if __name__ == "__main__":
while True:
nums = map( int, raw_input().split())
H = nums[0]
W = nums[1]
if H == 0:
if W == 0:
break
s = ""
j = 0
while j < W:
s += "#"
j += 1
i = 0
while i < H:
print s
i += 1
print
|
(H,N) = map(int,input().split())
l = []
for i in range(N):
l.append([int(x) for x in input().split()])
dp = [10**10 for i in range(H+10**4+1)]
dp[0] = 0
for i in range(H+10**4+1):
for j in range(N):
if l[j][0] <= i:
dp[i] = min(dp[i],dp[i-l[j][0]]+l[j][1])
ans = dp[H]
for i in range(1,10**4+1):
ans = min(ans,dp[H+i])
print(ans)
| 0 | null | 40,909,771,760,888 | 49 | 229 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
MOD = 998244353
n, k = map(int, input().split())
s = list()
for i in range(k):
s.append(tuple(map(int, input().split())))
dp = [0] + [0] * n
diff = [0] + [0] * n
dp[1] = 1
for i in range(1, n):
for j, k in s:
if i + j > n:
continue
diff[i + j] += dp[i]
if i + k + 1 > n:
continue
diff[i + k + 1] -= dp[i]
dp[i] = (dp[i - 1] + diff[i]) % MOD
dp[i + 1] = (dp[i] + diff[i + 1]) % MOD
print(dp[n])
|
mod = 998244353
# 貰うDP
def main(N, S):
dp = [0 if n != 0 else 1 for n in range(N)] # dp[i]はマスiに行く通り数. (答えはdp[-1]), dp[0] = 1 (最初にいる場所だから1通り)
A = [0 if n != 0 else 1 for n in range(N)] # dp[i] = A[i] - A[i-1] (i >= 1), A[0] = dp[0] = 1 (i = 0) が成り立つような配列を考える.
for i in range(1, N): # 今いる点 (注目点)
for l, r in S: # 選択行動範囲 (l: 始点, r: 終点)
if i - l < 0: # 注目点が選択行動範囲の始点より手前の場合 → 注目点に来るために使用することはできない.
break
else: # 注目点に来るために使用することができる場合
dp[i] += A[i-l] - A[max(i-r, 0)-1] # lからrの間で,注目点に行くために使用できる点を逆算. そこに行くことができる = 選択行動範囲の値を選択することで注目点に達することができる通り数.
dp[i] %= mod
A[i] = (A[i-1] + dp[i]) % mod
print(dp[-1])
if __name__ == '__main__':
N, K = list(map(int, input().split()))
S = {tuple(map(int, input().split())) for k in range(K)}
S = sorted(list(S), key = lambda x:x[0]) # 始点でsort (範囲の重複がないため)
main(N, S)
| 1 | 2,703,349,896,156 | null | 74 | 74 |
# -*- coding: utf-8 -*-
import sys
import fractions
import copy
import bisect
import math
import numpy as np
import itertools
from itertools import combinations_with_replacement
#import math#数学的計算はこれでいける。普通に0.5乗しても計算可能
#w=input()
from operator import itemgetter
from sys import stdin
#input = sys.stdin.readline#こっちの方が入力が早いが使える時に使っていこう
from operator import mul
from functools import reduce
from collections import Counter
#from collections import deque
#input = stdin.readline
j=0
k=0
n=3
r=1
a=[0]
#n=int(input())
#r=int(input())
#print(M)
#A=int(input())
#B=int(input())
#print(N)
"1行1つの整数を入力を取得し、整数と取得する"
#number_list=list(map(int, input().split(" ")))#数字の時
#print(number_list)
"12 21 332 とか入力する時に使う"
"1行に複数の整数の入力を取得し、整数として扱う"
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#メモ
for i in number_list:#こっちの方がrage使うより早いらしい
print(number_list[i-1])#
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''
x=[]
y=[]
for i in range(N):
x1, y1=[int(i) for i in input().split()]
x.append(x1)
y.append(y1)
print(x)
print(y)
"複数行に2数値を入力する形式 x座標とy座標を入力するイメージ"
'''
'''
mixlist=[]
for i in range(N):
a,b=input().split()
mixlist.append((int(a),b))
print(mixlist)
"複数行にintとstrを複合して入力するやつ,今回はリスト一つで処理している"
'''
'''
#array=[input().split()for i in range(N)]
#print(type(array[0][0]))
#print(array)
"正方行列にstr型の値を入力"
'''
#brray=[list(map(int, input().split(" ")))for i in range(N)]
#print(type(brray[0][0]))
#print(brray)
'''
入力
1 2
4 5
7 8
出力結果
[[1, 2], [4, 5], [7, 8]]
'''
"列数に関して自由度の高いint型の値を入力するタイプの行列"
#以下に別解を記載
#N, M = [int(i) for i in input().split()]
'''
table = [[int(i) for i in input().split()] for m in range(m)]
print(type(N))
print(N)
print(type(M))
print(M)
print(type(table))
print(table)
'''
#s=input()
#a=[int(i) for i in s]
#print(a[0])
#print([a])
#単数値.桁ごとに分割したい.入力と出力は以下の通り
#イメージとして1桁ごとにリストに値を入れているかんじ
#intを取ると文字列分解に使える
'''
入力
1234
出力
1
[[1, 2, 3, 4]]
'''
'''
word_list= input().split(" ")
print(word_list[0])
"連続文字列の入力"
"qw er ty とかの入力に使う"
"入力すると空白で区切ったところでlistの番号が与えられる"
'''
'''
A, B, C=stdin.readline().rstrip().split()#str style 何個でもいけることが多い
print(A)
"リストではなく独立したstr型を入れるなら以下のやり方でOK"
'''
#a= stdin.readline().rstrip()
#print(a.upper())
"aという変数に入っているものを大文字にして出力"
#a,b=map(int, input().split()) #int style 複数数値入力 「A B」みたいなスペース空いた入力のとき
#なんかうまく入力されるけど
#a=[[int(i) for i in 1.strip()]for 1 in sys.stdin]
#a = [[int(c) for c in l.strip()] for l in sys.stdin]]
#print(a)
#複数行の数値を入力して正方行列を作成
##############################################################################################
##############################################################################################
#under this line explains example calculation
'''
コンビネーションの組み合わせの中身を出力する形式
for i in itertools.combinations(brray, 2)
combinationsをpermutationsにすれば順列になる
今回なら(abc133B)
入力
1 2
5 5
-2 8
出力
[[1, 2], [5, 5], [-2, 8]]
もちろん一次元リストでも使えるし
何よりiもリストのように使えるので便利
'''
#nCr combination
'''
def cmb(n,r):
#When n < r , this function isn't valid
r= min(n-r,r)
#print(n,r)
if r == 0: return 1
over = reduce(mul, range(n, n-r, -1))
#flochart mul(n,n-1)=x
#next mul(x,n-2)........(n-r+1,n-r)
#mul read a,b and returns a*b
under = reduce(mul, range(1, r+1))
#print(over, under)
#reduce is applied mul(1,2)=2
#next mul(2,3)=6
#next mul(6,4)=4.........last(r!,r+1)=r+1!
return over // under
#// is integer divide
#calc example 5C2
#over=5*4*3
#under=3*2*1
a = cmb(n, r)
#print(a)
'''
'''
import itertools
from itertools import combinations_with_replacement
combinationについて
以下の違いを意識しよう
combinations() p, r 長さrのタプル列、ソートされた順で重複なし
combinations_with_replacement() p, r 長さrのタプル列、ソートされた順で重複あり
使用例 出力
combinations('ABCD', 2) AB AC AD BC BD CD
combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD DD
'''
'''
#集計
#example
#a=[2,2,2,3,4,3,1,2,1,3,1,2,1,2,2,1,2,1]
#a=Counter(a)
for i in a.most_common(n):print(i)
#most_common()メソッドは、出現回数が多い要素順にCounterオブジェクトを並び替えます。
#引数にint型の数字nを設定した場合は、出現回数が高い上位n個の要素を返します。
#何も設定しなければ、コンテナ型にあるすべての要素を出現回数の順番に並び替えたタプル型オブジェクトを返します。
#out put
#(2, 8)
#(1, 6)
#(3, 3)
#(4, 1)
'''
#二部探索(binary search)
#A = [1, 2, 3, 3, 3, 4, 4, 6, 6, 6, 6]
#print(A)
#index = bisect.bisect_left(A, 5) # 7 最も左(前)の挿入箇所が返ってきている
#A.insert(index, 5)
#print(index)
#print(A)
'''
bisect.bisect_left(a, x, lo=0, h=len(a))
引数
a: ソート済みリスト
x: 挿入したい値
lo: 探索範囲の下限
hi: 探索範囲の上限
(lo, hiはスライスと同様の指定方法)
bisect_leftはソートされたリストaに対して順序を保ったままxを挿入できる箇所を探索します。leftが示す通り、aにすでにxが存在している場合は、挿入箇所は既存のxよりも左側になります。また、lo, hiを指定することで探索範囲を絞り込むことも可能です。デフォルトはaの全体が探索対象です。
'''
'''
素数の判定
'''
def is_prime(n):
if n == 1: return False
for k in range(2, int(np.sqrt(n)) + 1):
#sqrt(n)+1以上は考えて約数はないので却下
if n % k == 0:
return False
#割り切れたらFalse
return True
'''
npのmaxとmaximumの違い
xs = np.array([1, -2, 3])
np.max(xs, 0)
この出力は3となります.[1, -2, 3]と0の4つの数字のうち,最も大きい値を出力します.
一方で,[max(1, 0), max(-2, 0), max(3, 0)]を出力したい時があります.
その時は,numpyのmaximum関数を用います.
xs = np.array([1, -2, 3])
np.maximum(xs, 0) # [1, 0, 3]
'''
########################################################################
########################################################################
#b2=a[:] #1次元のときはコピーはこれで良い
#print(b2)
#a= [[0]*3 for i in range(5)] #2次元配列はこう準備、[[0]*3]*5だとだめ
#b3=copy.deepcopy(a) #2次元配列はこうコピーする
#print(b3)
def main():
w=1
j=0
k=0
dlen=0
dsum=0
ota=0
n=int(input())
al=list(map(int, input().split(" ")))
dlen=sum(al)
for i in range(n):
dsum=dsum+al[i]
if dsum*2 > dlen:
ota=dsum-al[i]
break
#if dlen//2==0:#2で割り切れる時
# print(abs(dsum-dlen/2))
# sys.exit()
#print(2*dsum,2*ota,dlen)
print(min(abs(2*dsum-dlen),abs(2*ota-dlen)))
#r=int(input())
#dp= [[0]*3 for i in range(5)]#列 行
#dp用の0の入ったやつ
#dp= [[0]*(w+1) for i in range(n+1)]#0からwまでのw+1回計算するから
#print(dp)#初期条件が入る分計算回数+1列分必要(この場合は判断すべきものの数)
DP = np.zeros(w+1, dtype=int)#これでも一次元リストが作れる
exdp=np.zeros((3,4)) # 3×4の2次元配列を生成。2次元ならこう
#dtypeは指定しないとfloatになる
#for i in range(n):#ちょっとした入力に便利
# a, b = map(int, input().split())
#dp[i][0] += [a]
#これだとintとlistをつなぐことになって不適
# dp[i] += [a]
# dp[i] += [b]
#これはうまくいく
#やり方はいろいろあるということ
#print(dp)
"1行1つの整数を入力を取得し、整数と取得する"
#number_list=list(map(int, input().split(" ")))#数字の時
#print(number_list)
"12 21 332 とか入力する時に使う"
"1行に複数の整数の入力を取得し、整数として扱う"
#brray=[list(map(int, input().split(" ")))for i in range(N)
#print(brray)
#s=input()
#a=[int(i) for i in s]#int取るとstrでも行ける
#print(a)
'''
入力
1234
出力
[1, 2, 3, 4]
'''
pin_l=["x" for i in range(10)]#内包表記に慣れろ
#print(pin_l)
ls = ["a", "b", "c", "d", "e"]
#print(ls[2:5])
#スライスでの取得
#print(ls[:-3])
#一番左端から右から3番目より左まで取得
#print(ls[:4:2])
#スライスで1個飛ばしで取得
#ないときは左端スタート
#始点のインデックス番号 : 終点のインデックス番号 : スキップする数+1
#print(ls[::2])
'''
lsというリストの場合に、1つ飛びの値を取得したい場合には
ls[::2]
のようにします。こうすると、
["a", "c", "d"]と出力される
'''
if __name__ == "__main__":
main()
|
n=int(input())
box1=[]
box2=[]
for i in range(n):
i=input().rstrip().split(" ")
box1.append(i[0])
box2.append(int(i[1]))
num=box1.index(input())
del box2[:num+1]
print(sum(box2))
| 0 | null | 119,369,209,293,580 | 276 | 243 |
str = list(input())
for _ in range(int(input())):
cmd = input().split()
a, b = map(int, cmd[1:3])
if cmd[0] == 'print':
for i in range(a, b + 1):
print(str[i], end='')
print('')
if cmd[0] == 'reverse':
str = str[:a] + list(reversed(str[a:b + 1])) + str[b + 1:]
if cmd[0] == 'replace':
p = cmd[3]
str = str[:a] + list(p) + str[b + 1:]
|
s = input()
n = int(input())
for i in range(n):
c = input().split()
a = int(c[1])
b = int(c[2])
if "replace" in c:
s = s[:a] + c[3] + s[b+1:]
if "reverse" in c:
u = s[a:b+1]
s = s[:a] + u[:: -1] +s[b + 1:]
if "print" in c:
print(s[a:b+1], sep = '')
| 1 | 2,087,297,906,148 | null | 68 | 68 |
inp = input()
a = inp.split()
b = int(a[0])+int(a[1])
c = b*2
d = int(a[0])*int(a[1])
print(d,c)
|
a = input().split()
c = int(a[0]) * int(a[1])
d = (int(a[0])*2) + (int(a[1])*2)
print('%d %d' %(c,d))
| 1 | 304,586,224,420 | null | 36 | 36 |
class diceClass:
def __init__(self, valuelist):
self.valuelist = valuelist
self.t = valuelist[0]
self.b = valuelist[5]
self.n = valuelist[4]
self.s = valuelist[1]
self.e = valuelist[2]
self.w = valuelist[3]
def throw(self, direction):
# N,S,W,E
if direction == 'N':
self.t, self.s, self.b, self.n = self.s, self.b, self.n, self.t
elif direction == 'S':
self.t, self.s, self.b, self.n = self.n, self.t, self.s, self.b
elif direction == 'W':
self.t, self.e, self.b, self.w = self.e, self.b, self.w, self.t
elif direction == 'E':
self.t, self.e, self.b, self.w = self.w, self.t, self.e, self.b
arrinput = list(map(int, input().split()))
dirinput = input()
dice = diceClass(arrinput)
for s in dirinput:
dice.throw(s)
print(dice.t)
|
A = []
P = ['o']*9
for i in range(3):
a = [int(i) for i in input().split()]
for j in range(3):
A.append(a[j])
N = int(input())
for i in range(N):
b = int(input())
for j in range(9):
if A[j] == b:
P[j] = 'x'
t = 0
for i in range(3):
if (P[i] == P[i+3] == P[i+6] == 'x') or (P[3*i] == P[3*i+1] == P[3*i+2] == 'x'):
t += 1
break
if (P[0] == P[4] == P[8] == 'x') or (P[2] == P[4] == P[6] == 'x'):
t += 1
if t == 0:
print('No')
else:
print('Yes')
| 0 | null | 29,883,359,029,600 | 33 | 207 |
N=int(input())
ans=""
check="abcdefghijklmnopqrstuvwxyz"
while N!=0:
N-=1
ans+=check[N%26]
N=N//26
print(ans[::-1])
"""
while N>0:
N-=1
ans+=chr(ord("a")+ N%26)
N//=26
print(ans[::-1])
"""
|
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 7 02:42:25 2020
@author: liang
"""
"""
n進数問題
【原則】 大きな数の計算をしない
⇒ 1の桁から計算する
171-C いびつなn進数
27 -> a(26)a(1)となる
⇒先にa(1)だけもらってN%26とすることで解決
ASCII化 ord()
文字化 chr()
"""
N = int(input())
res = str()
while N > 0:
N -= 1 #"a"として予め設置
res += chr(ord("a") + N%26)
N //= 26
print(res[::-1])
| 1 | 11,881,521,785,670 | null | 121 | 121 |
A = input()
while(A != '-'):
m = int(input())
for i in range(m):
h = int(input())
A = A[h:]+A[:h]
print(A)
A = input()
|
while True:
chk_list = input()
if chk_list == "-":
break
num = int(input())
for i in range(num):
n = int(input())
chk_list = chk_list[n:] + chk_list[0:n]
print(chk_list)
| 1 | 1,936,203,389,580 | null | 66 | 66 |
n = int(input())
a = list(map(int, input().split()))
p = 1000
k = 0
for i in range(n-1):
if k>0 and a[i]>a[i+1]:
p += k*a[i]
k = 0
elif k==0 and a[i]<a[i+1]:
k = p//a[i]
p %= a[i]
if k>0:
p += k*a[-1]
print(p)
|
N = int(input())
A = list(map(int, input().split()))
iStock = 0
iMoney = 1000
for i in range(N-1):
if A[i] < A[i + 1]:
# A[i]Day 株購入 & A[i+1]Day 株売却
iStock = iMoney // A[i]
iMoney %= A[i]
iMoney += iStock * A[i+1]
print(iMoney)
| 1 | 7,325,425,682,672 | null | 103 | 103 |
n=list(input())
n=n[::-1]
k=int(n[0])
if k==3:
print("bon")
elif k==2 or k==4 or k==5 or k==7 or k==9:
print("hon")
else:
print("pon")
|
N = int(input())
n = N % 10
if n in [2,4,5,7,9]:
print('hon')#.format(N))
elif n in [0,1,6,8]:
print('pon')#.format(N))
else:
print('bon')#.format(N))
| 1 | 19,274,340,447,900 | null | 142 | 142 |
def main():
mod = pow(10, 9)+7
k = int(input())
s = input()
n = len(s)
ans = 0
key = pow(26, k, mod)
sub = 1
c = 1
for i in range(k+1):
ans += key*sub*c
ans %= mod
sub *= 25
sub %= mod
key = key*pow(26, mod-2, mod)%mod
c *= (n+i)
c *= pow(i+1, mod-2, mod)
c %= mod
print(ans)
if __name__ == "__main__":
main()
|
N = int(input())
X = input()
pc = X.count("1")
if pc == 1:
if X[-1] == "0":
for i, s in enumerate(X):
if i == N - 1:
print(2)
elif s == "0":
print(1)
else:
print(0)
else:
ans = [2] * (N - 1) + [0]
print(*ans, sep="\n")
exit()
m01 = 0
m10 = 0
for i, s in enumerate(X[::-1]):
if s == "1":
m01 += pow(2, i, pc + 1)
m01 %= pc + 1
m10 += pow(2, i, pc - 1)
m10 %= pc - 1
memo = [-1] * 200005
def pop_count(T):
T = (T & 0x55555555) + ((T >> 1) & 0x55555555)
T = (T & 0x33333333) + ((T >> 2) & 0x33333333)
T = (T & 0x0F0F0F0F) + ((T >> 4) & 0x0F0F0F0F)
T = (T & 0x00FF00FF) + ((T >> 8) & 0x00FF00FF)
T = (T & 0x0000FFFF) + ((T >> 16) & 0x0000FFFF)
return T
def F(n):
if memo[n] != -1:
return memo[n]
if n == 0:
return 0
memo[n] = F(n % pop_count(n)) + 1
return memo[n]
ans = [0] * N
for i, s in enumerate(X[::-1]):
if s == "0":
m = m01
m += pow(2, i, pc+1)
m %= pc + 1
else:
m = m10
m -= pow(2, i, pc-1)
m %= pc - 1
ans[i] = F(m) + 1
print(*ans[::-1], sep="\n")
| 0 | null | 10,521,105,296,780 | 124 | 107 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
N = int(input())
adj = [ [] for _ in range(N) ]
for i in range(N-1):
a,b = map(int,input().split())
a -= 1
b -= 1
adj[a].append((b,i))
res = [None] * (N-1)
def dfs(n, c=-1, p=-1):
if c==-1 or c>1:
nc = 1
else:
nc = c+1
for nei,i in adj[n]:
if nei == p: continue
res[i] = nc
dfs(nei, nc, n)
nc += 1
if nc==c: nc += 1
dfs(0)
print(max(res))
for r in res: print(r)
|
import sys
import numpy as np
from collections import deque
input = lambda: sys.stdin.readline().rstrip()
def solve():
N = int(input())
edge = [[] for _ in range(N)]
ab = [tuple() for _ in range(N - 1)]
for i in range(N - 1):
a, b = map(int, input().split())
a, b = a - 1, b - 1
edge[a].append(b)
edge[b].append(a)
ab[i] = (a, b)
# print(ab)
# print(edge)
max_v = 0
max_v_dim = 0
for i, e in enumerate(edge):
if max_v_dim < len(e):
max_v_dim = len(e)
max_v = i
# print(max_v)
# print(max_v_dim)
# bfs
q = deque()
q.append(max_v)
ec = np.full(N, -1, dtype='i8')
ec[max_v] = max_v_dim + 10
vc = dict()
# vc = np.full((N, N), -1, dtype='i8')
while q:
nv = q.popleft()
nc = ec[nv]
tc = 1
for v in edge[nv]:
v1, v2 = min(nv, v), max(nv, v)
if not ((v1, v2) in vc):
if nc == tc:
tc += 1
ec[v] = tc
vc[(v1, v2)] = tc
tc += 1
q.append(v)
print(max_v_dim)
for v1, v2 in ab:
print(vc[(v1, v2)])
if __name__ == '__main__':
solve()
| 1 | 135,659,916,795,920 | null | 272 | 272 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.