code1
stringlengths 16
427k
| code2
stringlengths 16
427k
| similar
int64 0
1
| pair_id
int64 6.82M
181,637B
⌀ | question_pair_id
float64 101M
180,471B
⌀ | code1_group
int64 2
299
| code2_group
int64 2
299
|
---|---|---|---|---|---|---|
def showrooms(building,floor,rooms):
for x in xrange(0,floor):
for y in xrange(0,rooms):
if y==0:
print "",
print building[x][y],
elif y ==rooms-1:
print building[x][y]
else:
print building[x][y],
FLOOR = 3
ROOMS = 10
n = input()
building1 = [[0 for i in range(ROOMS)] for j in range(FLOOR)]
building2 = [[0 for i in range(ROOMS)] for j in range(FLOOR)]
building3 = [[0 for i in range(ROOMS)] for j in range(FLOOR)]
building4 = [[0 for i in range(ROOMS)] for j in range(FLOOR)]
# for x in xrange(0,n):
for x in xrange(0,n):
b,f,r,v = map(int,raw_input().split())
f=f-1
r=r-1
if b==1:
building1[f][r] += v
elif b==2:
building2[f][r] += v
elif b==3:
building3[f][r] += v
elif b==4:
building4[f][r] += v
else:
print "your input is invalid format."
break
showrooms(building1,FLOOR,ROOMS)
print "####################"
showrooms(building2,FLOOR,ROOMS)
print "####################"
showrooms(building3,FLOOR,ROOMS)
print "####################"
showrooms(building4,FLOOR,ROOMS) | n = int(input())
count = 0
room = [int(0) for i in range(4) for j in range(3) for k in range(10)]
while count < n:
x = list(map(lambda k: int(k), input().split(" ")))
room[(x[0]-1)*30+(x[1]-1)*10+(x[2]-1)] += x[3]
count += 1
for i in range(4):
if i != 0:
print("####################")
for j in range(3):
for k in range(10):
print(" %d" % room[30*i+10*j+k], end="")
print("") | 1 | 1,084,928,742,138 | null | 55 | 55 |
A, B, C, D=map(int,input().split())
while C or A >= 0:
C -= B
A -= D
if C <= 0:
print("Yes")
break
if A <= 0:
print("No")
break |
A,B,C,D = map(int, input().split())
n = 0
if C%B ==0:
if A-(C//B-1)*D > 0:
print('Yes')
else:
print('No')
elif C%B != 0:
if A-(C//B)*D > 0:
print('Yes')
else:
print('No')
| 1 | 29,750,345,254,810 | null | 164 | 164 |
a, b, m = map(int, input().split())
lista = list(map(int, input().split()))
listb = list(map(int, input().split()))
ans = min(lista)+min(listb)
for i in range(m):
x, y, c = map(int, input().split())
dprice = lista[x-1]+listb[y-1] - c
if ans > dprice:
ans = dprice
print(ans)
| a,b,m = map(int,input().split())
r = tuple(map(int,input().split()))
d = tuple(map(int,input().split()))
ans = min(r)+min(d)
for i in range(m):
x,y,c = map(int,input().split())
ans = min(ans,r[x-1]+d[y-1]-c)
print(ans) | 1 | 53,930,435,733,188 | null | 200 | 200 |
n=input()
ans=0
if n=="0":
print("Yes")
else:
for i in n:
ans+=int(i)
if ans%9==0:
print("Yes")
else:
print("No") | print('No'if sum(map(int,list(input())))%9 else'Yes') | 1 | 4,416,665,828,012 | null | 87 | 87 |
n,m=map(int,input().split())
h=list(map(int,input().split()))
AB=[list(map(int,input().split())) for _ in range(m)]
from math import gcd
ans=[1 for _ in range(n)]
for ab in AB:
if h[ab[0]-1]>h[ab[1]-1]:
ans[ab[1]-1]=0
elif h[ab[0]-1]<h[ab[1]-1]:
ans[ab[0]-1]=0
else:
ans[ab[0]-1]=0
ans[ab[1]-1]=0
print(sum(ans)) | def main():
import collections
n, m = map(int, input().split())
hs = list(map(int, input().split()))
nmap = [0] * n
cnt = 0
for j in range(m):
v = input().split()
v0 = int(v[0]) - 1
v1 = int(v[1]) - 1
if hs[v0] < hs[v1]:
nmap[v0] += 1
elif hs[v0] == hs[v1]:
nmap[v0] += 1
nmap[v1] += 1
else:
nmap[v1] += 1
for i in nmap:
if i == 0:
cnt += 1
return cnt
if __name__ == '__main__':
print(main())
| 1 | 25,052,285,247,040 | null | 155 | 155 |
X = int(input())
for i in range(1,1000000000):
if ( X * i ) % 360 == 0:
print(i)
quit()
| from collections import deque
import sys
input = sys.stdin.readline
n = int(input())
l = deque()
for _ in range(n):
op = input().strip().split()
if op[0] == "insert":
l.appendleft(op[1])
elif op[0] == "delete":
if op[1] in l:
l.remove(op[1])
elif op[0] == "deleteFirst":
l.popleft()
elif op[0] == "deleteLast":
l.pop()
print(" ".join(l))
| 0 | null | 6,642,468,226,500 | 125 | 20 |
N = int(input())
K = []
for i in range(N):
X,L = map(int,input().split())
K.append([X-L,X+L])
T = sorted(K,key=lambda x:x[1])
a = T[0][1]
c = 1
for i in range(1,N):
if T[i][0] >= a:
c += 1
a = T[i][1]
print(c) | N = int(input())
rob = []
for i in range(N):
x, l = map(int,input().split())
t = x + l
rob.append((t,x,l))
rob.sort()
Max = -float("inf")
ans = 0
for i in range(len(rob)):
t = rob[i][0]
x = rob[i][1]
l = rob[i][2]
if x-l < Max:
continue
else:
ans += 1
Max = t
print(ans) | 1 | 90,000,849,783,556 | null | 237 | 237 |
date1 = input().split(" ")
date2 = input().split(" ")
if date1[0] != date2[0]:
print("1")
else:
print("0") | _, D1 = map(int, input().split())
_, D2 = map(int, input().split())
print(0 if D1 < D2 else 1) | 1 | 124,113,705,701,724 | null | 264 | 264 |
from collections import defaultdict
from math import gcd
import sys
input = sys.stdin.readline
N=int(input())
mod=10**9+7
dic=defaultdict(lambda: [0,0])
c=0
d=0
e=0
for i in [0]*N:
A,B = map(int,input().split())
if A==0 and B==0:
e+=1
elif A==0:
c+=1
elif B==0:
d+=1
else:
g=gcd(A,B)
A//=g
B//=g
if A*B>0:
dic[(abs(A),abs(B))][0]+=1
else:
dic[(abs(B),abs(A))][1]+=1
ans=1
for k in dic:
ans=ans*(pow(2,dic[k][0],mod)+pow(2,dic[k][1],mod) -1)
ans=ans*(pow(2,c,mod)+pow(2,d,mod)-1)
print((ans-1+e)%mod) | s = input()
n = len(s)
mod = 2019
t = [0]*n
dp = [0]*2020
t[0] = int(s[-1])
dp[t[0]] += 1
for i in range(n-1):
t[i+1] = t[i] + int(s[-2-i])*pow(10, i+1, mod)
t[i+1] %= mod
dp[t[i+1]] += 1
ans = 0
for D in dp[1:]:
ans += D*(D-1)//2
print(ans+(dp[0]+1)*(dp[0])//2)
| 0 | null | 25,809,025,026,500 | 146 | 166 |
if __name__ == '__main__':
n = int(input())
S = [0,0,0,0]
for _ in range(n):
cmd = input()
if cmd == "AC":
S[0] += 1
elif cmd == "TLE":
S[2] += 1
elif cmd == "WA":
S[1] += 1
else:
S[3] += 1
for i in range(4):
if i == 0:
print("AC x " + str(S[0]))
elif i == 1:
print("WA x " + str(S[1]))
elif i == 2:
print("TLE x " + str(S[2]))
else:
print("RE x " + str(S[3]))
| N=int(input())
item={"AC":0,"WA":0,"TLE":0,"RE":0}
for n in range(N):
S=input()
if S=="AC":
item["AC"]+=1
elif S=="WA":
item["WA"]+=1
elif S=="TLE":
item["TLE"]+=1
else:
item["RE"]+=1
print("AC x",end=" ")
print(item["AC"])
print("WA x",end=" ")
print(item["WA"])
print("TLE x",end=" ")
print(item["TLE"])
print("RE x",end=" ")
print(item["RE"])
| 1 | 8,669,027,714,518 | null | 109 | 109 |
import math
from numpy.compat.py3k import asstr
a, b = map(int, input().split())
ans = int(a * b / math.gcd(a, b))
print(str(ans))
| k=int(input())
s=input()
if len(s)<=k:
print(s)
else:
for i in range(k):
print(s[i],end="")
print("...",end="") | 0 | null | 66,271,980,603,730 | 256 | 143 |
N=int(input())
n=len(str(N))
res=0
for a in range(1,N+1):
a0=str(a)[0]
a1=str(a)[-1]
if a0=='0' or a1=='0':
a_res=res
continue
for i in range(1,n+1):
if i==1:
if a0==a1:
res+=1
elif i==2:
if 10*int(a1)+int(a0)<=N:
res+=1
elif i==n:
n0=str(N)[0]
n1=str(N)[-1]
if n0<a1:
res+=0
elif n0>a1:
res+=10**(i-2)
else:
res+=(N-int(a1)*10**(i-1))//10+1
if n1<a0:
res-=1
else:
res+=10**(i-2)
print(res) | N = int(input())
M = [[0]*10 for _ in range(10)]
for n in range(1,N+1):
head = int(str(n)[0])
tail = int(str(n)[-1])
M[head][tail] += 1
ans = 0
for i in range(10):
for j in range(i+1,10):
ans += M[i][j]*M[j][i]*2
ans += M[i][i]**2
print(ans)
| 1 | 86,387,454,212,346 | null | 234 | 234 |
A, B, K = map(int, input().split())
d = min(A, K)
#print('d:', d)
A -= d
K -= d
d = min(B, K)
#print('d:', d)
B -= d
K -= d
print(A, B) | N,K = map(int,input().split())
min = N%K
if min>abs(min-K):
min = abs(min-K)
print (min) | 0 | null | 71,682,172,865,920 | 249 | 180 |
# S の長さが K 以下であれば、S をそのまま出力してください。
# S の長さが K を上回っているならば、
# 先頭 K 文字だけを切り出し、末尾に ... を付加して出力してください。
# K は 1 以上 100 以下の整数
# S は英小文字からなる文字列
# S の長さは 1 以上 100 以下
K = int(input())
S = str(input())
if K >= len(S):
print(S)
else:
print((S[0:K] + '...'))
| from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
import math
rl = lambda: stdin.readline()
rll = lambda: stdin.readline().split()
rli = lambda: map(int, stdin.readline().split())
rlf = lambda: map(float, stdin.readline().split())
INF, NINF = float('inf'), float('-inf')
def main():
n = int(rl())
ans = 0
for i, a in enumerate(rli(), 1):
if i % 2 == 1 and a % 2 == 1:
ans += 1
print(ans)
stdout.close()
if __name__ == "__main__":
main() | 0 | null | 13,733,161,157,352 | 143 | 105 |
import math
def main():
r = int(input())
print(math.pi *r *2)
if __name__ == "__main__":
main() | def colorchange(i,l,r,col):
k=i-1
while(k>=0):
if not '#' in G[k]:
for j in range(l+1,r+1):
A[k][j]=col
else:
break
k-=1
k=i+1
while(k<H):
if not '#' in G[k]:
for j in range(l+1,r+1):
A[k][j]=col
else:
break
k+=1
H,W,K=map(int,input().split())
G=[list(input()) for i in range(H)]
s=set()
A=[[-1]*W for i in range(H)]
now=1
for i in range(H):
if not '#' in G[i]:
continue
last=-1
first=True
for j in range(W):
if G[i][j]=='#' and j==0:
first=False
A[i][j]=now
if j==W-1:
colorchange(i,last,j,now)
now+=1
elif G[i][j+1]=='#':
if first:
first=False
else:
colorchange(i,last,j,now)
last=j
now+=1
for i in range(H):
print(*A[i]) | 0 | null | 87,672,107,398,652 | 167 | 277 |
N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
ans = A[0]
N -= 2
for i in range(1, N):
if N >= 2:
ans += A[i]*2
N -= 2
elif N == 1:
ans += A[i]
N -= 1
else:
break
print(ans)
| #!/usr/bin/env python3
def next_line():
return input()
def next_int():
return int(input())
def next_int_array_one_line():
return list(map(int, input().split()))
def next_int_array_multi_lines(size):
return [int(input()) for _ in range(size)]
def next_str_array(size):
return [input() for _ in range(size)]
def main():
n = next_int()
ar = list(reversed(sorted(next_int_array_one_line())))
# print(ar)
res = ar[0]
n -= 2
use = 1
while n > 0:
if n >= 2:
res += ar[use] * 2
n -= 2
use += 1
else:
res += ar[use]
n -= 1
print(res)
if __name__ == '__main__':
main()
| 1 | 9,072,757,964,436 | null | 111 | 111 |
x = int(input())
n=100
tes = [0]
for i in range(-250,250):
for j in range(-250,250):
if pow(i,5) - pow(j,5) == x:
print(str(i)+" "+str(j))
exit() | x = int(input())
for i in range(1,121):
for j in range(-121,121):
if x == i**5 - j**5:
print(i,j)
exit()
| 1 | 25,550,500,793,572 | null | 156 | 156 |
NM=list(map(int,input().strip().split()))
N=NM[0]
M=NM[1]
if N==M:
print("Yes")
else:
print("No")
| import sys
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7
N, M = rl()
if N == M:
print('Yes')
else:
print('No') | 1 | 83,358,117,043,676 | null | 231 | 231 |
N,P=map(int,input().split())
S=input()
s=[0 for i in range(N+1)]
a=[0 for i in range(N+1)]
a[0]=(10**0)%P
for i in range(N):
A=a[i]
a[i+1]=(A*(10%P))%P
s[i+1]=(s[i]+A*int(S[N-i-1]))%P
d=[0 for i in range(P)]
for i in range(len(s)):
d[s[i]]+=1
ans=0
if P!=2 and P!=5:
for D in d:
ans+=D*(D-1)//2
print(ans)
elif P==2:
for i in range(N):
if int(S[N-1-i])%2==0:
ans+=(N-i)
print(ans)
else:
for i in range(N):
if int(S[N-1-i])%5==0:
ans+=(N-i)
print(ans) | n, p = map(int, input().split())
s = input()
if 10%p==0:
ans = 0
for r in range(n):
if int(s[r])%p == 0:
ans += r+1
print(ans)
exit()
d = [0]*(n+1)
ten = 1
for i in range(n-1, -1, -1):
a = int(s[i])*ten%p
d[i] = (d[i+1]+a)%p
ten *= 10
ten %= p
cnt = [0]*p
ans = 0
for i in range(n, -1, -1):
ans += cnt[d[i]]
cnt[d[i]] += 1
print(ans) | 1 | 58,178,468,486,460 | null | 205 | 205 |
a,b,m = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
ans = []
ans.append(min(A)+min(B))
for i in range(m):
M = list(map(int,input().split()))
tmp = A[M[0]-1] + B[M[1]-1] -M[2]
ans.append(tmp)
print(min(ans))
| #template
def inputlist(): return [int(j) for j in input().split()]
def listinput(): return input().split()
#template
N,R = inputlist()
if N >= 10:
print(R)
else:
print(R + 100*(10-N)) | 0 | null | 58,854,526,171,430 | 200 | 211 |
import math
def main():
A, B = map(int,input().split())
print(int(A*B/math.gcd(A,B)))
if __name__ =="__main__":
main() | from math import gcd
def snack(a, b):
icm = (a*b // gcd(a, b))
return icm
def main():
a, b = map(int, input().split())
print(snack(a, b))
if __name__ == '__main__':
main() | 1 | 113,224,091,635,130 | null | 256 | 256 |
# -*- coding: utf-8 -*-
n = int(input())
Univ = [[[0 for i in range(10)]for j in range(3)]for k in range(4)]
for i in range(n):
b,f,r,v =[int(i)for i in input().split(' ')]
Univ[b-1][f-1][r-1] += v
for b in range(4):
for f in range(3):
for r in range(10):
print('',Univ[b][f][r],end="")
print()
if b<3:
print("#"*20) | from copy import deepcopy
from collections import Counter, defaultdict, deque
def I(): return int(input())
def LI(): return list(map(int,input().split()))
def MI(): return map(int,input().split())
def LLI(n): return [list(map(int, input().split())) for _ in range(n)]
def maze_solve(S_1,S_2,maze_list):
d = deque()
dist[S_1][S_2] = 0
d.append([S_1,S_2])
dx = [0,0,1,-1]
dy = [1,-1,0,0]
while d:
v = d.popleft()
x = v[0]
y = v[1]
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or nx >= h or ny < 0 or ny >= w:
continue
if dist[nx][ny] == -1:
dist[nx][ny] = dist[x][y] + 1
d.append([nx,ny])
return max(list(map(lambda x: max(x), dist)))
h,w = MI()
ans = 0
maze = [list(input()) for _ in range(h)]
dist = [[-1]*w for _ in range(h)]
start_list = []
for i in range(h):
for j in range(w):
if maze[i][j] == "#":
dist[i][j] = 0
else:
start_list.append([i,j])
dist_copy = deepcopy(dist)
for k in start_list:
dist = deepcopy(dist_copy)
ans = max(ans,maze_solve(k[0],k[1],maze))
print(ans) | 0 | null | 48,081,302,050,580 | 55 | 241 |
import sys, os, math, bisect, itertools, collections, heapq, queue
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict, deque
import copy
sys.setrecursionlimit(10000000)
ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]
iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]
lcm = lambda x, y: (x * y) // math.gcd(x, y)
MOD = 10 ** 9 + 7
MAX = float('inf')
def req_count(P, K, W):
cnt = 0
for k in range(K):
p = 0
while p + W[cnt] <= P:
p += W[cnt]
cnt += 1
if cnt == len(W):
return cnt
else:
return cnt
def main():
if os.getenv("LOCAL"):
sys.stdin = open("input.txt", "r")
N, K = il()
W = [ii() for _ in range(N)]
left, right = 0, sum(W)
while right - left != 1:
middle = (left + right) // 2
n = req_count(middle, K, W)
if n >= N:
right = middle
else:
left = middle
print(right)
if __name__ == '__main__':
main()
| print('a' if input().islower()==True else 'A') | 0 | null | 5,664,293,083,302 | 24 | 119 |
n,m = map(int,input().split())
mat=[]
v=[]
for i in range(n):
a=list(map(int,input().split()))
mat.append(a)
for j in range(m):
v.append(int(input()))
for i in range(n):
w = 0
for j in range(m):
w += mat[i][j]*v[j]
print(w)
| def main():
n, k = map(int, input().split())
a_list = list(map(int, input().split()))
visited_list = [-1] * n # 何ワープ目で訪れたか
visited_list[0] = 0
city, loop, non_loop = 1, 0, 0 # 今いる街、何ワープでループするか、最初にループするまでのワープ数
for i in range(1, n + 1):
city = a_list[city - 1]
if visited_list[city - 1] != -1:
loop = i - visited_list[city - 1]
non_loop = visited_list[city - 1] - 1
break
else:
visited_list[city - 1] = i
city = 1
if k <= non_loop:
for _ in range(k):
city = a_list[city - 1]
else:
for _ in range(non_loop + (k - non_loop) % loop + loop):
city = a_list[city - 1]
print(city)
if __name__ == "__main__":
main()
| 0 | null | 11,948,902,223,120 | 56 | 150 |
import sys
import bisect
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())
class SegTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.ide_ele = ide_ele
self.segfunc = segfunc
self.num = 2**(n - 1).bit_length()
self.seg = [self.ide_ele] * 2 * self.num
for i in range(n):
self.seg[i + self.num - 1] = init_val[i]
for i in range(self.num - 2, -1, -1):
self.seg[i] = self.segfunc(self.seg[2 * i + 1], self.seg[2 * i + 2])
def update(self, k, x):
k += self.num - 1
self.seg[k] += x
while k:
k = (k - 1) // 2
self.seg[k] = self.segfunc(self.seg[k * 2 + 1], self.seg[k * 2 + 2])
def query(self, p, q):
if q <= p:
return self.ide_ele
p += self.num - 1
q += self.num - 2
res = self.ide_ele
while q - p > 1:
if p & 1 == 0:
res = self.segfunc(res, self.seg[p])
if q & 1 == 1:
res = self.segfunc(res, self.seg[q])
q -= 1
p = p // 2
q = (q - 1) // 2
if p == q:
res = self.segfunc(res, self.seg[p])
else:
res = self.segfunc(self.segfunc(res, self.seg[p]), self.seg[q])
return res
def main():
N, D, A = in_nn()
XH = sorted(in_nl2(N))
X = [0] * N
H = [0] * N
for i in range(N):
x, h = XH[i]
X[i] = x
H[i] = h
seg = SegTree([0] * N, segfunc=lambda a, b: a + b, ide_ele=0)
ans = 0
for i in range(N):
x, h = X[i], H[i]
j = bisect.bisect_right(X, x + 2 * D)
cnt_bomb = seg.query(0, i + 1)
h -= A * cnt_bomb
if h <= 0:
continue
cnt = -(-h // A)
ans += cnt
seg.update(i, cnt)
if j < N:
seg.update(j, -cnt)
# print(i, j)
# print(seg.seg)
print(ans)
if __name__ == '__main__':
main()
| import bisect
import sys
def main():
input = sys.stdin.readline
n, d, a = map(int, input().split())
fox = [None]*n
for i in range(n):
x, h = map(int, input().split())
fox[i] = (x, h)
fox.sort()
x = [int(fox[i][0]) for i in range(n)]
h = [int(fox[i][1]) for i in range(n)]
ans = 0
bit = [0]*n
for i in range(n):
if i != 0:
bit[i] += bit[i-1]
sub = max([(h[i]-bit[i]-1)//a+1, 0])
ans += sub
bit[i] += sub*a
index = bisect.bisect_right(x, x[i]+2*d)
if index != n:
bit[index] -= sub*a
print(ans)
if __name__ == "__main__":
main() | 1 | 82,409,741,215,958 | null | 230 | 230 |
A,V = [int(i) for i in input().split()]
B,W = [int(i) for i in input().split()]
T = int(input())
if A < B:
if A+V*T >= B+W*T:
print('YES')
else:
print('NO')
else:
if A-V*T <= B-W*T:
print('YES')
else:
print('NO')
| # 貪欲法 + 山登り法 + スワップ操作
import time
s__ = time.time()
limit = 1.9
#limit = 10
from numba import njit
import numpy as np
d = int(input())
cs = list(map(int, input().split()))
cs = np.array(cs, dtype=np.int64)
sm = [list(map(int, input().split())) for _ in range(d)]
sm = np.array(sm, dtype=np.int64)
@njit('i8(i8[:], i8)', cache=True)
def total_satisfaction(ts, d):
ls = np.zeros(26, dtype=np.int64)
s = 0
for i in range(d):
t = ts[i]
t -= 1
s += sm[i][t]
ls[t] = i + 1
dv = cs * ((i+1) - ls)
s -= dv.sum()
return s
@njit('i8[:]()', cache=True)
def greedy():
ts = np.array([0] * d, dtype=np.int64)
for i in range(d):
mx = -1e10
mxt = None
for t in range(1, 26+1):
ts[i] = t
s = total_satisfaction(ts, i + 1)
if s > mx:
mx = s
mxt = t
ts[i] = mxt
return ts
@njit('i8(i8, i8[:])', cache=True)
def loop(mxsc, ts):
it = 50
rds = np.random.randint(0, 4, (it,))
rdd = np.random.randint(1, d, (it,))
rdq = np.random.randint(1, 26, (it,))
rdx = np.random.randint(1, 12, (it,))
for i in range(it):
bk1 = 0
bk2 = 0
if rds[0] == 0:
# trailing
di = rdd[i]
qi = rdq[i]
bk1 = ts[di]
ts[di] = qi
else:
# swap
di = rdd[i]
xi = rdx[i]
if di + xi >= d:
xi = di - xi
else:
xi = di + xi
bk1 = ts[di]
bk2 = ts[xi]
ts[di] = bk2
ts[xi] = bk1
sc = total_satisfaction(ts, d)
if sc > mxsc:
#print(mxsc, '->', sc)
mxsc = sc
else:
# 最大値を更新しなかったら戻す
if rds[0] == 0:
ts[di] = bk1
else:
ts[di] = bk1
ts[xi] = bk2
return mxsc
ts = greedy()
mxsc = total_satisfaction(ts, d)
mxbk = mxsc
s_ = time.time()
mxsc = loop(mxsc, ts)
e_ = time.time()
consume = s_ - s__
elapsed = e_ - s_
#print('consume:', consume)
#print('elapsed:', elapsed)
if consume < limit:
lp = int((limit - consume)/ elapsed)
#print('loop', lp)
for _ in range(lp):
mxsc = loop(mxsc, ts)
for t in ts: print(t)
#print(mxbk, mxsc)
#print(time.time() - s__)
| 0 | null | 12,430,121,232,188 | 131 | 113 |
import math as mt
import sys, string
from collections import Counter, defaultdict
input = sys.stdin.readline
# input functions
I = lambda : int(input())
M = lambda : map(int, input().split())
ARR = lambda: list(map(int, input().split()))
n = I()
print(int(not n)) | import math
s = input().split(" ")
n = list(map(float,s))
d = math.sqrt((n[0]-n[2])**2 + (n[1]-n[3])**2)
print(d) | 0 | null | 1,512,786,066,080 | 76 | 29 |
import copy
H, W, K = map(int, input().split())
tiles = [list(input()) for _ in range(H)]
count = 0
for num in range(2**(H+W)):
copied_tiles = copy.deepcopy(tiles)
for i in range(H+W):
if num>>i&1:
if i < H:
for j in range(W):
copied_tiles[i][j] = 'R'
else:
for j in range(H):
copied_tiles[j][i-H] = 'R'
black_c = 0
for i in range(H):
for j in range(W):
if copied_tiles[i][j] == '#':
black_c += 1
if black_c == K:
count += 1
print(count) | import re
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
import functools
def v(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
cnt = 0
ans = 0
inf = float("inf")
h, w, k = map(int, input().split())
C = []
for _ in range(h): C.append(input())
from itertools import *
ans = 0
for bit in range(1<<(h+w)):
c = 0
for i, j in product(range(w, h+w), range(w)):
if bit>>i & 1 and bit>>j & 1: c += C[i-w][j] == '#'
if c == k: ans += 1
print(ans)
| 1 | 9,011,247,805,560 | null | 110 | 110 |
import sys
readline = sys.stdin.readline
N,X,Y = map(int,readline().split())
G = [[] for i in range(N)]
for i in range(N - 1):
G[i].append(i + 1)
G[i + 1].append(i)
G[X - 1].append(Y - 1)
G[Y - 1].append(X - 1)
ans = [0] * N
from collections import deque
for i in range(N):
q = deque([])
q.append([i, -1, 0])
seen = set()
while q:
v, parent,cost = q.popleft()
if v in seen:
continue
seen.add(v)
ans[cost] += 1
for child in G[v]:
if child == parent:
continue
q.append([child, i, cost + 1])
for i in range(1, N):
print(ans[i] // 2)
| n,x,y=map(int,input().split())
d=[[0 for _ in range(n)]for _ in range(n)]
for i in range(n):
for j in range(n):
d[i][j]=abs(j-i)
for i in range(n):
for j in range(n):
d[i][j]=min(d[i][j],d[i][x-1]+d[y-1][j]+1)
ans=[0]*n
for i in range(n):
for j in range(i+1,n):
ans[d[i][j]]+=1
for i in ans[1:]:
print(i) | 1 | 44,168,277,153,840 | null | 187 | 187 |
mounts =[int(input()) for i in range(10)]
mounts.sort(reverse = True)
for i in range(3):
print(mounts[i]) | from collections import Counter
N, K = map(int, input().split())
A = list(map(int, input().split()))
S = [0] * (N + 1)
for i in range(N):
S[i + 1] = (S[i] + A[i]) % K
# S[i + 1] = S[i] + A[i]
cnt = 0
C = Counter()
for r in range(N + 1):
R = (S[r] - r) % K
cnt += C[R]
C[R] += 1
l = r - (K - 1)
if l >= 0:
L = (S[l] - l) % K
C[L] -= 1
print(cnt)
| 0 | null | 68,498,270,774,710 | 2 | 273 |
#!/usr/bin/env python
contents = []
counter = 0
word = input()
while True:
text = input()
if text == "END_OF_TEXT":
break
textWords = text.split()
contents.append(textWords)
for x in contents:
for y in x:
if y.lower() == word:
counter += 1
print(counter) | T1, T2 = map(int, input().split())
A1, A2 = map(int, input().split())
B1, B2 = map(int, input().split())
SA = T1 * A1 + T2 * A2
SB = T1 * B1 + T2 * B2
if SA == SB or A1 == B1:
print('infinity')
exit()
if SA > SB and A1 < B1:
M = (B1 - A1) * T1
d = SA - SB
cnt = M // d
ans = cnt * 2
if M % d != 0:
ans += 1
print(max(0, ans))
elif SB > SA and B1 < A1:
M = (A1 - B1) * T1
d = SB - SA
cnt = M // d
ans = cnt * 2
if M % d != 0:
ans += 1
print(max(0, ans))
else:
print(0)
| 0 | null | 66,720,450,834,560 | 65 | 269 |
n, k, s = map(int,input().split())
if s == 10**9:
ans = [1 for i in range(n)]
for i in range(k):
ans[i] = 10**9
else:
ans = [10**9 for i in range(n)]
for i in range(k):
ans[i] = s
print(" ".join(map(str,ans)))
| N,K,S = map(int,input().split())
if S != 10**9:
for _ in range(K):
print(S,end = ' ')
for _ in range(N - K):
print(10**9,end = ' ')
else:
for _ in range(K):
print(10**9,end = ' ')
for _ in range(N - K):
print(1,end = ' ')
print()
| 1 | 90,907,367,754,048 | null | 238 | 238 |
n,m = list(map(int, input().split()))
parent = list(range(n))
def root(x):
if parent[x] == x: return x
rt = root(parent[x])
parent[x] = rt
return rt
def unite(x,y):
x = root(x)
y = root(y)
if x == y: return
parent[y] = x
for _ in range(m):
a,b = list(map(lambda x: int(x)-1, input().split()))
unite(a,b)
for i in range(n):
root(i)
cnt = len(set(parent)) - 1
print(cnt) | #!/usr/bin/env pypy3
import collections
import itertools as it
import math
#import numpy as np
# = input()
# = int(input())
a1, a2, a3 = map(int, input().split())
# = list(map(int, input().split()))
# = [int(input()) for i in range(N)]
#
# c = collections.Counter()
print('bust' if a1 + a2 + a3 >= 22 else 'win')
| 0 | null | 60,561,189,518,212 | 70 | 260 |
from itertools import product
H, W, K = map(int, input().split())
C = [list(input()) for _ in range(H)]
p1 = list(product([False, True], repeat=H))
p2 = list(product([False, True], repeat=W))
ans = 0
for i in range(len(p1)):
for j in range(len(p2)):
count = 0
for a in range(H):
for b in range(W):
if C[a][b] == "#" and not p1[i][a] and not p2[j][b]:
count += 1
if count == K:
ans += 1
print(ans) | import copy
def countKuro( t,p1,p2 ):
count=0
for i in range(h):
if p1 & (1<<i) :
for j in range(w):
if p2 & (1<<j) :
if t[i][j]=="#":
count+=1
return count
h,w,k=map(int, input().split())
s=[]
for i in range(h):
s.append( input() )
t=copy.copy(s)
ans=0
for i in range(1<<h):
for j in range(1<<w):
# print(i,j, countKuro(s,i,j))
if k==countKuro(s, i,j):
ans+=1
print(ans)
| 1 | 8,928,012,653,010 | null | 110 | 110 |
import numpy as np
def check_bingo(A):
for i in range(3):
if np.all(A[i] == -1) or np.all(A[:, i] == -1):
return 'Yes'
if np.all(A[list(range(3)), list(range(3))] == -1) \
or np.all(A[list(range(3)), list(range(3))[::-1]] == -1):
return 'Yes'
return 'No'
def main():
A = np.array([list(map(int, input().split())) for _ in range(3)])
n = int(input())
for i in range(n):
b = int(input())
A = np.where(A == b, -1, A)
ans = check_bingo(A)
print(ans)
if __name__ == '__main__':
main()
| def main():
A = [list(map(int,input().split())) for i in range(3)]
N = int(input())
b = [int(input()) for _ in range(N)]
for i in range(N):
for j in range(3):
for h in range(3):
if A[j][h] == b[i]:
A[j][h] = 0
if A[0][0]==0 and A[0][1]==0 and A[0][2]==0:
return 'Yes'
elif A[1][0]==0 and A[1][1]==0 and A[1][2]==0:
return 'Yes'
elif A[2][0]==0 and A[2][1]==0 and A[2][2]==0:
return 'Yes'
elif A[0][0]==0 and A[1][0]==0 and A[2][0]==0:
return 'Yes'
elif A[0][1]==0 and A[1][1]==0 and A[2][1]==0:
return 'Yes'
elif A[0][2]==0 and A[1][2]==0 and A[2][2]==0:
return 'Yes'
elif A[0][0]==0 and A[1][1]==0 and A[2][2]==0:
return 'Yes'
elif A[0][2]==0 and A[1][1]==0 and A[2][0]==0:
return 'Yes'
return ('No')
print(main())
| 1 | 60,146,005,876,180 | null | 207 | 207 |
N = int(input())
X = list(map(int, input().split()))
cur = 1000
stock = 0
state = 0 # 1=increase, 0=decrease
for i in range(N - 1):
if state == 1 and X[i] > X[i + 1]:
cur += X[i] * stock
stock = 0
state = 0
elif state == 0 and X[i] < X[i + 1]:
n = cur // X[i]
cur -= X[i] * n
stock += n
state = 1
print(cur + stock * X[-1])
| n, x, m = list(map(int, input().split()))
a = [x]
start = -1
end = -1
check = [0]*m
path = -1
loop = 0
for i in range(1, n):
ans = (a[i-1]**2) % m
p = check[ans]
if p != 0:
if start == -1:
start = i
path = ans
if p == 1:
end = i
if p >= 3:
break
check[ans] += 1
a.append(ans)
if start == -1 or end == -1:
print(sum(a))
else:
lenght = end-start+1
loop, mod = divmod(n-start, lenght)
ans = sum(a[:start])+sum(a[start:end+1])*loop + sum(a[start:start+mod])
print(ans) | 0 | null | 4,995,256,940,310 | 103 | 75 |
import math
A, B, H, M = map(int,input().split())
h = 30*H + (0.5)*M
m = 6*M
C = abs(h-m)
X = math.sqrt(A**2 + B**2 -(2*A*B*(math.cos(math.radians(C)))))
print(X) | import math
A, B, H, M = map(int, input().split())
wa = 360/12
wb = 360/1
t = H + M/60
theta = math.radians((wa*t)%360 - (wb*t)%360)
print(math.sqrt(A**2 + B**2 -2*A*B*math.cos(theta))) | 1 | 20,291,466,115,538 | null | 144 | 144 |
N = int(input())
XY_list = [[] for _ in range(N)]
for i in range(N):
num = int(input())
for j in range(num):
person, state = map(int, input().split())
XY_list[i].append([person - 1, state])
ans = 0
for i in range(1 << N):
bool = True
for j in range(N):
if (i >> j) & 1 == 1:
for person, state in XY_list[j]:
if (i >> person) & 1 != state:
bool = False
break
if bool:
ans = max(ans, bin(i)[2:].count("1"))
print(ans)
| import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
# あるbit列に対するコストの計算
def count(zerone):
one = 0
cnt = 0
for i in range(N):
flag = True
if zerone[i] == 1:
one += 1
for j in range(len(A[i])):
if A[i][j][1] != zerone[A[i][j][0]-1]:
flag = False
break
if flag:
cnt += 1
if cnt == N:
return one
else:
return 0
# bit列の列挙
def dfs(bits):
if len(bits) == N:
return count(bits)
res = 0
for i in range(2):
bits.append(i)
res = max(res, dfs(bits))
bits.pop()
return res
# main
N = int(input())
A = [[] for _ in range(N)]
for i in range(N):
a = int(input())
for _ in range(a):
A[i].append([int(x) for x in input().split()])
ans = dfs([])
print(ans) | 1 | 121,671,274,263,910 | null | 262 | 262 |
n1, n2 = [int(i) for i in input().split()]
if n1 * 500 >= n2:
print("Yes")
else:
print("No") | #!/usr/bin/env python3
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def main():
K, X = map(int, readline().split())
if 500 * K >= X:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main()
| 1 | 97,903,495,333,250 | null | 244 | 244 |
s=str(input())
t=str(input())
n=len(s)
ans=0
for i in range(n):
if s[i]==t[i]:
ans+=1
print(n-ans) | S = list(input())
T = list(input())
count = 0
for i in range(0, len(S)):
if S[i] != T[i]:
count += 1
print(count) | 1 | 10,508,929,931,460 | null | 116 | 116 |
n = input()
lst = list(map(int, input().split()))
print(min(lst), max(lst), sum(lst))
| n = input()
data_list = list(input("").split())
min_array = min(map(int,data_list))
max_array = max(map(int,data_list))
sum_array = sum(map(int,data_list))
print("{0} {1} {2}".format(min_array, max_array, sum_array)) | 1 | 727,287,753,350 | null | 48 | 48 |
N = int(input())
string = [0 for i in range(N)]
calc_str = lambda :"".join(list(chr(i+ord('a')) for i in string))
chr_a = ord('a')
print(calc_str())
now = N-2
while N > 1:
if string[now+1]-max(string[:now+1]) > 0:
if now == 0: break
string[now+1] = 0
now -= 1
else:
string[now+1] += 1
now = N-2
print(calc_str()) | n, m, l = map(int, raw_input().split(" "))
a = [map(int, raw_input().split(" ")) for j in range(n)]
b = [map(int, raw_input().split(" ")) for i in range(m)]
c = [[0 for k in range(l)] for j in range(n)]
for j in range(n):
for k in range(l):
for i in range(m):
c[j][k] += a[j][i] * b[i][k]
for j in range(n):
print " ".join(map(str, (c[j]))) | 0 | null | 27,007,299,474,800 | 198 | 60 |
N = int(input())
s = []
for i in range(N):
s.append(input())
inc = []
dec = []
total = 0
for i in s:
cn = 0
mn = 0
for j in i:
if j=="(":
cn+=1
else:
cn-=1
mn = min(cn,mn)
total += cn
if cn>=0:
inc.append([mn,cn])
else:
dec.append([mn-cn,-cn])
inc.sort(reverse=True,key=lambda x:x[0])
dec.sort(reverse=True,key=lambda x:x[0])
def check(lis):
hi = 0
for i in lis:
if hi+i[0]<0:
return False
else:
hi+=i[1]
return True
if check(inc) and check(dec) and total==0:
print("Yes")
else:
print("No")
| # -*- coding: utf-8 -*-
def round_robin_scheduling(process_name, process_time, q):
result = []
elapsed_time = 0
while len(process_name) > 0:
# print process_name
# print process_time
if process_time[0] <= q:
elapsed_time += process_time[0]
process_time.pop(0)
result.append(process_name.pop(0) + ' ' + str(elapsed_time))
else:
elapsed_time += q
process_name.append(process_name.pop(0))
process_time.append(process_time.pop(0) - q)
return result
if __name__ == '__main__':
N, q = map(int, raw_input().split())
process_name, process_time = [], []
for i in xrange(N):
process = raw_input().split()
process_name.append(process[0])
process_time.append(int(process[1]))
# N, q = 5, 100
# process_name = ['p1', 'p2', 'p3', 'p4', 'p5']
# process_time = [150, 80, 200, 350, 20]
result = round_robin_scheduling(process_name, process_time, q)
for i in xrange(len(result)):
print result[i] | 0 | null | 11,925,842,709,170 | 152 | 19 |
n = int(input())
a = input()
ans = ""
for i in a:
ans += chr(65 + (ord(i) - 65 + n )%26)
print(ans) | n = int(input())
s = list(input())
for i in range(len(s)):
s[i] = chr((ord(s[i]) + n - ord('A')) % 26 + ord('A'))
print(''.join(s)) | 1 | 134,362,078,169,120 | null | 271 | 271 |
n, m, x = map(int, input().split())
ca = [list(map(int, input().split())) for _ in range(n)]
ans = 12*(10**5)+1
for i in range(2**n):
a = [0] * m
cs = 0
for j in range(n):
if (i >> j) & 1:
cs += ca[j][0]
for k in range(1, m+1):
a[k-1] += ca[j][k]
flag = True
for j in range(m):
if a[j] < x:
flag = False
break
if flag:
ans = min(ans, cs)
if ans == 12*(10**5)+1:
ans = -1
print(ans) | n, m, x = map(int, input().split())
c = [0] * n
a = [[]] * n
for i in range(n):
c[i], *a[i] = map(int, input().split())
ans = 2**32
for mask in range(1 << n):
res = [0] * m
cost = 0
for i in range(n):
if mask >> i & 1:
cost += c[i]
for j in range(m):
res[j] += a[i][j]
if all(v >= x for v in res):
ans = min(ans, cost)
print(ans if ans != 2**32 else -1) | 1 | 22,133,005,155,548 | null | 149 | 149 |
def calcGaps(n):
gaps = [1]
while 3 * gaps[-1] + 1 < n:
gaps.append(3 * gaps[-1] + 1)
return gaps[::-1]
def insertionSort(a, n, gap, cnt):
for i in range(gap, n):
v = a[i]
j = i - gap
while j >= 0 and a[j] > v:
a[j + gap] = a[j]
j = j - gap
cnt += 1
a[j + gap] = v
return a, cnt
def shellSort(a, n):
cnt = 0
Gaps = calcGaps(n)
for gap in Gaps:
a, cnt = insertionSort(a, n, gap, cnt)
print(len(Gaps))
print(*Gaps)
print(cnt)
print(*a, sep='\n')
n = int(input())
A = [int(input()) for _ in range(n)]
shellSort(A, n)
| #from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
#import bisect
#
# d = m - k[i] - k[j]
# if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも!!
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
return list(map(int,input().split()))
def I():
return int(input())
import math
a,b,h,m = readInts()
h = h-12 if h>=12 else h
h_ = 30 * h + 30 * m/60
m_ = 360 * m / 60
kakudo = min(abs(m_ - h_), 360 - abs(m_ - h_))
c = pow(a**2 + b**2 - 2*a*b*math.cos(math.radians(kakudo)),.5)
print(c)
| 0 | null | 10,024,815,498,638 | 17 | 144 |
N, K = list(map(int, input().split()))
p = sorted(list(map(int, input().split())), reverse=False)
print(sum(p[:K])) | tmp = input().split(" ")
N = int(tmp[0])
K = int(tmp[1])
ary = list(map(lambda x: int(x), input().split(" ")))
ary.sort()
print(sum(ary[0:K])) | 1 | 11,598,997,406,290 | null | 120 | 120 |
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
a,b,c = MI()
if c < a+b:
print('No')
else:
print('Yes' if 4*a*b < (c-a-b)**2 else 'No')
| import sys
input = sys.stdin.readline
n = int(input())
a_ord = ord('a')
s = ["a"]
ans = []
def dfs(s):
max_ord = a_ord
for i in s:
max_ord = max(max_ord, ord(i))
for i in range(a_ord, max_ord + 2):
t = s[:]
t.append(chr(i))
if len(t) == n:
ans.append("".join(t))
else:
dfs(t)
if n == 1:
print('a')
else:
dfs(s)
ans.sort()
for w in ans:
print(w) | 0 | null | 52,079,874,971,280 | 197 | 198 |
def nCr(n,r,fac,finv):
mod = (10**9)+7
ans = fac[n] * (finv[r] * finv[n-r] % mod) % mod
return ans
k = int(input())
s = input()
l = len(s)
n = l+k+1
# als = list(map(int,input().split()))
# als.sort()
ans = 0
mod = (10**9)+7
fac = [1,1]+[0]*n
finv = [1,1]+[0]*n
inv = [1,1]+[0]*n
for i in range(2,n+1):
fac[i] = fac[i-1] * i % mod
inv[i] = mod - inv[mod%i] * (mod//i) % mod
finv[i] = finv[i-1] * inv[i] % mod
for i in range(k+1):
ans += nCr(l-i+k-1,l-1,fac,finv)*pow(26,i,mod)*pow(25,k-i,mod)
ans %= mod
print(ans) | #!/usr/bin python3
# -*- coding: utf-8 -*-
def main():
mod = 10**9+7
K = int(input())
S = input()
Nk = len(S)
ret = 0
nCk = 1
pw25 = 1
pw26 = pow(26,K,mod)
inv26 = pow(26,mod-2,mod)
for i in range(K+1):
ret += nCk * pw25 * pw26
ret %= mod
nCk *= (i+Nk) * pow(i+1,mod-2,mod)
nCk %= mod
pw25 = (pw25*25)%mod
pw26 = (pw26*inv26)%mod
print(ret)
if __name__ == '__main__':
main()
| 1 | 12,919,608,107,520 | null | 124 | 124 |
n = int(input())
ac = 0
wa = 0
tle = 0
re = 0
for _ in range(n):
s = input()
if s == "AC":
ac += 1
elif s == "WA":
wa += 1
elif s == "TLE":
tle += 1
elif s == "RE":
re += 1
print("AC x " + str(ac))
print("WA x " + str(wa))
print("TLE x " + str(tle))
print("RE x " + str(re)) | n=int(input())
S=[]
for i in range(n):
S.append(input())
print('AC', 'x', S.count('AC'))
print('WA', 'x', S.count('WA'))
print('TLE', 'x', S.count('TLE'))
print('RE', 'x', S.count('RE'))
| 1 | 8,658,308,588,480 | null | 109 | 109 |
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
# mod = 998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 1<<32-1
# INF = 10**18
def main():
n = int(ipt())
x,y = map(int,ipt().split())
mas = [x+y,x-y,-x-y,y-x]
ma = 0
for _ in range(n-1):
x,y = map(int,ipt().split())
cpr = [-y-x,y-x,x+y,x-y]
for i in range(4):
if mas[i]+cpr[i] > ma:
ma = mas[i]+cpr[i]
for i in range(4):
if mas[i] < cpr[i-2]:
mas[i] = cpr[i-2]
print(ma)
return None
if __name__ == '__main__':
main()
| #Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
threading.stack_size(10**8)
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n=int(input())
ans=0
d=defaultdict(int)
d1=defaultdict(int)
m=-10**13
m1=-10**13
mi=10**13
mi1=10**13
for i in range(n):
a,b=map(int,input().split())
m=max(m,a+b)
mi=min(mi,a+b)
m1=max(m1,a-b)
mi1=min(mi1,a-b)
#print(mi,mi1,m,m1)
print(max(m-mi,m1-mi1)) | 1 | 3,427,176,401,740 | null | 80 | 80 |
N = int(input())
arr = list(map(int, input().split()))
s = 0
for i in range(N):
s ^= arr[i]
for i in range(N):
arr[i] ^= s
print(' '.join(map(str, arr))) | n = int(input())
for i in range(1,n+1):
if i % 3 == 0 or i % 10 == 3:
print(" {}".format(i), end='')
else:
x = i
while True:
x = x // 10
if x == 0:
break
elif x % 10 == 3:
print(" {}".format(i), end='')
break
print("") | 0 | null | 6,783,946,518,988 | 123 | 52 |
a,b=map(int, input().split())
c=a-2*b
print(c if c>=0 else 0 ) | A, B, C, K = map(int, input().split())
if K <= A:
print(1 * K)
elif A < K <= A + B:
print(1 * A)
elif A + B < K:
print(1 * A - 1 * (K - A - B)) | 0 | null | 94,649,291,519,882 | 291 | 148 |
n = int(input())
x = 0
for i in range(n):
d1, d2 = map(int, input().split())
if x != 3:
if d1 != d2:
x = 0
else:
x += 1
print("Yes" if x == 3 else "No") | import sys
n=int(input())
d=[]
cnt=0
for i in range(n):
D=[int(x) for x in input().split()]
d.append(D)
for d1,d2 in d:
if d1==d2:
cnt+=1
else:
cnt=0
if 3<=cnt:
print("Yes")
sys.exit()
print("No") | 1 | 2,480,131,474,328 | null | 72 | 72 |
import sys
input = sys.stdin.buffer.readline
from collections import defaultdict
def main():
N,K = map(int,input().split())
a = list(map(int,input().split()))
d = defaultdict(int)
cum = [0]
for i in range(N):
cum.append((cum[-1]+a[i]-1)%K)
ans = 0
for i in range(N+1):
ans += d[cum[i]]
d[cum[i]] += 1
if i >= K-1:
d[cum[i-K+1]] -= 1
print(ans)
if __name__ == "__main__":
main()
| N,K = map(int,input().split())
A = list(map(int,input().split()))
A = [(a-1) % K for a in A]
S = [0 for i in range(N+1)]
for i in range(1, N+1):
S[i] = (S[i-1] + A[i-1]) % K
kinds = set(S)
counts = {}
ans = 0
for k in kinds:
counts[k] = 0
for i in range(N+1):
counts[S[i]] += 1
if i >= K:
counts[S[i-K]] -= 1
ans += (counts[S[i]] - 1)
print(ans) | 1 | 137,268,063,030,308 | null | 273 | 273 |
n = input()
ret = 0
for s in n:
ret *= 10
ret %= 9
ret += int(s)
ret %= 9
if ret == 0:
print("Yes")
else:
print("No") | N = int(input())
ans = 0
for i in range(N):
Y = int(N/(i+1))
ans += Y * (Y + 1) * (i + 1) // 2
print(ans) | 0 | null | 7,771,646,481,760 | 87 | 118 |
from collections import deque
import copy
H, W = map(int, input().split())
maze = [list(input()) for _ in range(H)]
# すべての.についてスタート地点と仮定してBFS
def bfs(i, j):
dq = deque()
maze_c = copy.deepcopy(maze)
maze_c[i][j] = 0
dq.appendleft([i, j])
res = 0
while len(dq) > 0:
ni, nj = dq.pop()
if maze_c[ni][nj] == "#":
continue
for di, dj in ((1, 0), (0, 1), (-1, 0), (0, -1)):
if ni + di < 0 or nj + dj < 0 or ni + di >= H or nj + dj >= W:
continue
if maze_c[ni + di][nj + dj] == ".":
maze_c[ni + di][nj + dj] = maze_c[ni][nj] + 1
res = max(res, maze_c[ni + di][nj + dj])
dq.appendleft([ni + di, nj + dj])
return res
ans = 0
for i in range(H):
for j in range(W):
if maze[i][j] == ".":
ans = max(ans, bfs(i, j))
print(ans) | import sys
from collections import deque
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
H, W = map(int, readline().split())
S = [[0] * W for _ in range(H)]
for i in range(H):
S[i] = readline().strip()
dxdy4 = ((-1, 0), (0, -1), (0, 1), (1, 0))
ans = 0
for i in range(H):
for j in range(W):
if S[i][j] == '#':
continue
dist = [[-1] * W for _ in range(H)]
dist[i][j] = 0
queue = deque([(i, j)])
res = 0
while queue:
x, y = queue.popleft()
for dx, dy in dxdy4:
nx, ny = x + dx, y + dy
if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.' and dist[nx][ny] == -1:
dist[nx][ny] = dist[x][y] + 1
if res < dist[nx][ny]:
res = dist[nx][ny]
queue.append((nx, ny))
if ans < res:
ans = res
print(ans)
return
if __name__ == '__main__':
main()
| 1 | 94,824,773,778,420 | null | 241 | 241 |
#template
def inputlist(): return [int(j) for j in input().split()]
#template
N,K = inputlist()
p = inputlist()
p.sort()
ans = 0
for i in range(K):
ans +=p[i]
print(ans) | N, K = list(map(int, input().split()))
price_list = list(map(int, input().split()))
price_list.sort()
answer = 0
for i in range(K):
answer += price_list[i]
print(answer) | 1 | 11,582,563,518,348 | null | 120 | 120 |
import math
n,k = (int(x) for x in input().split())
An = [int(i) for i in input().split()]
left = 0
right = max(An)
def check(x):
chk = 0
for i in range(n):
chk += math.ceil(An[i]/x)-1
return chk
while right-left!=1:
x = (left+right)//2
if check(x)<=k:
right = x
else:
left = x
print(right) | n,k = map(int,input().split())
friend = list(map(int,input().split()))
count = 0
for x in friend:
if x >= k:
count += 1
print(count)
| 0 | null | 92,607,089,862,208 | 99 | 298 |
while True:
a,op,b=input().split(" ")
a,b=[int(i) for i in (a,b)]
if op=="+":
print(a+b)
elif op=="-":
print(a-b)
elif op=="*":
print(a*b)
elif op=="/":
print(int(a/b))
else:
break | operand = ["+", "-", "*"]
src = [x if x in operand else int(x) for x in input().split(" ")]
stack = []
for s in src:
if isinstance(s, int):
stack.append(s)
elif s == "+":
b, a = stack.pop(), stack.pop()
stack.append(a+b)
elif s == "-":
b, a = stack.pop(), stack.pop()
stack.append(a-b)
elif s == "*":
b, a = stack.pop(), stack.pop()
stack.append(a*b)
print(stack[0]) | 0 | null | 363,545,261,312 | 47 | 18 |
n, m = map(int, input().split())
h = list(map(int, input().split()))
is_good_peak_arr = [True] * n
for i in range(m):
a, b = map(int, input().split())
a, b = a-1, b-1
if h[a] >= h[b]: is_good_peak_arr[b] = False
if h[b] >= h[a]: is_good_peak_arr[a] = False
print(is_good_peak_arr.count(True)) | input = input()
W,H,x,y,r = map(int ,input.split())
if x - r < 0 or x + r > W or y - r < 0 or y + r > H:
print("No")
if x - r >= 0 and x + r <= W and y - r >= 0 and y + r <= H:
print("Yes")
| 0 | null | 12,877,982,764,412 | 155 | 41 |
# coding: utf-8
# Your code here!
import bisect
N,D,A=map(int,input().split())
log=[]
loc=[]
ene=[]
for _ in range(N):
X,H=map(int,input().split())
log.append([X,H])
log.sort(key=lambda x:x[0])
for X,H in log:
loc.append(X)
ene.append(H)
syokan=[0]*N
power=0
for i in range(N):
temp=max(-((-ene[i]+power)//A),0)*A
power+=temp
rng=bisect.bisect_right(loc,loc[i]+2*D)
syokan[min(rng-1,N-1)]+=temp
power-=syokan[i]
#print(syokan)
#print(syokan)
print(sum(syokan)//A) | while 1:
x,y = map(int, raw_input().split())
if x == 0 and y == 0:
break
if y >= x:
print '%s %s' % (x, y)
else:
print '%s %s' % (y, x) | 0 | null | 41,306,670,084,992 | 230 | 43 |
n = input()
a = map(int, raw_input().split())
if len(a) == n:
a.reverse()
print ' '.join(map(str, a)) | n = input()
a = map(str,raw_input().split())
print ' '.join(a[::-1]) | 1 | 997,174,557,962 | null | 53 | 53 |
H,N = map(int,input().split())
A = list(map(int,input().split()))
for i in range(N):
H -= A[i]
if H > 0:
print('No')
else:
print('Yes') | H, N = map(int, input().split())
A = map(int, input().split())
print("Yes" if H <= sum(A) else "No") | 1 | 78,064,902,367,652 | null | 226 | 226 |
import sys
s = ''
for line in sys.stdin:
s += line
s = s.lower()
count = {letter: s.count(letter) for letter in set(s)}
for c in range(97,97+26):
if chr(c) in count:
print("%c : %d" % (chr(c), count[chr(c)]))
else:
print("%c : 0" % chr(c)) | import math
a,b,c,d=map(int,input().split())
print("Yes") if math.ceil(c/b)<=math.ceil(a/d) else print("No") | 0 | null | 15,570,599,315,570 | 63 | 164 |
import sys
import math
import bisect
def main():
n, m = map(int, input().split())
if n < 10:
m += 100 * (10 - n)
print(m)
if __name__ == "__main__":
main()
| n,r = input().split()
if int(n) >= 10:
print(r)
else:
k = (-int(r) - 100 * (10 - int(n) )) * -1
print(k)
| 1 | 63,309,915,524,508 | null | 211 | 211 |
x, y, z = map(int, input().split())
createNum = 0
createTime = 0
loopCnt = x//y
createNum = y*loopCnt
createTime = z*loopCnt
remain = x%y
if remain != 0:
createTime += z
print(createTime) | import math
def solve(n,x,t):
if n%x != 0:
return (math.ceil(n/x))*t
else:
return (n//x)*t
n,x,t = map(int, input().strip().split())
print(solve(n,x,t)) | 1 | 4,287,980,922,878 | null | 86 | 86 |
from collections import deque
def read():
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
return N, K, A
def sample():
from random import randint
N, K = 10**5, 10**4
A = [randint(-10**9, 10**9) for i in range(N)]
return N, K, A
def nCk_mod_v2_preprocess(n, p=10**9+7):
f = [0 for i in range(n+1)] # n!
invf = [0 for i in range(n+1)] # (n!)^-1
f[0] = 1
f[1] = 1
invf[0] = 1
invf[1] = 1
for i in range(2, n+1):
f[i] = f[i-1] * i % p
invf[i] = pow(f[i], p-2, p)
return f, invf
def nCk_mod(n, k, f, invf, p=10**9+7):
if n < k or n < 0 or k < 0:
return 0
else:
return (f[n] * invf[k] % p) * invf[n-k] % p
def solve(N, K, A, MOD=10**9+7):
A = list(sorted(A, reverse=True))
qmax = deque()
qmin = deque()
f, invf = nCk_mod_v2_preprocess(N, p=MOD)
for i in range(1, N+1):
# p = nCr(N-i-1, K-1)
p = nCk_mod(N-i, K-1, f, invf)
qmax.append(p * A[i-1] % MOD)
qmin.append(p * A[N-i] % MOD)
return (MOD + sum(qmax) - sum(qmin)) % MOD
if __name__ == '__main__':
inputs = read()
#inputs = sample()
print("{}".format(solve(*inputs)))
|
X = int(input())
c = X // 100
if c * 100 <= X <= c * 105:
print(1)
else:
print(0)
| 0 | null | 111,643,942,555,468 | 242 | 266 |
import sys
input = sys.stdin.readline
from collections import *
def bfs():
q = deque([0])
pre = [-1]*N
pre[0] = 0
while q:
v = q.popleft()
for nv in G[v]:
if pre[nv]==-1:
pre[nv] = v
q.append(nv)
return pre
N, M = map(int, input().split())
G = [[] for _ in range(N)]
for _ in range(M):
A, B = map(int, input().split())
G[A-1].append(B-1)
G[B-1].append(A-1)
pre = bfs()
print('Yes')
for pre_i in pre[1:]:
print(pre_i+1) | s = input()
x = ""
y = ""
Q = int(input())
rev = 0
for i in range(Q):
q = list(input().split())
if q[0] == "2":
q[1] = int(q[1])
q[1] -= 1
if rev:
q[1] = 1 - q[1]
if q[1] == 0:
x += q[2]
else:
y += q[2]
else:
rev = 1 - rev
x = x[::-1]
ans = x + s + y
if rev:
ans = ans[::-1]
print(ans) | 0 | null | 38,912,956,646,170 | 145 | 204 |
# Aizu Problem ALDS_1_4_D: Allocation
import sys, math, os
# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
sys.stdin = open("sample-input2.txt", "rt")
def check(n, k, W, p):
idx = 0
for i in range(k):
S = 0
while W[idx] + S <= p:
S += W[idx]
idx += 1
if idx == n:
return True
return False
n, k = [int(_) for _ in input().split()]
W = [int(input()) for _ in range(n)]
left, right = 0, 10**16
while right - left > 1:
mid = (left + right) // 2
if check(n, k, W, mid):
right = mid
else:
left = mid
print(right) | import math
import collections
n, k = map(int, input().split())
W = collections.deque()
for i in range(n):
W.append(int(input()))
left = max(math.ceil(sum(W) / k), max(W))
right = sum(W)
center = (left + right) // 2
# print('------')
while left < right:
i = 1
track = 0
# print(center)
for w in W:
# if center == 26:
# print('track: ' + str(track))
track += w
if track > center:
track = w
i += 1
if i > k:
left = center + 1
break
else:
right = center
center = (left + right) // 2
print(center)
| 1 | 85,142,615,686 | null | 24 | 24 |
def pascal(xdata):
for x in xrange(3):
for y in xrange(3):
for z in xrange(3):
if xdata[x]**2 + xdata[y]**2 == xdata[z]**2:
return True
return False
N = input()
data = [map(int, raw_input().split()) for x in range(N)]
for x in data:
if pascal(x):
print "YES"
else:
print "NO" | 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)&1:d.pop()
else:d.popleft()
print(*d)
if'__main__'==__name__:s()
| 0 | null | 25,149,269,770 | 4 | 20 |
from collections import Counter
N = int(input())
S = [input() for _ in range(N)]
# 方針:各文字列の出現回数を数え、出現回数が最大なる文字列を昇順に出力する
# Counter(リスト) は辞書型のサブクラスであり、キーに要素・値に出現回数という形式
# Counter(リスト).most_common() は(要素, 出現回数)というタプルを出現回数順に並べたリスト
S = Counter(S).most_common()
max_count = S[0][1] # 最大の出現回数
# 出現回数が最も多い単語を集計する
l = [s[0] for s in S if s[1] == max_count]
# 昇順にソートして出力
for i in sorted(l):
print(i) | N,M=map(int,input().split())
H=list(map(int,input().split()))
cnt=[1 for _ in range(N)]
for _ in range(M):
A,B=map(int,input().split())
A-=1
B-=1
if H[A]>H[B]:
cnt[B]=0
elif H[A]<H[B]:
cnt[A]=0
else:
cnt[A]=0
cnt[B]=0
print(cnt.count(1))
| 0 | null | 47,538,763,590,428 | 218 | 155 |
import sys
input = sys.stdin.readline
# A - Table Tennis Training
def move_left():
return A + (B-A-1)//2
def move_right():
return N - B + 1 + (B-A-1)//2
N, A, B = map(int, input().split())
if (B-A) % 2 == 0:
print(int((B-A)//2))
else:
l = move_left()
r = move_right()
print(min(l, r)) | i = raw_input()
N, A, B = i.split()
N = int(N)
A = int(A)
B = int(B)
if abs(A-B)%2 == 0:
print int(abs(A-B)/2)
else:
e = int(min(A-1, N-B))
d = (B-A+1) // 2
print e + d | 1 | 109,692,024,511,520 | null | 253 | 253 |
def main():
n = int(input())
T = tuple(map(int, input()))
ans = 0
for i in range(0, 1000):
a = i // 100
b = (i // 10) % 10
c = i % 10
flag1 = False
flag2 = False
flag3 = False
for t in T:
if flag2:
if t == c:
flag3 = True
break
if flag1:
if t == b:
flag2 = True
continue
if t == a:
flag1 = True
if flag3:
ans += 1
print(ans)
if __name__ == "__main__":
main() | n=int(input())
s=list(input())
ans=0
for i in range(10):
if str(i) in s:
first=s.index(str(i))
ss=s[first+1:]
for j in range(10):
if str(j) in ss:
sec=ss.index(str(j))
for k in range(10):
if str(k) in ss[sec+1:]:
ans+=1
print(ans) | 1 | 128,597,077,153,248 | null | 267 | 267 |
import sys
input = sys.stdin.readline
class Node:
def __init__(self, val):
self.val = val
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.sentinel = Node(None)
self.sentinel.prev = self.sentinel
self.sentinel.next = self.sentinel
def insert(self, val):
node = Node(val)
node.prev = self.sentinel
node.next = self.sentinel.next
self.sentinel.next.prev = node
self.sentinel.next = node
def delete(self, val):
self.delete_node(self.search(val))
def deleteFirst(self):
self.delete_node(self.sentinel.next)
def deleteLast(self):
self.delete_node(self.sentinel.prev)
def search(self, val):
cursor = self.sentinel.next
while cursor != self.sentinel and cursor.val != val:
cursor = cursor.next
return cursor
def delete_node(self, node):
if node == self.sentinel:
return
node.prev.next = node.next
node.next.prev = node.prev
n = int(input())
linked_list = DoublyLinkedList()
for index in range(n):
command = input().rstrip()
if command[0] == 'i':
linked_list.insert(command[7:])
elif command[6] == 'F':
linked_list.deleteFirst()
elif command[6] == 'L':
linked_list.deleteLast()
else:
linked_list.delete(command[7:])
node = linked_list.sentinel.next
output = []
while node != linked_list.sentinel:
output.append(node.val)
node = node.next
print(" ".join(map(str, output)))
| # -*- coding: utf-8 -*-
from collections import deque
if __name__ == '__main__':
n = int(input())
L = deque()
for _ in range(n):
command = input().split(" ")
if command[0] == "insert":
L.appendleft(command[1])
elif command[0] == "delete":
try:
L.remove(command[1])
except:
pass
elif command[0] == "deleteFirst":
L.popleft()
elif command[0] == "deleteLast":
L.pop()
print(" ".join(L))
| 1 | 47,181,192,672 | null | 20 | 20 |
def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b)
def main():
from math import ceil
n, m, *a = map(int, open(0).read().split())
c = 0
t = a[0]
while t % 2 == 0:
c += 1
t = t // 2
for x in a[1:]:
d = 0
while x % 2 == 0:
d += 1
x = x // 2
if d != c:
print(0)
break
t = lcm(t, x)
else:
ans = ceil(m // 2 ** (c-1) // t / 2)
print(ans)
if __name__ == "__main__":
main()
| from fractions import gcd
n, m = map(int, input().split())
lst = list(map(int, input().split()))
norm = 0
tmp = lst[0]
while tmp%2 == 0:
tmp = tmp//2
norm += 1
for i in range(n):
count = 0
tmp = lst[i]
while tmp%2 == 0:
tmp = tmp//2
count += 1
if norm != count:
print(0)
exit()
lst[i] = lst[i]//2
lst = sorted(list(set(lst)))
def lcm(a, b): # a, b の最大公約数を求める
return(a*b//gcd(a, b))
def lcms(List): # list[a[0], a[1], ... , a[n]]の最小公倍数を求める
if len(List) == 1:
return List[0]
ans = lcm(List[0], List[1])
for i in range(2, len(List)):
ans = lcm(ans, List[i])
return ans
lcm = lcms(lst)
ans = m//lcm
if ans%2 == 0:
ans = ans//2
else:
ans = ans//2 + 1
print(ans) | 1 | 101,840,880,597,540 | null | 247 | 247 |
str = input() *2
pattern = input()
if pattern in str:
print("Yes")
else:
print("No") | s=[ord(i) for i in input()]
n=[ord(i) for i in input()]
flag=0
flack=0
for i in range(len(s)):
flack=0
if n[0]==s[i]:
flack=1
for j in range(1,len(n)):
if i+j>=len(s):
if n[j]==s[i+j-len(s)]:
flack=flack+1
else:
break
else:
if n[j]==s[i+j]:
flack=flack+1
else:
break
if flack==len(n):
flag=1
break
if flag:
print('Yes')
else:
print('No') | 1 | 1,725,935,076,690 | null | 64 | 64 |
def pow_mod(a, b, p):
res = 1
mul = a
for i in range(len(bin(b)) - 2):
if (1 << i) & b:
res = (res * mul) % p
mul = (mul ** 2) % p
return res
def comb_mod(n, r, p, factorial, invert_factorial):
return (factorial[n] * invert_factorial[r] * invert_factorial[n - r]) % p
def main():
p = 10 ** 9 + 7
n, k = map(int, input().split())
factorial = [1] * (n + 1)
for i in range(1, n + 1):
factorial[i] = (factorial[i - 1] * i) % p
invert_factorial = [0] * (n + 1)
invert_factorial[n] = pow_mod(factorial[n], p - 2, p)
for i in range(n - 1, -1, -1):
invert_factorial[i] = (invert_factorial[i + 1] * (i + 1)) % p
res = 0
for i in range(min(k + 1, n)):
res = (res + comb_mod(n, i, p, factorial, invert_factorial)
* comb_mod(n - 1, i, p, factorial, invert_factorial)) % p
print(res)
main()
| # coding: utf-8
import sys
def gcd(a, b):
m = a % b
if m == 0:
return b
return gcd(b, m)
for l in sys.stdin:
x, y = map(int, l.split())
g = gcd(x, y)
l = x * y / g
print g, l | 0 | null | 33,779,929,523,770 | 215 | 5 |
n=int(input())
a= list(map(int, input().split()))
kt=1
a.sort()
for i in range (0,n-1):
if a[i]==a[i+1]:
kt=0
break
if kt==1:
print("YES")
else:
print("NO") | def check(seq):
return len(seq) != len(set(seq))
def main():
N = int(input())
A = list(map(int, input().split()))
ans = check(A)
if ans:
print("NO")
else:
print("YES")
main() | 1 | 74,031,899,132,772 | null | 222 | 222 |
n = int(input())
line = list(map(int, input().split()))
max = line[0]
min = line[0]
sum = line[0]
for i in range(1, n):
if max < line[i]:
max = line[i]
elif min > line[i]:
min = line[i]
sum += line[i]
print(min, max, sum)
| n,k=map(int,input().split())
A=list(map(int,input().split()))
MOD=10**9+7
ans=0
L=[1]*(n+1)
Linv=[1]*(n+1)
inv=[0]+[1]*n
for i in range(2,n+1):
L[i]=(L[i-1]*i)%MOD
inv[i]=(MOD-inv[MOD%i]*(MOD//i))%MOD
Linv[i]=(Linv[i-1]*inv[i])%MOD
def cmb(n,k):
return (((L[n]*Linv[k])%MOD)*Linv[n-k])%MOD
A.sort()
for j in range(n-k+1):
ans+=((A[-1-j]-A[j])*cmb(n-1-j,k-1))%MOD
if ans>=0:
print(ans%MOD)
else:
print(MOD+ans)
| 0 | null | 48,513,396,874,734 | 48 | 242 |
def main(X, A):
ans = 1
if 0 in A:
return 0
for a in A:
ans *= a
if ans > 1e18:
return -1
return ans
if __name__ == '__main__':
X = int(input())
A = list(map(int, input().split()))
ans = main(X, A)
print(ans)
| N = int(input())
line = [int(i) for i in input().split()]
sum = 1
line.sort(reverse=True)
if line[len(line) -1]== 0:
print(0)
exit()
for num in line:
sum = sum * num
if sum > 10 ** 18:
print(-1)
exit()
print(sum) | 1 | 16,171,514,475,814 | null | 134 | 134 |
import sys
BIG_NUM = 2000000000
MOD = 1000000007
EPS = 0.000000001
NUM = 20005
table = [""]*NUM
while True:
T = str(input())
if T == '-':
break
left = 0
right = 0
#長い配列にパターン文字列を転記
for i in range(len(T)):
# print(T[right])
table[left+right] = T[right]
right += 1
num_suffle = int(input())
for loop in range(num_suffle):
pick_num = int(input())
#先頭からpick_num文字を末尾に転記し、論理削除
for i in range(pick_num):
table[right+i] = table[left+i]
left += pick_num
right += pick_num
for i in range(left,right):
print("%s"%(table[i]),end = "")
print()
| string = []
while 1:
s = input()
if s == "-":
break
try:
n = int(s)
for i in range(n):
m = int(input())
string = string[m:] + string[:m]
output = "".join(string)
print(output)
except ValueError:
string = list(s)
continue | 1 | 1,895,798,863,222 | null | 66 | 66 |
N, K = map(int, input().split())
ans = min(N % K, K - N % K)
print(ans) | N,K=map(int,input().split())
m=N//K
print(min(abs(N-m*K),abs(N-(m+1)*K))) | 1 | 39,307,592,991,690 | null | 180 | 180 |
# AOJ ITP1_9_A
def numinput():
a = input().split()
for i in range(len(a)):
a[i] = int(a[i])
return a
# ※大文字と小文字を区別しないので注意!!!!
# 全部大文字にしちゃえ。
def main():
W = input().upper() # 大文字にする
line = ""
count = 0
while True:
line = input().split(" ")
if line[0] == "END_OF_TEXT": break
for i in range(len(line)):
word = line[i].upper()
if W == word: count += 1
print(count)
if __name__ == "__main__":
main()
| 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)
| 1 | 1,802,591,403,178 | null | 65 | 65 |
import sys
def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
a = [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 = I()
print(a[K -1 ]) | num = int(input())
K = "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"
l = K.split(',')
print(l[num-1]) | 1 | 49,881,505,213,788 | null | 195 | 195 |
s, t = map(str, input().split())
x = t + s
print(x) | def q1():
S, T = input().split()
print('{}{}'.format(T, S))
if __name__ == '__main__':
q1()
| 1 | 102,817,080,964,708 | null | 248 | 248 |
def solve():
s=input()
if(len(s)%2==0):
print("No")
return
else :
n=len(s)//2
str1=s[:n]
str2=s[n+1:]
# print(str1,str2)
if(str1==str2):
print("Yes")
else:
print("No")
if __name__ == "__main__":
solve() | s = input()
n = len(s)
if s != s[::-1]:
print("No")
elif s[0:(n-1)//2] != s[(n-1)//2-1::-1]:
print("No")
elif s[(n+3)//2-1:n] != s[n-1:(n+3)//2-2:-1]:
print("No")
else:
print("Yes") | 1 | 46,159,802,715,276 | null | 190 | 190 |
# -*- coding: utf-8 -*-
x=int(input())
a=360
b=x
r=a%b
while r!=0:
a=b
b=r
r=a%b
lcm=x*360/b
k=int(lcm/x)
print(k) | N = int(input())
multiple_list = {i*j for i in range(1,10) for j in range(1,10)}
print(['No','Yes'][N in multiple_list]) | 0 | null | 86,231,696,430,230 | 125 | 287 |
import sys
sys.setrecursionlimit(1000000000)
import math
from math import gcd
def lcm(a, b): return a * b // gcd(a, b)
from itertools import count, permutations, combinations, chain, product
from functools import lru_cache
from collections import deque, defaultdict
from operator import itemgetter
from pprint import pprint
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')
N1097 = 10**9 + 7
DEBUG = 'ONLINE_JUDGE' not in sys.argv
def meg(f, ok, ng):
while abs(ok-ng)>1:
mid = (ok+ng)//2
if f(mid):
ok=mid
else:
ng=mid
return ok
def get_inv(n, modp):
return pow(n, modp-2, modp)
def factorials_list(n, modp): # 10**6
fs = [1]
for i in range(1, n+1):
fs.append(fs[-1] * i % modp)
return fs
def invs_list(n, fs, modp): # 10**6
invs = [get_inv(fs[-1], modp)]
for i in range(n, 1-1, -1):
invs.append(invs[-1] * i % modp)
invs.reverse()
return invs
def comb(n, k, modp):
num = 1
for i in range(n, n-k, -1):
num = num * i % modp
den = 1
for i in range(2, k+1):
den = den * i % modp
return num * get_inv(den, modp) % modp
def comb_from_list(n, k, modp, fs, invs):
return fs[n] * invs[n-k] * invs[k] % modp
#
class UnionFindEx:
def __init__(self, size):
#正なら根の番号、負ならグループサイズ
self.roots = [-1] * size
def getRootID(self, i):
r = self.roots[i]
if r < 0: #負なら根
return i
else:
r = self.getRootID(r)
self.roots[i] = r
return r
def getGroupSize(self, i):
return -self.roots[self.getRootID(i)]
def connect(self, i, j):
r1, r2 = self.getRootID(i), self.getRootID(j)
if r1 == r2:
return False
if self.getGroupSize(r1) < self.getGroupSize(r2):
r1, r2 = r2, r1
self.roots[r1] += self.roots[r2] #サイズ更新
self.roots[r2] = r1
return True
Yes = 'Yes'
No = 'No'
def dprint(*args, **kwargs):
if DEBUG:
print(*args, **kwargs)
def main():
N, K = mis()
P = list(map(lambda x: x-1, mis()))
C = lmis()
ans = -INF
for i in range(N):
p = i
tmp_score = 0
k = K
cycle = 0
while k:
p = P[p]
tmp_score += C[p]
ans = max(ans, tmp_score)
k -= 1
cycle += 1
if p==i:
if tmp_score < 0:
break
elif k > cycle*2:
skip_loop = (k - cycle)//cycle
tmp_score *= skip_loop + 1
k -= skip_loop * cycle
ans = max(ans, tmp_score)
print(ans)
main()
| def insertionSort( nums, n, g ):
cnt = 0
for i in range( g, n ):
v = nums[i]
j = i - g
while j >= 0 and nums[j] > v:
nums[ j+g ] = nums[j]
j -= g
cnt += 1
nums[ j+g ] = v
return cnt
def shellSort( nums, n ):
g = []
v = 1
while v <= n:
g.append( v )
v = 3*v+1
g.reverse( )
m = len( g )
print( m )
print( " ".join( map( str, g ) ) )
cnt = 0
for i in range( m ):
cnt += insertionSort( nums, n, g[i] )
print( cnt )
n = int( input( ) )
nums = [ int( input( ) ) for i in range( n ) ]
nums.append( 0 )
shellSort( nums, n )
nums.pop( )
for v in nums:
print( v ) | 0 | null | 2,696,902,951,008 | 93 | 17 |
Nsum = 0
while True:
I = input()
if int(I) == 0:
break
for i in I:
Nsum += int(i)
print(Nsum)
Nsum = 0 | # -*-coding:utf-8
def main():
while True:
inputNumber = input()
if(inputNumber == '0'):
break
else:
print(sum(list(map(int, inputNumber))))
if __name__ == '__main__':
main() | 1 | 1,555,875,067,940 | null | 62 | 62 |
h,w = map(int,input().split())
g = []
for _ in range(h):
S = input()
tmp = [str(i) for i in S]
g.append(tmp)
from collections import deque
# print(g)
dp = [[0]*w for _ in range(h)]
def dfs(i,j):
seen = [[False]*w for _ in range(h)]
seen[i][j] = True
q = deque([])
q.append((i,j,0))
dist=[(1,0),(-1,0),(0,1),(0,-1)]
while q:
x,y,cnt = q.popleft()
for dx,dy in dist:
if 0 <=x+dx<h and 0<=y+dy<w and seen[x+dx][y+dy]==False and g[x+dx][y+dy]=='.':
seen[x+dx][y+dy] = True
q.append((x+dx,y+dy,cnt+1))
return cnt
ans = 0
for i in range(h):
for j in range(w):
if g[i][j] =='.':
ans =max(ans,dfs(i,j))
print(ans) | n = int(input())
cards = {
'S': [],
'H': [],
'C': [],
'D': []
}
for _ in range(n):
color, rank = input().split()
cards[color].append(rank)
for color in ['S', 'H', 'C', 'D']:
for rank in [x for x in range(1, 14) if str(x) not in cards[color]]:
print(color, rank) | 0 | null | 47,900,808,063,670 | 241 | 54 |
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, log
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 fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *
N = INT()
L = LIST()
L.sort()
ans = 0
for i in range(N-2):
a = L[i]
for j in range(i+1, N-1):
b = L[j]
idx = bisect_left(L, a+b) - 1
if j < idx:
ans += idx - j
print(ans)
| import bisect
n=int(input())
a=sorted(list(map(int,input().split())))
cnt=0
for i in range(n):
for j in range(i+1,n):
cnt+=bisect.bisect_left(a,a[i]+a[j])-(j+1)
print(cnt) | 1 | 171,368,956,355,884 | null | 294 | 294 |
N,K=map(int,input().split())
p=list(map(int, input().split()))
p.sort()
price=0
for idx in range(K):
price=price+p[idx]
print(price)
| n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
ps = sorted(p)
print(sum(ps[:k])) | 1 | 11,602,240,648,288 | null | 120 | 120 |
# Python3 implementation of the approach
# Function to find the number of divisors
# of all numbers in the range [1,n]
def findDivisors(n):
# List to store the count
# of divisors
div = [0 for i in range(n + 1)]
# For every number from 1 to n
for i in range(1, n + 1):
# Increase divisors count for
# every number divisible by i
for j in range(1, n + 1):
if j * i <= n:
div[i * j] += 1
else:
break
# Print the divisors
return div
# Driver Code
if __name__ == "__main__":
n = int(input())
print(sum(findDivisors(n-1)))
# This code is contributed by
# Vivek Kumar Singh
| n = int(input())
l = list(map(int, input().split()))
w = list(set(l))
r = {w[i]:0 for i in range(len(w))}
for i in range(n):
r[l[i]] += 1
t = list(r.items())
ans = 0
for i in range(len(t)-2):
for j in range(i+1, len(t)-1):
for k in range(j+1, len(t)):
y = sum([t[i][0], t[j][0], t[k][0]])
x = max([t[i][0], t[j][0], t[k][0]])
if 2*x < y:
ans += t[i][1] * t[j][1] * t[k][1]
print(ans) | 0 | null | 3,790,494,797,882 | 73 | 91 |
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7
x,k,d = map(int,readline().split())
x = abs(x)
if (x >= k*d):
print(x-k*d)
elif ((k-x//d)%2):
print(abs(x%d-d))
else:
print(x%d)
| N = input()
lenN = len(N)
sumN = 0
for x in N:
sumN += int(x)
if sumN > 9:
sumN %= 9
if sumN % 9 == 0:
print('Yes')
else:
print('No') | 0 | null | 4,798,221,621,362 | 92 | 87 |
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n):
res = [None] * n
for i in range(n):
res[i] = II()
return res
def LIR(n):
res = [None] * n
for i in range(n):
res[i] = LI()
return res
def FR(n):
res = [None] * n
for i in range(n):
res[i] = IF()
return res
def LIR(n):
res = [None] * n
for i in range(n):
res[i] = IF()
return res
def LIR_(n):
res = [None] * n
for i in range(n):
res[i] = LI_()
return res
def SR(n):
res = [None] * n
for i in range(n):
res[i] = S()
return res
def LSR(n):
res = [None] * n
for i in range(n):
res[i] = LS()
return res
mod = 1000000007
inf = float('INF')
#solve
def solve():
def f(n, c):
tmp = n % c
t = tmp
b = 0
while tmp:
if tmp & 1:
b += 1
tmp //= 2
if t:
return f(t, b) + 1
else:
return 1
n = II()
a = S()
b = 0
for ai in a:
if ai == "1":
b += 1
a = a[::-1]
bp = 0
bm = 0
if b != 1:
for i, ai in enumerate(a):
if ai == "1":
bp += pow(2, i, b + 1)
bm += pow(2, i, b - 1)
bp %= b + 1
bm %= b - 1
ans = []
for i, ai in enumerate(a):
if ai == "1":
tmpbm = bm - pow(2, i, b - 1)
tmpbm %= b - 1
ans.append(f(tmpbm, b - 1))
else:
tmpbp = bp + pow(2, i, b + 1)
tmpbp %= b + 1
ans.append(f(tmpbp, b + 1))
for ai in ans[::-1]:
print(ai)
return
else:
for i, ai in enumerate(a):
if ai == "1":
bp += pow(2, i, b + 1)
bp %= b + 1
ans = []
for i, ai in enumerate(a):
if ai == "1":
ans.append(0)
else:
tmpbp = bp + pow(2, i, b + 1)
tmpbp %= b + 1
ans.append(f(tmpbp, b + 1))
for ai in ans[::-1]:
print(ai)
return
#main
if __name__ == '__main__':
solve()
| #!/usr/bin/env python3
import sys
import collections as cl
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()
print((N/3)**3)
main()
| 0 | null | 27,558,914,775,872 | 107 | 191 |
k=int(input())
if k%7==0:
k = 9*k//7
else:
k *= 9
f=10%k
r = -1
for i in range(10**7):
if f==1:
r = i+1
break
else:
f = f*10%k
print(r) | n = int(input())
dp = [0]*(n+1)
for i in range(1,n+1):
x = n//i
for j in range(1,x+1):
dp[i*j]+=1
sum_div = 0
for i in range(1,n+1):
sum_div += i*dp[i]
print(sum_div) | 0 | null | 8,626,139,558,402 | 97 | 118 |
# pypy
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
R, C, K = map(int, readline().split())
rcv = list(map(int, read().split()))
rc2v = {}
for rr, cc, vv in zip(rcv[::3], rcv[1::3], rcv[2::3]):
rc2v[(rr, cc)] = vv
dp = [[0]*4 for c in range(C+1)]
for r in range(1, R+1):
for c in range(1, C+1):
v = rc2v[(r, c)] if (r, c) in rc2v else 0
dp[c][0] = max(dp[c-1][0], max(dp[c]))
dp[c][1] = max(dp[c-1][1], dp[c][0] + v)
dp[c][2] = max(dp[c-1][2], dp[c-1][1] + v)
dp[c][3] = max(dp[c-1][3], dp[c-1][2] + v)
print(max(dp[-1])) | ### ----------------
### ここから
### ----------------
import sys
from io import StringIO
import unittest
def yn(b):
print("Yes" if b==1 else "No")
return
def resolve():
readline=sys.stdin.readline
n,x,y=map(int, readline().rstrip().split())
ans = [0] * (n-1)
for i in range(1,n+1):
for j in range(i+1,n+1):
d1 = abs(i-x) + abs(j-x)
d2 = abs(i-y) + abs(j-y)
d3 = abs(i-x) + abs(j-y) + 1
d4 = abs(i-y) + abs(j-x) + 1
d5 = abs(i-j)
d=min(d1,d2,d3,d4,d5)
ans[d-1]+=1
for a in ans:
print(a)
#arr=list(map(int, readline().rstrip().split()))
#n=int(readline())
#ss=readline().rstrip()
#yn(1)
return
if 'doTest' not in globals():
resolve()
sys.exit()
### ----------------
### ここまで
### ---------------- | 0 | null | 24,934,075,782,722 | 94 | 187 |
cnt = 0
for _ in range(int(input())):
a, b = map(int, input().split())
if a == b:
cnt += 1
else:
cnt = 0
if cnt > 2:
print("Yes")
quit()
print("No") | if __name__ == '__main__':
from collections import deque
n = int(input())
dic = {}
for i in range(n):
x = input().split()
if x[0] == "insert":
dic[x[1]] = 1
if x[0] == "find":
if x[1] in dic:
print('yes')
else:
print('no')
| 0 | null | 1,300,340,452,202 | 72 | 23 |
from collections import defaultdict, deque
import sys, heapq, bisect, math, itertools, string, queue, copy, time
from fractions import gcd
import numpy as np
sys.setrecursionlimit(10**8)
INF = float('inf')
MOD = 10**9+7
EPS = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())
n = int(input())
a_list = np.array(list(map(int, input().split())))
a_mx = np.maximum.accumulate(a_list)
ans = (a_mx - a_list).sum()
print(ans) | def resolve():
X, Y, A, B, C = list(map(int, input().split()))
P = sorted(list(map(int, input().split())), reverse=True)
Q = sorted(list(map(int, input().split())), reverse=True)
R = sorted(list(map(int, input().split())), reverse=True)
eatreds = P[:X]
eatgreens = Q[:Y]
import heapq
heapq.heapify(eatreds)
heapq.heapify(eatgreens)
for r in R:
smallred = heapq.heappop(eatreds)
smallgreen = heapq.heappop(eatgreens)
reddiff = r-smallred
greendiff = r-smallgreen
if reddiff < 0 and greendiff < 0:
heapq.heappush(eatreds, smallred)
heapq.heappush(eatgreens, smallgreen)
break
if reddiff > greendiff:
heapq.heappush(eatreds, r)
heapq.heappush(eatgreens, smallgreen)
else:
heapq.heappush(eatreds, smallred)
heapq.heappush(eatgreens, r)
print(sum(eatreds)+sum(eatgreens))
if __name__ == "__main__":
resolve() | 0 | null | 24,582,980,141,082 | 88 | 188 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.