code1
stringlengths 16
427k
| code2
stringlengths 16
427k
| similar
int64 0
1
| pair_id
int64 6.82M
181,637B
⌀ | question_pair_id
float64 101M
180,471B
⌀ | code1_group
int64 2
299
| code2_group
int64 2
299
|
---|---|---|---|---|---|---|
A, B, C, D = map(int, input().split())
takahashi_turn = True
while A > 0 and C > 0:
if takahashi_turn:
C = C - B
else:
A = A - D
takahashi_turn = not takahashi_turn
if A > 0:
print('Yes')
else:
print('No') | a, b, c, d = map(int, input().split())
for i in range(101):
x = c - b*i
y = a - d*i
if x <= 0:
print("Yes")
break
elif y <= 0:
print("No")
break | 1 | 29,919,348,067,840 | null | 164 | 164 |
import math
R = float(input())
print(2*math.pi*R) | n = int(input())
st = list(map(int,input().split()))
st.sort(reverse = True)
count = 0
for i in range(n):
for j in range(i+1,n):
for k in range(j+1,n):
if (st[i] != st[j] != st[k]) and (st[i] < st[j] + st[k]):
count += 1
print(count)
| 0 | null | 18,197,890,207,304 | 167 | 91 |
last=input()
if last=="ABC":
print("ARC")
elif last=="ARC":
print("ABC") | a = str(input())
if a=="ABC":
print("ARC")
elif a=="ARC":
print("ABC") | 1 | 24,154,025,606,300 | null | 153 | 153 |
import sys
import bisect
input = sys.stdin.readline
class Bisect(object):
def bisect_max(self, reva, func,M):
ok = 0 # exist
ng = 4*(10**5) # not exist
while abs(ok-ng) > 1:
cnt = (ok + ng) // 2
if func(cnt,reva,M):
ok = cnt
else:
ng = cnt
return ok
def solve1(tgt,reva,M):
res=0
n = len(reva)
for i in range(n):
tmp = bisect.bisect_left(reva,tgt-reva[i])
tmp = n - tmp
res += tmp
if M <= res:
return True
else:
return False
N,M = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse=True)
reva = a[::-1]
bs = Bisect()
Kmax = (bs.bisect_max(reva,solve1,M))
r=[0]
for i in range(N):
r.append(r[i]+a[i])
res = 0
cnt = 0
t = 0
for i in range(N):
tmp = bisect.bisect_left(reva,Kmax-reva[N-i-1])
tmp2 = bisect.bisect_right(reva,Kmax-reva[N-i-1])
if tmp!=tmp2:
t = 1
tmp = N - tmp
cnt += tmp
res += tmp*a[i]+r[tmp]
if t==1:
res -= (cnt-M)*Kmax
print(res)
| n=int(input())
arr=[input() for _ in range(n)]
dic={}
for i in range(n): #各単語の出現回数を数える
if arr[i] not in dic:
dic[arr[i]]=1
else:
dic[arr[i]]+=1
largest=max(dic.values()) #最大の出現回数を求める
ans=[]
for keys in dic.keys():
if dic[keys]==largest: #出現回数が最も多い単語を集計する
ans.append(keys)
ans=sorted(ans) #単語を辞書順に並べ替えて出力する
for words in ans:
print(words) | 0 | null | 88,966,588,183,140 | 252 | 218 |
N,K=map(int,input().split())
if N > K:
N %= K
ans = min(N, K-N)
print(ans) | h = int(input())
cnt = 0
for i in range(h.bit_length()):
cnt += 2**i
print(cnt) | 0 | null | 59,862,877,640,488 | 180 | 228 |
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from collections import defaultdict
def main():
n, k, *a = map(int, read().split())
cur_town = 0
tran_time = defaultdict(int)
cnt = 0
while True:
if k == 0:
print(cur_town + 1)
sys.exit()
if cur_town in tran_time:
break
else:
tran_time[cur_town] = cnt
cur_town = a[cur_town] - 1
cnt += 1
k -= 1
k2 = k % (cnt - tran_time[cur_town])
while k2 > 0:
k2 -= 1
cur_town = a[cur_town] - 1
print(cur_town + 1)
if __name__ == '__main__':
main() | N, K = map(int,input().split())
As = list(map(int,input().split()))
visited = [0] * N
path = []
now_town = 1
while(True):
visited[now_town-1] = 1
path.append(now_town)
now_town = As[now_town-1]
if visited[now_town-1] == 1:
break
index = path.index(now_town)
loop = path[index:len(path)]
loop_len = len(loop)
if index < K:
k = K - index
r = k % loop_len
print(loop[r])
else:
print(path[K])
| 1 | 22,852,718,071,228 | null | 150 | 150 |
#!/usr/bin/env python
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**6)
INF = float("inf")
def main():
A,B = map(int,input().split())
print(max(0, A-B*2))
if __name__ == "__main__":
main() | x,y=map(int,input().split())
print(max(x-2*y,0)) | 1 | 167,245,220,880,492 | null | 291 | 291 |
w,h,x,y,r = map(int,input().split())
if x < r or y < r or w - x < r or h - y < r:
print("No")
else:
print("Yes")
| X=int(input())
a=int(X/500)
s=1000*a
X-=500*a
b=int(X/5)
s+=5*b
print(s) | 0 | null | 21,719,094,077,790 | 41 | 185 |
from collections import deque
N = int(input())
d = {i:[] for i in range(1, N+1)}
q = deque([(1, "a")])
while q:
pos, s = q.popleft()
if pos == N+1:
break
d[pos].append(s)
size = len(set(s))
for i in range(size+1):
q.append((pos+1, s+chr(97+i)))
for i in d[N]:
print(i) | N=int(input())
ans =0
for i in range(1,N):ans += (N-1)//i
print(ans) | 0 | null | 27,442,091,330,940 | 198 | 73 |
input();print(*input().split()[::-1])
| list = [input().split()]
r = int(list[0][0])
c = int(list[0][1])
i = 0
k = 0
sum2 = 0
list3 = [0] * c
while i < r:
sum = 0
list2 = [input().split()]
for j in list2[0]:
print(j, end=' '),
sum += int(j)
for k in range(c):
list3[k] += int(list2[0][k])
print(sum)
sum2 += sum
i += 1
for l in list3:
print(l, end=' ')
print(sum2) | 0 | null | 1,181,302,549,040 | 53 | 59 |
n = int(raw_input())
tp = 0; hp = 0
for i in range(n):
tw,hw = raw_input().split()
if tw == hw:
tp += 1
hp += 1
elif tw > hw:
tp += 3
elif tw < hw:
hp += 3
print '%s %s' % (tp,hp) | t = 0
h = 0
for i in range(int(input())):
cards = input().split()
if cards[0] > cards[1]:
t += 3
elif cards[0] == cards[1]:
t += 1
h += 1
else:
h += 3
print(str(t) + " " + str(h)) | 1 | 2,029,241,518,920 | null | 67 | 67 |
S = input()
if S[0] == 'R':
if S[1] == 'R':
if S[2] == 'R':
print(3)
else:
print(2)
else:
print(1)
else:
if S[1] == 'R':
if S[2] == 'R':
print(2)
else:
print(1)
else:
if S[2] == 'R':
print(1)
else:
print(0) | n = int(input())
s = input()
total = s.count("R") * s.count("G") * s.count("B")
#l = ["RGB", "RBG", "GRB", "GBR", "BRG", "BGR"]
lR = [0]*n
lG = [0]*n
lB = [0]*n
for i in range(len(s)):
if s[i] == "R":
lR[i] += 1
elif s[i] == "G":
lG[i] += 1
else:
lB[i] += 1
#print(lR)
#print(lG)
#print(lB)
for i in range(n):
j = 1
if lR[i]:
while i-j >= 0 and i+j < n:
if lG[i+j]!=0 and lG[i+j] == lB[i-j]:
total -= 1
elif lG[i-j]!=0 and lG[i-j] == lB[i+j]:
total -= 1
j += 1
elif lG[i]:
while i-j >= 0 and i+j < n:
if lR[i+j]!=0 and lR[i+j] == lB[i-j]:
total -= 1
elif lR[i-j]!=0 and lR[i-j] == lB[i+j]:
total -= 1
j += 1
elif lB[i]:
while i-j >= 0 and i+j < n:
if lG[i+j]!=0 and lG[i+j] == lR[i-j]:
total -= 1
elif lG[i-j]!=0 and lG[i-j] == lR[i+j]:
total -= 1
j += 1
print(total)
| 0 | null | 20,521,346,738,060 | 90 | 175 |
# ABC 143 B
N = int(input())
D =[int(d) for d in input().split()]
from itertools import combinations
ans =0
for i in list(combinations(D,2)):
ans+=i[0]* i[1]
print(ans) | N = int(input())
s = input()
ans = 1
for i in range(1, len(s)):
if s[i-1] != s[i]:
ans += 1
print(ans) | 0 | null | 169,185,479,945,670 | 292 | 293 |
m1, d1 = input().split()
m2, d2 = input().split()
print('1' if m1 != m2 else '0')
| x=list(map(int, input().split()))
if x[1]*2>x[0]:
print(0)
else:
print(x[0]-x[1]*2) | 0 | null | 145,900,677,364,010 | 264 | 291 |
def roll(l, command):
'''
return rolled list
l : string list
command: string
'''
res = []
i = -1
if command =='N':
res = [l[i+2], l[i+6], l[i+3], l[i+4], l[i+1], l[i+5]]
if command =='S':
res = [l[i+5], l[i+1], l[i+3], l[i+4], l[i+6], l[i+2]]
if command =='E':
res = [l[i+4], l[i+2], l[i+1], l[i+6], l[i+5], l[i+3]]
if command =='W':
res = [l[i+3], l[i+2], l[i+6], l[i+1], l[i+5], l[i+4]]
return res
faces = input().split()
commands = list(input())
for command in commands:
faces = roll(faces, command)
print(faces[0])
|
class Dice:
def __init__(self, label):
self.d = label
def roll(self, direction):
if direction == "N":
self.d[0], self.d[1], self.d[5], self.d[4] = self.d[1], self.d[5], self.d[4], self.d[0]
elif direction == "S":
self.d[0], self.d[1], self.d[5], self.d[4] = self.d[4], self.d[0], self.d[1], self.d[5]
elif direction == "E":
self.d[0], self.d[2], self.d[5], self.d[3] = self.d[3], self.d[0], self.d[2], self.d[5]
else:
self.d[0], self.d[2], self.d[5], self.d[3] = self.d[2], self.d[5], self.d[3], self.d[0]
label = [int(i) for i in input().split()]
cmd = input()
dice1 = Dice(label)
for i in cmd:
dice1.roll(i)
print(dice1.d[0]) | 1 | 235,046,007,680 | null | 33 | 33 |
from math import pi
print(2 * pi * int(input()), end='\n\r')
| import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
# from collections import Counter,defaultdict,deque
# from itertools import permutations, combinations
# from heapq import heappop, heappush
# # input = sys.stdin.readline
# sys.setrecursionlimit(10**8)
# mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])
n = inp()
S = input()
ans = 0
for a,b,c in itertools.product(map(str,range(10)),repeat=3):
aa = False
bb = False
for s in S:
if aa == False and s == a:
aa = True
continue
if bb == False and aa == True and s == b:
bb = True
continue
if aa == True and bb == True and s == c:
ans += 1
break
print(ans) | 0 | null | 79,845,835,746,532 | 167 | 267 |
while True:
s = raw_input()
if s == "-":
break
m = int(raw_input())
for i in range(m):
n = int(raw_input())
s = s[n:]+s[:n]
print s
| '''
0から9までの数字から成る長さNの文字列Sの部分文字列の内、
十進数表記の整数とみなした時、素数Pで割り切れるものの個数を求めよ。
部分文字列は先頭が0であっても良く、文字列の位置で区別する。
terms:
1<=n<=2*10**5
2<=p<=10**4
input:
4 3
3543
output:
6
'''
from collections import defaultdict
import sys
input = sys.stdin.readline
INF = float('inf')
mod = 10 ** 9 + 7
eps = 10 ** -7
def inpl():
'''
一行に複数の整数
'''
return list(map(int, input().split()))
n, p = inpl()
s = input()[:-1]
arr = [int(s[i]) for i in range(n)]
ans = 0
if p == 2 or p == 5:
'''
10を割り切ると桁の話が使えないので場合分け
1の位が割り切れればそれだけ
'''
for i in range(n):
if arr[i] % p == 0:
ans += i + 1
print(ans)
else:
'''
Pが10の約数である2,5だと以下の仮定が成り立たないので使えない
・ある数XがPで割り切れるならそれを10倍したものもPで割り切れる
f(i)=Sの下i桁をPで割った時の余り
として、f(i)=f(j)になる組を考える。
するとiからj桁目までの値はPで割り切れる(i%p-j%p≡(i-j)%p)
pow(x,y,z)=x^y%z
'''
dic = defaultdict(int)
# dic = { 余り: 個数}
now = 0
dic[0]=1 # 余り0ならまず条件一致。それ以外だったら同じあまりが出た時点で条件一致
for i in range(n-1,-1,-1): #下i桁をpで割った余り
now += arr[i] * pow(10, n - 1 - i, p)
now %= p
ans+=dic[now]
dic[now] += 1
print(ans) | 0 | null | 30,047,839,243,150 | 66 | 205 |
import math
def calc_combi(n,m):
if n<=1:
return 0
return math.factorial(n)/(math.factorial(m)*(math.factorial(n-m)))
n,m=map(int,input().split())
ans=int(calc_combi(n,2)+calc_combi(m,2))
print(ans) | import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
def select(n,k):
return math.factorial(n)//(math.factorial(k)*math.factorial(n-k))
n,m = LI()
ans = 0
if n>=2:
ans += n*(n-1)//2
if m>=2:
ans += m*(m-1)//2
print(ans)
main()
| 1 | 45,679,906,810,980 | null | 189 | 189 |
#!usr/bin/env pypy3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == "\n":
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
def main():
N, K = LI()
x = N % K
y = abs(x - K)
print(min(x, y))
main()
| N,K=map(int,input().split())
a=N%K
print(min([a,K-a]))
| 1 | 39,363,973,836,022 | null | 180 | 180 |
N = int(input())
a = 0
for i in range(1,int(N**0.5)+1):
if N%i == 0:
a = max(a,i)
b = N//a
print((a-1)+(b-1)) | #!/usr/bin/env python3
import sys
DEBUG = False
class SegmentTree:
# Use 1-based index internally
def __init__(self, n, merge_func, fillval=sys.maxsize):
self.n = 1
while self.n < n:
self.n *= 2
self.nodes = [fillval] * (self.n * 2 - 1 + 1) # +1 for 1-based index
self.merge_func = merge_func
self.fillval = fillval
def update(self, idx, val):
idx += 1 # for 1-based index
nodes = self.nodes
mergef = self.merge_func
idx += self.n - 1
nodes[idx] = val
while idx > 1: # > 1 for 1-based index
idx >>= 1 # parent(idx) = idx >> 1 for 1-based index segment tree
nodes[idx] = mergef(nodes[idx << 1], nodes[(idx << 1) + 1]) # child(idx) = idx << 1 and idx << 1 + 1
def query(self, l, r):
l += 1; r += 1 # for 1-based index
l += self.n - 1
r += self.n - 1
acc = self.fillval
while l < r:
if l & 1:
acc = self.merge_func(acc, self.nodes[l])
l += 1
if r & 1:
acc = self.merge_func(acc, self.nodes[r - 1])
r -= 1
l >>= 1
r >>= 1
return acc
def read(t = str):
return t(sys.stdin.readline().rstrip())
def read_list(t = str, sep = " "):
return [t(s) for s in sys.stdin.readline().rstrip().split(sep)]
def dprint(*args, **kwargs):
if DEBUG:
print(*args, **kwargs)
return
def main():
read()
s = read()
a_ord = ord("a")
bit_offsets = {chr(c_ord): c_ord - a_ord for c_ord in range(ord("a"), ord("z") + 1)}
apps = SegmentTree(len(s), lambda x, y: x | y, 0)
i = 0
for c in s:
apps.update(i, 1 << bit_offsets[c])
i += 1
nr_q = read(int)
for i in range(0, nr_q):
q = read_list()
if q[0] == "1":
_, i, c = q # i_q in the question starts from 1, not 0
apps.update(int(i) - 1, 1 << bit_offsets[c])
else:
_, l, r = q # l_q and r_q in the question start from 1, not 0
print(bin(apps.query(int(l) - 1, int(r) - 1 + 1)).count("1")) # query in the question includes both edges
if __name__ == "__main__":
main() | 0 | null | 111,856,411,980,878 | 288 | 210 |
n = int(input())
a = int(input())
b = int(input())
interest = b - a
min = min(a,b)
for i in range(n-2):
f = int(input())
if f - min > interest:
interest = f - min
elif f < min:
min = f
print(interest) | def solve():
MOD = 10**9 + 7
N = int(input())
As = list(map(int, input().split()))
ans = 0
for d in range(60):
mask = 1<<d
num1 = len([1 for A in As if A & mask])
ans += num1 * (N-num1) * mask
ans %= MOD
print(ans)
solve()
| 0 | null | 61,458,928,869,480 | 13 | 263 |
import math
while True:
n = int(input())
if n==0: break
s = list(map(float, input().split()))
t = sum(s)
a = t / n
b = sum(map(lambda x: (x-a)**2, s))
print(math.sqrt(b/n)) | a,b=map(int,input().split())
x=''
if a<b:
for i in range(b):
x+=str(a)
elif a>b:
for i in range(a):
x+=str(b)
elif a==b:
for i in range(a):
x+=str(a)
print(x) | 0 | null | 42,256,825,938,808 | 31 | 232 |
s = input()
n = len(s)
k = int(input())
start = True
start_count = 0
start_char = s[0]
inside_num = 0
end_count = 0
end_char = ""
memory = s[0]
count = 1
for i in range(1,n):
if s[i] == memory:
count += 1
else:
if start:
start_count = count
start = False
else:
inside_num += count//2
count = 1
memory = s[i]
end_count = count
end_char = memory
ans = 0
if start_char == end_char:
if end_count == n:
ans = n*k//2
else:
ans += inside_num*k
ans += (start_count+end_count)//2*(k-1)+start_count//2+end_count//2
else:
inside_num += start_count//2
inside_num += end_count//2
ans += inside_num*k
print(ans) | from itertools import groupby
s = input()
k = int(input())
if len(set(s)) == 1:
print(len(s)*k//2)
exit()
g = [len(list(v)) for _, v in groupby(s)]
ans = sum(i//2 for i in g)*k
if s[0] != s[-1]:
print(ans)
exit()
a, *_, b = g
ans -= (a//2 + b//2 - (a+b)//2)*(k-1)
print(ans)
| 1 | 174,921,043,744,070 | null | 296 | 296 |
x=int(input())
if x>=30:
print('Yes')
else:
print('No') | # -*- coding:utf-8 -*-
n = int(input())
s=''
for i in range(1,n+1):
if i%3==0 or i%10==3:
s = s + " " + str(i)
continue
else:
x = i
while x >0:
x //= 10
if x%10==3:
s = s + " " + str(i)
break
print(s) | 0 | null | 3,292,751,686,576 | 95 | 52 |
inps = input().split()
if len(inps) >= 2:
a = int(inps[0])
b = int(inps[1])
if a > b:
print("a > b")
elif a < b:
print("a < b")
else:
print("a == b")
else:
print("Input illegal.") | import string
L = string.split(raw_input())
a = int(L[0])
b = int(L[1])
if a == b:
print "a == b"
elif a > b:
print "a > b"
elif a < b:
print "a < b" | 1 | 359,417,714,238 | null | 38 | 38 |
class D_Linked_List:
class Node:
def __init__(self, key, next = None, prev = None):
self.next = next
self.prev = prev
self.key = key
def __init__(self):
self.nil = D_Linked_List.Node(None)
self.nil.next = self.nil
self.nil.prev = self.nil
def insert(self, key):
node_x = D_Linked_List.Node(key, self.nil.next, self.nil)
self.nil.next.prev = node_x
self.nil.next = node_x
def _listSearch(self, key):
cur_node = self.nil.next
while (cur_node != self.nil) and (cur_node.key != key):
cur_node = cur_node.next
return cur_node
def _deleteNode(self, node):
if node == self.nil:
return None
node.prev.next = node.next
node.next.prev = node.prev
def deleteFirst(self):
self._deleteNode(self.nil.next)
def deleteLast(self):
self._deleteNode(self.nil.prev)
def deleteKey(self, key):
node = self._listSearch(key)
self._deleteNode(node)
def show_keys(self):
cur_node = self.nil.next
keys_str = ''
while cur_node != self.nil:
keys_str += '{0} '.format(cur_node.key)
cur_node = cur_node.next
print(keys_str.rstrip())
import sys
d_ll = D_Linked_List()
for i in sys.stdin:
if 'insert' in i:
x = int(i.split()[1])
d_ll.insert(x)
elif 'deleteFirst' in i:
d_ll.deleteFirst()
elif 'deleteLast' in i:
d_ll.deleteLast()
elif 'delete' in i:
x = int(i.split()[1])
d_ll.deleteKey(x)
else:
pass
d_ll.show_keys() | from collections import deque
n = int(input())
l = deque()
for _ in range(n):
command = input().split()
if command[0] == "insert":
l.appendleft(command[1])
elif command[0] == "delete":
try:
ind = l.remove(command[1])
except ValueError:
pass
elif command[0] == "deleteFirst":
l.popleft()
elif command[0] == "deleteLast":
l.pop()
print (" ".join(l)) | 1 | 51,949,175,942 | null | 20 | 20 |
def f(n):
res = 0
s = 0
for i in range(1,n+1):
s += i
if s <=n:
res = i
else:
break
return res
n = int(input())
p =2
ans = 0
while p*p <= n:
e = 0
while n%p == 0:
e += 1
n//=p
ans += f(e)
p +=1
if n >1:
ans += 1
print(ans) | from math import sqrt
from collections import defaultdict
N = int(input())
def prime_factorize(n):
a = defaultdict(int)
while n % 2 == 0:
a[2] += 1
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a[f] += 1
n //= f
else:
f += 2
if n != 1:
a[n] += 1
return a
ps = prime_factorize(N)
def func2(k):
n = 1
count = 1
while count * (count+1) // 2 <= k:
count += 1
return count-1
res = 0
for value in ps.values():
if value > 0:
res += func2(value)
print(res) | 1 | 16,869,738,168,808 | null | 136 | 136 |
# -*- coding: utf-8 -*-
n = input()
a = map(int, raw_input().split())
max = a[0]
min = a[0]
sum = 0
for i in range(n):
if a[i] > max:
max = a[i]
elif a[i] < min:
min = a[i]
else:
pass
sum += a[i]
print "%d %d %d" %(min, max, sum) | # import string
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()
def resolve():
N = int(input())
A = list(map(int, input().split()))
from itertools import accumulate
B = [0] + A
B = list(accumulate(B)) # 累積和を格納したリスト作成
# この問題は長さが1-Nの連続部分の和の最大値を出せというものなので以下の通り
S=B[-1]
minans = 10 ** 20
for i in range(1,N):
val=abs(B[i]-(S-B[i]))
minans=min(minans,val)
print(minans)
resolve() | 0 | null | 71,643,972,460,060 | 48 | 276 |
H, W, K = map(int,input().split())
S = []
ans = [["" for _ in range(W)] for __ in range(H)]
checkBerry = []
cake = 1
for i in range(H):
s = input()
S.append(s)
flag = False
for ss in s:
if ss == "#":
flag = True
checkBerry.append(flag)
LS = []
n = 0
lss = []
while(n < H):
lss.append(n)
if (checkBerry[n] == True):
LS.append(lss.copy())
lss = []
n += 1
if lss != []:
LS[-1].extend(lss)
for ls in LS:
i = 0
for l in ls:
if checkBerry[l] == True:
i = l
firstBerry = False
for j in range(W):
if(S[i][j] == "#" and firstBerry == False):
firstBerry = True
elif(S[i][j] == "#" and firstBerry == True):
cake += 1
for l in ls:
ans[l][j] = str(cake)
cake += 1
for a in ans:
print(" ".join(a))
| n = int(input())
a = list(map(int,input().split()))
mod = 10**9+7
ans = 0
for i in range(60):
x = 1<< i
l = len([1 for j in a if j & x])
ans += x * l * (n-l) % mod
ans %= mod
print(ans) | 0 | null | 132,868,074,243,760 | 277 | 263 |
# -*- config: utf-8 -*-
if __name__ == '__main__':
for i in range(int(raw_input())):
nums = map(lambda x:x**2,map(int,raw_input().split()))
nums.sort()
if nums[0]+nums[1] == nums[2]:
print "YES"
else :
print "NO" | import time
import random
d = int(input())
dd = d * (d + 1) // 2
*C, = map(int, input().split())
S = [list(map(int, input().split())) for i in range(d)]
T = []
L = [-1 for j in range(26)]
for i in range(d):
max_diff = -10**7
arg_max = 0
for j in range(26):
memo = L[j]
L[j] = i
diff = S[i][j] - sum([C[k] * (i - L[k]) for k in range(26)])
if diff > max_diff:
max_diff = diff
arg_max = j
L[j] = memo
T.append(arg_max)
L[arg_max] = i
def calc_score(T):
L = [-1 for j in range(26)]
X = [0 for j in range(26)]
score = 0
for i in range(d):
score += S[i][T[i]]
X[T[i]] += (d - i) * (i - L[T[i]])
L[T[i]] = i
for j in range(26):
score -= C[j] * (dd - X[j])
return score
score = calc_score(T)
start = time.time()
cnt = 0
while True:
now = time.time()
if now - start > 1.8:
break
p = (cnt // 26) % d
q = cnt % 26
memo = T[p]
T[p] = q
new_score = calc_score(T)
temp = 20000 * (1 - (now - start) / 2)
prob = 2**((new_score - score) / temp)
if random.random() < prob:
score = new_score
else:
T[p] = memo
cnt = (cnt + 1) % (10**9 + 7)
for t in T:
print(t + 1)
| 0 | null | 4,850,939,280,990 | 4 | 113 |
L=int(input())
print("{:.010f}".format((L/3)**3))
| X,Y,Z=map(int,input().split(" "))
tmp=Y
Y=X
X=tmp
tmp=Z
Z=X
X=tmp
print(X,Y,Z,end=" ") | 0 | null | 42,726,271,971,450 | 191 | 178 |
import sys
import math
import copy
import heapq
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(1000000)
# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]
INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)
def nck(n, k, kaijyo):
return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD
def npk(n, k, kaijyo):
if k == 0 or k == n:
return n % MOD
return (kaijyo[n] * divide(kaijyo[n-k])) % MOD
def fact_and_inv(SIZE):
inv = [0] * SIZE # inv[j] = j^{-1} mod MOD
fac = [0] * SIZE # fac[j] = j! mod MOD
finv = [0] * SIZE # finv[j] = (j!)^{-1} mod MOD
inv[1] = 1
fac[0] = fac[1] = 1
finv[0] = finv[1] = 1
for i in range(2, SIZE):
inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
fac[i] = fac[i - 1] * i % MOD
finv[i] = finv[i - 1] * inv[i] % MOD
return fac, finv
def renritsu(A, Y):
# example 2x + y = 3, x + 3y = 4
# A = [[2,1], [1,3]])
# Y = [[3],[4]] または [3,4]
A = np.matrix(A)
Y = np.matrix(Y)
Y = np.reshape(Y, (-1, 1))
X = np.linalg.solve(A, Y)
# [1.0, 1.0]
return X.flatten().tolist()[0]
class TwoDimGrid:
# 2次元座標 -> 1次元
def __init__(self, h, w, wall="o"):
self.h = h
self.w = w
self.size = (h+2) * (w+2)
self.wall = wall
self.get_grid()
self.init_cost()
def get_grid(self):
grid = [self.wall * (self.w + 2)]
for i in range(self.h):
grid.append(self.wall + getS() + self.wall)
grid.append(self.wall * (self.w + 2))
self.grid = grid
def init_cost(self):
self.cost = [INF] * self.size
def pos(self, x, y):
# 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
return y * (self.w + 2) + x
def getgrid(self, x, y):
return self.grid[y][x]
def get(self, x, y):
return self.cost[self.pos(x, y)]
def set(self, x, y, v):
self.cost[self.pos(x, y)] = v
return
def show(self):
for i in range(self.h+2):
print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
def showsome(self, tgt):
for t in tgt:
print(t)
return
def showsomejoin(self, tgt):
for t in tgt:
print("".join(t))
return
def search(self):
grid = self.grid
move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
d = deque()
d.append((1,1))
self.set(1,1,0)
while(d):
cx, cy = d.popleft()
cc = self.get(cx, cy)
if self.getgrid(cx, cy) == self.wall:
continue
for dx, dy in [(1, 0), (0, 1)]:
nx, ny = cx + dx, cy + dy
if self.getgrid(cx, cy) == self.getgrid(nx, ny):
if self.get(nx, ny) > cc:
d.append((nx, ny))
self.set(nx, ny, cc)
else:
if self.get(nx, ny) > cc + 1:
d.append((nx, ny))
self.set(nx, ny, cc + 1)
# self.show()
ans = (self.get(self.w, self.h))
if self.getgrid(1,1) == "#":
ans += 1
print((ans + 1) // 2)
def soinsu(n):
ret = defaultdict(int)
for i in range(2, int(math.sqrt(n) + 2)):
if n % i == 0:
while True:
if n % i == 0:
ret[i] += 1
n //= i
else:
break
if not ret:
return {n: 1}
return ret
def solve():
h, w = getList()
G = TwoDimGrid(h, w)
G.search()
def main():
n = getN()
for _ in range(n):
solve()
return
if __name__ == "__main__":
# main()
solve() | d=int(input())
if d == 1:
print(0)
else:
print(1) | 0 | null | 26,140,745,474,148 | 194 | 76 |
s=input()
a=[0]*(len(s)+1)
for i in range(len(s)):
if s[i]=="<":
a[i+1]=a[i]+1
for i in range(len(s)-1,-1,-1):
if s[i]==">":
a[i]=max(a[i],a[i+1]+1)
print(sum(a)) | while True:
a, b = map(int, input().split())
if a == 0 and b == 0:
break;
for i in range(0, a):
if i % 2 == 0:
print(("#." * int((b + 1) / 2))[:b])
else:
print((".#" * int((b + 1) / 2))[:b])
print("") | 0 | null | 78,608,704,769,256 | 285 | 51 |
n=int(input())
for i in range(1,361):
if (n*i)%360==0:
print(i);exit() | X = int(input())
K = 1
while K > 0:
if X * K % 360 == 0:
print(K)
break
else:
K += 1
| 1 | 13,067,977,480,070 | null | 125 | 125 |
#coding:utf-8
#1_8_B 2015.4.7
while True:
number = input()
if number == '0':
break
print(sum(int(i) for i in number)) | S = input()
T = input()
l = len(S)
count = 0
for i in range(l):
if S[i] != T[i]:
count += 1
print(count) | 0 | null | 6,019,806,461,258 | 62 | 116 |
n,k=map(int,input().split())
s=n//k
m=min((n-s*k),((s+1)*k-n))
print(m) | # 問題:https://atcoder.jp/contests/abc142/tasks/abc142_a
n = int(input())
res = (n+1)//2
res /= n
print(res)
| 0 | null | 108,262,640,109,338 | 180 | 297 |
X = int(input())
money = 100
ans = 0
while money < X:
tax = money // 100
money += tax
ans += 1
print(ans) | X = int(input())
year = 0
amount = 100
while amount < X:
risi = amount // 100
amount += risi
year += 1
print(year)
| 1 | 27,049,302,578,158 | null | 159 | 159 |
def koch(x0,y0, x1,y1, n):
if n == 0:
return [(x0,y0)]
else:
v = (y0-y1,x1-x0)
#print(type(n))
#print(n[0])
m = ((x0+x1)/2,(y0+y1)/2)
c1 = ((2*x0+x1)/3,(2*y0+y1)/3)
#print(m[0],n[0],m[1],n[1])
c2x = m[0]+v[0]/(2*(3**(1/2)))
c2y = m[1]+v[1]/(2*(3**(1/2)))
c2 = (c2x,c2y)
c3 = ((x0+2*x1)/3,(y0+2*y1)/3)
return koch(x0,y0, c1[0],c1[1], n-1) \
+ koch(c1[0],c1[1], c2[0],c2[1], n-1) \
+ koch(c2[0],c2[1], c3[0],c3[1], n-1) \
+ koch(c3[0],c3[1], x1,y1, n-1)
def show_vertex(x,y):
print("%.8f %.8f" % (x,y))
N = int(input())
V = koch(0,0,100,0,N)+[[100,0]]
for x,y in V:
show_vertex(x,y)
| n = int(input())
xl = []
for i in range(n):
x,l = map(int,input().split())
xl.append([x-l,x+l])
xl.sort(key = lambda x: x[1])
ans = 0
arm = -10**18
for i in range(n):
if arm<=xl[i][0]:
ans += 1
arm = xl[i][1]
print(ans) | 0 | null | 45,252,628,778,368 | 27 | 237 |
N = int(input())
C = input()
WL = [0]
RR = [C.count('R')]
for i in range(0, N):
if C[i] == 'R':
WL.append(WL[i])
RR.append(RR[i] - 1)
else:
WL.append(WL[i] + 1)
RR.append(RR[i])
MM = N
for i in range(0, N + 1):
MM = min(MM, (max(WL[i], RR[i])))
print(MM) | import sys
input = sys.stdin.readline
def main():
N = int(input())
P = []
for i in range(N):
X, L = map(int, input().split())
S, T = X-L, X+L
P.append((S, T))
P.sort(key=lambda x: x[1])
ans = 0
r = -float('inf')
for s, t in P:
if s >= r:
ans += 1
r = t
print(ans)
if __name__ == "__main__":
main()
| 0 | null | 48,145,640,366,252 | 98 | 237 |
n = int(input())
P = list(map(int, input().split()))
ans = 0
m = 200002
for p in P:
if p <= m:
m = p
ans += 1
print(ans) | n = int(input())
p = list(map(int, input().split()))
ret = 1
minp = p[0]
for i in range(1, n):
if p[i] <= minp:
ret += 1
minp = min(minp, p[i])
print(ret)
| 1 | 85,467,506,613,160 | null | 233 | 233 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
N = int(input())
G = [list(map(lambda x: int(x)-1, input().split()))[2:] for _ in range(N)]
D = [-1]*N
D2 = [-1]*N
def dfs(cur, now):
if D[cur] != -1: return now
now += 1
D[cur] = now
for nex in G[cur]:
now = dfs(nex,now)
now += 1
D2[cur] = now
return now
now = 0
for i in range(N):
now = dfs(i,now)
for i in range(N):
print(i+1,D[i],D2[i])
| import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy
time = 1
def dfs(node):
global time
if visited[node] != -1:
return
visited[node] = 0
d[node] = time
time += 1
for v in edge[node]:
dfs(v)
f[node] = time
time += 1
if __name__ == "__main__":
n = int(input())
edge = []
for i in range(n):
u,k,*v_li = map(int,input().split())
for j in range(len(v_li)):
v_li[j] -= 1
u-=1
edge.append(v_li)
d = {}
f = {}
visited = [-1]*n
for i in range(n):
dfs(i)
for i in range(n):
print(i+1,d[i],f[i])
| 1 | 2,999,049,252 | null | 8 | 8 |
n,k=map(int,input().split())
w=[0]*n
for i in range(n):
w[i] = int(input())
def hantei(w,a,k):
tumu=a
daime=1
for ww in w:
if ww<=tumu:
tumu-=ww
else:
tumu=a
daime+=1
if ww<=tumu:
tumu-=ww
else:
return False
if daime >k:
return False
else:
return True
right= max(w)*n +1
left = min(w)
while left<right:
mid = (left+right)//2
if hantei(w,mid,k):
right=mid
else:
left=mid+1
print(left)
| a,b=[int(i) for i in input().split(" ")]
while b!=0:
t = min(a,b)
b = max(a,b) % min(a,b)
a = t
print(a) | 0 | null | 44,873,328,364 | 24 | 11 |
def main():
n, m = map(int, input().split(" "))
a =list(map(int, input().split(" ")))
if n - sum(a) <0:
print(-1)
else:
print(n-sum(a))
if __name__ == "__main__":
main() | import sys
sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline
def solve():
s = input()
if s[2] == s[3] and s[4] == s[5]:
print('Yes')
else:
print('No')
if __name__ == '__main__':
solve()
| 0 | null | 37,023,449,658,818 | 168 | 184 |
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy,bisect
#from operator import itemgetter
#from heapq import heappush, heappop
#import numpy as np
#from scipy.sparse.csgraph import breadth_first_order, depth_first_order, shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
#from scipy.sparse import csr_matrix
#from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
import sys
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7
stdin = sys.stdin
ni = lambda: int(ns())
nf = lambda: float(ns())
na = lambda: list(map(int, stdin.readline().split()))
nb = lambda: list(map(float, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip() # ignore trailing spaces
max_ = 10 ** 18
N = ni()
A = na()
A.sort()
ans = 1
for i in range(N):
ans *= A[i]
if ans > max_:
ans = -1
break
print(ans) | tempStr = input()
print("ARC" if tempStr == "ABC" else "ABC") | 0 | null | 20,016,957,775,162 | 134 | 153 |
# coding=utf-8
def fib(number):
if number == 0 or number == 1:
return 1
memo1 = 1
memo2 = 1
for i in range(number-1):
memo1, memo2 = memo1+memo2, memo1
return memo1
if __name__ == '__main__':
N = int(input())
print(fib(N))
| X = int(input())
P = 360
ans = 1
x = X
while x%P != 0:
ans += 1
x += X
print(ans)
| 0 | null | 6,611,609,058,100 | 7 | 125 |
import math
def koch(d, p1, p2):
if d == 0:
return
sx = (2*p1[0]+1*p2[0])/3
sy = (2*p1[1]+1*p2[1])/3
s = (sx, sy)
tx = (1*p1[0]+2*p2[0])/3
ty = (1*p1[1]+2*p2[1])/3
t = (tx, ty)
rad = math.radians(60)
ux = (t[0]-s[0])*math.cos(rad)-(t[1]-s[1])*math.sin(rad)+s[0]
uy = (t[0]-s[0])*math.sin(rad)+(t[1]-s[1])*math.cos(rad)+s[1]
u = (ux, uy)
koch(d-1, p1, s)
print(s[0], s[1])
koch(d-1, s, u)
print(u[0], u[1])
koch(d-1, u, t)
print(t[0], t[1])
koch(d-1, t, p2)
d = int(input())
p1 = (0, 0)
p2 = (100, 0)
print(p1[0], p1[1])
koch(d, p1, p2)
print(p2[0], p2[1])
| # coding: utf-8
# Your code here!
import math
n = int(input())
p1 = [0.0, 0.0]
p2 = [100.0, 0.0]
def rad(r) :
return math.radians(r)
def sin(s) :
return math.sin(s)
def cos(s) :
return math.cos(s)
def A(n, p1, p2) :
if n == 0 :
return 0
else :
s = [0, 0]
t = [0, 0]
u = [0, 0]
s[0] = (p2[0] - p1[0]) / 3 + p1[0]
s[1] = (p2[1] - p1[1]) / 3 + p1[1]
t[0] = (p2[0] - p1[0]) / 3 * 2 + p1[0]
t[1] = (p2[1] - p1[1]) / 3 * 2 + p1[1]
u[0] = (t[0] - s[0]) * cos(rad(60)) - (t[1] - s[1]) * sin(rad(60)) + s[0]
u[1] = (t[0] - s[0]) * sin(rad(60)) + (t[1] - s[1]) * cos(rad(60)) + s[1]
A(n - 1, p1, s)
p(s[0], s[1])
A(n - 1, s, u)
p(u[0], u[1])
A(n - 1, u, t)
p(t[0], t[1])
A(n - 1, t, p2)
def p(x, y) :
print(f"{x:.8f} {y:.8f}")
print(p1[0], p1[1])
A(n, p1, p2)
print(p2[0], p2[1])
| 1 | 127,719,994,108 | null | 27 | 27 |
n,m = map(int, input().split())
s_c = [tuple(map(int, input().split())) for _ in range(m)]
ans = -1
for num in range(1000):
if len(str(num)) != n: continue
for s,c in s_c:
if str(num)[s-1] != str(c):
break
else:
ans = num
break
print(ans)
| k=int(input())
s=input()
mod=10**9+7
import sys
sys.setrecursionlimit(10**9)
def cmb(n, r, p):
if (r < 0) or (n < r):
return 0
r = min(r, n - r)
return fact[n] * factinv[r] * factinv[n-r] % p
p = mod #割る数
N = 2*(10 ** 6) # N は必要分だけ用意する
fact = [1, 1] # fact[n] = (n! mod p)
factinv = [1, 1] # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1] # factinv 計算用
for i in range(2, N + 1):
fact.append((fact[-1] * i) % p)
inv.append((-inv[p % i] * (p // i)) % p)
factinv.append((factinv[-1] * inv[-1]) % p)
ans=0
for i in range(k+1):
ans = (ans+cmb(i+len(s)-1,i,mod)*pow(26,k-i,mod)*pow(25,i,mod)) % mod
#print(end,len(s)+k-end,ans,cmb(end,len(s),mod),pow(25,end-len(s),mod),pow(26,len(s)+k-end,mod))
print(ans%mod)
| 0 | null | 36,631,941,021,020 | 208 | 124 |
n=input()
L1=[[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
L2=[[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
L3=[[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
L4=[[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
Mantion=[L1,L2,L3,L4]
for i in range(n):
b,f,r,v=map(int, raw_input().split())
Mantion[b-1][f-1][r-1]+=v
for j in range(3):
L1_str=map(str, L1[j])
print "",
print " ".join(L1_str)
print "#"*20
for j in range(3):
L2_str=map(str, L2[j])
print "",
print " ".join(L2_str)
print "#"*20
for j in range(3):
L3_str=map(str, L3[j])
print "",
print " ".join(L3_str)
print "#"*20
for j in range(3):
L4_str=map(str, L4[j])
print "",
print " ".join(L4_str) | ryou = [0]*4
for i in range(4):
ryou[i] = [0]*3
for i in range(4):
for j in range(3):
ryou[i][j] = [0]*10
sep = '#' * 20
n = int(input())
for i in range(n):
b, f, r, v = [int(x) for x in input().split()]
ryou[b-1][f-1][r-1] += v
for i in range(4):
for j in range(3):
s = ' '
s += ' '.join(map(str,ryou[i][j]))
print(s)
if not i == 3:
print(sep) | 1 | 1,104,999,270,062 | null | 55 | 55 |
inp = [int(a) for a in input().split()]
X = inp[0]
N = inp[1]
if N == 0:
print(X)
else:
P = [int(b) for b in input().split()]
found = 0
num = 0
answer = X
while(found == 0):
if not (X - num in P):
found = 1
answer = X - num
elif not (X + num in P):
found = 1
answer = X + num
num += 1
print(answer) | h,w = map(int, input().split())
s = [input()+"." for i in range(h)] + ["."*(w+1)]
INF = 10 ** 18
dp = [[INF]*(w+1) for i in range(h+1)]
dp[0][0] = 1 if s[0][0] == "#" else 0
for i in range(h):
for j in range(w):
if s[i][j] == "#":
dp[i+1][j] = min(dp[i+1][j], dp[i][j])
dp[i][j+1] = min(dp[i][j+1], dp[i][j])
else:
vi = 1 if s[i+1][j] == "#" else 0
vj = 1 if s[i][j+1] == "#" else 0
dp[i+1][j] = min(dp[i+1][j], dp[i][j]+vi)
dp[i][j+1] = min(dp[i][j+1], dp[i][j]+vj)
print(dp[h-1][w-1]) | 0 | null | 31,582,006,496,182 | 128 | 194 |
sortingThreeNum = list(map(int, input().split()))
sortingThreeNum.sort()
print(sortingThreeNum[0], sortingThreeNum[1], sortingThreeNum[2])
| number = [i for i in input().split()]
number.sort()
print(' '.join(number))
| 1 | 429,100,347,000 | null | 40 | 40 |
#ABC 175 C
x, k, d = map(int, input().split())
x = abs(x)
syou = x // d
amari = x % d
if k <= syou:
ans = x - (d * k)
else:
if (k - syou) % 2 == 0: #残りの動ける数が偶数
ans = amari
else:#残りの動ける数が奇数
ans = abs(amari - d)
print(ans) | n = input()
a = [raw_input() for _ in range(n)]
b = []
for i in ['S ','H ','C ','D ']:
for j in range(1,14):
b.append(i+str(j))
for i in a:
b.remove(i)
for i in b:
print i | 0 | null | 3,152,289,710,592 | 92 | 54 |
S = input().split()
N = int(S[0])
R = int(S[1])
if N >= 10:
r = R
else:
r = R + (10 - N)*100
print(r) | def main():
N, R = map(int, input().split())
if N >= 10:
print(R)
else:
print(R+(100*(10-N)))
if __name__ == '__main__':
main() | 1 | 63,610,666,012,238 | null | 211 | 211 |
from collections import deque
import numpy
N, M, X = [int(x) for x in input().split()]
stack = deque()
stack.appendleft((numpy.array([0] * M, dtype='int64'), 0, 0))
min_cost = 10**9
book_list = {}
while stack:
info = stack.popleft()
skill = info[0]
cost = info[1]
book_idx = info[2]
if book_idx < N:
if book_idx in book_list:
book = book_list[book_idx]
else:
book = numpy.array([int(x)
for x in input().split()], dtype='int64')
book_list[book_idx] = book
after_skill = skill + book[1:]
after_cost = cost+book[0]
stack.appendleft((after_skill, after_cost, book_idx+1))
stack.appendleft((skill, cost, book_idx+1))
else:
if cost < min_cost:
if numpy.all(skill >= X):
min_cost = cost
if min_cost == 10**9:
print(-1)
else:
print(min_cost)
| # -*- coding:utf-8 -*-
from collections import deque
result = deque()
def operation(command):
if command[0] == "insert":
result.appendleft(command[1])
elif command[0] == "delete":
if command[1] in result:
result.remove(command[1])
elif command[0] == "deleteFirst":
result.popleft()
elif command[0] == "deleteLast":
result.pop()
n = int(input())
for i in range(n):
command = input().split()
operation(command)
print(*result) | 0 | null | 11,270,266,649,798 | 149 | 20 |
N = int(input())
A = [int(x) for x in input().split()]
if 0 in A :
print("0")
exit()
result = 1
for i in range(N) :
result *= A[i]
if result > 10**18 :
print("-1")
exit()
print(result) | from collections import defaultdict
from itertools import groupby, accumulate, product, permutations, combinations
from bisect import *
def solve():
ans = 0
N = int(input())
S = input()
d = defaultdict(lambda: [])
for i,s in enumerate(S):
d[int(s)].append(i)
for p in product(range(10),repeat=3):
if not len(d[p[0]]):
continue
ind1 = d[p[0]][0]
ind2 = bisect_right(d[p[1]],ind1)
if ind2==len(d[p[1]]):
continue
ind2 = d[p[1]][ind2]
ind3 = bisect_right(d[p[2]],ind2)
if ind3==len(d[p[2]]):
continue
ans += 1
return ans
print(solve()) | 0 | null | 72,582,423,154,838 | 134 | 267 |
import math
a, b, n = list(map(int, input().split()))
x = min(n, b - 1)
ans = math.floor((a * x) / b) - a * math.floor(x / b)
print(ans)
| a,b,n=map(int,input().split())
x=min(n,b-1)
print(int((a*x/b)//1)) | 1 | 27,904,545,102,560 | null | 161 | 161 |
n = int(input())
S = input()
l = len(S)
S += 'eeee'
cnt = 0
for i in range(10):
for j in range(10):
for k in range(10):
# tmp = str(i)+str(j)+str(k)
m = 0
while S[m] != str(i):
m += 1
if m >= l:
break
m += 1
while S[m] != str(j):
m += 1
if m >= l:
break
m += 1
while S[m] != str(k):
m += 1
if m >= l:
break
if m < l:
cnt += 1
print(cnt)
| import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7
def resolve():
H, W, k = map(int, input().split())
grid = [[0] * W for _ in range(H)]
for _ in range(k):
r, c, v = map(int, input().split())
grid[r - 1][c - 1] = v
# dp[i][h][w]:h行目のアイテムをi個取得した時の、座標(h,w)における価値の最大値
dp = [[[0] * W for _ in range(H)] for _ in range(4)]
dp[1][0][0] = grid[0][0]
for h in range(H):
for w in range(W):
for i in range(4):
# 下に移動する場合
if h + 1 < H:
# アイテムを取らない
dp[0][h + 1][w] = max(dp[0][h + 1][w], dp[i][h][w])
# アイテムを取る
dp[1][h + 1][w] = max(dp[1][h + 1][w], dp[i][h][w] + grid[h + 1][w])
# 右に移動する場合
if w + 1 < W:
# アイテムを取らない
dp[i][h][w + 1] = max(dp[i][h][w + 1], dp[i][h][w])
# アイテムを取る(但し、4個以上所持してはいけない)
if i + 1 < 4:
dp[i + 1][h][w + 1] = max(dp[i + 1][h][w + 1], dp[i][h][w] + grid[h][w + 1])
res = 0
for i in range(4):
res = max(res, dp[i][-1][-1])
print(res)
if __name__ == '__main__':
resolve()
| 0 | null | 67,029,231,210,102 | 267 | 94 |
while True:
m,f,r = map(int,raw_input().split())
if m == -1 and f == -1 and r == -1:
break
if m == -1 or f == -1:
print('F')
elif m+ f >= 80:
print('A')
elif m + f >= 65 and m + f < 80:
print('B')
elif m + f >= 50 and m + f < 65 or r >= 50:
print('C')
elif m + f >= 30 and m + f < 50:
print('D')
elif m + f <= 29:
print('F') | while 1:
m,f,r=map(int,raw_input().split())
if m==f==r==-1 :break
ans=''
if m==-1 or f==-1 :ans= 'F'
else :
mp=m+f
if mp>=80:ans='A'
elif mp>=65:ans='B'
elif mp>=50 or (mp>=30 and r>=50):ans='C'
elif mp>=30:ans='D'
else :ans='F'
print ans | 1 | 1,229,606,534,662 | null | 57 | 57 |
#created by nit1n
N, S = map(int,input().split())
A = list(map(int,input().split()))
mod = 998244353
dp = [[0 for j in range(S + 1)] for i in range(N + 1)]
dp[0][0] = 1
for i in range(N) :
for j in range (S+1) :
dp[i+1][j] += 2*dp[i][j]
dp[i+1][j] = dp[i+1][j]%mod
if j +A[i] <= S :
dp[i+1][j+A[i]] += dp[i][j]
dp[i+1][j+A[i]] %= mod
print(dp[N][S])
| 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,532,063,735,390 | null | 138 | 138 |
import sys
n, m, l = [ int( val ) for val in sys.stdin.readline().split( " " ) ]
matrixA = [ [ int( val ) for val in sys.stdin.readline().split( " " ) ] for row in range( n ) ]
matrixB = [ [ int( val ) for val in sys.stdin.readline().split( " " ) ] for row in range( m ) ]
matrixC = [ [ 0 for row in range( l ) ] for row in range( n ) ]
output = []
for i in range( n ):
for j in range( l ):
for k in range( m ):
matrixC[i][j] += ( matrixA[i][k] * matrixB[k][j] )
output.append( "{:d}".format( matrixC[i][j] ) )
output.append( " " )
output.pop()
output.append( "\n" )
output.pop()
print( "".join( output ) ) | import sys
N, M, L = map(int, raw_input().split())
a = []
b = []
for n in range(N):
a.append(map(int, raw_input().split()))
for m in range(M):
b.append(map(int, raw_input().split()))
c = [[0 for l in xrange(L)] for n in xrange(N)]
for n in xrange(N):
for l in xrange(L):
for m in xrange(M):
c[n][l] += a[n][m] * b[m][l]
for n in xrange(N):
for l in xrange(L-1):
sys.stdout.write(str(c[n][l])+" ")
print c[n][L-1] | 1 | 1,442,828,495,538 | null | 60 | 60 |
H, W, K = map(int, input().split())
sl = []
for _ in range(H):
sl.append(list(input()))
ans = 10**8
for i in range(2 ** (H-1)):
fail_flag = False
comb = []
for j in range(H-1):
if ((i >> j) & 1):
comb.append(j)
comb.append(H-1)
# print(comb)
sections = []
for k in range(0,len(comb)):
if k == 0:
sections.append( sl[0:comb[0]+1] )
else:
sections.append( sl[comb[k-1]+1:comb[k]+1] )
# print(sections)
partition_cnt = 0
sections_w_cnts = [0]*len(sections)
for w in range(W):
sections_curr_w_cnts = [0]*len(sections)
partition_flag = False
for i, sec in enumerate(sections):
for row in sec:
if row[w] == '1':
sections_curr_w_cnts[i] += 1
sections_w_cnts[i] += 1
if sections_curr_w_cnts[i] > K:
fail_flag = True
break
if sections_w_cnts[i] > K:
partition_flag = True
if fail_flag: break
if fail_flag: break
if partition_flag:
sections_w_cnts = [v for v in sections_curr_w_cnts]
# sections_w_cnts[:] = sections_curr_w_cnts[:]
partition_cnt += 1
if not fail_flag:
ans = min(len(comb)-1+partition_cnt, ans)
print(ans) | #!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from functools import reduce, lru_cache
import functools
import collections, heapq, itertools, bisect
import math, fractions
import sys, copy
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline().rstrip())
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def S(): return list(sys.stdin.readline().rstrip())
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
MOD = 1000000007
def main():
N = I()
A = LI()
C0, C1 = [0] * 60, [0] * 60
for d in range(60):
for ai in A:
C0[d] += (ai >> d & 1) == 0
C1[d] += (ai >> d & 1) == 1
ans = 0
for (d, (a, b)) in enumerate(zip(C0, C1)):
ans = (ans + a * b * (1 << d % MOD)) % MOD
print(ans % MOD)
if __name__ == '__main__':
main() | 0 | null | 85,382,946,710,270 | 193 | 263 |
import numpy as np
from numba import njit
@njit
def solve(stdin):
n, k = stdin[:2]
A = stdin[2: 2 + n]
A = np.sort(A)[::-1]
F = np.sort(stdin[2 + n:])
def is_ok(x):
tmp = 0
for a, f in zip(A, F):
y = a * f
if y > x:
tmp += a - x // f
return tmp <= k
ok = 10 ** 16
ng = -1
while ok - ng > 1:
mid = (ok + ng) // 2
if is_ok(mid):
ok = mid
else:
ng = mid
return ok
print(solve(np.fromstring(open(0).read(), dtype=np.int64, sep=' '))) | import sys
import numba as nb
import numpy as np
input = sys.stdin.readline
@nb.njit("i8(i8,i8[:],i8[:])", cache=True)
def binary_search(K, A, F):
"""Meguru type binary search"""
ng = -1
ok = A[-1] * F[0]
def is_ok(A, F, K, x):
count = 0
for a, f in zip(A, F):
count += max(0, a - x // f)
return count <= K
while (ok - ng) > 1:
mid = (ok + ng) // 2
if is_ok(A, F, K, mid):
ok = mid
else:
ng = mid
return ok
def main():
N, K = map(int, input().split())
A = np.array(input().split(), dtype=np.int64)
F = np.array(input().split(), dtype=np.int64)
A.sort()
F[::-1].sort()
ans = binary_search(K, A, F)
print(ans)
if __name__ == "__main__":
main()
| 1 | 164,574,675,648,168 | null | 290 | 290 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
6
5
3
1
3
4
3
output:
3
"""
import sys
def solve():
# write your code here
max_profit = -1 * float('inf')
min_stock = prices[0]
for price in prices[1:]:
max_profit = max(max_profit, price - min_stock)
min_stock = min(min_stock, price)
return max_profit
if __name__ == '__main__':
_input = sys.stdin.readlines()
p_num = int(_input[0])
prices = list(map(int, _input[1:]))
print(solve()) | n = int(input())
a = list(map(int,input().split()))
c = [0,0,0]
count = 1
for i in range(n):
match = (a[i]==c[0])+(a[i]==c[1])+(a[i]==c[2])
if match==0:
count = 0
break
elif match==1 or a[i]==0:
c[c.index(a[i])] += 1
else:
c[c.index(a[i])] += 1
count = (count*match)%(1e+9+7)
if count != 0:
c = sorted(c,reverse=True)
while 0 in c:
c.pop()
memory = set()
kinds = 0
for x in c:
if not x in memory:
kinds += 1
for i in range(3,3-kinds,-1):
count = (count*i)%(1e+9+7)
print(int(count)) | 0 | null | 65,233,362,118,968 | 13 | 268 |
K,N = map(int,input().split())
A1 = list(map(int,input().split()))
D = [0] * (N)
A2 = [A1[i]+K for i in range(len(A1)-1)]
A1 = A1+A2
for i in range(N):
D[i] = A1[i+N-1] - A1[i]
#print(A1[i],A1[i+N-1])
print(min(D)) | K, N= map(int, input().split())
A = list(map(int, input().split()))
max=K-(A[N-1]-A[0])
for i in range(N-1):
a=A[i+1]-A[i]
if max<a:
max=a
print(K-max) | 1 | 43,251,057,996,058 | null | 186 | 186 |
W = input().rstrip()
lst = []
while True:
line = input().rstrip()
if line == "END_OF_TEXT":
break
lst += line.lower().split()
print(lst.count(W))
| a,b=open(0);c=1;
for i in sorted(b.split()):
c*=int(i)
if c>10**18:c=-1;break
print(c) | 0 | null | 8,944,345,627,230 | 65 | 134 |
x = input().split()
print(x[1]+x[0]) | n,m,q = map(int,input().split())
A = [0]*q
B = [0]*q
C = [0]*q
D = [0]*q
for i in range(q):
a,b,c,d = map(int,input().split())
A[i] = a
B[i] = b
C[i] = c
D[i] = d
walist = []
for i in range(2**(n+m-1)):
if bin(i).count("1") == n:
wa = 0
seq = []
value = 1
for j in range(n+m-1):
if (i>>j)&1 == 1:
seq += [value]
else:
value += 1
for k in range(q):
if seq[B[k]-1] - seq[A[k]-1] == C[k]:
wa += D[k]
walist += [wa]
print(max(walist))
| 0 | null | 65,467,501,508,292 | 248 | 160 |
while True:
H, W = [int(i) for i in input().split()]
if H == 0 and W == 0:
break
for i in range(H):
for j in range(W):
if (i + j) % 2 == 0:
print('#', end='')
else:
print('.', end='')
print('')
print('') | def draw(h,w):
t = "#." * (w/2)
if w%2 == 0:
s = t
k = t.strip("#") + "#"
else:
s = t + "#"
k = "." + t
for i in range(0,h/2):
print s
print k
if h%2==1:
print s
print
if __name__ == "__main__":
while True:
h,w = map(int, raw_input().split())
if h==0 and w==0:
break
else:
draw(h,w) | 1 | 866,779,149,480 | null | 51 | 51 |
n = input()
A = list(map(int, input().split()))
ans = 1
for a in A:
ans *= a
ans = min(ans, 10**18+1)
if ans == 10**18+1:
ans = -1
print(ans) | n = int(input())
a = list(map(int,input().split()))
dota = 1
if 0 in set(a):
dota = 0
else:
for ai in a:
dota *= ai
if dota > 10**18:
dota = -1
break
print(dota) | 1 | 16,155,697,836,320 | null | 134 | 134 |
N=int(input())
S=[input() for _ in range(N)]
a=0
w=0
t=0
r=0
for i in range(N):
if S[i] =="AC":
a+=1
elif S[i] =="WA":
w+=1
elif S[i] =="TLE":
t+=1
elif S[i] =="RE":
r+=1
print("AC x "+ str(a))
print("WA x "+ str(w))
print("TLE x "+ str(t))
print("RE x "+ str(r))
| N, K = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
mod = 10 ** 9 + 7
fac = [1, 1]
finv = [1, 1]
inv = [0, 1]
ans = 0
def comb(n, r):
if n >= r:
return fac[n] * ( finv[r] * finv[n-r] % mod ) % mod
else:
return 0
for i in range(2, N + 1):
fac.append( ( fac[-1] * i ) % mod )
inv.append( mod - ( inv[mod % i] * (mod // i) % mod ) )
finv.append( finv[-1] * inv[-1] % mod )
if K == 1:
print(0)
else:
for i, x in enumerate(A):
cnt = x * ( comb(i, K-1) - comb(N-1-i, K-1) ) % mod
ans += cnt
ans %= mod
print(ans) | 0 | null | 52,532,422,074,234 | 109 | 242 |
a = int(input())
b, c = map(str, input().split())
d = ""
for i in range(0, a):
e = b[i] + c[i]
d += e
print(d) | n = int(input())
s,t = input().split(" ")
res = ""
for i in range(n):
res = res + s[i] + t[i]
print(res) | 1 | 112,030,812,150,432 | null | 255 | 255 |
from collections import Counter
a = map(int, input().split())
c = Counter(a)
d = {1: 300000, 2: 200000, 3: 100000}
ret = sum(c[rank] * d[rank] for rank in range(1, 3 + 1))
if c[1] == 2:
ret += 400000
print(ret)
| x, y = map(int, input().split())
s = [400000, 300000, 200000, 100000]
if x == 1 and y == 1:
print(sum(s))
elif x <= 3 and y <= 3:
print(s[x] + s[y])
elif x <= 3:
print(s[x])
elif y <= 3:
print(s[y])
else:
print(0) | 1 | 140,670,633,405,924 | null | 275 | 275 |
n=int(input())
l=sorted(list(map(int, input().split())))
ans=0
for i in range(len(l)):
for j in range(i+1, len(l)):
for k in range(j+1, len(l)):
if l[i]==l[j] or l[j]==l[k] or l[k]==l[i]:
continue
if l[i]+l[j]>l[k]:
ans+=1
print(ans) | def inp():
return input()
def iinp():
return int(input())
def inps():
return input().split()
def miinps():
return map(int,input().split())
def linps():
return list(input().split())
def lmiinps():
return list(map(int,input().split()))
def lmiinpsf(n):
return [list(map(int,input().split()))for _ in range(n)]
n = iinp()
l = lmiinps()
ans = 0
if n < 3:
print(0)
exit()
for i in range(n):
for j in range(i+1,n):
for k in range(j+1,n):
if l[i] == l[j] or l[j] == l[k] or l[i] == l[k]:
continue
if l[i]+l[j] > l[k] and l[j]+l[k] > l[i] and l[k]+l[i] > l[j]:
ans += 1
print(ans) | 1 | 5,022,103,105,328 | null | 91 | 91 |
S, T = input().split(' ')
print(T + S)
| a = input()
if a in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
print("A")
else:
print("a") | 0 | null | 57,463,093,614,208 | 248 | 119 |
#coding: utf-8
a, v = map(int,input().split())
b, w = map(int,input().split())
t = int(input())
dist = abs(a-b)
dist += (t*w)
if dist <= v*t:
print('YES')
else:
print('NO') | A, V = map(int, input().split())
B, W = map(int, input().split())
T = int(input())
firstDis = abs(A - B)
steps = (V - W)*T
print("YES" if firstDis <= steps else "NO")
| 1 | 15,145,674,256,150 | null | 131 | 131 |
h,k = map(int,input().split())
arr=list(map(int,input().split()))
arr.sort()
print(sum(arr[0:h-k]) if h>=k else 0) | import sys
n,k=map(int,input().split())
h=list(map(int,input().split()))
if n<=k:
print(0)
sys.exit()
hi=sorted(h)
if k:
print(sum(hi[:-k]))
else:
print(sum(hi))
| 1 | 79,241,038,922,510 | null | 227 | 227 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# FileName: C_fix_2
# CreatedDate: 2020-08-08 01:59:29 +0900
# LastModified: 2020-08-08 02:11:36 +0900
#
import os
import sys
# import numpy as np
# import pandas as pd
def main():
n, m = map(int, input().split())
h = [0] + list(map(int, input().split()))
path = [[] for _ in range(n+1)]
for _ in range(m):
a, b = map(int, input().split())
path[a].append(h[b])
path[b].append(h[a])
ans = 0
for index in range(1, n+1):
if path[index] and h[index] > max(path[index]):
ans += 1
elif not path[index]:
ans += 1
print(ans)
if __name__ == "__main__":
main()
| n, m = map(int, input().split())
height = [int(i) for i in input().split()]
neighbors = {}
for _ in range(m):
a, b = map(int, input().split())
if a not in neighbors:
neighbors.update({a:set()})
if b not in neighbors[a]:
neighbors[a].add(b)
if b not in neighbors:
neighbors.update({b:set()})
if a not in neighbors[b]:
neighbors[b].add(a)
#print(neighbors)
#print(height)
count = 0
visited = set()
for std, s in neighbors.items():
flag = True
visited.add(std)
height_std = height[std - 1]
for each in s:
h = height[each - 1]
if height_std <= h:
flag = False
break
if flag:
count += 1
#print(visited)
for i in range(n):
if i + 1 not in visited:
count += 1
print(count) | 1 | 24,955,009,506,292 | null | 155 | 155 |
s=input()
q=int(input())
mae=""
usr=""
flg=True
for i in range(q):
a=list(map(str,input().split()))
if a[0]=="1":
if flg:
flg=False
elif flg==False:
flg=True
if a[0]=="2":
if a[1]=="1":
if flg:
mae=a[2]+mae
else:
usr=usr+a[2]
if a[1]=="2":
if flg:
usr=usr+a[2]
else:
mae=a[2]+mae
if flg:
ans=mae+s+usr
else:
ans=usr[::-1]+s[::-1]+mae[::-1]
print(ans) | S=input()
Q=int(input())
Q=[input().split() for i in range(Q)]
Forward=[]
Backward=[]
count=0
for i in Q:
if i[0]=='1':
count+=1
else:
if (int(i[1])+count)%2==1:
Forward.append(i[2])
else:
Backward.append(i[2])
if count%2==0:
ans = (''.join(Forward))[::-1]+S+(''.join(Backward))
else:
ans = (''.join(Backward)[::-1]+S[::-1]+(''.join(Forward)))
print(ans) | 1 | 57,277,897,753,660 | null | 204 | 204 |
N = int(input())
count = 0
for i in range(1,N):
if int(N/i)-N/i == 0:
count += int(N/i)-1
else:
count += int(N/i)
print(count) |
def resolve():
N = int(input())
ans = 0
for i in range(1, N):
ans += (N - 1) // i
print(ans)
if __name__ == "__main__":
resolve() | 1 | 2,576,542,565,610 | null | 73 | 73 |
n = int(input())
ans = []
while n > 0:
n -= 1
k = n % 26
n = n // 26
ans.append(chr(ord('a') + k))
for j in reversed(range(len(ans))):
print(ans[j], end = '') | import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
n, x, y = LI()
ans = [0 for _ in range(n)]
m = y-x-1
for i in range(1,n):
for j in range(i+1,n+1):
direct = j-i
short = abs(i-x) + 1 + abs(y-j)
cnt = min(direct,short)
ans[cnt] += 1
print(*ans[1:],sep="\n")
main()
| 0 | null | 27,859,170,570,820 | 121 | 187 |
from collections import Counter
n = int(input())
if n == 1:
print(0)
else:
lis = [i for i in range(n+1)]
for i in range(2, int(n**0.5) + 1):
if lis[i] == i:
lis[i] = i
for j in range(i**2, n+1, i):
if lis[j] == j:
lis[j] = i
#print(lis)
def bunkai(m):
ans = []
now = lis[m]
cnt = 1
for i in range(m):
m = m//lis[m]
if now == lis[m]:
cnt += 1
else:
ans.append(cnt)
cnt = 1
now = lis[m]
if m == 1:
break
return ans
ans = 1
for i in range(2,n):
tmp = 1
yaku = bunkai(i)
for i in yaku:
tmp *= (i +1)
ans += tmp
print(ans)
| import numpy as np
N,K = map(int,input().split())
import math
A = list(map(int,input().split()))
flag = 0
if 0 in A:
flag = 1
A.sort()
plus = list(filter(lambda x:x>0, A))[::-1]
plus = list(map(lambda x:np.longdouble(math.log(x,10000000)),plus))
from itertools import accumulate
acc_plu = [0] + list(accumulate(plus))
minu = filter(lambda x:x<0, A)
minu = list(map(lambda x:np.longdouble(math.log(-x,10000000)),minu))
acc_min = [0] + list(accumulate(minu))
if K % 2 == 0 : num = K // 2 + 1
else: num = (K + 1) // 2
cand = []
x = K
y = 0
MOD = 10**9 +7
for i in range(num):
try:
cand.append((acc_plu[x] + acc_min[y],x ,y ))
except: pass
x -= 2
y += 2
ans = 1
if cand == []:
if flag:
print(0)
exit()
cnt = 0
#マイナス確定
abss = sorted(list(map(lambda x :abs(x),A)))
for x in abss:
if cnt == K:break
ans *= x
ans %= MOD
cnt += 1
ans *= -1
ans %= MOD
print(ans)
else:
cand = sorted(cand)[::-1]
plus = list(filter(lambda x:x>0, A))[::-1]
minu = list(filter(lambda x:x<0, A))
c = cand[0]
ans = 1
for i in range(c[1]):
ans *= plus[i]
ans %= MOD
for i in range(c[2]):
ans *= minu[i]
ans %= MOD
print(ans)
| 0 | null | 5,972,922,136,740 | 73 | 112 |
while 1:
data = input()
if "?" in data:
break
print(eval(data.replace("/","//"))) | import sys
def input(): return sys.stdin.readline().rstrip()
def main():
n,a,b=map(int,input().split())
if (b-a)%2==0:print((b-a)//2)
else:print(min((b+a-1)//2,(2*n-b+1-a)//2))
if __name__=='__main__':
main() | 0 | null | 54,938,923,735,648 | 47 | 253 |
# -*- coding: utf-8 -*-
import sys
import os
N = int(input())
score0 = 0
score1 = 0
for i in range(N):
word0, word1 = input().split()
if word0 < word1:
score1 += 3
elif word0 > word1:
score0 += 3
else:
score0 += 1
score1 += 1
print(score0, score1) | def main():
TaroScore = HanaScore = 0
n = int(input())
for _ in range(n):
[Taro, Hana] = list(input().lower().split())
lenT = len(Taro)
lenH = len(Hana)
lenMin = min(lenT, lenH)
if Taro == Hana:
TaroScore += 1
HanaScore += 1
else:
for i in range(lenMin+1):
if Taro == '':
HanaScore += 3
break
elif Hana == '':
TaroScore += 3
break
elif ord(Taro[0]) > ord(Hana[0]):
TaroScore += 3
break
elif ord(Taro[0]) < ord(Hana[0]):
HanaScore += 3
break
else:
Taro = Taro[1:]
Hana = Hana[1:]
print(TaroScore, HanaScore)
if __name__ == '__main__':
main()
| 1 | 2,012,973,247,476 | null | 67 | 67 |
from sys import stdin
n = int(input())
S = stdin.readline().split()
q = int(input())
T = stdin.readline().split()
cnt = 0
for x in T:
if x in S:
cnt += 1
print(cnt)
| import sys
n = int(input())
dic = set()
input_ = [x.split() for x in sys.stdin.readlines()]
for c, s in input_:
if c == 'insert':
dic.add(s)
else:
if s in dic:
print('yes')
else:
print('no') | 0 | null | 73,077,211,772 | 22 | 23 |
n,d,a = map(int,input().split())
xh = [list(map(int,input().split())) for _ in range(n)]
xh.sort()
j = 0
cnt = [0] * n
taken = 0
def problem(h):
if h <= 0:return 0
ans = h//a
if h%a :
ans += 1
return ans
for i in range(n):
[x,h] = xh[i]
while xh[j][0] + 2*d < x:
taken -= cnt[j]
j += 1
# if taken * a >= h:
# break
# if not h % a:
# cnt[i] = h//a - taken
# else:
# cnt[i] = h//a - taken + 1
cnt[i] = problem(h - taken * a)
taken += cnt[i]
print(sum(cnt))
| #!/usr/bin/env python3
from math import ceil
import heapq
def main():
n, d, a = map(int, input().split())
q = []
for i in range(n):
x, h = map(int, input().split())
heapq.heappush(q, (x, -(h // a + (1 if (h % a) else 0))))
bomb = 0
res = 0
while q:
x, h = heapq.heappop(q)
if h < 0:
h *= -1
if h > bomb:
heapq.heappush(q, (x + 2 * d, h - bomb))
res += h - bomb
bomb = h
else:
bomb -= h
print(res)
if __name__ == "__main__":
main()
| 1 | 82,227,810,272,000 | null | 230 | 230 |
N = int(input())
R = [int(input()) for _ in range(N)]
p_buy = R[0]
p_sale = R[1]
buy = R[1]
sale = None
for i in range(2, N):
if p_sale < R[i]:
p_sale = R[i]
if buy > R[i]:
if sale is None:
sale = R[i]
if p_sale - p_buy < sale - buy:
p_sale, p_buy = sale, buy
sale, buy = None, R[i]
else:
if sale is None or sale < R[i]:
sale = R[i]
p_gain = p_sale - p_buy
print(p_gain if sale is None else max(p_gain, sale - buy)) | n, k = map(int, input().split())
h = list(sorted(map(int, input().split())))
x = 0
if n > k:
for i in range(n - k):
x += h[i]
print(x) | 0 | null | 39,672,284,174,198 | 13 | 227 |
import sys
N = int(sys.stdin.readline().strip())
X = sys.stdin.readline().strip()
def popcount(n):
cnt = 0
while n > 0:
cnt += n & 1
n //= 2
return cnt
def f(n):
cnt = 0
while n != 0:
n = n % popcount(n)
cnt += 1
return cnt
#nX = int(X, 2)
pcnt = X.count('1')
MOD1 = pcnt + 1
MOD2 = pcnt - 1
nXp = 0
nXm = 0
pow1 = [1] * N
pow2 = [0] * N
for i in range(1, N):
pow1[i] = (pow1[i-1] * 2) % MOD1
if MOD2 != 0:
pow2[0] = 1
for i in range(1, N):
pow2[i] = (pow2[i-1] * 2) % MOD2
for i in range(N):
if X[i] == '1':
nXp += pow1[N-1-i]
nXp %= MOD1
if MOD2 != 0:
for i in range(N):
if X[i] == '1':
nXm += pow2[N-1-i]
nXm %= MOD2
for i in range(0, N):
if X[i] == '0':
k = (nXp + pow1[N-1-i]) % MOD1
print(f(k) + 1)
else:
if MOD2 == 0:
print(0)
else:
k = (nXm - pow2[N-1-i]) % MOD2
print(f(k) + 1) | N = int(input())
X = input()
memo = {}
X_int = int(X, 2)
def popcount(n: int):
x = bin(n)[2:]
return x.count("1")
pcf = popcount(int(X, 2))
pcm = pcf - 1
pcp = pcf + 1
xm = X_int % pcm if pcm != 0 else 0
xp = X_int % pcp
def f(n: int, ops: int):
while n != 0:
n %= popcount(n)
ops += 1
return ops
def rev(x: str, i: int):
if x == "1":
if pcm == 0:
return -1
n = (xm - (pow(2, N-i-1, pcm))) % pcm
else:
n = (xp + (pow(2, N-i-1, pcp))) % pcp
return n
if __name__ == "__main__":
for i, x in enumerate(X):
n = rev(x, i)
if n == -1:
print(0)
else:
print(f(n, 1))
| 1 | 8,218,182,166,842 | null | 107 | 107 |
import os, sys, re, math
N = int(input())
P = [int(n) for n in input().split()]
answer = 0
m = 2 * 10 ** 5
for p in P:
if p <= m:
answer += 1
m = p
print(answer)
| n = int(input())
p = list(map(int, input().split()))
ret = 1
minp = p[0]
for i in range(1, n):
if p[i] <= minp:
ret += 1
minp = min(minp, p[i])
print(ret)
| 1 | 85,478,490,386,782 | null | 233 | 233 |
def modinv(a, m):
b = m
u = 1
v = 0
while b:
t = a // b
a -= t * b
a, b = b, a
u -= t * v
u, v = v, u
u %= m
if u < 0:
u += m
return u
def nCk(N, k, mod):
ret_val = 1
for i in range(k):
ret_val *= (N - i)
ret_val %= mod
ret_val *= modinv(i + 1, mod)
ret_val %= mod
return ret_val
n, a, b = map(int, input().split())
MOD = 10 ** 9 + 7
all_cnt = pow(2, n, MOD) - 1
a_cnt = nCk(n, a, MOD)
b_cnt = nCk(n, b, MOD)
ans = all_cnt - a_cnt - b_cnt
while ans < 0:
ans += MOD
print(ans)
| import math
n, a, b = map(int, input().split())
mod = 10**9 + 7
s = pow(2, n, mod) - 1
def cal(n, r):
p = 1
q = 1
for i in range(r):
p = p*(n-i)%mod
q = q*(i+1)%mod
return p*pow(q, mod-2, mod)%mod
print((s - cal(n, a) - cal(n, b))%mod) | 1 | 66,477,505,713,390 | null | 214 | 214 |
x, y = map(int,input().split())
print((max(4-x, 0) + max(4-y, 0) + 4*max(3-x-y, 0)) * 100000) | N,M = map(int,input().split())
print((str(N)*M,str(M)*N)[N > M]) | 0 | null | 112,549,871,222,270 | 275 | 232 |
r, c, k = map(int, input().split())
rcv = [list(map(int, input().split())) for i in range(k)]
area = [[0] * (c+1) for i in range(r+1)]
for a, b, v in rcv:
area[a-1][b-1] = v
# dp[i][j][k]: その行でiまで拾っており、
# j行k列目に到達時点の最大スコア
dp = [[[-1] * (c+1) for i in range(r+1)] for j in range(4)]
dp[0][0][0] = 0
for rr in range(r+1):
for cc in range(c+1):
for i in range(4):
# 取って右
if i+1<4 and cc<c and area[rr][cc]>0:
dp[i+1][rr][cc+1] = max(dp[i+1][rr][cc+1],
dp[i][rr][cc]+area[rr][cc])
# 取って下
if i+1<4 and rr<r and area[rr][cc]>0:
dp[0][rr+1][cc] = max(dp[0][rr+1][cc],
dp[i][rr][cc]+area[rr][cc])
# 取らずに右
if cc<c:
dp[i][rr][cc+1] = max(dp[i][rr][cc+1],
dp[i][rr][cc])
# 取らずに下
if rr<r:
dp[0][rr+1][cc] = max(dp[0][rr+1][cc],
dp[i][rr][cc])
# ans: r行c列目の最大値(iは問わず)
ans = max([dp[i][r][c] for i in range(4)])
print(ans)
| R,C,K= map(int,input().split(" "))
original=[[0]*(C+1) for i in range(R+1)]
for _ in range(K):
r,c,v= map(int,input().split(" "))
original[r][c]=v
d1=[[0]*(C+1) for i in range(R+1)]
d2=[[0]*(C+1) for i in range(R+1)]
d3=[[0]*(C+1) for i in range(R+1)]
for i in range(1,R+1):
for j in range(1,C+1):
curr= original[i][j]
d1[i][j]=max(d1[i-1][j]+curr,d2[i-1][j]+curr,d3[i-1][j]+curr,d1[i][j-1],curr)
d2[i][j]=max(d2[i][j-1],d1[i][j-1]+curr)
d3[i][j]=max(d3[i][j-1],d2[i][j-1]+curr)
print(max(d1[-1][-1],d2[-1][-1],d3[-1][-1])) | 1 | 5,618,383,238,560 | null | 94 | 94 |
def main():
from sys import stdin
input=stdin.readline
import numpy as np
import scipy.sparse.csgraph as sp
n, m, l = map(int, input().split())
abc = [list(map(int, input().split())) for _ in [0]*m]
q = int(input())
st = [list(map(int, input().split())) for _ in [0]*q]
inf = 10**12
dist = np.full((n, n), inf, dtype=np.int64)
for i in range(n):
dist[i][i] = 0
for a, b, c in abc:
dist[a-1][b-1] = c
dist[b-1][a-1] = c
dist = sp.shortest_path(dist)
inf = 10**3
dist2 = np.full((n, n), inf, dtype=np.int16)
for i in range(n):
for j in range(n):
if dist[i][j] <= l:
dist2[i][j] = 1
dist2 = sp.shortest_path(dist2)
for i in range(n):
for j in range(n):
if dist2[i][j] == inf:
dist2[i][j] = -1
else:
dist2[i][j] -= 1
for s, t in st:
print(int(dist2[s-1][t-1]))
main()
| import numpy as np
from scipy.sparse.csgraph import floyd_warshall
from scipy.sparse import csr_matrix
INF = 10**12
N, M, L = map(int, input().split())
A = []; B = []; C = []
for i in range(M):
a, b, c = map(int, input().split())
A.append(a - 1); B.append(b - 1); C.append(c)
A = np.array(A); B = np.array(B); C = np.array(C)
graph = csr_matrix((C, (A, B)), (N, N))
d = floyd_warshall(graph, directed=False)
d[d <= L] = 1
d[d > L] = INF
d = floyd_warshall(d, directed=False)
Q = int(input())
for i in range(Q):
s, t = map(int, input().split())
if d[s - 1][t - 1] != INF:
print(int(d[s - 1][t - 1]) - 1)
else:
print(- 1) | 1 | 173,924,164,951,680 | null | 295 | 295 |
import math
(a,b,C) = [int(i) for i in input().split()]
c = math.sqrt(a ** 2 + b ** 2 - (2 * a * b) * math.cos(C * math.pi / 180))
h = float(b * math.sin(C * math.pi / 180))
s = float(a * h / 2)
l = float(a + b + c)
print(s)
print(l)
print(h) | import math
a,b,C=map(float,input().split())
S = a*b*math.sin(C*math.pi/180)/2
c = math.sqrt(a**2 + b**2 - 2*a*b*math.cos(C*math.pi/180))
h = 2*S/a
print("{:10f}".format(S))
print("{:10f}".format(a+b+c))
print("{:10f}".format(h))
| 1 | 174,904,187,898 | null | 30 | 30 |
a, b, c = map(int, input().split())
k = int(input())
while a >= b and k > 0:
b = b*2
k = k-1
while b >= c and k > 0:
c = c*2
k = k-1
if a < b < c:
print('Yes')
else:
print('No') | from time import *
from random import *
t=time()
T0,T1=2000,600
Tt=2000
D=int(input())
C=list(map(int,input().split()))
S=[list(map(int,input().split())) for i in range(D)]
X=[0]*26
XX=[0]*26
P=[]
for i in range(D):
for j in range(26):
X[j]+=C[j]
XX[j]+=X[j]
P.append([])
for j in range(26):
P[i].append(j)
P[i].sort(reverse=True,key=lambda x:X[x]+S[i][x])
XX[P[i][0]]-=X[P[i][0]]
X[P[i][0]]=0
SC,SC2=0,0
for i in range(D):
SC+=S[i][P[i][0]]
YY=[]
Y=[]
A,B=0,0
e=0
E=1
for i in range(50):
e+=E
E*=1/(i+1)
def f(x):
global e,Tt
if x>=0:
return True
else:
return randrange(0,10000000)<=pow(e,x/Tt)
for l in range(8):
for k in range(25):
for i in range(D):
SC2=SC
YY=XX[:]
Y=X[:]
SC2-=S[i][P[i][0]]
SC2+=S[i][P[i][k+1]]
for j in range(26):
Y[j]=0
YY[P[i][0]],YY[P[i][k+1]]=0,0
for j in range(D):
if j==i:
Z=P[j][k+1]
else:
Z=P[j][0]
Y[P[i][0]]+=C[P[i][0]]
Y[P[i][k+1]]+=C[P[i][k+1]]
Y[Z]=0
YY[P[i][0]]+=Y[P[i][0]]
YY[P[i][k+1]]+=Y[P[i][k+1]]
if f((SC2-sum(YY))-(SC-sum(XX))):
P[i].insert(0,P[i][k+1])
del P[i][k+2]
XX=YY[:]
SC=SC2
for i in range(1,D-1):
SC2=SC
YY=XX[:]
Y=X[:]
A=i
B=randrange(A+1,D)
SC2-=S[A][P[A][0]]+S[B][P[B][0]]
SC2+=S[A][P[B][0]]+S[B][P[A][0]]
for j in range(26):
Y[j]=0
YY[P[A][0]],YY[P[B][0]]=0,0
for j in range(D):
if j==A:
Z=P[B][0]
elif j==B:
Z=P[A][0]
else:
Z=P[j][0]
Y[P[A][0]]+=C[P[A][0]]
Y[P[B][0]]+=C[P[B][0]]
Y[Z]=0
YY[P[A][0]]+=Y[P[A][0]]
YY[P[B][0]]+=Y[P[B][0]]
if f((SC2-sum(YY))-(SC-sum(XX))):
P[A],P[B]=P[B][:],P[A][:]
XX=YY[:]
SC=SC2
if k&1:
continue
B=randrange(0,A)
SC2-=S[A][P[A][0]]+S[B][P[B][0]]
SC2+=S[A][P[B][0]]+S[B][P[A][0]]
for j in range(26):
Y[j]=0
YY[P[A][0]],YY[P[B][0]]=0,0
for j in range(D):
if j==A:
Z=P[B][0]
elif j==B:
Z=P[A][0]
else:
Z=P[j][0]
Y[P[A][0]]+=C[P[A][0]]
Y[P[B][0]]+=C[P[B][0]]
Y[Z]=0
YY[P[A][0]]+=Y[P[A][0]]
YY[P[B][0]]+=Y[P[B][0]]
if f((SC2-sum(YY))-(SC-sum(XX))):
P[A],P[B]=P[B][:],P[A][:]
XX=YY[:]
SC=SC2
Tt=pow(T0,1-(time()-t))*pow(T1,time()-t)
'''
X=[0]*26
SC=0
for i in range(D):
for j in range(26):
X[j]+=C[j]
X[P[i][0]]=0
SC-=sum(X)
SC+=S[i][P[i][0]]
print(SC)
'''
for i in range(D):
print(P[i][0]+1) | 0 | null | 8,321,049,145,918 | 101 | 113 |
N=int(input())
max_x=int(N**0.5)
ans_list=[0]*N
for x in range(1,max_x):
for y in range(1,max_x):
for z in range(1,max_x):
s=x**2+y**2+z**2+x*y+y*z+z*x
if s<=N:
ans_list[s-1]+=1
for i in range(N):
print(ans_list[i]) | from math import ceil
print(ceil(int(input())/2)) | 0 | null | 33,370,581,978,882 | 106 | 206 |
def main():
N, X, Y = (int(i) for i in input().split())
cnt = [0]*N
for i in range(1, N+1):
for j in range(i+1, N+1):
d = min(abs(i-j), abs(i-X)+1+abs(j-Y), abs(i-X)+abs(X-Y)+abs(j-Y))
cnt[d] += 1
for d in cnt[1:]:
print(d)
if __name__ == '__main__':
main()
| def main():
a, b, c = map(int, input().split())
if a == b == c:
print('No')
elif a != b and b != c and c != a:
print('No')
else:
print('Yes')
if __name__ == '__main__':
main() | 0 | null | 56,295,643,767,200 | 187 | 216 |
# 1???????????? W ??¨?????? T ,T ??????????????? W ?????°???????????????????????°??????
import sys
# ??????W?????????
w = input()
# ??????T?????????
t = []
# ??????T?????????
while 1:
temp = input()
if temp == "END_OF_TEXT":
break
t += temp.strip(".")
t += " "
# ??????????????????
t = "".join(t).split()
# print(t)
# ??????T???????????¨????????????W????????????????????????
count = 0
for i in range(len(t)):
if t[i].lower() == w:
count += 1
print(count) | import numpy as np
from fractions import gcd
N=int(input())
A=list(map(int, input().split()))
p=10**9+7
n = 10 ** 6 # N は必要分だけ用意する
#fact = [1, 1] # fact[n] = (n! mod p)
#factinv = [1, 1] # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1] # factinv 計算用 逆元
"""
for i in range(2, n + 1):
#fact.append((fact[-1] * i) % p)
inv.append((-inv[p % i] * (p // i)) % p)
#factinv.append((factinv[-1] * inv[-1]) % p)
#a//gcd(a,b)*b
"""
def lcm(a,b):
g=gcd(a,b)
#return ((a*b)*pow(g,p-2,p))%p
return a//gcd(a,b)*b
LCM=1
for x in A:
LCM=lcm(LCM,x)
#print(LCM)
ans=0
LCM%=p
for i in range(N):
#ans+=(LCM*inv[A[i]])%p
ans+=(LCM*pow(A[i],p-2,p))%p
ans%=p
print(ans) | 0 | null | 44,499,177,796,932 | 65 | 235 |
list_data = input().split(" ")
if int(list_data[0]) > int(list_data[1]) * int(list_data[2]):
print("No")
else:
print("Yes") | ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(map(int, input().split()))
d, t, s = mi()
print("Yes" if d <= t*s else "No") | 1 | 3,526,908,559,970 | null | 81 | 81 |
N,M=list(map(int, input().split()))
A=list(map(int, input().split()))
s=sum(A)
if s>N:
print(-1)
else:
print(N-s) | n = [int(i) for i in input().split()]
N = n[0]
M = n[1]
A = [int(i) for i in input().split()]
A_sum = sum(A)
if A_sum > N:
print(-1)
else:
print(N - A_sum) | 1 | 31,996,832,506,520 | null | 168 | 168 |
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]) | import numpy as np
N = int(input())
X = str(input())
num_one = X.count("1")
dp = [-1] * N
dp[0] = 0
def dfs(n):
if dp[n] == -1:
dp[n] = 1 + dfs(n % bin(n).count('1'))
return dp[n]
num_one = X.count("1")
bool_arr = np.array([True if X[N-i-1] == "1" else False for i in range(N)])
zero_ver = np.array([pow(2, i, num_one + 1) for i in range(N)])
zero_ver_sum = sum(zero_ver[bool_arr])
one_ver = -1
one_ver_sum = 0
flag = False
if num_one != 1:
one_ver = np.array([pow(2, i, num_one - 1) for i in range(N)])
one_ver_sum = sum(one_ver[bool_arr])
else:
flag = True
for i in range(1,N+1):
start = 0
if bool_arr[N-i] == False:
start = (zero_ver_sum + pow(2, N - i, num_one + 1)) % (num_one + 1)
print(dfs(start)+1)
else:
if flag:
print(0)
else:
start = (one_ver_sum - pow(2, N - i, num_one - 1)) % (num_one - 1)
print(dfs(start)+1)
| 0 | null | 21,174,570,776,840 | 172 | 107 |
from sys import stdin
from collections import deque
# 入力
n = int(input())
# command = [stdin.readline()[:-1] for a in range(n)]
command = stdin
# process
output = deque([])
for a in command:
if a[0] == 'i':
output.appendleft(int(a[7:]))
elif a[0:7] == 'delete ':
try:
output.remove(int(a[7:]))
except ValueError:
pass
elif a[6] == 'F':
output.popleft()
else:
output.pop()
# 出力
print(*list(output))
| from collections import deque
import sys
n = int(sys.stdin.readline())
q = deque()
for i in range(n):
command = sys.stdin.readline()[:-1]
if command[0] == 'i':
q.appendleft(command[7:])
elif command[6] == ' ':
try:
q.remove(command[7:])
except Exception as e:
pass
elif command[6] == 'F':
q.popleft()
else:
q.pop()
print(' '.join(q)) | 1 | 51,394,452,648 | null | 20 | 20 |
import math
r=float(input())
print(2*r*math.pi) | # -*- coding: utf-8 -*-
# input
a, b = map(int, input().split())
x = list(map(int, input().split()))
x.sort()
o = 0
for i in range(b):
o = o+x[i]
print(o)
| 0 | null | 21,564,540,132,654 | 167 | 120 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.