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;
for line in sys.stdin:
n = int(line);
for i in range(0, n):
a = [int(num) for num in input().split()];
a.sort();
if a[2] ** 2 == (a[0] ** 2) + (a[1] ** 2):
print('YES');
else:
print('NO'); | import sys
N = int(raw_input())
for line in sys.stdin:
a, b, c = sorted(map(int, line.split()))
if a ** 2 + b ** 2 == c ** 2:
print 'YES'
else:
print 'NO' | 1 | 340,406,928 | null | 4 | 4 |
def solve(string):
n, c = string.split()
n, c = int(n), list(c)
wi, ri = 0, n - 1
while wi < n and c[wi] == "R":
wi += 1
while ri >= 0 and c[ri] == "W":
ri -= 1
ans = 0
while wi < n and ri >= 0 and wi < ri:
c[wi], c[ri], ans = c[ri], c[wi], ans + 1
wi, ri = wi + 1, ri - 1
while wi < n and c[wi] == "R":
wi += 1
while ri >= 0 and c[ri] == "W":
ri -= 1
return str(ans)
if __name__ == '__main__':
import sys
print(solve(sys.stdin.read().strip())) | a,b,c,k = map(int,input().split())
s = 0
if k <= a:
s = k
elif k <= a + b:
s = a
else:
s = a - (k - a - b)
print(s) | 0 | null | 13,939,154,345,832 | 98 | 148 |
import sys
def input(): return sys.stdin.readline().strip()
def resolve():
x,y=map(int, input().split())
ans=0
if x<=3:
ans+=100000
if x<=2:
ans+=100000
if x==1:
ans+=100000
if y<=3:
ans+=100000
if y<=2:
ans+=100000
if y==1:
ans+=100000
if x==1 and y==1:
ans+=400000
print(ans)
resolve()
| data = list(input().split(" "))
stack = []
for d in data:
if d == '+':
stack.append(stack.pop() + stack.pop())
elif d == '-':
stack.append(- stack.pop() + stack.pop())
elif d == '*':
stack.append(stack.pop() * stack.pop())
else:
stack.append(int(d))
print(stack[0]) | 0 | null | 70,140,790,738,020 | 275 | 18 |
n=int(input())
li=[]
ans=0
flug=0
for i in range(n):
li.append(input().split())
x=input()
for j in range(n):
if flug==0:
if li[j][0]==x:
flug=1
else:
ans+=int(li[j][1])
print(ans) | n = int(input())
ss = []
tt = []
for _ in range(n):
s,t = input().split()
ss.append(s)
tt.append(int(t))
x = input()
for i in range(n):
if ss[i] == x:
ans = sum(tt[i+1:])
break
print(ans) | 1 | 97,158,802,934,720 | null | 243 | 243 |
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
return self.queue.pop(0)
class Task:
def __init__(self, name, time):
self.name = name
self.time = int(time)
self.endtime = 0
def __repr__(self):
return '{} {}'.format(self.name, self.endtime)
def rr(queue, q):
time = 0
while len(queue.queue) > 0:
task = queue.dequeue()
if task.time > q:
task.time -= q
time += q
queue.enqueue(task)
else:
time += task.time
task.time = 0
task.endtime = time
print(task)
if __name__ == '__main__':
nq = [int(s) for s in input().split()]
N = nq[0]
q = nq[1]
queue = Queue()
task_arr = [Task(*input().split()) for i in range(N)]
for t in task_arr:
queue.enqueue(t)
rr(queue, q) | import Queue
import sys
class Proc:
def __init__(self, name, time):
self.time = time
self.name = name
def main():
array = map(lambda x: int(x), sys.stdin.readline().strip().split(" "))
p_num = array[0]
q_time = array[1]
p_queue = Queue.Queue()
for i in range(0, p_num):
array = sys.stdin.readline().strip().split(" ")
p_queue.put(Proc(array[0], int(array[1])))
t = 0
while not p_queue.empty():
p = p_queue.get()
if p.time > q_time:
p.time = p.time - q_time
p_queue.put(p)
t += q_time
else:
t += p.time
print p.name + " " + str(t)
if __name__ == "__main__":
main() | 1 | 41,834,944,990 | null | 19 | 19 |
import sys
N,K = map(int,input().split())
array_hight = list(map(int,input().split()))
if not ( 1 <= N <= 10**5 and 1 <= K <= 500 ): sys.exit()
count = 0
for I in array_hight:
if not ( 1 <= I <= 500): sys.exit()
if I >= K:
count += 1
print(count) | N, K = map(int, input().split())
ans = 0
for height in map(int, input().split()):
if height >= K:
ans += 1
print(ans)
| 1 | 179,481,802,333,628 | null | 298 | 298 |
n=int(input())
a=1
b=1
i=0
while i<n:
a,b=b,a+b
i+=1
print(a)
| def fib2(n):
a1, a2 = 1, 0
while n > 0:
a1, a2 = a1 + a2, a1
n -= 1
return a1
n = int(input())
print(fib2(n)) | 1 | 2,230,342,268 | null | 7 | 7 |
n = int(input())
lst = list(map(int, input().split()))
mod = 10**9+7
# 累積和(Cumulative sum)リストの作成
cumsum = [0]*(n+1)
for i in range(n):
cumsum[i+1] = lst[i] + cumsum[i]
# 題意より、lst の1つ前までが対象
ans = 0
for i in range(n-1):
ans += (cumsum[n] - cumsum[i+1]) * lst[i]
print(ans % mod)
| import sys
W = input()
print(sum(line.lower().split().count(W) for line in sys.stdin.readlines())) | 0 | null | 2,831,495,881,032 | 83 | 65 |
def sheep_and_wolves():
condition = input()
condition_list = condition.split()
S = int(condition_list[0])
W = int(condition_list[1])
if S > W:
print('safe')
return
elif S <= W:
print('unsafe')
return
sheep_and_wolves() | a, b = map(int, input().split())
if a > b:
print('safe')
else:
print('unsafe') | 1 | 29,181,193,325,372 | null | 163 | 163 |
N, M = map(int, input().split())
A = list(map(int, input().split()))
cnt = 0
sumA = sum(A)
for a in A:
if a >= sumA / 4 / M:
cnt += 1
if cnt >= M:
print('Yes')
else:
print('No')
| def buble(C):
for i in range(len(C)):
for j in range(len(C)-1,i,-1):
if int(C[j][-1]) < int(C[j-1][-1]):
C[j],C[j-1] = C[j-1],C[j]
return C
def selection(C):
for i in range(len(C)):
mini = i
for j in range(i,len(C)):
if int(C[j][-1]) < int(C[mini][-1]):
mini = j
C[i],C[mini] = C[mini],C[i]
return C
n = int(raw_input())
card = map(str, raw_input().split())
card1 = card[:]
buble(card);selection(card1)
print " ".join(map(str, card))
print "Stable"
print " ".join(map(str, card1))
print "Stable" if card == card1 else "Not stable" | 0 | null | 19,358,172,002,400 | 179 | 16 |
import sys, math
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7
N, K = rl()
H = rl()
ans = 0
for h in H:
if h >= K:
ans += 1
print(ans) | x = [1,2,3,4,5,6,7,8,9]
y = [1,2,3,4,5,6,7,8,9]
for w in x :
for c in y :
print(w,"x",c,"=",w*c,sep="")
| 0 | null | 89,602,657,179,122 | 298 | 1 |
import math
count=0
n,d=map(int,input().split())
for _ in range(n):
x,y=map(int,input().split())
dis=math.sqrt(pow(x,2)+pow(y,2))
if dis<=d:
count+=1
print(count) | n,d = map(int, input().split())
xy = [map(int, input().split()) for _ in range(n)]
x, y = [list(i) for i in zip(*xy)]
ans=0
for i in range(n):
if x[i]**2+y[i]**2<=d**2:
ans+=1
print(ans) | 1 | 5,960,835,955,620 | null | 96 | 96 |
data = [None] * 4
for i in xrange(4):
data[i] = [None] * 3
for j in xrange(3):
data[i][j] = [0] * 10
n = input()
for i in xrange(n):
line = map(int, raw_input().split())
data[line[0] - 1][line[1] - 1][line[2] - 1] += line[3]
for i in xrange(4):
for j in xrange(3):
s = ""
for k in xrange(10):
s += ' '
s += str(data[i][j][k])
print s
if i < 3:
print '#' * 20 | n=int(input())
s=input()
ans=""
for i in range(len(s)):
num=ord(s[i])+n
if num>90:
num-=26
ans+=chr(num)
print(ans) | 0 | null | 67,838,077,231,232 | 55 | 271 |
N = int(input())
A = list(map(int,input().split()))
a = [0]*N
for i in range(N):
a[A[i]-1] = i + 1
print(*a) | n = int(input())
num_list = list(map(int, input().split()))
ans_list = [0]*n
for i, j in enumerate(num_list):
ans_list[j-1] = str(i+1)
ans = ' '.join(ans_list)
print(ans) | 1 | 180,850,273,942,998 | null | 299 | 299 |
import os, sys, re, math
(N, K) = [int(n) for n in input().split()]
H = [int(n) for n in input().split()]
H = sorted(H, reverse=True)[K:]
print(sum(H))
| import sys
input = sys.stdin.buffer.readline
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
n, k = MAP()
h = LIST()
h.sort(reverse=True)
if k >= n:
print(0)
else:
print(sum(h[k:]))
| 1 | 78,948,927,969,242 | null | 227 | 227 |
# coding: utf-8
# Your code here!
x = input()
lst = list(x)
pt = []
rst = []
k = 0
# point get
cnt = 0
tmp = ""
for s in lst:
if s == "/":
if tmp == "_" or tmp == "/":
cnt += 1
elif s == "\\":
if tmp == "\\":
cnt -= 1
else:
if tmp == "\\":
cnt -= 1
pt += [cnt]
tmp = s
#メンセキ
i,xs,m2 = 0,0,0
for s in lst:
if s == "/":
if i == xs and xs > 0:
rst += [m2]
k += 1
xs,m2 = 0,0
elif s == "_":
pass
else:
try:
x = pt[i+1:].index(pt[i])+i+1
m2 += x-i
if xs < x:
xs = x
except:
pass
i += 1
print(sum(rst))
print(k,*rst)
| string = input()
s = []
total = 0
s2 = []
for i in range(len(string)):
if string[i] == '\\':
s.append(i)
elif string[i] == '/' and len(s) > 0:
j = s.pop() # j: 対応する '\' の位置
area = i - j # 面積
total += area
while len(s2) > 0 and s2[-1][0] > j: # s2[-1][0] == s2.pop()[0]
area += s2[-1][1]
s2.pop()
s2.append([j, area]) # j: 水たまりの左端 / tmp: その水たまりの面積
ans = []
for i in range(len(s2)):
ans.append(str(s2[i][1]))
print(total)
if len(ans) == 0:
print(len(ans))
else:
print(len(ans), end = ' ')
print(' '.join(ans))
| 1 | 59,170,200,310 | null | 21 | 21 |
N=int(input())
A=list(map(int,input().split()))
ans=0
tree=1
node=sum(A)
flag=0
for i in A:
ans+=i
node-=i
if i>tree:
ans=-1
break
tree-=i
if tree<node:
ans+=tree
else:
ans+=node
tree=2*tree
print(ans) | N = int(input())
A = list(map(int, input().split()))
b = [0] * (N+1)
b[0] = 1
flag = True
for i in range(N):
if A[i] > b[i]:
flag = False
b[i+1] = (b[i] - A[i]) * 2
if A[N] > b[N]:
flag = False
ans = 0
l = 0
for i in range(N, -1, -1):
l += A[i]
ans += min(l, b[i])
if flag:
print(ans)
else:
print(-1)
| 1 | 18,933,852,563,928 | null | 141 | 141 |
S=input()
Q=int(input())
rev = 0
front, back=[],[]
for i in range(Q):
q = input()
if len(q)==1:rev = 1- rev
else:
n,f,c=q.split()
if f=='1' and rev==0:
front.append(c)
elif f=='2' and rev==1:
front.append(c)
elif f=='1' and rev==1:
back.append(c)
elif f=='2' and rev == 0:
back.append(c)
if rev==0:
S = ''.join(front[::-1]) + S + ''.join(back)
else:
S = ''.join(back[::-1]) + S[::-1] + ''.join(front)
print(S) | S = input()
N = int(input())
line = [''] * (N+1) * 2
rev = False
pos = N
line[pos] = S
leftPos = pos - 1
rightPos = pos + 1
for i in range(N):
A = input().split()
if len(A) == 1:
rev = not rev
else:
if A[1] == '1':
if rev == False:
pos = leftPos
leftPos -= 1
else:
pos = rightPos
rightPos += 1
else:
if rev == False:
pos = rightPos
rightPos += 1
else:
pos = leftPos
leftPos -= 1
line[pos] = A[2]
ans = line[leftPos+1:rightPos]
ans = "".join(ans)
if rev == False:
print(ans)
else:
print(ans[::-1])
| 1 | 57,314,423,573,652 | null | 204 | 204 |
i = 0
while True:
i += 1
num = raw_input()
if num == "0":
break
print "Case %d: %s" % (i,num) | # -*- coding: utf-8 -*-
x = []
while ( 1 ):
temp = int( input() )
if (temp == 0):
break
x.append(temp)
index = 1
for i in x:
print('Case {0}: {1}'.format(index, i))
index += 1 | 1 | 485,266,017,852 | null | 42 | 42 |
#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,m = readInts()
base = []
if n == 1 and m == 0:
print(0)
exit()
elif n == 2 and m == 0:
print(10)
exit()
elif n == 3 and m == 0:
print(100)
exit()
if n >= 1:
base.append('1')
if n >= 2:
base.append('0')
if n == 3:
base.append('0')
dic = defaultdict(int)
for i in range(m):
s,c = readInts()
s -= 1
if dic[s] != 0:
if int(base[s]) == c:
pass
else:
print(-1)
exit()
else:
dic[s] = 1
base[s] = str(c)
if s == 0 and c == 0 and n >= 2:
print(-1)
exit()
print(*base,sep='')
| A = int(input())
B = int(input())
print(*(set([1,2,3])-set([A,B]))) | 0 | null | 85,441,578,598,912 | 208 | 254 |
import time
_s = time.time()
import numpy as np
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
from numba import njit
def getInputs():
D = int(readline())
CS = np.array(read().split(), np.int32)
C = CS[:26]
S = CS[26:].reshape((-1, 26))
return D, C, S
@njit('Tuple((i4[:], i8))(i8, i4[:], i4[:, :], i4[:], )', cache=True)
def _compute_score1(D, C, S, out):
score = 0
last = np.zeros(26, np.int32)
for d in range(len(out)):
i = out[d]
score += S[d, i]
last[i] = d + 1
score -= np.sum(C * (d + 1 - last))
return last, score
def _update_score():
pass
@njit('Tuple((i4[:], i8))(i8, i4[:], i4[:, :], i4[:], i8, )', cache=True)
def _random_update(D, C, S, out, score):
d = np.random.randint(0, D)
q = np.random.randint(0, 26)
p = out[d]
if p == q:
return out, score
out[d] = q
_, new_score = _compute_score1(D, C, S, out)
if score < new_score:
score = new_score
else:
out[d] = p
return out, score
@njit('Tuple((i4[:], i8))(i8, i4[:], i4[:, :], i4[:], i8, i8, )', cache=True)
def _random_swap(D, C, S, out, score, delta):
d1 = np.random.randint(0, D)
d2 = np.random.randint(max(0, d1 - delta), min(D, d1 + delta))
#p, q = out[[d1, d2]]
p = out[d1]
q = out[d2]
if d1 == d2 or p == q:
return out, score
#out[[d1, d2]] = (q, p)
out[d1] = q
out[d2] = p
_, new_score = _compute_score1(D, C, S, out)
if score < new_score:
score = new_score
else:
#out[[d1, d2]] = (p, q)
out[d1] = p
out[d2] = q
return out, score
def step1(D, C, S):
out = []
LAST = 0
for d in range(D):
max_score = -10000000
best_i = 0
for i in range(26):
out.append(i)
last, score = _compute_score1(D, C, S, np.array(out, np.int32))
if max_score < score:
max_score = score
LAST = last
best_i = i
out.pop()
out.append(best_i)
return np.array(out), LAST, max_score
def step2(D, C, S, out, score):
while time.time() - _s <= 1.9:
flag = np.random.rand() >= 0.5
out = out.astype(np.int32)
if flag:
out, score = _random_update(D, C, S, out, score)
else:
out, score = _random_swap(D, C, S, out, score, 13)
return out, score
def output(out):
out += 1
print('\n'.join(out.astype(str).tolist()))
D, C, S = getInputs()
out, _, score = step1(D, C, S)
#print(score)
out, score = step2(D, C, S, out, score)
output(out)
#print(score) | n=input()
lis=["SUN","MON","TUE","WED","THU","FRI","SAT"]
ans=7
for i in lis:
if n==i:
print(ans)
break
ans-=1 | 0 | null | 71,567,117,612,068 | 113 | 270 |
n,m=map(int,input().split())
a=list(map(int,input().split()))
h=sum(a)
if n<h:
print('-1')
else:
print(n-h) | n, m = map(int, input().split())
a = list(map(int, input().split()))
ans = n - sum(a)
print(-1 if ans < 0 else ans) | 1 | 31,920,827,490,540 | null | 168 | 168 |
def kyu_in_atcoder():
X = int(input())
lis = [10 - i for i in range(10)]
x = X // 200
print(lis[x])
kyu_in_atcoder() | x=float(input())
for i in range(8):
if 400+200*i<=x<400+200*(i+1):
print(8-i) | 1 | 6,694,526,790,830 | null | 100 | 100 |
#!/usr/bin python3
# -*- coding: utf-8 -*-
n, k = map(int, input().split())
p = [int(i)-1 for i in input().split()]
c = list(map(int, input().split()))
rc = [0] * n
rp = [0] * n
for i in range(n):
if rc[i]!=0:
continue
else:
nw = set([i])
np = c[i]
nx = p[i]
while not nx in nw:
nw.add(nx)
np += c[nx]
nx = p[nx]
cnt = len(nw)
for x in nw:
rc[x] = cnt
rp[x] = np
ret = - 10 ** 18
for i in range(n):
if rc[i] == 1:
if rp[i]>=0:
ret = max(ret, k*rp[i])
else:
ret = max(ret, rp[i])
continue
pseq = [0]
nx = p[i]
for j in range(1,rc[i]+1):
pseq.append(pseq[-1]+c[nx])
nx = p[nx]
pseq = pseq[1:]
if k <= rc[i]:
ret = max(ret, max(pseq[:k]))
elif rp[i] < 0:
ret = max(ret, max(pseq))
else:
tmp = max(pseq)
if k%rc[i]!=0:
tmp = max(tmp, rp[i] + max(pseq[:k%rc[i]]))
tmp += rp[i]*(k//rc[i]-1)
ret = max(ret, tmp)
print(ret)
| import sys
readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
def solve():
n, k = nm()
p = nl()
_c = nl()
c = [0]*n
for i in range(n):
p[i] -= 1
c[i] = _c[p[i]]
m = 31
MIN = - (1 << 63)
vertex = list()
score = list()
vertex.append(p)
score.append(c)
for a in range(1, m+1):
p_ath = [0] * n
c_ath = [0] * n
for i in range(n):
p_ath[i] = vertex[a-1][vertex[a-1][i]]
c_ath[i] = score[a-1][i] + score[a-1][vertex[a-1][i]]
vertex.append(p_ath)
score.append(c_ath)
prv = [[MIN, 0] for _ in range(n)]
nxt = [[MIN, MIN] for _ in range(n)]
for b in range(m, -1, -1):
for i in range(n):
if (k >> b) & 1:
nxt[vertex[b][i]][0] = max(nxt[vertex[b][i]][0], prv[i][0] + score[b][i])
nxt[vertex[b][i]][1] = max(nxt[vertex[b][i]][1], prv[i][1] + score[b][i])
nxt[i][0] = max(nxt[i][0], prv[i][0], prv[i][1])
else:
nxt[vertex[b][i]][0] = max(nxt[vertex[b][i]][0], prv[i][0] + score[b][i])
nxt[i][0] = max(nxt[i][0], prv[i][0])
nxt[i][1] = max(nxt[i][1], prv[i][1])
prv, nxt = nxt, prv
ans = max(max(x) for x in prv)
if ans == 0:
ans = max(c)
print(ans)
return
solve() | 1 | 5,346,946,650,340 | null | 93 | 93 |
# 問題: https://atcoder.jp/contests/abc144/tasks/abc144_c
import math
n = int(input())
a = int(math.sqrt(n))
b = 0
while b == 0:
if n % a > 0:
a -= 1
continue
b = n / a
res = a + b - 2
print(int(res))
| n = list(map(int, input()[::-1])) + [0]
s = 0
res = 0
for i, ni in enumerate(n[:-1]):
k = ni + s
if k < 5 or (k == 5 and int(n[i + 1]) < 5):
res += k
s = 0
else:
res += 10 - k
s = 1
res += s
print(res)
| 0 | null | 116,154,980,393,452 | 288 | 219 |
N, M, L = map(int, input().split())
D = [[1000000000000]*N for i in range(N)]
for i in range(N):
D[i][i] = 0
for i in range(M):
A, B, C = map(int, input().split())
A, B = A-1, B-1
D[A][B] = C
D[B][A] = C
for k in range(N):
for i in range(N):
for j in range(N):
D[i][j] = min(D[i][j], D[i][k]+D[k][j])
E = [[1000000000000]*N for i in range(N)]
for i in range(N):
E[i][i] = 0
for i in range(N):
for j in range(N):
if D[i][j] <= L:
E[i][j] = 1
for k in range(N):
for i in range(N):
for j in range(N):
E[i][j] = min(E[i][j], E[i][k]+E[k][j])
Q = int(input())
for i in range(Q):
s, t = map(int, input().split())
s, t = s-1, t-1
if E[s][t] == 1000000000000:
r = -1
else:
r = E[s][t]-1
print(r)
| #!/usr/bin/env python3
from collections import Counter
def main():
S = input()
N = len(S)
T = [0] * (N+1)
for i in range(N-1,-1,-1):
T[i] = (T[i+1] + int(S[i]) * pow(10,N-i,2019)) % 2019
l = Counter(T)
ans = 0
for v in l.values():
ans += v * (v-1) // 2
print(ans)
if __name__ == "__main__":
main()
| 0 | null | 101,955,411,381,632 | 295 | 166 |
str1=input()
str2=str1.swapcase()
print(str2)
| N=int(input())
A=N/3
print(A*A*A) | 0 | null | 24,264,433,585,600 | 61 | 191 |
n,k=map(int,input().split())
P=list(map(int,input().split()))
for i in range(n):
P[i]-=1
C=list(map(int,input().split()))
ANS=-float('inf')
for i in range(n):
snp=P[i]
r=C[snp]
L=[r]
c=0
np=P[snp]
while True:
if c==k-1:
ANS=max(max(L),ANS)
break
if np==snp:
y=k%(c+1)
m=k//(c+1)
if y==0:
ANS=max(max(L),max(L)+(m-1)*L[-1],ANS)
break
else:
#print(m,y)
#print(L)
ANS=max(max(L),max(max(L[:y]),0)+m*L[-1],ANS)
break
r+=C[np]
L.append(r)
np=P[np]
c+=1
print(ANS) | n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]
INF = 10**18
score = -INF
for st in range(n):
lap_cn = 0
lap_sc = 0
nx = st
while True:
lap_cn += 1
lap_sc += C[nx]
nx = P[nx]
if nx == st: break
lap_sc = max(0, lap_sc)
sum_sc = 0
k_cn = 0
while True:
k_cn += 1
if k < k_cn: break
sum_sc += C[nx]
score = max(score, sum_sc + lap_sc * ((k - k_cn) // lap_cn))
nx = P[nx]
if nx == st: break
print(score)
| 1 | 5,423,587,935,370 | null | 93 | 93 |
N = int(input())
A = list(map(int, input().split()))
A_MAX = 10 ** 5
idx = [0] * (A_MAX + 1)
sum = 0
for i in A:
idx[i] += 1
sum += i
Q = int(input())
for i in range(Q):
B, C = list(map(int, input().split()))
sub = C - B
num = idx[B]
idx[B] = 0
idx[C] += num
sum += (sub * num)
print(sum) | N, X, M = map(int, input().split())
checked = [-1] * M
a = X
i = 0
while checked[a] == -1 and i < N:
checked[a] = i
a = a**2 % M
i += 1
if i == N:
a = X
ans = 0
for _ in range(N):
ans += a
a = a**2%M
print(ans)
else:
cycle_size = i - checked[a]
cycle_num = a
cycle = []
cycle_sum = 0
for _ in range(cycle_size):
cycle.append(cycle_num)
cycle_sum += cycle_num
cycle_num = cycle_num**2 % M
before_cycle_size = checked[a]
before_cycle = []
before_cycle_sum = 0
num = X
for _ in range(before_cycle_size):
before_cycle.append(num)
before_cycle_sum += num
num = num**2 % M
ans = before_cycle_sum
ans += (N-before_cycle_size)//cycle_size * cycle_sum
after_cycle_size = (N-before_cycle_size)%cycle_size
for i in range(after_cycle_size):
ans += cycle[i]
print(ans) | 0 | null | 7,482,099,528,660 | 122 | 75 |
def func(N):
strN = str(N)
sum = 0
for s in strN:
sum += int(s)
return "Yes" if sum % 9 == 0 else "No"
if __name__ == "__main__":
N = str(input())
print(func(N)) | N=int(input())
n= str(N)
total=0
for i in range(len(n)):
k = n[i]
k = int(k)
total += k
if total%9==0:
print("Yes")
else:
print("No") | 1 | 4,339,476,130,228 | null | 87 | 87 |
class dice:
def __init__(self,label):
self.top, self.front, self.right, self.left, self.rear, self.bottom \
= label
def roll(self,op):
if op=='N': self.top, self.front, self.bottom, self.rear = \
self.front, self.bottom, self.rear , self.top
elif op=='E': self.top, self.left , self.bottom, self.right = \
self.left , self.bottom, self.right, self.top
elif op=='W': self.top, self.right, self.bottom, self.left = \
self.right, self.bottom, self.left , self.top
elif op=='S': self.top, self.rear , self.bottom, self.front = \
self.rear , self.bottom, self.front, self.top
def print_top(self): print(self.top)
def print_right(self): print(self.right)
def get_label(self):
return [self.top, self.front, self.right, self.left, self.rear, self.bottom]
label = list(map(int,input().split()))
d = dice(label)
q = int(input())
for _ in range(q):
top_front = [int(x) for x in input().split()]
for op in 'EEESSSWWWNNNWWWSSWWSESWS':
if d.get_label()[:2] == top_front:
d.print_right()
break
d.roll(op) | T = input()
N = len(T)
after_T = ''
for i in range(N):
charr=T[i]
if(charr=='?'):
after_T+='D'
else:
after_T+=charr
print(after_T)
| 0 | null | 9,396,557,301,790 | 34 | 140 |
def main():
n = int(input())
nums = input().split(' ')
s = set()
result = 'YES'
for i in range(n):
num = nums[i]
if num in s:
result = 'NO'
break
s.add(num)
print(result)
if __name__ == '__main__':
main()
| import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7
DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def s(): return input()
def cuts(H):
for i in range(1<<H):
yield bin(i)[2:].zfill(H)
def main():
H, W, K = LI()
S = []
for _ in range(H):
S.append(s())
ans = inf
for cut in cuts(H-1):
p = sum([1 for x in cut if x == '1'])
cnt = p
lines = [[0 for _ in range(W)] for __ in range(p+1)]
cumr = 0
for c in range(W):
n_line = 0
for r in range(H):
if S[r][c] == '1':
cumr += 1
if r >= H-1:
continue
if cut[r] == '1':
lines[n_line][c] += cumr
n_line += 1
cumr = 0
lines[-1][c] = cumr
cumr = 0
ng = False
cumsum = [[0 for _ in range(W+1)] for __ in range(p+1)]
for i in range(p+1):
line = lines[i]
for j in range(W):
cumsum[i][j+1] = line[j] + cumsum[i][j]
before = 0
for j in range(1, W+1):
# import pdb
# pdb.set_trace()
for i in range(p+1):
if ng:
break
if cumsum[i][j] - cumsum[i][before] > K:
if j - before == 1:
ng = True
cnt += 1
before = j - 1
break
if ng:
continue
ans = min(ans, cnt)
print(ans)
main()
| 0 | null | 61,318,509,474,172 | 222 | 193 |
N = int(input())
A = list(map(int, input().split()))
import numpy as np
A = np.array(A)
ans = np.argsort(A)
ans = list(str(a + 1) for a in ans)
ans = ' '.join(ans)
print(ans) | N=int(input())
A=list(map(int,input().split()))
for i in range(N):
A[i] = [i+1, A[i]]
A.sort(key=lambda x:x[1])
ans=[]
for i in range(N):
ans.append(A[i][0])
ans = map(str, ans)
print(' '.join(ans))
| 1 | 180,337,362,069,760 | null | 299 | 299 |
d=input()
a,b,c=d.split()
if(int(a)<int(b)<int(c)):print('Yes')
else:print('No') | # Aizu Problem ITP_1_11_A: Dice I
#
import sys, math, os
# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
sys.stdin = open("sample-input.txt", "rt")
def do_roll(dice, roll):
d1, d2, d3, d4, d5, d6 = dice
if roll == 'E':
return [d4, d2, d1, d6, d5, d3]
elif roll == 'W':
return [d3, d2, d6, d1, d5, d4]
elif roll == 'N':
return [d2, d6, d3, d4, d1, d5]
elif roll == 'S':
return [d5, d1, d3, d4, d6, d2]
else:
assert False, "We should never reach this point!"
dice = [int(_) for _ in input().split()]
for roll in input().strip():
dice = do_roll(dice, roll)
print(dice[0]) | 0 | null | 304,606,631,432 | 39 | 33 |
n, m = map(int, input().split())
number = [0] * n
cou = [0] * n
#logging.debug(number)#
for i in range(m):
s, c = map(int, input().split())
s -= 1
if cou[s] > 0 and c != number[s]:
print(-1)
exit()
else:
cou[s] += 1
number[s] = c
#logging.debug("number = {}, cou = {}".format(number, cou))
if n > 1 and number[0] == 0 and cou[0] >= 1:
print(-1)
exit()
elif n > 1 and number[0] == 0:
number[0] = 1
number = map(str, number)
print(''.join(number)) | def f():
n, m = map(int, input().split())
num = [set() for i in range(n)]
for i in range(m):
s, c = map(int, input().split())
num[s-1].add(c)
s = []
for i in num:
if len(i) > 1:
print(-1)
return
if len(i) == 1:
for x in i:
s.append(x)
break
else:
s.append(0)
if s[0] == 0 and n != 1:
if len(num[0]) > 0:
print(-1)
return
else:
s[0] = 1
print(''.join(str(x) for x in s))
f() | 1 | 61,000,067,550,392 | null | 208 | 208 |
x=int(input())
A=int(x//500)
B=int((x%500)//5)
ans=0
ans=A*1000+B*5
print(ans) | from collections import Counter
S = input()
# S = "12345"*40000
N = len(S)
l = [0]*(N+1)
for i in range(N-1, -1, -1):
l[i] = (l[i+1] + pow(10, N-i, 2019) * int(S[i])) % 2019
# if i%10000 == 0:
# print(i)
# print(list(Counter(l).values()))
r = sum(m*(m-1)//2 for m in Counter(l).values())
print(r) | 0 | null | 36,655,812,741,408 | 185 | 166 |
x=int(input())
u_1000=x//500*1000
u_5=x%500//5*5
print(u_1000+u_5) | # coding: utf-8
x = int(input())
ans = x // 500
x = x - ans * 500
ans = ans * 1000
ans += (x // 5 * 5)
print(ans) | 1 | 42,958,334,555,380 | null | 185 | 185 |
isExist = [0]*2001
n = int( input() )
A = [ int( val ) for val in input().rstrip().split( ' ' ) ]
for i in A:
for j in range( 2000-i, 0, -1 ):
if 1 == isExist[j]:
isExist[ i+j ] = 1
isExist[i] = 1
q = int( input() )
M = [ int( val ) for val in input().rstrip().split( ' ' ) ]
for i in range( 0, q ):
if 1 == isExist[ M[i] ]:
print( "yes" )
else:
print( "no" ) | input()
A = [int(x) for x in input().split()]
input()
ms = [int(x) for x in input().split()]
enable_create = [False]*2000
for bit in range(1 << len(A)):
n = 0
for i in range(len(A)):
if 1 & (bit >> i) == 1:
n += A[i]
enable_create[n] = True
for m in ms:
print("yes" if enable_create[m] else "no") | 1 | 98,591,305,040 | null | 25 | 25 |
import math
import itertools
n=int(input())
k=int(input())
def comb(n,k):
return len(list(itertools.combinations(range(n), k)))
x=str(n)
m=len(x)
ans=0
for i in range(1,m):
ans+=(comb(i-1,k-1)*(9**k))
if k==1:
for i in range(1,10):
if i*(10**(m-1))<=n:
ans+=1
elif k==2:
for i in range(1,10):
if i*(10**(m-1))<=n:
for j in range(m-1):
for a in range(1,10):
if i*(10**(m-1))+a*(10**(j))<=n:
ans+=1
else:
break
else:
break
else:
po=[10**i for i in range(m)]
for i in range(1,10):
if i*po[m-1]<=n:
for j in range(m-1):
for a in range(1,10):
if i*po[m-1]+a*po[j]<=n:
for b in range(j):
for c in range(1,10):
ans+=(i*po[m-1]+a*po[j]+c*po[b]<=n)
else:
break
else:
break
print(ans)
| N=int(input())
K=int(input())
string = str(N)
digits = len(string)
#dp[i][j][k]=と同じ桁数の整数で上からi桁目までで0でない数字がj個あるものの個数
#k=0: i桁目まで見てN未満が確定, k=1: 未確定
dp = [[[0]*2 for _ in range(K+1)] for __ in range(digits+1)]
#初期状態
dp[0][0][1] = 1
for i in range(digits):
d = int(string[i])
ni = i+1
for j in range(K+1):
for k in range(2):
for nd in range(10):
nk = 1 if k == 1 and nd == d else 0
if k == 1 and nd > d: break
nj = j + (1 if nd != 0 else 0)
if nj > K: continue
dp[ni][nj][nk] += dp[i][j][k]
print(dp[digits][K][0] + dp[digits][K][1])
| 1 | 76,001,669,738,720 | null | 224 | 224 |
def solve(N, data):
ret = N
data.sort(key=lambda x: x[0] - x[1])
most_right = float("-inf")
for idx, d in enumerate(data):
l, r = d[0] - d[1], d[0] + d[1]
if not idx:
most_right = r
continue
if most_right <= l:
most_right = r
continue
ret -= 1
most_right = min(r, most_right)
return ret
if __name__ == "__main__":
N = int(input())
data = []
for _ in range(N):
data.append(list(map(int, input().split())))
print(solve(N, data)) | H,W,M=map(int,input().split())
L=[]
bh=[0]*(H+1)
bw=[0]*(W+1)
for _ in range(M):
h,w=map(int,input().split())
L.append((h,w))
bh[h]+=1
bw[w]+=1
p,q=max(bh),max(bw)
num=len(list(filter(p.__eq__, bh)))*len(list(filter(q.__eq__,bw)))
num-=len(list(filter(lambda x: bh[x[0]]==p and bw[x[1]]==q, L)))
ans=p+q-1
if num>0:
ans+=1
print(ans) | 0 | null | 47,316,789,034,940 | 237 | 89 |
input()
while True:
try:
lst = list(map(int,input().split()))
lst.sort()
if lst[2] ** 2 == lst[1] ** 2 + lst[0] ** 2:
print("YES")
else:
print("NO")
except EOFError:
break
| #!/usr/bin/python
import sys
t = raw_input()
for i in range(int(t)):
x = [int(s) for s in raw_input().split()]
x.sort()
if x[0] ** 2 + x[1] ** 2 == x[2] ** 2:
print "YES"
else:
print "NO" | 1 | 223,964,192 | null | 4 | 4 |
def main():
s = list(map(int,input().strip().split()))
tmp = s[0]
s[0] = s[1]
s[1] = tmp
tmp = s[0]
s[0] = s[2]
s[2] = tmp
print("{} {} {} ".format(s[0],s[1],s[2]))
main()
| a, b, c = map(int, input().split())
t = a
a = b
b = t
tt = a
a =c
c = tt
print(a, b, c) | 1 | 38,079,023,649,040 | null | 178 | 178 |
import math
n = input()
p = 0
money = 100
while p != n:
money = math.ceil(money * 1.05)
p += 1
print int(money * 1000) | n = input()
debt = 100000
for i in range(n):
debt *= 1.05
if(debt % 1000):
debt -= debt % 1000
debt += 1000
print(int(debt)) | 1 | 1,211,357,752 | null | 6 | 6 |
import sys
input = sys.stdin.readline
import math
def INT(): return int(input())
def MAPINT(): return map(int, input().split())
def LMAPINT(): return list(map(int, input().split()))
def STR(): return input()
def MAPSTR(): return map(str, input().split())
def LMAPSTR(): return list(map(str, input().split()))
f_inf = float('inf')
x = LMAPINT()
for i, y in enumerate(x):
if y == 0:
print(i+1)
exit() | #self.r[x] means root of "x" if "x" isn't root, else number of elements
class UnionFind():
def __init__(self, n):
self.r = [-1 for i in range(n)]
#use in add-method
def root(self, x):
if self.r[x] < 0: #"x" is root
return x
self.r[x] = self.root(self.r[x])
return self.r[x]
#add new path
def add(self, x, y):
x = self.root(x)
y = self.root(y)
if x == y:
return False
self.r[x] += self.r[y]
self.r[y] = x
return True
n, m = map(int, input().split())
UF = UnionFind(n)
for i in range(m):
a, b = map(lambda x: int(x)-1, input().split())
UF.add(a, b)
ans = 0
for i in UF.r:
if i < 0:
ans += 1
print(ans-1)
| 0 | null | 7,837,075,268,620 | 126 | 70 |
n,m=map(int,input().split())
a=list(map(int,input().split()))
for i in range(n):a[i]*=-1
a.sort()
from bisect import bisect_left,bisect_right
def check(mid):
mm=0
for i in range(n):
if -(a[i]+a[0])<mid:break
mm+=bisect_right(a,-(mid+a[i]))
return mm
ok=0
ng=10**10+7
while ng!=ok+1:
mid=(ok+ng)//2
if check(mid)>=m:ok=mid
else:ng=mid
b=[0]
for i in a:b.append(b[-1]+i)
ans=0
for i in range(n):
if -(a[i]+a[0])<ok:break
ind=bisect_right(a,-(ok+a[i]))
ans+=a[i]*ind
ans+=b[ind]
print(-(ans+(check(ok)-m)*ok)) | import sys
import bisect
import itertools
def solve():
readline = sys.stdin.buffer.readline
mod = 10 ** 9 + 7
n, m = list(map(int, readline().split()))
a = list(map(int, readline().split()))
a.sort()
cor_v = -1
inc_v = a[-1] * 2 + 1
while - cor_v + inc_v > 1:
bin_v = (cor_v + inc_v) // 2
cost = 0
#条件を満たすcostを全検索
p = n
for v in a:
p = bisect.bisect_left(a, bin_v - v, 0, p)
cost += n - p
if cost > m:
break
#costが制約を満たすか
if cost >= m:
cor_v = bin_v
else:
inc_v = bin_v
acm = [0] + list(itertools.accumulate(a))
c = 0
t = 0
for v in a:
p = bisect.bisect_left(a, cor_v - v)
c += n - p
t += acm[-1] - acm[p] + v * (n - p)
print(t - (c - m) * cor_v)
if __name__ == '__main__':
solve()
| 1 | 108,518,314,871,392 | null | 252 | 252 |
A,B,C,K=map(int,input().split())
cnt=0
if A>=K:
print(K)
else:
if A+B>=K:
print(A)
else:
if A+B+C<=K:
print(A-C)
else:
print(A-(K-(A+B))) | a,b,c,k = list(map(int,input().split()))
ans = 0
if a >= k:
print(k)
elif a+b >= k:
print(a)
else:
ans += a
k -= (a+b)
ans -= k
print(ans)
| 1 | 21,847,246,325,592 | null | 148 | 148 |
while True:
a,b = map(int,input().split())
if a == 0 and b == 0:
break
if a < b:
print(a,b)
elif b < a:
print(b,a)
else:
print(a,b) | # -*- config: utf-8 -*-
if __name__ == '__main__':
for i in range(int(raw_input())):
nums = map(lambda x:x**2,map(int,raw_input().split()))
flg = False
for i in range(3):
s = int(0)
for j in range(3):
if i == j :
continue
s += nums[j]
if s == nums[i] :
flg = True
if flg == True :
print "YES"
else :
print "NO" | 0 | null | 261,835,078,362 | 43 | 4 |
import sys
N, M, K = map(int, input().split())
friends = [set() for _ in range(N)]
for _ in range(M):
a, b = map(int, sys.stdin.readline().split())
friends[a-1].add(b-1)
friends[b-1].add(a-1)
blocks = [set() for _ in range(N)]
for _ in range(K):
c, d = map(int, sys.stdin.readline().split())
blocks[c-1].add(d-1)
blocks[d-1].add(c-1)
done = set()
chains = []
todo = []
for s in range(N):
if s in done:
continue
chain = set()
todo.append(s)
while todo:
i = todo.pop()
for ni in friends[i]:
if ni in done:
continue
done.add(ni)
chain.add(ni)
todo.append(ni)
chains.append(chain)
ans = [0] * N
for chain in chains:
for i in chain:
blocks[i].intersection_update(chain)
ans[i] = len(chain) - len(blocks[i]) - len(friends[i]) - 1
print(" ".join(map(str, ans))) | #UnionFind
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
n,m,k = map(int,input().split())
V = [[] for i in range(n+1)]
W = [0]*(n+1)
uf = UnionFind(n+1)
for _ in range(m):
a,b = map(int,input().split())
V[a].append(b)
V[b].append(a)
uf.union(a,b)
for _ in range(k):
c,d = map(int,input().split())
if uf.find(d) == uf.find(c):
W[c] += 1
W[d] += 1
for i in range(1,n+1):
ans = uf.size(i) - len(V[i]) - W[i] - 1
print(ans,end="")
print(" ",end="")
print() | 1 | 61,631,841,515,850 | null | 209 | 209 |
H, N = [int(s) for s in input().split()]
A = [int(s) for s in input().split()]
print('Yes' if H - sum(A) <= 0 else 'No') | import math
def main():
n = int(input())
# n, k = map(int, input().split())
# h = list(map(int, input().split()))
# s = input()
# h = [int(input()) for _ in rane(n)]
ans = 0
for i in range(1, n):
ans += (n - 1) // i
print(ans)
if __name__ == '__main__':
main()
| 0 | null | 40,418,078,283,652 | 226 | 73 |
from collections import deque
from sys import stdin
n = int(input())
ddl = deque()
for i in stdin:
inp = i.split()
if len(inp) == 2:
op, data = inp
data = int(data)
else: op, data = inp[0], None
if op == 'insert':
ddl.appendleft(data,)
elif op == 'delete':
try:
ddl.remove(data)
except ValueError:
pass
elif op == 'deleteFirst':
ddl.popleft()
elif op == 'deleteLast':
ddl.pop()
print(' '.join([str(item) for item in ddl])) | N = input()
L = len(N)
# dp[i][j]: 紙幣の最小枚数
# i: 決定した桁数
# j: 1枚多めに渡すフラグ
dp = [[float("inf")] * 2 for _ in range(L + 1)]
# 初期条件
dp[0][0] = 0
dp[0][1] = 1
# 貰うDP
for i in range(L):
n = int(N[i])
dp[i + 1][0] = min(dp[i][0] + n, dp[i][1] + (10 - n))
dp[i + 1][1] = min(dp[i][0] + (n + 1), dp[i][1] + (10 - (n + 1)))
print(dp[L][0]) | 0 | null | 35,668,034,274,180 | 20 | 219 |
N,R=map(int,input().split())
if N>10:
print(R)
elif N<=10:
print(R+(100*(10-N))) | n, r = map(int, input().split(' '))
ans = 0
if n <= 10:
ans = r + 100 *(10-n)
else:
ans = r
print(ans) | 1 | 63,213,978,662,480 | null | 211 | 211 |
d = int(input())
c = list(map(int, input().split()))
s = [list(map(int, input().split())) for _ in range(d)]
t = [int(input()) for _ in range(d)]
TYPES = 26
history = [-1] * TYPES
satisfaction_level = [0] * (d+1)
def last(day, i):
if history[i] == -1:
return 0
else:
return history[i]
def satisfaction(day, typ):
# コンテスト実施記録を更新
history[typ] = day
# 満足度の減少
decrease = sum((c[i]*(day-last(day,i)) for i in range(TYPES)))
value = s[day-1][typ] - decrease + satisfaction_level[day-1]
satisfaction_level[day] = value
return value
for day, typ in enumerate(t):
print(satisfaction(day+1, typ-1)) | n,k = map(int,input().split())
li = []
for i in range(k) :
gomi = input()
[li.append(int(j)) for j in input().split()]
st = set(li)
print(n - len(st)) | 0 | null | 17,302,227,960,696 | 114 | 154 |
import fractions
mod=10**9+7
def lcm(m,n):return m//fractions.gcd(m,n)*n
n=int(input())
a=list(map(int,input().split()))
l=a[0]
ans=0
for i in a:l=lcm(i,l)
for i in a:ans+=l*pow(i,mod-2,mod)%mod
print(ans%mod) | k = int(input())
ans = 1
a = 7 % k
while a != 0:
ans += 1
a = (10*a + 7) % k
if ans == 10**6:
ans = -1
break
print(ans) | 0 | null | 46,768,413,270,492 | 235 | 97 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
N = int(input())
adj = [ [] for _ in range(N) ]
for i in range(N-1):
a,b = map(int,input().split())
a -= 1
b -= 1
adj[a].append((b,i))
res = [None] * (N-1)
def dfs(n, c=-1, p=-1):
if c==-1 or c>1:
nc = 1
else:
nc = c+1
for nei,i in adj[n]:
if nei == p: continue
res[i] = nc
dfs(nei, nc, n)
nc += 1
if nc==c: nc += 1
dfs(0)
print(max(res))
for r in res: print(r) | import random
D = int(input())
last = [0 for i in range(26)]
s = [[0 for j in range(26)] for i in range(D)]
c = list(map(int, input().split(" ")))
result = []
for i in range(D):
a = list(map(int, input().split(" ")))
score = [0 for i in range(26)]
for j, k in enumerate(a):
s[i][j] = int(k)
for j in range(26):
score[j] = s[i][j]
for k in range(26):
if j != k:
score[j] -= (i + 1 - last[k]) * c[k]
score_sort = sorted(score,reverse=True)
score_max = random.choice(score_sort[:1])
for j in range(26):
if score_max == score[j]:
result.append(j)
last[j] = i
for i in range(D):
print(result[i]+1)
| 0 | null | 72,674,697,158,800 | 272 | 113 |
def calc_divisor(x):
divisor = []
for i in range(1, int(x ** 0.5) + 1):
if x % i == 0:
divisor.append(i)
if i != x // i:
divisor.append(x // i)
return divisor
N = int(input())
ans = len(calc_divisor(N - 1)) - 1
cand = sorted(calc_divisor(N))[1:]
for k in cand:
x = N
while x % k == 0:
x //= k
if x % k == 1:
ans += 1
print(ans)
|
N = int(input())
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
# divisors.sort()
return divisors
ans = len(make_divisors(N-1)) - 1
#print(ans)
divisors = make_divisors(N)
def dfs(x,N):
while N % x == 0:
N //= x
# print(N)
N %= x
# print(N)
return N == 1
counta = 0
for i in range(1,len(divisors)):
if dfs(divisors[i],N):
counta += 1
#print(counta)
ans += counta
print(ans) | 1 | 41,473,829,879,848 | null | 183 | 183 |
def main():
from math import gcd
K = int(input())
ans = 0
for a in range(1, K+1):
for b in range(1, K+1):
g = gcd(a, b)
for c in range(1, K+1):
ans += gcd(g, c)
print(ans)
if __name__ == '__main__':
main()
| def main():
n, k = map(int, input().split())
d_lst = [0 for _ in range(k)]
a_lst = [0 for _ in range(k)]
for i in range(k):
d_lst[i] = int(input())
a_lst[i] = list(map(int, input().split()))
snuke_lst = [0 for _ in range(n)]
for i in range(k):
for a in a_lst[i]:
snuke_lst[a - 1] = 1
ans = n - sum(snuke_lst)
print(ans)
if __name__ == "__main__":
main()
| 0 | null | 29,892,082,762,292 | 174 | 154 |
import sys
for line in sys.stdin:
m, f, r = map(int, line.split())
if m == f == r == -1:
break
if m == -1 or f == -1:
print('F')
elif (m + f) >= 80:
print('A')
elif (m + f) >= 65:
print('B')
elif (m + f) >= 50:
print('C')
elif (m + f) >= 30:
if r >= 50:
print('C')
else:
print('D')
else:
print('F') | ans = ''
while True:
m, f, r = map(int, input().split(' '))
if (m == -1 and f == -1) and r == -1:
break
else:
x = m + f
if (m == -1) or (f == -1):
ans += 'F\n'
elif x >= 80:
ans += 'A\n'
elif x >= 65:
ans += 'B\n'
elif x >= 50:
ans += 'C\n'
elif x >= 30:
if r >= 50:
ans += 'C\n'
else:
ans += 'D\n'
else:
ans += 'F\n'
if ans != '':
print(ans[:-1])
| 1 | 1,227,817,842,846 | null | 57 | 57 |
N, K, *A = map(int, open(0).read().split())
for a, b in zip(A[K:], A):
if a > b:
print("Yes")
else:
print("No") | n = int(input())
a = list(map(int,input().split()))
m = max(a) + 1
li = [0]*m
for x in a:
li[x] += 1
ans = 0
for i in range(1,m):
if li[i]:
if li[i]==1:
ans += 1
for j in range(i,m,i):
li[j] = 0
print(ans) | 0 | null | 10,744,593,484,340 | 102 | 129 |
def main():
A, B, C = (int(x) for x in input().split())
K = int(input())
while not A < B < C and K > 0:
if A >= B: B *= 2
else: C *= 2
K -= 1
# print(A, B, C, K)
if A < B < C: print('Yes')
else: print('No')
if __name__ == '__main__':
main() | a, b, c = map(int, input().split())
k = int(input())
for i in range(k):
if a < b < c:
break
elif b <= a:
b = b*2
elif c <= b:
c = c*2
if a < b < c:
print("Yes")
else:
print("No") | 1 | 6,967,668,815,240 | null | 101 | 101 |
r=int(input())
print(pow(r,2)) | nums = [int(e) for e in input().split()]
if (nums[2]+nums[4])<=nums[0] and (nums[3]+nums[4])<=nums[1] and (nums[2]-nums[4])>=0 and (nums[3]-nums[4])>=0:
print("Yes")
else:
print("No")
| 0 | null | 72,733,927,714,950 | 278 | 41 |
from collections import deque
from copy import deepcopy
# 初期入力
import sys
input = sys.stdin.readline
H,W = (int(i) for i in input().split())
map_initial =[["#"]*(W+2) for i in range(H+2)] #周囲を壁にするため+2
for h in range(1,H+1):
map_initial[h] =["#"] +list(input().strip()) +["#"]
def BSF(x,y):
dist =0
map =deepcopy(map_initial)
if map[x][y] =="#":
return dist
dq =set()
dq.add((x,y))
dq_sarch =set()
while len(dq) >0:
h,w =dq.pop()
map[h][w] ="#" #通り済を壁にする
if map[h+1][w]==".":
dq_sarch.add((h+1,w))
if map[h-1][w]==".":
dq_sarch.add((h-1,w))
if map[h][w+1]==".":
dq_sarch.add((h,w+1))
if map[h][w-1]==".":
dq_sarch.add((h,w-1))
if len(dq)==0:
dq =deepcopy(dq_sarch)
dq_sarch.clear()
dist +=1
#print(h,w,dist,end="\t")
return dist-1
#スタート位置を全探索し、最長距離を探す
dist_all =[]
for i in range(1,H+1):
for j in range(1,W+1):
dist_all.append(BSF(i,j) )
print(max(dist_all)) | N = int(input())
d = list(map(int,input().split()))
sum = 0
for i in range(0,len(d)):
for j in range(0,len(d)):
if(i != j):
sum += d[i] * d[j]
print(int(sum/2)) | 0 | null | 131,832,636,117,830 | 241 | 292 |
#ITP1_11-B Dice 2
rep=[
[1,2,4,3,1],
[2,0,3,5,2],
[0,1,5,4,0],
[0,4,5,1,0],
[0,2,5,3,0],
[1,3,4,2,1]
]
d = input().split(" ")
q = int(input())
dic={}
for i in range(6):
dic.update({d[i]:i})
for i in range(q):
a,b = input().split(" ")
for j in range(4):
top=dic[a]
front = dic[b]
if(d[rep[top][j]]==d[front]):
print(d[rep[top][j+1]]) | W = input()
T = input()
count = 0
while T != 'END_OF_TEXT':
T = T.lower().split()
count += T.count(W.lower())
T = input()
print(count) | 0 | null | 1,029,255,287,840 | 34 | 65 |
cnt = 0
def insertionSort(A, n, g):
global cnt####スコープ指定
for i in range(g,n):
v = A[i]
j = i - g
while j >= 0 and A[j] > v:##後半の条件が付いていてもiを回すのでソートされる
A[j+g] = A[j]
j = j - g
cnt+=1
A[j+g] = v
def shellSort(A, n):
tmp = 1
G=[]
while tmp<n:
G.append(tmp)
tmp*=3
tmp+=1###なぜ要るのか分からないが
G.reverse()
for i in range(len(G)):
insertionSort(A, n, G[i])
n = int(input())
G1=[]
tmp=1
while tmp<n:
G1.append(tmp)
tmp*=3
tmp += 1
G1.reverse()
A1 =[int(input()) for _ in range(n)]
m = len(G1)
shellSort(A1, n)
print(max(m,1))
if G1:
print(*G1)
else:
print(1)
print(cnt)
for a in A1:
print(a)
| # シェルソート
N = int(input())
A = []
for i in range(N):
A.append(int(input()))
cnt = 0
def insertionSort(A, n, g):
global cnt
for i in range(g, n):
for j in range(i-g, -1, -g):
if A[j+g] < A[j]:
A[j + g], A[j] = A[j], A[j + g]
cnt += 1
else:
break
def shellSort(A, n):
# gn+1 = 3gn + 1
h = 1
G = []
while h <= n:
G.append(h)
h = 3 * h + 1
G.reverse()
print(len(G))
print(" ".join([str(x) for x in G]))
for g in G:
insertionSort(A, n, g)
shellSort(A, N)
print(cnt)
for a in A:
print(a)
| 1 | 31,729,427,850 | null | 17 | 17 |
import sys
N = int(input())
A = list(map(int,input().split()))
fin = 1
if 0 in A:
fin = 0
else:
for i in A:
fin *= i
if fin > 10**18:
print(-1)
sys.exit()
print(fin) | N = int(input())
A = list(map(int, input().split()))
if 0 in A:
print(0)
else:
ans = 1
a = sorted(A, reverse=True)
for i in a:
ans *= i
if ans > 10 ** 18:
print(-1)
break
else:
print(ans) | 1 | 16,190,473,311,612 | null | 134 | 134 |
n = int(input())
a = list(map(int, input().split()))
q = int(input())
m = list(map(int, input().split()))
def memoize(f):
cache = {}
def helper(x, y):
if (x, y) not in cache:
cache[(x, y)] = f(x, y)
return cache[(x, y)]
return helper
def main():
for number in m:
if solve(0, number):
print('yes')
else:
print('no')
@memoize
def solve(i, m):
if m == 0:
return True
if i >= n:
return False
res = solve(i + 1, m) or solve(i + 1, m - a[i])
return res
if __name__ == '__main__':
main()
| N, M = map(int, input().split())
S = ['a'] * (N+1)
for i in range(M):
s, c = list(map(int, input().split()))
if S[s] != 'a' and S[s] != str(c):
print(-1)
exit()
S[s] = str(c)
if S[1] == '0' and N > 1:
print(-1)
exit()
for i in range(1, N+1):
if S[i] == 'a':
if i == 1 and N > 1:
S[i] = '1'
else:
S[i] = '0'
print(int(''.join(S[1:])))
| 0 | null | 30,625,757,727,906 | 25 | 208 |
L = int(input())
l = L / 3
print(l ** 3) | x,y = map(int,input().split(" "))
while y != 0:
x,y=y,x%y
print(x)
| 0 | null | 23,488,356,220,928 | 191 | 11 |
a, b, k = map( int, input().split() )
if a + b < k:
print( "0 0" )
elif a < k:
print( "0 " + str( a + b - k ) )
else:
print( str( a - k ) + " " + str( b ) ) | A, B, K = map(int, input().split())
print(max(0, A-K), max(A+B-K-max(0, A-K), 0)) | 1 | 104,405,002,838,488 | null | 249 | 249 |
N, K = map(int, input().split())
H = tuple(map(int, input().split()))
assert len(H) == N
print(len([h for h in H if h >= K])) | import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
n,k = list(map(int, input().split()))
h = list(map(int, input().split()))
ans = sum(item>=k for item in h)
print(ans) | 1 | 179,584,095,665,178 | null | 298 | 298 |
from sys import stdin
from itertools import product
suits = ['S', 'H', 'C', 'D']
suits_priority = {
'S': 1,
'H': 2,
'C': 3,
'D': 4
}
ranks = list(range(1, 14))
original_deck = set(product(suits, ranks))
if __name__ == '__main__':
n = int(stdin.readline().rstrip())
deck = set()
for _ in range(n):
suit, rank = stdin.readline().rstrip().split()
deck.add((suit, int(rank)))
diff = list(original_deck - deck)
diff.sort(key=lambda x: x[1])
diff.sort(key=lambda x: suits_priority[x[0]])
for card in diff:
print("{} {}".format(*card))
| #!/usr/bin/env python3
# Generated by https://github.com/kyuridenamida/atcoder-tools
from typing import *
import collections
import functools as fts
import itertools as its
import math
import sys
INF = float('inf')
def solve(S: str):
return sum([S == "RRR", "RR" in S, "R" in S])
def main():
sys.setrecursionlimit(10 ** 6)
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
S = next(tokens) # type: str
print(f'{solve(S)}')
if __name__ == '__main__':
main()
| 0 | null | 3,002,487,514,620 | 54 | 90 |
import itertools
N = int(input())
P = tuple(map(int, input().split(' ')))
Q = tuple(map(int, input().split(' ')))
ls = [ x for x in itertools.permutations(range(1, N + 1)) ]
a = [ key for key, val in enumerate(ls) if P == val ][0] + 1
b = [ key for key, val in enumerate(ls) if Q == val][0] + 1
print(abs(a - b)) | n = str(input())
k = int(input())
l = len(n)
def f(dig, under, num):
if num > l - dig: return 0
if num == 0: return 1
if dig == l-1:
if under: return int(n[dig])
else: return 9
if under:
if n[dig] == '0':
res = f(dig+1, True, num)
#print(dig, under, num, res, 'aaa')
return res
else:
res = f(dig+1, False, num)
if int(n[dig]) > 1:
res += (int(n[dig])-1) * f(dig+1, False, num-1)
res += f(dig+1, True, num-1)
#print(dig, under, num, res, 'bbb')
return res
else:
res = f(dig+1, False, num)
res += 9 * f(dig+1, False, num-1)
#print(dig, under, num, res, 'ccc')
return res
ans = f(0, True, k)
print(ans) | 0 | null | 88,475,579,641,092 | 246 | 224 |
K=int(input())
s=''
for _ in range(K):
s+='ACL'
print(s)
| n, m, x = map(int, input().split())
books_info = []
price_info = []
for i in range(n):
c, *a = map(int, input().split())
books_info.append(a)
price_info.append(c)
pattern_list = []
for j in range(2 ** n):
tmp_list = []
for k in range(n):
if ((j >> k) & 1):
tmp_list.append(k)
else:
pass
pattern_list.append(tmp_list)
book_price = 10 ** 5 * 12 + 1
for pattern in pattern_list:
# 全ての参考書を買わない=len(pattern)が0の場合はスキップする
if len(pattern) == 0:
continue
is_ok = False
price = 0
for j in range(m):
m_sum = 0
price_sum = 0
for k in pattern:
m_sum += books_info[k][j]
price_sum += price_info[k]
if m_sum >= x:
is_ok = True
else:
is_ok = False
break
price = price_sum
if is_ok == True:
book_price = min(price, book_price)
else:
pass
print(book_price if book_price != 10 ** 5 * 12 + 1 else -1)
| 0 | null | 12,306,875,216,572 | 69 | 149 |
h,w=map(int,input().split())
print((h*w+1)//2 if h*w>h+w else 1) | from numba import njit
import numpy as np
d = int(input())
cs = list(map(int, input().split()))
cs = np.array(cs, dtype=np.int64)
sm = [list(map(int, input().split())) for _ in range(d)]
sm = np.array(sm, dtype=np.int64)
@njit('i8(i8[:], i8)', cache=True)
def total_satisfaction(ts, d):
ls = np.zeros(26, dtype=np.int64)
s = 0
for i in range(d):
t = ts[i]
t -= 1
s += sm[i][t]
ls[t] = i + 1
dv = cs * ((i+1) - ls)
s -= dv.sum()
return s
@njit('i8(i8, i8, i8, i8, i8[:])', cache=True)
def differential(s, i, t, d, ls):
t -= 1
bk = ls[t]
s += sm[i][t]
ls[t] = i + 1
dv = cs * ((i+1) - ls)
s -= dv.sum()
ls[t] = bk
return s
ts = np.array([], dtype=np.int64)
for i in range(d):
sc = 0
if len(ts) > 0:
tt = np.array(ts, dtype=np.int64)
sc = total_satisfaction(tt, i)
ls = np.zeros(26, np.int64)
for i, t in enumerate(ts, 1):
ls[t-1] = i
mx = -99999999
mxt = -1
for t in range(1, 26+1):
df = differential(sc, len(ts), t, i + 1, ls)
s = sc + df
if s > mx:
mx = s
mxt = t
ts = np.append(ts, [mxt])
print(mxt)
| 0 | null | 30,366,713,506,488 | 196 | 113 |
x=int(input())
for i in range(3,11):
if x<i*200:
print(11-i)
break | n = int(input())
if n <= 599:
print(8)
elif 600 <= n <= 799:
print(7)
elif 800 <= n <= 999:
print(6)
elif 1000 <= n <= 1199:
print(5)
elif 1200 <= n <= 1399:
print(4)
elif 1400 <= n <= 1599:
print(3)
elif 1600 <= n <= 1799:
print(2)
elif 1800 <= n <= 1999:
print(1) | 1 | 6,746,067,456,612 | null | 100 | 100 |
H = int(input())
count = 0
for i in range(10**12):
if H == 0:
break
H = int(H/2)
count += 2 ** i
print(count) | print(2**int(input()).bit_length()-1)
| 1 | 80,151,375,273,090 | null | 228 | 228 |
s = input()
k = int(input())
s_list = []
ans = 0
def rle(s):
tmp, count = s[0], 1
for i in range(1, len(s)):
if tmp == s[i]:
count += 1
else:
s_list.append(count)
tmp = s[i]
count = 1
s_list.append(count)
return
rle(s)
if len(s_list) >= 2:
for i in range(len(s_list)):
if s_list[i] >= 2:
ans += s_list[i] // 2
ans *= k
if (s_list[0] + s_list[-1]) % 2 == 0 and s[0] == s[-1]:
ans += k - 1
else:
ans = len(s) * k // 2
print(ans)
| # -*- coding: utf-8 -*-
import sys
def get_digits(n):
if n < 0:
n *= -1
return len(str(n))
def main():
data = []
for line in sys.stdin:
a, b = map(int, line.split())
digits = get_digits(a+b)
print(digits)
if __name__ == '__main__':
main() | 0 | null | 88,073,653,856,618 | 296 | 3 |
import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy
import bisect
import functools
@functools.lru_cache(None)
def dfs(i,sum_v,val):
if i == n:
return sum_v == val
if dfs(i+1,sum_v,val):
return True
if dfs(i+1,sum_v + A[i],val):
return True
return False
n = int(input())
A = list(map(int,input().split()))
q = int(input())
m = list(map(int,input().split()))
for i in range(q):
if dfs(0,0,m[i]):
print("yes")
else:
print("no")
| K = int(input())
A, B = map(int,input().split())
N = B//K
if K*N <A:
print("NG")
else:
print("OK") | 0 | null | 13,440,774,510,742 | 25 | 158 |
import sys, math
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial#, gcd
from bisect import bisect_left #bisect_left(list, value)
sys.setrecursionlimit(10**7)
enu = enumerate
MOD = 10**9+7
def input(): return sys.stdin.readline()[:-1]
def pri(x): print('\n'.join(map(str, x)))
N = int(input())
ukv = [list(map(int, input().split())) for _ in range(N)]
dist = [-1]*N
dist[0] = 0
deq = deque()
#deq.append(ukv[0][2:])
deq.append([1])
step = 0
while deq[0]:
# print('deq:', deq)
nextvs = []
currvs = deq.popleft()
for v in currvs:
for nv in ukv[v-1][2:]:
if dist[nv-1] == -1:
dist[nv-1] = step+1
nextvs.append(nv)
deq.append(nextvs)
step += 1
res = [[val1, val2] for val1, val2 in zip(range(1, N+1), dist)]
for a in res:
print(*a)
| from collections import deque
n=int(input())
edge=[[] for _ in range(n+1)]
for i in range(n):
v,k,*u=map(int,input().split())
edge[v]=u
p=[-1]*(n+1)
p[1]=0
q=deque([])
q.append(1)
v=[1]*(n+1)
v[1]=0
while q:
now=q.popleft()
for i in edge[now]:
if v[i]:
q.append(i)
p[i]=p[now]+1
v[i]=0
for i in range(1,n+1):
print(i,p[i])
| 1 | 4,367,945,088 | null | 9 | 9 |
while True:
try:
a, b = map(int, input().rstrip().split())
print(len(str(a + b)))
except Exception:
break
| A,B,M=map(int,input().split())
a=[int(x) for x in input().split()]
b=[int(x) for x in input().split()]
m=[[] for i in range(M)]
for i in range(M):
m[i]=[int(x) for x in input().split()]
for i in range(M):
m[i]=a[m[i][0]-1]+b[m[i][1]-1]-m[i][2]
if(min(m)>min(a)+min(b)):
print(min(a)+min(b))
else:
print(min(m)) | 0 | null | 27,056,779,731,312 | 3 | 200 |
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
n,m = list(map(int, input().split()))
s = input()
c = n
ans = []
while c>0:
val = None
for i in range(1,m+1):
if c-i>=0 and s[c-i]=="0":
val = i
if val is None:
ans = -1
break
c = c-val
ans.append(val)
if ans==-1:
print(ans)
else:
write(" ".join(map(str, ans[::-1]))) | def bfs(n,e,fordfs,D):
#点の数、スタートの点、有向グラフ
W = [-1]*(n-1)
#各点の状態量、最短距離とか,見たかどうかとか
used = defaultdict(bool)
que = deque()
que.append(e)
while que:
now = que.popleft()
i = 1
for ne in fordfs[now]:
l = min(now,ne); r = max(now,ne)
if W[D[(l,r)]] == -1:
while(True):
if not used[(now,i)]:
used[(now, i)] = True
used[(ne, i)] = True
break
i +=1
que.append(ne)
W[D[(l,r)]] = i
return W
def examD():
N = I()
V = [[]for _ in range(N)]
d = defaultdict(int)
for i in range(N-1):
a, b = LI()
V[a-1].append(b-1)
V[b-1].append(a-1)
d[(a-1,b-1)] = i
ans = bfs(N,0,V,d)
print(max(ans))
for v in ans:
print(v)
return
def examF():
N, M = LI()
S = SI()
ans = []
cur = N
while(cur>0):
k = min(M,cur)
while(S[cur-k]=="1"):
k -=1
if k==0:
print("-1")
return
ans.append(k)
cur -=k
for v in ans[::-1]:
print(v)
return
import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]
if __name__ == '__main__':
examF()
| 1 | 139,253,816,946,968 | null | 274 | 274 |
def gcd(x, y):
if x < y:
x, y = y, x
while y != 0:
x, y = y, x % y
return x
if __name__ == "__main__":
x, y = list(map(int, input().split()))
print(gcd(x, y)) | X, Y, Z = [int(x) for x in input().split()]
print('{} {} {}'.format(Z, X, Y))
| 0 | null | 18,924,893,492,670 | 11 | 178 |
#!/usr/bin/env python3
import sys
import collections as cl
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def main():
S = input()
Q = II()
direction = 1
pre = []
sur = []
for i in range(Q):
query = input()
if query == '1':
direction *= -1
else:
_, f, c = query.split()
if direction == 1:
if f == '1':
pre.append(c)
else:
sur.append(c)
else:
if f == '1':
sur.append(c)
else:
pre.append(c)
if direction == 1:
ans = "".join(pre[::-1]) + S + "".join(sur)
else:
ans = "".join(sur[::-1]) + "".join(S[::-1]) + "".join(pre)
print(ans)
main()
| a,b,c = map(int, raw_input().split(' '))
print 'Yes' if a+b < c and 4*a*b < (c - a - b) **2 else 'No'
| 0 | null | 54,526,599,443,302 | 204 | 197 |
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10
N = INT()
x = []
for _ in range(N):
X, L = MAP()
x.append([X-L, X+L])
x.sort(key = lambda x: x[1])
ans = 0
tmp = -INF
for l, r in x:
if tmp <= l:
tmp = r
ans += 1
print(ans) | N, *A = map(int, open(0).read().split())
X = [(x-l, x+l) for x, l in zip(*[iter(A)]*2)]
X.sort()
ans = 1
L, R = X[0]
for l, r in X[1:]:
if R <= l:
ans += 1
L = l
R = r
elif R > r:
R = r
print(ans)
| 1 | 90,061,326,421,002 | null | 237 | 237 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
a, b, m =[int(i) for i in input().split(" ")]
res = 0
for i in range(a, b + 1):
if m % i == 0:
res += 1
print(res)
if __name__ == '__main__':
main() | 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=int(input())
B=int(input())
A2=min(A,B)
B2=max(A,B)
if(A2==1 and B2==2):
print(3)
sys.exit(0)
if(A2==2 and B2==3):
print(1)
sys.exit(0)
if(A2==1 and B2==3):
print(2)
sys.exit(0)
| 0 | null | 55,362,603,361,408 | 44 | 254 |
import collections, sys
sys.setrecursionlimit(100005)
N = int(input())
A = [int(_) for _ in input().split()]
INF = float('inf')
memo = collections.defaultdict(lambda: INF)
def c(start, res):
if memo[start, res] != INF:
return memo[start, res]
elif 2 * res - 1 > N - start:
memo[start, res] = -INF
elif start >= N:
memo[start, res] = -INF
elif res > 1:
memo[start, res] = max(A[start] + c(start + 2, res - 1),
c(start + 1, res), c(start + 2, res))
else:
memo[start, res] = max(A[start], c(start + 1, res))
return memo[start, res]
print(c(0, N // 2))
| import math;
n,x,t=list(map(int,input().split()))
print(math.ceil(n/x)*t) | 0 | null | 20,929,909,238,850 | 177 | 86 |
def main():
H, W, K = map(int, input().split())
S = [list(map(int,list(input()))) for _ in range(H)]
ans = float('inf')
for i in range(1<<H-1):
cut = []
for j in range(H):
if (i >> j) & 1:
cut.append(j+1)
tmp_S = [[0] * W for _ in range(len(cut) + 1)]
tmp_id = 0
for i in range(H):
if i in cut:
tmp_id += 1
for j in range(W):
tmp_S[tmp_id][j] += S[i][j]
isOK = True
for i in range(len(cut) + 1):
for w in range(W):
if tmp_S[i][w] > K:
isOK = False
if not isOK:
continue
cnt = len(cut)
white = [0] * (len(cut)+1)
flag = False
for w in range(W):
for i in range(len(cut) + 1):
white[i] += tmp_S[i][w]
if white[i] > K:
cnt += 1
flag = True
break
if flag:
for i in range(len(cut) + 1):
white[i] = tmp_S[i][w]
flag = False
ans = min(ans, cnt)
print(ans)
if __name__ == "__main__":
main() | from bisect import bisect_left
N = int(input())
L = list(map(int, input().split()))
L.sort()
ans = 0
for i in range(N):
for j in range(i + 1, N):
c = L[i] + L[j]
# a+bが入る場所を返す
idx = bisect_left(L, c)
ans += max(0, idx - (j + 1))
print(ans)
| 0 | null | 110,408,541,613,888 | 193 | 294 |
n,m = map(int,input().split())
s = input()
s_0 = []
for i in range(n+1):
if(s[i] == '0'):
s_0.append(i)
# 二分木
import bisect
now = n
ans_rev = []
while(now != 0):
next_i = bisect.bisect_left(s_0, now-m)
next = s_0[next_i]
if(now == next):
print(-1)
exit()
ans_rev.append(now-next)
now = next
print(' '.join(map(str, ans_rev[::-1]))) | l = input()
stack1 = []
stack2 = []
all_area = 0
for val in range(len(l)):
if l[val] == "\\":
stack1.append(val)
elif l[val] == "/" and stack1 != []:
temp = stack1.pop(-1)
all_area = all_area + (val - temp)
each_area = val - temp
while stack2 != [] and stack2[-1][0] > temp:
each_area = each_area + stack2.pop(-1)[1]
stack2.append([temp, each_area])
else:
pass
print(all_area)
print(len(stack2), end="")
for i in range(len(stack2)):
print(" ", end="")
print(stack2[i][1],end="")
print("")
| 0 | null | 69,490,775,622,358 | 274 | 21 |
N,K = map(int,input().split())
H = list(map(int,input().split()))
res = 0
for i in range(N):
if H[i]>=K:
res += 1
print(res) | H = int(input())
W = int(input())
N = int(input())
big = max(H,W)
bigsum = 0
ans = 0
while bigsum < N:
bigsum += big
ans += 1
print(ans)
| 0 | null | 133,585,075,045,732 | 298 | 236 |
import sys
#from collections import deque
#from functools import *
#from fractions import Fraction as f
from copy import *
from bisect import *
#from heapq import *
#from math import ceil
#from itertools import permutations ,product
def eprint(*args):
print(*args, file=sys.stderr)
zz=1
#sys.setrecursionlimit(10**6)
if zz:
input=sys.stdin.readline
else:
sys.stdin=open('input.txt', 'r')
sys.stdout=open('all.txt','w')
di=[[-1,0],[1,0],[0,1],[0,-1]]
def inc(d,c,x=1):
d[c]=d[c]+x if c in d else x
def bo(i):
return ord(i)-ord('A')
def li():
return [int(xx) for xx in input().split()]
def fli():
return [float(x) for x in input().split()]
def comp(a,b):
if(a>b):
return 2
return 2 if a==b else 0
def gi():
return [xx for xx in input().split()]
def fi():
return int(input())
def pro(a):
return reduce(lambda a,b:a*b,a)
def swap(a,i,j):
a[i],a[j]=a[j],a[i]
def si():
return list(input().rstrip())
def mi():
return map(int,input().split())
def gh():
sys.stdout.flush()
def isvalid(i,j):
return 0<=i<n and 0<=j<m and a[i][j]!="."
def bo(i):
return ord(i)-ord('a')
def graph(n,m):
for i in range(m):
x,y=mi()
a[x].append(y)
a[y].append(x)
mod=10**9+7
t=1
while t>0:
t-=1
n=fi()
a=[]
b=[]
for i in range(n):
x,y=mi()
a.append(x+y)
b.append(x-y)
p=max(a)-min(a)
q=max(b)-min(b)
print(max(p,q))
| def main():
n = int(input())
X, Y = [], []
for _ in range(n):
x, y = map(int, input().split())
X.append(x + y)
Y.append(x - y)
X.sort()
Y.sort()
print(max(X[-1] - X[0], Y[-1] - Y[0]))
if __name__ == '__main__':
main()
| 1 | 3,472,445,563,342 | null | 80 | 80 |
n,k = map(int, input().split())
r, s, p = map(int, input().split())
T = list(str(input()))
ans = 0
S = [-1]*n
for i in range(n):
if i <= k-1:
if T[i] == 'r':
S[i] = 'p'
ans += p
elif T[i] == 's':
S[i] = 'r'
ans += r
else:
S[i] = 's'
ans += s
else:
if T[i] == 'r':
if S[i-k] != 'p':
S[i] = 'p'
ans += p
else:
if i+k <= n-1:
if T[i+k] == 's':
S[i] = 's'
elif T[i+k] == 'p':
S[i] = 'r'
else:
S[i] = 'r'
else:
S[i] = 'r'
elif T[i] == 's':
if S[i-k] != 'r':
S[i] = 'r'
ans += r
else:
if i+k <= n-1:
if T[i+k] == 'p':
S[i] = 'p'
elif T[i+k] == 'r':
S[i] = 's'
else:
S[i] = 's'
else:
S[i] = 's'
else:
if S[i-k] != 's':
S[i] = 's'
ans += s
else:
if i+k <= n-1:
if T[i+k] == 's':
S[i] = 'p'
elif T[i+k] == 'r':
S[i] = 'r'
else:
S[i] = 'p'
else:
S[i] = 'p'
print(ans)
| n,k=map(int,input().split())
r,s,p=map(int,input().split())
t=input()
d={'r':p,'s':r,'p':s}
d_={'r':'p','s':'r','p':'s'}
s=0
for i in range(k):
a=0
z='0'
t_=t[i::k]
for a in range(len(t_)):
if a==0:
s+=d[t_[a]]
z=d_[t_[a]]
a+=1
else:
if z==d_[t_[a]]:
z='0'
a+=1
else:
s+=d[t_[a]]
z=d_[t_[a]]
a+=1
print(s)
| 1 | 107,028,888,274,120 | null | 251 | 251 |
N = int(input())
A = list(map(int, input().split()))
MOD = 10**9 + 7
def gcd(n, m):
if m == 0:
return n
return gcd(m, n % m)
def lcm(a, b):
return a * b // gcd(a, b)
L = 1
for a in A:
L = lcm(L, a)
L %= MOD
coef = 0
for a in A:
coef += pow(a, MOD - 2, MOD)
print((L * coef) % MOD)
| #S, L, h
import math
a, b, C = map(int, input().split())
S = a*b*math.sin(C*math.pi/180)*(1/2)
L = a+b+math.sqrt(a*a+b*b-2*a*b*math.cos(C*math.pi/180))
h = 2*S/a
print('%.4f'% S)
print('%.4f'% L)
print('%.4f'% h) | 0 | null | 44,014,521,313,468 | 235 | 30 |
N,X,M = map(int, input().split())
A = [X]
S = set(A)
cnt = 0
i = 0
for i in range(1, N):
A.append(A[i-1] ** 2 % M)
if A[i] in S:
break
else:
S.add(A[i])
roup_cycle = i - A.index(A[i])
before_roup_sums = sum(A[:A.index(A[i])])
roup_sums = sum(A[A.index(A[i]):i])
if roup_cycle != 0:
roup_amount = (N - A.index(A[i])) // roup_cycle
roup_mod = (N - A.index(A[i])) % roup_cycle
print(before_roup_sums + roup_sums * roup_amount + sum(A[A.index(A[i]):(A.index(A[i]) + roup_mod)]))
else:
print(sum(A)) | n,m = map(int,input().split())
k = 1
k_even = n//2+1
p_even = k_even+1
def rotate(s,diff):
if s + diff < 1:
return s+diff+n
elif s + diff > n:
return s+diff-n
return s+diff
for i in range(m+1):
if i != 0 and i % 2 == 0:
print(rotate(k,-(i//2)),rotate(k,i//2))
if i % 2 == 1:
print(rotate(k_even,-(i//2)),rotate(p_even,i//2))
| 0 | null | 15,685,657,670,102 | 75 | 162 |
T1, T2 = map(int, input().split())
A1, A2 = map(int, input().split())
B1, B2 = map(int, input().split())
SA = T1 * A1 + T2 * A2
SB = T1 * B1 + T2 * B2
if SA == SB or A1 == B1:
print('infinity')
exit()
if SA > SB and A1 < B1:
M = (B1 - A1) * T1
d = SA - SB
cnt = M // d
ans = cnt * 2
if M % d != 0:
ans += 1
print(max(0, ans))
elif SB > SA and B1 < A1:
M = (A1 - B1) * T1
d = SB - SA
cnt = M // d
ans = cnt * 2
if M % d != 0:
ans += 1
print(max(0, ans))
else:
print(0)
| T1, T2 = map(int, input().split())
A1, A2 = map(int, input().split())
B1, B2 = map(int, input().split())
v1, v2 = A1 - B1, A2 - B2
d1, d2 = v1 * T1, v2 * T2
if d1 > 0:
d1 *= -1
d2 *= -1
if d1 + d2 < 0:
print(0)
elif d1 + d2 == 0:
print("infinity")
elif d1 + d2 > 0:
s, t = divmod(-d1, d1+d2)
print(2*s+(t!=0)) | 1 | 131,761,134,943,328 | null | 269 | 269 |
def main():
import sys
input = sys.stdin.readline
N, R = map(int, input().split())
if N < 10:
K = N
else:
K = 10
print(R+100*(10-K))
if __name__ == "__main__":
main()
| n, r = [int(i) for i in input().split()]
ans = r if n >= 10 else r + 100 *(10 - n)
print(ans) | 1 | 63,806,547,247,560 | null | 211 | 211 |
# -*- coding: utf-8 -*-
def get_input() -> tuple:
"""
標準入力を取得する.
Returns:\n
tuple: 標準入力
"""
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
return N, K, A
def main(N: int, K: int, A: list) -> None:
"""
メイン処理.
Args:\n
N (int): 学期数(2 <= N <= 200000)
K (int): 直近何回分までの点数を考慮するか(1 <= K <= N - 1)
A (list): i学期の期末テストの点数
"""
# 求解処理
for i in range(K, N):
if A[i] > A[i - K]:
print("Yes")
else:
print("No")
if __name__ == "__main__":
# 標準入力を取得
N, K, A = get_input()
# メイン処理
main(N, K, A)
| a,b = map(int,input().split())
d,r = divmod(a,b)
print("{} {} {:.6f}".format(d,r,a/b)) | 0 | null | 3,803,541,129,778 | 102 | 45 |
n = int(input())
c = input()
cnt = 0
ans = 0
for i in range(n):
if(c[i]=='R'):
cnt+=1
for i in range(cnt):
if(c[i]=='W'):
ans+=1
print(ans) | N = int(input())
A = list(map(int, input().split()))
B = [0] * N
for i in range(0, N):
B[A[i]-1] = i+1
[print(x, end=' ') for x in B] | 0 | null | 93,310,339,493,130 | 98 | 299 |
import itertools
import numpy as np
d_list = []
sum_d = 0
N, M, Q = map(int, input().split())
abcd = [list(map(int, input().split())) for i in range(Q)]
ans = 0
A = [1 for i in range(N)]
for A in itertools.combinations_with_replacement(range(1, M+1), N):
for i in range(Q):
if A[abcd[i][1]-1]-A[abcd[i][0]-1] == abcd[i][2]:
d_list.append(abcd[i][3])
if sum_d <= sum(d_list):
sum_d = sum(d_list)
d_list.clear()
print(sum_d) | N,M,Q=map(int,input().split())
Query=[list(map(int,input().split())) for i in range(Q)]
import itertools
ans=0
for x in itertools.combinations_with_replacement(range(1, M+1), N):
l=0
for i in range(Q):
a,b,c,d=map(int,Query[i])
if x[b-1]-x[a-1]==c:
l+=d
ans=max(ans,l)
print(ans) | 1 | 27,615,274,641,202 | null | 160 | 160 |
N = input()
A = list(int(x) for x in input().split())
if len(set(A)) == len(A):
print('YES')
else:
print('NO')
| from math import floor
def main():
X=int(input())
tmp=100
for year in range(1,4000):
tmp += tmp//100
if tmp >= X:
print(year)
exit()
main()
| 0 | null | 50,798,361,620,128 | 222 | 159 |
H, W = map(int, input().split())
S = [list(input()) for h in range(H)]
table = [[0 for w in range(W)] for h in range(H)]
table[0][0] = int(S[0][0]=='#')
for i in range(1, H):
table[i][0] = table[i-1][0] + int(S[i-1][0]=='.' and S[i][0]=='#')
for j in range(1, W):
table[0][j] = table[0][j-1] + int(S[0][j-1]=='.' and S[0][j]=='#')
for i in range(1, H):
for j in range(1, W):
table[i][j] = min(table[i-1][j] + int(S[i-1][j]=='.' and S[i][j]=='#'),
table[i][j-1] + int(S[i][j-1]=='.' and S[i][j]=='#'))
print(table[-1][-1]) | from collections import deque
h,w=map(int,input().split())
field=[["*" for i in range(w+2)]]+[["*"]+list(input())+["*"] for i in range(h)]+[["*" for i in range(w+2)]]
cost=[[500 for i in range(w+2)] for j in range(h+2)]
cost[1][1]=0
ans=0
for i in range(1,h+1):
for j in range(1,w+1):
color=field[i][j]
if color=="." and field[i][j+1]=="#":
cost[i][j+1]=min(cost[i][j]+1,cost[i][j+1])
else:cost[i][j+1]=min(cost[i][j],cost[i][j+1])
if color=="." and field[i+1][j]=="#":
cost[i+1][j]=min(cost[i][j]+1,cost[i+1][j])
else:cost[i+1][j]=min(cost[i][j],cost[i+1][j])
print(cost[h][w] if field[1][1]=="." else cost[h][w]+1)
| 1 | 49,241,648,462,486 | null | 194 | 194 |
turn = int(input())
tp, hp = 0, 0
for i in range(turn):
t, h = input().split()
if t == h:
tp += 1
hp += 1
elif t > h:
tp += 3
elif t < h:
hp += 3
print(tp, hp)
| #! python3
# card_game.py
n = int(input())
turns = [input() for i in range(n)]
taro, hanako = 0, 0
for turn in turns:
t, h = turn.split(' ')
min_len = len(t) if len(t) <= len(h) else len(h)
win_flag = 0 # -1: taro, 1: hanako, 0: draw
for i in range(min_len):
if ord(t[i]) < ord(h[i]):
win_flag = 1
break
elif ord(h[i]) < ord(t[i]):
win_flag = -1
break
if win_flag == 0:
if len(t) < len(h):
win_flag = 1
elif len(h) < len(t):
win_flag = -1
if win_flag == -1:
taro += 3
elif win_flag == 1:
hanako += 3
else:
taro += 1
hanako += 1
print(taro, hanako)
| 1 | 1,990,531,345,920 | null | 67 | 67 |
from collections import deque
n = int(input())
adj = [ [] for _ in range(n+1) ]
for _ in range(n):
lst = list(map(int,input().split()))
if lst[1] > 0:
adj[lst[0]] = lst[2:]
q = deque([1])
dist = [-1] * (n+1)
dist[1] = 0
q = deque([1])
while q:
node = q.popleft()
for nei in adj[node]:
if dist[nei] != -1: continue
dist[nei] = dist[node] + 1
q.append(nei)
for i,s in enumerate(dist):
if i==0: continue
print(i, s)
| from collections import deque
n = int(input())
d = [-1]*n
d[0] = 0
M = []
for i in range(n):
adj = list(map(int,input().split()))
if adj[1] == 0:
M += [[]]
else:
M += [adj[2:]]
Q = deque([0])
while Q != deque([]):
u = Q.popleft()
for i in range(len(M[u])):
v = M[u][i]-1
if d[v] == -1:
d[v] = d[u] + 1
Q.append(v)
for i in range(n):
print(i+1,d[i])
| 1 | 4,116,161,472 | null | 9 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.