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
|
---|---|---|---|---|---|---|
import sys
array = []
for inp in sys.stdin.readlines():
array.append(inp.split())
for i in range(len(array)):
a =int(array[i][0]) + int(array[i][1])
print(len(str(a))) | import sys
from math import log10
for line in sys.stdin:
a, b = map(int, line.split())
digitNumber = int(log10((a + b))) + 1
print(digitNumber) | 1 | 89,633,600 | null | 3 | 3 |
class Stack:
def __init__(self, n):
self.n = n
self._l = [None for _ in range(self.n + 1)]
self._top = 0
def push(self, x):
if self.isFull():
raise IndexError("stack is full")
else:
self._top += 1
self._l[self._top] = x
def pop(self):
if self.isEmpty():
raise IndexError("pop from empty stack")
else:
e = self._l[self._top]
self._l[self._top] = None
self._top -= 1
return e
def isEmpty(self):
return self._top == 0
def isFull(self):
return self._top == self.n
def poland_calculator(s):
n = len(s)
stack = Stack(n)
i = 0
while i < n:
if s[i] == ' ':
i += 1
continue
elif s[i].isdigit():
sn = ''
while s[i].isdigit():
sn += s[i]
i += 1
stack.push(int(sn))
else:
b = stack.pop()
a = stack.pop()
if s[i] == '+':
e = a + b
elif s[i] == '-':
e = a - b
else:
e = a * b
stack.push(e)
i +=1
return stack.pop()
if __name__ == '__main__':
s = input()
res = poland_calculator(s)
print(res)
| def add(x,y):
return x+y
def sub(x,y):
return x-y
def mul(x,y):
return x*y
def div(x,y):
return x/float(y)
a=input().split()
i=0
for j in range(len(a)):
if a[i]=="+":
a[i-2]=int(a[i-2])
a[i-1]=int(a[i-1])
a[i]=int(add(a[i-2],a[i-1]))
del a[i-2]
del a[i-2]
i=i-2
elif a[i]=="-":
a[i-2]=int(a[i-2])
a[i-1]=int(a[i-1])
a[i]=int(sub(a[i-2],a[i-1]))
del a[i-2]
del a[i-2]
i=i-2
elif a[i]=="*":
a[i-2]=int(a[i-2])
a[i-1]=int(a[i-1])
a[i]=int(mul(a[i-2],a[i-1]))
del a[i-2]
del a[i-2]
i=i-2
elif a[i]=="/":
a[i-2]=int(a[i-2])
a[i-1]=int(a[i-1])
a[i]=int(div(a[i-2],a[i-1]))
del a[i-2]
del a[i-2]
i=i-2
i=i+1
print(a[0])
| 1 | 35,965,223,188 | null | 18 | 18 |
n = int(input())
an = [int(num) for num in input().split()]
sum = 0
for i in range(len(an)-1):
if an[i] > an[i+1]:
sum += an[i] - an[i+1]
an[i+1] += an[i] - an[i+1]
print(sum) | n=int(input())
a=list(map(int,input().split()))
b=a[0]
ans=0
for n in range(n):
if a[n]>b:
b=a[n]
else:
ans+=b-a[n]
print(ans) | 1 | 4,601,593,256,910 | null | 88 | 88 |
import sys
input = sys.stdin.readline
n = int(input())
num = list(map(int, input().split()))
mod = 10**9+7
num = tuple(num)
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1:
arr.append([temp, 1])
if arr==[]:
arr.append([n, 1])
return arr
lcd = dict()
for i in num:
j = factorization(i)
for x,y in j:
if not x in lcd.keys():
lcd[x] = y
else:
lcd[x] = max(lcd[x],y)
lc = 1
for i,j in lcd.items():
lc *= pow(i,j,mod)
ans =0
for i in range(n):
ans += lc*pow(num[i], mod-2, mod)
ans %= mod
print(ans) | N,T = map(int, input().split())
data = [list(map(int, input().split())) for i in range(N)]
dp1 = [[0]*(N+1) for _ in range(T+1)]
dp2 = [[0]*(N+1) for _ in range(T+1)]
for t in range(T):
for n in range(N):
if t+1-data[n][0]>=0:
dp1[t+1][n+1] = max(dp1[t+1][n],dp1[t+1-data[n][0]][n]+data[n][1])
dp2[t+1][n+1] = max(dp2[t+1][n],dp2[t+1-data[n][0]][n]+data[n][1],
dp1[t][n]+data[n][1])
else:
dp1[t+1][n+1] = dp1[t+1][n]
dp2[t+1][n+1] = max(dp2[t+1][n],dp1[t][n]+data[n][1])
print(dp2[T][N])
| 0 | null | 119,731,980,291,180 | 235 | 282 |
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
from collections import defaultdict, deque
from sys import exit
import math
import copy
from bisect import bisect_left, bisect_right
from heapq import *
import sys
# sys.setrecursionlimit(1000000)
INF = 10 ** 17
MOD = 1000000007
from fractions import *
def inverse(f):
# return Fraction(f.denominator,f.numerator)
return 1 / f
def combmod(n, k, mod=MOD):
ret = 1
for i in range(n - k + 1, n + 1):
ret *= i
ret %= mod
for i in range(1, k + 1):
ret *= pow(i, mod - 2, mod)
ret %= mod
return ret
def bunsu(n):
ret = []
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
tmp = 0
while (True):
if n % i == 0:
tmp += 1
n //= i
else:
break
ret.append((i, tmp))
ret.append((n, 1))
return ret
MOD = 998244353
def solve():
n, k = getList()
nums = getList()
dp = [0 for i in range(k+1)]
dp[0] = 1
for i, num in enumerate(nums):
new = [0 for i in range(k+1)]
for j, d in enumerate(dp):
new[j] += d * 2
if (j + num) <= k:
new[j+num] += d
dp = [ne%MOD for ne in new]
print(dp[-1])
def main():
# n = getN()
# for _ in range(n):
solve()
if __name__ == "__main__":
solve() | n,s=map(int,input().split())
a=list(map(int,input().split()))
mod=998244353
dp=[[0 for i in range(s+1)] for j in range(n+1)]
dp[0][0]=1
for i in range(1,n+1):
see=a[i-1]
for j in range(s+1):
dp[i][j]=dp[i-1][j]*2
dp[i][j]%=mod
if see>j:
continue
dp[i][j]+=dp[i-1][j-see]
dp[i][j]%=mod
print(dp[-1][-1])
| 1 | 17,529,515,350,100 | null | 138 | 138 |
def main():
s = list(input())
k = int(input())
lst = []
cnt = 1
flg = 0
ans = 0
prev = s[0]
for i in range(1, len(s)):
if prev == s[i]:
cnt += 1
else:
lst.append(cnt)
cnt = 1
prev = s[i]
flg = 1
lst.append(cnt)
if len(lst) == 1:
ans = len(s) * k // 2
else:
ans += sum(map(lambda x: x // 2, lst[1:len(lst)-1])) * k
# for l in lst[1: len(lst) - 1]:
# ans += l // 2 * k
if s[-1] == s[0]:
ans += (lst[0] + lst[-1]) // 2 * (k - 1)
ans += lst[0] // 2 + lst[-1] // 2
else:
ans += (lst[0] // 2 + lst[-1] // 2) * k
print(ans)
if __name__ == "__main__":
main()
| def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
k = int(input())
ans = 0
for a in range(1, k + 1):
for b in range(a, k + 1):
for c in range(b, k + 1):
d = gcd(a, b)
if len({a, b, c}) == 1:
ans += gcd(c, d)
elif len({a, b, c}) == 2:
ans += 3 * gcd(c, d)
else:
ans += 6 * gcd(c, d)
print(ans)
| 0 | null | 105,222,226,053,732 | 296 | 174 |
S=int(input())
a,s=divmod(S,60)
h,m=divmod(a,60)
print(str(h)+':'+str(m)+':'+str(s))
| S = int(input())
h = S // 3600
m = (S % 3600) // 60
s = (S % 3600) % 60
print(str(h) + ':' + str(m) + ':' + str(s))
| 1 | 339,237,936,272 | null | 37 | 37 |
mod = int(1e9+7)
def add(a, b):
c = a + b
if c >= mod:
c -= mod
return c
def mul(a, b):
return (a * b) % mod
def my_pow(a, b):
if b == 0:
return 1
elif b % 2 == 1:
return mul(a, my_pow(a, b-1))
else:
temp = my_pow(a, b/2)
return mul(temp, temp)
def my_inv(a):
return my_pow(a, mod-2)
def modInverse(a, m) :
m0 = m
y = 0
x = 1
if (m == 1) :
return 0
while (a > 1) :
# q is quotient
q = a // m
t = m
# m is remainder now, process
# same as Euclid's algo
m = a % m
a = t
t = y
# Update x and y
y = x - q * y
x = t
# Make x positive
if (x < 0) :
x = x + m0
return x
def main():
n = int(raw_input())
arr = [int(x) for x in raw_input().split()]
answer = {}
for i in range(n):
cnt = {}
x = arr[i]
i = 2
while i * i <= x:
while x % i == 0:
x /= i
cnt[i] = cnt.get(i, 0) + 1
i += 1
if x != 1:
cnt[x] = cnt.get(x, 0) + 1
for key in cnt:
answer[key] = max(answer.get(key, 0), cnt[key])
lcm = 1
for prime in answer:
for _ in range(answer[prime]):
lcm = mul(lcm, prime)
#print(lcm)
ans = 0
#print(my_pow(22, 3))
for x in arr:
#print(my_inv(x))
ans = add(ans, mul(lcm, my_inv(x)))
ans = int(ans)
print(ans)
main()
"""
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MOD = 1e9+7;
ll add(ll a, ll b) {
return (a + b) % MOD;
}
ll divi(ll a, ll b) {
return (a / b) % MOD;
}
ll mul(ll a, ll b) {
return (a * b) % MOD;
}
// Return a ^ b
int my_pow(int a, int b) {
if (b == 0) {
return 1;
}
else if (b % 2 == 1) {
return mul(a, my_pow(a, b-1));
}
else {
int temp = my_pow(a, b/2);
return mul(temp, temp);
}
}
int my_inv(int a) {
return my_pow(a, MOD-2);
}
int main() {
int n;
scanf("%d", &n);
vector<int> arr(n);
map<int, int> answer;
//cout << "test" << endl;
for (int i = 0; i < n; i++) {
map<int, int> cnt;
scanf("%d", &arr[i]);
int x = arr[i];
//cout << x << endl;
for (int i = 2; i * i <= x; i++) {
while (x % i == 0) {
cnt[i] += 1;
x /= i;
}
}
if (x != 1) {
cnt[x] += 1;
}
//cout << "test_x" << endl;
for (pair<int, int> p : cnt) {
answer[p.first] = max(answer[p.first], p.second);
}
}
//cout << "test2" << endl;
ll lcm = 1;
for (pair<int, int> p : answer) {
int prime = p.first;
int k = p.second;
for (int i = 0; i < k; i++) {
lcm = mul(lcm, prime);
}
}
ll ans = 0;
//cout << "test1" << endl;
for (int i = 0; i < n; i++) {
ans = add(ans, mul(lcm, my_inv(arr[i])));
}
//cout << "test2" << endl;
printf("%lld", ans);
return 0;
}
""" | N=int(input())
*A,=map(int, input().split())
M=10**3
P=[]
isp=[True]*M
for n in range(2,M):
if isp[n]==False: continue
P.append(n)
for m in range(n*n, M, n):
isp[m]=False
from collections import defaultdict
D=[defaultdict(int) for _ in range(N)]
for i in range(N):
a=A[i]
for p in P:
while a>1:
if a%p==0:
D[i][p]+=1
a//=p
else:
break
else:
break
if a>1:
D[i][a]+=1
d=defaultdict(int)
for i in range(N):
for k,v in D[i].items():
d[k] = max(d[k], v)
gcd=1
for k,v in d.items():
gcd*=k**v
print(sum([gcd//a for a in A])%(10**9+7))
| 1 | 87,596,937,621,622 | null | 235 | 235 |
_ = input()
l = reversed(input().split())
print(' '.join(l)) | H, W, M = map(int, input().split())
row=[0]*H #x座標を入れるっちゅうかカウント
col=[0]*W #y座標を入れる
mat=[] #座標を入れる
for i in range(M):
h, w = map(int, input().split())
row[h-1]+=1
col[w-1]+=1
mat.append((h-1,w-1))
r=max(row)
c=max(col)
rr=[1 if row[i]==r else 0 for i in range(H)] #maxな列のインデックス
cc=[1 if col[i]==c else 0 for i in range(W)] #maxな行のインデックス
x=0 #maxな列と行の交差点にある爆弾の個数をカウント
for k in mat:
if rr[k[0]]==1 and cc[k[1]]==1:
x+=1
if sum(rr)*sum(cc)==x: #行と列の全ての交差点に爆弾があれば-1する
print(r+c-1)
else:
print(r+c) | 0 | null | 2,861,034,204,758 | 53 | 89 |
a,b = map(int,input().split())
l=[]
if a>=b:
for i in range(a):
l.append(b)
else:
for i in range(b):
l.append(a)
print(''.join(map(str,l))) | a,b = map(int,input().split())
num = 0
if a <= b:
for i in range(b):
num += a * 10**i
print(num)
else:
for i in range(a):
num += b * 10**i
print(num) | 1 | 83,972,803,139,556 | null | 232 | 232 |
def resolve():
from scipy.sparse.csgraph import floyd_warshall
import numpy as np
import sys
input = sys.stdin.readline
n, m, l = map(int, input().split())
inf = 10 ** 20
ar = [[0] * n for _ in range(n)]
for _ in range(m):
a, b, c = map(int, input().split())
ar[a - 1][b - 1] = c
ar[b - 1][a - 1] = c
x = floyd_warshall(ar)
br = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
if x[i, j] <= l:
br[i][j] = 1
br[j][i] = 1
y = floyd_warshall(br)
q = int(input())
for _ in range(q):
s, t = map(int, input().split())
p = y[s - 1, t - 1]
print(int(p) - 1 if p < inf else -1)
if __name__ == "__main__":
resolve()
| x=int(input())
A=[i**5 for i in range(-2000,2000)]
for i in range(4000):
for j in range(i):
if A[i]-A[j]==x:
print(*[i-2000,j-2000]);exit()
| 0 | null | 99,545,019,500,290 | 295 | 156 |
x=input()
x=x**3
print x | # A We Love Golf
K = int(input())
A, B = map(int, input().split())
for i in range(A, B+1):
if i % K == 0:
print("OK")
exit()
else:
print("NG") | 0 | null | 13,435,661,857,760 | 35 | 158 |
import sys
import math
import fractions
from collections import defaultdict
stdin = sys.stdin
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))
A,B,C=nm()
print('bust' if 22<=(A+B+C) else 'win') | def main():
a, b, c = map(int, input().split())
if (a + b + c) >= 22:
print("bust")
else:
print("win")
main() | 1 | 118,387,458,987,070 | null | 260 | 260 |
import sys
a = list(map(int,sys.stdin.readlines()))
for i in range(10):
for j in range(i+1,10):
if a[i] < a[j]:
a[i],a[j] = a[j],a[i]
for i in range(3):
print(a[i]) | def quicksort(array):
if len(array) < 2:
return array
else:
pivot = array[0]
less = [i for i in array[1:] if i <= pivot]
greater = [i for i in array[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksort(greater)
array = []
for _ in range(10):
array.append(int(input()))
sorted_array = quicksort(array)
for i in range(3):
print(sorted_array[9-i]) | 1 | 30,080,540 | null | 2 | 2 |
# coding: utf-8
# Your code here!
a,b=map(int,input().split())
if (1<=a<=9) and (1<=b<=9):
print(a*b)
else:
print(-1) |
def main():
a, b = map(int, input().split())
if a <= 9 and b <= 9:
print(a * b)
else:
print(-1)
if __name__ == "__main__":
main()
| 1 | 158,107,147,479,948 | null | 286 | 286 |
import collections
N = int(input())
A = list(map(int, input().split()))
#i + Ai
plus = [0] * N
#i - Ai
minus = [0] * N
for i in range(N):
plus[i] = i + 1 + A[i]
minus[i] = i + 1 - A[i]
#print(plus, minus)
plus = dict(collections.Counter(plus))
minus = dict(collections.Counter(minus))
#print(plus)
#print(minus)
ans = 0
for i in plus.keys():
#print(i)
if i in minus:
#print(i)
ans += plus[i] * minus[i]
#print(ans)
print(ans)
| import numpy as np
n, k = map(int, input().split())
fruits = np.array(input().split(),dtype=np.int64)
fruits.sort()
ans = 0
cnt = 0
for i in fruits:
if(cnt < k):
ans += i
cnt += 1
print(ans)
| 0 | null | 18,872,834,122,560 | 157 | 120 |
h,n = map(int,input().split())
a = [0 for _ in range(n)]
b = [0 for _ in range(n)]
for i in range(n):
a[i],b[i] = map(int,input().split())
cost = [int(1e+9) for _ in range(h+1)]
cost[0] = 0
for i in range(h):
for j in range(n):
if i+a[j] <= h:
cost[i+a[j]] = min(cost[i+a[j]],cost[i]+b[j])
else:
cost[-1] = min(cost[-1],cost[i]+b[j])
print(cost[-1]) | import heapq
import sys
input = sys.stdin.readline
def dijkstra_heap(s,edge,n):
#始点sから各頂点への最短距離
d = [10**20] * n
used = [True] * n #True:未確定
d[s] = 0
used[s] = False
edgelist = []
for a,b in edge[s]:
heapq.heappush(edgelist,a*(10**6)+b)
while len(edgelist):
minedge = heapq.heappop(edgelist)
#まだ使われてない頂点の中から最小の距離のものを探す
if not used[minedge%(10**6)]:
continue
v = minedge%(10**6)
d[v] = minedge//(10**6)
used[v] = False
for e in edge[v]:
if used[e[1]]:
heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
return d
def main():
N, u, v = map(int, input().split())
u -= 1
v -= 1
edge = [[] for i in range(N)]
for _ in range(N-1):
A, B = map(int, input().split())
A -= 1
B -= 1
edge[A].append([1,B])
edge[B].append([1,A])
d1 = dijkstra_heap(u,edge, N)
d2 = dijkstra_heap(v,edge, N)
ans = 0
for i in range(N):
if d1[i] < d2[i]:
ans = max(ans, d2[i]-1)
print(ans)
if __name__ == "__main__":
main() | 0 | null | 99,492,735,566,180 | 229 | 259 |
n = int(input());div=[];ans=[]
for i in range(1,int(n**0.5)+2):
if n%i == 0:
div.append(i);div.append(n//i)
for i in div:
if i == 1:
continue
tmp = n
while tmp % i == 0:
tmp //= i
if tmp % i ==1:
ans.append(i)
n -= 1
for i in range(1,int(n**0.5)+2):
if n%i == 0:
ans.append(i);ans.append(n//i)
print(len(set(ans))-1) | print("YNeos"['7' not in input()::2])
| 0 | null | 37,838,927,200,138 | 183 | 172 |
N = int(input())
#stones = list(input())
stones = input()
#print(stones)
a = stones.count('W')
b = stones.count('R')
left_side =stones.count('W', 0, b)
print(left_side) | #!/usr/bin/env python3
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]
def inside(y, x, H, W):
return 0 <= y < H and 0 <= x < W
def ceil(a, b):
return (a + b - 1) // b
def sum_of_arithmetic_progression(s, d, n):
return n * (2 * s + (n - 1) * d) // 2
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
g = gcd(a, b)
return a / g * b
def solve():
N = int(input())
C = input()
num_r = C.count("R")
num_w = C.count("W")
ans = min(num_r, num_w)
left_r = 0
left_w = 0
for i in range(N):
left_r += C[i] == 'R'
left_w += C[i] == 'W'
right_r = num_r - left_r
right_w = num_w - left_w
ans = min(ans, min(left_w, right_r) + abs(left_w - right_r))
print(ans)
def main():
solve()
if __name__ == '__main__':
main()
| 1 | 6,320,165,394,330 | null | 98 | 98 |
#!/usr/bin python3
# -*- coding: utf-8 -*-
def main():
A, B = map(int, input().split())
print(max(0,A-2*B))
if __name__ == '__main__':
main() | x = list(map(int,input().split()))
a = x[0]
b = x[1]
if(2*b < a):
print(a-2*b)
else:
print(0) | 1 | 167,210,745,722,316 | null | 291 | 291 |
def main():
n, m = map(int, input().split())
matrix = [
list(map(int, input().split()))
for _ in range(n)
]
vector = [
int(input())
for _ in range(m)
]
for v in matrix:
res = sum(x * y for x, y in zip(v, vector))
print(res)
if __name__ == "__main__":
main() | [r,c] = raw_input().split()
r = int(r)
c = int(c)
M = []
V = []
for y in range(0,r):
s = raw_input().split()
k = []
for x in range(0,c):
v = int(s[x])
k.append(v)
M.append(k)
for y in range(0,c):
s = int(raw_input())
V.append(s)
for y in range(0,r):
ss = 0
for x in range(0,c):
ss = ss + M[y][x] * V[x]
print ss | 1 | 1,147,150,341,048 | null | 56 | 56 |
def main():
S = input()
ans = [s if s != '?' else 'D' for s in S]
print(''.join(ans))
if __name__ == '__main__':
main() | line = list(input())
N = len(line)
i = 1
for i in range(N):
if line[i] == "?":
line[i] = "D"
print("".join(line)) | 1 | 18,528,822,525,640 | null | 140 | 140 |
def main():
X = int(input())
fifth_power = [x ** 5 for x in range(201)]
for i in range(len(fifth_power)):
p = fifth_power[i]
q1 = abs(X - p)
q2 = abs(X + p)
if q1 in fifth_power:
if p + q1 == X:
print(fifth_power.index(p), -fifth_power.index(q1))
elif p - q1 == X:
print(fifth_power.index(p), fifth_power.index(q1))
return 0
if q2 in fifth_power:
print(fifth_power.index(q2), fifth_power.index(p))
return 0
main() | def solve():
x = int(input())
for i in range(-150, 151):
for j in range(-150,i):
if i ** 5 - j ** 5 == x:
print(i,j)
return
if __name__ == '__main__':
solve() | 1 | 25,513,031,423,118 | null | 156 | 156 |
a = list(map(int, input().split()))
suma = a[0] + a[1] + a[2]
if suma >= 22:
print('bust')
else:
print('win') | # Aizu Problem ITP_1_7_A: Grading
#
import sys, math, os
# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
sys.stdin = open("sample-input.txt", "rt")
while True:
m, f, r = [int(_) for _ in input().split()]
score = m + f
if m == f == r == -1:
break
elif m == -1 or f == -1:
print('F')
elif score >= 80:
print('A')
elif score >= 65:
print('B')
elif score >= 50 or (score >= 30 and r >= 50):
print('C')
elif score >= 30:
print('D')
else:
print('F') | 0 | null | 59,921,922,858,840 | 260 | 57 |
N, K = map(int, input().split())
mod = 10 ** 9 + 7
print(((N+1)*(N*N+2*N+6)//6+(K-1)*(2*K*K-(3*N+4)*K-6)//6) % mod) | import sys
def resolve(in_):
mod = 1000000007 # 10 ** 9 + 7
n, k = map(int, in_.readline().split())
n += 1
# ans = 0
ans = 1
# while n >= k:
while n > k:
ans += (
((n + (n - k)) * k // 2) % mod -
((1 + k - 1) * k // 2) % mod +
1
) % mod
ans %= mod
k += 1
return ans
def main():
answer = resolve(sys.stdin.buffer)
print(answer)
if __name__ == '__main__':
main() | 1 | 33,215,448,534,630 | null | 170 | 170 |
N = int(input())
XYS = [list(map(int, input().split())) for _ in range(N)]
s = 0
def perm(ns):
acc = []
def fill(ms, remains):
if remains:
for m in remains:
fill(ms + [m], [x for x in remains if x != m])
else:
acc.append(ms)
fill([], ns)
return acc
s = 0
for indexes in perm(list(range(N))):
xys = [XYS[i] for i in indexes]
x0, y0 = xys[0]
for x1, y1 in xys:
s += ((x0 - x1)**2 + (y0 - y1)**2) ** 0.5
x0 = x1
y0 = y1
nf = 1
for i in range(1, N+1):
nf *= i
ans = s / nf
print(ans) | import itertools
import math
N = int(input())
x_list = [0] * N
y_list = [0] * N
for i in range(N):
x_list[i], y_list[i] = map(int, input().split())
l_sum = 0
l = 0
for comb in itertools.combinations(range(N), 2):
l = (
(x_list[comb[0]] - x_list[comb[1]]) ** 2
+ (y_list[comb[0]] - y_list[comb[1]]) ** 2
) ** 0.5
l_sum += l
ans = 2 * l_sum / N
print(ans) | 1 | 148,436,574,433,532 | null | 280 | 280 |
N = int(input())
A = input().split()
num_list = [0] * 10**5
ans = 0
for i in range(N):
num_list[int(A[i])-1] += 1
for i in range(10**5):
ans += (i+1) * num_list[i]
Q = int(input())
for i in range(Q):
B, C = map(int, input().split())
ans = ans + C * num_list[B-1] - B * num_list[B-1]
num_list[C-1] += num_list[B-1]
num_list[B-1] = 0
print(ans) | n = int(input())
A = list(map(int, input().split()))
q = int(input())
S = []
for _ in range(q):
x, y = map(int, input().split())
S.append((x, y))
sum = sum(A)
# print(sum)
R = [0 for _ in range(10**5+1)]
for a in A:
R[a-1] += 1
for (x,y) in S:
sum += (y-x)*R[x-1]
R[y-1] += R[x-1]
R[x-1] = 0
print(sum) | 1 | 12,199,017,462,214 | null | 122 | 122 |
n,k=map(int,input().split())
p=list(map(int,input().split()))
dp=[0]*(n-k+1)
dp[0]=sum(p[:k])
for i in range(n-k):
dp[i+1]=dp[i]+p[k+i]-p[i]
print((max(dp)+k)/2) | n,k = map(int, input().split())
p = [int(x) for x in input().split()]
p_kitaiti=[float((x+1)/2) for x in p]
ruisekiwa=[p_kitaiti[0]]
for i in range(1,len(p_kitaiti)):
ruisekiwa.append(ruisekiwa[-1]+p_kitaiti[i])
ans=ruisekiwa[k-1]
for i in range(1,len(ruisekiwa)-k+1):
ans=max(ans,ruisekiwa[i+k-1]-ruisekiwa[i-1])
print(ans) | 1 | 75,056,232,968,640 | null | 223 | 223 |
#145_E
n, t = map(int, input().split())
ab = [tuple(map(int, input().split())) for _ in range(n)]
#dp1[i][j] ... 1~iでj分以内の最大値
#dp2[i][j] ... i~nでj分以内の最大値
dp1 = [[0 for _ in range(t)] for _ in range(n+1)]
dp2 = [[0 for _ in range(t)] for _ in range(n+2)]
for i in range(1, n+1):
a, b = ab[i-1]
for j in range(1, t):
if j - a >= 0:
dp1[i][j] = max(dp1[i-1][j], dp1[i-1][j-a] + b)
else:
dp1[i][j] = dp1[i-1][j]
for i in range(n, 0, -1):
a, b = ab[i-1]
for j in range(1, t):
if j - a >= 0:
dp2[i][j] = max(dp2[i+1][j], dp2[i+1][j-a] + b)
else:
dp2[i][j] = dp2[i+1][j]
ans = 0
for i in range(1, n+1):
b = ab[i-1][1]
for j in range(0, t):
x = dp1[i-1][j] + dp2[i+1][t-j-1] + b
ans = max(ans, x)
print(ans) | from collections import deque
import sys
sys.setrecursionlimit(10**9)
def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))
INF=10**20
def main():
N=ii()
G = [[] for _ in range(N)]
E = []
_E = set()
for i in range(N-1):
a,b=mi()
G[a-1].append(b-1)
G[b-1].append(a-1)
E.append((a-1,b-1))
_E.add((a-1,b-1))
leaf = 0
for i in range(N):
g = G[i]
if len(g) == 1:
leaf = i
stack = deque([(leaf,1,None)])
seen = set()
path = {x:0 for x in E}
K = 0
def save(edge,color):
if edge == None: return
a,b = edge
if (a,b) in _E:
path[(a,b)] = color
else:
path[(b,a)] = color
while stack:
current,color,edge = stack.popleft()
seen.add(current)
save(edge,color)
K = max(K,color)
# print(current,color,edge)
i = 1
for next in G[current]:
if next in seen: continue
if color == i:
i += 1
stack.append((next,i,(current,next)))
i += 1
if N == 2:
print(1)
print(1)
exit()
print(K)
for i in range(N-1):
a,b = E[i]
print(path[(a,b)],sep="")
if __name__ == "__main__":
main() | 0 | null | 143,467,670,200,232 | 282 | 272 |
#146_F
n, m = map(int, input().split())
s = input()[::-1]
ans = []
flg = True
cur = 0
while cur < n and flg:
for to in range(cur + m, cur, -1):
if to > n:
continue
if s[to] == '0':
ans.append(to - cur)
cur = to
break
if to == cur + 1:
flg = False
if flg:
print(*ans[::-1])
else:
print(-1) | def main():
_, *S = open(0)
print(len(set(S)))
if __name__ == "__main__":
main() | 0 | null | 84,701,081,957,600 | 274 | 165 |
# coding:utf-8
import math
N=int(input())
x=list(map(int,input().split()))
y=list(map(int,input().split()))
manh_dist=0.0
for i in range(0,N):
manh_dist=manh_dist+math.fabs(x[i]-y[i])
print('%.6f'%manh_dist)
eucl_dist=0.0
for i in range(0,N):
eucl_dist=eucl_dist+(x[i]-y[i])**2
eucl_dist=math.sqrt(eucl_dist)
print('%.6f'%eucl_dist)
mink_dist=0.0
for i in range(0,N):
mink_dist=mink_dist+math.fabs(x[i]-y[i])**3
mink_dist=math.pow(mink_dist,1.0/3)
print('%.6f'%mink_dist)
cheb_dist=0.0
for i in range(0,N):
if cheb_dist<math.fabs(x[i]-y[i]):
cheb_dist=math.fabs(x[i]-y[i])
print('%.6f'%cheb_dist) | import sys
def popcount(x: int):
return bin(x).count("1")
def main():
N = int(sys.stdin.readline().rstrip())
X = sys.stdin.readline().rstrip()
Xdec = int(X, 2)
# 1回目の演算用
md = popcount(Xdec)
md_p, md_m = md + 1, md - 1
tmp_p = Xdec % md_p
if md_m > 0:
tmp_m = Xdec % md_m
for i in range(0, N, 1):
if X[i] == "1": # 1->0
if md_m == 0:
print(0)
continue
x_m = pow(2, (N - 1 - i), md_m)
tmp = (tmp_m - x_m) % md_m
if X[i] == "0": # 0->1
x_p = pow(2, (N - 1 - i), md_p)
tmp = (tmp_p + x_p) % md_p
cnt = 1
while tmp:
tmp = tmp % popcount(tmp)
cnt += 1
print(cnt)
main()
| 0 | null | 4,166,990,327,560 | 32 | 107 |
import bisect
N, M, K = map(int, input().split())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
sAs = [0]
sBs = [0]
for a in As:
sAs.append(sAs[-1]+a)
for b in Bs:
sBs.append(sBs[-1]+b)
rlt = 0
for i in range(N+1):
t = K - sAs[i]
if t < 0:
break
j = bisect.bisect_right(sBs, t)
rlt = max(rlt, i+j-1)
print(rlt) | import sys
input = sys.stdin.readline
import numpy as np
from numba import njit
def read():
D = int(input().strip())
C = np.fromstring(input().strip(), dtype=np.int32, sep=" ")
S = np.empty((D, 26), dtype=np.int32)
for i in range(D):
s = np.fromstring(input().strip(), dtype=np.int32, sep=" ")
S[i, :] = s[:]
M = 10000
RD = np.random.randint(D, size=(M, ), dtype=np.int32)
RQ = np.random.randint(26, size=(M, ), dtype=np.int32)
DQ = np.stack([RD, RQ]).T
return D, C, S, M, DQ
@njit
def diff_satisfaction(C, S, d, p, last):
"""d日目にコンテストpを開催するときの、満足度の更新量を求める
"""
v = 0
for i in range(26):
v -= C[i] * (d - last[i])
v += C[p] * (d - last[p])
v += S[d, p]
return v
@njit
def change_schedule(D, C, S, T, d, q, cumsat):
"""d日目のコンテストをqに変更する
"""
p = T[d]
dp1, dq1 = -1, -1
dp3, dq3 = D, D
for i in range(0, d):
if T[i] == p:
dp1 = i
if T[i] == q:
dq1 = i
for i in range(D-1, d, -1):
if T[i] == p:
dp3 = i
if T[i] == q:
dq3 = i
cumsat = cumsat - S[d, p] + S[d, q] - C[p] * (dp3-d) * (d-dp1) + C[q] * (dq3-d) * (d-dq1)
return cumsat
@njit
def greedy(D, C, S):
T = np.zeros(D, dtype=np.int32)
last = -np.ones(26, dtype=np.int32)
cumsat = 0
for d in range(D):
max_p = 0
max_diff = -999999999
# select contest greedily
for p in range(26):
diff = diff_satisfaction(C, S, d, p, last)
if diff > max_diff:
max_p = p
max_diff = diff
# update schedule
cumsat += max_diff
T[d] = max_p
last[max_p] = d
return cumsat, T
@njit
def solve(D, C, S, M, DQ):
cumsat, T = greedy(D, C, S)
for i in range(M):
d, q = DQ[i, :]
newsat = change_schedule(D, C, S, T, d, q, cumsat)
if newsat > cumsat:
cumsat = newsat
T[d] = q
for t in T:
print(t+1)
if __name__ == '__main__':
inputs = read()
outputs = solve(*inputs)
if outputs is not None:
print("%s" % str(outputs))
| 0 | null | 10,206,817,875,408 | 117 | 113 |
n, k = map(int, input().split())
enemy = list(map(int, input().split()))
enemy.sort(reverse=True)
if n <= k :
print(0)
else :
for i in range(k) :
enemy[i] = 0
print(sum(enemy))
| def solve():
N, K = map(int, input().split())
H = list(map(int, input().split()))
H.sort()
ans = sum(H[:max(N-K,0)])
return ans
print(solve()) | 1 | 78,899,718,028,960 | null | 227 | 227 |
import sys
from collections import defaultdict
def input(): return sys.stdin.readline().rstrip()
def main():
H, W, K = map(int, input().split())
S = [input() for _ in range(H)]
ans = 10 ** 9
for bit in range(1 << (H-1)):
canSolve = True
ord = defaultdict(int)
N = 0
for i in range(H):
if bit & 1 << i:
ord[i+1] = ord[i] + 1
N += 1
else:
ord[i+1] = ord[i]
add = 0
nums = defaultdict(int)
for w in range(W):
one = defaultdict(int)
ok = True
for h in range(H):
one[ord[h]] += int(S[h][w])
nums[ord[h]] += int(S[h][w])
if one[ord[h]] > K:
canSolve = False
if nums[ord[h]] > K:
ok = False
if not ok:
add += 1
nums = one
if canSolve and ans > N + add:
ans = N + add
print(ans)
if __name__ == '__main__':
main()
| import itertools
def check(H, W, K, S, p):
num_groups = p.count(True) + 1
group_total = [0] * num_groups
ret = p.count(True)
for j in range(W):
group_value = [0] * num_groups
group_value[0] += int(S[0][j])
group_idx = 0
for i in range(H-1):
if p[i]:
group_idx += 1
group_value[group_idx] += int(S[i+1][j])
if max(group_value) > K:
return float("inf")
group_total_tmp = list(map(sum, zip(group_value, group_total)))
if max(group_total_tmp) <= K:
group_total = group_total_tmp
else:
group_total = group_value
ret += 1
return ret
def main():
H, W, K = map(int, input().split())
S = [input() for _ in range(H)]
ans = float("inf")
for p in itertools.product([True, False], repeat=H-1):
ans = min(ans, check(H, W, K, S, p))
print(ans)
if __name__ == "__main__":
main()
| 1 | 48,448,868,444,368 | null | 193 | 193 |
import math
def main():
K = int(input())
s = 0
for i in range(K):
for j in range(K):
tmp = math.gcd(i+1, j+1)
for k in range(K):
s += math.gcd(tmp, k+1)
print(s)
if __name__=="__main__":
main()
| N = int(input())
count = 0
for i in range(1, N):
if i != N - i:
count += 1
print(count // 2)
| 0 | null | 94,725,139,888,700 | 174 | 283 |
# モンスターの体力H
# アライグマの必殺技の種類N
# i番目の必殺技使うと、モンスターの体力Ai減らせる
# H - (A1 + A2 + A3...) <= 0 となるなら 'Yes',
# ならないなら'No'が出力される
h, n = map(int, input().split())
damage = list(map(int, input().split()))
if h - sum(damage) <= 0:
print("Yes")
else:
print("No") | n, m, x = map(int, input().split())
price = []
ability = []
for _ in range(n):
lst = []
lst = [int(i) for i in input().split()]
price.append(lst[0])
ability.append(lst[1:m + 1])
#print(price)
#print(ability)
min_price = float('inf')
for i in range(2 ** n):
flag = True
total = 0
obtain = [0] * m
for j in range(n):
if ((i >> j) & 1):
total += price[j]
for k in range(m):
obtain[k] += ability[j][k]
for j in range(m):
if obtain[j] < x:
flag = False
break
if flag:
if total < min_price:
min_price = total
if min_price == float('inf'):
print(-1)
else:
print(min_price) | 0 | null | 50,127,493,297,504 | 226 | 149 |
A, B, C, D = map(int, input().split())
if C % B == 0:
Takahashi_attacks = C // B
else:
Takahashi_attacks = C // B + 1
if A % D == 0:
Aoki_attacks = A // D
else:
Aoki_attacks = A // D + 1
if Takahashi_attacks <= Aoki_attacks:
print('Yes')
else:
print('No') | from math import ceil
a, b, c, d = map(int, input().split())
x = ceil(c/b)
y = ceil(a/d)
if x <= y:
print('Yes')
else:
print('No') | 1 | 29,919,405,873,280 | null | 164 | 164 |
#coding:utf-8
#1_6_A 2015.4.1
n = int(input())
numbers = list(map(int,input().split()))
for i in range(n):
if i == n - 1:
print(numbers[-i-1])
else:
print(numbers[-i-1], end = ' ') | # -*- coding:utf-8 -*-
x = 100000
n = int(input())
for i in range(n):
x = x + x*0.05
a = x // 1000
r = x % 1000
if r != 0:
x = 1000*a + 1000
else:
x = 1000*a
print(int(x)) | 0 | null | 479,452,242,418 | 53 | 6 |
W=input()
count=0
while True:
text=input()
if text == 'END_OF_TEXT':
break
else:
ls = list(map(str, text.split()))
for s in ls:
if s.lower() == W.lower():
count += 1
print(count) | N, K = map(int, input().split())
mod = 10 ** 9 + 7
cnt = [0] * (K + 1)
answer = 0
for i in range(K, 0, -1):
tmp = pow(K // i, N, mod) - sum(cnt[::i])
cnt[i] = tmp
answer = (answer + tmp * i) % mod
print(answer)
| 0 | null | 19,275,965,722,620 | 65 | 176 |
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time
def I(): return int(input())
def S(): return input()
def MI(): return map(int, input().split())
def MS(): return map(str, input().split())
def LI(): return [int(i) for i in input().split()]
def LI_(): return [int(i)-1 for i in input().split()]
def StoI(): return [ord(i)-97 for i in input()]
def ItoS(nn): return chr(nn+97)
def input(): return sys.stdin.readline().rstrip()
yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
show_flg = False
# show_flg = True
def main():
N = I()
a = LI()
dp = [0] * N
dp[1] = max(a[0], a[1])
c = a[0]
for i in range(2, N):
if i % 2 == 0:
c += a[i]
dp[i] = max(dp[i-2] + a[i], dp[i-1])
else:
dp[i] = max(dp[i-2] + a[i], c)
print(dp[-1])
if __name__ == '__main__':
main()
| from collections import defaultdict
def main():
INF = float("inf")
N, *A = map(int, open(0).read().split())
dp_in = defaultdict(lambda: -INF)
dp_out = defaultdict(lambda: -INF)
dp_out[(0, 0)] = 0
for i, a in enumerate(A, 1):
p = i // 2
for j in [p - 1, p, p + 1]:
dp_in[(i, j)] = a + dp_out[(i - 1, j - 1)]
dp_out[(i, j)] = max(dp_in[(i - 1, j)], dp_out[(i - 1, j)])
print(max(dp_in[(N, N // 2)], dp_out[(N, N // 2)]))
main() | 1 | 37,246,764,794,556 | null | 177 | 177 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
h, w = map(int, input().split())
if h == 1 or w == 1:
print(1)
sys.exit(0)
# a/bの切り上げ: (a + b - 1)//b
print(((h * w) + 2 - 1) // 2)
| h,w=map(int, input().split())
cnt=(w//2)*h
if w%2==1:
cnt+=h//2+h%2
if h==1 or w==1:
cnt=1
print(cnt) | 1 | 50,454,458,732,498 | null | 196 | 196 |
import math
X = int(input())
for k in range(1, 361):
if (k * X) % 360 == 0:
print(k)
break | n,k = map(int,input().split())
sunuke = []
for _ in range(k):
d = input()
tmp = [int(s) for s in input().split()]
for i in range(len(tmp)):
sunuke.append(tmp[i])
print(n - len(set(sunuke))) | 0 | null | 18,875,075,867,958 | 125 | 154 |
j = 1
def dfs(graph, start, result, visited=None):
global j
if visited == None:
visited = []
visited.append(start)
result[start][1] = j
for next in graph[start][2:]:
if next in visited:
continue
j += 1
dfs(graph, next, result, visited)
else:
j += 1
result[start][2] = j
n = int(input())
g = [[]]
r = [[i,0,0] for i in range(n + 1)]
v = []
for i in range(n):
g.append(list(map(int, input().split())))
for i in range(1, n + 1):
if i in v:
continue
dfs(g,i,r,v)
j += 1
for i in range(1,n+1):
print(*r[i]) | import abc
class AdjacentGraph:
"""Implementation adjacency-list Graph.
Beware ids are between 1 and size.
"""
def __init__(self, size):
self.size = size
self._nodes = [[0] * (size+1) for _ in range(size+1)]
def set_adj_node(self, id_, adj_id):
self._nodes[id_][adj_id] = 1
def __iter__(self):
self._id = 0
return self
def __next__(self):
if self._id < self.size:
self._id += 1
return (self._id, self._nodes[self._id][1:])
raise StopIteration()
def dfs(self, handler=None):
visited = []
while len(visited) < self.size:
for id_ in range(1, self.size+1):
if id_ not in visited:
stack = [(id_, 0)]
break
while len(stack) > 0:
i, j = stack.pop()
if j == 0:
if handler:
handler.visit(i)
visited.append(i)
yield i
try:
j = self._nodes[i].index(1, j+1)
stack.append((i, j))
if j not in visited:
stack.append((j, 0))
except ValueError:
if handler:
handler.leave(i)
class EventHandler(abc.ABC):
@abc.abstractmethod
def visit(self, i):
pass
@abc.abstractmethod
def leave(self, i):
pass
class Logger(EventHandler):
def __init__(self, n):
self.log = [(0, 0)] * n
self.step = 0
def visit(self, i):
self.step += 1
self.log[i-1] = (self.step, 0)
def leave(self, i):
self.step += 1
(n, m) = self.log[i-1]
self.log[i-1] = (n, self.step)
def by_node(self):
i = 1
for discover, finish in self.log:
yield (i, discover, finish)
i += 1
def run():
n = int(input())
g = AdjacentGraph(n)
log = Logger(n)
for i in range(n):
id_, c, *links = [int(x) for x in input().split()]
for n in links:
g.set_adj_node(id_, n)
for i in g.dfs(log):
pass
for node in log.by_node():
print(" ".join([str(i) for i in node]))
if __name__ == '__main__':
run()
| 1 | 2,966,204,150 | null | 8 | 8 |
def solve():
N, K = map(int, input().split())
As = list(map(int, input().split()))
Fs = list(map(int, input().split()))
As.sort()
Fs.sort(reverse=True)
def isOK(score):
d = 0
for A, F in zip(As, Fs):
if A*F > score:
d += -(-(A*F-score) // F)
return d <= K
ng, ok = -1, 10**12
while abs(ok-ng) > 1:
mid = (ng+ok) // 2
if isOK(mid):
ok = mid
else:
ng = mid
print(ok)
solve()
| #!/usr/bin/env pypy
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**6)
INF = float("inf")
import math
def solve(x, N, K, A, F):
total = 0
for i in range(N):
total += max(0, math.ceil((A[i]*F[i] - x) / F[i]))
if total <= K:
return True
else:
return False
def main():
N,K = map(int,input().split())
A = list(map(int,input().split()))
F = list(map(int,input().split()))
A.sort()
F.sort(reverse=True)
ok = 10**13+1
ng = -1
while ok - ng > 1:
mid = (ng + ok) // 2
if solve(mid, N, K, A, F):
ok = mid
else:
ng = mid
print(ok)
if __name__ == "__main__":
main() | 1 | 164,529,283,046,570 | null | 290 | 290 |
n = int(raw_input())
ai_list = map(int, raw_input().split())
max_ai = max(ai_list)
min_ai = min(ai_list)
sum_ai = sum(ai_list)
print '%d %d %d' % (min_ai, max_ai, sum_ai) | n = input()
l = map(int, raw_input().split())
max = l[0]
min = l[0]
s = l[0]
k = 1
while k < n:
if max < l[k]:
max = l[k]
if min > l[k]:
min = l[k]
s = s + l[k]
k = k + 1
print min, max, s | 1 | 718,127,499,710 | null | 48 | 48 |
s=input()
if len(s)%2!=0:
print("No")
else:
bool=False
for i in range(len(s)):
if i%2==0:
if s[i]!="h":
print("No")
bool=True
break
else:
if s[i]!="i":
print("No")
bool=True
break
if bool is False:
print("Yes")
| a, b, c, d, e = map(int, input().split())
if a == 0:
print(1)
if b == 0:
print(2)
if c == 0:
print(3)
if d == 0:
print(4)
if e == 0:
print(5)
| 0 | null | 33,289,709,816,242 | 199 | 126 |
N = input()
ans = "No"
for s in N:
if s == "7":
ans = "Yes"
break
print(ans) | while True:
a=map(int,raw_input().split())
if a==[0,0]:
break
if a[0]>a[1]:print(str(a[1])+" "+str(a[0]))
else: print(str(a[0])+" "+str(a[1])) | 0 | null | 17,370,868,456,732 | 172 | 43 |
from sys import stdin
while True:
(a, op, b) = stdin.readline().split(' ')
a = int(a)
b = int(b)
if op == "?":
break;
elif op == "+":
print(a + b)
elif op == "-":
print(a - b)
elif op == "*":
print(a * b)
elif op == "/":
print(a // b) | while 1:
a, b, c = raw_input().split()
if b == "?":
break
a = int(a)
c = int(c)
if b == "+":
print a+c
elif b == "-":
print a-c
elif b == "*":
print a*c
elif b == "/":
print a//c
| 1 | 691,690,302,980 | null | 47 | 47 |
fib = [1]*100
for i in range(2,100):
fib[i] = fib[i-1] + fib[i-2]
print(fib[int(input())])
| #!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin
def fibo(n):
a, b = 1, 1
while n:
a, b = b, a + b
n -= 1
return a
print(fibo(int(stdin.readline()))) | 1 | 1,893,129,502 | null | 7 | 7 |
N, K = map(int, input().split())
W = [0] * (N + 1)
W[1] = 1
R = []
for i in range(K):
l, r = map(int, input().split())
R.append((l, r))
MOD = 998244353
for i in range(1, N):
for l, r in R:
a = max(i - r, 0)
b = i - l
if b < 0:
continue
W[i + 1] += (W[b + 1] - W[a])
W[i + 1] %= MOD
W[i + 1] += W[i]
print(W[N] - W[N - 1])
| N, K = map(int, input().split())
mod = 998244353
move = []
for _ in range(K):
L, R = map(int, input().split())
move.append((L, R))
S = [0]*K
dp = [0]*(2*N)
dp[N] = 1
for i in range(N+1, 2*N):
for k, (l, r) in enumerate(move):
S[k] -= dp[i-r-1]
S[k] += dp[i-l]
dp[i] += S[k]
dp[i] %= mod
print(dp[-1]) | 1 | 2,687,141,566,928 | null | 74 | 74 |
n = int(input())
s, t = map(str, input().split())
new_word_list = []
for i in range(n):
new_word_list.append(s[i])
new_word_list.append(t[i])
print(''.join(new_word_list))
| import math
a,b,C = map(float,input().split())
C_rad=math.pi*C/180
print("{0:.8f}".format(math.sin(C_rad)*a*b/2))
print("{0:.8f}".format(a+b+math.sqrt(a**2+b**2-2*a*b*math.cos(C_rad))))
print("{0:.8f}".format(b*math.sin(C_rad))) | 0 | null | 55,813,283,417,302 | 255 | 30 |
def main():
import math
N = int(input())
ans=0
for i in range(1,N+1):
for j in range(1, N+1):
for k in range(1, N+1):
t=math.gcd(i,j)
t=math.gcd(t,k)
ans+=t
print(ans)
if __name__=='__main__':
main() | k=int(input())
l=['ACL']*k
print(*l,sep='')
| 0 | null | 18,939,526,861,500 | 174 | 69 |
S=str(input())
ans=''
for i in range(3):
ans+=S[i]
print(ans) | ct=0
def merge(A,left,mid,right):
global ct
n1=mid-left
n2=right-mid
l=[A[left+i] for i in xrange(n1)]
r=[A[mid+i] for i in xrange(n2)]
l.append(float('inf'))
r.append(float('inf'))
i=0
j=0
for k in xrange(left,right):
ct+=1
if l[i]<=r[j]:
A[k]=l[i]
i=i+1
else:
A[k]=r[j]
j=j+1
def mergesort(A,left,right):
if left+1<right:
mid=(left+right)/2
mergesort(A,left,mid)
mergesort(A,mid,right)
merge(A,left,mid,right)
n=input()
s=map(int,raw_input().split())
mergesort(s,0,n)
i=0
s=map(str,s)
print(" ".join(s))
print(ct) | 0 | null | 7,383,667,045,152 | 130 | 26 |
o = ['No','Yes']
f = 0
N = input()
s = str(N)
for c in s:
t = int(c)
if t == 7:
f = 1
print(o[f]) | def selectionSort(a, n):
count = 0
for i in range(0, n):
minj = i
for j in range(i, n):
if a[j] < a[minj]:
minj = j
a[i], a[minj] = a[minj], a[i]
if i != minj:
count += 1
return count
def main():
n = int(input())
a = [int(x) for x in input().split(' ')]
count = selectionSort(a, n)
print(' '.join([str(x) for x in a]))
print(count)
if __name__ == '__main__':
main() | 0 | null | 17,107,161,447,530 | 172 | 15 |
# -*- coding: utf-8 -*-
a, b = list(map(int, input().split()))
print(a * b)
| a, b = map(int, input().split())
answer = a * b
print(answer)
| 1 | 15,786,327,830,830 | null | 133 | 133 |
import sys
sys.setrecursionlimit(4100000)
import math
INF = 10**9
def main():
n = int(input())
s,t = input().split()
ans = ''
for i in range(n):
ans += s[i] + t[i]
print(ans)
if __name__ == '__main__':
main()
| n, m = map(int, input().split())
coins = list(map(int, input().split()))
coins = sorted(coins, reverse=False)
dp = [[float('inf')] * (n + 1) for _ in range(m)]
for j in range(n+1):
dp[0][j] = j
for i in range(m-1):
for j in range(n+1):
if j - coins[i+1] >= 0:
dp[i+1][j] = min(dp[i][j],
dp[i][j - coins[i+1]] + 1,
dp[i+1][j - coins[i+1]] + 1)
else:
dp[i+1][j] = dp[i][j]
print(dp[m-1][n])
| 0 | null | 55,944,490,218,220 | 255 | 28 |
def main():
import itertools
n = int(input())
test = []
for i in range(n):
a = int(input())
t = []
for j in range(a):
x,y = map(int,input().split())
t.append([x,y])
test.append(t)
stats = ((0,1) for i in range(n))
ans = 0
for k in itertools.product(*stats):
tf = [-1 for i in range(n)]
flg = 0
for i in range(len(k)):
if k[i]==1:
for t in test[i]:
if tf[t[0]-1]==-1:
tf[t[0]-1] = t[1]
else:
if tf[t[0]-1] != t[1]:
flg = 1
break
for i in range(len(k)):
if tf[i] != -1:
if tf[i] != k[i]:
flg = 1
break
if flg == 0:
if ans < sum(k):
ans = sum(k)
print(ans)
if __name__ == "__main__":
main()
| import sys
N = int(input())
List = [[-1] * N for i in range(N)]
for i in range(N):
A = int(input())
for j in range(A):
x, y = map(int, input().split())
List[i][x - 1] = y
Max = 0
for i in range(2 ** N):
flag = True
Sum = 0
for j in range(N): # このループが一番のポイント
if ((i >> j) & 1): # 順に右にシフトさせ最下位bitのチェックを行う
for k in range(N):
if (List[j][k] != int((i >> k) & 1)) and List[j][k] != -1:
flag = False
Sum += 1
if flag:
#print(i,Sum)
Max = max(Max, Sum)
print(Max)
| 1 | 121,471,132,850,912 | null | 262 | 262 |
import sys , math
from bisect import bisect
N=int(input())
alp="abcdefghijklmnopqrstuvwxyz"
R=[]
i=1
tot = 0
while tot < 1000000000000001:
tar = 26**i
tot+=tar
R.append(tot+1)
i+=1
keta = bisect(R , N)+1
if keta == 1:
print(alp[N-1])
sys.exit()
ans = ""
M = N - R[keta - 1]
for i in range(keta):
j = keta - i - 1
ind = M // (26**j)
M -= ind * (26**j)
ans+=alp[ind]
print(ans) | N = int(input())
A = list(map(int, input().split()))
t = 0
for c in A:
t ^= c
ans = []
for b in A:
ans.append(t^b)
print(*ans) | 0 | null | 12,300,801,700,528 | 121 | 123 |
l = int(input())
print(pow(l/3,3)) | L = int(input())
x = L/3
y = L/3
z = L/3
V = x * y * z
print(V) | 1 | 46,966,866,832,500 | null | 191 | 191 |
t = input()
n = int(input())
for i in range(n):
orders = input().split()
order = orders[0]
a = int(orders[1])
b = int(orders[2])
if order == "replace":
word = orders[3]
t = t[:a] + word + t[b+1:]
if order == "print":
print(t[a:b+1])
if order == "reverse":
t = t[:a] + t[a:b+1][::-1]+ t[b+1:]
| N=int(input())
s=set()
for _ in range(N):
S=input()
s|={S}
print(len(s))
| 0 | null | 16,270,382,717,872 | 68 | 165 |
n = int(input())
y =list(map(int,input().split()))
x = list()
for i in range(n-1,-1,-1):
arry = y[i]
x.append(arry)
for i in range(n):
if(i == n-1):
print('{}'.format(x[i]))
else:
print(x[i],end=' ')
| x, y = map(int, input().split())
ans = 'No'
for i in range(x + 1):
j = x - i
if i * 2 + j * 4 == y:
ans = 'Yes'
break
print(ans)
| 0 | null | 7,344,592,550,540 | 53 | 127 |
n,inc,dec=int(input()),[],[]
for _ in range(n):
s,d,r=input(),0,0
for c in s:
d=d+(1 if c=='(' else -1)
r=max(r,-d)
(dec if d<0 else inc).append((d,r))
inc.sort(key=lambda x:x[1])
dec.sort(key=lambda x:x[0]+x[1])
p1,p2,ok=0,0,True
for s in inc:
ok&=s[1]<=p1
p1+=s[0]
for s in dec:
ok&=p2>=s[0]+s[1]
p2-=s[0]
ok&=p1==p2
print('Yes'if ok else'No')
| def resolve():
H, W = list(map(int, input().split()))
S = [list(input()) for _ in range(H)]
import collections
maxdist = 0
for startx in range(H):
for starty in range(W):
if S[startx][starty] == "#":
continue
visited = [[-1 for _ in range(W)] for __ in range(H)]
visited[startx][starty] = 0
q = collections.deque([(startx, starty)])
while q:
x, y = q.pop()
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nx = x + dx
ny = y + dy
if 0 <= nx < H and 0 <= ny < W and S[nx][ny] != "#" and visited[nx][ny] == -1:
visited[nx][ny] = visited[x][y] + 1
q.appendleft((nx, ny))
maxdist = max(maxdist,max(sum(visited, [])))
print(maxdist)
if '__main__' == __name__:
resolve()
| 0 | null | 58,889,283,749,648 | 152 | 241 |
x = int(input())
n=100
tes = [0]
for i in range(-250,250):
for j in range(-250,250):
if pow(i,5) - pow(j,5) == x:
print(str(i)+" "+str(j))
exit() | inf = 10**10
n,m,l = map(int,input().split())
def warshall_floyd(d):
for i in range(n):
for j in range(n):
for k in range(n):
d[j][k] = min(d[j][k],d[j][i]+d[i][k])
return d
G = [[inf] * n for _ in range(n)] #重み付きグラフ
for i in range(n):
G[i][i] = 0
for _ in range(m):
a,b,c = map(int,input().split())
G[a-1][b-1] = c
G[b-1][a-1] = c
G = warshall_floyd(G)
P = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if i == j:
P[i][j] = 0
elif G[i][j] <= l:
P[i][j] = 1
else:
P[i][j] = inf
p = warshall_floyd(P)
q = int(input())
for _ in range(q):
s,t = map(int,input().split())
ans = p[s-1][t-1]-1
print(ans if ans <= 10**9 else -1) | 0 | null | 99,695,755,910,912 | 156 | 295 |
dice = list(map(int, input().split()))
q = int(input())
class Dice():
def __init__(self, dice, top, front):
self.dice = dice
self.top = top
self.front = front
def get_right(self):
right_list =[
(1, 2, 4, 3), #0
(0, 3, 5, 2), #1
(0, 1, 5, 4), #2
(0, 4, 5, 1), #3
(0, 2, 5, 3), #4
(1, 3, 4, 2) #5
]
for i in range(6):
if self.dice[i] == self.top:
for j in range(4):
if self.dice[right_list[i][j]] == self.front:
print(self.dice[right_list[i][j-3]])
for i in range(q):
top, front = map(int, input().split())
dice_right = Dice(dice, top, front)
dice_right.get_right()
| import random
class Dice():
def __init__(self):
self.face = [i for i in range(6)]
self.memo = [i for i in range(6)]
def setface(self,initface):
for i in range(6):
self.face[i] = initface[i]
def roll(self,direction):
for i in range(6):
self.memo[i] = self.face[i]
index = {'E':(3,1,0,5,4,2),'N':(1,5,2,3,0,4),'S':(4,0,2,3,5,1),'W':(2,1,5,0,4,3)}
for i in range(6):
self.face[i] = self.memo[index[direction][i]]
def top(self):
return self.face[0]
dice = Dice()
initface = list(map(int,input().split()))
dice.setface(initface)
q = int(input())
for _ in range(q):
u,f = map(int,input().split())
while True:
dice.roll(['E','N','S','W'][random.randint(0,3)])
if dice.face[0]==u and dice.face[1]==f:
print(dice.face[2])
break
| 1 | 258,521,743,744 | null | 34 | 34 |
import numpy as np
t1,t2 = map(int, input().split())
a1,a2 = map(int, input().split())
b1,b2 = map(int, input().split())
# まず大きい方にswap
if a1 <= b1:
a1,b1 = b1,a1
a2,b2 = b2,a2
# t1での距離
x1 = a1*t1 - b1*t1
# t2での距離
x2 = x1 + a2*t2 - b2*t2
if x2 == 0:
print("infinity")
elif x2 > 0:
print(0)
else:
ans = int(np.ceil(x1/abs(x2))*2)
if x1 % abs(x2) != 0:
ans -= 1
print(ans) | 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:
if((-P)%(P+Q)==0):
print((-P)//(P+Q)*2)
else:
print((-P)//(P+Q)*2+1) | 1 | 132,089,290,712,932 | null | 269 | 269 |
n = int(input())
s = input()
ans = 0
for i in range(n - 2):
a = s[i:i + 3]
if a == "ABC":
ans += 1
print(ans) | x, y = map(int, input().split())
ans = 0
for i in range(0, x + 1):
# i is the number of the crane
rest = y - (2 * i)
if rest / 4 == x - i:
print('Yes')
ans = 1
break
if ans == 0:
print('No')
| 0 | null | 56,299,722,690,720 | 245 | 127 |
def II(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
N=II()
A=LI()
#A.sort()
SA=sum(A)
#print(SA)
AccA=[A[0]]
for i in range(1,N):
AccA.append(AccA[-1]+A[i])
#AccA.reverse()
ans=0
for i in range(N-1):
ans+=A[i]*(SA-AccA[i])
ans=ans%(10**9+7)
print(ans) | N = int(input())
A = list(map(int, input().split()))
B = []
b = 0
e = 10 ** 9 + 7
for i in range(N - 1):
b += A[N - 1 - i]
b = b % e
B.append(b)
result = 0
for i in range(N - 1):
result += A[i] * B[N - 2 - i]
result = result % e
print(result) | 1 | 3,830,469,187,470 | null | 83 | 83 |
import os, sys, re, math
import itertools
N = int(input())
P = tuple([int(n) for n in input().split()])
Q = tuple([int(n) for n in input().split()])
nums = [n for n in range(1, N + 1)]
patterns = itertools.permutations(nums, N)
i = 0
for pattern in patterns:
if pattern == P:
pi = i
if pattern == Q:
qi = i
i += 1
print(abs(pi - qi)) | #k = int(input())
#s = input()
#a, b = map(int, input().split())
#s, t = map(str, input().split())
#l = list(map(int, input().split()))
#l = [list(map(int,input().split())) for i in range(n)]
#a = [input() for _ in range(n)]
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
if (p == q):
print(0)
exit()
seq = []
for i in range(1,n+1):
seq.append(i)
t = list(itertools.permutations(seq))
ans = []
for i in range(len(t)):
if list(t[i]) == p or list(t[i]) == q:
ans.append(i)
print(ans[1]-ans[0])
| 1 | 100,630,333,887,490 | null | 246 | 246 |
N = int(input())
P = tuple(map(int, input().split()))
minp = P[0]
ans = 1
for i in range(1, N):
if P[i] <= minp:
ans += 1
minp = min(minp, P[i])
print(ans) | from collections import deque
def main():
process_count, process_time, processes = get_input()
result = run_roundrobin(processes=processes, time=process_time)
for r in result:
print(r.name, r.time)
def run_roundrobin(processes, time, total_time=0, result=[]):
while processes:
p = processes.popleft()
if p.time <= time:
total_time += p.time
p.time = total_time
result.append(p)
else:
total_time += time
p.time -= time
processes.append(p)
return result
def get_input():
count, time = list(map(lambda x: int(x), input().split(' ')))
processes = deque([])
for _ in range(count):
im = input().split(' ')
p = Process(im[0], int(im[1]))
processes.append(p)
return count, time, processes
class Process():
def __init__(self, name, time):
self.name = name
self.time = time
main() | 0 | null | 42,486,503,524,010 | 233 | 19 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
face = sys.stdin.readline().split()
right = [[None for front in range(6)] for top in range(6)]
# Top:1 Face:2 -> Right:3, Top:2 Face:6 -> Right:3 ...
right[0][1] = right[1][5] = right[5][4] = right[4][0] = 3 - 1
right[1][0] = right[5][1] = right[4][5] = right[0][4] = 4 - 1
right[0][2] = right[2][5] = right[5][3] = right[3][0] = 5 - 1
right[2][0] = right[5][2] = right[3][5] = right[0][3] = 2 - 1
right[3][1] = right[1][2] = right[2][4] = right[4][3] = 1 - 1
right[1][3] = right[2][1] = right[4][2] = right[3][4] = 6 - 1
# print(right)
q = int(sys.stdin.readline())
for i in range(q):
top, front = sys.stdin.readline().split()
r_index = right[face.index(top)][face.index(front)]
print(face[r_index])
| x,y = map(int,input().split())
a = (4*x-y)/2
b = (-2*x+y)/2
if a%1 == 0 and 0 <= a and b%1 == 0 and 0 <=b:
print("Yes")
else:
print("No")
| 0 | null | 7,042,057,197,270 | 34 | 127 |
def resolve():
N = int(input())
A = list(map(int, input().split()))
B = A[0]
for i in range(1, N):
B = B^A[i]
ans = []
for i in range(N):
ans.append(B^A[i])
print(*ans)
if __name__ == "__main__":
resolve()
| import math
R = int(input())
pi = math.pi
ans = 2*R * pi
print(ans) | 0 | null | 21,804,937,289,252 | 123 | 167 |
a, b = input().split()
a = int(a)
b1, b2 = b.split('.')
b3 = int(b1)*100 + int(b2)
print(a*b3//100)
| import math
A, B = input().split()
A = int(A)
B = int(B.replace(".", ""))
ans = (A * B) // 100
print(ans)
| 1 | 16,502,003,428,262 | null | 135 | 135 |
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
i8 = np.int64
i4 = np.int32
def main():
stdin = open('/dev/stdin')
pin = np.fromstring(stdin.read(), i8, sep=' ')
N = pin[0]
M = pin[1]
L = pin[2]
ABC = pin[3: M * 3 + 3].reshape((-1, 3))
A = ABC[:, 0] - 1
B = ABC[:, 1] - 1
C = ABC[:, 2]
Q = pin[M * 3 + 3]
st = (pin[M * 3 + 4: 2 * Q + M * 3 + 4] - 1).reshape((-1, 2))
s = st[:, 0]
t = st[:, 1]
graph = csr_matrix((C, (A, B)), shape=(N, N))
dist = np.array(floyd_warshall(graph, directed=False))
dist[dist > L + 0.5] = 0
dist[dist > 0] = 1
min_dist = np.array(floyd_warshall(dist))
min_dist[min_dist == np.inf] = 0
min_dist = (min_dist + .5).astype(int)
x = min_dist[s, t] - 1
print('\n'.join(x.astype(str).tolist()))
if __name__ == '__main__':
main()
| tmp = int(input())
if tmp>=30:
print("Yes")
else:
print("No") | 0 | null | 89,866,478,921,868 | 295 | 95 |
n, k = (int(x) for x in input().split())
# すぬけ君は全員お菓子を持っていないと仮定する
list_snuke = [str(i) for i in range(1, n + 1)]
# お菓子をもっているすぬけ君の番号を削除
# appendではなくリスト内包表記で書きたい
for i in range(0, k):
d = int(input())
a = [s for s in input().split()]
for j in range(0, d):
if a[j] in list_snuke:
list_snuke.remove(a[j])
# お菓子をもっていないすぬけ君の人数を出力
print(len(list_snuke)) | n,k = map(int,input().split())
t = [1]*n
for i in range(k):
input()
for j in map(int,input().split()):
t[j-1] = 0
print(sum(t)) | 1 | 24,534,815,945,222 | null | 154 | 154 |
from fractions import gcd
from functools import reduce
def lcm(x,y):
return (x*y)//gcd(x,y)
def lcm_list(nums):
return reduce(lcm,nums,1)
mod=10**9+7
n=int(input())
A=list(map(int,input().split()))
num=lcm_list(A)
cnt=0
for i in A:
cnt +=num//i
print(cnt%mod) | # https://atcoder.jp/contests/abc152/tasks/abc152_e
# 1 <= i < j <= N (i < j)について AiBi = AjBjが成り立つBの和の最小値
# LCM/Ai
from collections import defaultdict
from math import gcd
MOD = 10 ** 9 + 7
N = int(input())
A = list(map(int, input().split()))
lcm = A[0]
for a in A:
lcm = (lcm * a) // gcd(lcm, a)
lcm %= MOD
# フェルマーの小定理 a^{P-1} = 1 (mod P)
ans = 0
for a in A:
ans += lcm * pow(a, MOD - 2, MOD) % MOD
ans %= MOD
print(ans) | 1 | 87,891,743,049,066 | null | 235 | 235 |
H,W=map(int,input().split())
w1=0--W//2
w2=W//2
if H==1 or W==1:
print(1)
else:
print(w1*(0--H//2)+w2*(H//2)) | N = int(input())
n = 0
if not N%2:
s = 5
N = N//2
while N>=s:
n += N//s
s *= 5
print(n)
| 0 | null | 82,970,067,520,592 | 196 | 258 |
import math
from collections import deque
N,D,A = map(int,input().split(' '))
XHn = [ list(map(int,input().split(' '))) for _ in range(N)]
ans = 0
XHn.sort()
attacks = deque([]) # (区間,攻撃回数)
attack = 0
ans = 0
for i in range(N):
x = XHn[i][0]
h = XHn[i][1]
while len(attacks) > 0 and x > attacks[0][0]:
distance,attack_num = attacks.popleft()
attack -= attack_num*A
if h > attack:
diff = h - attack
distance_attack = x + D*2
need_attack = math.ceil(diff/A)
attacks.append((distance_attack,need_attack))
attack += A*need_attack
ans += need_attack
print(ans) | import itertools
import math
N = int(input())
L = [list(map(int,input().split())) for n in range(N)]
I = list(itertools.permutations(L))
sum = 0
for i in I:
for n in range(N-1):
sum += math.sqrt((i[n+1][0]-i[n][0])**2+(i[n+1][1]-i[n][1])**2)
print(sum/len(I)) | 0 | null | 114,881,691,530,452 | 230 | 280 |
import string
print raw_input().translate(string.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')) | n = list(raw_input())
for i in xrange(len(n)):
if n[i].isupper(): n[i]=n[i].lower()
elif n[i].islower(): n[i]=n[i].upper()
print ''.join(n) | 1 | 1,511,619,548,626 | null | 61 | 61 |
# def gen_is_prim(n):
# is_prim = [i%2==1 for i in range(n+1)]
# is_prim[1] = False; is_prim[2] = True
# for i in range(3, n+1, 2):
# if not is_prim[i]: continue
# for j in range(i+i, n+1, i):
# is_prim[j] = False
# return is_prim
def gen_d_prim(n):
D = [n+1 if i%2 else 2 for i in range(n+1)]
D[0] = D[1] = 0
for i in range(3, n+1, 2):
if D[i] != n+1: continue
for j in range(i, n+1, i): D[j] = i
return D
def gcd_all(A):
from math import gcd
g = 0
for a in A: g = gcd(g, a)
return g
def is_pairwise():
# MAX_A = 10**6 + 1
# C = [0] * MAX_A
# for a in A: C[a] += 1
# if sum(C[2::2]) > 1: return False
# for i in range(3, MAX_A, 2):
# if sum(C[i::i]) > 1: return False
# return True
MAX_A = 10**6
D = gen_d_prim(MAX_A)
C = [0] * (MAX_A + 1)
all_p = set()
for a in A:
p = set()
while a != 1:
if not D[a] in p:
if D[a] in all_p:
return False
all_p.add(D[a])
p.add(D[a])
a //= D[a]
# print('pre {}'.format(pre))
# print('now {}'.format(now))
# print('now & pre {}'.format(now & pre))
# if len(now & all) > 0: return False
# all = all | now
return True
def solve():
if is_pairwise(): return 0
if gcd_all(A) == 1: return 1
return 2
# if gcd_all(A) > 1: return 2
# if is_pairwise(): return 0
# return 1
n = int(input())
A = [*map(int, input().split())]
print(['pairwise','setwise','not'][solve()], 'coprime')
| num = list(map(int,input().split()))
print("%d %d %f" %(num[0]/num[1],num[0]%num[1],num[0]/num[1] ))
| 0 | null | 2,357,921,826,898 | 85 | 45 |
import math
PI = math.pi
r = input()
men = r*r * PI
sen = r*2 * PI
print('%.6f %.6f' % (men, sen)) | r=float(raw_input())
p=float(3.14159265358979323846264338327950288)
s=p*r**2.0
l=2.0*p*r
print"%.5f %.5f"%(float(s),float(l)) | 1 | 640,195,121,520 | null | 46 | 46 |
import math
INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))
def do():
n=INT()
ans=0
for i in range(1,n+1):
if i%3==0 or i%5==0:
pass
else:
ans+=i
print(ans)
if __name__ == '__main__':
do() | t = input().lower()
cnt = 0
while True:
w = input()
if w == 'END_OF_TEXT': break
cnt += len(list(filter(lambda x: x == t, [v.lower() for v in w.split(' ')])))
print(cnt)
| 0 | null | 18,385,409,676,380 | 173 | 65 |
# Template 1.0
import sys, re
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, log
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx): return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))
toret = {}
for tup in temp:
toret[tup[0]] = tup[1]
return toret
def sortDictWithKey(passedDic):
return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
n = INT()
a = LIST()
flag = 0
for el in a:
if(el%2==0):
if(el%3==0 or el%5==0):
continue
else:
flag = 1
break
if(flag==0):
print("APPROVED")
else:
print("DENIED") | N = int(input())
A = list(map(int,input().split()))
for i in range(N):
if A[i] % 2 ==0:
if A[i] % 3 ==0 or A[i] % 5 ==0:
pass
if i == N-1:
print('APPROVED')
else:
pass
else:
print('DENIED')
break
else:
if i == N-1:
print('APPROVED')
else:
pass | 1 | 69,040,719,470,688 | null | 217 | 217 |
from math import gcd
def mod_prod(X,M):
c=1
for x in X:
c*=x
c%=M
return c
N=int(input())
A=list(map(int,input().split()))
Mod=10**9+7
E=[0]*N
a=1
for i in range(N):
E[i]=A[i]//gcd(a,A[i])
a*=E[i]
P=mod_prod(E,Mod)
Q=0
for a in A:
Q+=pow(a,Mod-2,Mod)
Q%=Mod
print((P*Q)%Mod) | import math
N = int(input())
A = list(map(int, input().split()))
mod = 10**9+7
def lcm(x, y):
return (x // math.gcd(x, y)) * y
LCM = A[0]
for i in range(N-1):
LCM = lcm(LCM, A[i+1])
#LCM %= mod
ans = 0
for a in A:
ans += LCM * pow(a, mod-2, mod) % mod
ans %= mod
print(ans) | 1 | 87,903,053,248,710 | null | 235 | 235 |
N = int(input())
A = list(map(int, input().split()))
mod = 10**9+7
D = {}
for a in A:
bit = bin(a)[2:][::-1]
for i in range(len(bit)):
if bit[i] == '1':
if i not in D:
D[i] = 1
else:
D[i] += 1
ans = 0
for k, v in D.items():
ans += (N-v)*v*2**k % mod
ans = ans % mod
print(ans) | import sys
from collections import defaultdict, deque, Counter
import math
# import copy
from bisect import bisect_left, bisect_right
import heapq
# sys.setrecursionlimit(1000000)
# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]
INF = 10 ** 20
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)
def nck(n, k, kaijyo):
return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD
def npk(n, k, kaijyo):
if k == 0 or k == n:
return n % MOD
return (kaijyo[n] * divide(kaijyo[n-k])) % MOD
def kaijyo(n):
ret = [1]
for i in range(1, n + 1):
ret.append((ret[-1] * i)% MOD)
return ret
def solve():
n = getN()
nums = getList()
keta = [[0, 0] for i in range(62)]
for num in nums:
tmp = num
for i in range(62):
if tmp % 2 == 1:
keta[i][1] += 1
else:
keta[i][0] += 1
tmp //= 2
ans = 0
dig = 0
for k1, k2 in keta:
ans += ((k1 * k2) * (2**dig)) % MOD
dig += 1
print(ans % MOD)
def main():
n = getN()
for _ in range(n):
solve()
if __name__ == "__main__":
# main()
solve() | 1 | 123,526,782,436,574 | null | 263 | 263 |
k=int(input())
flag=0
s=0
for i in range(1,9*k):
s+=7
s%=k
if s==0:
flag=i
break
s*=10
if flag:
print(flag)
else:
print(-1)
| N=int(input())
L=list(map(int, input().split()))
L=sorted(L)
import bisect
ans=0
for i in range(N-1):
for j in range(i+1,N):
a=L[i]
b=L[j]
upper = bisect.bisect_left(L,a+b)
lower=max(j+1, bisect.bisect_right(L, a-b), bisect.bisect_right(L, b-a))
#print(upper, lower)
ans+=max(0, upper-lower)
print(ans) | 0 | null | 88,662,900,345,538 | 97 | 294 |
n=int(input())
a=[]
for i in range(1,int(n**(1/2))+1):
if n%i==0:
a.append(i)
a.append(int(n/i))
print(a[-1]+a[-2]-2 if len(a)%2==0 else a[-1]*2-2) | import math
n=int(input())
m=int(math.sqrt(n))+1
for i in range(m):
if n%(m-i)==0:
k=m-i
l=n//(m-i)
break
print(k+l-2) | 1 | 162,000,168,310,980 | null | 288 | 288 |
def resolve():
N = int(input())
g = {}
for i in range(N-1):
a, b = list(map(int, input().split()))
g.setdefault(a-1, [])
g[a-1].append((b-1, i))
g.setdefault(b-1, [])
g[b-1].append((a-1, i))
nodes = [(None, 0)]
colors = [None for _ in range(N-1)]
maxdeg = 0
while nodes:
prevcol, node = nodes.pop()
maxdeg = max(maxdeg, len(g[node]))
color = 1 if prevcol != 1 else 2
for nxt, colidx in g[node]:
if colors[colidx] is None:
colors[colidx] = color
nodes.append((color, nxt))
color += 1 if prevcol != color+1 else 2
print(maxdeg)
for col in colors:
print(col)
if '__main__' == __name__:
resolve()
| from sys import stdin
while True:
(a, op, b) = stdin.readline().split(' ')
a = int(a)
b = int(b)
if op == "?":
break;
elif op == "+":
print(a + b)
elif op == "-":
print(a - b)
elif op == "*":
print(a * b)
elif op == "/":
print(a // b) | 0 | null | 68,556,434,393,150 | 272 | 47 |
# -*-coding:utf-8
import math
def main():
a, b, degree = map(int, input().split())
radian = math.radians(degree)
S = 0.5*a*b*math.sin(radian)
x = a + b + math.sqrt(pow(a,2)+pow(b,2)-2*a*b*math.cos(radian))
print('%.8f' % S)
print('%.8f' % x)
print('%.8f' % ((2*S)/a))
if __name__ == '__main__':
main() | #coding = utf-8
import math
a, b, c = map(float, raw_input().split())
h = b * math.sin(math.pi*c/180)
s = a * h / 2
x = math.sqrt(h**2 + (a-b*math.sin(math.pi*(90-c)/180))**2)
l = a + b + x
#print "%.8f, %.8f, %.8f" % (s, l, h)
print "\n".join([str(s), str(l), str(h)])
#print "%.1f, %.1f, %.1f" % (s, l, h) | 1 | 176,716,216,050 | null | 30 | 30 |
inps = input().split()
if len(inps) >= 3:
a = int(inps[0])
b = int(inps[1])
c = int(inps[2])
if a < b and b < c:
print("Yes")
else:
print("No")
else:
print("Input illegal.") | in_str = input().split(" ")
a = int(in_str[0])
b = int(in_str[1])
c = int(in_str[2])
if a < b:
if b < c:
print("Yes")
else:
print("No")
else:
print("No") | 1 | 391,751,799,158 | null | 39 | 39 |
strn = list(input())
intn = []
for i in strn:
intn.append(int(i))
if sum(intn) % 9 == 0:
print('Yes')
else:
print('No')
| # coding: utf-8
N = list(map(int,list(input())))
sN = sum(N)
if sN%9 ==0:
print("Yes")
else:
print("No")
| 1 | 4,396,036,139,220 | null | 87 | 87 |
import time as ti
class MyQueue(object):
"""
My Queue class
Attributes:
queue: queue
head
tail
"""
def __init__(self):
"""Constructor
"""
self.length = 50010
self.queue = []
counter = 0
while counter < self.length:
self.queue.append(Process())
counter += 1
self.head = 0
self.tail = 0
def enqueue(self, name, time):
"""enqueue method
Args:
name: enqueued process name
time: enqueued process time
Returns:
None
"""
self.queue[self.tail].name = name
self.queue[self.tail].time = time
self.tail = (self.tail + 1) % self.length
def dequeue(self):
"""dequeue method
Returns:
None
"""
self.queue[self.head].name = ""
self.queue[self.head].time = 0
self.head = (self.head + 1) % self.length
def is_empty(self):
"""check queue is empty or not
Returns:
Bool
"""
if self.head == self.tail:
return True
else:
return False
def is_full(self):
"""chech whether queue is full or not"""
if self.tail - self.head >= len(self.queue):
return True
else:
return False
class Process(object):
"""process class
"""
def __init__(self, name="", time=0):
"""constructor
Args:
name: name
time: time
"""
self.name = name
self.time = time
def forward_time(self, time):
"""time forward method
Args:
time: forward time interval
Returns:
remain time
"""
self.time -= time
return self.time
def time_forward(my_queue, interval, current_time, end_time_list):
"""
Args:
my_queue: queue
interval: time step interval
current_time: current time
"""
value = my_queue.queue[my_queue.head].forward_time(interval)
if value <= 0:
current_time += (interval + value)
end_time_list.append([my_queue.queue[my_queue.head].name, current_time])
# print my_queue.queue[my_queue.head].name, current_time
my_queue.dequeue()
elif value > 0:
current_time += interval
name, time = my_queue.queue[my_queue.head].name, \
my_queue.queue[my_queue.head].time
my_queue.dequeue()
my_queue.enqueue(name, time)
return current_time
my_queue = MyQueue()
n, q = [int(x) for x in raw_input().split()]
counter = 0
while counter < n:
name, time = raw_input().split()
my_queue.enqueue(name, int(time))
counter += 1
end_time_list = []
current_time = 0
while not my_queue.is_empty():
current_time = time_forward(my_queue, q, current_time, end_time_list)
for data in end_time_list:
print data[0], data[1] | from decimal import *
getcontext().prec=1000
a,b,c=map(int,input().split())
A=Decimal(a)**Decimal("0.5")
B=Decimal(b)**Decimal("0.5")
C=Decimal(c)**Decimal("0.5")
D= Decimal(10) ** (-100)
if A+B+D<C:
print("Yes")
else:
print("No") | 0 | null | 25,790,004,508,320 | 19 | 197 |
a,b=map(int, input().split())
if 1<=a*b and a*b<=81 and a<10 and b<10:
print(a*b)
else:
print(-1)
| import collections
N=int(input())
P=[input() for i in range(N)]
c=collections.Counter(P)
print(len(c)) | 0 | null | 94,092,470,028,128 | 286 | 165 |
n, x, t = map(int, input().split())
i = 0
while True:
i += 1
if i*x >= n :
break
print(i*t) | from math import ceil
N,X,T = list(map(int,input().split(' ')))
print(ceil(N/X)*T) | 1 | 4,287,965,604,212 | null | 86 | 86 |
from collections import Counter
N = int(input())
A = list(map(int, input().split()))
L = [-1 for _ in range(N)]
R = [-1 for _ in range(N)]
for i in range(N):
L[i] = A[i] - i-1
R[i] = A[i] + i+1
# L = -R となる物のうち、i>jになりゃいいんだけど、最後にいくつかで破れば良い気がす
# i > 0 なので、自分自身を2回選んでL=Rみたいにはならない・・・?
LC = Counter(L)
RC = Counter(R)
ans = 0
for k,v in LC.items():
if (-1) * k in RC:
ans += v * RC[(-1)*k]
#print(k,v,(-1)*k,RC[(-1)*k], ans)
print(ans)
| import sys
from functools import lru_cache
from collections import defaultdict
inf = float('inf')
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10**6)
def input(): return sys.stdin.readline().rstrip()
def read():
return int(readline())
def reads():
return map(int, readline().split())
x=read()
a=list(reads())
dic=[]
dic2=defaultdict(int)
for i in range(x):
dic.append(i+a[i])
dic2[i-a[i]]+=1
ans=0
#print(dic,dic2)
for i in dic:
ans+=dic2[i]
print(ans)
| 1 | 26,256,786,066,660 | null | 157 | 157 |
import itertools
n=int(input())
a= list(map(int, input().split()))
# aを偶数奇数の要素で振り分け
a1=[]
a2=[]
for i in range(n):
if i%2==0:
a1.append(a[i])
else:
a2.append(a[i])
# 累積和も作っておく
a3=list(itertools.accumulate(a1))
a4=list(itertools.accumulate(a2))
x1=sum(a1)
x2=sum(a2)
if n%2==0:
ans=-float('inf')
for i in range(n//2):
ans=max(a3[i]+x2-a4[i],ans)
print(max(ans,x1,x2))
else:
# 奇数番目だけの要素を選んだ時の最大値
ans1=sum(a1)-min(a1)
# dp1[i]=奇数偶数奇数or偶数奇数と移動した時のi番目までのMAX
dp1 = [-float('inf')] * (n // 2 + 1)
dp1[0] = a1[0]
# dp2[i]=奇数偶数or偶数のみと移動した時のi番目までのMAX
dp2 = [-float('inf')] * (n // 2)
dp2[0] = a2[0]
for i in range(n // 2 - 1):
dp2[i + 1] = max(a3[i] + a2[i + 1], dp2[i] + a2[i + 1])
if i==0:
dp1[i + 2] = dp2[i] + a1[i + 2]
else:
dp1[i + 2] = max(dp2[i] + a1[i + 2], dp1[i + 1] + a1[i + 2])
print(max(dp1[-1], dp2[-1],ans1)) | n = int(input())
a = list(map(int,input().split()))
# i個使う時の要素の和の最大値
dp = [0]*(n+1)
dp[1] = 0
dp[2] = max(a[0],a[1])
# 奇数の番号の累積和
b = [0]*(n+1)
b[1] = a[0]
for i in range(1,n-1,2):
b[i+2] = b[i] + a[i+1]
# print(b)
for i in range(3,n+1):
if i % 2 == 0:
dp[i] = max(dp[i-2] + a[i-1], b[i-1])
else:
dp[i] = max(dp[i-2] + a[i-1], dp[i-3] + a[i-2], b[i-2])
# print(dp)
print(dp[n]) | 1 | 37,388,717,370,080 | null | 177 | 177 |
n=input()
s=range(1,14)
h=range(1,14)
c=range(1,14)
d=range(1,14)
trump={'S':s,'C':c,'H':h,'D':d}
for i in range(n):
suit,num=raw_input().split()
num=int(num)
trump[suit].remove(num)
count=0
for suit in ['S','H','C','D']:
for num in trump[suit]:
print('%s %d'%(suit,num)) |
def check(mlist, s):
if len(mlist) == 13:
return 0
else:
lack = []
for i in range(1, 14):
if not i in mlist:
lack.append(i)
#print(lack)
for j in lack:
print("{} {}".format(s, j))
return 0
n = int(input())
Slist = []
Hlist = []
Clist = []
Dlist = []
for i in range(n):
mark, num = input().split()
num = int(num)
if mark == 'S':
Slist.append(num)
elif mark == 'H':
Hlist.append(num)
elif mark == 'C':
Clist.append(num)
else:
Dlist.append(num)
Slist.sort()
Hlist.sort()
Clist.sort()
Dlist.sort()
check(Slist, 'S')
check(Hlist, 'H')
check(Clist, 'C')
check(Dlist, 'D')
| 1 | 1,033,649,307,300 | null | 54 | 54 |
N,M = map(int,input().split())
ans = [-1]*N
flg = 0
for i in range(M):
s,c = map(int, input().split())
s -= 1
if ans[s] == -1 or ans[s] == c:
ans[s] = c
else:
flg = 1
if flg == 0:
if N == 1 and ans[0] == -1 or N == 1 and ans[0] == 0:
print("0")
elif ans[0] == 0:
print("-1")
else:
if ans[0] == -1:
ans[0] = 1
for i in range(1,N):
if ans[i] == -1:
ans[i] = 0
print(int("".join(map(str,ans))))
else:
print("-1") | n,m=map(int,input().split())
sc=[list(map(int,input().split())) for _ in range(m)]
for i in range(10**n):
ans=str(i)
if len(ans)==n and all(ans[s-1]==str(c) for s,c in sc):
print(ans)
exit()
print(-1) | 1 | 60,670,064,704,000 | null | 208 | 208 |
from collections import defaultdict
N, u, v = map(int, input().split())
d = defaultdict(list)
for _ in range(N-1):
A, B = map(int, input().split())
d[A].append(B)
d[B].append(A)
def get_dist(s):
dist = [-1]*(N+1)
dist[s] = 0
q = [s]
while q:
a = q.pop()
for b in d[a]:
if dist[b]!=-1:
continue
dist[b] = dist[a] + 1
q.append(b)
return dist
du, dv = get_dist(u), get_dist(v)
ds = [(i,j[0], j[1]) for i,j in enumerate(zip(du, dv)) if j[0]<j[1]]
ds.sort(key=lambda x:-x[2])
a, b, c = ds[0]
print(c-1) | import math
foo = []
while True:
n = int(input())
if n == 0:
break
a = [int(x) for x in input().split()]
ave = sum(a)/len(a)
hoge = 0
for i in a:
hoge += (i - ave) ** 2
hoge /= len(a)
foo += [math.sqrt(hoge)]
for i in foo:
print(i) | 0 | null | 58,550,754,138,240 | 259 | 31 |
n = int(input())
print(len(set([input() for i in range(n)]))) | #!/usr/bin/env python3
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def main():
K, X = map(int, readline().split())
if 500 * K >= X:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main()
| 0 | null | 64,302,337,902,220 | 165 | 244 |
N,K = map(int,input().split())
if N<=K :
print(0)
else :
H = list(map(int,input().split()))
H.sort()
if 0<K :
del H[-K:]
print(sum(H)) | n,k=map(int,input().split());print(sum(sorted(map(int,input().split()),reverse=True)[k:])) | 1 | 78,816,641,250,880 | null | 227 | 227 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.