code1
stringlengths 16
427k
| code2
stringlengths 16
427k
| similar
int64 0
1
| pair_id
int64 2
178,025B
⌀ | question_pair_id
float64 27.1M
177,113B
⌀ | code1_group
int64 1
297
| code2_group
int64 1
297
|
---|---|---|---|---|---|---|
N, K = map(int, input().split())
LR = [tuple(map(int, input().split())) for _ in range(K)]
MOD = 998244353
class Mint:
__slots__ = ('value')
def __init__(self, value=0):
self.value = value % MOD
if self.value < 0: self.value += MOD
@staticmethod
def get_value(x): return x.value if isinstance(x, Mint) else x
def inverse(self):
a, b = self.value, MOD
u, v = 1, 0
while b:
t = a // b
b, a = a - t * b, b
v, u = u - t * v, v
if u < 0: u += MOD
return u
def __repr__(self): return str(self.value)
def __eq__(self, other): return self.value == other.value
def __neg__(self): return Mint(-self.value)
def __hash__(self): return hash(self.value)
def __bool__(self): return self.value != 0
def __iadd__(self, other):
self.value = (self.value + Mint.get_value(other)) % MOD
return self
def __add__(self, other):
new_obj = Mint(self.value)
new_obj += other
return new_obj
__radd__ = __add__
def __isub__(self, other):
self.value = (self.value - Mint.get_value(other)) % MOD
if self.value < 0: self.value += MOD
return self
def __sub__(self, other):
new_obj = Mint(self.value)
new_obj -= other
return new_obj
def __rsub__(self, other):
new_obj = Mint(Mint.get_value(other))
new_obj -= self
return new_obj
def __imul__(self, other):
self.value = self.value * Mint.get_value(other) % MOD
return self
def __mul__(self, other):
new_obj = Mint(self.value)
new_obj *= other
return new_obj
__rmul__ = __mul__
def __ifloordiv__(self, other):
other = other if isinstance(other, Mint) else Mint(other)
self *= other.inverse()
return self
def __floordiv__(self, other):
new_obj = Mint(self.value)
new_obj //= other
return new_obj
def __rfloordiv__(self, other):
new_obj = Mint(Mint.get_value(other))
new_obj //= self
return new_obj
LR.sort(key=lambda x: x[1])
pl = pr = -1
LR2 = []
for l, r in LR:
if LR2:
pl, pr = LR2.pop()
if l <= pl:
LR2.append((l, r))
elif l <= pr:
LR2.append((pl, r))
else:
LR2.append((pl, pr))
LR2.append((l, r))
else:
LR2.append((l, r))
dp = [Mint() for _ in range(N + 5)]
dp[1] += 1
dp[2] -= 1
for i in range(1, N):
dp[i] += dp[i - 1]
for l, r in LR2:
nl = min(i + l, N + 1)
nr = min(i + r, N + 1)
dp[nl] += dp[i]
dp[nr + 1] -= dp[i]
dp[N] += dp[N - 1]
print(dp[N])
|
class UnionFind:
def __init__(self, sz: int):
self._par: list[int] = [-1] * sz
def root(self, a: int):
if self._par[a] < 0:
return a
self._par[a] = self.root(self._par[a])
return self._par[a]
def size(self, a: int):
return -self._par[self.root(a)]
def unite(self, a, b):
a = self.root(a)
b = self.root(b)
if a != b:
if self.size(a) < self.size(b):
a, b = b, a
self._par[a] += self._par[b]
self._par[b] = a
if __name__ == '__main__':
N, M = map(int, input().split())
uf = UnionFind(N + 1)
for i in range(M):
a, b = map(int, input().split())
uf.unite(a, b)
ans = 1
for i in range(1, N + 1):
ans = max(ans, uf.size(i))
print(ans)
| 0 | null | 3,319,164,790,452 | 74 | 84 |
from sys import stdin
import sys
import math
from functools import reduce
a,b = [int(x) for x in stdin.readline().rstrip().split()]
c = int(b*10)
for i in range(10):
if a == int(c*0.08):
print(c)
sys.exit()
c = c + 1
print(-1)
|
#!/usr/bin/python3
import sys
input = lambda: sys.stdin.readline().strip()
a, b = [int(x) for x in input().split()]
try:
print(next(x for x in range(2000) if 8 * x // 100 == a and 10 * x // 100 == b))
except StopIteration:
print(-1)
| 1 | 56,572,586,565,892 | null | 203 | 203 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# This problem can be solved smarter. But this example shows simple method
#
import sys
while True:
s = sys.stdin.readline().strip()
if s == '-':
break
n = int(sys.stdin.readline())
for i in range(n):
h = int(sys.stdin.readline())
s = s[h:] + s[:h]
print(s)
|
while True:
try:
# a >=b
a, b = sorted(map(int, input().strip("\n").split(" ")), reverse=True)
d = a * b
# calc. gcm by ユークリッド互除法
while True:
c = a % b
# print("{0} {1} {2}".format(a, b, c))
if c == 0:
break
else:
a, b = sorted([b, a % b], reverse=True)
gcm = b
lcm = d / gcm
# print("gcm is {}".format(b))
print("{0:d} {1:d}".format(int(gcm), int(lcm)))
#print("{0} {1}".format(a, b))
#a, b = sorted([b, a % b], reverse=True)
#print("{0} {1}".format(a, b))
except EOFError:
break # escape from while loop
| 0 | null | 965,838,158,638 | 66 | 5 |
def readInt():
return int(input())
def readList():
return list(map(int,input().split()))
def readMap():
return map(int,input().split())
def readStr():
return input()
inf=float('inf')
mod = 10**9+7
import math
def solve(N,X,M):
seen=set()
order_seen=[]
while X not in seen:
seen.add(X)
order_seen.append(X)
X=f(X,M)
pos=order_seen.index(X) # Find position of when the cycle begins
if pos>N: # If position is greater than N, then we know we are not going to include any values from the cycle.
return sum(order_seen[:N])
terms_before_cycle=order_seen[:pos]
sum_terms_before_cycle=sum(terms_before_cycle)
ans=sum_terms_before_cycle
terms_in_cycle=order_seen[pos:]
sum_cycle=sum(terms_in_cycle)
length_cycle=len(terms_in_cycle)
number_remaining_terms=N-pos
mult_factor=(number_remaining_terms)//length_cycle
ans+=(sum_cycle*mult_factor)
numb_remain=(number_remaining_terms)%length_cycle
ans+=sum(terms_in_cycle[:numb_remain])
return ans
# The function for the recurrence relation. A_n+1=A_n^2%M
def f(A,M):
return pow(A,2,M)
N,X,M=readMap()
print(solve(N,X,M))
|
from collections import deque
def solve(n,t):
q=deque([])
for i in range(n):
l=list(input().split())
q.append(l)
time=0
while not len(q)==0:
x=q.popleft()
if int(x[1])-t>0:
x[1]=str(int(x[1])-t)
time+=t
q.append(x)
else:
print(x[0]+" "+str(time+int(x[1])))
time+=int(x[1])
n,t=map(int,input().split())
solve(n,t)
| 0 | null | 1,444,104,851,680 | 75 | 19 |
al = list("abcdefghijklmnopqrstuvwxyz")
c = input()
pos = al.index(c)
print(al[pos+1])
|
# !/use/bin/python3
"""
https://atcoder.jp/contests/abc151/tasks/abc151_a
Next Alphabate
"""
def solve(c):
ans = ord(c)
return chr(ans+1)
if __name__ == "__main__":
c = input()
print(solve(c))
| 1 | 91,961,670,228,868 | null | 239 | 239 |
1
2
3
4
5
6
7
L=map(int, raw_input().split())
if L[0]>L[1]:
print "a > b"
elif L[0]<L[1]:
print "a < b"
else:
print "a == b"
|
X,Y=map(int,input().split())
def ans170(X:int, Y:int):
if Y<=X*4 and Y>=X*2 and Y%2==0:
return("Yes")
else:
return("No")
print(ans170(X,Y))
| 0 | null | 7,136,141,419,050 | 38 | 127 |
a = input().split()
d = int(a[0]) // int(a[1])
r = int(a[0]) % int(a[1])
f = float(a[0]) / float(a[1])
print('{0} {1} {2:.5f}'.format(d,r,f))
|
def main(X, Y):
for n_crane in range(X + 1):
n_turtle = X - n_crane
y = n_crane * 2 + n_turtle * 4
if y == Y:
print('Yes')
return
print('No')
if __name__ == "__main__":
X, Y = [int(s) for s in input().split(' ')]
main(X, Y)
| 0 | null | 7,122,741,371,720 | 45 | 127 |
import heapq
n,k = map(int,input().split())
a = [int(i) for i in input().split()]
low = 0
high = 10**9
if k == 0:
print(max(a))
exit()
while low+1 < high:
tmp = 0
mid = (low + high) //2
for i in range(n):
tmp += ((a[i]+mid-1) // mid)-1
if tmp <= k:
high = mid
else:
low = mid
print(high)
|
from sys import stdin
import numpy as np
n, k = map(int, stdin.buffer.readline().split())
a = np.fromstring(stdin.buffer.read(), dtype=np.int, sep=' ')
ng = 0
ok = 10 ** 9 + 1
while ok - ng > 1:
mid = (ok + ng) >> 1
if np.sum(np.ceil(a / mid) - 1) <= k:
ok = mid
else:
ng = mid
print(ok)
| 1 | 6,437,050,096,968 | null | 99 | 99 |
print(int((int(input())+1)/2-1))
|
#import numpy as np
#import math
#from decimal import *
#from numba import njit
#@njit
def main():
S,W = map(int, input().split())
if S <= W:
print('unsafe')
else:
print('safe')
main()
| 0 | null | 91,291,607,765,372 | 283 | 163 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = input()
if a.upper() == a:
print('A')
else:
print('a')
|
x = int(input())
if x == 0:
x = 1
else:
x = 0
print(x)
| 0 | null | 7,103,041,179,872 | 119 | 76 |
a = input().split()
b = []
for i in a:
if i.isdigit():
b.append(i)
else:
c = b.pop()
d = b.pop()
ans = eval(str(d)+i+str(c))
b.append(ans)
print(b[0])
|
n = int(input())
a = list(map(int, input().split()))
sub_list = [0] * n
for i in (a):
sub_list[i - 1] += 1
for i in range(n):
print(sub_list[i], sep = ',')
| 0 | null | 16,363,151,238,490 | 18 | 169 |
S = input()
def kaibun(S):
for i in range(len(S) // 2):
if S[i] != S[len(S) - i - 1]:
return False
return True
if kaibun(S) and kaibun(S[:(len(S) - 1)//2]) and kaibun(S[(len(S) + 3) // 2-1:]):
print('Yes')
else:
print('No')
|
S = input()
array = list(S)
N = len(array)
a = (N-2)//2
b = (N+2)//2
if array[0:a+1] == array[b:N]:
print('Yes')
else:
print('No')
| 1 | 46,179,422,833,870 | null | 190 | 190 |
S=input()
t=len(S)
print("YNeos"[sum(1for i in range(t) if S[i]!=S[~i] )!=0 or S[(t+2)//2:]!=S[:(t-1)//2]::2])
|
s = list(input())
n = len(s)
if (
s[: (n - 1) // 2] == s[: (n - 1) // 2][::-1]
and s[(n + 1) // 2 :] == s[(n + 1) // 2 :][::-1]
and s == s[::-1]
):
print("Yes")
else:
print("No")
| 1 | 46,459,295,402,748 | null | 190 | 190 |
H=int(input())
W=int(input())
N=int(input())
cnt=0
black=0
if H>=W:
for i in range(W):
black+=H
cnt+=1
if black>=N:
break
elif H<W:
for i in range(H):
black+=W
cnt+=1
if black>=N:
break
print(cnt)
|
H,W,N=[int(input()) for i in range(3)]
print(min((N+H-1)//H,(N+W-1)//W))
| 1 | 88,524,705,456,068 | null | 236 | 236 |
s=list(input())
t=list(input())
count = 0
for i,w in enumerate(s):
if w != t[i]:
count += 1
print(count)
|
s = input()
t = input()
cnt = 0
word = list(s)
answer = list(t)
for i in range(len(s)):
if word[i] != answer[i]:
cnt+=1
print(cnt)
| 1 | 10,509,945,812,762 | null | 116 | 116 |
n = int(input())
a_list = [int(i) for i in input().split()]
a_dict = {}
for a in a_list:
if a in a_dict:
a_dict[a] += 1
else:
a_dict[a] = 1
q = int(input())
si = 0
for a in a_dict:
si += a * a_dict[a]
for _ in range(q):
bi, ci = [int(i) for i in input().split()]
if not bi in a_dict:
print(si)
continue
if not ci in a_dict:
a_dict[ci] = 0
a_dict[ci] += a_dict[bi]
si += (ci - bi) * a_dict[bi]
a_dict[bi] = 0
print(si)
|
def check_weather(weathers: str) -> int:
count = weathers.count('R')
return 1 if weathers[1] == 'S' and count == 2 else count
if __name__=='__main__':
print(check_weather(input()))
| 0 | null | 8,455,810,215,272 | 122 | 90 |
H, W, K = map(int, input().split())
A = [[0] * W for _ in range(H)]
for i in range(K):
y, x, v = map(int, input().split())
A[y - 1][x - 1] = v
dp = [[0] * 4 for i in range(W)]
pre = []
dp[0][1] = A[0][0]
for i in range(H):
for j in range(W):
if i:
dp[j][0] = max(dp[j][0], max(pre[j]))
dp[j][1] = max(dp[j][1], max(pre[j]) + A[i][j])
for k in range(4):
if j:
if 0 < k:
dp[j][k] = max(dp[j][k], dp[j - 1][k - 1] + A[i][j])
dp[j][k] = max(dp[j][k], dp[j - 1][k])
pre = dp
ans = 0
for j in range(W):
ans = max(ans, max(dp[j]))
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,574,362,641,572 | null | 94 | 94 |
S = input()
sum = 0
for i in range(3):
if S[i]=="R":
sum += 1
if sum == 2 and S[1] == "S":
sum = 1
print(sum)
|
#!/usr/bin/env python3
import sys
from math import gcd
from collections import defaultdict
sys.setrecursionlimit(10**8)
MOD = 1000000007 # type: int
def solve(N: int, A: "List[int]", B: "List[int]"):
def quadrant(a, b):
if a > 0 and b >= 0:
return 0
elif a <= 0 and b > 0:
return 1
elif a < 0 and b <= 0:
return 2
elif a >= 0 and b < 0:
return 3
else:
return None
def norm(a, b):
g = gcd(a, b)
a //= g
b //= g
while quadrant(a, b) != 0:
a, b = -b, a
return a, b
d = defaultdict(lambda: [0, 0, 0, 0])
kodoku = 0
for i, (a, b) in enumerate(zip(A, B)):
if (a, b) == (0, 0):
kodoku += 1
else:
d[norm(a, b)][quadrant(a, b)] += 1
ans = 1
for v in d.values():
buf = pow(2, v[0]+v[2], MOD)
buf += pow(2, v[1]+v[3], MOD)
buf = (buf-1) % MOD
ans *= buf
ans %= MOD
print((ans-1+kodoku) % MOD)
return
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
A = [int()] * (N) # type: "List[int]"
B = [int()] * (N) # type: "List[int]"
for i in range(N):
A[i] = int(next(tokens))
B[i] = int(next(tokens))
solve(N, A, B)
if __name__ == '__main__':
main()
| 0 | null | 12,860,361,945,700 | 90 | 146 |
import sys
import itertools
# import numpy as np
import time
import math
sys.setrecursionlimit(10 ** 7)
from collections import defaultdict
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(input())
adj = [[] for _ in range(N)]
degrees = [0 for _ in range(N)]
edges = {}
for i in range(N - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
adj[a].append(b)
adj[b].append(a)
degrees[a] += 1
degrees[b] += 1
edges[(a, b)] = i
max_degree = max(degrees)
print(max_degree)
edge_colors = [-1 for _ in range(N - 1)]
visited = [False for _ in range(N)]
def dfs(v, color):
global max_degree
if visited[v]:
return
visited[v] = True
next_color = color + 1
next_color %= max_degree
for u in adj[v]:
if visited[u]:
continue
if u < v:
edge_colors[edges[(u, v)]] = next_color
else:
edge_colors[edges[(v, u)]] = next_color
dfs(u, next_color)
next_color += 1
# if color == next_color:
next_color %= max_degree
dfs(0, -1)
for i in range(N - 1):
print(edge_colors[i] + 1)
|
from collections import Counter
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)
N = int(input())
edge = [[] for _ in range(N + 1)]
for i in range(N - 1):
x, y = map(int, input().split())
edge[x].append((y, i))
edge[y].append((x, i))
color = [-1] * (N - 1)
def dfs(s, p=-1, pc=-1):
c = 0
for t, x in edge[s]:
if color[x] != -1:
continue
if t == p:
continue
c += 1
if c == pc:
c += 1
color[x] = c
dfs(t, s, c)
dfs(1)
print(len(Counter(color)))
print(*color, sep="\n")
| 1 | 135,910,031,506,770 | null | 272 | 272 |
n,k,s=list(map(int,input().split()))
if s>n:
ans=["1" for _ in range(n)]
else:
ans=[str(s+1) for _ in range(n)]
for i in range(k):
ans[i]=str(s)
print(" ".join(ans))
|
N, K, S = map(int, input().split())
print(" ".join([str(S)] * K + [str(S+1)] * (N-K)) if S<10**9 else " ".join([str(S)] * K + ['1'] * (N-K)))
| 1 | 91,538,784,332,082 | null | 238 | 238 |
N, *A = map(int, open(0).read().split())
A = sorted(enumerate(A), reverse=True, key=lambda x: x[1])
dp = [[0] * (N + 1) for _ in range(N + 1)]
for i, (p, a) in enumerate(A):
for j in range(i + 1):
dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + a * (p - j))
dp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + a * (N - (i - j) - 1 - p))
print(max(dp[N]))
|
while True:
n, x = map(int, input().split())
if n == x == 0:
break
cnt = 0
for i in range(1, min(n - 1, int(x / 3))):
for j in range(i + 1, n):
for k in range(j + 1, n + 1):
if (i + j + k) == x:
cnt += 1
print(cnt)
| 0 | null | 17,417,762,273,216 | 171 | 58 |
def resolve():
word=input()
print(chr(ord(word)+1))
resolve()
|
c = input()
ls = [chr(ord('a') + i) for i in range(26)]
for i in range(len(ls)):
if ls[i] == c:
print(ls[i + 1])
break
| 1 | 92,536,565,826,200 | null | 239 | 239 |
a = input()
N = len(a)
c = []
temp = int(1)
ans = int(0)
for i in range(N):
if i != N-1:
if a[i] == a[i+1]:
temp += 1
else:
c.append(temp)
temp = 1
else:
if a[i-1] == a[i]:
c.append(temp)
else:
c.append(1)
clen = len(c)
if a[0] == "<" and clen % 2 == 1:
c.append(0)
elif a[0] == ">" and clen % 2 == 0:
c.append(0)
if a[0] == "<":
for i in range(0,clen,2):
maxi = max([c[i],c[i+1]])
mini = min([c[i],c[i+1]])
ans += maxi*(maxi+1)/2
ans += mini*(mini-1)/2
else:
ans += c[0]*(c[0]+1)/2
for i in range(1,clen,2):
maxi = max([c[i],c[i+1]])
mini = min([c[i],c[i+1]])
ans += maxi*(maxi+1)/2
ans += mini*(mini-1)/2
print(int(ans))
|
S = input()
ans = ''.join(['x' for ch in S])
print(ans)
| 0 | null | 115,150,134,264,780 | 285 | 221 |
ans = 0
for i in xrange(input()):
n = int(raw_input())
if n <= 1:
continue
j = 2
while j*j <= n:
if n%j == 0:
break
j += 1
else:
ans += 1
print ans
|
c = 0
while True:
try:
n = int(input())
except EOFError:
break
c += 1
for i in range(2, int(n ** 0.5 + 1)):
if n % i == 0:
c -= 1
break
print(c)
| 1 | 10,418,543,020 | null | 12 | 12 |
mod = 1000000007
n,k = map(int, input().split())
d = [0]*(k+1)
for i in range(1,k+1):
d[i] = pow(k//i,n,mod)
for i in range(k,0,-1):
for j in range(2*i,k+1,i):
d[i] -= d[j]
d[i] %= mod
ans = 0
for i in range(1,k+1):
ans += d[i]*i
ans %= mod
print(ans)
|
N, K = map(int, input().split())
mod = 10**9 + 7
fact_count = [0 for _ in range(K+1)]
for k in range(1, K+1):
fact_count[k] = K//k
ans = 0
count = [0 for _ in range(K+1)]
for k in range(K, 0, -1):
c = pow(fact_count[k], N, mod)
j = 2*k
l = 2
while(j<=K):
c -= count[j]
l += 1
j = k*l
count[k] = c
c = c*k%mod
ans += c
ans %= mod
print(ans)
| 1 | 36,565,825,009,600 | null | 176 | 176 |
S = input()
ans = [0]*(len(S)+1)
for i in range(len(S)):
if S[i] == "<":
ans[i+1] = max(ans[i+1], ans[i]+1)
for i in range(len(S)):
i = len(S)-1 - i
if S[i] == ">":
ans[i] = max(ans[i],ans[i+1]+1)
print(sum(ans))
|
n = int(input())
i = 1
while i * 1000 < n:
i += 1
print(i*1000 - n)
| 0 | null | 82,652,032,340,320 | 285 | 108 |
try:
while True:
N=list(str(input()))
M=int(input())
for i in range(M):
H=int(input())
for j in range(H):
A=N[0]
N.remove(A)
N.append(A)
j+=1
for k in range(len(N)):
print(N[k],end='')
print()
except EOFError:
pass
|
# AOJ ITP1_9_B
def main():
while True:
string = input()
if string == "-": break
n = int(input()) # シャッフル回数
for i in range(n):
h = int(input())
front = string[0 : h] # 0番からh-1番まで
back = string[h : len(string)] # h番からlen-1番まで
string = back + front
print(string)
if __name__ == "__main__":
main()
| 1 | 1,922,755,895,698 | null | 66 | 66 |
k,n = map(int,input().split())
a = list(map(int,input().split()))
for i in range(n-1):
a.append(k+a[i])
ans = a[n-1]-a[0]
for i in range(n,n*2-1):
ans = min(ans,a[i]-a[i-n+1])
print(ans)
|
k,n = map(int,input().split())
lst = list(map(int,input().split()))
m = 0
for i in range(n-1):
m = max(lst[i+1]-lst[i],m)
m = max(m,k+lst[0]-lst[n-1])
print(k-m)
| 1 | 43,652,835,094,242 | null | 186 | 186 |
# フェルマーの小定理
K = int(input())
S = input()
m = 1000000007
result = 0
a = 1
b = 1
for i in range(K + 1):
# result += pow(26, K - i, m) * mcomb(len(S) - 1 + i, i) * pow(25, i, m)
result += pow(26, K - i, m) * (a * pow(b, m - 2, m)) * pow(25, i, m)
result %= m
a *= len(S) - 1 + (i + 1)
a %= m
b *= i + 1
b %= m
print(result)
|
N,K = map(int,input().split())
p=list(map(int,input().split()))
p.sort()
sum = 0
for i in range(K):
sum += p[i]
print(sum)
| 0 | null | 12,191,930,735,558 | 124 | 120 |
import sys
import math
from collections import deque
sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()
def main():
N, X, Y = NMI()
counts = [0] * N
for i in range(1, N):
for j in range(i+1, N+1):
dist = min(abs(j-i), abs(i-X) + 1 + abs(Y-j))
counts[dist] += 1
for d in counts[1:]:
print(d)
if __name__ == "__main__":
main()
|
from collections import defaultdict
MOD = (10 ** 9) + 7
assert MOD == 1000000007
def gcd(a, b):
if a % b == 0:
return b
return gcd(b, a % b)
n = int(raw_input())
ns = []
d = defaultdict(int)
zero = 0
for i in xrange(n):
a, b = map(int, raw_input().split())
ns.append((a, b))
if a and b:
s = 1 if a * b >= 0 else -1
g = gcd(abs(a), abs(b))
m1 = (s * abs(a) / g, abs(b) / g)
m2 = (-s * abs(b) / g, abs(a) / g)
elif a == 0 and b == 0:
zero += 1
continue
elif a == 0:
m1 = (1, 0)
m2 = (0, 1)
elif b == 0:
m1 = (0, 1)
m2 = (1, 0)
d[m1] += 1
d[m2] += 0
'''
res = 0
for i in xrange(1 << n):
fs = []
flag = True
for j in xrange(n):
if i & (1 << j):
fs.append(ns[j])
for i, f1 in enumerate(fs):
for f2 in fs[i + 1:]:
(a1, b1) = f1
(a2, b2) = f2
if a1 * a2 + b1 * b2 == 0:
flag = False
break
if not flag:
break
if flag:
res += 1
print res - 1
'''
pre = 1
for k in d.keys():
if k[0] <= 0:
assert (k[1], -k[0]) in d
continue
else:
k1 = k
k2 = (-k[1], k[0])
tot = pow(2, d[k1], MOD) + pow(2, d[k2], MOD) - 1
pre = pre * tot % MOD
print (pre - 1 + zero + MOD) % MOD
| 0 | null | 32,649,717,981,450 | 187 | 146 |
a, b, c, d = map(int, input().split())
print(max(a * c, a * d, b * c, b * d))
|
#!/usr/bin/env python3
# encoding:utf-8
import copy
import random
import bisect #bisect_left これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections
from decimal import Decimal # 10進数で考慮できる
mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000
d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))
a, b, c, d = LI()
ans = max(a*c, a*d, b*c, b*d)
print(ans)
| 1 | 3,046,911,534,540 | null | 77 | 77 |
import sys
#da[i][j]:(0,0)~(i,j)の長方形の和
def da_generate(h, w, a):
da = [[0] * w for j in range(h)]
da[0][0] = a[0][0]
for i in range(1, w):
da[0][i] = da[0][i - 1] + a[0][i]
for i in range(1, h):
cnt_w = 0
for j in range(w):
cnt_w += a[i][j]
da[i][j] = da[i - 1][j] + cnt_w
return da
#da_calc(p,q,x,y):(p,q)~(x,y)の長方形の和
def da_calc(p, q, x, y):
if p > x or q > y:
return 0
if p == 0 and q == 0:
return da[x][y]
if p == 0:
return da[x][y] - da[x][q - 1]
if q == 0:
return da[x][y] - da[p - 1][y]
return da[x][y] - da[p - 1][y] - da[x][q - 1] + da[p - 1][q - 1]
H, W, K = map(int, sys.stdin.readline().rstrip().split())
grid = [list(map(int, list(sys.stdin.readline().rstrip()))) for _ in range(H)]
da = da_generate(H, W, grid)
ans = 10 ** 18
for i in range(2**(H - 1)):
res = 0
s = [k for k, j in enumerate(range(H), 1) if i >> j & 1] # s行は含まない
res += len(s)
s.append(H)
y = 0
for w in range(1, W + 1): # w行は含まない
x = 0
flag = False
for s_i in s:
if da_calc(x, y, s_i - 1, w - 1) > K:
if y + 1 < w:
res += 1
y = w - 1
else:
flag = True
break
x = s_i
else:
pass
if flag:
break
else:
ans = min(ans, res)
print(ans)
|
import sys
mod=10**9+7 ; inf=float("inf")
from math import sqrt, ceil
from collections import deque, Counter, defaultdict #すべてのkeyが用意されてる defaultdict(int)で初期化
# input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from decimal import ROUND_HALF_UP,Decimal #変換後の末尾桁を0や0.01で指定
#Decimal((str(0.5)).quantize(Decimal('0'), rounding=ROUND_HALF_UP))
from functools import lru_cache
#メモ化再帰defの冒頭に毎回 @lru_cache(maxsize=10**10)
#引数にlistはだめ
#######ここまでテンプレ#######
#ソート、"a"+"b"、再帰ならPython3の方がいい
#######ここから天ぷら########
h,w,k=map(int,input().split())
# R=[]
A=[[0]*w for i in range(h)]
dp=[[[0 for j in range(w)] for i in range(h)] for i in range(4)]
for s in sys.stdin.readlines():
x,y,v=map(int,s.split())
x-=1;y-=1
A[x][y]=v
# dp[x][y][1]=v
# dp[x][y][2]=v
# dp[x][y][3]=v;
dp[1][0][0]=A[0][0]
for i in range(h):
for j in range(w):
for k in range(4):
here=dp[k][i][j]
if i<h-1:
dp[0][i+1][j] = max(here,dp[0][i+1][j])
dp[1][i+1][j] = max(here+A[i+1][j], dp[1][i+1][j])
if j<w-1:
dp[k][i][j+1] = max(dp[k][i][j+1], here)
if k<=2:
dp[k+1][i][j+1]= max(dp[k+1][i][j+1],here+ A[i][j+1])
ans=0
for i in range(4):
ans=max(ans, dp[i][-1][-1])
print(ans)
| 0 | null | 26,922,062,190,140 | 193 | 94 |
t = raw_input()
s = t.split()
if s[0] == s[1]:
print "a == b"
else:
if int(s[0]) > int(s[1]):
print "a > b"
else:
print "a < b"
|
line = list(map(int,input().split()))
if line[0]==line[1]: op = '=='
if line[0]>line[1]: op = '>'
if line[0]<line[1]: op = '<'
print('a {op} b'.format(op=op))
| 1 | 350,010,398,628 | null | 38 | 38 |
x = int(input());
h = x // 3600;
m = x % 3600 // 60;
s = x % 60;
print(h,m,s,sep=':');
|
S,T = open(0).read().split()
ls = len(S)
lt = len(T)
ans = float('inf')
for i in range(ls-lt+1):
temp = S[i:i+lt]
t2 = 0
for j in range(lt):
if temp[j] != T[j]:
t2 += 1
ans = min(ans,t2)
print(ans)
| 0 | null | 1,975,420,882,648 | 37 | 82 |
a, b, c = list(map(int, input().split()))
if a < b and b < c:
print("Yes")
else:
print("No")
|
import sys
num = map(int, raw_input().split())
if num[0] < num[1]:
if num[1] < num[2]:
print "Yes"
else:
print "No"
else:
print "No"
| 1 | 382,362,196,922 | null | 39 | 39 |
import heapq
X, Y, A, B, C = map(int, input().split())
apples = []
for x in input().split():
apples.append((int(x), 'r'))
for x in input().split():
apples.append((int(x), 'g'))
for x in input().split():
apples.append((int(x), 'n'))
apples.sort()
apples.reverse()
r_count = 0
g_count = 0
n_count = 0
yummy = 0
for _ in range(A+B+C):
apple = apples[_]
if apple[1] == 'g' and not g_count == Y:
g_count += 1
yummy += apple[0]
elif apple[1] == 'r' and not r_count == X:
r_count += 1
yummy += apple[0]
elif apple[1] == 'n':
n_count += 1
yummy += apple[0]
if g_count + r_count + n_count == X+Y:
break
print(yummy)
|
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 | 36,495,166,932,172 | 188 | 162 |
from collections import Counter
from sys import exit
N = int(input())
A = list(map(int,input().split()))
cnt = Counter(A)
for i in cnt.values():
if i != 1:
print("NO")
exit(0)
print("YES")
|
N = int(input())
A = [int(i) for i in input().split()]
B = set(A)
b = len(B)
if N == b:
print('YES')
else:
print('NO')
| 1 | 73,855,406,830,592 | null | 222 | 222 |
a = input()
if a == '1':
print('0')
else:
print('1')
|
# -*- coding:utf-8 -*-
stack = list()
def deal_expression(x):
if x.isdigit():
stack.append(int(x))
else:
a = stack.pop()
b = stack.pop()
if x == '+':
stack.append(b + a)
elif x == '-':
stack.append(b - a)
elif x == '*':
stack.append(b * a)
elif x == '/':
stack.append(b / a)
for x in input().split():
deal_expression(x)
print(stack[0])
| 0 | null | 1,459,988,772,668 | 76 | 18 |
N=int(input())
A=list(map(int, input().split()))
A.sort()
if N==1:
print('YES')
exit()
for i in range(N-1):
if A[i]==A[i+1]:
print('NO')
exit()
else:
print('YES')
|
N = int(input())
A = [int(x) for x in input().split()]
cnt = dict()
for i in range(N):
cnt[A[i]] = cnt.get(A[i], 0) + 1
if max(cnt.values()) > 1:
print('NO')
else:
print('YES')
| 1 | 73,672,624,419,930 | null | 222 | 222 |
A = int(input())
B = int(input())
if A == 1 and B == 2:
print(3)
elif A == 2 and B == 1:
print(3)
elif A == 1 and B == 3:
print(2)
elif A == 3 and B == 1:
print(2)
elif A == 2 and A == 3:
print(1)
else:
print(1)
|
class Dice:
def __init__( self, nums ):
self.face = nums
def rolltoTop( self, dicenum ):
num = 0
for i,val in enumerate( self.face ):
if dicenum == val:
num = i
break
if num == 1:
self.roll( "N" )
elif num == 2:
self.roll( "W" )
elif num == 3:
self.roll( "E" )
elif num == 4:
self.roll( "S" )
elif num == 5:
self.roll( "NN" )
def roll( self, actions ):
for act in actions:
t = 0
if act == "E":
t = self.face[0]
self.face[0] = self.face[3]
self.face[3] = self.face[5]
self.face[5] = self.face[2]
self.face[2] = t
elif act == "N":
t = self.face[0]
self.face[0] = self.face[1]
self.face[1] = self.face[5]
self.face[5] = self.face[4]
self.face[4] = t
elif act == "S":
t = self.face[ 0]
self.face[0] = self.face[4]
self.face[4] = self.face[5]
self.face[5] = self.face[1]
self.face[1] = t
elif act == "W":
t = self.face[0]
self.face[0] = self.face[2]
self.face[2] = self.face[5]
self.face[5] = self.face[3]
self.face[3] = t
elif act == "M":
t = self.face[1]
self.face[1] = self.face[2]
self.face[2] = self.face[4]
self.face[4] = self.face[3]
self.face[3] = t
diceface = [ int( val ) for val in raw_input( ).split( " " ) ]
dice = Dice( diceface )
q = int( raw_input( ) )
for i in range( q ):
topnum, frontnum = [ int( val ) for val in raw_input( ).split( " " ) ]
dice.rolltoTop( topnum )
while dice.face[1] != frontnum:
dice.roll( "M" )
print( dice.face[2] )
| 0 | null | 55,519,833,879,228 | 254 | 34 |
N=int(input())
A=list(map(int,input().split()))
A.sort()
sum=1
for i in range(N):
sum=sum*A[i]
if sum>10**18:
sum=-1
break
print(sum)
|
# 解説AC
mod = 10 ** 9 + 7
n, k = map(int, input().split())
dp = [-1] * (k + 1)
ans = 0
for i in range(k, 0, -1):
dp[i] = pow(k // i, n, mod)
t = 0
t += 2 * i
while t <= k:
dp[i] -= dp[t]
dp[i] %= mod
t += i
ans += i * dp[i]
ans %= mod
print(ans)
| 0 | null | 26,613,709,273,230 | 134 | 176 |
n = int(input())
a = [int(i) for i in input().split()]
def trace(a):
a = map(str, a)
print(' '.join(a))
def insertion(a):
for i in range(1, n):
v = a[i]
j = i -1
while j >= 0 and a[j] > v:
a[j+1] = a[j]
j -= 1
a[j+1] = v
trace(a)
trace(a)
insertion(a)
|
def insertionSort(a):
for i,v in enumerate(a):
j=i-1
while j>=0 and a[j]>v:
a[j+1]=a[j]
j-=1
a[j+1]=v
print(*a)
n = int(input())
a = list(map(int,input().split()))
insertionSort(a)
| 1 | 6,015,676,544 | null | 10 | 10 |
MOD = 1e9 + 7
n = int(input())
ans = [[0, 1, 1, 8]]
for i in range(n-1):
a, b, c, d = ans.pop()
a = (a * 10 + b + c) % MOD
b = (b * 9 + d) % MOD
c = (c * 9 + d) % MOD
d = (d * 8) % MOD
ans.append([a, b, c, d])
a, b, c, d = ans.pop()
print(int(a))
|
a,b,c,d = map(int, input().split())
if a*b <= 0 and c*d <= 0:
print(max([a*c, b*d]))
elif a*b <= 0 and c >= 0:
print(b*d)
elif a*b <=0 and d <=0:
print(a*c)
elif a>=0 and c*d<=0:
print(b*d)
elif a>=0 and c>=0:
print(b*d)
elif a>=0 and d<=0:
print(a*d)
elif b<=0 and c*d<=0:
print(a*c)
elif b<=0 and c>=0:
print(b*c)
elif b<=0 and d<=0:
print(a*c)
| 0 | null | 3,067,496,155,032 | 78 | 77 |
from collections import deque
N,K = map(int,input().split())
H = list(map(int,input().split()))
H.sort(reverse=True)
deqH = deque(H)
if N <= K:
print(0)
else:
for i in range(K):
deqH.popleft()
#H.remove(max(H))
#print(H)
print(sum(deqH))
|
N=int(input())
A=list(map(int, input().split()))
if len(set(A))==N:
print("YES")
else:
print("NO")
| 0 | null | 76,690,925,610,108 | 227 | 222 |
N = map(int,input().split())
if (sum(N) % 9 == 0 ):
print('Yes')
else:
print('No')
|
import math
N = int(input())
X = N / 1.08
floor = math.ceil(N/1.08)
ceil = math.ceil((N+1)/1.08)
for i in range(floor,ceil):
print(i)
break
else:
print(":(")
| 0 | null | 65,027,484,158,560 | 87 | 265 |
import math
a, b, x = map(int, input().split())
if x < a ** 2 * b / 2:
theta = math.atan2(b, 2 * x / b / a)
else:
theta = math.atan2(2 * b - 2 * x / a / a, a)
deg = math.degrees(theta)
print(deg)
|
N=int(input())
A=[]
B=[]
for i in range(N):
a,b=map(int,input().split())
A.append(a)
B.append(b)
A.sort()
B.sort()
if N%2!=0:
n=(N+1)//2
ans=B[n-1]-A[n-1]+1
else:
n=N//2
ans1=(A[n-1]+A[n])/2
ans2=(B[n-1]+B[n])/2
ans=(ans2-ans1)*2+1
print(int(ans))
| 0 | null | 90,508,343,091,488 | 289 | 137 |
n,k = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
g = [[0]*(n) for _ in range(n)]
A = [n]*n
# for i in range(n):
# tmp = 0
# idx = i
# cnt = 0
# set_ =set()
# while cnt<n:
# if C[idx] not in set_:
# tmp += C[idx]
# set_.add(C[idx])
# g[i][cnt] = tmp
# idx = P[idx]-1
# cnt += 1
# else:
# p = len(set_)
# A[i] = p
# break
ans = -float('inf')
for i in range(n):
S = []
idx = P[i]-1
S.append(C[idx])
while idx != i:
idx = P[idx]-1
S.append(S[-1] +C[idx])
v,w = k//len(S),k%len(S)
if k<=len(S):
val = max(S[:k])
elif S[-1]<=0:
val = max(S)
else:
val1 = S[-1] *(v-1)
val1 += max(S)
val2 = S[-1]*v
if w!=0:
val2 += max(0,max(S[:w]))
val = max(val1,val2)
ans = max(ans,val)
# for i in range(n):
# v,w = k//A[i],k%A[i]
# if A[i]<k:
# if g[i][A[i]-1]<=0:
# val = max(g[i][:A[i]])
# else:
# val1 = (v-1)*g[i][A[i]-1]
# val1 += max(g[i][:A[i]])
# val2 = v*g[i][A[i]-1]
# if w!=0:
# val2 += max(0,max(g[i][:w]))
# val = max(val1,val2)
# else:
# val = max(g[i][:k])
# ans = max(ans,val)
print(ans)
|
def solve():
ans = -float('inf')
N, K = map(int, input().split())
P = list(map(lambda x:int(x)-1, input().split()))
C = list(map(int, input().split()))
for i in range(N):
score = 0
now = i
visited = [-1]*N
scores = [0]*N
visited[now] = 0
for j in range(1,K+1):
now = P[now]
score += C[now]
ans = max(ans, score)
if visited[now]>=0:
cyc = j - visited[now]
up = score - scores[now]
break
scores[now] = score
visited[now] = j
else:
continue
if up<=0:
continue
cnt = j+1
if K-cyc>=j:
score += (K-cyc-j)//cyc * up
ans = max(ans, score)
cnt += (K-cyc-j)//cyc*cyc
for j in range(cnt,K+1):
now = P[now]
score += C[now]
ans = max(ans, score)
return ans
print(solve())
| 1 | 5,394,019,162,672 | null | 93 | 93 |
import sys
import fractions
from functools import reduce
readline = sys.stdin.buffer.readline
def main():
gcd = fractions.gcd
def lcm(a, b):
return a * b // gcd(a, b)
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 = reduce(lcm, (a // 2 for a in A))
print((M // semi_lcm + 1) // 2)
return
if __name__ == '__main__':
main()
|
import math
a, b, x = map(int, input().split())
full = a * a * b
if x > full / 2:
x = full - x
tan_x = 2.0 * x / (a*a) / a
print(math.atan(tan_x) / math.pi * 180.0)
else:
tan_x = 2.0 * x / (a*b) / b
print(90-math.atan(tan_x) / math.pi * 180.0)
| 0 | null | 132,634,717,038,940 | 247 | 289 |
from itertools import combinations
while True:
n,m=map(int,input().split())
if n==m==0: break
print(sum(1 for p in combinations(range(1,n+1),3) if sum(p)==m))
|
results = []
while True:
n,x = map(int ,raw_input().split())
if n is x is 0:
break
s = 0
for i in xrange(1,n+1):
for j in xrange(1,n+1):
for k in xrange(1,n+1):
if i+j+k == x:
if i != j and j != k and k != i :
s+=1
results.append(s/6)
for i in results:
print i
| 1 | 1,298,386,752,860 | null | 58 | 58 |
l = input().split()
'''
a = int(l[0])
b = int(l[1])
'''
#存在していないインデックスは出せない
l = list(map(int,l))
a = l[0]*l[1]
b = 2*(l[0]+l[1])
print(a,b)
|
a = raw_input()
for i, b in enumerate(a.split()):
if i==0:
x=int(b)
else:
y=int(b)
print x*y,x*2+y*2
| 1 | 313,371,649,188 | null | 36 | 36 |
def resolve():
N = int(input())
A = list(map(int, input().split()))
broken = 0
cnt = 1
for i in range(N):
if cnt == A[i]:
cnt += 1
else:
broken += 1
print(broken if broken != N else -1)
if '__main__' == __name__:
resolve()
|
n = int(input())
a = list(map(int, input().split()))
ans = 0
cnt = 0
for i in a:
if i == cnt+1:
cnt += 1
else:
ans += 1
print(ans if cnt else -1)
| 1 | 114,378,158,398,020 | null | 257 | 257 |
import copy
def inputInline():
N = int(input())
cards = input().split(" ")
return cards
def selectionSort(list):
cards=copy.deepcopy(list)
n = len(cards)
count = 0
for i in range(n):
min_j = i
for j in range(i + 1, n):
if int(cards[j][1]) < int(cards[min_j][1]):
min_j = j
if min_j != i:
temp = cards[i]
cards[i] = cards[min_j]
cards[min_j] = temp
count += 1
return (" ".join(cards), count)
def bubbleSort(list):
cards=copy.deepcopy(list)
N = len(cards)
count = 0
flag = True
while flag:
flag = False
for i in range(N - 1):
if int(cards[i][1]) > int(cards[i + 1][1]):
temp = cards[i]
cards[i] = cards[i + 1]
cards[i + 1] = temp
flag = True
count += 1
return (" ".join(cards), count)
cards=inputInline()
sortedbubble=bubbleSort(cards)[0]
sortedselection=selectionSort(cards)[0]
print(sortedbubble)
print("Stable")
print(sortedselection)
if sortedbubble==sortedselection:
print("Stable")
else:
print("Not stable")
|
N,A,B = map(int,input().split())
a = N//(A+B)
b = N%(A+B)
if b>A:
print(a*A+A)
else:
print(a*A+b)
| 0 | null | 27,652,035,128,658 | 16 | 202 |
S = list(input().split())[::-1]
res = "".join(S)
print(res)
|
s, t = input().split()
print(''.join(t+s))
| 1 | 103,311,063,551,780 | null | 248 | 248 |
import sys
input = lambda: sys.stdin.readline().rstrip()
s = input()
n = len(s)
if n == s.count("hi")*2:
print("Yes")
else:
print("No")
|
a, b, c = map(int, input().split())
if(a < b & b < c) :
print("Yes")
else :
print("No")
| 0 | null | 26,625,898,603,748 | 199 | 39 |
# -*- coding: utf-8 -*-
"""
Created on Wed May 2 21:28:06 2018
ALDS1_5a
@author: maezawa
"""
import itertools as itr
n = int(input())
a = list(map(int, input().split()))
q = int(input())
m = list(map(int, input().split()))
sum_array = []
for r in range(1,n+1):
for comb in itr.combinations(a, r):
sum_array.append(sum(comb))
for i in m:
yesorno = 'no'
for j in sum_array:
#print(i, j)
if i == j:
yesorno = 'yes'
break
print(yesorno)
|
N = int(input())
S = str(input())
import itertools
ans=0
for num in range(1000):
num=str(num).zfill(3)
a0=S.find(str(num[0]))
if a0>=0:
S1=S[(a0+1):]
a1=S1.find(str(num[1]))
if a1>=0:
S2=S1[(a1+1):]
if str(num[2]) in S2:
ans+=1
print(ans)
# 2darray [[0] * 4 for i in range(3)]
| 0 | null | 64,248,935,914,670 | 25 | 267 |
s = input()
if s[0] == '>':
a = [0]
else:
a = []
flg = 1
for i in range(1,len(s)):
if s[i] != s[i-1]:
a.append(flg)
flg = 1
else:
flg += 1
a.append(flg)
if s[-1] == '<':
a.append(0)
ans = 0
for i in range(len(a)//2):
if a[2*i] > a[2*i+1]:
a[2*i+1] -= 1
ans += a[2*i]*(a[2*i]+1)//2 + a[2*i+1]*(a[2*i+1]+1)//2
else:
a[2*i] -= 1
ans += a[2*i]*(a[2*i]+1)//2 + a[2*i+1]*(a[2*i+1]+1)//2
print(ans)
|
a = list(map(int, input().split()))
if a[3] <= a[0]:
print(a[3])
elif a[3] <= a[0] + a[1]:
print(a[0])
else:
print(a[0] - (a[3] - a[0] -a[1]))
| 0 | null | 88,973,941,969,610 | 285 | 148 |
import math
h,w = map(int,input().split())
if h == 1 or w == 1:
print(1)
else:
print(math.ceil(h/2*w))
|
x, y = map(int, input().split())
if x == 1 or y == 1:
print(1)
elif (x * y) % 2 == 0:
print((x * y) // 2)
else:
print((x * y + 1) // 2)
| 1 | 50,993,327,203,870 | null | 196 | 196 |
a=input()
c=len(a)
b=a[:(c-1)//2]
d=a[(c+3)//2-1:]
if a==a[::-1] and b==b[::-1] and d==d[::-1]:
print("Yes")
else:
print("No")
|
# AtCoder
from collections import deque
S = input()
Q = int(input())
qs = [input().split() for i in range(Q)]
ans = deque(S)
flag = 0
count = 0
for q in qs:
if q[0] == '1':
if flag == 0:
flag = 1
else:
flag = 0
count += 1
else:
if flag == 0:
if q[1] == '1':
ans.appendleft(q[2])
else:
ans.append(q[2])
else:
if q[1] == '1':
ans.append(q[2])
else:
ans.appendleft(q[2])
if count % 2 == 1:
ans.reverse()
print(*ans, sep='')
| 0 | null | 51,721,216,876,770 | 190 | 204 |
a, v = map(int, input().split())
b, w = map(int, input().split())
t = int(input())
dist = abs(a - b)
vd = v - w
if vd > 0:
if 0 <= dist/vd/t <= 1:
print("YES")
else:
print("NO")
elif vd == 0 and dist == 0:
print("YES")
else:
print("NO")
|
A,V = map(int,input().split())
B,W = map(int,input().split())
T = int(input())
d = abs(A-B)
dv = V-W
if dv<=0:
print("NO")
else:
if T*dv>=d:
print("YES")
else:
print("NO")
| 1 | 15,141,506,621,180 | null | 131 | 131 |
for i in xrange(81):print "{}x{}={}".format(i/9+1,i%9+1,(i/9+1)*(i%9+1))
|
n = int(input())
str = input()
if (n%2 == 0) and (str[:(n//2)] == str[n//2:]):
print("Yes")
else:
print("No")
| 0 | null | 73,202,495,528,312 | 1 | 279 |
A,B,C,K = map(int,input().split())
ans = 0
if K > A:
ans += A
K -= A
if K > B:
ans += 0
K -= B
if K > 0:
ans -= K
else:
ans += 0
else:
ans = K
print(ans)
|
import sys
from collections import defaultdict
time = 1
def dfs(g, visited, start, ans):
global time
visited[start - 1] = True
ans[start - 1][0] = time
for e in g[start]:
if not visited[e - 1]:
time += 1
dfs(g, visited, e, ans)
time += 1
ans[start - 1][1] = time
def main():
input = sys.stdin.buffer.readline
n = int(input())
g = defaultdict(list)
for i in range(n):
line = list(map(int, input().split()))
if line[1] > 0:
g[line[0]] = line[2:]
visited = [False] * n
ans = [[1, 1] for _ in range(n)]
global time
while False in visited:
start = visited.index(False) + 1
dfs(g, visited, start, ans)
time += 1
for i in range(1, n + 1):
print(i, *ans[i - 1])
if __name__ == "__main__":
main()
| 0 | null | 10,942,604,886,038 | 148 | 8 |
N, K = map(int, input().split())
A = [0] + list(map(int, input().split()))
L = [-1] * (N+1)
L[1] = 0
idx = 1
for i in range(1, N+1):
idx = A[idx]
if L[idx] >= 0:
t = i - L[idx]
b = L[idx]
break
else:
L[idx] = i
if K <= b:
print(L.index(K))
else:
print(L.index((K-b)%t+b))
|
N,K=map(int, input().split())
a_ls=list(map(int, input().split()))
j=1
step=0
s=set([])
l=[]
loop_s=-1
loop_g=-1
while True:
s.add(j)
l+=[j]
j=a_ls[j-1] #update
if j in s:
loop_s=l.index(j)
loop_g=len(l)
break
#print(l)
#print(loop_s)
#print(loop_g)
if K<loop_s:
print(l[K])
elif (K+1-loop_s)%(loop_g-loop_s)!=0:
print(l[loop_s+(K+1-loop_s)%(loop_g-loop_s)-1])
else:
print(l[-1])
| 1 | 22,640,415,238,518 | null | 150 | 150 |
m1,d1 = map(int,input().split())
m2,d2 = map(int,input().split())
print(1 if m1!=m2 else 0)
|
m1, d1 = input().split()
m2, d2 = input().split()
print('1' if m1 != m2 else '0')
| 1 | 124,268,917,343,910 | null | 264 | 264 |
from collections import deque
N = int(input())
A = deque(map(int, input().split()))
mod = 10**9 + 7
M = len(bin(max(A))) - 2
ans = 0
bitlist = [1]
anslist = [0 for _ in range(M)]
for k in range(M):
bitlist.append(bitlist[-1]*2%mod)
counter = [0 for _ in range(M)]
for k in range(N):
a = A.pop()
c = 0
while a:
b = a & 1
if b == 0:
anslist[c] += counter[-c-1]
else:
anslist[c] += k - counter[-c-1]
counter[-c-1] += 1
c += 1
a >>= 1
while c < M:
anslist[c] += counter[-c-1]
c += 1
for k in range(M):
ans += anslist[k]*bitlist[k]%mod
ans %= mod
print(ans)
|
N = int(input())
A = list(map(int, input().split()))
A = sorted(A)
count = 0
max = A[-1]
if max == 0:
print(0)
exit()
import math
V = [0]*(math.floor(math.log(max, 2))+1)
for i in range (0, N):
B = A[i]
vount = 0
while B > 0:
if B%2 == 0:
B = B//2
vount+=1
else:
B = (B-1)//2
V[vount]+=1
vount+=1
for i in range (0, len(V)):
count+=((V[i]*(N-V[i]))*(2**i))
print(count%(10**9+7))
| 1 | 122,713,424,696,030 | null | 263 | 263 |
N,K=map(int,input().split())
MOD = 998244353
dp = [0]*(N+1)
LR = []
for _ in range(K):
l, r = map(int, input().split())
LR.append((l,r))
LR.sort()
dp[1] = 1
dp_sum = [0]*(N+1) # dp[i]の累積和
dp_sum[1] = 1
for i in range(2, N+1):
for l, r in LR:
if i - l >= 1:
dp[i] += dp_sum[i-l] - dp_sum[max(0, i-r-1)]
dp[i] %= MOD
dp[i] %= MOD
dp_sum[i] = dp_sum[i-1] + dp[i]
print(dp[N]%MOD)
|
n, s = map(int, input().split())
a = list(map(int, input().split()))
mod = 998244353
ans = 0
inv_2 = pow(2, mod-2, mod)
dp = [[0 for _ in range(s+1)] for _ in range(n+1)]
dp[0][0] = pow(2, n, mod)
for i in range(n):
for j in range(s+1):
dp[i+1][j] += dp[i][j]
dp[i+1][j] %= mod
if j + a[i] <= s:
dp[i+1][j+a[i]] += dp[i][j] * inv_2
dp[i+1][j+a[i]] %= mod
#print(dp)
print(dp[n][s])
| 0 | null | 10,153,574,082,652 | 74 | 138 |
def main():
h,w,k=map(int,input().split())
s=[list(input()) for _ in range(h)]
ans=[[0]*w for _ in range(h)]
for idx in range(h):
if '#' in s[idx]:
i=idx
break
start,j,cnt,first=i,0,1,True
while i<h:
if j==w:
if first:
ans[i]=ans[i-1]
i+=1
j=0
continue
first=True
i+=1
j=0
cnt+=1
continue
if s[i][j]=='#':
if first:
first=False
ans[i][j]=cnt
j+=1
continue
cnt+=1
ans[i][j]=cnt
else:
ans[i][j]=cnt
j+=1
for i in range(start):
ans[i]=ans[start]
for i in range(h):
print(*ans[i])
if __name__=='__main__':
main()
|
import collections
def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]
def main():
H, W, K = ZZ()
C = [input() for _ in range(H)]
atode = collections.deque()
last = -1
cakeId = 0
output = [[0] * W for _ in range(H)]
for i in range(H):
if not '#' in C[i]:
atode.append(i)
continue
ichigo = []
last = i
for j in range(W):
if C[i][j] == '#': ichigo.append(j)
itr = 0
for j in ichigo:
cakeId += 1
while itr <= j:
output[i][itr] = cakeId
itr += 1
while itr < W:
output[i][itr] = cakeId
itr += 1
while atode:
j = atode.popleft()
for k in range(W): output[j][k] = output[i][k]
while atode:
j = atode.popleft()
for k in range(W): output[j][k] = output[last][k]
for i in range(H): print(*output[i])
return
if __name__ == '__main__':
main()
| 1 | 143,739,332,175,712 | null | 277 | 277 |
n = int(input())
a = {}
for i in range(n):
x,m = input().split()
if x[0] =='i':a[m] = 0
else:
if m in a:
print('yes')
else:
print('no')
|
import sys
def main():
lines = sys.stdin.readlines()
n = int(lines[0])
repo = {}
for i in range(1, n + 1):
command, acgt = lines[i].split()
if command[0] == 'i':
if acgt not in repo:
repo[acgt] = 0
elif command[0] == 'f':
if acgt in repo:
print('yes')
else:
print('no')
return
main()
| 1 | 74,901,208,502 | null | 23 | 23 |
import copy
class Dice2:
def __init__(self, nums):
self.nums = nums
self.dic = \
{(1,2):3, (1,3):5, (1,4):2, (1,5):4, (2,3):1, (2,4):6, (2,6):3, (3,5):1, (3,6):5, (4,5):6, (4,6):2, (5,6):4}
def output_right(self, x):
x[0] = self.nums.index(x[0]) + 1
x[1] = self.nums.index(x[1]) + 1
nums = self.nums
y = copy.deepcopy(x)
x.sort()
key = tuple(x)
if tuple(y)==key:
return nums[self.dic[key]-1]
else:
return nums[6-self.dic[key]]
dice = Dice2(list(map(int, input().split())))
q = int(input())
for i in range(q):
print(dice.output_right(list(map(int, input().split()))))
|
N = int(input())
S = list(input())
a = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
ans = ''
for s in S:
num = a.index(s) + N
if num <= 25: ans += a[num]
else: ans += a[num-26]
print(ans)
| 0 | null | 67,711,306,335,036 | 34 | 271 |
H,W,M=map(int,input().split())
#二次元リストではなく列行を一個のボムで消してくれるためそれぞれのリストを用意。
sumh = [0] * H
sumw = [0] * W
bomb=[]
for i in range(M):
h,w=map(int,input().split())
sumh[h-1]+=1
sumw[w-1]+=1
bomb.append((h,w))
#爆弾の個数の最大値とその最大値がいくつずつあるか(ch,cw)に保存。最大の列と最大の行のいずれかの組み合わせに置くことで爆破数を最大化できる。
maxh=max(sumh)
maxw=max(sumw)
ch=sumh.count(maxh)
cw=sumw.count(maxw)
#print(maxh,maxw,ch,cw)
#爆弾のある場所がH,Wの座標で両方共で最大個数の場所であった場合その数を加算
count=0
for h,w in bomb:
if sumh[h-1]==maxh and sumw[w-1]==maxw:
count+=1
#print(count)
#破壊できる数は、そのマスに爆破対象があるとき一つ減ってしまう。
if count==ch*cw:
print(maxh+maxw-1)
else:
print(maxh+maxw)
|
# -*- coding: utf-8 -*-
def get_input() -> tuple:
"""
標準入力を取得する.
Returns:\n
tuple: 標準入力
"""
a, b, c, d = list(map(int, input().split()))
return a, b, c, d
def main(a: int, b: int, c: int, d: int) -> None:
"""
メイン処理.
Args:\n
a (int): 整数(-10**9 <= a <= b <= 10**9)
b (int): 整数(-10**9 <= a <= b <= 10**9)
c (int): 整数(-10**9 <= c <= d <= 10**9)
d (int): 整数(-10**9 <= c <= d <= 10**9)
"""
# 求解処理
ans = max([a * c, a * d, b * c, b * d])
# 結果出力
print(ans)
if __name__ == "__main__":
# 標準入力を取得
a, b, c, d = get_input()
# メイン処理
main(a, b, c, d)
| 0 | null | 3,865,110,799,858 | 89 | 77 |
def DFS(num):
global time
time +=1
color[num]="gray"
D[num][0]=time
for i in M[num]:
if color[i]=="white":
DFS(i)
color[num]="black"
time +=1
D[num][1]=time
n=int(input())
M=[[] for _ in range(n+1)]
for i in range(n):
for j in list(map(int,input().split()))[2:]:
M[i+1].append(j)
color=["white" for _ in range(n+1)]
D=[[0,0] for _ in range(n+1)]
time=0
for i in range(n):
if color[i+1]=="white":
DFS(i+1)
for i in range(n):
print(i+1,*D[i+1])
|
# -*- coding: utf_8 -*-
level = False
def debug(v):
if level:
print(v)
n = int(input())
a = [0]
for i in range(n):
v = input().split()
v.pop(0)
v.pop(0)
a.append([int(x) for x in v])
debug(a)
stack = [1]
results = [[0 for i in range(2)] for j in range(n + 1)]
results[0][0] = 0
time = 0
def depth_first_search(a, stack):
debug(a)
debug(results)
debug(stack)
global time
if len(stack) == 0:
return
v = stack.pop()
if results[v][0] == 0:
time += 1
results[v][0] = time
es = a[v]
if len(es) == 0 and results[v][1] == 0:
time += 1
results[v][1] = time
if len(es) != 0:
stack.append(v)
next_vert = es.pop(0)
if results[next_vert][0] == 0:
stack.append(next_vert)
depth_first_search(a, stack)
for i in range(n):
stack = [i + 1]
depth_first_search(a, stack)
debug(results)
results.pop(0)
i = 1
for row in results:
print(str(i) + " " + str(row[0]) + " " + str(row[1]))
i += 1
| 1 | 2,559,886,888 | null | 8 | 8 |
import math
A, B, H, M = map(int, input().split())
SP_HOUR = 360 / (12 * 60)
SP_MIN = 360 / 60
angle = (H * 60 + M) * SP_HOUR - M * SP_MIN
if angle < 0:
angle += 360
# print(math.cos(0))
# print(math.cos(3.14))
# print("angle", angle)
# print("angle in radian", math.radians(angle))
#Law of cosines
ans_squ = A * A + B * B - 2 * A * B * math.cos(math.radians(angle))
print(math.sqrt(ans_squ))
|
import math
A,B,H,M = map(int,input().split())
degree = 0
minute = 6*M
hour=30*H+0.5*M
if abs(minute-hour)>=180:
degree = 360-abs(minute-hour)
else :
degree = abs(minute-hour)
#print (degree)
#print (math.degrees(degree))
#print (math.cos(math.radians(degree)))
c=A**2+B**2-2*A*B*math.cos(math.radians(degree))
print (math.sqrt(c))
| 1 | 20,077,261,149,032 | null | 144 | 144 |
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(buff_readline())
def read_int_n():
return list(map(int, buff_readline().split()))
def read_float():
return float(buff_readline())
def read_float_n():
return list(map(float, buff_readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
class Mod:
def __init__(self, m):
self.m = m
def add(self, a, b):
return (a + b) % self.m
def sub(self, a, b):
return (a - b) % self.m
def mul(self, a, b):
return ((a % self.m) * (b % self.m)) % self.m
def div(self, a, b):
return self.mul(a, pow(b, self.m-2, self.m))
def pow(self, a, b):
return pow(a, b, self.m)
class Bisect:
def __init__(self, func):
self.__func = func
def bisect_left(self, x, lo, hi):
while lo < hi:
mid = (lo+hi)//2
if self.__func(mid) < x:
lo = mid+1
else:
hi = mid
return lo
def bisect_right(self, x, lo, hi):
while lo < hi:
mid = (lo+hi)//2
if x < self.__func(mid):
hi = mid
else:
lo = mid+1
return lo
def f(n):
r = 1
for i in range(1, n+1):
r *= i
return r
@mt
def slv(N, K, A, F):
A.sort()
F.sort(reverse=True)
def f(x):
y = 0
for a, f in zip(A, F):
b = a - x//f
if b > 0:
y += b
if y <= K:
return 1
return 0
return Bisect(f).bisect_left(1, 0, 10**18)
def main():
N, K = read_int_n()
A = read_int_n()
F = read_int_n()
print(slv(N, K, A, F))
if __name__ == '__main__':
main()
|
# coding: utf-8
N = int(input())
A=list(map(int,input().split()))
dansa = []
top = 0
for i in range(N):
dansa.append(max(0,top-A[i]))
top = max(top,A[i])
print(sum(dansa))
| 0 | null | 84,798,893,729,500 | 290 | 88 |
import sys
input = sys.stdin.readline
def main():
N, K, S = map(int, input().split())
if S == 10**9:
ans = [S] * K + [1] * (N-K)
else:
ans = [S] * K + [10**9] * (N-K)
print(*ans)
if __name__ == "__main__":
main()
|
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
r = int(readline())
print(r ** 2)
| 0 | null | 118,134,619,107,312 | 238 | 278 |
N = int(input())
S = list(input())
Q = int(input())
class Bit:
"""1-indexed"""
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
def sum(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
self.tree[i] += x
i += i & -i
en2asc = lambda s: ord(s) - 97
Bits = [Bit(N) for _ in range(26)]
for i, s in enumerate(S):
Bits[en2asc(s)].add(i + 1, 1)
for _ in range(Q):
q = input().split()
if q[0] == '1':
i, c = int(q[1]), q[2]
old = S[i - 1]
Bits[en2asc(old)].add(i, -1)
Bits[en2asc(c)].add(i, 1)
S[i - 1] = c
else:
l, r = int(q[1]), int(q[2])
ans = 0
for b in Bits:
ans += bool(b.sum(r) - b.sum(l - 1))
print(ans)
|
a = input()
b = ord(a)
print(chr(ord(a)+1))
| 0 | null | 77,321,746,339,990 | 210 | 239 |
N=int(input())
X=list(map(int,input().split()))
Y=[]
for i in range(1,101):
tot=0
for n in range(N):
tot+=(X[n]-i)**2
Y.append(tot)
print(min(Y))
|
N = int(input())
X = list(map(int, input().split()))
ans = 100 ** 100
for p in range(1, 101):
now = 0
for x in X:
now += (p - x) ** 2
ans = min(ans, now)
print(ans)
| 1 | 65,287,638,613,682 | null | 213 | 213 |
N,A,B = map(int,input().split())
mod = 10**9 + 7
def cmb(n,r,mod):
a=1
b=1
r = min(r,n-r)
for i in range(r):
a = a*(n-i)%mod
b = b*(i+1)%mod
return a*pow(b,mod-2,mod)%mod
all = pow(2,N,mod) + mod
nCa = cmb(N,A,mod)
nCb = cmb(N,B,mod)
ans = all - nCa - nCb
print((ans-1)%mod)
|
MOD = pow(10, 9)+7
def combi(n, k, MOD):
numer = 1
for i in range(n, n-k, -1):
numer *= i
numer %= MOD
denom = 1
for j in range(k, 0, -1):
denom *= j
denom %= MOD
return (numer*(pow(denom, MOD-2, MOD)))%MOD
def main():
n, a, b = map(int, input().split())
allsum = pow(2, n, MOD)
s1 = combi(n, a, MOD)
s2 = combi(n, b, MOD)
ans = (allsum - s1 - s2 - 1)%MOD
print(ans)
if __name__ == "__main__":
main()
| 1 | 65,942,461,238,624 | null | 214 | 214 |
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
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
mod = 10**9+7 # 出力の制限
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 i in range(N-K+1):
ans += A[-1-i]*cmb(N-1-i, K-1, mod)
ans %= mod
ans -= A[i]*cmb(N-1-i, K-1, mod)
ans %= mod
print(ans)
|
import math
K = int(input())
total = 0
for x in range(1, K+1):
for y in range(1, K+1):
for z in range(1, K+1):
total = total+math.gcd(x, math.gcd(y, z))
print(total)
| 0 | null | 65,660,835,345,044 | 242 | 174 |
#
# 10d
#
import math
def main():
n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
d1 = 0
d2 = 0
d3 = 0
dn = 0
for i in range(n):
d1 += abs(x[i] - y[i])
d2 += (x[i] - y[i])**2
d3 += abs(x[i] - y[i])**3
dn = max(dn, abs(x[i] - y[i]))
d2 = math.sqrt(d2)
d3 = math.pow(d3, 1/3)
print(f"{d1:.5f}")
print(f"{d2:.5f}")
print(f"{d3:.5f}")
print(f"{dn:.5f}")
if __name__ == '__main__':
main()
|
N = int(input())
A = list(map(int,input().split()))
m = max(A) + 1
cnt = [0]*m
for i in A:
cnt[i] += 1
ans = 0
for i in range(1,m):
if cnt[i]:
if cnt[i]==1:
ans += 1
for j in range(i,m,i):
cnt[j] = 0
print(ans)
| 0 | null | 7,263,811,058,490 | 32 | 129 |
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15
def main():
N = int(input())
word = []
time = []
for _ in range(N):
a,b = input().split()
word.append(a)
time.append(int(b))
X = input()
s = -1
for i in range(N):
if word[i] == X:
s = i + 1
ans = sum(time[s:])
print(ans)
if __name__ == '__main__':
main()
|
N = int(input())
M = [""] * N
T = [0] * N
for i in range(N):
m, t = input().split(" ")
M[i] = m
T[i] = int(t)
X = input()
id = M.index(X)
s = sum(T[id+1:])
print(s)
| 1 | 97,006,704,859,900 | null | 243 | 243 |
while True:
H,W=[int(i) for i in input().split(" ")]
if H==W==0:
break
for h in range(H):
print("#"*W)
print()
|
N = int(input())
if N%1000 == 0:
print(0)
else:
print(1000-(N%1000))
| 0 | null | 4,624,383,956,050 | 49 | 108 |
#! python3
a, b, c = [int(x) for x in input().strip().split(' ')]
r = 0
for i in range(a, b+1):
if c % i == 0:
r += 1
print(r)
|
num = [int(x) for x in input().split() if x.isdigit()]
count = 0
for i in range(num[0], num[1]+1):
if num[2] % i == 0:
count += 1
print(count)
| 1 | 570,041,442,194 | null | 44 | 44 |
n,k = map(int,input().split())
a = [0]*n
for _ in range(k):
kind = int(input())
for i in list(map(int,input().split())):
a[i-1] += 1
print(a.count(0) if 0 in a else 0)
|
def main():
n, p = map(int, input().split())
s = input()
mu = [None]*n
ans = 0
c = [0]*p
if 10%p == 0:
ss = map(int, s)
ss = list(ss)
for i in range(n):
if ss[i]%p == 0:
ans += i+1
print(ans)
return
sr = s[::-1]
ssr = map(int, sr)
tens = 1
v = 0
for i, si in enumerate(ssr):
v = (v + (si%p)*tens)%p
mu[i] = v
c[v] += 1
tens *= 10
tens %= p
c[0] += 1
for i in c:
if i:
ans += ((i-1)*i)//2
print(ans)
if __name__ == "__main__":
main()
| 0 | null | 41,287,842,636,012 | 154 | 205 |
l = range(1, 10)
for i in ["%dx%d=%d" % (x, y, x*y) for x in l for y in l]:
print i
|
for i in range(1,10):
for j in range(1,10):
print "%dx%d=%d" % (i,j,i*j)
| 1 | 39,104 | null | 1 | 1 |
import sys
import time
import math
import itertools as it
def inpl():
return list(map(int, input().split()))
st = time.perf_counter()
# ------------------------------
A, B, H, M = inpl()
h = 360 * H / 12 + 30 * M / 60
m = 360 * M / 60
sa = abs(h - m)
sa = min(sa, 360-sa)
print((A*A + B*B - 2*A*B*math.cos(sa*math.pi/180))**0.5)
# ------------------------------
ed = time.perf_counter()
print('time:', ed-st, file=sys.stderr)
|
def main():
n = int(input())
a_lst = list(map(int, input().split()))
lst = [0 for _ in range(2 * 10 ** 5 + 1)]
for a in a_lst:
lst[a] += 1
for i in range(1, n + 1):
print(lst[i])
if __name__ == "__main__":
main()
| 0 | null | 26,244,382,687,500 | 144 | 169 |
from collections import deque
n,m=map(int,input().split())
r=[[] for i in range(n+1)]
for i in range(m):
a,b=map(int,input().split())
r[a].append(b)
r[b].append(a)
dep=[-1]*(n+1)
dep[0]=0
dep[1]=0
data=deque([1])
d=0
while len(data)>0:
p=data.popleft()
for i in r[p]:
if dep[i]==-1:
dep[i]=dep[p]+1
data.append(i)
if not all(dep[i+1]>=0 for i in range(n)):
print("No")
else:
print("Yes")
for i in range(2,n+1):
for j in r[i]:
if dep[j]==dep[i]-1:
print(j)
break
|
N,K = map(int,input().split())
P = list(map(int,input().split()))
# 累積和
s = [0] * (N+1)
for i in range(N):# O(N)
s[i+1] = s[i] + P[i]
# [j,j+K) の和の最大値と j を保持
m = 0
midx = 0
for j in range(N-K+1):# O(N)
v = s[j+K] - s[j]
if v > m:
m = v
midx = j
E = 0
for k in range(midx,midx+K):# O(K)
x = P[k]
E += (1/x)*(x*(x+1)/2)
print(E)
| 0 | null | 47,763,630,821,804 | 145 | 223 |
MOD = 10**9 + 7
K = int(input())
S = len(input())
FCT = [1]
for i in range(1, K+S+1):
FCT.append((FCT[-1] * i)%MOD)
def pmu(n, r, mod=MOD):
return (FCT[n] * pow(FCT[n-r], mod-2, mod)) % mod
def cmb(n, r, mod=MOD):
return (pmu(n, r) * pow(FCT[r], mod-2, mod)) % mod
def solve():
ans = 1
for i in range(S+1, K+S+1):
ans = (ans*26) % MOD
add = pow(25, i-S, MOD)
add = (add * cmb(i-1, i-S)) % MOD
ans = (ans + add) % MOD
return ans
if __name__ == "__main__":
print(solve())
|
import sys
input = sys.stdin.readline
K = int(input())
S = list(input())[: -1]
N = len(S)
mod = 10 ** 9 + 7
class Factorial:
def __init__(self, n, mod):
self.f = [1]
for i in range(1, n + 1):
self.f.append(self.f[-1] * i % mod)
self.i = [pow(self.f[-1], mod - 2, mod)]
for i in range(1, n + 1)[: : -1]:
self.i.append(self.i[-1] * i % mod)
self.i.reverse()
def factorial(self, i):
return self.f[i]
def ifactorial(self, i):
return self.i[i]
def combi(self, n, k):
return self.f[n] * self.i[n - k] % mod * self.i[k] % mod
f = Factorial(N + K + 1, mod)
res = 0
for l in range(K + 1):
r = K - l
res += f.combi(l + N - 1, l) * pow(25, l, mod) % mod * pow(26, r, mod) % mod
res %= mod
print(res)
| 1 | 12,872,966,583,552 | null | 124 | 124 |
# -*- coding:utf-8 -*-
x = int(input())
if x == False:
print("1")
else:
print("0")
|
N = input()
nums = []
for num in N:
nums.append(int(num))
s = sum(nums)
if s % 9 == 0:
print("Yes")
else:
print("No")
| 0 | null | 3,637,975,109,878 | 76 | 87 |
def main():
S = input()
K = int(input())
A = []
last = S[0]
count = 1
for i in range(1, len(S)):
s = S[i]
if last == s:
count += 1
else:
A.append({'key': last, 'count': count})
count = 1
last = s
A.append({'key': last, 'count': count})
# print(A)
if len(A) == 1:
c = A[0]['count']
l = c*K
ans = l//2
print(ans)
return
ans = 0
if A[0]['key'] != A[-1]['key']:
for a in A:
c = a['count']
ans += (c//2) * K
print(ans)
return
for i in range(1, len(A) - 1):
a = A[i]
c = a['count']
ans += (c//2) * K
a0 = A[0]
a1 = A[-1]
c0 = a0['count']
c1 = a1['count']
ans += c0//2
ans += c1//2
ans += ((c0 + c1)//2) * (K - 1)
print(ans)
if __name__ == '__main__':
main()
|
s=input()
n=int(input())
if len(s)==1:print(n//2);exit()
if len(set(s))==1:print(len(s)*n//2);exit()
c=1
l=[]
for x in range(1,len(s)):
if s[x-1]==s[x]:
c+=1
if x==len(s)-1:l.append(c)
else:l.append(c);c=1
t=0
if s[0]==s[-1] and l[0]%2==1 and l[-1]%2==1:t=n-1
print(sum([i//2 for i in l])*n+t)
| 1 | 175,050,977,217,412 | null | 296 | 296 |
H,W = [int(x) for x in input().split()]
s = ""
while not H == W == 0:
for i in range(H):
for j in range(W):
s+= "." if (i+j)%2 else "#"
print(s)
s = ""
print()
H,W = [int(x) for x in input().split()]
|
N, X, T = map(int, input().split())
A = N // X
B = N % X
if B == 0:
print(A * T)
else:
print((A+1)*T)
| 0 | null | 2,545,672,527,440 | 51 | 86 |
n,d=map(int,input().split())
ans=0
for _ in range(n):
x,y=map(int,input().split())
dist=x**2+y**2
dist=dist**(1/2)
if dist<=d:
ans+=1
print(ans)
|
c = ord(input())
c += 1
n = chr(c)
print(n)
| 0 | null | 49,131,770,333,812 | 96 | 239 |
a = int(input())
ans = a + (a ** 2) + (a ** 3)
print(ans)
|
def main():
a=int(input())
print(a*(1+a+a*a))
main()
| 1 | 10,216,908,428,410 | null | 115 | 115 |
import math
member = []
score = []
while True:
num = int(raw_input())
if num == 0: break
member.append(num)
score.append(map(int, raw_input().split()))
alpha = []
for m, s in zip(member, score):
average = sum(s)/float(m)
sigma = 0
for t in s:
sigma += (t - average)**2
else:
alpha += [sigma/m]
for a in alpha:
#print '%.8f' % math.sqrt(a)
print math.sqrt(a)
|
n = int(input())
Ai = list(map(int, input().split()))
sum_ans = sum(Ai)
ans = 0
mod = 1000000007
for i in range(n-1):
sum_ans -= Ai[i]
ans += sum_ans * Ai[i]
ans %= mod
print(ans)
| 0 | null | 1,995,290,387,010 | 31 | 83 |
import sys
from collections import Counter
n = int(input())
D = list(map(int,input().split()))
if D[0] != 0 or D.count(0) != 1:
print(0)
sys.exit()
D = Counter(D)
L = sorted(D.items())
pk = 0
pv = 1
ans = 1
for i,j in L:
if i == 0:
continue
if i != pk+1:
print(0)
break
ans *= pv**j
ans %= 998244353
pk = i
pv = j
else:
print(ans)
|
N = int(input())
D = list(map(int, input().split()))
M = 998244353
from collections import Counter
if D[0] != 0:
print(0)
exit(0)
cd = Counter(D)
if cd[0] != 1:
print(0)
exit(0)
tmp = sorted(cd.items(), key=lambda x: x[0])
ans = 1
for kx in range(1, max(D)+1):
ans *= pow(cd[kx-1], cd[kx],M)
ans %= M
print(ans)
| 1 | 154,863,136,026,870 | null | 284 | 284 |
count_al = list(0 for i in range(26))
while True :
try :
a = str(input())
b = a.lower()
for i in range(len(b)) :
c = ord(b[i])
if c > 96 and c < 123 :
count_al[c - 97] += 1
except EOFError :
break
for i in range(97, 123) :
print(chr(i), ":", count_al[i-97])
|
cnt = [0 for i in range (26)]
alphabet = 'abcdefghijklmnopqrstuvwxyz'
str = open(0).read()
for x in str:
for k in range(len(alphabet)):
if x == alphabet[k] or x == alphabet[k].upper():
cnt[k] = cnt[k] + 1
break
for i in range(26):
print(alphabet[i], ':', cnt[i])
| 1 | 1,658,531,311,790 | null | 63 | 63 |
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)
S = int(input())
mod = 10**9+7
pos = {0: 1}
neg = {0: 1}
for i in range(1, 10**4):
pos[i] = (pos[i-1]*i)%mod
neg[i] = pow(pos[i], mod-2, mod)
cnt = 1
ans = 0
while 3*cnt<=S:
rest = S-3*cnt
ans += pos[rest+cnt-1]*neg[rest]*neg[cnt-1]
ans %= mod
cnt += 1
print(ans)
|
while True:
L = raw_input().split()
a = int(L[0])
o = (L[1])
b = int(L[2])
if o == "?":
break
elif o == "+":
print a + b
elif o == "-":
print a - b
elif o == "*":
print a * b
elif o == "/":
print a/b
| 0 | null | 1,992,241,154,512 | 79 | 47 |
while True:
x,y = map(int,raw_input().split())
if x==0:
break
else:
for i in xrange(x):
print y*"#"
print ""
|
while True:
H, W = list(map(int, input().split()))
if H == 0 & W == 0:
break
print(("#"*W + "\n")*H)
| 1 | 784,608,437,492 | null | 49 | 49 |
num=(int)(input())
n=num//100
amari=num%100
if num <= 99 or amari / n > 5:
print(0)
else:
print(1)
|
import sys
sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline
def solve():
N, M, L = map(int, rl().split())
INF = 10 ** 18
dist = [[INF] * N for _ in range(N)]
for _ in range(M):
a, b, c = map(int, rl().split())
a, b = a - 1, b - 1
dist[a][b] = dist[b][a] = c
for k in range(N):
for i in range(N):
for j in range(N):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
cost = [[INF] * N for _ in range(N)]
for i in range(N):
for j in range(N):
if dist[i][j] <= L:
cost[i][j] = 1
for k in range(N):
for i in range(N):
for j in range(N):
cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j])
Q = int(rl())
st = [list(map(lambda n: int(n) - 1, rl().split())) for _ in range(Q)]
ans = [-1] * Q
for i, (s, t) in enumerate(st):
if cost[s][t] != INF:
ans[i] = cost[s][t] - 1
print(*ans, sep='\n')
if __name__ == '__main__':
solve()
| 0 | null | 150,833,038,105,020 | 266 | 295 |
n = int(input())
a = list(map(int, input().split()))
i = 1
if 0 in a:
i = 0
else:
for j in range(n):
if i >= 0:
i = i * a[j]
if i > 10 ** 18:
i = -1
print(int(i))
|
n = int(input())
a = list(map(int,input().split()))
dota = 1
if 0 in set(a):
dota = 0
else:
for ai in a:
dota *= ai
if dota > 10**18:
dota = -1
break
print(dota)
| 1 | 16,179,738,655,680 | null | 134 | 134 |
#(身長)ー(番号)=ー(身長)ー(番号)はありえない、身長=0にならないから
N = int(input())
A = list(map(int,input().split()))
from collections import defaultdict
AB = defaultdict(int)
_AB = defaultdict(int)
for i,a in enumerate(A):
AB[i+1+A[i]]+=1
_AB[-A[i]+i+1]+=1
ans = 0
for key,val in AB.items():
ans += val*_AB[key]
print(ans)
|
n = int(input())
a = list(map(int,input().split()))
sa = sorted(a,reverse=True)
ans = sa[0]
i = 2
for v in sa[1:]:
if i >= n:
break
#print("i:{} ans:{}".format(i,ans))
ans += v
i += 1
if i >= n:
break
#print("i:{} ans:{}".format(i,ans))
ans += v
i += 1
print(ans)
| 0 | null | 17,521,605,817,860 | 157 | 111 |
n,a,b = map(int, input().split())
if n % (a+b) >= a:
print((n // (a+b))*a + a)
else:
print((n // (a+b))*a + (n % (a+b)))
|
N = int(input())
P = list(map(int,input().split()))
ans = 1
min = P[0]
for i in P[1:]:
if min >= i:
ans += 1
min = i
print(ans)
| 0 | null | 70,406,112,693,424 | 202 | 233 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.