code1
stringlengths 16
427k
| code2
stringlengths 16
427k
| similar
int64 0
1
| pair_id
int64 2
178,025B
⌀ | question_pair_id
float64 27.1M
177,113B
⌀ | code1_group
int64 1
297
| code2_group
int64 1
297
|
---|---|---|---|---|---|---|
#ALDS1_2-B Sort 1 - Selection Sort
def selectionSort(A,N):
c=0
for i in range(N):
minj = i
j=i
while j<N:
if(int(A[j])<int(A[minj])):
minj = j
j+=1
if(i!=minj):
A[i],A[minj]=A[minj],A[i]
c+=1
return c
N=int(input())
A=input().split()
c=selectionSort(A,N)
S=""
for i in range(N-1):
S+=A[i]+" "
S+=str(A[-1])
print(S)
print(c)
|
#coding: UTF-8
import sys
import math
class Algo:
@staticmethod
def insertionSort(r, n):
count = 0
for i in range(0,n):
minj = i
for j in range(i,n):
if r[j] < r[minj]:
minj = j
if r[i] != r[minj]:
r[i], r[minj] = r[minj], r[i]
count += 1
for i in range(0,n):
if i == n-1:
print(r[i])
else:
print(r[i], " ", sep="", end="")
print(count)
N = int(input())
R= list(map(int, input().split()))
Algo.insertionSort(R, N)
| 1 | 20,360,330,688 | null | 15 | 15 |
n,k=map(int,input().split())
H = list(map(int, input().split()))
if n <= k:
print('0')
exit()
H.sort()
H.reverse()
print(sum(H)-sum(H[0:k]))
|
N, K = map(int, input().split())
H = list(map(int, input().split()))
if N <= K:
print(0)
else:
H = sorted(H)
ans = 0
for i in range(N-K):
ans += H[i]
print(ans)
| 1 | 79,206,215,548,668 | null | 227 | 227 |
n,m=map(int,input().split())
num=[-1]*(n)
total=""
ans=-1
if n==1 and m==0:
print(0)
exit()
for i in range(m):
a,c=map(int,input().split())
if num[a-1]==-1 or num[a-1]==c:
num[a-1]=c
elif num[a-1]!=-1 and num[a-1]!=c:
print(ans)
exit()
for i in range(n):
if num[i]==-1:
if i==0:
num[i]=1
else:
num[i]=0
for i in range(n):
total+=str(num[i])
total=int(total)
total=str(total)
if len(total)==n:
ans=int(total)
print(ans)
|
import math
H = int(input())
W = int(input())
N = int(input())
for i in range(1, max(H, W)+1):
if(max(H, W)*i >= N):
print(i)
break
| 0 | null | 74,766,670,724,772 | 208 | 236 |
from sys import stdin
input = stdin.readline
def main():
N = int(input())
if N % 2:
print(0)
return
nz = 0
i = 1
while True:
if N//(5**i)//2 > 0:
nz += (N//(5**i)//2)
i += 1
else:
break
print(nz)
if(__name__ == '__main__'):
main()
|
N = int(input())
if N % 2 == 1:
print(0)
else:
rlt = 0
i = 10
while N // i > 0:
rlt += N // i
i *= 5
print(rlt)
| 1 | 115,872,049,880,522 | null | 258 | 258 |
A, B = map(int, input().split())
print(A * B) if len(str(A)) == 1 and len(str(B)) == 1 else print(-1)
|
num = []
ans = []
while True:
num = map(int,raw_input())
if num == list([0]):
break
ans.append(sum(num))
for i in range(len(ans)):
print ans[i]
| 0 | null | 79,702,555,800,960 | 286 | 62 |
n=int(input())
flag=0
for i in range(1,10):
if (n%i)==0:
if (n//i)<=9:
flag=1
break
if flag==1:
print ('Yes')
else:
print ('No')
|
N=int(input())
from collections import Counter
if max(Counter([int(x) for x in input().split()]).values())==1:
print("YES")
else:
print("NO")
| 0 | null | 117,192,073,278,688 | 287 | 222 |
D = int(input())
cs = list(map(int, input().split()))
ss = [input().split() for l in range(D)]
ts = [int(input()) for i in range(D)]
ans=0
all_cs=sum(cs)
cs_last=[0]*26
def c0(d):
mainas=0
for i in range(26):
#print(cs[i]*(d-cs_last[i]))
mainas-=cs[i]*(d-cs_last[i])
return mainas
for i in range(D):
cs_last[ts[i]-1]=i+1
ans+=int(ss[i][ts[i]-1])+c0(i+1)
print(ans)
|
N=int(input())
*A,=map(int, input().split())
B=[(i+1,a) for i,a in enumerate(A)]
from operator import itemgetter
B.sort(reverse=True, key=itemgetter(1))
dp = [[-1] * (N+1) for _ in range(N+1)]
dp[0][0] = 0
for i in range(1,N+1):
idx, act = B[i-1]
for j in range(i+1):
k = i-j
if 0<j: dp[j][k] = max(dp[j][k], dp[j-1][k] + act * abs(idx-j))
if 0<k: dp[j][k] = max(dp[j][k], dp[j][k-1] + act * abs(idx-(N-k+1)))
ans=0
for j in range(N+1):
ans = max(ans, dp[j][N-j])
print(ans)
| 0 | null | 21,856,425,389,178 | 114 | 171 |
import sys
rr = lambda: sys.stdin.readline().rstrip()
rs = lambda: sys.stdin.readline().split()
ri = lambda: int(sys.stdin.readline())
flag = False
s = rr()
q = ri()
front = ''
end = ''
for _ in range(q):
query = list(rs())
if query[0] == '1':
flag = not flag
continue
else:
f = int(query[1])
c = query[-1]
if flag == True:
if f == 1:
end += c
else:
front = c+front
else:
if f == 1:
front = c+front
else:
end += c
if flag:
print((front+s+end)[::-1])
else:
print(front+s+end)
|
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
from collections import deque
def main():
mod=10**9+7
S=input()
from collections import deque
dq=deque()
for c in S:
dq.appendleft(c)
rev=0
Q=I()
for _ in range(Q):
q=input().split()
if q[0]=="1":
rev=(rev+1)%2
else:
f=int(q[1])
c=q[2]
if (rev+f)%2==1:
dq.append(c)
else:
dq.appendleft(c)
ans=[]
if rev:
while dq:
ans.append(dq.popleft())
else:
while dq:
ans.append(dq.pop())
print(''.join(map(str, ans)))
main()
| 1 | 57,358,731,392,948 | null | 204 | 204 |
from collections import defaultdict
def dfs(here, connect, visited, answer):
global time
answer[here][1] = time
time += 1
visited[here] = 1
for c in connect[here]:
if not visited[c]:
dfs(c, connect, visited, answer)
answer[here][2] = time
time += 1
v_num = int(input())
connect = defaultdict(list)
for _ in range(v_num):
inp = [int(n) - 1 for n in input().split(" ")]
connect[inp[0]].extend(sorted(inp[2:]))
answer = [[n + 1 for m in range(3)] for n in range(v_num)]
time = 1
visited = [0 for n in range(v_num)]
for i in range(v_num):
if not visited[i]:
dfs(i, connect, visited, answer)
for v in range(v_num):
print(*answer[v])
|
s = input()
print('Yes') if s[2:3] == s[3:4] and s[4:5] == s[5:6] else print('No')
| 0 | null | 21,105,982,441,280 | 8 | 184 |
N, X, T = map(int, input().split())
print((N // X + bool(N % X))* T)
|
time = int(input())
if time != 0:
h = time // 3600
time = time % 3600
m = time // 60
s = time % 60
print(str(h) + ':' + str(m) + ':' + str(s))
else:
print('0:0:0')
| 0 | null | 2,251,225,832,128 | 86 | 37 |
N = int(input())
A = list(map(int, input().split()))
B = [0 for i in range(max(A)+1)]
for i in range(2, len(B)):
if B[i] != 0:
continue
for j in range(i, len(B), i):
B[j] = i
def func(X):
buf = set()
while X>1:
x = B[X]
buf.add(x)
while X%x==0:
X = X//x
#print(buf)
return buf
set1 = func(A[0])
set2 = func(A[0])
totallen = len(set1)
for a in A[1:]:
set3 = func(a)
totallen += len(set3)
#print(a, set1, set2)
set1 |= set3
set2 &= set3
#print(set1, set2, set3)
#print(totallen, set1, set2)
if len(set2)!=0:
print("not coprime")
elif len(set1)==totallen:
print("pairwise coprime")
else:
print("setwise coprime")
|
x,y,a,b,c = map(int,input().split())
R=list(map(int,input().split()) )
G=list(map(int,input().split()) )
W=list(map(int,input().split()) )
R.sort(reverse=True)
G.sort(reverse=True)
Z = W+R[0:x] + G[0:y]
Z.sort(reverse=True)
print(sum(Z[0:x+y]))
| 0 | null | 24,564,198,928,192 | 85 | 188 |
N=int(input())
A=list(map(int,input().split()))
SUM=sum(A)
Q=int(input())
List=[0 for _ in range(10**5+1)]
for a in A:
List[a]+=1
for q in range(Q):
B,C=map(int,input().split())
SUM-=B*List[B]
SUM+=C*List[B]
List[C]+=List[B]
List[B]=0
print(SUM)
|
def main():
N = int(input())
A = [int(a) for a in input().split(" ")]
S = sum(A)
cA = [0] * 1000001
for i in range(len(A)):
cA[A[i]] += 1
Q = int(input())
for i in range(Q):
B, C = [int(x) for x in input().split(" ")]
diff = (C-B)*cA[B]
S += diff
cA[C] += cA[B]
cA[B] = 0
print(S)
main()
| 1 | 12,211,049,321,212 | null | 122 | 122 |
import math
n = int(input())
print(360*n//math.gcd(360,n)//n)
|
a,b=map(int,input().split())
def gcd(x, y):
while y:
x, y = y, x % y
return x
l=gcd(a,b)
print(int(a*b/l))
| 0 | null | 63,012,111,456,700 | 125 | 256 |
while True:
n = int(input())
if n == 0:
break
s = list(map(int, input().split()))
m = sum(s) / n
b = 0
for i in range(n):
b += (s[i] - m) ** 2
ans = (b / n) ** 0.5
print(ans)
|
n = int(input())
print(max(0,((n-1)//2)))
| 0 | null | 77,037,830,814,982 | 31 | 283 |
import sys
Stack = []
def push(x):
Stack.append(x)
def pop():
Stack.pop(-1)
def cul(exp):
for val in exp:
if val in ["+", "-", "*"]:
a = int(Stack[-2])
b = int(Stack[-1])
if val == "+":
x = a + b
elif val == "-":
x = a - b
elif val == "*":
x = a * b
for i in range(2):
pop()
push(x)
else:
push(val)
return Stack[0]
if __name__ == "__main__":
exp = sys.stdin.read().strip().split(" ")
ans = cul(exp)
print ans
|
x,y = map(int,input().split())
ans = 'No'
for a in range(x+1):
b = x - a
if 2 * a + 4 * b == y:
ans = 'Yes'
print(ans)
| 0 | null | 6,875,836,289,110 | 18 | 127 |
from functools import reduce
n, a, b = map(int, input().split())
mod = 10**9 + 7
def f(A):
bunsi = reduce(lambda x, y: x*y%mod, range(n, n-A, -1))
bunbo = reduce(lambda x, y: x*y%mod, range(1, A+1))
return bunsi * pow(bunbo, mod-2, mod) % mod
ans = pow(2, n, mod) - f(a) -f(b) - 1
ans %= mod
print(ans)
|
a, b, k = map(int,input().split())
if a+b <= k:
print(0, 0)
elif a <= k:
num = k-a
b -= num
print(0, b)
else:
a = a - k
print(a, b)
| 0 | null | 85,249,222,710,790 | 214 | 249 |
a, b, c, d = map(int, input().split())
v1 = a * c
v2 = a * d
v3 = b * c
v4 = b * d
print(max(v1, v2, v3, v4))
|
a,b,c,d = map(int,input().split())
result = max(max(a*c,a*d),max(b*c,b*d))
print(result)
| 1 | 3,082,460,632,804 | null | 77 | 77 |
N = int(input())
As = list(map(int,input().split()))
Q = int(input())
count_array = [0]*(10**5+1)
for i in range(N):
count_array[As[i]] += 1
sum = 0
for i in range(len(As)):
sum += As[i]
for i in range(Q):
x,y = map(int,input().split())
sum += count_array[x]*(y-x)
print(sum)
count_array[y] += count_array[x]
count_array[x] = 0
|
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
# 値がiであるようなA_iの個数を格納する
val_count = [0] * (10 ** 5 + 1)
total_A = 0
for a in A:
total_A += a
val_count[a] += 1
S = []
for i in range(Q):
B, C = map(int, input().split())
B_count = val_count[B]
total_A -= B * B_count
total_A += C * B_count
S.append(total_A)
val_count[B] = 0
val_count[C] += B_count
for s in S:
print(s)
| 1 | 12,147,013,825,490 | null | 122 | 122 |
def main():
N = int(input())
total = 0
for i in range(N):
i = i + 1
if i % 3 == 0 and i % 5 == 0:
continue
elif i % 3 == 0:
continue
elif i % 5 == 0:
continue
total = total + i
print(total)
main()
|
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def pre(s):
n = len(s)
pi = [0] * n
for i in range(1, n):
j = pi[i - 1]
while j and s[i] != s[j]:
j = pi[j - 1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
def prod(a):
ans = 1
for each in a:
ans = (ans * each)
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
#n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
h, w, k = map(int, input().split())
a = []
for __ in range(h):
a += [[k for k in input()]]
ans = 0
for ch1 in range(2**h):
for ch2 in range(2**w):
rowchosen = binary(ch1, h)
colchosen = binary(ch2, w)
count = 0
for i in range(h):
for j in range(w):
if rowchosen[i] != '1' and colchosen[j] != '1' and a[i][j] == '#':
count += 1
if count == k:ans+=1
print(ans)
| 0 | null | 21,993,793,411,360 | 173 | 110 |
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
MAX = 2 * 10**6 + 10
MOD = 10**9+7
fac = [1] * MAX
f_inv = [1] * MAX
def prepare(n, mod):
for i in range(1, n+1):
fac[i] = (fac[i-1] * i) % mod
f_inv[n] = pow(fac[n], -1, MOD)
for i in range(n-1, 0, -1):
f_inv[i] = (f_inv[i+1] * (i+1)) % MOD
def modcmb(n, r, mod):
if n < 0 or r < 0:
return 0
if r > n:
return 0
return fac[n] * f_inv[r] * f_inv[n-r] % mod
def main():
K = int(readline())
S = readline().strip()
N = len(S)
prepare(N + K + 5, MOD)
inv26 = pow(26, -1, MOD)
pow26 = pow(26, K, MOD)
pow25 = 1
ans = 0
for i in range(K+1):
ans += (modcmb(N-1+i, i, MOD) * pow25 * pow26) % MOD
ans %= MOD
pow25 *= 25
pow25 %= MOD
pow26 *= inv26
pow26 %= MOD
print(ans)
if __name__ == "__main__":
main()
|
def modpow(x, n, p):
res = 1
while n > 0:
if n & 1:
res = res * x % p
x = x * x % p
n >>= 1
return res
MOD = pow(10, 9) + 7
k = int(input())
s = input()
n = len(s)
fact = [1 for _ in range(n + k + 1)]
p25 = [1 for _ in range(n + k + 1)]
for i in range(1, n + k + 1):
fact[i] = fact[i - 1] * i % MOD
p25[i] = p25[i - 1] * 25 % MOD
inv = [1 for _ in range(n + k + 1)]
inv[n + k] = modpow(fact[n + k], MOD - 2, MOD)
for i in range(n + k - 1, -1, -1):
inv[i] = inv[i + 1] * (i + 1) % MOD
ans = modpow(26, n + k, MOD)
for i in range(n):
ans -= fact[n + k] * inv[i] % MOD * inv[n + k - i] % MOD * p25[n + k - i] % MOD
if ans < 0:
ans += MOD
print(ans)
| 1 | 12,921,720,518,500 | null | 124 | 124 |
word = input()
print(str.swapcase(word))
|
import sys
input()
rl = sys.stdin.readlines()
d = {}
for i in rl:
#c, s = i.split()
if i[0] == 'i':
#if c[0] == 'i':
d[i[7:]] = 0
#d[s] = 0
else:
if i[5:] in d:
#if s in d:
print('yes')
else:
print('no')
| 0 | null | 806,570,505,568 | 61 | 23 |
n=int(input())
a=list(map(int,input().split()))
ans=0
for i in range(n):
minj=i
for j in range(i,n):
if a[j]<a[minj]:
j,minj=minj,j
if i!=minj:
a[i],a[minj]=a[minj],a[i]
ans+=1
print(' '.join(map(str,a)))
print(ans)
|
print('Yes') if len(set(input().split()))==1 else print('No')
| 0 | null | 41,460,302,367,750 | 15 | 231 |
from collections import deque
n = int(input())
que = deque()
for _ in range(n):
cmd = input()
if cmd == 'deleteFirst':
try:
que.popleft()
except:
pass
elif cmd == 'deleteLast':
try:
que.pop()
except:
pass
else:
cmd, x = cmd.split()
if cmd == 'insert':
que.appendleft(x)
elif cmd == 'delete':
try:
que.remove(x)
except:
pass
print(*que)
|
from sys import stdin
class DList:
class Cell:
def __init__(self, k):
self.key = k
self.prev = None
self.next = None
def __init__(self):
self.head = DList.Cell(None)
self.last = DList.Cell(None)
self.head.next = self.last
self.last.prev = self.head
def insert(self, x):
c = DList.Cell(x)
c.prev = self.head
c.next = self.head.next
c.next.prev = c
self.head.next = c
def delete(self, x):
c = self.__find(x)
if c != None:
self.__delete(c)
def __delete(self, c):
c.prev.next = c.next
c.next.prev = c.prev
def __find(self, x):
c = self.head.next
while c != None and c.key != x:
c = c.next
return c
def deleteFirst(self):
self.__delete(self.head.next)
def deleteLast(self):
self.__delete(self.last.prev)
def __iter__(self):
self.it = self.head.next
return self
def __next__(self):
if self.it == self.last:
raise StopIteration
k = self.it.key
self.it = self.it.next
return k
dlist = DList()
n = int(stdin.readline())
for i in range(n):
cmd = stdin.readline()
if cmd.startswith('insert'):
dlist.insert(cmd[7:-1])
elif cmd.startswith('deleteFirst'):
dlist.deleteFirst()
elif cmd.startswith('deleteLast'):
dlist.deleteLast()
elif cmd.startswith('delete'):
dlist.delete(cmd[7:-1])
print(' '.join(dlist))
| 1 | 49,975,384,848 | null | 20 | 20 |
x,y=map(int,input().split())
k=[1,2,3]
l=[0,300000,200000,100000]
p=0
if x in k:
p+=l[x]
if y in k:
p+=l[y]
if x==1 and y==1:
p+=400000
print(p)
|
import math
def lcm(a,b):
return (a*b)//math.gcd(a,b)
def co(num):
return format(num, 'b')[::-1].find('1')
N,M=map(int,input().split())
L=list(map(int,input().split()))
L2=[co(i) for i in L]
if len(set(L2))!=1:
print(0)
exit()
L=[i//2 for i in L]
s=L[0]
for i in range(N):
s=lcm(s,L[i])
c=M//s
print((c+1)//2)
| 0 | null | 121,876,713,048,740 | 275 | 247 |
x,n= map(int,input().split())
p = list(map(int,input().split()))
ans,i = 0,0
while True:
if x-i not in p:
ans = x-i
break
if x+i not in p:
ans = x+i
break
i = i+1
print(ans)
|
X, N = map(int, input().split())
P = list(map(int, input().split()))
st = set(P)
for i in range(111):
if not X - i in st:
print(X - i)
exit(0)
if not X + i in st:
print(X + i)
exit(0)
| 1 | 14,107,337,452,052 | null | 128 | 128 |
a, b, c, d = map(int, input().split())
x_li = [a, b]
y_li = [c, d]
my_list = []
for x in x_li:
for y in y_li:
my_list.append(x * y)
print(max(my_list))
|
while True:
(H,W) = [int(x) for x in input().split()]
if H == W == 0:
break
for hc in range(H):
print('#'*W)
print()
| 0 | null | 1,911,623,657,632 | 77 | 49 |
import sys
from collections import Counter
from itertools import combinations
def input():
return sys.stdin.readline().strip()
sys.setrecursionlimit(20000000)
MOD = 10 ** 9 + 7
INF = float("inf")
def main():
N = int(input())
L = list(map(int, input().split()))
count = Counter(L)
key = count.keys()
set_list = combinations(key, 3)
answer = 0
for s in set_list:
a = s[0]
b = s[1]
c = s[2]
if (a + b) > c and (b + c) > a and (c + a) > b:
answer += count[a] * count[b] * count[c]
print(answer)
if __name__ == "__main__":
main()
|
import itertools
def is_triangle(list_L):
if (list_L[0] + list_L[1] > list_L[2]) and (list_L[1] + list_L[2] > list_L[0]) and (list_L[2] + list_L[0] > list_L[1]) :
return True
else :
return False
def is_uniqueL(list_L):
return len(list_L) == len(set(list_L))
N = int(input())
L = map(int,input().split())
comb_L = list(itertools.combinations(L, 3))
sum = 0
for a_comb_L in comb_L :
if is_uniqueL(a_comb_L) == True and is_triangle(a_comb_L) == True:
sum += 1
print(sum)
| 1 | 5,045,416,737,572 | null | 91 | 91 |
i=input;i();l=i().split();x=1-('0'in l)
for j in l:
x*=int(j)
if x>1e18:
print(-1);quit()
print(x)
|
#template
def inputlist(): return [int(j) for j in input().split()]
#template
N = int(input())
A = inputlist()
A.sort()
ans = 1
if A[0] == 0:
print(0)
exit()
for i in range(N):
ans *= A[i]
if ans > 10**18:
print(-1)
exit()
print(ans)
| 1 | 16,151,807,911,862 | null | 134 | 134 |
while(True):
h,w = [int(i) for i in input().split()]
if h == 0 and w == 0:
break
for i in range(h):
out = ''
for j in range(w):
if j == 0 or j == (w-1) or i == 0 or i == (h-1):
out += '#'
else :
out += '.'
print(out)
print('')
|
import itertools
n = int(input())
A = list(map(int,input().split()))
q = int(input())
M = list(map(int,input().split()))
dp = []
for i in itertools.product([0, 1], repeat=n):
tmp = 0
for j in range(n):
tmp += A[j] * i[j]
dp.append(tmp)
for i in M:
if i in dp:
print('yes')
else:print('no')
| 0 | null | 455,457,001,508 | 50 | 25 |
x = int(input())
n = 120
for i in range(n):
for j in range(i):
if x == i**5-j**5:
print(i,j)
exit(0)
if x == i**5+j**5:
print(i,-j)
exit(0)
|
#import math
import collections
n, m = map(int, input().split( ))
lis = [[] for _ in range(n+1)]
for _ in range(m):
a,b = map(int, input().split( ))
lis[a].append(b)
lis[b].append(a)
#print(lis)
ans = [0]*(n+1)
q = collections.deque()
q.append(1)
count = [0]*(n+1)
#1の時は動かない
count[1] = 1
while len(q) != 0:
v = q.popleft()
# print(lis[v], count)
#まずは1につながっている部屋を探索その後順に探索
for u in lis[v]:
if count[u] == 0:
count[u] = 1
ans[u] = v
q.append(u)
print('Yes')
for i in range(2,n+1):
print(ans[i])
| 0 | null | 23,080,093,961,800 | 156 | 145 |
from random import randint, random, seed
from math import exp
import sys
input = sys.stdin.buffer.readline
INF = 9223372036854775808
T0 = 1480.877007252879
T1 = 2.43125135
def calc_score(D, C, S, T):
"""
開催日程Tを受け取ってそこまでのスコアを返す
コンテストi 0-indexed
d 0-indexed
"""
score = 0
last = [0]*26 # コンテストiを前回開催した日
for d, t in enumerate(T):
last[t] = d + 1
for i in range(26):
score -= (d + 1 - last[i]) * C[i]
score += S[d][t]
return score
def update_score(D, C, S, T, score, ct, ci):
"""
ct日目のコンテストをコンテストciに変更する
スコアを差分更新する
ct: change t 変更日 0-indexed
ci: change i 変更コンテスト 0-indexed
"""
new_score = score
last = [0]*26 # コンテストiを前回開催した日
prei = T[ct] # 変更前に開催する予定だったコンテストi
for d, t in enumerate(T, start=1):
last[t] = d
new_score += (d - last[prei])*C[prei]
new_score += (d - last[ci])*C[ci]
last = [0]*26
for d, t in enumerate(T, start=1):
if d-1 == ct:
last[ci] = d
else:
last[t] = d
new_score -= (d - last[prei])*C[prei]
new_score -= (d - last[ci])*C[ci]
new_score -= S[ct][prei]
new_score += S[ct][ci]
return new_score
def evaluate(D, C, S, T, k):
"""
d日目終了時点での満足度を計算し,
d + k日目終了時点での満足度の減少も考慮する
"""
score = 0
last = [0]*26
for d, t in enumerate(T):
last[t] = d + 1
for i in range(26):
score -= (d + 1 - last[i]) * C[i]
score += S[d][t]
for d in range(len(T), min(len(T) + k, D)):
for i in range(26):
score -= (d + 1 - last[i]) * C[i]
return score
def greedy(D, C, S):
Ts = []
for k in range(5, 13):
T = [] # 0-indexed
max_score = -INF
for d in range(D):
# d+k日目終了時点で満足度が一番高くなるようなコンテストiを開催する
max_score = -INF
best_i = 0
for i in range(26):
T.append(i)
score = evaluate(D, C, S, T, k)
if max_score < score:
max_score = score
best_i = i
T.pop()
T.append(best_i)
Ts.append((max_score, T))
return max(Ts, key=lambda pair: pair[0])
def local_search(D, C, S, score, T):
# sTime = time()
# TL = 1.8
Temp = T0
# cnt = 0
t = 0
best_score = score
best_T = T.copy()
for cnt in range(70000):
if cnt % 100 == 0:
t = cnt / (140000 - 1)
Temp = pow(T0, 1-t) * pow(T1, t)
sel = randint(1, 100)
lim = random()
if sel != 1:
# ct 日目のコンテストをciに変更
ct = randint(0, D-1)
ci = randint(0, 25)
new_score = update_score(D, C, S, T, score, ct, ci)
if score < new_score or \
(lim < exp((new_score - score)/Temp)):
T[ct] = ci
score = new_score
else:
# ct1 日目と ct2 日目のコンテストをswap
ct1 = randint(0, D-1)
ct2 = randint(0, D-1)
ci1 = T[ct1]
ci2 = T[ct2]
new_score = update_score(D, C, S, T, score, ct1, ci2)
new_score = update_score(D, C, S, T, new_score, ct2, ci1)
if score < new_score or \
(lim < exp((new_score - score)/Temp)):
score = new_score
T[ct1] = ci2
T[ct2] = ci1
if best_score < score:
best_score = score
best_T = T.copy()
# cnt += 1
return best_T
if __name__ == '__main__':
seed(20)
D = int(input())
C = [int(i) for i in input().split()]
S = [[int(i) for i in input().split()] for j in range(D)]
init_score, T = greedy(D, C, S)
T = local_search(D, C, S, init_score, T)
for t in T:
print(t+1)
|
D = int(input())
C = [int(T) for T in input().split()]
S = [[] for TD in range(0,D)]
for TD in range(0,D):
S[TD] = [int(T) for T in input().split()]
for TD in range(0,D):
print(S[TD].index(max(S[TD]))+1)
| 1 | 9,616,063,888,608 | null | 113 | 113 |
from sys import stdin,stdout
from collections import defaultdict
import sys
sys.setrecursionlimit(10**7)
def dfs1(src):
global steps
if steps==rem:return src
steps+=1
return dfs1(g[src][0])
def dfs(src):
global steps,done,boc,nic
vis[src]=1
steps+=1
if steps-1==k:
print(src)
exit(0)
dfn[src]=steps
for neigh in g[src]:
if not vis[neigh]:dfs(neigh)
else:
boc,done,nic=[neigh,steps,steps-dfn[neigh]+1]
# print(done,boc,nic)
return
n,k=list(map(int,stdin.readline().split()))
done,boc,nic=0,0,0
a=list(map(int,stdin.readline().split()))
g=defaultdict(list)
for i in range(1,n+1):
g[i]+=[a[i-1]]
vis=[0]*(n+1)
dfn=[0]*(1+n)
steps=0
dfs(1)
# print(done,boc,nic)
left=k-done
rem=(left%nic)
if rem==0:rem=nic
steps=1
print(dfs1(g[boc][0]))
|
a, b = input().split(" ")
x = int(a)
y = int(b)
amt = 0
if x == 1:
amt += 300000
elif x == 2:
amt += 200000
elif x == 3:
amt += 100000
if y == 1:
amt += 300000
elif y == 2:
amt += 200000
elif y == 3:
amt += 100000
if x == 1 and y == 1:
amt += 400000
print (amt)
| 0 | null | 81,971,030,419,090 | 150 | 275 |
n=int(input())
a=[]
for i in range(1,n+1):
if not(i%3==0 or i%5==0):
a.append(i)
print(sum(a))
|
A,B = map(int,input().split())
C = A*B
print(str(C))
| 0 | null | 25,178,208,066,780 | 173 | 133 |
import math
n = int(input())
mod = 1000000007
ab = [list(map(int,input().split())) for _ in range(n)]
dic = {}
z = 0
nz,zn = 0,0
for a,b in ab:
if a == 0 and b == 0:
z += 1
continue
elif a == 0:
zn += 1
continue
elif b == 0:
nz += 1
if a< 0:
a = -a
b = -b
g = math.gcd(a,b)
tp = (a//g,b//g)
if tp not in dic:
dic[tp] = 1
else:
dic[tp] += 1
ans = 1
nn = n - z - zn - nz
for tp,v in dic.items():
if v == 0:
continue
vt = (tp[1],-1*tp[0])
if vt in dic:
w = dic[vt]
#print(tp)
e = pow(2,v,mod) + pow(2,w,mod) - 1
ans *= e
ans %= mod
nn -= v + w
dic[tp] = 0
dic[vt] = 0
ans *= pow(2,nn,mod)
if zn == 0:
ans *= pow(2,nz,mod)
elif nz == 0:
ans *= pow(2,zn,mod)
else:
ans *= pow(2,nz,mod) + pow(2,zn,mod) - 1
ans += z - 1
print(ans%mod)
#print(dic)
|
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
p = 10**9+7
from math import gcd
from collections import Counter
from collections import defaultdict
used = defaultdict(list)
n = int(input())
ctr = Counter()
az = bz = zz = 0
for i in range(n):
a, b = map(int, input().split())
if a==b==0:
zz+=1
elif a==0:
az+=1
elif b==0:
bz+=1
else:
g = gcd(a,b)
a,b = a//g, b//g
if b < 0:
a*=-1
b*=-1
ctr[(a,b)]+=1
used[(a,b)]=False
ans = 1
# 仲の悪いグループ対ごとに処理する
for (a1,b1),v1 in ctr.items():
if used[(a1,b1)]:
continue
a2,b2=-b1,a1
if b2 < 0:
b2*=-1
a2*=-1
v2 = ctr[(a2,b2)]
r = (pow(2,v1,p)+pow(2,v2,p)-1)%p
ans*=r
ans%=p
used[(a1,b1)]=True
used[(a2,b2)]=True
# 片方が0のクループ対
r = (pow(2,az,p)+pow(2,bz,p)-1)%p
ans*=r
ans%=p
ans+=zz # 0匹のケースは禁止されている
ans-=1 # 0匹のケースは禁止されている
ans%=p
print(ans)
| 1 | 21,025,823,211,470 | null | 146 | 146 |
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
n,x,y = map(int, input().split())
ans = [0] * n
for i in range(1, n + 1):
for j in range(1 + i, n + 1):
a = abs(i - x) + abs(j - y) + 1
b = abs(i - j)
c = min(a, b)
ans[c] += 1
for i in range(1, n):
print(ans[i])
|
n, x, y = map(int, input().split())
graph = [[] for _ in range(n)]
for i in range(n):
if i+1 < n:
graph[i].append(i+1)
if i-1 >=0:
graph[i].append(i-1)
graph[x-1].append(y-1)
graph[y-1].append(x-1)
ans = [0] * (n-1)
from collections import deque
for i in range(n):
dist = [-1] * n
dist[i] = 0
d = deque()
d.append(i)
while d:
v = d.popleft()
for j in graph[v]:
if dist[j] != -1:
continue
dist[j] = dist[v] + 1
ans[dist[j] - 1] += 1
d.append(j)
for a in ans:
print(a//2)
| 1 | 44,031,179,166,238 | null | 187 | 187 |
s = input()
for i in range(int(input())):
cmd = input().split()
a, b = int(cmd[1]), int(cmd[2])
if cmd[0] == 'print':
print(s[a:b+1])
elif cmd[0] == 'reverse':
s = s[:a] + s[a:b+1][::-1] + s[b+1:]
elif cmd[0] == 'replace':
s = s[:a] + cmd[3] + s[b+1:]
|
import sys
from fractions import gcd
[print("{} {}".format(gcd(*x), x[0] * x[1] // gcd(*x))) for x in [list(map(int, x.split())) for x in sys.stdin]]
| 0 | null | 1,029,694,859,200 | 68 | 5 |
N = int(input())
A = input().split()
ans = 1
zero_count = A.count("0")
if zero_count != 0:
print(0)
else:
for i in range(N):
ans *= int(A[i])
if ans > 10**18:
ans = -1
break
print(ans)
|
N =int(input())
A = sorted(list(map(int,input().split())))
B = 1
C = 10 ** 18
for i in range(N):
B = B * A[i]
if B == 0:
break
elif B > C:
B = -1
break
print(B)
| 1 | 16,198,930,003,670 | null | 134 | 134 |
from collections import deque
import sys
def bfs(graph, N, start):
visited = [0] * N
visited[start] = 1
que = deque([start])
while que:
node = que.popleft()
for n in graph[node]:
if not visited[n]:
visited[n] = node + 1
que.append(n)
return visited
input = sys.stdin.readline
def main():
N, M = map(int, input().split())
graph = [[] for _ in range(N)]
for i in range(M):
A, B = map(lambda n: int(n) - 1, input().split())
graph[A].append(B)
graph[B].append(A)
visited = bfs(graph, N, 0)[1:]
if all(visited):
print("Yes")
print(*visited, sep="\n")
else:
print("No")
main()
|
from collections import deque
N,M=map(int,input().split())
C=[[] for i in range(N+1)]
for i in range(M):
A,B=sorted(list(map(int,input().split())))
C[A].append(B)
C[B].append(A)
d=[-1]*(N+1)
d[0]=0
d[1]=0
queue=deque([1])
while queue:
now = queue.popleft()
for i in C[now]:
if d[i]!=-1:continue
d[i]=now
queue.append(i)
if d.count(0)>2:print('No');exit
print('Yes')
for i in range(2,N+1):
print(d[i])
| 1 | 20,433,811,379,310 | null | 145 | 145 |
al = 'abcdefghijklmnopqrstuvwxyz'
text = ''
while True:
try:
text += input().lower()
except EOFError:
break
for i in al:
print('{} : {}'.format(i, text.count(i)))
|
import sys
from collections import Counter
S = ""
for s in sys.stdin:
s = s.strip().lower()
if not s:
break
S += s
for i in 'abcdefghijklmnopqrstuvwxyz':
print(i, ":", S.count(i))
| 1 | 1,684,075,007,300 | null | 63 | 63 |
n,x,m = map(int, input().split())
#xに何番目にきたかを記録していく。-1じゃなければ一回以上きている
table = [-1] * m
extra = []
l = 0
total = 0
#table[x]は周期が始まる点
while table[x] == -1:
extra.append(x)
table[x] = l
l += 1
total += x
x = (x*x) % m
#周期の長さ
c = l - table[x]
#周期の和
s = 0
for i in range(table[x], l):
s += extra[i]
ans = 0
#周期がnより長い場合
if n <= l:
for i in range(n):
ans += extra[i]
else:
#最初の一週目を足す
ans += total
n -= l
#残りの周期の周の和を足す
ans += s*(n//c)
n %= c
for i in range(n):
ans += extra[table[x]+i]
print(ans)
|
S = input()
T = input()
ans = len(T)
for i in range(len(S)-len(T)+1):
count = 0
#print(S[i:i+len(T)], T)
for s, t in zip(S[i:i+len(T)], T):
if s != t:
count += 1
ans = min(count, ans)
print(ans)
| 0 | null | 3,293,503,341,284 | 75 | 82 |
import sys
while True :
h,w = map(int,raw_input().split())
if h==0 and w==0 :
break
else :
for i in range(h):
if i%2:
for j in range(w):
if j%2:
if j==w-1:
sys.stdout.write('#\n')
else :
sys.stdout.write('#')
else :
if j==w-1:
sys.stdout.write('.\n')
else :
sys.stdout.write('.')
else :
for j in range(w):
if j%2 :
if j==w-1:
sys.stdout.write('.\n')
else :
sys.stdout.write('.')
else :
if j==w-1:
sys.stdout.write('#\n')
else :
sys.stdout.write('#')
print''
|
while True:
H, W = map(int, input().split())
if (H == W == 0):
break
else:
for j in range(H):
if (j % 2 == 0):
for i in range(W):
if(i % 2 == 0):
print("#", end='')
else:
print(".", end='')
else:
for f in range(W):
if(f % 2 == 0):
print(".", end='')
else:
print("#", end='')
print()
print()
| 1 | 868,972,972,700 | null | 51 | 51 |
n,k = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
print(sum(sorted(arr)[::-1][k:]))
|
N,K = map(int,input().split())
H = list(map(int,input().split()))
H.sort()
reversed(H)
for i in range(K):
if len(H)==0:
break
else:
H.pop()
if len(H)==0:
print(0)
else:
print(sum(H))
| 1 | 79,481,689,218,812 | null | 227 | 227 |
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"
s = [int(i) for i in s.split(",")]
print(s[int(input())-1])
|
suuretsu = [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]
number = int(input(''))
print(suuretsu[number - 1])
| 1 | 50,040,148,859,392 | null | 195 | 195 |
n, k = map(int, input().split()); m = 998244353; a = []
for i in range(k): a.append(list(map(int, input().split())))
b = [0]*n; b.append(1); c = [0]*n; c.append(1)
for i in range(1, n):
d = 0
for j in range(k): d = (d+c[n+i-a[j][0]]-c[n+i-a[j][1]-1])%m
b.append(d); c.append(c[-1]+d)
print(b[-1]%m)
|
# 解説を見て解き直し
N, K = [int(x) for x in input().split()]
ranges = [tuple(int(x) for x in input().split()) for _ in range(K)]
ranges.sort()
p = 998244353
dp = [0] * (N + 1)
dpsum = [0] * (N + 1)
dp[1] = 1
dpsum[1] = 1
for i in range(2, N + 1):
for l, r in ranges:
rj = i - l
lj = max(1, i - r) # 1以上
if rj <= 0: continue
dp[i] += dpsum[rj] - dpsum[lj - 1]
dp[i] %= p
dpsum[i] = dpsum[i - 1] + dp[i]
dpsum[i] %= p
print(dp[N])
| 1 | 2,724,607,049,180 | null | 74 | 74 |
n = int(input())
for i in range(1000):
for j in range(-1000,1000):
if (i**5-j**5)==n:
print(i,j)
exit()
|
H, W = map(int, input().split())
if H == 1 or W == 1:
print(1)
elif H % 2 == 0:
print(H*W//2)
else:
if W % 2 == 0:
print(H*W//2)
else:
print((H//2)*(W//2) + (H//2+1)*(W//2+1))
| 0 | null | 38,389,070,050,842 | 156 | 196 |
import sys
sys.setrecursionlimit(300000)
def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI0(): return map(lambda s: int(s) - 1, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
def LMI0(): return list(map(lambda s: int(s) - 1, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')
N = I()
A = LMI()
ans = 0
for i, a in enumerate(A):
if i % 2 == 0 and a % 2 != 0:
ans += 1
print(ans)
|
a=raw_input()
debt = 100000
for i in range(int(a)):
debt += debt/20
b=debt%1000
if b > 0:
debt += 1000-b
print debt
| 0 | null | 3,925,565,275,608 | 105 | 6 |
N = int(input())
a = list(map(int,input().split()))
aset = set(a)
if 1 not in aset:
print(-1)
else:
nex = 1
counter = 0
for i in range(N):
if a[i] == nex:
nex += 1
else:
counter += 1
print(counter)
|
def solve():
N = int(input())
A = list(map(int, input().split()))
ans = 0
p = 1
for a in A:
if a==p:
p += 1
else:
ans += 1
if p==1:
ans = -1
return ans
print(solve())
| 1 | 114,695,559,506,878 | null | 257 | 257 |
inData = int(input())
inSeries = [int(i) for i in input().split()]
outData =[0]*inData
for i in range(inData):
outData[i] = inSeries[inData-1-i]
print(" ".join(map(str,outData)))
|
s = []
p = []
a = i = 0
for c in input():
if c == "\\":
s += [i]
elif c == "/" and s:
j = s.pop()
t = i-j
a += t
while p and p[-1][0] > j:
t += p[-1][1]
p.pop()
p += [(j,t)]
i += 1
print(a)
if p:
print(len(p),*list(zip(*p))[1])
else:
print(0)
| 0 | null | 513,234,635,172 | 53 | 21 |
class ModInt:
def __init__(self, x):
self.x = x % MOD
def __str__(self):
return str(self.x)
__repr__ = __str__
def __add__(self, other):
return (
ModInt(self.x + other.x) if isinstance(other, ModInt) else
ModInt(self.x + other)
)
def __sub__(self, other):
return (
ModInt(self.x - other.x) if isinstance(other, ModInt) else
ModInt(self.x - other)
)
def __mul__(self, other):
return (
ModInt(self.x * other.x) if isinstance(other, ModInt) else
ModInt(self.x * other)
)
def __truediv__(self, other):
return (
ModInt(
self.x * pow(other.x, MOD - 2, MOD)
) if isinstance(other, ModInt) else
ModInt(self.x * pow(other, MOD - 2, MOD))
)
def __pow__(self, other):
return (
ModInt(self.power_func(self.x, other.x, MOD)) if isinstance(other, ModInt) else
ModInt(self.power_func(self.x, other, MOD))
)
__radd__ = __add__
def __rsub__(self, other):
return (
ModInt(other.x - self.x) if isinstance(other, ModInt) else
ModInt(other - self.x)
)
__rmul__ = __mul__
def __rtruediv__(self, other):
return (
ModInt(
other.x * pow(self.x, MOD - 2, MOD)
) if isinstance(other, ModInt) else
ModInt(other * pow(self.x, MOD - 2, MOD))
)
def __rpow__(self, other):
return (
ModInt(pow(other.x, self.x, MOD)) if isinstance(other, ModInt) else
ModInt(pow(other, self.x, MOD))
)
def power_func(self,a,n,p):
bi=str(format(n,"b"))#2進表現に
res=1
for i in range(len(bi)):
res=(res*res) %p
if bi[i]=="1":
res=(res*a) %p
return res
#グローバル変数MODを決めてあげてください
#グローバル変数MODを決めてあげてください
MOD = 10**9 + 7
N,K=[int(hoge) for hoge in input().split()]
Kazus = [0]*(K+1)
for x in range(K,0,-1):
Dmax = K//x
MoDmax = ModInt(Dmax)
kazu = MoDmax ** N
for d in range(Dmax,1,-1):
kazu -= Kazus[d*x]
Kazus[x] = kazu
print(sum([x*k for x,k in enumerate(Kazus) ]))
|
import math
N,K= map(int, input().split())
a=[0]*(K+1)
co=0
mod=(10**9+7)
for i in range(K,0,-1):
b=K//i
t=2*i
m=0
while t<=K:
m=m+a[t]
t+=i
c=pow(b,N,mod)
a[i]=c-m
co+=(a[i]*i)%mod
print(co%mod)
| 1 | 36,801,892,649,942 | null | 176 | 176 |
from itertools import product
H, W, K = map(int, input().split())
choco = [list(input()) for _ in range(H)]
def cnt(array):
count = [0] * H
split_cnt = 0
for w in range(W):
for h in range(H):
if choco[h][w] == "1":
count[array[h]] += 1
if any(i > K for i in count):
split_cnt += 1
count = [0] * H
for h in range(H):
if choco[h][w] == "1":
count[array[h]] += 1
if any(i > K for i in count):
return 10 ** 20
return split_cnt
def get_array(array):
l = len(array)
ret = [0] * l
for i in range(1, l):
ret[i] = ret[i-1] + array[i]
return ret
ans = 10 ** 20
for p in product(range(2), repeat=H-1):
p = get_array([0]+list(p))
ans = min(ans, cnt(p)+max(p))
print(ans)
|
S = input()
if S == 'ABC': print('ARC')
elif S == 'ARC': print('ABC')
| 0 | null | 36,294,381,143,680 | 193 | 153 |
def main():
import sys
def input(): return sys.stdin.readline().rstrip()
k = int(input())
s = input()
n = len(s)
mod = 10**9+7
p25 = [0]*(k+1)
p26 = [0]*(k+1)
c = [0]*(k+1)
p25[0], p26[0] = 1, 1
c[0]= 1
for i in range(1, k+1):
p25[i] = p25[i-1]*25
p25[i] %= mod
p26[i] = p26[i-1]*26
p26[i] %= mod
c[i] = (n+i-1)*c[i-1]
c[i] *= pow(i, mod-2, mod)
c[i] %= mod
p25.reverse()
c.reverse()
ans = 0
for i in range(k+1):
tmp = p25[i]*p26[i]*c[i]
tmp %= mod
ans += tmp
ans %= mod
print(ans)
if __name__ == '__main__':
main()
|
h = int(input())
w = int(input())
n = int(input())
if n % max(h, w) == 0:
print(int(n//max(h, w)))
else:
print(int(n//max(h, w))+1)
| 0 | null | 50,569,930,242,216 | 124 | 236 |
import bisect
import collections
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7
kaijo_memo = []
def kaijo(n):
if(len(kaijo_memo) > n):
return kaijo_memo[n]
if(len(kaijo_memo) == 0):
kaijo_memo.append(1)
while(len(kaijo_memo) <= n):
kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
return kaijo_memo[n]
gyaku_kaijo_memo = []
def gyaku_kaijo(n):
if(len(gyaku_kaijo_memo) > n):
return gyaku_kaijo_memo[n]
if(len(gyaku_kaijo_memo) == 0):
gyaku_kaijo_memo.append(1)
while(len(gyaku_kaijo_memo) <= n):
gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
return gyaku_kaijo_memo[n]
def nCr(n,r):
if(n == r):
return 1
if(n < r or r < 0):
return 0
ret = 1
ret = ret * kaijo(n) % MOD
ret = ret * gyaku_kaijo(r) % MOD
ret = ret * gyaku_kaijo(n-r) % MOD
return ret
N,K = map(int,(input().split()))
a = list(map(int,(input().split())))
a.sort()
ans = 0
for i in range(1,N-K+2):
ans += (a[-i] - a[i-1]) * nCr(N-i,K-1)
ans %= MOD
print(ans)
|
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 = 10 ** 9 + 7
N = 10 ** 5 + 1 # N は必要分だけ用意する
fact = [1, 1]
factinv = [1, 1]
inv = [0, 1]
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)
N, K = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
ans = 0
for ri in range(2):
for i in range(N):
now = cmb(i, K - 1, p)
if ri == 1:
now = - now
ans += A[i] * now
ans %= p
A.sort(reverse=True)
print(ans)
| 1 | 95,933,441,889,676 | null | 242 | 242 |
n,m=map(int,input().split())
c=list(map(int,input().split()))
c.sort(reverse=True)
#print(c)
dp=[0]
for i in range(1,n+1):
mini=float("inf")
for num in c:
if i-num>=0:
mini=min(mini,dp[i-num]+1)
dp.append(mini)
#print(dp)
print(dp[-1])
|
INF = 1e5
n, m = list(map(int, input().split()))
C = list(map(int, input().split()))
dp = [[INF] * (n + 1) for _ in range(m)]
for i in range(m):
dp[i][0] = 0
for j in range(1 + n):
dp[0][j] = j
from itertools import product
for i, j in product(range(1, m), range(1, n + 1)):
dp[i][j] = min(dp[i][j], dp[i - 1][j])
if 0 <= j - C[i]:
dp[i][j] = min(dp[i][j], dp[i][j - C[i]] + 1)
print(dp[i][j])
| 1 | 144,398,733,960 | null | 28 | 28 |
n,m,k = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
t = sum(b)
ans = 0
j = m
for i in range(n+1):
while j > 0 and t>k:
j -= 1
t -= b[j]
if t>k: break
ans = max(ans, i+j)
if i==n: break
t += a[i]
print(ans)
|
n, m, k = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
sum_A = [0 for _ in range(n+1)] # sum_A[i]:=上からi冊の本を読むときにかかる時間
for i in range(1, n+1):
sum_A[i] = sum_A[i-1] + A[i-1]
sum_B = [0 for _ in range(m+1)] # sum_B[i]:=上からj冊の本を読むときにかかる時間
for j in range(1, m+1):
sum_B[j] = sum_B[j-1] + B[j-1]
ans = 0
i = 0
j = m
while i <= n and sum_A[i] <= k:
while sum_A[i] + sum_B[j] > k:
j -= 1
ans = max(ans, i + j)
i += 1
print(ans)
| 1 | 10,859,943,684,472 | null | 117 | 117 |
S = input()
print('No' if S == 'AAA' or S == 'BBB' else 'Yes')
|
s=input()
if s.count('A') and s.count('B'): print('Yes')
else: print('No')
| 1 | 55,027,069,426,212 | null | 201 | 201 |
x = input().split()
print(int(x[0]) * int(x[1]), 2 * (int(x[0])+ int(x[1])))
|
string = input()
a,b = map(int,string.split(' '))
print(a*b, 2*(a+b))
| 1 | 308,759,033,252 | null | 36 | 36 |
n,k = map(int,input().split())
res = n*500
if res >= k:
print("Yes")
else:
print("No")
|
from collections import deque
slope = input()
down_slope = deque()
total_slopes = deque()
for i in range(len(slope)):
if slope[i] == '\\':
down_slope.append(i)
elif slope[i] == '/':
area = 0
if len(down_slope) > 0:
while len(total_slopes) > 0 and total_slopes[-1][0] > down_slope[-1]:
area += total_slopes[-1][1]
total_slopes.pop()
area += i-down_slope[-1]
total_slopes.append([down_slope[-1],area])
down_slope.pop()
if len(total_slopes) > 0:
total_slopes = [i[1] for i in total_slopes]
print(sum(total_slopes))
print(len(total_slopes),end=' ')
print(' '.join(map(str,total_slopes)))
else:
print(0)
print(0)
| 0 | null | 49,118,777,157,500 | 244 | 21 |
import random
import copy
def evaluateSatisfaction(d, c, s, ans):
score = 0
last = [-1 for i in range(26)]
for i in range(d):
score += s[i][ans[i]]
last[ans[i]] = i
for j in range(26):
if j != ans[i] or True:
score -= c[j]*(i - last[j])
return score
def valuationFunction(d,c,s,contestType,day,last):
return s[day][contestType]
def Input():
d = int(input())
c = list(map(int, input().split()))
s = [list(map(int, input().split())) for i in range(d)]
#s[3][25] = contest(25+1) of day(3+1)
return d, c, s
def evolution(d, c, s, ans):
score_before = evaluateSatisfaction(d, c, s, ans)
ans_after = copy.copy(ans)
idx1 = random.randint(0,d-1)
idx2 = random.randint(0,d-1)
tmp = ans_after[idx1]
ans_after[idx1] = ans_after[idx2]
ans_after[idx2] = tmp
score_after = evaluateSatisfaction(d,c,s,ans_after)
if score_after > score_before:
return ans_after
else:
return ans
if __name__ == "__main__":
d, c, s = Input()
#print("val =", evaluateSatisfaction(d, c, s, [1, 17, 13, 14, 13]))
#calc start
ans = [0 for i in range(d)]
last = [-1 for i in range(26)]
for i in range(d):
evalValueList = [0 for j in range(26)]
for j in range(26):
evalValueList[j] = valuationFunction(d, c, s, j,i,last)
max_idx = 0
max = evalValueList[0]
for j in range(26):
if (max < evalValueList[j]):
max_idx = j
max = evalValueList[j]
ans[i] = max_idx
last[ans[i]] = i
for i in range(100):
ans = evolution(d, c, s, ans)
#print(evaluateSatisfaction(d,c,s,ans))
for x in ans:
print(x+1)
|
from time import time
from random import random
limit_secs = 2
start_time = time()
D = int(input())
c = list(map(int, input().split()))
s = [list(map(int, input().split())) for _ in range(D)]
def calc_score(t):
score = 0
S = 0
last = [-1] * 26
for d in range(len(t)):
S += s[d][t[d]]
last[t[d]] = d
for i in range(26):
S -= c[i] * (d - last[i])
score += max(10 ** 6 + S, 0)
return score
def solution1():
return [i % 26 for i in range(D)]
def solution2():
t = None
score = -1
for i in range(26):
nt = [(i + j) % 26 for j in range(D)]
if calc_score(nt) > score:
t = nt
return t
#def solution3():
# t = []
# for _ in range(D):
# for i in range(26):
def optimize0(t):
return t
def optimize1(t):
score = calc_score(t)
while time() - start_time + 0.15 < limit_secs:
d = int(random() * D)
q = int(random() * 26)
old = t[d]
t[d] = q
new_score = calc_score(t)
if new_score < score:
t[d] = old
else:
score = new_score
return t
t = solution2()
t = optimize0(t)
print('\n'.join(str(e + 1) for e in t))
| 1 | 9,749,146,298,650 | null | 113 | 113 |
A,B,N=map(int,input().split())
if N<B:
x=N
elif N==B:
x=N-1
else:
x=(N//B)*B-1
ans=(A*x/B)//1-A*(x//B)
print(int(ans))
|
a = int(input())
b = int(input())
l = {1, 2, 3}
m = {a, b}
ans = list(l ^ m)
print(ans[0])
| 0 | null | 69,594,446,560,736 | 161 | 254 |
while 1:
x,y,z=raw_input().split()
x=int(x)
z=int(z)
if(y=='?'):
break
if(y=='+'):
print x+z
if(y=='-'):
print x-z
if(y=='/'):
print x/z
if(y=='%'):
print x%z
if(y=='*'):
print x*z
|
from queue import LifoQueue
MAP = input()
que = LifoQueue()
res = LifoQueue()
for i, m in enumerate(MAP):
if m=='\\':
que.put(i)
elif m=='/':
if not que.empty():
j = que.get(False)
v = i - j
t = (j, v)
while not res.empty():
pre = res.get(False)
if (pre[0] > j):
t = (t[0], t[1] + pre[1])
else:
res.put(pre)
res.put(t)
break
else:
res.put(t)
summaly = 0
lakes = []
while not res.empty():
v = res.get()
lakes.append(v[1])
summaly += v[1]
print(summaly)
print(len(lakes), *(reversed(lakes)))
| 0 | null | 373,682,804,480 | 47 | 21 |
import numpy as np
from numba import njit
(N, K) = map(int, input().split())
A = np.array(list(map(int, input().split())))
@njit
def solve(N,K,A):
for j in range(0, K):
B = np.zeros(N, dtype=np.int64)
for i in range(0,N):
f = max(0, i - A[i])
t = min(N-1, i + A[i])
#for j in range(max(0, f), min(N, t)+1):
# B[j] += 1
B[f] += 1
if t+1 < N:
B[t+1] -= 1
A = np.cumsum(B)
if np.all(A == N):
return A
i += 1
return A
print(" ".join(map(str, solve(N,K,A))))
|
N, K = map(int, input().split())
A_list = list(map(int, input().split()))
for _ in range(K):
count_list = [0] * N
for i, v in enumerate(A_list):
count_list[i - v if i - v > 0 else 0] += 1
if i + v + 1 < N:
count_list[i + v + 1] -= 1
temp = 0
flag = True
for i in range(len(A_list)):
temp += count_list[i]
if temp != N:
flag = False
A_list[i] = temp
if flag:
break
print(*A_list)
| 1 | 15,399,389,143,622 | null | 132 | 132 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
???????????????
"""
inputstr = input().strip()
cmdnum = int(input().strip())
for i in range(cmdnum) :
cmd = input().strip().split()
if cmd[0] == "print":
start = int(cmd[1])
end = int(cmd[2]) + 1
print(inputstr[start:end])
if cmd[0] == "reverse":
start = int(cmd[1])
end = int(cmd[2]) + 1
prev = inputstr[:start]
revr = inputstr[start:end]
next = inputstr[end:]
inputstr = prev + revr[::-1] + next
if cmd[0] == "replace":
start = int(cmd[1])
end = int(cmd[2]) + 1
inputstr = inputstr[:start] + cmd[3] + inputstr[end:]
|
s=input()
n=int(input())
for _ in range(n):
tmp=list(map(str,input().split()))
a,b=int(tmp[1]),int(tmp[2])+1
if tmp[0]=="print":
print(s[a:b])
elif tmp[0]=="reverse":
stmp=s[a:b]
s=s[:a]+stmp[::-1]+s[b:]
else:
p=tmp[3]
s=s[:a]+p+s[b:]
| 1 | 2,100,257,024,712 | null | 68 | 68 |
n = int(input())
dic = {}
for i in range(1,n+1):
if str(i)[-1] == 0:
continue
key = str(i)[0]
key += "+" + str(i)[-1]
if key in dic:
dic[key] += 1
else:
dic[key] = 1
res = 0
for i in range(1,n+1):
if str(i)[-1] == 0:
continue
key = str(i)[-1]
key += "+" + str(i)[0]
if key in dic:
res += dic[key]
print(res)
|
N=int(input())
D={(x//10,x%10):0 for x in range(100)}
for i in range(1,N+1):
if i<10:
D[(i,i)]=1
else:
Q=int(str(i)[0])
R=i%10
D[(Q,R)]+=1
S=0
for x in range(1,10):
for y in range(1,10):
S+=D[(x,y)]*D[(y,x)]
print(S)
| 1 | 86,805,670,923,718 | null | 234 | 234 |
n, k = map(int, input().split())
p = list(map(int, input().split()))
e = []
for i in range(n):
e.append(p[i] + 1)
sum_e = [0]
for i in range(1,n+1):
sum_e.append(sum_e[i-1]+e[i-1])
ans = []
for i in range(n-k+1):
ans.append(sum_e[i+k]-sum_e[i])
print(max(ans)/2)
|
n = int(input())
s = input()
if s[0:n // 2] ==s[n//2:]:
print('Yes')
else:
print('No')
| 0 | null | 110,672,990,239,760 | 223 | 279 |
inData = int(input())
seqData = list(range(1,inData+1,1))
outData = [0] * inData
for thisData in seqData:
if thisData == inData:
if thisData%3 == 0 or thisData%10==3:
print(" "+str(thisData))
else:
for i in range(5):
i=i+1
over = 10 ** i
tmp = thisData/over
if int(tmp % 10) == 3:
print(" "+str(thisData))
break
else:
pass
print("")
else:
if thisData%3 == 0 or thisData%10==3:
print(" "+str(thisData), end = "")
else:
for i in range(5):
i=i+1
over = 10 ** i
tmp = thisData/over
if int(tmp % 10) == 3:
print(" "+str(thisData), end = "")
break
else:
pass
|
N,K = [int(x) for x in input().split()]
count = [0]*(K+1)
ans = 0
mod = 1000000007
for i in range(K,0,-1):
kosuu = pow(K//i,N,mod)
if K // i >= 2:
for j in range(K//i,1,-1):
kosuu -= count[j*i]
ans += i*kosuu
count[i] = kosuu
print(ans%mod)
| 0 | null | 18,818,952,309,230 | 52 | 176 |
n=int(input())
s=input()
S=[]
for i in s:
if ord(i)+n > 90:
S.append(chr(ord(i)+n-26))
else:
S.append(chr(ord(i)+n))
print(''.join(S))
|
n = int(input())
s = input()
x = len(s)
for i in range(x):
a = s[i]
b = ord(a)
c = ord("A")
d = (b + n - c)%26
print(chr(c + d), end = '')
print()
| 1 | 134,515,528,947,940 | null | 271 | 271 |
import numpy as np
n = int(input())
a = np.array(list(map(int,input().split())))
amax=max(a)+1
ah=[0]*amax
for i in a:
for j in range(i,amax,i):
ah[j]+=1
an=0
for i in a:
if ah[i]==1:
an+=1
print(an)
|
N = int(input())
ary = [int(input()) for _ in range(N)]
def insertion_sort(ary, g):
cnt = 0
for i in range(g, N):
v = ary[i]
j = i - g
while j >= 0 and ary[j] > v:
ary[j + g] = ary[j]
j -= g
cnt += 1
ary[j + g] = v
return cnt
def shell_sort(ary):
g = [1]
while True:
if 3 * g[-1] + 1 < N:
g.append(3 * g[-1] + 1)
else:
break
m = len(g)
g = g[::-1]
cnt = 0
for i in range(0, m):
cnt += insertion_sort(ary, g[i])
print(m)
print(' '.join([str(_) for _ in g]))
print(cnt)
[print(_) for _ in ary]
shell_sort(ary)
| 0 | null | 7,205,998,318,360 | 129 | 17 |
from decimal import *
import math
getcontext().prec = 50
a, b, c = map(int, input().split())
a = Decimal(a)
b = Decimal(b)
c = Decimal(c)
a = Decimal.sqrt(a)
b = Decimal.sqrt(b)
c = Decimal.sqrt(c)
if a + b < c:
print("Yes")
else:
print("No")
|
from decimal import Decimal
A,B,C=map(str,input().split())
if Decimal(A)**Decimal("0.5")+Decimal(B)**Decimal("0.5")<Decimal(C)**Decimal("0.5"):
print("Yes")
else:
print("No")
| 1 | 51,575,081,575,872 | null | 197 | 197 |
n,k=map(int,input().split())
ans=[1]+[0]*n
for i in range(k):
d=int(input())
l=list(map(int,input().split()))
for i in l:
ans[i]=1
print(ans.count(0))
|
a,b,k=map(int,input().split())
if a<k:
b-=k-a
a=0
if b<0:
b=0
else:
a-=k
print(a,b)
| 0 | null | 64,651,916,973,900 | 154 | 249 |
N=int(input())
*X,=sorted(map(int,input().split()))
a=10**9
for p in range(X[0], X[-1]+1):
a=min(a, sum((n-p)**2 for n in X))
print(a)
|
N=int(input())
#people
li = list(map(int, input().split()))
Ave1=sum(li)//N
Ave2=sum(li)//N+1
S1=0
S2=0
for i in range(N):
S1=S1+(Ave1-li[i])**2
for i in range(N):
S2=S2+(Ave2-li[i])**2
if S1>S2:
print(S2)
else:
print(S1)
| 1 | 65,269,109,996,606 | null | 213 | 213 |
def main():
n, k = [int(x) for x in input().split()]
scores = [int(x) for x in input().split()]
for index in range(n - k):
if scores[index] < scores[index + k]:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main()
|
N, K = map(int, input().split())
H = list(map(int, input().split()))
if N <= K:
print(0)
exit()
H.sort(reverse=True)
print(sum(H[K:]))
| 0 | null | 42,851,191,415,812 | 102 | 227 |
n, m = map(int, input().split())
a = list(map(int, input().split()))
a.sort(reverse=True)
if len(list(filter(lambda v: v * 4 * m >= sum(a), a[:m]))) == m:
print("Yes")
else:
print("No")
|
n = int(input())
L = []
for _ in range(n):
L.append(int(input()))
def InsertionSort(L, n, g):
for i in range(n):
global cnt
v = L[i]
j = i - g
while j >= 0 and L[j] > v:
L[j+g] = L[j]
j -= g
cnt += 1
L[j+g] = v
def ShellSort(L, n):
gt = 1
g = []
while n >= gt:
g.append(gt)
gt = 3 * gt + 1
print(len(g))
g = g[::-1]
print(' '.join(str(x) for x in g))
for x in g:
InsertionSort(L, n, x)
print(cnt)
for i in L:
print(i)
cnt = 0
ShellSort(L, n)
| 0 | null | 19,225,585,882,828 | 179 | 17 |
N, K = map(int, input().split())
# 最小値として取りうる値は、t or K-t
t = N % K
ans = min(t, K-t)
print(ans)
|
#C - Replacing Intege
N,K = map(int, input().split())
for i in range(N):
if N % K == 0:
N = 0
break
N = N % K
if abs(N-K) < N:
N = abs(N-K)
else :
break
print(N)
| 1 | 39,294,065,852,148 | null | 180 | 180 |
r, c = map(int, input().split())
output = []
for _ in range(r):
l = list(map(int, input().split()))
s = sum(l)
l.append(s)
output.append(l)
final = []
for i in range(c):
t = 0
for j in range(r):
t += output[j][i]
final.append(t)
s = sum(final)
final.append(s)
output.append(final)
for i in output:
print(*i)
|
r, c = map(int, input().split())
arr = []
for i in range(r):
arr.append(list(map(int, input().split())))
for line in arr:
line.append(sum(line))
arr.append([sum([line[i] for line in arr]) for i in range(c + 1)])
for line in arr:
print(*line)
| 1 | 1,358,792,061,988 | null | 59 | 59 |
n = int(input())
x = list(map(float, input().split(' ')))
y = list(map(float, input().split(' ')))
p1 = 0.0
p2 = 0.0
p3 = 0.0
pm = 0.0
i = 0
while i < n:
p1 += abs(x[i] - y[i])
p2 += pow(abs(x[i] - y[i]), 2)
p3 += pow(abs(x[i] - y[i]), 3)
pm = max(pm, abs(x[i] - y[i]))
i += 1
p2 = pow(p2, 0.5)
p3 = pow(p3, 0.333333333333333)
ans = '{0:.8f}'.format(p1) + '\n'
ans += '{0:.8f}'.format(p2) + '\n'
ans += '{0:.8f}'.format(p3) + '\n'
ans += '{0:.8f}'.format(pm)
print(ans)
|
import math
def minkowski(x, y, p):
if p == 0:
return max(map(lambda xi,yi: abs(xi-yi), x, y))
else:
return math.pow(sum(map(lambda xi,yi: math.pow(abs(xi-yi), p), x, y)), 1/p)
if __name__ == '__main__':
n = int(input())
x = [int(i) for i in input().split()]
y = [int(i) for i in input().split()]
print("{0:.6f}".format(minkowski(x, y, 1)))
print("{0:.6f}".format(minkowski(x, y, 2)))
print("{0:.6f}".format(minkowski(x, y, 3)))
print("{0:.6f}".format(minkowski(x, y, 0)))
| 1 | 216,212,540,278 | null | 32 | 32 |
def main():
N = int(input())
*A, = map(int, input().split())
ans = sum(A[i] & 1 for i in range(0, N, 2))
print(ans)
if __name__ == '__main__':
main()
|
num1 = int(input())
num = (int(x) for x in input().split())
count = 0
for i, name in enumerate(num):
if i % 2 == 0:
if name % 2 == 1:
count = count + 1
print(count)
| 1 | 7,768,865,132,752 | null | 105 | 105 |
h, w, k = map(int, input().split())
c = []
ans = 0
for i in range(h):
c_i = list(input())
c.append(c_i)
for i in range(1 << h):
for j in range(1 << w):
cnt = 0
for ii in range(h):
for jj in range(w):
if (i >> ii & 1):
continue
if (j >> jj & 1):
continue
if c[ii][jj] == "#":
cnt += 1
if cnt == k:
ans += 1
print(ans)
|
H,W,K=map(int,input().split())
c=[input() for _ in range(H)]
ans=0
for i in range(1<<H):
for j in range(1<<W):
cnt=0
for h in range(H):
for w in range(W):
if c[h][w]=='#':
if (i>>h)%2==0 and (j>>w)%2==0:
cnt+=1
if cnt==K:
ans+=1
print(ans)
| 1 | 8,941,201,997,390 | null | 110 | 110 |
dice=input().split()
q=int(input())
do = [(2,3,5,4), (6,3,1,4), (2,6,5,1), (2,1,5,6), (1,3,6,4), (2,4,5,3)]
def check(top, front):
top_index=dice.index(top)
front_index=dice.index(front)+1
tmp=do[top_index]
tmp_index=tmp.index(front_index)
# print(top_index,front_index,tmp,tmp_index)
i = 0
if tmp_index == 3:
i = tmp[0]
else:
i = tmp[tmp_index+1]
print(dice[i-1])
for i in range(q):
top,front=input().split()
check(top,front)
|
num=list(map(int,input().split()))
q=int(input())
def E(ls):
ls=[ls[3],ls[1],ls[0],ls[5],ls[4],ls[2]]
return ls
def N(ls):
ls=[ls[1],ls[5],ls[2],ls[3],ls[0],ls[4]]
return ls
def R(ls):
ls=[ls[0],ls[2],ls[4],ls[1],ls[3],ls[5]]
return ls
for i in range(q):
num0,num1=list(map(int,input().split()))
if num.index(num0) in [0,2,3,5]:
while num[0]!=num0:
num=E(num)
while num[1]!=num1:
num=R(num)
print(num[2])
else:
while num[0]!=num0:
num=N(num)
while num[1]!=num1:
num=R(num)
print(num[2])
| 1 | 255,825,176,332 | null | 34 | 34 |
N = int(input())
A = list(map(int, input().split()))
INF = 10**18
dp0 = 0
dp1 = -INF
dp2 = -INF
for i, a in enumerate(A):
if i % 2 == 0:
dp1 = max(dp1, dp0)
dp0 += a
dp2 += a
else:
dp2 = max(dp2, dp1)
dp1 += a
if N % 2 == 1:
print(max(dp1, dp2))
else:
print(max(dp0, dp1))
|
from collections import defaultdict
n = int(input())
A = list(map(int, input().split()))
m = n//2
INF = 10**18
dp = [defaultdict(lambda: -INF) for _ in range(n+1)]
for i in range(1, n+1):
for j in range(i//2-1, (i+1)//2+1):
if j == 1:
dp[i][j] = max(dp[i-1][j], A[i-1])
elif 0 <= i-2 and 0 <= j <= m:
dp[i][j] = max(dp[i-1][j], dp[i-2][j-1]+A[i-1])
print(dp[-1][m])
| 1 | 37,364,925,535,240 | null | 177 | 177 |
N = int(input())
if N%2 == 0:
print(N//2)
elif N%2 != 0:
print(N//2+1)
|
N = int(input())
print(int(N / 2)) if N % 2 == 0 else print(N // 2 + 1)
| 1 | 59,024,464,852,260 | null | 206 | 206 |
S = input()
N = len(S)
S1 = S[0:(N-1)//2]
S2 = S[(N+3)//2-1:]
print('Yes' if S == S[::-1] and S1 == S1[::-1] and S2 == S2[::-1] else 'No')
|
n = int(input())
dic = set()
for i in range(n):
order, Str = input().split()
if order=='insert':
dic.add(Str)
if order=='find':
if Str in dic:
print('yes')
else:
print('no')
| 0 | null | 23,337,358,759,000 | 190 | 23 |
def Next(): return input()
name = Next()
print(name[:3])
|
def main():
S, W = map(int, input().split())
cond = S <= W
print('unsafe' if cond else 'safe')
if __name__ == '__main__':
main()
| 0 | null | 22,045,089,037,942 | 130 | 163 |
list = map(int, raw_input().split())
print list[0] / list[1], list[0] % list[1], "%.5f" %(1.0*list[0] / list[1])
|
a, b = map(int, input().split())
d = a//b
r = a%b
f = float(a/b)
print('%s %s %.5f' % (d, r, f))
| 1 | 612,786,844,550 | null | 45 | 45 |
s,t = (i for i in input().split())
print(t+s)
|
def solve():
N, M = input().split()
return M+N
print(solve())
| 1 | 103,032,443,524,362 | null | 248 | 248 |
import sys
r = int(sys.stdin.readline().rstrip())
def main():
print(r ** 2)
if __name__ == '__main__':
main()
|
from itertools import combinations
N = int(input())
L = sorted(list(map(int, input().split())))
ans = 0
for a,b,c in combinations(L, 3):
ans += a < b < c < a+b
print(ans)
| 0 | null | 74,987,184,354,742 | 278 | 91 |
N = input()
L=len(N)
DP=[[N]*2 for _ in range(L+1)]
DP[0][0]=0
DP[0][1]=1
for i,n in enumerate(N,1):
DP[i][0]= min(DP[i-1][0]+int(n),DP[i-1][1]+10-int(n))
DP[i][1] = min(DP[i-1][0]+int(n)+1,DP[i-1][1]+9-int(n))
print(DP[L][0])
|
def resolve():
S = "0" + input()
N = len(S)
dp = [[1<<60]*2 for _ in range(N+1)]
dp[0][0] = 0
for i in range(N):
now = int(S[i])
dp[i+1][0] = min(dp[i][0]+now, dp[i][1]+(10- now))
dp[i + 1][1] = min(dp[i][0] + now + 1, dp[i][1] + (10 - now - 1))
print(dp[N][0])
if __name__ == "__main__":
resolve()
| 1 | 71,044,238,580,930 | null | 219 | 219 |
import bisect
N=int(input())
S=list(str(input()))
def ci(x):
return "abcdefghijklmnopqrstuvwxyz".find(x)
d=[[] for _ in range(26)]
for i,s in enumerate(S):
d[ci(s)].append(i)
for i in range(int(input())):
t,x,y=input().split()
if t=="1":
x=int(x)-1
if S[x]!=y:
l=bisect.bisect_left(d[ci(S[x])],x)
d[ci(S[x])].pop(l)
bisect.insort(d[ci(y)],x)
S[x]=y
else:
x,y=int(x)-1,int(y)-1
c=0
for j in range(26):
l=bisect.bisect_left(d[j],x)
if l<len(d[j]) and d[j][l] <= y:
c += 1
print(c)
|
import sys
n = int(input())
dic =set()
t = sys.stdin.readlines()
for i in t:
i,op = i.split()
if i == 'insert':
dic.add(op)
else:
if op in dic:
print('yes')
else:
print('no')
| 0 | null | 31,300,580,639,998 | 210 | 23 |
import sys
input = sys.stdin.readline
from collections import defaultdict
x = int(input())
pre = [i ** 5 for i in range(1001)] # Fuck it
for i in range(1001):
for j in range(i + 1):
if pre[i] - pre[j] == x: print(i, j); exit()
elif pre[i] + pre[j] == x: print(i, -j); exit()
|
import math
while True:
n = input()
if n == 0:
break
s = map(int, raw_input().split())
sumS = 0.0
sum = 0.0
for i in s:
sumS += i**2
sum += i
v = sumS / n - (sum / n)**2
print math.sqrt(v)
| 0 | null | 12,838,352,070,840 | 156 | 31 |
MOD = 998244353
class mint:
def __init__(self, x):
if isinstance(x, int):
self.x = x % MOD
elif isinstance(x, mint):
self.x = x.x
else:
self.x = int(x) % MOD
def __str__(self):
return str(self.x)
__repr__ = __str__
def __iadd__(self, other):
self.x += other.x if isinstance(other, mint) else other
self.x -= MOD if self.x >= MOD else 0
return self
def __isub__(self, other):
self.x += MOD-other.x if isinstance(other, mint) else MOD-other
self.x -= MOD if self.x >= MOD else 0
return self
def __imul__(self, other):
self.x *= other.x if isinstance(other, mint) else other
self.x %= MOD
return self
def __add__(self, other):
return (
mint(self.x + other.x) if isinstance(other, mint) else
mint(self.x + other)
)
def __sub__(self, other):
return (
mint(self.x - other.x) if isinstance(other, mint) else
mint(self.x - other)
)
def __mul__(self, other):
return (
mint(self.x * other.x) if isinstance(other, mint) else
mint(self.x * other)
)
def __floordiv__(self, other):
return (
mint(
self.x * pow(other.x, MOD - 2, MOD)
) if isinstance(other, mint) else
mint(self.x * pow(other, MOD - 2, MOD))
)
def __pow__(self, other):
return (
mint(pow(self.x, other.x, MOD)) if isinstance(other, mint) else
mint(pow(self.x, other, MOD))
)
__radd__ = __add__
def __rsub__(self, other):
return (
mint(other.x - self.x) if isinstance(other, mint) else
mint(other - self.x)
)
__rmul__ = __mul__
def __rfloordiv__(self, other):
return (
mint(
other.x * pow(self.x, MOD - 2, MOD)
) if isinstance(other, mint) else
mint(other * pow(self.x, MOD - 2, MOD))
)
def __rpow__(self, other):
return (
mint(pow(other.x, self.x, MOD)) if isinstance(other, mint) else
mint(pow(other, self.x, MOD))
)
n,s = map(int, input().split())
a = list(map(int, input().split()))
import copy
dp = [[0 for _ in range(s+1)] for _ in range(n+1)]
dp[0][0]=pow(2,n,MOD)
div=pow(2,MOD-2,MOD)
for i in range(n):
for j in range(s+1):
dp[i+1][j]=dp[i][j]
if j-a[i]>=0:
dp[i+1][j]+=dp[i][j-a[i]]*div
dp[i+1][j]%=MOD
print(dp[n][s])
|
from functools import reduce
from fractions import gcd
import math
import bisect
import itertools
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
INF = float("inf")
MOD = 998244353
# 処理内容
def main():
N, S = map(int, input().split())
A = list(map(int, input().split()))
dp = [[0]*(S+1) for _ in range(N+1)]
dp[0][0] = 1
for i in range(N):
for j in range(S+1):
dp[i+1][j] += dp[i][j] * 2
dp[i+1][j] %= MOD
if j + A[i] > S:
continue
dp[i+1][j+A[i]] += dp[i][j]
dp[i+1][j+A[i]] %= MOD
print(dp[N][S])
if __name__ == '__main__':
main()
| 1 | 17,806,435,491,968 | null | 138 | 138 |
print((float(input())**3)/27)
|
import math
a,b = map(int, input().split())
ans = 10000
for i in range(1010):
if math.floor(i*0.08) == a and math.floor(i*0.1) == b:
ans = i
break
if ans == 10000:
print(-1)
else:
print(ans)
| 0 | null | 51,607,882,751,530 | 191 | 203 |
s = input()
a = 0
ans = 0
b = 0
d = [0]
e = []
now = 0
for i in range(len(s)):
if s[i] == '<':
if a != 0:
if a > now:
ans = ans - d[-1] + a
for j in range(a):
ans = ans + j
d.append(a - j)
e.append(">")
now = 0
a = 0
ans = ans + now + 1
now = now + 1
d.append(now)
else:
a = a + 1
b = 0
if a != 0:
if a > now:
ans = ans - d[-1] + a
for j in range(a):
ans = ans + j
d.append(a - j)
e.append(">")
print(ans)
|
s = input()
cnt_l = [0]*(len(s)+1)
cnt_r = [0]*(len(s)+1)
for i in range(1, len(s)+1):
if s[i-1] == "<":
cnt_l[i] = cnt_l[i-1] + 1
else:
cnt_l[i] = 0
for i in range(len(s)-1, -1, -1):
if s[i] == ">":
cnt_r[i] = cnt_r[i+1]+1
else:
cnt_r[i] = 0
ans = 0
for l, r in zip(cnt_l, cnt_r):
ans += max(l, r)
print(ans)
| 1 | 156,437,992,722,732 | null | 285 | 285 |
import itertools
import numpy as np
d_list = []
sum_d = 0
N, M, Q = map(int, input().split())
abcd = [list(map(int, input().split())) for i in range(Q)]
ans = 0
A = [1 for i in range(N)]
for A in itertools.combinations_with_replacement(range(1, M+1), N):
for i in range(Q):
if A[abcd[i][1]-1]-A[abcd[i][0]-1] == abcd[i][2]:
d_list.append(abcd[i][3])
if sum_d <= sum(d_list):
sum_d = sum(d_list)
d_list.clear()
print(sum_d)
|
import sys
import collections
input = lambda: sys.stdin.readline().rstrip()
def main():
n = int(input())
a = list(map(int, input().split()))
cnt = collections.Counter(a)
all_comb = 0
for i in cnt.keys():
all_comb += cnt[i] * (cnt[i]-1) // 2
for i in range(n):
comb = all_comb
comb -= cnt[a[i]] * (cnt[a[i]]-1) // 2
comb += (cnt[a[i]]-1) * (cnt[a[i]]-2) // 2
print(comb)
if __name__ == '__main__':
main()
| 0 | null | 37,500,013,957,248 | 160 | 192 |
import sys
def main():
A,B,N=tuple(map(int,sys.stdin.readline().split()))
L=max([1,min([B-1,N])])
print((A*L)//B) if B!=1 else print(0)
if __name__=='__main__':main()
|
import math
a, b, n = map(int, input().split())
if n < b:
print(math.floor(a * n / b) - 5 * math.floor(n / b))
else:
print(math.floor(a * (b - 1) / b) - 5 * math.floor((b - 1) / b))
| 1 | 28,107,298,772,232 | null | 161 | 161 |
S=input()
S2=S[:(len(S)-1)//2]
S3=S[(len(S)+3)//2-1:]
if S==S[::-1] and S2==S2[::-1] and S3==S3[::-1]:
print("Yes")
else:
print("No")
|
a,b,c,d=map(int,input().split())
X=[a,b]
Y=[c,d]
ans=-10**30
for x in X:
for y in Y:
if ans<x*y:
ans=x*y
print(ans)
| 0 | null | 24,547,847,036,000 | 190 | 77 |
N, K = map(int, input().split())
ls1 = list(map(int, input().split()))
d = dict()
ls2 = ['r', 's', 'p']
for x, y in zip(ls1, ls2):
d[y] = x
T = input()
S = T.translate(str.maketrans({'r': 'p', 's': 'r', 'p': 's'}))
ans = 0
for i in range(K):
cur = ''
for j in range(i, N, K):
if cur != S[j]:
ans += d[S[j]]
cur = S[j]
else:
cur = ''
print(ans)
|
s = int(input())
m = 10**9+7
a = [1,0,0,1]
if s < 4:
print(a[s])
exit()
for i in range(4,s+1):
a.append((a[3]+a[1])%m)
a.pop(0)
print(a[3])
| 0 | null | 55,387,415,592,760 | 251 | 79 |
#%%time
from itertools import accumulate
import numpy as np
from numba import njit
n, k = map(int, input().split())
a = np.array(list(map(int, input().split())), dtype=np.int64)
@njit
def loop1(a):
#b = [0]*(n+1)
b = np.zeros(n+1, dtype=np.int64)
for i in range(n):
l = max(0, i-a[i])
r = min(i+a[i]+1, n)
b[l] += 1
if r <= n-1: b[r] -= 1
b = np.cumsum(b)[:-1]
return b
#a = list(accumulate(b))
#a = a[:-1]
#if np.all(a == n):
# break
for q in range(min(42, k)):
a = loop1(a)
print(*a)
|
N = int(input())
A = list(map(int, input().split()))
M = 1000
S = 0
for i in range(N-1):
if A[i] < A[i+1]:
S = M // A[i]
M = M % A[i] + S*A[i+1]
S = 0
else:
pass
print(M)
| 0 | null | 11,371,430,037,298 | 132 | 103 |
def bubble_sort(A):
flag = True
swap = 0
while flag:
flag = False
for j in range(len(A)-1,0,-1):
if A[j] < A[j-1]:
A[j],A[j-1] = A[j-1],A[j]
swap += 1
flag = True
return swap
if __name__=='__main__':
N=int(input())
A=list(map(int,input().split()))
swap = bubble_sort(A)
print(*A)
print(swap)
|
def bubble_sort(A):
cnt = 0
for i in range(len(A) - 1):
for j in reversed(range(i+1, len(A))):
if A[j] < A[j - 1]:
cnt += 1
tmp = A[j]
A[j] = A[j - 1]
A[j - 1] = tmp
return cnt
cnt = 0
amount = int(input())
nl = list(map(int, input().split()))
cnt = bubble_sort(nl)
for i in range(amount - 1):
print(nl[i], end=" ")
print(nl[amount - 1])
print(cnt)
| 1 | 15,900,654,848 | null | 14 | 14 |
h,w,k = map(int,input().split())
s = [list(map(int,input())) for _ in range(h)]
ans = h*w
for div in range(1<<(h-1)):
row = 0
S = [[0]*w]
S[row] = [s[0][i] for i in range(w)]
for i in range(1,h):
if 1&(div>>i-1):
row += 1
S.append([s[i][j] for j in range(w)])
else:
S[row] = [S[row][j]+s[i][j] for j in range(w)]
count = [0]*(row+1)
ans_ = row
a = True
for i in range(w):
for j in range(row+1):
if S[j][i] > k:
a = False
break
count[j] += S[j][i]
if count[j] > k:
ans_+=1
count = [0]*(row+1)
for l in range(row+1):
count[l] += S[l][i]
break
if ans_ >= ans or a==False:
break
if a:
ans = min(ans,ans_)
print(ans)
|
# https://atcoder.jp/contests/abc159/tasks/abc159_e
import sys
ans = sys.maxsize
H, W, K = map(int, input().split())
s = [input() for _ in range(H)]
for h in range(1 << (H - 1)):
g = 0
ids = [-1 for _ in range(H)]
for i in range(H):
ids[i] = g
if (h >> i) & 1:
g += 1
g += 1
num = g - 1
if num >= ans:
continue
c = [[0] * W for _ in range(g)]
for i in range(H):
for j in range(W):
c[ids[i]][j] = c[ids[i]][j] + (s[i][j] == '1')
now = [0 for _ in range(g)]
def add(j):
for i in range(g):
now[i] += c[i][j]
for i in range(g):
if now[i] > K:
return False
return True
for j in range(W):
if not add(j):
num += 1
if num >= ans:
continue
now = [0 for _ in range(g)]
if not add(j):
num = sys.maxsize
break
ans = min(ans, num)
print(ans)
| 1 | 48,322,911,629,838 | null | 193 | 193 |
n, k = map(int, input().split())
p = sorted(list(map(int, input().split())))
a = 0
for i in range(k):
a += p[i]
print(a)
|
n, k = map(int, input().split())
price = sorted(list(map(int, input().split())))
min_price = 0
for i in range(k) :
min_price += price[i]
print(min_price)
| 1 | 11,680,536,405,400 | null | 120 | 120 |
(N,) = map(int, input().split())
As = list(enumerate(map(int, input().split())))
As.sort(key=lambda x: -x[1])
dp = [[0] * (N + 1) for _ in range(N + 1)]
for i, (pos, val) in enumerate(As):
for j in range(i + 1):
k = i - j
dp[j + 1][k] = max(dp[j + 1][k], dp[j][k] + abs(j - pos) * val)
dp[j][k + 1] = max(dp[j][k + 1], dp[j][k] + abs(N - 1 - k - pos) * val)
print(max(dp[i][N - i] for i in range(N + 1)))
|
S,T = input().split()
print(T,S, sep='')
| 0 | null | 68,244,921,312,220 | 171 | 248 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.