code1
stringlengths 17
427k
| code2
stringlengths 17
427k
| similar
int64 0
1
| pair_id
int64 2
181,637B
⌀ | question_pair_id
float64 3.7M
180,677B
⌀ | code1_group
int64 1
299
| code2_group
int64 1
299
|
---|---|---|---|---|---|---|
N, M = map(int, input().split())
A = list(map(int, input().split()))
cnt = 0
thr = -(-sum(A)//(4*M))
for a in A:
if a >= thr:
cnt += 1
if cnt >= M:
print("Yes")
else:
print("No")
|
N, M = map(int, input().split())
A = list(map(int, input().split()))
cnt = 0
sum_A = sum(A)
A.sort(reverse=True)
for a in A:
if a >= sum_A / (4 * M):
cnt += 1
else:
break
if cnt >= M:
print('Yes')
else:
print('No')
| 1 | 38,497,677,078,400 | null | 179 | 179 |
from itertools import accumulate
n = int(input())
song= []
time = []
for i in range(n):
s, t = input().split()
song.append(s)
time.append(int(t))
time_acc = list(accumulate(time))
x = input()
print(time_acc[n - 1] - time_acc[song.index(x)])
|
def main():
N = int(input())
S = [0] * N
T = [0] * N
for i in range(N):
S[i], T[i] = input().split()
X = input()
idx = S.index(X)
ans = sum(map(int, T[idx+1:]))
print(ans)
if __name__ == "__main__":
main()
| 1 | 96,839,295,653,632 | null | 243 | 243 |
import sys
input = lambda: sys.stdin.readline().rstrip()
def resolve():
S = input()
cnt = [0]*2019
cnt[0] = 1
# Sの右側から1ずつ左に伸ばして、cntの対応するところに加算
rmd = 0
num_rate = 1
L = len(S)
for i in range(L):
rmd = (int(S[L-i-1])*num_rate + rmd) % 2019
num_rate = num_rate*10%2019
cnt[rmd] += 1
ans = sum([i*(i-1)//2 for i in cnt])
print(ans)
if __name__ == '__main__':
resolve()
|
def solve(s, p=2019):
s = s[::-1]
memo = [0] * p
memo[0] = 1
ans = 0
q = 0
r = 1
for c in s:
q = (q + int(c)*r) % p
ans += memo[q]
r = 10*r % p
memo[q] += 1
return ans
s = input()
print(solve(s))
| 1 | 30,863,712,738,442 | null | 166 | 166 |
# -*- 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]
|
import math
X = int(input())
N = 100
t = 0
while N<X:
t+=1
N = N*101//100
print(t)
| 0 | null | 13,586,662,255,698 | 19 | 159 |
K = int(input())
print("ACL" * K)
|
n = int(raw_input())
C = {'S':range(13), 'H':range(13), 'C':range(13), 'D':range(13)}
for i in range(n):
suit, num = raw_input().split()
num = int(num)
C[suit][num-1] = 14
for i in ['S', 'H', 'C', 'D']:
for j in range(13):
if C[i][j] != 14:
print "%s %d" %(i, j+1)
| 0 | null | 1,607,862,350,208 | 69 | 54 |
def main():
N, M = map(int, input().split())
if N == M:
print("Yes")
else:
print("No")
if __name__ == "__main__":
main()
|
import math
from functools import reduce
N = int(input())
A = list(map(int, input().split()))
P = int(1e9+7)
def lcm_base(x, y):
ret = (x * y) // math.gcd(x, y)
return ret
def lcm(iter):
return reduce(lcm_base, iter, 1)
lcm_a = lcm(A) % P
ans = 0
for a in A:
a_inv = pow(a, P-2, P)
ans = (ans + lcm_a*a_inv) %P
print(ans)
| 0 | null | 85,647,305,789,200 | 231 | 235 |
import math
n = int(raw_input())
cnt = 0
for i in range(n):
j = 2
num = int(raw_input())
while j <= math.sqrt(num):
if num % j == 0:
break
j+=1
if j > math.sqrt(num):
cnt+=1
print cnt
|
def is_prime(x):
if x == 1:
return False
l = x ** 0.5
n = 2
while n <= l:
if x % n == 0:
return False
n += 1
return True
import sys
def solve():
file_input = sys.stdin
N = file_input.readline()
cnt = 0
for l in file_input:
x = int(l)
if is_prime(x):
cnt += 1
print(cnt)
solve()
| 1 | 10,671,757,712 | null | 12 | 12 |
n, m = map(int, input().split(" "))
if n <= 9:
print(m + (100 * (10 - n)))
else:
print(m)
|
N,R=map(int,input().split())
if N<10:
print(int(R+(100*(10-N))))
else:
print(R)
| 1 | 63,460,223,687,170 | null | 211 | 211 |
def resolve():
import sys
input = sys.stdin.readline
# 整数 1 つ
n = int(input())
s = input()
# 整数複数個
# a, b = map(int, input().split())
# 整数 N 個 (改行区切り)
# N = [int(input()) for i in range(N)]
# 整数 N 個 (スペース区切り)
# N = list(map(int, input().split()))
# 整数 (縦 H 横 W の行列)
# A = [list(map(int, input().split())) for i in range(H)]
cnt = 0
for i in range(n-2):
if s[i]+s[i+1]+s[i+2] == "ABC":
cnt += 1
print(cnt)
resolve()
|
def resolve():
N = int(input())
S = str(input())
print(S.count('ABC'))
return
resolve()
| 1 | 99,542,121,495,520 | null | 245 | 245 |
#1indexed
class BIT():
def __init__(self, n):
self.size = n
self.bit = [0] * (n+1)
def sum(self, i):
s = 0
while i > 0:
s += self.bit[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
self.bit[i] += x
i += i & -i
n = int(input())
s = input()
q = int(input())
bit = [BIT(n+1) for i in range(26)]
for i in range(n):
bit[ord(s[i])-97].add(i+1, 1)
s = list(s)
for _ in range(q):
query, a, b = input().split()
if query == "1":
i = int(a)
c = ord(b)-97
bit[c].add(i, 1)
bit[ord(s[i-1])-97].add(i, -1)
s[i-1] = b
else:
ans = 0
for k in range(26):
if bit[k].sum(int(b))-bit[k].sum(int(a)-1) >= 1:
ans += 1
print(ans)
|
import sys
# input = sys.stdin.buffer.readline
def input(): return sys.stdin.readline().rstrip()
sys.setrecursionlimit(10 ** 7)
import bisect
from string import ascii_lowercase
d = dict()
for i, c in enumerate(ascii_lowercase):
d[c] = i
N = int(input())
S = list(input())
lst = [[] for _ in range(26)]
for i in range(N):
lst[d[S[i]]].append(i)
Q = int(input())
for q in range(Q):
a, b, c = input().split()
if a=='1':
i = int(b)-1
if c == S[i]: # 変更なし
continue
idx = bisect.bisect_left(lst[d[S[i]]],i)
del lst[d[S[i]]][idx]
bisect.insort_left(lst[d[c]],i)
S[i] = c
else:
l = int(b)-1
r = int(c)
ans = 0
for i in range(26):
cnt = bisect.bisect_left(lst[i],r) - bisect.bisect_left(lst[i],l)
if cnt:
ans += 1
print(ans)
| 1 | 62,455,260,308,248 | null | 210 | 210 |
n = int(input())
s = [str(input()) for i in range(n)]
a = s.count(('AC'))
b = s.count(('WA'))
c = s.count(('TLE'))
d = s.count(('RE'))
print("AC x {}".format(a))
print("WA x {}".format(b))
print("TLE x {}".format(c))
print("RE x {}".format(d))
|
from collections import defaultdict
n = int(input())
d = defaultdict(int)
for i in range(n):
d[input()] += 1
for v in ['AC', 'WA', 'TLE', 'RE']:
print(v, 'x', d[v])
| 1 | 8,739,918,851,492 | null | 109 | 109 |
x = int(input())
count_500 = 0
count_5 = 0
count_500 = x // 500
x -= 500 * count_500
count_5 = x // 5
x -= 5 * count_5
print(1000 * count_500 + 5 * count_5)
|
not_ans = []
not_ans.append(int(input()))
not_ans.append(int(input()))
for i in range(1, 4):
if i not in not_ans:
print(i)
| 0 | null | 76,623,002,721,912 | 185 | 254 |
def fibonacci(n):
if n == 0 or n == 1:
F[n] = 1
return F[n]
if F[n] is not None:
return F[n]
F[n] = fibonacci(n - 1) + fibonacci(n - 2)
return F[n]
n = int(input())
F = [None]*(n + 1)
print(fibonacci(n))
|
n = int(input())
memo = [-1]*(n+1)
memo[0] = 1
memo[1] = 1
def fib(n):
if memo[n] != -1:
return memo[n]
else:
ans = fib(n-1)+fib(n-2)
memo[n] = ans
return ans
print(fib(n))
| 1 | 1,753,511,100 | null | 7 | 7 |
Rad=int(input())
print(Rad**2)
|
x=int(input())
print(x*x)
| 1 | 144,590,906,293,340 | null | 278 | 278 |
n = int(input())
for cnt in range(n):
t = list(map(int, input().split()))
t.sort()
if t[2]**2 == t[1]**2 + t[0]**2:
print('YES')
else:
print('NO')
|
pnum,mtime = map(int,input().split(" "))
total = [list(input().split(" ")) for _ in range(pnum)]
cnt=0
tcnt=0
while len(total) > 0:
ztime = int(total[0][1]) - mtime
if ztime <= 0:
tcnt += int(total[0][1])
print(total[0][0],int(tcnt))
total.pop(0)
else:
total.append([total[0][0],ztime])
total.pop(0)
tcnt += mtime
cnt += 1
| 0 | null | 21,759,965,060 | 4 | 19 |
N,K = map(int,input().split())
m = 10**9 + 7
ans = 0
cnt_arr = [0]*(K+1)
for i in range(K,0,-1):
cnt = pow(int(K//i), N, mod=m)
j = 2
while i*j<=K:
cnt -= cnt_arr[i*j]
j+=1
cnt_arr[i]=cnt
ans += i*cnt
print(int(ans%m))
|
N, K = map(int, input().split())
MOD = 10**9+7
mx = [0]*(K+1)
ans = 0
for i in range(K, 0, -1):
mx[i] = pow(K//i, N, MOD)
for j in range(2*i, K+1, i):
mx[i] -= mx[j]
ans += i*mx[i]
print(ans%MOD)
| 1 | 36,590,886,868,300 | null | 176 | 176 |
mod=10**9+7
n,k=map(int,input().split())
cnt=[0]*k
for i in range(k,0,-1):
cnt[i-1]=pow(k//i,n,mod)
for j in range(i*2,k+1,i):
cnt[i-1]-=cnt[j-1]
cnt[i-1]%=mod
ans=0
for i in range(k):
ans+=cnt[i]*(i+1)%mod
print(ans%mod)
|
n, k = map(int, input().split())
mod = 10**9+7
def power(a, n, mod):
bi=str(format(n,"b")) #2進数
res=1
for i in range(len(bi)):
res=(res*res) %mod
if bi[i]=="1":
res=(res*a) %mod
return res
D = [0]*(k+1)
ans = 0
for i in reversed(range(1, k+1)):
a = k//i
d = power(a, n, mod)
j = 1
while i*j <= k:
d -= D[i*j]
j += 1
D[i] = d
ans += (d*i)%mod
print(ans%mod)
| 1 | 36,745,721,897,180 | null | 176 | 176 |
from collections import Counter
S = input()
S = S + '0'
mod = 2019
p = [-1] * len(S)
r = 0
d = 1
for i,s in enumerate(S[::-1]):
t = int(s)%mod
r += t*d
r %= mod
d = d*10%mod
p[i] = r
ans = 0
c = Counter(p)
for k,n in c.most_common():
if n > 1:
ans += n*(n-1)//2
else:break
print(ans)
|
x = input()
print(int(x)*int(x)*int(x))
| 0 | null | 15,592,732,819,272 | 166 | 35 |
def main():
S, W = map(int, input().split())
un = "un" if W >= S else ""
print(un + "safe")
if __name__ == "__main__":
main()
|
from collections import Counter
n,*a = map(int,open(0).read().split())
s = set(a)
c = Counter(a)
m = max(s)
l = [True]*(m+1)
ans = 0
for i in range(1,m+1):
if i in s and l[i]:
if c[i] == 1:
ans += 1
for j in range(1,m//i+1):
l[i*j] = False
print(ans)
| 0 | null | 21,897,994,974,592 | 163 | 129 |
n = int(input())
alst = list(map(int, input().split()))
alst.sort()
bef = -1
for a in alst:
if bef == a:
print("NO")
break
bef = a
else:
print("YES")
|
N_List = list(map(int,input().split()))
print(N_List.index(0)+1)
| 0 | null | 43,654,897,782,132 | 222 | 126 |
def main():
H, W, M = (int(i) for i in input().split())
hc = [0]*(H+1)
wc = [0]*(W+1)
maps = set()
for _ in range(M):
h, w = (int(i) for i in input().split())
hc[h] += 1
wc[w] += 1
maps.add((h, w))
mah = max(hc)
maw = max(wc)
ans = mah+maw
hmaps = []
wmaps = []
for i, h in enumerate(hc):
if mah == h:
hmaps.append(i)
for i, w in enumerate(wc):
if maw == w:
wmaps.append(i)
if M < len(hmaps) * len(wmaps):
# 爆破対象の合計が最大になるマスがM個より多ければ,
# 必ず爆破対象がないマスに爆弾を置くことができる
# 逆にM個以下なら3*10^5のループにしかならないので
# このようにif文で分けなくても,必ずO(M)になるのでelse節のforを回してよい
print(ans)
else:
for h in hmaps:
for w in wmaps:
if (h, w) not in maps:
print(ans)
return
else:
print(ans-1)
if __name__ == '__main__':
main()
|
s=input()
if s=="hi" or s=="hihi" or s=="hihihi" or s=="hihihihi" or s=="hihihihihi":
print("Yes")
else:
print("No")
| 0 | null | 28,955,474,566,522 | 89 | 199 |
s=input()
if s=="hi" or s=="hihi" or s=="hihihi" or s=="hihihihi" or s=="hihihihihi":
print("Yes")
else:
print("No")
|
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 # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
# d = m - k[i] - k[j]
# if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも!!
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
def readInts():
return list(map(int,input().split()))
def I():
return int(input())
h = I()
w = I()
n = I()
if h < w:
for i in range(1,h+1):
if i * w >= n:
print(i)
exit()
else:
for i in range(1,w+1):
if i*h >= n:
print(i)
exit()
| 0 | null | 70,732,100,070,202 | 199 | 236 |
import itertools
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
num = [i+1 for i in range(N)]
p_ord = 0
q_ord = 0
cnt = 0
for pre in itertools.permutations(num, N):
if P == list(pre):
p_ord = cnt
if Q == list(pre):
q_ord = cnt
cnt += 1
print(abs(p_ord-q_ord))
|
w,h,x,y,r = map(int, input().split())
if x>= r and y >= r and x+r <= w and y+r <= h:
print('Yes')
else:
print('No')
| 0 | null | 50,747,667,485,862 | 246 | 41 |
import math
N = int(input())
# A = list(map(int, input().split()))
A = [int(x) for x in input().split(' ')]
a_max = [0] * (N+1)
a_min = [0] * (N+1)
a = [0] * (N+1)
#1.可・不可の判定
# 最下段からとりうる個数の範囲を考える
#0段目の範囲に1が含まれないならば”不可”(根=1)
for i in range(N+1):
if i == 0:
a_max[N-i] = A[N-i]
a_min[N-i] = A[N-i]
else:
a_max[N-i] = a_max[N-i+1] + A[N-i]
a_min[N-i] = math.ceil(a_min[N-i+1]/2) + A[N-i]
#check print
# for i in range(N+1):
# print(str(i) + ':----')
# print(a_min[i],a_max[i])
#最上段から個数のカウント
for i in range(N+1):
if i == 0:
a[i] = 1
else:
a[i] = min((a[i-1] - A[i-1])*2 , a_max[i])
#不可は-1を、可は個数の合計を
if a_min[0] > 1:
print(-1)
else:
print(sum(a))
|
N, M = map(int,input().split())
A=sorted(list(map(int, input().split())),reverse=True)
if A[M-1]>=sum(A)/(4*M):
print('Yes')
else:
print('No')
| 0 | null | 28,623,959,290,642 | 141 | 179 |
n, m, l = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
b = [list(map(int, input().split())) for _ in range(m)]
for i in a:
c = []
for j in zip(*b):
c.append(sum([k * l for k, l in zip(i, j)]))
print(*c)
|
x = int(input())
if x >= 30:
print("Yes")
else:
print("No")
| 0 | null | 3,622,348,342,022 | 60 | 95 |
N, M = map(int, input().split())
A = list(map(int, input().split()))
s = sum(A)
A = sorted(A, reverse=True)
ans = 'Yes'
for i in range(M):
if A[i]*(4*M) < s:
ans = 'No'
break
print(ans)
|
# -*- coding: utf-8 -*-
import sys
import copy
import collections
from bisect import bisect_left
from bisect import bisect_right
from collections import defaultdict
from heapq import heappop, heappush, heapify
import math
import itertools
import random
# NO, PAY-PAY
#import numpy as np
#import statistics
#from statistics import mean, median,variance,stdev
INF = float('inf')
def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))
def main():
N = inputInt()
ans = N-1
ans = ans // 2
print(ans)
if __name__ == "__main__":
main()
| 0 | null | 96,247,787,507,840 | 179 | 283 |
r = float(input())
pi = 3.141592653589
S = r * r * pi
L = 2 * r * pi
print(str(S) + " " + str(L))
|
import math
r = float(input())
s = r ** 2 * math.pi
l = 2 * r * math.pi
print("{:.6f}".format(s), "{:.6f}".format(l))
| 1 | 632,477,674,098 | null | 46 | 46 |
n,k = map(int,input().split())
a = list(map(int,input().split()))
ans = []
for i in range(k,n):
ans.append(a[i] - a[i-k])
for j in ans:
if j > 0:
print('Yes')
else:
print('No')
|
from sys import stdin,stdout
n,k=map(int,stdin.readline().split())
a=list(map(int,stdin.readline().split()))
for i in range(k,n):
print('Yes' if a[i]>a[i-k] else 'No')
| 1 | 7,130,222,965,310 | null | 102 | 102 |
class Stack:
def __init__(self):
self.values = []
self.n = 0
def pop(self):
if self.n == 0:
raise Exception("stack underflow")
else:
v = self.values[-1]
del self.values[-1]
self.n -= 1
return v
def push(self,x):
self.values.append(x)
self.n += 1
operators = set(['+', '-', '*'])
stack = Stack()
for op in raw_input().split(' '):
if op in operators:
b = stack.pop()
a = stack.pop()
if op == '+':
stack.push(a+b)
elif op == '-':
stack.push(a-b)
elif op == '*':
stack.push(a*b)
else:
raise Exception("Unkown operator")
else:
stack.push(int(op))
print stack.pop()
|
a = input().split()
b = []
for i in range(len(a)):
if a[i] == "+":
b[-2] = b[-2] + b[-1]
b.pop()
elif a[i] == "-":
b[-2] = b[-2] - b[-1]
b.pop()
elif a[i] == "*":
b[-2] = b[-2] * b[-1]
b.pop()
else:
b.append(int(a[i]))
print(b[-1])
| 1 | 35,473,608,590 | null | 18 | 18 |
import random
class Dice:
def __init__(self):
self.u=1
self.w=2
self.s=3
self.e=4
self.n=5
self.d=6
self.dic={"W":0,"S":1,"E":2,"N":3}
def __init__(self,u,w,s,e,n,d):
self.u=u
self.w=w
self.s=s
self.e=e
self.n=n
self.d=d
self.dic={"W":0,"S":1,"E":2,"N":3}
def rot(self,way):
if isinstance(way,str):
way=self.dic[way]
if way==0:
c=self.u
self.u=self.e
self.e=self.d
self.d=self.w
self.w=c
elif way==1:
c=self.u
self.u=self.n
self.n=self.d
self.d=self.s
self.s=c
elif way==2:
c=self.u
self.u=self.w
self.w=self.d
self.d=self.e
self.e=c
else :
c=self.u
self.u=self.s
self.s=self.d
self.d=self.n
self.n=c
lst=["W","S","E","N"]
u,s,e,w,n,d=map(int,input().split())
N=int(input())
dice=Dice(u,w,s,e,n,d)
for i in range(N):
top,front=map(int,input().split())
while True:
if dice.u==top and dice.w==front:
break
else:
dice.rot(random.choice(lst))
print(dice.s)
|
class dice:
def __init__(self,label):
self.label = {i+1: l for i,l in enumerate(label)}
def roll(self,op):
l = self.label
if op=='N': self.label = {1:l[2], 2:l[6], 3:l[3], 4:l[4], 5:l[1], 6:l[5]}
elif op=='E': self.label = {1:l[4], 2:l[2], 3:l[1], 4:l[6], 5:l[5], 6:l[3]}
elif op=='W': self.label = {1:l[3], 2:l[2], 3:l[6], 4:l[1], 5:l[5], 6:l[4]}
elif op=='S': self.label = {1:l[5], 2:l[1], 3:l[3], 4:l[4], 5:l[6], 6:l[2]}
def yaw(self,op):
l = self.label
if op=='CW' : self.label = {1:l[1], 2:l[3], 3:l[5], 4:l[2], 5:l[4], 6:l[6]}
elif op=='CCW': self.label = {1:l[1], 2:l[4], 3:l[2], 4:l[5], 5:l[3], 6:l[6]}
def get_label(self,i):
return self.label[i]
if __name__ == '__main__':
d0 = dice(list(map(int,input().split())))
q = int(input())
for _ in range(q):
t,f = list(map(int,input().split()))
for _ in range(3):
if d0.get_label(1) == t: break
d0.roll('E')
if d0.get_label(1) != t:
d0.roll('N')
if d0.get_label(1) != t:
for _ in range(2): d0.roll('N')
if d0.get_label(2) != f:
for _ in range(3):
d0.yaw('CW')
if d0.get_label(2) == f: break
print(d0.get_label(3))
| 1 | 261,433,032,350 | null | 34 | 34 |
import sys
input = sys.stdin.readline
R, C, K = map(int, input().split())
item = [[0 for _ in range(C + 1)] for _ in range(R + 1)]
for _ in range(K):
r, c, v = map(int, input().split())
item[r][c] = v
# dp[n][i][j] = その行で取得したアイテムがn個で、(i,j)でのmax_value
dp = [[[0 for _ in range(C + 1)]for _ in range(R + 1)]for _ in range(4)]
for i in range(R + 1):
for j in range(C + 1):
# 下に移動
if i <= R - 1:
# アイテムを取らない
dp[0][i + 1][j] = max(dp[0][i + 1][j],
dp[0][i][j],
dp[1][i][j],
dp[2][i][j],
dp[3][i][j])
# アイテムを取る
dp[1][i + 1][j] = max(dp[1][i + 1][j],
dp[0][i][j] + item[i + 1][j],
dp[1][i][j] + item[i + 1][j],
dp[2][i][j] + item[i + 1][j],
dp[3][i][j] + item[i + 1][j])
# 右に移動
if j <= C - 1:
# アイテムを取らない
dp[0][i][j + 1] = max(dp[0][i][j + 1], dp[0][i][j])
dp[1][i][j + 1] = max(dp[1][i][j + 1], dp[1][i][j])
dp[2][i][j + 1] = max(dp[2][i][j + 1], dp[2][i][j])
dp[3][i][j + 1] = max(dp[3][i][j + 1], dp[3][i][j])
# アイテムを取る
dp[1][i][j + 1] = max(dp[1][i][j + 1],
dp[0][i][j] + item[i][j + 1])
dp[2][i][j + 1] = max(dp[2][i][j + 1],
dp[1][i][j] + item[i][j + 1])
dp[3][i][j + 1] = max(dp[3][i][j + 1],
dp[2][i][j] + item[i][j + 1])
ans = max(dp[0][R][C], dp[1][R][C], dp[2][R][C], dp[3][R][C])
print(ans)
|
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def Rtest(T):
case,err=0,0
for i in range(T):
inp=INP()
a1,ls=naive(*inp)
a2=solve(*inp)
if a1!=a2:
print((a1,a2),inp)
err+=1
case+=1
print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
org_inp=[];g=[[] for i in range(V)]
FromStdin=True if ls==None else False
for i in range(E):
if FromStdin:
inp=LI()
org_inp.append(inp)
else:
inp=ls[i]
if len(inp)==2:
a,b=inp;c=1
else:
a,b,c=inp
if index==1:a-=1;b-=1
aa=(a,c);bb=(b,c);g[a].append(bb)
if not Directed:g[b].append(aa)
return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
mp=[boundary]*(w+2);found={}
for i in R(h):
s=input()
for char in search:
if char in s:
found[char]=((i+1)*(w+2)+s.index(char)+1)
mp_def[char]=mp_def[replacement_of_found]
mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
mp+=[boundary]*(w+2)
return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
rt=[0]
for i in ls:rt+=[rt[-1]+i]
return rt
def bit_combination(n,base=2):
rt=[]
for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
return rt
def gcd(x,y):
if y==0:return x
if x%y==0:return y
while x%y!=0:x,y=y,x%y
return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
if show_flg:print(*inp,end=end)
mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()
show_flg=False
show_flg=True
ans=0
h,w,k=LI()
v=[[0]*(w+1) for i in range(h+1)]
for i in rep(k):
a,b,x=LI()
v[a][b]=x
dp=[[[0]*(w+1) for i in range(h+1)] for i in range(4)]
for i in range(1,h+1):
for j in range(1,w+1):
up_max=max(dp[x][i-1][j]for x in range(4))
dp[0][i][j]=up_max
if v[i][j]!=0:
dp[1][i][j]=max(dp[1][i][j],up_max+v[i][j])
dp[0][i][j]=max(dp[0][i][j],dp[0][i][j-1])
for x in range(1,4)[::-1]:
dp[x][i][j]=max(dp[x][i][j],dp[x][i][j-1],dp[x-1][i][j-1]+v[i][j])
ans=max([dp[x][h][w]for x in range(4)])
print(ans)
| 1 | 5,593,937,503,032 | null | 94 | 94 |
import math
N, X, T = map(int, input().split())
a = math.ceil(N/X)
b = a * T
print(b)
|
t1,t2 = map(int, input().split())
a1,a2 = map(int, input().split())
b1,b2 = map(int, input().split())
d1=(a1-b1)*t1
d2=(a2-b2)*t2
if abs(d1) == abs(d2):
print("infinity")
exit()
if abs(d1) > abs(d2) or d1*d2>0:
print(0)
exit()
dif = abs(d2) - abs(d1)
ans=2*(abs(d1)//dif)
if abs(d1)%dif != 0:
ans+=1
print(ans)
| 0 | null | 67,853,019,062,432 | 86 | 269 |
import sys
# \n
def input():
return sys.stdin.readline().rstrip()
def main():
N, K = map(int, input().split())
A = list(map(int, input().split()))
F = list(map(int, input().split()))
A.sort(reverse=True) # 0(NlogN)
F.sort() # O(NlogN)
def train(X, Y, T): # O(N) ans: 回数
ans = 0
for i in range(len(X)):
ans += max(0, X[i] - T // Y[i])
return ans
ok = 10**18+1 #時間
ng = -1
while ok - ng > 1:
mid = (ok + ng) // 2 #時間
ans = train(A,F,mid) #kaisuu
if ans >K:
ng =mid
else:
ok =mid
print(ok)
if __name__ == "__main__":
main()
|
s = list(input())
nick = s[0]+s[1]+s[2]
print(nick)
| 0 | null | 90,039,423,979,228 | 290 | 130 |
import sys
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
N, U, V = lr()
graph = [[] for _ in range(N+1)] # 1-indexed
for _ in range(N-1):
a, b = lr()
graph[a].append(b)
graph[b].append(a)
def dfs(start): # 木グラフの時
dist = [-1] * (N+1)
dist[start] = 0
stack = [start]
while stack:
s = stack.pop()
for x in graph[s]:
if dist[x] != -1:
continue
dist[x] = dist[s] + 1
stack.append(x)
return dist
dist_U = dfs(U); dist_V = dfs(V)
answer = 0
for u, v in zip(dist_U[1:], dist_V[1:]):
if v > u:
x = v - 1
if x > answer:
answer = x
print(answer)
|
import heapq
import sys
input = sys.stdin.readline
def dijkstra_heap(s,edge,n):
#始点sから各頂点への最短距離
d = [10**20] * n
used = [True] * n #True:未確定
d[s] = 0
used[s] = False
edgelist = []
for a,b in edge[s]:
heapq.heappush(edgelist,a*(10**6)+b)
while len(edgelist):
minedge = heapq.heappop(edgelist)
#まだ使われてない頂点の中から最小の距離のものを探す
if not used[minedge%(10**6)]:
continue
v = minedge%(10**6)
d[v] = minedge//(10**6)
used[v] = False
for e in edge[v]:
if used[e[1]]:
heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
return d
def main():
N, u, v = map(int, input().split())
u -= 1
v -= 1
edge = [[] for i in range(N)]
for _ in range(N-1):
A, B = map(int, input().split())
A -= 1
B -= 1
edge[A].append([1,B])
edge[B].append([1,A])
d1 = dijkstra_heap(u,edge, N)
d2 = dijkstra_heap(v,edge, N)
ans = 0
for i in range(N):
if d1[i] < d2[i]:
ans = max(ans, d2[i]-1)
print(ans)
if __name__ == "__main__":
main()
| 1 | 117,587,065,672,998 | null | 259 | 259 |
import sys
#UnionFindTreeクラスの定義
class UnionFind():
#クラスコンストラクタ
#selfはインスタンス自身
def __init__(self, n):
#親ノードを-1に初期化する
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]
#xとyの木を併合する
def union(self, x, y):
#x,yの根をX,Yとする
X = self.find(x)
Y = self.find(y)
#根が同じなら結合済み
if X == Y:
return
#ノード数が多い方をXとする
if self.parents[X] > self.parents[Y]:
X, Y = Y, X
#XにYのノード数を足す
self.parents[X] += self.parents[Y]
#Yの根をXとする
self.parents[Y] = X
N, M = map(int, input().split())
info = [tuple(map(int, s.split())) for s in sys.stdin.readlines()]
#UnionFindインスタンスの生成
uf = UnionFind(N)
for a, b in info:
#インデックスを調整し、a,bの木を結合
a -= 1; b -= 1
uf.union(a, b)
ans = min(uf.parents)
print(-ans)
|
'''
Created on 2020/09/03
@author: harurun
'''
from dataclasses import *
@dataclass
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
def main():
import sys
pin=sys.stdin.readline
N,M=map(int,pin().split())
uf=UnionFind(N)
for i in range(M):
A,B=map(int,pin().split())
A-=1
B-=1
uf.union(A, B)
ans=0
for j in range(N):
ans=max(ans,uf.size(j))
print(ans)
return
main()
#解説AC
| 1 | 3,975,562,709,534 | null | 84 | 84 |
N=input().split()
X=N[0]
Y=N[1]
Z=N[2]
print(Z + ' ' + X + ' ' + Y)
|
num = input().split(" ")
a = int(num[0])
b = int(num[1])
c = a/b
print(int(a/b),int(a%b),"%f" % c)
| 0 | null | 19,413,681,288,362 | 178 | 45 |
import sys
def main():
for line in iter(sys.stdin.readline, ""):
#print (line)
a = line.rstrip("\n")
tmp = a.split(" ")
a = int(tmp[0])
b = int(tmp[1])
n = int(tmp[2])
cnt = 0
for i in range(1, n+1):
if (n % i == 0) and (a <= i and i <= b):
cnt = cnt + 1
#print (i)
print (cnt)
if __name__ == "__main__":
main()
|
a, b ,c = [int(i) for i in input().split()]
total = 0
for d in range(a, b + 1):
if c % d == 0:
total += 1
print(total)
| 1 | 561,899,262,452 | null | 44 | 44 |
#!/usr/bin/env python3
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]
def inside(y, x, H, W):
return 0 <= y < H and 0 <= x < W
def ceil(a, b):
return (a + b - 1) // b
def sum_of_arithmetic_progression(s, d, n):
return n * (2 * s + (n - 1) * d) // 2
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
g = gcd(a, b)
return a / g * b
def solve():
N = int(input())
A = list(map(int, input().split()))
d = defaultdict(int)
ans = 1
d[-1] = 3
for a in A:
ans *= (d[a - 1] - d[a])
ans %= 1000000007
d[a] += 1
print(ans)
def main():
solve()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
n = I()
a = LI()
ans = 1
cnt = [0] * (n+1)
for i in range(n):
if a[i] == 0:
ans *= 3 - cnt[0]
ans %= mod
else:
ans *= cnt[a[i]-1] - cnt[a[i]]
ans %= mod
cnt[a[i]] += 1
print(ans)
| 1 | 130,186,736,403,430 | null | 268 | 268 |
import sys
input = sys.stdin.buffer.readline
n = int(input())
# n+1個
A = list(map(int, input().split()))
if n == 0:
if A[0] == 1:
print(1)
else:
print(-1)
exit()
if A[0] > 0:
print(-1)
exit()
ans = 0
max2 = 0
kouho = [0] * (n + 1)
for i in range(n, 0, -1):
max1 = pow(2, i)
max2 += A[i]
max2 = min(max1, max2)
kouho[i] = max2
kouho[0] = 1
not_leave = 1
for i in range(1, n + 1):
cnt = 0
not_leave *= 2
temp = min(kouho[i], not_leave)
ans += temp
not_leave -= A[i]
if not_leave <= 0 and i != n:
print(-1)
exit()
if i == n:
if not_leave == 0:
continue
elif not_leave < 0:
print(-1)
exit()
ans += 1
print(ans)
|
S = int(input())
S = S % (24 * 3600)
hour = S // 3600
S %= 3600
minutes = S // 60
S %= 60
seconds = S
print("%d:%d:%d" % (hour, minutes, seconds))
| 0 | null | 9,501,235,548,288 | 141 | 37 |
def INT():
return int(input())
def MI():
return map(int, input().split())
def LI():
return list(map(int, input().split()))
N = INT()
cnt = 0
for _ in range(N):
D1, D2 = MI()
if D1 == D2:
cnt += 1
else:
cnt = 0
if cnt == 3:
print("Yes")
exit()
print("No")
|
import sys
import os
import math
import bisect
import itertools
import collections
import heapq
import queue
import array
# 時々使う
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque
# 再帰の制限設定
sys.setrecursionlimit(10000000)
def ii(): return int(sys.stdin.buffer.readline().rstrip())
def il(): return list(map(int, sys.stdin.buffer.readline().split()))
def fl(): return list(map(float, sys.stdin.buffer.readline().split()))
def iln(n): return [int(sys.stdin.buffer.readline().rstrip())
for _ in range(n)]
def iss(): return sys.stdin.buffer.readline().decode().rstrip()
def sl(): return list(map(str, sys.stdin.buffer.readline().decode().split()))
def isn(n): return [sys.stdin.buffer.readline().decode().rstrip()
for _ in range(n)]
def lcm(x, y): return (x * y) // math.gcd(x, y)
MOD = 10 ** 9 + 7
INF = float('inf')
def main():
if os.getenv("LOCAL"):
sys.stdin = open("input.txt", "r")
N = ii()
D = [il() for _ in range(N)]
for i in range(N - 2):
for j in range(i, i + 3):
if D[j][0] != D[j][1]:
break
else:
print('Yes')
exit()
else:
print('No')
if __name__ == '__main__':
main()
| 1 | 2,458,682,822,650 | null | 72 | 72 |
n = input().split(" ")
for i,j in enumerate(n,1):
if 0 == int(j):
print(i)
|
s = ""
while True:
try:
s += input().lower()
except:
break
dic = {}
orda = ord("a")
ordz = ord("z")
for c in s:
if orda <= ord(c) <= ordz:
try:
dic[c] += 1
except:
dic[c] = 1
for i in range(orda,ordz + 1):
c = chr(i)
try:
print("%s : %d" % (c, dic[c]))
except:
print("%s : %d" % (c, 0))
| 0 | null | 7,594,106,080,048 | 126 | 63 |
n,t=map(int,input().split())
l=[list(map(int,input().split())) for _ in range(n)]
dp=[0]*(t+max(l)[0])
l.sort()
for a,b in l:
for i in range(0,t+a)[::-1]:
if i-a>=0:
dp[i]=max(dp[i],dp[i-a]+b)
print(max(dp[t:]))
|
n, m = map(int, input().split())
a = 1
b = m + 1
while a < b:
print(a, b)
a += 1
b -= 1
a = m + 2
b = 2 * m + 1
while a < b:
print(a, b)
a += 1
b -= 1
| 0 | null | 89,978,509,525,190 | 282 | 162 |
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
idx_B = M-1
m = sum(B)
an = M
ans = 0
for a in [0] + A:
m += a
while idx_B >= 0 and m > K:
m -= B[idx_B]
idx_B -= 1
an -= 1
if m > K:
break
if an > ans:
ans = an
an += 1
print(ans)
|
n=int(input())
a=list(map(int,input().split()))
q=int(input())
s=sum(a)
data=[0]*10**5
for i in a:
data[i-1]+=1
for i in range(q):
b,c=map(int,input().split())
s+=(c-b)*data[b-1]
print(s)
data[c-1]+=data[b-1]
data[b-1]=0
| 0 | null | 11,529,050,845,426 | 117 | 122 |
from collections import defaultdict
d = defaultdict(lambda: 0)
N = int(input())
for _ in range(N):
ord, str = input().split()
if ord == 'insert':
d[str] = 1
else:
if str in d:
print('yes')
else:
print('no')
|
n,m = map(int,input().split())
A = list(map(int,input().split()))
judge = sum(A) / (4 * m)
ans = []
for i in range(n):
if A[i] < judge :
continue
else:
ans.append(A[i])
print("Yes") if len(ans) >= m else print("No")
| 0 | null | 19,233,287,017,520 | 23 | 179 |
n = int(input())
L = list(map(int, input().split()))
L.sort()
ans = 0
for i, a in enumerate(L[2:]):
k = i + 1
for j, b in enumerate(L[:i + 2]):
while j < k and a - b < L[k]:
k -= 1
ans += i - max(k, j) + 1
print(ans)
|
import bisect
N = int(input())
Ls = list(map(int, input().split(" ")))
Ls.sort()
ans = 0
for i in range(0,N-2):
for j in range(i+1,N-1):
k = bisect.bisect_left(Ls,Ls[i]+Ls[j])
ans += k - (j + 1)
print(ans)
| 1 | 171,229,062,560,320 | null | 294 | 294 |
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
|
n = input()
data = []
space = []
for i in ['S ', 'H ', 'C ', 'D ']:
for j in map( str , xrange(1, 14)):
data.append(i + j)
for i in xrange(n):
data.remove(raw_input())
for i in xrange(len(data)):
print data[i]
| 1 | 1,029,423,127,372 | null | 54 | 54 |
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7
def prime_factorization(n):
res = []
for i in range(2, int(pow(n, 0.5)) + 1):
if n % i == 0:
ex = 0
while n % i == 0:
ex += 1
n //= i
res.append([i, ex])
if n != 1:
res.append([n, 1])
return res
def resolve():
n = int(input())
A = list(map(int, input().split()))
prime = [0] * max(A)
for a in A:
primes = prime_factorization(a)
for num, ex in primes:
prime[num - 1] = max(prime[num - 1], ex)
L = 1
for i in range(len(prime)):
if prime[i] == 0:
continue
L *= pow(i + 1, prime[i])
res = 0
for a in A:
res += L * pow(a, mod - 2, mod)
res %= mod
print(res)
if __name__ == '__main__':
resolve()
|
itemCount = int(input())
items = list(map(int, input().split(" ")))
def bubbleSort(items, itemCount):
hasPrevious = True
swapCount = 0
while hasPrevious:
hasPrevious = False
for index in reversed(range(1, itemCount )):
if items[index] < items[index - 1]:
items[index], items[index - 1] = [items[index - 1], items[index]]
hasPrevious = True
swapCount += 1
print(" ".join(map(str, items)))
print(swapCount)
bubbleSort(items, itemCount)
| 0 | null | 43,670,839,915,658 | 235 | 14 |
s=input()
t=input()
count_min = 1000
for i in range(len(s)-len(t)+1):
count = 0
for j in range(len(t)):
if s[i+j] != t[j]:
count+=1
if count < count_min:
count_min = count
print(count_min)
|
S = input()
T = input()
m = 0
for i in range(len(S) - len(T) + 1):
cnt = 0
for j in range(len(T)):
if S[i+j] == T[j]:
cnt += 1
m = max(m, cnt)
ANS = len(T) - m
print(ANS)
| 1 | 3,682,692,758,562 | null | 82 | 82 |
def main():
import sys
input=sys.stdin.buffer.readline
n=int(input())
d=[0]*n+[1<<c-97for c in input()[:n]]
for i in range(n-1,0,-1):d[i]=d[i+i]|d[i-~i]
r=[]
for _ in range(int(input())):
q,a,b=input().split()
i,s=int(a)+n-1,0
if q<b'2':
d[i]=1<<b[0]-97
while i:
i//=2
d[i]=d[i+i]|d[i-~i]
continue
j=int(b)+n
while i<j:
if i&1:
s|=d[i]
i+=1
if j&1:
j-=1
s|=d[j]
i//=2
j//=2
r+=bin(s).count('1'),
print(' '.join(map(str,r)))
main()
|
SIZE = 2**20 # 2**20 > N=500000
class SegmentTree:
def __init__(self, size):
self.size = size
self.seg = [0] * (2 * size)
def update(self, pos, ch):
# update leaf
i = self.size + pos - 1
self.seg[i] = 1 << (ord(ch)-ord('a'))
# update tree
while i > 0:
i = (i - 1) // 2
self.seg[i] = self.seg[i*2+1] | self.seg[i*2+2]
def _query(self, a, b, k, left, right):
if right<a or b<left:
return 0
if a<=left and right<=b:
return self.seg[k]
vl = self._query(a,b,k*2+1, left, (left+right)//2)
vr = self._query(a,b,k*2+2, (left+right)//2+1, right)
return vl | vr
def query(self, a, b):
return self._query(a,b,0,0,self.size-1)
def resolve():
N = int(input())
S = input().strip()
Q = int(input())
table = [[] for _ in range(26)]
sg = SegmentTree(SIZE)
for i,ch in enumerate(S):
sg.update(i, ch)
for i in range(Q):
query = input().strip().split()
if query[0] == '1':
pos = int(query[1])-1
sg.update(pos, query[2])
else:
left = int(query[1])-1
right = int(query[2])-1
bits = sg.query(left, right)
count = 0
for j in range(26):
count += (bits>>j) & 1
print(count)
resolve()
| 1 | 62,631,004,612,160 | null | 210 | 210 |
N = int(input())
d_list = list(map(int,input().split()))
ans = 0
for i in range(N-1):
for j in range(i+1,N):
ans += d_list[i] * d_list[j]
print(ans)
|
N=int(input())
d=list(map(int,input().split()))
l=len(d)
s=0
for i in range(l):
for j in range(i+1,l):
s+=d[i]*d[j]
print(s)
| 1 | 168,141,699,776,160 | null | 292 | 292 |
a,b=map(int,input().split())
x=a-(b+b)
print(x if x>=0 else 0)
|
A,B = map(int,input().split())
print(max(A-B-B,0))
| 1 | 166,009,057,460,610 | null | 291 | 291 |
n = int(input())
if n%2 == 1:
print(0)
exit()
num = 5
i = 1
ans = 0
while num**i < n:
ans += n//num**i//2
i += 1
print(ans)
|
n=int(input())
box1=[]
box2=[]
for i in range(n):
i=input().rstrip().split(" ")
box1.append(i[0])
box2.append(int(i[1]))
num=box1.index(input())
del box2[:num+1]
print(sum(box2))
| 0 | null | 106,594,946,575,012 | 258 | 243 |
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()
n,m = na()
a,b = 1,n-(n%2)
for i in range(m):
if n%2 == 0 and i == (m+1)//2:
a += 1
print(a,b)
a,b = a+1, b-1
|
from sys import setrecursionlimit, exit
setrecursionlimit(1000000000)
def main():
n, m = map(int, input().split())
a = 1
d = n - 1
for _ in range(m):
if d % 2 == 1 and (d == n // 2 or d == n // 2 - 1):
d -= 1
print(a, a + d)
a += 1
d -= 2
main()
| 1 | 28,671,914,295,210 | null | 162 | 162 |
from collections import Counter
from collections import defaultdict
from collections import deque
from functools import reduce
import math
import itertools
import heapq
import numpy as np
import bisect
import sys
sys.setrecursionlimit(10**6)
def bfs(s,n,node):
#頂点が探索済みかどうかのチェック配列
check=[False for _ in range(n)]
check[s]=True
#次見る頂点を格納するキュー
queue=deque([s])
visited_num=1
#問題固有の配列
#color_check=[[True for _ in range(l)] for _ in range(n)]
color=[-1 for _ in range(n)]
color[s]=0
while visited_num<n:
#グラフが全連結ではない場合
if len(queue)==0:
#空配列を返す
#現状までの計算済み配列を返してもいいと思う
return color
now_vertex=queue.popleft()
#インデックスがない場合は
for next_vertex in node[now_vertex]:
if check[next_vertex]==True:
continue
queue.append(next_vertex)
check[next_vertex]=True
#問題固有の計算
color[next_vertex]=color[now_vertex]+1
visited_num+=1
return color
#n=int(input())z
#n,m=list(map(int,input().split()))
#a=list(map(int,input().split()))
ceil=lambda x,y: (x+y-1)//y
input_list = lambda : list(map(int,input().split()))
#n=int(input())
#n,m=input_list()
#a=input_list()
s=input()
ans=0
s=[i if i!="?" else "D" for i in s]
print("".join(s))
|
s = input()
for i in range(len(s)):
if s[i] == '?':
if i == 0 and len(s) == 1:
s = s.replace('?','D',1)
elif i == 0 and s[1] == 'D':
s = s.replace('?','P',1)
elif i == 0 and s[1] == 'P':
s = s.replace('?','D',1)
elif i == 0 and s[1] == '?':
s = s.replace('?','D',1)
elif s[i-1] =='P':
s = s.replace('?','D',1)
elif s[i-1] =='D' and (i ==len(s)-1):
s = s.replace('?','D',1)
elif s[i-1] =='D' and (i <len(s)-1 and(s[i+1] == 'P' or s[i+1] == '?')):
s = s.replace('?','D',1)
else:
s = s.replace('?','P',1)
print(s)
| 1 | 18,380,966,814,980 | null | 140 | 140 |
import math
a,b=map(int,input().split())
ans=a*b//(math.gcd(a,b))
print(ans)
|
def gcd(a,b):
while a!=0 and b!=0:
if a>b:
c = a
a = b
b = c
b %= a
return max(a,b)
a,b = map(int,input().split())
print(a*b//gcd(a,b))
| 1 | 113,343,792,915,068 | null | 256 | 256 |
# Begin Header {{{
from math import gcd
from collections import Counter, deque, defaultdict
from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
from bisect import bisect_left, bisect_right, bisect, insort_left, insort_right, insort
from itertools import accumulate, product, permutations, combinations, combinations_with_replacement
# }}} End Header
# _________コーディングはここから!!___________
def cmb(n, r, mod):
if ( r<0 or r>n ):
return 0
r = min(r, n-r)
return g1[n] * g2[r] * g2[n-r] % mod
s = int(input())
mod = 10**9+7 #出力の制限
N = 10**4
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル
for i in range( 2, N + 1 ):
g1.append( ( g1[-1] * i ) % mod )
inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
g2.append( (g2[-1] * inverse[-1]) % mod )
ans = 0
for x in range(1, s):
if s < 3*x: break
ans+=cmb(s-3*x + x-1, s-3*x, mod)
ans%=mod
print(ans)
|
while True:
x, y = map(int, raw_input().split())
if x == 0 and y == 0:
break
elif x <= y:
print("%d %d" % (x, y))
elif x > y:
print("%d %d" % (y, x))
| 0 | null | 1,919,396,349,500 | 79 | 43 |
n,k = map(int, input().split())
a = list(map(int, input().split()))
gki = sum(a[0:k])
tmp = gki
rng = k
for i in range(k,n):
tmp = tmp-a[i-k]+a[i]
if tmp>gki:
gki = tmp
rng = i+1
E = 0
for i in a[rng-k:rng]:
E += (i+1)/2
print(E)
|
def find_primes(n):
ps = []
t = [True] * n
t[0] = t[1] = False
for i in range(2, n):
if not t[i]:
continue
ps.append(i)
for j in range(i, n, i):
t[j] = False
return ps
def solve(string):
n = int(string)
if n == 1:
return "0"
rn = int(n**0.5 + 1)
ps = find_primes(rn)
ans = 0
for i in ps:
k = 1
while n % (i**k) == 0:
ans += 1
n //= i**k
k += 1
return str(ans + (n >= rn))
if __name__ == '__main__':
import sys
print(solve(sys.stdin.read().strip()))
| 0 | null | 45,775,425,102,252 | 223 | 136 |
N,K = map(int,input().split())
have = [0] * N
for i in range(K):
d = int(input())
As = list(map(int,input().split()))
for j in range(d):
have[As[j]-1] += 1
ans = 0
for i in range(N):
if have[i] == 0:
ans += 1
print(ans)
|
N, K = map(int, input().split())
count = 0
num_people = []
num_people_snacks = []
for i in range(1, N + 1):
num_people.append(i)
while K > count:
d = int(input())
A = list(map(int, input().split()))
for k in A:
num_people_snacks.append(k)
count += 1
ans = 0
for j in range(N):
if num_people[j] not in num_people_snacks:
ans += 1
print(ans)
| 1 | 24,660,805,394,320 | null | 154 | 154 |
def main(s, w):
if s > w:
return 'safe'
else:
return 'unsafe'
if __name__ == '__main__':
S, W = map(int, input().split(' '))
print(main(S, W))
|
s,w = list(map(int,input().split()))
if w >= s:
print('unsafe')
else:
print('safe')
| 1 | 29,291,901,254,262 | null | 163 | 163 |
# ALDS1_5_B Merge Sort
import sys
count = 0
def merge(A, left, mid, right):
global count
l = A[left: mid]
r = A[mid: right]
l.append(float('inf'))
r.append(float('inf'))
i = 0
j = 0
for k in range(left, right, 1):
count += 1
if l[i] <= r[j]:
A[k] = l[i]
i += 1
else:
A[k] = r[j]
j += 1
def merge_sort(A, left, right):
if left + 1 < right:
mid = (left + right) // 2
merge_sort(A, left, mid)
merge_sort(A, mid, right)
merge(A, left, mid, right)
n = int(input())
S = [int(i) for i in sys.stdin.readline().strip().split()]
merge_sort(S, 0, n)
print(' '.join(map(str, S)))
print(count)
|
def merge(A, left, mid, right):
global c
n1 = mid - left
n2 = right - mid
L = [0 for e in range(n1+1)]
R = [0 for e in range(n2+1)]
L = A[left:mid] + [10 ** 9]
R = A[mid:right] + [10 ** 9]
i = 0
j = 0
for k in range(left,right):
if L[i] <= R[j]:
A[k] = L[i]
i = i + 1
else:
A[k] = R[j]
j = j + 1
c += right - left
def mergeSort(A, left, right):
if left+1 < right:
mid = (left + right)//2
mergeSort(A, left, mid)
mergeSort(A, mid, right)
merge(A, left, mid, right)
if __name__ == "__main__":
n = int(input())
S = [int(e) for e in input().split()]
c = 0
mergeSort(S,0,n)
print(*S)
print(c)
| 1 | 109,635,300,218 | null | 26 | 26 |
k , x = (int(a) for a in input().split())
if k*500 >= x :
print("Yes")
else : print("No")
|
def func(K, X):
YEN = 500
ans = 'Yes' if YEN * K >= X else 'No'
return ans
if __name__ == "__main__":
K, X = map(int, input().split())
print(func(K, X))
| 1 | 98,321,412,752,988 | null | 244 | 244 |
n = int(input())
ls = [0]*n
ls1 = list(map(int, input().split()))
for i in ls1:
ls[i-1] += 1
for j in ls:
print(j)
|
import sys
def main():
N=int(sys.stdin.readline())
A=tuple(map(int,sys.stdin.readline().split()))
R=[0 for _ in range(N)]
for a in A:R[a-1]+=1
for r in R:print(r)
if __name__=='__main__':main()
| 1 | 32,735,514,276,640 | null | 169 | 169 |
# coding: utf-8
num = int(input())
count = 0
str = input().split()
table = [int(i) for i in str]
#全探索
for j in range(num): #ループ1
for k in range(j+1, num): #ループ2
for l in range(k+1, num): #ループ3
if table[j] != table[k] and table[k] != table[l] and table[j] != table[l]:
len = table[j] + table[k] + table[l] #周の長さ
ma = max(table[j], max(table[k], table[l])) #一番長い辺
rest = len - ma #残りの2辺の合計
if ma < rest: #最大の辺が残り2辺より小さければ三角形は成立する
count += 1
print(count)
|
from itertools import combinations
N = int(input())
L = list(map(int, input().split()))
count = 0
for C in combinations(L, 3):
l_list = list(C)
l_list.sort()
if l_list[2] > l_list[1] and l_list[1] > l_list[0]:
if l_list[2] < l_list[1] + l_list[0]:
count += 1
print(count)
| 1 | 5,067,106,894,640 | null | 91 | 91 |
# D - Sum of Divisors
N = int(input())
# 1と自分自身はかならず約数になるので、計算から除外
f = [2] * (N + 1)
for i in range(2, N//2 + 1):
j = 2
while True:
if i * j <= N:
f[i*j] += 1
j += 1
else:
break
ans = 1
for i in range(2, N + 1):
ans += f[i] * i
print(ans)
|
import sys
T1, T2 = map(int,input().split())
A1, A2 = map(int,input().split())
B1, B2 = map(int,input().split())
if A1 < B1:
A1, B1 = B1, A1
A2, B2 = B2, A2
if A1 * T1 + A2 * T2 > B1 * T1 + B2 * T2:
print(0)
sys.exit()
if A1 * T1 + A2 * T2 == B1 * T1 + B2 * T2:
print('infinity')
sys.exit()
N = (T1 * (A1 - B1) - 1) // (T1 * (B1 - A1) + T2 * (B2 - A2)) + 1
ans = N * 2 - 1
if N * (T1 * (B1 - A1) + T2 * (B2 - A2)) == T1 * (A1 - B1):
ans += 1
print(ans)
| 0 | null | 71,513,035,204,832 | 118 | 269 |
H, W = map(int, input().split())
s = [input() for _ in range(H)]
dp = [[float('inf') for _ in range(W)] for _ in range(H)]
if s[0][0] == '#':
dp[0][0] = 1
else:
dp[0][0] = 0
dx = [0, 1]
dy = [1, 0]
for i in range(H):
for j in range(W):
for k in range(2):
ni = i + dx[k]
nj = j + dy[k]
if ni >= H or nj >= W:
continue
add = 0
# print(i, j, ni, nj)
if s[i][j] == '.' and s[ni][nj] == '#': add += 1
dp[ni][nj] = min(dp[ni][nj], dp[i][j] + add)
# print(dp)
print(dp[H-1][W-1])
|
h, w = map(int, input().split())
h_odd = (h+1)//2
h_even = h//2
w_odd = (w+1)//2
w_even = w//2
if h == 1 or w ==1:
print(1)
else:
ans = h_odd * w_odd + h_even *w_even
print(ans)
| 0 | null | 49,729,270,341,310 | 194 | 196 |
N = int(input())
S = input()
print('Yes' if S[:len(S)//2] == S[len(S)//2:] else 'No')
|
a,b = map(int,input().split())
print(a//b,a%b,"{:.5f}".format(a/b))
| 0 | null | 73,910,935,149,058 | 279 | 45 |
import math
a, b, ca = map(float, input().split())
ca = math.radians(ca)
s = a * b * math.sin(ca) / 2
c = (a ** 2 + b ** 2 - 2 * a * b * math.cos(ca)) ** 0.5
h = b * math.sin(ca)
print("{:.5f}".format(s))
print("{:.5f}".format(a + b + c))
print("{:.5f}".format(h))
|
import math
a, b, c = map(float,input().split())
e = b*math.sin(math.radians(c))
print(a*e/2)
print(((a-b*math.cos(math.radians(c)))**2+e**2)**0.5+a+b)
print(e)
| 1 | 179,599,755,008 | null | 30 | 30 |
n = int(input())
a = list(map(int, input().split()))
cnt = [0] * (10 ** 6 + 1)
a.sort()
ans = 0
for i in a:
cnt[i] += 1
a = set(a)
for k in a:
for l in range(k * 2, (10 ** 6 + 1), k):
cnt[l] += 1
for m in a:
if cnt[m] == 1:
ans += 1
print(ans)
|
n = int(input())
a = list(map(int, input().split()))
from collections import Counter
c = Counter(a)
vals = [True]*(max(a)+1)
ans = 0
m = max(a)+1
for i in range(1, m):
if i not in c:
continue
if c[i]>=2:
vals[i] = False
for j in range(2*i, m, i):
vals[j] = False
ans = 0
for i in range(1, max(a)+1):
if vals[i] and i in c:
ans += 1
print(ans)
| 1 | 14,455,495,459,078 | null | 129 | 129 |
h, w = map(int, input().split())
mat = [[] for _ in range(h)]
for i in range(h):
mat[i] = input()
dp = [[float("inf")] * w for _ in range(h)]
if mat[0][0] == "#":
dp[0][0] = 1
else:
dp[0][0] = 0
for i in range(h):
for j in range(w):
if mat[i][j - 1] != mat[i][j]:
left = dp[i][j - 1] + 1
else:
left = dp[i][j - 1]
if mat[i - 1][j] != mat[i][j]:
top = dp[i - 1][j] + 1
else:
top = dp[i - 1][j]
dp[i][j] = min(dp[i][j], left, top)
print((dp[h - 1][w - 1] + 1) // 2)
|
import sys
from collections import deque
input = sys.stdin.readline
H, W = map(int, input().split())
grid = []
for _ in range(H):
grid.append(list(input().strip()))
q = deque()
# x, y, count, pre color
q.append((0, 0, 1 if grid[0][0] == "#" else 0, grid[0][0]))
visited = [[-1 for _ in range(W)] for _ in range(H)]
ans = float("inf")
while q:
x, y, count, pre = q.popleft()
# print(x, y, count, pre)
v_score = visited[y][x]
if v_score != -1 and v_score <= count:
continue
visited[y][x] = count
for dx, dy in ((1, 0), (0, 1)):
nx = x + dx
ny = y + dy
nc = count
if nx < 0 or W <= nx or ny < 0 or H <= ny:
continue
n_color = grid[ny][nx]
if n_color != pre and n_color == "#":
nc += 1
if nx == W-1 and ny == H-1:
ans = min(ans, nc)
print(ans)
sys.exit()
else:
if visited[ny][nx] != -1 and visited[ny][nx] <= nc:
continue
if count == nc:
q.appendleft((nx, ny, nc, n_color))
else:
q.append((nx, ny, nc, n_color))
# print(visited)
print(ans)
| 1 | 49,414,019,695,788 | null | 194 | 194 |
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())
x-=1;y-=1
fl=[0 for i in range(n-1)]
for i in range(n):
for j in range(i+1,n):
fl[min(abs(j-i),abs(j-x)+1+abs(y-i),abs(i-x)+1+abs(y-j))]+=1
print(*fl[1:],sep="\n")
print(0)
| 1 | 44,061,850,420,170 | null | 187 | 187 |
N = int(input())
L = [[int(l) for l in input().split()] for _ in range(N)]
L1 = [0]*N
L2 = [0]*N
for i in range(N):
L1[i] = L[i][0]+L[i][1]
L2[i] = L[i][0]-L[i][1]
L1.sort()
L2.sort()
print(max(L1[-1]-L1[0], L2[-1]-L2[0]))
|
n=int(input())
x=[0]*n
y=[0]*n
z=[]
w=[]
for i in range(n):
x[i],y[i]= list(map(int, input().strip().split()))
z.append(x[i]+y[i])
w.append(x[i]-y[i])
a=max(z)-min(z)
b=max(w)-min(w)
print(max(a,b))
| 1 | 3,425,858,475,940 | null | 80 | 80 |
A, B = input().split()
C = B + A
print(C)
|
s,t=input().split()
x=t+s
print(x)
| 1 | 103,036,776,440,432 | null | 248 | 248 |
n,x,y = map(int,input().split())
k = [0]*(n)
for i in range(1,n):
for j in range(i+1,n+1):
if i < x and j <= x:
k[j-i] += 1
elif i >= y and j > y:
k[j-i] += 1
elif x <= i < y and x< j <= y:
ind = min(j-i,i-x+y-j+1)
k[ind] += 1
elif i < x and x < j <= y:
ind = min(j-i,x-i+y-j+1)
k[ind] += 1
elif x <= i < y and y < j:
ind = min(j-i,i-x+1+j-y)
k[ind] += 1
elif i< x and j > y:
ind = x - i + 1 + j - y
k[ind] += 1
for i in range(1,n):
print(k[i])
|
n,m,l=map(int,input().split())
#基本的にワーシャルフロイドの場合、行列式のリストで距離を保管する
from scipy.sparse import csr_matrix
from scipy.sparse import csgraph
d = [[10**12 for i in range(n+1)] for i in range(n+1)]
for i in range(m):
x,y,z = map(int,input().split())
#有向グラフか無向グラフかによってここで場合わけが生じる
d[x][y] = z
d[y][x] = z
for i in range(n+1):
d[i][i] = 0 #自身のところに行くコストは0
q=int(input())
que=[]
for _ in range(q):
s,t=map(int,input().split())
que.append((s,t))
csr=csr_matrix(d)
K=csgraph.shortest_path(csr,method="FW",directed=True)
e = [[10**12 for i in range(n+1)] for i in range(n+1)]
for i in range(1,n+1):
for j in range(1,n+1):
if K[i][j]<=l:
e[i][j]=1
for i in range(n+1):
e[i][i]=0
A=csr_matrix(e)
ANS=csgraph.shortest_path(A,method="FW",directed=True)
for some in que:
s,t=some[0],some[1]
if int(ANS[s][t])<10**12:
print(int(ANS[s][t])-1)
else:
print(-1)
| 0 | null | 109,136,610,405,020 | 187 | 295 |
unused = input()
values = [x for x in input().split()]
print(' '.join(values[::-1]))
|
_ = input()
l = reversed(input().split())
print(' '.join(l))
| 1 | 976,878,834,750 | null | 53 | 53 |
def main():
N = int(input())
x, y = map(int, input().split())
a1 = x + y
a2 = x + y
b1 = y - x
b2 = y - x
N -= 1
while N != 0:
x, y = map(int, input().split())
a1 = max(a1, x + y)
a2 = min(a2, x + y)
b1 = max(b1, y - x)
b2 = min(b2, y - x)
N = N - 1
print(max(a1 - a2, b1 - b2))
main()
|
N=int(input())
xy=[tuple(map(int,input().split())) for _ in range(N)]
ans=0
zmi=10**10
zma=-10**10
wmi=10**10
wma=-10**10
for x,y in xy:
zmi=min(zmi,x+y)
zma=max(zma,x+y)
wmi=min(wmi,x-y)
wma=max(wma,x-y)
print(max(zma-zmi,wma-wmi))
| 1 | 3,419,849,215,452 | null | 80 | 80 |
N=int(input())
X=input()
popcount=X.count('1')
bi1=[]
bi0=[]
Xnum1 = 0
Xnum0 = 0
if popcount != 1:
for i in range(N):
if i==0: bi1.append(1)
else: bi1.append(bi1[i-1]*2%(popcount-1))
Xnum1 = (Xnum1 + int(X[N-i-1])*bi1[i])%(popcount-1)
for i in range(N):
if i==0: bi0.append(1)
else: bi0.append(bi0[i-1]*2%(popcount+1))
Xnum0 = (Xnum0 + int(X[N-i-1])*bi0[i])%(popcount+1)
for i in range(N):
if popcount==1 and X[i]=='1':
print(0)
continue
if X[i]=='1':
Xi = (Xnum1 - bi1[N-i-1])%(popcount-1)
else:
Xi = (Xnum0 + bi0[N-i-1])%(popcount+1)
ans = 1
while Xi!=0:
Xi = Xi % bin(Xi).count('1')
ans += 1
print(ans)
|
import numpy as np
N = int(input())
X = str(input())
num_one = X.count("1")
dp = [-1] * N
dp[0] = 0
def dfs(n):
if dp[n] == -1:
dp[n] = 1 + dfs(n % bin(n).count('1'))
return dp[n]
num_one = X.count("1")
bool_arr = np.array([True if X[N-i-1] == "1" else False for i in range(N)])
zero_ver = np.array([pow(2, i, num_one + 1) for i in range(N)])
zero_ver_sum = sum(zero_ver[bool_arr])
one_ver = -1
one_ver_sum = 0
flag = False
if num_one != 1:
one_ver = np.array([pow(2, i, num_one - 1) for i in range(N)])
one_ver_sum = sum(one_ver[bool_arr])
else:
flag = True
for i in range(1,N+1):
start = 0
if bool_arr[N-i] == False:
start = (zero_ver_sum + pow(2, N - i, num_one + 1)) % (num_one + 1)
print(dfs(start)+1)
else:
if flag:
print(0)
else:
start = (one_ver_sum - pow(2, N - i, num_one - 1)) % (num_one - 1)
print(dfs(start)+1)
| 1 | 8,149,068,114,528 | null | 107 | 107 |
import math
n = int(input())
x, y = math.floor(n / 1.08), math.ceil(n / 1.08)
ans = ":("
if int(x * 1.08) == n:
ans = x
elif int(y * 1.08) == n:
ans = y
print(ans)
|
n = int(input())
for i in range(1,n+1):
ans = int(i*1.08)
if ans == n:
print(i)
break
else:
print(":(")
| 1 | 125,269,284,298,960 | null | 265 | 265 |
#!/usr/bin/env python
# encoding: utf-8
class Solution:
def __init__(self):
self.count = 0
def shell_sort(self):
array_length = int(input())
array = []
# array_length = 10
# array = [15, 12, 8, 9, 3, 2, 7, 2, 11, 1]
for m in range(array_length):
array.append(int(input()))
G = [1]
while True:
g = G[0] * 3 + 1
if g > array_length:
break
G.insert(0, g)
g_length = len(G)
result = []
for j in range(g_length):
result = self.insertion_sort(array=array, array_length=array_length, g=G[j])
# print(result, 'r', G[j])
print(g_length)
print(" ".join(map(str, G)))
print(self.count)
for k in range(array_length):
print(result[k])
def insertion_sort(self, array, array_length, g):
# write your code here
for i in range(g, array_length):
v = array[i]
j = i - g
while j >= 0 and array[j] > v:
array[j + g] = array[j]
j -= g
self.count += 1
array[j + g] = v
# print(" ".join(map(str, array)))
return array
if __name__ == '__main__':
solution = Solution()
solution.shell_sort()
|
tmp = int(input())
if tmp>=30:
print("Yes")
else:
print("No")
| 0 | null | 2,919,200,305,850 | 17 | 95 |
N, K, S = map(int, input().split())
rem = 1 if S >= 10**9 else S+1
ret = [S]*K + [rem]*(N-K)
print(' '.join(map(str, ret)))
|
n,k,s=map(int,input().split())
a=[s]*k
b=[3]*(n-k)+[s]*k
p=max(s//2-1,1)
for i in range(n-k):
if i%p==0:
a.append(s-1)
else:
a.append(2)
if s!=2 and s!=1:
print(*a)
else:
print(*b)
| 1 | 90,662,540,580,544 | null | 238 | 238 |
N = int(input())
S = [str(input()) for i in range(N)]
gocha = {}
for s in S:
gocha[s] = 1
print(len(gocha))
|
import numpy as np
N = int(input())
data_list = []
for i in range(N):
si = input()
data_list.append(si)
data_list = np.array(data_list)
print(len(np.unique(data_list)))
| 1 | 30,353,282,428,768 | null | 165 | 165 |
n = int(input())
score = [0,0]
for _ in range(n):
tc, hc = input().split()
if tc == hc:
score[0] += 1
score[1] += 1
elif tc > hc:
score[0] += 3
else:
score[1] += 3
print(*score)
|
def bubble_sort(A):
cnt = 0
for i in range(len(A) - 1):
for j in reversed(range(i+1, len(A))):
if A[j] < A[j - 1]:
cnt += 1
tmp = A[j]
A[j] = A[j - 1]
A[j - 1] = tmp
return cnt
cnt = 0
amount = int(input())
nl = list(map(int, input().split()))
cnt = bubble_sort(nl)
for i in range(amount - 1):
print(nl[i], end=" ")
print(nl[amount - 1])
print(cnt)
| 0 | null | 1,013,977,763,548 | 67 | 14 |
a = input()
if a[-1] == 's':
print(a + 'es')
else:
print(a + 's')
|
import itertools
n=int(input())
list1=list(map(int,input().split()))
q=int(input())
list2=list(map(int,input().split()))
sum1=set()
for i in range(1,n+1):
x=list(itertools.combinations(list1,i))
for j in x:
sum1.add(sum(j))
for i in list2:
if i in sum1:
print("yes")
else:
print("no")
| 0 | null | 1,258,942,128,332 | 71 | 25 |
N, K = map(int, input().split())
P = list(map(int, input().split()))
S = [0]
sum_ = 0
for i, p in enumerate(P):
sum_ += p
S.append(sum_)
max_sum = 0
for i in range(N-K+1):
max_sum = max(max_sum, S[i+K] - S[i])
res = (max_sum + K) / 2
print(res)
|
n=int(input())
a=list(map(int,input().split()))
tot=sum(a)
v=[1]
for q in a:
tot-=q
v.append(min(2*(v[-1]-q),tot))
if all([u>=0 for u in v]):
print(sum(v))
else:
print(-1)
| 0 | null | 47,013,562,374,080 | 223 | 141 |
from fractions import gcd
from functools import reduce
def lcm(a,b): # lcmは標準ライブラリには存在しない
return a * b // gcd(a,b)
def ls_lcm(A): # リストを引数に取れる
return reduce(lcm ,A)
def ls_gcd(A): # リストを引数に取れる
return reduce (gcd, A)
def count_two(n): # 2で割れる回数を取得
cnt = 0
while(n & 1 == 0): # 最下位ビットが0かどうか
cnt += 1
n = n >> 1 # 右ビットシフト
return cnt
N, M = map(int, input().split())
A = list(map(int, input().split()))
if len(set([count_two(a) for a in A])) != 1:
print (0)
exit()
A = [a//2 for a in A] # a_k/2 を考える
lc = ls_lcm(A)
print ((M + lc) // (2*lc)) # 最小公倍数を奇数倍したものが条件を満たす
|
from math import gcd
from functools import reduce
import sys
input = sys.stdin.readline
def lcm(a, b):
return a*b // gcd(a, b)
def count_factor_2(num):
count = 0
while num % 2 == 0:
num //= 2
count += 1
return count
def main():
n, m = map(int, input().split())
A = list(map(lambda x: x//2, set(map(int, input().split()))))
check = len(set(map(count_factor_2, A)))
if check != 1:
print(0)
return
lcm_a = reduce(lcm, A)
step = lcm_a * 2
ans = (m + lcm_a) // step
print(ans)
if __name__ == "__main__":
main()
| 1 | 101,936,432,479,360 | null | 247 | 247 |
N = int(input())
S = []
for _ in range(N):
S.append(input())
ans = set(S)
print(len(ans))
|
from collections import defaultdict
N, K = map(int, input().split())
A = list(map(int, input().split()))
cum = [0]*(N+1)
for i in range(1,N+1):
cum[i] = cum[i-1] + A[i-1]
ans = 0
dic = defaultdict(int)
v_by_indx = defaultdict(int)
for i in range(N+1):
if i-K >= 0:
dic[v_by_indx[i-K]] -= 1
diff = (cum[i]-i)%K
ans += dic[diff]
dic[diff] += 1
v_by_indx[i] = diff
print(ans)
| 0 | null | 83,922,516,087,630 | 165 | 273 |
N = int(input())
S, T = input().split()
charac = []
for i in range(N):
charac += S[i]
charac += T[i]
print(''.join(charac))
|
n=int(input())
s=input().split(' ')
m=0
for i in range(n):
minj=i
for j in range(i,n):
if int(s[j])<int(s[minj]):
minj=j
if i!=minj:
a=s[minj]
s[minj]=s[i]
s[i]=a
m+=1
print(' '.join(s))
print(m)
| 0 | null | 55,748,964,930,720 | 255 | 15 |
while True :
char_line = raw_input().split()
a = int(char_line[0])
b = int(char_line[2])
if char_line[1] == '?':
break
elif char_line[1] =='+':
print(a+b)
elif char_line[1]=='-':
print(a-b)
elif char_line[1]=='*':
print(a*b)
else:
print(a/b)
|
while True:
a,op,b=input().split()
a,b=int(a),int(b)
if op=="+":
print(a+b)
elif op=="-":
print(a-b)
elif op=="*":
print(a*b)
elif op=="/":
print(a//b)
else:
break
| 1 | 686,604,986,820 | null | 47 | 47 |
import sys
import heapq
sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inm = lambda: map(int, sys.stdin.readline().split())
inl = lambda: list(inm())
ins = lambda: sys.stdin.readline().rstrip()
debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw))
N, K = inm()
A = inl()
F = inl()
A.sort()
F.sort(reverse=True)
def check(val):
k = K
for i in range(N):
tmp = A[i] * F[i]
if tmp <= val:
continue
dec = ((tmp - val) + F[i] - 1) // F[i]
assert A[i] >= dec
assert (A[i] - dec) * F[i] <= val
k -= dec
if k < 0:
return False
return True
def solve():
ng, ok = -1, max([A[i] * F[i] for i in range(N)])
while ok - ng > 1:
mid = (ok + ng) // 2
if check(mid):
ok = mid
else:
ng = mid
return ok
print(solve())
|
import heapq
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
f = list(map(int, input().split()))
f.sort(reverse=True)
asum = sum(a)
def test(x):
t = [min(a[i], x//f[i]) for i in range(n)]
return asum - sum(t)
ng = -1
ok = 10**13
while abs(ok-ng)>1:
mid = (ok+ng)//2
if test(mid) <= k:
ok = mid
else:
ng = mid
print(ok)
| 1 | 164,899,487,784,096 | null | 290 | 290 |
N = int(input())
S = input()
count = 0
for i in range(1, N):
if S[i-1] != S[i]:
count += 1
print(count+1)
|
n = int(input())
s = input()
if n % 2 == 1:
res = "No"
else:
if s[:n//2] == s[n//2:]:
res = "Yes"
else:
res = "No"
print(res)
| 0 | null | 158,529,174,011,612 | 293 | 279 |
N = int(input())
C1 = list(input().split())
C2 = C1[:]
def get_card_suit(card):
return card[:1]
def get_card_value(card):
return card[1:]
def bubble_sort(card):
r_exists = True
while r_exists == True:
r_exists = False
i = N - 1
while i >= 1:
if get_card_value(card[i]) < get_card_value(card[i - 1]):
card[i], card[i - 1] = card[i - 1], card[i]
r_exists = True
i -= 1
def select_sort(card):
i = 0
while i < N:
min_j = i
j = i
while j < N:
if get_card_value(card[j]) < get_card_value(card[min_j]):
min_j = j
j += 1
card[i], card[min_j] = card[min_j], card[i]
i += 1
def output(card):
s = ''
for x in card:
s = s + str(x) + ' '
print(s.rstrip())
def is_stable():
i = 0
while i < N:
if get_card_suit(C1[i]) != get_card_suit(C2[i]):
return False
i += 1
return True
bubble_sort(C1)
select_sort(C2)
output(C1)
print('Stable')
output(C2)
if is_stable() == True:
print('Stable')
else:
print('Not stable')
|
from itertools import permutations
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
M = []
for i in range(N):
M.append(i+1)
p, q = 0, 0
for i, n in enumerate(list(permutations(M))):
if n == P:
p = i
if n == Q:
q = i
print(abs(p - q))
| 0 | null | 50,041,030,583,868 | 16 | 246 |
import bisect
N, M = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
# ある値以上のAiがいくつあるかの情報を累積和で保持
num_A_or_more = [0]*(10**5)
for a in A:
num_A_or_more[a-1] += 1
for i in range(1, 10**5):
j = 10**5 - i
num_A_or_more[j-1] += num_A_or_more[j]
# x以上となる手の組み合わせがM種類以上あるかどうかを判定
def check(x):
count = 0
for a in A:
idx = max(x-a-1, 0)
if idx >= 10**5:
continue
count += num_A_or_more[idx]
return count>=M
# 2分探索でM種類以上の手の組み合わせがある満足度の最大値を求める
left = 0
right = 2*10**5 + 1
mid = (left + right) // 2
while right - left > 1:
if check(mid):
left = mid
else:
right = mid
mid = (left + right)//2
# これがM種類以上の手の組み合わせがある満足度の最大値
x = left
# 降順に並べなおして累積和を求めておく
rev_A = A[::-1]
accum_A = [rev_A[0]]
for i, a in enumerate(rev_A):
if i == 0:
continue
accum_A.append(accum_A[-1] + a)
ans = 0
count = 0
surplus = 2*10**5 # M種類を超えた場合は、一番小さくなる握手の組を最後に削る
for ai in rev_A:
idx = bisect.bisect_left(A, x-ai)
if idx == N:
break
ans += (N-idx)*ai + accum_A[N-idx-1]
count += N - idx
surplus = min(surplus, ai+A[idx])
print(ans - (count-M)*surplus)
|
import sys
import bisect
import itertools
def solve():
readline = sys.stdin.buffer.readline
mod = 10 ** 9 + 7
n, m = list(map(int, readline().split()))
a = list(map(int, readline().split()))
a.sort()
cor_v = -1
inc_v = a[-1] * 2 + 1
while - cor_v + inc_v > 1:
bin_v = (cor_v + inc_v) // 2
cost = 0
#条件を満たすcostを全検索
p = n
for v in a:
p = bisect.bisect_left(a, bin_v - v, 0, p)
cost += n - p
if cost > m:
break
#costが制約を満たすか
if cost >= m:
cor_v = bin_v
else:
inc_v = bin_v
acm = [0] + list(itertools.accumulate(a))
c = 0
t = 0
for v in a:
p = bisect.bisect_left(a, cor_v - v)
c += n - p
t += acm[-1] - acm[p] + v * (n - p)
print(t - (c - m) * cor_v)
if __name__ == '__main__':
solve()
| 1 | 108,346,572,708,032 | null | 252 | 252 |
n, m = map(int, input().split())
prob = [0]*n
AC = 0
WA = 0
for _ in range(m):
p, s = input().split()
p = int(p)
if prob[p-1] == -1:
continue
if s == 'WA':
prob[p-1] += 1
else:
WA += prob[p-1]
AC += 1
prob[p-1] = -1
print(AC, WA)
|
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
if n == 1:
print(1)
exit()
ans = [1] * (a[n-1]+1)
for i in range(n):
if i >= 1 and a[i] == a[i-1]:
ans[a[i]] = 0
else:
j = 2
while j*a[i] <= a[n-1]:
ans[j*a[i]] = 0
j += 1
sum = 0
for i in range(n):
sum += ans[a[i]]
print(sum)
| 0 | null | 53,942,266,673,360 | 240 | 129 |
X = int(input())
if X < 30:
ans = 'No'
else:
ans = 'Yes'
print(ans)
|
a=int(input())
if a<30:
print("No")
else:
print("Yes")
| 1 | 5,693,392,970,030 | null | 95 | 95 |
import math
a,b,x=map(int,input().split())
if x<a*a*b/2:
t=a*b*b/2/x
else:
t=2*b/a-2*x/(a**3)
print(math.atan(t)/math.pi*180)
|
import math
def LI():
return list(map(int, input().split()))
a, b, x = LI()
if x == (a**2*b)/2:
ans = 45
elif x > (a**2*b)/2:
ans = math.degrees(math.atan((2*(b-x/(a**2)))/a))
else:
ans = math.degrees(math.atan(a*b**2/(2*x)))
print(ans)
| 1 | 162,877,864,963,242 | null | 289 | 289 |
# import sys
# input = sys.stdin.readline
import collections
def main():
n, m = input_list()
Friend = [[] for i in range(n+1)]
for _ in range(m):
a, b = input_list()
Friend[a].append(b)
Friend[b].append(a)
Flag = [False for i in range(n+1)]
ans = 1
for i in range(1, n+1):
if Flag[i]:
continue
q = collections.deque()
q.append(i)
cnt = 1
while q:
st = q.popleft()
Flag[st] = True
for j in Friend[st]:
if Flag[j]:
continue
cnt += 1
Flag[j] = True
q.append(j)
ans = max(ans, cnt)
print(ans)
def input_list():
return list(map(int, input().split()))
def input_list_str():
return list(map(str, input().split()))
if __name__ == "__main__":
main()
|
def root(x):
if F[x] < 0:
return x
else:
F[x] = root(F[x])
return F[x]
def unite(x, y):
x = root(x)
y = root(y)
if x == y:
return
if x > y:
x, y = y, x
F[x] += F[y]
F[y] = x
N, M = map(int, input().split())
F = [-1] * N
for m in range(M):
a, b = map(int, input().split())
unite(a - 1, b - 1)
ans = 0
for f in F:
ans = min(ans, f)
print(-ans)
| 1 | 3,957,716,033,908 | null | 84 | 84 |
H, W = map(int, input().split())
h_odd = 1 if H%2 == 1 else 0
if H == 1 or W == 1:
print("1")
else:
if h_odd == 1:
H += 1
print(W * H//2 - int(W//2 + 2**-1) * h_odd)
|
import math
loan = 100000
n = int(input())
for i in range(n):
interest = math.ceil(loan * 0.05 / 1000) * 1000
loan += interest
print(loan)
| 0 | null | 25,532,304,153,212 | 196 | 6 |
N,M = map(int, input().split())
C = list(map(int, input().split()))
C.sort()
DP = [i for i in range(N+1)]
for m in range(1,M):
coin = C[m]
for total in range(1, N+1):
if total - coin >= 0:
DP[total] = min(DP[total], DP[total - coin] + 1)
print(DP[-1])
|
n, x, y = map(int, input().split())
x -= 1
y -= 1
dist = [0]*(n-1)
for start in range(n):
for end in range(start+1, n):
dst = min(end-start, abs(x-start) + abs(end-y) + 1)
dist[dst-1] += 1
for d in dist:
print(d)
| 0 | null | 22,203,740,943,358 | 28 | 187 |
H, N = map(int, input().split())
A_list = []
for i in range(1, N+1):
A_list.append("A_" + str(i))
A_list = map(int, input().split())
A_total = sum(A_list)
if A_total >= H:
print("Yes")
else:
print("No")
|
h,n = map(int,input().split())
L = list(map(int,input().split()))
L.sort(reverse = True)
cnt = 0
for i in range(n):
cnt += L[i]
if cnt >= h:
print("Yes")
exit()
print("No")
| 1 | 78,096,161,970,080 | null | 226 | 226 |
import sys
sys.setrecursionlimit(10 ** 9)
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
N, M, K = map(int, input().split())
uf = UnionFind(N)
FG = [0] * N
BG = [0] * N
for _ in range(M):
a, b = map(int, input().split())
a, b = a-1, b-1
uf.union(a, b)
FG[a] += 1
FG[b] += 1
for _ in range(K):
c, d = map(int, input().split())
c, d = c-1, d-1
if uf.same(c, d):
BG[c] += 1
BG[d] += 1
ans = []
for i in range(N):
ans.append(uf.size(i) - FG[i] - BG[i] - 1)
print(*ans)
|
import sys,collections
input = sys.stdin.readline
def main():
N,M,K = list(map(int,input().split()))
fr = [[] for i in range(N+1)]
bl = [[] for i in range(N+1)]
for _ in range(M):
a,b = map(int,input().split())
fr[a].append(b)
fr[b].append(a)
for _ in range(K):
c,d = map(int,input().split())
bl[c].append(d)
bl[d].append(c)
fl = [-1 for i in range(N+1)]
fl[0] = 0
fl[1] = 1
nxt = 1
dic = {}
s = set(range(1,N+1))
while nxt != 0:
q = collections.deque([nxt])
fl[nxt]=nxt
cnt = 0
while q:
now = q.popleft()
s.discard(now)
for f in fr[now]:
if fl[f] == -1:
fl[f] = nxt
cnt +=1
q.append(f)
dic[nxt] = cnt
#try:
#nxt = fl.index(-1)
#except:
#nxt = 0
if len(s) == 0:
nxt = 0
else:
nxt = s.pop()
mbf = collections.deque()
for i in range(1,N+1):
ff = 0
for j in bl[i]:
if fl[j] == fl[i]:
ff -= 1
ff += dic[fl[i]]-len(fr[i])
mbf.append(ff)
print(*mbf)
if __name__ == '__main__':
main()
| 1 | 61,449,220,021,322 | null | 209 | 209 |
a,b,c,d = map(float,input().split())
print(abs(complex(c-a,d-b)))
|
import math;
x1,y1,x2,y2 = map(float,input().split());
x = (x2 - x1)**2;
y = (y2 - y1)**2;
c = math.sqrt(x + y);
print('{:.8f}'.format(c));
| 1 | 159,197,258,962 | null | 29 | 29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.