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
|
---|---|---|---|---|---|---|
s = raw_input()
r = ''
for c in s:
d = c
if c >= 'a' and c <= 'z':
d = chr(ord(c) - ord('a') + ord('A'))
if c >= 'A' and c <= 'Z':
d = chr(ord(c) - ord('A') + ord('a'))
r = r + d
print r | import re
def transletter(matchobj):
letter = matchobj.group(0)
if letter.islower(): return letter.upper()
else: return letter.lower()
def main():
text = input()
print(re.sub(r'[a-zA-Z]', transletter, text))
main() | 1 | 1,510,156,614,580 | null | 61 | 61 |
n = int(input())
ans = 0
for i in range(1,n+1):
m = n // i
ans += m*(m+1)*i//2
print(ans) | N = int(input())
S = input()
r = [0 for _ in range(N + 1)]
g = [0 for _ in range(N + 1)]
b = [0 for _ in range(N + 1)]
for i in reversed(range(N)):
r[i] = r[i + 1]
g[i] = g[i + 1]
b[i] = b[i + 1]
if S[i] == "R":
r[i] += 1
if S[i] == "G":
g[i] += 1
if S[i] == "B":
b[i] += 1
ans = 0
for i in range(N):
if S[i] == "R":
for j in range(i + 1, N):
if S[j] == "G":
if 2 * j - i < N:
if S[2 * j - i] == "B":
ans += (b[j + 1] - 1)
else:
ans += b[j + 1]
else:
ans += b[j + 1]
for i in range(N):
if S[i] == "R":
for j in range(i + 1, N):
if S[j] == "B":
if 2 * j - i < N:
if S[2 * j - i] == "G":
ans += (g[j + 1] - 1)
else:
ans += g[j + 1]
else:
ans += g[j + 1]
for i in range(N):
if S[i] == "B":
for j in range(i + 1, N):
if S[j] == "R":
if 2 * j - i < N:
if S[2 * j - i] == "G":
ans += (g[j + 1] - 1)
else:
ans += g[j + 1]
else:
ans += g[j + 1]
for i in range(N):
if S[i] == "B":
for j in range(i + 1, N):
if S[j] == "G":
if 2 * j - i < N:
if S[2 * j - i] == "R":
ans += (r[j + 1] - 1)
else:
ans += r[j + 1]
else:
ans += r[j + 1]
for i in range(N):
if S[i] == "G":
for j in range(i + 1, N):
if S[j] == "R":
if 2 * j - i < N:
if S[2 * j - i] == "B":
ans += (b[j + 1] - 1)
else:
ans += b[j + 1]
else:
ans += b[j + 1]
for i in range(N):
if S[i] == "G":
for j in range(i + 1, N):
if S[j] == "B":
if 2 * j - i < N:
if S[2 * j - i] == "R":
ans += (r[j + 1] - 1)
else:
ans += r[j + 1]
else:
ans += r[j + 1]
print(ans) | 0 | null | 23,672,619,399,360 | 118 | 175 |
import queue
n = int(input())
e = []
f = [{} for i in range(n)]
for i in range(n-1):
a,b = map(int, input().split())
a-=1
b-=1
e.append([a,b])
f[a][b]=0
f[b][a]=0
k = 0
for i in range(n-1):
k = max(k,len(f[i]))
q = queue.Queue()
q.put(0)
used = [[0] for i in range(n)]
while not q.empty():
p = q.get()
for key,c in f[p].items():
if c == 0:
if used[p][-1]<k:
col = used[p][-1]+1
else:
col = 1
f[p][key] = col
f[key][p] = col
used[p].append(col)
used[key].append(col)
q.put(key)
print(k)
for a,b in e:
print(max(f[a][b],f[b][a]))
| while True:
try:
print len(list(str(sum(map(int,raw_input().split())))))
except:
break | 0 | null | 68,292,575,627,360 | 272 | 3 |
N = int(input())
S = input()
ans = 0
for n in range(N-2):
if S[n:n+3] == "ABC":
ans += 1
print(ans) | f=lambda:map(int,input().split())
n,d,a=f()
lt=sorted(tuple(f()) for _ in range(n))
from collections import *
q=deque()
c=s=0
for x,h in lt:
while q and q[0][0]<x: s+=q.popleft()[1]
h-=s
if h>0: t=-h//a; c-=t; s-=t*a; q.append((x+d*2,t*a))
print(c) | 0 | null | 90,702,508,891,070 | 245 | 230 |
from itertools import product
n = int(input())
test = []
for i in range(n):
a = int(input())
test.append([list(map(int, input().split())) for i in range(a)])
ans = 0
for i in product(range(2), repeat=n):
flag = True
for j in range(n):
if i[j] == 1:
for s in test[j]:
if i[s[0]-1] != s[1]:
flag = False
break
if flag == True:
cnt = i.count(1)
if cnt > ans:
ans = cnt
print(ans) | from itertools import product
def max2(x,y):
return x if x > y else y
N = int(input())
data = [[] for _ in range(N)]
res = 0
for i in range(N):
for _ in range(int(input())):
data[i].append(tuple(map(int, input().split())))
for a in product((0,1), repeat=N):
flg = False
for i in range(N):
for x, y in data[i]:
x -= 1
if a[i] == 1:
if a[x] != y:
flg = True
break
if flg:
break
if i == N-1:
res = max2(res, sum(a))
print(res)
| 1 | 121,554,777,111,938 | null | 262 | 262 |
n = int(input())
p = 10 ** 9 + 7
all_ptn = 10 ** n
anti_ptn = 2 * (9 ** n) - 8 ** n
print((all_ptn - anti_ptn) % p) | N = int(input())
mod = int(1e9) + 7
def doubling(n, m):
y = 1
bas = n
tmp = m
while tmp:
if tmp % 2:
y *= bas
y %= mod
bas *= bas
bas %= mod
tmp >>= 1
return y
d10 = doubling(10, N)
d9 = doubling(9, N)
d8 = doubling(8, N)
print((d10 - 2*d9 + d8) % mod) | 1 | 3,199,149,146,140 | null | 78 | 78 |
n,m,k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a_c_sum = [0]*(n + 1)
for i in range(n):
a_c_sum[i + 1] = a_c_sum[i] + a[i]
b_c_sum = [0]*(m + 1)
for i in range(m):
b_c_sum[i + 1] = b_c_sum[i] + b[i]
ans, best_b = 0, m
for i in range(n + 1):
if a_c_sum[i] > k:
break
else:
while 1:
if b_c_sum[best_b] + a_c_sum[i] <= k:
ans = max(ans, i + best_b)
break
else:
best_b -= 1
if best_b == 0:
break
print(ans) | N, M, K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
Asum = [0]
Bsum = [0]
a = 0
b = 0
for i in range(N):
a += A[i]
Asum.append(a)
for i in range(M):
b += B[i]
Bsum.append(b)
Asum.append(0)
Bsum.append(0)
res, j = 0, M
for i in range(N+1):
if Asum[i] > K:
break
while Asum[i] + Bsum[j] > K:
j -= 1
res = max(res,i+j)
print(res) | 1 | 10,784,277,859,382 | null | 117 | 117 |
N = int(input())
alp = {"a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9, "j":10}
alp2 = "abcdefghij"
def solve(N):
ans = []
if N == 1:
ans.append("a")
else:
pre = solve(N-1)
for i in range(len(pre)):
tmp = sorted(pre[i])
num = alp[tmp[len(tmp)-1]]
for j in range(num+1):
ans.append(pre[i]+alp2[j])
return ans
f_ans = solve(N)
f_ans.sort()
for i in range(len(f_ans)):
print(f_ans[i])
| while 1:
x,op,y = raw_input().split()
if op == "?":
break
x = int(x)
y = int(y)
if op == "+":
print x+y
elif op == "-":
print x-y
elif op == "*":
print x*y
else:
print x/y | 0 | null | 26,508,950,784,512 | 198 | 47 |
import statistics
N = int(input())
AB = [map(int, input().split()) for _ in range(N)]
A,B = [list(i) for i in zip(*AB)]
if N%2 == 1:
low_med = statistics.median(A)
high_med = statistics.median(B)
print(high_med - low_med +1)
else:
low_med = statistics.median(A)
high_med = statistics.median(B)
print(int(2 * (high_med - low_med) +1)) | def to_fizzbuzz(num: int) -> str:
if num % 15 == 0:
return 'FizzBuzz'
if num % 3 == 0:
return 'Fizz'
if num % 5 == 0:
return 'Buzz'
return str(num)
N = int(input())
answer = 0
for i in range(1, N + 1):
fb_str = to_fizzbuzz(i)
if fb_str.isdecimal():
answer += int(fb_str)
print(answer) | 0 | null | 26,159,046,804,280 | 137 | 173 |
import bisect
n,m = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
S = [0]*(n+1)
for i in range(n):
S[i+1] = S[i] + A[i]
def cnt(x,A,S):
res = 0
for i,a in enumerate(A):
res += bisect.bisect_left(A,x - a)
return res
def ans(x,A,S):
res = 0
for i,a in enumerate(A):
res += a*bisect.bisect_left(A,x-a) + S[bisect.bisect_left(A,x-a)]
return res
top = A[-1]*2+1
bottom = 0
# mid以上が何個あるか
while top - bottom > 1:
mid = (top + bottom)//2
if n*n - cnt(mid,A,S) > m:
bottom = mid
else:
top = mid
print(S[-1]*2*n - ans(top,A,S) + bottom*(m - (n*n - cnt(top,A,S))))
| a,b=map(int, input().split())
if 1<=a*b and a*b<=81 and a<10 and b<10:
print(a*b)
else:
print(-1)
| 0 | null | 133,226,480,304,540 | 252 | 286 |
# -*- coding: utf-8 -*-
# input
a, b = map(int, input().split())
x = list(map(int, input().split()))
print('Yes') if a <= sum(x) else print('No') | h,n = map(int,input().split())
xlist = list(map(int,input().split()))
if sum(xlist)>=h:
print("Yes")
else:
print("No") | 1 | 77,940,750,996,668 | null | 226 | 226 |
X,Y = map(int, input().split())
ans = "No"
for turtle in range(X+1):
crain = X - turtle
if 2 * crain + 4 * turtle == Y:
ans = "Yes"
print(ans) | x, y = map(int, input().split())
t = (4*x-y)/2
k = x - t
if (int(t) -t == 0) and (t>=0) and (k>=0):
print('Yes')
else:
print('No') | 1 | 13,631,543,333,760 | null | 127 | 127 |
while True:
try:
value = input().split(" ")
result = str(int(value[0]) + int(value[1]))
print(len(result))
except EOFError:
break | a, b = [int(i) for i in input().split(" ")]
num1 = a // b
num2 = a % b
num3 = "{:.8f}".format(a / b)
print(num1, num2, num3) | 0 | null | 290,715,219,038 | 3 | 45 |
#get input
n = input()
S = map(lambda x: int(x), input().split(' '))
q = input()
T = list(map(lambda x: int(x), input().split(' ')))
#create T set
T_set = set(T)
#iterate S and counting
count = 0
for i in S:
if i in T_set:
count += 1
T_set.remove(i)
print(count)
| n = int(input())
S = list(map(int, input().split()))
q = int(input())
T = list(map(int, input().split()))
count = 0
for i in range(q):
for j in range(n):
if T[i] == S[j]:
count += 1
break
print(count)
| 1 | 67,975,670,752 | null | 22 | 22 |
import sys
from collections import deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N,X,Y = map(int,readline().split())
ans = [0]*N
graph = [[] for _ in range(N)]
for i in range(N-1):
graph[i].append(i+1)
graph[i+1].append(i)
graph[X-1].append(Y-1)
graph[Y-1].append(X-1)
def bfs(x,q,dist):
while q:
v = q.popleft()
for nx in graph[v]:
if dist[nx] != 0:
continue
dist[nx] = dist[v] + 1
q.append(nx)
if nx > x:
ans[dist[nx]] +=1
for i in range(N):
dist = [0]*N
q = deque([i])
bfs(i,q,dist)
print('\n'.join(str(n) for n in ans[1:])) | import sys
from collections import defaultdict
# from collections import Counter
# from queue import PriorityQueue
# sys.setrecursionlimit(2000000)
def distance(X, Y, start, goal):
ans = float('inf')
tmp = goal - start
if tmp < ans:
ans = tmp
# start ~ X ~ Y ~ goal,
tmp = abs(X - start) + 1 + abs(goal - Y)
if tmp < ans:
ans = tmp
# start ~ Y ~ X ~ goal
tmp = abs(Y - start) + 1 + abs(goal - X)
if tmp < ans:
ans = tmp
return ans
# # 短絡パスを使える場合
# if start <= X and Y <= goal
# # 短絡パスを使えないならば、普通に距離を計算
# if X < start:
# return goal - start
# # 短絡パスを使えても、隣のパスへの距離は1
# if goal - start == 1:
# return 1
# # 短絡パスより手前だと使えない
# if goal < Y:
# return goal - start
# return goal - start - 1
def main():
# N = int(input())
N, X, Y = [int(s) for s in input().split()]
distance_dict = defaultdict(int)
for i in range(1, N+1):
for j in range(i + 1, N+1):
d = distance(X, Y, i, j)
# sys.stderr.write('{} to {} : d = {}\n'.format(i, j, d))
# ditance_dict[(i, j)] = d
distance_dict[d] += 1
for k in range(1, N):
# print(str(distance_dict[k]))
print(distance_dict[k])
# As = []
# Bs = []
# for i in range(N):
# A, B = [int(s) for s in input().split()]
# As.append(A)
# Bs.append(B)
return 0
if __name__ == '__main__':
sys.exit(main())
| 1 | 44,028,892,160,930 | null | 187 | 187 |
from collections import deque
import sys
c=sys.stdin
def main():
q = deque()
N=int(input())
for i in range(N):
order=c.readline()
if order[6]==" ":
if order[0]=="i":
q.appendleft(int(order[7:]))
else:
try :
q.remove(int(order[7:]))
except:
pass
else:
if order[6]=="F":
q.popleft()
else:
q.pop()
print(*list(q))
if __name__ == "__main__":
main()
| from collections import deque
deq = deque()
n = int(input())
for _ in range(n):
operation = input()
if operation == "deleteFirst":
deq.popleft()
elif operation == "deleteLast":
deq.pop()
else:
command, value = operation.split()
if command == "insert":
deq.appendleft(int(value))
elif command == "delete":
try:
deq.remove(int(value))
except ValueError:
pass
print(*deq)
| 1 | 52,056,431,438 | null | 20 | 20 |
import sys
read = sys.stdin.buffer.read
def main():
N, K, *AF = map(int, read().split())
A = AF[:N]
F = AF[N:]
A.sort()
F.sort(reverse=True)
ok = pow(10, 12)
ng = -1
while ok - ng > 1:
mid = (ok + ng) // 2
k = 0
for i in range(N):
if A[i] * F[i] > mid:
k += A[i] - mid // F[i]
if k <= K:
ok = mid
else:
ng = mid
print(ok)
return
if __name__ == '__main__':
main()
| N, K = map(int, input().split())
A = list(map(int, input().split()))
F = list(map(int, input().split()))
A.sort(reverse=True)
F.sort()
C = [None] * N
for i, (a, f) in enumerate(zip(A, F)):
C[i] = (a * f, f)
def solve(x):
global K, N
t = 0
for c, f in C:
temp = ((c - x) + f - 1) // f
t += max(0, temp)
if t > K:
result = False
break
else:
result = True
return result
ok = A[0] * F[N - 1]
ng = -1
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if solve(mid):
ok = mid
else:
ng = mid
print(ok)
| 1 | 164,466,936,774,268 | null | 290 | 290 |
N=int(input())
A = sorted(map(int, input().split()), reverse=True)
if N%2==1:
print(sum(A[0:(N-1)//2])+sum(A[1:(N+1)//2]))
else:
print(sum(A[0:N//2])+sum(A[1:N//2]))
| n, q = map(int, input().split())
l = []
for i in range(n):
t = []
for j in input().split():
t += [j]
t[1] = int(t[1])
l += [t]
c = 0
while len(l) > 0:
if l[0][1] > q:
l[0][1] -= q
l += [l[0]]
l.pop(0)
c += q
else:
c += l[0][1]
print(l[0][0], c)
l.pop(0)
| 0 | null | 4,649,020,723,802 | 111 | 19 |
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
#from fractions import gcd
#input=sys.stdin.readline
import bisect
s=input()
if s[-1]=="s":
print(s+"es")
else:
print(s+"s") | import numpy as np
from fractions import gcd
def lcm(a,b):
return a*b//gcd(a,b)
N,M=map(int,input().split())
a=[i//2 for i in map(int,input().split())]
b=np.array(a)
cnt=0
while all(b%2==0):
b//=2
if any(b%2==0):
print(0)
exit()
ans=1
for i in a:
ans=lcm(ans,i)
print((M//ans-1)//2+1)
| 0 | null | 51,837,671,112,368 | 71 | 247 |
W = input().rstrip().lower()
ans = 0
while True:
line = input().rstrip()
if line == 'END_OF_TEXT': break
line = line.lower().split(' ')
for word in line:
if word == W: ans += 1
print(ans)
| one_word = raw_input()
word_count = 0
word_list = []
while 1:
temp = raw_input()
word_list += temp.split()
if word_list[len(word_list)-1] == "END_OF_TEXT":
break
for word in word_list:
if one_word.lower() == word.lower():
word_count += 1
print word_count | 1 | 1,819,436,986,918 | null | 65 | 65 |
def main():
target_word = str(input()).lower()
texts_tuple = tuple()
while True:
text = input()
if text == 'END_OF_TEXT': break
texts_tuple += tuple(text.lower().split())
print(texts_tuple.count(target_word))
main() | def main():
Counter = 0
Text_W = input()
while True:
Text_T = input()
if "END_OF_TEXT" in Text_T:
temp = Text_T.lower().split()
for i in range(len(temp)):
Counter += 1 if Text_W == temp[i] else 0
break
else:
temp = Text_T.lower().split()
for i in range(len(temp)):
Counter += 1 if Text_W == temp[i] else 0
print (Counter)
if __name__ == '__main__':
main()
| 1 | 1,838,112,671,560 | null | 65 | 65 |
import math
t1,t2 = map(int,(input().split(' ')))
a1,a2 = map(int,(input().split(' ')))
b1,b2 = map(int,(input().split(' ')))
n = t1*a1+t2*a2
m = t1*b1+t2*b2
if(n==m):
print("infinity")
exit(0)
ans1 = max(0,math.ceil((b1-a1)*t1/(n-m)))
ans2 = max(0,math.ceil((t1*(b1-a1)+t2*(b2-a2))/(n-m))-1)
#if((t1*(b1-a1))%(n-m) == 1):
# ans3 = 1
#else:
# ans3 = 0
ans3 = max(0,math.floor(t1*(b1-a1)/(n-m))+1)
print(max(ans1+ans2+ans3-1,0)) | n, m = map(int, input().split())
print("YNeos"[n != m::2]) | 0 | null | 107,683,933,572,640 | 269 | 231 |
#!/usr/bin/env python3
from pprint import pprint
import sys
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
n = int(input())
x = input()
x_pc = x.count('1')
x_pc_plus = x_pc + 1
x_pc_minus = x_pc - 1
# 2 ** i % x_pc_plus, 2 ** i % x_pc_minus を予め計算しておく
r_plus_list = [pow(2, i, x_pc_plus) for i in range(n+1)]
r_minus_list = [0] * (n+1)
if x_pc_minus > 0:
r_minus_list = [pow(2, i, x_pc_minus) for i in range(n+1)]
x = x[::-1]
r_plus = 0
r_minus = 0
for i in range(n):
if x[i] == '1':
r_plus += r_plus_list[i]
r_minus += r_minus_list[i]
for i in range(n-1, -1, -1):
if x[i] == '0':
diff = (r_plus + r_plus_list[i]) % x_pc_plus
elif x_pc_minus >= 1:
diff = (r_minus - r_minus_list[i]) % x_pc_minus
else:
print(0)
continue
ans = 1
while diff > 0:
diff = diff % bin(diff).count('1')
ans += 1
print(ans)
| N, S = map(int, input().split())
A = list(map(int, input().split()))
MOD = 998244353
dp = [[0] * (S + 1) for _ in range(N + 1)]
dp[0][0] = 1
for i, a in enumerate(A):
for j in range(S + 1):
dp[i + 1][j] += 2 * dp[i][j]
dp[i + 1][j] %= MOD
if j + a <= S:
dp[i + 1][j + a] += dp[i][j]
dp[i + 1][j + a] %= MOD
print(dp[-1][-1] % MOD)
| 0 | null | 13,004,181,402,550 | 107 | 138 |
MOD = 10**9 + 7
N = int(input())
x = pow(10, N, MOD)
x -= pow(9, N, MOD) * 2
x += pow(8, N, MOD)
print(x % MOD) | def input_array():
return list(map(int,input().split()))
n=int(input())
D=[input_array() for i in range(n)]
count=0
for d in D:
if d[0]==d[1]:
count+=1
else:
count=0
if count==3:
break
if count==3:
print("Yes")
else:
print("No") | 0 | null | 2,868,086,309,818 | 78 | 72 |
def main():
a,b,c=map(int,input().split())
k = int(input())
for i in range(k):
if a < b < c:
break
elif a >= b:
b *= 2
elif b >= c:
c *= 2
if a < b < c:
print('Yes')
else:
print('No')
main() | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip() # ignore trailing spaces
ans = collections.deque(ns())
q = ni()
now = 0
for i in range(q):
query = ns().split(' ')
if query[0] == '1':
now = 1 - now
else:
f, c = query[1], query[2]
if f == '1':
if now == 1:
ans.append(c)
else:
ans.appendleft(c)
else:
if now != 1:
ans.append(c)
else:
ans.appendleft(c)
if now == 1:
for i in range(len(ans)):
print(ans[-(i+1)], end="")
else:
for i in range(len(ans)):
print(ans[i], end="")
print() | 0 | null | 31,973,002,131,080 | 101 | 204 |
N = int(input())
if (N % 10 == 0) or (N % 10 == 1) or (N % 10 == 6) or (N % 10 == 8):
print("pon")
elif N % 10 == 3:
print("bon")
else:
print("hon") | n,k,*a=map(int, open(0).read().split())
b=[0]*-~n
for i in range(n):b[i+1]=(a[i]+b[i]-1)%k
d={k:0}
a=0
for l,r in zip([k]*min(k,n+1)+b,b):d[l]-=1;t=d.get(r,0);a+=t;d[r]=t+1
print(a) | 0 | null | 78,476,982,501,650 | 142 | 273 |
import sys
input = sys.stdin.readline
#n = int(input())
#l = list(map(int, input().split()))
'''
a=[]
b=[]
for i in range():
A, B = map(int, input().split())
a.append(A)
b.append(B)'''
def cal(n,li):
lis=[True]*(n+1)
for item in li:
if lis[item]:
for i in range(item*2,n+1,item):
lis[i]=False
return lis
from collections import Counter
n=int(input())
a=list(map(int,input().split()))
a.sort()
l=cal(a[-1],a)
ll=Counter(a)
#print(l,ll)
ans=0
for i in range(n):
if ll[a[i]]==1:
if l[a[i]]:
ans+=1
print(ans)
| import sys
from collections import Counter
import numba as nb
import numpy as np
input = sys.stdin.readline
@nb.njit("i8(i8[:],i8[:])", cache=True)
def solve(keys, values):
MAX_A = 10 ** 6
divisible = [False] * (MAX_A + 1)
ans = 0
for k, v in zip(keys, values):
if v == 1 and not divisible[k]:
ans += 1
for i in range(k, MAX_A + 1, k):
divisible[i] = True
return ans
def main():
N = int(input())
A = list(map(int, input().split()))
A.sort()
c = Counter(A)
keys = np.array(tuple(c.keys()), dtype=np.int64)
values = np.array(tuple(c.values()), dtype=np.int64)
ans = solve(keys, values)
print(ans)
if __name__ == "__main__":
main()
| 1 | 14,442,034,081,960 | null | 129 | 129 |
import statistics
while True:
n = input()
if n == '0': break
print(statistics.pstdev(map(int, input().split()))) | N, T = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(N)]
Dp = [0 for _ in range(T+1)]
ab = sorted(ab, key = lambda x: x[0])
for i in range(N):
for j in range(T-1,-1, -1):
if j+ab[i][0] <= T-1:
kari2 = Dp[j] + ab[i][1]
if Dp[j+ab[i][0]] < kari2:
Dp[j+ab[i][0]] = kari2
else:
kari2 = Dp[j] +ab[i][1]
if Dp[T] < kari2:
Dp[T] = kari2
print(max(Dp)) | 0 | null | 75,913,588,532,970 | 31 | 282 |
n = int(input());print(n//2 if n%2==1 else n//2 -1) | a = str(input())
if a[0] == a[1] != a[2]:
print("Yes")
elif a[1] == a[2] != a[0]:
print("Yes")
elif a[0] == a[2] != a[1]:
print("Yes")
else:
print("No") | 0 | null | 104,020,373,563,090 | 283 | 201 |
n = int(input())
if n>=3:
if n%2==0:
print(n//2-1)
else:
print(n//2)
else:
print(0) | N,K=map(int, input().split())
def change(N,shinsu):
keta=0
for i in range(10**9):
if N<shinsu**i:
keta+=i
break
ans=[0]*keta
check=0
for i in range(1,keta+1):
j=N//(shinsu**(keta-i))
ans[check]=j
check+=1
N-=(j)*(shinsu**(keta-i))
return ans
print(len(change(N,K))) | 0 | null | 108,378,018,238,868 | 283 | 212 |
def gcd(a, b):
c = max([a, b])
d = min([a, b])
if c % d == 0:
return d
else:
return gcd(d, c % d)
nums = input().split()
print(gcd(int(nums[0]), int(nums[1])))
| n = input().split()
x = int(n[0])
y = int(n[1])
if x < y:
bf = x
x = y
y = bf
while y > 0:
r = x % y
x = y
y = r
print(str(x)) | 1 | 8,309,251,090 | null | 11 | 11 |
x = int(input())
m = divmod(x, 500)
print(m[0] * 1000 + m[1] // 5 * 5) | # 2:01
X = int(input())
ans = 0
ans += X // 500 * 1000
X %= 500
ans += X // 5 * 5
print(ans)
| 1 | 42,540,281,417,438 | null | 185 | 185 |
N, M, K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
sumA = [0]
sumB = [0]
tmp = 0
answer = 0
st = 0
for i in range(N):
tmp = tmp + A[i]
sumA.append(tmp)
tmp = 0
for i in range(M):
tmp = tmp + B[i]
sumB.append(tmp)
for i in range(N, -1, -1):
booktmp = 0
for j in range(st, M + 1):
if sumA[i] + sumB[j] <= K:
booktmp = i + j
else:
st = j
break
answer = max(answer, booktmp)
if j == M:
break
print(answer)
| # ==================================================-
# 二分探索
# functionを満たす,search_listの最大の要素を出力
# 【注意点】searchリストの初めの方はfunctionを満たし、後ろに行くにつれて満たさなくなるべき
import math
import sys
sys.setrecursionlimit(10 ** 9)
def binary_research(start, end,function):
if start == end:
return start
middle = math.ceil((start + end) / 2)
if function(middle, k, a_sum, b_sum):
start = middle
else:
end = middle - 1
return binary_research(start, end, function)
# ==================================================-
n, m, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
a_sum = [0]
b_sum = [0]
for book in a:
a_sum.append(a_sum[-1] + book)
for book in b:
b_sum.append(b_sum[-1] + book)
def can_read(num, k, a_sum, b_sum):
min_read_time = 1000000000000
for i in range(max(0, num - m), min(num+1,n+1)):
a_num = i
b_num = num - i
min_read_time = min(min_read_time, a_sum[a_num] + b_sum[b_num])
if min_read_time <= k:
return True
return False
start = 0
end = n + m
print(binary_research(start, end, can_read)) | 1 | 10,806,287,593,880 | null | 117 | 117 |
#k = int(input())
#s = input()
#a, b = map(int, input().split())
#l = list(map(int, input().split()))
s = input()
if s[0] != s[1] or s[1] != s[2] or s[0] != s[2]:
print ("Yes")
else:
print("No")
| import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
S = readline().decode()
if 'A' in S and 'B' in S:
print('Yes')
else:
print('No') | 1 | 54,680,558,986,582 | null | 201 | 201 |
import sys
input = sys.stdin.readline
S=tuple(input().strip())
N=len(S)+1
sets = []
count = 0
for c in S:
d = 1 if c == '<' else -1
if count * d < 0:
sets.append(count)
count = d
else:
count += d
sets.append(count)
sum = 0
for i in range(len(sets)):
k=sets[i]
if k > 0:
sum += (k*(k+1))//2
else:
sum += (k*(k-1))//2
if i > 0:
sum -= min(sets[i-1], -k)
print(sum)
| S = input()
count_more = 0
count_less = 0
ans = 0
pre_si = '>'
for i, si in enumerate(S):
if pre_si == '>' and si == '<':
max_n = max(count_more, count_less)
min_n = min(count_more, count_less)
ans += (max_n+1)*(max_n)//2
# print(i, ans)
ans += (min_n)*(min_n-1)//2
count_more = 0
count_less = 0
# print(i, ans)
if si == '<':
count_more += 1
elif si == '>':
count_less += 1
pre_si = si
max_n = max(count_more, count_less)
min_n = min(count_more, count_less)
ans += (max_n+1)*(max_n)//2
ans += (min_n)*(min_n-1)//2
print(ans)
| 1 | 156,097,737,578,348 | null | 285 | 285 |
A,B = map(int,(input().split()))
l = 0
if A > B:
l = A
s = B
else:
l = B
s = A
for i in range(1,10**10):
if (l*i)%s == 0:
print(l*i)
exit()
else:
continue | h, n = [int(i) for i in input().split()]
magics = [None]
class Magic:
def __init__(self, attack, cost):
self.attack = attack
self.cost = cost
maxA = 0
for i in range(n):
attack, cost = [int(i) for i in input().split()]
maxA = max(maxA, attack)
magics.append(Magic(attack, cost))
dp = [[10 ** 9 for i in range(h + maxA)] for j in range(n + 1)]
for i in range(n + 1):
for j in range(h + maxA):
if j == 0:
dp[i][j] = 0
elif i == 0:
continue
elif j - magics[i].attack >= 0:
dp[i][j] = min(dp[i - 1][j], dp[i][j - magics[i].attack] + magics[i].cost)
else:
dp[i][j] = dp[i - 1][j]
print(min(dp[-1][h:]))
| 0 | null | 97,570,814,693,408 | 256 | 229 |
n = input()
d = [99999 for i in range(n)]
G = [0 for i in range(n)]
v = [[0 for i in range(n)] for j in range(n)]
def bfs(u):
for i in range(n):
if v[u][i] == 1:
if d[i] > d[u] + 1:
d[i] = d[u] + 1
bfs(i)
else:
continue
def _():
d[0] = 0
for i in range(n):
bfs(i)
for i in range(n):
if d[i] == 99999:
d[i] = -1
for i in range(n):
print '{0} {1}'.format(i+1, d[i])
for i in range(n):
G = map(int, raw_input().split())
for j in range(G[1]):
v[G[0]-1][G[2+j]-1] = 1
_() | import math
ni = int(input())
xi = map(int, raw_input().split())
yi = map(int, raw_input().split())
p1 = []
p2 = []
p3 = []
p4 = []
for x, y in zip(xi, yi):
p1.append(abs(x - y))
p2.append(abs(x - y)**2)
p3.append(abs(x - y)**3)
p4.append(abs(x - y))
print '%.8f' % reduce(lambda x, y: x + y, p1)
print '%.8f' % reduce(lambda x, y: x + y, p2) ** (1.0/2.0)
print '%.8f' % reduce(lambda x, y: x + y, p3) ** (1.0/3.0)
print '%.8f' % max(p4) | 0 | null | 103,506,907,140 | 9 | 32 |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def main():
S = input()
if S[-1] == 's':
print(S+'es')
else:
print(S+'s')
if __name__ == '__main__':
main()
| N = input()
if N.endswith('s'):
print(N + 'es')
else:
print(N + 's')
| 1 | 2,380,920,566,528 | null | 71 | 71 |
N, K = map(int, input().split())
moves = [0] + list(map(int, input().split()))
points = [0] + list(map(int, input().split()))
INF = 10**10
arrived = [0 for _ in range(N+1)]
answer = -INF
for move in range(1, N+1):
if arrived[move] == 1:
continue
else:
arrived[move] = 1
komas = [move]
next = moves[move]
while(arrived[next] == 0):
arrived[next] = 1
komas.append(next)
next = moves[next]
len_k = len(komas)
sum_k = [0 for _ in range(len_k*2)]
sum_k[0] = points[komas[0]]
for i in range(1, len_k*2):
sum_k[i] = sum_k[i-1] + points[komas[i%len_k]]
scores = [-INF for _ in range(len_k+1)]
for j in range(len_k):
for k in range(1, len_k+1):
scores[k] = max(scores[k], sum_k[j+k] - sum_k[j])
if K > len_k and scores[len_k] > 0:
max_s = -INF
max_k = -INF
for m in range(1, len_k+1):
if m <= K%len_k:
max_k = max(max_k, scores[m])
max_s = max(max_s, scores[m])
answer = max(answer, max_k+scores[len_k]*(K//len_k), max_s+scores[len_k]*(K//len_k-1))
else:
max_s = -INF
for m in range(1, min(K, len_k)+1):
max_s = max(max_s, scores[m])
answer = max(answer, max_s)
print(answer) | N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
P=[i-1 for i in P]
idle_max=-10**27
for s in range(0,N):
k=K-1
score=0
s=P[s]
score+=C[s]
count=1
idle_max=max(idle_max,score)
visited={s:[count,score]}
while k and not P[s] in visited:
k-=1
count+=1
s=P[s]
score+=C[s]
visited[s]=[count,score]
idle_max=max(idle_max,score)
#print(visited)
if k:
c1,score1=visited[s]
c2,score2=visited[P[s]]
c1+=1
s=P[s]
score1+=C[s]
score+=C[s]
k-=1
n=c1-c2
score+=(score1-score2)*(k//n)
k%=n
idle_max=max(idle_max,score)
while k:
k-=1
s=P[s]
score+=C[s]
idle_max=max(idle_max,score)
print(idle_max)
| 1 | 5,345,849,593,260 | null | 93 | 93 |
# usr/bin/python
# coding: utf-8
################################################################################
# Is it a Right Triangle?
# Write a program which judges wheather given length of three side form a right triangle.
# Print "YES" if the given sides (integers) form a right triangle, "NO" if not so.
#
# Input
# Input consists of several data sets. In the first line, the number of data set,
# N is given. Then, N lines follow, each line corresponds to a data set.
# A data set consists of three integers separated by a single space.
#
# Constraints
# 1 ??? length of the side ??? 1,000
# N ??? 1,000
# Output
# For each data set, print "YES" or "NO".
#
# Sample Input
# 3
# 4 3 5
# 4 3 6
# 8 8 8
# Output for the Sample Input
# YES
# NO
# NO
#
################################################################################
if __name__ == "__main__":
num = int(input())
inputline = [""]*num
for i in range(0,num):
inputline[i] = input()
for line in inputline:
a = int(line.split(" ")[0])
b = int(line.split(" ")[1])
c = int(line.split(" ")[2])
if (a*a+b*b == c*c or b*b+c*c == a*a or c*c+a*a == b*b):
print("YES")
else:
print("NO") | import sys
for line in range(int(input())):
str = input().split(" ")
nums = sorted([int(str[2]), int(str[1]), int(str[0])])
if nums[2]*nums[2] == nums[1]*nums[1] + nums[0]*nums[0]:
print("YES")
else:
print("NO") | 1 | 231,722,400 | null | 4 | 4 |
N = int(input())
S = input()
res = 0
f = S[0]
for i in range(N):
if S[i] != f:
f = S[i]
res += 1
print(res+1) | n = int(input())
a = list(map(int,input().split()))
a.sort()
t = 1
for i in range(len(a)):
t *= a[i]
if t > 10**18:
break
if t > 10**18 :
print("-1")
else:
print(str(t)) | 0 | null | 93,112,565,615,268 | 293 | 134 |
import sys, bisect
N = int(input())
L = list(map(int, sys.stdin.readline().rsplit()))
L.sort()
res = 0
for i in reversed(range(1, N)):
for j in reversed(range(i)):
l = bisect.bisect_left(L, L[i] + L[j])
# r = bisect.bisect_right(L, abs(L[i] - L[j]))
res += l - 1 - i
print(res)
| #それゆけにぶたんまん
#python3.8.2のTLEの壁に阻まれました
n = int(input())
l = sorted(list(map(int,input().split())))
ans = 0
for i in range(n):
for j in range(i+1,n):
#jより大きい整数kでl[k]<l[i]+l[j]を満たす最大のk
le = j
ri = n
while ri-le>1:
m = (ri+le)//2
if l[m]<l[i]+l[j]:
le = m
else:
ri = m
ans += le-j
print(ans)
| 1 | 172,122,607,886,932 | null | 294 | 294 |
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
wins = {"p":"s", "r":"p", "s":"r"}
points = {"p":S, "r":P, "s":R}
hands = []
ans = 0
for i in range(N):
if i - K < 0:
hands.append(wins[T[i]])
ans += points[T[i]]
else:
if hands[i-K] == wins[T[i]]:
#あいこにするしか無い時
hands.append("-")
else:
#勝てる時
hands.append(wins[T[i]])
ans += points[T[i]]
print(ans)
| import sys
n,x,m = map(int,input().split())
lst_sum = [0,x]
loop = [0]*(10**5)
loop[x] = 1
s = 1
for i in range(2,n+1):
y = ((lst_sum[-1] - lst_sum[-2])**2)%m
if loop[y] != 0:
l = i-loop[y]
d = (n-loop[y]+1) // l
q = (n-loop[y]+1) % l
sum_loop = lst_sum[-1]-lst_sum[loop[y]-1]
sum_first = lst_sum[loop[y]-1]
if q == 0:
sum_rest = 0
else:
sum_rest = lst_sum[loop[y] + q-1] - lst_sum[loop[y]-1]
print(sum_first+d*sum_loop+sum_rest)
sys.exit()
else:
s += 1
loop[y] = s
lst_sum.append(lst_sum[-1] + y)
print(lst_sum[-1])
| 0 | null | 54,870,638,228,960 | 251 | 75 |
from fractions import gcd
def lcm(*args):
ans = 1
for x in args:
ans = ans * x // gcd(ans, x)
return ans
n, m = map(int, input().split())
a = [int(x) for x in input().split()]
def log(x):
ans = 0
while x % 2 == 0:
ans += 1
x //= 2
return ans
def solve(a):
tmp = None
for ta in a:
if tmp is None:
tmp = log(ta)
else:
if tmp == log(ta):
continue
else:
print(0)
return
l = lcm(*a)
print(m // (l//2) - m // l)
solve(a) | from math import gcd
n, m = (int(x) for x in input().split())
A = list(int(x) for x in input().split())
B = [a // 2 for a in set(A)]
lcm = 1
div2_count = -1
for b in B:
lcm = lcm * b // gcd(lcm, b)
if lcm > m:
print(0)
exit()
count = 0
while b % 2 == 0:
b //= 2
count += 1
if div2_count == -1 or div2_count == count:
div2_count = count
else:
print(0)
exit()
limit = m // lcm
ans = (limit + 1) // 2
print(ans) | 1 | 101,865,587,237,688 | null | 247 | 247 |
n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
def solve(start):
loop = []
llen = 0
lsum = 0
reach = [0]*n
now = start
while True:
nxt = P[now]-1
loop.append(now)
llen += 1
lsum += C[now]
reach[now] = 1
if reach[nxt]:
break
now = nxt
if lsum <= 0 or llen >= k:
res = -10 ** 20
s = 0
now = start
for i in range(min(llen, k)):
s += C[now]
res = max(res, s)
now = P[now]-1
return res
else:
s = lsum * (k // llen)
now = start
for i in range(k % llen):
s += C[now]
now = P[now]-1
j = loop.index(now)
res = -10**20
for i in range(llen):
j -= 1
res = max(res, s)
s -= C[loop[j]]
return res
def solver():
ans = -10 ** 20
for i in range(n):
ans = max(ans, solve(i))
return ans
print(solver())
| from itertools import accumulate
N, K, *PC = map(int, open(0).read().split())
P, C = [0] + PC[:N], [0] + PC[N:]
ans = float("-inf")
for start in range(1, N + 1):
path = []
cur = P[start]
path = [C[start]]
while cur != start:
path.append(C[cur])
cur = P[cur]
A = list(accumulate(path))
q, r = divmod(K, len(path))
res = 0
if A[-1] >= 0:
if r == 0:
q -= 1
r += len(path)
res += A[-1] * q
elif q >= 1:
r = len(path)
ans = max(ans, res + max(A[:r]))
print(ans) | 1 | 5,406,211,631,380 | null | 93 | 93 |
N = int(input())
S = input()
cnt = 1
last = S[0]
for s in S:
if last == s:
continue
else:
cnt += 1
last = s
print(cnt) | def main():
L, R, d = map(int, input().split())
ans = 0
for i in range(L, R + 1):
if i % d == 0:
ans += 1
print(ans)
if __name__ == "__main__":
main() | 0 | null | 88,923,060,802,212 | 293 | 104 |
for x in range(1, 10):
for y in range(1, 10):
print(x , "x" , y , "=" , x*y, sep = "")
| for i in xrange(1, 10):
for j in xrange(1, 10):
print "%sx%s=%s" % (i,j, i*j) | 1 | 2,111,128 | null | 1 | 1 |
l, r, d = [int(x) for x in input().rstrip().split(" ")]
print(r//d-l//d + (l%d==0)) | T1, T2 = map(int, input().split())
A1, A2 = map(int, input().split())
B1, B2 = map(int, input().split())
a1 = T1 * A1
a2 = T2 * A2
a = a1 + a2
b1 = T1 * B1
b2 = T2 * B2
b = b1 + b2
def bis(p, ok, ng):
mid = (ok + ng) // 2
return (
ok if abs(ok - ng) == 1 else
bis(p, mid, ng) if p(mid) else
bis(p, ok, mid)
)
def p(k):
x = k * a
y = k * b
# print(f"k: {k}, x: {x}, y: {y}")
#print(f"k: {k}, x+: {x + a1}, y+: {y + b1}")
if x < y:
return x + a1 >= y + b1
else:
return y + b1 >= x + a1
def p2(k):
x = k * a + a1
y = k * b + b1
if x < y:
return x + a2 >= y + b2
elif x > y:
return y + b2 >= x + a2
else:
return False
if a == b:
ans = "infinity"
else:
# print(bis(p, -1, 10**16))
# print(bis(p2, -1, 10**16))
c = 1 if (a1 < b1 and a > b) or (b1 < a1 and b > a) else 0
# k = bis(lambda k: k * a + a1 >= k * b + b1, 0, 10**16) if a < b else bis(lambda k: k * a + a1 <= k * b + b1, 0, 10**16)
# d = if k * a + a1 == k * b + b1
ans = bis(p, 0, 10**16) + bis(p2, 0, 10**16) + c
print(ans)
# print('-------')
# x = 0
# y = 0
# for i in range(114):
# x += a1
# y += b1
# #print(x, y)
# print(f"{i} {x < y}")
# x += a2
# y += b2
# print(f"{i} {x < y}")
# #print(x, y)
| 0 | null | 69,458,374,815,698 | 104 | 269 |
x,y=map(int,input().split())
c=x%y
while c!=0:
x=y
y=c
c=x%y
print(y)
| # Euclidean algorithm
def gcd(x, y):
if x < y:
x, y = y, x
while y > 0:
r = x % y
x = y
y = r
return x
print(gcd(*map(int, input().split()))) | 1 | 7,711,623,480 | null | 11 | 11 |
import math
x1,y1,x2,y2 = map(float,raw_input().split())
r = math.sqrt(abs((x1-x2)**2+(y1-y2)**2))
print r | N,M=list(map(int, input().split()))
P=[0]*M
S=[0]*M
for i in range(M):
P[i],S[i]=list(input().split())
P[i]=int(P[i])
flagac=[False]*N
pnlt=[0]*N
for i in range(M):
p=P[i]-1
s=S[i]
if s=='AC':
flagac[p]=True
else:
pnlt[p]+=(flagac[p]+1)%2
# print(flagac)
# print(pnlt)
ctac=0
ctwa=0
for i in range(N):
if flagac[i]:
ctac+=1
ctwa+=pnlt[i]
print(ctac, ctwa) | 0 | null | 46,716,083,069,150 | 29 | 240 |
import sys
def input():
return sys.stdin.readline().strip()
n, d, a = map(int, input().split())
x = []
h = {} # x:h
for _ in range(n):
i, j = map(int, input().split())
x.append(i)
h[i] = j
x.sort()
x.append(x[-1] + 2*d + 1)
# attackで累積和を用いる
ans = 0
attack = [0 for _ in range(n+1)]
for i in range(n):
attack[i] += attack[i-1]
if attack[i] >= h[x[i]]:
continue
if (h[x[i]] - attack[i]) % a == 0:
j = (h[x[i]] - attack[i]) // a
else:
j = (h[x[i]] - attack[i]) // a + 1
attack[i] += a * j
ans += j
# 二分探索で、x[y] > x[i] + 2*d、を満たす最小のyを求める
# start <= y <= stop
start = i + 1
stop = n
k = stop - start + 1
while k > 1:
if x[start + k//2 - 1] <= x[i] + 2*d:
start += k//2
else:
stop = start + k//2 - 1
k = stop - start + 1
attack[start] -= a * j
print(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)]
n = inN()
s = input()
r = s.count('R')
b = s.count('B')
g = s.count('G')
cnt = 0
for i in range(n):
for j in range(i+1,n):
k = 2*j - i
if k < n:
if s[i] != s[j] and s[j] != s[k] and s[i] != s[k]:
cnt += 1
print(r*g*b - cnt) | 0 | null | 59,560,268,638,364 | 230 | 175 |
import math
N = int(input())
x = []
y = []
for i in range(N):
tmp = input().split(" ")
x.append(int(tmp[0]))
y.append(int(tmp[1]))
d = 0
for i in range(N):
for j in range(N):
d += math.sqrt((x[j]-x[i]) ** 2 + (y[j]-y[i]) ** 2)
print(d/N) | from itertools import permutations
import math
n = int(input())
x,y = [],[]
for _ in range(n):
x_, y_ =map(int,input().split())
x.append(x_)
y.append(y_)
c = list(permutations([i for i in range(1,n+1)],n))
g = [[-1]*(n+1) for _ in range(n+1)]
sum = 0
for ci in (c):
tmp = 0
for i in range(len(ci)-1):
if g[ci[i]][ci[i+1]] == -1:
tmp += math.sqrt((x[ci[i]-1]-x[ci[i+1]-1])**2
+ (y[ci[i]-1]-y[ci[i+1]-1])**2)
else:
tmp += g[ci[i]][ci[i+1]]
sum += tmp
print(sum/len(c)) | 1 | 148,578,605,518,508 | null | 280 | 280 |
class UnionFind():
def __init__(self, N):
# parent of each node
self.parent = [n for n in range(N)]
# number of nodes in union
self.rank = [1] * N
def find(self, u):
if self.parent[u] == u:
return u
else:
# recursive call
return self.find(self.parent[u])
def union(self, u, v):
pu = self.find(u)
pv = self.find(v)
# same union
if pu == pv:
return
# let pv join into pu union
if self.rank[pu] < self.rank[pv]:
pu, pv = pv, pu
self.rank[pu] += self.rank[pv]
self.parent[pv] = pu
N, M = map(int, input().split())
UF = UnionFind(N)
for _ in range(M):
A, B = map(int, input().split())
A, B = A-1, B-1
UF.union(A, B)
ret = 0
for n in range(N):
ret = max(ret, UF.rank[n])
print(ret)
| from math import floor
X = int(input())
deposit, year = 100, 0
while deposit < X:
deposit += deposit // 100
year += 1
print(year) | 0 | null | 15,453,676,307,460 | 84 | 159 |
print "\n".join(["%dx%d=%d"%((i/10+1),(i%10),(i/10+1)*(i%10)) for i in xrange(90)if i%10!=0]) | import sys
import math
prime_numbers = [2, 3, 5, 7]
def prime_numbers_under(num):
global prime_numbers
prime_number_max = max(prime_numbers)
if prime_number_max > num:
return prime_numbers
for i in range(prime_number_max + 1, num + 1):
check_max = math.floor(math.sqrt(i))
for j in prime_numbers:
if j <= check_max:
if i % j == 0:
break
else:
prime_numbers.append(i)
return prime_numbers
def main():
amount = 0
length = int(input())
for _ in range(0, length):
i = int(input())
check_max = math.floor(math.sqrt(i))
for j in prime_numbers_under(check_max):
if j <= check_max:
if i % j == 0:
break
else:
amount += 1
print(amount)
return 0
if __name__ == '__main__':
main() | 0 | null | 5,489,036,266 | 1 | 12 |
n,k=map(int,input().split())
ans=[0 for _ in range(n*3)]
ans[1]=1
idou=[]
for _ in range(k):
a=list(map(int,input().split()))
idou.append(a)
mod=998244353
rui=[0 for _ in range(n+1)]
rui[1]=1
for i in range(2,n+1):
for g in idou:
x,y=g
left=max(0,i-y-1)
right=max(0,i-x)
ans[i]+=(rui[right]-rui[left])%mod
rui[i]+=((rui[i-1]+ans[i]))%mod
print(ans[n]%mod)
|
N, K = map(int, input().split())
mod = 998244353
move = []
for _ in range(K):
L, R = map(int, input().split())
move.append((L, R))
dp = [0]*(2*N+1)
dp[0] = 1
for i in range(N):
for l, r in move:
dp[i+l] += dp[i]
dp[i+l] %= mod
dp[i+r+1] -= dp[i]
dp[i+r+1] %= mod
if i:
dp[i+1] += dp[i]
dp[i] %= mod
print(dp[N-1]) | 1 | 2,668,547,362,010 | null | 74 | 74 |
r,c = map(int,raw_input().split(' '))
sheet = [[0 for i in range((c+1))]for j in range((r+1))]
for i in range(r):
s = map(int,raw_input().split(' '))
for j in range(c):
sheet[i][j] = s[j]
sheet[i][c] += s[j]
sheet[r][j] += s[j]
print sheet[i][j],
sheet[r][c] += sheet[i][c]
print sheet[i][c]
for i in range(c):
print sheet[r][i],
print sheet[r][c] | N, K, S = map(int, input().split())
print(" ".join([str(S)] * K + [str(S+1)] * (N-K)) if S<10**9 else " ".join([str(S)] * K + ['1'] * (N-K)))
| 0 | null | 46,476,637,700,612 | 59 | 238 |
while 1:
n=int(input())
if n==0:break
s=list(map(int,input().split()))
print((sum([(m-sum(s)/n)**2 for m in s])/n)**.5) | X=int(input())
a=X%500
to=X//500*1000+a//5*5
print(to) | 0 | null | 21,426,435,256,212 | 31 | 185 |
from itertools import accumulate
from bisect import bisect_left
def main():
n,m=map(int,input().split())
A=list(map(int,input().split()))
A.sort()
def count(k):
cnt=0
for a in A:
cnt+=bisect_left(A,k-a)
return cnt
ok=0
ng=2*10**5+1
while ng-ok>1:
mid=(ok+ng)//2
if count(mid)<n**2-m:
ok=mid
else:
ng=mid
border=ok
k=n**2-count(border)
Acc=[0]+list(accumulate(A))
s=Acc[-1]
ans=0
for a in A:
idx=bisect_left(A,border-a)
ans+=a*(n-idx)+(s-Acc[idx])
ans-=border*(k-m)
print(ans)
if __name__=='__main__':
main() | import math
import numpy as np
pi = math.pi
a, b, x = map(int, input().split())
if x >= a**2*b/2:
print(180/pi*np.arctan(2*(a**2*b-x)/a**3))
else:
print(180/pi*np.arctan(a*b**2/(2*x))) | 0 | null | 135,514,679,187,612 | 252 | 289 |
import math
N=int(input())
if (N/1.08).is_integer()==True:
S=int(N/1.08)
else:
S=math.ceil(N/1.08)
if (S*1.08)//1==N:
print(S)
else:
print(':(') | from typing import List
class Info:
def __init__(self, arg_start, arg_end, arg_area):
self.start = arg_start
self.end = arg_end
self.area = arg_area
if __name__ == "__main__":
LOC: List[int] = []
POOL: List[Info] = []
all_symbols = input()
loc = 0
total_area = 0
for symbol in all_symbols:
if symbol == '\\':
LOC.append(loc)
elif symbol == '/':
if len(LOC) == 0:
continue
tmp_start = int(LOC.pop())
tmp_end = loc
tmp_area = tmp_end - tmp_start
total_area += tmp_area
while len(POOL) > 0:
# \ / : (tmp_start, tmp_end)
# \/ : (POOL[-1].start, POOL[-1].end)
if tmp_start < POOL[-1].start and POOL[-1].end < tmp_end:
tmp_area += POOL[-1].area
POOL.pop()
else:
break
POOL.append(Info(tmp_start, tmp_end, tmp_area))
else:
pass
loc += 1
print(f"{total_area}")
print(f"{len(POOL)}", end="")
while len(POOL) > 0:
print(f" {POOL[0].area}", end="")
POOL.pop(0)
print()
| 0 | null | 62,978,478,110,822 | 265 | 21 |
"""
dp[i][j][k] => i行目j列到達時点での最大価値。i行目において拾えるアイテムの数はK個。
"""
def main():
import sys
input = sys.stdin.readline
R,C,K = map(int,input().split())
items = [[0]*C for _ in range(R)]
for _ in range(K):
r,c,v = map(int,input().split())
items[r-1][c-1] = v
dp = [[0]*4 for _ in range(C)]
for i in range(R):
for j in range(C):
v = items[i][j]
#上から入るパターン
dp[j][0] = max(dp[j])
if v:
dp[j][1] = dp[j][0]+v
#左から入ってくるパターン
if j > 0:
for k in range(4):
#このマスのアイテムをとらないパターン
dp[j][k] = max(dp[j][k],dp[j-1][k])
if v and k>0:
dp[j][k] = max(dp[j][k],dp[j-1][k-1]+v)
print(max(dp[-1]))
main() | import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
i8 = np.int64
i4 = np.int32
def main():
stdin = open('/dev/stdin')
pin = np.fromstring(stdin.read(), i8, sep=' ')
N = pin[0]
M = pin[1]
L = pin[2]
ABC = pin[3: M * 3 + 3].reshape((-1, 3))
A = ABC[:, 0] - 1
B = ABC[:, 1] - 1
C = ABC[:, 2]
Q = pin[M * 3 + 3]
st = (pin[M * 3 + 4: 2 * Q + M * 3 + 4] - 1).reshape((-1, 2))
s = st[:, 0]
t = st[:, 1]
graph = csr_matrix((C, (A, B)), shape=(N, N))
dist = np.array(floyd_warshall(graph, directed=False))
dist[dist > L + 0.5] = 0
dist[dist > 0] = 1
min_dist = np.array(floyd_warshall(dist))
min_dist[min_dist == np.inf] = 0
min_dist = (min_dist + .5).astype(int)
x = min_dist[s, t] - 1
print('\n'.join(x.astype(str).tolist()))
if __name__ == '__main__':
main()
| 0 | null | 89,743,070,012,878 | 94 | 295 |
import math
while True:
n = input()
if n == 0:
break
s = map(int, raw_input().split())
sumS = 0.0
sum = 0.0
for i in s:
sumS += i**2
sum += i
v = sumS / n - (sum / n)**2
print math.sqrt(v) | import math
from statistics import mean
ans = []
while True:
n = int(input())
if n == 0:
break
s = list(map(int,input().split()))
ss = []
for i in s:
ss.append(i**2)
sd = math.sqrt(mean(ss)-mean(s)**2)
ans.append(sd)
for k in ans:
print(k)
| 1 | 197,100,462,206 | null | 31 | 31 |
n, k = map(int, input().split())
h = list(map(int, input().split()))
def answer(n: int, k: int, h: list) -> int:
ans = 0
for i in range(0, n):
if h[i] >= k:
ans += 1
return ans
print(answer(n, k, h))
| n,k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
res = 0
for i in range(n):
if k <= a[i]:
res += 1
print(res) | 1 | 178,899,124,642,230 | null | 298 | 298 |
# -*- coding: utf-8 -*-
def main():
K = int(input())
S = input()
if len(S) <= K:
ans = S
else:
ans = S[:K] + '...'
print(ans)
if __name__ == "__main__":
main() | k=int(input())
s=input()
n=len(s)
if(n<=k):
print(s)
else:
print(s[:k]+'...')
| 1 | 19,720,468,028,170 | null | 143 | 143 |
class UnionFind:
def __init__(self, n):
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
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
N, M = map(int, input().split())
uf = UnionFind(N)
for i in range(M):
a,b = map(int, input().split())
uf.union(a-1,b-1)
ans = 0
for i in range(N):
ans = max(ans, -uf.parents[i])
print(ans) | class UnionFind:
def __init__(self, sz: int):
self._par: list[int] = [-1] * sz
def root(self, a: int):
if self._par[a] < 0:
return a
self._par[a] = self.root(self._par[a])
return self._par[a]
def size(self, a: int):
return -self._par[self.root(a)]
def unite(self, a, b):
a = self.root(a)
b = self.root(b)
if a != b:
if self.size(a) < self.size(b):
a, b = b, a
self._par[a] += self._par[b]
self._par[b] = a
if __name__ == '__main__':
N, M = map(int, input().split())
uf = UnionFind(N + 1)
for i in range(M):
a, b = map(int, input().split())
uf.unite(a, b)
ans = 1
for i in range(1, N + 1):
ans = max(ans, uf.size(i))
print(ans) | 1 | 3,965,175,390,750 | null | 84 | 84 |
S=input()
lis=['SUN','MON','TUE','WED','THU','FRI','SAT']
i=lis.index(S)
if S=='SUN':
print(7)
else:
for j in range(1,8):
if lis[i-j]=='SUN':
print(7-j)
break | N = int(input())
mod = int(1e9) + 7
def doubling(n, m):
y = 1
bas = n
tmp = m
while tmp:
if tmp % 2:
y *= bas
y %= mod
bas *= bas
bas %= mod
tmp >>= 1
return y
d10 = doubling(10, N)
d9 = doubling(9, N)
d8 = doubling(8, N)
print((d10 - 2*d9 + d8) % mod) | 0 | null | 68,210,281,133,500 | 270 | 78 |
k=int(input())
a,b=map(int,input().split())
ans=False
for i in range(a,b+1):
if i%k==0:
ans=True
break
print("NOGK"[ans::2]) | from sys import stdin
rs = stdin.readline
ri = lambda : int(rs())
ril = lambda : list(map(int, rs().split()))
def main():
K = ri()
A, B = ril()
for i in range(A, B + 1):
if i % K == 0:
ans = 'OK'
break
else:
ans = 'NG'
print(ans)
if __name__ == '__main__':
main()
| 1 | 26,558,849,051,148 | null | 158 | 158 |
def resolve():
A, B, C, K = map(int, input().split())
if K < A:
ans = K
elif (A + B) >= K:
ans = A
else:
ans = A - (K - A - B)
print(ans)
if __name__ == "__main__":
resolve() | a, b, c, k = map(int, input().split())
ans = 0
if a >= k:
ans = k * 1
else:
ans = a * 1 + max(0, (k - a)) * 0 + max(0, (k - a - b)) * (-1)
print(ans)
| 1 | 21,756,666,304,870 | null | 148 | 148 |
from functools import reduce
print(reduce(lambda a, b: 'a {} b'.format('<' if a < b else (
'>' if a > b else '==')),
map(int, input().split()))) | I = input().split()
if int(I[0]) < int(I[1]):
print("a < b")
if int(I[0]) > int(I[1]):
print("a > b")
if int(I[0]) == int(I[1]):
print("a == b") | 1 | 366,918,843,300 | null | 38 | 38 |
n = list(input())
n1 = int(n[-1])
if n1 == 2 or n1 == 4 or n1 == 5 or n1 == 7 or n1 == 9:
print("hon")
elif n1 == 0 or n1 == 1 or n1 == 6 or n1 == 8:
print("pon")
else:
print("bon")
| n = map(int, raw_input().split())
if (n[0] < n[1] and n[1] < n[2]):
print "Yes"
else:
print "No" | 0 | null | 9,777,743,505,408 | 142 | 39 |
import sys
sys.setrecursionlimit(10**7)
readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))
n = readint()
ans = [[[0],[0]]]
i = 0
while len(ans[i][0])<n:
a = ans[i]
for x in a[1]:
ans.append([a[0]+[x],a[1]])
x = a[1][-1]+1
ans.append([a[0]+[x],a[1] + [x]])
i+=1
a_ = ord('a')
for i in range(len(ans)):
a = ans[i][0]
if len(a)<n:
continue
for x in a[:-1]:
print(chr(x+a_),end='')
print(chr(a[-1]+a_))
| a,b = input().split()
t = a*int(b)
q = b*int(a)
if t < q:
print(t)
else:
print(q) | 0 | null | 68,630,819,269,772 | 198 | 232 |
N=int(input())
Alist=list(map(int,input().split()))
ans=0
for i in range(N):
if Alist[i]%2==0:
if Alist[i]%3!=0 and Alist[i]%5!=0:
ans=1
break
print("APPROVED"*(1+(-1)*ans)+"DENIED"*ans) | from functools import lru_cache
@lru_cache(maxsize=1024)
def fib(n):
if n in [0, 1]:
return 1
return fib(n - 1) + fib(n - 2)
if __name__ == '__main__':
print(fib(int(input()))) | 0 | null | 34,462,366,705,408 | 217 | 7 |
k = int(input())
a, b = list(map(int, input().split()))
p = 0
while p <= 1000:
if a <= p <= b:
print("OK")
exit()
p += k
print("NG")
| k = int(input())
a, b = map(int, input().split())
n = a // k
if k * n == a:
print('OK')
elif k * (n + 1) <= b:
print('OK')
else:
print('NG') | 1 | 26,565,382,755,710 | null | 158 | 158 |
a,b,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
l=[list(map(int,input().split())) for _ in range(m)]
ans=min(a)+min(b)
for x,y,c in l:
ans=min(ans,a[x-1]+b[y-1]-c)
print(ans) | N = int(input())
S = 'X' + input()
cnt_R, cnt_G, cnt_B = 0, 0, 0
for s in S[1:]:
if s == 'R':
cnt_R += 1
elif s == 'G':
cnt_G += 1
elif s == 'B':
cnt_B += 1
ans = cnt_R * cnt_G * cnt_B
for i in range(1,N-1):
for j in range(i+1,N):
k = 2*j - i
if k > N:
break
a = S[i]; b = S[j]; c = S[k]
if a != b and b != c and c != a:
ans -= 1
print(ans) | 0 | null | 44,839,708,176,230 | 200 | 175 |
def li():
return [int(x) for x in input().split()]
MOD = 998244353
N, K = li()
L, R = [], []
for _ in range(K):
l, r = li()
L.append(l)
R.append(r)
#dp[i]: マスiにいく場合の数
dp = [0] * (2 * N + 1)
dp[1] = 1
dp[2] = -1
for i in range(1, N):
dp[i+1] += dp[i]
dp[i+1] %= MOD
for k in range(K):
l, r = L[k], R[k]
dp[i+l] += dp[i]
dp[i+l] %= MOD
dp[i+r+1] -= dp[i]
dp[i+r+1] %= MOD
print(dp[N])
| N, K = map(int, input().split())
MOD = 998244353
S = []
for _ in range(K):
l, r = map(int, input().split())
S.append((l, r))
dp = [0] * (N + 1)
accDp = [0] * (N + 1)
dp[1] = 1
accDp[1] = 1
for i in range(2, N + 1):
for l, r in S:
r, l = max(0, i - l), max(1, i - r)
dp[i] += accDp[r] - accDp[l - 1]
dp[i] %= MOD
accDp[i] = (accDp[i - 1] + dp[i]) % MOD
print(dp[N])
| 1 | 2,685,059,819,210 | null | 74 | 74 |
S=list(str(input()))
a=[]
b=[]
count = 1
direction=S[0]
for i in range(1,len(S)):
if S[i]== direction:
count += 1
else:
a.append(S[i-1])
b.append(count)
direction=S[i]
count=1
a.append(S[-1])
b.append(count)
m=max(b)+1
dp=[0]*m
for i in range(1,m):
dp[i] += dp[i-1]+i
ans=0
for i in range(1,len(a)):
if a[i-1]=='<' and a[i]=='>':
ans+=dp[max(b[i-1],b[i])] + dp[min(b[i-1],b[i])-1]
if a[0]=='>':
ans+=dp[b[0]]
if a[-1]=='<':
ans+=dp[b[-1]]
print(ans) | n = int(input())
a = list(map(int, input().split()))
print('APPROVED' if all(ai % 3 == 0 or ai % 5 == 0 for ai in a if ai % 2 == 0) else 'DENIED') | 0 | null | 112,999,520,218,370 | 285 | 217 |
from bisect import bisect_left
from itertools import accumulate
def resolve():
def getCount(x):
cnt = 0
for a in A:
# X未満の個数
idx = bisect_left(A, x - a)
# X以上の個数
cnt += N - idx
# X以上を使う!と決めた時、M個以上になるか
return cnt >= M
N, M = map(int, input().split())
A = sorted(map(int, input().split()))
ng = 10 ** 9
ok = 0
# X以上を使う!と決めるとX以上の個数が自明にわかる。
while ng - ok > 1:
mid = (ok + ng) // 2
if getCount(mid):
ok = mid
else:
ng = mid
# M個以上あることがわかれば、Mよりも余分な数(同じ値が複数ある場合)
# はすべてXである事がわかるため、差分だけ引けば良い。
B = [0] + list(accumulate(A))
ans = 0
cnt = 0
for i in range(N):
idx = bisect_left(A, ok - A[i])
ans += B[N] - B[idx] + A[i] * (N - idx)
cnt += N - idx
rest = (cnt - M) * ok
print(ans - rest)
if __name__ == "__main__":
resolve()
| N, M = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]
# N, M = map(int, input().split())
# A = list(map(int, input().split()))
# print(len(A))
max_p = max(A)
X = max_p
cnt = [0 for x in range(100001)]
hpp = [0 for x in range(100001)]
# print(A)
for i in A:
# print(i)
# if cnt[i] != 0:
# continue
cnt[i] += 1
hpp[i] += i
# print(cnt[:100])
for i in range(1, 100001)[::-1]:
cnt[i - 1] += cnt[i]
hpp[i - 1] += hpp[i]
def countpair(left, x):
# return cnt[x - left + 1] if (x - left > 0) else N
if x - left <= 0:
return N
elif x - left > 100000:
return 0
else:
return cnt[x - left]
def get_hpp(left, x):
if x - left <= 0:
return hpp[0]
elif x - left > 100000:
return 0
else:
return hpp[x - left]
# print(hpp[:100])
# print(cnt[:100])
small = 0
large = max_p * 2
threshold = 0
# d_c = 0
# mems = []
while (small <= large):
# d_c += 1
# print(small, large)
X = (small + large) // 2
nums = 0
for i in range(N):
left = A[i]
# print(len(A))
nums += countpair(left, X)
if nums >= M:
threshold = X
small = X + 1
else:
large = X - 1
X = threshold
# print("X:", X)
# print("threshold:", threshold)
Y = X + 1
hpp_sum = 0
num_sum = 0
for i in range(N):
# print("-----------")
left = A[i]
cnt_num = countpair(left, Y)
num_sum += cnt_num
# print("left:", left)
# print("cnt_num:", cnt_num)
hpp_sum += left * cnt_num
# print("get_hpp:", get_hpp(left, Y))
hpp_sum += get_hpp(left, Y)
# print("hpp_sum:", hpp_sum)
hpp_sum += X * (M - num_sum) if (M - num_sum > 0) else 0
print(hpp_sum)
# print(out)
# for i in range(N):
| 1 | 108,024,631,987,148 | null | 252 | 252 |
import collections
N = int(input())
A = [0] * N
B = [0] * N
for i in range(N):
a, b = map(int, input().split())
A[i] = a
B[i] = b
A.sort()
B.sort()
N_q, N_mod = divmod(N, 2)
if N_mod == 1:
ans = B[N_q] - A[N_q] + 1
else:
ans = B[N_q - 1] - A[N_q - 1] + B[N_q] - A[N_q] + 1
print(ans) | import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy
sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()
def main():
h,w=LI()
l=[]
l.append('.'*(w+1))
for _ in range(h):
x='.'
x+=S()
l.append(x)
dp=[[inf]*(w+10) for _ in range(h+10)]
if l[1][1]=='#':
dp[1][1]=1
else:
dp[1][1]=0
for i in range(1,h+1):
for j in range(1,w+1):
if i==1 and j==1:
continue
if l[i][j]=='#':
if l[i-1][j]=='.':
dp[i][j]=min(dp[i][j],dp[i-1][j]+1)
else:
dp[i][j]=min(dp[i][j],dp[i-1][j])
if l[i][j-1]=='.':
dp[i][j]=min(dp[i][j],dp[i][j-1]+1)
else:
dp[i][j]=min(dp[i][j],dp[i][j-1])
else:
dp[i][j]=min(dp[i-1][j],dp[i][j-1])
# print(dp)
return dp[h][w]
# main()
print(main())
| 0 | null | 33,231,733,420,712 | 137 | 194 |
import sys
N = int(input())
S,T = input().split()
if not ( 1 <= N <= 100 ): sys.exit()
if not ( len(S) == len(T) and len(S) == N ): sys.exit()
if not ( S.islower() and T.islower() ): sys.exit()
for I in range(N):
print(S[I],end='')
print(T[I],end='') | i = input().split(' ')
W = int(i[0])
H = int(i[1])
x = int(i[2])
y = int(i[3])
r = int(i[4])
if x - r >= 0 and y - r >= 0 and x + r <= W and y + r <= H:
print('Yes')
else:
print('No') | 0 | null | 56,174,143,938,172 | 255 | 41 |
import sys
import copy
def print_data(data):
last_index = len(data) - 1
for idx, item in enumerate(data):
print(item, end='')
if idx != last_index:
print(' ', end='')
print('')
def bubbleSort(data, N):
for i in range(N):
j = N -1
while j >= i+1:
if data[j][1] < data[j-1][1]:
hoge = data[j]
data[j] = data[j-1]
data[j-1] = hoge
j -= 1
return data
def selectSort(data, N):
for i in range(N):
mini = i
for j in range(i, N):
if data[j][1] < data[mini][1]:
mini = j
if i == mini:
pass
else:
hoge = data[mini]
data[mini] = data[i]
data[i] = hoge
return data
def isStable(inData, outData, N):
for i in range(N):
for j in range(i+1, N):
if inData[i][1] == inData[j][1]:
a = outData.index(inData[i])
b = outData.index(inData[j])
if a > b :
return False
return True
def main():
N = int(input())
data0 = list(input().split())
data1 = copy.deepcopy(data0)
data2 = copy.deepcopy(data0)
bubbleData = bubbleSort(data1, N)
selectData = selectSort(data2, N)
print_data(bubbleData)
if isStable(data0, bubbleData, N):
print('Stable')
else:
print('Not stable')
print_data(selectData)
if isStable(data0, selectData, N):
print('Stable')
else:
print('Not stable')
if __name__ == '__main__':
main()
| def bubbleSort(cards, N):
flag = True
while flag:
flag = False
for j in range(N-1, 0, -1):
if cards.numbers[j] < cards.numbers[j - 1]:
cards.swap(j, j-1)
flag = True
return cards
def selectionSort(cards,N):
for i in range(N):
minj = i
for j in range(i, N):
if cards.numbers[j] < cards.numbers[minj]:
minj = j
if minj != i:
cards.swap(i, minj)
return cards
class Cards(object):
def __init__(self, cards):
self.cards = cards
self.numbers = [int(card[1]) for card in cards]
def filter_by_number(self, number):
return [card for card in self.cards if card.endswith(str(number))]
def swap(self, i, j):
self.cards[i], self.cards[j] = self.cards[j], self.cards[i]
self.numbers = [int(card[1]) for card in self.cards]
def show(self):
print(' '.join(self.cards))
def is_stable(self, cards):
for n in range(1,10):
suits_x = self.filter_by_number(str(n))
suits_y = cards.filter_by_number(str(n))
if suits_x != suits_y:
return False
return True
def copy(self):
return Cards([card for card in self.cards])
def run():
n = int(input())
cards = Cards(input().split())
cards_sorted = bubbleSort(cards.copy(),n)
cards_sorted.show()
if cards.is_stable(cards_sorted):
print('Stable')
else:
print('Not stable')
cards_sorted = selectionSort(cards.copy(),n)
cards_sorted.show()
if cards.is_stable(cards_sorted):
print('Stable')
else:
print('Not stable')
if __name__ == '__main__':
run()
| 1 | 27,003,463,868 | null | 16 | 16 |
n = int(input())
a = int(n//1.08)
for x in range(a, a+2):
if x < (n + 1)/1.08 and x >= n/1.08:
print(x)
exit()
print(':(') | # coding: utf-8
def showBuilding(mansion):
for i, building in enumerate(mansion):
for line in building:
for room in line:
print(' ' + str(room), end='')
print()
if i != 3:
print('####################')
def calcMoving(mansion, moving_status):
b, f, r, v = moving_status
live_in_person = mansion[b-1][f-1][r-1]
if live_in_person + v >= 9:
live_in_person = 9
elif live_in_person + v < 0:
live_in_person = 0
else:
live_in_person += v
mansion[b-1][f-1][r-1] = live_in_person
if __name__ == '__main__':
mansion = [[[0 for _ in range(10)] for _ in range(3)] for _ in range(4)]
for _ in range(int(input())):
calcMoving(mansion, map(int, input().split()))
showBuilding(mansion)
| 0 | null | 63,327,324,743,812 | 265 | 55 |
A, B = map(int, input().split())
if A>=10 or B>=10:
print('-1')
exit()
else:
print(A*B) | A=input();print(sum(i!=j for i,j in zip(A,A[::-1]))//2) | 0 | null | 139,378,714,423,872 | 286 | 261 |
from collections import deque
H,W=map(int,input().split())
S=[[c=='#' for c in input()] for _ in range(H)]
def bfs(i,j):
if S[i][j]:
return 0
que=deque()
que.append((i,j))
vis=[row[:] for row in S]
vis[i][j]=1
ans=-1
while que:
ans+=1
for _ in range(len(que)):
i,j=que.popleft()
for ni,nj in nbs(i,j):
if not vis[ni][nj]:
que.append((ni,nj))
vis[ni][nj]=1
return ans
def nbs(i,j):
for ni,nj in (i-1,j),(i,j+1),(i+1,j),(i,j-1):
if 0<=ni<H and 0<=nj<W:
yield ni,nj
ans=0
for i in range(H):
for j in range(W):
ans=max(ans,bfs(i,j))
print(ans)
| import sys
import math
import string
import fractions
import random
from operator import itemgetter
import itertools
from collections import deque
import copy
import heapq
import bisect
MOD = 10 ** 9 + 7
INF = float('inf')
input = lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(10 ** 8)
n = int(input())
dis = [-1] * n
info = [list(map(int, input().split())) for _ in range(n)]
stack = [[0, 0]]
ans = 0
while len(stack) > 0:
num = stack.pop(0)
if dis[num[0]] == -1:
dis[num[0]] = num[1]
for i in info[num[0]][2:]:
if dis[i-1] == -1:
stack.append([i - 1, num[1] + 1])
for i in range(n):
print(str(i+1) + " " + str(dis[i]))
| 0 | null | 47,542,433,131,170 | 241 | 9 |
import collections,sys
def s():
d=collections.deque()
input()
for e in sys.stdin:
if'i'==e[0]:d.appendleft(e[7:-1])
else:
if' '==e[6]:
m=e[7:-1]
if m in d:d.remove(m)
elif len(e)%2:d.pop()
else:d.popleft()
print(*d)
s()
| word = raw_input()
text = []
while True:
raw = raw_input()
if raw == "END_OF_TEXT":
break
text += raw.lower().split()
print(text.count(word))
# print(text.lower().split().count(word)) | 0 | null | 954,981,924,920 | 20 | 65 |
import math
import sys
from decimal import Decimal
a,b,c = map(int,input().split())
if c-a-b <= 0:
print('No')
sys.exit()
if Decimal((c-a-b)*(c-a-b) - 4*a*b) > 0:
print("Yes")
else:
print('No')
| N = int(input())
S = [input() for i in range(N)]
# N = 5
# S = ['aa', 'a', 'aa', 'aaaa', 'aa']
C = dict([s,1] for s in S)
L = len(C)
print(L) | 0 | null | 40,947,301,712,710 | 197 | 165 |
from collections import defaultdict
from collections import deque
from collections import OrderedDict
import itertools
from sys import stdin
input = stdin.readline
def main():
N = int(input())
set_ = set()
for i in range(N):
set_.add(input()[:-1])
print(len(set_))
if(__name__ == '__main__'):
main()
| N, K = map(int, input().split())
A = [0]*(N+2)
for i in range(N+1):
A[i+1] += A[i] + i
ans = 0
for i in range(K, N+2):
minv = A[i]
maxv = A[N+1]-A[N-i+1]
ans += maxv-minv+1
ans %= 10**9+7
print(ans)
| 0 | null | 31,724,837,071,110 | 165 | 170 |
fact = [None]*1000001
inv = [0,1]
finv = [1,1]
x, y = map(int, input().split())
total = x+y
ans = 0
MOD = 10**9+7
if total%3 == 0 and max(x,y) <= min(x,y)*2:
fact[1] = 1
for i in range(2,1000001):
fact[i] = fact[i-1]*i%MOD
inv.append((-inv[MOD%i] * (MOD//i)) % MOD)
finv.append(finv[-1] * inv[-1] % MOD)
step = int(total/3)
sa = abs(x-y)
a = int((step-sa)/2)
b = int((step+sa)/2)
ans = fact[step] * finv[a] * finv[b] % MOD
print(ans) | # https://atcoder.jp/contests/abc145/tasks/abc145_d
import math
X, Y = list(map(int, input().split()))
if (X + Y) % 3 != 0:
print(0)
exit()
n = int((2*X - Y) // 3)
m = int((2*Y - X) // 3)
if n < 0 or m < 0:
print(0)
exit()
def comb(n, k):
c = 1
for i in range(k):
c *= n - i
c %= MOD
d = 1
for i in range(1, k + 1):
d *= i
d %= MOD
return (c * pow(d, MOD - 2, MOD)) % MOD
MOD = 10 ** 9 + 7
result = comb(n+m, n)
print(result)
| 1 | 150,217,438,296,960 | null | 281 | 281 |
x, y = map(int,input().split())
min = 2 * x
gap = y - min
if gap < 0 or gap > min:
print("No")
else:
if gap % 2 == 0:
print("Yes")
else:
print("No")
| print ((int(raw_input()))**3) | 0 | null | 6,976,412,114,658 | 127 | 35 |
n = float(input())
print((n - (n // 2)) / n)
| N=int(input())
K=(N+1)//2
print(K/N) | 1 | 177,022,187,968,262 | null | 297 | 297 |
import math
y=int(input())
cnt=0
for i in range (1,y+1):
for k in range(1,y+1):
for j in range(1,y+1):
a = [i,j,k]#リスト
ans = a[0]
for x in range(len(a)):
ans = math.gcd(ans, a[x])
cnt+=ans
print(cnt) | import math
K = int(input())
S = 0
for a in range(1, K+1):
for b in range(1, K+1):
T = math.gcd(a, b)
for c in range(1, K+1):
S += math.gcd(T, c)
print(S) | 1 | 35,510,193,985,728 | null | 174 | 174 |
ans = []
while True:
tmp = input().split()
a, b = map(int, [tmp[0], tmp[2]])
op = tmp[1]
if op == "?":
break
if op == "+":
ans.append(a + b)
if op == "-":
ans.append(a - b)
if op == "*":
ans.append(a * b)
if op == "/":
ans.append(a // b)
print("\n".join(map(str, ans)))
| n = int(input())
a = []
x = []
y = []
for i in range(n):
ai = int(input())
a.append(ai)
xi = []
yi = []
for j in range(ai):
xij, yij = map(int, input().split(' '))
xi.append(xij)
yi.append(yij)
x.append(xi)
y.append(yi)
ans = 0
for case in range(2**n):
truth_t = 0 #正直者の真の数
truth = 0 #正直者の確認した数
for i in range(n): #人ごとに矛盾が生じないか確認
if (case>>i)&1: #正直者であれば証言に矛盾がないか確認
truth_t+=1
proof=0
for j in range(a[i]):
if ((case>>(x[i][j]-1))&1)==y[i][j]:
proof+=1
if proof==a[i]:
truth += 1
if truth==truth_t:
if ans<truth:
ans = truth
print(ans)
| 0 | null | 61,082,972,933,852 | 47 | 262 |
from collections import defaultdict
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = 0
ruiseki = [0]
d = defaultdict(int)
d[0]=1
for i in range(n):
if i - k + 1>= 0:
d[ruiseki[i - k+1]]-=1
ruiseki.append((ruiseki[i] + a[i] - 1)%k)
ans += d[ruiseki[i+1]]
d[ruiseki[i + 1]] += 1
print(ans)
if __name__ == '__main__':
main() | # AtCoder Beginner Contest 146
# E - Rem of Sum is Num
# https://atcoder.jp/contests/abc146/tasks/abc146_e
from collections import defaultdict
N, K = map(int, input().split())
*A, = map(int, input().split())
A = [0]+A
d = []
c = defaultdict(int)
x = 0
ans = 0
for i, a in enumerate(A):
x += a - 1
x %= K
d.append(x)
if i-K >= 0:
c[d[i-K]] -= 1
ans += c[x]
c[x] += 1
print(ans) | 1 | 137,076,932,226,520 | null | 273 | 273 |
n, k = map(int,input().split())
count = 0
while True:
n = n//k
count += 1
if n <1:
break
print(count) | n,k = map(int, input().split())
def Base_10_to_n(X, n):
if (int(X/n)):
return Base_10_to_n(int(X/n), n)+str(X%n)
return str(X%n)
s = Base_10_to_n(n, k)
print(len(s)) | 1 | 64,187,727,198,012 | null | 212 | 212 |
import sys
input = sys.stdin.readline
def solve():
INF = float('inf')
def max2(x, y): return x if x >= y else y
R, C, K = map(int, input().split())
Vss = [[0]*(C+1) for _ in range(R+1)]
for _ in range(K):
r, c, v = map(int, input().split())
Vss[r][c] = v
dpMax = [0]*(C+1)
for i in range(1, R+1):
dp0 = [0]*(C+1)
dp1 = [-INF]*(C+1)
dp2 = [-INF]*(C+1)
dp3 = [-INF]*(C+1)
for j in range(1, C+1):
V = Vss[i][j]
dp0[j] = max2(dp0[j-1], dpMax[j])
dp1[j] = max2(dp0[j] + V, dp1[j-1])
dp2[j] = max2(dp1[j-1] + V, dp2[j-1])
dp3[j] = max2(dp2[j-1] + V, dp3[j-1])
dpMax[j] = max(dp0[j], dp1[j], dp2[j], dp3[j])
ans = dpMax[C]
print(ans)
solve()
| a,b=input().split()
A=int(a)
B=int(b)
aa=a
bb=b
for i in range(B-1):
aa+=a
for j in range(A-1):
bb+=b
if aa >= bb:
print(bb)
else:
print(aa) | 0 | null | 45,134,794,356,420 | 94 | 232 |
a,b,c,k=[int(x) for x in input().split()]
ans=0
if a<=k:
ans+=a
k-=a
elif k>0:
ans+=k
k=0
if b<=k:
k-=b
elif k>0:
k=0
if k>0:
ans-=k
print(ans) | # -*- coding: utf-8 -*-
def main():
A, B, C, K = map(int, input().split())
ans = 0
if K <= A:
ans = K
else:
if K <= A + B:
ans = A
else:
ans = A + (-1 * (K - A - B))
print(ans)
if __name__ == "__main__":
main() | 1 | 21,715,556,047,610 | null | 148 | 148 |
# coding: utf-8
import sys
from collections import deque
output_str = deque()
data_cnt = int(input())
for i in range(data_cnt):
in_command = input().rstrip().split(" ")
if in_command[0] == "insert":
output_str.appendleft(in_command[1])
elif in_command[0] == "delete":
if output_str.count(in_command[1]) > 0:
output_str.remove(in_command[1])
elif in_command[0] == "deleteFirst":
output_str.popleft()
elif in_command[0] == "deleteLast":
output_str.pop()
print(" ".join(output_str)) | 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))
| 1 | 49,723,476,790 | null | 20 | 20 |
from itertools import permutations
from math import sqrt, pow, factorial
N = int(input())
l = [list(map(int, input().split())) for _ in range(N)]
def calc(a, b):
[x1, y1] = a
[x2, y2] = b
return sqrt(pow(x1 - x2, 2) + pow(y1 -y2, 2))
ans = 0
for order in permutations(range(N)):
tmp = 0
for i in range(1, N):
tmp += calc(l[order[i]], l[order[i-1]])
ans += tmp
print(ans/factorial(N))
| s = int(input())
m = 10**9+7
a = [1,0,0,1,1,1,2]
if s < 7:
print(a[s])
exit()
for i in range(7,s+1):
a.append((sum(a[3:i-2])+1)%m)
print(a[s]) | 0 | null | 75,525,098,742,082 | 280 | 79 |
# Date [ 2020-08-29 21:59:01 ]
# Problem [ e.py ]
# Author Koki_tkg
# After Contest
import sys
import math
# import bisect
# import numpy as np
# from decimal import Decimal
# from numba import njit, i8, u1, b1 #JIT compiler
# from itertools import combinations, product
# from collections import Counter, deque, defaultdict
# sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
INF = 10 ** 9
PI = 3.14159265358979323846
def read_str(): return sys.stdin.readline().strip()
def read_int(): return int(sys.stdin.readline().strip())
def read_ints(): return map(int, sys.stdin.readline().strip().split())
def read_ints2(x): return map(lambda num: int(num) - x, sys.stdin.readline().strip().split())
def read_str_list(): return list(sys.stdin.readline().strip().split())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))
def GCD(a: int, b: int) -> int: return b if a%b==0 else GCD(b, a%b)
def LCM(a: int, b: int) -> int: return (a * b) // GCD(a, b)
# osa_k 法 O(NloglogN + logA)
class PrimeFactorization():
def __init__(self, num):
self.num = num
self.factor_table = [0] * (num + 1)
self.eratosthenes()
def eratosthenes(self):
for i in range(2, self.num + 1):
if self.factor_table[i] == 0:
self.factor_table[i] = i
for j in range(i * i, self.num + 1, i):
if self.factor_table[j] == 0:
self.factor_table[j] = i
def factorization(self, a):
now = a
ret = []
while now > 1:
cnt = 0
prime = self.factor_table[now]
while now % prime == 0:
cnt += 1
now //= prime
ret.append((prime, cnt))
return ret
def Main():
n = read_int()
a = read_int_list()
max_num = max(a)
pf = PrimeFactorization(max_num + 1)
used_prime = [False] * (max_num + 1)
for x in a:
factor = pf.factorization(x)
for prime, cnt in factor:
if used_prime[prime]:
break
used_prime[prime] = True
else:
continue
break
else:
print('pairwise coprime')
exit()
gcd_num = a[0]
for x in a[1:]:
gcd_num = math.gcd(gcd_num, x)
print('setwise coprime' if gcd_num == 1 else 'not coprime')
if __name__ == '__main__':
Main() | def main():
x = int(input())
if x >= 30:
print('Yes')
else:
print("No")
if __name__ == main():
main() | 0 | null | 4,928,469,064,548 | 85 | 95 |
from scipy.special import comb
S = int(input())
ans = 0
mod = 10**9+7
for i in range(3, S+1, 3):
ans = (ans +comb(S-2*(i//3)-1, i//3-1, exact=True)) % mod
print(ans)
| days = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]
S = input()
if S == "SUN":
print(7)
else:
print(days.index("SUN") - days.index(S))
| 0 | null | 68,307,324,858,630 | 79 | 270 |
def merge(A, left, mid, right):
global count
n1 = mid - left
n2 = right - mid
L=[]
R=[]
# for i in range(n1):
# L.append(A[left + i])
# for i in range(n2):
# R.append(A[mid + i])
L=A[left:mid]
R=A[mid:right]
L.append(10e10)
R.append(10e10)
i = 0
j = 0
for k in range(left , right):
count +=1
if L[i] <= R[j]:
A[k] = L[i]
i = i + 1
else:
A[k] = R[j]
j = j + 1
def mergeSort(A, left, right):
if left+1 < right:
mid = (left + right)//2
mergeSort(A, left, mid)
mergeSort(A, mid, right)
merge(A, left, mid, right)
n = int(input())
A = list(map(int, input().split()))
count = 0
mergeSort(A, 0, n)
print(*A)
print(count)
| n,p = map(int,input().split())
s = input()
l = [0 for i in range(p)]
l[0] = 1
ten = 1
cnt = 0
ans = 0
if p == 2 or p == 5:
for i in range(n):
if int(s[i]) % p == 0:
ans += i+1
else:
for i in range(n):
cnt = (cnt + int(s[-i-1]) * ten) % p
l[cnt] += 1
ten = (ten * 10) % p
for i in l:
if i > 1:
ans += i * (i - 1) // 2
print(ans) | 0 | null | 29,122,124,740,252 | 26 | 205 |
N ,K = map(int,input().split())
Ps = list(map(int,input().split()))
Ps.sort()
ans = 0
for i in range(K):
ans += Ps[i]
print(ans)
| import numpy as np
def main():
n,s=map(int,input().split())
A=list(map(int,input().split()))
dp=np.array([0 for i in range(s+1)])
dp[0]=1
for ai in A:
tmp=dp[:-ai].copy()
#print(tmp)
dp*=2
dp[ai:]+=tmp
dp%=998244353
print(dp[s])
if __name__=="__main__":
main()
| 0 | null | 14,533,016,306,148 | 120 | 138 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.