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
|
---|---|---|---|---|---|---|
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
def main():
n,m,k = map(int,ipt().split())
fl = [[] for i in range(n)]
bl = [set() for i in range(n)]
for i in range(m):
a,b = map(int,ipt().split())
fl[a-1].append(b-1)
fl[b-1].append(a-1)
for i in range(k):
c,d = map(int,ipt().split())
bl[c-1].add(d-1)
bl[d-1].add(c-1)
ans = [-1]*n
al = [True]*n
for i in range(n):
if al[i]:
q = [i]
al[i] = False
st = set([i])
while q:
qi = q.pop()
for j in fl[qi]:
if al[j]:
st.add(j)
al[j] = False
q.append(j)
lst = len(st)
for j in st:
tmp = lst-len(fl[j])-1
for k in bl[j]:
if k in st:
tmp -= 1
ans[j] = tmp
print(" ".join(map(str,ans)))
return None
if __name__ == '__main__':
main()
|
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=" ")
| 1 | 61,909,494,018,008 | null | 209 | 209 |
#encoding=utf-8
import sys
num = []
ans = []
def prime(q):
q = abs(q)
if q == 2: return True
if q < 2 or q&1 == 0: return False
return pow(2, q-1, q) == 1
for i in sys.stdin:
inp = map(int , i.split())
if prime(inp[0]):
num.append(inp)
num.sort()
for i in xrange(1, len(num)):
if num[i - 1] != num[i]:
ans.append(num[i][0])
print len(ans) + 1
|
def maybe_prime(d,s,n):
for a in (2,3,5,7):
p = False
x = pow(a,d,n)
if x==1 or x==n-1:
continue
for i in range(1,s):
x = x*x%n
if x==1: return False
elif x == n-1:
p = True
break
if not p: return False
return True
def is_prime(n):
if n in (2,3,5,7): return True
elif n%2==0: return False
else:
d,s = n-1, 0
while not d%2:
d,s = d>>1,s+1
return maybe_prime(d,s,n)
cnt = 0
n = int(input())
for i in range(n):
n = int(input())
if is_prime(n): cnt+=1
print(cnt)
| 1 | 9,559,739,640 | null | 12 | 12 |
m,d=map(int,input().split())
n,e=map(int,input().split())
print(1 if m!=n else 0)
|
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
# d = m - k[i] - k[j]
# if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも!!
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
def readInts():
return list(map(int,input().split()))
def I():
return int(input())
m1,d1 = readInts()
m2,d2 = readInts()
print('1' if m1 != m2 else '0')
| 1 | 124,452,511,025,220 | null | 264 | 264 |
def solve():
string = list(input())
ans = 0
if string[-1]=="s":
ans = "".join(string)+"es"
print(ans)
return
else:
print("".join(string)+"s")
return
solve()
|
x = input()
if x[-1] in 'sS':
x += 'es'
else:
x += 's'
print(x)
| 1 | 2,422,041,798,660 | null | 71 | 71 |
#!/usr/bin/env python3
def main():
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
command = [''] * N
ans = 0
for i, t in enumerate(T):
if t == 'r':
point = P
command_candidate = 'p'
elif t == 's':
point = R
command_candidate = 'r'
else:
point = S
command_candidate = 's'
if i >= K and command[i - K] == command_candidate:
point = 0
command_candidate = ''
ans += point
command[i] = command_candidate
print(ans)
if __name__ == '__main__':
main()
|
# abc149_d.py
def janken(idx,mine):
if i >= K:
if flg[i-K] and T[i-K]==T[i]:
return 0
flg[i] = True
if mine=="r":
return R
if mine=="p":
return P
if mine=="s":
return S
N, K = map(int,input().split())
R,S,P = map(int,input().split())
T = input()
flg = [False]*N
ans = 0
for i,v in enumerate(T):
if v=="s":
ans += janken(i,"r")
elif v=="r":
ans += janken(i,"p")
elif v=="p":
ans += janken(i,"s")
print(ans)
| 1 | 106,327,476,479,212 | null | 251 | 251 |
a=input()
b=input()
c=a*2
if b in c:
print("Yes")
else:
print("No")
|
import sys
s = list(input())
p = list(input())
for i in range(len(s)):
counter = 0
for j in range(len(p)):
m = (i+j)%len(s)
if s[m] == p[j]:
counter += 1
if counter == len(p):
print('Yes')
sys.exit()
print('No')
| 1 | 1,737,158,302,180 | null | 64 | 64 |
time = int(input())
h = time // 3600
m = (time - h * 3600) // 60
s = time - h * 3600 - m * 60
print("{0}:{1}:{2}".format(h, m, s))
|
S = int(input())
h = str(S // 3600)
m = str((S % 3600) // 60)
s = str(((S % 3600) % 60))
print(h + ":" + m + ":" + s)
| 1 | 330,670,752,828 | null | 37 | 37 |
n,m = list(map(int, input().split()))
parent = list(range(n))
def root(x):
if parent[x] == x: return x
rt = root(parent[x])
parent[x] = rt
return rt
def unite(x,y):
x = root(x)
y = root(y)
if x == y: return
parent[y] = x
for _ in range(m):
a,b = list(map(lambda x: int(x)-1, input().split()))
unite(a,b)
for i in range(n):
root(i)
cnt = len(set(parent)) - 1
print(cnt)
|
import sys
l = sys.stdin.readlines()
minv = int(l[1])
maxv = -1000000000
for r in map(int,l[2:]):
m = r-minv
if maxv < m:
maxv = m
if m < 0: minv = r
elif m < 0: minv = r
print(maxv)
| 0 | null | 1,170,603,299,360 | 70 | 13 |
i = int(input())
print(i*(1+i*(1+i)))
|
#!/usr/bin/env python3
import sys, math
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
sys.setrecursionlimit(10**8)
inf = float('inf')
ans=count=0
n,m=map(int,input().split())
A=list(map(int,input().split()))
dp=[inf]*(n+1)
dp[0]=0
for a in A:
for i in range(a,n+1):
dp[i]=min(dp[i],dp[i-a]+1)
print(dp[n])
| 0 | null | 5,222,269,802,882 | 115 | 28 |
A, B, M = map(int, input().split())
a = [int(a) for a in input().split()]
b = [int(b) for b in input().split()]
X = [0] * M
Y = [0] * M
C = [0] * M
for i in range(M):
X[i], Y[i], C[i] = map(int, input().split())
all_prices = []
for x, y, c in zip(X, Y, C):
all_prices.append(a[x-1] + b[y-1] - c)
prices = [min(a) + min(b), min(all_prices)]
print(min(prices))
|
(A, B, M), aa, bb, *xyc = [list(map(int, s.split())) for s in open(0)]
ans = min(aa)+min(bb)
for x, y, c in xyc:
ans = min(ans, aa[x-1]+bb[y-1]-c)
print(ans)
| 1 | 54,243,367,626,660 | null | 200 | 200 |
def main(X, Y):
for n_crane in range(X + 1):
n_turtle = X - n_crane
y = n_crane * 2 + n_turtle * 4
if y == Y:
print('Yes')
return
print('No')
if __name__ == "__main__":
X, Y = [int(s) for s in input().split(' ')]
main(X, Y)
|
x,y = map(int,input().split())
for i in range(x+1):
if 2*i+4*(x-i) == y:
print('Yes')
exit()
print('No')
| 1 | 13,726,821,960,992 | null | 127 | 127 |
n=int(input())
a=list(map(int,input().split()))
d={}
for i in a:
if d.get(i):d[i]+=1
else:d[i]=1
ans=0
for i in d:
ans+=d[i]*(d[i]-1)//2
for i in a:
print(ans-(d[i]-1))
|
""" スニペット """
def get_int():
return int(input())
def get_ints():
return list(map(int, input().split()))
""" スニペット """
import math
# 2つ選ぶ通り数を算出 nC2
def choose2(n):
return math.floor(n*(n-1)/2)
# インプット
N = get_int()
An = get_ints()
""" 全ての要素から2つのボールを選ぶ通り数を求める """
uni = [0] * (N+1)
# ユニーク数の配列を求める
for i in range(N):
uni[An[i]] += 1
sumWay = 0
# 各数値の2通りの選択通り数を足していく ここのindex=0がいらない
for i in range(N+1):
sumWay += choose2(uni[i])
""" 全ての要素数 - 削除する要素の通り数 + 削除する要素を引いた際の通り数 を求める """
for i in range(N):
print(sumWay - choose2(uni[An[i]]) + choose2(uni[An[i]]-1))
| 1 | 47,982,577,600,162 | null | 192 | 192 |
def lcm(x, y):
return x / gcd(x, y) * y
def gcd(a, b):
if (b == 0):
return a
return gcd(b, a % b);
a, b = [int(i) for i in input().split()]
print(int(lcm(a, b)))
|
# ABC155E
s = input()
d0 = [0,1,2,3,4,5,6,7,8,9]
d1 = [0,1,2,3,4,5,5,4,3,2] # 通常時
a0 = d1[int(s[0])]
a1 = d1[int(s[0]) + 1] if int(s[0])<=8 else 1
for c in s[1:]:
c = int(c)
b0 = min(a0 + c, a1 + (10 - c))
b1 = min(a0 + c + 1, a1 + (9 - c)) if c <=8 else a1
a0, a1 = b0, b1
print(a0)
| 0 | null | 92,180,123,715,680 | 256 | 219 |
N = int(input())
A = list(map(int, input().split()))
ary = [0]*(N-1)
for i in reversed(range(N-1)):
if i+1 >= (N-1):
ary[i] = A[N-1]
else:
ary[i] = ary[i+1] + A[i+1]
s = 0
for i in range(N-1):
s += A[i]*ary[i]
print(s%(10**9+7))
|
n = int(input())
a = list(map(int, input().split()))
mod = 10 ** 9 + 7
def cumsum(num, lst):
cumsumlst = [0] * num
for hoge in range(1, n):
cumsumlst[hoge] = (cumsumlst[hoge-1] + lst[hoge]) % mod
return cumsumlst
lst = cumsum(n, a)
ans = 0
for i in range(n-1):
ans += (a[i] * (lst[n-1] - lst[i])) % mod
ans %= mod
print(ans)
| 1 | 3,812,875,314,428 | null | 83 | 83 |
height = []
for i in range(10):
height.append(input())
height.sort(reverse=True)
for i in range(3):
print(height[i])
|
import sys
import numpy as np
import numba
from numba import jit
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
@jit
def main(n, a):
ans = np.zeros(n)
for i, j in enumerate(a):
ans[j-1] = i+1
for i in ans:
print(int(i), end=' ')
n = int(readline())
a = np.array(readline().split(), np.int64)
main(n,a)
| 0 | null | 90,627,761,975,350 | 2 | 299 |
N = int(input())
A = list(map(int,input().split()))
m = max(A) + 1
cnt = [0]*m
for i in A:
cnt[i] += 1
ans = 0
for i in range(1,m):
if cnt[i]:
if cnt[i]==1:
ans += 1
for j in range(i,m,i):
cnt[j] = 0
print(ans)
|
from collections import Counter
n = int(input())
a = list(map(int,input().split()))
a.sort()
ct = Counter(a)
st = set()
ans = 0
x = max(a)
for i in range(n):
if a[i] in st:
continue
if ct[a[i]]>1:
st.add(a[i])
for j in range(2,x//a[i]+1):
st.add(a[i]*j)
for i in range(n):
if not a[i] in st:
ans += 1
print(ans)
| 1 | 14,383,839,961,190 | null | 129 | 129 |
def main():
H, W = (int(i) for i in input().split())
c = [input() for i in range(H)]
dp = [[10**3]*W for _ in range(H)]
if c[0][0] == "#":
dp[0][0] = 1
else:
dp[0][0] = 0
for h in range(H):
for w in range(W):
if c[h][w] == ".":
if w < W-1 and c[h][w+1] == ".":
dp[h][w+1] = min(dp[h][w+1], dp[h][w])
elif w < W-1 and c[h][w+1] == "#":
dp[h][w+1] = min(dp[h][w+1], dp[h][w] + 1)
if h < H-1 and c[h+1][w] == ".":
dp[h+1][w] = min(dp[h+1][w], dp[h][w])
elif h < H-1 and c[h+1][w] == "#":
dp[h+1][w] = min(dp[h+1][w], dp[h][w] + 1)
else:
if w < W-1:
dp[h][w+1] = min(dp[h][w+1], dp[h][w])
if h < H-1:
dp[h+1][w] = min(dp[h+1][w], dp[h][w])
print(dp[H-1][W-1])
# print(*dp, sep="\n")
if __name__ == '__main__':
main()
|
h, w = map(int, input().split())
mat = [[] for _ in range(h)]
for i in range(h):
mat[i] = input()
dp = [[float("inf")] * w for _ in range(h)]
if mat[0][0] == "#":
dp[0][0] = 1
else:
dp[0][0] = 0
for i in range(h):
for j in range(w):
if mat[i][j - 1] != mat[i][j]:
left = dp[i][j - 1] + 1
else:
left = dp[i][j - 1]
if mat[i - 1][j] != mat[i][j]:
top = dp[i - 1][j] + 1
else:
top = dp[i - 1][j]
dp[i][j] = min(dp[i][j], left, top)
print((dp[h - 1][w - 1] + 1) // 2)
| 1 | 49,373,314,127,980 | null | 194 | 194 |
ls = list(map(int, input().split(' ')))
if sum(ls) >= 22:
print('bust')
else:
print('win')
|
a = list(map(int, input().split()))
print('bust' if sum(a) >= 22 else 'win')
| 1 | 118,506,185,476,592 | null | 260 | 260 |
N,K = map(int, input().split())
N = N%K
while(abs(N-K) < N):
N = abs(N-K)
print(N)
|
a,b,c,k = list(map(int,input().split()))
ans = min(a,k)
k = max(0,k-a-b)
ans -= k
print(ans)
| 0 | null | 30,629,020,482,438 | 180 | 148 |
import sys
from collections import deque
def m():
s=sys.stdin.readlines()
q=int(s[0].split()[1])
f=lambda x,y:(x,int(y))
d=deque(f(*e.split())for e in s[1:])
t,a=0,[]
while d:
k,v=d.popleft()
if v>q:v-=q;t+=q;d.append([k,v])
else:t+=v;a+=[f'{k} {t}']
print('\n'.join(a))
if'__main__'==__name__:m()
|
n,q=map(int,input().split())
Q=[]
sum=0
for i in range(n):
tmp=input().split()
tmp[1]=int(tmp[1])
Q.append(tmp[0])
Q.append(tmp[1])
loop=0
while loop==0:
for i in range(len(Q)//2):
tmp=[Q[0],Q[1]]
if tmp[1]>q:
sum+=q
Q.append(tmp[0])
Q.append(tmp[1]-q)
else:
sum+=tmp[1]
print(tmp[0],sum)
Q.pop(0)
Q.pop(0)
if len(Q)==0:
break
| 1 | 42,140,701,268 | null | 19 | 19 |
#!/usr/bin/env python3
# encoding:utf-8
import copy
import random
import bisect #bisect_left これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections
from decimal import Decimal # 10進数で考慮できる
mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000
d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))
a = int(input())
print(a + a** 2 + a**3)
|
n,k=map(int,input().split())
lst_1=list(map(int,input().split()))
# print(lst_1)
lst_2=[]
for i in range(n-k):
temp=1
temp=lst_1[i+k]/lst_1[i]
lst_2.append(temp)
for i in lst_2:
if i>1:
print("Yes")
else:print("No")
| 0 | null | 8,686,850,929,312 | 115 | 102 |
import sys
input = sys.stdin.readline
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def main():
mod=10**9+7
N=I()
#約数列挙
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
# divisors.sort()
return divisors
ans=set(make_divisors(N-1))
ans=ans - set([1])
ans.add(2)
L=make_divisors(N)
for i in range(1,len(L)):
temp=L[i]
N2=N
while N2>=temp:
if N2%temp==0:
N2=N2//temp
else:
N2=N2%temp
if N2==1:
ans.add(temp)
print(len(ans))
main()
|
M1,D1 = map(int,input().split())
M2,D2 = map(int,input().split())
print(1) if(M1 != M2) else print(0)
| 0 | null | 82,550,158,974,558 | 183 | 264 |
S = list(map(str,input()))
for i in range(len(S)):
S[i] = 'x'
print(''.join(map(str,S)))
|
s=list(input())
n=len(s)
ans=['x']*n
print(''.join(ans))
| 1 | 73,211,995,566,490 | null | 221 | 221 |
MODINT = 10**9+7
n, k = map(int, input().split())
ans = 0
"""
dp[i] = gdc がi となる場合のgcdの総和
"""
dp = [0] * (k+100)
for i in range(k, 0, -1):
dp[i] = pow(k//i, n, MODINT)
for j in range(i*2, k+1, i):
dp[i] -= dp[j]
ans += (dp[i]*i)%MODINT
print(ans%MODINT)
|
n, k = map(int, input().split())
MOD = 10 ** 9 + 7
a = [0] *(k+1)
for x in range(1, k + 1):
a[x] = pow(k // x, n, MOD)
for x in range(k, 0, -1):
for i in range(2, k // x + 1):
a[x] -= a[x * i]
answer = sum([i * x for i,x in enumerate(a)])
print(answer % MOD)
| 1 | 36,722,186,380,210 | null | 176 | 176 |
while True:
H,W = map(int,input().split())
if H == W == 0:
break
a = '#.'
b = '#'
c = '.#'
d = '.'
def bw(n):
if n % 2 == 0:
print((n//2)*a)
else:
print((n//2)*a + b)
def wb(n):
if n % 2 == 0:
print((n//2)*c)
else:
print((n//2)*c + d)
for i in range(1,H + 1):
if i % 2 == 0:
wb(W)
else:
bw(W)
print()
|
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()
def resolve():
a,b= map(int,input().split())
print(0 if a-b*2<0 else a-b*2)
resolve()
| 0 | null | 84,165,633,989,152 | 51 | 291 |
h = int(input())
ans = 1
while h > 0:
h //= 2
ans *= 2
print(ans-1)
|
import math
h = int(input())
n = int(math.log2(h))
a = 2
r = 2
S = (a*(r**n)-a) // (r-1)
print(S + 1)
| 1 | 79,824,698,540,742 | null | 228 | 228 |
import math
def koch(start,end,n):
if n==0:
return
else:
point1=[0,0]
point2=[0,0]
point3=[0,0]
point1[0]=(end[0]-start[0])/3 +start[0]
point1[1]=(end[1]-start[1])/3 +start[1]
point3[0]=(end[0]-start[0])*2/3+start[0]
point3[1]=(end[1]-start[1])*2/3+start[1]
rad60 = math.radians(60)
point2[0]=(point3[0]-point1[0])* math.cos(rad60) -(point3[1]-point1[1])*math.sin(rad60) +point1[0]
point2[1]=(point3[0]-point1[0])* math.sin(rad60) +(point3[1]-point1[1])*math.cos(rad60) +point1[1]
koch(start,point1,n-1)
print(*point1)
koch(point1,point2,n-1)
print(*point2)
koch(point2,point3,n-1)
print(*point3)
koch(point3,end,n-1)
n=int(input())
start=[0,0]
end=[100,0]
print(*start)
if n>0:
koch(start,end,n)
print(*end)
|
s=input()
ls=len(s)
m=[0]*(2019)
m[0]+=1
cnt = 0
b = 0
for i in range(ls):
a = (b + pow(10,cnt,2019)*int(s[ls - i -1])) % 2019
m[a] += 1
b = a
cnt += 1
ans = 0
for i in m:
if i <= 1:
continue
ans += i*(i-1)//2
print(ans)
| 0 | null | 15,590,890,151,410 | 27 | 166 |
import math
X = int(input())
year = 0
amount = 100
while True:
if amount >= X:
break
amount += math.floor(amount//100)
year += 1
print(year)
|
K=int(input())
S=input()
M=10**9+7
#----------------------------------------------------------------
f=1
Fact=[f]
for i in range(1,len(S)+K+1):
f=(f*i)%M
Fact.append(f)
Inv=[0]*(len(S)+K+1)
g=pow(f,M-2,M)
Inv=[0]*(len(S)+K+1)
Inv[-1]=g
for j in range(len(S)+K-1,-1,-1):
Inv[j]=(Inv[j+1]*(j+1))%M
def nCr(n,r):
if 0<=r<=n:
return (Fact[n]*Inv[r]*Inv[n-r])%M
else:
return 0
A=len(S)
T=0
for i in range(K+1):
T=(T+nCr(A+K-1-i,K-i)*pow(25,K-i,M)*pow(26,i,M))%M
print(T)
| 0 | null | 20,073,574,103,648 | 159 | 124 |
import bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
return sys.stdin.readline()[:-1]
def ruiseki(lst):
return [0]+list(accumulate(lst))
def celi(a,b):
return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]
n=int(input())
x=list(map(int,input().split()))
ans=float('inf')
for i in range(100):
tmp=0
for j in range(n):
tmp+=(x[j]-i-1)**2
ans=min(ans,tmp)
print(ans)
|
string = input()
for i in range(int(input())):
lst = list(map(str, input().split()))
if lst[0] == "replace":
string = string[:int(lst[1])] + lst[3] + string[int(lst[2])+1:]
if lst[0] == "reverse":
rev_str = str(string[int(lst[1]):int(lst[2])+1])
string = string[:int(lst[1])] + rev_str[::-1] + string[int(lst[2])+1:]
if lst[0] == "print":
print(string[int(lst[1]):int(lst[2])+1])
| 0 | null | 33,820,722,600,838 | 213 | 68 |
while True:
num = raw_input()
if num == "0":
break
output = 0
for i in num:
output += int(i)
print output
|
# 入力
N = int(input())
A = list(map(int, input().split()))
# 上限を決める
NowNode = 2**0
NextNode = (NowNode - A[0])*2
UpperLimit = [0] * (N+1)
UpperLimit[0] = 1
if A[0] == 1:
if N == 0:
print(1)
exit()
print(-1)
exit()
for d in range(1, N+1, 1):
NowNode = NextNode
NextNode = (NowNode - A[d]) * 2
UpperLimit[d] = NowNode
# print(UpperLimit)
UpperLimit[-1] = min(A[-1], UpperLimit[-1])
# 下から見ていく
NowNode = A[-1]
ans = 0
for d in range(N, -1, -1):
PrevNode = NowNode
if UpperLimit[d] < A[d]:
print(-1)
exit()
if NowNode + A[d] <= UpperLimit[d]:
NowNode += A[d]
else:
NowNode = UpperLimit[d]
ans += NowNode
# print(d, NowNode)
print(ans)
| 0 | null | 10,170,199,504,920 | 62 | 141 |
h,w=map(int,input().split())
g=[[*input()] for _ in range(h)]
from collections import *
def bfs(sx,sy):
d=[[-1]*w for _ in range(h)]
d[sx][sy]=0
q=deque([(sx,sy)])
while q:
x,y=q.popleft()
t=d[x][y]+1
for dx,dy in [(1,0),(0,1),(-1,0),(0,-1)]:
nx,ny=x+dx,y+dy
if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and d[nx][ny]<0:
d[nx][ny]=t
q.append((nx,ny))
return d
import numpy as np
a=0
for sx in range(h):
for sy in range(w):
if g[sx][sy]=='#': continue
a=max(a,np.max(bfs(sx,sy)))
print(a)
|
input()
l = [int(i) for i in input().split()]
print(" ".join(map(str,l[::-1])))
| 0 | null | 47,654,112,870,210 | 241 | 53 |
# -*- coding: utf-8 -*-
l = input()
S1, S2 = [], []
sum = 0
n = len(l)
for i in range(n):
if l[i] == "\\":
S1.append(i)
elif l[i] == "/" and S1:
j = S1.pop()
a = i - j
sum += a
while S2 and S2[-1][0] > j:
a += S2.pop()[1]
S2.append([j, a])
print(sum)
print(len(S2), *(a for j, a in S2))
|
A, B = map(int, input().split())
a = [i for i in range(int((A-1)*100/8 ), int((A+1)*100/8 ))]
b = [i for i in range(int((B-1)*100/10), int((B+1)*100/10))]
a = [i for i in a if int(i*0.08) == A]
b = [i for i in b if int(i*0.10) == B]
ans = list(set(a) & set(b))
if ans and min(ans) > 0:
print(min(ans))
else:
print(-1)
| 0 | null | 28,347,043,071,138 | 21 | 203 |
# Aizu Problem ALDS_1_4_D: Allocation
import sys, math, os
# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
sys.stdin = open("sample-input2.txt", "rt")
def check(n, k, W, p):
idx = 0
for i in range(k):
S = 0
while W[idx] + S <= p:
S += W[idx]
idx += 1
if idx == n:
return True
return False
n, k = [int(_) for _ in input().split()]
W = [int(input()) for _ in range(n)]
left, right = 0, 10**16
while right - left > 1:
mid = (left + right) // 2
if check(n, k, W, mid):
right = mid
else:
left = mid
print(right)
|
a=int(input())
b=a//100
b*=5
c=a%100
print("1" if b>=c else "0")
| 0 | null | 63,491,151,083,818 | 24 | 266 |
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('')
|
# -*- coding: utf-8 -*-
import sys
import os
def frame(w, h):
top = '#' * w
inner = ['.'] * w
inner[0] = '#'
inner[-1] = '#'
inner_str = ''.join(inner)
print(top)
for i in range(h - 2):
print(inner_str)
print(top)
for s in sys.stdin:
H, W = list(map(int, s.split()))
if W == H == 0:
break
else:
frame(W, H)
print()
| 1 | 819,857,456,108 | null | 50 | 50 |
import sys
input = sys.stdin.readline
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return -self.parents[self.find(x)]
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
return -self.parents[self.find(x)]
def main():
N, M = map(int, input().split())
uf = UnionFind(N+1)
ans = 1
if M == 0:
print(ans)
return
for i in range(M):
x, y = map(int, input().split())
ans = max(uf.union(x,y), ans)
print(ans)
if __name__ == '__main__':
main()
|
n, m = map(int, input().split())
ab = []
for i in range (m):
ab.append(list(map(int, input().split())))
par = [-1] * (n+1)
#Union Find
#xの根を求める
def find(x):
if par[x] < 0:
return x
else:
tank = []
while par[x] >= 0:
tank.append(x)
x = par[x]
for elt in tank:
par[elt] = x
return x
#xとyの属する集合の併合
def unite(x,y):
x = find(x)
y = find(y)
if x == y:
return
else:
#sizeの大きいほうがx
if par[x] > par[y]:
x,y = y,x
par[x] += par[y]
par[y] = x
return
for j in range(m):
unite(ab[j][0], ab[j][1])
m = -1*min(par)
print(m)
| 1 | 3,934,455,284,480 | null | 84 | 84 |
n, m = map(int,input().split())
count = 0
l = []
for i in range(n):
for i2 in range(i,n):
if i != i2:
l.append([i,i2])
for i in range(m):
for i2 in range(i,m):
if i != i2:
l.append([i,i2])
print(len(l))
|
# 159 ########## dbt
n, m = map(int, input().split())
def factorial(a):
p = 1
for i in range(a, 0 , -1):
p *= i
return p
def combo(b, num):
ans = factorial(b) // (factorial(num) * factorial(b - num))
return ans
print(combo(n, 2) + combo(m, 2))
| 1 | 45,397,981,778,292 | null | 189 | 189 |
a,b=map(str,input().split())
res = ""
if a < b:
for i in range(int(b)):
res += a
else:
for i in range(int(a)):
res += b
print(res)
|
import sys
input = sys.stdin.readline
def main():
N = int(input())
A = list(map(int, input().split()))
p = 10**9 + 7
total = 0
for i in range(60):
cnt_1, cnt_0 = 0, 0
for j in range(N):
if (A[j]>>i)&1:
cnt_1 += 1
else:
cnt_0 += 1
total += pow(2, i, p) * cnt_0 * cnt_1 %p
print(total%p)
main()
| 0 | null | 103,527,993,886,720 | 232 | 263 |
n,m = map(int,input().split())
AB = [[] for _ in range(n)]
for i in range(m):
a,b = map(int,input().split())
AB[a-1].append(b-1)
AB[b-1].append(a-1)
visited = set()
ans = [0]*n
stack = [0]
for i in stack:
# このへんあやしい
for j in AB[i]:
if j in visited:
continue
visited.add(j)
ans[j] = i+1
stack.append(j)
# このへんまで
for i in ans[1:]:
if i==0:
print('No')
exit()
print('Yes')
for i in ans[1:]:
print(i)
|
from collections import deque
q=deque()
def MI(): return map(int, input().split())
N,M=MI()
g=[[] for _ in range(N+1)]
for _ in range(M):
a,b=MI()
g[a].append(b)
g[b].append(a)
check=[0]*(N+1)
check[1]=1
ans=[0]*(N+1)
q.append(1)
while len(q)>0:
v=q.popleft()
for u in g[v]:
if check[u]==0:
check[u]=1
ans[u]=v
q.append(u)
print('Yes')
for i in range(2,N+1):
print(ans[i])
| 1 | 20,578,336,243,500 | null | 145 | 145 |
def kton(S):
r = 0
m = 0
for s in S:
r += 1 if s == '(' else -1
m = min(m, r)
return r, m
def main():
N = int(input())
RM = [kton(input()) for _ in range(N)]
pos = 0
negp = []
negn = []
posn = []
for r, m in RM:
if m < 0:
if r >= 0:
negp.append((-m, r))
else:
negn.append((-(r-m), -r, m))
else:
pos += r
negp.sort()
for m, r in negp:
if pos - m < 0:
return False
pos += r
negn.sort()
for _, r, m in negn:
if pos + m < 0:
return False
pos -= r
return pos == 0
print('Yes' if main() else 'No')
|
# coding: utf-8
import sys
from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import combinations, product
#import bisect# lower_bound etc
#import numpy as np
#import queue# queue,get(), queue.put()
def run():
N = int(input())
current = 0
ways = []
dic = {'(': 1, ')': -1}
SS = read().split()
for S in SS:
path = [0]
for s in S:
path.append(path[-1]+ dic[s])
ways.append((path[-1], min(path)))
ways_pos = sorted([(a,b) for a,b in ways if a >= 0], key = lambda x:(x[1], x[0]), reverse=True)
ways_neg = sorted([(a,b) for a,b in ways if a < 0], key = lambda x:(x[1] - x[0], -x[0]))
for i in range(len(ways_pos)):
go, max_depth = ways_pos[i]
if current + max_depth >= 0:
current += go
else:
print("No")
return None
for i in range(len(ways_neg)):
go, max_depth = ways_neg[i]
if current + max_depth >= 0:
current += go
else:
print("No")
return None
if current == 0:
print('Yes')
else:
print('No')
if __name__ == "__main__":
run()
| 1 | 23,698,836,387,532 | null | 152 | 152 |
x,y=map(int ,input().split())
if x*2<=y<=x*4 and y%2==0:
print("Yes")
else:
print("No")
|
x,y = map(int,input().split())
cnt = 0
for b in range(x+1) :
for t in range(x+1) :
if x == b+t and y == 2*b+4*t :
print('Yes')
exit()
else :
continue
print('No')
| 1 | 13,719,122,084,028 | null | 127 | 127 |
n, k = map(int, input().split())
lst = [0] + list(map(int, input().split()))
dic = {1:0}
loc = 1
for i in range(1, k + 1):
loc = lst[loc]
if loc not in dic:
dic[loc] = i
else:
span = i - dic[loc]
initial = dic[loc]
z = (k - initial) % span
for j in range(z):
loc = lst[loc]
print(loc)
exit()
print(loc)
|
N,K=map(int,input().split())
A=list(map(int,input().split()))
B=[1]
C=["#"]*N
roop=False
for i in range(K):
if C[B[i]-1]=="#":
C[B[i]-1]="$"
else:
roop=True
break
B.append(A[B[i]-1])
if roop==True:
f=B.index(B[i])
T=i-f
if T==0:
print(B[f])
else:
r=(K-f)%T
print(B[f+r])
else:
print(B[K])
| 1 | 22,681,315,319,172 | null | 150 | 150 |
input()
a = list(map(int, input().split()))
c = 1000000007
print(((sum(a)**2-sum(map(lambda x: x**2, a)))//2)%c)
|
## necessary imports
import sys
input = sys.stdin.readline
# from math import ceil, floor, factorial;
def ceil(x):
if x != int(x):
x = int(x) + 1;
return x;
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if b == 0:
return a
return gcd(b, a % b);
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return int(res)
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0, hi = None):
if hi == None:
hi = len(a);
while lo < hi:
mid = (lo+hi)//2
if a[mid] < x:
lo = mid+1
else:
hi = mid
return lo
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0 and n > 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0 and n > 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()))
## taking string array input
def str_array():
return input().strip().split();
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
n, k = int_array(); a = int_array();
pos = []; neg = []; ans = 1;
for i in a:
if i < 0:
neg.append(i);
else:
pos.append(i);
if n == k:
for i in a:
ans = (ans * i) % MOD;
elif not pos:
if k & 1:
neg.sort(reverse = 1);
else:
neg.sort();
for i in range(k):
ans = (ans * neg[i]) % MOD;
else:
pos.sort(); neg.sort(reverse = 1);
if k & 1:
ans = pos.pop();
for _ in range(k // 2):
if len(pos) > 1 and len(neg) > 1:
if pos[-1] * pos[-2] >= neg[-1] * neg[-2]:
ans = (ans * pos.pop()) % MOD;
ans = (ans * pos.pop()) % MOD;
else:
ans = (ans * neg.pop()) % MOD;
ans = (ans * neg.pop()) % MOD;
elif len(pos) > 1:
ans = (ans * pos.pop()) % MOD;
ans = (ans * pos.pop()) % MOD;
else:
ans = (ans * neg.pop()) % MOD;
ans = (ans * neg.pop()) % MOD;
print(ans);
| 0 | null | 6,596,958,171,958 | 83 | 112 |
from collections import deque
def read_int():
return int(input().strip())
def read_ints():
return list(map(int, input().strip().split(' ')))
def solve():
N, K, C = read_ints()
S = input().strip()
earliest = []
i = 0
while len(earliest) < K:
if S[i] == 'o':
earliest.append(i)
i += C+1
else:
i += 1
latest = []
i = N-1
while len(latest) < K:
if S[i] == 'o':
latest.append(i)
i -= C+1
else:
i -= 1
latest.reverse()
for i, j in zip(earliest, latest):
if i == j:
print(i+1)
if __name__ == '__main__':
solve()
|
from heapq import heappush, heappop
N, K, C = map(int, input().split())
S = input()
if C == 0 :
if K == S.count('o') :
for i, s in enumerate(S) :
if s == 'o' :
print(i + 1)
else :
N += 2
S = 'x' + S + 'x'
dpL = [0] * N
dpR = [0] * N
for l in range(1, N) :
r = N - 1 - l
dpL[l] = max(dpL[l - 1], int(S[l] == 'o'))
dpR[r] = max(dpR[r + 1], int(S[r] == 'o'))
if l - C - 1 >= 0 and S[l] == 'o' :
dpL[l] = max(dpL[l], dpL[l - C - 1] + 1)
if r + C + 1 < N and S[r] == 'o' :
dpR[r] = max(dpR[r], dpR[r + C + 1] + 1)
h = []
for r in range(C + 1) :
heappush(h, (-dpR[r], r))
for l in range(1, N) :
r = l - 1 + C + 1
if r < N :
cost = dpL[l - 1] + dpR[r]
else :
cost = dpL[l - 1]
heappush(h, (-cost, r))
while h[0][1] <= l :
heappop(h)
if -h[0][0] < K and S[l] == 'o' :
print(l)
| 1 | 40,471,959,612,138 | null | 182 | 182 |
N, A, B = [int(x) for x in input().split()]
if (B-A) % 2 == 0:
print((B-A) // 2)
else:
print(min(A-1, N-B) + 1 + (B - A - 1) // 2)
|
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
N, A, B = MAP()
if abs(A-B)%2 == 0:
print(abs(A-B)//2)
else:
A, B = min(A, B), max(A, B)
print(min((N-B)-(-(B-A)//2), A-1-(-(B-A)//2)))
| 1 | 109,614,157,235,210 | null | 253 | 253 |
N = int(input())
ans = (N + 1) // 2 / N
print(ans)
|
import math
import sys
from collections import deque
import heapq
import copy
import itertools
from itertools import permutations
from itertools import combinations
import bisect
def mi() : return map(int,sys.stdin.readline().split())
def ii() : return int(sys.stdin.readline().rstrip())
def i() : return sys.stdin.readline().rstrip()
a=ii()
if a%2==0:
print(1/2)
else:
print(math.ceil(a/2)/a)
| 1 | 177,045,628,982,830 | null | 297 | 297 |
x = int(input())
a, r = x // 500, x % 500
b = r // 5
print(1000 * a + 5 * b)
|
# 2:01
X = int(input())
ans = 0
ans += X // 500 * 1000
X %= 500
ans += X // 5 * 5
print(ans)
| 1 | 42,625,404,505,882 | null | 185 | 185 |
a = int(input())
i = 1
while a!=0:
print("Case "+str(i)+":",a)
a = int(input())
i = i+1
|
count = 0
for i in range(10000):
a = input()
a = int(a)
if a >= 1:
count += 1
print('Case '+str(count)+': '+str(a))
else:
break
| 1 | 487,713,410,140 | null | 42 | 42 |
import sys
input = sys.stdin.readline
def main():
from collections import deque
from collections import defaultdict
n=int(input())
ab=[list(map(int,input().split())) for _ in range(n-1)]
g=[[] for _ in range(n)]
for i,abi in enumerate(ab):
a,b=abi
g[b-1].append(a-1)
g[a-1].append(b-1)
todo=deque([(0,-1)])
dc={}
while len(todo)>0:
a,pc=todo.popleft()
l=g[a]
c=0
for li in l:
d,e=min(a,li),max(a,li)
if (d,e) not in dc:
c+=1 if c+1!=pc else 2
dc[(d,e)]=c
todo.append([li,c])
print(max(dc.values()))
for a,b in ab:
print(dc[(a-1,b-1)])
if __name__=='__main__':
main()
|
# coding:utf-8
W=input()
W=W.lower()
ct=0
while True:
S=map(str,input().split())
for i in S:
if i=="END_OF_TEXT":
print(ct)
exit(0)
elif i.lower()==W:
ct=ct+1
| 0 | null | 68,911,264,077,290 | 272 | 65 |
# -*- coding: utf-8 -*-
## Library
import sys
from fractions import gcd
import math
from math import ceil,floor
import collections
from collections import Counter
import itertools
import copy
## input
# N=int(input())
# A,B,C,D=map(int, input().split())
# S = input()
# yoko = list(map(int, input().split()))
# tate = [int(input()) for _ in range(N)]
# N, M = map(int,input().split())
# P = [list(map(int,input().split())) for i in range(M)]
# S = []
# for _ in range(N):
# S.append(list(input()))
N=int(input())
print(N+N**2+N**3)
|
import time
a=int(input())
time.sleep(1.975)
print(a+a*a+a*a*a)
| 1 | 10,151,193,282,768 | null | 115 | 115 |
N = int(input())
if N % 2 == 0:
print("0.5")
else:
a = N // 2 + 1
print(a/N)
|
x = int(input())
A = str()
for i in range(x):
A = A + 'ACL'
i += 1
print(A)
| 0 | null | 89,526,225,027,392 | 297 | 69 |
MOD = 10 ** 9 + 7
N = int(input())
Sall = pow(10, N, MOD)
S0 = S9 = pow(9, N, MOD)
S09 = pow(8, N, MOD)
ans = (Sall - (S0 + S9 - S09)) % MOD
print(ans)
|
import math
N = int(input())
MOD_VALUE = math.pow(10, 9) + 7
def pow_mod(value, pow):
ret = 1
for _ in range(pow):
ret = ret * value % MOD_VALUE
return ret
result = pow_mod(10, N) - pow_mod(9, N) * 2 + pow_mod(8, N)
print(int(result % MOD_VALUE))
| 1 | 3,143,334,075,666 | null | 78 | 78 |
N = int(input())
list1 = []
for i in range(N+1):
if i%3 ==0 or i%5 ==0:
list1.append(i)
total1 =0
total2 = 0
for i in list1:
total1 += i
for i in range(N+1):
total2 += i
print(total2 -total1)
|
k,n = map(int,input().split())
A = list(map(int,input().split()))
B=[]
t=0
for a in A:
B.append(a-t)
t=a
B[0] +=k-t
print(k-max(B) )
| 0 | null | 39,261,422,401,916 | 173 | 186 |
n=int(input())
ans=0
m=1
while n>1:
n=n//2
ans+=m
m*=2
print(ans+m)
|
H = int(input())
ans = 0
cnt = 0
while True:
ans += 2 ** cnt
if H == 1:
break
H = H//2
cnt += 1
print(ans)
| 1 | 80,442,842,508,700 | null | 228 | 228 |
a,b,c,d = map(int,input().split())
answers = []
one = a*c
two = a*d
three = b*c
four = b*d
answers.append(one)
answers.append(two)
answers.append(three)
answers.append(four)
print(max(answers))
|
while 1:
s=input()
if len(s)==1:break
for _ in range(int(input())):
a=int(input())
s=s[a:]+s[:a]
print(s)
| 0 | null | 2,468,647,766,300 | 77 | 66 |
# 解説AC
mod = 10 ** 9 + 7
n, k = map(int, input().split())
dp = [-1] * (k + 1)
ans = 0
for i in range(k, 0, -1):
dp[i] = pow(k // i, n, mod)
t = 0
t += 2 * i
while t <= k:
dp[i] -= dp[t]
dp[i] %= mod
t += i
ans += i * dp[i]
ans %= mod
print(ans)
|
if __name__ == '__main__':
n = int(input())
print(n + n * n + n * n * n )
| 0 | null | 23,535,214,738,926 | 176 | 115 |
[S,T] = input().split()
print(T+S)
|
strs = list(input().split())
print(strs[1]+strs[0])
| 1 | 103,107,437,721,888 | null | 248 | 248 |
a = int(input())
sum = a + a*a +a*a*a
print(sum)
|
a = int(input())
ans = a * (1 + a + a * a)
print(ans)
| 1 | 10,315,083,058,430 | null | 115 | 115 |
n = int(input())
N = int(n/1.08)
for i in range(3):
if int((N + i) * 1.08) == n:
print(N+i)
break
else:
print(':(')
|
n,m = map(int,input().split())
a = [1]*(n+1)
b = [0]*(n+1)
for i in range(m):
x,y = map(int,input().split())
u = x
while a[u]==0:
u = b[u]
v = y
while a[v]==0:
v = b[v]
if u!=v:
b[v] = u
b[y] = u
b[x] = u
a[u] += a[v]
a[v] = 0
print(max(a))
| 0 | null | 64,680,991,720,552 | 265 | 84 |
while True:
n, x = map(int, input().split())
if n == x == 0:
break
cnt = 0
for a in range(1, x // 3):
for b in range(a + 1, x // 2):
c = x - a - b
if b < c <= n:
cnt += 1
print(cnt)
|
H ,W = map(int,input().split())
from collections import deque
S = [input() for i in range(H)]
directions = [[0,1],[1,0],[-1,0],[0,-1]]
counter = 0
#インデックス番号 xが行番号 yが列番号
for x in range(H):
for y in range(W):
if S[x][y]=="#":
continue
que = deque([[x,y]])
memory = [[-1]*W for _ in range(H)]
memory[x][y]=0
while True:
if len(que)==0:
break
h,w = que.popleft()
for i,k in directions:
x_new,y_new = h+i,w+k
if not(0<=x_new<=H-1) or not(0<=y_new<=W-1) :
continue
elif not memory[x_new][y_new]==-1 or S[x_new][y_new]=="#":
continue
memory[x_new][y_new] = memory[h][w]+1
que.append([x_new,y_new])
counter = max(counter,max(max(i) for i in memory))
print(counter)
| 0 | null | 47,787,048,151,780 | 58 | 241 |
#coding:UTF-8
n = input()
a = map(int,raw_input().split())
a.reverse()
for i in range(n):
print a[i],
|
n = int(input())
X_MAX = 50001
for x in range(X_MAX):
if int(x * 1.08) == n:
print(x)
exit()
print(":(")
| 0 | null | 63,207,140,435,472 | 53 | 265 |
X, Y = map(int, input().split(' '))
print('Yes' if (X * 2 <= Y <= X * 4) and (Y % 2 == 0) else 'No')
|
kazu=int(input())
A=[int(i) for i in input().split()]
# kazu=6
# A=[5,2,4,6,1,3]
j=0
for i in range(kazu - 1):
print(A[i], end=" ")
print(A[kazu-1])
for i in range(1,kazu):
v=A[i]
j=i-1
while j>=0 and A[j] >v:
A[j+1]=A[j]
j =j -1
A[j+1]=v
for i in range(kazu-1):
print(A[i],end=" ")
print(A[kazu-1])
| 0 | null | 6,820,689,951,320 | 127 | 10 |
# -*- coding: utf-8 -*-
def main():
n, m = map(int, input().split())
h = list(map(int, input().split()))
h_dict = {}
for i in range(len(h)):
h_dict[i+1] = h[i]
out = []
for k in range(m):
a, b = map(int, input().split())
ha = h_dict[a]
hb = h_dict[b]
if ha > hb:
out.append(b)
elif ha < hb:
out.append(a)
else:
out.append(a)
out.append(b)
out = set(out)
print(n - len(out))
if __name__ == '__main__':
main()
|
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 | 28,549,930,560,606 | 155 | 168 |
A, B, M = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
ans = []
for i in range(M):
x, y, c = map(int,input().split())
z = a[x - 1] + b[y - 1] - c
ans.append(z)
z = min(a) + min(b)
ans.append(z)
ans = sorted(ans)
print(ans[0])
|
a,b,m=map(int,input().split())
ali= list(map(int,input().split()))
bli= list(map(int,input().split()))
min=min(ali)+min(bli)
for i in range(0,m):
x,y,c=map(int,input().split())
mon=ali[x-1]+bli[y-1]-c
if mon<min:
min=mon
print(min)
| 1 | 54,092,072,714,810 | null | 200 | 200 |
import os
import sys
from collections import defaultdict, Counter
from itertools import product, permutations,combinations, accumulate
from operator import itemgetter
from bisect import bisect_left,bisect
from heapq import heappop,heappush,heapify
from math import ceil, floor, sqrt
from copy import deepcopy
def main():
a,b,c = map(int, input().split())
k = int(input())
flag = False
if a < b < c:
print("Yes")
sys.exit()
for i in range(k):
if a < b < c:
c *= 2
if a >= b:
if b >= c:
c *= 2
else:
b *= 2
else:
if b >= c:
c *= 2
else:
b *= 2
if a < b < c:
print("Yes")
else:
print("No")
if __name__ == '__main__':
main()
|
A,B,C = map(int, input().split())
K = int(input())
n = 0
while (A >= B):
B = 2*B
n +=1
while B>=C:
C = 2*C
n += 1
#print(A,B,C,n)
if n <= K:
print('Yes')
else:
print('No')
| 1 | 6,927,124,283,680 | null | 101 | 101 |
n,k = map(int,input().split())
r,s,p = map(int,input().split())
t = [_ for _ in str(input())]
ans = 0
for i in range(n):
if i - k < 0:
if t[i] == "r":
ans += p
elif t[i] == "s":
ans += r
elif t[i] == "p":
ans += s
else:
if t[i] == "r" and t[i-k] != "r":
ans += p
elif t[i] == "s" and t[i-k] != "s":
ans += r
elif t[i] == "p" and t[i-k] != "p":
ans += s
else:
t[i] = "a"
print(ans)
|
n,k = map(int,input().split())
R,S,P = map(int,input().split())
T = input()
slist = ['']*k
for i in range(n):
slist[i%k] += T[i]
ans = 0
for s in slist:
dp = [[0,0,0]for i in range(len(s))]
#dp[i][j] = 直前にjを出したときの得点の最大値
'''
0..r
1..s
2..p
'''
dp[0][1] = S if s[0] == 'p' else 0
dp[0][0] = R if s[0] == 's' else 0
dp[0][2] = P if s[0] == 'r' else 0
for i in range(1,len(s)):
if s[i] == 'r':
dp[i][2] = max(dp[i-1][0],dp[i-1][1]) + P
dp[i][1] = max(dp[i-1][0],dp[i-1][2])
dp[i][0] = max(dp[i-1][1],dp[i-1][2])
elif s[i] == 's':
dp[i][0] = max(dp[i-1][2],dp[i-1][1]) + R
dp[i][1] = max(dp[i-1][0],dp[i-1][2])
dp[i][2] = max(dp[i-1][1],dp[i-1][0])
else:
dp[i][1] = max(dp[i-1][2],dp[i-1][0]) + S
dp[i][0] = max(dp[i-1][1],dp[i-1][2])
dp[i][2] = max(dp[i-1][1],dp[i-1][0])
ans += max(dp[len(s)-1][0],dp[len(s)-1][1],dp[len(s)-1][2])
#print(slist)
print(ans)
| 1 | 106,952,692,240,900 | null | 251 | 251 |
x = int(input())
answer = 0
answer = (x//500)*1000
x = x%500
answer += (x//5)*5
print(answer)
|
import re
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
import functools
def v(): 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)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
cnt = 0
ans = 1
inf = float("inf")
al = "abcdefghijklmnopqrstuvwxyz"
a,b = I()
A = str(a)*b
B = str(b)*a
print(min(A,B))
| 0 | null | 63,693,319,954,950 | 185 | 232 |
w = int(input())
h = w // 3600
m = (w % 3600) // 60
s = w % 60
print(f"{h}:{m}:{s}")
|
a = int(raw_input())
h = a / 3600
m = (a % 3600) / 60
s = a % 60
print "{0}:{1}:{2}".format(h, m, s)
| 1 | 321,187,847,722 | null | 37 | 37 |
s = input()
a = s[:len(s)//2]
b = s[len(s)//2+1:]
print('Yes' if s == s[::-1] and a == a[::-1] and b == b[::-1] else 'No')
|
S = input()
N = len(S)
count1,count2,count3 = 0,0,0
flg1,flg2,flg3 = False,False,False
for i in range(N):
#print(S[i],S[-1-i])
if S[i] == S[-1-i]:
count1 += 1
if count1 == N:
flg1 = True
#print(count1,flg1)
a = int((N-1)/2)
for i in range(a):
#print(S[i],S[a-1-i])
if S[i] == S[a-1-i]:
count2 += 1
if count2 == int((N-1)/2):
flg2 = True
#print(count2,flg2,a)
b = int((N+3)/2)
#print(b)
for i in range(N-b+1):
#print(S[b+i-1],S[N-1-i])
if S[b+i-1] == S[N-i-1]:
count3 += 1
if count3 == N-b+1 :
flg3 = True
if flg1 == True and flg2 == True and flg3 == True:
print("Yes")
else:
print("No")
| 1 | 46,028,333,070,468 | null | 190 | 190 |
#E
H,N=map(int,input().split())
A=[]
B=[]
DP=[0]+[float('Inf')]*(2*10**4)
for i in range(N):
a,b=map(int,input().split())
A.append(a)
B.append(b)
for j in range(10**4):
for i in range(N):
DP[j+A[i]]=min(B[i]+DP[j],DP[j+A[i]])
print(min(DP[H:]))
|
h, n = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(n)]
INF = 1 << 60
dp = [INF] * (h + 1)
dp[0] = 0
for i in range(0, h + 1):
# hを超えるために必要な最小コストは?
for a, b in ab:
if i + a <= h:
dp[i + a] = min(dp[i] + b, dp[i + a])
else:
dp[h] = min(dp[i] + b, dp[h])
print(dp[h])
| 1 | 80,869,797,201,468 | null | 229 | 229 |
count = int(raw_input())
S = []
H = []
C = []
D = []
while count:
arr = map(str, raw_input().split(" "))
if arr[0] == "S":
S.append(int(arr[1]))
elif arr[0] == "H":
H.append(int(arr[1]))
elif arr[0] == "C":
C.append(int(arr[1]))
else:
D.append(int(arr[1]))
count -= 1
S.sort()
H.sort()
C.sort()
D.sort()
ans_s = []
ans_h = []
ans_c = []
ans_d = []
for x in range(1, 14):
if not x in S:
ans_s.append(x)
if not x in H:
ans_h.append(x)
if not x in C:
ans_c.append(x)
if not x in D:
ans_d.append(x)
def answer(arr, value):
for x in arr:
print "%s %s" % (value, str(x))
answer(ans_s, 'S')
answer(ans_h, 'H')
answer(ans_c, 'C')
answer(ans_d, 'D')
|
import itertools
n = int(input())
a = [input() for _ in range(n)]
suits = ['S', 'H', 'C', 'D']
cards = ["%s %d" % (s, r) for s, r in itertools.product(suits, range(1, 14))]
answers = [c for c in cards if c not in a]
for card in answers:
print(card)
| 1 | 1,037,792,410,512 | null | 54 | 54 |
X = int(input())
happy = X // 500 * 1000
happy += X % 500 // 5 * 5
print(happy)
|
s=input()
print("x"*(len(s)))
| 0 | null | 58,156,089,382,534 | 185 | 221 |
import os, sys, re, math
N = int(input())
S = []
for i in range(N):
S.append(input())
d = {}
for s in S:
if not s in d:
d[s] = 0
d[s] += 1
d = sorted(d.items(), key=lambda x:x[1], reverse=True)
names = [v[0] for v in d if v[1] == d[0][1]]
for name in sorted(names):
print(name)
|
from collections import Counter
N = int(input())
S = [input() for _ in range(N)]
cntr = Counter(S)
mc = cntr.most_common()
n = mc[0][1]
ans = []
for k, v in mc:
if n!=v:
break
ans.append(k)
ans.sort()
print("\n".join(ans))
| 1 | 70,082,444,774,620 | null | 218 | 218 |
import collections
n = int(input())
adj_list = []
for _ in range(n):
adj = list(map(int, input().split(" ")))
adj_list.append([c - 1 for c in adj[2:]])
distances = [-1 for _ in range(n)]
queue = collections.deque()
queue.append(0)
distances[0] = 0
while queue:
p = queue.popleft()
for next_p in adj_list[p]:
if distances[next_p] == -1:
distances[next_p] = distances[p] + 1
queue.append(next_p)
for i in range(n):
print(i+1, distances[i])
|
import collections
N = int(input())
UKV = [list(map(int,input().split())) for _ in range(N)]
dist = [-1]*N
que = collections.deque()
G = [[]]*N
for ukv in UKV:
G[ukv[0]-1] = sorted(ukv[2:])
dist[0] = 0
que.append(1)
while len(que) != 0:
v = que.popleft()
for nv in G[v-1]:
if dist[nv-1] != -1:
continue
dist[nv-1] = dist[v-1] + 1
que.append(nv)
for i,d in enumerate(dist):
print(i+1, d)
| 1 | 4,114,922,668 | null | 9 | 9 |
x,k=map(int,input().split())
ans=0
while k**ans<=x:
ans+=1
print(ans)
|
import sys
stdin = sys.stdin
def ni(): return int(ns())
def na(): return list(map(int, stdin.readline().split()))
def naa(N): return [na() for _ in range(N)]
def ns(): return stdin.readline().rstrip() # ignore trailing spaces
A, B = na()
print(A * B)
| 0 | null | 39,961,978,778,020 | 212 | 133 |
N = int(input())
S = ["*"]*(N+1)
S[1:] = list(input())
Q = int(input())
q1,q2,q3 = [0]*Q,[0]*Q,[0]*Q
for i in range(Q):
tmp = input().split()
q1[i],q2[i] = map(int,tmp[:2])
if q1[i] == 2:
q3[i] = int(tmp[2])
else:
q3[i] = tmp[2]
class BIT:
def __init__(self, n, init_list):
self.num = n + 1
self.tree = [0] * self.num
for i, e in enumerate(init_list):
self.update(i, e)
#a_kにxを加算
def update(self, k, x):
k = k + 1
while k < self.num:
self.tree[k] += x
k += (k & (-k))
return
def query1(self, r):
ret = 0
while r > 0:
ret += self.tree[r]
r -= r & (-r)
return ret
#通常のスライスと同じ。lは含み、rは含まない
def query2(self, l, r):
return self.query1(r) - self.query1(l)
s_pos = [BIT(N+1,[0]*(N+1)) for _ in range(26)]
for i in range(1,N+1):
s_pos[ord(S[i]) - ord("a")].update(i,1)
alphabets = [chr(ord("a") + i) for i in range(26)]
for i in range(Q):
if q1[i] == 1:
s_pos[ord(S[q2[i]]) - ord("a")].update(q2[i],-1)
S[q2[i]] = q3[i]
s_pos[ord(q3[i]) - ord("a")].update(q2[i],1)
else:
ans = 0
for c in alphabets:
if s_pos[ord(c) - ord("a")].query2(q2[i],q3[i]+1) > 0:
ans += 1
print(ans)
|
import sys
sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7
class BIT:
def __init__(self, L):
self.n = len(L)
self.bit = [0] * (self.n + 1)
def update(self, idx, x):
while idx <= self.n:
self.bit[idx] += x
idx += idx & (-idx)
def query(self, idx):
res = 0
while idx > 0:
res += self.bit[idx]
idx -= idx & (-idx)
return res
def sec_sum(self, left, right):
return self.query(right) - self.query(left - 1)
def debug(self):
print(*[self.sec_sum(i, i) for i in range(1, self.n + 1)])
def resolve():
n = int(input())
S = list(input().rstrip())
q = int(input())
bits = [BIT(S) for _ in range(26)]
for idx in range(1, n + 1):
s = S[idx - 1]
bits[ord(s) - ord("a")].update(idx, 1)
for _ in range(q):
query = list(input().split())
if query[0] == "1":
i, c = int(query[1]), query[2]
prev = S[i - 1]
bits[ord(prev) - ord("a")].update(i, -1)
bits[ord(c) - ord("a")].update(i, 1)
S[i - 1] = c
else:
l, r = int(query[1]), int(query[2])
res = 0
for j in range(26):
if bits[j].sec_sum(l, r):
res += 1
print(res)
if __name__ == '__main__':
resolve()
| 1 | 62,107,785,558,592 | null | 210 | 210 |
def main():
n, k = map(int, input().split())
arr = list(map(int, input().split()))
L, R = 0, max(arr)
while L+1 < R:
P = (L+R+1)//2
cnt = 0
for a in arr:
if P < a:
if a % P == 0:
cnt += a//P - 1
else:
cnt += a//P
if cnt <= k:
R = P
else:
L = P
print(R)
if __name__ == "__main__":
main()
|
def selectionSort(a, n):
count = 0
for i in range(0, n):
minj = i
for j in range(i, n):
if a[j] < a[minj]:
minj = j
a[i], a[minj] = a[minj], a[i]
if i != minj:
count += 1
return count
def main():
n = int(input())
a = [int(x) for x in input().split(' ')]
count = selectionSort(a, n)
print(' '.join([str(x) for x in a]))
print(count)
if __name__ == '__main__':
main()
| 0 | null | 3,288,812,966,690 | 99 | 15 |
S,T = input().split()
print(T,S, sep='')
|
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
| 0 | null | 66,316,596,643,180 | 248 | 164 |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
check = list(map(int, readline().split()))
prize = [3 * 10 ** 5, 2 * 10 ** 5, 10 ** 5]
ans = 0
if check.count(1) == 2:
ans = 10 ** 6
else:
if check[0] <= 3:
ans += prize[check[0] - 1]
if check[1] <= 3:
ans += prize[check[1] - 1]
print(ans)
|
import numpy as np
n = int(input())
a = np.array(list(map(int,input().split())))
ans = np.argsort(a)
print(*ans + 1)
| 0 | null | 161,286,040,089,140 | 275 | 299 |
codePlace, implePlace = map(int, input().split(" "))
priceDict = {
1:300000,
2:200000,
3:100000
}
totalPrice = priceDict[codePlace] if codePlace in priceDict.keys() else 0
totalPrice += priceDict[implePlace] if implePlace in priceDict.keys() else 0
totalPrice += 400000 if codePlace == 1 and implePlace == 1 else 0
print(totalPrice)
|
n,m = map(int,input().split())
lis = [0]*205
lis[0] = 300000
lis[1] = 200000
lis[2] = 100000
if n == m and n == 1:
print(1000000)
else:
print(lis[n-1]+lis[m-1])
| 1 | 141,181,890,773,888 | null | 275 | 275 |
def examA():
N = I()
ans = (N-1)//2
print(ans)
return
def examB():
N = I()
D = LI()
d = Counter(D)
loop = max(d.keys())
if D[0]!=0 or d[0]!=1:
print(0)
return
# print(d,loop)
ans = 1; cur = 1
for i in range(loop+1):
if d[i]==0:
print(0)
return
for _ in range(d[i]):
ans *= cur
ans %= mod2
cur = d[i]
print(ans)
return
def examC():
ans = 0
print(ans)
return
def examD():
ans = 0
print(ans)
return
def examE():
ans = 0
print(ans)
return
def examF():
ans = 0
print(ans)
return
import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LFI(): return list(map(float,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]
if __name__ == '__main__':
examB()
"""
"""
|
def main():
n = int(input())
d = list(map(int,input().split()))
mod = 998244353
if d[0]!=0:
print(0)
return
D = {0:1}
for i in range(1,n):
if d[i]==0:
print(0)
return
if D.get(d[i]) == None:
D[d[i]] = 1
else:
D[d[i]] += 1
ans = 1
if sorted(D.keys())[-1]!=len(D.keys())-1:
print(0)
return
for k in range(1,len(D.keys())):
ans *= pow(D[k-1],D[k],mod)
ans = ans % mod
print(ans)
if __name__ == "__main__":
main()
| 1 | 155,026,362,139,650 | null | 284 | 284 |
s = input()
len_s = len(s)
s_array = [int(i) for i in s]
mod = 2019
mod_array = [0]*mod
num = 0
mod_array[0] += 1
for i in range(len_s):
num = pow(10, i, mod) * s_array[len_s - i - 1] + num
num %= mod
mod_array[num] += 1
ans = 0
for i in mod_array:
ans += (i * (i - 1)) / 2
print(int(ans))
|
def inN():
return int(input())
def inL():
return list(map(int,input().split()))
def inNL(n):
return [list(map(int,input().split())) for i in range(n)]
s = input()
n = int(s)
l = len(s)
cnt = 0
mod = [0]*2019
m = 0
for i in range(l):
m = (int(s[l-1-i])*pow(10,i,2019) + m)%2019
mod[m] += 1
cnt += mod[0]
for i in range(2019):
if mod[i] > 1:
cnt += (mod[i]*(mod[i]-1))/2
#print(i)
print(int(cnt))
| 1 | 30,883,992,705,152 | null | 166 | 166 |
n = [int(i) for i in input().split()]
print(max(n[0] - 2*n[1], 0))
|
from sys import stdin,stdout
def INPUT():return list(int(i) for i in stdin.readline().split())
import math
def inp():return stdin.readline()
def out(x):return stdout.write(x)
import math as M
MOD=10**9+7
import sys
#####################################
a,b=INPUT()
if a>=2*b:
print(a-2*b)
else:
print(0)
| 1 | 166,690,472,571,898 | null | 291 | 291 |
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15
def main():
K = int(input())
S = input()
M = len(S)
N = M + K
MAXN = N + 2
fact = [1]
for i in range(1,MAXN + 1):
fact.append(fact[-1]*i%MOD)
inv_fact = [-1] * (MAXN + 1)
inv_fact[-1] = pow(fact[-1],MOD - 2,MOD)
for i in range(MAXN - 1,-1,-1):
inv_fact[i] = inv_fact[i + 1]*(i + 1)%MOD
nck = lambda N,K: 0 if K > N or K < 0 else fact[N]*inv_fact[N - K]*inv_fact[K]%MOD
power25 = [1]
power26 = [1]
for i in range(N):
power25.append(power25[-1]*25%MOD)
power26.append(power26[-1]*26%MOD)
ans = 0
for i in range(M,N + 1):
ans += nck(i - 1,M - 1) * power25[i - M] * power26[N - i] % MOD
ans %= MOD
print(ans)
if __name__ == '__main__':
main()
|
import sys
n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
l, r = 0, max(a)
while r - l > 1:
# satisfy l < t < r
t = (l + r) // 2
c = sum([(e-1) // t for e in a])
if k < c:
l = t
else:
r = t
print(r)
| 0 | null | 9,676,059,822,656 | 124 | 99 |
A1, A2, A3 = map(int, input().split())
print("bust") if (A1+A2+A3)>=22 else print("win")
|
n = int(input())
d = [[0]*9 for _ in range(9)]
ans = 0
for num in range(1, n+1):
s = str(num)
x, y = int(s[0]), int(s[-1])
if x != 0 and y != 0:
d[x-1][y-1] += 1
for i in range(9):
k = -1
for j in range(9):
if i == j:
ans += pow(d[i][j], 2)
k = 1
elif k == 1:
ans += 2*d[i][j]*d[j][i]
print(ans)
| 0 | null | 102,638,326,671,744 | 260 | 234 |
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)
|
num = map(int,input().split())
s=sum(num)
print(15-s)
| 0 | null | 87,135,616,471,156 | 288 | 126 |
import heapq
K = int(input())
def NewLun(strX):
if strX[-1] != '0' and strX[-1] != '9':
intX0 = int(strX[-1])
heapq.heappush(Lun,int(strX + str(intX0+1)))
heapq.heappush(Lun,int(strX + str(intX0)))
heapq.heappush(Lun,int(strX + str(intX0-1)))
elif strX[-1] == '0':
heapq.heappush(Lun,int(strX + '0'))
heapq.heappush(Lun,int(strX+'1'))
else:
heapq.heappush(Lun,int(strX +'9'))
heapq.heappush(Lun,int(strX+'8'))
Lun = [i for i in range(1,10)]
heapq.heapify(Lun)
for _ in range(K):
Ans = heapq.heappop(Lun)
NewLun(str(Ans))
print(Ans)
|
print(input().find('0')//2+1)
| 0 | null | 26,753,000,794,048 | 181 | 126 |
N = int(input())
X = list(map(int, input().split()))
INF = 10**6 + 1
mintotal = INF
for p in range(1, 101):
total = 0
for x in X:
total += (x-p)**2
mintotal = min(mintotal, total)
print(mintotal)
|
#!/usr/bin/env python3
# from numba import njit
import sys
sys.setrecursionlimit(10**8)
# input = stdin.readline
# @njit
def solve(n,k,r,s,p,t):
winHand = {"r":"p", "s":"b", "p":"s"}
bestHandMemo = [""]*(n+1) # i手目の勝ち手
memo = [-1]*(n+1)
def calcPoint(char):
if char == "r":
return p
elif char == "s":
return r
elif char == "p":
return s
else:
raise ValueError
def dp(i):
if i == 0:
return 0
elif memo[i] != -1:
return memo[i]
elif i <= k:
bestHandMemo[i-1] = winHand[t[i-1]] # 自由に出せる
return dp(i-1) + calcPoint(t[i-1])
elif winHand[t[i-1]] == bestHandMemo[i-k-1]:
bestHandMemo[i-1] = "" # あいこでも負けても同じこと
return dp(i-1)
else: # 勝てる
bestHandMemo[i-1] = winHand[t[i-1]]
return dp(i-1) + calcPoint(t[i-1])
for i in range(n+1):
memo[i] = dp(i)
return memo[n]
def main():
N,K = map(int,input().split())
R,S,P = map(int,input().split())
T = input()
print(solve(N,K,R,S,P,T))
return
if __name__ == '__main__':
main()
| 0 | null | 85,978,483,587,360 | 213 | 251 |
n, p = [int(_) for _ in input().split()]
s = input()
if p == 2 or p == 5:
ans = 0
for i in range(n):
if int(s[i]) % p == 0:
ans += i+1
print(ans)
exit()
t = [0 for i in range(n+1)]
P = [0 for i in range(p)]
P[0] += 1
d = 1
for i in range(1, n+1):
t[i] = (t[i-1]+int(s[n-i])*d) % p
P[t[i]] += 1
d = d*10 % p
ans = 0
for c in P:
ans += c*(c-1)//2
# print(t)
print(ans)
|
import math
N = int(input())
lst = list(map(int, input().split()))
X = math.floor(sum(lst)/N + 0.5)
ans = 0
for i in lst:
ans = ans + (X - i)**2
print(ans)
| 0 | null | 61,917,582,263,850 | 205 | 213 |
h = int(input())
w = int(input())
n = int(input())
if h >= w:
print(-(-n//h))
elif w > h:
print(-(-n//w))
|
h,w,n = int(input()),int(input()),int(input())
ans = 0
s = 0
while s < n:
s += max(h,w)
ans += 1
print(ans)
| 1 | 88,784,875,704,992 | null | 236 | 236 |
import sys
sys.setrecursionlimit(10**9)
f=lambda:map(int,input().split())
n,st,sa=f()
st-=1
sa-=1
g=[[] for _ in range(n)]
for _ in range(n-1):
a,b=f()
g[a-1].append(b-1)
g[b-1].append(a-1)
def dfs(v,p=-1,d=0):
l[v]=d
for c in g[v]:
if c==p: continue
dfs(c,v,d+1)
def dist(s):
global l
l=[0]*n
dfs(s)
return l
lt=dist(st)
la=dist(sa)
m=0
for i in range(n):
if lt[i]<la[i]: m=max(m,la[i])
print(m-1)
|
def miller_rabin(n):
""" primality Test
if n < 3,825,123,056,546,413,051, it is enough to test
a = 2, 3, 5, 7, 11, 13, 17, 19, and 23.
Complexity: O(log^3 n)
"""
if n == 2: return True
if n <= 1 or not n&1: return False
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
d = n - 1
s = 0
while not d&1:
d >>= 1
s += 1
for prime in primes:
if prime >= n: break
x = pow(prime, d, n)
if x == 1: break
for r in range(s):
if x == n - 1: break
if r + 1 == s: return False
x = x * x % n
return True
N = int(input())
print(sum(1 for _ in range(N) if miller_rabin(int(input()))))
| 0 | null | 58,701,673,726,720 | 259 | 12 |
import bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
return sys.stdin.readline()[:-1]
def ruiseki(lst):
return [0]+list(accumulate(lst))
def celi(a,b):
return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]
x=int(input())
def is_prime(n):
if n == 1: return False
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
ans=x
while not is_prime(ans):
ans+=1
print(ans)
|
import math
X = int(input())
def is_prime(x):
a = int(math.sqrt(X)) + 1#ある数が素数かどうかはO(√A)で判定できる
for i in range(2,a):
if x % i == 0:
return False
return True#xは素数
for j in range(X,10**5+4):
if is_prime(j):
ans = j
break
print(ans)
| 1 | 105,270,750,962,480 | null | 250 | 250 |
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate, product, combinations_with_replacement
import sys
import bisect
import string
import math
import time
def I(): return int(input())
def S(): return input()
def MI(): return map(int, input().split())
def MS(): return map(str, input().split())
def LI(): return [int(i) for i in input().split()]
def LI_(): return [int(i)-1 for i in input().split()]
def StoI(): return [ord(i)-97 for i in input()]
def ItoS(nn): return chr(nn+97)
def input(): return sys.stdin.readline().rstrip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def print_matrix(mat):
for i in range(len(mat)):
print(*['IINF' if v == IINF else "{:0=4}".format(v) for v in mat[i]])
yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**19
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
show_flg = False
# show_flg = True
def main():
N = I()
X = S()
bit_cnt = X.count('1')
one_inv_cnt = bit_cnt - 1
zero_inv_cnt = bit_cnt + 1
MAX = 2 * 10 ** 5 + 1
# 大きい数の余り
# 繰り返し2乗法の発展?
zero_mod = 0
one_mod = 0
for i in range(0, len(X)):
b = int(X[i])
if one_inv_cnt != 0:
one_mod = (one_mod * 2 + b) % one_inv_cnt
zero_mod = (zero_mod * 2 + b) % zero_inv_cnt
f = [0] * MAX
for i in range(1, MAX):
f[i] = f[i % str(bin(i)).count('1')] + 1
for i in range(len(X)-1, -1, -1):
if X[N-1-i] == '1':
if one_inv_cnt != 0:
nxt = one_mod
nxt -= pow(2, i, one_inv_cnt)
nxt %= one_inv_cnt
print(f[nxt] + 1)
else:
print(0)
else:
nxt = zero_mod
nxt += pow(2, i, zero_inv_cnt)
nxt %= zero_inv_cnt
print(f[nxt] + 1)
if __name__ == '__main__':
main()
|
N = int(input())
X = input()
memo = {}
X_int = int(X, 2)
def popcount(n: int):
x = bin(n)[2:]
return x.count("1")
pcf = popcount(int(X, 2))
pcm = pcf - 1
pcp = pcf + 1
xm = X_int % pcm if pcm != 0 else 0
xp = X_int % pcp
def f(n: int, ops: int):
while n != 0:
n %= popcount(n)
ops += 1
return ops
def rev(x: str, i: int):
if x == "1":
if pcm == 0:
return -1
n = (xm - (pow(2, N-i-1, pcm))) % pcm
else:
n = (xp + (pow(2, N-i-1, pcp))) % pcp
return n
if __name__ == "__main__":
for i, x in enumerate(X):
n = rev(x, i)
if n == -1:
print(0)
else:
print(f(n, 1))
| 1 | 8,201,317,829,308 | null | 107 | 107 |
n = int(input())
for i in range(1,10):
if (n%i==0) and ((n//i) in range(1,10)):
print("Yes")
break
else:
print("No")
|
import sys
N = int(sys.stdin.readline())
for i in range(1, 10):
for j in range(1, 10):
if i * j == N:
print("Yes")
sys.exit()
print("No")
| 1 | 160,276,536,049,904 | null | 287 | 287 |
n=int(input())
a=list(map(int,input().split()))
ans=[0 for s in range(n)]
for i in range(n-1):
x = int(a[i])
ans[x-1] +=1
for j in range(n):
print(ans[j])
|
w = int(input())
h = w // 3600
m = (w % 3600) // 60
s = w % 60
print(f"{h}:{m}:{s}")
| 0 | null | 16,554,027,258,088 | 169 | 37 |
rooms = [0] * (4*3*10)
count = int(input())
for i in range(count):
b, f, r, v = [int(x) for x in input().split()]
rooms[30*(b-1) + 10*(f-1) + (r-1)] += v
for i, room in enumerate(rooms, start=1):
print('', room, end='')
if i%10 == 0:
print()
if i%30 == 0 and i%120 != 0:
print('#'*20)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 01:24:25 2020
@author: saito
"""
# %% import phase
# %% define phase
# %% input phase
N = int(input())
# %% process phase
answer = 1000-((N-1)%1000+1)
# %%output phase
print(answer)
| 0 | null | 4,788,820,281,652 | 55 | 108 |
from collections import deque
n = int(input())
my_list = deque()
for t in range(n):
i = input().split()
if i[0] == "insert":
my_list.appendleft(i[1])
elif i[0] == "delete" and i[1] in my_list:
my_list.remove(i[1])
elif i[0] == "deleteFirst":
my_list.popleft()
elif i[0] == "deleteLast":
my_list.pop()
print(" ".join(my_list))
|
from collections import deque
n = int(input())
d = deque()
for i in range(n):
x = input().split()
if x[0] == "insert":
d.appendleft(x[1])
elif x[0] == "delete":
if x[1] in d:
d.remove(x[1])
elif x[0] == "deleteFirst":
d.popleft()
elif x[0] == "deleteLast":
d.pop()
print(*d)
| 1 | 50,694,834,500 | null | 20 | 20 |
import math
a, b, n = map(int, input().split())
if n < b:
print(math.floor(a * n / b) - 5 * math.floor(n / b))
else:
print(math.floor(a * (b - 1) / b) - 5 * math.floor((b - 1) / b))
|
n, m, k = map(int, input().split())
a_books = [int(i) for i in input().split()]
b_books = [int(i) for i in input().split()]
time = 0
count = 0
for i in range(n):
time += a_books[i]
if time > k:
time -= a_books[i]
i -= 1
break
count += 1
for j in range(m):
time += b_books[j]
if time > k:
time -= b_books[j]
j -= 1
break
count += 1
max_count = count
#print(max_count, time)
while j < m and i >= 0:
time -= a_books[i]
i -= 1
count -= 1
j += 1
while j < m:
time += b_books[j]
if time > k:
time -= b_books[j]
j -= 1
break
count += 1
j += 1
if count > max_count:
max_count = count
#print(count, time)
#print(max_count)
print(max_count)
| 0 | null | 19,557,057,128,642 | 161 | 117 |
def insertion_sort(A, N):
for i in range(N):
v = A[i]
j = i - 1
while j >= 0 and A[j] > v:
A[j + 1] = A[j]
j -= 1
A[j + 1] = v
print(' '.join(map(str, A)))
def main():
N = int(input().rstrip())
A = list(map(int, input().rstrip().split()))
insertion_sort(A, N)
if __name__ == '__main__':
main()
|
def main():
A, B, C = (int(x) for x in input().split())
K = int(input())
while not A < B < C and K > 0:
if A >= B: B *= 2
else: C *= 2
K -= 1
# print(A, B, C, K)
if A < B < C: print('Yes')
else: print('No')
if __name__ == '__main__':
main()
| 0 | null | 3,471,427,938,528 | 10 | 101 |
n, q = map(int, input().split())
processes = [[li[0], int(li[1])] for li in [input().split() for _ in range(n)]]
elapsed_time = 0
while len(processes):
process = processes.pop(0)
if process[1] > q:
process[1] -= q
processes.append(process)
elapsed_time += q
else:
elapsed_time += process[1]
print(process[0], elapsed_time)
|
N = int(input())
n = 0
if not N%2:
s = 5
N = N//2
while N>=s:
n += N//s
s *= 5
print(n)
| 0 | null | 57,738,931,554,012 | 19 | 258 |
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")
import bisect
S = input()
if S == "SUN":
print(7)
elif 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)
|
#n = int(input())
#a, b = map(int,input().split())
#l = list(map(int,input().split()))
#l = [list(map(int,input().split())) for i in range(n)]
from collections import deque
# n = int(input())# ノードの数
n, m = map(int, input().split())
# 隣接リストで格納する
adjl = [[] for _ in range(n+1)]
for i in range(m): # 隣接関係を受け取る
a, b = map(int, input().split())
adjl[a].append(b)
adjl[b].append(a)
NIL = -1 # 未発見を示す値
d = [-1 for i in range(n+1)] # 頂点1からの距離を格納するリスト
color = [NIL for i in range(n+1)] # 未到達かを示すリスト
def bfs(start_node, color_id): # start_nodeは探索の開始点
global color, d
q = deque([start_node])
d[start_node] = 0
color[start_node] = color_id
while len(q) != 0:
u = q.popleft()
for v in adjl[u]:
if color[v] == NIL:
d[v] = d[u]+1
color[v] = color_id
q.append(v)
color_id = 0
for u in range(1, n+1): # node全てからスタートする
if color[u] == NIL:
color_id += 1
bfs(u, color_id)
colordic = {}
for u in range(1, n+1):
colordic[color[u]] = True
print(len(colordic)-1)
| 0 | null | 67,975,915,277,702 | 270 | 70 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.