code1
stringlengths 16
427k
| code2
stringlengths 16
427k
| similar
int64 0
1
| pair_id
int64 2
178,025B
⌀ | question_pair_id
float64 27.1M
177,113B
⌀ | code1_group
int64 1
297
| code2_group
int64 1
297
|
---|---|---|---|---|---|---|
import sys
readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)
def main():
N, M = map(int, readline().split())
if N == M:
print("Yes")
else:
print("No")
if __name__ == '__main__':
main()
| S, W = map(int, input().split())
print('safe') if S>W else print('unsafe') | 0 | null | 56,203,311,653,230 | 231 | 163 |
h, w, k = list(map(int, input().split()))
masu = [input() for _ in range(h)]
ans = 0
for idx_h in range(2 ** h):
for idx_w in range(2 ** w):
m = masu.copy()
for i_row, row in enumerate(m):
for j_col, col in enumerate(row):
if idx_h & (2 ** i_row) > 0 or idx_w & (2 ** j_col) > 0:
# m[i_row][j_col] = 'r'
m[i_row] = m[i_row][:j_col] + 'r' + m[i_row][j_col+1:]
count_black = sum(map(lambda x: x.count('#'), m))
if count_black == k:
ans += 1
print(ans)
| from itertools import combinations
import copy
H, W, K = map(int, input().split())
C = [list(input()) for _ in range(H)]
ans = 0
w = list(range(W))
h = list(range(H))
for i in range(W+1):
for comi in combinations(w, i):
for j in range(H+1):
for comj in combinations(h, j):
tmpC = copy.deepcopy(C)
for ci in comi:
for hj in range(H):
tmpC[hj][ci] = '.'
for cj in comj:
for wi in range(W):
tmpC[cj][wi] = '.'
tmp = 0
for tc in tmpC:
tmp += tc.count('#')
if tmp == K:
ans += 1
print(ans) | 1 | 8,869,582,618,758 | null | 110 | 110 |
n,k = map(int,input().split())
A=list(map(int,input().split()) )
kyori = [-1] *len(A)
junban =[]
x=0
d=0
while kyori[x] == -1:
junban.append(x)
kyori[x]=d
d+=1
x=A[x]-1
roop_x = x
roop_d = d - kyori[x]
# for k in range(100):
if k<d:
print(junban[k]+1)
else:
k0 = kyori[x]
k1 = (k-k0)%roop_d
print(junban[k0+k1]+1)
| #!/usr/bin/env python3
def main():
from collections import deque
N, M, K = map(int, input().split())
friends = [set() for _ in range(N + 1)]
for _ in range(M):
a, b = map(int, input().split())
friends[a].add(b)
friends[b].add(a)
blocks = [set() for _ in range(N + 1)]
for _ in range(K):
c, d = map(int, input().split())
blocks[c].add(d)
blocks[d].add(c)
friends_chain = []
seen = [-1] * (N + 1)
cnt = 0
for person in range(1, N + 1):
if seen[person] != -1:
continue
q = deque([person])
friends_chain.append(set(q))
while q:
now = q.pop()
seen[now] = cnt
for next in friends[now]:
if seen[next] != -1:
continue
friends_chain[-1].add(next)
q.append(next)
cnt += 1
for person in range(1, N + 1):
res = friends_chain[seen[person]]
tmp_ans = len(res) - len(friends[person]) - 1
for block in blocks[person]:
tmp_ans -= 1 if block in res else 0
print(tmp_ans, end=' ')
if __name__ == '__main__':
main()
| 0 | null | 42,043,454,712,288 | 150 | 209 |
N = int(input())
sum = 0
if (1 <= N and N <= 10 ** 6):
for i in range(1,N + 1):
if ( i % 3 == 0) and ( i % 5 == 0):
#if i % 15 ==0:
N = 'Fizz Buzz'
elif i % 3 == 0:
N = 'Fizz'
elif i % 5 == 0:
N = 'Buzz'
else:
sum += i
print(sum)
| n = int(input())
sum = 0
for i in range(1, n+1):
if((i % 3 * i % 5 * i % 15) != 0):
sum += i
print(sum) | 1 | 35,010,421,908,930 | null | 173 | 173 |
import sys
import fractions
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
H, W = lr()
dp = [[0 for _ in range(W)] for _ in range(H)]
masu = [sr() for _ in range(H)]
dp[0][0] = 1 if masu[0][0] == "#" else 0
for h, m in enumerate(masu):
for w, s in enumerate(m):
if w == 0 and h == 0:
continue
if w == 0:
if masu[h-1][w] != s and s == "#":
dp[h][w] += dp[h-1][w] + 1
else:
dp[h][w] += dp[h-1][w]
continue
if h == 0:
if masu[h][w-1] != s and s == "#":
dp[h][w] += dp[h][w-1] + 1
else:
dp[h][w] += dp[h][w-1]
continue
if masu[h-1][w] != s and s == "#":
cand1 = dp[h][w] + dp[h-1][w] + 1
else:
cand1 = dp[h][w] + dp[h-1][w]
if masu[h][w-1] != s and s == "#":
cand2 = dp[h][w] + dp[h][w-1] + 1
else:
cand2 = dp[h][w] + dp[h][w-1]
dp[h][w] = min(cand1, cand2)
print(dp[H-1][W-1])
| import sys
import math
import copy
import heapq
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(1000000)
# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]
INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)
def nck(n, k, kaijyo):
return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD
def npk(n, k, kaijyo):
if k == 0 or k == n:
return n % MOD
return (kaijyo[n] * divide(kaijyo[n-k])) % MOD
def fact_and_inv(SIZE):
inv = [0] * SIZE # inv[j] = j^{-1} mod MOD
fac = [0] * SIZE # fac[j] = j! mod MOD
finv = [0] * SIZE # finv[j] = (j!)^{-1} mod MOD
inv[1] = 1
fac[0] = fac[1] = 1
finv[0] = finv[1] = 1
for i in range(2, SIZE):
inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
fac[i] = fac[i - 1] * i % MOD
finv[i] = finv[i - 1] * inv[i] % MOD
return fac, finv
def renritsu(A, Y):
# example 2x + y = 3, x + 3y = 4
# A = [[2,1], [1,3]])
# Y = [[3],[4]] または [3,4]
A = np.matrix(A)
Y = np.matrix(Y)
Y = np.reshape(Y, (-1, 1))
X = np.linalg.solve(A, Y)
# [1.0, 1.0]
return X.flatten().tolist()[0]
class TwoDimGrid:
# 2次元座標 -> 1次元
def __init__(self, h, w, wall="o"):
self.h = h
self.w = w
self.size = (h+2) * (w+2)
self.wall = wall
self.get_grid()
self.init_cost()
def get_grid(self):
grid = [self.wall * (self.w + 2)]
for i in range(self.h):
grid.append(self.wall + getS() + self.wall)
grid.append(self.wall * (self.w + 2))
self.grid = grid
def init_cost(self):
self.cost = [INF] * self.size
def pos(self, x, y):
# 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
return y * (self.w + 2) + x
def getgrid(self, x, y):
return self.grid[y][x]
def get(self, x, y):
return self.cost[self.pos(x, y)]
def set(self, x, y, v):
self.cost[self.pos(x, y)] = v
return
def show(self):
for i in range(self.h+2):
print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
def showsome(self, tgt):
for t in tgt:
print(t)
return
def showsomejoin(self, tgt):
for t in tgt:
print("".join(t))
return
def search(self):
grid = self.grid
move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
d = deque()
d.append((1,1))
self.set(1,1,0)
while(d):
cx, cy = d.popleft()
cc = self.get(cx, cy)
if self.getgrid(cx, cy) == self.wall:
continue
for dx, dy in [(1, 0), (0, 1)]:
nx, ny = cx + dx, cy + dy
if self.getgrid(cx, cy) == self.getgrid(nx, ny):
if self.get(nx, ny) > cc:
d.append((nx, ny))
self.set(nx, ny, cc)
else:
if self.get(nx, ny) > cc + 1:
d.append((nx, ny))
self.set(nx, ny, cc + 1)
# self.show()
ans = (self.get(self.w, self.h))
if self.getgrid(1,1) == "#":
ans += 1
print((ans + 1) // 2)
def soinsu(n):
ret = defaultdict(int)
for i in range(2, int(math.sqrt(n) + 2)):
if n % i == 0:
while True:
if n % i == 0:
ret[i] += 1
n //= i
else:
break
if not ret:
return {n: 1}
return ret
def solve():
h, w = getList()
G = TwoDimGrid(h, w)
G.search()
def main():
n = getN()
for _ in range(n):
solve()
return
if __name__ == "__main__":
# main()
solve() | 1 | 49,175,346,558,778 | null | 194 | 194 |
ls = [1,2,3]
ls.remove(int(input()))
ls.remove(int(input()))
print(ls[0]) | a=int(input())
b=int(input())
print(6//(a*b)) | 1 | 110,604,285,589,982 | null | 254 | 254 |
n, d = map(int, input().split())
x, y = zip(*[list(map(int, input().split())) for i in range(n)])
ans = 0
for i in range(n):
if x[i]**2 + y[i]**2 <= d**2:
ans += 1
print(ans) | x = list(map(int, input().split()))
if x[0] == 0:
print('1')
elif x[1] == 0:
print('2')
elif x[2] == 0:
print('3')
elif x[3] == 0:
print('4')
else:
print('5') | 0 | null | 9,700,306,458,280 | 96 | 126 |
def main(h: int, w: int, n: int):
m = max(h, w)
if n % m == 0:
print(n // m)
else:
print((n // m) + 1)
if __name__ == "__main__":
h = int(input())
w = int(input())
n = int(input())
main(h, w, n)
| size = int(input())
element = list(map(int,input().split()))
print(" ".join(map(str,element)))
for i in range(1,len(element)):
v = element[i]
j = i-1
while j >=0 and element[j] > v:
element[j+1] = element[j]
j -=1
element[j+1] = v
print(" ".join(map(str,element))) | 0 | null | 44,162,210,263,532 | 236 | 10 |
def biserch(n,List):
left = 0
right = len(List)
while left < right:
mid = (left+right)//2
if n <= List[mid]:
right = mid
else:
left = mid + 1
return left
N = int(input())
L = list(map(int,input().split()))
L.sort()
ans = 0
for i in range(N):
for j in range(i+1,N):
key = L[i] + L[j]
anchor = biserch(key,L)
ans += max(anchor - (j+1),0)
print(ans) | n,m = map(int,input().split())
coins = list(map(int,input().split()))
dp = [20**10]*(n+1)
dp[0] = 0
for coin in coins:
for price in range(coin,n+1):
dp[price] = min(dp[price],dp[price-coin]+1)
print(dp[n])
| 0 | null | 85,787,340,070,912 | 294 | 28 |
a=int(input())
print(int((a-1)/2)) | n = int(input())
iteration = n
ex = 0
count = 0
for i in range(1,n):
ex = iteration-i
#print(ex)
if ex <=i:
break
else:
count += 1
print(count) | 1 | 153,282,269,256,132 | null | 283 | 283 |
n,k=map(int,input().split())
L=[1]*n
for i in range(k):
d=int(input())
A=list(map(int,input().split()))
for a in A:
L[a-1] = 0
print(sum(L)) | n , d = map(int, input().split())
ans = 0
for _ in range(n):
p, q = map(int, input().split())
if (p ** 2 + q ** 2) ** 0.5 <= d:
ans += 1
print(ans) | 0 | null | 15,218,789,218,564 | 154 | 96 |
import re
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
import functools
def v(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 6)
mod = 10**9+7
cnt = 1
ans = 0
inf = float("inf")
al = "abcdefghijklmnopqrstuvwxyz"
AL = al.upper()
n = k()
s = v()
s1,s2,s3 = set(),set(),set()
for x in s:
for z in s2:
s3.add(z+x)
for y in s1:
s2.add(y+x)
s1.add(x)
print(len(s3))
| from itertools import product
N = int(input())
S = input()
pins = list(product([i for i in range(10)], repeat=3))
ans = 0
for pin in pins:
i = 0
for s in S:
if pin[i] == int(s):
i += 1
if i == 3:
ans += 1
break
print(ans) | 1 | 128,654,637,703,200 | null | 267 | 267 |
N,D = [int(i) for i in input().split()]
XY = []
count = 0
for i in range(N):
XY.append([int(i) for i in input().split()])
for xy in XY:
dd = xy[0]**2+xy[1]**2
if dd <= D**2:
count +=1
print(count) | import sys
def ISI(): return map(int, sys.stdin.readline().rstrip().split())
h, a =ISI()
print((h+a-1)//a) | 0 | null | 41,470,345,709,540 | 96 | 225 |
def main(S, T):
ans = 0
for i in range(len(S)):
if S[i] != T[i]:
ans += 1
return ans
if __name__ == '__main__':
S = input()
T = input()
ans = main(S, T)
print(ans)
| while True :
H, W = [int(temp) for temp in input().split()]
if H == W == 0 :
break
for making in range(H):
if making == 0 or making == (H - 1) : print('#' * W)
else : print('#' + ('.' * (W - 2)) + '#')
print() | 0 | null | 5,614,726,218,620 | 116 | 50 |
import heapq
from collections import deque
from enum import Enum
import sys
import math
from _heapq import heappush, heappop
BIG_NUM = 2000000000
MOD = 1000000007
EPS = 0.000000001
global current_time
global visited,go_time,back_time
global G
def dfs(node_id):
global current_time #書かないとローカル変数扱いされる
go_time[node_id] = current_time
current_time += 1
for next_node in G[node_id]:
if visited[next_node] == True:
continue
visited[next_node] = True
dfs(next_node)
back_time[node_id] = current_time
current_time += 1
V = int(input())
G = [[] for i in range(V)]
visited = [False]*V
go_time = [0]*V
back_time = [0]*V
for loop in range(V):
node_id,num,*tmp_adj = list(map(int,input().split()))
node_id -= 1
for i in range(num):
G[node_id].append(tmp_adj[i]-1)
current_time = 1;
for i in range(V):
if visited[i] == True:
continue
visited[i] = True
dfs(i)
for i in range(V):
print("%d %d %d"%(i+1,go_time[i],back_time[i]))
| from typing import List
def DFS(G: List[int]):
global time
time = 0
n = len(G)
for u in range(n):
if color[u] == "WHITE":
DFS_Visit(u)
def DFS_Visit(u: int):
global time
color[u] = "GRAY"
time += 1
d[u] = time
for v in G[u]:
if color[v] == "WHITE":
pi[v] = u
DFS_Visit(v)
color[u] = "BLACK"
time += 1
f[u] = time
if __name__ == "__main__":
n = int(input())
G = []
color = ["WHITE" for _ in range(n)]
pi = [None for _ in range(n)]
d = [0 for _ in range(n)]
f = [0 for _ in range(n)]
for _ in range(n):
command = list(map(int, input().split()))
G.append([x - 1 for x in command[2:]])
DFS(G)
for i in range(n):
print(f"{i + 1} {d[i]} {f[i]}")
| 1 | 2,861,993,432 | null | 8 | 8 |
N = int(input())
if N == 1:
print(0)
else:
mod = 10**9+7
print((10**N - (2*(9**N) - 8**N)) % mod)
| import sys
input = sys.stdin.readline
'''
'''
s = input().rstrip()
if s == "MON": print(6)
elif s == "SAT": print(1)
elif s == "FRI": print(2)
elif s == "THU": print(3)
elif s == "WED": print(4)
elif s == "TUE": print(5)
else:
print(7) | 0 | null | 67,955,142,885,868 | 78 | 270 |
N = int(input())
A = [int(x) for x in input().split()]
M = max(A)
count = [0 for _ in range(M + 1)]
for i in range(N):
count[A[i]] += 1
S = 0
for i in range(M + 1):
m = count[i]
S += (m * (m - 1)) // 2
ans = [S for _ in range(N)]
for i in range(N):
m = count[A[i]]
ans[i] -= m - 1
for i in range(N):
print(ans[i]) | n = int(input())
a = [int(i) for i in input().split()]
ball_count = [0] * (n + 1)
for i in a:
ball_count[i] += 1
def nCr(i):
if i<=1:
return 0
else:
return i*(i-1)//2
def get_total(ball_count):
ans = 0
for i in ball_count:
ans += nCr(i)
return ans
total = get_total(ball_count)
for i in range(1, n + 1):
num = ball_count[a[i - 1]]
ans = total - nCr(num) + nCr(num-1)
print(ans)
| 1 | 47,701,369,770,810 | null | 192 | 192 |
n,m = map(int, input().split())
s = int((n + m) * (n + m -1) / 2)
s -= n * m
print(s) | import math
n, m = map(int, input().split())
if n >= 2:
a = math.factorial(n)/(math.factorial(2)*math.factorial(n-2))
else:
a = 0
if m >= 2:
b = math.factorial(m)/(math.factorial(2)*math.factorial(m-2))
else:
b = 0
print(int(a + b)) | 1 | 45,592,774,905,258 | null | 189 | 189 |
a,b = map(int,input().split())
s = list(map(int,input().split()))
w = []
for i in range(b):
w.append(min(s))
s.remove(min(s))
print(sum(w)) | a=str(input())
print(a[0:3])
| 0 | null | 13,279,196,920,000 | 120 | 130 |
S = input()
count = 0
if S[0] == 'R' or S[1] == 'R' or S[2] == 'R':
count = 1
if (S[0] == 'R' and S[1] == 'R') or (S[1] == 'R' and S[2] == 'R'):
count = 2
if S[0] == 'R' and S[1] == 'R' and S[2] == 'R':
count = 3
print(count) | num = input()
streaks = []
streak = 0
for letter in num:
if letter == "R":
streak += 1
elif letter != "R":
streaks.append(streak)
streak = 0
else:
streaks.append(streak)
print(max(streaks)) | 1 | 4,881,851,548,992 | null | 90 | 90 |
input()
numbers = input().split()
#print(numbers)
r_numbers = reversed(numbers)
#print(r_numbers)
print(" ".join(r_numbers)) | num = int(input())
numbers = list(map(int,input().split()))
for i in reversed(numbers):
print(i,end="")
if i != numbers[0]:
print(" ",end="")
print()
| 1 | 989,375,968,310 | null | 53 | 53 |
def main():
L, R, d = map(int, input().split(' '))
X = 0
if L % d == 0:
X = int(L / d) - 1
else:
X = int(L / d)
print(int(R / d) - X)
main() | A,B,H,M=map(int, input().split())
import math
angle = abs(30*H-5.5*M)
angle = min(angle, 360-angle)*math.pi/180
c=A**2 + B**2 -2*A*B* math.cos(angle)
c=c**0.5
print(c) | 0 | null | 13,688,679,567,840 | 104 | 144 |
#全点対間最短経路を求めるアルゴリズム
def warshall_floyd(d):
#d[i][j]:iからjに行く最短経路
for k in range(1,n+1):
for i in range(1,n+1):
for j in range(1,n+1):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
return d
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**9)
n, m , l = map(int, input().split())
INF = 10 ** 11
d = [[INF]*(n+1) for _ in range(n+1)]
for i in range(m):
x, y, z = map(int, input().split())
if z <= l:
d[x][y] = z
d[y][x] = z #無向グラフならつける
for i in range(1,n+1):
d[i][i] = 0
ss = warshall_floyd(d)
for i in range(1,n+1):
for j in range(1,n+1):
if ss[i][j] <= l:
ss[i][j] = 1
#補給回数
vv = warshall_floyd(ss)
for i in range(1,n+1):
for j in range(1,n+1):
if vv[i][j] == INF:
vv[i][j] = -1
q = int(input())
for _ in range(q):
x, y = map(int, input().split())
if vv[x][y] != -1:
print(vv[x][y]-1)
else:
print(vv[x][y]) | def A():
seq = [1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51]
K = int(input())
print(seq[K-1])
A() | 0 | null | 111,968,870,834,440 | 295 | 195 |
n = int(input())
songs = []
for _ in range(n):
s, t = input().split()
t = int(t)
songs.append((s, t))
x = input()
ans = 0
flag = False
for s, t in songs:
if flag:
ans += t
if s == x:
flag = True
print(ans)
| a=input()
c=len(a)
b=a[:(c-1)//2]
d=a[(c+3)//2-1:]
if a==a[::-1] and b==b[::-1] and d==d[::-1]:
print("Yes")
else:
print("No") | 0 | null | 71,433,214,478,032 | 243 | 190 |
n = int(input())
tp = ((1,1),(1,-1))
for i in range(200):
for j in range(200):
for k in tp:
a,b = i*k[0],j*k[1]
if((a**5 - b**5)==n):
print(a,b)
exit() | def main():
X = int(input())
for i in range(-1000, 1000):
for j in range(-1000, 1000):
if i ** 5 - j ** 5 == X:
print(i, j)
return
main()
| 1 | 25,685,125,056,288 | null | 156 | 156 |
X=int(input())
#m1,d1=map(int,input().split())
#hl=list(map(int,input().split()))
#l=[list(map(int,input().split())) for i in range(n)]
flag=0
for i in range(1,1001):
if i*100 <= X and X <= i*105:
flag=1
break
print(flag)
| N = int(input())
S = input()
if N % 2 != 0:
print('No')
else:
left = S[:N//2]
right = S[N//2:]
if left == right:
print('Yes')
else:
print('No')
| 0 | null | 136,797,316,395,792 | 266 | 279 |
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
L1 = factorization(N - 1)
s = 1
# print(L1)
for [a, b] in L1:
s *= (b + 1)
# print(s)
def make_divisors(n):
lower_divisors, upper_divisors = [], []
i = 1
while i*i <= n:
if n % i == 0:
lower_divisors.append(i)
if i != n // i:
upper_divisors.append(n//i)
i += 1
return lower_divisors + upper_divisors[::-1]
for i in set(make_divisors(N))-{1}:
temp = N
while temp % i == 0:
temp //= i
if (temp-1) % i == 0:
s += 1
s -= 1
if N == 2:
print(1)
else:
print(s) | from collections import defaultdict
roots = defaultdict(list)
for k in range(2, 10 ** 6 + 1):
ki = k * k
while ki <= 10 ** 12:
roots[ki].append(k)
ki *= k
def factors(n):
fhead = []
ftail = []
for x in range(1, int(n ** 0.5) + 1):
if n % x == 0:
fhead.append(x)
if x * x != n:
ftail.append(n // x)
return fhead + ftail[::-1]
def solve(N):
works = set()
# Answer seems to be anything of the form: N = (K ** i) * (j * K + 1)
# Try every divisor of N as K ** i
for d in factors(N):
# If i == 1, then K == d
k = d
if (N // d) % k == 1:
assert k <= N
works.add(k)
if d == 1:
# If i == 0, then K ** 0 == 1, so K = (N - 1) // j, so anything that is a factor of N - 1 works
works.update(factors(N - 1))
elif d in roots:
# For i >= 2, see if it's in the list of precomputed roots
for k in roots[d]:
if k > N:
break
if (N // d) % k == 1:
works.add(k)
works.discard(1)
return len(works)
(N,) = [int(x) for x in input().split()]
print(solve(N))
if False:
def brute(N, K):
while N >= K:
if N % K == 0:
N = N // K
else:
N = N - K
return N
for N in range(2, 10000):
count = 0
for K in range(2, N + 1):
temp = brute(N, K)
if temp == 1:
print(N, K, temp)
count += 1
print("##########", N, count, solve(N))
assert count == solve(N)
| 1 | 41,256,621,310,252 | null | 183 | 183 |
N, M = map(int, input().split())
A = sorted(list(map(int, input().split())))
def count_bigger_x(x):
cnt = 0
piv = N-1
for a in A:
while piv >= 0 and a + A[piv] >= x:
piv -= 1
cnt += N - piv - 1
return cnt
def is_ok(x):
cnt = count_bigger_x(x)
return cnt >= M
def bisect(ng, ok):
while (abs(ok - ng) > 1):
mid = (ok + ng) // 2
if is_ok(mid):
ok = mid
else:
ng = mid
return ok
x = bisect(2 * A[-1] + 1, 2 * A[0] - 1)
ans = 0
piv = N-1
for a in A:
while piv >= 0 and a + A[piv] >= x:
piv -= 1
ans += (N - piv - 1) * a
ans *= 2
ans -= 1 * x * (count_bigger_x(x) - M)
print(ans)
| S = list(input())
K = int(input())
#print(S)
N=len(S)
#if K==1:
kosuu=[]
cnt=1
for i in range(N-1):
if S[i]==S[i+1]:
cnt+=1
if i==N-2:
kosuu.append(cnt)
elif S[i]!=S[i+1]:
kosuu.append(cnt)
cnt=1
#print('kosuu', kosuu)
dammy=0
for i in range(len(kosuu)):
dammy+=kosuu[i]//2
#else:
if K==1:
out=dammy
elif S[0]!=S[-1]:
out = dammy * K
elif len(S)==1:
out=K//2
elif len(kosuu)==1:
out=(kosuu[0]*K)//2
else:
#kotei=kosuu[1:-1] #少ないとき
kotei = dammy - kosuu[0]//2 - kosuu[-1]//2
aida = (kosuu[0] + kosuu[-1]) // 2
#print('aida',aida)
out = kosuu[0]//2 + (kotei*K) + aida*(K-1) + kosuu[-1]//2
print(out) | 0 | null | 141,474,876,571,552 | 252 | 296 |
x,y=map(int,input().split())
a=[300000,200000,100000]
b=[0]*300
a=a+b
add=0
if x*y==1:
add=400000
print(a[x-1]+a[y-1]+add)
| def keisan(x):
if x==1:
return 300000
elif x==2:
return 200000
elif x==3:
return 100000
else:
return 0
X,Y=map(int,input().split())
ans=keisan(X)+keisan(Y)
if X==Y==1:
ans+=400000
print(ans)
| 1 | 141,043,742,656,190 | null | 275 | 275 |
import math
while True:
n = input()
if(n == 0):
break
s = map(int, raw_input().split())
average = 0.0
for i in s:
average += i
average /= len(s)
alpha_pow = 0.0
for i in range(len(s)):
alpha_pow += (s[i] - average) * (s[i] - average)
alpha_pow /= n
print(math.sqrt(alpha_pow)) | i=0
while True:
N=int(input())
if N==0:
break
else:
a = list(map(float,input().split()))
m=sum(a)/N
#print(m)
for i in range(N):
a[i]=(float)(a[i]-m)**2
#print(a[i])
i+=1
A=(sum(a)/N)**(1/2)
print(A)
| 1 | 187,899,063,364 | null | 31 | 31 |
class UnionFind():
def __init__(self, n):
self.par = [i for i in range(n+1)]
self.rank = [0] * (n+1)
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if self.rank[x] < self.rank[y]:
self.par[x] = y
else:
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def same(self, x, y):
return self.find(x) == self.find(y)
N,M=map(int,input().split())
city=UnionFind(N)
for i in range(M):
A,B=map(int,input().split())
city.unite(A,B)
ck=[0]*(N+10)
for i in range(1,N+1):
root=city.find(i)
if ck[root]==0:
ck[root]=1
#print(city.par)
#print(ck)
Ans=sum(ck)-1
print(Ans)
| from collections import Counter
N, M = map(int, input().split())
class UnionFind:
def __init__(self, n):
self.root = [i for i in range(n)]
def unite(self, x, y):
if not self.same(x, y):
self.root[self.find(y)] = self.find(x)
def find(self, x):
if x == self.root[x]:
return x
else:
self.root[x] = self.find(self.root[x])
return self.root[x]
def same(self, x, y):
return self.find(x) == self.find(y)
UF = UnionFind(N)
ans = N-1
for _ in range(M):
x, y = map(int, input().split())
if not UF.same(x-1, y-1):
UF.unite(x-1, y-1)
ans -= 1
print(ans) | 1 | 2,289,710,479,650 | null | 70 | 70 |
import sys
sys.setrecursionlimit(10000000)
n = int(input())
G = [[] for i in range(n)]
d = [0 for i in range(n)]
f = [0 for i in range(n)]
color = [0 for i in range(n)]
stamp = 0
def dfs(u):
global stamp
if d[u]:
return
stamp += 1
d[u] = stamp
for v in G[u]:
if color[v] != 0:
continue
color[v] = 1
dfs(v)
color[u] = 2
stamp += 1
f[u] = stamp
color[0] = 1
for i in range(n):
inp = list(map(int, input().split()))
u = inp[0]
u -= 1
k = inp[1]
for j in range(k):
v = inp[j+2]
v -= 1
G[u].append(v)
#G[v].append(u)
for i in range(n):
dfs(i)
for i in range(n):
print("{0} {1} {2}".format(i+1, d[i], f[i]))
| 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 | 2,862,177,148 | null | 8 | 8 |
n, k = map(int, input().split())
s = []
mod = 998244353
for i in range(k):
l, r = map(int, input().split())
s.append([l, r])
dp = [0 for _ in range(n+1)]
dp[1] = 1
dpsum = [0 for _ in range(n+1)]
dpsum[1] = 1
for i in range(2,n+1):
for l, r in s:
li = max(i-r,1)
ri = max(i-l,0)
dp[i] += (dpsum[ri] - dpsum[li-1])%mod
dpsum[i] = (dpsum[i-1] + dp[i])%mod
print(dp[n]%mod) | N,K = map(int,input().split())
l = []
mod = 998244353
for i in range(K):
L,R = map(int,input().split())
l.append([L,R])
l.sort()
a = [0 for i in range(N+1)]
a[1] = 1
b = [0 for i in range(N+1)]
b[1] = 1
for i in range(2,N+1):
for j in range(K):
if l[j][0] < i:
a[i] += (b[i-l[j][0]]-b[max(0,i-l[j][1]-1)])%mod
else:
break
b[i] = (b[i-1]+a[i])%mod
mod = 998244353
print(a[N]%mod) | 1 | 2,660,911,978,880 | null | 74 | 74 |
import sys
def solve():
readline = sys.stdin.buffer.readline
mod = 10 ** 9 + 7
n, m = list(map(int, readline().split()))
print("Yes" if n == m else "No")
if __name__ == '__main__':
solve()
| def get_ints():
return map(int, input().split())
n, m = get_ints()
print('Yes' if n == m else 'No')
| 1 | 83,690,366,839,740 | null | 231 | 231 |
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
a,b,n=map(int, input().split())
if b<=n:
n=b-1
print(((a*n)//b) - (a*(n//b)))
if __name__ == '__main__':
main() | import sys
A,B,N = map(int, input().split())
def calc(a,b,x):
num = ((a*x)//b)-a*(x//b)
return num
if B == N:
X = N-1
print(calc(A,B,X))
sys.exit()
if B < N:
X = B-1
print(calc(A,B,X))
sys.exit()
if B > N:
X = N
print(calc(A,B,X))
sys.exit() | 1 | 28,304,592,219,820 | null | 161 | 161 |
n,m = map(int,input().split())
A = list(map(int,input().split()))
judge = sum(A) / (4 * m)
ans = []
for i in range(n):
if A[i] < judge :
continue
else:
ans.append(A[i])
print("Yes") if len(ans) >= m else print("No") | import sys
mod=10**9+7 ; inf=float("inf")
from math import sqrt, ceil
from collections import deque, Counter, defaultdict #すべてのkeyが用意されてる defaultdict(int)で初期化
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from decimal import ROUND_HALF_UP,Decimal #変換後の末尾桁を0や0.01で指定
#Decimal((str(0.5)).quantize(Decimal('0'), rounding=ROUND_HALF_UP))
from functools import lru_cache
#メモ化再帰defの冒頭に毎回 @lru_cache(maxsize=10**10)
#引数にlistはだめ
#######ここまでテンプレ#######
#ソート、"a"+"b"、再帰ならPython3の方がいい
#######ここから天ぷら########
n,k=map(int,input().split())
P=list(map(int,input().split()))
P=[i-1 for i in P]
C=list(map(int,input().split()))
ans=-inf
for i in range(n):
now=i
total=0
roop= 0
po=deque([0])
for kai in range(1,k+1):
now=P[now]
total += C[now]
roop+=1
po.append(total)
ans=max(ans, total)
if now == i:
la= kai;break
else: continue
if total<0 : continue
po=list(po)
ans=max(ans, total* (k//roop) + max(po[:k%roop+1]), total*(k//roop-1) + max(po))
#print(total, roop,po ,ans)
print(ans) | 0 | null | 21,880,053,686,748 | 179 | 93 |
import cmath
import sys
INF=10**18
MOD=10**9+7
MAX=10**5+7
def main():
s=input()
for i in range(6):
if s=="hi"*i:
print("Yes")
return
print("No")
if __name__=='__main__':
main() | X = input()
l = len(X)
m = l//2
if (X == 'hi'*m):
print("Yes")
else:
print("No") | 1 | 53,052,551,268,584 | null | 199 | 199 |
import math
t = float(input())
a = math.pi * t**2
b = 2 * t * math.pi
print(str("{0:.8f}".format(a)) + " " + "{0:.8f}".format(b)) | import sys
import decimal # 10進法に変換,正確な計算
def input():
return sys.stdin.readline().strip()
def main():
a, b = map(int, input().split())
if a >= 10 or b >= 10:
print(-1)
return
print(a*b)
main()
| 0 | null | 79,115,578,156,720 | 46 | 286 |
import sys
def input(): return sys.stdin.readline().rstrip()
A,B,C,K = map(int,input().split())
point = 0
if A <= K:
point += A
K -= A
else:
point += K
K = 0
if B <= K:
K -= B
else:
K = 0
point -= K
print(point) | n = int(input())
i = 0
l = list(map(int, input().split()))
Max = l[0]
Min = l[0]
sum = 0
for i in range(0,n):
sum += l[i]
a = l[i]#変数の値が下の行の処理で変わってしまうのでaとかにしておく
if a > Max:
a,Max = Max,a
if a < Min:
a,Min = Min,a
print(f"{Min} {Max} {sum}")
| 0 | null | 11,304,384,012,304 | 148 | 48 |
n,m = map(int,input().split())
h = list(map(int,input().split()))
r = ['t'] * n
for i in range(m):
x,y = map(int,input().split())
if h[x-1] > h[y-1]:
r[y-1] = 'f'
elif h[x-1] < h[y-1]:
r[x-1] = 'f'
else:
r[y-1] = 'f'
r[x-1] = 'f'
s = 0
for i in range(n):
if r[i] == 't':
s += 1
print(s) | def main() -> None:
n, m = map(int, input().split())
heights = tuple(map(int, input().split()))
good = [1] * n
for _ in range(m):
a, b = map(int, input().split())
height_a, height_b = heights[a-1], heights[b-1]
if height_a == height_b:
good[a-1], good[b-1] = 0, 0
elif height_a < height_b:
good[a-1] = 0
else:
good[b-1] = 0
print(good.count(1))
return
if __name__ == '__main__':
main()
| 1 | 25,076,408,199,520 | null | 155 | 155 |
N = int(input())
MOD = 1000000007
ans = (10**N - 9**N - 9**N + 8**N) % MOD
print(ans) | s=input()*2
r=input()
if(r in s):
print('Yes')
else:
print('No') | 0 | null | 2,488,104,290,400 | 78 | 64 |
N = int(input())
S = list(input())
ans = 0
for x in range(1000) :
X = list(str(x).zfill(3))
i = 0
j = 0
if X[0] in S[:N-2] :
i = S.index(X[0])
else :
continue
if X[1] in S[i+1:N-1] :
j = S[i+1:N-1].index(X[1])+i+1
else :
continue
if X[2] in S[j+1:N] :
ans += 1
print(ans)
| MOD = 998244353
N,K = map(int,input().split())
l = []
dp = [0]*N
sdp = [0]*(N+1)
for i in range(K):
L,R = map(int,input().split())
l.append([L,R])
dp[0] = 1
sdp[1] = 1
for i in range(1,N):
for L, R in l:
dp[i] += sdp[max(0,i - L+1)] - sdp[max(0,i - R)]
dp[i] %= MOD
sdp[i+1] = sdp[i] + dp[i]
sdp[i+1] %= MOD
print(dp[N-1]) | 0 | null | 65,794,180,928,708 | 267 | 74 |
class UnionFind:
def __init__(self, n: int) -> None:
self.forest = [-1] * n
def union(self, x: int, y: int) -> None:
x = self.findRoot(x)
y = self.findRoot(y)
if x == y:
return
if self.forest[x] > self.forest[y]:
x,y = y,x
self.forest[x] += self.forest[y]
self.forest[y] = x
return
def findRoot(self, x: int) -> int:
if self.forest[x] < 0:
return x
else:
self.forest[x] = self.findRoot(self.forest[x])
return self.forest[x]
def issame(self, x: int, y: int) -> bool:
return self.findRoot(x) == self.findRoot(y)
def size(self,x: int) -> int:
return -self.forest[self.findRoot(x)]
n,m = map(int,input().split())
uf = UnionFind(n)
s = set()
for i in range(m):
ai,bi = map(int,input().split())
uf.union(ai-1,bi-1)
for i in range(n):
s.add(uf.findRoot(i))
print(len(s)-1) | a = 0
n,k=input().split()
p=input().split(" ")
for i in range(int(n)):
p[i] = int(p[i])
p=sorted(p)
for i in range(int(k)):
a += int(p[i])
print(a) | 0 | null | 6,902,134,292,768 | 70 | 120 |
def main():
N, M = map(int, input().split())
A = list(map(int, input().split()))
threshold = sum(A) / (4 * M)
if sorted(A, reverse=True)[M-1] >= threshold:
print("Yes")
else:
print("No")
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
# Generated by https://github.com/kyuridenamida/atcoder-tools
from typing import *
import collections
import itertools
import math
import sys
INF = float('inf')
def solve(X: int, Y: int, Z: int):
return f"{Z} {X} {Y}"
def main():
sys.setrecursionlimit(10 ** 6)
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
X = int(next(tokens)) # type: int
Y = int(next(tokens)) # type: int
Z = int(next(tokens)) # type: int
print(f'{solve(X, Y, Z)}')
if __name__ == '__main__':
main()
| 0 | null | 38,472,317,357,860 | 179 | 178 |
import math
def koch(n, p1, p2):
if n == 0:
return
s = [(2 * p1[0] + p2[0]) / 3, (2 * p1[1] + p2[1]) / 3]
t = [(p1[0] + 2 * p2[0]) / 3, (p1[1] + 2 * p2[1]) / 3]
u = [(t[0] - s[0]) * math.cos(math.radians(60))
- (t[1] - s[1]) * math.sin(math.radians(60)) + s[0],
(t[0] - s[0]) * math.sin(math.radians(60))
+ (t[1] - s[1]) * math.cos(math.radians(60)) + s[1]]
koch(n - 1, p1, s)
print(s[0], s[1])
koch(n - 1, s, u)
print(u[0], u[1])
koch(n - 1, u, t)
print(t[0], t[1])
koch(n - 1, t, p2)
n = int(input())
p1 = (0, 0)
p2 = (100, 0)
print(p1[0], p1[1])
koch(n, p1, p2)
print(p2[0], p2[1]) | 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)
| 0 | null | 1,391,437,130,930 | 27 | 74 |
import sys
K = int(input())
A, B = (int(x) for x in input().split())
num=0
while B>=num:
num+=K
if A<=num and num<=B:
print("OK")
sys.exit(0)
print("NG") | from sys import stdin
n, k, s = map(int, stdin.readline().rstrip().split())
flag = 0
for i in range(n):
if flag < k:
print(s)
flag += 1
else:
if s == 10 ^ 9:
print(s-1)
else:
if s == 1:
print(2)
else:
print(s-1) | 0 | null | 58,993,663,200,470 | 158 | 238 |
# -*- coding: utf-8 -*-
char = input()
print(char.swapcase())
| K = int(input())
ai_1 = 0
for i in range(K):
ai = (10*ai_1 + 7)%K
if ai==0:
print(i+1)
exit()
ai_1 = ai
print("-1")
| 0 | null | 3,850,780,165,400 | 61 | 97 |
N = int(input())
C = input()
r_n = 0
ans = 0
for c in C:
if c == 'R':
r_n += 1
for i in range(r_n):
if C[i] == 'W':
ans += 1
print(ans) | s = input()
for _ in range(int(input())):
c = input().split()
a = int(c[1])
b = int(c[2])
if c[0] == "replace":
s = s[:a] + c[3] + s[b+1:]
elif c[0] == "reverse":
s = s[:a] + s[a:b+1][::-1] + s[b+1:]
else:
print(s[a:b+1])
| 0 | null | 4,227,638,937,000 | 98 | 68 |
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal
#from numba import jit
INF = 1 << 50
EPS = 1e-8
mod = 10 ** 9 + 7
def mapline(t = int):
return map(t, sysread().split())
def mapread(t = int):
return map(t, read().split())
def generate_inv(n,mod):
"""
逆元行列
n >= 2
Note: mod must bwe a prime number
"""
ret = [0, 1]
for i in range(2,n+1):
next = -ret[mod%i] * (mod // i)
next %= mod
ret.append(next)
return ret
def run():
N, *A = mapread()
maxA = max(A)
L = maxA.bit_length()
subs = [0] * L
for k in range(L):
sum = 0
for a in A:
if (a >> k) & 1:
sum += 1 << k
sum %= mod
subs[k] = sum
sumA = 0
for a in A:
sumA += a
sumA %= mod
ret = 0
ret += (sumA * N) % mod
ret += (sumA * N) % mod
sub_sum = 0
for a in A:
sums = 0
for k in range(L):
if (a >> k) & 1:
sums += subs[k] * 2
sums %= mod
sub_sum += sums
sub_sum %= mod
ret -= sub_sum
ret %= mod
inv = generate_inv(2, mod)
ret *= inv[2]
ret %= mod
print(ret)
if __name__ == "__main__":
run()
| import numpy as np
N=int(input())
A=np.array([int(x) for x in input().split()])
ans=0
M=pow(10,9)+7
for i in range(100):
one=int(np.sum((A>>i)&1))
zero=N-one
ans+=(one*zero)*pow(2,i)
ans%=M
#print(one,zero)
print(ans) | 1 | 122,652,338,770,830 | null | 263 | 263 |
n = input()
if '7' in n:
print('Yes')
exit()
else:
print('No') | import sys, bisect, collections, math
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
INF = 10**20
MOD = 1000000007
def I(): return int(input())
def F(): return float(input())
def S(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()
def resolve():
N = I()
AB = [LI() for _ in range(N)]
# A, Bを標準化 互いに疎でAは正
def normalize(AB):
A = AB[0]
B = AB[1]
if A==B==0:
return (0, 0)
elif A==0:
return(0, 1)
elif B==0:
return(1, 0)
else:
gcd = math.gcd(A, B)
A //= gcd
B //= gcd
if A<0:
A, B = -A, -B
return (A, B)
def orthogonal(AB):
A = AB[0]
B = AB[1]
if B>0:
return (B, -A)
else:
return(-B, A)
AB_n = [normalize(i) for i in AB]
counter = collections.Counter(AB_n)
# 場合の数を求める
used = set()
ans = 1
# (0, 0)以外について
for A, B in AB_n:
if not (A, B) in used:
if (A, B)!=(0, 0):
ans *= pow(2, counter[(A, B)], MOD) + pow(2, counter[orthogonal((A, B))], MOD) - 1
ans %= MOD
used.add((A, B))
used.add(orthogonal((A, B)))
ans -= 1
# (0, 0)について
ans += counter[(0, 0)]
ans %= MOD
print(ans)
if __name__ == '__main__':
resolve()
| 0 | null | 27,543,194,334,084 | 172 | 146 |
N=int(input())
S=['A']*N
T=[0]*N
for i in range(N):
s,t=input().split()
S[i]=s
T[i]=int(t)
print(sum(T[S.index(input())+1:])) | A,B,C,K = map(int,input().split())
ans = 0
if K > A:
ans += A
K -= A
if K > B:
ans += 0
K -= B
if K > 0:
ans -= K
else:
ans += 0
else:
ans = K
print(ans) | 0 | null | 59,221,283,955,610 | 243 | 148 |
import sys
input = sys.stdin.readline
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in range(n)]
ab = [(x,y) for x,y in zip(a,b)]
from operator import itemgetter
ab = tuple(sorted(ab,key=itemgetter(0),reverse=True))
dp = [[-10**14]*(n+1) for i in range(n+1)]
dp[0][0] = 0
for i in range(n):
for j in range(i+2):
if j >= 1:
dp[i+1][j] = max(dp[i][j]+ab[i][0]*abs(ab[i][1]-(n-1-(i-j))),dp[i][j-1]+ab[i][0]*abs(ab[i][1]+1-j))
if j == 0:
dp[i+1][0] = dp[i][0] + ab[i][0]*abs(ab[i][1]-(n-1-i))
print(max(dp[n])) | N=int(input())
S=[]
T=[]
total=0
for i in range(N):
s,t=map(str,input().split())
t=int(t)
total+=t
S.append(s)
T.append(t)
X=input()
flag=True
a=0
j=0
while flag:
a+=T[j]
if S[j]==X:
flag=False
j+=1
print(total-a) | 0 | null | 64,968,199,891,932 | 171 | 243 |
N = int(input())
A = [int(i) for i in input().split()]
maxA=max(A)
pn=list(range(maxA+1))
n=2
while n*n <= maxA:
if n == pn[n]:
for m in range(n, len(pn), n):
if pn[m] == m:
pn[m] = n
n+=1
s=set()
for a in A:
st = set()
while a > 1:
st.add(pn[a])
a//=pn[a]
if not s.isdisjoint(st):
break
s |= st
else:
print("pairwise coprime")
exit()
from math import gcd
n = gcd(A[0], A[1])
for a in A[2:]:
n=gcd(n,a)
if n == 1:
print("setwise coprime")
else:
print("not coprime")
| n = int(input())
a = list(map(int, input().split()))
num = [0]*(10**6+1)
for x in a:
num[x] += 1
pairwise = True
for i in range(2, 10**6+1):
cnt = sum(num[i::i])
if cnt == n:
print('not coprime')
exit()
if cnt > 1:
pairwise = False
if pairwise:
print('pairwise coprime')
else:
print('setwise coprime')
| 1 | 4,119,152,626,308 | null | 85 | 85 |
a, b = map(int, input().split())
print(a //b , a % b, "{0:.5f}".format(a / b)) | n=int(input())
A=list(map(int,input().split()))
m=max(A)
X=[0]*(m+1)
A.sort()
for i in range(n):
for j in range(A[i]*2,m+1,A[i]):
X[j]=2
X[A[i]]+=1
print(X.count(1)) | 0 | null | 7,573,008,971,170 | 45 | 129 |
x,k = map(int,input().split())
y = x % k
print(min(y,k-y)) | '''
Created on 2020/09/04
@author: harurun
'''
def main():
import sys
pin=sys.stdin.readline
pout=sys.stdout.write
perr=sys.stderr.write
N=int(pin())
S=pin()[:-1]
cnt=0
l=["0","1","2","3","4","5","6","7","8","9"]
for i in l:
for j in l:
for k in l:
c=[i,j,k]
n=0
for m in S:
if m==c[n]:
if n==2:
cnt+=1
break
else:
n+=1
print(cnt)
return
main()
#解説AC | 0 | null | 84,267,604,333,572 | 180 | 267 |
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
divisors.sort()
return divisors[1:]
n = int(input())
a = make_divisors(n-1)
b = make_divisors(n)
count = 0
for kk in b:
mom = n
while mom % kk == 0:
mom //= kk
if mom % kk == 1:
count +=1
print(len(a) + count)
| N = int(input())
count = 0
if N ==2:
print(1)
else:
for i in range(2,int((N-1)**0.5)+1):
if (N-1)%i == 0:
count += 1
if (N-1)//i != i:
count += 1
for j in range(2,int(N**0.5)+1):
if N%j == 0:
n = N
while n%j == 0:
n = n//j
if n%j == 1:
count += 1
if N//j != j:
n = N
while n%(N//j) == 0:
n = n//(N//j)
if n%(N//j) == 1:
count += 1
print(count+2)
| 1 | 41,367,466,663,200 | null | 183 | 183 |
N=int(input())
A=list(map(int,input().split()))
import itertools
ACU=itertools.accumulate(A)
B=list(ACU)
MAX=B[-1]
tmp=10**10
for i in B:
tmp=min(tmp,abs(2*i-MAX))
print(tmp) | if __name__ == '__main__':
s = input()
t = input()
if s == t[:-1]:
print("Yes")
else:
print("No")
| 0 | null | 81,810,434,418,928 | 276 | 147 |
s = input()*2
print('Yes' if input() in s else 'No') | a,b = raw_input().split(" ")
x = int(a)*2+int(b)*2
y = int(a)*int(b)
print "%d %d"%(y,x) | 0 | null | 1,006,590,745,190 | 64 | 36 |
N = int(input())
A = list(map(int, input().split()))
sm=0
mod=10**9+7
s=sum(A)
for i in A:
s-=i
sm+=i*s
sm%=mod
print(sm) | N = int(input())
A = list(map(int, input().split()))
mod = 10**9+7
k = int((10**9 + 8)/2)
sum = 0
sum_1 = 0
for i in range(N):
sum += A[i]
sum = (sum**2)%mod
for j in range(N):
sum_1 += A[j]**2
sum_1 = (sum_1)%mod
ans = sum - sum_1
ans = (ans*k)%mod
print(ans)
| 1 | 3,806,411,546,410 | null | 83 | 83 |
#!/usr/bin/env python3
import collections as cl
import sys
def II():
return int(sys.stdin.readline())
def MI():
return map(int, sys.stdin.readline().split())
def LI():
return list(map(int, sys.stdin.readline().split()))
def main():
N = II()
S = LI()
if len(set(S)) == N:
print("YES")
else:
print("NO")
main()
| import sys
input = sys.stdin.readline
n=int(input())
L=list(map(int,input().split()))
if len(set(L))!=n:
print('NO')
else:
print('YES')
| 1 | 73,742,348,393,058 | null | 222 | 222 |
a,b=input().split()
a=int(a)
b=int(b)
if a*500>=b:
print("Yes")
else:
print("No") | import sys
import math
import itertools
k,x=(int(i) for i in input().split())
if(k*500>=x):
print("Yes")
else:
print("No") | 1 | 98,181,366,457,472 | null | 244 | 244 |
s = input().rstrip()
p = input().rstrip()
line = s + s
print("Yes") if p in line else print("No")
| a,b,c = [int(i) for i in input().split()]
print("Yes" if(a * a + b * b + c * c - 2 * a * b - 2 * b * c - 2 * c * a > 0 and c - a - b > 0) else "No") | 0 | null | 26,747,169,847,332 | 64 | 197 |
N = int(input())
A = [int(i) for i in input().split()]
ans = 0
for i,a in enumerate(A):
idx = i+1
if a%2 == 1 and idx%2 == 1:
ans += 1
print(ans) | input()
result = 0
for i, x in enumerate([int(a) for a in input().split()]):
result += (i+1) & 1 and x & 1
print(result) | 1 | 7,757,066,131,346 | null | 105 | 105 |
ab = input().split()
print(int(ab[0]) * int(ab[1])) | #142-A
N = int(input())
D = []
for i in range(1,N+1):
D.append(i)
#print(D)
cnt = 0
for j in D:
if j % 2 != 0:
cnt += 1
#print(cnt)
print(cnt / len(D))
| 0 | null | 96,882,586,824,628 | 133 | 297 |
n, m, k = map(int, input().split())
mod = 998244353
N = 10**5 * 2 # N!まで求める
fact = [1, 1] # 階乗の元テーブル
fact_inv = [1, 1] # 階乗の逆元テーブル
inv = [0, 1] # 逆元テーブル計算用テーブル 1,2,,...の逆元を求めてる
# 計算 O(1)
def comb(n, r, mod):
if (r<0 or r>n):
return 0
r = min(r, n-r)
return fact[n] * fact_inv[r] * fact_inv[n-r] % mod
# 順列
def perm(n, r, mod):
if (r<0 or r>n):
return 0
return fact[n] * fact_inv[n-r] % mod
# 前処理 O(n)
for i in range(2, N + 1):
fact.append((fact[-1] * i) % mod)
inv.append((-inv[mod % i] * (mod//i)) % mod)
fact_inv.append((fact_inv[-1] * inv[-1]) % mod)
ans = 0
for i in range(k+1):
ans += comb(n-1, i, mod) * m * pow(m-1, n-i-1, mod)
ans %= mod
print(ans) | import math
a, b, h, m = map(int, input().split())
st = (60*h+m)/360*math.pi
lt = m/30*math.pi
sx = a*math.sin(st)
sy = a*math.cos(st)
lx = b*math.sin(lt)
ly = b*math.cos(lt)
print(math.sqrt((lx-sx)**2+(ly-sy)**2))
| 0 | null | 21,645,675,956,440 | 151 | 144 |
int(input())
s = list(input())
ans = 0
for i in range(10):
if str(i) in s:
ss = s[s.index(str(i))+1:]
for j in range(10):
if str(j) in ss:
sss = ss[ss.index(str(j))+1:]
for k in range(10):
if str(k) in sss:
ans += 1
print(ans) | contests = ['ABC', 'ARC']
before_contest = input()
print(contests[0] if before_contest == contests[1] else contests[1]) | 0 | null | 76,327,166,641,220 | 267 | 153 |
n, k = map(int, input().split())
A = list(map(int, input().split()))
F = list(map(int, input().split()))
A = sorted(A)
Minus_A = [-x for x in A]
F = sorted(F, reverse=True)
high = 10**12
low = 0
while high - low > 1:
mid = low + (high-low)//2
count = 0
for i in range(n):
now = mid // F[i]
count += max(A[i] - now, 0)
# print('-'*30)
# print(mid)
# print(count)
if count > k:
low = mid
else:
high = mid
ans = high
if sum(A) <= k:
ans = 0
print(ans)
| a = input()
if a == 'SUN':
print(7)
elif a == 'MON':
print(6)
elif a == 'TUE':
print(5)
elif a == 'WED':
print(4)
elif a == 'THU':
print(3)
elif a == 'FRI':
print(2)
else:
print(1)
| 0 | null | 149,243,822,821,300 | 290 | 270 |
n=int(input())
c=0
a=list(map(int,input().split()))
for i in range(n):
m=i
for j in range(i,n):
if a[m]>a[j]:m=j
if i!=m:a[m],a[i]=a[i],a[m];c+=1
print(*a)
print(c) | l= list(input().split())
a,b = map(int,input().split())
u = input()
if u == l[0]:
a -= 1
else:
b -= 1
print(a,b) | 0 | null | 35,918,694,620,492 | 15 | 220 |
def yumiri(L, n):
for i in range(len(L)):
if L[i] > n:
return i - 1
def parunyasu(a, b, p, q):
reans = ans
rd1, rq1, d1, nd1, nq1, q1, newans = naobou(a, q, reans)
rd2, rq2, d2, nd2, nq2, q2, newans = naobou(b, p, newans)
if reans <= newans:
t[d1 - 1] = q1
t[d2 - 1] = q2
return newans
else:
ayaneru(rd2, rq2, d2, nd2, nq2)
ayaneru(rd1, rq1, d1, nd1, nq1)
return reans
def ayaneru(rd, rq, d, nd, nq):
ZL[rd].insert(rq, d)
del ZL[nd][nq + 1]
def naobou(d, q, ans):
newans = ans
rd = t[d - 1] - 1
rq = yumiri(ZL[rd], d)
newans += SUMD[ZL[rd][rq] - ZL[rd][rq - 1] - 1] * c[rd]
newans += SUMD[ZL[rd][rq + 1] - ZL[rd][rq] - 1] * c[rd]
newans -= SUMD[ZL[rd][rq + 1] - ZL[rd][rq - 1] - 1] * c[rd]
del ZL[rd][rq]
nd = q - 1
nq = yumiri(ZL[nd], d)
newans += SUMD[ZL[nd][nq + 1] - ZL[nd][nq] - 1] * c[nd]
newans -= SUMD[d - ZL[nd][nq] - 1] * c[nd]
newans -= SUMD[ZL[nd][nq + 1] - d - 1] * c[nd]
ZL[nd].insert(nq + 1, d)
newans -= s[d - 1][rd]
newans += s[d - 1][nd]
return rd, rq, d, nd, nq, q, newans
def rieshon():
ans = 0
for i in range(D):
ans += s[i][t[i] - 1]
for j in range(26):
if t[i] - 1 == j:
L[j] = 0
ZL[j].append(i + 1)
else:
L[j] += 1
ans -= L[j] * c[j]
for i in range(26):
ZL[i].append(D + 1)
return ans
import time
import random
startTime = time.time()
D = int(input())
c = list(map(int, input().split()))
s = [list(map(int, input().split())) for _ in range(D)]
L = [0] * 26
ZL = [[0] for _ in range(26)]
SUMD = [0] * (D + 1)
for i in range(1, D + 1):
SUMD[i] = SUMD[i - 1] + i
RD = [0] * 26
t = [0] * D
for i in range(D):
RD[0] += 1
ma = s[i][0] + RD[0] * c[0]
man = 0
for j in range(1, 26):
RD[j] += 1
k = s[i][j] + RD[j] * c[j]
if k > ma:
ma = k
man = j
t[i] = man + 1
RD[man] = 0
ans = rieshon()
while time.time() - startTime < 1.8:
l = random.randrange(min(D - 1, 13)) + 1
d = random.randrange(D - l) + 1
p = t[d - 1]
q = t[d + l - 1]
if p == q: continue
ans = parunyasu(d, d + l, p, q)
for i in range(D):
print(t[i])
| def insertion_sort(array, size, gap=1):
""" AOJ??¬??¶?????¬???
http://judge.u-aizu.ac.jp/onlinejudge/commentary.jsp?id=ALDS1_1_A
:param array: ?????????????±??????????
:return: ?????????????????????
"""
global Count
for i in range(gap, len(array)): # i????¬??????????????????????????????????
v = array[i] # ?????¨?????\???????????¨????????????????????????????????´???
j = i - gap
while j >= 0 and array[j] > v:
array[j + gap] = array[j]
j = j - gap
Count += 1
array[j + gap] = v
return array
def shell_sort(array, n):
Count = 0
G = calc_gap(n)
m = len(G)
print(m)
print(' '.join(map(str, G)))
for i in range(0, m):
insertion_sort(array, n, G[i])
def calc_gap(n):
results = [1]
while results[-1] < n:
results.append(3 * results[-1] + 1)
if len(results) > 1:
results = results[:-1]
results.sort(reverse=True)
return results
Count = 0
if __name__ == '__main__':
# ??????????????\???
# data = [5, 1, 4, 3, 2]
data = []
num = int(input())
for i in range(num):
data.append(int(input()))
# ???????????????
shell_sort(data, len(data))
# ???????????¨???
print(Count)
for i in data:
print(i) | 0 | null | 4,843,290,900,102 | 113 | 17 |
H,W,M=map(int,input().split())
#二次元リストではなく列行を一個のボムで消してくれるためそれぞれのリストを用意。
sumh = [0] * H
sumw = [0] * W
bomb=[]
for i in range(M):
h,w=map(int,input().split())
sumh[h-1]+=1
sumw[w-1]+=1
bomb.append((h,w))
#爆弾の個数の最大値とその最大値がいくつずつあるか(ch,cw)に保存。最大の列と最大の行のいずれかの組み合わせに置くことで爆破数を最大化できる。
maxh=max(sumh)
maxw=max(sumw)
ch=sumh.count(maxh)
cw=sumw.count(maxw)
#print(maxh,maxw,ch,cw)
#爆弾のある場所がH,Wの座標で両方共で最大個数の場所であった場合その数を加算
count=0
for h,w in bomb:
if sumh[h-1]==maxh and sumw[w-1]==maxw:
count+=1
#print(count)
#破壊できる数は、そのマスに爆破対象があるとき一つ減ってしまう。
if count==ch*cw:
print(maxh+maxw-1)
else:
print(maxh+maxw) | N=int(input())
A=list(map(int,input().split()))
sumA=0
sumB=[0]
for i in range(N):
sumB.append(sumB[i]+A[i])
i=i+1
for j in range(N-1):
sumA=sumA+(A[j]*(sumB[N]-sumB[j+1]))%(10**9+7)
j=j+1
print(sumA%(10**9+7)) | 0 | null | 4,243,712,292,796 | 89 | 83 |
from sys import stdout
printn = lambda x: stdout.write(str(x))
inn = lambda : int(input())
inl = lambda: list(map(int, input().split()))
inm = lambda: map(int, input().split())
ins = lambda : input().strip()
DBG = True and False
BIG = 999999999
R = 10**9 + 7
def ddprint(x):
if DBG:
print(x)
n,t = inm()
ab = []
for i in range(n):
aa,bb = inm()
ab.append((aa,-bb))
ab.sort()
d = [ [-1]*(t+1) for i in range(n+1) ]
for i in range(n+1):
d[i][0] = 0
#ddprint(d)
for i in range(n):
for j in range(t+1):
d[i+1][j] = max(d[i+1][j], d[i][j])
if j<t and d[i][j]>=0:
s = min(t,j+ab[i][0])
d[i+1][s] = max(d[i+1][s], d[i][j]-ab[i][1])
if DBG:
for i in range(n):
printn(i)
ddprint(d[i])
mx = 0
for j in range(t,-1,-1):
if d[n][j]>=0:
mx = max(mx,d[n][j])
print(mx)
| n = int(input())
nums=list(input().split())
def selectionSort(nums):
count=0
for i in range(len(nums)):
minj=i
for j in range(i,len(nums)):
if int(nums[j])<int(nums[minj]):
minj=j
if i!=minj:
tmp=nums[minj]
nums[minj]=nums[i]
nums[i]=tmp
count+=1
print(' '.join(nums))
print(count)
selectionSort(nums)
| 0 | null | 75,944,432,606,280 | 282 | 15 |
N, A, B = map(int, input().split())
cont_num = A+B
k = N // cont_num
# print(k)
adjust_num = N - k*cont_num
add_blue = 0
if adjust_num >= A:
add_blue = A
else:
add_blue = adjust_num
print(k*A + add_blue) | n,a,b = map(int,input().split())
A=n//(a+b)
B=n%(a+b)
ans = a * A
if B>=a:
ans += a
else:
ans += B
print(ans) | 1 | 55,385,991,718,948 | null | 202 | 202 |
n, k = map(int, input().split())
if n>k:
n= n-(n//k)*k
while n >abs(k-n):
n= abs(k-n)
print(n) | N, K = list(map(int, input().split()))
if N >= K:
N = N % K
print(min(N, max(N-K, K-N))) | 1 | 39,333,233,681,940 | null | 180 | 180 |
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = 10**6#float('inf')
mod = 10 ** 9 + 7
#mod = 998244353
#from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10
N, T = MAP()
AB = [LIST() for _ in range(N)]
AB.sort(key = lambda x:x[0])
t = [0]*T
ans = 0
for A, B in AB:
for i in range(T-1, 0, -1):
if t[i]:
if T <= i+A:
ans = max(ans, t[i]+B)
else:
t[i+A] = max(t[i+A], t[i]+B)
if T <= A:
ans = max(ans, B)
else:
t[A] = max(t[A], B)
ans = max(ans, max(t))
print(ans) | import math
N,K = map(int,input().split())
A = sorted(list(map(int,input().split())))
F = sorted(list(map(int,input().split())),reverse=True)
high = 0
for i in range(N):
high = max(high,A[i]*F[i])
low = -1
while high-low>1:
mid = (high+low)//2
flag = 1
T = K
for i in range(N):
if A[i]*F[i]<=mid:continue
else:
T -= math.ceil(A[i]-mid/F[i])
if T<0:
flag = 0
break
if flag==1:
high = mid
else:
low = mid
print(high) | 0 | null | 158,804,931,550,368 | 282 | 290 |
from fractions import gcd
def lcm(x, y):
return (x * y) // gcd(x, y)
def main():
a,b = map(int,input().split())
print(lcm(a, b))
main()
| 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 | 1 | 113,529,611,475,200 | null | 256 | 256 |
while True:
H, W = map(int, input().split())
if H == W == 0:
break
for i in range(H):
for j in range(W):
if (i + j) % 2 == 0:
print('#', end = '')
else:
print('.', end = '')
print()
print()
| while True:
s = input().split(" ")
H = int(s[0])
W = int(s[1])
if H == 0 and W == 0:
break
for i in range(H):
for j in range(W):
if i % 2 == 0:
if j % 2 == 0:
print("#",end="")
else:
print(".",end="")
else:
if j % 2 == 0:
print(".",end="")
else:
print("#",end="")
print("")
print("") | 1 | 864,001,894,678 | null | 51 | 51 |
a=['SUN','MON','TUE','WED','THU','FRI','SAT']
s=input()
for i in range(7):
if a[i]==s:
print(7-i) | import math
r = float(input())
print("{:.6f}".format(r*r*math.pi), "{:.6f}".format(2*r*math.pi))
| 0 | null | 67,163,344,486,770 | 270 | 46 |
def lu(n):
L.append(n)
a=n%10
if len(str(n))>11:
return 1
if a==0:
lu(n*10+1)
lu(n*10)
elif a==9:
lu(n*10+9)
lu(n*10+8)
else:
lu(n*10+1+a)
lu(n*10+a-1)
lu(n*10+a)
L=list()
lu(1)
lu(2)
lu(3)
lu(4)
lu(5)
lu(6)
lu(7)
lu(8)
lu(9)
L=sorted(set(L))
k=int(input())
print(L[k-1]) | a=list(map(int,input().split()))
print(*[a[2],a[0],a[1]],sep=' ') | 0 | null | 39,101,919,225,500 | 181 | 178 |
def run(N, M, A):
'''
Aiが10^5なので、searchを以下に変えられる
サイズ10**5のリストで、その満足度を持つ数の件数を事前計算しておけばO(1)で求められる
'''
A = sorted(A, reverse=True)
cnt_A = [len(A)]
pre_a = 0
cnt_dict_A = {}
for a in sorted(A):
cnt_dict_A[a] = cnt_dict_A.get(a, 0) + 1
next_cnt = cnt_A[-1]
for a in sorted(cnt_dict_A.keys()):
cnt_A.extend([next_cnt]*(a-pre_a))
pre_a = a
next_cnt = cnt_A[-1]-cnt_dict_A[a]
right = A[0] * 2
left = 0
while left <= right:
X = (left + right) // 2
# 左手の相手がaで、満足度がX以上となる組合せの数
cnt = 0
for a in A:
# cnt += search(A, X - a)
if X - a <= A[0]:
if X - a >= 0:
cnt += cnt_A[X - a]
else:
cnt += cnt_A[0]
if cnt >= M:
res = X
left = X + 1
else:
right = X - 1
X = res
# Xが決まったので、累積和で組合せの数分の値を求める
sum_A = [0]
for a in sorted(A):
sum_A.append(sum_A[-1] + a)
sum_cnt = 0
ans = 0
for a in A:
cnt = search(A, X - a)
sum_cnt += cnt
if cnt > 0:
ans += cnt * a + sum_A[-1] - sum_A[-cnt-1]
if sum_cnt > M:
ans -= X * (sum_cnt - M)
return ans
def search(A, X):
'''
AのリストからX以上となる数値がいくつか探す
Aはソート済み(降順)
二分探索で実装O(logN)
leftとrightはチェック未
middleはループ終了後チェック済み
'''
left = 0
right = len(A) - 1
res = 0
while left <= right:
middle = (left + right) // 2
if A[middle] >= X:
res = middle + 1
left = middle + 1
else:
right = middle - 1
return res
def main():
N, M = map(int, input().split())
A = list(map(int, input().split()))
print(run(N, M, A))
if __name__ == '__main__':
main()
| import sys
import bisect
import itertools
def solve():
readline = sys.stdin.buffer.readline
mod = 10 ** 9 + 7
n, m = list(map(int, readline().split()))
a = list(map(int, readline().split()))
a.sort()
cor_v = -1
inc_v = a[-1] * 2 + 1
while - cor_v + inc_v > 1:
bin_v = (cor_v + inc_v) // 2
cost = 0
#条件を満たすcostを全検索
p = n
for v in a:
p = bisect.bisect_left(a, bin_v - v, 0, p)
cost += n - p
if cost > m:
break
#costが制約を満たすか
if cost >= m:
cor_v = bin_v
else:
inc_v = bin_v
acm = [0] + list(itertools.accumulate(a))
c = 0
t = 0
for v in a:
p = bisect.bisect_left(a, cor_v - v)
c += n - p
t += acm[-1] - acm[p] + v * (n - p)
print(t - (c - m) * cor_v)
if __name__ == '__main__':
solve()
| 1 | 108,149,517,937,380 | null | 252 | 252 |
k=int(input())
from collections import deque
q=deque([])
i=0
while True:
if i<=8:
q.append(i+1)
i+=1
if i==k:break
continue
x=q.popleft()
if x%10!=0:
q.append(x*10+x%10-1)
i+=1
if i==k:break
q.append(x*10+x%10)
i+=1
if i==k:break
if x%10!=9:
q.append(x*10+x%10+1)
i+=1
if i==k:break
print(q.pop()) | from sys import stdin
from collections import deque
def main():
#入力
readline=stdin.readline
k=int(readline())
lunlun_number=[]
d=deque(map(str,range(1,10)))
cnt=0
while cnt<k:
now=d.popleft()
lunlun_number.append(now)
cnt+=1
if now[-1]=="0":
nex=("0","1")
elif now[-1]=="9":
nex=("8","9")
else:
last=int(now[-1])
nex=(str(last-1),str(last),str(last+1))
for x in nex:
d.append(now+x)
print(lunlun_number[k-1])
if __name__=="__main__":
main() | 1 | 40,116,592,353,502 | null | 181 | 181 |
s = input()
L = s.split("hi")
ans = 1
for x in L:
if x != "":
ans = 0
print(["No","Yes"][ans]) | S = input()
if len(S) % 2 != 0:
print('No')
exit()
tmp = [S[i:i+2] for i in range(0, len(S), 2)]
for s in tmp:
if s != 'hi':
print('No')
exit()
print('Yes')
| 1 | 53,207,410,169,620 | null | 199 | 199 |
h1,m1,h2,m2,k=map(int,raw_input().split())
print max(h2*60+m2-h1*60-m1-k,0) | dict = {}
def insert(word):
global dict
dict[word] = 0
def find(word):
global dict
if word in dict:
print('yes')
else:
print('no')
def main():
N = int(input())
order = [list(input().split()) for _ in range(N)]
for i in range(N):
if order[i][0] == 'insert':
insert(order[i][1])
elif order[i][0] == 'find':
find(order[i][1])
main()
| 0 | null | 9,051,197,529,832 | 139 | 23 |
class UnionFind():
#https://note.nkmk.me/python-union-find/
#note.nkmk.me 2019-08-18
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)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
#初期入力、集合とユニオンファインド
import sys
input = sys.stdin.readline
N,M,K = (int(x) for x in input().split())
#接続(友好関係、ブロック関係)
uf =UnionFind(N+1)
conn_fri ={i:set() for i in range(1,N+1)}
conn_blo ={i:set() for i in range(1,N+1)}
for i in range(M):
a,b = (int(x) for x in input().split())
uf.union(a,b)
conn_fri[a].add(b)
conn_fri[b].add(a)
for i in range(K):
c,d = (int(x) for x in input().split())
conn_blo[c].add(d)
conn_blo[d].add(c)
#友達候補の数=同じグループにいる、友達関係でない、ブロック関係でない
ans ={i:0 for i in range(1,N+1)}
for i in range(1,N+1):
root =uf.find(i)
all =uf.size(root)
same_groop_block =0
for j in conn_blo[i]:
if uf.same(i,j): #同じグループにいるけどブロック関係
same_groop_block +=1
ans[i] =all -len(conn_fri[i]) -same_groop_block -1 #-1 自分を引く
#出力
print(*ans.values())
#print(all)
| L = int(input())
print("{}".format((L / 3)**3)) | 0 | null | 54,213,681,666,738 | 209 | 191 |
def main():
h, w, m = map(int, input().split())
hp = [0]*h
wp = [0]*w
hw = set()
for _ in range(m):
h1, w1 = map(int, input().split())
hp[h1-1] += 1
wp[w1-1] += 1
hw.add((h1, w1))
h_max = max(hp)
w_max = max(wp)
hh = [i+1 for i, v in enumerate(hp) if v == h_max]
ww = [i+1 for i, v in enumerate(wp) if v == w_max]
ans = h_max + w_max
for hb in hh:
for wb in ww:
if (hb, wb) not in hw:
print(ans)
exit()
print(ans-1)
if __name__ == '__main__':
main() | from collections import defaultdict
H, W, M = map(int, input().split())
row_bom_cnt = defaultdict(int)
col_bom_cnt = defaultdict(int)
row_max = 0
col_max = 0
boms = [list(map(int, input().split())) for _ in range(M)]
for rm, cm in boms:
row_bom_cnt[rm] += 1
col_bom_cnt[cm] += 1
row_max = max(row_max, row_bom_cnt[rm])
col_max = max(col_max, col_bom_cnt[cm])
target_row = set()
for r, val in row_bom_cnt.items():
if val == row_max:
target_row.add(r)
target_col = set()
for c, val in col_bom_cnt.items():
if val == col_max:
target_col.add(c)
cnt = 0
for rm, cm in boms:
if rm in target_row and cm in target_col:
cnt += 1
if len(target_row) * len(target_col) == cnt:
print(row_max + col_max - 1)
else:
print(row_max + col_max)
| 1 | 4,714,914,322,372 | null | 89 | 89 |
N,K = list(map(int,input().split()))
P = list(map(int,input().split()))
def bubblesort(l):
for index in range(len(l)-1, 0, -1):
for low in range(index):
if l[low] > l[low+1]:
tmp = l[low+1]
l[low+1] = l[low]
l[low] = tmp
return l
bubblesort(P)
sum = 0
for i in range(K):
sum = sum + P[i]
print(sum) | import sys
def Ii():return int(sys.stdin.readline())
def Mi():return map(int,sys.stdin.buffer.readline().split())
def Li():return list(map(int,sys.stdin.buffer.readline().split()))
n,k = Mi();
p = Li();
p.sort();
print(sum(p[:k]))
| 1 | 11,639,049,436,478 | null | 120 | 120 |
x,y=map(int,input().split())
ans=0
if x<=3:
ans+=(4-x)*100000
if y<=3:
ans+=(4-y)*100000
if ans==600000:
ans=1000000
print(ans) | def insertionSort(A,g):
global cnt
for i in range(g,len(A)):
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
def shellSort(A):
global cnt
cnt = 0
h = 1
g = []
while h <= len(A):
g.append(h)
h = 3*h+1
g.reverse()
m = len(g)
print(m)
print(' '.join(map(str,g)))
for i in range(m):
insertionSort(A,g[i])
n = int(input())
A = [int(input()) for i in range(n)]
shellSort(A)
print(cnt)
for i in A:
print(i)
| 0 | null | 70,346,990,391,188 | 275 | 17 |
#coding:utf-8
#????????¢?????????
def draw_square(h, w):
for i in range(h):
a = ""
for j in range(w):
a += "#"
print a
while 1:
HW = raw_input().split()
H = int(HW[0])
W = int(HW[1])
if H == 0 and W == 0:
break
draw_square(H, W)
print "" | #ABC158-A
s=input()
if s!='AAA' and s!='BBB':
print('Yes')
else:
print('No')
| 0 | null | 27,616,806,497,842 | 49 | 201 |
n = int(input())
print(int((n + 1)/2)) | import math
n = int(input())
m = n//2
if n % 2 == 0:
print(m)
else:
print(m+1)
| 1 | 59,271,196,690,564 | null | 206 | 206 |
K=int(input())
S=input()
l=[]
if len(S)<=K:
print(S)
else:
for i in range(K):
l.append(S[i])
print("".join(l)+'...') | k = int (input())
s = input()
line = []
if (len(s) > k):
for i in range(k):
line.append(s[i])
print (''.join(line) + "...")
else:
print(s) | 1 | 19,559,537,607,610 | null | 143 | 143 |
N = int(input())
A = list(map(int, input().split()))
M = 0
S = 0
for a in A:
if M < a:
M = a
if a < M:
S += M - a
print(S) | n=int(input())
a=list(map(int,input().split()))
b=a[0]
ans=0
for n in range(n):
if a[n]>b:
b=a[n]
else:
ans+=b-a[n]
print(ans) | 1 | 4,634,522,184,732 | null | 88 | 88 |
import sys
input=sys.stdin.readline
import numpy as np
from numpy.fft import rfft,irfft
n,m=[int(j) for j in input().split()]
l=np.array([int(j) for j in input().split()])
a=np.bincount(l)
fft_len=1<<18
fft = np.fft.rfft
ifft = np.fft.irfft
Ff = fft(a,fft_len)
x=np.rint(ifft(Ff * Ff,fft_len)).astype(np.int64)
p=x.cumsum()
i=np.searchsorted(p,n*n-m)
q=n*n-m-p[i-1]
ans=(x[:i]*np.arange(i,dtype=np.int64)).sum()+i*q
print(int(l.sum()*2*n-ans))
| from itertools import accumulate
n, m, *a = map(int, open(0).read().split())
a = [-x for x in a]
a.sort()
acc = list(accumulate(a))
l, r = 0, 2 * 10 ** 5 + 1
while r - l > 1:
mid = (l + r) // 2
border = n - 1
cnt = 0
for x in a:
while x + a[border] > -mid:
border -= 1
if border < 0:
break
if border < 0:
break
cnt += border + 1
if cnt >= m:
break
if cnt >= m:
l = mid
else:
r = mid
ans = tot = 0
border = n - 1
for x in a:
while x + a[border] > -l:
border -= 1
if border < 0:
break
if border < 0:
break
ans += acc[border] + x * (border + 1)
tot += border + 1
ans += l * (tot - m)
print(-ans) | 1 | 108,381,019,238,688 | null | 252 | 252 |
while True:
n=input()
if n=='-':
break
else:
m=int(input())
for i in range(m):
h=int(input())
n=n[h:len(n)]+n[:h]
print(n)
| while True:
temp = input()
if temp == '-':
break
else:
cards = temp
for i in range(int(input())):
h = int(input())
cards = cards[h:] + cards[:h]
print(cards) | 1 | 1,906,473,807,432 | null | 66 | 66 |
k = int(input())
a,b = map(int,input().split())
ans = 0
for i in range(a//k,b//k+1):
if a <= k * i <= b:
ans = 1
if ans == 1:
print('OK')
else:
print('NG') | K = int(input())
A, B = map(int,input().split())
N = B//K
if K*N <A:
print("NG")
else:
print("OK") | 1 | 26,579,172,597,990 | null | 158 | 158 |
import math
import sys
sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7
def input():
return sys.stdin.readline().strip()
def main():
X = int(input())
lcm = X * 360 // math.gcd(X, 360)
ans = lcm // X
print(ans)
if __name__ == "__main__":
main()
| s = input()
count = 1; memo = 0; x = 0
for i in range(1, len(s)):
if s[i-1] == "<" and s[i] == ">":
x += count*(count-1)//2
memo = count
count = 1
elif s[i-1] == ">" and s[i] == "<":
x += count*(count-1)//2+max(count, memo)
memo = 0
count = 1
else:
count += 1
else:
if s[-1] == "<":
x += count*(count+1)//2
else:
x += count*(count-1)//2+max(count, memo)
print(x) | 0 | null | 84,562,058,734,692 | 125 | 285 |
H, W = map(int, raw_input().split())
while H | W != 0:
for i in range(H):
if i == 0 or i == H - 1:
print '#' * W
else:
print '#' + '.' * (W - 2) + '#'
print ''
H, W = map(int, raw_input().split()) | N = int(input())
S = str(N)
m = len(S)
K = int(input())
#dp[i][j][k]: 上からi桁目までに0以外がj個あって、Nと一致しているならばk=0
dp = [[[0] * 2 for _ in range(4)] for _ in range(m+1)]
dp[0][0][0] = 1
for i in range(m): #i=0は架空の桁に相当。
for j in range(4):
for k in range(2):
#dp[i][j][k]という状態が次の桁でどこに遷移するかを考える。遷移先のni,nj,nkを決定する。
nd = int(S[i]) #Nのi桁目。1桁目はS[0]。
for d in range(10): #dというのが今の桁(i+1)の値
ni = i+1 #今の桁
nj = j
nk = k
if d != 0: #もし今の桁が0でなければjは一つ増える。
nj += 1
if nj > K: #もしnjが許容値のKを超えたら無視。
continue
if k == 0: #ここまで完全一致の時
if d > nd: #今の桁がNのi桁目より大きいつまりNを超えているので無視。
continue
elif d < nd: #今の桁がNのi桁目より小さいなら完全一致ではないのでnk=1と変更。
nk = 1
dp[ni][nj][nk] += dp[i][j][k]
ans = dp[m][K][0] + dp[m][K][1]
print(ans) | 0 | null | 38,599,478,094,122 | 50 | 224 |
from scipy.sparse.csgraph import floyd_warshall
import sys
input = sys.stdin.readline
def solve():
inf = float("Inf")
n,m,l = (int(i) for i in input().split())
path = [[-1*inf]*n for _ in range(n)]
for i in range(m):
a,b,c = (int(i) for i in input().split())
path[a-1][b-1] = c
path[b-1][a-1] = c
d = floyd_warshall(path)
q = int(input())
minipath = [[-1*inf]*n for _ in range(n)]
for i in range(n):
for j in range(n):
if d[i][j] <= l:
minipath[i][j] = 1
d2 = floyd_warshall(minipath)
for i in range(q):
s,t = (int(i) for i in input().split())
s,t = s-1,t-1
cost = d2[s][t]
if cost == inf:
print(-1)
else:
print(int(cost)-1)
solve() | n,m,l=map(int,input().split())
abc=[list(map(int,input().split())) for _ in [0]*m]
q=int(input())
st=[list(map(int,input().split())) for _ in [0]*q]
inf=10**12
dist=[[inf]*n for _ in [0]*n]
for i in range(n):
dist[i][i]=0
for a,b,c in abc:
dist[a-1][b-1]=c
dist[b-1][a-1]=c
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j])
inf=10**3
dist2=[[inf]*n for _ in [0]*n]
for i in range(n):
for j in range(n):
if dist[i][j]<=l:
dist2[i][j]=1
for k in range(n):
for i in range(n):
for j in range(n):
dist2[i][j]=min(dist2[i][j],dist2[i][k]+dist2[k][j])
for i in range(n):
for j in range(n):
if dist2[i][j]==inf:
dist2[i][j]=-1
else:
dist2[i][j]-=1
for s,t in st:
print(dist2[s-1][t-1]) | 1 | 174,041,601,497,332 | null | 295 | 295 |
input_line = set([])
input_line.add(int(input()))
input_line.add(int(input()))
for i in range(1,4):
if i not in input_line:
print(i) | l = [1,2,3]
l.remove(int(input()))
l.remove(int(input()))
print(l[0])
| 1 | 110,473,394,255,720 | null | 254 | 254 |
n1 = input()
A = map(int, raw_input().split())
n2 = input()
q = map(int, raw_input().split())
list = set()
def solve(i,m):
if m == 0:
return True
if i >= n1 or m > sum(A):
return False
res = solve(i+1,m) or solve(i+1,m-A[i])
return res
for m in q:
if solve(0,m):
print "yes"
else:
print "no" | n = int(input())
A = list(map(int,input().split()))
m = int(input())
q = list(map(int,input().split()))
S = set()
for i in range(1<<n):
s = 0
for j in range(n):
if (i>>j)&1:
s += A[j]
S.add(s)
for j in q:
if j in S:
print("yes")
else:
print("no")
| 1 | 99,766,069,380 | null | 25 | 25 |
N, K = map(int, input().split())
if N % K == 0:
print(0)
elif N % K > abs((N%K)-K):
print(abs((N%K)-K))
else:
print(N%K) | N,K=map(int,input().split())
x=N%K
y=abs(x-K)
print(min(x,y)) | 1 | 39,534,721,422,154 | null | 180 | 180 |
N, R = list(map(int, input().split()))
if N >= 10:
print(R)
else:
ans = 100 * (10 - N) + R
print(ans) | S = input()
INC = '<'
DEC = '>'
icnt = 0
dcnt = 0
mode = DEC
ans = 0
for c in S:
if mode == DEC:
if c == DEC:
dcnt += 1
elif c == INC:
if icnt <= dcnt:
ans += (dcnt + 1) * dcnt // 2
else:
ans += icnt + dcnt * (dcnt - 1) // 2
icnt = 1
mode = INC
elif mode == INC:
if c == INC:
icnt += 1
elif c == DEC:
ans += icnt * (icnt - 1) // 2
dcnt = 1
mode = DEC
if mode == INC:
ans += (icnt + 1) * icnt // 2
elif mode == DEC:
if icnt <= dcnt:
ans += (dcnt + 1) * dcnt // 2
else:
ans += icnt + dcnt * (dcnt - 1) // 2
print(ans) | 0 | null | 109,892,123,632,678 | 211 | 285 |