code1
stringlengths 16
24.5k
| code2
stringlengths 16
24.5k
| similar
int64 0
1
| pair_id
int64 2
181,637B
⌀ | question_pair_id
float64 3.71M
180,628B
⌀ | code1_group
int64 1
299
| code2_group
int64 1
299
|
---|---|---|---|---|---|---|
import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)
INF = 10**30
M = []
w = 0
h = 0
num = 1
def solve2(p, q, r, s, ans):
global num
for i in range(p, q+1):
for j in range(r, s+1):
ans[i][j] = num
num += 1
return ans
def solve(p, q, ans):
v = []
for i in range(p, q+1):
for j in range(w):
if M[i][j] == '#':
v.append(j)
v.sort()
prev = 0
for i, b in enumerate(v):
if i == len(v)-1:
ans = solve2(p, q, prev, w-1, ans)
else:
ans = solve2(p, q, prev, b, ans)
prev = b+1
return ans
def main():
global M, h, w
h, w, k = list(map(int, input().strip().split()))
M = [0] * h
G = [False] * h
ans = [[0] * w for _ in range(h)]
total1Row = 0
for i in range(h):
M[i] = input().strip()
if '#' in M[i]:
G[i] = True
total1Row += 1
prev = 0
vc = 0
for i, v in enumerate(G):
if v and vc == total1Row-1:
ans = solve(prev, h-1, ans)
elif v:
vc += 1
ans = solve(prev, i, ans)
prev = i+1
for i in range(h):
print(" ".join(str(s) for s in ans[i]))
if __name__ == '__main__':
main()
| k,n = map(int,input().split())
lst = list(map(int,input().split()))
m = 0
for i in range(n-1):
m = max(lst[i+1]-lst[i],m)
m = max(m,k+lst[0]-lst[n-1])
print(k-m) | 0 | null | 93,899,438,888,192 | 277 | 186 |
import math , sys
N = int( input() )
A = list(map(int, input().split() ) )
def Prime(x):
ub=int(math.sqrt(x))+2
if x==2 or x==3 or x==5 or x==7:
return True
for i in range(2,ub):
if x%i==0:
return False
return True
y = N
while not Prime(y):
y+=1
def h1(x):
return x % y
def h2(x):
return 1+ x%(y-1)
def h(x,i):
return (h1(x) + i*h2(x)) % y
def insert(T,x):
i=0
while True:
j=h(x,i)
if T[j][0]== -1:
T[j][0]=x
T[j][1]=1
return j
elif x ==T[j][0]:
T[j][1]+=1
return j
else:
i+=1
def search(T,x):
i=0
while True:
j=h(x,i)
if T[j][0] == x:
return T[j][1]
elif T[j][0] == -1:
return -1
else:
i+=1
T = [[-1,0] for _ in range(y)]
for i in range(N):
insert(T , i + A[i])
ans =0
for j in range(N):
if j - A[j]>=0:
s = search(T, j - A[j])
if s >=0:
ans+=s
print(ans) | import collections
n = int(input())
a = list(map(int, input().split()))
l = []
r = []
for i in range(n):
l.append(i+a[i])
r.append(i-a[i])
count_l = collections.Counter(l)
count_r = collections.Counter(r)
ans = 0
for i in count_l:
ans += count_r.get(i,0) * count_l[i]
print(ans) | 1 | 25,952,619,416,220 | null | 157 | 157 |
import sys
#from collections import defaultdict, deque, Counter
#import bisect
#import heapq
#import math
#from itertools import accumulate
#from itertools import permutations as perm
#from itertools import combinations as comb
#from itertools import combinations_with_replacement as combr
#from fractions import gcd
#import numpy as np
stdin = sys.stdin
sys.setrecursionlimit(10 ** 7)
MIN = -10 ** 9
MOD = 10 ** 9 + 7
INF = float("inf")
IINF = 10 ** 18
def main():
#n = int(stdin.readline().rstrip())
h1,m1,h2,m2,k = map(int, stdin.readline().rstrip().split())
#l = list(map(int, stdin.readline().rstrip().split()))
#numbers = [[int(c) for c in l.strip().split()] for l in sys.stdin]
#word = [stdin.readline().rstrip() for _ in range(n)]
#number = [[int(c) for c in stdin.readline().rstrip()] for _ in range(n)]
#zeros = [[0] * w for i in range(h)]
wake = (h2-h1)*60 + m2-m1
ans = wake - k
print(ans)
main()
| a,b,c,d = (int(x) for x in input().split())
ans = max(a*c,a*d,b*c,b*d)
print(ans) | 0 | null | 10,595,867,486,720 | 139 | 77 |
n, a, b = map(int, input().split())
ans = pow(2,n,10**9+7)-1
A = 1
for i in range(1,a+1):
A = (A*(n-i+1))%(10**9+7)
x = pow(i,10**9+5,10**9+7)
A *= x
B = 1
for i in range(1,b+1):
B = (B*(n-i+1))%(10**9+7)
y = pow(i,10**9+5,10**9+7)
B *= y
ans = ans-A-B
if ans < 0:
ans = ans+10**9+7
ans = int(ans%(10**9+7))
print(ans) | D = 100000
N = int(raw_input())
for i in xrange(N):
D += D/20
if D % 1000 > 0:
D += 1000-D%1000
print D | 0 | null | 32,959,376,633,702 | 214 | 6 |
n=int(input())
l = [int(x) for x in input().split(' ')]
c=0
for i in range(0,len(l),2):
if((i+1)%2!=0 and l[i]%2!=0):
c+=1
print(c) | n = int(input())
a = list(map(int, input().split()))
ans = 0
for i, v in enumerate(a, 1):
if i % 2 == 1 and v % 2 == 1:
ans += 1
print(ans)
| 1 | 7,777,764,302,938 | null | 105 | 105 |
import sys
S = input()
if not ( S == 'ABC' or S == 'ARC' ): sys.exit()
print('ABC') if S == 'ARC' else print('ARC') | a = str(input())
if a == 'ABC':
print('ARC')
else:
print('ABC')
| 1 | 24,059,054,964,362 | null | 153 | 153 |
S = input()
mod = 2019
array = []
for i in range(len(S)):
x = (int(S[len(S)-1-i])*pow(10,i,mod))%mod
array.append(x)
array2 = [0]
y = 0
for i in range(len(S)):
y = (y+array[i])%mod
array2.append(y)
array3 = [0] * 2019
ans = 0
for i in range(len(array2)):
z = array2[i]
ans += array3[z]
array3[z] += 1
print(ans)
#3*673
| MOD = 2019
def solve(S):
N = len(S)
dp = [0 for _ in range(MOD)]
tmp = 0
ret = 0
for i in range(N - 1, -1, -1):
m = (tmp + int(S[i]) * pow(10, N - i - 1, MOD)) % MOD
ret += dp[m]
dp[m] += 1
tmp = m
ret += dp[0]
return ret
if __name__ == "__main__":
S = input()
print(solve(S)) | 1 | 30,698,294,077,320 | null | 166 | 166 |
S = input()
T = input()
print('Yes') if T[:len(S)] == S else print('No') | s=input()
t=input()
print(["No","Yes"][t[:-1]==s]) | 1 | 21,567,218,634,850 | null | 147 | 147 |
while True:
H, W = [int(x) for x in input().split()]
if H == W == 0:
break
for i in range(H):
if i == 0 or i == H - 1:
print('#'*W)
else:
print(''.join(['#' if c == 0 or c == W - 1 else '.' for c in range(W)]))
print() | import sys
import numpy as np
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# ----------------------------------------------
aa = str(input())
#print(aa)
tar = ord(aa)
if (tar <= 91):
print('A')
else:
print('a')
| 0 | null | 6,095,863,969,650 | 50 | 119 |
N,M = map(int,input().split())
H = list(map(int,input().split()))
bad = []
for i in range(M):
A,B = map(int,input().split())
if H[A-1] > H[B-1]:
bad.append(B-1)
elif H[A-1] < H[B-1]:
bad.append(A-1)
else:
bad.append(A-1)
bad.append(B-1)
print(N-len(set(bad))) | def main():
n,m = map(int,input().split())
a = [int(i) for i in input().split()]
Sum = sum(a)
if n<Sum:
print('-1')
else:
print(n-Sum)
main()
| 0 | null | 28,492,369,590,958 | 155 | 168 |
# ABC156 D
n,a,b=map(int,input().split())
p=10**9+7
def nCr_init(L,p):
for i in range(L+1):
if i<=1:
inv[i]=1
else:
inv[i]=(p-inv[p%i]*(p//i))%p
def pow_k(x,n,p=10**9+7):
if n==0:
return 1
K=1
while n>1:
if n%2!=0:
K=(K*x)%p
x=(x*x)%p
n//=2
return (K*x)%p
nck=[0]*(b+10)
inv=[1]*(b+15)
nck[0]=1
nCr_init(b+10,p)
for i in range(b+5):
nck[i+1]=(nck[i]*(n-i)*inv[i+1])%p
print((pow_k(2,n,p)-nck[a]-nck[b]-1)%p) | n, q = [ int( val ) for val in raw_input( ).split( " " ) ]
ps = [0]*n
t = [0]*n
for i in range( n ):
ps[i], t[i] = raw_input( ).split( " " )
qsum = 0
while t:
psi = ps.pop( 0 )
ti = int( t.pop( 0 ) )
if ti <= q:
qsum += ti
print( "{:s} {:d}".format( psi, qsum ) )
else:
t.append( ti - q )
ps.append( psi )
qsum += q | 0 | null | 33,197,178,112,510 | 214 | 19 |
X,k,d = map(int,input().split())
x = abs(X)
if x >= k*d:
print(x - d*k)
else:
e = x//d
k -= e
x %= d
if k % 2 == 0:
print(x)
else:
print(d-x)
| x,k,d=map(int,input().split());xx=abs(x)
tmp=xx;tmp=(xx//d);cc=min(tmp,k)
xx-=d*cc;k-=cc;k&=1;xx-=d*k
print(abs(xx)) | 1 | 5,229,907,167,082 | null | 92 | 92 |
import math
n= int(input())
x=n+1
for i in range(2,int(math.sqrt(n)+1)):
if n%i==0:
x= i+ (n/i)
print(int(x)-2) | import math
from decimal import *
def cnt_prime(p, n):
div = Decimal(str(n))
s = 0
while True:
div /= p
if div < 1:
break
if p == 2:
s += int(div.quantize(Decimal('0.0'), rounding=ROUND_FLOOR))
else:
s += int(div.quantize(Decimal('0.0'), rounding=ROUND_FLOOR)) // 2
return s
N = int(input())
if N % 2 == 1:
print(0)
else:
print(min(cnt_prime(2, N), cnt_prime(5, N))) | 0 | null | 138,964,622,505,380 | 288 | 258 |
n = int(input())
S = [c for c in input()]
ans = 0
i = 0
j = n-1
while i < j:
if S[i] == "W":
if S[j] == "R":
S[i] = "R"
S[j] = "W"
j -= 1
i += 1
ans += 1
else:
j -= 1
else:
i += 1
print(ans) | #ciが R のとき赤、W のとき白です。
#入力
#N
#c1...cN
N = int(input())
C = input()
Rednum = C.count('R')
#print(Rednum)
#Rの数 - 左にある赤の数が答
NewC = C[:Rednum]
#print(NewC)
Whinum = NewC.count('R')
print(Rednum - Whinum)
| 1 | 6,301,988,684,332 | null | 98 | 98 |
import sys
sys.setrecursionlimit(10**9)
k=int(input())
def dfs(keta,num):
lunlun.append(int(num))
if keta==10:
return
min_v=max(0,int(num[-1])-1)
max_v=min(9,int(num[-1])+1)
for i in range(min_v,max_v+1):
dfs(keta+1,num+str(i))
lunlun=[]
for i in range(1,10):
dfs(0,str(i))
lunlun.sort()
print(lunlun[k-1]) | s=input()
ans=(6-(["MON","TUE","WED","THU","FRI","SAT","SUN"].index(s)))
if ans==0:
print(7)
else:
print(ans) | 0 | null | 86,474,684,605,848 | 181 | 270 |
N=int(input())
L=list(map(int,input().split()))
s=0
R=list()
for i in range(N):
s=s^L[i]
for i in range(N):
R.append(str(s^L[i]))
print(" ".join(R)) | N = int(input())
P = 0
A = list(map(int,input().split()))
for i in range(N):
P = P ^ A[i]
ans = [A[i] ^ P for i in range(N)]
print(" ".join(map(str,ans))) | 1 | 12,406,274,327,612 | null | 123 | 123 |
N,K = map(int,input().split())
H = list(map(int,input().split()))
res = 0
for i in range(N):
if H[i]>=K:
res += 1
print(res) | N, K = map(int, input().split())
H = list(map(int, input().split()))
print(len(list(filter(lambda x: x >= K, H)))) | 1 | 179,109,999,708,520 | null | 298 | 298 |
s,t,a,b,u=open(0).read().split()
if s==u:
print(int(a)-1,b)
elif t==u:
print(a,int(b)-1) | a,b = map(str, input().split())
a2 = a*int(b)
b2 = b*int(a)
print(a2) if a2 < b2 else print(b2)
| 0 | null | 78,391,734,452,668 | 220 | 232 |
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
def resolve():
n,T=map(int,input().split())
AB=[tuple(map(int,input().split())) for _ in range(n)]
AB.sort()
dp=[0]*T
ans=0
for a,b in AB:
ndp=dp[:]
for t in range(T):
if(t+a<T):
ndp[t+a]=max(ndp[t+a],dp[t]+b)
else:
ans=max(ans,dp[t]+b)
dp=ndp
print(ans)
resolve() | N, T = map(int, input().split())
A, B = zip(*[tuple(map(int, input().split())) for _ in range(N)])
dp1 = [[0]*(T) for _ in range(N+1)]
dp2 = [[0]*(T) for _ in range(N+2)]
for i in range(N):
for j in range(T):
dp1[i+1][j] = max(dp1[i][j], dp1[i][j-A[i]]+B[i]) if j-A[i]>=0 else dp1[i][j]
for i in range(N, 0, -1):
for j in range(T):
dp2[i][j] = max(dp2[i+1][j], dp2[i+1][j-A[i-1]]+B[i-1]) if j-A[i-1]>=0 else dp2[i+1][j]
ans = -1
for i in range(1, N+1):
for j in range(T):
ans = max(ans, dp1[i-1][j]+dp2[i+1][T-j-1]+B[i-1])
print(ans) | 1 | 151,664,014,853,622 | null | 282 | 282 |
def main():
h,n=map(int,input().split())
dp=[10**9]*(h+1)
dp[h]=0
for i in range(n):
a,b=map(int,input().split())
for j in range(h,0,-1):
nxt=j-a
if nxt<0:
nxt=0
if dp[nxt]>dp[j]+b:
dp[nxt]=dp[j]+b
print(dp[0])
main() | from collections import defaultdict
def mod_inv(a, m):
return pow(a, m-2, m)
def combination(a, b):
if b > a - b:
return combination(a, a - b)
ans = fact[a] * ifact[b] * ifact[a-b]
return ans
MOD = 10**9+7
n, k = map(int, input().split())
k = min(k, n-1)
fact = defaultdict(int)
fact[0] = 1
for i in range(1, n+1):
fact[i] = fact[i-1] * i
fact[i] %= MOD
ifact = defaultdict(int)
ifact[n] = mod_inv(fact[n], MOD)
for i in reversed(range(1, n + 1)):
ifact[i-1] = ifact[i] * i
ifact[i-1] %= MOD
ans = 0
for i in range(k+1):
ans += combination(n, i) * combination((n-i-1)+i, i)
ans %= MOD
print(ans % MOD)
| 0 | null | 74,527,418,123,072 | 229 | 215 |
N=int(input())
A=list(map(int,input().split()))
total=sum(A)
cost=total
cumulative=0
for i in range(N):
cumulative+=A[i]
cost=min(cost,abs(cumulative-(total-cumulative)))
print(cost) | n = int(input())
a = list(map(int, input().split())) # 横入力
x = [0]
aaa = 0
for i in range(n):
aaa += a[i]
x.append(aaa)
aa = sum(a)
y = [aa]
for i in range(n):
aa -= a[i]
y.append(aa)
ans = 202020202020
for i in range(n+1):
ans = min(ans, abs(x[i] - y[i]))
print(ans) | 1 | 141,823,835,159,580 | null | 276 | 276 |
digits = [int(i) for i in list(input())]
Sum = 0
for i in digits:
Sum += i
if Sum%9 == 0:
print("Yes")
else:
print("No") | print("Yes" if int(input())%9 == 0 else "No") | 1 | 4,370,216,430,732 | null | 87 | 87 |
import math
a, b, x = [int(w) for w in input().split()]
if x > a * a * b / 2:
rad = math.atan(2*(a ** 2 * b - x) / a ** 3)
else:
rad = math.atan((a * b ** 2) / (2 * x))
print(math.degrees(rad))
| abef=0
bbef=1
s=input()
for i in range(len(s)):
curr=int(s[len(s)-1-i])
a=abef+curr
b=bbef+9-curr
a=min(a,1+bbef+curr)
b=min(b,abef+10-curr)
abef=a
bbef=b
curr=0
a=abef+curr
b=bbef+9-curr
a=min(a,1+bbef+curr)
b=min(b,abef+10-curr)
print(min(a,b)) | 0 | null | 116,569,594,734,820 | 289 | 219 |
from functools import lru_cache
import sys
sys.setrecursionlimit(10 ** 8)
h,n=map(int,input().split())
ab=[tuple(map(int,input().split())) for _ in range(n)]
ab.sort(key=lambda abi:(abi[1]/abi[0],abi[0]))
@lru_cache(maxsize=None)
def dp(i):
if i<=0:
return 0
else:
ans=float('inf')
for a,b in ab:
val=b+dp(i-a)
if val<ans:
ans=val
else:
break
return ans
print(dp(h)) | if __name__ == "__main__":
n = int(input())
S = list(map(int, input().split()))
q = int(input())
T = list(map(int, input().split()))
ans = 0
for i in T:
if i in S:
ans += 1
print(ans) | 0 | null | 40,683,546,462,286 | 229 | 22 |
from _collections import deque
n = int(input())
data_input = []
dlList = deque()
for i in range(n):
x = input().split()
if x[0] == 'insert':
dlList.appendleft(x[1])
elif x[0] == 'delete':
if x[1] in dlList:
dlList.remove(x[1])
else :
pass
elif x[0] == 'deleteFirst':
dlList.popleft()
elif x[0] == 'deleteLast':
dlList.pop()
else:
pass
print(' '.join(dlList)) | from collections import deque
def print_list(que):
for i, q in enumerate(que):
if i != len(que)-1:
print(q, end=' ')
else:
print(q)
def main():
List = deque()
n = int(input())
for i in range(n):
order = input().split()
if order[0] == "insert":
List.appendleft(order[1])
elif order[0] == "delete":
try:
List.remove(order[1])
except ValueError:
pass
elif order[0] == "deleteFirst":
List.popleft()
elif order[0] == "deleteLast":
List.pop()
print_list(List)
if __name__ == "__main__":
main()
| 1 | 50,701,079,360 | null | 20 | 20 |
def DICE(dice,dir):
if dir == "N":
dice[0],dice[1],dice[4],dice[5] = dice[1],dice[5],dice[0],dice[4]
elif dir == "S":
dice[0],dice[1],dice[4],dice[5] = dice[4],dice[0],dice[5],dice[1]
elif dir == "E":
dice[0],dice[2],dice[3],dice[5] = dice[3],dice[0],dice[5],dice[2]
elif dir == "W":
dice[0],dice[2],dice[3],dice[5] = dice[2],dice[5],dice[0],dice[3]
return dice
tmp = raw_input().split()
s = raw_input()
for i in s:
tmp = DICE(tmp, i)
print tmp[0]
| from typing import List
class Dice:
def __init__(self, surface: List[int]):
self.surface = surface
def get_upper_sursurface(self) -> int:
return self.surface[0]
def invoke_method(self, mkey: str) -> None:
if mkey == 'S':
self.S()
return None
if mkey == 'N':
self.N()
return None
if mkey == 'E':
self.E()
return None
if mkey == 'W':
self.W()
return None
raise ValueError(f'This method does not exist. : {mkey}')
def S(self) -> None:
tmp = [i for i in self.surface]
self.surface[0] = tmp[4]
self.surface[1] = tmp[0]
self.surface[2] = tmp[2]
self.surface[3] = tmp[3]
self.surface[4] = tmp[5]
self.surface[5] = tmp[1]
def N(self) -> None:
tmp = [i for i in self.surface]
self.surface[0] = tmp[1]
self.surface[1] = tmp[5]
self.surface[2] = tmp[2]
self.surface[3] = tmp[3]
self.surface[4] = tmp[0]
self.surface[5] = tmp[4]
def E(self) -> None:
tmp = [i for i in self.surface]
self.surface[0] = tmp[3]
self.surface[1] = tmp[1]
self.surface[2] = tmp[0]
self.surface[3] = tmp[5]
self.surface[4] = tmp[4]
self.surface[5] = tmp[2]
def W(self) -> None:
tmp = [i for i in self.surface]
self.surface[0] = tmp[2]
self.surface[1] = tmp[1]
self.surface[2] = tmp[5]
self.surface[3] = tmp[0]
self.surface[4] = tmp[4]
self.surface[5] = tmp[3]
# 提出用
data = [int(i) for i in input().split()]
order = list(input())
# # 動作確認用
# data = [int(i) for i in '1 2 4 8 16 32'.split()]
# order = list('EESWN')
dice = Dice(data)
for o in order:
dice.invoke_method(o)
print(dice.get_upper_sursurface())
| 1 | 229,516,225,990 | null | 33 | 33 |
n=int(input())
if 30<=n :
print('Yes')
else:
print('No') | X=input()
X=int(X)
if X >= 30:
print('Yes')
else:
print('No') | 1 | 5,704,241,025,362 | null | 95 | 95 |
A,B = map(int,input().split())
C,D = map(int,input().split())
if C - A == 1:
print(1)
else:
print(0) | x,y=list(map(int, input().split()))
x,y=list(map(int, input().split()))
if y==1:
print(1)
else:
print(0) | 1 | 124,429,007,058,080 | null | 264 | 264 |
n=int(input())
while n>0:
n-=1000
print(abs(n)) | s = input()
ans = 0
for i in range(3):
if s[i] == "R":
ans = 1
for i in range(2):
if s[i:i+2] == "RR":
ans = 2
if s == "RRR":
ans = 3
print(ans)
| 0 | null | 6,618,401,520,518 | 108 | 90 |
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)
N, X, mod = mapint()
doubling = [[i*i%mod for i in range(mod)]]
accu = [doubling[0][:]]
for i in range(40):
tmp1 = [None]*mod
tmp2 = [None]*mod
for j in range(mod):
tmp1[j] = doubling[-1][doubling[-1][j]]
tmp2[j] = accu[-1][doubling[-1][j]] + accu[-1][j]
doubling.append(tmp1)
accu.append(tmp2)
now = X
ans = X
for i in range(40):
if (N-1)>>i&1:
ans += accu[i][now]
now = doubling[i][now]
print(ans) | N = int(input())
S = input()
ans = 0
for i in range(1000):
res = str(i).zfill(3)
cnt = 0
p = res[cnt]
for s in S:
if p == s:
cnt += 1
if cnt == 3:
ans += 1
break
p = res[cnt]
print(ans) | 0 | null | 65,508,882,783,168 | 75 | 267 |
a = [int(x) for x in input()[::-1]] + [0]
n = len(a)
dp = [[0] * 2 for _ in range(n)]
dp[0][0], dp[0][1] = a[0], 10-a[0]
for i in range(n-1):
dp[i+1][0] = min(a[i+1]+dp[i][0], a[i+1]+dp[i][1]+1)
dp[i+1][1] = min(10-a[i+1]+dp[i][0], 10-(a[i+1]+1)+dp[i][1])
print(min(dp[n-1]))
| from collections import deque
n,limit = map(int,input().split())
total_time = 0
queue = deque()
for _ in range(n):
p,t = input().split()
queue.append([p,int(t)])
while len(queue) > 0:
head = queue.popleft()
if head[1] <= limit:
total_time += head[1]
print('{} {}'.format(head[0],total_time))
else:
head[1] -= limit
total_time += limit
queue.append(head)
| 0 | null | 35,595,995,013,828 | 219 | 19 |
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") | import math
from functools import reduce
"""[summary]
全体:10^N
0が含まれない:9^N
9が含まれない:9^N
0,9の両方が含まれない:8^N
0,9のどちらか一方が含まれない:9^N + 9^N - 8^N
"""
N = int(input())
mod = (10 ** 9) + 7
calc = (10**N - 9**N - 9**N + 8**N) % mod
print(calc) | 0 | null | 24,769,324,711,510 | 190 | 78 |
s = input()
l = 0
r = len(s)-1
c = 0
while l <= r:
if s[l] != s[r]:
c += 1
l += 1
r -=1
print(c) | # Nとcの定義
N = int(input())
C = input()
# 赤色の個数
red_num = str.count(C, "R")
# 左からred_num個までに含まれる白色の個数
white_num_left = str.count(C[:red_num], "W")
# 最小の操作回数
min_ope = white_num_left
# 最小の操作回数の出力
print(min_ope) | 0 | null | 62,949,643,762,128 | 261 | 98 |
from itertools import product
N = int(input())
G = {i:[] for i in range(1,N+1)}
for i in range(1,N+1):
a = int(input())
G[i] = [list(map(int,input().split())) for _ in range(a)]
cmax = 0
for z in product((0,1),repeat=N+1):
if z[0]==0:
X = []
for i in range(1,N+1):
if z[i]==1:
X.append(i)
A = []
B = []
for i in X:
for x,y in G[i]:
if y==1:
A.append(x)
else:
B.append(x)
flag = 0
for a in A:
if a not in X:
flag = 1
break
for b in B:
if b in X:
flag = 1
break
if flag==0:
cmax = max(cmax,sum(z[1:]))
print(cmax) | n = int(input())
XY = []
for i in range(n):
a = int(input())
xy = []
for j in range(a):
x, y = map(int, input().split())
xy.append([x, y])
XY.append(xy)
ans = 0
for i in range(2 ** n):
s = [0] * n
cnt = 0
case = True
for j in range(n):
if (i >> j) & 1:
s[j] = 1
cnt += 1
for k in range(n):
if s[k] == 1:
for l in range(len(XY[k])):
if s[XY[k][l][0] - 1] != XY[k][l][1]:
case = False
if case is True:
ans = max(ans, cnt)
print(ans)
| 1 | 121,049,766,471,600 | null | 262 | 262 |
# coding: UTF-8
import sys
import numpy as np
n = int(input())
ans = (n // 500) * 1000
n -= (n // 500) * 500
ans += (n // 5) * 5
print(ans)
| k=int(input())
count=1
num=7
for _ in range(k):
if num%k == 0:
print(count)
break
else:
count += 1
num = (num % k)*10 + 7
else:
print(-1) | 0 | null | 24,522,698,585,952 | 185 | 97 |
while 1:
h,w=map(int,raw_input().split())
if h==w==0:break
else:
for i in range(h):
print '#'*w
print'' | def paint(h, w):
print("\n".join(["#" * w] * h))
while True:
H, W = map(int, input().split())
if H == W == 0: break
paint(H, W)
print()
| 1 | 768,814,090,550 | null | 49 | 49 |
input()
s=set(input().split())
print(int(input())-len(set(input().split())-s))
| def main():
n = int(input())
S = list(map(int, input().split()))
q = int(input())
T = list(map(int, input().split()))
res = 0
for i in T:
if i in S:
res += 1
print(res)
if __name__ == '__main__':
main()
| 1 | 66,094,855,226 | null | 22 | 22 |
n = int(input())
buf = list(map(int,input().split()))
a = []
for i in range(n):
a.append([buf[i],i])
a = sorted(a,reverse=True)
dp = [[0]*(n+1) for i in range(n+1)]
for i in range(n):
for j in range(n-i):
cur = i+j
temp1 = dp[i][j]+a[cur][0]*abs(n-1-a[cur][1]-j)
temp2 = dp[i][j]+a[cur][0]*abs(a[cur][1]-i)
dp[i+1][j] = max(dp[i+1][j],temp2)
dp[i][j+1] = max(dp[i][j+1],temp1)
print(max([max(i) for i in dp])) | N = int(input())
A = list(map(int, input().split()))
p = list(range(N))
p.sort(key=lambda i: A[i], reverse=True)
dp = [[0]*(N + 1) for _ in range(N + 1)]
for i in range(N):
for j in range(i + 1):
pi = p[i]
dp[i+1][j] = max(dp[i+1][j], dp[i][j] + A[pi]*(N - i + j - 1 - pi))
dp[i+1][j+1] = dp[i][j] + A[pi]*(pi - j)
print(max(dp[N]))
| 1 | 33,761,686,622,440 | null | 171 | 171 |
import sys
input = sys.stdin.readline
def main():
N = int( input())
S = [input().strip() for _ in range(N)]
Up = []
Down = []
for s in S:
now = 0
m = 0
for t in s:
if t == "(":
now += 1
else:
now -= 1
if now < m:
m = now
# print(t, now)
if now >= 0:
Up.append((m,now))
else:
Down.append((m-now,-now))
up = 0
Up.sort(reverse=True)
for m, inc in Up:
if up+m < 0:
print("No")
return
up += inc
down = 0
Down.sort(reverse=True)
# print(Up, Down)
for m, dec in Down:
if down+m < 0:
print("No")
return
down += dec
if up != down:
print("No")
return
print("Yes")
if __name__ == '__main__':
main()
| n,m = map(int,input().split())
a = [1]*(n+1)
b = [0]*(n+1)
for i in range(m):
x,y = map(int,input().split())
u = x
while a[u]==0:
u = b[u]
v = y
while a[v]==0:
v = b[v]
if u!=v:
b[v] = u
b[y] = u
b[x] = u
a[u] += a[v]
a[v] = 0
print(max(a)) | 0 | null | 13,924,149,877,028 | 152 | 84 |
import sys
sys.setrecursionlimit(10**9)
def main():
N,K = map(int,input().split())
A = [0] + sorted(list(map(int,input().split())))
MOD = 10**9+7
def get_fact(maxim,mod):
maxim += 1
fact = [0]*maxim
fact[0] = 1
for i in range(1,maxim):
fact[i] = fact[i-1] * i % mod
invfact = [0]*maxim
invfact[maxim-1] = pow(fact[maxim-1],mod-2,mod)
for i in reversed(range(maxim-1)):
invfact[i] = invfact[i+1] * (i+1) % mod
return fact, invfact
def powerful_comb(n,r,mod,fact,invfact):
if n < 0 or n < r: return 0
return fact[n] * invfact[r] * invfact[n-r] % mod
ans = 0
fact,invfact = get_fact(N,MOD)
for i in range(K,N+1):
ans += ((A[i]-A[N-i+1]) * powerful_comb(i-1,K-1,MOD,fact,invfact)) % MOD
print(ans % MOD)
# print(A)
if __name__ == "__main__":
main() |
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
# prepare combs upto 10000
mod = 10**9 + 7
facts = [1] * 100001
for i in range(0, 100000):
facts[i+1] = facts[i] * (i + 1) % mod
ifacts = [1] * 100001
ifacts[100000] = pow(facts[100000], mod - 2, mod)
for i in range(100000, 0, -1):
ifacts[i-1] = ifacts[i] * i % mod
def comb(n, k):
return facts[n] * ifacts[n-k] % mod * ifacts[k] % mod
ans = 0
for i in range(k-1, n):
# take k-1 from i
ans = (ans + a[i] * comb(i, k-1)) % mod
for i in range(0, n-k+1):
# take k-1 from n-i-1
ans = (ans - a[i] * comb(n-i-1, k-1)) % mod
print(ans) | 1 | 95,878,626,826,758 | null | 242 | 242 |
import sys
array_data = map(int, raw_input().split())
n = array_data[0]
m = array_data[1]
l = array_data[2]
a = []
for i in range(n):
partial_a = map(int, raw_input().split())
a.append(partial_a)
b = []
for j in range(m):
partial_b = map(int, raw_input().split())
b.append(partial_b)
c = []
for i in range(n):
c.append([])
for j in range(l):
c[i].append([])
wa = 0
for k in range(m):
wa += a[i][k] * b[k][j]
c[i][j] = wa
for i in range(len(c)):
for j in range(len(c[i])):
if j != len(c[i])-1:
sys.stdout.write("{:} ".format(c[i][j]))
else:
print(c[i][j]) | import sys
n, m, l = [ int( val ) for val in sys.stdin.readline().split( " " ) ]
matrixA = [ [ int( val ) for val in sys.stdin.readline().split( " " ) ] for row in range( n ) ]
matrixB = [ [ int( val ) for val in sys.stdin.readline().split( " " ) ] for row in range( m ) ]
matrixC = [ [ sum( matrixA[i][k] * matrixB[k][j] for k in range( m ) ) for j in range( l ) ] for i in range( n ) ]
for i in range( n ):
print( " ".join( map( str, matrixC[i] ) ) ) | 1 | 1,434,076,713,342 | null | 60 | 60 |
class Stack:
def __init__(self, n):
self.A = [0 for i in range(n)]
self.len = n
self.top = 0
def is_empty(self):
return self.top == 0
def is_full(self):
return self.top == self.len - 1
def push(self, x):
if not self.is_full():
self.top += 1
self.A[self.top] = x
def pop(self):
if not self.is_empty():
x = self.A[self.top]
self.top -= 1
return x
def top_element(self):
if not self.is_empty():
return self.A[self.top]
if __name__ == '__main__':
S1 = Stack(20005) # for \
S2 = Stack(10005) # for ponds
line = raw_input()
for i in range(len(line)):
if line[i] == '\\':
S1.push(i)
elif line[i] == '/':
if S1.is_empty():
continue
j = S1.pop()
cnt = 0 # total area of ponds that can be merged
# no more ponds can be merged if S2.top_element()[0] < j, why?
# because '/' is clearly increasing toward the stack top
# and '\' is increasing toward the stack top, too
# if not, there exists a pond that should have been merged
while not S2.is_empty() and S2.top_element()[0] > j:
cnt += S2.pop()[1]
S2.push((j, cnt + i - j))
else:
pass
l = []
cnt = 0
while not S2.is_empty():
x = S2.pop()
cnt += x[1]
l.append(x)
l.reverse()
print cnt
print len(l),
for x in l:
print x[1],
print
| N, K = [int(a) for a in input().split()]
num_count = (N-N%K)//K
ans = min(abs(N - num_count*K), abs(N - (num_count+1)*K))
if num_count > 0:
ans = min(abs(N - (num_count-1)*K), ans)
print(ans) | 0 | null | 19,596,534,522,150 | 21 | 180 |
A=[]
for _ in range(3):
A.append(list(map(int,input().split())))
n=int(input())
B=[]
for _ in range(n):
B.append(int(input()))
def get_unique_list(seq):
seen = []
return [x for x in seq if x not in seen and not seen.append(x)]
B=get_unique_list(B)
s=0
if A[0][0] in B and A[1][1] in B and A[2][2] in B:
s+=1
elif A[0][2] in B and A[1][1] in B and A[2][0] in B:
s+=1
else:
for i in range(3):
if A[0][i] in B and A[1][i] in B and A[2][i] in B:
s+=1
elif A[i][0] in B and A[i][1] in B and A[i][2] in B:
s+=1
if s>=1:
print("Yes")
else:
print("No")
| def LIHW(h):
return [list(map(int, input().split())) for _ in range(h)]
def LIH(h):
return [int(input()) for _ in range(h)]
card = LIHW(3)
N = int(input())
num = LIH(N)
bingo = [[0, 0, 0] for _ in range(3)]
for i in num:
for a in range(3):
for b in range(3):
if i == card[a][b]:
bingo[a][b] = 1
break
ans = "No"
for i in range(3):
if bingo[i][0] == 1 and bingo[i][1] == 1 and bingo[i][2] == 1:
ans = "Yes"
for i in range(3):
if bingo[0][i] == 1 and bingo[1][i] == 1 and bingo[2][i] == 1:
ans = "Yes"
if bingo[0][0] == 1 and bingo[1][1] == 1 and bingo[2][2] == 1:
ans = "Yes"
if bingo[0][2] == 1 and bingo[1][1] == 1 and bingo[2][0] == 1:
ans = "Yes"
print(ans)
| 1 | 59,836,279,649,640 | null | 207 | 207 |
n=int(input())
arr1=[]
arr2=[]
for _ in range(n):
s=input()
cnt1=0
cnt2=0
for i in range(len(s)):
if s[i]=='(':
cnt1+=1
else:
if cnt1==0:
cnt2+=1
else:
cnt1-=1
if cnt1-cnt2>=0:
arr1.append([cnt1,cnt2])
else:
arr2.append([cnt1,cnt2])
arr1=sorted(arr1,key=lambda x:x[1])
arr2=sorted(arr2,reverse=True,key=lambda x:x[0])
arr=arr1+arr2
cnt=0
for a,b in arr:
if b>cnt:
print('No')
break
else:
cnt+=a-b
else:
if cnt==0:
print('Yes')
else:
print('No') | Flag = True
data = []
while Flag:
H, W = map(int, input().split())
if H == 0 and W == 0:
Flag = False
else:
data.append((H, W))
#print(data)
for (H, W) in data:
for i in range(H):
print('#' * W)
print('\n', end="")
| 0 | null | 12,117,204,569,922 | 152 | 49 |
#ライブラリインポート
from collections import defaultdict
con = 10 ** 9 + 7
#入力受け取り
def getlist():
return list(map(int, input().split()))
#処理内容
def main():
N, K, C = getlist()
S = list(input())
D1 = defaultdict(int)
D2 = defaultdict(int)
var = - float("inf")
cnt = 0
for i in range(N):
if S[i] == "o":
if i - var >= C + 1:
cnt += 1
var = i
D1[i] += 1
if cnt >= K + 1:
return
#詰める
var = float("inf")
cnt = 0
for i in range(N):
if S[N - 1 - i] == "o":
if var - (N - 1 - i) >= C + 1:
cnt += 1
var = N - 1 - i
D2[N - 1 - i] += 1
# print(D1)
# print(D2)
ans = []
for i in D1:
if D2[i] == 1:
ans.append(i)
ans = sorted(ans)
for i in ans:
print(i + 1)
if __name__ == '__main__':
main() | h = int(input())
w = int(input())
n = int(input())
all_cell = 0
count = 0
while all_cell < n:
if h > w:
all_cell += h
w -= 1
else:
all_cell += w
h -= 1
count += 1
print(count) | 0 | null | 64,741,478,658,350 | 182 | 236 |
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from math import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect
import heapq
#
#
#
# pythonで無理なときは、pypyでやると正解するかも!!
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
INF = float('inf')
from sys import stdin
readline = stdin.readline
def readInts():
return list(map(int,readline().split()))
def readTuples():
return tuple(map(int,readline().split()))
def I():
return int(readline())
n,x,m = readInts()
lis = []
prv = None
dic = defaultdict(int)
for i in range(m):
if i == 0:
A = x%m
lis.append(A)
dic[A] = 1
else:
A = (A*A)%m
if dic[A]:
prv = A
break
else:
dic[A] = 1
lis.append(A)
cnt = None
for i in range(len(lis)):
if lis[i] == prv:
cnt = i
break
if cnt == None:
cnt = len(lis)
front_arr = lis[:cnt]
loop_arr = lis[cnt:]
if x == 0:
print(0)
exit()
len_loop_arr = len(loop_arr)
if n < cnt:
ans = sum(front_arr[:n])
else:
ans = sum(front_arr)
sum_loop_arr = sum(loop_arr)
n -= cnt
loop = n//len_loop_arr
rest = n - (loop*len_loop_arr)
mid = loop * sum_loop_arr
ans += mid
ans += sum(loop_arr[:rest])
print(ans)
| # -*- coding: utf-8 -*-
l = input()
S1, S2 = [], []
sum = 0
n = len(l)
for i in range(n):
if l[i] == "\\":
S1.append(i)
elif l[i] == "/" and S1:
j = S1.pop()
a = i - j
sum += a
while S2 and S2[-1][0] > j:
a += S2.pop()[1]
S2.append([j, a])
print(sum)
print(len(S2), *(a for j, a in S2)) | 0 | null | 1,449,094,348,948 | 75 | 21 |
from sys import exit
n, K = map(int, input().split())
A = list(map(lambda x: int(x) - 1, input().split()))
done = [-1 for _ in range(n)]
tmp = 0
done[0] = 0
for k in range(1, K + 1):
tmp = A[tmp]
if done[tmp] >= 0:
for i in range((K - done[tmp]) % (k - done[tmp])):
tmp = A[tmp]
print(tmp + 1)
exit()
else:
done[tmp] = k
print(tmp + 1)
| #!/usr/bin/env python3
def main():
N, K = map(int, input().split())
A = [int(x) - 1 for x in input().split()]
way = []
seen = [False for _ in [0] * (2 * 10 ** 5 + 1)]
now = 0
for _ in range(K):
if seen[now]:
loop_start = way.index(now)
loop = way[loop_start:]
K -= len(way[:loop_start])
now = loop[K % len(loop)]
break
way.append(now)
seen[now] = True
now = A[now]
print(now + 1)
if __name__ == '__main__':
main()
| 1 | 22,805,560,846,808 | null | 150 | 150 |
import sys, bisect, math, itertools, string, queue, copy
import numpy as np
import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
from fractions import gcd
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])
x = inp()
if x < 600:
ans = 8
elif x < 800:
ans = 7
elif x < 1000:
ans = 6
elif x < 1200:
ans = 5
elif x < 1400:
ans = 4
elif x < 1600:
ans = 3
elif x < 1800:
ans = 2
elif x < 2000:
ans = 1
print(ans) | N, M = map(int, input().split())
S = input()
if N <= M:
print(N)
exit()
if '1'*M in S:
print(-1)
exit()
from collections import deque
count = deque([])
for k in range(M+1):
if S[k] == '1':
count.append(-1)
else:
count.append(k)
sgn = deque([])
k = 0
while k < N:
k += 1
if S[k] == '0':
sgn.append(M)
else:
d = 0
while k < N:
if S[k] == '1':
k += 1
d += 1
continue
else:
break
while d > 0:
sgn.append(M-d)
d -= 1
sgn.append(M)
now = M
while now < N:
now += 1
a = sgn.popleft()
if S[now] == '1':
count.append(-1)
else:
count.append(a)
count = list(count)
c = 0
ans = ''
while c < N:
ans = str(count[-1-c]) + ' ' + ans
c += count[-1-c]
print(ans) | 0 | null | 72,610,488,728,998 | 100 | 274 |
K, N = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
ans = 0
del_A = []
for i in range(N):
if(i==(N-1)):
del_A.append(A[0]+K-A[i])
else:
del_A.append(A[i+1]-A[i])
print(sum(del_A)-max(del_A)) | import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
#mod = 10**9+7
#mod = 998244353
#INF = 10**18
#eps = 10**-7
def main():
N,K = map(int,readline().split())
A = list(map(int,readline().split()))
F = list(map(int,readline().split()))
A.sort()
F.sort(reverse=True)
ng = -1
ok = 10**12+100
while ok - ng > 1:
mid = (ok + ng) // 2
if sum(max(0,a-mid//f) for a,f in zip(A,F)) <= K:
ok = mid
else:
ng = mid
print(ok)
if __name__ == '__main__':
main()
| 0 | null | 104,387,190,103,282 | 186 | 290 |
X, Y, A, B, C = map(int, input().split())
p = sorted(list(map(int, input().split())))[::-1]
q = sorted(list(map(int, input().split())))[::-1]
r = sorted(list(map(int, input().split())))[::-1]
i = X - 1
j = Y - 1
k = 0
p.append(float("INF"))
q.append(float("INF"))
r.append(-1)
while p[i] < r[k] or q[j] < r[k]:
if p[i] < q[j]:
i -= 1
k += 1
else:
j -= 1
k += 1
ans = 0
if i != -1:
ans += sum(p[:i+1])
if j != -1:
ans += sum(q[:j+1])
if k != 0:
ans += sum(r[:k])
print(ans) | import itertools
N = int(input())
cities = [tuple(map(int, input().split())) for _ in range(N)]
distance = 0
for c in itertools.combinations(range(N), 2):
c1, c2 = c
distance += ((cities[c1][0] - cities[c2][0]) ** 2 + (cities[c1][1] - cities[c2][1]) ** 2) **0.5
answer = 2 * distance / N
print(answer)
| 0 | null | 97,137,227,885,412 | 188 | 280 |
N, K = map(int, input().split())
AAA = []
for _ in range(K):
d = int(input())
A = list(map(int, input().split()))
AAA = AAA + A
AAA = list(set(AAA))
AA = []
for i in range(N):
AA = AA + [i + 1]
a = AAA + AA
ANS = len([i for i in list(set(a)) if a.count(i) == 1])
print(ANS) | n = -100
i = 1
while n != 0:
n = int(raw_input())
if n != 0:
print 'Case %d: %d' %(i,n)
i = i + 1 | 0 | null | 12,497,861,247,368 | 154 | 42 |
import bisect
n = int(input())
L = list(map(int, input().split()))
#%%
L.sort()
ans = 0
for i in range(n-2): # aを固定
for j in range(i+1, n-1): # bを固定
ab = L[i] + L[j]
idx = bisect.bisect_left(L, ab, lo=j)
ans += max(idx - (j+1), 0)
print(ans)
| import sys
input = sys.stdin.readline
# D - Triangles
def binary_search(i, j):
global N
left = j
right = N
while right - left > 1:
mid = (left + right) // 2
if is_match(mid, i, j):
left = mid
else:
right = mid
return left
def is_match(mid, i, j):
global L
a = L[i]
b = L[j]
c = L[mid]
if b < c + a and c < a + b:
return True
else:
return False
N = int(input())
L = list(map(int, input().split()))
L.sort()
ans = 0
for i in range(N - 2):
for j in range(i + 1, N - 1):
k = binary_search(i, j)
if k > j and k < N:
ans += k - j
print(ans) | 1 | 172,046,222,504,672 | null | 294 | 294 |
import sys
sys.setrecursionlimit(10 ** 6)
# input = sys.stdin.readline ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return input().split()
def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))
INF = float('inf')
from math import ceil, floor, log2
from collections import deque
from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product
def solve():
n = II()
A = LI()
memo = {}
ans = 0
for i in range(n):
mae = (i+1) + A[i]
ima = (i+1) - A[i]
ans += memo.get(ima, 0)
memo[mae] = memo.get(mae, 0) + 1
# print(memo)
print(ans)
if __name__ == '__main__':
solve()
| # https://atcoder.jp/contests/abc166/tasks/abc166_e
"""
変数分離すれば互いに独立なので、
連想配列でO(N)になる。
"""
import sys
input = sys.stdin.readline
from collections import Counter
N = int(input())
A = list(map(int, input().split()))
P = (j+1-A[j] for j in range(N))
M = (i+1+A[i] for i in range(N))
dic = Counter(P)
res = 0
for m in M:
res += dic.get(m,0)
print(res) | 1 | 26,216,751,746,724 | null | 157 | 157 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(pow(10, 6))
def main():
n, m, l = map(int, input().split())
d = [[float("inf") for _ in range(n)] for _ in range(n)]
for i in range(n):
d[i][i] = 0
for _ in range(m):
a, b, c = map(int, input().split())
d[a-1][b-1] = c
d[b-1][a-1] = c
for k in range(n):
for i in range(n):
for j in range(n):
if d[i][j] > d[i][k] + d[k][j]:
d[i][j] = d[i][k] + d[k][j]
dl = [[float("inf") for _ in range(n)] for _ in range(n)]
for i in range(n):
d[i][i] = 0
for i in range(n):
for j in range(i+1, n):
if i != j and d[i][j] <= l:
dl[i][j] = 1
dl[j][i] = 1
for k in range(n):
for i in range(n):
for j in range(n):
if dl[i][j] > dl[i][k] + dl[k][j]:
dl[i][j] = dl[i][k] + dl[k][j]
q = int(input())
for _ in range(q):
s, t = map(int, input().split())
if dl[s-1][t-1] == float("inf"):
print(-1)
else:
print(dl[s-1][t-1] - 1)
if __name__ == '__main__':
main()
| 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() | 1 | 173,482,682,954,922 | null | 295 | 295 |
n = int(input())
Ai = list(map(int, input().split()))
sum_ans = sum(Ai)
ans = 0
mod = 1000000007
for i in range(n-1):
sum_ans -= Ai[i]
ans += sum_ans * Ai[i]
ans %= mod
print(ans) | N = int(input())
A = list(map(int,input().split()))
mod = 1000000000 + 7
add = 0
tmp = sum(A)
for i in range(N):
tmp -= A[i]
add += tmp * A[i]
print(add%mod) | 1 | 3,837,858,664,550 | null | 83 | 83 |
#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, product # (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)
# 四捨五入g
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
return list(map(int,input().split()))
def I():
return int(input())
H = I()
def monster(n):
if n == 1:
return 1
return 1 + 2*(monster(n//2))
print(monster(H))
| def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a,b):
return (a*b) / gcd(a,b)
if __name__ == "__main__":
n1,n2=map(int,input().split(' '))
print(int(lcm(n1,n2))) | 0 | null | 96,332,497,984,598 | 228 | 256 |
n,m=map(int,input().split())
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1]*n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x=self.find(x)
y=self.find(y)
if x== y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
uf = UnionFind(n)
ans=0
for i in range(m):
a, b = map(int,input().split())
a -= 1
b -= 1
uf.union(a, b)
for i in range(n):
ans = max(ans, uf.size(i))
print(ans) | N,M=map(int,input().split())
par=[i for i in range(N)]
size=[1 for i in range(N)]
def find(x):
if par[x]==x:
return x
else:
par[x]=find(par[x])
return par[x]
def union(a,b):
x=find(a)
y=find(b)
if x!=y:
if size[x]<size[y]:
par[x]=par[y]
size[y]+=size[x]
else:
par[y]=par[x]
size[x]+=size[y]
else:
return
for i in range(M):
a,b=map(int,input().split())
union(a-1,b-1)
print(max(size)) | 1 | 3,969,887,351,540 | null | 84 | 84 |
from collections import deque
n = int(input())
d = deque()
for i in range(n):
x = input().split()
if x[0] == "insert":
d.appendleft(x[1])
elif x[0] == "delete":
if x[1] in d:
d.remove(x[1])
elif x[0] == "deleteFirst":
d.popleft()
elif x[0] == "deleteLast":
d.pop()
print(*d)
|
n = input()
s = []
h = []
c = []
d = []
for i in range(n):
spare = raw_input().split()
if spare[0]=='S':
s.append(int(spare[1]))
elif spare[0]=='H':
h.append(int(spare[1]))
elif spare[0]=='C':
c.append(int(spare[1]))
else :
d.append(int(spare[1]))
for j in range(1,14):
judge = True
for k in range(len(s)):
if j==s[k] :
judge = False
break
if judge :
print 'S %d' %j
for j in range(1,14):
judge = True
for k in range(len(h)):
if j==h[k] :
judge = False
break
if judge :
print 'H %d' %j
for j in range(1,14):
judge = True
for k in range(len(c)):
if j==c[k] :
judge = False
break
if judge :
print 'C %d' %j
for j in range(1,14):
judge = True
for k in range(len(d)):
if j==d[k] :
judge = False
break
if judge :
print 'D %d' %j | 0 | null | 534,677,069,852 | 20 | 54 |
# coding=utf-8
inputs = raw_input().rstrip().split()
nums = [int(x) for x in inputs]
print ' '.join([str(x) for x in sorted(nums)]) | list = [int(s) for s in input().split()]
list.sort()
print(" ".join(map(str,list))) | 1 | 416,770,277,468 | null | 40 | 40 |
a = input()
if ("AB" in a) or ("BA" in a):
print("Yes")
else:
print("No") | # AAA or BBB ならNo
S = list(input())
S_sorted = ''.join(sorted(S))
# print(S_sorted)
if S_sorted == 'AAA' or S_sorted == 'BBB':
print('No')
else:
print('Yes')
| 1 | 54,950,873,791,900 | null | 201 | 201 |
a,b=[int(i) for i in input().split()]
c=[int(i) for i in input().split()]
if(sum(c)>=a):
print('Yes')
else:
print('No') | a, b, c, d = map(int, input().split())
v1 = a * c
v2 = a * d
v3 = b * c
v4 = b * d
print(max(v1, v2, v3, v4)) | 0 | null | 40,322,188,985,342 | 226 | 77 |
import collections
n = int(input())
s = [input() for l in range(n)]
word = collections.Counter(s)
ma = max(word.values())
z = [kv for kv in word.items() if kv[1] == ma]
z = sorted(z)
for c in z:
print(c[0])
| n = int(input())
ans = []
while(n > 0):
x = n % 26
n = n // 26
if(x == 0):
x = 26
n -= 1
ans.append(chr(x + ord('a') -1))
# print(x,n)
ans.reverse()
print("".join(ans))
| 0 | null | 40,746,962,387,108 | 218 | 121 |
import sys
from collections import defaultdict, deque, Counter
import math
# import copy
from bisect import bisect_left, bisect_right
import heapq
# 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 = 10 ** 20
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 kaijyo(n):
ret = [1]
for i in range(1, n + 1):
ret.append((ret[-1] * i)% MOD)
return ret
def solve():
n, m = getList()
nums = getList()
peaks = [[] for i in range(n)]
for i in range(m):
a,b = getZList()
peaks[a].append(b)
peaks[b].append(a)
ans = 0
for i, num in enumerate(nums):
flg = True
for p in peaks[i]:
if nums[p] >= num:
flg = False
if flg:
ans += 1
print(ans)
def main():
n = getN()
for _ in range(n):
solve()
if __name__ == "__main__":
# main()
solve() | 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
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 = float('inf')
mod = 10 ** 9 + 7
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10
T1, T2 = MAP()
A1, A2 = MAP()
B1, B2 = MAP()
if (A1-B1)*T1 + (A2-B2)*T2 == 0:
print("infinity")
elif 0 < ((A1-B1)*T1) * ((A1-B1)*T1 + (A2-B2)*T2):
print(0)
else:
p = A1*T1-B1*T1
q = 2*A1*T1+A2*T2-2*B1*T1-B2*T2
if p*q < 0:
print(1)
elif p%(p-q):
print(2*(p//(p-q))+ 1)
else:
print(2*(p//(p-q)))
| 0 | null | 78,658,834,172,382 | 155 | 269 |
def main():
N = int(input())
A = list(map(int, input().split()))
MOD = 10 ** 9 + 7
ans = 1
cnt = [0] * (N + 1)
for i in range(N):
if A[i] == 0:
ans *= 3 - cnt[A[i]]
cnt[A[i]] += 1
else:
ans *= cnt[A[i]-1] - cnt[A[i]]
cnt[A[i]] += 1
ans %= MOD
print(ans)
if __name__ == "__main__":
main() | #!python3
from collections import deque
LI = lambda: list(map(int, input().split()))
# input
N, M = LI()
S = input()
INF = 10 ** 6
def main():
w = [(INF, INF)] * (N + 1)
w[0] = (0, 0)
# (cost, index)
dq = deque([(0, 0)])
for i in range(1, N + 1):
if i - dq[0][1] > M:
dq.popleft()
if len(dq) == 0:
print(-1)
return
if S[i] == "0":
w[i] = (dq[0][0] + 1, i - dq[0][1])
dq.append((w[i][0], i))
ans = []
x = N
while x > 0:
d = w[x][1]
ans.append(d)
x -= d
ans = ans[::-1]
print(*ans)
if __name__ == "__main__":
main()
| 0 | null | 134,136,813,370,720 | 268 | 274 |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 01:25:53 2020
@author: saito
"""
# %% import phase
#from collections import deque
# %% define phase
# %% input phase
K = int(input())
# %% process phase
r = 0
answer = -1
h = []
for cnt in range(K):
r = (10*r+7) % K
if r == 0:
answer = cnt + 1
break
# %%output phase
print(answer) | from decimal import Decimal
N = int(input())
M = int(N/Decimal(1.08)) + 1
if N == int(M*Decimal(1.08)) :
print( int(M))
else :
print(':(') | 0 | null | 65,820,146,509,132 | 97 | 265 |
n = int(input())
taro = 0
hanako = 0
for ni in range(n):
t, h = input().split()
if t < h:
hanako += 3
elif t > h:
taro += 3
else:
hanako += 1
taro += 1
print(taro, hanako) | n = int(input())
t_point = h_point = 0
for i in range(n):
t_card,h_card = [x for x in input().split( )]
if t_card > h_card:
t_point += 3
elif t_card < h_card:
h_point += 3
else:
t_point += 1
h_point += 1
print(t_point,h_point)
| 1 | 2,020,810,666,798 | null | 67 | 67 |
m = 2000003
def MyHash(k,i):
return (k%m+i*(1+(k%m)))%m
def main():
n = input()
T = ['']*2000003
O = []
for i in range(n):
c, k = raw_input().split()
i = 0
if c == 'insert':
k_hashed = hash(k)
while True:
j = MyHash(k_hashed,i)
if T[j] == '':
T[j] = k
break
else:
i += 1
else:
O.append(search(T,k))
for item in O:
print item
return 0
def search(T,k):
k_hashed = hash(k)
i = 0
while True:
j = MyHash(k_hashed,i)
if T[j] == k:
o = 'yes'
break
elif T[j] == '':
o = 'no'
break
else:
i += 1
return o
if __name__ == "__main__":
main() | n = int( raw_input( ) )
dic = {}
for i in range( n ):
cmd, word = raw_input( ).split( " " )
if "insert" == cmd:
dic[ word ] = True
elif "find" == cmd:
if not dic.get( word ):
print( "no" )
else:
print( "yes" ) | 1 | 76,206,300,290 | null | 23 | 23 |
from collections import deque
from sys import stdin
n = int(input())
ddl = deque()
for i in stdin:
inp = i.split()
if len(inp) == 2:
op, data = inp
data = int(data)
else: op, data = inp[0], None
if op == 'insert':
ddl.appendleft(data,)
elif op == 'delete':
try:
ddl.remove(data)
except ValueError:
pass
elif op == 'deleteFirst':
ddl.popleft()
elif op == 'deleteLast':
ddl.pop()
print(' '.join([str(item) for item in ddl])) | import sys
class Node():
def __init__(self, key=None, prev=None, next=None):
self.key = key
self.prev = prev
self.next = next
class DoublyLinkedList():
def __init__(self):
self.head = Node()
self.head.next = self.head
self.head.prev = self.head
def insert(self, x):
node = Node(key=x, prev=self.head, next=self.head.next)
self.head.next.prev = node
self.head.next = node
def search(self, x):
node = self.head.next
while node is not self.head and node.key != x:
node = node.next
return node
def delete_key(self, x):
node = self.search(x)
self._delete(node)
def _delete(self, node):
if node is self.head:
return None
node.prev.next = node.next
node.next.prev = node.prev
def deleteFirst(self):
self._delete(self.head.next)
def deleteLast(self):
self._delete(self.head.prev)
def getKeys(self):
node = self.head.next
keys = []
while node is not self.head:
keys.append(node.key)
node = node.next
return " ".join(keys)
L = DoublyLinkedList()
n = int(input())
for i in sys.stdin:
if 'insert' in i:
x = i[7:-1]
L.insert(x)
elif 'deleteFirst' in i:
L.deleteFirst()
elif 'deleteLast' in i:
L.deleteLast()
elif 'delete' in i:
x = i[7:-1]
L.delete_key(x)
else:
pass
print(L.getKeys())
| 1 | 50,329,055,360 | null | 20 | 20 |
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
def gcd(*numbers): reduce(math.gcd, numbers)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
count = 0
ans = 0
N = k()
a = l()
for i in a:
if i == ans+1:
ans+=1
if ans == 0:
print(-1)
else:
print(N-ans)
| def main():
N = int(input())
A = list(map(int, input().split()))
if 1 not in A:
print(-1)
exit()
next = 1
for a in A:
if a == next:
next += 1
print(N - next + 1)
if __name__ == '__main__':
main()
| 1 | 114,222,211,875,980 | null | 257 | 257 |
import sys
import itertools
# import numpy as np
import time
import math
sys.setrecursionlimit(10 ** 7)
from collections import defaultdict
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from functools import reduce
# from math import *
from fractions import *
N, M = map(int, readline().split())
A = list(map(lambda x: int(x) // 2, readline().split()))
def f(n):
cnt = 0
while n % 2 == 0:
n //= 2
cnt += 1
return cnt
t = f(A[0])
for i in range(N):
if f(A[i]) != t:
print(0)
exit(0)
A[i] >>= t
M >>= t
lcm = reduce(lambda a, b: (a * b) // gcd(a, b), A)
if lcm > M:
print(0)
exit(0)
print((M // lcm + 1) // 2)
| D, T, S = map(int,input().split())
Distance = T * S
if(D <= Distance):
print('Yes')
else:
print('No') | 0 | null | 52,605,627,040,028 | 247 | 81 |
N=int(input())
if N%2==0:
ans=0
x=10
while x<=N:
ans+=N//x
x*=5
else:
ans=0
print(ans) | N = int(input())
if N%2==1:
ans = 0
else:
n = N//10
ans = n
k = 1
while 5**k<=n:
ans += n//(5**k)
k += 1
print(ans) | 1 | 115,822,401,487,492 | null | 258 | 258 |
N,M = map(int, input().split())
S = list(input())
S.reverse()
ans = []
i = 0
while i < N:
num = 0
for j in range(min(N, i+M), i, -1):
if S[j] == "0":
num = j-i
i = j
break
if num == 0:
ans = -1
break
ans.append(num)
if ans == -1:
print(ans)
else:
ans.reverse()
print(*ans) | import sys
N, M = map(int,input().split())
S = input()
S = S[::-1]
i = 0
ans = []
while i < N:
flag = 0
for j in range(M,0,-1):
if i + j <= N and S[i + j] == '0':
i += j
flag = 1
ans.append(j)
break
if flag:
continue
print(-1)
sys.exit()
ans.reverse()
print(*ans) | 1 | 139,096,475,065,896 | null | 274 | 274 |
from collections import deque
N=int(input())
G=[[] for _ in [0]*(N+1)]
for i in range(1,N):
a,b=map(int,input().split())
G[a].append((b,i))
G[b].append((a,i))
root,res=0,0
for i in range(1,N+1):
tmp=len(G[i])
if tmp>res:
res=tmp
root=i
q=deque()
q.append((root,0))
color=[0]*N
D=[N+10]*(N+1)
D[root]=0
while q:
p,c=q.popleft()
nc=1
while G[p]:
np,ni=G[p].pop()
if D[np]>D[p]:
D[np]=D[p]+1
if nc==c:
nc+=1
color[ni]=nc
q.append((np,nc))
nc+=1
print(res,*color[1:],sep='\n') | n = int(raw_input())
i = 0
s = []
h = []
c = []
d = []
def order_list(list):
l = len(list)
for i in xrange(l):
j = i + 1
while j < l:
if list[i] > list[j]:
temp = list[i]
list[i] = list[j]
list[j] = temp
j += 1
return list
def not_enough_cards(mark, list):
list = order_list(list)
# line = "########################################"
# print line
# print mark + ":"
# print list
# print line
i = 0
for x in xrange(1, 14):
# print "x = " + str(x) + ", i = " + str(i)
if i >= len(list):
print mark + " " + str(x)
elif x != list[i]:
print mark + " " + str(x)
else:
i += 1
while i < n:
line = raw_input().split(" ")
line[1] = int(line[1])
if line[0] == "S":
s.append(line[1])
elif line[0] == "H":
h.append(line[1])
elif line[0] == "C":
c.append(line[1])
elif line[0] == "D":
d.append(line[1])
i += 1
not_enough_cards("S", s)
not_enough_cards("H", h)
not_enough_cards("C", c)
not_enough_cards("D", d) | 0 | null | 68,836,930,624,462 | 272 | 54 |
import sys
from collections import deque
queue = deque()
for _ in range(int(sys.stdin.readline())):
commands = sys.stdin.readline()[:-1].split(" ")
if commands[0] == "insert":
queue.appendleft(commands[1])
elif commands[0] == "delete":
try:
queue.remove(commands[1])
except ValueError:
pass
elif commands[0] == "deleteFirst":
queue.popleft()
elif commands[0] == "deleteLast":
queue.pop()
print(" ".join(queue)) | from collections import deque
times = int(input())
stack = deque()
for i in range(times):
op = input().split()
if op[0] == "insert":
stack.appendleft(op[1])
if op[0] == "delete":
if op[1] in stack:
stack.remove(op[1])
if op[0] == "deleteFirst":
stack.popleft()
if op[0] == "deleteLast":
stack.pop()
print(*stack)
| 1 | 50,828,342,880 | null | 20 | 20 |
a,b,c,d=map(float,input().split())
r=((c-a)**2+(d-b)**2)**(1/2)
print(f'{r:5f}')
| import math
x1,y1,x2,y2 = map(float,raw_input().split())
a = math.sqrt((x1-x2)**2+(y1-y2)**2)
print '%f'%a | 1 | 157,543,397,662 | null | 29 | 29 |
while True:
[H,W]=[int(x) for x in input().split()]
if [H,W]==[0,0]:
break
unit="#."
for i in range(0,H):
print(unit*(W//2)+unit[0]*(W%2))
unit=unit[1]+unit[0]
print("") | H, W = map(int, raw_input().split())
while H | W != 0:
for i in range(H):
s = ''
for j in range(W):
s += '#' if (j + i) % 2 == 0 else '.'
print s
print ''
H, W = map(int, raw_input().split()) | 1 | 886,204,003,484 | null | 51 | 51 |
n=int(input())
for i in range(1,10):
if n%i==0 and 1<=n//i<=9:
print("Yes")
break
else:
print("No") | # 問題: https://atcoder.jp/contests/abc144/tasks/abc144_b
n = int(input())
has_multiple = False
for a in range(1, 10):
if n % a > 0:
continue
b = n / a
if 0 < b < 10:
has_multiple = True
break
if has_multiple:
print('Yes')
else:
print('No')
| 1 | 160,103,717,659,380 | null | 287 | 287 |
import sys
def main():
n, x, y = map(int, sys.stdin.buffer.readline().split())
L = [0] * n
for i in range(1, n):
for j in range(i + 1, n + 1):
d = j - i
if i <= x and y <= j:
d -= y - x - 1
elif i <= x and x < j < y:
d = min(d, x - i + y - j + 1)
elif x < i < y and y <= j:
d = min(d, i - x + j - y + 1)
elif x < i and j < y:
d = min(d, i - x + y - j + 1)
L[d] += 1
for a in L[1:]:
print(a)
main() | N, X, Y = map(int, input().split())
ans = [0]*(N-1)
def cal_dis(i, j):
return min(j-i, abs(i-X)+abs(j-Y)+1)
for i in range(1, N+1):
for j in range(i+1, N+1):
k = cal_dis(i, j)
ans[k-1] += 1
print('\n'.join(map(str, ans)))
| 1 | 44,097,835,737,540 | null | 187 | 187 |
N = int(input())
lst = list(map(int, input().split()))
anslst = [0]*N
for i in lst:
anslst[i-1] += 1
for i in anslst:
print(i) | n = int(input())
a = list(map(int, input().split()))
sub_list = [0] * n
for i in (a):
sub_list[i - 1] += 1
for i in range(n):
print(sub_list[i], sep = ',')
| 1 | 32,575,319,023,068 | null | 169 | 169 |
for a in [1,2,3,4,5,6,7,8,9]:
for b in [1,2,3,4,5,6,7,8,9]:
print ("{0}x{1}={2}".format(a,b,a*b)) | import sys
for i in range(1,10):
for j in range(1,10):
print("{0}x{1}={2}".format(i,j,i*j)) | 1 | 1,343,300 | null | 1 | 1 |
lst = [True for i in range(52)]
n = int(input())
for i in range (n):
suit, rank = input().split()
rankn = int(rank)
if suit == 'S':
lst[rankn-1] = False
elif suit == 'H':
lst[rankn+12] = False
elif suit == 'C':
lst[rankn+25] = False
else:
lst[rankn+38] = False
for i in range(52):
tf = lst[i]
if i <= 12 and tf:
print ('S %d' % (i+1))
elif 12 < i <= 25 and tf:
print ('H %d' % (i-12))
elif 25 < i <= 38 and tf:
print ('C %d' % (i-25))
elif tf:
print ('D %d' % (i-38))
| n,m=map(int,input().split())
h=list(map(int,input().split()))
c=0
d=[0]*n
for i in range(m):
a,b=map(int,input().split())
d[a-1]=max(d[a-1],h[b-1])
d[b-1]=max(d[b-1],h[a-1])
for i in range(n):
if h[i]>d[i]:
c+=1
print(c) | 0 | null | 12,998,631,576,348 | 54 | 155 |
class BIT:
"""Binary Indexed Tree (Fenwick Tree)
Range Sum QueryにO(log N)時間で答える
1-indexed
"""
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
self.depth = n.bit_length()
def sum(self, i):
"""a[1]~a[i]の区間和を取得"""
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
"""a[i]にxを足す"""
while i <= self.size:
self.tree[i] += x
i += i & -i
def lower_bound(self, x):
""" 累積和がx以上になる最小のindexと、その直前までの累積和 """
sum_ = 0
pos = 0
for i in range(self.depth, -1, -1):
k = pos + (1 << i)
if k <= self.size and sum_ + self.tree[k] < x:
sum_ += self.tree[k]
pos += 1 << i
return pos + 1, sum_
def main():
N = int(input())
S = list(input())
Q = int(input())
alphabets = list("abcdefghijklmnopqrstuvwxyz")
c2n = {c: i for i, c in enumerate(alphabets)}
Trees = [BIT(N+2) for _ in range(26)]
for i in range(N):
Trees[c2n[S[i]]].add(i+1, 1)
for _ in range(Q):
tmp = list(input().split())
if tmp[0] == "1":
_, i, c = tmp
i = int(i)
Trees[c2n[S[i-1]]].add(i, -1)
Trees[c2n[c]].add(i, 1)
S[i-1] = c
else:
ans = 0
_, l, r = tmp
l = int(l)
r = int(r)
for char in range(26):
if Trees[char].sum(r) - Trees[char].sum(l-1) > 0:
ans += 1
print(ans)
if __name__ == "__main__":
main() |
import numpy as np
a= 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]
print(K[int(a)-1])
| 0 | null | 56,233,847,983,192 | 210 | 195 |
N = input()
if int(N[(len(N)-1)]) in [2,4,5,7,9]:print('hon')
elif int(N[(len(N)-1)]) in [0,1,6,8]:print('pon')
elif int(N[(len(N)-1)]) in [3]:print('bon') | a=int(input())
if a%10==3:
print("bon")
else:
if a%10==0 or a%10==1 or a%10==6 or a%10==8:
print("pon")
else:
print("hon") | 1 | 19,292,228,352,572 | null | 142 | 142 |
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from math import ceil
def main():
n, k = map(int, input().split())
a = tuple(map(int, input().split()))
def kaisu(long):
return(sum([ceil(ae/long) - 1 for ae in a]))
def bs_meguru(key):
def isOK(index, key):
if kaisu(index) <= key:
return True
else:
return False
ng = 0
ok = max(a)
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if isOK(mid, key):
ok = mid
else:
ng = mid
return ok
print(bs_meguru(k))
if __name__ == '__main__':
main()
| n,k = map(int,input().split())
L = list(map(int,input().split()))
def A(x):
cnt = 0
for i in range(n):
if L[i]%x == 0:
cnt +=L[i]//x-1
else:
cnt +=L[i]//x
return cnt <= k
lower = 0
upper = max(L)
while upper - lower > 1:
mid = (lower + upper)//2
if A(mid):
upper = mid
else:
lower = mid
print(upper) | 1 | 6,511,939,083,402 | null | 99 | 99 |
n,k=map(int,input().split())
mod=10**9+7
count=[0]*(k+1)
def getnum(m):
ret = pow(k//m,n,mod)
mul=2
while m*mul<=k:
ret-=count[m*mul]
mul+=1
return ret%mod
ans=0
for i in range(1,k+1)[::-1]:
g=getnum(i)
count[i]=g
ans+=g*i
ans%=mod
print(ans) | N, K = map(int, input().split())
ans = 0
lis = [0]*K
mod = 10**9 + 7
def modpow(a, n, mod):
ans = 1
while n > 0:
if n&1:
ans = ans * a % mod
a = a * a % mod
n = n >> 1
return ans
for x in range(K,0, -1):
a = int((K // x) % mod)
b = modpow(a, N, mod)
for i in range(2, K//x +1):
b = (b - lis[x*i-1]) %mod
if b < 0:
b += mod
lis[x-1] = b
ans = (ans + b*x%mod) % mod
print(int(ans))
| 1 | 36,636,642,751,140 | null | 176 | 176 |
n, k = map(int, input().split())
a = list(map(int, input().split()))
mod = 10**9 + 7
ans = 1
if k == n:
for i in range(n):
ans *= a[i]
ans %= mod
print(ans)
exit()
if max(a) < 0 and k%2 == 1:
a.sort(reverse=True)
for i in range(k):
ans *= a[i]
ans %= mod
print(ans)
exit()
a.sort(key=lambda x: abs(x))
cnt = 0
for i in range(1, k+1):
ans *= a[-i]
ans %= mod
if a[-i] < 0:
cnt += 1
if cnt%2 == 0:
print(ans)
else:
a_plus = None
a_minus = None
b_plus = None
b_minus = None
for i in range(k, 0, -1):
if a[-i] >= 0 and a_plus == None:
a_plus = a[-i]
if a[-i] < 0 and a_minus == None:
a_minus = a[-i]
for i in range(k+1, n+1):
if a[-i] >= 0 and b_plus == None:
b_plus = a[-i]
if a[-i] < 0 and b_minus == None:
b_minus = a[-i]
if a_plus == None or b_minus == None:
ans *= pow(a_minus, mod-2, mod)
ans %= mod
ans *= b_plus
ans %= mod
elif a_minus == None or b_plus == None:
ans *= pow(a_plus, mod-2, mod)
ans %= mod
ans *= b_minus
ans %= mod
else:
if abs(a_plus*b_plus) > abs(a_minus*b_minus):
ans *= pow(a_minus, mod-2, mod)
ans %= mod
ans *= b_plus
ans %= mod
else:
ans *= pow(a_plus, mod-2, mod)
ans %= mod
ans *= b_minus
ans %= mod
print(ans) | x = int(input())
hap = x // 500
hap2 = (x - hap*500)//5
ans = hap*1000 + hap2*5
print(ans) | 0 | null | 26,012,554,823,808 | 112 | 185 |
num = int(input())
if num%2==0:
print((num//2) / num)
else:
print(((num//2)+1) / num) | t = int(input())
h = int(t/3600)
m = int(t%3600/60)
s = int(t%3600%60)
print(str(h) + ":" + str(m) + ":" + str(s)) | 0 | null | 88,480,176,004,612 | 297 | 37 |
n,k,c = map(int,input().split())
s = list(input())
L = []
R = []
i = -1
j = n
for ki in range(k):
while i < n:
i += 1
if s[i] == 'o':
L += [i]
i += c
break
for ki in range(k):
while 0 <= j:
j -= 1
if s[j] == 'o':
R += [j]
j -= c
break
for i in range(k):
if L[i] == R[-i-1] :
print(L[i]+1) | from math import sqrt
x1, y1, x2, y2 = map(float, input().split())
X = abs(x1 - x2)
Y = abs(y1 - y2)
print(sqrt(X**2 + Y**2))
| 0 | null | 20,356,137,326,668 | 182 | 29 |
#ALDS1_3-B Elementary data structures - Queue
n,q = [int(x) for x in input().split()]
Q=[]
for i in range(n):
Q.append(input().split())
t=0
res=[]
while Q!=[]:
if int(Q[0][1])<=q:
res.append([Q[0][0],int(Q[0][1])+t])
t+=int(Q[0][1])
else:
Q.append([Q[0][0],int(Q[0][1])-q])
t+=q
del Q[0]
for i in res:
print(i[0]+" "+str(i[1])) | n = int(input())
S = [c for c in input()]
ans = 0
i = 0
j = n-1
while i < j:
if S[i] == "W":
if S[j] == "R":
S[i] = "R"
S[j] = "W"
j -= 1
i += 1
ans += 1
else:
j -= 1
else:
i += 1
print(ans) | 0 | null | 3,163,809,236,720 | 19 | 98 |
#!/usr/bin/env python3
class UnionFind():
def __init__(self, n):
self.n = n
self.root = [-1] * (n + 1)
self.rnk = [0] * (n + 1)
def Find_Root(self, x):
if self.root[x] < 0:
return x
else:
self.root[x] = self.Find_Root(self.root[x])
return self.root[x]
def Unite(self, x, y):
x = self.Find_Root(x)
y = self.Find_Root(y)
if x == y:
return
elif self.rnk[x] > self.rnk[y]:
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if self.rnk[x] == self.rnk[y]:
self.rnk[y] += 1
def roots(self):
return [i for i, x in enumerate(self.root) if x < 0]
def group_count(self):
return len(self.roots())
def main():
n, m = map(int, input().split())
UF = UnionFind(n)
for _ in range(m):
a, b = map(int, input().split())
UF.Unite(a, b)
print(UF.group_count() - 2)
if __name__ == "__main__":
main()
| import networkx as nx
n, m = map(int, input().split())
nodes = [0 for i in range(n)]
L = []
for i in range(m):
a, b = map(int, input().split())
L.append((a,b))
nodes[a-1] += 1
nodes[b-1] += 1
num = 0
for node in nodes:
if node == 0:
num += 1
graph = nx.from_edgelist(L)
num += len(list(nx.connected_components(graph)))
print(num-1) | 1 | 2,269,672,168,858 | null | 70 | 70 |
n=int(input())
wl={}
for i in range(n):
w=input()
if w not in wl:
wl[w]=0
wl[w]+=1
wm=max(wl.values())
wl3=sorted(wl.items())
for i in range(len(wl3)):
if wl3[i][1]==wm:
print(wl3[i][0]) | S = int(input())
h = S//3600
m = S%3600//60
s = S%60
print(f"{h}:{m}:{s}")
| 0 | null | 35,213,456,246,750 | 218 | 37 |
import sys
N = int(input())
if not ( 1 <= N <= 100 ):sys.exit()
print(1-(int(N/2)/N)) | import sys
input = sys.stdin.readline
ins = lambda: input().rstrip()
ini = lambda: int(input().rstrip())
inm = lambda: map(int, input().split())
inl = lambda: list(map(int, input().split()))
n = ini()
print(n + n**2 + n**3) | 0 | null | 93,533,803,852,362 | 297 | 115 |
H,N=map(int,input().split())
A=sorted(list(map(int,input().split())))
for i in range(1,N+1):
H-=A[-i]
if H<=0:
print('Yes')
exit()
print('No') | """
n=int(input())
s=[int(x) for x in input().split()]
q=int(input())
t=[int(x) for x in input().split()]
#print(s)
c=0
for i in t:
if i in s:
c+=1
print(c)
"""
"""
n=int(input())
s=[int(x) for x in input().split()]
q=int(input())
t=[int(x) for x in input().split()]
#binary search
a=0
for i in range(q):
L=0
R=n-1#探索する方の配列(s)はソート済みでないといけない
while L<=R:
M=(L+R)//2
if s[M]<t[i]:
L=M+1
elif s[M]>t[i]:
R=M-1
else:
a+=1
break
print(a)
"""
#Dictionary
#dict型オブジェクトに対しinを使うとキーの存在確認になる
n=int(input())
d={}
for i in range(n):
command,words=input().split()
if command=='find':
if words in d:
print('yes')
else:
print('no')
else:
d[words]=0
| 0 | null | 38,935,776,735,570 | 226 | 23 |
D = {"SUN":7,"MON":6,"TUE":5,"WED":4,"THU":3,"FRI":2,"SAT":1}
print(D[input().strip()]) | S = input()
if(S=='SUN'):
print(7)
elif(S=='MON'):
print(6)
elif(S=='TUE'):
print(5)
elif (S=='WED'):
print(4)
elif (S=='THU'):
print(3)
elif (S=='FRI'):
print(2)
else:
print(1) | 1 | 132,856,024,909,912 | null | 270 | 270 |
S = input()
L = len(S)
for i in range(L):
print("x",end='') | n = int(input())
str = input().split(" ")
S = [int(str[i]) for i in range(n)]
q = int(input())
str = input().split(" ")
T = [int(str[i]) for i in range(q)]
S_set = set(S)
S = list(S_set)
T.sort()
result = 0
for s in S:
for t in T:
if s == t:
result += 1
break
print(result)
| 0 | null | 36,672,530,839,662 | 221 | 22 |
#####segfunc######
def segfunc(x, y):
return x | y
def init(init_val):
# set_val
for i in range(n):
seg[i + num - 1] = set(init_val[i])
# built
for i in range(num - 2, -1, -1):
seg[i] = segfunc(seg[2 * i + 1], seg[2 * i + 2])
def update(k, x):
k += num - 1
seg[k] = set(x)
while k:
k = (k - 1) // 2
seg[k] = segfunc(seg[k * 2 + 1], seg[k * 2 + 2])
def query(p, q):
if q <= p:
return ide_ele
p += num - 1
q += num - 2
res = ide_ele
while q - p > 1:
if p & 1 == 0:
res = segfunc(res, seg[p])
if q & 1 == 1:
res = segfunc(res, seg[q])
q -= 1
p = p // 2
q = (q - 1) // 2
if p == q:
res = segfunc(res, seg[p])
else:
res = segfunc(segfunc(res, seg[p]), seg[q])
return res
#####単位元######
ide_ele = set()
n = int(input())
S = input().strip()
Q = int(input())
num = 2 ** (n - 1).bit_length()
seg = [set()] * 2 * num
init(S)
for _ in range(Q):
a, b, c = [x for x in input().split()]
if a == "1":
update(int(b) - 1, c)
else:
print(len(query(int(b) - 1, int(c))))
| import sys, bisect, math, itertools, heapq, collections
from operator import itemgetter
# a.sort(key=itemgetter(i)) # i番目要素でsort
from functools import lru_cache
# @lru_cache(maxsize=None)
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp():
'''
一つの整数
'''
return int(input())
def inpl():
'''
一行に複数の整数
'''
return list(map(int, input().split()))
class SegmentTree():
def __init__(self, init_val, N):
"""
Parameters
----------
init_val:int
identity element
N:int
the number of nodes
"""
self.init_val=init_val
# Range Minimum Query
self.N0 = 2**(N-1).bit_length()
# 0-indexedで管理
self.data = [self.init_val] * (2 * self.N0)
def _segfunc(self, left, right):
res= left | right
return res
def update(self,k, x):
"""
Parameters
----------
k:int
target index(0-index)
x:any
target value
"""
k += self.N0-1
self.data[k] = x
while k > 0:
k = (k - 1) // 2
self.data[k] = self._segfunc(self.data[2*k+1], self.data[2*k+2])
def query(self, l, r):
"""
Parameters
----------
l,r:int
target range [l,r)
Return
----------
res:any
val
"""
L = l + self.N0
R = r + self.N0
s = self.init_val
while L < R:
if R & 1:
R -= 1
s = self._segfunc(s, self.data[R-1])
if L & 1:
s = self._segfunc(s,self.data[L-1])
L += 1
L >>= 1; R >>= 1
return s
n=inp()
s=input()
st = SegmentTree(0,n)
for i in range(n):
st.update(i,1<<(int.from_bytes(s[i].encode(),'little')-int.from_bytes('a'.encode(),'little')))
q = inp()
ans = []
for i in range(q):
mode, first, second = input().split()
if mode == "1":
st.update(int(first)-1,1<<(int.from_bytes(second.encode(),'little')-int.from_bytes('a'.encode(),'little')))
else:
ans.append(bin(st.query(int(first) - 1, int(second))).count("1"))
for i in ans:
print(i)
| 1 | 62,702,455,853,792 | null | 210 | 210 |
s = input()
p = input()
if len(p) <= len(s) and (s+s).find(p) > -1:
print("Yes")
else:
print("No")
| s=input()
p=input()
b=s
s+=s
ans=0
same_count=0
for i in range(len(b)):
for j in range(len(p)):
if s[i+j]==p[j]:
same_count+=1
if same_count==len(p):
ans=1
same_count=0
if ans==1:
print("Yes")
else:
print("No")
| 1 | 1,733,268,691,392 | null | 64 | 64 |
from collections import deque
N, D, A = map(int, input().split())
ls = []
for i in range(N):
x,h = map(int, input().split())
h = h//A if h%A==0 else h//A+1
ls += [(x,h)]
ls.sort(key=lambda x:x[0])
deq = deque([])
ans = 0
acc = 0
for i in range(N):
x, h = ls[i]
while deq and deq[0][0]<x:
y, d = deq.popleft()
acc -= d
n = max(0,h-acc)
ans += n
acc += n
if n:
deq += [(x+2*D,n)]
print(ans) | n, d, a = map(int, input().split())
xh = []
for _ in range(n):
x, h = map(int, input().split())
h = (h - 1) // a + 1
xh.append([x, h])
xh.sort()
damage = xh[0][1]
ans = damage
damage_lst = [[xh[0][0] + d * 2, damage]]
pos = 0
for i, (x, h) in enumerate(xh[1:], start = 1):
while x > damage_lst[pos][0]:
damage -= damage_lst[pos][1]
pos += 1
if pos == i:
break
damage_tmp = max(h - damage, 0)
ans += damage_tmp
damage += damage_tmp
damage_lst.append([x + d * 2, damage_tmp])
print(ans) | 1 | 81,742,229,106,720 | null | 230 | 230 |
def main():
S = str(input())
s = ''
for i in range(len(S)):
s = s + 'x'
print(s)
main() | 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 *
#階乗#
lim = 10**6 #必要そうな階乗の限界を入力
fact = [1] * (lim+1)
for n in range(1, lim+1):
fact[n] = n * fact[n-1] % mod
#階乗の逆元#
fact_inv = [1]*(lim+1)
fact_inv[lim] = pow(fact[lim], mod-2, mod)
for n in range(lim, 0, -1):
fact_inv[n-1] = n*fact_inv[n]%mod
def C(n, r):
return (fact[n]*fact_inv[r]%mod)*fact_inv[n-r]%mod
X, Y = MAP()
a = (Decimal("2")*Decimal(str(X))-Decimal(str(Y)))/Decimal("3")
b = (Decimal("2")*Decimal(str(Y))-Decimal(str(X)))/Decimal("3")
if a%1 == b%1 == 0 and 0 <= a and 0 <= b:
print(C(int(a+b), int(a)))
else:
print(0)
| 0 | null | 111,461,379,851,768 | 221 | 281 |
from decimal import Decimal
a, b = input().split()
a = Decimal(a)
b = Decimal(b)
print(int(a*b)) |
#<D>wa
n, k = map(int,input().split())
r, s, p = map(int,input().split())
q = input()
d = {"r":p,"s":r, "p":s}
ans = 0
wins = [False] * k
for i in range(len(q)):
if not wins[i % k] or q[i] != q[i - k]:
ans += d[q[i]]
wins[i % k] = True
else:
wins[i % k] = False
print(ans)
| 0 | null | 61,722,683,084,722 | 135 | 251 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.