code1
stringlengths 17
427k
| code2
stringlengths 17
427k
| similar
int64 0
1
| pair_id
int64 2
181,637B
⌀ | question_pair_id
float64 3.7M
180,677B
⌀ | code1_group
int64 1
299
| code2_group
int64 1
299
|
---|---|---|---|---|---|---|
n=int(input())
s=100000
for i in range(n):
s*=1.05
m = s % 1000
if m!=0:
s=s-m+1000
print(int(s))
| import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
s = S()
k = I()
same = len(set(list(s)))==1
ans = None
if same:
ans = len(s)*k//2
else:
if s[0]!=s[-1]:
cnt = 0
change = False
for i in range(1,len(s)):
if s[i] == s[i-1] and not change:
cnt += 1
change = True
else:
change = False
ans = cnt*k
else:
char = s[0]
start = len(s)
goal = -1
cnt = 0
while s[start-1] == char:
start -= 1
while s[goal+1] == char:
goal += 1
lenth = len(s)-start + goal+1
cnt += lenth//2 * (k-1)
ccnt = 0
change = False
for i in range(goal+1+1,start):
if s[i] == s[i-1] and not change:
ccnt += 1
change = True
else:
change = False
cnt += ccnt * (k-2)
ccnt = 0
change = False
for i in range(1,start):
if s[i] == s[i-1] and not change:
ccnt += 1
change = True
else:
change = False
cnt += ccnt
ccnt = 0
change = False
for i in range(goal+1+1, len(s)):
if s[i] == s[i-1] and not change:
ccnt += 1
change = True
else:
change = False
cnt += ccnt
ans = cnt
print(ans)
main()
| 0 | null | 87,345,798,376,496 | 6 | 296 |
N = int(input())
tracks = [tuple(input().split()) for _ in range(N)]
X = input()
sleep = False
ans = 0
for s, t in tracks:
t = int(t)
if sleep:
ans += t
if s == X:
sleep = True
print(ans) | import sys, bisect, math, itertools, heapq, collections
from operator import itemgetter
# a.sort(key=itemgetter(i)) # i番目要素でsort
from functools import lru_cache
# @lru_cache(maxsize=None)
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = float('inf')
mod = 10**9 + 7
eps = 10**-7
def inp():
'''
一つの整数
'''
return int(input())
def inpl():
'''
一行に複数の整数
'''
return list(map(int, input().split()))
class combination():
def __init__(self, mod):
'''
modを指定して初期化
'''
self.mod = mod
self.fac = [1, 1] # 階乗テーブル
self.ifac = [1, 1] # 階乗の逆元テーブル
self.inv = [0, 1] # 逆元計算用
def calc(self, n, k):
'''
nCk%modを計算する
'''
if k < 0 or n < k:
return 0
self.make_tables(n) # テーブル作成
k = min(k, n - k)
return self.fac[n] * (self.ifac[k] * self.ifac[n - k] %
self.mod) % self.mod
def make_tables(self, n):
'''
階乗テーブル・階乗の逆元テーブルを作成
'''
for i in range(len(self.fac), n + 1):
self.fac.append((self.fac[-1] * i) % self.mod)
self.inv.append(
(-self.inv[self.mod % i] * (self.mod // i)) % self.mod)
self.ifac.append((self.ifac[-1] * self.inv[-1]) % self.mod)
comb = combination(mod)
n, k = inpl()
ans = 0
# m個の0人の部屋を作る
for m in range(min(n, k + 1)):
# n個の部屋からm個の0人の部屋を選ぶ
a = comb.calc(n, m) % mod
# n個の部屋にm人を自由に割り当てる
b = comb.calc(n - 1, n - m - 1) % mod
ans += a * b % mod
print(ans % mod)
| 0 | null | 82,000,459,922,872 | 243 | 215 |
n = int(input())
p = list(map(int, input().split()))
m = p[0]
ans = 0
for i in p:
if (m >= i):
ans += 1
m = min(i,m)
print(ans) | #!/usr/bin/env python3
N = int(input())
if N % 2 == 1:
print(0)
else:
ret = 0
for i in range(1, 27):
ret += N // (2*5**i)
print(ret)
| 0 | null | 100,958,745,374,018 | 233 | 258 |
n = int(input())
dictionary = {}
for i in range(n):
a = input().split()
if a[0] == "insert":
dictionary[a[1]] = 0
if a[0] == "find":
if a[1] in dictionary:
print("yes")
else:
print("no") | import sys
input()
rl = sys.stdin.readlines()
d = {}
for i in rl:
c, s = i.split()
#if i[0] == 'i':
if c[0] == 'i':
#d[i[7:]] = 0
d[s] = 0
else:
#if i[5:] in d:
if s in d:
print('yes')
else:
print('no') | 1 | 77,730,579,708 | null | 23 | 23 |
def main():
s, w = map(int, input().split())
if s <= w:
ans = 'unsafe'
else:
ans = 'safe'
print(ans)
if __name__ == "__main__":
main()
| n = int(input())
l = list(map(int,input().split()))
mod = 10**9+7
ones = [0]*60
ans = 0
for i in range(n):
x = l[i]
for j in range(60):
ones[j] += (x>>j)&1
ans = (ans + (n-1)*x)%mod
# print(ans)
for i in range(60):
ans = (ans - ones[i]*(ones[i]-1)*2**i)%mod
print(ans) | 0 | null | 75,711,918,775,388 | 163 | 263 |
input_line = input()
l = input_line.split()
if int(l[0]) < int(l[1]) < int(l[2]):
print("Yes")
else:
print("No") | x=raw_input()
list=x.split()
a=int(list[0])
b=int(list[1])
c=int(list[2])
if a<b<c:
print 'Yes'
else:
print 'No' | 1 | 384,876,176,722 | null | 39 | 39 |
def resolve():
X, Y, Z = list(map(int, input().split()))
print(Z, X, Y)
if '__main__' == __name__:
resolve() | import sys
sys.setrecursionlimit(10**6)
N, u, v = map(int, input().split())
tree = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, input().split())
tree[a-1].append(b-1)
tree[b-1].append(a-1)
#print(tree)
def calc_dist(dlist, n, dist, nnode):
for c in tree[n]:
if c == nnode:
continue
dlist[c] = dist
calc_dist(dlist, c, dist+1, n)
u_dist_list = [0] * N
calc_dist(u_dist_list, u-1, 1, -1)
#print(u_dist_list)
v_dist_list = [0] * N
calc_dist(v_dist_list, v-1, 1, -1)
#print(v_dist_list)
ans = 0
for i in range(N):
if (v_dist_list[i] - u_dist_list[i]) > 0 and v_dist_list[i] > ans:
ans = v_dist_list[i] - 1
print(ans) | 0 | null | 77,635,479,671,050 | 178 | 259 |
S = input()
result = 0
if "R" in S:
if "RR" in S:
result = S.count("R")
else:
result = 1
print(result)
| lst = list(input())
tmp = 0
ans = 0
for i in lst:
if i == "R":
tmp = tmp + 1
ans = max(ans, tmp)
else:
tmp = 0
print(ans) | 1 | 4,862,516,606,750 | null | 90 | 90 |
def main():
import sys
input=sys.stdin.readline
s,w=map(int,input().split())
if s<=w:
print("unsafe")
else:
print("safe")
if __name__ == '__main__':
main() | import copy
def main():
h, o = map(int, input().split(' '))
if h <= o:
print('unsafe')
else:
print('safe')
main() | 1 | 29,157,695,586,402 | null | 163 | 163 |
def resolve():
from scipy.sparse.csgraph import floyd_warshall
import numpy as np
import sys
input = sys.stdin.readline
n, m, l = map(int, input().split())
inf = 10 ** 20
ar = [[0] * n for _ in range(n)]
for _ in range(m):
a, b, c = map(int, input().split())
ar[a - 1][b - 1] = c
ar[b - 1][a - 1] = c
x = floyd_warshall(ar)
br = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
if x[i, j] <= l:
br[i][j] = 1
br[j][i] = 1
y = floyd_warshall(br)
q = int(input())
for _ in range(q):
s, t = map(int, input().split())
p = y[s - 1, t - 1]
print(int(p) - 1 if p < inf else -1)
if __name__ == "__main__":
resolve()
| import sys
input = sys.stdin.readline
def main():
N, M = map(int, input().split())
S = input()
ans = []
check = [False] * (N+1)
idx = N
while 0 < idx:
f = False
for i in range(M, 0, -1):
if idx-i < 0: continue
if S[idx-i] == '1':
if check[idx-i]: print(-1); sys.exit()
else: check[idx-i] = True
else:
ans.append(i)
idx -= i
f = True
break
if not f: print(-1); sys.exit()
for a in ans[::-1]: print(a)
if __name__ == '__main__':
main() | 0 | null | 156,667,494,946,820 | 295 | 274 |
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
ls = list(itertools.permutations(range(1, n + 1)))
print(abs(ls.index(p) - ls.index(q))) | def getval():
h,n = map(int,input().split())
m = [list(map(int,input().split())) for i in range(n)]
return h,n,m
def main(h,n,m):
#DP for minimal mp needed to do h damage
dp = [0]
for i in range(h):
update = 2**60
for j in m:
if j[0]>=(i+1):
update = min(update,j[1])
else:
update = min(update,j[1]+dp[i+1-j[0]])
dp.append(update)
print(dp[h])
if __name__=="__main__":
h,n,m = getval()
main(h,n,m) | 0 | null | 90,839,069,227,452 | 246 | 229 |
#
# abc145 c
#
import sys
from io import StringIO
import unittest
import math
import itertools
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, stdin
self.assertEqual(out, output)
def test_入力例_1(self):
input = """3
0 0
1 0
0 1"""
output = """2.2761423749"""
self.assertIO(input, output)
def test_入力例_2(self):
input = """2
-879 981
-866 890"""
output = """91.9238815543"""
self.assertIO(input, output)
def test_入力例_3(self):
input = """8
-406 10
512 859
494 362
-955 -475
128 553
-986 -885
763 77
449 310"""
output = """7641.9817824387"""
self.assertIO(input, output)
def resolve():
N = int(input())
P = [list(map(int, input().split())) for _ in range(N)]
R = itertools.permutations(range(N))
all = 0
for r in R:
for pi in range(1, len(r)):
all += math.sqrt((P[r[pi]][0]-P[r[pi-1]][0])**2 +
(P[r[pi]][1]-P[r[pi-1]][1])**2)
n = 1
for i in range(1, N+1):
n *= i
print(f"{all/n:.10f}")
if __name__ == "__main__":
# unittest.main()
resolve()
| N = int(input())
X = input()
val = int(X,2)
C = X.count("1")
if C==1:
for i in range(N):
if X[i]=='1':
print(0)
elif i==N-1:
print(2)
else:
print(1)
exit()
# xをpopcountで割ったあまりに置き換える
def f(x):
if x==0: return 0
return 1 + f(x % bin(x).count("1"))
# 初回のpopcountでの割り方は、(C+1) or (C-1)
Y = val%(C+1)
if C-1 != 0:
Z = val%(C-1)
else:
Z = 0
for i in range(N):
if X[i] == "1":
if Z - 1 == 0:
print(0)
continue
k = (Z - pow(2,N-i-1,C-1)) % (C-1)
else:
k = (Y + pow(2,N-i-1,C+1)) % (C+1)
print(f(k)+1) | 0 | null | 78,657,739,623,260 | 280 | 107 |
# walking takahashi
def walk(X, K, D):
abX = abs(X)
if abX >= K*D:
return abX - K*D
itr = round(abX/D)
ret = K - itr
res = abs(abX - D*itr)
if (ret % 2) == 0:
return res
return abs(res - D)
if __name__ == "__main__":
inputs = list(map(int, input().split()))
print(walk(inputs[0], inputs[1], inputs[2]))
| while True:
a,op,b=raw_input().split()
if op == "?":break
if op == "+":print int(a) + int(b)
if op == "-":print int(a) - int(b)
if op == "*":print int(a) * int(b)
if op == "/":print int(a) / int(b) | 0 | null | 2,970,195,223,360 | 92 | 47 |
X, K, D = map(int, input().split())
X = abs(X)
div, mod = divmod(X, D)
if X > D * K:
ans = X - D * K
elif (K - div) % 2 == 0:
ans = mod
else:
ans = D - mod
print(ans) | # D - Alter Altar
N = int(input())
c = input()
white_l = 0
red_r = 0
for i in range(N):
if c[i]=='R':
red_r += 1
ans = red_r
for i in range(N):
if c[i]=='W':
white_l += 1
else:
red_r -= 1
ans = min(ans, max(red_r,white_l))
print(ans) | 0 | null | 5,766,788,796,902 | 92 | 98 |
N=int(input())
L=list(map(int,input().split()))
A=1
if 0 in L:
print(0)
exit()
for i in range(N):
A=A*L[i]
if 10**18<A:
print(-1)
exit()
if 10**18<A:
print(-1)
else:
print(A) | N = int(input())
line = [int(i) for i in input().split()]
sum = 1
line.sort(reverse=True)
if line[len(line) -1]== 0:
print(0)
exit()
for num in line:
sum = sum * num
if sum > 10 ** 18:
print(-1)
exit()
print(sum) | 1 | 16,170,313,815,722 | null | 134 | 134 |
# ai の大きい方から左端か右端
# はるかに問題なのはそこから先だがDP
n=int(input())
*a,=map(int, input().split( ))
dp = [0]
#周回が総数、dpのindexが左に置いた数
aii = [(ai,i) for i,ai in enumerate(a)]
aii.sort(key= lambda x:-x[0])
for j,(ai,i) in enumerate(aii):
dp2 = [0]*(j+2)
dp2[0]=dp[0]+ai*abs(n-j-1-i)
dp2[-1]=dp[-1]+ai*abs(j-i)
for k in range(j):
dp2[k+1] = max(dp[k]+ai*abs(k-i), dp[k+1]+ai*abs((n-(j-k-1)-1)-i))##abs((n-(j-k-1)-1)-i)
dp = dp2
print(max(dp)) | import sys
try:
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
input = sys.stdin.readline
n = int(input())
arr = list(map(int,input().split()))
arr = list(enumerate(arr))
arr.sort(reverse = True, key = lambda x:(x[1]))
dp = [[0 for c in range(n+1)] for r in range(n+1)]
ans = 0
for r in range(n+1):
st = r-1
for c in range(n+1-r):
if r==c==0:
pass
elif r-1<0:
dp[r][c] = dp[r][c-1] + ( arr[st][1] * abs((arr[st][0]+1) - (n+1-c)) )
elif c-1<0:
dp[r][c] = dp[r-1][c] + ( arr[st][1] * abs((arr[st][0]+1) - r) )
else:
dp[r][c] = max( dp[r-1][c] + ( arr[st][1] * abs((arr[st][0]+1) - r) ),
dp[r][c-1] + ( arr[st][1] * abs((arr[st][0]+1) - (n+1-c)) )
)
ans = max(ans, dp[r][c])
st += 1
print(ans) | 1 | 33,585,987,663,888 | null | 171 | 171 |
from sys import stdin, stdout
n,k=map(int,input().split())
a=[int(o) for o in input().split()]
prod=1
for i in range(k,n):
prev=a[i-k]
if a[i]>prev: stdout.write("Yes\n")
else: stdout.write("No\n")
| from sys import stdin,stdout
n,k=map(int,stdin.readline().split())
a=list(map(int,stdin.readline().split()))
for i in range(k,n):
print('Yes' if a[i]>a[i-k] else 'No') | 1 | 7,141,412,333,902 | null | 102 | 102 |
input();print(*input().split()[::-1])
| def i():
return int(input())
def i2():
return map(int,input().split())
def s():
return str(input())
def l():
return list(input())
def intl():
return list(int(k) for k in input().split())
n = i()
a = intl()
for i in range(n):
if a[i]%2 == 0:
if a[i]%3 != 0 and a[i]%5 !=0:
print("DENIED")
exit()
print("APPROVED") | 0 | null | 34,823,548,473,280 | 53 | 217 |
n = int(input())
a = list(map(int,input().split()))
t=0
for i in a:
t = t ^ i
ans = []
for i in a:
ans.append(t ^ i)
print(" ".join(str(i) for i in ans)) | N = int(input())
alphas = list(map(int, input().split()))
all_xor = alphas[0] ^ alphas[1]
for i in range(2, N):
all_xor = all_xor ^ alphas[i]
ans_list = []
for i in range(N):
num_i = all_xor ^ alphas[i]
ans_list.append(str(num_i))
ans = " ".join(ans_list)
print(ans) | 1 | 12,453,996,585,360 | null | 123 | 123 |
import copy
class Dice:
def __init__(self, numbers):
self.dd = dict(zip(['U', 'S', 'E', 'W', 'N', 'B'], numbers))
def next(self, o):
old = copy.deepcopy(self.dd)
if o == 'E':
self.dd['B'] = old['E']
self.dd['U'] = old['W']
self.dd['E'] = old['U']
self.dd['W'] = old['B']
elif o == 'S':
self.dd['B'] = old['S']
self.dd['U'] = old['N']
self.dd['S'] = old['U']
self.dd['N'] = old['B']
elif o == 'W':
self.dd['B'] = old['W']
self.dd['U'] = old['E']
self.dd['E'] = old['B']
self.dd['W'] = old['U']
elif o == 'N':
self.dd['B'] = old['N']
self.dd['U'] = old['S']
self.dd['S'] = old['B']
self.dd['N'] = old['U']
dn = [int(n) for n in input().split()]
op = input()
ad = Dice(dn)
for o in op:
ad.next(o)
print(ad.dd['U']) | n=int(input())
a=1
b=1
i=0
while i<n:
a,b=b,a+b
i+=1
print(a)
| 0 | null | 115,192,848,760 | 33 | 7 |
n = int(input())
a = list(map(int, input().split()))
cnt = [0] * (10 ** 6 + 1)
a.sort()
ans = 0
for i in a:
cnt[i] += 1
a = set(a)
for k in a:
for l in range(k * 2, (10 ** 6 + 1), k):
cnt[l] += 1
for m in a:
if cnt[m] == 1:
ans += 1
print(ans) | n = int(input()) % 10
if n == 3:
print('bon')
elif n == 0 or n == 1 or n == 6 or n == 8:
print('pon')
else:
print('hon') | 0 | null | 16,723,928,230,630 | 129 | 142 |
import math
r = float(raw_input())
print "{0:.10f} {1:.10f}".format(r*r*math.pi, 2*r*math.pi) | if __name__ == "__main__":
from decimal import Decimal
r = Decimal(raw_input())
pi = Decimal("3.14159265358979")
print "{0:.6f} {1:.6f}".format( r * r * pi, 2 * r * pi) | 1 | 628,191,315,970 | null | 46 | 46 |
n = int(input())
a = list(map(int, input().split()))
tmp = 0
sum = 0
for i in a:
if tmp > i:
dif = tmp - i
sum += dif
else:
tmp = i
print(sum)
| import bisect
N = int(input())
L = list(map(int, input().split()))
L.sort()
ans = 0
for i in range(N-1, 1, -1):
for j in range(i-1, 0, -1):
a, b = L[i], L[j]
c = a - b + 1
if c > b: continue
ans += (j - bisect.bisect_left(L, c))
print(ans) | 0 | null | 87,954,851,483,380 | 88 | 294 |
import collections
#nを素因数分解したリストを返す
def prime_decomposition(n):
i = 2
table = []
while i * i <= n:
while n % i == 0:
n //= i
table.append(i)
i += 1
if n > 1:
table.append(n)
return table
N = int(input())
if N == 1:
print(0)
else:
A = prime_decomposition(N)
c = collections.Counter(A)
values, counts = zip(*c.most_common())
cnt = 0
for i in range(len(counts)):
for j in range(10,0,-1):
if counts[i] >= j * (j + 1)//2:
cnt += j
break
print(cnt) | # -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from collections import deque
from functools import lru_cache
import bisect
import re
import queue
import copy
import decimal
class Scanner():
@staticmethod
def int():
return int(sys.stdin.readline().rstrip())
@staticmethod
def string():
return sys.stdin.readline().rstrip()
@staticmethod
def map_int():
return [int(x) for x in Scanner.string().split()]
@staticmethod
def string_list(n):
return [Scanner.string() for i in range(n)]
@staticmethod
def int_list_list(n):
return [Scanner.map_int() for i in range(n)]
@staticmethod
def int_cols_list(n):
return [Scanner.int() for i in range(n)]
def pop_count(x):
x = x - ((x >> 1) & 0x5555555555555555)
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
x = x + (x >> 32)
return x & 0x0000007f
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
return (a * b) // gcd(a, b)
MOD = 10**9 + 7
def solve():
N = Scanner.int()
A = Scanner.map_int()
l = 1
for a in A:
l = lcm(a, l)
ans = 0
for a in A:
ans += l // a
ans %= MOD
print(ans)
def main():
# sys.setrecursionlimit(1000000)
# sys.stdin = open("sample.txt")
# T = Scanner.int()
# for _ in range(T):
# solve()
# print('YNeos'[not solve()::2])
solve()
if __name__ == "__main__":
main()
| 0 | null | 52,259,252,535,540 | 136 | 235 |
def find_primes(n):
ps = []
t = [True] * n
t[0] = t[1] = False
for i in range(2, n):
if not t[i]:
continue
ps.append(i)
for j in range(i, n, i):
t[j] = False
return ps
def solve(string):
n = int(string)
if n == 1:
return "0"
rn = int(n**0.5 + 1)
ps = find_primes(rn)
ans = 0
for i in ps:
k = 1
while n % (i**k) == 0:
ans += 1
n //= i**k
k += 1
return str(ans + (n >= rn))
if __name__ == '__main__':
import sys
print(solve(sys.stdin.read().strip()))
| N=int(input())
*A,=map(int, input().split())
M=10**3
P=[]
isp=[True]*M
for n in range(2,M):
if isp[n]==False: continue
P.append(n)
for m in range(n*n, M, n):
isp[m]=False
from collections import defaultdict
D=[defaultdict(int) for _ in range(N)]
for i in range(N):
a=A[i]
for p in P:
while a>1:
if a%p==0:
D[i][p]+=1
a//=p
else:
break
else:
break
if a>1:
D[i][a]+=1
d=defaultdict(int)
for i in range(N):
for k,v in D[i].items():
d[k] = max(d[k], v)
gcd=1
for k,v in d.items():
gcd*=k**v
print(sum([gcd//a for a in A])%(10**9+7))
| 0 | null | 52,294,895,385,314 | 136 | 235 |
ini = lambda : int(input())
inm = lambda : map(int,input().split())
inl = lambda : list(map(int,input().split()))
gcd = lambda x,y : gcd(y,x%y) if x%y else y
n,k = inm()
p = inl()
p = sorted(p)
print(sum(p[:k]))
| def main():
N, K = map(int, input().split())
*P, = map(int, input().split())
P.sort()
print(sum(P[:K]))
if __name__ == '__main__':
main()
| 1 | 11,718,544,442,968 | null | 120 | 120 |
import sys
while (True):
L = map(int, sys.stdin.readline().split())
if L:
(a, b) = L
c = a + b
cnt = 1
while (c >= 10):
c /= 10
cnt += 1
print cnt
else:
break | while True:
try:
a,b = map(int, input().split())
d = 0
s = sum([a,b])
while (s):
s //= 10
d += 1
print(d)
except EOFError: break
| 1 | 103,173,760 | null | 3 | 3 |
import sys, math
from itertools import permutations, combinations, accumulate
from collections import defaultdict, Counter, deque
from math import factorial#, gcd
from bisect import bisect_left #bisect_left(list, value)
sys.setrecursionlimit(10**7)
enu = enumerate
MOD = 10**9+7
def input(): return sys.stdin.readline()[:-1]
def pri(x): print('\n'.join(map(str, x)))
N = int(input())
G = [list(map(int, input().split())) for _ in range(N)]
c = [0]*N # 0:not found, 1:found, 2:finished
res = [[0]*2 for _ in range(N)]
time = 1
def dfs(index):
# print('index:', index)
global time
if c[index]==0:
c[index]=1
res[index][0] = time # found
time += 1
elif c[index]==1:
return
elif c[index]==2:
return
u, k, *v = G[index]
for node in v:
dfs(node-1) # 1-index -> 0-index
c[index] = 2
res[index][1] = time # finished
time += 1
return
for i in range(N):
dfs(i)
res = [[val1]+val2 for val1, val2 in zip(list(range(1, N+1)), res)]
for val in res:
print(*val)
| from collections import deque
N=int(input())
color=["w"]*(N+1)
start=[None]*(N+1)
finish=[0]*(N+1)
rinsetu=[[] for i in range(N+1)]
for i in range(1,N+1):
a=list(map(int,input().split()))
a=a[2:]
rinsetu[i]=a
def dfs(i,t):
if color[i]=="w":
t+=1
start[i]=t
color[i]="g"
for j in rinsetu[i]:
t=dfs(j,t)
t+=1
finish[i]=t
return t
else:return t
t=dfs(1,0)
while(None in start[1:]):
a=start[1:].index(None)
t=dfs(a+1,t)
for i in range(1,N+1):
print("%d %d %d" %(i,start[i],finish[i]))
| 1 | 3,071,493,660 | null | 8 | 8 |
A,B =map(int,input().split())
if A-B == 0:
print("a == b")
elif A >= B:
print("a > b")
else:
print("a < b")
| import sys
(a, b) = [int(i) for i in sys.stdin.readline().split()]
if a < b:
print("a < b")
elif a > b:
print("a > b")
else:
print("a == b") | 1 | 353,740,386,738 | null | 38 | 38 |
n=int(input())
ans=0
for x in range(1,n+1):
b=n//x
c=x*b
ans1=(x+c)*b//2
ans+=ans1
print(ans)
| N = int(input())
print(int(N**2)) | 0 | null | 78,429,193,266,550 | 118 | 278 |
n, m = map(int, input().split())
total = sum(list(map(int, input().split())))
if n - total >= 0:
print(n-total)
else:
print("-1") | n, m = input().split()
a = list(map(int, input().split()))
s = 0
for i in a:
s += int(i)
if int(s) <= int(n):
print(int(n) - int(s))
else:
print("-1") | 1 | 31,823,545,715,328 | null | 168 | 168 |
S,T = input().split()
A,B = map(int, input().split())
U = input()
ans=0
if U==S:
ans=A-1,B
else:
ans=A,B-1
print(' '.join(map(str,ans))) | import bisect, collections, copy, heapq, itertools, math, string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int, sys.stdin.readline().rstrip().split())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
N =I()
if N % 2 == 0:
print(N // 2)
else:
print(N // 2 + 1)
if __name__ == "__main__":
main() | 0 | null | 65,112,201,577,540 | 220 | 206 |
import sys
input = sys.stdin.readline
import collections
# 持っているビスケットを叩き、1枚増やす
# ビスケット A枚を 1円に交換する
# 1円をビスケット B枚に交換する
def main():
s = input().strip()
q = int(input())
flg = True
deq = collections.deque(s)
for i in range(q):
t = input_list_str()
if len(t) == 1:
n = t[0]
flg = False if flg is True else True
else:
n, f, c = t
c = str(c).strip()
if f == '1':
if flg:
deq.appendleft(c)
else:
deq.append(c)
else:
if flg:
deq.append(c)
else:
deq.appendleft(c)
if flg is False:
deq.reverse()
print(''.join(deq))
def bi(num, a, b, x):
print((a * num) + (b * len(str(b))))
if (a * num) + (b * len(str(b))) <= x:
return False
return True
def input_list():
return list(map(int, input().split()))
def input_list_str():
return list(map(str, input().split()))
if __name__ == "__main__":
main()
| import sys
n = int(input())
A=[int(e)for e in sys.stdin]
cnt = 0
G = [int((3**i-1)/2)for i in range(14,0,-1)]
G = [v for v in G if v <= n]
def insertionSort(A, n, g):
global cnt
for i in range(g, n):
v = A[i]
j = i - g
while j >= 0 and A[j] > v:
A[j+g] = A[j]
j = j - g
cnt += 1
A[j+g] = v
for g in G:
insertionSort(A, n, g)
print(len(G))
print(*G)
print(cnt)
print(*A,sep='\n')
| 0 | null | 28,552,160,534,768 | 204 | 17 |
import itertools
import functools
import math
from collections import Counter
from itertools import combinations
N=int(input())
print((N+1)//2)
| from collections import deque
N = int(input())
# 有向グラフと見る、G[親] = [子1, 子2, ...]
G = [[] for _ in range(N + 1)]
# 子ノードを記録、これで辺の番号を管理
G_order = []
# a<bが保証されている、aを親、bを子とする
for i in range(N - 1):
a, b = map(lambda x: int(x) - 1, input().split())
G[a].append(b)
G_order.append(b)
# どこでも良いが、ここでは0をrootとする
que = deque([0])
# 各頂点と「親」を結ぶ辺の色
# 頂点0をrootとするのでC[0]=0で確定(「無色」), 他を調べる
colors = [0] * N
# BFS
while que:
# prt = 親
# 幅優先探索
prt = que.popleft()
color = 0
# cld = 子
for cld in G[prt]:
color += 1
# 「今考えている頂点とその親を結ぶ辺の色」と同じ色は使えないので次の色にする
if color == colors[prt]:
color += 1
colors[cld] = color
que.append(cld)
# それぞれの頂点とその親を結ぶ辺の色
# print(colors)
# 必要な最小の色数
print(max(colors))
# 辺の番号順に色を出力
for i in G_order:
print(colors[i])
| 0 | null | 97,960,353,239,420 | 206 | 272 |
# AOJ ITP1_9_C
def numinput():
a = input().split()
for i in range(len(a)):
a[i] = int(a[i])
return a
def main():
SCORE_taro = 0
SCORE_hanako = 0
n = int(input())
for i in range(n):
words = input().split()
if words[0] > words[1]: SCORE_taro += 3
elif words[0] < words[1]: SCORE_hanako += 3
else:
SCORE_taro += 1; SCORE_hanako += 1
print(str(SCORE_taro) + " " + str(SCORE_hanako))
if __name__ == "__main__":
main()
| n = int(input())
a, b = 0, 0
for i in range(n):
s1, s2 = input().split()
if s1 > s2:
a += 3
elif s1 == s2:
a += 1
b += 1
else:
b += 3
print('{0} {1}'.format(a, b)) | 1 | 1,973,161,715,140 | null | 67 | 67 |
import os, sys, re, math
N = int(input())
print(((N + 1) // 2) / N)
| from _collections import deque
from _ast import Num
def parser():
while 1:
data = list(input().split(' '))
for number in data:
if len(number) > 0:
yield (number)
input_parser = parser()
def gw():
global input_parser
return next(input_parser)
def gi():
data = gw()
return int(data)
MOD = int(1e9 + 7)
import numpy
from collections import deque
from math import sqrt
from math import floor
# https://atcoder.jp/contests/abc145/tasks/abc145_e
# E - All-you-can-eat
"""
DP1[i][j] =the maximum sum of deliciousness of dishes, which are chosen from 1st- to i-th dishes,
such that he can finish them in j minutes
still WA!!!
"""
t1 = gi()
t2 = gi()
a1 = gi()
a2 = gi()
b1 = gi()
b2 = gi()
if a1 < b1:
a1, b1 = b1, a1
a2, b2 = b2, a2
#print(a1, a2, b1, b2)
d1 = (a1 - b1) * t1
d2 = (a2 - b2) * t2
net = d1 + d2
def run():
if d1 == 0 or net == 0:
print('infinity')
return
elif net > 0:
print(0)
return
d = abs(net)
ans = 0
p2 = (d1 // d)
if (d1 % d == 0):
ans = 2 * p2
else:
ans = 2 * p2 + 1
print(ans)
run()
| 0 | null | 154,177,087,504,790 | 297 | 269 |
a = int(input())
b = int(input())
ans = {1,2,3} - {a,b}
print(ans.pop()) | m1,_ = input().split()
m2,_ = input().split()
ans = 0
if m1 != m2:
ans = 1
print(ans) | 0 | null | 117,632,919,726,166 | 254 | 264 |
input();print(*input().split()[::-1])
| N = int(input().rstrip())
A = list(map(int, input().rstrip().split()))
flag = True
c = 0
while flag:
flag = False
for j in reversed(range(1, N)):
if A[j - 1] > A[j]:
A[j - 1], A[j] = A[j], A[j - 1]
c += 1
flag = True
print(' '.join(map(str, A)))
print(c) | 0 | null | 513,468,516,538 | 53 | 14 |
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal
def input():
x=sys.stdin.readline()
return x[:-1] if x[-1]=="\n" else x
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False):
inds=sorted(range(len(s)), key=lambda k: s[k])
if return_sorted: return inds, [s[i] for i in inds]
return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
K,N,M=len(B),len(A),len(B[0])
return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
N,size=len(v),len(M)
return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
n,m=len(M),len(M[0])
return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
mod = 1000000007
#w.sort(key=itemgetter(1),reversed=True) #二個目の要素で降順並び替え
N = input()
K= int(input())
#N, K = map(int, input().split())
#A = tuple(map(int, input().split())) #1行ベクトル
#L = tuple(int(input()) for i in range(N)) #改行ベクトル
#S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
keta=100+1
dp=[[0]*(keta+1) for _ in range(keta+1)]
dp[0][0]=1
for i in range(1,keta+1):
for j in range(0,i+1):
dp[i][j]+=dp[i-1][j]+dp[i-1][j-1]*9
l=len(N)
cur0=0
tot=0
for i,si in enumerate(N):
n=int(si)
if n!=0:
tot+=(n-1)*dp[l-1-i][K-i-1+cur0]+dp[l-1-i][K-i+cur0]
else:
cur0+=1
ic=0
for s in N:
if s!='0':ic+=1
if ic==K:tot+=1
print(tot)
if __name__ == "__main__":
main() | from numpy import*
n,m,*a=int_(open(0).read().split())
a=int_(fft.irfft(fft.rfft(bincount(a,[1]*n,2**18))**2)+.5)
c=0
for i in where(a>0)[0][::-1]:
t=min(m,a[i])
c+=i*t
m-=t
if m<1:break
print(c) | 0 | null | 91,938,235,657,742 | 224 | 252 |
N, M = map(int, input().split())
pena= 0
ac = [0]*(10**5)
for _ in range(M):
tmp = input().split()
if ac[int(tmp[0])-1] < 1:
if tmp[1] == "AC":
pena -= ac[int(tmp[0])-1]
ac[int(tmp[0])-1] = 1
else: ac[int(tmp[0])-1] -= 1 #penalty
print(ac.count(1), pena) | S = input()
T = input()
lens = len(S)
lent = len(T)
ans = lent
for i in range(lens - lent + 1):
count = 0
for j in range(lent):
if S[i+j] != T[j]:
count = count + 1
if count < ans:
ans = count
print(ans)
| 0 | null | 48,286,064,099,512 | 240 | 82 |
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1:
arr.append([temp, 1])
if arr==[]:
arr.append([n, 1])
return arr
def countstep(a):
i = 0
while a>=i+1:
i += 1
a -= i
return i
def main():
n = int(input())
a = factorization(n)
if n==1:
print(0)
return
if a[0][0]==0:
print(0)
else:
count = 0
for i in range(len(a)):
count += countstep(a[i][1])
print(count)
if __name__ == "__main__":
main() | from math import sqrt
from collections import defaultdict
N = int(input())
def prime_factorize(n):
a = defaultdict(int)
while n % 2 == 0:
a[2] += 1
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a[f] += 1
n //= f
else:
f += 2
if n != 1:
a[n] += 1
return a
ps = prime_factorize(N)
def func2(k):
n = 1
count = 1
while count * (count+1) // 2 <= k:
count += 1
return count-1
res = 0
for value in ps.values():
if value > 0:
res += func2(value)
print(res) | 1 | 16,899,554,992,288 | null | 136 | 136 |
n = int(raw_input())
A = map(int, raw_input().strip().split(' '))
q = int(raw_input())
M = map(int, raw_input().strip().split(' '))
S = [0]*len(A)
flags = [False]*len(M)
def brute_force(n):
if n == len(S):
ans = 0
for i in range(len(S)):
if S[i] == 1: ans += A[i]
for i in range(len(M)):
if ans == M[i]: flags[i] = True
else:
S[n] = 0
brute_force(n+1)
S[n] = 1
brute_force(n+1)
brute_force(0)
for flag in flags:
if flag: print "yes"
else: print "no" | import itertools
def main():
n = int(input())
p_list = list(itertools.permutations ([i+1 for i in range(n)]))
p = tuple(map(int, input().split(" ")))
q = tuple(map(int, input().split(" ")))
pn = 0
qn = 0
for i in range(len(p_list)):
if p == p_list[i]:
pn = i
if q == p_list[i]:
qn = i
print(abs(pn-qn))
if __name__ == "__main__":
main() | 0 | null | 50,242,834,580,730 | 25 | 246 |
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
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
n, m, k = map(int, input().split())
u = UnionFind(n + 1)
already = [0] * (n + 1)
for i in range(m):
a, b = map(int, input().split())
u.union(a, b)
already[a] += 1
already[b] += 1
for i in range(k):
c, d = map(int, input().split())
if u.same(c, d):
already[c] += 1
already[d] += 1
for i in range(1, n + 1):
print(u.size(i) - already[i] - 1)
| import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
n = I()
s = S()
rgb = ["R","G","B"]
rgb_st = set(rgb)
rgb_acc = [[0]*n for _ in range(3)]
index = rgb.index(s[0])
rgb_acc[index][0] += 1
ans = 0
for i in range(1,n):
for j in range(3):
rgb_acc[j][i] = rgb_acc[j][i-1]
index = rgb.index(s[i])
rgb_acc[index][i] += 1
for i in range(n-2):
for j in range(i+1,n-1):
if s[i] != s[j]:
ex = (rgb_st-{s[i],s[j]}).pop()
index = rgb.index(ex)
cnt = rgb_acc[index][-1] - rgb_acc[index][j]
if j<2*j-i<n:
if s[2*j-i] == ex:
cnt -= 1
ans += cnt
print(ans)
main()
| 0 | null | 48,935,375,777,542 | 209 | 175 |
import sys
def input():
return sys.stdin.readline().rstrip()
def dfs(c, n, G, ans):
count = c
for i, flag in enumerate(G[n]):
if flag == 1 and ans[i][0] == 0:
count += 1
ans[i][0] = i + 1
ans[i][1] = count
ans[i][2] = dfs(count, i, G, ans)
count = ans[i][2]
else:
return count + 1
def main():
n = int(input())
G = [[0] * n for _ in range(n)]
ans = [[0] * 3 for _ in range(n)]
for i in range(n):
u, k, *v = map(int, input().split())
for j in range(k):
G[u-1][v[j]-1] = 1
count = 1
for i in range(n):
if ans[i][0] == 0:
ans[i][0] = i + 1
ans[i][1] = count
ans[i][2] = dfs(count, i, G, ans)
count = ans[i][2] + 1
for i in range(n):
print(*ans[i])
if __name__ == '__main__':
main()
| def depth_search(i, adj, d, f, t):
if d[i - 1]:
return t
d[i - 1] = t
t += 1
for v in adj[i - 1]:
t = depth_search(v, adj, d, f, t)
f[i - 1] = t
t += 1
return t
n = int(input())
adj = [list(map(int, input().split()))[2:] for _ in range(n)]
d = [0] * n
f = [0] * n
t = 1
for i in range(n):
if d[i] == 0:
t = depth_search(i + 1, adj, d, f, t)
for i, df in enumerate(zip(d, f)):
print(i + 1, *df) | 1 | 3,053,962,240 | null | 8 | 8 |
name = str(input())
print(name[0:3])
| #!/usr/bin/env python3
import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random # random, uniform, randint, randrange, shuffle, sample
# import string # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict # subclass of dict. defaultdict(facroty)
# from collections import Counter # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce # reduce(f, iter[, init])
# from functools import lru_cache # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate # accumulate(iter[, f])
# from operator import itemgetter # itemgetter(1), itemgetter('key')
# from fractions import gcd # for Python 3.4 (previous contest @AtCoder)
def main():
mod = 998244353 # 10^9+7
inf = float('inf') # sys.float_info.max = 1.79...e+308
# inf = 2 ** 64 - 1 # (for fast JIT compile in PyPy) 1.84...e+19
sys.setrecursionlimit(10**6) # 1000 -> 1000000
def input(): return sys.stdin.readline().rstrip()
def ii(): return int(input())
def mi(): return map(int, input().split())
def mi_0(): return map(lambda x: int(x)-1, input().split())
def lmi(): return list(map(int, input().split()))
def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
def li(): return list(input())
# def my_update(seq, L):
# n = len(seq)
# for i in range(n-1):
# seq[i+1] += L[i]
# n, s = mi()
# L = lmi()
# dp = [[0] * (n + 1) for j in range(s + 1)] # chain の長さ、場合のかず
# # print(dp)
# for i in range(n):
# for j in range(s, -1, -1):
# if j == 0 and L[i] <= s:
# dp[L[i]][1] += 1
# elif j + L[i] <= s and dp[j]:
# my_update(dp[j + L[i]], dp[j]) # counter
# # print(dp)
# ans = 0
# for chain_len, num in enumerate(dp[s]):
# ans = (ans + pow(2, n - chain_len, mod) * num) % mod
# print(ans)
# write-up solution
"""
Ai それぞれ選ぶ or 選ばないと選択して行った時、足して S にできる組み合わせは何パターンできるか?
->
まさに二項定理の発想
fi = 1+x^Ai として
T = {1, 2, 3} に対する答えは [x^S]f1*f2*f3
T = {1, 2} に対する答えは [x^S]f1*f2
のように計算していく
全パターン f1*f2*f3 + f1*f2 + f1*f3 + f2*f3 + f1 + f2 + f3 の [x^S] の値が答え
->
(1+f1)*...*(1+fi)*...*(1+fn) の x^S の係数と一致
[x^S] Π{i=1...n} (2 + x^Ai)
を計算せよ、という問である
"""
n, s = mi()
A = lmi()
power_memo = [0] * (s + 1)
power_memo[0] = 2
if A[0] <= s:
power_memo[A[0]] = 1
for i in range(1, n):
# print(power_memo)
for j in range(s, -1, -1):
tmp = (power_memo[j] * 2) % mod
if j - A[i] >= 0 and power_memo[j - A[i]]:
tmp += power_memo[j - A[i]]
power_memo[j] = tmp % mod
# print(power_memo)
print(power_memo[s])
if __name__ == "__main__":
main()
| 0 | null | 16,227,596,248,530 | 130 | 138 |
N=int(input())
n=N
ans=0
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)
return divisors
l=make_divisors(N-1)
r=make_divisors(N)
ans=len(l)-1
for i in range(len(r)):
N=n
K=r[i]
if K==1:
continue
while(N%K==0):
N=N//K
if N%K==1:
#print(K)
ans+=1
print(ans) | h, w = map(int, input().split())
h_odd = (h+1)//2
h_even = h//2
w_odd = (w+1)//2
w_even = w//2
if h == 1 or w ==1:
print(1)
else:
ans = h_odd * w_odd + h_even *w_even
print(ans) | 0 | null | 46,046,986,053,310 | 183 | 196 |
h = -1
w = -1
while (h != 0) and (w != 0):
input = map(int, raw_input().split(" "))
h = input[0]
w = input[1]
if (h == 0 and w == 0):
break
i = 0
j = 0
line = ""
while j < w:
line += "#"
j += 1
while i < h:
print line
i += 1
print "" | while True:
[h,w] = map(int,input().split())
if h==0 and w ==0: break
print(('#'*w + '\n')*h) | 1 | 758,849,892,020 | null | 49 | 49 |
import math
foo = []
while True:
n = int(input())
if n == 0:
break
a = [int(x) for x in input().split()]
ave = sum(a)/len(a)
hoge = 0
for i in a:
hoge += (i - ave) ** 2
hoge /= len(a)
foo += [math.sqrt(hoge)]
for i in foo:
print(i) | import math
while True:
n=int(input())
if n==0:
break
s=[int(0) for i in range(n)]
s[:]=(int(x) for x in input().split())
m=sum(s)/n
a2=0
for i in range(n):
a2+=(s[i]-m)**2
a2/=n
print('{:.05f}'.format(math.sqrt(a2)))
| 1 | 195,767,119,872 | null | 31 | 31 |
#144_C
import math
n = int(input())
m = math.floor(math.sqrt(n))
div = 1
for i in range(1,m+1):
if n % i == 0:
div = i
print(int(div + n/div -2)) | a,b=map(int,input().split())
print('{0} {1} {2:.5f}'.format(a//b,a%b,a/b))
| 0 | null | 81,426,727,980,522 | 288 | 45 |
import bisect
import copy
def check(a, b, bar):
sm = 0
cnt = 0
n = len(a)
for x in a:
i = bisect.bisect_left(a, bar - x)
if i == n:
continue
cnt += n - i
sm += b[i] + x * (n-i)
return cnt, sm
n,m = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
b = copy.deepcopy(a)
for i,_ in enumerate(b[:-1]):
b[n-i-2] += b[n-i-1]
left = 0
right = b[0] * 2
while right - left > 1:
middle = ( right + left ) // 2
if check(a, b, middle)[0] < m:
right = middle
else:
left = middle
print(check(a, b, left)[1] - left * (check(a, b, left)[0]-m) ) | from bisect import bisect_left
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
l, r = 0, 10000000000
while r - l > 1:
m = (l + r) // 2
res = 0
for x in a:
res += n - bisect_left(a, m - x)
if res >= k:
l = m
else:
r = m
b = [0] * (n + 1)
for i in range(1, n + 1):
b[i] = b[i - 1] + a[n - i]
cnt = 0
ans = 0
for x in a:
t = n - bisect_left(a, l - x)
ans += b[t] + x * t
cnt += t
print(ans - (cnt - k) * l)
| 1 | 107,930,321,737,602 | null | 252 | 252 |
n = int(input())
A = list(map(int,input().split()))
m = int(input())
B = list(map(int,input().split()))
max = 2000
def solve(x,y):
if x==n:
S[y] = 1
else:
solve(x+1,y)
if y+A[x] < max+1:
solve(x+1,y+A[x])
S = [0 for i in range(max+1)]
solve(0,0)
for i in range(m):
if S[B[i]] == 1:
print("yes")
else:
print("no")
| N = int(input().rstrip())
A = [int(_) for _ in input().rstrip().split(" ")]
Q = int(input().rstrip())
M = [int(_) for _ in input().rstrip().split(" ")]
import itertools
from functools import lru_cache
@lru_cache(maxsize=2**12)
def solve(i, m):
if m == 0:
return True
elif i >= N:
return False
res = solve(i+1, m) or solve(i+1, m - A[i])
return res
for m in M:
if solve(0, m):
print("yes")
else:
print("no")
| 1 | 96,391,265,766 | null | 25 | 25 |
res_list = [[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]]
n = int(input())
for i in range(n):
io_rec = list(map(int, input().split(" ")))
bld_num = io_rec[0] - 1
floor_num = io_rec[1] - 1
room_num = io_rec[2] - 1
io_headcnt = io_rec[3]
res_list[bld_num][floor_num][room_num] += io_headcnt
for i in range(4):
if i:
print("#" * 20)
bld = res_list[i]
for j in bld:
floor_str = map(str, j)
print(" " + " ".join(floor_str)) | inp = [int(input()) for i in range(10)]
m1, m2, m3 = 0, 0, 0
for h in inp:
if(h > m1):
m3 = m2
m2 = m1
m1 = h
elif(h > m2):
m3 = m2
m2 = h
elif(h > m3):
m3 = h
print(m1)
print(m2)
print(m3) | 0 | null | 554,402,999,008 | 55 | 2 |
order_num = int(input())
jisho = {}
for _i in range(order_num):
order, key = input().split()
if order == 'insert':
jisho[key] = ''
elif order == 'find':
try:
jisho[key]
print('yes')
except KeyError:
print('no')
| h, w = map(int, input().split())
s = []
for _ in range(h):
s.append(input())
dp = [[h*w for i in range(w+1)] for j in range(h+1)]
dp[0][1] = 0
dp[1][0] = 0
for i in range(h):
for j in range(w):
# print("i", i, "j", j, "s[i][j]", s[i][j])
# print(s[i][j] == '#' and (i == 0 or s[i-1][j] == '.'))
#前の道が("."またはグリッド外)かつ現在地が#の場合に1を加える
#前の道が"#"であればまとめて変換できるので何も加えない
dp[i+1][j+1] = min(
dp[i][j+1] + (s[i][j] == '#' and (i == 0 or s[i-1][j] == '.')),
dp[i+1][j] + (s[i][j] == '#' and (j == 0 or s[i][j-1] == '.'))
)
print(dp[-1][-1])
| 0 | null | 24,849,976,544,872 | 23 | 194 |
from itertools import accumulate,chain
n,*s=open(0).read().split()
t=[2*i.count("(")-len(i) for i in s]
st=[[min(accumulate(s_,lambda a,b: a+(1 if b=="(" else -1),initial=0)),t_] for s_,t_ in zip(s,t)]
now=0
for c,d in chain(sorted([x for x in st if x[1]>=0])[::-1],sorted([x for x in st if x[1]<0],key=lambda z:z[1]-z[0])[::-1]):
if now+c<0:
print("No");break
now+=d
else:
print("No" if now else "Yes") | while 1:
r=0
S=0
n=int(input())
if n==0:break
s=list(map(int,input().split()))
a=(sum(s)/n)
for i in s:
S=((a-i)**2)/n
r+=S
print(r**0.5) | 0 | null | 11,990,408,818,612 | 152 | 31 |
x, k, d = map(int, input().split())
x = abs(x)
num = x // d
if num >= k:
ans = x - k*d
else:
if (k-num)%2 == 0:
ans = x - num*d
else:
ans = min(abs(x - num*d - d), abs(x - num*d + d))
print(ans) | x,k,d=map(int,input().split())
x=abs(x)
if x%d==0:
minNear = x%d + d
minFar = x%d
minTransitionToNear = (x-minNear)/d
#print(minNear)
#print(minFar)
#print(minTransitionToNear)
else:
minNear = x%d
minFar = x%d - d
minTransitionToNear = (x-minNear)/d
#print(minNear)
#print(minFar)
#print(minTransitionToNear)
if k<minTransitionToNear:
print(x-k*d)
else:
if (k-minTransitionToNear)%2==0:
print(abs(minNear))
else:
print(abs(minFar)) | 1 | 5,186,226,103,254 | null | 92 | 92 |
input()
line = input().split()
line.reverse()
print(' '.join(line)) | n = int(input())
l = (input().split())
out=""
for i in reversed(l): out+=i+" "
print(out.strip()) | 1 | 974,073,727,380 | null | 53 | 53 |
import copy
class Dice(object):
def __init__(self,List):
self.face=List
def n_spin(self,a_list):
List=copy.copy(a_list)
temp=List[0]
List[0]=List[1]
List[1]=List[5]
List[5]=List[4]
List[4]=temp
return List
def s_spin(self,a_list):
List=copy.copy(a_list)
temp=List[0]
List[0]=List[4]
List[4]=List[5]
List[5]=List[1]
List[1]=temp
return List
def e_spin(self,a_list):
List=copy.copy(a_list)
temp=List[0]
List[0]=List[3]
List[3]=List[5]
List[5]=List[2]
List[2]=temp
return List
def w_spin(self,a_list):
List = copy.copy(a_list)
temp=List[0]
List[0]=List[2]
List[2]=List[5]
List[5]=List[3]
List[3]=temp
return List
dice=Dice(map(int,raw_input().split()))
emer=copy.copy(dice.face)
face_storage=[]
face_storage.append(emer)
q=input()
for a in range(q):
question=map(int,raw_input().split())
for a in range(24):
face_storage.append(dice.n_spin(face_storage[a]))
face_storage.append(dice.s_spin(face_storage[a]))
face_storage.append(dice.e_spin(face_storage[a]))
face_storage.append(dice.w_spin(face_storage[a]))
for c in face_storage:
if c[0]==question[0] and c[1]==question[1]:
print(c[2])
break | x1,x2,x3,x4,x5 = map(int,input().split())
if x1==0:
print('1')
elif x2==0:
print('2')
elif x3==0:
print('3')
elif x4==0:
print('4')
elif x5==0:
print('5') | 0 | null | 6,773,281,458,732 | 34 | 126 |
import sys
readline = sys.stdin.readline
S = readline().rstrip()
from collections import deque
S = deque(S)
Q = int(readline())
turn = False
for i in range(Q):
query = readline().split()
if query[0] == "1":
turn ^= True
elif query[0] == "2":
if query[1] == "1":
if turn:
S.append(query[2])
else:
S.appendleft(query[2])
elif query[1] == "2":
if turn:
S.appendleft(query[2])
else:
S.append(query[2])
S = "".join(S)
if turn:
S = S[::-1]
print(S) | data = list(map(int,input().split()))
if(data[0] < data[1]): data[0],data[1] = data[1],data[0]
def gcd(x,y):
return x if y == 0 else gcd(y,x%y)
print(gcd(data[0],data[1]))
| 0 | null | 28,656,523,016,550 | 204 | 11 |
s=input()
ans='Yes'
a=s[0]
b=s[1]
c=s[2]
if a==b and b==c and a==c:
ans='No'
print(ans)
| print('NYoe s'[len(set(input()))==2::2]) | 1 | 54,906,875,731,772 | null | 201 | 201 |
n,m=map(int,input().split())
a=[0]*n
ans=0
for i in range(m):
p,s=input().split()
p=int(p)-1
if a[p]!=1:
if s=='WA':a[p]-=1
else:
ans-=a[p]
a[p]=1
for i in range(n):
a[i]=max(a[i],0)
print(sum(a),ans) | n,m = map(int, input().split())
l = [[] for _ in range(n)]
ac,wa = (0,0)
for i in range(m):
p,s = input().split()
p = int(p)
if s == "AC":
if s not in l[p-1]:
l[p-1].append(s)
ac += 1
wa += l[p-1].count("WA")
else:
l[p-1].append(s)
print(ac,wa) | 1 | 93,728,635,111,090 | null | 240 | 240 |
n = int(input())
lst = [(m,no) for m in ['S','H','C','D'] for no in range(1,14)]
for i in range(n):
m,no = input().split()
lst.remove((m,int(no)))
for (m,no) in lst:
print(m,no)
|
INF = 1<<60
def resolve():
def judge(j):
for i in range(group):
cnt_Wchoco[i] += div_G[i][j]
if cnt_Wchoco[i] > K:
return False
return True
H, W, K = map(int, input().split())
G = [list(map(int, input())) for _ in range(H)]
ans = INF
for bit in range(1<<(H-1)):
group = 0 # 分かれたブロック数
row = [0]*H
for i in range(H):
# 分割ライン
row[i] = group
if bit>>i & 1:
group += 1
group += 1 # 1つ折ったら2つに分かれるのでプラス1, 折らなかったら1つ
# 分割したブロックを列方向で見る
div_G = [[0] * W for _ in range(group)]
for i in range(H):
for j in range(W):
div_G[row[i]][j] += G[i][j]
num = group-1
cnt_Wchoco = [0]*group
for j in range(W):
if not judge(j):
num += 1
cnt_Wchoco = [0] * group
if not judge(j):
num = INF
break
ans = min(ans, num)
print(ans)
if __name__ == "__main__":
resolve()
| 0 | null | 24,635,504,639,002 | 54 | 193 |
class AlgUnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n #各要素の親要素の番号を格納するリスト 要素が根(ルート)の場合は-(そのグループの要素数)を格納する
def find(self, x): #要素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が属するグループと要素yが属するグループとを併合する
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x): #要素xが属するグループのサイズ(要素数)を返す
return -self.parents[self.find(x)]
def same(self, x, y): #要素x, yが同じグループに属するかどうかを返す
return self.find(x) == self.find(y)
def members(self, x): #要素xが属するグループに属する要素をリストで返す
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self): #すべての根の要素をリストで返す
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self): #グループの数を返す
return len(self.roots())
def all_group_members(self): #{ルート要素: [そのグループに含まれる要素のリスト], ...}の辞書を返す
return {r: self.members(r) for r in self.roots()}
def __str__(self): #print()での表示用 ルート要素: [そのグループに含まれる要素のリスト]を文字列で返す
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
if __name__ == "__main__":
N, M = map(int, input().split())
A = [list(map(int, input().split())) for i in range(M)]
for j in range(M):
A[j][0] -= 1
A[j][1] -= 1
uf = AlgUnionFind(N)
for i in range(M):
uf.union(A[i][0], A[i][1])
count = uf.group_count() - 1
print(count)
| N = int(input())
S = dict()
for i in range(N):
s = input()
if s in S:
S[s] += 1
else:
S[s] = 1
max_val = max(S.values())
max_key = [key for key in S if S[key] == max_val]
print("\n".join(sorted(max_key)))
| 0 | null | 35,950,509,093,730 | 70 | 218 |
x = list(map(int, input().split()))
for i in range(len(x)):
if x[i] is 0:
print(i+1)
| import sys
array = list(map(int,input().split()))
print(array.index(0)+1) | 1 | 13,485,639,067,192 | null | 126 | 126 |
import queue
h,w,m = ( int(x) for x in input().split() )
h_array = [ 0 for i in range(h) ]
w_array = [ 0 for i in range(w) ]
ps = set()
for i in range(m):
hi,wi = ( int(x)-1 for x in input().split() )
h_array[hi] += 1
w_array[wi] += 1
ps.add( (hi,wi) )
h_great = max(h_array)
w_great = max(w_array)
h_greats = list()
w_greats = list()
for i in range( h ):
if h_array[i] == h_great:
h_greats.append(i)
for i in range( w ):
if w_array[i] == w_great:
w_greats.append(i)
ans = h_great + w_great - 1
escaper = False
for i in range( len(h_greats) ):
hi = h_greats[i]
for j in range( len(w_greats) ):
wi = w_greats[j]
if (hi,wi) not in ps:
ans += 1
escaper = True
break
if escaper:
break
print(ans) | N = int(input())
P = tuple(map(int, input().split()))
minp = P[0]
ans = 1
for i in range(1, N):
if P[i] <= minp:
ans += 1
minp = min(minp, P[i])
print(ans) | 0 | null | 44,817,883,473,162 | 89 | 233 |
a, v = map(int, input().split())
b, w = map(int, input().split())
t = int(input())
d = abs(a - b)
u = abs(v - w)
if w >= v:
print("NO")
else:
if u * t >= d:
print('YES')
else:
print('NO') | while 1:
try:
print(len(str(sum(map(int,input().split())))))
except: break | 0 | null | 7,544,571,813,570 | 131 | 3 |
S = str(input())
if S == 'hi' or S == 'hihi' or S == 'hihihi' or S == 'hihihihi' or S == 'hihihihihi':
print ('Yes')
else:
print ('No')
| s=input()
for i in range(len(s)):
if s=="hi"*i:
print("Yes")
exit()
print("No")
| 1 | 53,392,315,263,430 | null | 199 | 199 |
S = input()
result = ''
for _ in S:
result += 'x'
print(result) | S = list(map(str,input()))
for i in range(len(S)):
S[i] = 'x'
print(''.join(map(str,S))) | 1 | 73,010,328,116,642 | null | 221 | 221 |
n = int(input())
ac = 0
wa = 0
tle = 0
re = 0
for _ in range(n):
s = input()
if s == "AC":
ac += 1
elif s == "WA":
wa += 1
elif s == "TLE":
tle += 1
elif s == "RE":
re += 1
print("AC x " + str(ac))
print("WA x " + str(wa))
print("TLE x " + str(tle))
print("RE x " + str(re)) | H, W = list(map(int, input().split()))
### 片方だけ奇数のマスには行くことができない
### Hが偶数、Wが偶数の場合 → H*W // 2
### Hが奇数、Wが偶数の場合 → H*W // 2 (Wが奇数の場合も同様)
### Hが奇数、Wが奇数の場合 → H*W // 2 + 1
if H == 1 or W == 1:
print(1)
elif H % 2 != 0 and W % 2 != 0:
print(int(H * W // 2) + 1)
else:
print(int(H * W // 2)) | 0 | null | 29,605,336,146,948 | 109 | 196 |
if __name__ == '__main__':
from collections import deque
n = int(input())
dic = {}
for i in range(n):
x = input().split()
if x[0] == "insert":
dic[x[1]] = 1
if x[0] == "find":
if x[1] in dic:
print('yes')
else:
print('no')
| import itertools
n = int(input())
d = list(map(int, input().split()))
lst = list(itertools.combinations(d, 2))
ans = 0
for i in lst:
a = i[0] * i[1]
ans += a
print(ans)
| 0 | null | 83,800,331,269,210 | 23 | 292 |
S = input()
n = len(S) + 1
A = []
mini = 0
for i in range(n-1):
if i==0:
if S[i]=="<":
A.append([1,0])
else:
A.append([0,1])
else:
if S[i]=="<" and S[i-1]==">":
A.append([1,0])
elif S[i]=="<":
A[-1][0] += 1
else:
A[-1][1] += 1
summ = 0
for x in A:
ma = max(x)
mi = min(x)
summ += (ma+1)*ma//2
summ += (mi-1)*mi//2
print(summ) | import math
a,b,c,d=map(float,input().split())
x=math.sqrt((a-c)**2 + (b-d)**2)
print(round(x,8))
#round(f,6)でfを小数点以下6桁にまとめる。
| 0 | null | 78,239,161,595,892 | 285 | 29 |
n,k = map(int,input().split())
mod = 10**9+7
"""
dp[i] := gcd(a1,...,an) = i となるものがいくつあるか
"""
dp = [0 for _ in range(k+1)]
subdp = [0 for _ in range(k+1)]
for i in range(1, k+1)[::-1]:
target = pow(k//i, n, mod)
for j in range(2*i, k+1, i):
target -= dp[j]
dp[i] = target
ans = 0
for i in range(k+1):
ans = (ans + dp[i]*i) % mod
print(ans) | a=list(map(int,input().split()))
if a[0]+a[1]+a[2]>=22:
print("bust")
else:
print("win") | 0 | null | 77,741,944,834,412 | 176 | 260 |
n=int(input())
l=sorted([list(map(int,input().split())) for i in range(n)],key=lambda x:x[0]-x[1],reverse=1)
now=float("INF")
ans=0
for i in l:
if sum(i)<=now:
now=i[0]-i[1]
ans+=1
print(ans) | N=int(input())
arms=[list(map(int,input().split())) for _ in range(N)]
points=[]
for i in range(N):
points.append([arms[i][0]-arms[i][1],arms[i][0]+arms[i][1]])
#print(points)
points.sort(key=lambda x:x[1])
#print(points)
nowr=-float("inf")
cnt=0
for i in points:
l,r=i
if nowr<=l:
nowr=r
cnt=cnt+1
print(cnt)
| 1 | 89,978,062,049,440 | null | 237 | 237 |
N=int(input())
D=[]
TF=[]
for i in range(N):
Input=list(map(int,input().split()))
D.append(Input)
if D[i][0]==D[i][1]:
TF.append(1)
else:
TF.append(0)
TF.append(0)
TF.append(0)
Q=[]
for i in range(N):
temp=TF[i]+TF[i+1]+TF[i+2]
Q.append(temp)
if max(Q)==3:
print("Yes")
else:
print("No") | import sys
def popcount(x: int):
return bin(x).count("1")
def main():
N = int(sys.stdin.readline().rstrip())
X = sys.stdin.readline().rstrip()
Xdec = int(X, 2)
# 1回目の演算用
md = popcount(Xdec)
md_p, md_m = md + 1, md - 1
tmp_p = Xdec % md_p
if md_m > 0:
tmp_m = Xdec % md_m
for i in range(0, N, 1):
if X[i] == "1": # 1->0
if md_m == 0:
print(0)
continue
x_m = pow(2, (N - 1 - i), md_m)
tmp = (tmp_m - x_m) % md_m
if X[i] == "0": # 0->1
x_p = pow(2, (N - 1 - i), md_p)
tmp = (tmp_p + x_p) % md_p
cnt = 1
while tmp:
tmp = tmp % popcount(tmp)
cnt += 1
print(cnt)
main()
| 0 | null | 5,301,624,010,160 | 72 | 107 |
# -*-coding:utf-8
import math
def main():
a, b, degree = map(int, input().split())
radian = math.radians(degree)
S = 0.5*a*b*math.sin(radian)
x = a + b + math.sqrt(pow(a,2)+pow(b,2)-2*a*b*math.cos(radian))
print('%.8f' % S)
print('%.8f' % x)
print('%.8f' % ((2*S)/a))
if __name__ == '__main__':
main() | import math
in_line = raw_input().split()
a = float(in_line[0])
b = float(in_line[1])
c = float(in_line[2])
print 0.5*a*b*math.sin(math.radians(c))
print a+b+math.sqrt(a*a+b*b-2*a*b*math.cos(math.radians(c)))
print b*math.sin(math.radians(c)) | 1 | 175,145,824,448 | null | 30 | 30 |
from math import floor
s = input()
k = int(input())
if len(set(s)) == 1:
print(floor(len(s) * k / 2))
exit(0)
x = s[0]
y = 1
ans = 0
for i in s[1:]:
if i == x:
y += 1
else:
ans += floor(y / 2)
x = i
y = 1
ans += floor(y / 2)
if s[0] != s[-1]:
print(ans * k)
else:
x = s[0]
y = 1
for i in s[1:]:
if x == i:
y += 1
else:
a = y
break
y = 0
for i in s[::-1]:
if x == i:
y += 1
else:
b = y
break
print(ans * k - ((floor(a / 2) + floor(b / 2) - floor((a + b) / 2)) * (k - 1))) | X,Y,Z = map(int,input().split())
X,Y = Y,X
X,Z = Z,X
print(X,Y,Z,sep=" ") | 0 | null | 106,842,002,400,914 | 296 | 178 |
def InsertionSort(a, N, Gap):
c = 0
for i in range(Gap, N):
v = a[i]
j = i - Gap
while j >= 0 and a[j] > v:
a[j+Gap] = a[j]
j -= Gap
c += 1
a[j+Gap] = v
return a, c
def ShellSort(a, N):
cnt = 0
G = [1]
for i in range(1, N):
if (3*G[i-1]+1) <= N:
G.append(3*G[i-1]+1)
else:
break
for g in G[::-1]:
a, c = InsertionSort(a, N, g)
cnt += c
return a, cnt, G
N = int(input())
A = []
cnt = 0
for _ in range(N):
A.append(int(input()))
sorted_A, cnt, G = ShellSort(A, N)
print(len(G))
print(*G[::-1])
print(cnt)
print(*sorted_A, sep="\n") | def insertion_sort(a,n,g,cnt):
for i in range(g,n):
v = a[i]
j = i-g
while j >= 0 and a[j] > v:
a[j+g] = a[j]
j -= g
cnt+=1
a[j+g] = v
return a,cnt
def shell_sort(a,n,G):
cnt=0
for g in G:
a,cnt = insertion_sort(a,n,g,cnt)
return a,cnt
n = int(raw_input())
a = []
for i in range(n):
a.append(int(raw_input()))
g = 1
G = [g]
while True:
g = 3*g + 1
if g > n:
break
G.append(g)
G = sorted(G,reverse=True)
a,cnt = shell_sort(a,n,G)
print len(G)
print ' '.join([str(v) for v in G])
print cnt
for v in a:
print v | 1 | 30,350,598,300 | null | 17 | 17 |
n=int(input())
print((n//2+n%2)/n)
| n = int(input())
A = [int(input()) for _ in range(n)]
G = [1]
a=1
while True:
a = 3*a+1
if a>=n:
break
G.append(a)
if len(G)>1:
G.sort(reverse=True)
m = len(G)
cnt = 0
def shellSort(A,n):
cccnt = 0
for k in range(m):
cccnt += insertionSort(A,n,G[k])
return cccnt
def insertionSort(A,n,g): #Aはリスト nは要素数 gは間隔
ccnt = 0
for i in range(g,n):
v = A[i]
j = i-g
while j>=0 and A[j] > v:
A[j+g] = A[j]
j -= g
ccnt += 1
A[j+g] = v
return ccnt
cnt = shellSort(A,n)
print(m)
print(' '.join(map(str,G)))
print(cnt)
for _ in range(n):
print(A[_])
| 0 | null | 89,006,374,272,960 | 297 | 17 |
class UnionFind:
def __init__(self,n):
self.par = {i:i for i in range(1,n+1)}
self.rank = {i:0 for i in range(1,n+1)}
self.size = {i:1 for i in range(1,n+1)}
def find(self,x):
if x != self.par[x]:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self,x,y):
px,py = self.find(x),self.find(y)
res = 0
if px != py:
if self.rank[px] < self.rank[py]:
self.par[px] = py
self.size[py] += self.size[px]
res = self.size[py]
else:
self.par[py] = px
self.size[px] += self.size[py]
if self.rank[px] == self.rank[py]:
self.rank[px] += 1
res = self.size[px]
return res
n,m = map(int,input().split())
ans = 1
uf = UnionFind(n)
for _ in range(m):
a,b = map(int,input().split())
ans = max(ans,uf.union(a,b))
print(ans) | N, K = map(int,input().split())
ans = 0
MOD = 10**9 + 7
for i in range(K,N+2):
x = (N+1-i) * i + 1
ans += x
ans %= MOD
print (ans) | 0 | null | 18,418,710,212,992 | 84 | 170 |
1
2
a,b = map(int, input().split())
print("a "+("==" if a == b else "<" if a < b else ">")+" b")
| n =raw_input()
m =n.split(" ")
a = int(m[0])
b = int(m[1])
if a < b :print "a < b"
if a > b :print "a > b"
if a == b :print "a == b" | 1 | 362,069,417,402 | null | 38 | 38 |
s = input()
st1=[]
st2=[]
st3=[]
total=0
for i in range(len(s)):
c=s[i]
if c=='\\':
st1.append(i)
elif c=='/':
if len(st1) > 0:
j = st1.pop()
a = i - j
total+=a
tmp=0
while len(st2)>0 and st2[-1]>j:
st2.pop()
tmp+=st3.pop()
st3.append(a+tmp)
st2.append(j)
print(total)
n = len(st3)
print(n,end='')
for i in range(n):
print(' '+str(st3[i]),end='')
print()
| down_positions = []
ponds = []
for index, value in enumerate(raw_input()):
if value == '\\':
down_positions.append(index)
elif value == '/' and down_positions:
right = index
left = down_positions.pop()
area = right - left
candidate_area = 0
while ponds and left < ponds[-1][0]:
candidate_area += ponds.pop(-1)[1]
ponds.append((left, area + candidate_area))
print sum(x[1] for x in ponds)
print len(ponds),
for pond in ponds:
print pond[1], | 1 | 59,361,490,368 | null | 21 | 21 |
A=1
B=1
C=0 #2つ前の項
D=0 #1
N=int(input())
if N==0 or N==1:
print(1)
elif N==2:
print(2)
else:
C=B #1
D=A+B #2
for i in range (N-3):
B=C
C=D
D=B+C
print(C+D)
| n = int(input())
dp = [0] * 45
dp[0], dp[1] = 1, 1
for i in range(2, 44+1):
dp[i] += dp[i-1] + dp[i-2]
print(dp[n])
| 1 | 1,943,543,252 | null | 7 | 7 |
S = input()
T = input()
l = len(S) - len(T) + 1
ans = len(T)
t = len(T)
for i in range(l):
s = S[i:i+t]
ans = min(ans, len([0 for i in range(t) if T[i] != s[i]]))
print(ans) | 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
x=I()
t=1800
for i in range(10):
if x>=t:
print(i+1)
exit()
t-=200
main()
| 0 | null | 5,203,875,022,112 | 82 | 100 |
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
n = int(input())
increasing = []
decreasing = []
dec_special = []
for _ in range(n):
s = input().rstrip()
minima = 0
fin = 0
for ch in s:
if ch == ")":
fin -= 1
if fin < minima:
minima = fin
else:
fin += 1
if fin >= 0:
increasing.append((minima, fin))
elif minima < fin:
dec_special.append((minima, fin))
else:
decreasing.append((minima, fin))
increasing.sort(reverse=True)
decreasing.sort()
dec_special.sort()
current = 0
for minima, diff in increasing:
if current + minima < 0:
print("No")
exit()
current += diff
for minima, diff in dec_special:
if current + minima < 0:
print("No")
exit()
current += diff
for minima, diff in decreasing:
if current + minima < 0:
print("No")
exit()
current += diff
if current != 0:
print("No")
else:
print("Yes")
| import sys
X,K,D= map(int,input().split())
temp = X
if abs(X) > K*D:
print(abs(X)-K*D)
sys.exit()
for t in range(K):
# 絶対値の小さい方に移動
if abs(temp - D) < abs(temp + D):
temp = temp-D
else:
temp = temp+D
# 移動幅より小さくなったとき
if abs(temp) < D:
if (K-t-1) % 2 == 0:
print(abs(temp))
sys.exit()
else:
if abs(temp - D) < abs(temp + D):
temp = temp-D
print(abs(temp))
sys.exit()
else:
temp = temp+D
print(abs(temp))
sys.exit()
print(abs(temp))
| 0 | null | 14,522,555,406,880 | 152 | 92 |
import sys
from collections import deque
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
n = I()
A = LI()
q = I()
m = LI()
ans = 0
partial_sum = set()
for i in range(2 ** n):
bit = [i>>j&1 for j in range(n)]
partial_sum.add(sum(A[k]*bit[k] for k in range(n)))
for x in m:
print('yes' if x in partial_sum else 'no')
| # coding: utf-8
N = int(input())
A = [int(i) for i in input().split()]
q = int(input())
m = [int(i) for i in input().split()]
MAX_LENGTH = len(A)
dp = [[-1 for i in range(max(m) + 1)] for j in range(MAX_LENGTH + 1)]
# i番目以降の値を使ってmを作ればTrueを返す
def fullSearch(i, m):
# 終了条件
if m < 0:
return False
elif dp[i][m] != -1:
return dp[i][m]
elif m == 0:
return True
elif i >= MAX_LENGTH:
return False
else:
# 全探索かっこわるい
res = fullSearch(i + 1, m) or fullSearch(i + 1, m - A[i])
# のでメモ化
dp[i][m] = res
return res
for mi in m:
print("yes" if fullSearch(0, mi) else "no") | 1 | 99,296,219,272 | null | 25 | 25 |
N, P = map(int, input().split())
S = input()
XX = 0
if P == 2:
for i in range(N):
if int(S[i]) % 2 == 0:
XX += i + 1
print(XX)
elif P == 5:
for i in range(N):
if int(S[i]) % 5 == 0:
XX += i + 1
print(XX)
else:
base = 1
X = [0 for i in range(N)]
X[-1] = int(S[-1])
for i in range(N, 0, -1):
X[i-1] = (base * int(S[i-1])) % P
base *= 10
base %= P
for i in range(1, N):
X[i] += X[i-1]
X[i] %= P
D = {i: 0 for i in range(P)}
D[0] = 1
for i in range(N):
D[X[i]] += 1
XX = 0
for i in D:
XX += (D[i] * (D[i] - 1)) // 2
print(XX) | import numpy as np
[N, D] = map(int, input().split())
X, Y = np.zeros(N), np.zeros(N)
for i in range(N):
[x, y] = map(int, input().split())
X[i], Y[i] = x, y
dist = np.sqrt(X * X + Y * Y)
print(len(np.where(dist <= D)[0]))
| 0 | null | 31,802,267,663,712 | 205 | 96 |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
N = int(input())
A = list(map(int, input().split()))
B = [bin(a) for a in A]
maxA = max(A)
mask = 1
count = 0
i = 0
while maxA >> i:
zeros = sum([1 for a in A if (mask * 2**i) & a == 0]) % MOD
ones = (len(A) - zeros) % MOD
count += zeros * ones * ((2**i) % MOD)
count %= MOD
i += 1
print(count) | import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7
def resolve():
n = int(input())
A = list(map(int, input().split()))
res = 0
for i in range(60):
cnt = 0
for a in A:
cnt += (a >> i) & 1
res += (cnt * (n - cnt) % mod) * (1 << i) % mod
res %= mod
print(res)
if __name__ == '__main__':
resolve()
| 1 | 123,367,528,820,802 | null | 263 | 263 |
while True:
(x, y) = [int(i) for i in input().split()]
if x < y:
print(x, y)
elif x > y:
print(y, x)
elif x == y:
if x == 0 and 0 == y:
break
print(x, y) | x = 1
y = 1
while x != 0 or y != 0:
n = map(int,raw_input().split())
x = n[0]
y = n[1]
if x == 0 and y == 0:
break
elif x <= y:
print x,y
elif x > y:
print y,x | 1 | 514,044,706,912 | null | 43 | 43 |
height = []
for i in range(10):
height.append(input())
height.sort(reverse=True)
for i in range(3):
print(height[i]) | t = 0
h = 0
for i in range(int(input())):
cards = input().split()
if cards[0] > cards[1]:
t += 3
elif cards[0] == cards[1]:
t += 1
h += 1
else:
h += 3
print(str(t) + " " + str(h)) | 0 | null | 1,015,079,876,850 | 2 | 67 |
from collections import defaultdict
def prime_factor(n):
d = defaultdict(int)
for i in range(2, n + 1):
if i * i > n:
break
while n % i == 0:
d[i] += 1
n //= i
if n != 1:
d[n] += 1
return d
N = int(input())
d = prime_factor(N)
ans = 0
for v in d.values():
i = 1
cur = 1
cnt = 0
while cur <= v:
cnt += 1
i += 1
cur += i
ans += cnt
print(ans)
| N = int(input())
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1:
arr.append([temp, 1])
if arr==[]:
arr.append([n, 1])
return arr
def add(X):
counter = 0
while True:
if counter * (counter + 1) <= X * 2:
counter += 1
else:
counter -= 1
break
# print(X, counter)
return counter
facts = factorization(N)
answer = 0
for f in facts:
if f[0] != 1:
answer += add(f[1])
print(answer) | 1 | 16,858,703,688,502 | null | 136 | 136 |
N = int(input())
total = 0
for n in range(1, N+1):
if (n % 3 > 0) and (n % 5 > 0):
# print(n)
total += n
print(total) | total = 0
n = int(input())
for i in range(1, n + 1):
if not ((i % 5 == 0) or (i % 3 == 0)):
total = total + i
print(total)
| 1 | 34,717,889,440,240 | null | 173 | 173 |
A, B, K = map(int, input().split())
print(max(0, A-K), max(A+B-K-max(0, A-K), 0)) | class Dice():
def __init__(self, nums):
self.nums = nums
self.top, self.front, self.right = 0, 1, 2
def move(self, op):
for c in op:
if c == 'N':
self.top, self.front = self.front, 5 - self.top
elif c == 'S':
self.top, self.front = 5 - self.front, self.top
elif c == 'E':
self.top, self.right = 5 - self.right, self.top
else:
self.top, self.right = self.right, 5 - self.top
dice = Dice([int(n) for n in input().split()])
dice.move(input())
print(dice.nums[dice.top]) | 0 | null | 52,319,033,918,228 | 249 | 33 |
def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [input().split() for _ in range(n)]
def s4(n):return [[x for x in s] for s in s2(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]
def t3(n):return [tuple(int(x) for x in input().split()) for _ in range(n)]
def p0(b,yes="Yes",no="No"): print(yes if b else no)
# from sys import setrecursionlimit
# setrecursionlimit(1000000)
# from collections import Counter,deque,defaultdict
# import itertools
# import math
# import networkx as nx
# from bisect import bisect_left,bisect_right
# from heapq import heapify,heappush,heappop
a,b,m=n1()
A=n1()
B=n1()
X=n3(m)
A2=sorted(A)
B2=sorted(B)
ans=A2[0]+B2[0]
for a,b,c in X:
if A[a-1]+B[b-1]-c<ans:
ans=A[a-1]+B[b-1]-c
print(ans) | s=int(input())
a=1
mod=10**9+7
x=s//3
y=s%3
ans=0
while x>=1:
xx=1
for i in range(1,x):
xx*=i
xx%=mod
yy=1
for j in range(1,1+y):
yy*=j
yy%=mod
fx=pow(xx,mod-2,mod)
fy=pow(yy,mod-2,mod)
xxyy=1
for k in range(1,x+y):
xxyy*=k
xxyy%=mod
ans+=(xxyy*fx*fy)%mod
x-=1
y+=3
print(ans%mod) | 0 | null | 28,472,180,079,910 | 200 | 79 |
N,K = map(int,input().split())
MOD = 998244353
interval = []
for i in range(K):
intv = [int(x) for x in input().split()]
interval.append(intv)
dp = [0]*N
diff = [0]*(N-1)
dp[0] = 1
diff[0] = -1
for i in range(N-1):
for L,R in interval:
if L <= N-1 - i:
diff[i+L-1] += dp[i]
if R+1 <= N-1 - i:
diff[i+R] -= dp[i]
dp[i+1] = dp[i] + diff[i]
dp[i+1] %= MOD
print(dp[N-1]) | A,V=map(int,input().split())
B,W=map(int,input().split())
T=int(input())
X=abs(B-A)
sp=V-W
Z=sp*T-X
if Z<0:
print("NO")
else:
print("YES") | 0 | null | 8,905,504,529,740 | 74 | 131 |
n = int(input())
pair = [1, 1]
for i in range(n - 1):
pair[i % 2] = sum(pair)
print(pair[n % 2])
| n = int(input())
dp = [1] * (n+1)
for j in range(n-1):
dp[j+2] = dp[j+1] + dp[j]
print(dp[n])
| 1 | 1,887,282,088 | null | 7 | 7 |
s = list(input())
a = 0
b = 0
c = 0
for i in range(len(s)):
if i%2 == 0 and s[i] == "h":
a += 1
elif i%2 == 1 and s[i] == "i":
b += 1
else:
c += 1
if a == b and c == 0:
print('Yes')
else:
print('No') | print('No' if input().replace('hi', '') else 'Yes') | 1 | 53,116,678,405,052 | null | 199 | 199 |
#---Strings
S, T = map(str, input().split(" "))
print(T, S, sep="")
|
def resolve():
MOD = 10 ** 9 + 7
N, K = map(int, input().split())
ans = 0
for k in range(K, N + 2):
min_num = k * (k - 1) // 2
max_num = k * (N * 2 - k + 1) // 2
add = max_num - min_num + 1
ans = (ans + add) % MOD
print(ans)
if __name__ == "__main__":
resolve() | 0 | null | 67,946,178,511,630 | 248 | 170 |
kyu = [2000, 1800, 1600, 1400, 1200, 1000, 800, 600, 400, 0]
x = int(input())
for k, num in enumerate(kyu):
if num > x >= kyu[k+1]:
print(k + 1)
break | from functools import reduce
from fractions import gcd
import math
import bisect
import itertools
import sys
input = sys.stdin.readline
INF = float("inf")
# 処理内容
def main():
X = int(input())
print(10 - X // 200)
if __name__ == '__main__':
main() | 1 | 6,709,691,005,440 | null | 100 | 100 |
X, K, D = map(int, input().split())
X = abs(X)
ans = 0
if X // D > K:
ans = X - D*K
else:
e = X // D
K -= e
X -= D * e
if K % 2 == 1: X = abs(X-D)
ans = X
print(ans) | X, K, D = list(map(int, input().split()))
X = abs(X)
if(X >= K * D):
print(X - K * D)
else:
q = X // D
r = X % D
if((K - q) % 2 == 0):
print(r)
else:
print(abs(r - D))
| 1 | 5,254,507,270,218 | null | 92 | 92 |
def solve(l):
e = l.pop()
if e == '*':
return solve(l) * solve(l)
elif e == '+':
return solve(l) + solve(l)
elif e == '-':
return - solve(l) + solve(l)
else:
return int(e)
formula = input().split()
print(solve(formula)) | import sys
import bisect
import math
input = sys.stdin.readline
N, K = map(int, input().split())
A = list(map(int, input().split()))
F = list(map(int, input().split()))
A.sort()
F.sort(reverse=True)
B = [(A[i]*F[i], F[i]) for i in range(N)]
B.sort(reverse=True)
L = 0
R = B[0][0]
if sum(A) <= K:
print(0)
exit(0)
while(1):
ans = (L+R) // 2
flag = True
tmp = 0
for i in range(N):
tmp += math.ceil(max(B[i][0] - ans, 0) / B[i][1])
if tmp > K:
flag = False
break
if flag:
R = ans
else:
L = ans
if L == R or L+1 == R:
print(R)
break
| 0 | null | 82,409,508,731,388 | 18 | 290 |
S = input()
N = len(S)
print("x" * N) | N = int(input())
print(N ** 2)
| 0 | null | 109,157,018,172,328 | 221 | 278 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.