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
|
---|---|---|---|---|---|---|
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, accumulate, combinations, combinations_with_replacement
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy
from operator import itemgetter
from functools import reduce, lru_cache # @lru_cache(None)
from fractions import gcd
import sys
def input(): return sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**6)
# ----------------------------------------------------------- #
s = input()
print(s[:3])
|
N, M = map(int, input().split())
arr = [10] * N
for _ in range(M):
idx, num = map(int, input().split())
if arr[idx - 1] == 10:
arr[idx - 1] = num
else:
if arr[idx - 1 ] != num:
print(-1)
exit()
if arr[0] == 0:
if N == 1:
print(0)
exit()
else:
print(-1)
exit()
elif arr[0] == 10:
if N == 1:
print(0)
exit()
else:
arr[0] = 1
for i in range(N):
if arr[i] == 10:
arr[i] = 0
for i in arr:
print(i,end="")
| 0 | null | 37,644,471,749,990 | 130 | 208 |
def gcd(x, y):
if y == 0:
return x
else:
return gcd(y, x%y)
def lcm(x,y):
return x/gcd(x, y)*y
while True:
try:
x, y = map(int, raw_input().split())
except EOFError:
break
print "%d %d" % (gcd(x, y), lcm(x, y))
|
while 1:
try:
a, b = map(int,raw_input().split())
except EOFError:
break
ac, bc = a, b
while 1:
if a < b:
b = b - a
elif b < a:
a = a - b
elif a == b:
x = [a,ac*bc/a]
print "{:.10g} {:.10g}".format(*x)
break
| 1 | 606,000,230 | null | 5 | 5 |
N=int(raw_input())
s=[int(raw_input()) for x in range(N)]
def is_prime(n):
i = 2
while i * i <=n:
if n % i == 0:
return False
i += 1
return True
a=filter(is_prime,s)
print len(a)
|
from sys import stdin
import math
def isPrime(x):
if x == 2 or x == 3: return True
elif (x < 2 or x % 2 == 0 or x % 3 == 0): return False
s = int(math.sqrt(x) + 1)
for i in range(5, s + 1, 2):
if x % i == 0: return False
return True
print(sum([isPrime(int(stdin.readline())) for _ in range(int(stdin.readline()))]))
| 1 | 10,823,359,700 | null | 12 | 12 |
c = 0
while True:
x = int(input())
if x == 0:
break;
c += 1
print('Case', str(c) + ':', x)
|
s = input()
map = {'SSS': 0, 'SSR': 1, 'SRS': 1, 'RSS': 1, 'SRR': 2, 'RSR': 1, 'RRS': 2, 'RRR': 3}
for key in map.keys():
if s == key:
print(map[key])
break
| 0 | null | 2,646,727,693,610 | 42 | 90 |
n = (int)(input())
a = list(map(int, input().split(" ")))
q = (int)(input())
m = list(map(int, input().split(" ")))
lst = []
for i in range(2 ** n, 0, -1):
temp = 0
for j in range(n):
if (i >> j) & 1:
temp += a[j]
lst.append(temp)
for k in range(q):
if m[k] in lst:
print("yes")
else:
print("no")
|
N = int(input())
A = list(map(int, input().split()))
se = set()
for i in range(1<<N):
tot = 0
for j in range(N):
if i&(1<<j): tot += A[j]
se.add(tot)
_ = int(input())
Q = list(map(int, input().split()))
for q in Q:
if q in se:
print("yes")
else:
print("no")
| 1 | 100,610,090,112 | null | 25 | 25 |
if __name__ == "__main__":
a = []
for i in range(0,10):
val = input()
a.append(int(val))
a.sort()
a.reverse()
for i in range(0,3):
print(a[i])
|
a=['SUN','MON','TUE','WED','THU','FRI','SAT']
s=input()
for i in range(7):
if a[i]==s:
print(7-i)
| 0 | null | 66,839,390,515,800 | 2 | 270 |
#coding:utf-8
h = 1
w = 1
while h+w != 0:
h, w=input().rstrip().split(" ")
h = int(h)
w = int(w)
if h == 0:
if w==0:
break
for i in range(h):
print("#"*w)
print("")
|
n, k = map(int, input().split())
mod = 10 ** 9 + 7
ans = 0
coma = 1
comb = 1
for i in range(min(k+1, n)):
ans += coma * comb
ans %= mod
coma *= (n-i) * pow(i+1, mod-2, mod)
coma %= mod
comb *= (n-i-1) * pow(i+1, mod-2, mod)
comb %= mod
print(ans)
| 0 | null | 34,006,495,975,860 | 49 | 215 |
import numpy as np
N, M, K = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
# cumsum
i = 0
A_sum = [0]
while (i < len(A)) and (A_sum[i] + A[i] <= K):
A_sum.append(A_sum[i] + A[i])
i += 1
i = 0
B_sum = [0]
while (i < len(B)) and (B_sum[i] + B[i] <= K):
B_sum.append(B_sum[i] + B[i])
i += 1
# count
max_book = 0
ind = len(B_sum) - 1
for i in range(len(A_sum)):
while (A_sum[i] + B_sum[ind] > K) and (ind > 0):
ind -= 1
if i + ind > max_book:
max_book = i + ind
print(max_book)
|
n, m, k = map(int, input().split(' '))
list_a = list(map(int, input().split(' ')))
list_b = list(map(int, input().split(' ')))
a_sum=[list_a[0]]
for i in range(1, n):
a_sum.append(list_a[i]+a_sum[i-1])
b_sum=[list_b[0]]
for i in range(1, m):
b_sum.append(list_b[i]+b_sum[i-1])
ans=0
if (a_sum[0]>k) and (b_sum[0]>k):
print(0)
else:
for j in range(m):
if b_sum[j]<=k:
ans=max(ans, j+1)
j=m-1
for i in range(n):
if a_sum[i]<=k:
ans=max(ans, i+1)
while a_sum[i] + b_sum[j] > k and j>0:
j-=1
if a_sum[i]+b_sum[j]<=k:
ans=max(ans, i+j+2)
print(ans)
| 1 | 10,761,091,760,430 | null | 117 | 117 |
N = int(input())
S_ord = [ord(i) for i in input()]
S_ord_change = []
for i in S_ord:
i += N
if i >= 91:
i = i - 26
S_ord_change.append(i)
S_change_chr = [chr(i) for i in S_ord_change]
result = ''.join(S_change_chr)
print(result)
|
N=int(input())
S=input()
indices = list(map(ord, S))
indices2 = []
for idx in indices:
if idx + N > 90: indices2.append(idx - 26 + N)
else: indices2.append(idx + N)
S2 = list(map(chr,indices2))
print(''.join(S2))
| 1 | 134,818,417,968,948 | null | 271 | 271 |
s,j= input().split()
if s==j:
print("Yes")
else:
print("No")
|
import math
A, B = input().split()
A = int(A)
B = int(''.join(B.split('.')))
print((A * B) // 100)
| 0 | null | 49,667,655,615,380 | 231 | 135 |
N=int(input())
ans=0
speech_l=[[] for _ in range(N)]
for i in range(N):
tmp=int(input())
for j in range(tmp):
speech_l[i].append(list(map(int,input().split())))
for i in range(2**N):
sw=0
l=[1]*N
tmp=N
for j in range(N):
if ((i >> j)&1):
tmp-=1
l[j]=0
for j in range(N):
if l[j] == 1:
for k in speech_l[j]:
if l[k[0]-1] != k[1]:
sw=1
if sw==0:
ans=max(ans,tmp)
print(ans)
|
#
# abc147 c
#
import sys
from io import StringIO
import unittest
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, stdin
self.assertEqual(out, output)
def test_入力例_1(self):
input = """3
1
2 1
1
1 1
1
2 0"""
output = """2"""
self.assertIO(input, output)
def test_入力例_2(self):
input = """3
2
2 1
3 0
2
3 1
1 0
2
1 1
2 0"""
output = """0"""
self.assertIO(input, output)
def test_入力例_3(self):
input = """2
1
2 0
1
1 0"""
output = """1"""
self.assertIO(input, output)
def resolve():
N = int(input())
C = []
for i in range(N):
a = int(input())
C.append([list(map(int, input().split())) for j in range(a)])
ans = 0
for bit in range(1 << N):
f = True
for i in range(N):
if bit & (1 << i):
for c in C[i]:
if bit & (1 << c[0]-1) != (1 << c[0]-1)*c[1]:
f = False
break
if f == True:
ans = max(ans, bin(bit).count("1"))
print(ans)
if __name__ == "__main__":
# unittest.main()
resolve()
| 1 | 121,397,601,671,400 | null | 262 | 262 |
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from math import pi
def main():
n, *a = map(int, read().split())
cnt = [0] * n
for ae in a:
cnt[ae-1] += 1
print(*cnt, sep='\n')
if __name__ == '__main__':
main()
|
def main():
# n=int(input())
n,k= map(int, input().split())
p=n-2*k
print(p) if p>0 else print(0)
return
main()
| 0 | null | 99,243,546,962,020 | 169 | 291 |
n = int(input())
a = list(map(int, input().split()))
def f():
for i in range(n):
if a[i] % 2 == 0:
if a[i] % 3 != 0 and a[i] % 5 != 0:
return "DENIED"
return "APPROVED"
print(f())
|
n = int(input())
al = list(map(int, input().split()))
flg = True
for a in al:
if a%2 == 0:
if a%3 == 0 or a%5 == 0:
continue
else:
flg = False
break
if flg:
print('APPROVED')
else:
print('DENIED')
| 1 | 69,018,154,503,298 | null | 217 | 217 |
n = int(input())
i = 1
while i <= n:
x = i
if x % 3 == 0:
print(" {:d}".format(i),end="")
else:
while x:
if x % 10 == 3:
print(" {:d}".format(i),end="")
break
x = x // 10
i += 1
print("")
|
n=int(input())
a=list(map(int,input().split()))
s=sum(a)
res=0
m=1
for i in a:
b=m-i
if b<0:
print(-1)
exit(0)
res+=i
res+=b
s-=i
m=min(b*2,s)
print(res)
| 0 | null | 9,832,151,786,210 | 52 | 141 |
N, M, X = map(int, input().split())
book_lists = [list(map(int, input().split())) for _ in range(N)]
max_cost = 10**5*12+1
min_cost = max_cost
for i in range(1, 2**N):
score_list = [0 for _ in range(M)]
cost = 0
for j in range(N):
if i >> j & 1:
cost += book_lists[j][0]
for k in range(M):
score_list[k] += book_lists[j][k+1]
if min(score_list) >= X:
min_cost = min(cost, min_cost)
print(min_cost if not min_cost == max_cost else -1)
|
n,m,x=map(int,input().split())
c=[list(map(int,input().split())) for _ in range(n)]
ans=float('inf')
for i in range(2**n):
data=[0]*(m+1)
for j in range(n):
if i&(1<<j):
for k in range(m+1):
data[k]+=c[j][k]
cnt=0
for l in range(1,m+1):
if data[l]>=x:
cnt+=1
if cnt==m:
ans=min(ans,data[0])
if ans==float('inf'):
print(-1)
exit()
print(ans)
| 1 | 22,249,476,166,940 | null | 149 | 149 |
# -*- coding: utf-8 -*-
while True:
x, y = map(int, raw_input().split())
if x+y:
if x < y:
print "%d %d" %(x, y)
else:
print "%d %d" %(y, x)
else:
break;
|
A,B = map(int,input().split())
print([A-2*B,0][A<=2*B])
| 0 | null | 83,192,173,618,720 | 43 | 291 |
f = list(input())
s = []
for i, v in enumerate(f):
if v == '\\':
s.append([v, i])
elif v == '/' and len(s) > 0:
n = s.pop()
if n[0] == '\\':
t = i-n[1]
s.append(['.', t])
elif len(s) > 0:
j = len(s)-1
n1 = n[1]
while j >= 0 and s[j][0] == '.':
#print(n1, s[j][1])
n1 += s[j][1]
j -= 1
if j >= 0:
m = s[j]
# print(m)
n1 += i-m[1]
s = s[:j]
s.append(['.', n1])
else:
# print("err")
s.append(n)
else:
s.append(n)
#print(v, s, i)
a = [v[1] for v in s if v[0] == '.']
print(sum(a))
a.insert(0, len(a))
print(" ".join([str(v) for v in a]))
|
A = 0
left = []
Lake = []
s = input()
for i in range(len(s)):
if s[i] == "\\":
left.append(i)
elif s[i] == "/":
if len(left) > 0:
w = left.pop()
goukei = i - w
A += goukei
for i in range(len(Lake)-1,-1,-1):
if Lake[i][0] > w:
x = Lake.pop()
goukei += x[1]
Lake.append([w, goukei])
print(A)
if len(Lake) == 0:
print(0)
else:
print(len(Lake),end=" ")
for i in range(len(Lake)):
if i == len(Lake) - 1:
print(Lake[i][1])
else:
print(Lake[i][1],end=" ")
| 1 | 60,859,849,652 | null | 21 | 21 |
a,v = map(int,input().split())
b,w = map(int,input().split())
t = int(input())
a_t = t*v
b_t = t*w
if a_t >= b_t+abs(a-b):
print('YES')
else:
print('NO')
|
import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
import bisect
con = 10 ** 9 + 7; INF = float("inf")
def getlist():
return list(map(int, input().split()))
def Binary_Search(A, N, M):
#初期化
left = 0
right = 10 ** 7
ans = 0
#累積和
Asum = [0]
for i in range(N):
Asum.append(Asum[i] + A[-1 - i])
leftj = [INF, INF]
rightj = [0, 0]
#二分探索
while left <= right:
mid = (left + right) // 2
var = 0
happiness = 0
for i in range(N):
ind = bisect.bisect_left(A, mid - A[i])
ind = N - ind
var += ind
happiness += ind * A[i] + Asum[ind]
# print(var, happiness)
if var == M:
return happiness
elif var > M:
leftj = min(leftj, [var, -mid])
left = mid + 1
else:
ans = max(ans, happiness)
rightj = max(rightj, [var, -mid])
right = mid - 1
# print(ans)
# print(leftj)
# print(rightj)
ans = ans + (M - rightj[0]) * (-leftj[1])
return ans
#処理内容
def main():
N, M = getlist()
A = getlist()
A.sort()
ans = Binary_Search(A, N, M)
print(ans)
if __name__ == '__main__':
main()
| 0 | null | 61,499,919,096,672 | 131 | 252 |
# 726 diff 1000
# 解法 836 XYへ到達する場合はどの経路も合計の長さは同じ = 動き方1,2の合計は同じ.
# なので合計値 L がわかればLについてmove1=i,move2=L-iとして,実際の経路の構成の仕方は,L_C_iなので
move1 = [1,2]
move2 = [2,1]
X,Y = map(int,input().split())
# まず,目的地へ到達できるか?到達できる場合は合計どれだけの移動量が必要かを計算する
max_move1 = int(Y/2)
move2_num = -1
move1_num = -1
for i in range(max_move1+1):
rest = [X-i,Y-2*i]
if (X-i) == 2*(Y-2*i):
move1_num = i
move2_num = (Y-2*i)
if move1_num == -1:
print(0)
exit()
# 到達するのに必要な合計の移動量がわかったので,それらの並べ替えについて考える.
# 求めるのは nCk すなわち,いつもの奴
large = 10**9 + 7
# mod(x^p-1,p) = 1 よってmod(x^p-2,p) = 1/x となる.
ans = 1
for i in range(move1_num):
ans *= (move1_num+move2_num - i)
ans %= large
for j in range(2,move1_num+1):
ans *= pow(j,large-2,large)
ans %= large
print(ans)
|
import math
import itertools
for i in range(int(input())):
a, b, c = sorted(map(int, input().split()))
print('YES' if a*a+b*b==c*c else 'NO')
| 0 | null | 75,060,846,005,248 | 281 | 4 |
import sys
sys.setrecursionlimit(10**9)
from collections import deque
n = int(input())
u = [[] for i in range(n+1)] #隣接リスト
for i in range(n):
v = list(map(int, input().split()))
u[v[0]] = v[1:] #v = [次数, 頂点...]
d = [-1] * (n+1)
f = [-1] * (n+1)
visited = [False] * (n+1)
visited[0] = True
time = 1
#再帰
def dfs(c):
global time
d[c] = time
time += 1
visited[c] = True
for i in range(1, u[c][0]+1):
if not visited[u[c][i]]:
dfs(u[c][i])
f[c] = time
time += 1
"""
探索は元の始点から到達可能なすべての頂点を発見するまで続き、
未発見の頂点が残っていれば、
その中の番号が一番小さい1つを新たな始点として探索を続けます。
"""
while False in visited:
dfs(visited.index(False))
for i in range(1, n+1):
print(i, d[i], f[i])
|
A1, A2, A3 = map(int,input().split())
if A1+A2+A3<=21:
print("win")
else:
print("bust")
| 0 | null | 59,462,114,323,872 | 8 | 260 |
for j in range(1,10,1):
for k in range(1,10,1):
print("{}x{}={}".format(j,k,j*k))
|
x = range(1, 10)
y = range(1, 10)
for i in x:
for j in y:
print(str(i)+'x'+str(j)+'='+str(i*j))
| 1 | 3,995,920 | null | 1 | 1 |
raw_input()
a = raw_input().split(" ")
a.reverse()
print " ".join(a)
|
N = int(input())
n = input().split()
line = '{0}'.format(n[-1])
for i in range(1,N):
line += ' {0}'.format(n[N-i-1])
print(line)
| 1 | 980,490,698,020 | null | 53 | 53 |
a, b, c, d = map(int,input().split())
x = (a+d-1)//d
y = (c+b-1)//b
if x >= y:
print('Yes')
else:
print('No')
|
import numpy as np
a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
left = 4 * a * b
right = (c - (a + b)) ** 2
judge = c - (a + b)
if(judge < 0):
print("No")
else:
if(left < right):
print("Yes")
else:
print("No")
| 0 | null | 40,783,448,831,580 | 164 | 197 |
S, T = input().split()
A, B = map(int, input().split())
U = input()
if U == S: A -= 1
else: B -= 1
print(A, B)
|
if(int(input()) %2 == 1):
print("No")
exit()
t = input()
if(t[:len(t)//2] == t[len(t)//2:]):
print("Yes")
else:
print("No")
| 0 | null | 109,681,439,682,556 | 220 | 279 |
# -*- coding: utf-8 -*-
n = input()
x = y = 0
for _ in xrange(n):
a, b = raw_input().split()
if a==b:
x += 1
y += 1
elif a>b:
x += 3
else:
y += 3
print x, y
|
A=list(map(int,input().rstrip().split(" ")))
#print(A)
B=A.index(0)
print(B+1)
| 0 | null | 7,763,285,963,848 | 67 | 126 |
import sys
import collections
input = sys.stdin.readline
s, t = map(str,input().split())
a, b = map(int, input().split())
u = input().strip()
if u == s:
print(a - 1, b)
else:
print(a, b - 1)
|
N=int(input())
c=list(input())
R=c.count('R')
L=c[:R].count('R')
print(R-L)
| 0 | null | 39,132,943,024,160 | 220 | 98 |
n = int(input())
steps = []
for x in range(int(n ** 0.5)):
if n % (x + 1) == 0:
steps.append(x + n // (x + 1) - 1)
print(min(steps))
|
A, V = map(int, input().split())
B, W = map(int, input().split())
T = int(input())
firstDis = abs(A - B)
steps = (V - W)*T
print("YES" if firstDis <= steps else "NO")
| 0 | null | 88,494,393,762,170 | 288 | 131 |
MOD = 10 ** 9 + 7
MAX = 60
n = int(input())
a = list(map(int, input().split()))
cnt = [0 for i in range(MAX)]
for i in range(n):
bit = bin(a[i])[2:].zfill(MAX)
for j in range(MAX):
cnt[j] += int(bit[j])
ans = 0
for i in range(MAX):
ans += cnt[MAX - i - 1] * (n - cnt[MAX - i - 1]) * 2 ** i
ans %= MOD
print(ans)
|
a,b=map(int,input().split(' '))
count=0
if a==b:
print("Yes")
else:
print("No")
| 0 | null | 103,152,240,659,852 | 263 | 231 |
a,b,c=map(int,input().split())
k=int(input())
i=0
while True:
if a<b:
break
b*=2
i+=1
while True:
if b<c:
break
c*=2
i+=1
if i<=k:
print("Yes")
elif i>k:
print("No")
|
import numpy as np
from collections import Counter
n = int(input())
a = np.array(list(map(int, input().split())))
ni = np.array([i for i in range(n)])
ap = a + ni
an = (a - ni) * -1
cp = Counter(ap)
cn = Counter(an)
ans = 0
for i in cp.keys():
ans += cp[i] * cn[i]
print(ans)
| 0 | null | 16,568,319,705,348 | 101 | 157 |
def num2alpha(num):
if num<=26:
return chr(64+num)
elif num%26==0:
return num2alpha(num//26-1)+chr(90)
else:
return num2alpha(num//26)+chr(64+num%26)
print(num2alpha(int(input())).lower())
|
nm = input().split()
n, m = map(int, nm)
A = [[int(i) for i in input().split()] for j in range(n)]
b = [int(input()) for i in range(m)]
for row in A:
s = 0
for i, elm in enumerate(row):
s += (elm*b[i])
print(s)
| 0 | null | 6,499,267,122,890 | 121 | 56 |
def main():
N=int(input())
A=list(map(int,input().split()))
s=sum(A)
Q=int(input())
d=[0]*(10**5 +1)#各数字の個数
for i in A:
d[i]+=1
for i in range(Q):
B,C=map(int,input().split())
s += (C-B)*d[B]
print(s)
d[C]+=d[B]
d[B]=0
if __name__ == "__main__":
main()
|
def main():
s, t = map(str, input().split(' '))
a, b = map(int, input().split())
u = str(input())
if u == s:
print(str(a - 1) + ' ' + str(b))
else:
print(str(a) + ' ' + str(b - 1))
main()
| 0 | null | 41,833,059,165,550 | 122 | 220 |
n = int(input())
x = n%10
if (x == 2 or x == 4 or x == 5 or x == 7 or x == 9):
print("hon")
elif (x == 0 or x == 1 or x == 6 or x == 8):
print("pon")
else:
print("bon")
|
N = int(input())
N1 = N % 10
if N1 == 3:
print("bon")
elif (N1 == 0) or (N1 == 1) or (N1 == 6) or (N1 == 8):
print("pon")
else:
print("hon")
| 1 | 19,280,194,897,460 | null | 142 | 142 |
#coding: UTF-8
import statistics as st
while True:
N = int(input())
if N == 0:
break
buf = list(map(float, input().split()))
sd = st.pstdev(buf)
print("%.8f"%sd)
|
n=input()
ans=0
for i in n:
ans+=int(i)
ans%=9
if ans==0:
print('Yes')
else:
print('No')
| 0 | null | 2,282,131,761,810 | 31 | 87 |
N = int(input())
cnt = 0
flg = False
for _ in range(N):
a, b = map(int, input().split())
if a != b:
cnt = 0
else:
cnt += 1
if cnt >= 3:
flg = True
if flg:
print('Yes')
else:
print('No')
|
n = int(input())
d = [list(map(int, input().split())) for _ in range(n)]
cnt = 0
for i in range(n):
d1, d2 = d[i]
if d1 == d2:
cnt += 1
if cnt == 3:
print("Yes")
exit(0)
else:
cnt = 0
print("No")
| 1 | 2,480,691,700,672 | null | 72 | 72 |
N = int(input())
z = []
w = []
for i in range(N):
x,y = map(int,input().split())
z.append(x+y)
w.append(x-y)
z_max = max(z)
z_min = min(z)
w_max = max(w)
w_min = min(w)
print(max(z_max-z_min,w_max-w_min))
|
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
def main():
N = int(input())
XY = [[int(x) for x in input().split()] for _ in range(N)]
arr1 = []
arr2 = []
for x, y in XY:
arr1.append(x - y)
arr2.append(x + y)
print(max(abs(max(arr1) - min(arr1)), abs(max(arr2) - min(arr2))))
if __name__ == '__main__':
main()
| 1 | 3,426,297,185,448 | null | 80 | 80 |
while True:
try:
a, b = map(int, raw_input().split())
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a%b)
g = gcd(a,b)
l = a*b/g
print g, l
except:
break
|
def gcd(a, b):
"""Return greatest common divisor using Euclid's Algorithm."""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""Return lowest common multiple."""
return a * b // gcd(a, b)
try:
while True:
a, b = map(int, raw_input().split(' '))
print gcd(a, b), lcm(a, b)
except EOFError:
pass
| 1 | 538,830,142 | null | 5 | 5 |
from collections import deque
N = int(input())
X = [list(map(int, input().split())) for _ in range(N - 1)]
tree = [[] for _ in range(N + 1)]
for i, (a, b) in enumerate(X):
tree[a].append((b, i))
tree[b].append((a, i))
visited = [False] * (N + 1)
visited[1] = True
color = [0] * (N - 1)
stack = deque()
stack.append((1, 0))
while stack:
u, c = stack.popleft()
tmp = 0
for v, i in tree[u]:
if visited[v]:
continue
tmp += 1
if tmp == c:
tmp += 1
visited[v] = True
color[i] = tmp
stack.append((v, tmp))
print(max(color))
print(*color, sep="\n")
|
import sys
n = input()
a = []
flag = {}
for j in range(1, 14):
flag[('S',j)] = 0
flag[('H',j)] = 0
flag[('C',j)] = 0
flag[('D',j)] = 0
for i in range(n):
temp = map(str, raw_input().split())
a.append((temp[0],temp[1]))
#print a[i][0]
#print a[i][1]
card = ['S', 'H', 'C', 'D']
#print card
for egara in card:
for i in range(n):
if(a[i][0] == egara):
for j in range(1,14):
if(int(a[i][1]) == j):
flag[(egara, j)] = 1
for egara in card:
for j in range(1,14):
if(flag[(egara, j)] == 0):
sys.stdout.write(egara)
sys.stdout.write(' ')
sys.stdout.write(str(j))
print
exit(0)
| 0 | null | 68,873,057,667,920 | 272 | 54 |
n = int(input())
a = [int(i) for i in input().split()]
cnt = [0]*(n+1)
cnt[-1] = 3
mod = 1000000007
ans = 1
for i in range(n):
ans *= cnt[a[i]-1]
ans %= mod
cnt[a[i]-1] -= 1
cnt[a[i]] += 1
print(ans)
|
# 解説を見て解き直し
N, K = [int(x) for x in input().split()]
ranges = [tuple(int(x) for x in input().split()) for _ in range(K)]
ranges.sort()
p = 998244353
dp = [0] * (N + 1)
dpsum = [0] * (N + 1)
dp[1] = 1
dpsum[1] = 1
for i in range(2, N + 1):
for l, r in ranges:
rj = i - l
lj = max(1, i - r) # 1以上
if rj <= 0: continue
dp[i] += dpsum[rj] - dpsum[lj - 1]
dp[i] %= p
dpsum[i] = dpsum[i - 1] + dp[i]
dpsum[i] %= p
print(dp[N])
| 0 | null | 66,419,702,769,540 | 268 | 74 |
from math import pi # 円周率
# 浮動小数点数で読む
r = float(input())
area = r * r * pi
cir =(r+r) * pi
print(f'{(area):.6f} {(cir):.6f}')
|
import math
r = float(input())
print('%.5f' % (r * r * math.pi), '%.5f' % (2 * math.pi * r))
| 1 | 647,941,020,832 | null | 46 | 46 |
#coding: UTF-8
l = raw_input().split()
l.sort()
a = int(l[0])
b = int(l[1])
c = int(l[2])
print "%d %d %d" %(a, b, c)
|
s=input()
x=list(map(int,s.split()))
x.sort()
print("%d %d %d"%tuple(x))
| 1 | 417,094,472,480 | null | 40 | 40 |
H, W = map(int, input().split())
if (H*W) % 2 == 0:
if H == 1 or W == 1:
res = 1
else:
res = int(H * W / 2)
else:
if H == 1 or W == 1:
res = 1
else:
res = int(H * (W//2) + int(H/2) + 1)
print('{0:d}'.format(res))
|
H, W = map(int, input().split())
ans = 0
x = H * W
if H == 1 or W == 1:
ans = 1
elif x % 2 == 0:
ans = x // 2
else:
ans = (x // 2) + 1
print(ans)
| 1 | 51,042,678,988,308 | null | 196 | 196 |
n = int(input())
print(n * n * n)
|
def main():
X, Y = map(int, input().split())
print(gcd(X, Y))
def gcd(a, b):
if a < b:
a, b = b, a
r = a % b
if r == 0:
return b
else:
a = b
b = r
return gcd(a, b)
main()
| 0 | null | 146,560,727,092 | 35 | 11 |
from collections import deque
h, w = list(map(int, input().split()))
grid = [input() for _ in range(h)]
ans = [[10000]*w for _ in range(h)]
ans[0][0] = 0 if grid[0][0] == "." else 1
queue = deque([(0, 0)])
while len(queue) > 0:
x, y = queue.popleft()
for xo, yo in [(0, 1), (1, 0)]:
xnext, ynext = x+xo, y+yo
if xnext >= w or ynext >= h:
continue
if grid[y][x] == "." and grid[ynext][xnext] == "#":
if ans[y][x] + 1 < ans[ynext][xnext]:
ans[ynext][xnext] = ans[y][x] + 1
queue.append((xnext, ynext))
else:
if ans[y][x] < ans[ynext][xnext]:
ans[ynext][xnext] = ans[y][x]
queue.append((xnext, ynext))
print(ans[h-1][w-1])
|
n=int(input())
arr = [[False for i in range(13)] for j in range(4)]
for count in range(n):
code = input().split()
if (code[0]=="S"):
arr[0][int(code[1])-1]=True
elif (code[0]=="H"):
arr[1][int(code[1])-1]=True
elif(code[0]=="C"):
arr[2][int(code[1])-1]=True
else:
arr[3][int(code[1])-1]=True
for i in range(4):
if(i==0):
img="S"
elif(i==1):
img="H"
elif(i==2):
img="C"
else:
img="D"
for j in range(13):
if(arr[i][j]==False):
print(img+" "+str(j+1))
| 0 | null | 25,004,750,563,118 | 194 | 54 |
n=int(input())
dic={}
for i in range(n):
s=input()
if s not in dic:
dic[s]=1
else:
dic[s]+=1
dic = sorted(dic.items(),key=lambda x:x[0])
dic = sorted(dic,key=lambda x:x[1],reverse=True)
ma=dic[0][1]
for i,v in dic:
if v!=ma:
break
else:
print(i)
|
a,b = map(str,input().split())
As = a * int(b)
Bs = b * int(a)
if As<Bs:
print(As)
else:
print(Bs)
| 0 | null | 77,065,310,806,290 | 218 | 232 |
from time import time
from random import random
limit_secs = 2
start_time = time()
D = int(input())
c = list(map(int, input().split()))
s = [list(map(int, input().split())) for _ in range(D)]
def calc_score(t):
score = 0
S = 0
last = [-1] * 26
for d in range(len(t)):
S += s[d][t[d]]
last[t[d]] = d
for i in range(26):
S -= c[i] * (d - last[i])
score += max(10 ** 6 + S, 0)
return score
def solution1():
return [i % 26 for i in range(D)]
def solution2():
t = None
score = -1
for i in range(26):
nt = [(i + j) % 26 for j in range(D)]
if calc_score(nt) > score:
t = nt
return t
#def solution3():
# t = []
# for _ in range(D):
# for i in range(26):
def optimize0(t):
return t
def optimize1(t):
score = calc_score(t)
while time() - start_time + 0.15 < limit_secs:
d = int(random() * D)
q = int(random() * 26)
old = t[d]
t[d] = q
new_score = calc_score(t)
if new_score < score:
t[d] = old
else:
score = new_score
return t
t = solution2()
t = optimize0(t)
print('\n'.join(str(e + 1) for e in t))
|
# -*- coding: utf-8 -*-
N = int(raw_input())
A = map(str, raw_input().split())
B = A[:]
for i in range(N):
for j in range(N-1, i, -1):
if int(A[j][1]) < int(A[j-1][1]):
A[j], A[j-1] = A[j-1], A[j]
bubble = " ".join(A)
for i in range(N):
minj = i
for j in range(i, N):
if int(B[j][1]) < int(B[minj][1]):
minj = j
B[i], B[minj] = B[minj], B[i]
select = " ".join(B)
print bubble
print "Stable"
print select
if bubble == select:
print "Stable"
else:
print "Not stable"
| 0 | null | 4,914,565,215,450 | 113 | 16 |
N,M = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(M)]
n = -1
for x in range(1000):
x = str(x)
if len(x)!=N:continue
ind = 0
for i in range(M):
s,c = A[i]
if x[int(s)-1]!=str(c):
ind=1
break
if ind==0:
n = x
break
print(n)
|
a,b=map(int,input().split())
m=min(a,b)
kouyakusuu=1
for i in range(1,m+1):
if a%i==0 and b%i==0:
kouyakusuu=i
print(a*b//kouyakusuu)
| 0 | null | 87,271,732,070,592 | 208 | 256 |
def resolve():
n=int(input())
ans=0
for i in range(1,n):
ans+=(n-1)//i
print(ans)
resolve()
|
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import Counter
h,w,m=nii()
h_bomb=[0 for i in range(h)]
w_bomb=[0 for i in range(w)]
l=set()
for i in range(m):
th,tw=nii()
th-=1
tw-=1
h_bomb[th]+=1
w_bomb[tw]+=1
l.add((th,tw))
h_max=max(h_bomb)
w_max=max(w_bomb)
h_cand=[]
w_cand=[]
for i in range(len(h_bomb)):
if h_bomb[i]==h_max:
h_cand.append(i)
for i in range(len(w_bomb)):
if w_bomb[i]==w_max:
w_cand.append(i)
for i in h_cand:
for j in w_cand:
if (i,j) not in l:
print(h_max+w_max)
exit()
print(h_max+w_max-1)
| 0 | null | 3,621,900,297,322 | 73 | 89 |
N = int(input())
#1 is dividable by all
#-> sum = 1 + 2 + .. + N = (N+1)*N//2
ans = (N+1)*N//2
for num in range(2, N+1):
for tt in range(N//num+1):
ans += num*tt
print(ans)
|
n,m=map(int,input().split())
if n%2==1:
for i in range(m):
print(n-i-1,i+1)
else:
cnt=1
for i in range(m):
if i%2==0:
print(n//4-i//2,n//4-i//2+cnt)
else:
print(n//2+n//4-i//2,n//2+n//4-i//2+cnt)
cnt+=1
| 0 | null | 19,920,403,337,060 | 118 | 162 |
import math
H,W,N = [int(input()) for i in range(3)]
print(min(math.ceil(N/H),math.ceil(N/W)))
|
A,B=map(int,input().split())
ma,mi=0,0
ma=max(A,B)
mi=min(A,B)
if A%B==0 or B%A==0:
print(ma)
else :
for i in range(2,ma+1):
if (ma*i)%mi==0:
print(ma*i)
break
i+=(mi-1)
| 0 | null | 101,215,381,290,618 | 236 | 256 |
def inpl(): return list(map(int, input().split()))
print((int(input())-1)//2)
|
n = int(input())
iteration = n
ex = 0
count = 0
for i in range(1,n):
ex = iteration-i
#print(ex)
if ex <=i:
break
else:
count += 1
print(count)
| 1 | 152,990,674,809,600 | null | 283 | 283 |
N=int(input())
s=list()
t=list()
st=[]
for i in range(N):
st.append(input().split())
X=input()
ans=0
count=False
for j in range(N):
if count:
ans+=int(st[j][1])
if st[j][0]==X:
count=True
print(ans)
|
n = int(input())
s = []
t = []
for i in range(n):
ss,tt = map(str,input().split())
s.append(ss)
t.append(tt)
x = input()
ans = 0
for i in range(n-1):
if ans != 0:
ans += int(t[i+1])
elif s[i] == x:
ans += int(t[i+1])
print(ans)
| 1 | 97,350,230,120,192 | null | 243 | 243 |
from collections import deque
n,u,v=map(int,input().split())
g=[set([]) for _ in range(n+1)]
for i in range(n-1):
a,b=map(int,input().split())
g[a].add(b)
g[b].add(a)
leaf=[]
for i in range(1,n+1):
if(len(g[i])==1):
leaf.append(i)
d_u=[-1 for _ in range(n+1)]
d_v=[-1 for _ in range(n+1)]
def bfs(start,d):
d[start]=0
q=deque([start])
while(len(q)>0):
qi=q.popleft()
di=d[qi]
next_qi=g[qi]
for i in next_qi:
if(d[i]==-1):
d[i]=di+1
q.append(i)
return d
d_u=bfs(u, d_u)
d_v=bfs(v, d_v)
if(u in leaf and list(g[u])[0]==v):
print(0)
else:
ans=0
for li in leaf:
if(d_u[li]<d_v[li]):
ans=max(ans,d_v[li]-1)
print(ans)
|
def miller_rabin(n):
""" primality Test
if n < 3,825,123,056,546,413,051, it is enough to test
a = 2, 3, 5, 7, 11, 13, 17, 19, and 23.
Complexity: O(log^3 n)
"""
if n == 2: return True
if n <= 1 or not n&1: return False
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
d = n - 1
s = 0
while not d&1:
d >>= 1
s += 1
for prime in primes:
if prime >= n: break
x = pow(prime, d, n)
if x == 1: break
for r in range(s):
if x == n - 1: break
if r + 1 == s: return False
x = x * x % n
return True
N = int(input())
print(sum(1 for _ in range(N) if miller_rabin(int(input()))))
| 0 | null | 58,602,048,182,372 | 259 | 12 |
n = int(input())
a = list(map(int, input().split()))
ans = 0
a.sort(reverse=True)
for i in range(n-1):
ii = int((i+(i%2))/2)
ans += a[ii]
print(ans)
|
# import sys
# input = sys.stdin.readline
import itertools
import collections
from decimal import Decimal
from functools import reduce
import heapq
def main():
n = int(input())
a = input_list()
aa = a + a
aa.sort(reverse=True)
ans = 0
for i in range(1, n):
ans += aa[i]
print(ans)
def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
def bfs(H, W, black_cells, dist):
d = 0
while black_cells:
h, w = black_cells.popleft()
d = dist[h][w]
for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
new_h = h + dy
new_w = w + dx
if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
continue
if dist[new_h][new_w] == -1:
dist[new_h][new_w] = d + 1
black_cells.append((new_h, new_w))
return d
def input_list():
return list(map(int, input().split()))
def input_list_str():
return list(map(str, input().split()))
if __name__ == "__main__":
main()
| 1 | 9,177,945,819,110 | null | 111 | 111 |
def coin(larger=False, single=False):
"""
ナップサックに入れる重さが W 丁度になる時の価値の最小値
:param larger: False = (重さ = W)の時の最小価値
True = (重さ =< W)の時の最小価値
:param single: False = 重複あり
dp[weight <= W+1] = 重さを固定した時の最小価値
dp[W+1] = 重さがWより大きい時の最小価値
"""
W2 = W + 1 # dp[W+1] に W より大きい時の全ての場合の情報を持たせる
dp_max = float("inf") # 総和価値の最大値
dp = [dp_max] * (W2 + 1)
dp[0] = 0 # 重さ 0 の時は価値 0
for item in range(N):
if single:
S = range(W2, weight_list[item] - 1, -1)
else:
S = range(W2)
for weight in S:
dp[min2(weight + weight_list[item], W2)] = min2(dp[min2(weight + weight_list[item], W2)], dp[weight] + cost_list[item])
if larger:
return min(dp[w] for w in range(W, W2+1))
else:
return dp[W]
#######################################################################################################
import sys
input = sys.stdin.readline
def max2(x, y):
return x if x > y else y
def min2(x, y):
return x if x < y else y
W, N = map(int, input().split()) # N: 品物の種類 W: 重量制限
cost_list = []
weight_list = []
for _ in range(N):
""" cost と weight が逆転して入力されている場合有り """
weight, cost = map(int, input().split())
cost_list.append(cost)
weight_list.append(weight)
print(coin(larger=True, single=False))
|
point_a,point_b = 0,0
for i in range(int(input())):
k =[]
a,b = input().split()
k = [[i,j] for i,j in zip(a,b) if i != j]
if k == []:
if len(a) < len(b):
point_b+=3
elif len(a) > len(b):
point_a += 3
else:
point_a+=1
point_b+=1
elif ord(k[0][0]) < ord(k[0][1]):
point_b += 3
else :
point_a += 3
print(point_a,point_b)
| 0 | null | 41,344,784,427,440 | 229 | 67 |
n = int(input())
debt = 100000
for i in range(n):
debt = debt * 1.05
round = debt % 1000
if round != 0:
debt = (debt // 1000 + 1) * 1000
print(int(debt))
|
import bisect,collections,copy,heapq,itertools,math,string
import sys
def S(): return sys.stdin.readline().rstrip()
def M(): return map(int,sys.stdin.readline().rstrip().split())
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LS(): return list(sys.stdin.readline().rstrip().split())
N = I()
d = LI()
ans = 0
l = list(itertools.combinations(d,2))
for i, j in l:
ans += i*j
print(ans)
| 0 | null | 84,091,610,590,392 | 6 | 292 |
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7
def resolve():
D = int(input())
C = list(map(int, input().split()))
S = [list(map(int, input().split())) for _ in range(D)]
T = list(int(input()) for _ in range(D))
sat = 0
last = [0] * 26
for d in range(D):
t = T[d] - 1
sat += S[d][t]
dsat = 0
for i in range(26):
if i == t:
continue
dsat += C[i] * ((d + 1) - last[i])
last[t] = d + 1
sat -= dsat
print(sat)
if __name__ == '__main__':
resolve()
|
N,R=map(int,input().split())
if 10<=N:
print(R)
else:
a=R+100*(10-N)
print(a)
| 0 | null | 36,908,726,879,668 | 114 | 211 |
n=int(input())
a=[]
while n>26:
n=n-1
a.append(chr(ord('a') + n%26))
n=n//26
n=n-1
a.append(chr(ord('a') + n%26))
a.reverse()
print("".join(a))
|
n = int(input())
class Node:
def __init__(self, idd, neighbors):
self.idd = idd
self.neighbors = neighbors
self.foundAt = 0
self.completeAt = 0
def __repr__(self):
return "{0} {1} {2}".format(self.idd, self.foundAt, self.completeAt)
Nodes = [None] * n
for i in range(n):
row = [int(tt) for tt in input().split()]
Nodes[row[0]-1] = Node(row[0], [ row[j + 2] for j in range(row[1])])
def depthSearch(Nodes):
stack = [Nodes[0]]
time = 2
current = stack[-1]
current.foundAt = 1
while len(stack) > 0 or any([node.foundAt==0 for node in Nodes]):
if(len(stack)==0):
newStart = [node for node in Nodes if node.foundAt==0][0]
newStart.foundAt = time
stack.append(newStart)
time += 1
current = stack[-1]
if(len(current.neighbors) > 0):
next_n = Nodes[current.neighbors.pop(0)-1]
if(next_n.foundAt != 0):
continue
next_n.foundAt = time
stack.append(next_n)
else:
current.completeAt = time
stack.pop(-1)
time += 1
return Nodes
Nodes = depthSearch(Nodes)
for node in Nodes:
print(node)
| 0 | null | 5,948,184,201,320 | 121 | 8 |
from sys import stdin
from collections import deque
n = int(stdin.readline())
g = [None] * n
for _ in range(n):
u, _, *cs = [int(s) for s in stdin.readline().split()]
g[u-1] = [c - 1 for c in cs]
ds = [-1] * n
v = [False] * n
v[0] = True
q = deque([(0, 0)])
while len(q):
u, d = q.popleft()
ds[u] = d
for c in g[u]:
if not v[c]:
v[c] = True
q.append((c, d + 1))
for u, d in enumerate(ds):
print(u + 1, d)
|
def main():
n = int(raw_input())
data = {}
for a in xrange(1,n):
b = n-a
if a == b:
continue
data[(min(a,b), max(a, b))] = 1
print(len(data.keys()))
main()
| 0 | null | 76,908,805,907,012 | 9 | 283 |
a=[]
for i in range(10):
a.append(input())
a.sort()
a=a[::-1]
a=a[:3]
print(a[0])
print(a[1])
print(a[2])
|
m = []
f = []
r = []
while(1):
a,b,c = map(int,raw_input().split())
if a == -1 and b == -1 and c == -1:
break
else:
m.append(a)
f.append(b)
r.append(c)
for i in range(len(m)):
if m[i] == -1 or f[i] == -1:
print "F"
elif m[i] + f[i] >= 80:
print "A"
elif m[i] + f[i] >= 65:
print "B"
elif m[i] + f[i] >= 50 or r[i] >= 50:
print "C"
elif m[i] + f[i] >= 30:
print "D"
else:
print "F"
| 0 | null | 614,359,768,992 | 2 | 57 |
n = int(input())
nums = list(map(int, input().split(' ')))
rnums = []
for i in range(n):
rnums.append(nums[-1*i -1])
print(' '.join([str(x) for x in rnums]))
|
n = input().split()
x = int(n[0])
y = int(n[1])
if x < y:
bf = x
x = y
y = bf
while y > 0:
r = x % y
x = y
y = r
print(str(x))
| 0 | null | 498,602,309,170 | 53 | 11 |
import sys
def main():
s,w = list(map(int,(input().split())))
if s<=w:
print('unsafe')
sys.exit()
else:
print('safe')
sys.exit()
if __name__ == '__main__':
main()
|
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
S,W = map(int, readline().split())
if S > W:
print('safe')
else:
print('unsafe')
| 1 | 29,245,502,348,324 | null | 163 | 163 |
def sol(s, p):
n = len(s)
cnt = 0
if p == 2 or p == 5:
for i in range(n):
if (s[i] % p == 0):
cnt += i + 1
else:
pre = [0] * (n+2)
pre[n+1] = 0
b = 1
for i in range(n, 0, -1):
pre[i] = (pre[i+1] + s[i-1] * b) % p
b = (b * 10) % p
rec = [0] * p
rec[0] = 1
for i in range(n, 0, -1):
cnt += rec[pre[i]]
rec[pre[i]] += 1
return cnt
if __name__ == "__main__":
n, p = map(int, input().split())
s = input()
print (sol([int(i) for i in s], p))
|
from collections import deque
s = list(input())
moji = deque(s)
is_forward = True
q = int(input())
for i in range(q):
query = input()
if query[0] == "1":
is_forward = is_forward ^ 1
elif query[0] == "2":
_, f, c = query.split()
f = int(f)
f %= 2
is_end = f ^ is_forward
if is_end:
moji.append(c)
else:
moji.appendleft(c)
if is_forward == False:
moji = list(moji)[::-1]
print("".join(moji))
| 0 | null | 57,699,882,223,360 | 205 | 204 |
import sys
def input(): return sys.stdin.readline().rstrip()
class Sieve: #区間[2,n]の値の素因数分解
def __init__(self,n=1):
self.primes=[]
self.f=[0]*(n+1) #ふるい(素数ならその値)
self.f[0]=self.f[1]=-1
for i in range(2,n+1): #素数リスト作成
if self.f[i]: continue
self.primes.append(i)
self.f[i]=i
for j in range(i*i,n+1,i):
if not self.f[j]:
self.f[j]=i # 最小の素因数を代入
def is_prime(self, x):
return self.f[x]==x
def prime_fact(self,x): # 素因数分解の昇順リスト, {2:p,3:q,5:r,...}
fact_dict=dict()
while x!=1:
p=self.f[x]
fact_dict[p]=fact_dict.get(p,0)+1
x//=self.f[x]
return fact_dict
def main():
n=int(input())
A=list(map(int,input().split()))
mod=10**9+7
p_lis={}
Prime=Sieve(10**6+5)
for a in A:
f=Prime.prime_fact(a)
#print(f)
for key in f:
p_lis[key]=max(p_lis.get(key,0),f[key])
lcm=1
#print(p_lis)
for key in p_lis:
lcm=(lcm*pow(key,p_lis[key],mod))%mod
ans=0
#print(lcm)
for a in A:
b=lcm*pow(a,mod-2,mod)%mod
ans=(ans+b)%mod
print(ans)
if __name__ == '__main__':
main()
|
n = int(input())
num_AC = 0
num_WA = 0
num_TLE = 0
num_RE = 0
for i in range(n):
i = input()
if i == "AC":
num_AC += 1
elif i == "WA":
num_WA += 1
elif i == "TLE":
num_TLE += 1
elif i == "RE":
num_RE += 1
print("AC x " + str(num_AC))
print("WA x " + str(num_WA))
print("TLE x " + str(num_TLE))
print("RE x " + str(num_RE))
| 0 | null | 48,437,854,439,042 | 235 | 109 |
import numpy as np
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
n, t = map(int, input().split())
dp = np.zeros(t,dtype=int)
food = []
for _ in range(n):
a, b = map(int, input().split())
food.append([a, b])
food.sort(key=lambda x: x[0]*-1)
for j in range(n):
a, b = food[j][0], food[j][1]
a=min(a,t)
dptmp=np.zeros(t,dtype=int)
dptmp[a:] = np.maximum(dp[a:],dp[:-a]+b)
dptmp[:a] = np.maximum(np.full(a,b,dtype=int), dp[:a])
dp=dptmp
print(dp[-1])
if __name__ == '__main__':
main()
|
import sys
input = sys.stdin.readline
n, t = map(int, input().split())
DISHES = [(0, 0)]
for _ in range(n):
a, b = map(int, input().split())
DISHES.append((a, b))
DISHES.sort()
DP = [[0] * (t + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
a, b = DISHES[i]
for j in range(1, t + 1):
if j - a < 0:
DP[i][j] = DP[i - 1][j]
else:
DP[i][j] = max(DP[i - 1][j], DP[i - 1][j - a] + b)
answer = 0
for k in range(1, n + 1):
answer = max(answer, DP[k - 1][t - 1] + DISHES[k][1])
print(answer)
| 1 | 152,089,017,367,760 | null | 282 | 282 |
A,B,C,D=map(int,input().split())
ans=0
while 1:
C-=B
if C<=0:
ans=1
break
A-=D
if A<=0:
break
if ans==1:
print("Yes")
else:
print("No")
|
x, k, d = map(int, input().split())
ax = abs(x)
n = ax // d
if n >= k:
ans = ax - k*d
else:
a = ax - n*d
if (k - n) % 2:
ans = abs(a - d)
else:
ans = abs(a)
print(ans)
| 0 | null | 17,348,265,664,778 | 164 | 92 |
n = int(input())
s = input()
ans = 0
for i in range(n-2):
if s[i:i+3] == "ABC":
ans += 1
print(ans)
|
K=int(input())
l=list(input())
c=0
for i in range(K-2):
if l[i]=="A":
if l[i+1]=="B":
if l[i+2]=="C":
c+=1
print(c)
| 1 | 99,323,100,307,900 | null | 245 | 245 |
import sys
s=0
N=int(input())
if N%2==1:
print(0)
sys.exit()
N=N//2
while True:
N=N//5
s+=N
if N==0:
break
print(s)
|
import math
import sys
readline = sys.stdin.readline
def main():
n = int(readline().rstrip())
if n % 2 == 1:
print(0)
else:
n = n // 2
num = 0
for i in range(1, 100):
num += n // (5 ** i)
print(num)
if __name__ == '__main__':
main()
| 1 | 116,465,846,333,378 | null | 258 | 258 |
import statistics
while True:
n = int(input())
if n == 0:
break
s = map(int, input().split())
print('{:.5f}'.format(statistics.pstdev(s)))
|
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
def input():
return sys.stdin.readline()[:-1]
def ruiseki(lst):
return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
h,w=map(int,input().split())
s=[input() for i in range(h)]
d=deque([[0,0]])
itta=[[float('inf')]*w for i in range(h)]
if s[0][0]=="#":
itta[0][0]=1
else:
itta[0][0]=0
# print(itta)
ans=0
for i in range(h+w-2):
# print(itta)
for j in range(len(d)):
now=d.popleft()
nh,nw=now
cnt=itta[nh][nw]
if nh+1<h:
tmp=cnt
if s[nh][nw]=="." and s[nh+1][nw]=="#":
tmp+=1
if itta[nh+1][nw]==float('inf'):
d.append([nh+1,nw])
itta[nh+1][nw]=min(itta[nh+1][nw],tmp)
if nw+1<w:
tmp=cnt
if s[nh][nw]=="." and s[nh][nw+1]=="#":
tmp+=1
if itta[nh][nw+1]==float('inf'):
d.append([nh,nw+1])
itta[nh][nw+1]=min(itta[nh][nw+1],tmp)
# print(itta)
# for i in range(len(d)):
print(itta[-1][-1])
| 0 | null | 24,871,020,203,612 | 31 | 194 |
time = int(input())
if time != 0:
h = time // 3600
time = time % 3600
m = time // 60
s = time % 60
print(str(h) + ':' + str(m) + ':' + str(s))
else:
print('0:0:0')
|
import sys
n,m=map(int,input().split())
ans=[0]*n
for i in range(m):
s,c=map(int,input().split())
s-=1
if ans[s]!=0 and ans[s]!=c:
print(-1)
sys.exit()
else:
ans[s]=c
if n==3 and m==1 and ans==[0,0,0]:
print(-1)
sys.exit()
if n!=1 and ans[0]==0:
ans[0]=1
for i in range(n):
ans[i]=str(ans[i])
print("".join(ans))
| 0 | null | 30,511,347,469,188 | 37 | 208 |
s = input()
ans = 0
if "RRR" == s:
ans = 3
elif "RR" in s:
ans = 2
elif "R" in s:
ans = 1
print(ans)
|
import sys
def I(): return int(sys.stdin.readline().rstrip())
def S(): return sys.stdin.readline().rstrip()
N = I()
ST = [tuple(map(str,S().split())) for _ in range(N)]
X = S()
ans = 0
for i in range(N):
s,t = ST[i]
ans += int(t)
if s == X:
break
print(sum(int(ST[i][1]) for i in range(N))-ans)
| 0 | null | 51,083,674,784,150 | 90 | 243 |
import sys
input = sys.stdin.readline
#道がない場合、infで初期化したい
inf = 10 ** 13 + 1
#input
n, m, l = list(map(int, input().split()))
way = [[inf for i in range(n)] for j in range(n)]
oil = [[400 for i in range(n)] for j in range(n)]
for i in range(m):
a, b, c, = list(map(int, input().split()))
way[a - 1][b - 1] = c
way[b - 1][a - 1] = c
q = int(input())
query = []
for i in range(q):
query.append(list(map(int, input().split())))
#ワーシャルフロイド法を使い、各道への最短経路を調べる。計算量はO(N**3)
for k in range(n):
for i in range(n):
for j in range(n):
if i == j:
way[i][j] = 0
continue
way[i][j] = min(way[i][j],way[i][k] + way[k][j])
#oilの補給できる回数もワーシャルフロイドで求める。まず、一補給でいけるところに辺を張る
for i in range(n):
for j in range(n):
if i == j:
oil[i][j] = 0
if way[i][j] <= l:
oil[i][j] = oil[j][i] = 1
#の後でワーシャルフロイド
for k in range(n):
for i in range(n):
for j in range(n):
if i == j:
oil[i][j] = 0
continue
oil[i][j] = min(oil[i][j],oil[i][k] + oil[k][j])
for i in range(q):
ans = oil[query[i][0] - 1][query[i][1] - 1] - 1
if way[query[i][0] - 1][query[i][1] - 1] == inf or oil[query[i][0] - 1][query[i][1] - 1] == 400:
ans = -1
print(ans)
|
N, M, L = map(int, input().split())
INF = float('inf')
d1 = [[INF]*N for _ in range(N)]
for _ in range(M):
a, b, c = map(int, input().split())
a -= 1
b -= 1
d1[a][b] = c
d1[b][a] = c
for i in range(N):
d1[i][i] = 0
for k in range(N):
for i in range(N):
for j in range(N):
d1[i][j] = min(d1[i][k] + d1[k][j], d1[i][j])
d2 = [[INF]*N for _ in range(N)]
for i in range(N):
for j in range(N):
if i == j:
d2[i][j] = 0
if d1[i][j] <= L and i != j:
d2[i][j] = 1
for k in range(N):
for i in range(N):
for j in range(N):
d2[i][j] = min(d2[i][k] + d2[k][j], d2[i][j])
Q = int(input())
for _ in range(Q):
s, t = map(int, input().split())
s -= 1
t -= 1
if d2[s][t] == INF:
print(-1)
else:
print(d2[s][t]-1)
| 1 | 173,376,700,577,640 | null | 295 | 295 |
n,x,m = map(int, input().split())
be = x % m
ans = be
memo = [[0,0] for i in range(m)]
am = [be]
memo[be-1] = [1,0] #len-1
for i in range(n-1):
be = be**2 % m
if be == 0:
break
elif memo[be-1][0] == 1:
kazu = memo[be-1][1]
l = len(am) - kazu
syou = (n-i-1) // l
amari = (n-i-1)%l
sum = 0
for k in range(kazu, len(am)):
sum += am[k]
ans = ans + syou*sum
if amari > 0:
for j in range(kazu,kazu + amari):
ans += am[j]
break
else:
ans += be
am.append(be)
memo[be-1][0] = 1
memo[be-1][1] = len(am) -1
print(ans)
|
def resolve():
N = int(input())
S = list(input())
ans = [chr(((ord(s)-65+N)%26)+65) for s in S]
print("".join(ans))
if '__main__' == __name__:
resolve()
| 0 | null | 68,421,538,547,792 | 75 | 271 |
#coding:utf-8
n = int(input())
numbers = list(map(int, input().split()))
def selectionSort(ary):
count = 0
for i in range(len(ary)):
minj = i
for j in range(i, len(ary)):
if ary[minj] > ary[j]:
minj = j
if minj != i:
ary[minj], ary[i] = ary[i], ary[minj]
count += 1
return (ary, count)
result = selectionSort(numbers)
print(*result[0])
print(result[1])
|
def selection_sort(A, n):
count = 0
for i in range(n-1):
minj = i
for j in range(i, n):
if A[j] < A[minj]:
minj = j
if i != minj:
A[i], A[minj] = A[minj], A[i]
count += 1
print(' '.join(map(str, A)))
print(count)
if __name__ == '__main__':
n = int(input())
A = list(map(int, input().split()))
selection_sort(A, n)
| 1 | 19,546,109,120 | null | 15 | 15 |
import math
n = int(input())
m = math.floor(math.sqrt(n)) + 1
ans = 10**12
for a in range(1,m+1):
b = n/a
if b.is_integer():
move = a+b-2
else:
continue
ans = min(ans,move)
print(int(ans))
|
N = int(input())
ans = N - 1
for i in range(2, int((N ** 0.5) + 1)):
if N % i == 0:
j = N // i
m = i + j - 2
ans = min(ans, m)
print(ans)
| 1 | 161,445,938,032,512 | null | 288 | 288 |
S = input()
ans = 0
flag = False #繰り上がりありならTrue
flag2 = False #前が5ならTrue
for k in range(len(S)):
n = int(S[-k-1])
if flag2:
if n < 5:
flag = False
else:
flag = True
if flag:
n += 1
if n == 5:
ans += 5
flag2 = True
flag = False
elif n < 5:
ans += n
flag2 = False
flag = False
else:
ans += 10-n
flag2 = False
flag = True
if flag:
ans += 1
print(ans)
|
N = input()
over = 1
eq = 0
for n in map(int, N):
o = min(eq + n + 1, over + (10 - n) - 1)
e = min(eq + n, over + (10 - n))
over = o
eq = e
print(eq)
| 1 | 71,070,085,046,572 | null | 219 | 219 |
def inpl(): return list(map(int, input().split()))
print((int(input())-1)//2)
|
#import numpy as np
#from numpy import*
#from scipy.sparse.csgraph import shortest_path #shortest_path(csgraph=graph) # dijkstra# floyd_warshall
#from scipy.sparse import csr_matrix
from collections import* #defaultdict Counter deque appendleft
from fractions import gcd
from functools import* #reduce
from itertools import* #permutations("AB",repeat=2) combinations("AB",2) product("AB",2) groupby accumulate
from operator import mul,itemgetter
from bisect import* #bisect_left bisect_right
from heapq import* #heapify heappop heappushpop
from math import factorial,pi
from copy import deepcopy
import sys
sys.setrecursionlimit(10**8)
#input=sys.stdin.readline
def main():
n=int(input())
ans=0
for i in range(1,n):
if (i!=n-i and i<n-i):
ans+=1
elif i>n-1:
break
print(ans)
if __name__ == '__main__':
main()
| 1 | 153,164,213,565,568 | null | 283 | 283 |
from collections import deque
n = int(input())
G = []
for _ in range(n):
tmp = list(map(int, input().split()))
u = tmp.pop(0)
k = tmp.pop(0)
t = []
for i in range(k):
a = tmp.pop(0)
t.append(a-1)
G.append(t)
dist = [-1]*n
dist[0] = 0
que = deque()
que.append(0)
while que:
v = que.popleft()
for nv in G[v]:
if dist[nv] != -1:
continue
dist[nv] = dist[v] + 1
que.append(nv)
for i in range(n):
print(i+1, dist[i])
|
import collections
N = int(input())
UKV = [list(map(int,input().split())) for _ in range(N)]
dist = [-1]*N
que = collections.deque()
G = [[]]*N
for ukv in UKV:
G[ukv[0]-1] = sorted(ukv[2:])
dist[0] = 0
que.append(1)
while len(que) != 0:
v = que.popleft()
for nv in G[v-1]:
if dist[nv-1] != -1:
continue
dist[nv-1] = dist[v-1] + 1
que.append(nv)
for i,d in enumerate(dist):
print(i+1, d)
| 1 | 4,726,567,368 | null | 9 | 9 |
N = int(input())
inf = 10 ** 6
graph = [[] for i in range(N)]
visited = [0 for i in range(N)]
time = [[inf,inf] for i in range(N)]
for i in range(N):
a = list(map(int,input().split()))
a = list(map(lambda x: x - 1,a))
k,n = a[0],a[1]
if n >= 0:
graph[k] = a[2:]
con = 0
def dfs(cur,par):
#print("v",visited)
global con
visited[cur] = 1
con += 1
time[cur][0] = min(time[cur][0],con)
#print("cur1,con1",cur,con)
if (graph[cur] == [] or graph[cur] == [cur]):
visited[cur] = 1
time[cur][0] = min(con,time[cur][0])
con += 1
time[cur][1] = min(con,time[cur][1])
#print("curif,conif",cur,con)
return
else:
for chi in graph[cur]:
if visited[chi] == 0:
dfs(chi,cur)
if any(visited[i] == 0 for i in graph[cur]):
continue
else:
con += 1
time[cur][1] = min(con,time[cur][1])
#print("cur2,con2",cur,con)
return
dfs(0,-1)
if any([i == 0 for i in visited]):
f = visited.index(0)
dfs(f,f - 1)
for i,t in enumerate(time):
print(i + 1 ,*t)
|
T1,T2=map(int,input().split())
A1,A2=map(int,input().split())
B1,B2=map(int,input().split())
OU=T1*(A1-B1)
HUKU=T2*(A2-B2)
TOTAL=OU+HUKU
if TOTAL==0:
print("infinity")
elif (OU>0 and TOTAL>0) or (OU<0 and TOTAL<0):
print(0)
elif (OU>0 and TOTAL*(-1)>OU) or (OU<0 and TOTAL*(-1)<OU):
print(1)
else:
K=int(OU/TOTAL)*-1
if (OU%TOTAL)==0:
print(K*2)
else:
print(K*2+1)
| 0 | null | 65,661,911,174,072 | 8 | 269 |
import sys
n = int(raw_input())
R = [int(raw_input()) for i in xrange(n)]
minimum = sys.maxint
maximum = -sys.maxint - 1
for x in R:
p = x - minimum
if maximum < p:
maximum = p
if minimum > x:
minimum = x
print maximum
|
n = input()
R = [input() for i in range(n)]
max = R[1] - R[0]
min = R[0]
for i in range(1,n):
if R[i] - min > max:
max = R[i] - min
if R[i] < min:
min = R[i]
print max
| 1 | 13,131,745,130 | null | 13 | 13 |
n = input()
if n[0] == '7' or n[1] == '7' or n[2] == '7':
ans = 'Yes'
else:
ans = 'No'
print(ans)
|
length = raw_input()
a, b = length.split()
a = int(a)
b = int(b)
if a < b:
print "a < b"
elif a == b:
print "a == b"
elif a > b:
print "a > b"
| 0 | null | 17,241,613,989,084 | 172 | 38 |
K = int(input())
S = input()
if K >= len(S):
print(S)
elif K < len(S):
print(S[:K] + "...")
|
K=int(input())
S=input()
print(S if len(S)<=K else S[:K]+"...")
| 1 | 19,810,317,144,800 | null | 143 | 143 |
data = []
da = []
a = input().split()
a[0] = int(a[0])
a[1] = int(a[1])
for i in range(a[0]):
b = input().split()
for j in range(a[1]):
b[j] = int(b[j])
data.append(b)
for i in range(len(data)):
data[i].append(sum(data[i]))
for i in range(a[1]+1):
da.append(0)
for i in range(a[0]):
for j in range(a[1]+1):
da[j] += data[i][j]
data.append(da)
for i in data:
for j in range(len(i)):
i[j] = str(i[j])
for i in data:
print(" ".join(i))
|
height,width=map(int,input().split())
A=[]
for i in range(height):
A.append([int(j) for j in input().split()])
for i in range(height):
print(' '.join(map(str,A[i])),str(sum(A[i])))
B=[]
C=[0 for _ in range(width)]
for i in range(width):
for j in range(height):
s=0
s+=A[j][i]
B.append(s)
C[i]=sum(B)
B=[]
print(' '.join(map(str,C)),str(sum(C)))
| 1 | 1,336,869,608,580 | null | 59 | 59 |
import sys
alist = list('abcdefghijklmnopqrstuvwxyz')
r = {}
for al in alist:
r[al] = 0
line = sys.stdin.read().lower()
for i in range(len(line)):
if line[i] in r.keys():
r[line[i]] += 1
for k,v in r.items():
print("{} : {}".format(k, v))
|
N, R = map(int, input().split())
ans = R + 100*max(0, (10-N))
print(ans)
| 0 | null | 32,624,821,396,410 | 63 | 211 |
if __name__ == '__main__':
N, K = map(int, input().split())
H = list(map(int, input().split()))
H = sorted(H)[::-1]
cnt = 0
for h in H:
if K>0:
K -= 1
else:
cnt += h
print(cnt)
|
def solve():
N, K = map(int, input().split())
H = list(map(int, input().split()))
if K>=N:
return 0
H.sort()
ans = sum(H[:N-K])
return ans
print(solve())
| 1 | 79,233,975,742,180 | null | 227 | 227 |
import math
h = int(input())
num = math.log(h,2)
num = int(num)
ans = 0
for i in range(num+1):
ans += 2**i
print(ans)
|
a = input()
print(a[0] + a[1] + a[2])
| 0 | null | 47,551,376,664,220 | 228 | 130 |
fib = [1]*100
for i in range(2,100):
fib[i] = fib[i-1] + fib[i-2]
print(fib[int(input())])
|
N,K = map(int,input().split())
A = list(map(int, input().split()))
F = list(map(int, input().split()))
if sum(A) <= K:
print(0)
exit()
A.sort()
F.sort(reverse=True)
def check(x):
k = 0
for a,f in zip(A, F):
k += max(0, a-(x//f))
return k <= K
# AをX以下にできるか??
ng,ok = 0, 10**18+1
while ok-ng > 1:
x = (ok+ng)//2
if check(x):
ok = x
else:
ng = x
print(ok)
| 0 | null | 82,751,553,008,312 | 7 | 290 |
pi = 3.14159265358
r = input()
r = int(r)
l = 2*r* pi
print(l)
|
from math import pi
print(2 * pi * int(input()), end='\n')
| 1 | 31,469,920,399,318 | null | 167 | 167 |
import numpy as np
N = int(input())
def divisor(N):
x = np.arange(1, int(N**(1/2))+1, dtype=np.int64)
div = set(x[N % x == 0])
return div | set(N // x for x in div)
cand = divisor(N) | divisor(N - 1)
def test(N, K):
if K == 1:
return False
while N % K == 0:
N //= K
return N % K == 1
answer = sum(test(N, d) for d in cand)
print(answer)
|
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
# d = m - k[i] - k[j]
# if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも!!
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
def readInts():
return list(map(int,input().split()))
def main():
n = int(input())
# 一番大きいものは何か、それを保存してdfs
def dfs(cnt, s):
if cnt == n:
print(s)
return
biggest = 'a'
c = 0
while c < len(s):
if s[c] == biggest:
biggest = chr(ord(biggest)+1)
c += 1
else:
c += 1
for i in range(0,ord(biggest) - ord('a') + 1):
sc = chr(ord('a')+i)
s += sc
dfs(cnt + 1, s)
s = s[:-1]
dfs(0,"")
if __name__ == '__main__':
main()
| 0 | null | 46,899,276,366,098 | 183 | 198 |
n = int(input())
print(sum(i for i in range(1, n + 1) if i % 3 != 0 and i % 5 != 0))
|
a = input()
s = a[0],a[1],a[2]
print("".join(s))
| 0 | null | 24,797,453,476,220 | 173 | 130 |
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7
def resolve():
T1, T2 = map(int, input().split())
A1, A2 = map(int, input().split())
B1, B2 = map(int, input().split())
P = (A1 - B1) * T1
Q = (A2 - B2) * T2
if P > 0:
P *= -1
Q *= -1
if P + Q < 0:
print(0)
elif P + Q == 0:
print("infinity")
else:
S = (-P) // (P + Q)
T = (-P) % (P + Q)
if T != 0:
print(S * 2 + 1)
else:
print(S * 2)
if __name__ == '__main__':
resolve()
|
def maximum_volume():
"""
立方体に近いほど体積が大きくなる
"""
# 入力
L = int(input())
# 処理
one_side = L / 3
# 体積
return one_side ** 3
result = maximum_volume()
print(result)
| 0 | null | 89,115,998,111,140 | 269 | 191 |
N = int(input())
def resolve():
a = 7
for i in range(1,N+1):
if a % N == 0:
return i
a = (a * 10 + 7) % N
return -1
ans = resolve()
print(ans)
|
K = int(input())
ai_1 = 0
for i in range(K):
ai = (10*ai_1 + 7)%K
if ai==0:
print(i+1)
exit()
ai_1 = ai
print("-1")
| 1 | 6,136,499,133,380 | null | 97 | 97 |
class Node(object):
def __init__(self, key=None):
self.key = key
self.prev = None
self.next = None
class DoublyLinkedList(object):
def __init__(self):
self.first = Node()
self.first.prev = self.first
self.first.next = self.first
def insert(self, key):
x = Node(key)
x.next = self.first.next
self.first.next.prev = x
self.first.next = x
x.prev = self.first
def search(self, key):
cur = self.first.next
while cur != self.first and cur.key != key:
cur = cur.next
return cur
def delete(self, key):
self.delete_node(self.search(key))
def delete_node(self, node):
if node == self.first:
return
else:
node.prev.next = node.next
node.next.prev = node.prev
def delete_first(self):
self.delete_node(self.first.next)
def delete_last(self):
self.delete_node(self.first.prev)
if __name__ == "__main__":
import sys
input = sys.stdin.readline # faster input
linklist = DoublyLinkedList()
n = int(input())
for _ in range(n):
inputs = input().rstrip()
if inputs[0] == 'i':
linklist.insert(inputs[7:])
elif inputs[6] == 'F':
linklist.delete_first()
elif inputs[6] == 'L':
linklist.delete_last()
else:
linklist.delete(inputs[7:])
result = []
cur = linklist.first.next
while cur != linklist.first:
result.append(cur.key)
cur = cur.next
print(' '.join(result))
|
from sys import stdin
n = int(stdin.readline())
q = []
bottom = 0
for i in range(n):
cmd = stdin.readline()[:-1]
if cmd[0] == 'i':
q.append(cmd[7:])
elif cmd[6] == ' ':
try:
q.pop(~q[::-1].index(cmd[7:]))
except:
pass
elif cmd[6] == 'F':
q.pop()
else:
bottom += 1
print(' '.join(q[bottom:][::-1]))
| 1 | 51,268,803,210 | null | 20 | 20 |
#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import Counter
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"
input = sys.stdin.readline
########################################
ans = 0
n = int(input())
for i in range(1,n+1):
for j in range(1,n+1):
if i*j >= n:
break
ans+=1
print(ans)
'''
# Wrap solution for more recursion depth
#submit as python3
import collections,sys,threading
sys.setrecursionlimit(10**9)
threading.stack_size(10**8)
threading.Thread(target=solve).start()
'''
|
#!/usr/bin/env python3
import sys
import numpy as np
import numba
from numba import njit, b1, i4, i8, f8
input = sys.stdin.readline
def I():
return int(input())
@njit((i8,), cache=True)
def main(n):
table = np.zeros(n, np.int64)
for i in range(1, n):
table[::i] += 1
ans = 0
for n in table[1:]:
q, r = divmod(n, 2)
ans += q * 2 + 1 * r
return ans
N = I()
print(int(main(N)))
| 1 | 2,607,210,914,296 | null | 73 | 73 |
n = int(input())
branch = [[] for _ in range(n)]
a, b, inda, indb = [], [], [], []
for _ in range(n-1):
i, j = map(int, input().split())
i -= 1
j -= 1
branch[i].append(j)
branch[j].append(i)
a.append(i)
b.append(j)
inda.append(len(branch[i])-1)
indb.append(len(branch[j])-1)
kind = max([len(i) for i in branch])
print(kind)
# DFS
color = [0 for _ in range(n)]
todo = [0]
color[0] = 1
while len(todo) > 0:
num = todo.pop(-1)
col = color[num]
if col == kind:
col = 1
else:
col = col + 1
for i in range(len(branch[num])):
if color[branch[num][i]] == 0:
color[branch[num][i]] = col
todo.append(branch[num][i])
branch[num][i] = -col
if col == kind:
col = 1
else:
col = col + 1
for i in range(n-1):
if branch[a[i]][inda[i]] < 0:
print(-branch[a[i]][inda[i]])
else:
print(-branch[b[i]][indb[i]])
|
a,b=map(int,input().split())
def gcd(a,b):
while b:a,b=b,a%b
return a
def lcm(a,b):return a*b//gcd(a,b)
print(lcm(a,b))
| 0 | null | 124,588,118,650,566 | 272 | 256 |
import math
x = float(input())
print("%.6f %.6f"%(x*x*math.pi, x*2*math.pi))
|
N,K=map(int,input().split())
R,S,P=map(int,input().split())
T=input()
cnt=[0 for _ in range(N)]
score={'r':P,'s':R,'p':S}
for i in range(N):
if i<K:
cnt[i]=score[T[i]]
else:
if T[i-K]!=T[i]:
cnt[i]=score[T[i]]
else:
if cnt[i-K]==0:
cnt[i]=score[T[i]]
print(sum(cnt))
| 0 | null | 53,951,099,672,480 | 46 | 251 |
# import sys
# sys.setrecursionlimit(10 ** 6)
# import bisect
# from collections import deque
# from decorator import stop_watch
#
#
# @stop_watch
def solve(H, W, K, Si):
Si = [[int(i) for i in S] for S in Si]
ans = H + W
for i in range(2 ** (H - 1)):
h_border = bin(i).count('1')
w_border = 0
white_counts = [0] * (h_border + 1)
choco_w = 0
for w in range(W):
choco_w += 1
wc_num = 0
tmp_count = [0] * (h_border + 1)
for h in range(H):
white_counts[wc_num] += Si[h][w]
tmp_count[wc_num] += Si[h][w]
if i >> h & 1:
wc_num += 1
if max(white_counts) > K:
if choco_w == 1:
break # 1列の時点で > K の場合は条件を達成できない
w_border += 1
white_counts = tmp_count
choco_w = 1
else:
ans = min(ans, h_border + w_border)
print(ans)
if __name__ == '__main__':
H, W, K = map(int, input().split())
Si = [input() for _ in range(H)]
solve(H, W, K, Si)
# # test
# from random import randint
# from func import random_str
#
# H, W, K = 10, 1000, randint(1, 100)
# Si = [random_str(W, '01') for _ in range(H)]
# print(H, W, K)
# for S in Si:
# print(S)
# solve(H, W, K, Si)
|
# encoding: utf-8
import sys
from collections import deque
class Solution:
@staticmethod
def doubly_linked_list():
# write your code here
array_length = int(input())
task_deque = deque()
_input = sys.stdin.readlines()
for i in range(array_length):
l_arg = _input[i].split()
action = l_arg[0]
if len(l_arg) > 1:
value = l_arg[-1]
# print(action, 'v', value)
if action == 'insert':
task_deque.appendleft(value)
elif action == 'deleteFirst':
task_deque.popleft()
elif action == 'deleteLast':
task_deque.pop()
elif action == 'delete':
try:
task_deque.remove(value)
except Exception as e:
pass
print(" ".join(task_deque))
if __name__ == '__main__':
solution = Solution()
solution.doubly_linked_list()
| 0 | null | 24,443,253,802,464 | 193 | 20 |
n = int(input())
ls = list(map(int, input().split()))
count = 0
flag = 1
while flag:
flag = 0
for i in range(len(ls)-1, 0, -1):
if ls[i] < ls[i-1]:
ls[i], ls[i-1] = ls[i-1], ls[i]
count += 1
flag = 1
print(' '.join(map(str, ls)))
print(count)
|
#!/usr/bin/env python
# encoding: utf-8
class Solution:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
@staticmethod
def bubble_sort():
# write your code here
array_length = int(input())
unsorted_array = [int(x) for x in input().split()]
flag = 1
count = 0
while flag:
flag = 0
for j in range(array_length - 1, 0, -1):
if unsorted_array[j] < unsorted_array[j - 1]:
unsorted_array[j], unsorted_array[j - 1] = unsorted_array[j - 1], unsorted_array[j]
flag = 1
count += 1
print(" ".join(map(str, unsorted_array)))
print(str(count))
if __name__ == '__main__':
solution = Solution()
solution.bubble_sort()
| 1 | 16,279,190,190 | null | 14 | 14 |
S = input()
wait_day = 0
if S == "SUN":
wait_day = 7
elif S == "MON":
wait_day = 6
elif S == "TUE":
wait_day = 5
elif S == "WED":
wait_day = 4
elif S == "THU":
wait_day = 3
elif S == "FRI":
wait_day = 2
elif S == "SAT":
wait_day = 1
print(wait_day)
|
day = input('')
if day == 'SUN':
print('7')
elif day == 'MON':
print('6')
elif day == 'TUE':
print('5')
elif day == 'WED':
print('4')
elif day == 'THU':
print('3')
elif day == 'FRI':
print('2')
else:
print('1')
| 1 | 132,722,680,914,700 | null | 270 | 270 |
N, K = list(map(int, input().split()))
H = list(map(int, input().split()))
H = sorted(H, reverse=True)
for i in range(min(K,len(H))):
H[i] = 0
print(sum(H))
|
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
#import bisect
#
# d = m - k[i] - k[j]
# if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも!!
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
return list(map(int,input().split()))
def I():
return int(input())
n,k = readInts()
H = sorted(readInts(),reverse=True)
if n <= k:
print(0)
else:
print(sum(H[k:]))
| 1 | 79,192,067,949,640 | null | 227 | 227 |
n, m = map(int, input().split())
V = [set() for _ in range(n)] # 隣接リスト
for a, b in [[*map(lambda x: int(x)-1, input().split())] for _ in range(m)]:
V[a].add(b)
V[b].add(a)
from collections import deque
G = [-1] * n # グループ色分け
for s in range(n): # BFS
dq = deque([s])
while dq:
p = dq.popleft()
if G[p] >= 0: continue
G[p] = s # 色付け
for c in V[p]: dq.append(c)
C = dict() # グループメンバ数集計
for g in G:
if not g in C: C[g] = 0
C[g] += 1
print(max(C.values())) # 最大メンバ数
|
class UnionFind:
def __init__(self):
self.data = {}
self.heights = {}
self.sizes = {}
def get_num_trees(self):
return len(self.heights)
def get_tree_size(self, a):
return self.sizes[self.get_root(a)]
def add_node(self, a):
self.data[a] = a
self.heights[a] = 1
self.sizes[a] = 1
def get_root(self, a):
nodes = [a]
while nodes[-1] not in self.heights:
nodes.append(self.data[nodes[-1]])
for x in nodes:
self.data[x] = nodes[-1]
return nodes[-1]
def union(self, a, b):
root_a = self.get_root(a)
root_b = self.get_root(b)
if root_a == root_b:
return
if self.heights[root_a] > self.heights[root_b]:
a, b = b, a
root_a, root_b = root_b, root_a
self.data[root_a] = root_b
self.heights[root_b] = max(self.heights.pop(root_a) + 1, self.heights[root_b])
self.sizes[root_b] += self.sizes.pop(root_a)
def find(self, a, b):
return self.get_root(a) == self.get_root(b)
N, M = map(int, input().split())
uf = UnionFind()
for i in range(1, N + 1):
uf.add_node(i)
for _ in range(M):
A, B = map(int, input().split())
uf.union(A, B)
print(max(uf.sizes.values()))
| 1 | 3,911,877,800,480 | null | 84 | 84 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.