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
|
---|---|---|---|---|---|---|
#ALDS1_1_D Maximum Profit
n=int(input())
A=[]
max_dif=-1*10**9
for i in range(n):
A.append(int(input()))
min=A[0]
for i in range(n-1):
if(A[i+1]-min>max_dif):
max_dif=A[i+1]-min
if(min>A[i+1]):
min=A[i+1]
print(max_dif) | n,*a=map(int,open(0).read().split())
mod=10**9+7
ans=0
for j in range(60):
cnt=0
for i in range(n):
cnt+=a[i]&1
a[i]=(a[i]>>1)
ans+=(cnt*(n-cnt)%mod)*pow(2,j,mod)
ans%=mod
print(ans) | 0 | null | 61,212,040,664,388 | 13 | 263 |
from math import gcd
def lcm(a, b):
return a * b // gcd(a, b)
A, B = map(int, input().split())
print(lcm(A, B)) | import fractions
a,b = map(int,input().split())
def lcm(x,y):
z = int(x*y/fractions.gcd(x,y))
return z
print(lcm(a,b)) | 1 | 113,578,395,877,500 | null | 256 | 256 |
def fina(n, fina_list):
if n <= 1:
fina_list[n] = 1
return fina_list[n]
elif fina_list[n]:
return fina_list[n]
else:
fina_list[n] = fina(n-1, fina_list) + fina(n-2, fina_list)
return fina_list[n]
n = int(input())
fina_list = [None]*(n + 1)
print(fina(n, fina_list))
|
def main():
n = int(input())
dp = [0] * 100
dp[0] = 1
dp[1] = 1
for i in range(2, len(dp)):
dp[i] = dp[i - 1] + dp[i - 2]
print(dp[n])
if __name__ == '__main__':
main() | 1 | 1,989,199,628 | null | 7 | 7 |
from sys import exit
def mod_pow(a, n, p):
"""累乗 O(logN)
Args:
a (int): 対象の値
n (int): 指数
p (int): 除数
Returns:
int: a^n mod p
"""
res = 1
while n > 0:
if n & 1:
res = res * a % p
a = a * a % p
n >>= 1
return res
def mod_comb_k(n, k, p):
"""二項係数 0(1)
Args:
n (int): 添字
k (int): 添字
p (int): 除数
Returns:
int: nCk mod p
"""
if n < k or n < 0 or k < 0:
return 0
else:
return fact[n] * fact_inv[k] * fact_inv[n-k] % p
def com_init(n, p):
"""二項係数の計算の前処理 O(N)
Args:
n (int): 上限値
p (int): 除数
"""
for i in range(n):
fact.append(fact[-1] * (i+1) % p)
fact_inv[-1] = pow(fact[-1], p-2, p)
for i in range(n-1, -1, -1):
fact_inv[i] = fact_inv[i+1] * (i+1) % p
n = int(input())
mod = 10 ** 9 + 7
if n == 1:
print(0)
exit()
res1 = mod_pow(10, n, mod)
res2 = mod_pow(8, n, mod)
res3 = 0
fact = [1]
fact_inv = [0] * (n+1)
com_init(n, mod)
for i in range(1, n+1):
res3 = (res3 + mod_pow(8, n-i, mod) * mod_comb_k(n, i, mod) % mod) % mod
print(((res1 - res2) % mod - res3 * 2 % mod) % mod) | def main():
N=int(input())
m=int(1e9+7)
print((pow(10,N,m)-pow(9,N,m)-pow(9,N,m)+pow(8,N,m))%m)
if __name__=='__main__':
main()
| 1 | 3,152,603,109,568 | null | 78 | 78 |
from fractions import gcd
from functools import reduce
def lcm_base(x,y):
return (x*y)//gcd(x,y)
def lcm(A):
return reduce(lcm_base,A,1)
n,m=map(int,input().split())
A=list(map(int,input().split()))
num=lcm(A)
semi=num//2
ans=0
if any([True for i in range(n) if semi%A[i]==0]):print(0)
elif semi<=m:
ans +=1
m -=semi
ans +=m//num
print(ans)
else:print(0) | import math
def lcm(a,b):
return (a*b)//math.gcd(a,b)
def co(num):
return format(num, 'b')[::-1].find('1')
N,M=map(int,input().split())
L=list(map(int,input().split()))
L2=[co(i) for i in L]
if len(set(L2))!=1:
print(0)
exit()
L=[i//2 for i in L]
s=L[0]
for i in range(N):
s=lcm(s,L[i])
c=M//s
print((c+1)//2) | 1 | 102,237,108,749,220 | null | 247 | 247 |
def update(i,x):
i += d-1
bit = ord(x)-97
seg[i] = 0 | (1<<bit)
while i > 0:
i = (i-1)//2
seg[i] = seg[i*2+1]|seg[i*2+2]
def find(a,b,k,l,r):
if r <= a or b <= l:
return 0
if a <= l and r <= b:
return seg[k]
c1 = find(a,b,2*k+1,l,(l+r)//2)
c2 = find(a,b,2*k+2,(l+r)//2,r)
return c1|c2
n = int(input())
s = input()
q = int(input())
d = 1
while d < n:
d *= 2
seg = [0]*(2*d-1)
for i in range(n):
update(i,s[i])
for i in range(q):
type,a,b = input().split()
if type == "1":
update(int(a)-1,b)
else:
part = find(int(a)-1,int(b),0,0,d)
print(bin(part).count("1"))
| import sys
def input(): return sys.stdin.readline().rstrip()
def ctoi(c):
return ord(c)-97
class BIT:
def __init__(self, n):
self.unit_sum=0 # to be set
self.n=n
self.dat=[0]*(n+1)#[1,n]
def add(self,a,x): #a(1-)
i=a
while i<=self.n:
self.dat[i]+=x
i+=i&-i
def sum(self,a,b=None):
if b!=None:
return self.sum(b-1)-self.sum(a-1) #[a,b) a(1-),b(1-)
res=self.unit_sum
i=a
while i>0:
res+=self.dat[i]
i-=i&-i
return res #Σ[1,a] a(1-)
def __str__(self):
self.ans=[]
for i in range(1,self.n):
self.ans.append(self.sum(i,i+1))
return ' '.join(map(str,self.ans))
def main():
n=int(input())
S=list(input())
q=int(input())
BIT_tree=[]
for i in range(26):
obj=BIT(n+1)
BIT_tree.append(obj)
for i in range(n):
BIT_tree[ctoi(S[i])].add(i+1,1)
for _ in range(q):
query=input().split()
if query[0]=="1":
index,x=int(query[1])-1,query[2]
BIT_tree[ctoi(S[index])].add(index+1,-1)
BIT_tree[ctoi(x)].add(index+1,1)
S[index]=x
else:
l,r=int(query[1])-1,int(query[2])-1
ans=0
for c in range(26):
if BIT_tree[c].sum(l+1,r+2):
ans+=1
print(ans)
if __name__=='__main__':
main() | 1 | 62,762,239,616,412 | null | 210 | 210 |
ans=[]
for i in range (0,10):
ans.append(int(input()))
ans.sort(reverse=True)
for i in range (0,3):
print(ans[i]) | import sys
# import bisect
# from collections import Counter, deque, defaultdict
# import copy
# from heapq import heappush, heappop, heapify
# from fractions import gcd
# import itertools
# from operator import attrgetter, itemgetter
# import math
# from numba import jit
# from scipy import
# import numpy as np
# import networkx as nx
# import matplotlib.pyplot as plt
readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)
def main():
n, p = list(map(int, readline().split()))
s = input()
ans = 0
if p == 2 or p == 5:
for i in range(n):
if int(s[i]) % p == 0:
ans += (i + 1)
else:
c = [0] * p
prev = 0
c[0] = 1
for i in range(n):
num = int(s[n - i - 1])
m = (num * pow(10, i, p) + prev) % p
c[m] += 1
prev = m
for i in range(p):
cnt = c[i]
ans += cnt * (cnt - 1) // 2
print(ans)
if __name__ == '__main__':
main()
| 0 | null | 29,042,031,027,800 | 2 | 205 |
n = input()
if '7' in n :
print("Yes")
else :
print("No")
| a = int(input())
b = a // 100
c = a // 10 - b * 10
d = a - b * 100 - c * 10
if b != 7 and c != 7 and d != 7:
print("No")
else:
print("Yes") | 1 | 34,295,298,780,638 | null | 172 | 172 |
import sys
from collections import defaultdict
N,S=map(int, sys.stdin.readline().split())
A=map(int, sys.stdin.readline().split())
mod=998244353
cur=defaultdict(lambda: 0)
new=defaultdict(lambda: 0)
cur[0]=1
for a in A:
for i in cur.keys():
if i+a<=S:
new[i+a]+=cur[i]
new[i+a]%=mod
new[i]+=cur[i]*2
new[i]%=mod
cur=new
new=defaultdict(lambda: 0)
print cur[S]
| def main():
from decimal import Decimal
N, M = (Decimal(i) for i in input().split())
print(int(N * M))
if __name__ == '__main__':
main()
| 0 | null | 17,040,065,262,780 | 138 | 135 |
import sys
def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))
def RN(N): return [input().strip() for i in range(N)]
def main():
N, M = MI()
if N == M:
print("Yes")
else:
print("No")
if __name__ == "__main__":
main() | N=int(input())
S=input()
b=S.count('ABC')
print(b) | 0 | null | 90,965,516,784,172 | 231 | 245 |
while True:
try:
s = input()
a, b = [int(i) for i in s.split()]
print(len(str(a + b)))
except:
break
| try:
s=[]
while True:
t = input()
s.append(t)
except EOFError:
for i in range(len(s)):
print(len(str(int(s[i].split(' ')[0])+int(s[i].split(' ')[1])))) | 1 | 154,856,470 | null | 3 | 3 |
n = int(input())
a = list(map(int,input().split()))
mod = 10**9+7
ans = 0
for i in range(60):
keta=1<<i
cnt=0
for j in a:
if keta & j:
cnt+=1
ans+=((keta%mod)*cnt*(n-cnt))%mod
print(ans%mod)
| import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
class UnionFind(object):
def __init__(self, n, recursion = False):
self._par = list(range(n))
self._size = [1] * n
self._recursion = recursion
def root(self, k):
if self._recursion:
if k == self._par[k]:
return k
self._par[k] = self.root(self._par[k])
return self._par[k]
else:
root = k
while root != self._par[root]: root = self._par[root]
while k != root: k, self._par[k] = self._par[k], root
return root
def unite(self, i, j):
i, j = self.root(i), self.root(j)
if i == j: return False
if self._size[i] < self._size[j]: i, j = j, i
self._par[j] = i
self._size[i] += self._size[j]
return True
def is_connected(self, i, j):
return self.root(i) == self.root(j)
def size(self, k):
return self._size[self.root(k)]
def resolve():
n, m = map(int, input().split())
uf = UnionFind(n)
for _ in range(m):
u, v = map(int, input().split())
u -= 1; v -= 1
uf.unite(u, v)
ans = len(set(uf.root(v) for v in range(n))) - 1
print(ans)
resolve() | 0 | null | 62,591,057,919,490 | 263 | 70 |
from sys import stdin, setrecursionlimit
input = stdin.buffer.readline
N = int(input())
A = list(map(int, input().split()))
max_A = max(A)
if max_A == 1:
print("pairwise coprime")
exit()
class Prime:
def __init__(self, n):
self.prime_factor = [i for i in range(n + 1)]
self.prime = []
for i in range(2, n + 1):
if self.prime_factor[i] == i:
for j in range(2, n // i + 1):
self.prime_factor[i * j] = i
self.prime.append(i)
#print(self.prime_factor)
#print(self.prime)
def factorize(self, m):
ret = []
while m != 1:
if not ret:
ret = [[self.prime_factor[m], 1]]
elif self.prime_factor[m] == ret[-1][0]:
ret[-1][1] += 1
else:
ret.append([self.prime_factor[m], 1])
m //= self.prime_factor[m]
return ret
def divisors(self, m):
ret = []
for i in range(1, int(m ** 0.5) + 1):
if m % i == 0:
ret.append(i)
if i != m // i:
ret.append(m // i)
#self.divisors.sort()
return ret
pm = Prime(max_A)
def is_pairwise_coprime(arr):
cnt = [0] * (max_A + 1)
for a in arr:
for b, c in pm.factorize(a):
cnt[b] += 1
if max(cnt[2:]) <= 1:
return 1
else:
return 0
def gcd(a, b):
while b:
a, b = b, a % b
return a
def is_setwise_coprime(A):
gcd_a = 0
for a in A:
gcd_a = gcd(gcd_a, a)
if gcd_a == 1:
return 1
else:
return 0
if is_pairwise_coprime(A):
print("pairwise coprime")
elif is_setwise_coprime(A):
print("setwise coprime")
else:
print("not coprime") | from math import gcd
from functools import reduce
from collections import defaultdict
n=int(input())
a=list(map(int,input().split()))
g=reduce(gcd,a)
if g!=1:
print("not coprime")
exit()
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
#d=defaultdict(int)
s=set()
for q in a:
p=primeFactor(q)
for j in p:
if j in s:
print("setwise coprime")
exit()
s.add(j)
print("pairwise coprime") | 1 | 4,068,765,676,790 | null | 85 | 85 |
K, X = map(int, input().split())
if K*500 >= X:
print('Yes')
else:
print('No') | from collections import deque
def bfs(maze, visited, x):
queue = deque([x])
visited[x] = 1
ans_list[x] = 0
while queue:
#queueには訪れた地点が入っている。そこから、移動できるか考え、queueから消す。
y = queue.popleft()#queueに入っていたものを消す。
r = maze[y - 1][2:]
for i in r:
if visited[i] == 0:
if ans_list[i] >= 10 ** 10:
ans_list[i] = ans_list[y] + 1
queue.append(i)
return 0
if __name__ == "__main__":
N = int(input())
A = [0] * N
for i in range(N):
A[i] = list(map(int, input().split()))
visited = [0] * (N + 1)
ans_list = [float("inf")] * (N + 1)
bfs(A, visited, 1)
#print(bfs(A, visited, 1))
for i in range(1, N + 1):
if ans_list[i] >= 10 ** 10:
print(i, -1)
else:
print(i, ans_list[i])
| 0 | null | 49,130,475,226,628 | 244 | 9 |
n, m, q = map(int, input().split())
a = [0] * q
b = [0] * q
c = [0] * q
d = [0] * q
for i in range(q):
a[i], b[i], c[i], d[i] = map(int, input().split())
score = []
# 数列Aの全探索
import copy
def dfs(A):
if len(A) == n+1:
# score計算
tmp = 0
#print(A)
for i in range(q):
if A[b[i]] - A[a[i]] == c[i]:
tmp += d[i]
score.append(tmp)
return
else:
tmp = A[-1]
arr = copy.copy(A)
arr.append(tmp)
while(arr[-1] <= m):
dfs(arr)
arr[-1] += 1
dfs([1])
print(max(score))
| from itertools import combinations_with_replacement as cwr
N, M, Q = map(int, input().split())
abcd = [list(map(int, input().split())) for i in range(Q)]
def calc_score(A):
score = 0
for a, b, c, d in abcd:
if A[b-1] - A[a-1] == c:
score += d
return score
ans = 0
for A in cwr([i for i in range(1, M+1)], N):
ans = max(ans, calc_score(A))
print(ans) | 1 | 27,637,654,077,348 | null | 160 | 160 |
N = int(input())
import sys
if N & 1:
print(0)
sys.exit()
ans = 0
N //= 2
while N != 0:
ans += N // 5
N //= 5
print(ans) | if __name__ == '__main__':
# ??????????????\???
num = int(input())
triangles = []
for i in range(num):
triangles.append([int(x) for x in input().split(' ')])
# ??´?§?????§???¢?????????????????????
results = []
for t in triangles:
t.sort()
if t[0]**2 + t[1]**2 == t[2]**2:
results.append('YES')
else:
results.append('NO')
# ???????????????
for r in results:
print(r) | 0 | null | 58,068,619,107,938 | 258 | 4 |
def bubblesort(N, A):
C, flag = [] + A, True
while flag:
flag = False
for j in range(N-1, 0, -1):
if int(C[j][1]) < int(C[j-1][1]):
C[j], C[j-1] = C[j- 1], C[j]
flag = True
return C
def selectionSort(N, A):
C = [] + A
for i in range(N):
minj = i
for j in range(i,N):
if int(C[j][1]) < int(C[minj][1]):
minj = j
C[i], C[minj] = C[minj], C[i]
return C
N, A= int(input()), input().split()
Ab = bubblesort(N, A)
print(*Ab)
print('Stable')
As = selectionSort(N, A)
print(*As)
if Ab != As:
print('Not stable')
else:
print('Stable') | n = int(input())
s = input()
a = s.split()
def value(a, i):
return int(a[i][-1])
def isstable(s, a, n):
for i in range(n - 1):
if value(a, i) == value(a, i + 1):
v1 = s.index(a[i])
v2 = s.index(a[i + 1])
if v1 > v2:
return "Not stable"
return "Stable"
for i in range(n - 1):
for j in range(i + 1, n)[::-1]:
if value(a, j) < value(a, j - 1):
a[j], a[j - 1] = a[j - 1], a[j]
print(" ".join(a))
print(isstable(s.split(), a, n))
a = s.split()
for i in range(n - 1):
minj = i
for j in range(i + 1, n):
if value(a, j) < value(a, minj):
minj = j
a[i], a[minj] = a[minj], a[i]
print(" ".join(a))
print(isstable(s.split(), a, n))
| 1 | 26,200,999,752 | null | 16 | 16 |
import queue
n = int(input())
alp = "abcdefghijklmn"
q = queue.Queue()
q.put("a")
while not q.empty():
qi = q.get()
if len(qi) == n:
print(qi)
elif len(qi) < n:
idx = alp.index(max(qi))
for i in range(idx+2):
q.put(qi+alp[i])
|
n = map(int, raw_input().split(' '))[0]
def dfs(i, mx, n, res, cur = []):
if i==n:
res.append(''.join(cur[::]))
return
for v in range(0, mx + 1):
dfs(i + 1, mx + (1 if v == mx else 0), n , res, cur + [chr(v+ ord('a'))])
res =[]
dfs(0,0,n,res)
for w in res: print w | 1 | 52,317,261,311,730 | null | 198 | 198 |
X,N = map(int,input().split())
P = list(map(int,input().split()))
a = list(range(102))
for i in range(N):
a[P[i]] = -2
m = 102
for i in range(102):
if m > (abs(X - a[i])):
m = (abs(X - a[i]))
ans = a[i]
print(ans) | A,B = input().split()
print((int(A)*round(100*float(B)))//100) | 0 | null | 15,345,940,385,852 | 128 | 135 |
from collections import Counter
n, k = map(int, input().split())
a = list(map(int, input().split()))
f = list(map(int, input().split()))
a.sort()
f.sort(reverse=True)
la = 10**6+1
cnt = [0] * la
for u in a:
cnt[u] += 1
for i in range(1, la):
cnt[i] += cnt[i-1]
def judge(x):
y = k
for i in range(n):
goal = x//f[i]
if a[i] > goal:
y -= a[i] - goal
if y < 0:
return False
return y >= 0
left = -1
right = 10**12 + 1
while left + 1 < right:
mid = (left + right)//2
if judge(mid):
right = mid
else:
left = mid
print(right)
| # いきぬきreview 忘れた問題
# gluttony
N, K = map(int, input().split())
A = list(map(int, input().split()))
F = list(map(int, input().split()))
F.sort()
A.sort(reverse=True)
def func(X):
s = 0
for i in range(N):
a, f = A[i], F[i]
s += max(0, a-X//f)
return s <= K
R = 10**12
L = -1
while R-L > 1:
m = (R+L)//2
if func(m):
R = m
else:
L = m
print(R) | 1 | 165,325,018,808,496 | null | 290 | 290 |
H, M = map(int, input().split())
A = list(map(int, input().split()))
a = (sum(A))
if a >= H:
ans = "Yes"
else:
ans = "No"
print(ans)
| h, n = [int(i) for i in input().split()]
magics = [None]
class Magic:
def __init__(self, attack, cost):
self.attack = attack
self.cost = cost
maxA = 0
for i in range(n):
attack, cost = [int(i) for i in input().split()]
maxA = max(maxA, attack)
magics.append(Magic(attack, cost))
dp = [[10 ** 9 for i in range(h + maxA)] for j in range(n + 1)]
for i in range(n + 1):
for j in range(h + maxA):
if j == 0:
dp[i][j] = 0
elif i == 0:
continue
elif j - magics[i].attack >= 0:
dp[i][j] = min(dp[i - 1][j], dp[i][j - magics[i].attack] + magics[i].cost)
else:
dp[i][j] = dp[i - 1][j]
print(min(dp[-1][h:]))
| 0 | null | 79,584,101,073,568 | 226 | 229 |
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
from heapq import heappop, heappush
from collections import defaultdict
sys.setrecursionlimit(10**7)
import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal
#from numba import jit
INF = 1 << 50
EPS = 1e-8
mod = 10 ** 9 + 7
def mapline(t = int):
return map(t, sysread().split())
def mapread(t = int):
return map(t, read().split())
def run():
N, *A = mapread()
dp = [defaultdict(lambda:0) for _ in range(N+1)]
dp[0][(0,0,0)] = 1
for i in range(N):
a = A[i]
k = i + 1
for key in dp[k-1].keys():
for ii, v in enumerate(key):
if v == a:
tmp = list(key)
tmp[ii] += 1
dp[k][tuple(tmp)] += dp[k-1][key] % mod
ans = 0
for key in dp[N].keys():
ans = (ans + dp[N][key]) % mod
#print(dp)
print(ans)
if __name__ == "__main__":
run()
| p = 1000000007
n = int(input())
A = list(map(int, input().split()))
ans = 1
cnt = [3 if i == 0 else 0 for i in range(n+1)]
for a in A:
ans *= cnt[a]
ans %= p
cnt[a] -= 1
cnt[a+1] += 1
print(ans) | 1 | 129,861,985,971,338 | null | 268 | 268 |
N = int(input())
print(N**2) | def myAnswer(a:int,b:int,c:int) -> str:
A = ( a + b - c) ** 2
B = 4 * a * b
return "Yes" if( A - B > 0 and (c - a - b) > 0) else "No"
def modelAnswer():
return
def main():
a,b,c = map(int,input().split())
print(myAnswer(a,b,c))
if __name__ == '__main__':
main() | 0 | null | 98,369,439,705,990 | 278 | 197 |
n, x, m = map(int, input().split())
ans = []
flag = False
for i in range(n):
if x in ans:
v = x
flag = True
break
ans.append(x)
x = x**2 % m
if flag:
p = ans.index(v)
l = len(ans) - p
d, e = divmod(n-p, l)
print(sum(ans[:p]) + d*sum(ans[p:]) + sum(ans[p:p+e]))
else:
print(sum(ans))
| def solve():
N, X, M = map(int,input().split())
past_a = {X}
A = [X]
ans = prev = X
for i in range(1, min(M,N)):
next_a = prev ** 2 % M
if next_a in past_a:
loop_start = A.index(next_a)
loop_end = i
loop_size = loop_end - loop_start
loop_elem = A[loop_start:loop_end]
rest_n = N-i
ans += rest_n // loop_size * sum(loop_elem)
ans += sum(loop_elem[:rest_n%loop_size])
break
ans += next_a
past_a.add(next_a)
A.append(next_a)
prev = next_a
print(ans)
if __name__ == '__main__':
solve() | 1 | 2,823,438,519,268 | null | 75 | 75 |
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():
musics = int(input())
title = []
time = []
for _ in range(musics):
s, t = input().split()
title.append(s)
time.append(int(t))
last_song = input()
for i in range(musics):
if title[i] == last_song:
print(sum(time[i + 1:]))
break
if __name__ == '__main__':
main()
| 1 | 96,947,116,276,540 | null | 243 | 243 |
import sys
def Ii():return int(sys.stdin.readline())
def Mi():return map(int,sys.stdin.readline().split())
def Li():return list(map(int,sys.stdin.readline().split()))
n = Ii()
a = Li()
b = 0
for i in range(n):
b ^= a[i]
ans = []
for i in range(n):
print(b^a[i],end=' ') | N=int(input())
*A,=map(int,input().split())
total=0
for i in range(N):
total ^= A[i]
print(*[total^A[i] for i in range(N)]) | 1 | 12,546,805,249,022 | null | 123 | 123 |
s, w = map(int, input().split())
if s<=w:
print("unsafe")
else:
print("safe") | X, Y = [int(x) for x in input().split()]
M = 10**9+7
if (X + Y) % 3:
print(0)
else:
x = X - (X+Y)//3
y = Y - (X+Y)//3
if x < 0 or y < 0:
print(0)
else:
#print(x, y)
#x+y c x
#(x+y)!/x!/y!
ans = 1
for j in range(y):
#print(j)
#print(x+j+1, j+1)
ans *= (x+j+1) * pow(j+1, -1, M)
ans %= M
print(ans) | 0 | null | 89,702,814,291,200 | 163 | 281 |
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)
N, K = mapint()
As = sorted(list(mapint()))
Fs = sorted(list(mapint()))[::-1]
from math import ceil
L, R = -1, 10**12
while L+1<R:
half = (L+R)//2
k = 0
for a, f in zip(As, Fs):
k += max(0, ceil(((a*f)-half)/f))
if k>K:
L = half
break
else:
R = half
print(R) | import sys
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1:
arr.append([temp, 1])
if arr==[]:
arr.append([n, 1])
return arr
n=int(input())
if n==1:
print(0)
sys.exit()
l=factorization(n)
ans =0
for x in l:
a=x[0] #素数
b=x[1] #素数の個数
k=0
t=0
while(True):
t += 1
k += t
if k==b:
ans += t
break
elif k > b:
ans += t-1
break
print(ans) | 0 | null | 90,809,749,784,448 | 290 | 136 |
a=int(input())
print(max(8-(a-400)//200,1))
| def main():
x = int(input())
print((2199 - x) // 200)
if __name__ == '__main__':
main()
| 1 | 6,727,751,343,978 | null | 100 | 100 |
D = int(input())
c = list(map(int, input().split()))
s = []
t = []
for _ in range(D):
s.append(list(map(int, input().split())))
for _ in range(D):
t.append(int(input()))
ans = 0
last_date = [0]*26
for day in range(D):
contest = t[day]-1
ans += s[day][contest]
last_date[contest] = day+1
for j in range(26):
ans -= c[j] * (day+1 - last_date[j])
print(ans)
| a,b=map(int,input().split())
print("safe" if a>b else "unsafe") | 0 | null | 19,482,231,025,818 | 114 | 163 |
# E - Active Infants
N = int(input())
A = list(map(int,input().split()))
dp = [[] for _ in range(N+1)]
dp[0].append(0)
for i in range(N):
A[i] = [A[i],i+1]
A.sort(reverse=True)
for M in range(1,N+1):
Ai,i = A[M-1]
# x=0
dp[M].append(dp[M-1][0]+Ai*(N-(M-1)-i))
# 1<=x<=M-1
for x in range(1,M):
dp[M].append(max(dp[M-1][x-1]+Ai*(i-x),dp[M-1][x]+Ai*(N-(M-x-1)-i)))
# x=M
dp[M].append(dp[M-1][M-1]+Ai*(i-M))
print(max(dp[N])) | import sys
import numpy as np
sys.setrecursionlimit(10 ** 9)
#def input():
# return sys.stdin.readline()[:-1]
N = int(input())
#X, Y = map(int,input().split())
A = list(map(int,input().split()))
B = []
for i in range(N):
B.append([A[i], i])
B.sort(reverse=True)
#dp = [[0 for _ in range(N+2)] for _ in range(N+2)]
#for x in range(1,N+2):
# for y in range(1,N+2):
## print(act,i)
# dp[x][y] = max(dp[x-1][y] + B[y][0] * (B[y][1] - 0 - (x-2))
# , dp[x][y-1] + B[y][0] * (N - 1 - B[y][1] - (y-2)))
dp = np.zeros(1, dtype=int)
zero = np.zeros(1, dtype=int)
for act, i in B:
prev = dp.copy()
dp = np.append(dp,[0])
l = len(prev)
right = np.arange((N-1-i)*act,(N-1-i)*act - (act*(l)),-act)
left = np.arange(i*act-(act*(l-1)),(i+1)*act,act)
# print(left,right,prev,dp)
np.maximum(np.concatenate([prev + left, zero]),
np.concatenate([zero, prev + right]),
out = dp)
# print(dp)
print(np.max(dp)) | 1 | 33,740,083,043,958 | null | 171 | 171 |
S = input()
youbi = ['SAT', 'FRI', 'THU', 'WED', 'TUE', 'MON', 'SUN']
print(youbi.index(S) + 1) | n = int(input())
arrey = [int(i) for i in input().split()]
count = 0
for i in range(len(arrey)):
minj = i
change = False
for j in range(i+1, len(arrey)):
if arrey[minj] > arrey[j]:
minj = j
change = True
if change:
arrey[i], arrey[minj] = arrey[minj], arrey[i]
count += 1
for i in range(len(arrey)):
print(str(arrey[i])+' ',end='') if i != len(arrey)-1 else print(arrey[i])
print(count) | 0 | null | 66,311,890,481,408 | 270 | 15 |
from itertools import permutations
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
r = 0
for i, x in enumerate(permutations([j for j in range(1,N+1)])):
if x == P:
r = abs(r-i)
if x == Q:
r = abs(r-i)
print(r)
| N = int(input())
L = list(map(int, input().split()))
le = len(L)
score = 0
for i in range(le):
for j in range(i+1,le):
for k in range(j+1,le):
if (L[i] + L[j] > L[k] and
L[i] + L[k] > L[j] and
L[k] + L[j] > L[i] ):
if (L[i] != L[j] and
L[i] != L[k] and
L[k] != L[j]):
score += 1
print(score) | 0 | null | 52,817,546,935,468 | 246 | 91 |
n=int(input())
l=[int(i) for i in input().split()]
l.sort()
def func(one,two,three):
if len({one,two,three})==3 and one+two>three:
return True
return False
ans=0
for i in range(n-2):
for j in range(i+1,n-1):
for k in range(j+1,n):
one=l[i]
two=l[j]
three=l[k]
if func(one,two,three):
ans+=1
print(ans) | N = int(input())
L = [int(i) for i in input().split()]
count = 0
L.sort()
for i in range(N) :
for j in range(i+1,N) :
for k in range(j+1,N) :
if L[i]!=L[j]!=L[k]:
if ((L[i]+L[j]>L[k]) and (L[j]+L[k]>L[i]) and (L[i]+L[k]>L[j])) :
count += 1
print(count) | 1 | 4,987,211,043,272 | null | 91 | 91 |
N = int(input())
p = 10**9 + 7
A = [int(i) for i in input().split()]
S = sum(A)%p
ans = S**2 % p
B = [(i**2%p) for i in A]
ans -= sum(B)%p
if ans < 0:
ans += p
if ans % 2 == 0:
print(ans//2)
else:
print((ans+p)//2) | N = int(input())
A = list(map(int,input().split()))
cums = [0]
for a in A:
cums.append(cums[-1] + a)
MOD = 10**9+7
ans = 0
for i in range(N-1):
ans += A[i] * (cums[-1] - cums[i+1])
ans %= MOD
print(ans) | 1 | 3,817,110,928,232 | null | 83 | 83 |
K=int(input())
S=input()
if len(S)<K or len(S)==K:
print (S)
elif len(S)>K:
print(S[0:K]+"...") | n = int(input())
s = 0
a = 1
b = 1
while a*b < n:
while a*b < n and b <= a:
if a == b:
s += 1
else:
s += 2
b += 1
a += 1
b = 1
print(s)
| 0 | null | 11,220,470,440,128 | 143 | 73 |
H = int(input())
cnt = 0
while True:
H //= 2
cnt += 1
if H == 0:
break
print(2**cnt-1)
| def solve(n):
if n is 0:
return 0
return 1 + 2 * solve(n // 2)
print(solve(int(input()))) | 1 | 80,161,701,747,660 | null | 228 | 228 |
n = int(input())
ans = 100000
# ans += (n*(100000*0.05))
for i in range(n):
ans *= 1.05
if ans % 1000 > 0:
ans = ans // 1000 * 1000 + 1000
print(int(ans))
| #! /usr/bin/python3
m=100
for _ in range(int(input())):
m = int(m*1.05+0.999)
print(m*1000) | 1 | 988,474,980 | null | 6 | 6 |
import sys
mapin = lambda: map(int, sys.stdin.readline().split())
listin = lambda: list(map(int, sys.stdin.readline().split()))
inp = lambda: sys.stdin.readline()
N = int(inp())
mp = {}
for i in range(N):
S = inp()
S = S[:-1]
if S in mp:
mp[S] += 1
else:
mp[S] = 1
ans = 0
vec = []
for i in mp.values():
if ans < i:
ans = i
for i in mp.keys():
if mp[i] == ans:
vec.append(i)
vec.sort()
for i in vec:
print(i) | # coding: utf-8
from collections import defaultdict
def main():
N = int(input())
dic = defaultdict(int)
max_p = 0
for i in range(N):
dic[input()] += 1
d = dict(dic)
l = []
for key, value in d.items():
l.append([key, value])
if max_p < value: max_p = value
l.sort(key=lambda x: (-x[1], x[0]), reverse=False)
for i, j in l:
if j == max_p:
print(i)
else:
break
if __name__ == "__main__":
main()
| 1 | 69,937,991,615,698 | null | 218 | 218 |
import sys
sys.setrecursionlimit(10**6)
def root(x):
if pair[x]<0:
return x
else:
tmp=root(pair[x])
pair[x]=tmp
return tmp
def unite(x,y):
x=root(x)
y=root(y)
if x==y:return False
if pair[x]>pair[y]:
x,y=y,x
pair[x]+=pair[y]
pair[y]=x
return True
def size(x):
return -pair[root(x)]
icase=0
if icase==0:
n,m,k=map(int,input().split())
g=[[] for i in range(n)]
x=[[] for i in range(n)]
a=[0]*m
b=[0]*m
pair=[-1]*n
for i in range(m):
ai,bi=map(int,input().split())
g[ai-1].append(bi-1)
g[bi-1].append(ai-1)
a[i]=ai-1
b[i]=bi-1
unite(a[i],b[i])
for i in range(k):
ci,di=map(int,input().split())
x[ci-1].append(di-1)
x[di-1].append(ci-1)
for i in range(n):
ss=size(i)-1
rooti=root(i)
for gi in g[i]:
if root(gi)==rooti:
ss-=1
for xi in x[i]:
if root(xi)==rooti:
ss-=1
print(ss,end=" ")
print(" ")
| n, k = map(int, input().split())
su = 0
for i in range(k, n+2):
co = (n+(n-i+1))*i/2 - (i-1)*i/2 + 1
su = (su + int(co)) % (10**9 + 7)
print(su) | 0 | null | 47,541,945,925,202 | 209 | 170 |
def solve():
N = int(input())
S = input()
C = [c for c in S]
left = 0
right = len(C) -1
ans = 0
while left < right:
while left < right and C[left] == 'R':
left += 1
while left < right and C[right] == 'W':
right -= 1
if left < right:
C[left] = 'R'
C[right] = 'W'
ans += 1
left += 1
right -= 1
print(ans)
if __name__ == "__main__":
solve() | n = int(input())
c = list(input())
r = 0
temp = 0
for i in c:
if i == 'R':
r += 1
w = n - r
for i in range(r):
if c[i] == 'R':
temp += 1
print(r - temp) | 1 | 6,312,946,791,356 | null | 98 | 98 |
from collections import defaultdict
money = defaultdict(int)
for i, m in enumerate([300000, 200000, 100000]):
money[i] = m
X, Y = map(int, input().split())
X -= 1; Y -= 1
ans = money[X] + money[Y]
if X + Y:
print(ans)
else:
print(ans + 400000) | def main():
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
#from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil
#from operator import itemgetter
#inf = 10**17
#mod = 10**9 + 7
x,y = map(int, input().split())
a = 0
b = 0
if x==1:
a += 300000
if x==2:
a += 200000
if x==3:
a += 100000
if y==1:
b += 300000
if y==2:
b += 200000
if y==3:
b += 100000
if a+b == 600000:
print(1000000)
else:
print(a+b)
if __name__ == '__main__':
main() | 1 | 140,271,871,826,622 | null | 275 | 275 |
def resolve():
S = "0" + input()
N = len(S)
dp = [[1<<60]*2 for _ in range(N+1)]
dp[0][0] = 0
for i in range(N):
now = int(S[i])
dp[i+1][0] = min(dp[i][0]+now, dp[i][1]+(10- now))
dp[i + 1][1] = min(dp[i][0] + now + 1, dp[i][1] + (10 - now - 1))
print(dp[N][0])
if __name__ == "__main__":
resolve()
| n, k = map(int, input().split())
treat_array = [0]*n
for i in range(k):
d = int(input())
for j in map(int, input().split()):
treat_array[j-1] += 1
ans = 0
for i in range(n):
if treat_array[i] == 0:
ans += 1
print(ans) | 0 | null | 47,971,175,090,850 | 219 | 154 |
import sys
from builtins import enumerate
from io import StringIO
import unittest
import os
# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)
# 実装を行う関数
def resolve(test_def_name=""):
# 数値取得サンプル
# 1行1項目 n = int(input())
# 1行2項目 x, y = map(int, input().split())
# 1行N項目 x = list(map(int, input().split()))
# N行1項目 x = [int(input()) for i in range(n)]
# N行N項目 x = [list(map(int, input().split())) for i in range(n)]
# 文字取得サンプル
# 1行1項目 x = input()
# 1行1項目(1文字ずつリストに入れる場合) x = list(input())
n, k = map(int, input().split())
p_s = [0] + list(map(int, input().split()))
avr_s = [0]
cumsum = 0
for i in range(1, 1001):
cumsum += i
avr_s.append(cumsum / i)
ans = 0
val = 0
for i in range(1, len(p_s)):
val += avr_s[p_s[i]]
if i < k:
continue
elif i == k:
ans = val
else:
val -= avr_s[p_s[i - k]]
ans = max(ans, val)
print(ans)
# テストクラス
class TestClass(unittest.TestCase):
def assertIO(self, assert_input, output):
stdout, sat_in = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
resolve(sys._getframe().f_back.f_code.co_name)
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, sat_in
self.assertEqual(out, output)
def test_input_1(self):
test_input = """5 3
1 2 2 4 5"""
output = """7.000000000000"""
self.assertIO(test_input, output)
def test_input_2(self):
test_input = """4 1
6 6 6 6"""
output = """3.500000000000"""
self.assertIO(test_input, output)
def test_input_3(self):
test_input = """10 4
17 13 13 12 15 20 10 13 17 11"""
output = """32.000000000000"""
self.assertIO(test_input, output)
# 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
def tes_t_1original_1(self):
test_input = """データ"""
output = """データ"""
self.assertIO(test_input, output)
# 実装orテストの呼び出し
if __name__ == "__main__":
if os.environ.get("USERNAME") is None:
# AtCoder提出時の場合
resolve()
else:
# 自PCの場合
unittest.main()
| n, k = map(int, input().split())
p = list(map(int, input().split()))
q = [0]
m = 0
for i in p:
m += (1+i)/2
q.append(m)
ans = 0
for i in range(k, n+1):
ans = max(q[i]-q[i-k], ans)
#あまり深く事を考えずに
print(ans) | 1 | 74,683,844,653,578 | null | 223 | 223 |
n=int(input())
dic=dict()
for i in range(n):
s=input()
if s in dic:
dic[s]+=1
else:
dic[s]=1
ans=[]
val=max(dic.values())
for kv in dic.items():
if kv[1]==val:
ans.append(kv[0])
ans=sorted(ans)
for a in ans:
print(a)
| import numpy as np
# import math
# import copy
# from collections import deque
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(10000)
def main():
N = int(input())
xy = [list(map(int,input().split())) for i in range(N)]
z_max = 0
z_min = 2 * 10 **9
w_max = - 10 ** 9
w_min = 10 ** 9
for i in range(N):
z = xy[i][0] + xy[i][1]
w = xy[i][0] - xy[i][1]
z_max = max(z_max,z)
z_min = min(z_min,z)
w_max = max(w_max,w)
w_min = min(w_min,w)
res = max(z_max-z_min,w_max-w_min)
print(res)
main()
| 0 | null | 36,640,204,028,640 | 218 | 80 |
from itertools import combinations
N = int(input())
takoyaki = list(int(x) for x in input().split())
life = 0
for c in combinations(range(N), 2):
life += takoyaki[c[0]] * takoyaki[c[1]]
print(life)
| from itertools import combinations
n = int(input())
d = list(map(int, input().split()))
ans = 0
sum = sum(d)
for i in d:
sum -= i
ans += i*sum
print(ans) | 1 | 168,210,896,103,588 | null | 292 | 292 |
#D
X,Y=map(int,input().split())
mod=10**9+7
N=10**6
fact=[1 for i in range(N+1)]
for i in range(1,N):
fact[i+1]=(fact[i]*(i+1))%mod
def nCk(n,k):
return fact[n]*pow(fact[n-k]*fact[k],mod-2,mod)
ans=0
if (2*Y-X)%3==0 and (2*X-Y)%3==0 and (2*Y-X)>=0 and (2*X-Y)>=0:
cntx=(2*Y-X)//3
cnty=(2*X-Y)//3
ans=nCk(cntx+cnty,cntx)%mod
print(ans) | n=int(input())
for x in range(n+1):
if int(x*1.08)==n:
print(x)
exit()
print(":(") | 0 | null | 138,436,865,440,228 | 281 | 265 |
n=int(input())
A=[]
for i in range(n):
for _ in range(int(input())):
x,y=map(int,input().split())
A+=[(i,x-1,y)]
a=0
for i in range(2**n):
if all(i>>j&1<1 or i>>x&1==y for j,x,y in A):
a=max(a,sum(map(int,bin(i)[2:])))
print(a) | n = int(input())
testimonies = [[] for i in range(n)]
for idx1 in range(n):
count = int(input())
for idx2 in range(count):
x,y = map(int, input().split())
testimonies[idx1].append((x-1, y))
output = 0
for combination in range(2 ** n):
consistent = True
for index in range(n):
if (combination >> index) & 1 == 0:
continue
for x,y in testimonies[index]:
if (combination >> x) & 1 != y:
consistent = False
break
if not consistent:
break
if consistent:
output = max(output, bin(combination)[2:].count("1"))
print(output) | 1 | 121,156,166,936,932 | null | 262 | 262 |
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
#import numpy as np
from collections import Counter
def main():
n, *a = map(int, read().split())
if 1 in a:
count1 = a.count(1)
if count1 == 1:
print(1)
sys.exit()
else:
print(0)
sys.exit()
maxa = max(a)
seq = [0] * (maxa + 1)
ac = Counter(a)
for ae in ac.items():
if ae[1] == 1:
seq[ae[0]] = 1
for ae in a:
t = ae * 2
while t <= maxa:
seq[t] = 0
t += ae
r = sum(seq)
print(r)
if __name__ == '__main__':
main()
|
N = int(input())
X = list(map(int, input().split()))
MAX = 10 ** 6 + 1
prime = [True] * MAX
counted = set()
for v in X:
if v in counted:
prime[v] = False
continue
for j in range(2 * v, MAX, v):
prime[j] = False
counted.add(v)
ans = 0
for v in X:
ans += int(prime[v])
print(ans)
| 1 | 14,564,424,578,340 | null | 129 | 129 |
n = int(input())
a = list(map(int, input().split()))
ret = 0
now = a[0]
for i in range(1, n):
if now > a[i]:
ret += now - a[i]
a[i] = now
now = a[i]
print(ret) | N,K = map(int, input().split())
P=list(map(int, input().split()))
print(sum(sorted(P)[0:K])) | 0 | null | 8,117,547,003,042 | 88 | 120 |
# coding: utf-8
# Your code here!
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read
n,*a = [int(i) for i in read().split()]
from itertools import accumulate
if n%2==0:
a1 = list(accumulate([0]+a[::2]))
a2 = list(accumulate([0]+a[n-1::-2]))[::-1]
#print(a1,a2)
print(max(x+y for x,y in zip(a1,a2)))
#elif n==3: print(max(a))
else:
dp0 = [0]*(n+9)
dp1 = [0]*(n+9)
dp2 = [0]*(n+9)
for i in range(n):
if i%2==0:
dp0[i] = dp0[i-2]+a[i]
if i >= 2:
dp2[i] = max(dp2[i-2],dp1[i-3],dp0[i-4]) + a[i]
else:
dp1[i] = max(dp1[i-2],dp0[i-3]) + a[i]
#print(dp0)
#print(dp1)
#print(dp2)
print(max(dp2[n-1],dp1[n-2],dp0[n-3]))
| from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n,m = inpl()
a = sorted(inpl())
ng = 10**9+1
ok = -1
def sol(x):
cnt = 0
for i,t in enumerate(a):
tmp = x - t
c = bisect.bisect_left(a,tmp)
cnt += n-c
return True if cnt >= m else False
while ng-ok > 1:
mid = (ng+ok)//2
if sol(mid):
ok = mid
else: ng = mid
# print(ok,ng)
# print(ok)
res = 0
cnt = 0
revc = [0]
for i in range(n)[::-1]:
revc.append(revc[-1] + a[i])
# print(revc)
for i in range(n):
j = n-bisect.bisect_left(a,ok-a[i])
res += j*a[i] + revc[j]
cnt += j
res -= (cnt-m) * ok
print(res) | 0 | null | 73,010,832,804,464 | 177 | 252 |
N, M = map(int, input().split())
A = list(map(int, input().split()))
for i in A:
N -= i
if N >= 0:
print(N)
else:
print(-1)
| N = int(input())
S = input()
if len(S) % 2 == 0 :
for i in range(len(S)//2) :
if S[i] != S[i+len(S)//2] :
print("No")
exit()
print("Yes")
exit()
print("No") | 0 | null | 89,593,844,184,352 | 168 | 279 |
H,W,K = map(int,input().split())
S = [input() for _ in range(H)]
ans = 10**10
for i in range(2**(H-1)): # iはbit
rel = [0 for h in range(H)]
a,b = 0,0
for h in range(H-1):
if i>>h&1:
b += 1
rel[h+1] = b
a += b
cnt = [0 for j in range(b+1)]
for w in range(W):
for h in range(H):
if S[h][w] == '1':
cnt[rel[h]] += 1
OK = True
for j in range(b+1):
if cnt[j] > K:
OK = False
break
if OK:
continue
a += 1
cnt = [0 for j in range(b+1)]
for h in range(H):
if S[h][w] == '1':
cnt[rel[h]] += 1
OK2 = True
for j in range(b+1):
if cnt[j] > K:
OK2 = False
break
if OK2:
continue
a = 10**10
break
ans = min(ans,a)
print(ans)
| n=input()
a=[int(i) for i in raw_input().split()]
a.sort()
s=a[n-1]
for i in range(n/2,n-1):
s+=a[i]*2
if(n%2==1):
s-=a[n/2]
print s | 0 | null | 28,767,338,848,512 | 193 | 111 |
#C
def gcd(a, b):
while b:
a, b = b, a % b
return a
K = int(input())
ans = 0
for a in range(1,K+1):
for b in range(a,K+1):
for c in range(b,K+1):
if a != b and b != c and a != c:
ans += 6*gcd(gcd(a,b),c)
elif a == b or b == c or a == c:
if a == b and b == c:
ans += gcd(gcd(a,b),c)
else:
ans += 3*gcd(gcd(a,b),c)
print(ans) | n=int(input())
s,t = map(str, input().split())
print(''.join([s[i] + t[i] for i in range(0,n)])) | 0 | null | 73,376,440,904,458 | 174 | 255 |
from collections import defaultdict, deque
N, u, v = map(int, input().split())
G = defaultdict(lambda: [])
for _ in range(N-1):
a,b=map(int,input().split())
G[a].append(b)
G[b].append(a)
if G[u] == [v]:
print(0)
exit()
def bfs(v):
seen = [0]*(N+1)
queue = deque()
dist = [-1]*(N+1)
dist[v] = 0
seen[v] = 1
queue.append(v)
while queue:
q = queue.popleft()
for nx in G[q]:
if seen[nx]:
continue
dist[nx] = dist[q] + 1
seen[nx] = 1
queue.append(nx)
return dist
d_u = bfs(u)
d_v = bfs(v)
ans = 0
for node in range(1, N+1):
if d_u[node] < d_v[node] and len(G[node]) == 1:
ans = max(ans, d_v[node]-1)
print(ans) | f=lambda:map(int,input().split())
n,st,sa=f()
g=[set() for _ in range(n)]
for _ in range(n-1):
a,b=f()
g[a-1].add(b-1)
g[b-1].add(a-1)
def bfs(s):
l=[-1]*n; l[s]=0; q=[s]
while q:
v=q.pop(); d=l[v]+1
for c in g[v]:
if l[c]<0: l[c]=d; q+=[c]
return l
lt=bfs(st-1)
la=bfs(sa-1)
print(max(la[i] for i in range(n) if lt[i]<la[i])-1) | 1 | 117,945,775,718,072 | null | 259 | 259 |
import numpy as np
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
from numba import njit
def getInputs():
D = int(readline())
CS = np.array(read().split(), np.int32)
C = CS[:26]
S = CS[26:].reshape((-1, 26))
return D, C, S
@njit('(i8, i4[:], i4[:, :], i4[:], )', cache=True)
def _compute_score1(D, C, S, out):
score = 0
last = np.zeros((D, 26), np.int32)
for d in range(len(out)):
if d:
last[d, :] = last[d - 1, :]
i = out[d]
score += S[d, i]
last[d, i] = d + 1
score -= np.sum(C * (d + 1 - last[d, :]))
return last, score
def _update_score():
pass
@njit('(i8, i4[:], i4[:, :], i4[:], i8, )', cache=True)
def _random_update(D, C, S, out, score):
d = np.random.randint(0, D)
q = np.random.randint(0, 26)
p = out[d]
out[d] = q
if p == q:
return out, score
last, new_score = _compute_score1(D, C, S, out)
if score < new_score:
score = new_score
else:
out[d] = p
return out, score
def _random_swap():
pass
def step1(D, C, S):
out = []
LAST = 0
for d in range(D):
max_score = -10000000
best_i = 0
for i in range(26):
out.append(i)
last, score = _compute_score1(D, C, S, np.array(out, np.int32))
if max_score < score:
max_score = score
LAST = last
best_i = i
out.pop()
out.append(best_i)
return np.array(out), LAST, max_score
def step2(D, C, S, out, score):
for i in range(10 ** 4):
out = out.astype(np.int32)
out, score = _random_update(D, C, S, out, score)
return out, score
def output(out):
out += 1
print('\n'.join(out.astype(str).tolist()))
D, C, S = getInputs()
out, _, score = step1(D, C, S)
#print(score)
out, score = step2(D, C, S, out, score)
output(out)
#print(score) | import random
import time
import copy
start = time.time()
D = int(input())
s = [[0 for j in range(26)] for i in range(D)]
c = list(map(int, input().split(" ")))
result = []
total = -10000000
for i in range(D):
a = list(map(int, input().split(" ")))
for j, k in enumerate(a):
s[i][j] = int(k)
cnt=0
score = [0 for i in range(26)]
while(1):
cnt+=1
result_tmp = []
total_tmp = 0
last = [0 for i in range(26)]
for i in range(D):
for j in range(26):
score[j] = s[i][j]
for k in range(26):
if j != k:
score[j] -= (i + 1 - last[k]) * c[k]
score_max = max(score)
tmp = []
for j in range(26):
if score_max >= 0 and score_max*0.8 <= score[j]:
tmp.append(j)
if score_max < 0 and score_max*1.1 <= score[j]:
tmp.append(j)
score_max = random.choice(tmp)
result_tmp.append(score_max)
last[score_max] = i + 1
total_tmp += score[score_max]
if total < total_tmp:
total = total_tmp
result = result_tmp.copy()
end = time.time()
if end - start > 1.8:
break
#print("total",total,cnt)
for i in range(D):
print(result[i]+1) | 1 | 9,569,040,708,370 | null | 113 | 113 |
import math
def run():
x1,y1,x2,y2=tuple(map(float,input().split()))
r=math.sqrt((x1-x2)**2+(y1-y2)**2)
print(f"{r:.30f}")
run()
| n = int(input())
tenant = [
[ [0]*10, [0]*10, [0]*10, ],
[ [0]*10, [0]*10, [0]*10, ],
[ [0]*10, [0]*10, [0]*10, ],
[ [0]*10, [0]*10, [0]*10, ]
]
for i in range(n):
b,f,r,nu = map(int, input().split())
tenant[b-1][f-1][r-1] += nu
for b in range(4):
for f in range(3):
print(' ', end='')
print(' '.join(map(str,tenant[b][f])))
if b < 3:
print('#'*20) | 0 | null | 615,673,451,578 | 29 | 55 |
n, m, l = map(int, raw_input().split(" "))
a = [map(int, raw_input().split(" ")) for j in range(n)]
b = [map(int, raw_input().split(" ")) for i in range(m)]
c = [[0 for k in range(l)] for j in range(n)]
for j in range(n):
for k in range(l):
for i in range(m):
c[j][k] += a[j][i] * b[i][k]
for j in range(n):
print " ".join(map(str, (c[j]))) | #!/usr/bin/env python3
# Generated by https://github.com/kyuridenamida/atcoder-tools
from typing import *
import collections
import functools as fts
import itertools as its
import math
import sys
INF = float('inf')
def solve(S: str, T: str):
return len(T) - max(sum(s == t for s, t in zip(S[i:], T)) for i in range(len(S) - len(T) + 1))
def main():
sys.setrecursionlimit(10 ** 6)
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
S = next(tokens) # type: str
T = next(tokens) # type: str
print(f'{solve(S, T)}')
if __name__ == '__main__':
main()
| 0 | null | 2,581,687,891,900 | 60 | 82 |
s = input()
ans = 0
for i in range(3):
if s[i] == 'R':
ans += 1
else:
if ans == 1:
break
print(ans) | n = int(input())
s = input()
if n % 2 != 0:
print('No')
else:
if s[:int((n/2))] == s[int((n/2)):]:
print('Yes')
else:
print('No')
| 0 | null | 76,249,395,329,910 | 90 | 279 |
A,V = map(int,input().split())
B,W = map(int,input().split())
T = int(input())
D1 = abs(A-B)
D2 = (V-W)*T
if (D1 - D2) <=0:
print("YES")
else:
print("NO")
| #https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/3/ALDS1_3_D
s = str(input())
l = len(s)
h = [0]
for i in range(l):
if s[i] == '\\':
h.append(h[i]-1)
elif s[i] == '/':
h.append(h[i]+1)
else:
h.append(h[i])
a = []
m = -200000
n = 0
for i in range(l+1):
if m == h[i] and i != 0:
a.append([n,i,m])
m = -200000
if m < h[i] or i == 0:
m = h[i]
n = i
if (m in h[i+1:]) == False:
m = -200000
b = []
tmp = 0
for i in range(len(a)):
for j in range(a[i][0],a[i][1]):
tmp += a[i][2] - h[j]
if s[j] == '/':
tmp += 1 / 2
elif s[j] == '\\':
tmp -= 1 / 2
b.append(int(tmp))
tmp = 0
if len(b) != 0:
i=0
while True:
if b[i] == 0:
del b[i]
i -= 1
i += 1
if i == len(b):
break
A = sum(b)
k = len(b)
print(A)
print(k,end = '')
if k != 0:
print(' ',end='')
for i in range(k-1):
print(b[i],end=' ')
print(b[len(b)-1])
else:
print('')
| 0 | null | 7,502,693,813,368 | 131 | 21 |
a, b, c, k = map(int, input().split())
ans = 0
if k <= a:
ans = k
elif k <= a+b:
ans = a
else:
ans = 2*a +b - k
print(ans) |
a,b,c,k = map(int,input().split())
ans = min(a,k)
k -= ans
if k == 0:
print(ans)
exit(0)
k -= min(b,k)
if k == 0:
print(ans)
exit(0)
ans -= min(c,k)
print(ans) | 1 | 21,867,330,287,710 | null | 148 | 148 |
N = int(input())
X = []
Y = []
for _ in range(N):
x, y = list(map(int, input().split()))
X.append(x)
Y.append(y)
points = []
for x, y in zip(X, Y):
points.append((
x + y,
x - y
))
print(max(max(dim) - min(dim) for dim in zip(*points))) | n=int(input())
p=[input().split() for _ in range(n)]
x=input()
ans=0
flag=False
for i in p:
if i[0]==x:
flag=True
continue
if flag:
ans+=int(i[1])
print(ans)
| 0 | null | 50,452,521,547,428 | 80 | 243 |
from sys import stdin
input = stdin.readline
def main():
S = input()[:-1]
N = len(S)+1
from_left = [0]*N
from_right = [0]*N
for i, s in enumerate(S, 1):
if s == '>':
from_left[i] = 0
else:
from_left[i] = from_left[i-1]+1
for i, s in enumerate(S[::-1]):
i = N-2-i
if s == '<':
from_right[i] = 0
else:
from_right[i] = from_right[i+1]+1
seq = [x if x>y else y for x, y in zip(from_left, from_right)]
answer = sum(seq)
print(answer)
if(__name__ == '__main__'):
main()
| s=list(input())
k=0
bef="x"
n=[]
ans=0
def kai(n):
if n==0:
return 0
ret=0
for i in range(1,n+1):
ret+=i
return ret
for i in s:
if bef!=i:
if bef=="x":
st=i
bef=i
k+=1
continue
bef=i
n.append(k)
k=0
k+=1
n.append(k)
n.reverse()
if st==">":
ans+=kai(n.pop())
while len(n)!=0:
if len(n)==1:
ans+=kai(n.pop())
else:
f=n.pop()
s=n.pop()
if f>s:
ans+=kai(f)+kai(s-1)
else:
ans+=kai(f-1)+kai(s)
#print("{} {}".format(f,s))
print(ans) | 1 | 156,887,959,101,020 | null | 285 | 285 |
N=int(input())
A=list(map(int,input().split()))
c=0
flug = 1
while flug:
flug = 0
for j in range(1,N)[::-1]:
if A[j]<A[j-1]:
A[j],A[j-1]=A[j-1],A[j]
flug=1
c+=1
print(*A)
print(c) |
def swap(A, i, j):
tmp = A[i]
A[i] = A[j]
A[j] = tmp
def bubble_sort(A, n):
count = 0
for i in range(0, n):
for j in range(n-1, i, -1):
if A[j] < A[j-1]:
swap(A, j, j-1)
count += 1
return A, count
n = int(input())
A = [int(x) for x in input().split()]
s_A, count = bubble_sort(A, n)
print(" ".join([str(x) for x in s_A]))
print(count)
| 1 | 16,833,801,040 | null | 14 | 14 |
k = int(input())
a,b = map(int, input().split())
if (int(b/k)*k >= a):
print("OK")
else:
print("NG") | k=int(input())
a,b = map(int, input().split())
if a%k==0:
print("OK")
exit()
if a+k-a%k<=b:
print("OK")
else:
print("NG")
| 1 | 26,373,844,870,298 | null | 158 | 158 |
N = int(input())
A = list(map(int,input().split()))
B = []
B_val = 0
ans = 0
for i in A[::-1]:
B.append(B_val)
B_val += i
for i in range(N):
ans += ( A[i] * B[-i-1] ) % (1000000000 + 7 )
print(ans % (1000000000 + 7 ) )
| from math import gcd
K=int(input())
result=0
for a in range(1,K+1):
for b in range(1,K+1):
for c in range(1,K+1):
result+=gcd(gcd(a,b),c)
print(result) | 0 | null | 19,512,131,849,810 | 83 | 174 |
N, K = (int(x) for x in input().split())
check=[False]*N
ans=N
for i in range(K):
d=int(input())
A=list(map(int, input().split()))
for j in range(d):
if check[A[j]-1]==False:
ans-=1
check[A[j]-1]=True
print(ans) | from collections import Counter
N, M = map(int, input().split())
class UnionFind:
def __init__(self, n):
self.root = [i for i in range(n)]
def unite(self, x, y):
if not self.same(x, y):
self.root[self.find(y)] = self.find(x)
def find(self, x):
if x == self.root[x]:
return x
else:
self.root[x] = self.find(self.root[x])
return self.root[x]
def same(self, x, y):
return self.find(x) == self.find(y)
UF = UnionFind(N)
ans = N-1
for _ in range(M):
x, y = map(int, input().split())
if not UF.same(x-1, y-1):
UF.unite(x-1, y-1)
ans -= 1
print(ans) | 0 | null | 13,544,103,556,750 | 154 | 70 |
import sys
import math
import copy
import heapq
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(1000000)
# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]
INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)
def nck(n, k, kaijyo):
return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD
def npk(n, k, kaijyo):
if k == 0 or k == n:
return n % MOD
return (kaijyo[n] * divide(kaijyo[n-k])) % MOD
def fact_and_inv(SIZE):
inv = [0] * SIZE # inv[j] = j^{-1} mod MOD
fac = [0] * SIZE # fac[j] = j! mod MOD
finv = [0] * SIZE # finv[j] = (j!)^{-1} mod MOD
inv[1] = 1
fac[0] = fac[1] = 1
finv[0] = finv[1] = 1
for i in range(2, SIZE):
inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
fac[i] = fac[i - 1] * i % MOD
finv[i] = finv[i - 1] * inv[i] % MOD
return fac, finv
def renritsu(A, Y):
# example 2x + y = 3, x + 3y = 4
# A = [[2,1], [1,3]])
# Y = [[3],[4]] または [3,4]
A = np.matrix(A)
Y = np.matrix(Y)
Y = np.reshape(Y, (-1, 1))
X = np.linalg.solve(A, Y)
# [1.0, 1.0]
return X.flatten().tolist()[0]
class TwoDimGrid:
# 2次元座標 -> 1次元
def __init__(self, h, w, wall="o"):
self.h = h
self.w = w
self.size = (h+2) * (w+2)
self.wall = wall
self.get_grid()
self.init_cost()
def get_grid(self):
grid = [self.wall * (self.w + 2)]
for i in range(self.h):
grid.append(self.wall + getS() + self.wall)
grid.append(self.wall * (self.w + 2))
self.grid = grid
def init_cost(self):
self.cost = [INF] * self.size
def pos(self, x, y):
# 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
return y * (self.w + 2) + x
def getgrid(self, x, y):
return self.grid[y][x]
def get(self, x, y):
return self.cost[self.pos(x, y)]
def set(self, x, y, v):
self.cost[self.pos(x, y)] = v
return
def show(self):
for i in range(self.h+2):
print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
def showsome(self, tgt):
for t in tgt:
print(t)
return
def showsomejoin(self, tgt):
for t in tgt:
print("".join(t))
return
def search(self):
grid = self.grid
move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
d = deque()
d.append((1,1))
self.set(1,1,0)
while(d):
cx, cy = d.popleft()
cc = self.get(cx, cy)
if self.getgrid(cx, cy) == self.wall:
continue
for dx, dy in [(1, 0), (0, 1)]:
nx, ny = cx + dx, cy + dy
if self.getgrid(cx, cy) == self.getgrid(nx, ny):
if self.get(nx, ny) > cc:
d.append((nx, ny))
self.set(nx, ny, cc)
else:
if self.get(nx, ny) > cc + 1:
d.append((nx, ny))
self.set(nx, ny, cc + 1)
# self.show()
ans = (self.get(self.w, self.h))
if self.getgrid(1,1) == "#":
ans += 1
print((ans + 1) // 2)
def soinsu(n):
ret = defaultdict(int)
for i in range(2, int(math.sqrt(n) + 2)):
if n % i == 0:
while True:
if n % i == 0:
ret[i] += 1
n //= i
else:
break
if not ret:
return {n: 1}
return ret
def solve():
h, w = getList()
G = TwoDimGrid(h, w)
G.search()
def main():
n = getN()
for _ in range(n):
solve()
return
if __name__ == "__main__":
# main()
solve() | from math import gcd
K = int(input())
ans = 0
for i in range(1, K+1):
for j in range(i+1, K+1):
for k in range(j+1, K+1):
ans += gcd(gcd(i, j), k)*6
for i in range(1, K+1):
for j in range(i+1, K+1):
ans += gcd(i, j)*6
ans += K*(K+1)//2
print(ans)
| 0 | null | 42,422,152,540,196 | 194 | 174 |
n=int(input())
a=list(map(int,input().split()))
dp=[0]*(n+1)
for i in range(n-1):
dp[a[i]]+=1
for i in range(n):
print(dp[i+1]) | #-*-coding:utf-8-*-
import sys
input=sys.stdin.readline
import collections
def main():
bosses=[]
count={}
n = int(input())
bosses=list(map(int,input().split()))
ans=[0]*n
for i in bosses:
ans[i-1]+=1
for a in ans:
print(a)
if __name__=="__main__":
main() | 1 | 32,436,898,942,500 | null | 169 | 169 |
import sys
from functools import reduce
from math import gcd
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
mod = 10 ** 9 + 7
N = int(readline())
A = list(map(int,readline().split()))
lcm = reduce(lambda x,y:x*y//gcd(x,y),A)
ans = 0
ans = sum(lcm//x for x in A)
print(ans%mod) | from fractions import gcd
import sys
input = sys.stdin.buffer.readline
mod = 10 ** 9 + 7
def modinv(a, mod):
return pow(a, mod - 2, mod)
n = int(input())
if n == 1:
print(1)
exit()
A = list(map(int, input().split()))
lcm = A[0]
for i in range(n):
g = gcd(lcm, A[i])
lcm *= A[i] // g
ans = 0
for i in range(n):
gyaku = modinv(A[i], mod)
ans += lcm * gyaku
ans %= mod
print(ans)
| 1 | 87,701,440,237,140 | null | 235 | 235 |
n=list(map(int,input().split()))
a=list(map(int,input().split()))
count=0
for i in range(0,len(a)):
if n[1]<=a[i]:
count+=1
print(count) | from collections import deque
n = int(input())
q = deque(["a"])
# 最後に最新の文字数のセットだけ拾う
for i in range(n - 1):
next_q = deque()
for curr in q:
suffix = ord(max(curr)) + 1
for x in range(ord("a"), suffix + 1):
next_q.append(curr + chr(x))
q = next_q
print(*q, sep="\n") | 0 | null | 115,748,552,674,360 | 298 | 198 |
N = int(input())
sum = 0
for i in range(1, N + 1):
if not i % 3 == 0 and not i % 5 == 0:
sum += i
print(sum) | N = int(input())
A = []
for i in range(N+1):
if i % 15 == 0:
pass
elif i % 3 == 0:
pass
elif i % 5 == 0:
pass
else:
A.append(i)
print(sum(A)) | 1 | 35,018,623,496,732 | null | 173 | 173 |
def function(n):
if n < 3:
lis.append(0)
elif 3 <= n < 6:
lis.append(1)
else:
lis.append(lis[n-1] + lis[n-3])
def recri(s):
for n in range(s):
function(n)
# for n in range(20):
# print(function(n))
if __name__ == '__main__':
lis = []
s = int(input()) + 1
recri(s)
print(lis[s-1]%(10 ** 9 + 7)) | mod = 10**9 + 7
n = int(input())
dp = [0]*(n+1)
dp[0] = 1
if n >= 3:
for i in range(3,n+1):
dp[i] = dp[i-1] + dp[i-3]
print(dp[n] % mod) | 1 | 3,295,723,489,082 | null | 79 | 79 |
word = input()
q = int(input())
for _ in range(q):
s = input().split(" ")
command = s[0]
a = int(s[1])
b = int(s[2])
if command == "print":
print(word[a:b+1])
elif command == "reverse":
word = word[:a] + word[a:b+1][::-1] + word[b+1:]
elif command == "replace":
word = word[:a] + s[3] + word[b+1:] | n = int(input())
s = input()
count = 0
for i in range(len(list(s))-2):
if s[i] == "A" and s[i+1] == "B" and s[i+2] =="C":
count += 1
print(count) | 0 | null | 50,681,593,390,080 | 68 | 245 |
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
MOD = 998244353
P = [tuple(map(int, input().split())) for _ in range(K)]
E = [0] * N
def update(i, v):
while i < N:
E[i] = (E[i] + v) % MOD
i |= i+1
def query(i):
r = 0
while i > 0:
r += E[i-1]
i &= i-1
return r % MOD
update(0, 1)
update(1, -1)
for i in range(N-1):
v = query(i+1)
for L, R in P:
if i + L < N:
update(i+L, v)
if i + R + 1 < N:
update(i+R+1, -v)
print(query(N))
| from itertools import accumulate
N, K = map(int, input().split())
mod = 998244353
Move = [list(map(int, input().split())) for _ in range(K)]
DP = [0] * N
DP[0] = 1
DP[1] = -1
cnt = 0
for i in range(N):
DP[i] += cnt
DP[i] %= mod
cnt = DP[i]
for l, r in Move:
if i + l < N:
DP[i+l] += DP[i]
if i + r + 1 < N:
DP[i + r + 1] -= DP[i]
print(DP[-1]) | 1 | 2,715,446,450,652 | null | 74 | 74 |
print('bust' if sum(list(map(int,input().split()))) > 21 else 'win') | def main():
a, b = map(int, input().split())
import math
print(int(a*b/math.gcd(a,b)))
if __name__ == "__main__":
main()
| 0 | null | 116,233,869,330,342 | 260 | 256 |
N,K=map(int,input().split())
p,c=1,1
while p<=N:
p*=K
c+=1
print(c-1) | a, b = map(int, input().split())
def base10to(n, b):
if (int(n/b)):
return base10to(int(n/b), b) + str(n%b)
return str(n%b)
print(len(base10to(a,b))) | 1 | 64,099,740,088,970 | null | 212 | 212 |
# coding: utf-8
# Your code here!
#一時保存
def count(target):
num=0
for i in range(N):
temp=target//F[i]
num+=max(A[i]-temp,0)
return num
N,K=map(int,input().split())
A=list(map(int,input().split()))
F=list(map(int,input().split()))
A.sort()
F.sort(reverse=True)
ok=10**16+1
ng=0
if count(0)<=K:
print(0)
exit()
while ok-ng>1:
mid=(ok+ng)//2
if count(mid)>K:
ng=mid
else:
ok=mid
ng=0
while ok-ng>1:
mid=(ok+ng)//2
if count(mid)>K:
ng=mid
else:
ok=mid
print(ok)
| n, x, m = map(int, input().split())
li = [x]
se = {x}
for i in range(n-1):
x = x*x%m
if x in se:
idx = li.index(x)
break
li.append(x)
se.add(x)
else:
print(sum(li))
exit(0)
ans = sum(li) + sum(li[idx:])*((n-len(li)) // (len(li)-idx)) + sum(li[idx:idx+(n-len(li)) % (len(li)-idx)])
print(ans) | 0 | null | 83,989,210,852,012 | 290 | 75 |
x, y = map(int, input().split())
ans = 'No'
for i in range(x + 1):
j = x - i
if i * 2 + j * 4 == y:
ans = 'Yes'
break
print(ans)
| X,Y = map(int,input().split())
if Y%2 == 0 and 2*X<=Y<=4*X:
print('Yes')
else:
print('No') | 1 | 13,785,447,598,310 | null | 127 | 127 |
l,r,f = map(int,input().split())
count = 0
for i in range(l,r+1):
if i % f == 0 :
count = count + 1
print(count) |
s=[0,0]
for i in range(int(input())):
r=input().split()
if r[0]<r[1]:
s[1]+=3
elif r[1]<r[0]:
s[0]+=3
else:
s[0]+=1
s[1]+=1
print(str(s[0])+' '+str(s[1]))
| 0 | null | 4,735,593,929,900 | 104 | 67 |
N = int(input())
ans = (N * 100 + 99) // 108
if N==int(ans*1.08):
print(ans)
else:
print(':(')
| n=int(input())
a=[int(v) for v in input().split()]
check=1
a.sort()
for i in range (0,n-1):
if a[i]==a[i+1]:
check=0
break
if check==0:
print("NO")
else:
print("YES")
| 0 | null | 99,677,984,091,022 | 265 | 222 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
6
5
3
1
3
4
3
output:
3
"""
import sys
def solve():
# write your code here
max_profit = -1 * float('inf')
min_stock = prices[0]
for price in prices[1:]:
max_profit = max(max_profit, price - min_stock)
min_stock = min(min_stock, price)
return max_profit
if __name__ == '__main__':
_input = sys.stdin.readlines()
p_num = int(_input[0])
prices = list(map(int, _input[1:]))
print(solve()) | import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
D = int(input())
C = list(map(int,input().split()))
S = [list(map(int,input().split())) for _ in range (D)]
t = [int(input()) for _ in range(D)]
M = 26
last = [0]*M
score = 0
for i in range(D):
score += S[i][t[i]-1]
last[t[i]-1] = i+1
for m in range(M):
score -= C[m]*(i+1-last[m])
print(score)
| 0 | null | 4,932,420,267,040 | 13 | 114 |
S=input();print(sum(a!=b for a,b in zip(S,S[::-1]))//2) | Ss = input().rstrip()
lenS = len(Ss)
ans = 0
for S, T in zip(Ss[:lenS//2], Ss[::-1]):
ans += S != T
print(ans)
| 1 | 119,653,947,959,268 | null | 261 | 261 |
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b)
def main():
N, M = map(int, readline().split())
A = list(set(map(int, readline().split())))
B = A[::]
while not any(b % 2 for b in B):
B = [b // 2 for b in B]
if not all(b % 2 for b in B):
print(0)
return
semi_lcm = 1
for a in A:
semi_lcm = lcm(semi_lcm, a // 2)
if semi_lcm > M:
print(0)
return
print((M // semi_lcm + 1) // 2)
return
if __name__ == '__main__':
main()
| import math
def makelist(n, m):
return [[0 for _ in range(m)] for _ in range(n)]
N, M = list(map(int, input().split()))
a = list(map(int, input().split()))
# 最小公倍数
# ユークリッドの互除法
def lcm(a, b):
def gcd(a, b): # a >= b
if b == 0:
return a
else:
return gcd(b, a % b)
return a * b // gcd(a, b)
c = 1
for e in a:
c = lcm(c, e // 2)
hoge = [ (c // (e // 2)) % 2 == 1 for e in a ]
if all(hoge):
ans = 0
if c <= M:
ans += 1
M -= c
ans += M // (c * 2)
print(ans)
else:
print(0)
| 1 | 102,022,542,035,638 | null | 247 | 247 |
while True:
try:
a, b = map(int, input().split())
except EOFError:
break
count=1
k=a+b
while k>=10:
k//=10
count+=1
print(count) | import sys
import math
for line in sys.stdin:
try:
a, b = [int(i) for i in line.split()]
print(int(math.log10(a + b) + 1))
except:
break | 1 | 145,327,002 | null | 3 | 3 |
import sys
input = sys.stdin.buffer.readline
H, W, K = map(int, input().split())
B = {}
for _ in range(K):
r, c, v = map(int, input().split())
B[(r, c)] = v
dp = [[0]*(W+1) for _ in range(4)]
for i in range(1, H+1):
for j in range(1, W+1):
if (i, j) in B:
v = B[(i, j)]
dp[0][j] = max(dp[0][j-1], dp[0][j], dp[1][j], dp[2][j], dp[3][j])
dp[1][j] = max(dp[1][j-1], dp[0][j]+v)
dp[2][j] = max(dp[2][j-1], dp[1][j-1]+v)
dp[3][j] = max(dp[3][j-1], dp[2][j-1]+v)
else:
dp[0][j] = max(dp[0][j-1], dp[0][j], dp[1][j], dp[2][j], dp[3][j])
dp[1][j] = dp[1][j-1]
dp[2][j] = dp[2][j-1]
dp[3][j] = dp[3][j-1]
print(max(dp[i][-1] for i in range(4)))
| import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal, ROUND_CEILING
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
R, C, K = MAP()
dp1 = [[0]*4 for _ in range(C+1)]
dp2 = [[0]*4 for _ in range(C+1)]
field = [[0]*(C+1)] + [[0]*(C+1) for _ in range(R)]
for _ in range(K):
r, c, v = MAP()
field[r][c] = v
for i in range(1, R+1):
for j in range(1, C+1):
if i%2 == 0:
up_max = max(dp1[j])
p = field[i][j]
dp2[j][0] = max(up_max, dp1[j-1][0])
dp2[j][1] = max(up_max+p, dp2[j-1][1], dp2[j-1][0]+p)
dp2[j][2] = max(dp2[j-1][2], dp2[j-1][1]+p)
dp2[j][3] = max(dp2[j-1][3], dp2[j-1][2]+p)
else:
up_max = max(dp2[j])
p = field[i][j]
dp1[j][0] = max(up_max, dp2[j-1][0])
dp1[j][1] = max(up_max+p, dp1[j-1][1], dp1[j-1][0]+p)
dp1[j][2] = max(dp1[j-1][2], dp1[j-1][1]+p)
dp1[j][3] = max(dp1[j-1][3], dp1[j-1][2]+p)
a = max(dp1[-1])
b = max(dp2[-1])
print(max(a, b))
| 1 | 5,615,444,045,970 | null | 94 | 94 |
h, w = map(int, input().split())
ma = [ list(input()) for _ in range(h) ]
d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
ans = 0
def bfs(sy, sx):
if ma[sy][sx] == "#":
return 0
q = [[sy, sx, 0]]
flag = [[0] * w for _ in range(h)]
flag[sy][sx] = 1
ans = 0
while True:
if len(q) == 0:
break
y, x, dist = q.pop(0)
for dy, dx in d:
if 0 <= y + dy < h and 0 <= x + dx < w and flag[y + dy][x + dx] == 0 and ma[y + dy][x + dx] == ".":
flag[y + dy][x + dx] = 1
q.append([y + dy, x + dx, dist + 1])
ans = max(ans, dist + 1)
return ans
for j in range(h):
for i in range(w):
ans = max(ans, bfs(j, i))
print(ans) | import sys
from collections import deque
sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7
def resolve():
H, W = map(int, input().split())
grid = [input() for _ in range(H)]
res = []
for sh in range(H):
for sw in range(W):
if grid[sh][sw] == "#":
continue
maze = [[f_inf] * W for _ in range(H)]
maze[sh][sw] = 0
que = deque([[sh, sw]])
while que:
h, w = que.popleft()
for dh, dw in ((1, 0), (-1, 0), (0, 1), (0, -1)):
next_h, next_w = h + dh, w + dw
if next_h < 0 or next_h >= H or next_w < 0 or next_w >= W or grid[next_h][
next_w] == "#":
continue
if maze[next_h][next_w] > maze[h][w] + 1:
maze[next_h][next_w] = maze[h][w] + 1
que.append([next_h, next_w])
res.append(maze[next_h][next_w])
print(max(res))
if __name__ == '__main__':
resolve()
| 1 | 94,586,152,369,870 | null | 241 | 241 |
N, M = map(int, input().split())
corret_list = [False] * (N+1)
wa_number = [0] * (N+1)
true_ans = 0
penalty = 0
for _ in range(M):
P, S = input().split()
P = int(P)
if S == 'AC':
if not corret_list[P]:
true_ans += 1
corret_list[P] = True
continue
else:
continue
else:
if not corret_list[P]:
wa_number[P] += 1
continue
for i in range(len(corret_list)):
if corret_list[i]:
penalty += wa_number[i]
print(true_ans, penalty) | #coding: utf-8
num1, num2= list(map(int, input().split()))
print(num1*num2) | 0 | null | 54,273,293,566,140 | 240 | 133 |
def main():
N = int(input())
num = 0
B = 1
for A in range(1, N):
for B in range(1, N):
if N - A * B >= 1:
num = num + 1
else:
break
print(num)
main()
| #! /usr/bin/env python
#-*- coding: utf-8 -*-
''' ?????\????????? '''
#
# ?¨??????????O()
def insertion_sort(A, N):
for i in range(N):
tmp = A[i]
j = i - 1
while j >= 0 and A[j] > tmp:
A[j + 1] = A[j]
j -= 1
A[j + 1] = tmp
print(' '.join(map(str, A)))
return A
if __name__ == "__main__":
N = int(input())
A = list(map(int, input().split()))
# N = 6
# A = [5, 2, 4, 6, 1, 3]
array_sorted = insertion_sort(A, N) | 0 | null | 1,281,242,573,380 | 73 | 10 |
a = 100
x = int(input())
count = 0
while a < x:
a = a + a // 100
count += 1
print(count) | n = int(input())
all_result = 10 ** n
nothing = 8 ** n
only_1 = 9 ** n
result = all_result + nothing - 2 * only_1
print(result % (10**9+7)) | 0 | null | 15,093,386,828,222 | 159 | 78 |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 8 18:25:14 2020
@author: liang
"""
H, W = map(int, input().split())
field = [input() for i in range(H)]
def Init():
return [[-1]*W for _ in range(H)]
ans = -1
from collections import deque
q = deque()
adj = ((1,0), (-1,0), (0,1), (0,-1))
def BFS(y,x):
def isValid(t):
if t[0] < 0 or t[0] >= H or t[1] < 0 or t[1] >= W or field[t[0]][t[1]] == "#":
return False
return True
d = Init()
if field[y][x] == '#':
return -1
d[y][x] = 0
q.append((y,x))
res = 0
while q:
cur = q.popleft()
for a in adj:
nex = (cur[0]+a[0], cur[1]+a[1])
if isValid(nex) and (d[nex[0]][nex[1]]== -1 or d[nex[0]][nex[1]] > d[cur[0]][cur[1]]+1):
d[nex[0]][nex[1]] = d[cur[0]][cur[1]]+1
#if res < d[nex[0]][nex[1]]:
# res = d[nex[0]][nex[1]]
res = max(res, d[nex[0]][nex[1]])
q.append(nex)
return res
for i in range(H):
for j in range(W):
tmp = BFS(i,j)
if tmp > ans:
ans = tmp
print(ans) | H, W = map(int, input().split())
maze = [input() for i in range(H)]
direction = [
(0, 1),
(1, 0),
(-1, 0),
(0, -1)
]
def bfs(sy, sx):
reached = [[-1] * W for _ in range(H)]
reached[sy][sx] = 0
from collections import deque
que = deque([[sy, sx]])
#d_max = 0
while que:
iy, ix = que.popleft()
for d in direction:
tx, ty = ix + d[0], iy + d[1]
if tx >= W or ty >= H or tx < 0 or ty < 0:
continue
if reached[ty][tx] != -1 or maze[ty][tx] == '#':
continue
reached[ty][tx] = reached[iy][ix] + 1
#d_max = max(reached[ty][tx], d_max)
que.append([ty, tx])
d_max = 0
for i in range(H):
for j in range(W):
d_max = max(d_max,reached[i][j])
return d_max
ans = 0
for i in range(H):
for j in range(W):
if maze[i][j] == '.':
ans = max(ans, bfs(i, j))
# for i in range(H):
# for j in range(i, W):
# for k in range(H):
# for l in range(k, W):
# if maze[i][j] == '#' or maze[k][l] == '#':
# continue
# else:
# ans = max(ans, bfs(i, j, k, l))
print(ans)
| 1 | 94,539,227,011,900 | null | 241 | 241 |
a = list(map(int,input().split()))
print("bust" if sum(a) >= 22 else "win") | A1, A2, A3 = [int(s) for s in input().split(' ')]
print('win' if A1+A2+A3 < 22 else 'bust')
| 1 | 118,519,461,503,612 | null | 260 | 260 |
N,K = [int(i) for i in input().split()]
H = [int(i) for i in input().split()]
ans = 0
for i in range(N):
if K <= H[i]:
ans += 1
print(ans)
| s, w=map(int, input().split())
if s>w:
print('safe')
elif s<=w:
print('unsafe') | 0 | null | 103,629,277,948,382 | 298 | 163 |
a,k,d = map(int, input().split())
if a < 0:
x = -a
else:
x = a
y = x % d
l = x // d
m = k - l
if m < 0:
ans = x - (k * d)
elif m % 2 ==0:
ans = y
else :
ans = y - d
print(abs(ans)) | import math
X,K,D=map(int,input().split())
count=0
#Xが初期値
#Dが移動量(+or-)
#K回移動後の最小の座標
#X/D>Kの場合、K*D+Xが答え
Y = 0
#X>0 D>0 の場合
if X / D > K and X / D > 0:
Y = abs(X - D * K)
elif abs(X / D) > K and X / D < 0:
Y = abs(X + D * K)
else:
#X/D<Kの場合、X mod D
L = abs(X) % D
M = math.floor(abs(X) / D)
if (K - M) % 2 == 0:
Y = L
else:
Y=abs(L-D)
print(Y) | 1 | 5,221,377,931,678 | null | 92 | 92 |
import math
a = float(input())
print("{0:.6f} {1:.6f}".format(a*a*math.pi, a*2.0*math.pi)) | #!/usr/bin/env python3
import sys
MOD = 1000000007 # type: int
def solve(N: int, K: int):
num_gcd = {}
for k in range(K, 0, -1):
num_select = K // k
num_gcd_k = pow(num_select, N, MOD)
for multiple in range(2, num_select+1):
num_gcd_k -= num_gcd[k * multiple]
num_gcd[k] = num_gcd_k
result = 0
for k in range(1, K+1):
result += (k * num_gcd[k]) % MOD
print(result % MOD)
return
# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
K = int(next(tokens)) # type: int
solve(N, K)
if __name__ == '__main__':
main()
| 0 | null | 18,602,618,410,560 | 46 | 176 |
s = input()
for _ in range(int(input())):
o = input().split()
a, b = map(int, o[1:3])
b += 1
c = o[0][2]
if c == 'p':
s = s[:a]+o[3]+s[b:]
elif c == 'i':
print(s[a:b])
elif c == 'v':
s = s[:a]+s[a:b][::-1]+s[b:]
| def rvrs(base, start, end):
r = base[int(start):int(end) + 1][::-1]
return base[:int(start)] + r + base[int(end) + 1:]
def rplc(base, start, end, string):
return base[:int(start)] + string + base[int(end) + 1:]
ans = input()
q = int(input())
for _ in range(q):
ORD = list(input().split())
if ORD[0] == 'print':
print(ans[int(ORD[1]):int(ORD[2])+1])
elif ORD[0] == 'reverse':
ans = rvrs(ans, int(ORD[1]), int(ORD[2]))
elif ORD[0] == 'replace':
ans = rplc(ans, int(ORD[1]), int(ORD[2]), ORD[3])
| 1 | 2,084,093,964,448 | null | 68 | 68 |
N = int(input())
"""nを素因数分解"""
"""2以上の整数n => [[素因数, 指数], ...]の2次元リスト"""
def factorization(n):
if (n == 1):
return []
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1:
arr.append([temp, 1])
if arr==[]:
arr.append([n, 1])
return arr
#print(factorization(N))
list_a = factorization(N)
count = 0
for i in range(len(list_a)):
num = list_a[i][1]
cal = 1
while(num > 0):
num -= cal
cal += 1
if(num < 0) :
break
count += 1
#print(num,count)
print(count)
| from collections import defaultdict
N = int(input())
S = defaultdict(int)
for i in range(N):
S[input()] += 1
m = max(S.values())
for s in sorted(filter(lambda x: S[x] == m, S)):
print(s) | 0 | null | 43,661,485,438,298 | 136 | 218 |
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
# INF = float("inf")
INF = 10**18
import bisect
import statistics
mod = 10**9+7
# mod = 998244353
N = int(input())
if N % 2 == 0:
print(0.5)
else:
print(1.0-((N-1)//2.0)/N)
| num = int(input())
if num%2==0:
print((num//2) / num)
else:
print(((num//2)+1) / num) | 1 | 176,622,731,829,792 | null | 297 | 297 |
xy = [map(int,input().split()) for i in range(2)]
x,y = [list(j) for j in zip(*xy)]
if (y[0] + 1) == y[1] :
ans = 0
else:
ans = 1
print(ans) | m_one = list(map(int, input().split()))
m_two = list(map(int,input().split()))
print(1 if m_one[1] > m_two[1] else 0) | 1 | 123,939,836,446,030 | null | 264 | 264 |
a, b, c = map(int, input().split())
k = int(input())
if a >= b:
while a >= b:
if k == 0:
print("No")
exit()
b *= 2
k -= 1
if b >= c:
while b >= c:
if k == 0:
print("No")
exit()
c *= 2
k -= 1
print("Yes")
| A,B,C=map(int,input().split())
K=int(input())
for i in range(K):
if A>=B:
B=2*B
elif B>=C:
C=2*C
if A<B and B<C:
print('Yes')
break
else:
print('No') | 1 | 6,896,878,506,912 | null | 101 | 101 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.