code1
stringlengths 16
24.5k
| code2
stringlengths 16
24.5k
| similar
int64 0
1
| pair_id
int64 2
181,637B
⌀ | question_pair_id
float64 3.71M
180,628B
⌀ | code1_group
int64 1
299
| code2_group
int64 1
299
|
---|---|---|---|---|---|---|
n = int(input())
s, t = [], []
for i in range(n):
ss = input().split()
s.append(ss[0])
t.append(int(ss[1]))
x = input()
start = n
for i in range(n):
if s[i] == x:
start = i + 1
res = 0
for i in range(start, n):
res += t[i]
print(res)
|
import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(input())
A = list(map(int, input().split()))
A_and_i = [[a, i] for i, a in enumerate(A)]
A_and_i.sort(reverse=True)
DP = [[0] * (N + 1) for _ in range(N + 1)]
for i in range(N):
a, idx = A_and_i[i]
for j in range(N):
# 右に持っていく
if j <= i:
DP[i + 1][j] = max(DP[i + 1][j], DP[i][j] +
a * abs(N - 1 - (i - j) - idx))
DP[i + 1][j + 1] = max(DP[i + 1][j + 1], DP[i]
[j] + a * abs(idx - j))
ans = max(DP[N])
print(ans)
| 0 | null | 65,494,318,903,440 | 243 | 171 |
str_search = input().upper()
int_cnt = 0
len_search = len(str_search)
while True:
str_line = input()
if str_line == "END_OF_TEXT":
break
str_line = str_line.upper()
int_cnt = int_cnt + str_line.split().count(str_search)
print(str(int_cnt))
|
h,w,k=map(int,input().split())
S=[input() for i in range(h)]
LIS=[]
def saiki(x,st):
if x==h-1:
LIS.append(st)
return
else:
saiki(x+1,st+st[-1])
saiki(x+1,st+str(int(st[-1])+1))
saiki(0,"0")
DIC1={c:0 for c in "0123456789"}
DIC2={c:0 for c in "0123456789"}
ans=10**9
for cod in LIS:
for ele in DIC1:
DIC1[ele]=0
cnt=int(cod[-1])
end=False
for i in range(w):
for ele in DIC2:
DIC2[ele]=0
for q in range(h):
if S[q][i]=="1":
DIC2[cod[q]]+=1
if max(DIC2.values())>k:
end=True
break
flg=True
for ele in DIC1:
if DIC1[ele]+DIC2[ele]>k:
flg=False
break
if flg:
for ele in DIC1:
DIC1[ele]+=DIC2[ele]
else:
for ele in DIC1:
DIC1[ele]=DIC2[ele]
cnt+=1
if end:
continue
ans=min(ans,cnt)
#print(cod,cnt)
print(ans)
| 0 | null | 25,223,568,881,738 | 65 | 193 |
X,Y=map(int, input().split())
v1 = [300000, 200000, 100000]
v2 = [300000, 200000, 100000]
x = 0
y = 0
if X <= 3:
x = int(v1[X-1])
if Y <= 3:
y = int(v2[Y-1])
if ((X==1) & (Y==1)):
print(int(x + y + 400000))
else:
print(int(x + y))
|
# -*- coding: utf-8 -*-
def selection_sort(n, a):
cnt = 0
for i in range(n):
minj = i
for j in range(i, n):
if a[j] < a[minj]:
minj = j
if i != minj:
tmp = a[minj]
a[minj] = a[i]
a[i] = tmp
cnt += 1
return a, cnt
if __name__ == '__main__':
n = int(input())
a = [int(n) for n in input().split()]
ans, cnt = selection_sort(n, a)
print(' '.join(map(str, ans)))
print(cnt)
| 0 | null | 70,123,689,911,648 | 275 | 15 |
s = input()
t = input()
ans = len(t)
for i in range(len(s) - len(t) + 1):
tmp = s[i:i+len(t)]
count = 0
for t1, t2 in zip(tmp, t):
if t1 != t2:
count += 1
ans = min(ans, count)
print(ans)
|
s=input()
t=input()
lt=len(t);ls=len(s)
ans=lt
for i in range(ls-lt+1):
cnt=0
for j in range(len(t)):
if s[i:i+lt][j]!=t[j]:
cnt+=1
ans=min(ans,cnt)
print(ans)
| 1 | 3,717,204,546,340 | null | 82 | 82 |
N = int(input())
S = int(N**(1/2))
for i in range(S,0,-1):
if N%i == 0:
A = N//i
B = i
break
print(A+B-2)
|
import math
N = int(input())
start_digit = math.ceil(math.sqrt(N))
for i in range(start_digit, 0, -1):
q, r = divmod(N, i)
if r == 0:
output = i+q-2
break
print(output)
| 1 | 161,568,397,615,586 | null | 288 | 288 |
n, m = map(int, input().split())
def check_ans(list_pairs):
dict_people = {i: i for i in range(1, n+1)}
for i in range(n):
for k in range(m):
val1 = dict_people[list_pairs[k][0]]
val2 = dict_people[list_pairs[k][1]]
if val1>val2:
print(val2, val1, end=" / ")
else:
print(val1, val2, end=" / ")
print("")
for j in range(1, n+1):
dict_people[j] = (dict_people[j]+1)%n
if dict_people[j] == 0: dict_people[j] = n
ans = list()
if n%2 == 1:
for i in range(m):
node1 = (1-i)%n
if node1 == 0: node1 = n
node2 = 2+i
ans.append((node1, node2))
else:
distance = -1
node2 = 1
for i in range(m):
node1 = (1-i)%n
if node1 == 0: node1 = n
node2 = node2+1
distance += 2
if distance == n//2 or distance == n//2 + 1:
node2 += 1
ans.append((node1, node2))
[print(str(values[0])+" "+str(values[1])) for values in ans]
# check_ans(ans)
|
l = []
a,b,c = map(int,input().split())
for i in range(a,b+1):
if c % i == 0:
l.append(i)
ll = len(l)
print(str(ll))
| 0 | null | 14,615,940,679,782 | 162 | 44 |
array_str = '1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51'
array = array_str.split(', ')
k = int(input())
print(array[k - 1])
|
#!python3
# import numpy as np
# input
K = int(input())
def main():
l = [1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51]
ans = l[K-1]
print(ans)
if __name__ == "__main__":
main()
| 1 | 49,917,061,544,896 | null | 195 | 195 |
from collections import deque
dq = deque()
for _ in [None]*int(input()):
s = input()
if s == "deleteFirst":
dq.popleft()
elif s == "deleteLast":
dq.pop()
else:
a, b = s.split()
if a == "insert":
dq.appendleft(b)
else:
if b in dq:
dq.remove(b)
print(" ".join(dq))
|
import sys
class Node():
def __init__(self, key=None, prev=None, next=None):
self.key = key
self.prev = prev
self.next = next
class DoublyLinkedList():
def __init__(self):
self.head = Node()
self.head.next = self.head
self.head.prev = self.head
def insert(self, x):
node = Node(key=x, prev=self.head, next=self.head.next)
self.head.next.prev = node
self.head.next = node
def search(self, x):
node = self.head.next
while node is not self.head and node.key != x:
node = node.next
return node
def delete_key(self, x):
node = self.search(x)
self._delete(node)
def _delete(self, node):
if node is self.head:
return None
node.prev.next = node.next
node.next.prev = node.prev
def deleteFirst(self):
self._delete(self.head.next)
def deleteLast(self):
self._delete(self.head.prev)
def getKeys(self):
node = self.head.next
keys = []
while node is not self.head:
keys.append(node.key)
node = node.next
return " ".join(keys)
L = DoublyLinkedList()
n = int(input())
for i in sys.stdin:
if 'insert' in i:
x = i[7:-1]
L.insert(x)
elif 'deleteFirst' in i:
L.deleteFirst()
elif 'deleteLast' in i:
L.deleteLast()
elif 'delete' in i:
x = i[7:-1]
L.delete_key(x)
else:
pass
print(L.getKeys())
| 1 | 49,435,113,728 | null | 20 | 20 |
w,h,x,y,r = map(int, raw_input().split())
if x >= r and x <= (w-r) and y >= r and y <= (h-r):
print 'Yes'
else:
print 'No'
|
W, H, x, y, r = map(int, input().split())
if x - r < 0 or x + r > W or y - r < 0 or y + r > H:
print('No')
else:
print('Yes')
| 1 | 450,466,709,472 | null | 41 | 41 |
a,b,c= list(map(int,input().split()))
n = int(input())
ans = "No"
for i in range(n):
if b <= a:
b = 2*b
elif c <= b:
c = 2*c
if a<b<c:
ans = "Yes"
print(ans)
|
def A():
n = int(input())
print(-(-n//2))
A()
| 0 | null | 33,195,890,659,052 | 101 | 206 |
N, M = map(int,input().split())
for i in range(1, M+1):
a = N+1 - i
if N % 2 == 0 and i > (N // 4):
a -= 1
print(i, a)
|
n, m = map(int, input().split())
s = input()
s = s[::-1]
loc = 0
anslist=[]
while True:
if loc >= n-m:
anslist.append(n-loc)
break
quit()
next = m
while s[loc+next]=="1":
next-=1
if next == 0:
print(-1)
quit()
anslist.append(next)
loc+=next
ans=anslist[::-1]
ans = list(map(str, ans))
print(" ".join(ans))
| 0 | null | 83,965,020,959,450 | 162 | 274 |
MOD = 10 ** 9 + 7
N = int(input())
A = list(map(int, input().split()))
S = sum(A) % MOD
ans = 0
for x in A:
S -= x
S %= MOD
ans += S * x
ans %= MOD
ans %= MOD
print(ans)
|
#169D
#Div Game
n=int(input())
def factorize(n):
fct=[]
b,e=2,0
while b**2<=n:
while n%b==0:
n/=b
e+=1
if e>0:
fct.append([b,e])
b+=1
e=0
if n>1:
fct.append([n,1])
return fct
l=factorize(n)
ans=0
for i in l:
c=1
while i[1]>=c:
ans+=1
i[1]-=c
c+=1
print(ans)
| 0 | null | 10,468,285,021,828 | 83 | 136 |
k=int(input())
a="1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51"
list=a.split(',')
print(list[k-1])
|
n = int(input())
a, b = map(int, input().split())
ans = 0
for i in range(a, b + 1):
if i % n == 0:
ans += 1
break
print("OK" if ans == 1 else "NG")
| 0 | null | 38,229,013,123,542 | 195 | 158 |
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
k = int(input())
keta = 1
mod = 7%k
while keta < 10**7:
if mod==0:
print(keta)
break
keta += 1
mod = (mod*10 + 7)%k
else:
print(-1)
if __name__=='__main__':
main()
|
N,X,M=map(int,input().split())
a=[0]*(M)
A=X%M
a[A]=1
ans=A
Ans=[A]
flag=0
for i in range(N-1):
A=A*A%M
if A==0:
break
if a[A]==1:
flag=1
break
a[A]=1
ans+=A
Ans.append(A)
if flag==1:
for num in range(len(Ans)):
if A==Ans[num]:
break
n=len(Ans)-num
b=sum(Ans[:num])
x=(N-num)//n
y=(N-num)%n
Sum=b+(ans-b)*(x)+sum(Ans[num:y+num])
else:
Sum=sum(Ans)
print(Sum)
| 0 | null | 4,466,409,703,078 | 97 | 75 |
import math
h = int(input())
n = int(math.log2(h))
a = 2
r = 2
S = (a*(r**n)-a) // (r-1)
print(S + 1)
|
from collections import Counter
n = int(input())
A = list(map(int, input().split()))
P = [i+a+1 for i,a in enumerate(A)]
Q = [j-a+1 for j,a in enumerate(A)]
cQ = Counter(Q)
ans = 0
for p in P:
ans += cQ[p]
print(ans)
| 0 | null | 53,062,758,622,942 | 228 | 157 |
import math
from collections import deque
def main():
t = [int(t)for t in input().split()]
x,y = t[0],t[1]
earned = 0
if x == 1:
earned += 300000
elif x == 2:
earned += 200000
elif x == 3:
earned += 100000
if y == 1:
earned += 300000
elif y == 2:
earned += 200000
elif y == 3:
earned += 100000
if x == y and x == 1:
earned += 400000
print(earned)
if __name__ == "__main__":
main()
|
x, y = map(int, input().split())
ans = 0
if x + y == 2:
ans += 400000
ans += ((4-min(4, x)) + (4-min(4, y))) * 100000
print(ans)
| 1 | 140,608,827,342,780 | null | 275 | 275 |
a = input();
print(int(a.split()[0])*int(a.split()[1]),int(a.split()[0]) * 2 + int(a.split()[1])*2, end="\n")
|
S=list(input())
T=list(input())
total = 0
for i in range(len(S)):
if S[i] == T[i]:
continue
else:
total += 1
print(str(total))
| 0 | null | 5,419,955,395,792 | 36 | 116 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
height, width = map(int, raw_input().split())
print("%d %d") % (height * width, (height + width) * 2)
|
MOD = 998244353
n = int(input())
d = list(map(int, input().split()))
dist_map = [0]*n
for dist in d:
dist_map[dist] += 1
ans = 1
if d[0] != 0 or dist_map[0] > 1:
print(0)
exit()
for i in range(1, n):
ans *= pow(dist_map[i-1], dist_map[i], MOD)
ans %= MOD
print(ans)
| 0 | null | 77,870,060,111,602 | 36 | 284 |
k = int(input())
a, b = list(map(int, input().split()))
c = a / k
if c == int(c):
print("OK")
else:
d = int(c) + 1
if (d*k) <=b:
print("OK")
else:
print("NG")
|
K = int(input())
A, B = map(int, input().split())
if A % K == 0 or B % K ==0:
print('OK')
elif int(B/K) - int(A/K) >= 1:
print('OK')
else:
print('NG')
| 1 | 26,508,013,375,860 | null | 158 | 158 |
import sys
import os
def file_input():
f = open('ABC167/input.txt', 'r')
sys.stdin = f
fact = [1, 1]
factinv = [1, 1]
inv = [0, 1]
def init_cmb(N,p):
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)
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
def main():
#file_input()
N,M,K=map(int, input().split())
mod=998244353
ans=0
init_cmb(N,mod)
for k in range(K+1):
ans+=M*cmb(N-1,k,mod)*pow(M-1,N-1-k,mod)
print(ans%mod)
if __name__ == '__main__':
main()
|
fact = [1 for _ in range(200000)]
inv = [1 for _ in range(200000)]
fact_inv = [1 for _ in range(200000)]
mod = 998244353
for i in range(2, 200000):
fact[i] = (fact[i-1]*i) % mod
inv[i] = mod - (inv[mod % i] * (mod // i)) % mod
fact_inv[i] = (fact_inv[i-1] * inv[i]) % mod
N, M, K = map(int, input().split())
ans = 0
a = pow(M-1, N-1-K, mod)
for i in range(K, -1, -1):
ans += (fact[N-1] * fact_inv[i] * fact_inv[N-1-i]) * M * a
ans = ans % mod
a *= M-1
a = a % mod
print(ans)
| 1 | 23,134,333,945,560 | null | 151 | 151 |
N, K = map(int, input().split())
d = list()
have = list()
for i in range(K):
d.append(int(input()))
holders = list(map(int, input().split()))
for holder in holders:
if holder not in have:
have.append(holder)
print(N - len(have))
|
while True:
n=input()
if n=='-':
break
else:
m=int(input())
for i in range(m):
h=int(input())
n=n[h:len(n)]+n[:h]
print(n)
| 0 | null | 13,221,350,254,492 | 154 | 66 |
while True:
d = input()
if d == '-':
break
m = int(input())
h = [int(input()) for _ in range(m)]
for i in h:
d = d[i:] + d[:i]
print(d)
|
import sys
printf = sys.stdout.write
ans = []
while True:
word = list(raw_input())
if word[0] == "-":
break
x = input()
suff = []
for i in range(x):
suff.append(input())
for i in range(len(suff)):
for j in range(suff[i]):
word.insert(int(len(word)), word[0])
del word[0]
ans.append(word)
word = 0
for i in range(len(ans)):
for j in range(len(ans[i])):
printf(ans[i][j])
print ""
| 1 | 1,915,088,057,344 | null | 66 | 66 |
import sys
from collections import Counter
n = int(input())
a_ls = [int(i) for i in sys.stdin.readline().split()]
minus_a_ct = Counter([-a-i for i,a in enumerate(a_ls)])
a_ct = Counter([a-i for i,a in enumerate(a_ls)])
_sum = 0
for k, v in a_ct.items():
_sum += v * minus_a_ct[k]
print(_sum)
|
import sys
n = int(input())
a = list(map(int,input().split()))
ans = 0
if 1 not in a:
print(-1)
sys.exit()
index = 1
for i in a:
if i != index:
ans+=1
else:
index+=1
print(ans)
| 0 | null | 70,537,644,373,892 | 157 | 257 |
N, K = map(int, input().split())
if N % K == 0:
print(0)
elif N % K > abs((N%K)-K):
print(abs((N%K)-K))
else:
print(N%K)
|
N, K = list(map(int, input().split()))
if abs(N - K) > N:
print(N)
else:
if N % K == 0:
N = 0
else:
N = abs(N % K - K)
print(N)
| 1 | 39,495,203,642,662 | null | 180 | 180 |
a,b,c,k=map(int,input().split())
ai=0
bi=0
ci=0
if a >= k:
ai=k
else:
ai=a
if b>= k-ai:
bi=k-ai
else:
bi=b
ci= k - ai - bi
print(ai-ci)
|
a = list(map(int, input().split()))
if a[3] <= a[0]:
print(a[3])
elif a[3] <= a[0] + a[1]:
print(a[0])
else:
print(a[0] - (a[3] - a[0] -a[1]))
| 1 | 21,889,517,485,390 | null | 148 | 148 |
A,B = map(int,input().split())
if A < 10 and B < 10:
answer = A * B
print(answer)
else:
print('-1')
|
a,b=map(int,input().split())
if a<0 or a>9:
print(-1)
elif b<0 or b>9:
print(-1)
else:
print(a*b)
| 1 | 158,354,834,541,510 | null | 286 | 286 |
n = int(input())
Building = [[[0 for r in range(11)] for f in range(4)] for b in range(5)]
for i in range(n):
b, f, r, v = map(int, input().split())
Building[b][f][r] += v
for b in range(1, 5):
for f in range(1, 4):
for r in range(1, 11):
print(" " + str(Building[b][f][r]), end = "")
print()
if b != 4:
print("####################")
|
import math
def is_prime(n):
global primes
if n == 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
s = int(math.sqrt(n))
for x in range(3, s + 1, 2):
if n % x == 0:
return False
else:
return True
N = int(input())
d = [int(input()) for _ in range(N)]
d.sort()
print([is_prime(x) for x in d].count(True))
| 0 | null | 546,158,431,392 | 55 | 12 |
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
n=int(input())
if n%2==1:
print(0)
else:
m=n//2
ans=0
for i in range(1,30):
ans+=m//(5**i)
print(ans)
if __name__=='__main__':
main()
|
n=int(input())
if n%2==1:
print(0)
exit(0)
n//=2
from math import floor,factorial
ans=0
deno=5
while deno<=n:
ans+=n//deno
deno*=5
print(ans)
| 1 | 116,119,015,654,528 | null | 258 | 258 |
n = int(input())
a = list(map(int, input().split()))
for i in range(n):
if a[i]%2 == 0:
if (a[i]%3 != 0) and (a[i]%5 != 0):
print('DENIED')
exit()
print('APPROVED')
|
n = int(input())
a = list(map(int,input().split()))
ok = True
for i in range(n):
if a[i] % 2 == 0 and a[i] % 3 != 0 and a[i] % 5 != 0:
ok = False
if ok:
print("APPROVED")
else:
print("DENIED")
| 1 | 69,333,410,366,440 | null | 217 | 217 |
#import numpy as np
import math
#from decimal import *
#from numba import njit
#@njit
def main():
(N, M, K) = map(int, input().split())
MOD = 998244353
fact = [1]*(N+1)
factinv = [1]*(N+1)
for i in range(1,N+1):
fact[i] = fact[i-1]*i % MOD
factinv[i] = pow(fact[i], MOD-2, MOD)
def comb(n, k):
return fact[n] * factinv[k] * factinv[n-k] % MOD
ans = 0
for k in range(K+1):
ans += (comb(N-1,k)*M*pow(M-1, N-k-1, MOD))%MOD
print(ans%MOD)
main()
|
from math import*
A,B,H,M = map(int, input().split())
print((A*A+B*B-2*A*B*cos((M*11/360-H/6)*pi))**.5)
| 0 | null | 21,680,366,689,436 | 151 | 144 |
# -*- coding: utf-8 -*-
# モジュールのインポート
import itertools
def get_input() -> tuple:
"""
標準入力を取得する.
Returns:\n
tuple: 標準入力
"""
# 標準入力を取得
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
return N, P, Q
def main(N: int, P: tuple, Q: tuple) -> None:
"""
メイン処理.
Args:\n
N (int): 数列の大きさ
P (tuple): 順列
Q (tuple): 順列
"""
# 求解処理
p = 0
q = 0
order = 1
for t in itertools.permutations(range(1, N + 1), N):
if t == P:
p = order
if t == Q:
q = order
order += 1
ans = abs(p - q)
# 結果出力
print(ans)
if __name__ == "__main__":
# 標準入力を取得
N, P, Q = get_input()
# メイン処理
main(N, P, Q)
|
class UnionFind:
def __init__(self, n=0):
self.d = [-1]*n
def find(self, x):
if self.d[x] < 0:
return x
else:
self.d[x] = self.find(self.d[x])
return self.d[x]
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return False
if self.d[x] > self.d[y]:
x, y = y, x
self.d[x] += self.d[y]
self.d[y] = x
return True
def same(self, x, y):
return self.find(x) == self.find(y)
def size(self, x):
return -self.d[self.find(x)]
n, m, k = map(int, input().split())
deg = [0]*100005
uf = UnionFind(n)
for _ in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
deg[a] += 1
deg[b] += 1
uf.unite(a, b)
for _ in range(k):
c, d = map(int, input().split())
c -= 1
d -= 1
if uf.same(c, d):
deg[c] += 1
deg[d] += 1
for i in range(n):
print(uf.size(i) - 1 - deg[i], end="")
if i == n-1:
print()
else:
print(" ", end="")
| 0 | null | 80,839,799,085,108 | 246 | 209 |
s = input()
q = []
for i in s:
q.append(int(i))
if sum(q)%9 == 0:
print('Yes')
else:print('No')
|
N=list(map(int,input().split()))
temp = sum(N)
if temp%9 == 0:print("Yes")
else:print("No")
| 1 | 4,455,640,040,772 | null | 87 | 87 |
N = int(input())
ST = [list(input().split()) for _ in [0]*N]
X = input()
ans = 0
for i,st in enumerate(ST):
s,t = st
if X==s:
break
for s,t in ST[i+1:]:
ans += int(t)
print(ans)
|
def resolve():
N = int(input())
s = []
t = []
for i in range(N):
S, T = input().split()
s.append(S)
t.append(int(T))
X = input()
print(sum(t[s.index(X)+1:]))
resolve()
| 1 | 97,274,241,816,990 | null | 243 | 243 |
class UnionFind():
# 作りたい要素数nで初期化
# 使用するインスタンス変数の初期化
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
# ノードxのrootノードを見つける
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def unite(self, x, y):
# 木の併合、入力は併合したい各ノード⇒(a,b)
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):
# ノードxが属する木のサイズを返す
return -self.parents[self.find(x)]
def same(self, x, y):
# 入力ノード(x,y)が同じグループに属するかを返す
return self.find(x) == self.find(y)
def members(self, x):
#ノード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())
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
n,m=map(int,input().split())
u=UnionFind(n)
for i in range(m):
a,b=map(int,input().split())
a-=1
b-=1
u.unite(a,b)
ans=u.roots()
print(len(ans)-1)
|
import sys
input = sys.stdin.readline
n,m=map(int,input().split())
d={i+1:[] for i in range(n)}
for i in range(m):
x,y=map(int,input().split())
d[x].append(y)
d[y].append(x)
visit=set()
ans= 0
for i in range(1,n+1):
if i not in visit:
ans+=1
stack = [i]
while stack:
c=stack.pop()
visit.add(c)
for i in d[c]:
if i not in visit:
stack.append(i)
print(ans-1)
| 1 | 2,265,992,615,850 | null | 70 | 70 |
# encoding:utf-8
import math as ma
# math.pi
x = float(input())
pi = (x * x) * ma.pi
# Circumference
pi_line = (x + x) * ma.pi
print("{0} {1}".format(pi,pi_line))
|
import math
a=float(input())
print("{0:.9f} {1:.9f}".format(a*a*math.pi,a*2*math.pi))
| 1 | 638,496,896,390 | null | 46 | 46 |
def solve():
N,M = [int(i) for i in input().split()]
ans = 0
if N > 1:
ans += N * (N-1) // 2
if M > 1:
ans += M * (M-1) // 2
print(ans)
if __name__ == "__main__":
solve()
|
N, M = map(int, input().split())
if N < 2:
A = 0
else:
A = int(N * (N - 1) / 2)
if M < 2:
B = 0
else:
B = int(M * (M - 1) / 2)
print(A + B)
| 1 | 45,723,153,572,082 | null | 189 | 189 |
import sys
h,w,m = map(int, sys.stdin.readline().split())
num_in_h = [0] * h
num_in_w = [0] * w
targets = set()
for _ in range(m):
t_h, t_w = map(lambda x: int(x)-1, sys.stdin.readline().split())
num_in_h[t_h] += 1
num_in_w[t_w] += 1
targets.add((t_h, t_w))
max_h = max(num_in_h)
max_w = max(num_in_w)
max_h_set = set([i for i, v in enumerate(num_in_h) if v == max_h])
max_w_set = set([i for i, v in enumerate(num_in_w) if v == max_w])
ans = max_h + max_w - 1
flag = False
for i in max_h_set:
for j in max_w_set:
if (i, j) not in targets:
flag = True
break
if flag: break
print(ans+1 if flag else ans)
|
t1,t2 = map(int,input().split())
a1,a2 = map(int,input().split())
b1,b2 = map(int,input().split())
if a1*t1 + a2*t2 == b1*t1 + b2*t2:
print("infinity")
else:
A = a1*t1 + a2*t2
B = b1*t1 + b2*t2
M1,m1 = max(a1*t1,b1*t1),min(a1*t1,b1*t1)
M2,m2 = max(A,B),min(A,B)
gap1,gap2 = M1-m1,M2-m2
Mv,mv = max(a1,b1),min(a1,b1)
vgap = Mv-mv
possible = vgap*t1
count = possible//gap2
if possible%gap2 == 0:
pitta = 1
else:
pitta = 0
if (a1*t1 > b1*t1 and A > B) or (a1*t1 < b1*t1 and A < B):
print(0)
elif (a1*t1 > b1*t1 and A < B) or (a1*t1 < b1*t1 and A > B):
if pitta == 1:
print(1+count*2-1)
else:
print(1+count*2)
| 0 | null | 68,208,695,915,570 | 89 | 269 |
h,w,x=map(int,input().split())
a=[list(input()) for i in range(h)]
ans=0
for i in range(2**(h+w)):
b=0
for j in range(h):
for k in range(w):
if (i>>j)&1==1 and (i>>k+h)&1==1 and a[j][k]=="#":
b+=1
if b==x:
ans+=1
print(ans)
|
N = int(input())
A = [0]+list(map(int, input().split(" ")))
dp_list = [{0, 0}, {0: 0, 1: A[1]}, {0: 0, 1: A[1] if A[1] > A[2] else A[2]}]
for i in range(3, N+1):
b = (i-1)//2
f = (i+1)//2
dp_list.append({})
for j in range(b, f+1):
if j in dp_list[i-1]:
dp_list[i][j] = dp_list[i-2][j-1]+A[i] if dp_list[i -
2][j-1]+A[i] > dp_list[i-1][j] else dp_list[i-1][j]
else:
dp_list[i][j] = dp_list[i-2][j-1]+A[i]
print(dp_list[-1][N//2])
| 0 | null | 23,278,965,493,052 | 110 | 177 |
x = list(map(int, input().split()))
print(x[2], x[0], x[1])
|
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
input = sys.stdin.buffer.readline
#sys.setrecursionlimit(10**9)
#from functools import lru_cache
def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode('utf-8')
#import numpy as np
def main():
x,y,z=MI()
print(z,x,y)
if __name__ == "__main__":
main()
| 1 | 37,970,116,627,618 | null | 178 | 178 |
import math
N = int(input())
A = [0]*(N)
for i in range(0,N):
A[i] = math.floor((N-1)/(i+1))
print(sum(A))
|
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()
| 1 | 2,624,086,761,020 | null | 73 | 73 |
N = input()
n = map(int,raw_input().split(' '))
c = 0
for i in range(0,N-1):
for j in range(1,N-i):
if n[j-1] > n[j]:
temp = n[j-1]
n[j-1] = n[j]
n[j] = temp
c += 1
print " ".join(str(i) for i in n)
print c
|
n=int(input())
if n==0:
p=0
print("%.9f"%p)
elif n&1:
p=(n//2)+1
print("%.9f"%(p/n))
else:
p=n//2
print("%.9f"%(p/n))
| 0 | null | 88,408,315,656,160 | 14 | 297 |
#C
A,B=map(int,input().split())
GCD=1
for i in range(2,10**5+1):
if A%i==0 and B%i==0:
GCD=i
LCM=A*B/GCD
print(int(LCM))
|
def actual(n, k, h_list):
return len([h for h in h_list if h >= k])
n, k = map(int, input().split())
h_list = map(int, input().split())
print(actual(n, k, h_list))
| 0 | null | 146,164,647,598,150 | 256 | 298 |
import math
n = int(input())
a = n/2
print(math.ceil(a)-1)
|
n = int(input())
print((n-1)//2)
| 1 | 153,303,848,680,022 | null | 283 | 283 |
N, K = map(int, input().split())
A = list(map(int, input().split()))
m = 1000000007
a = [e for e in A if e > 0]
b = [e for e in A if e < 0]
c = [e for e in A if e == 0]
# プラスルート
if len(a) >= K - (min(K, len(b)) // 2) * 2:
a.sort(reverse=True)
b.sort()
result = 1
i = 0
j = 0
k = 0
while k < K:
if k < K - 1 and i < len(a) - 1 and j < len(b) - 1:
x = a[i] * a[i + 1]
y = b[j] * b[j + 1]
if y >= x:
result *= y
result %= m
j += 2
k += 2
else:
result *= a[i]
result %= m
i += 1
k += 1
elif k < K - 1 and j < len(b) - 1:
y = b[j] * b[j + 1]
result *= y
result %= m
j += 2
k += 2
elif i < len(a):
result *= a[i]
result %= m
i += 1
k += 1
elif j < len(b):
result *= b[j]
result %= m
j += 1
k += 1
print(result)
# 0 ルート
elif len(c) != 0:
print(0)
# マイナスルート
else:
a.sort()
b.sort(reverse=True)
result = 1
i = 0
j = 0
k = 0
while k < K:
if i < len(a) and j < len(b):
if a[i] <= -b[i]:
result *= a[i]
result %= m
i += 1
k += 1
else:
result *= b[j]
result %= m
j += 1
k += 1
elif i < len(a):
result *= a[i]
result %= m
i += 1
k += 1
elif j < len(b):
result *= b[j]
result %= m
j += 1
k += 1
print(result)
|
s = input()
n = int(input())
for _ in range(n):
orders = input().split()
order = orders[0]
a = int(orders[1])
b = int(orders[2])
if order == 'print':
print(s[a:b + 1])
elif order == 'reverse':
s = s[:a] + ''.join(list(reversed(s[a:b+1]))) + s[b + 1:]
elif order == 'replace':
s = s[:a] + orders[-1] + s[b + 1:]
| 0 | null | 5,770,709,391,632 | 112 | 68 |
n = int(input())
a = 0
for i in range(10):
for j in range(10):
if i*j == n:
a +=1
if a == 0:
print("No")
else:
print("Yes")
|
a,b=input().split()
A=a*int(b)
B=b*int(a)
if A[0] > B[0]:
print(B)
else:
print(A)
| 0 | null | 121,729,342,178,510 | 287 | 232 |
while True:
H, W = map(int, raw_input().split())
if (H + W) == 0:
break
printW = ['#'] * W
if W != 0:
for h in range(H):
print ''.join(printW)
print ""
|
while True:
h, w = [int(i) for i in input().split(' ')]
if h ==0 and w ==0:
break
for i in range(h):
row = ''
for j in range(w):
row = row + '#'
print(row)
print('')
| 1 | 782,755,044,062 | null | 49 | 49 |
h, a = map(int, input().split())
print(int((a + h - 1) / a))
|
H, A = (int(x) for x in input().split())
dm = divmod(H,A)
if dm[1] == 0:
print(dm[0])
else:
print(dm[0]+1)
| 1 | 76,640,995,448,820 | null | 225 | 225 |
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)
N = int(input())
As = list(mapint())
mod = 10**9+7
bits = [0]*70
for a in As:
for l in range(a.bit_length()):
if (a>>l)&1:
bits[l] += 1
ans = 0
for i in range(70):
one = bits[i]
zero = N-one
mul = pow(2, i, mod)
ans += one*zero*mul
ans %= mod
print(ans)
|
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n = inp()
a = inpl()
ln = len(bin(max(a))) -2
cnt = [0] * ln
for x in a:
for shift in range(ln):
cnt[shift] += (x>>shift)%2
# print(cnt)
res = 0
for i in range(ln):
now = cnt[i] * (n-cnt[i])
res += now*pow(2,i)
res %= mod
print(res)
| 1 | 122,601,176,320,832 | null | 263 | 263 |
import queue
n, m = map(int, input().split())
a = [[] for _ in range(n)]
ans = 0
for _ in range(m):
x, y = map(int, input().split())
a[x-1].append(y-1)
a[y-1].append(x-1)
route = set()
route.add(0)
q = queue.Queue()
q.put(0)
for i in range(n):
if not i in route:
route.add(i)
q.put(i)
ans += 1
while not q.empty():
c = q.get()
for k in a[c]:
if not k in route:
q.put(k)
route.add(k)
if len(route) == n:
print(ans)
break
|
import sys
from io import StringIO
import unittest
import os
# 検索用タグ、10^9+7 組み合わせ、スプレッドシートでのトレース
# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)
def cmb(n, r):
mod = 10 ** 9 + 7
ans = 1
for i in range(r):
ans *= n - i
ans %= mod
for i in range(1, r + 1):
ans *= pow(i, mod - 2, mod)
ans %= mod
return ans
def prepare_simple(n, mod=pow(10, 9) + 7):
# n! の計算
f = 1
for m in range(1, n + 1):
f *= m
f %= mod
fn = f
# n!^-1 の計算
inv = pow(f, mod - 2, mod)
# n!^-1 - 1!^-1 の計算
invs = [1] * (n + 1)
invs[n] = inv
for m in range(n, 1, -1):
inv *= m
inv %= mod
invs[m - 1] = inv
return fn, invs
def prepare(n, mod=pow(10, 9) + 7):
# 1! - n! の計算
f = 1
factorials = [1] # 0!の分
for m in range(1, n + 1):
f *= m
f %= mod
factorials.append(f)
# n!^-1 の計算
inv = pow(f, mod - 2, mod)
# n!^-1 - 1!^-1 の計算
invs = [1] * (n + 1)
invs[n] = inv
for m in range(n, 1, -1):
inv *= m
inv %= mod
invs[m - 1] = inv
return factorials, invs
# 実装を行う関数
def resolve(test_def_name=""):
x, y = map(int, input().split())
all_move_count = (x + y) // 3
x_move_count = all_move_count
y_move_count = 0
x_now = all_move_count * 2
y_now = all_move_count
canMake= False
for i in range(all_move_count+1):
if x_now == x and y_now == y:
canMake = True
break
x_move_count -= 1
y_move_count += 1
x_now -= 1
y_now += 1
if not canMake:
print(0)
return
ans = cmb(all_move_count,x_move_count)
print(ans)
# テストクラス
class TestClass(unittest.TestCase):
def assertIO(self, assert_input, output):
stdout, sat_in = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
resolve(sys._getframe().f_back.f_code.co_name)
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, sat_in
self.assertEqual(out, output)
def test_input_1(self):
test_input = """3 3"""
output = """2"""
self.assertIO(test_input, output)
def test_input_2(self):
test_input = """2 2"""
output = """0"""
self.assertIO(test_input, output)
def test_input_3(self):
test_input = """999999 999999"""
output = """151840682"""
self.assertIO(test_input, output)
# 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
def tes_t_1original_1(self):
test_input = """データ"""
output = """データ"""
self.assertIO(test_input, output)
# 実装orテストの呼び出し
if __name__ == "__main__":
if os.environ.get("USERNAME") is None:
# AtCoder提出時の場合
resolve()
else:
# 自PCの場合
unittest.main()
| 0 | null | 76,201,410,999,840 | 70 | 281 |
# -*- coding:utf-8 -*-
import math
n = int(input())
ret_just = math.floor(n/1.08)
ret_minus1 = ret_just - 1
ret_plus1 = ret_just + 1
if math.floor(ret_just*1.08) == n:
print(ret_just)
elif math.floor(ret_minus1*1.08) == n:
print(ret_minus1)
elif math.floor(ret_plus1*1.08) == n:
print(ret_plus1)
else:
print(":(")
|
n = int(input())
r = n % 27
if r == 13 or r == 26:
print(':(')
elif r ==0:
x = int(100*n/108)
print(x)
else:
for i in range(1, 25):
if 1.08*(i-1) < r <= 1.08*i:
break
x = int(100*(n - i)/108) + i
print(x)
| 1 | 125,686,228,245,120 | null | 265 | 265 |
n = int(input())
s = input()
t = s[:len(s)//2]
if 2*t == s:
print("Yes")
else:
print("No")
|
import sys
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
read = sys.stdin.buffer.read
sys.setrecursionlimit(10 ** 7)
INF = float('inf')
N, A, B = map(int, input().split())
dis = B - A
if dis % 2 == 0:
ans = dis // 2
else:
ans = min(A - 1, N - B) + 1 + ((B - A) // 2)
print(ans)
| 0 | null | 128,034,597,234,502 | 279 | 253 |
A, B, N = map(int, input().split())
from math import floor
if B - 1 <= N:
x = B - 1
else:
x = N
print(floor(A*x/B) - A*floor(x/B))
|
import math
n = int(input())
i = 1
tmp = n-1
while i <= math.sqrt(n):
if n%i == 0:
j = n//i
if i + j < tmp:
tmp = i + j -2
else:
pass
else:
pass
i += 1
print(tmp)
| 0 | null | 94,623,835,623,668 | 161 | 288 |
num=input().split()
print(num[2],num[0],num[1])
|
X, Y, Z = map(str, input().split())
print(Z+" "+X+" "+Y)
| 1 | 37,931,911,007,392 | null | 178 | 178 |
print(sum(i%2for i in map(int,[*open(0)][1].split()[::2])))
|
# -*- coding: utf-8 -*-
def maximum_profit(profits):
max_v = profits[1] - profits[0]
min_v = profits[0]
for j in range(1, len(profits)):
max_v = max(max_v, profits[j]-min_v)
min_v = min(min_v, profits[j])
print(max_v)
def to_int(v):
return int(v)
if __name__ == '__main__':
l = to_int(input())
profits = [to_int(input()) for i in range(l)]
maximum_profit(profits)
| 0 | null | 3,904,721,411,588 | 105 | 13 |
N,K=map(int,input().split())
A=list(map(int,input().split()))
B=[N-A[K-1]+A[0]]
for i in range(K-1):
b=A[i+1]-A[i]
B.append(b)
B.sort()
print(sum(B)-B[K-1])
|
a=input()
b=a.split(" ")
c=list(map(int,b))
w=c[0]
h=c[1]
x=c[2]
y=c[3]
r=c[4]
if((x-r)<0 or (x+r)>w or (y-r)<0 or (y+r)>h):
str="No"
else :
str="Yes"
print(str)
| 0 | null | 22,044,602,148,304 | 186 | 41 |
from math import atan, degrees
a,b,x= map(int,input().split())
yoseki = a**2*b
if x <= yoseki/2:
# b*y*a/2==x
y= 2*x/b/a
# 90からシータを引けば良い
print(90-degrees(atan(y/b)))
else:
# a*y*a/2==yoseki-x
y = 2*(yoseki-x)/a**2
print(degrees(atan(y/a)))
|
from math import atan2, degrees
a,b,x = map(int, input().split())
s = x/a
if x >= a**2*b/2:
print(degrees(atan2(2*(a*b-s)/a, a)))
else:
print(degrees(atan2(b, 2*s/b)))
| 1 | 162,731,392,743,290 | null | 289 | 289 |
a,b = map(int, input().split())
hirosa = a*b
nagasa = 2*(a+b)
print(hirosa,nagasa)
|
h, a = map(int, input().split())
ans = h/float(a)
if ans == float(int(ans)):
print(int(ans))
else:
print(int(ans)+1)
| 0 | null | 38,877,233,005,482 | 36 | 225 |
import itertools
N, K = map(int, input().split())
d = []
A = []
for i in range(K):
d.append(int(input()))
A.append(list(map(int, input().split())))
A = list(itertools.chain.from_iterable(A))
ans = 0
for i in range(1, N + 1):
if i in A:
continue
else:
ans += 1
print(ans)
|
N, K = map(int, input().split())
sunuke = [False] * N
for _ in range(K):
d = int(input())
A = list(map(int, input().split()))
for a in A:
a -= 1
sunuke[a] = True
ans = N - sum(sunuke)
print(ans)
| 1 | 24,491,463,904,478 | null | 154 | 154 |
K = int(input())
ai_1 = 0
for i in range(K):
ai = (10*ai_1 + 7)%K
if ai==0:
print(i+1)
exit()
ai_1 = ai
print("-1")
|
n, k= map(int, input().split())
x = [0]*n
for i in range(k):
z = int(input())
if z == 1:
x[int(input())-1] +=1
else:
a = list(map(int, input().split()))
for j in a:
x[j-1] +=1
print(x.count(0))
| 0 | null | 15,459,197,601,380 | 97 | 154 |
a = int(input())
l = []
c,f =0, 0
for i in range(a):
ta,tb = map(int,input().split())
if ta==tb : c+=1
else: c = 0
if c>=3 : f = 1
print('YNeos'[f==0::2])
|
from sys import stdin,stdout
st=lambda:list(stdin.readline().strip())
li=lambda:list(map(int,stdin.readline().split()))
mp=lambda:map(int,stdin.readline().split())
inp=lambda:int(stdin.readline())
pr=lambda n: stdout.write(str(n)+"\n")
mod=1000000007
INF=float('inf')
for _ in range(1):
n=inp()
f=0
ans=0
for i in range(n):
a,b=mp()
if a==b:
ans+=1
else:
ans=0
if ans==3:
f=1
break
if f:
pr('Yes')
else:
pr('No')
| 1 | 2,524,347,086,308 | null | 72 | 72 |
s = input()
t = input()
cnt = 0
ans = 0
while cnt < len(s) - len(t) + 1:
chk = 0
for i, j in zip(range(cnt,cnt+len(t)),range(len(t))):
if s[i] == t[j]:
chk += 1
ans = max(ans,chk)
cnt += 1
print(len(t) - ans)
|
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def main():
S = input()
T = input()
#TがSの部分文字列になるようにSを書き換える
N = len(S)
M = len(T)
L = N - M #Sを調べるループの回数
#二重ループが許される
ans = M
for i in range(L+1):
#最大M個一致していない。
cnt = M
for j in range(M):
if S[i+j] == T[j]:
cnt -= 1
#最小を取る
ans = min(ans, cnt)
print(ans)
if __name__ == '__main__':
main()
| 1 | 3,687,593,858,188 | null | 82 | 82 |
N = int(input())
A_list = list(map(int, input().split()))
MOD = 10**9 + 7
zeros = [0] * 61
ones = [0] * 61
for a in A_list:
for i, b in enumerate([1 if (a >> j & 1) else 0 for j in range(61)]):
if b == 1:
ones[i] += 1
else:
zeros[i] += 1
res = 0
for a in A_list:
twice = 1
for i, b in enumerate([1 if (a >> j & 1) else 0 for j in range(61)]):
if b == 1:
cnt = zeros[i]
ones[i] -= 1
else:
cnt = ones[i]
zeros[i] -= 1
res += twice * cnt
twice *= 2
res %= MOD
print(res)
|
N = int(input())
A = list(map(int, input().split()))
m = 1000000007
result = 0
for i in range(60):
j = 1 << i
c = sum((a & j) >> i for a in A)
result += (c * (N - c)) << i
result %= m
print(result)
| 1 | 123,138,333,235,708 | null | 263 | 263 |
from sys import stdin, stdout
s = input()
n = len(s)
if len(s) <= 3:
print(0)
exit()
suffix_rems = [-1]*n
suffix_rems[-1] = int(s[-1])
suffix_rems[-2] = int(s[-2:])
suffix_rems[-3] = int(s[-3:])
rems_d = dict()
rems_d[0] = 1
rems_d[int(s[-1])] = 1
rems_d[int(s[-2:])] = 1
rems_d[int(s[-3:])] = 1
special_keys = set()
for i in range(n-3)[::-1]:
rem = (pow(10, n-i-1, 2019) * int(s[i]) + suffix_rems[i + 1])%2019
if rem in rems_d:
rems_d[rem] += 1
special_keys.add(rem)
else:
rems_d[rem] = 1
suffix_rems[i] = rem
ans = 0
for key in special_keys:
t = rems_d[key]
ans += (t*(t-1))//2
print(ans)
|
def main():
from collections import Counter
s = input()
l = [0]
t = 1
for i, x in enumerate(s[::-1]):
t = t * 10 % 2019
y = (l[-1] + int(x) * t) % 2019
l.append(y)
c = Counter(l)
ans = sum([v * (v - 1) // 2 for v in c.values()])
print(ans)
if __name__ == '__main__':
main()
| 1 | 30,897,130,600,678 | null | 166 | 166 |
n, k = map(int, input().split())
*a, = map(int, input().split())
for i, j in zip(a, a[k:]):
print('Yes' if i < j else 'No')
|
import heapq
def main():
N, M = list(map(int, input().split(' ')))
S = input()
# 最短手数のdpテーブルを作る
T = S[::-1] # ゴールから逆順にたどる(最後に逆にする)
dp = [-1] * (N + 1)
que = [0] * M
for i, t in enumerate(T):
if i == 0:
dp[0] = 0
continue
if len(que) == 0:
print(-1)
return
index = heapq.heappop(que)
if t == '1':
continue
dp[i] = 1 + dp[index]
while len(que) < M:
heapq.heappush(que, i)
dp.reverse()
# 細切れに進んでいく
path = list()
target = dp[0] - 1
cnt = 0
for i in range(N + 1):
if dp[i] != target:
cnt += 1
else:
path.append(cnt)
cnt = 1
target -= 1
print(' '.join(map(str, path)))
if __name__ == '__main__':
main()
| 0 | null | 73,376,965,551,022 | 102 | 274 |
N = int(input())
for i in range(1,10):
if N % i == 0 and 1<=N/i<=9:
print('Yes')
break
elif i == 9:
print('No')
# break:その後の処理を行わない。
|
import sys
def value(w,n,P):
tmp_w = 0
k = 1
for i in range(n):
if tmp_w + w[i] <= P:
tmp_w += w[i]
else:
tmp_w = w[i]
k += 1
return k
def test():
inputs = list(map(int,sys.stdin.readline().split()))
n = inputs[0]
k = inputs[1]
w = []
max = 0
sum = 0
for i in range(n):
w.append(int(sys.stdin.readline()))
if w[i] > max:
max = w[i]
sum += w[i]
while max != sum:
mid = (max + sum) // 2
if value(w,n,mid) > k:
max = mid + 1
else:
sum = mid
print(max)
if __name__ == "__main__":
test()
| 0 | null | 80,294,942,885,848 | 287 | 24 |
import sys
input = sys.stdin.readline
def main():
H, W, K = map(int, input().split())
cake = [[0]*W for _ in range(H)]
sb = []
for y in range(H):
s = input().strip()
for x, c in enumerate(s):
if c == "#":
sb.append((y, x))
for i, (y, x) in enumerate(sb):
cake[y][x] = i+1
import collections
for i, s in enumerate(sb):
Q = collections.deque()
Q.appendleft(s[1])
y = s[0]
while Q:
x = Q.pop()
if x-1 >= 0 and cake[y][x-1] == 0:
cake[y][x-1] = i+1
Q.appendleft(x-1)
if x+1 <= W-1 and cake[y][x+1] == 0:
cake[y][x+1] = i+1
Q.appendleft(x+1)
for y in range(1, H):
for x in range(W):
if cake[y][x] == 0:
cake[y][x] = cake[y-1][x]
for y in range(H-2, -1, -1):
for x in range(W):
if cake[y][x] == 0:
cake[y][x] = cake[y+1][x]
for c in cake:
print(*c)
if __name__ == '__main__':
main()
|
X, Y = list(map(int, input().split()))
crane = 0
turtle = X
while turtle >= 0:
allLegs = crane * 2 + turtle * 4
if allLegs == Y:
print("Yes")
exit()
crane += 1
turtle -= 1
print("No")
| 0 | null | 78,588,736,577,812 | 277 | 127 |
import sys
n, truck_num = map(int, input().split())
weights = [int(x) for x in map(int, sys.stdin)]
def main():
# 最小値と最大値をもとに二分探索する
print(binary_search(max(weights), sum(weights)))
def binary_search(left, right):
"""二分探索
:param left: 最小値
:param right: 最大値
:return:
"""
while left < right:
# 真ん中の値を割り当てる
middle = (left + right) // 2
# 真ん中の値で一旦シミュレート
if simulate(middle, weights, truck_num):
# OKならば、最大値をシミュレートした値に
right = middle
else:
# NGならば、最小値をシミュレートした+1に
left = middle + 1
return left
def simulate(mid, wei, t_num):
"""
:param mid: 中央値
:param wei: 荷物が格納されたリスト
:param t_num: トラックの台数
:return: シミュレートOKかNGか
"""
count = 1
tmp = 0
for w in wei:
tmp += w
# 積載量(tmp)が求める答え(mid)より大きくなったら
if mid < tmp:
# tmpを次の積載物に初期化
tmp = w
count += 1
if t_num < count:
return False
return True
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
import sys,collections
n,k = map(int,sys.stdin.readline().split())
w = list(map(int,sys.stdin.readlines()))
ng = sum(w)//k-1
ok = sum(w)
def isOK(p):
j = 0
for i in range(k):
s = 0
while j < n and s + w[j] <= p:
s += w[j]
j += 1
return j == n
while ok - ng > 1:
mid = (ok+ng)//2
t = collections.Counter(w)
if isOK(mid):
ok = mid
else:
ng = mid
print(ok)
| 1 | 86,899,377,322 | null | 24 | 24 |
n = int(input())
alist = list(map(int,input().split()))
syain = [0]*n
for i in range(n-1):
syain[alist[i]-1] += 1
for i in range(n):
print(syain[i])
|
w=input()
a=0
while True:
t=input().split()
l=[]
for T in t:
l.append(T.lower())
a+=l.count(w)
if t[0]=="END_OF_TEXT":
break
print(a)
| 0 | null | 17,275,984,932,262 | 169 | 65 |
S = list(input())
T = list(input())
count = 0
for i,j in zip(S,T):
if i != j:
count += 1
print(count)
|
a,b=map(str,input().split())
res = ""
if a < b:
for i in range(int(b)):
res += a
else:
for i in range(int(a)):
res += b
print(res)
| 0 | null | 47,226,410,092,540 | 116 | 232 |
k = int(input())
s = "1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51"
l = s.split(",")
print(int(l[k-1]))
|
def common_raccoon_vs_monster():
# 入力
H, N = map(int, input().split())
A = list(map(int, input().split()))
# 必殺技の合計攻撃力
sum_A = 0 # 必殺技の攻撃力の合計
for i in range(len(A)):
sum_A += A[i]
# 比較
if H > sum_A:
return 'No'
else:
return 'Yes'
result = common_raccoon_vs_monster()
print(result)
| 0 | null | 64,154,871,941,650 | 195 | 226 |
N = int(input())
n = 0
for i in range(1,N+1):
if i % 3 == 0 and i % 5 == 0:
continue
elif i % 3 == 0:
continue
elif i % 5 == 0:
continue
else:
n += i
print(n)
|
from collections import deque
n, x, y = map(int, input().split())
g = [[] for _ in range(n)]
# make graph
for i in range(n - 1):
g[i].append(i + 1)
g[i + 1].append(i)
g[x - 1].append(y - 1)
g[y - 1].append(x - 1)
def bfs(g, n_node, start_node):
dist = [-1] * n_node
dist[start_node] = 0
queue = deque([start_node])
while queue:
node = queue.popleft()
for n in g[node]:
if dist[n] != -1:
continue
dist[n] = dist[node] + 1
queue.append(n)
return dist
ans_array = [0] * n
for i in range(n):
dist = bfs(g, n, i)
for d in dist:
ans_array[d] += 1
for i in ans_array[1:]:
print(i // 2)
| 0 | null | 39,389,949,729,518 | 173 | 187 |
def main():
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
import math
#from math import gcd
inf = 10**17
#mod = 10**9 + 7
N,M,L = map(int, input().split())
dp = [[inf]*N for _ in range(N)]
for i in range(N):
dp[i][i] = 0
for _ in range(M):
a,b,c = map(int, input().split())
dp[a-1][b-1] = c
dp[b-1][a-1] = c
#kを経由してiからjに行く行き方を考える
#これで上手く行くのは与えられた辺の和しか考えていないため
for k in range(N):
for i in range(N):
for j in range(N):
if dp[i][j] > dp[i][k] + dp[k][j]:
dp[i][j] = dp[j][i] = dp[i][k]+dp[k][j]
dp2 = [[inf]*N for _ in range(N)]
for i in range(N):
for j in range(N):
if dp[i][j] <= L:
dp2[i][j] = dp2[j][i] = 1
for k in range(N):
for i in range(N):
for j in range(N):
if dp2[i][j] > dp2[i][k] + dp2[k][j]:
dp2[i][j] = dp2[j][i] = dp2[i][k]+dp2[k][j]
q = int(input())
for _ in range(q):
s, t = map(int, input().split())
if dp2[s-1][t-1] == inf:
print(-1)
else:
print(dp2[s-1][t-1]-1)
if __name__ == '__main__':
main()
|
import sys
input = sys.stdin.buffer.readline
n, m, limit = map(int, input().split())
infi = 10 ** 15
graph = [[infi] * (n + 1) for _ in range(n + 1)]
step = [[infi] * (n + 1) for _ in range(n + 1)]
for _ in range(m):
a, b, c = map(int, input().split())
graph[a][b] = c
graph[b][a] = c
for k in range(1, n + 1):
for i in range(1, n + 1):
for j in range(1, n + 1):
graph[i][j] = min(graph[i][k] + graph[k][j], graph[i][j])
for i in range(1, n + 1):
for j in range(1, n + 1):
if graph[i][j] <= limit:
graph[i][j] = 1
elif graph[i][j] == 0:
graph[i][j] = 0
else:
graph[i][j] = infi
for k in range(1, n + 1):
for i in range(1, n + 1):
for j in range(1, n + 1):
graph[i][j] = min(graph[i][k] + graph[k][j], graph[i][j])
q = int(input())
for _ in range(q):
a, b = map(int, input().split())
if graph[a][b] == infi:
graph[a][b] = 0
print(graph[a][b] - 1 if graph[a][b] != infi else -1)
| 1 | 173,882,981,731,720 | null | 295 | 295 |
#
import sys
input=sys.stdin.readline
from collections import deque
def main():
N,X,Y=map(int,input().split())
X-=1
Y-=1
adj=[[] for i in range(N)]
adj[X].append(Y)
adj[Y].append(X)
for i in range(N-1):
adj[i].append(i+1)
adj[i+1].append(i)
cnt=[0]*(N)
for i in range(N):
dist=[-1]*N
qu=deque([i])
dist[i]=0
while(len(qu)>0):
v=qu.popleft()
for nv in adj[v]:
if dist[nv]==-1:
dist[nv]=dist[v]+1
cnt[dist[nv]]+=1
qu.append(nv)
for i in range(1,N):
print(cnt[i]//2)
if __name__=="__main__":
main()
|
### ----------------
### ここから
### ----------------
import sys
from io import StringIO
import unittest
def yn(b):
print("Yes" if b==1 else "No")
return
def resolve():
readline=sys.stdin.readline
n,x,y=map(int, readline().rstrip().split())
ans = [0] * (n-1)
for i in range(1,n+1):
for j in range(i+1,n+1):
d1 = abs(i-x) + abs(j-x)
d2 = abs(i-y) + abs(j-y)
d3 = abs(i-x) + abs(j-y) + 1
d4 = abs(i-y) + abs(j-x) + 1
d5 = abs(i-j)
d=min(d1,d2,d3,d4,d5)
ans[d-1]+=1
for a in ans:
print(a)
#arr=list(map(int, readline().rstrip().split()))
#n=int(readline())
#ss=readline().rstrip()
#yn(1)
return
if 'doTest' not in globals():
resolve()
sys.exit()
### ----------------
### ここまで
### ----------------
| 1 | 44,069,029,122,510 | null | 187 | 187 |
import sys
read = sys.stdin.read
T1, T2, A1, A2, B1, B2 = map(int, read().split())
answer = 0
v1 = A1 - B1
v2 = A2 - B2
d = v1 * T1 + v2 * T2
if d == 0:
print('infinity')
exit()
elif v1 * d > 0:
print(0)
exit()
if v1 * T1 % -d == 0:
print(v1 * T1 // -d * 2)
else:
print(v1 * T1 // -d * 2 + 1)
|
class LCA(object):
def __init__(self, n, root, edges, decrement=True):
"""
:param n: 頂点数
:param root: 木の根
:param edges: 辺のリスト
:param decrement:
:param self.depth: rootを根とした時の各頂点の深さ
"""
self.n = n
self.decrement = decrement
self.root = root - self.decrement
self.edges = [set() for _ in range(self.n)]
for x, y in edges:
self.add_edge(x,y)
self.k_max = (self.n - 1).bit_length()
self.depth = [-1 if i != self.root else 0 for i in range(self.n)]
self.doubling = [[-1] * self.n for _ in range(self.k_max)]
self.parent = [-1]*self.n
self.dfs()
for i in range(1, self.k_max):
for k in range(self.n):
if self.doubling[i - 1][k] != -1:
self.doubling[i][k] = self.doubling[i - 1][self.doubling[i - 1][k]]
def add_edge(self, x, y):
"""
後から追加した場合は update() をする
"""
if self.decrement:
x -= 1
y -= 1
self.edges[x].add(y)
self.edges[y].add(x)
def update(self):
self.depth = [-1 if i != self.root else 0 for i in range(self.n)]
self.doubling = [[-1] * self.n for _ in range(self.k_max)]
self.dfs()
for i in range(1, self.k_max):
for k in range(self.n):
if self.doubling[i - 1][k] != -1:
self.doubling[i][k] = self.doubling[i - 1][self.doubling[i - 1][k]]
def dfs(self):
next_set = [self.root]
while next_set:
p = next_set.pop()
for q in self.edges[p]:
if self.depth[q] == -1:
self.depth[q] = self.depth[p] + 1
self.doubling[0][q] = p
next_set += [q]
def get(self, u, v):
"""
:return: u と v の最近共通祖先の頂点番号を返す
"""
if self.decrement:
u -= 1
v -= 1
if self.depth[v] < self.depth[u]:
u, v = v, u
for i in range(self.k_max):
""" v を u の位置まで遡らせる """
if (self.depth[v] - self.depth[u]) >> i & 1:
v = self.doubling[i][v]
if v == u:
""" v の祖先が u だった場合"""
return u + self.decrement
for i in range(self.k_max-1, -1, -1):
""" k = 2**(k_max-1), ..., 2**0 について、
「k個先を確認して共通祖先でないなら u1,v1 をk個先に移動」ということを繰り返す"""
parent_u, parent_v = self.doubling[i][u], self.doubling[i][v]
if parent_u != parent_v:
u, v = parent_u, parent_v
return self.doubling[0][u] + self.decrement
def distance(self, u, v):
"""
:return: u と v の最短距離を求める
備考: 経路復元をしようとすると O(E)かかるので、経路復元が必要な場合は dfs を用いるとよい
"""
lca_at = self.get(u,v)
if self.decrement:
u -= 1
v -= 1
lca_at -= 1
return self.depth[u] + self.depth[v] - 2*self.depth[lca_at]
def distance_list(self, start=1, save=False):
"""
:param start: スタート地点
:return: スタート地点から各点への距離のリスト
"""
dist = [-1]*self.n
if self.decrement:
start -= 1
if not save:
self.parent = [-1] * self.n
p, t = start, 0
self.parent[p] = -2
dist[p] = 0
next_set = deque([(p, t)])
while next_set:
p, t = next_set.popleft()
for q in self.edges[p]:
if self.parent[q] != -1:
continue
if q == xx-1:
continue
dist[q] = t + 1
self.parent[q] = p
next_set.append((q, t + 1))
return dist
def most_distant_point(self, start=1, save=False):
"""
計算量 O(N)
:return: (start から最も遠い頂点, 距離)
"""
if not save:
self.parent = [-1] * self.n
res = (start - self.decrement, 0)
temp = 0
for i, dist in enumerate(self.distance_list(start, save=save)):
if dist > temp:
temp = dist
res = (i + self.decrement, dist)
return res
#################################################################################################
import sys
from collections import deque
input = sys.stdin.readline
N, u, v = map(int, input().split())
edges = []
for _ in range(N-1):
x, y = map(int, input().split())
edges.append((x,y))
xx = -3
lca = LCA(N, 1, edges, decrement=True)
p = lca.get(u,v)
lu, lv = lca.depth[u-1] - lca.depth[p-1], lca.depth[v-1] - lca.depth[p-1]
if lu <= lv:
q, _ = lca.most_distant_point(v)
print(lca.distance(q,v)-1)
exit()
else:
L = (lu+lv)//2
cnt = 0
lca.distance_list()
if lca.depth[u-1] >= lca.depth[v-1]:
a = u-1
while cnt < L:
a = lca.parent[a]
cnt += 1
xx, s = lca.parent[a]+1, a+1
else:
a = v-1
while cnt < L+1:
a = lca.parent[a]
cnt += 1
xx, s = a+1, lca.parent[a]+1
q, _ = lca.most_distant_point(s)
print(lca.distance(q,v)-1)
exit()
| 0 | null | 124,341,120,487,820 | 269 | 259 |
N, K = [int(x) for x in input().split()]
l = []
while N > 0:
l.insert(0, N % K)
N = N // K
print(len(l))
|
input()
myarr = list(map(int, input().split()))
for i in range(len(myarr)):
for j in range(i, 0,-1):
if myarr[j] < myarr[j-1]:
t = myarr[j]
myarr[j] = myarr[j-1]
myarr[j-1] = t
else:
break
print(" ".join(map(str, myarr)))
| 0 | null | 32,035,837,883,618 | 212 | 10 |
X = int(input())
num1000 = X // 500
r500 = X % 500
num5 = r500 // 5
print(num1000 * 1000 + num5 * 5)
|
# coding: UTF-8
import sys
import numpy as np
n = int(input())
ans = (n // 500) * 1000
n -= (n // 500) * 500
ans += (n // 5) * 5
print(ans)
| 1 | 42,743,229,378,550 | null | 185 | 185 |
import sys
input = sys.stdin.readline
A = sorted(list(map(int,input().split())))
if (A[0] != A[1] and A[1] == A[2]) or (A[0] == A[1] and A[1] != A[2]) :
print('Yes')
else:
print('No')
|
a,b,c = map(int,input().split())
if a == b and b == c and c == a: print('No')
elif a != b and b != c and c != a: print('No')
else: print('Yes')
| 1 | 68,046,536,283,308 | null | 216 | 216 |
N=int(input())
D=list(map(int, input().split()))
if D[0]!=0:
print(0)
exit()
if 0 in D[1:]:
print(0)
exit()
D=sorted(D)
p=998244353
edge=[0]*(N)
ans=1
for i in range(N):
d=D[i]
if i==0:
if d==0:
edge[0]+=1
continue
else:
print(0)
exit()
if d==0:
print(0)
exit()
if edge[d-1]==0:
print(0)
exit()
else:
edge[d]+=1
ans*=edge[d-1]
ans%=p
print(ans%p)
|
N = int(input())
ansAC = 0
ansWA = 0
ansTLE = 0
ansRE = 0
for i in range(N):
S = input()
if S == "AC":
ansAC += 1
elif S == "TLE":
ansTLE += 1
elif S == "WA":
ansWA += 1
elif S == "RE":
ansRE += 1
print("AC x " + str(ansAC))
print("WA x " + str(ansWA))
print("TLE x " + str(ansTLE))
print("RE x " + str(ansRE))
| 0 | null | 82,068,942,897,202 | 284 | 109 |
def solve():
H,A = [int(i) for i in input().split()]
print((H+A-1)//A)
if __name__ == "__main__":
solve()
|
#0からiまでのSを2019で割ったときのあまりを調べる
#A%mod =a,B$mod=aなら(A-B)%mod=0
from collections import Counter
S = input()
dp = [0]
mod = 2019
for i in reversed(range(len(S))):
dp.append(dp[-1]%mod+pow(10,len(S)-i-1,mod)*int(S[i]))
dp[-1]%=mod
count = Counter(dp)
ans = 0
for key,val in count.items():
if val>=2:
ans += val*(val-1)//2
print(ans)
| 0 | null | 53,890,286,762,076 | 225 | 166 |
#!/usr/bin/env python3
import sys
import math
# import re # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from collections import deque # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict # subclass of dict. defaultdict(facroty)
# from collections import Counter # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product # product(iter, repeat=n)
# from itertools import accumulate # accumulate(iter[, f])
# from functools import reduce # reduce(f, iter[, init])
# from functools import lru_cache # @lrucache ...arguments of functions should be able to be keys of dict
from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy # to copy multi-dimentional matrix without reference
# from fractions import gcd # for Python 3.4
def main():
mod = 1000000007 # 10^9+7
inf = float('inf')
sys.setrecursionlimit(10**6) # 1000 -> 1000000
def input(): return sys.stdin.readline().rstrip()
def ii(): return int(input())
def mi(): return map(int, input().split())
def mi_0(): return map(lambda x: int(x)-1, input().split())
def lmi(): return list(map(int, input().split()))
def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
def li(): return list(input())
n, d, a = mi()
monsters = sorted([lmi() for _ in range(n)])
monster_points = []
monster_hps= []
for pair in monsters:
monster_points.append(pair[0])
monster_hps.append(pair[1])
# どの monster_points[ind] での ind の表すモンスターまで巻き込めるか (右端)
right_end_monster_ind = [0] * (n)
for i in range(n):
right_end_monster_ind[i] = bisect_right(monster_points, monster_points[i]+2*d) - 1
# print(right_end_monster_ind)
imos_list = [0] * (n+1)
damage = 0
ans = 0
for i in range(n):
damage += imos_list[i]
rest_hp = max(0, monster_hps[i] - damage)
# print("rest {}".format(rest_hp))
cnt = math.ceil(rest_hp / a)
ans += cnt
imos_list[i+1] += (a * cnt)
imos_list[right_end_monster_ind[i]+1] -= (a * cnt)
# print(imos_list)
print(ans)
if __name__ == "__main__":
main()
|
n, d, a = map(int, input().split())
xh = []
for _ in range(n):
x, h = map(int, input().split())
h = (h - 1) // a + 1
xh.append([x, h])
xh.sort()
damage = xh[0][1]
ans = damage
damage_lst = [[xh[0][0] + d * 2, damage]]
pos = 0
for i, (x, h) in enumerate(xh[1:], start = 1):
while x > damage_lst[pos][0]:
damage -= damage_lst[pos][1]
pos += 1
if pos == i:
break
damage_tmp = max(h - damage, 0)
ans += damage_tmp
damage += damage_tmp
damage_lst.append([x + d * 2, damage_tmp])
print(ans)
| 1 | 81,767,138,215,658 | null | 230 | 230 |
h, w, k = map(int, input().split())
s = [list(map(int, input())) for _ in range(h)]
ans = float("inf")
for sep in range(1 << (h-1)):
g_id = [0] * h
cur = 0
for i in range(h-1):
g_id[i] = cur
if sep >> i & 1: cur += 1
g_id[h-1] = cur
g_num = cur+1
ng = False
for i in range(w):
tmp = [0] * g_num
for j in range(h): tmp[g_id[j]] += s[j][i]
if any([x > k for x in tmp]): ng = True; break
if ng: continue
res = g_num-1
gs = [0] * g_num
for i in range(h):
gs[g_id[i]] += s[i][0]
for i in range(1, w):
tmp = gs[::]
for j in range(h):
tmp[g_id[j]] += s[j][i]
if any([x > k for x in tmp]):
res += 1
gs = [0] * g_num
for j in range(h): gs[g_id[j]] += s[j][i]
ans = min(ans, res)
print(ans)
|
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()
| 1 | 48,508,821,660,112 | null | 193 | 193 |
a,b=1,0
for c in map(int,input()):a,b=min(a+10-c-1,b+c+1),min(a+10-c,b+c)
print(b)
|
def y_solver(tmp):
l=len(tmp)
rev=[int(i) for i in tmp[::-1]+"0"]
ans=0
for i in range(l):
num=rev[i]
next_num=rev[i+1]
if (num>5) or (num==5 and next_num>=5):
rev[i+1]+=1
ans+=min(num,10-num)
last=rev[l]
ans+=min(last,10-last)
return ans
s=input()
ans=y_solver(s)
print(ans)
| 1 | 70,954,434,079,864 | null | 219 | 219 |
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, y = LMAPINT()
for i in range(x+1):
for j in range(x+1):
if i + j == x and i*2 + j*4 == y:
print('Yes')
exit()
print('No')
|
N, K = map(int, input().split())
A = [int(a) for a in input().split()]
print(len([a for a in A if a >= K]))
| 0 | null | 96,730,535,860,288 | 127 | 298 |
t1,t2 = map(int,input().split())
a1,a2 = map(int,input().split())
b1,b2 = map(int,input().split())
if (a1<b1 and a2<b2) or (a1>b1 and a2>b2):
print(0)
exit()
if a1 > b1:
a1,b1 = b1,a1
a2,b2 = b2,a2
_b1 = b1 - a1
_a2 = a2 - b2
v1 = t1*_b1
v2 = t2*_a2
if v1 == v2:
print('infinity')
exit()
if v1 > v2:
print(0)
exit()
d = v2 - v1
k = v1 // d
ans = k*2 + 1
if v2*k == v1*(k+1):
ans -= 1
print(ans)
|
t1, t2 = list(map(int, input().split()))
a1, a2 = list(map(int, input().split()))
b1, b2 = list(map(int, input().split()))
a1 *= t1
a2 *= t2
b1 *= t1
b2 *= t2
if a1 > b1:
l1 = a1
l2 = a2
s1 = b1
s2 = b2
else:
l1 = b1
l2 = b2
s1 = a1
s2 = a2
if l1 + l2 == s1 + s2:
print('infinity')
elif l1 + l2 < s1 + s2:
lim = l1 - s1
if lim % (s1+s2-l1-l2):
print(1 + 2 * (lim // (s1+s2-l1-l2)))
else:
print(2 * (lim // (s1+s2-l1-l2)))
else:
print(0)
| 1 | 131,301,656,775,618 | null | 269 | 269 |
#!/usr/bin/python3
import sys
from functools import reduce
from operator import mul
input = lambda: sys.stdin.readline().strip()
n, k = [int(x) for x in input().split()]
a = sorted((int(x) for x in input().split()), key=abs)
sgn = [0 if x == 0 else x // abs(x) for x in a]
M = 10**9 + 7
def modmul(x, y):
return x * y % M
if reduce(mul, sgn[-k:]) >= 0:
print(reduce(modmul, a[-k:], 1))
else:
largest_unselected_neg = next(i for i, x in enumerate(reversed(a[:-k])) if x < 0) if any(x < 0 for x in a[:-k]) else None
largest_unselected_pos = next(i for i, x in enumerate(reversed(a[:-k])) if x > 0) if any(x > 0 for x in a[:-k]) else None
smallest_selected_neg = next(i for i, x in enumerate(a[-k:]) if x < 0) if any(x < 0 for x in a[-k:]) else None
smallest_selected_pos = next(i for i, x in enumerate(a[-k:]) if x > 0) if any(x > 0 for x in a[-k:]) else None
can1 = largest_unselected_neg is not None and smallest_selected_pos is not None
can2 = largest_unselected_pos is not None and smallest_selected_neg is not None
def ans1():
return list(reversed(a[:-k]))[largest_unselected_neg] * reduce(modmul, (x for i, x in enumerate(a[-k:]) if i != smallest_selected_pos), 1) % M
def ans2():
return list(reversed(a[:-k]))[largest_unselected_pos] * reduce(modmul, (x for i, x in enumerate(a[-k:]) if i != smallest_selected_neg), 1) % M
if can1 and not can2:
print(ans1())
elif can2 and not can1:
print(ans2())
elif can1 and can2:
if list(reversed(a[:-k]))[largest_unselected_neg] * a[-k:][smallest_selected_neg] > list(reversed(a[:-k]))[largest_unselected_pos] * a[-k:][smallest_selected_pos]:
print(ans1())
else:
print(ans2())
else:
print(reduce(modmul, a[:k], 1))
|
def make_divisors(n: int):
lower_divs = []
upper_divs = []
i = 1
while i**2 <= n:
if n % i == 0:
lower_divs.append(i)
if i != n // i:
upper_divs.append(n // i)
i += 1
return lower_divs + upper_divs[::-1]
n = int(input())
ans = len(make_divisors(n - 1)) - 1
for x in make_divisors(n)[1:]:
if x == 1:
continue
z = n
while z % x == 0:
z = z // x
z = z % x
if z == 1:
ans += 1
print(ans)
| 0 | null | 25,369,733,347,282 | 112 | 183 |
N=int(input())
def struct(s,i,n,ma):
if i==n:
print(s)
else:
for j in range(0,ma+2):
struct(s+chr(ord('a')+j),i+1,n,max(j,ma))
struct('a',1,N,0)
|
n=int(input())
l=[0]
c=0
l=l+(list(map(int,input().split())))
try:
for i in range(1,n+1,2):
if l[i]&1:
c+=1
except:
pass
print(c)
| 0 | null | 30,085,241,607,374 | 198 | 105 |
N, K = map(int, input().split())
area = []
for i in range(K):
L, R = map(int, input().split())
area.append((L, R))
area.sort()
d = [0] * N
a = [0] * N
def func(pos):
for l, r in area:
if pos + l - 1 < N:
a[pos + l-1] += d[pos]
if pos + r < N:
a[pos + r] -= d[pos]
d[pos+1] = (d[pos] + a[pos]) % 998244353
d[0] = 1
a[0] = -1
for i in range(0, N-1):
func(i)
print(d[N-1] % 998244353)
|
X,Y=map(int,input().split())
M=[0]*206
M[0],M[1],M[2]=300000,200000,100000
if X+Y==2:
print(1000000)
else:
print(M[X-1]+M[Y-1])
| 0 | null | 71,381,658,604,608 | 74 | 275 |
N = int(input())
def solve(x1, y1, x2, y2, n):
if n == 0:
return print(x1, y1)
else:
solve(x1, y1, (2 * x1 + x2) / 3, (2 * y1 + y2) / 3, n - 1)
solve((2 * x1 + x2) / 3, (2 * y1 + y2) / 3, (x1 + x2) / 2 + (y1 - y2) * (3 ** (1 / 2)) / 6, (y1 + y2) / 2 + (x2 - x1) * (3 ** (1 / 2)) / 6, n - 1)
solve((x1 + x2) / 2 + (y1 - y2) * (3 ** (1 / 2)) / 6, (y1 + y2) / 2 + (x2 - x1) * (3 ** (1 / 2)) / 6, (x1 + 2 * x2) / 3, (y1 + 2 * y2) / 3, n - 1)
solve((x1 + 2 * x2) / 3, (y1 + 2 * y2) / 3, x2, y2, n - 1)
solve(0, 0, 100, 0, N)
print(100, 0)
|
import math
def kochCurve(d, p1, p2):
if d <= 0:
return
s = [(2.0*p1[0]+1.0*p2[0])/3.0, (2.0*p1[1]+1.0*p2[1])/3.0]
t = [(1.0*p1[0]+2.0*p2[0])/3.0, (1.0*p1[1]+2.0*p2[1])/3.0]
u = [(t[0]-s[0])*math.cos(math.radians(60))-(t[1]-s[1])*math.sin(math.radians(60))+s[0], (t[0]-s[0])*math.sin(math.radians(60))+(t[1]-s[1])*math.cos(math.radians(60))+s[1]]
kochCurve(d-1, p1, s)
print(s[0], s[1])
kochCurve(d-1, s, u)
print(u[0], u[1])
kochCurve(d-1, u, t)
print(t[0], t[1])
kochCurve(d-1, t, p2)
n = int(input())
s = [0.00000000, 0.00000000]
e = [100.00000000, 0.00000000]
print(s[0],s[1])
if n != 0:
kochCurve(n,s,e)
print(e[0],e[1])
| 1 | 125,480,387,332 | null | 27 | 27 |
h1, m1, h2, m2, k = map(int, input().split())
time = (h2 - h1) * 60
time += m2 - m1
print(time - k)
|
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
def main():
n,u,v = map(int,ipt().split())
way = [[] for _ in range(n+1)]
for _ in range(n-1):
a,b = map(int,ipt().split())
way[a].append(b)
way[b].append(a)
ta = [-1]*(n+1)
tt = [-1]*(n+1)
ta[v] = 0 #AOKI
tt[u] = 0
qa = queue.Queue()
qt = queue.Queue()
qt.put((0,u,-1))
qa.put((0,v,-1))
while not qa.empty():
ti,pi,pp = qa.get()
for i in way[pi]:
if i == pp:
continue
if ta[i] == -1:
ta[i] = ti+1
qa.put((ti+1,i,pi))
while not qt.empty():
ti,pi,pp = qt.get()
if ta[pi] <= ti:
continue
for i in way[pi]:
if i == pp:
continue
if ta[i] > ti:
tt[i] = ti+1
qt.put((ti+1,i,pi))
ma = 0
for i in range(1,n+1):
if tt[i] == -1:
continue
if ma < tt[i]+max(0,ta[i]-tt[i]-1):
ma = tt[i]+max(0,ta[i]-tt[i]-1)
print(ma)
return
if __name__ == '__main__':
main()
| 0 | null | 67,480,121,261,472 | 139 | 259 |
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
#import math
#import time
#import random # randome is not available at Codeforces
def I():
return int(input())
def MI():
return map(int,input().split())
def LI():
return [int(i) for i in input().split()]
def LI_():
return [int(i)-1 for i in input().split()]
def StoI():
return [ord(i)-97 for i in input()]
def show(*inp,end='\n'):
if show_flg:
print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
#eps=10**(-10)
#ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()
show_flg=False
show_flg=True
def wf(d):
n=len(d)
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])
return d
n,m,l=MI()
d=[[inf]*n for _ in range(n)]
for i in range(m):
a,b,c=LI_()
d[a][b]=c+1
d[b][a]=c+1
d=wf(d)
g=[[inf]*n for i in range(n)]
for i in range(n):
for j in range(i+1,n):
if d[i][j]<=l:
g[i][j]=1
g[j][i]=1
g=wf(g)
q=I()
for _ in range(q):
s,t=LI_()
if g[s][t]==inf:
ans=-1
else:
ans=g[s][t]-1
print(ans)
|
def warshall_floyd(d,n):
#d[i][j]: iからjへの最短距離
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])
return d
def main():
INF = 10**18
n,m,l = map(int, input().split())
d = [ [INF]*(n+1) for _ in range(n+1) ]
for _ in range(m):
a,b,c = map(int, input().split())
d[a][b] = c
d[b][a] = c
d = warshall_floyd(d,n+1)
new_d = [ [INF]*(n+1) for _ in range(n+1) ]
for a in range(n+1):
for b in range(n+1):
if d[a][b] <= l:
new_d[a][b] = 1
new_d[b][a] = 1
new_d = warshall_floyd(new_d,n+1)
ansl = []
q = int(input())
for _ in range(q):
s,t = map(int, input().split())
ans = new_d[s][t]
if ans >= INF: ans = 0
ansl.append(ans-1)
for a in ansl: print(a)
if __name__ == "__main__":
main()
| 1 | 173,682,429,227,168 | null | 295 | 295 |
import sys
read = sys.stdin.read
readline = sys.stdin.readline
n = int(readline())
#print(n)
a_list = list([int(x) for x in readline().rstrip().split()])
#print(a_list)
count = 0
for i in a_list[::2]:
#print(i)
if i % 2 != 0:
count += 1
print(count)
|
N = int(input())
s = "ACL"
ans = ""
for i in range(N):
ans += s
print(ans)
| 0 | null | 5,023,229,894,880 | 105 | 69 |
s = input()
t = input()
ans = 1001
if len(s)-len(t)==0:
temp = 0
for j in range(len(t)):
if s[j]!=t[j]:
temp+=1
ans = min(ans, temp)
else:
for i in range(len(s)-len(t)):
temp = 0
for j in range(len(t)):
if s[i+j]!=t[j]:
temp+=1
ans = min(ans, temp)
print(ans)
|
S = input()
T = input()
min_dist = 10**10
for i in range(len(S) - len(T) + 1):
for k in range(len(T)):
dist = 0
for s, t in zip(S[i:i + len(T)], T):
if s != t:
dist += 1
if dist >= min_dist:
break
min_dist = min(dist, min_dist)
if min_dist == 0:
print(0)
exit()
print(min_dist)
| 1 | 3,718,650,818,542 | null | 82 | 82 |
import math
n = int(input())
def koch(n, p1_x, p2_x, p1_y, p2_y):
if n == 0:
return
s_x = (2*p1_x + p2_x) / 3
s_y = (2*p1_y + p2_y) / 3
t_x = (p1_x + 2*p2_x) / 3
t_y = (p1_y + 2*p2_y) / 3
u_x = (t_x - s_x)/2 - (t_y - s_y) * math.sqrt(3)/2 + s_x
u_y = (t_x - s_x) * math.sqrt(3)/2 + (t_y - s_y)/2 + s_y
koch(n-1, p1_x, s_x, p1_y, s_y)
print (s_x, s_y)
koch(n-1, s_x, u_x, s_y, u_y)
print (u_x, u_y)
koch(n-1, u_x, t_x, u_y, t_y)
print (t_x, t_y)
koch(n-1, t_x, p2_x, t_y, p2_y)
p1_x = 0.0
p1_y = 0.0
p2_x = 100.0
p2_y = 0.0
print (p1_x, p1_y)
koch(n, 0, 100, 0, 0)
print (p2_x, p2_y)
|
def koch_curve(point1, point2, N):
if N == 0:
print('{:8f} {:8f}'.format(point1[0], point1[1]))
return
pointS = ((2 * point1[0] + point2[0]) / 3,
(2 * point1[1] + point2[1]) / 3)
pointT = ((point2[0] - point1[0]) / 2 - (point2[1] - point1[1]) / 3.46410161514 + point1[0],
(point2[0] - point1[0]) / 3.46410161514 + (point2[1] - point1[1]) / 2 + point1[1])
pointU = ((point1[0] + 2 * point2[0]) / 3,
(point1[1] + 2 * point2[1]) / 3)
if N > 1:
koch_curve(point1, pointS, N - 1)
koch_curve(pointS, pointT, N - 1)
koch_curve(pointT, pointU, N - 1)
koch_curve(pointU, point2, N - 1)
else:
print('{:8f} {:8f}'.format(point1[0], point1[1]))
print('{:8f} {:8f}'.format(pointS[0], pointS[1]))
print('{:8f} {:8f}'.format(pointT[0], pointT[1]))
print('{:8f} {:8f}'.format(pointU[0], pointU[1]))
N = int(input())
koch_curve((0.0, 0.0), (100.0, 0.0), N)
print('100.00000000 0.00000000')
| 1 | 128,771,492,928 | null | 27 | 27 |
N,K = map(int,input().split())
scores = list(map(int,input().split()))
for i in range(N-K):
#print(scores[K-K+i:K+i+1],scores[K-K + i],scores[K+i])
if scores[K-K + i ] >= scores[K+i]:
print("No")
else:
print("Yes")
|
from collections import defaultdict
from math import sqrt
def main():
n = int(input())
wi = 2
cnt = 0
d = defaultdict(lambda:0)
fi = int(sqrt(1e12)+1)
for i in range(2, fi):
while n % i == 0:
d[i] += 1
n //= i
if n != 1:
d[n] = 1
for val in d.values():
x = val
wi = 1
while(x >= wi):
x -= wi
wi += 1
cnt += 1
print(cnt)
if __name__ == "__main__":
main()
| 0 | null | 12,044,124,762,298 | 102 | 136 |
import math
import sys
readline = sys.stdin.readline
def main():
a, b, c = map(int, readline().rstrip().split())
print(c, a, b)
if __name__ == '__main__':
main()
|
bilding = [[[0 for x in range(10)] for x in range(3)]for x in range(4)]
n = int(input())
for k in range(n):
b, f, r, v = map(int, raw_input().split())
bilding[b-1][f-1][r-1] += v
for b in range(4):
for f in range(3):
print(" "+" ".join(map(str, bilding[b][f])))
if b < 3:
print("#"*20)
| 0 | null | 19,730,937,249,212 | 178 | 55 |
n = int(input())
A = list(map(int, input().split()))
ans = 10**18
total = sum(A)
acc = 0
for a in A:
acc += a
ans = min(ans, abs(total - acc * 2))
print(ans)
|
k, n = map(int, input().split())
a = list(map(int, input().split()))
max_kyori = 0
a.append(k + a[0])
for i in range(1, n+1):
kyori = a[i] - a[i-1]
if(kyori > max_kyori):
max_kyori = kyori
print(k - max_kyori)
| 0 | null | 93,080,610,313,570 | 276 | 186 |
import math
h,w=map(int,input().split())
if h==1 or w==1:
print(1)
elif (h*w)%2==0:
print(int((h*w)/2))
else:
print(math.ceil((h*w)/2))
|
H,W=map(int,input().split())
import math
A=[0,math.ceil(W/2)]
if (H-1)*(W-1)!=0:
c=W*math.floor(H/2)+A[H%2]
else:
c=1
print(c)
| 1 | 50,692,309,717,488 | null | 196 | 196 |
import sys
input = sys.stdin.readline
# B - An Odd Problem
N = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(N):
if i % 2 == 0:
if a[i] % 2 == 1:
ans += 1
print(ans)
|
N = int(input())
a = list(map(int, input().split()))
print(sum((i + 1) % 2 == 1 and a[i] % 2 == 1 for i in range(N)))
| 1 | 7,725,043,705,380 | null | 105 | 105 |
N, M, K = map(int, input().split())
MOD = 998244353
# 階乗 & 逆元計算
factorial = [1]
inverse = [1]
for i in range(1, N+2):
factorial.append(factorial[-1] * i % MOD)
inverse.append(pow(factorial[-1], MOD - 2, MOD))
# 組み合わせ計算
def nCr(n, r):
if n < r or r < 0:
return 0
elif r == 0:
return 1
return factorial[n] * inverse[r] * inverse[n - r] % MOD
ans = 0
for k in range(K + 1):
ans += M * nCr(N - 1, k) * pow(M - 1, N - 1 - k, MOD) % MOD
ans %= MOD
print(ans % MOD)
|
N, K = list(map(int, input().split()))
ans = 0
all_sum = N*(N+1)/2
mod = 10**9+7
for i in range(K,N+2):
min_val = i*(i-1)/2
max_val = N*(N+1)/2 - (N-i+1)*(N-i)/2
ans += (int(max_val) - int(min_val) + 1) % mod
# print(i, min_val, max_val)
print(ans%mod)
| 0 | null | 28,178,799,874,948 | 151 | 170 |
n=int(input())
ans=0
for i in range(1,50000+1):
z=i*1.08
if n<=z<(n+1):
ans=i
break
if ans==0:
print(":(")
else:
print(ans)
|
import sys
import time
import math
def inpl():
return list(map(int, input().split()))
st = time.perf_counter()
# ------------------------------
N = int(input())
ls = [0] * 50505
for i in range(len(ls)):
ls[i] = int(i * 1.08)
for i in range(N, 0, -1):
if ls[i] == N:
print(i)
sys.exit()
print(':(')
# ------------------------------
ed = time.perf_counter()
print('time:', ed-st, file=sys.stderr)
| 1 | 125,705,063,997,392 | null | 265 | 265 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.