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
|
---|---|---|---|---|---|---|
a,b,c = map(int,input().split())
tmp = a
a = b
b = tmp
tmp = a
a = c
c = tmp
print(a,b,c)
|
import math
a, b, C = map(float, input().split(' '))
rad = math.radians(C)
c = math.sqrt(a**2+b**2-2*a*b*math.cos(rad))
S = a*b*math.sin(rad)*1/2
L = a+b+c
h = abs(b*math.sin(rad))
print('{:.5f} {:.5f} {:.5f}'.format(S, L, h))
| 0 | null | 19,135,766,457,080 | 178 | 30 |
S,T = open(0).read().split()
print(T+S)
|
b,a = input().split()
print(a + b)
| 1 | 102,708,923,677,920 | null | 248 | 248 |
a, b, c, d = [int(e) for e in input().split(" ")]
print(max((a*c), (a*d), (b*c), (b*d)))
|
arr = input().split()
a = int(arr[0])
b = int(arr[1])
c = int(arr[2])
d = int(arr[3])
tmp = []
tmp.append(a*c)
tmp.append(a*d)
tmp.append(b*c)
tmp.append(b*d)
ans = max(tmp)
print(ans)
| 1 | 3,023,938,773,790 | null | 77 | 77 |
import numpy as np
n, k = map(int, input().split())
a = np.arange(n+1, dtype='int')
b = np.cumsum(a)
s = 0
for i in range(k, n+1):
s += (b[n] - b[n-i]) - b[i-1] + 1
s = s % 1000000007
s += 1
s = s % 1000000007
print(s)
|
n,k=map(int,input().split())
mod=10**9+7
def f(i):
return (1+i*(n-i+1))%mod
ans=0
for i in range(k,n+2):
ans=(ans+f(i))%mod
print(ans)
| 1 | 33,018,824,518,052 | null | 170 | 170 |
def main():
n = int(input())
a = list(map(int, input().split()))
a.sort()
ans = 0
sieve = [False for _ in range(1000001)]
for i in range(n):
if sieve[a[i]]:
continue
for j in range(a[i], 1000001, a[i]):
sieve[j] = True
if i > 0:
if a[i] == a[i-1]:
continue
if i < n-1:
if a[i] == a[i+1]:
continue
ans += 1
print(ans)
if __name__ == '__main__':
main()
|
N = int(input())
A = sorted(list(map(int,input().split())))
B = (10**6+1)*[0]
for a in A:
B[a]+=1
if B[a]==1:
for n in range(2*a,10**6+1,a):
B[n]+=2
print(B.count(1))
| 1 | 14,421,065,289,572 | null | 129 | 129 |
A = int(input())
B = int(input())
anss = set([1, 2, 3])
anss.remove(A)
anss.remove(B)
for i in anss:
print(i)
|
N=int(input())
A=list(map(int,input().split()))
count=0
for i,a in enumerate(A):
n=i+1
if n%2==1 and a%2==1:
count+=1
print(count)
| 0 | null | 59,094,340,137,830 | 254 | 105 |
#!/usr/bin/python3
def find(id, V, d, dist):
i = id - 1
dist[i] = d
for v in V[i]:
if dist[v - 1] == -1 or dist[v - 1] > d + 1:
find(v, V, d + 1, dist)
n = int(input())
# [isFind, d, f]
A = [[False, 0, 0] for i in range(n)]
U = []
V = []
dist = [-1] * n
for i in range(n):
l = list(map(int, input().split()))
U.append(l[0])
V.append(l[2:])
find(1, V, 0, dist)
for u in U:
print(u, dist[u - 1])
|
# -*- coding: utf-8 -*-
import sys
import os
import math
N = int(input())
E = []
E.append([])
d = [-1] * (N + 1)
for i in range(N):
lst = list(map(int, input().split()))
nodes = lst[2:]
E.append(nodes)
#print(E)
q = []
q.append(1)
visited = [False] * (N + 1)
d[1] = 0
visited[1] = True
while q:
index = q.pop(0)
# ???????????????????????´???
for v in E[index]:
if not visited[v]:
q.append(v)
d[v] = d[index] + 1
visited[v] = True
#print(d)
for i in range(1, N + 1):
print(i, d[i])
| 1 | 4,096,138,232 | null | 9 | 9 |
def main():
s = str(input())
dic = {'SUN': 7, 'MON': 6, 'TUE': 5, 'WED': 4, 'THU': 3, 'FRI': 2, 'SAT': 1}
print(dic.get(s))
main()
|
Day = ['', 'SAT', 'FRI', 'THU', 'WED', 'TUE', 'MON', 'SUN']
print(Day.index(input()))
| 1 | 133,303,787,182,170 | null | 270 | 270 |
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right
sys.setrecursionlimit(10**7)
def input():
return sys.stdin.readline()[:-1]
mod = 10**9 + 7
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
if row <= 0:
return [[] for _ in range(col)]
elif col == 1:
return [I() for _ in range(row)]
else:
read_all = [LI() for _ in range(row)]
return map(list, zip(*read_all))
#################
N,K = LI()
A = LI()
ans = []
for i in range(N-K):
if A[i] < A[K+i]:
ans.append('Yes')
else:
ans.append('No')
for a in ans:
print(a)
|
n, k = map(int, input().split())
data = list(map(int, input().split()))
left = 0
right = k
while right < n:
if data[left] < data[right]:
print('Yes')
else:
print('No')
left += 1
right += 1
| 1 | 7,145,636,592,550 | null | 102 | 102 |
import os, sys, re, math
S = input()
count = 0
for i in range(len(S) // 2):
if S[i] != S[-i - 1]:
count += 1
print(count)
|
import math
from decimal import *
import random
mod = int(1e9)+7
s = str(input())
n =len(s)
if(n%2==0):
s1, s2 = s[:n//2], s[n//2:][::-1]
ans =0
for i in range(len(s1)):
if(s1[i]!= s2[i]):
ans+=1
print(ans)
else:
s1, s2 = s[:(n-1)//2], s[(n-1)//2:][::-1]
ans = 0
for i in range(len(s1)):
if(s1[i]!= s2[i]):
ans+=1
print(ans)
| 1 | 120,151,354,297,170 | null | 261 | 261 |
from decimal import Decimal
A, B = input().split()
A = int(A)
if len(B) == 1:
B = int(B[0] + '00')
elif len(B) == 3:
B = int(B[0] + B[2] + '0')
else:
B = int(B[0]+B[2]+B[3])
x = str(A*B)
print(x[:-2] if len(x) > 2 else 0)
|
import math
def main() -> None:
a, b = input().split()
print((int(a)*int(b.replace('.', ''))) // 100)
return
if __name__ == '__main__':
main()
| 1 | 16,638,410,766,950 | null | 135 | 135 |
N,M=map(int,input().split())
#brr=[list(map(int,input().split())) for i in range(M)]
arr=[[] for i in range(N)]
check=[0]*N
ans=[]
for i in range(M):
a,b=map(int,input().split())
arr[a-1].append(b-1)
arr[b-1].append(a-1)
q=[]
cnt=0
for i in range(N):
if check[i]==0:
cnt+=1
q.append(i)
#print(cnt,q)
while q:
x=q.pop()
if check[x]==0:
check[x]=1
for j in arr[x]:
q.append(j)
print(cnt-1)
|
code = """
# distutils: language=c++
# distutils: include_dirs=[/home/USERNAME/.local/lib/python3.8/site-packages/numpy/core/include, /opt/ac-library]
# cython: boundscheck=False
# cython: wraparound=False
from libcpp cimport bool
from libc.stdio cimport getchar, printf
from libcpp.string cimport string
from libcpp.vector cimport vector
cdef extern from "<atcoder/dsu>" namespace "atcoder":
cdef cppclass dsu:
dsu(int n)
int merge(int a, int b)
bool same(int a, int b)
int leader(int a)
int size(int a)
vector[vector[int]] groups()
cdef class Dsu:
cdef dsu *_thisptr
def __cinit__(self, int n):
self._thisptr = new dsu(n)
cpdef int merge(self, int a, int b):
return self._thisptr.merge(a, b)
cpdef bool same(self, int a, int b):
return self._thisptr.same(a, b)
cpdef int leader(self, int a):
return self._thisptr.leader(a)
cpdef int size(self, int a):
return self._thisptr.size(a)
cpdef vector[vector[int]] groups(self):
return self._thisptr.groups()
cpdef inline vector[int] ReadInt(int n):
cdef int b, c
cdef vector[int] *v = new vector[int]()
for i in range(n):
c = 0
while 1:
b = getchar() - 48
if b < 0: break
c = c * 10 + b
v.push_back(c)
return v[0]
cpdef inline vector[string] Read(int n):
cdef char c
cdef vector[string] *vs = new vector[string]()
cdef string *s
for i in range(n):
s = new string()
while 1:
c = getchar()
if c<=32: break
s.push_back(c)
vs.push_back(s[0])
return vs[0]
cpdef inline void PrintLongN(vector[long] l):
cdef int n = l.size()
for i in range(n): printf("%ld\\n", l[i])
cpdef inline void PrintLong(vector[long] l):
cdef int n = l.size()
for i in range(n): printf("%ld ", l[i])
"""
import os, sys, getpass
if sys.argv[-1] == 'ONLINE_JUDGE':
code = code.replace("USERNAME", getpass.getuser())
open('atcoder.pyx','w').write(code)
os.system('cythonize -i -3 -b atcoder.pyx')
sys.exit(0)
from atcoder import Dsu, ReadInt
def main():
N,M = ReadInt(2)
dsu = Dsu(N)
for i in range(M):
a,b = ReadInt(2)
dsu.merge(a-1,b-1)
print(len(dsu.groups())-1)
if __name__ == "__main__":
main()
| 1 | 2,301,104,419,024 | null | 70 | 70 |
def main1():
s = input()
s1 = s[0:len(s)//2]
s2 = s[::-1]
s2 = s2[0:len(s)//2]
ans = 0
for i in range(len(s)//2):
if s1[i]==s2[i]:
continue
else:
ans+=1
print(ans)
if __name__ == '__main__':
main1()
|
x,y = map(int,input().split())
if 2*x <= y and y <= 4*x and (4*x - y) % 2 == 0:
print("Yes")
else:
print("No")
| 0 | null | 66,901,947,403,042 | 261 | 127 |
N=int(input())
if N%2:
print(0)
else:
ans=0
tmp=10
while tmp<=N:
ans+=N//tmp
tmp*=5
print(ans)
|
# dp[i][j](各マスの値) = i-1番目の品物の中からj円を支払うときの最小枚数
# → 個数制限なし
# <DP初期状態>
# i\j 0 1 2 3 ... n (お金(yen))
# 0 0 INF INF INF ... INF
# 1 0 INF INF INF ... INF
# ...
# m-1 0 INF INF INF ... INF
# m 0 INF INF INF ... INF
# (i番目のコイン)
#
# <DP遷移式>
# if(j >= c_i): c[i]のコイン採用可
# dp[i+1] = min(dp[i][j-c[i]]+1 : c[i]を採用する(コイン枚数:1枚増える)
# , dp[i][j]) : c[i]を採用しない
# , dp[i+1][j-c[i]]+1) : c[i]を重複を許して採用
# elif(j < c_j): money[i]のコイン採用不可
# dp[i+1][j] = dp[i][j] : c[i]を採用しない
n,m = map(int,input().split())
c = list(map(int,input().split()))
# DP配列の初期化
dp = []
for i in range(m+100):
tmp = [0]
for j in range(n+99): tmp.append(float('inf'))
dp.append(tmp)
# DP遷移
for i in range(m):
#print_dp(dp,i)
for j in range(n+1):
if(j>=c[i]): # i番目のコイン採用可
dp[i+1][j] = min(dp[i][j-c[i]]+1,
dp[i][j],
dp[i+1][j-c[i]]+1)
else: # i番目のコイン採用不可
dp[i+1][j] = dp[i][j]
#print_dp(dp,i+1)
# 出力
print(dp[m][n])
| 0 | null | 58,098,367,923,870 | 258 | 28 |
N = int(input())
X = list(map(int, input().split()))
ans = [0] * (N + 1)
for v in X:
ans[v] += 1
print(*ans[1:], sep="\n")
|
N = int(input())
ans = 0
cnt = 1
while N > 0:
if N == 1:
ans += cnt
break
N //= 2
ans += cnt
cnt *= 2
print(ans)
| 0 | null | 56,186,816,096,510 | 169 | 228 |
N = int(input())
S = [str(input()) for _ in range(N)]
S = set(S)
print(len(S))
|
N = int(input())
#リスト内包表記
Ss = [input() for _ in range(N)]
Ss_set = set(Ss)
print(len(Ss_set))
| 1 | 30,140,280,839,592 | null | 165 | 165 |
# coding: utf-8
import numpy as np
from numba import i8, njit
@njit(i8[:](i8, i8[:]), cache=True)
def f(k, A):
n = len(A)
cur = A
for _ in range(k):
prev = cur
cur = np.zeros_like(A)
for x, p in enumerate(prev):
cur[max(0, x-p)] += 1
if x+p+1 < n:
cur[x+p+1] -= 1
satulated = True
for i in range(1, n):
cur[i] += cur[i-1]
satulated &= cur[i] == n
if satulated:
break
return cur
def solve(*args: str) -> str:
n, k = map(int, args[0].split())
A = np.array(tuple(map(int, args[1].split())))
return ' '.join(map(str, f(k, A)))
if __name__ == "__main__":
print(solve(*(open(0).read().splitlines())))
|
print(eval(input().replace(*' *')))
| 0 | null | 15,553,198,755,880 | 132 | 133 |
n = 0
T=""
s= input().lower()
while True:
t=input()
T += t + " "
if T.count("END_OF_TEXT")>0:
break
TL = T.split(" ")
for i in TL:
i = i.replace('"','')
i= i.replace(".","")
if i.lower() == str(s):
n += 1
else:
pass
print (n)
|
#! /usr/bin/env python3
import sys
get = sys.stdin.read().split('\n')
for g in get:
nums = list(map(int, g.split()))
output = ''
if (nums != []):
# print(nums)
[a, b] = nums
while ((a != 0) and (b != 0)):
larger = max([a, b])
smaller = min([a, b])
a = larger - smaller
b = smaller
output += str(max([a, b])) + ' ' + str((nums[0]*nums[1])//max([a,b]))
print(output)
| 0 | null | 922,940,046,632 | 65 | 5 |
N=input()
A=list(map(int,input().split()))
m=1000
tmp = A[0]
stock=0
for i,ai in enumerate(A):
if tmp>=ai:
m+=tmp*stock
stock=0
if ai < max(A[i:]):
stock=m//ai
m-=ai*stock
tmp = ai
print(m+stock*A[-1])
|
n = int(input())
a = list(map(int, input().split()))
money = 1000
kabu = 0
for i in range(n-1):
if a[i] < a[i+1]:
kabu += money//a[i]
money %= a[i]
else:
money += kabu * a[i]
kabu = 0
if kabu > 0:
money += kabu*a[n-1]
print(money)
| 1 | 7,409,618,361,418 | null | 103 | 103 |
n=int(input())
a=list(map(int,input().split()))
b=[]
for i in range(n):
tmp=[i+1,a[i]]
b.append(tmp)
b=sorted(b,key=lambda x:x[1])
ans=[]
for j in b:
ans.append(j[0])
print(*ans)
|
import sys
import math
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
MOD = 10**9+7
N = int(input())
dic = defaultdict(int)
zero = 0
left_zero = 0
right_zero = 0
for i in range(N):
a, b = map(int, input().split())
if b < 0:
a = -a
b = -b
if a == 0 and b == 0:
zero += 1
elif a == 0:
left_zero += 1
elif b == 0:
right_zero += 1
else:
g = math.gcd(a, b)
a //= g
b //= g
dic[a,b] += 1
done = set()
ans = 1
for a,b in dic:
k = (a, b)
if k in done: continue
rk = (-b, a)
rk2 = (b, -a)
done.add(k)
done.add(rk)
done.add(rk2)
c = pow(2, dic[k], MOD)-1
if rk in dic:
c += pow(2, dic[rk], MOD)-1
if rk2 in dic:
c += pow(2, dic[rk2], MOD)-1
c += 1
ans *= c
ans %= MOD
c1 = pow(2, left_zero, MOD)-1
c2 = pow(2, right_zero, MOD)-1
c = c1+c2+1
ans *= c
ans += zero
print((ans-1)%MOD)
| 0 | null | 100,477,039,316,018 | 299 | 146 |
# https://atcoder.jp/contests/nikkei2019-2-qual/tasks/nikkei2019_2_qual_b
# まず、本当に木を構築するモノではないだろう
from collections import Counter
n = int(input())
nums = [int(i) for i in input().split()]
mod = 998244353
MAX = max(nums)
c = Counter(nums)
if nums[0] != 0 or nums.count(0) != 1:
ans = 0
else:
ans = 1
for i in range(1, MAX + 1):
ans = ans * pow(c.get(i - 1, 0), c.get(i, 0), mod) % mod
ans %= mod
print(ans)
|
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import Counter
n=int(input())
d=lnii()
mod=998244353
c=Counter(d)
max_key=max(d)
if d[0]!=0 or c[0]!=1:
print(0)
exit()
ans=1
patterns=1
for i in range(max_key+1):
p_num=c[i]
ans*=patterns**p_num
ans%=mod
patterns=p_num
print(ans)
| 1 | 154,949,896,173,512 | null | 284 | 284 |
import sys
sys.setrecursionlimit(2000)
def joken(a,n):
if n==1:
return 0
elif a%n==0 and a//n>=n:
return joken(a//n,n)
elif a%n==1:
return 1
elif a%n==0 and a//n==1:
return 1
else:
return 0
def make_divisors(n):
lower_divisors , upper_divisors = [], []
i = 1
while i*i <= n:
if n % i == 0:
lower_divisors.append(i)
if i != n // i:
upper_divisors.append(n//i)
i += 1
return lower_divisors + upper_divisors[::-1]
N=int(input())
c=len(make_divisors(N-1))
d=make_divisors(N)
a=0
for i in range(len(d)):
a+=joken(N,d[i])
print(a+c-1)
|
nums = []
while True:
num = [int(e) for e in input().split()]
if num[0]==0 and num[1]==0:
break
nums.append(num)
for i in range(len(nums)):
for j in range(len(nums[i])):
for k in range(j):
if nums[i][k] > nums[i][j]:
a = nums[i][k]
nums[i][k] = nums[i][j]
nums[i][j] = a
for i in range(len(nums)):
print(" ".join(map(str, nums[i])))
| 0 | null | 20,772,313,549,658 | 183 | 43 |
S=input()
N=len(S)
S=list(S)
ct=0
for i in range(N//2):
if S[i]!=S[-i-1]:
ct+=1
print(ct)
|
S = input()
hug = 0
if len(S) % 2 == 0:
for i in range(int(len(S)/2)):
if not S[i] == S[-i-1]:
hug += 1
else:
pass
else:
for i in range(int((len(S)+1)/2)):
if not S[i] ==S[-i-1]:
hug += 1
else:
pass
print(hug)
| 1 | 119,994,439,898,272 | null | 261 | 261 |
# -*- coding: utf-8 -*-
# combinationを使う
import math
def comb(n, r):
return math.factorial(n) // (math.factorial(r) * math.factorial(n - r))
n, m = map(int, input().split())
counter = 0
if n >= 2:
counter = counter + comb(n, 2)
if m >= 2:
counter = counter + comb(m, 2)
print(counter)
|
A,B,C=map(int,input().split())
if len(set([A,B,C]))==2:print('Yes')
else:print('No')
| 0 | null | 56,958,220,917,466 | 189 | 216 |
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(buff_readline())
def read_int_n():
return list(map(int, buff_readline().split()))
def read_float():
return float(buff_readline())
def read_float_n():
return list(map(float, buff_readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
@mt
def slv(N, A):
sa = [0]
for a in A:
sa.append(sa[-1]+a)
if N == 0:
if A[0] == 1:
return 1
else:
return -1
if A[0] != 0:
return -1
ans = 1
p = 1
for i in range(1, N+1):
m = min(p*2, sa[-1] - sa[i])
ans += m
if m - A[i] < 0:
return -1
p = m - A[i]
return ans
def main():
N = read_int()
A = read_int_n()
print(slv(N, A))
if __name__ == '__main__':
main()
|
a,b,c,d=map(int, input().split())
if b<0 and c>0:
print(c*b)
elif d<0 and a>0:
print(d*a)
elif b>=0 or d>=0:
print(max(b*d,a*c))
else:
print(a*c)
| 0 | null | 10,870,078,335,920 | 141 | 77 |
import sys
input = sys.stdin.readline
h,n = map(int,input().split())
ab = [list(map(int,input().split()))for i in range(n)]
amx = 0
for i in range(n):
if amx < ab[i][0]:
amx = ab[i][0]
#dp[i] = モンスターの削る体力がiの時の魔力の消費の最小値
dp = [float('inf')]*(amx + h + 1)
dp[0] = 0
for i in range(amx + h + 1):
for m in ab:
if i-m[0] >= 0:
dp[i] = min(dp[i], dp[i-m[0]] + m[1])
ans = float('inf')
for i in range(h,amx + h + 1):
ans = min(ans, dp[i])
print(ans)
|
n_s = list(input().rstrip())
n_t = list(input().rstrip())
cnt = 0
for i in range(len(n_s)):
if n_s[i] != n_t[i]:
cnt += 1
print(cnt)
| 0 | null | 45,878,750,243,612 | 229 | 116 |
import sys, re
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
from collections import deque, defaultdict, Counter
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop, heapify
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
class UnionFind():
def __init__(self, n):
self.n = n
# parents[i]: 要素iの親要素の番号
# 要素iが根の場合、parents[i] = -(そのグループの要素数)
self.parents = [-1] * n
def find(self, x):
if 0 > self.parents[x]:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
# 要素xが属するグループの要素数を返す
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
# 要素xが属するグループに属する要素をリストで返す
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
# 全ての根の要素をリストで返す
def roots(self):
return [i for i, x in enumerate(self.parents) if 0 > x]
# グループの数を返す
def group_count(self):
return len(self.roots())
# 辞書{根の要素: [そのグループに含まれる要素のリスト], ...}を返す
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
# print()での表示用
# all_group_members()をprintする
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
N, M, K = MAP()
tree = UnionFind(N)
friends = [[] for _ in range(N)]
for _ in range(M):
A, B = MAP()
tree.union(A-1, B-1)
friends[A-1].append(B-1)
friends[B-1].append(A-1)
blocks = [[] for _ in range(N)]
for _ in range(K):
C, D = MAP()
blocks[C-1].append(D-1)
blocks[D-1].append(C-1)
for i in range(N):
blocks_cnt = sum([tree.same(i, j) for j in blocks[i]])
print(tree.size(i) - len(friends[i]) - 1 - blocks_cnt, end=" ")
print()
|
s = input()
a = 0
if(len(s)%2 == 1):
print('No')
else:
for i in range(len(s)//2):
if(s[2*i] != 'h' or s[2*i+1] != 'i'):
a = 1
print('No')
break
if(a == 0):
print('Yes')
| 0 | null | 57,307,471,986,040 | 209 | 199 |
N, M = map(int, input().split())
ans = []
if N % 2 == 1:
l, r = 1, N - 1
while l < r:
ans.append((l, r))
l += 1
r -= 1
else:
l, r = 1, N - 1
flag = False
while l < r:
if not flag and r - l <= N // 2:
r -= 1
flag = True
ans.append((l, r))
l += 1
r -= 1
for i in range(M):
print(ans[i][0], ans[i][1])
|
N,M=map(int,input().split())
x=list(range(1,N+1,1))
if N%2==1:
for i in range(M):
print(x.pop(0),x.pop(-1))
else:
x_f=x[1:int(N/2+1)]
x_l=x[int(N/2+1):]
count=0
for i in range(M):
if len(x_f)>1:
print(x_f.pop(0),x_f.pop(-1))
count+=1
if count==M:
break
if len(x_l)>1:
print(x_l.pop(0),x_l.pop(-1))
count+=1
if count==M:
break
| 1 | 28,674,830,781,520 | null | 162 | 162 |
N, X, M = map(int, input().split())
A = X
ans = A
visited = [0]*M
tmp = []
i = 2
while i <= N:
A = (A*A) % M
if visited[A] == 0:
visited[A] = i
tmp.append(A)
ans += A
else:
ans += A
loop_length = i-visited[A]
loop_val = tmp[-1*loop_length:]
loop_count = (N-i) // loop_length
ans += sum(loop_val) * loop_count
visited = [0]*M
i += loop_length * loop_count
i += 1
print(ans)
|
N = int(input())
C = {}
for _ in range(N):
s = input().strip()
if s not in C:
C[s] = 0
C[s] += 1
print(len(C))
| 0 | null | 16,552,051,486,688 | 75 | 165 |
def bubbleSort(A, N):
swap = 0
flag = True
while flag:
flag = False
for j in range(N-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
N = int(input())
A = list(map(int,input().split()))
swap=bubbleSort(A,N)
print(" ".join(map(str,A)))
print (swap)
|
def solve():
for i in range(1,10):
for j in range(1,10):
print("{0}x{1}={2}".format(i,j,i*j))
solve()
| 0 | null | 7,989,609,728 | 14 | 1 |
n,m = map(int,input().split())
ans = 0
for i in range(n-1):
ans = ans + i+1
for b in range(m-1):
ans = ans + b+1
print(ans)
|
score = list(map(int,input().split()))
if score[0] == 1:
evennum = 0
else:
evennum = score[0]*(score[0]-1)/2
if score[1] == 1:
oddnum = 0
else:
oddnum = score[1]*(score[1]-1)/2
print(int(evennum+oddnum))
| 1 | 45,477,223,489,500 | null | 189 | 189 |
H, W, K = map(int, input().split())
S = [list(input()) for _ in range(H)]
res = float('inf')
for i in range(2**(H-1)):
c = bin(i).count('1')
cnt = c
sum_l = [0] * (c+1)
j = 0
flag = True
while j < W:
tmp = sum_l.copy()
pos = 0
for k in range(H):
if S[k][j] == '1':
tmp[pos] += 1
if (i >> k) & 1:
pos += 1
if max(tmp) <= K:
sum_l = tmp.copy()
j += 1
flag = False
else:
if flag:
cnt = float('inf')
break
cnt += 1
flag = True
sum_l = [0] * (c+1)
res = min(res, cnt)
print(res)
|
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)
def main():
h,w,k = LI()
aa = [[int(c) for c in S()] for _ in range(h)]
def f(hs):
l = len(hs)
c = [0] * l
r = l - 1
for i in range(w):
nc = [0] * l
bf = False
for j in range(l):
for h in hs[j]:
nc[j] += aa[h][i]
if nc[j] > k:
return -1
if nc[j] + c[j] > k:
bf = True
if bf:
r += 1
c = nc
else:
for j in range(l):
c[j] += nc[j]
return r
r = inf
for bi in range(2**(h-1)):
hs = [[0]]
for i in range(h-1):
if 2**i & bi > 0:
hs.append([])
hs[-1].append(i+1)
t = f(hs)
if t >= 0 and r > t:
r = t
return r
print(main())
| 1 | 48,647,228,307,612 | null | 193 | 193 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)
# mod = 10 ** 9 + 7
mod = 998244353
def read_values():
return map(int, input().split())
def read_index():
return map(lambda x: int(x) - 1, input().split())
def read_list():
return list(read_values())
def read_lists(N):
return [read_list() for n in range(N)]
class V:
def __init__(self, f, v=None):
self.f = f
self.v = v
def __str__(self):
return str(self.v)
def ud(self, n):
if n is None:
return
if self.v is None:
self.v = n
return
self.v = self.f(self.v, n)
def main():
N, P = read_values()
S = input().strip()
if P in (2, 5):
res = 0
for i, s in enumerate(S):
if int(s) % P == 0:
res += i + 1
print(res)
else:
r = 0
D = {0: 1}
res = 0
d = 1
for i, s in enumerate(S[::-1]):
r += int(s) * d
r %= P
d *= 10
d %= P
c = D.setdefault(r, 0)
res += c
D[r] += 1
print(res)
if __name__ == "__main__":
main()
|
N,P = map(int, input().split())
S = input()
"""
たとえばSが 123456789 だとすると
3456 = (3456789 - 789) // 1000
と表せる。
これがPで割り切れる場合、基本的には 3456789 と 789 がPで割り切れるとよい。
これはPと 10**x が互いに素の場合。
なので、10**x とPが互いに素の場合は、
・S[l:]をPで割った時余りがXXXになるものが何個、という情報を、Sの右端から集めていく。ただし、
・あるindexのlのS[l:]を見ているときに、その部分をPで割って余りがKになるなら、そのlに対してlより右にあるrについて、
S[r:]をPで割った余りがKになるようにrを選んでS[l:r]を作ると、Pで割り切れる数字が得られる。その時点でのmod P = Kの個数に対応する。
ただし、rに何も選ばない場合(lから端までを数字にする場合)もあるので、これも考慮に入れる。
Pが10と互いに素でない場合は、2と5がありうる。
これについて、それぞれ末尾が2の倍数か5の倍数であれば割り切れるので、
Sを左から見ていって、その数字が見つかれば、そのindexをふくむ左の位置で数字を作ればPで割れる数字ができる
"""
ans = 0
if P in [2, 5]:
for i in range(N):
if int(S[i]) % P == 0:
ans += i+1
else:
mod_P = [0] * P
mod_P[0] += 1
# Sを右端から何個かまで見てできる数字をPで割ってできる余り。
# 数字のまま持っておいて、都度mod P をとるとTLEになるので。
# 3543 で 3543 % P = (3000 + 543) % P のような感じで右から左にSを見ていく
curr = 0
for i in range(N):
curr = curr + int(S[N-1-i]) * pow(10, i, P)
curr %= P
ans += mod_P[curr]
mod_P[curr] += 1
print(ans)
| 1 | 57,871,815,303,558 | null | 205 | 205 |
from math import atan, degrees
def main():
a, b, x = map(int, input().split())
# xが多い場合:水が三角形になる前に溢れるパターン
if (a**2*b) / 2 < x:
# 水じゃないところが三角形 を area
area = a * b - x/a
c = 2 * area / a
# thetaが逆だから
t = c / a
ans = degrees(atan(t))
else:
# 面積で考えるので水の量/奥行き
area = x / a
c = 2 * area / b
t = b / c
ans = degrees(atan(t))
print(ans)
if __name__ == '__main__':
main()
|
S=input()
N=len(S)
S=list(S)
ct=0
for i in range(N//2):
if S[i]!=S[-i-1]:
ct+=1
print(ct)
| 0 | null | 141,088,239,671,580 | 289 | 261 |
S = input()
if(S == 'RRR'):
print(3)
elif(S=='RRS' or S=='SRR'):
print(2)
elif(S == 'SSS'):
print(0)
else:
print(1)
|
s = input()
ans = 0
for i in range(0, 3):
if s[i] == 'R':
ans += 1
if ans == 2 and s[1] == 'S':
ans -= 1
print(ans)
| 1 | 4,910,930,951,940 | null | 90 | 90 |
n = int(input())
s = []
t = []
for i in range(n):
s_, t_ = map(str, input().split())
s.append(s_)
t.append(int(t_))
x = input()
for i in range(n):
if s[i] == x:
break
ans = 0
for j in range(n-1, i, -1):
ans += t[j]
print(ans)
|
from collections import deque
N = int(input())
# 有向グラフと見る、G[親] = [子1, 子2, ...]
G = [[] for _ in range(N + 1)]
# 子ノードを記録、これで辺の番号を管理
G_order = []
# a<bが保証されている、aを親、bを子とする
for i in range(N - 1):
a, b = map(lambda x: int(x) - 1, input().split())
G[a].append(b)
G_order.append(b)
# どこでも良いが、ここでは0をrootとする
que = deque([0])
# 各頂点と「親」を結ぶ辺の色
# 頂点0をrootとするのでC[0]=0で確定(「無色」), 他を調べる
colors = [0] * N
# BFS
while que:
# prt = 親
# 幅優先探索
prt = que.popleft()
color = 0
# cld = 子
for cld in G[prt]:
color += 1
# 「今考えている頂点とその親を結ぶ辺の色」と同じ色は使えないので次の色にする
if color == colors[prt]:
color += 1
colors[cld] = color
que.append(cld)
# それぞれの頂点とその親を結ぶ辺の色
# print(colors)
# 必要な最小の色数
print(max(colors))
# 辺の番号順に色を出力
for i in G_order:
print(colors[i])
| 0 | null | 117,050,747,172,198 | 243 | 272 |
K,N = map(int,input().split())
A = list(map(int,input().split()))
tmin = 2*K
for i in range(1,N):
tmin = min(tmin,K-(A[i]-A[i-1]))
tmin = min(tmin,A[N-1]-A[0])
print(tmin)
|
k, n = map(int, input().split())
a = sorted(map(int, input().split()))
ans = a[-1]-a[0]
for i in range(1, n-1):
path = k- a[-i] + a[-i-1]
ans = min(ans, path)
print(ans)
| 1 | 43,393,921,669,998 | null | 186 | 186 |
# -*- coding: utf-8 -*-
def main():
A = int(input())
B = int(input())
for i in range(1, 4):
if i != A and i != B:
ans = i
print(ans)
if __name__ == "__main__":
main()
|
t=int(input())
if t==0:
print("1")
elif t==1:
print("0")
| 0 | null | 56,700,582,743,948 | 254 | 76 |
S = input()
T = input()
ans = 0
for i in range(len(S)):
if S[i] == T[i]:
continue
ans += 1
print(ans)
|
input_line = input()
input_line_cubic = input_line ** 3
print input_line_cubic
| 0 | null | 5,337,197,488,320 | 116 | 35 |
days = ['SUN','MON','TUE','WED','THU','FRI','SAT']
s = input()
x = days.index(s)
print(7-x)
|
import math
x = int(input())
n = 100
i = 0
while n < x:
# 複利の計算方法がわかっていない
n = n * 101 // 100
i += 1
print(i)
| 0 | null | 80,335,497,050,632 | 270 | 159 |
import sys
A,B,C,D = map(int,input().split())
while True:
C -= B
if C <= 0:
print("Yes")
sys.exit()
A -= D
if A <= 0:
print("No")
sys.exit()
|
import math
from math import gcd
INF = float("inf")
import sys
input=sys.stdin.readline
sys.setrecursionlimit(500*500)
import itertools
from collections import Counter,deque
def main():
a,b,c,d = map(int, input().split())
while True:
c -= b
if c<= 0:
print("Yes")
exit()
a -= d
if a <= 0:
print("No")
exit()
if __name__=="__main__":
main()
| 1 | 29,712,217,285,348 | null | 164 | 164 |
A,B,M = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
x = []
y = []
c = []
for _ in range(M):
X,Y,Z = map(int,input().split())
x.append(X)
y.append(Y)
c.append(Z)
mini = min(a) + min(b)
for i in range(M):
rei = a[x[i]-1]
den = b[y[i]-1]
coop = c[i]
if rei + den - coop < mini:
mini = rei + den - coop
print(mini)
|
lst1 = input().split()
A = int(lst1[0])
B = int(lst1[1])
M = int(lst1[2])
list_A = input().split()
list_B = input().split()
for i in range(A):
list_A[i] = int(list_A[i])
for i in range(B):
list_B[i] = int(list_B[i])
result = min(list_A) + min(list_B)
list_M = []
for i in range(M):
lst2 = input().split()
n = list_A[int(lst2[0]) - 1] + list_B[int(lst2[1]) - 1] - int(lst2[2])
if n < result:
result = n
print(result)
| 1 | 54,024,379,361,538 | null | 200 | 200 |
Nin = int(input())
a = [input() for i in range(Nin)]
ac = 0
wa = 0
tle = 0
re = 0
for i in range(Nin):
if a[i] == "AC":
ac += 1
elif a[i] == "WA":
wa += 1
elif a[i] == "TLE":
tle += 1
elif a[i] == "RE":
re += 1
print("AC x", ac)
print("WA x", wa)
print("TLE x", tle)
print("RE x", re)
|
n,k = map(int,input().split())
keta = 1
while True:
if n >= k:
n = n//k
keta += 1
else:
break
print(keta)
| 0 | null | 36,765,086,323,250 | 109 | 212 |
def prepare(n, MOD):
f = 1
factorials = [1]
for m in range(1, n + 1):
f *= m
f %= MOD
factorials.append(f)
inv = pow(f, MOD - 2, MOD)
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
n, k = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
MOD = 10 ** 9 + 7
facts, invs = prepare(n, MOD)
ans_max = 0
for i in range(k - 1, n):
ans_max += (arr[i] * facts[i] * invs[k - 1] * invs[i - k + 1]) % MOD
arr.sort(reverse=True)
ans_min = 0
for i in range(k - 1, n):
ans_min += (arr[i] * facts[i] * invs[k - 1] * invs[i - k + 1]) % MOD
print((ans_max - ans_min) % MOD)
|
n,k=map(int,input().split())
A=sorted(list(map(int,input().split())))
F=sorted(list(map(int,input().split())),reverse=True)
ng=-1
ok=10**12+10
while ok-ng>1:
mid=(ok+ng)//2
a=0
for i in range(n):
a=a+max(0,A[i]-mid//F[i])
if a>k:
ng=mid
else:
ok=mid
print(ok)
| 0 | null | 130,476,794,749,742 | 242 | 290 |
while True:
(x, y) = [int(i) for i in input().split()]
if x == y == 0:
break
if x < y:
print(x, y)
else:
print(y, x)
|
a, b, c, d, K = map(int, input().split())
hour = (c-a) * 60
min = d - b
ans = hour + min - K
print(ans)
| 0 | null | 9,259,290,605,088 | 43 | 139 |
s = input()
l = []
for i in range(len(s)):
l.append(s[i])
if l[len(l)-1] == "s":
print(s+str("es"))
else:
print(s+str("s"))
|
x = input()
if x[-1] in 'sS':
x += 'es'
else:
x += 's'
print(x)
| 1 | 2,430,218,960,868 | null | 71 | 71 |
def main():
import numpy as np
n=int(input())
a=list(enumerate(map(int,input().split())))
a.sort(key=lambda x: -x[1])
dp=[np.zeros(i+1,dtype=np.int64) for i in range(n+1)]
dp[0]=np.zeros(1,dtype=np.int64)
r=np.arange(n+1,dtype=np.int64)
for time,ix in enumerate(a):
i,x=ix
dp[time+1][1:]=dp[time][:time+1]+(i-r[:time+1])*x
np.maximum(dp[time+1][:-1],dp[time]+((n-1-(time-r[:time+1]))-i)*x,out=dp[time+1][:-1])
print(np.max(dp[n]))
main()
|
def main():
n=int(input())
A=list(zip(list(map(int,input().split())),range(n)))
A.sort(reverse=True)
DP=[[0]*(n+1) for _ in range(n+1)]
for i in range(n+1):
for j in range(n+1):
if i+j>n:
break
a,idx=A[i+j-1]
if i>0:
DP[i][j]=max(DP[i][j],DP[i-1][j]+a*abs(idx-(i-1)))
if j>0:
DP[i][j]=max(DP[i][j],DP[i][j-1]+a*abs(idx-(n-j)))
ans=0
for i in range(n+1):
ans=max(ans,DP[i][n-i])
print(ans)
if __name__=='__main__':
main()
| 1 | 33,706,264,323,854 | null | 171 | 171 |
import bisect
from collections import deque
import math
n, d, A = map(int, input().split())
xh = []
for _ in range(n):
x, h = map(int, input().split())
xh.append([x, h])
xh.sort(key=lambda x: x[0])
monster_x = []
monster_hp = []
for i in range(n):
monster_x.append(xh[i][0])
monster_hp.append(xh[i][1])
dist = 2 * d
ans = 0
damage = 0
cum_damage = [0] * (n + 1)
for i in range(n):
cum_damage[i + 1] += cum_damage[i]
damage = cum_damage[i + 1] * A
if damage < monster_hp[i]:
min_attack_num = math.ceil((monster_hp[i] - damage) / A)
index = bisect.bisect_right(monster_x, monster_x[i] + dist)
cum_damage[i + 1] += min_attack_num
if index < n:
t = min(index + 1, n)
cum_damage[t] -= min_attack_num
ans += min_attack_num
print(ans)
|
import sys
def input():
return sys.stdin.readline().strip()
n, d, a = map(int, input().split())
x = []
h = {} # x:h
for _ in range(n):
i, j = map(int, input().split())
x.append(i)
h[i] = j
x.sort()
x.append(x[-1] + 2*d + 1)
# attackで累積和を用いる
ans = 0
attack = [0 for _ in range(n+1)]
for i in range(n):
attack[i] += attack[i-1]
if attack[i] >= h[x[i]]:
continue
if (h[x[i]] - attack[i]) % a == 0:
j = (h[x[i]] - attack[i]) // a
else:
j = (h[x[i]] - attack[i]) // a + 1
attack[i] += a * j
ans += j
# 二分探索で、x[y] > x[i] + 2*d、を満たす最小のyを求める
# start <= y <= stop
start = i + 1
stop = n
k = stop - start + 1
while k > 1:
if x[start + k//2 - 1] <= x[i] + 2*d:
start += k//2
else:
stop = start + k//2 - 1
k = stop - start + 1
attack[start] -= a * j
print(ans)
| 1 | 82,556,538,785,280 | null | 230 | 230 |
A, B, C, D = map(int, input().split())
while True:
# 高橋
C -= B
if C <= 0:
print('Yes')
break
# 青木
A -= D
if A <= 0:
print('No')
break
|
n, k = map(int, input().split())
okashi = set()
for _ in range(k):
d = int(input())
lst = [int(i) for i in input().split()]
for i in range(d):
if lst[i] not in okashi:
okashi.add(lst[i])
count = 0
for i in range(n):
if i + 1 not in okashi:
count += 1
print(count)
| 0 | null | 26,995,370,304,646 | 164 | 154 |
from collections import Counter
import itertools
n=int(input())
rgb=list(input())
rgb_counter=Counter(rgb)
n_list=[i for i in range(1,n+1)]
count=0
for i,j in itertools.combinations(n_list,2):
k=2*j-i
if k<=n and rgb[j-1]!=rgb[i-1] and rgb[j-1]!=rgb[k-1] and rgb[i-1]!=rgb[k-1]:
count+=1
print(rgb_counter["R"]*rgb_counter["G"]*rgb_counter["B"]-count)
|
# F - Sugoroku
import sys
sys.setrecursionlimit(10 ** 9)
n,m = map(int,input().split())
s = input()
# r[i]:sを後ろから見ていって、iから最小何手でゴールするかを求める。
INF = float('inf')
r = [INF for _ in range(n+1)]
r[n] = 0
idx = n
for i in range(n-1,-1,-1):
while(idx-i > m or r[idx] == INF):
idx -= 1
if idx <= i:
print(-1)
exit()
if s[i] == '0':
r[i] = r[idx]+1
p = r[i]
#print(r)
# rを先頭から見ていき、rの数字が変わる直前まで進むようにすれば
# 最短で辞書順最小なルートが求まる。
ans = []
c = 0
for i in range(n+1):
if r[i] != INF and r[i] != p:
p = r[i]
ans.append(c)
c = 1
else:
c += 1
print(*ans)
# mnr = [m for _ in range(n+1)]
# mnl = n+1
# def dfs(x,c):
# global mnr,mnl
# #print(x,c)
# if x == n:
# #print(r)
# if len(r) < mnl or (len(r) == mnl and r < mnr):
# mnr = r[:]
# mnl = len(r)
# return True
# if c >= mnl or x > n or s[x] == '1':
# return False
# for i in range(m,0,-1):
# r.append(i)
# dfs(x+i,c+1)
# r.pop()
# dfs(0,0)
# if mnl < n+1:
# print(*mnr)
# else:
# print(-1)
| 0 | null | 87,900,219,643,872 | 175 | 274 |
from math import *
x1, y1, x2, y2 = map(float, input().split())
print(hypot(x1 - x2, y1 - y2))
|
import numpy as np
a, b, c, d = map(int, input().split())
x = np.array([a, b])
y = np.array([c, d])
z = np.outer(x, y)
print(z.max())
| 0 | null | 1,578,449,349,840 | 29 | 77 |
from math import sqrt
a,b,c,d = map(float,input().split())
print(sqrt((c-a)**2+(d-b)**2))
|
x, y = map(int, input().split())
if y >= x:
print("unsafe")
else:
print("safe")
| 0 | null | 14,801,180,948,898 | 29 | 163 |
for i in range(9):
for j in range(9):
print("{}x{}={}".format(i+1,j+1,(i+1)*(j+1)))
|
# usr/bin/python
# coding: utf-8
################################################################################
#Write a program which prints multiplication tables in the following format:
#
#1x1=1
#1x2=2
#.
#.
#9x8=72
#9x9=81
#
################################################################################
if __name__ == "__main__":
for i in range(1, 10):
for j in range(1, 10):
print("{0}x{1}={2}".format(i,j,i*j))
exit(0)
| 1 | 1,501,368 | null | 1 | 1 |
def search(n):
res = 0
while n:
n %= bin(n).count("1")
res += 1
return res
def main():
n = int(input())
x = list(input())
x_decimal = int("".join(map(str, x)), 2)
first_mod = sum(map(int, list(x)))
increase_mod = first_mod + 1
increase_base = x_decimal % increase_mod # 反転させる桁が元々0だった場合
decrease_mod = first_mod - 1
if decrease_mod:
decrease_base = x_decimal % decrease_mod # 反転させる桁が元々1だった場合
for i in range(n):
cnt = 0
if x[i] == "1" and decrease_mod:
cnt = 1 + search((decrease_base - pow(2, n - i - 1, decrease_mod)) % decrease_mod)
elif x[i] == "0":
cnt = 1 + search((increase_base + pow(2, n - i - 1, increase_mod)) % increase_mod)
print(cnt)
if __name__ == '__main__':
main()
|
from collections import Counter
S = input()
S = S[::-1]
# 1桁のmod2019, 2桁の2019, ...
# 0桁のmod2019=0と定めると都合が良いので入れておく
l = [0]
num = 0
for i in range(len(S)):
# 繰り返し二乗法で累乗の部分を高速化
# 自分で書かなくてもpow()で既に実装されている
# 一つ前のmodを利用するとPythonで通せた、それをしなくてもPyPyなら通る
num += int(S[i]) * pow(10,i,2019)
l.append(num % 2019)
# print(l)
ans = 0
c = Counter(l)
for v in c.values():
ans += v*(v-1)//2
print(ans)
| 0 | null | 19,641,788,970,760 | 107 | 166 |
from math import floor,ceil,sqrt,factorial,log
from collections import Counter, deque
from functools import reduce
import itertools
def S(): return input()
def I(): return int(input())
def MS(): return map(str,input().split())
def MI(): return map(int,input().split())
def FLI(): return [int(i) for i in input().split()]
def LS(): return list(MS())
def LI(): return list(MI())
def LLS(): return [list(map(str, l.split() )) for l in input()]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def LLSN(n: int): return [LS() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
N = I()
A = LI()
ans = True
for a in A:
if a % 2 != 0:
continue
if a % 3 != 0 and a % 5 != 0:
ans = False
if ans:
print("APPROVED")
else:
print("DENIED")
|
N=input()
n=N[-1]
if n=='3':
ans='bon'
elif n=='0' or n=='1' or n=='6' or n=='8':
ans='pon'
else:
ans='hon'
print(ans)
| 0 | null | 44,320,313,243,830 | 217 | 142 |
clr = list(map(int, input().split()))
k = int(input())
for i in range(k):
if clr[2] <= clr[1] :
clr[2] *= 2
elif clr[1] <= clr[0]:
clr[1] *= 2
else:
break
if clr[2] > clr[1] > clr[0] :
print("Yes")
else:
print("No")
|
INF = 10 ** 20
n, m = map(int, input().split())
c_lst = list(map(int, input().split()))
dp = [INF for _ in range(n + 1)]
dp[0] = 0
for coin in c_lst:
for price in range(coin, n + 1):
dp[price] = min(dp[price], dp[price - coin] + 1)
print(dp[n])
| 0 | null | 3,504,032,560,170 | 101 | 28 |
import fractions
lst = []
for i in range(200):
try:
lst.append(input())
except EOFError:
break
nums = [list(map(int, elem.split(' '))) for elem in lst]
# gcd
res_gcd = [fractions.gcd(num[0], num[1]) for num in nums]
# lcm
res_lcm = [nums[i][0] * nums[i][1] // res_gcd[i] for i in range(len(nums))]
for (a, b) in zip(res_gcd, res_lcm):
print('{} {}'.format(a, b))
|
a,b,c,d=map(int,input().split())
for i in range(a, 0, -d):
c=c-b
a=a-d
if c<=0:
print("Yes")
else:
print("No")
| 0 | null | 14,798,509,476,322 | 5 | 164 |
import bisect
n=int(input())
a=list(map(int,input().split()))
suma=[]
sumans=0
for i in range(n):
sumans += a[i]
suma.append(sumans)
u=bisect.bisect_right(suma, sumans//2)
print(min(abs(2*suma[u-1]-sumans), abs(2*suma[u]-sumans)))
|
import numpy
N = int(input())
A = list(map(int, input().split()))
res = numpy.cumsum(A)
if res[-1] % 2 == 0:
L = res[-1]//2
ans = [abs(r - L) for r in res]
print(2*min(ans))
else:
L1 = res[-1]//2
L2 = L1 + 1
ans = [min(abs(r - L1),abs(r-L2)) for r in res]
print(2*min(ans)+1)
| 1 | 142,152,546,239,318 | null | 276 | 276 |
ary = list(map(int, input().split()))
print('Yes' if len(set(ary)) == 2 else 'No')
|
def RSQ_add(i, x, y):
while True:
if i > n:
break
BIT[y][i] += x
i += i & -i
def RSQ_getsum(i, x):
s = 0
while True:
if i <= 0:
break
s += BIT[x][i]
i -= i & -i
return s
n = int(input())
s = list(input())
q = int(input())
BIT = [[0] * (n + 1) for _ in range(26)]
for i in range(n):
y = ord(s[i]) - 97
RSQ_add(i + 1, 1, y)
for _ in range(q):
com, a, b = map(str, input().split())
com, a = int(com), int(a)
if com == 1:
RSQ_add(a, -1, ord(s[a - 1]) - 97)
RSQ_add(a, 1, ord(b) - 97)
s[a - 1] = b
else:
b = int(b)
ans = 0
for i in range(26):
if RSQ_getsum(b, i) - RSQ_getsum(a - 1, i) >= 1:
ans += 1
print(ans)
| 0 | null | 64,981,465,077,910 | 216 | 210 |
N, K = map(int, input().split())
A = list(map(int, input().split()))
def check(lst):
for i in range(N):
if lst[i] != N:
return False
return True
def move(lst):
tmp = [0] * (N + 1)
for i in range(N):
a = lst[i]
left = max(0, i - a)
right = min(N, i + a + 1)
tmp[left] += 1
tmp[right] -= 1
for i in range(N):
tmp[i + 1] += tmp[i]
return tmp
for i in range(K):
A = move(A)
if check(A):
# print (i)
break
print (*A[:-1])
|
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,k = inpl()
now = inpl()
now.append(0)
for _ in range(k):
pre = now[::]
now = [0] * (n+1)
for j in range(n):
a = max(0,j-pre[j])
b = min(n,j+pre[j]+1)
now[a] += 1
now[b] -= 1
x = 0
mi = INF
for j in range(n):
x += now[j]
mi = min(mi,x)
now[j] = x
if mi == n:
break
print(*now[:n])
| 1 | 15,589,576,256,870 | null | 132 | 132 |
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
count = 0
stack = set()
visited = []
visited_set = set()
endf = False
current = 0
while True:
i = A[current]-1
visited_set.add(current)
visited.append(current)
if not i in visited_set:
current = i
count += 1
else:
leng = len(visited_set)
roop_len = leng - visited.index(i)
header_len = leng - roop_len
break
if count >= K:
endf = True
print(i+1)
break
if not endf:
roop_ind = (K - header_len + 1) % roop_len
if roop_ind == 0:
print(visited[-1]+1)
else:
print(visited[header_len + roop_ind-1]+1)
|
alpha = input()
if ord(alpha) <= 90:
print('A')
else:
print('a')
| 0 | null | 16,957,806,193,488 | 150 | 119 |
N=int(input())
ans =0
for i in range(1,N):ans += (N-1)//i
print(ans)
|
from math import sqrt
# Function to return count of Ordered pairs
# whose product are less than N
def countOrderedPairs(N):
# Initialize count to 0
count_pairs = int(0)
# count total pairs
p = int(sqrt(N - 1)) + 1
q = N
# q = int(sqrt(N)) + 2
for i in range(1, p, 1):
for j in range(i, q, 1):
if i * j > N-1:
break
# print(i,j)
count_pairs += 1
#print(count_pairs)
# multiply by 2 to get ordered_pairs
count_pairs *= 2
#print(count_pairs)
# subtract redundant pairs (a, b) where a==b.
count_pairs -= int(sqrt(N - 1))
# return answer
return count_pairs
# Driver code
N = int(input())
print(countOrderedPairs(N))
# ans=prime_factorize(N)
# print(ans)
| 1 | 2,593,655,625,180 | null | 73 | 73 |
S=input()
if len(S)%2==0:
S_mae=S[:len(S)//2]
S_ushiro=S[len(S)//2:]
else:
S_mae=S[:len(S)//2+1]
S_ushiro=S[len(S)//2:]
ans=0
for i in range(len(S_mae)):
if S_mae[-i-1]!=S_ushiro[i]:
ans += 1
print(ans)
|
N = int(input())
A = [int(a) for a in input().split()]
xor = 0
for x in A:
xor ^= x
for v in A:
print(xor^v, end=' ')
| 0 | null | 66,561,835,573,572 | 261 | 123 |
n = int(input())
x = list(map(float, input().split()))
y = list(map(float, input().split()))
list=[]
for j in range(3):
D=0
for i in range(n):
if x[i]<y[i]:
d = (y[i]-x[i])
else:
d = (x[i]-y[i])
list.append(d)
D += (d**(j+1))
print(f"{D**(1/(j+1)):.6f}")
print(f"{max(list):.6f}")
|
name = input()
length = len(name)
if "s" == name[length-1]:
name = name + "es"
else:
name = name + "s"
print(name)
| 0 | null | 1,313,510,837,184 | 32 | 71 |
apple = [1, 2, 3]
apple.remove(int(input()))
apple.remove(int(input()))
print(apple[0])
|
x='123'
for _ in range(2):
x=x.replace(input(),'')
print(x)
| 1 | 110,547,766,112,940 | null | 254 | 254 |
from typing import List
class Info:
def __init__(self, arg_start, arg_end, arg_area):
self.start = arg_start
self.end = arg_end
self.area = arg_area
if __name__ == "__main__":
LOC: List[int] = []
POOL: List[Info] = []
all_symbols = input()
loc = 0
total_area = 0
for symbol in all_symbols:
if symbol == '\\':
LOC.append(loc)
elif symbol == '/':
if len(LOC) == 0:
continue
tmp_start = int(LOC.pop())
tmp_end = loc
tmp_area = tmp_end - tmp_start
total_area += tmp_area
while len(POOL) > 0:
# \ / : (tmp_start, tmp_end)
# \/ : (POOL[-1].start, POOL[-1].end)
if tmp_start < POOL[-1].start and POOL[-1].end < tmp_end:
tmp_area += POOL[-1].area
POOL.pop()
else:
break
POOL.append(Info(tmp_start, tmp_end, tmp_area))
else:
pass
loc += 1
print(f"{total_area}")
print(f"{len(POOL)}", end="")
while len(POOL) > 0:
print(f" {POOL[0].area}", end="")
POOL.pop(0)
print()
|
class Info:
def __init__(self,arg_start,arg_end,arg_S):
self.start = arg_start
self.end = arg_end
self.S = arg_S
POOL = []
LOC = []
cnt = 0
sum_S = 0
line = input()
for c in line:
if c == "\\":
LOC.append(cnt)
elif c == "/":
if len(LOC) == 0:
continue
tmp_start = LOC.pop()
tmp_end = cnt
tmp_S = tmp_end - tmp_start
sum_S += tmp_S
while len(POOL) > 0:
if POOL[-1].start > tmp_start and POOL[-1].end < tmp_end:
tmp_S += POOL[-1].S
POOL.pop()
else:
break
POOL.append(Info(tmp_start,tmp_end,tmp_S))
else:
pass
cnt += 1
lst = [len(POOL)]
for i in range(len(POOL)):
lst.append(POOL[i].S)
print(sum_S)
print(*lst)
| 1 | 58,819,023,082 | null | 21 | 21 |
while 1:
H, W = map(int, raw_input().split())
if H == W == 0:
break
print '#'*W
print ('#'+'.'*(W-2)+'#'+'\n')*(H-2)+'#'*W + '\n'
|
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
def resolve():
n = int(input())
now = 0
for _ in range(n):
x, y = map(int, input().split())
if x == y:
now += 1
else:
now = 0
if now == 3:
print("Yes")
return
print("No")
resolve()
| 0 | null | 1,630,884,942,610 | 50 | 72 |
from copy import deepcopy
import numpy as np
H, W, K = map(int, input().split())
matrix = []
for i in range(H):
matrix.append(input())
matrix_int = np.ones((H, W), dtype=np.uint8)
# 1 == 黒、 0 == 白
for row in range(H):
for column in range(W):
if matrix[row][column] == ".":
matrix_int[row, column] = 0
count = 0
for row_options in range(2**H):
for col_options in range(2**W):
tmp_matrix_int = deepcopy(matrix_int)
tmp_row_options = row_options
tmp_col_options = col_options
for row in range(H):
mod = tmp_row_options % 2
if mod == 0:
tmp_matrix_int[row,:] = 0
tmp_row_options = tmp_row_options // 2
for col in range(W):
mod = tmp_col_options % 2
if mod == 0:
tmp_matrix_int[:,col] = 0
tmp_col_options = tmp_col_options // 2
# print(tmp_matrix_int.sum())
if tmp_matrix_int.sum() == K:
count += 1
print(count)
|
X = int(input())
A = 100
for i in range(10**5):
A = A*101//100
if X <= A:
break
print(i+1)
| 0 | null | 17,867,832,846,490 | 110 | 159 |
# -*- coding: utf-8 -*-
def selection_sort(seq, l):
cnt = 0
for head_i in range(l):
flag = False
min_i = head_i
for target_i in range(head_i+1, l):
if seq[target_i] < seq[min_i]:
min_i = target_i
flag = True
if flag:
seq[head_i], seq[min_i] = seq[min_i], seq[head_i]
cnt += 1
print(' '.join([str(n) for n in seq]))
print(cnt)
def to_int(v):
return int(v)
def to_seq(v):
return [int(c) for c in v.split()]
if __name__ == '__main__':
l = to_int(input())
seq = to_seq(input())
selection_sort(seq, l)
|
N = int(input())
a = list(map(int, input().split()))
count = 0
for i in range(N):
minj = i
for j in range(i, N):
if a[j] < a[minj]:
minj = j
if a[i] != a[minj]:
a[minj], a[i] = a[i], a[minj]
count += 1
print(*a)
print(count)
| 1 | 20,299,442,690 | null | 15 | 15 |
inp = input()
a = inp.split()
a[0] = int(a[0])
a[1] = int(a[1])
a[2] = int(a[2])
c = 0
for i in range(a[0],a[1]+1):
if a[2] % i == 0:
c += 1
print(c)
|
number_list=[int(i) for i in input().split()]
counter=0
for r in range(number_list[0],number_list[1]+1):
if number_list[2]%r==0:
counter+=1
print(counter)
| 1 | 573,165,065,828 | null | 44 | 44 |
roop_num = int(input())
xy = [map(int, input().split()) for _ in range(roop_num)]
x, y = [list(i) for i in zip(*xy)]
z_counter = 0
flg = False
for i in range(roop_num):
if(x[i] == y[i]):
z_counter = z_counter +1
else:
z_counter = 0
if(z_counter == 3):
flg = True
break
if(flg):
print("Yes")
else:
print("No")
|
n = int(input())
z = []
cnt = 0
for _ in range(n):
a, b = map(int, input().split())
if a == b:
cnt += 1
else:
cnt = 0
if cnt == 3:
print('Yes')
exit()
print('No')
| 1 | 2,474,957,132,384 | null | 72 | 72 |
def bubblesort(N, A):
c, flag = 0, 1
while flag:
flag = False
for j in range(N-1, 0, -1):
if A[j] < A[j-1]:
A[j], A[j-1] = A[j- 1], A[j]
c += 1
flag = True
return (A, c)
A, c = bubblesort(int(input()), list(map(int, input().split())))
print(' '.join([str(v) for v in A]))
print(c)
|
length, t = map(int, input().split(" "))
target = [int(n) for n in input().split(" ")]
dp = [float("inf") for n in range(length + 1)]
dp[0] = 0
for i, coin in enumerate(target):
for j in range(length):
if coin + j <= length:
dp[coin + j] = min(dp[coin + j], dp[j] + 1)
print(dp[length])
| 0 | null | 75,264,160,860 | 14 | 28 |
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
n, m, k = map(int, input().split())
uf = UnionFind(n)
friend = [set([]) for i in range(n)]
for i in range(m):
ai, bi = map(int, input().split())
ai -= 1; bi -= 1
uf.union(ai, bi)
friend[ai].add(bi)
friend[bi].add(ai)
block = [set([]) for i in range(n)]
for i in range(k):
ci, di = map(int, input().split())
ci -= 1; di -= 1
block[ci].add(di)
block[di].add(ci)
for i in range(n):
uf.find(i)
ans = []
for i in range(n):
num = uf.size(i) - len(friend[i]) - 1
for j in block[i]:
if uf.find(i) == uf.find(j):
num -= 1
ans.append(num)
print(' '.join(map(str, ans)))
|
from collections import deque
N, M, K = map(int, input().split())
F = [[] for _ in range(N)]
B = [[] for _ in range(N)]
# フレンドの隣接リスト
for _ in range(M):
a, b = map(int, input().split())
a, b = a - 1, b - 1
F[a].append(b)
F[b].append(a)
# ブロックの隣接リスト
for _ in range(K):
c, d = map(int, input().split())
c, d = c - 1, d - 1
B[c].append(d)
B[d].append(c)
# 交友関係グループ(辞書型)
D = {}
# グループの親
parent = [-1] * N
# 訪問管理
visited = [False] * N
for root in range(N):
cnt = 0
if visited[root]:
continue
# D[root] = set([root])
# 訪問先のスタック
stack = [root]
# 訪問先が無くなるまで
while stack:
# 訪問者をポップアップ
n = stack.pop()
# 訪問者を訪問済み
if visited[n]:
continue
visited[n] = True
cnt +=1
# 訪問者のグループの親を設定
parent[n] = root
# root のフレンドをグループと訪問先に追加
for to in F[n]:
if visited[to]:
continue
# D[root].add(to)
stack.append(to)
if cnt!=0:
D[root]=cnt
# print(D)
ans = [0]*N
for iam in range(N):
# group = gro[parent[iam]]
tmp_ans = D[parent[iam]]
tmp_ans -=1
tmp_ans -= len(F[iam])
for block in B[iam]:
if parent[block]==parent[iam] :
tmp_ans -=1
ans[iam]=tmp_ans
print(*ans, sep=' ')
| 1 | 61,649,512,005,210 | null | 209 | 209 |
n, a, b = map(int, input().split())
lm = min(n, 2*10**5)
# ①nCrの各項のmod(10^9+7)を事前計算
p = 10 ** 9 + 7
fact = [1, 1] # fact[n] = (n! mod p)
factinv = [1, 1] # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1] # factinv 計算用
for i in range(2, lm + 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)
rt = 1
for i in range(r):
rt = (rt * (n-i)) % p
rt = rt*factinv[r] % p
return rt
def pow_r(x, n, p):
"""
O(log n)
"""
if n == 0: # exit case
return 1
if n % 2 == 0: # standard case ① n is even
return pow_r(x ** 2 % p, n // 2, p)
else: # standard case ② n is odd
return x * pow_r(x ** 2 % p, (n - 1) // 2, p) % p
rlt = pow_r(2,n,p)
rlt -= 1
rlt -= cmb(n,a,p) % p
rlt -= cmb(n,b,p) % p
while rlt < 0:
rlt += p
print(rlt)
|
MOD = 10**9 + 7
n, a, b = map(int, input().split())
def pow(x, n, MOD):
res = 1
while n:
if n & 1:
res *= x
res %= MOD
x *= x
x %= MOD
n >>= 1
return res
def fact(a, b, MOD):
res = 1
for i in range(a, b+1):
res *= i
res %= MOD
return res
def combi(n, k, MOD):
x = fact(n - k + 1, n, MOD)
y = fact(1, k, MOD)
return x * pow(y, MOD - 2, MOD) % MOD
def solve():
ans = pow(2, n, MOD) - 1 - combi(n, a, MOD) - combi(n, b, MOD)
print(ans % MOD)
#print(pow(2, MOD, MOD))
if __name__ == "__main__":
solve()
| 1 | 66,239,238,161,120 | null | 214 | 214 |
num = int(input())
numbers = list(map(int,input().split()))
for i in reversed(numbers):
print(i,end="")
if i != numbers[0]:
print(" ",end="")
print()
|
input();print(*input().split()[::-1])
| 1 | 1,008,717,117,760 | null | 53 | 53 |
#!/usr/bin/env python3
def solve(S: str):
if S >= 30:
return "Yes"
return "No"
def main():
S = int(input())
answer = solve(S)
print(answer)
if __name__ == "__main__":
main()
|
a = int(input())
res = a > 29 and 'Yes' or 'No'
print(res)
| 1 | 5,702,440,858,280 | null | 95 | 95 |
__author__ = 'CIPHER'
_project_ = 'PythonLehr'
class BoundingBox:
def __init__(self, width, height):
self.width = width;
self.height = height;
def CalculateBox(self, x, y, r):
if x>= r and x<=(self.width-r) and y>=r and y<=(self.height-r):
print("Yes")
else:
print("No")
'''
width = int(input("Width of the Box: "))
height = int(input("Height of the Box: "))
x = int(input("location of x: "))
y = int(input("location of y: "))
r = int(input("radius of the circle; "))
'''
# alternative input
inputList = input()
inputList = inputList.split(' ')
inputList = [int(x) for x in inputList]
# print(inputList)
width = inputList[0]
height = inputList[1]
x = inputList[2]
y = inputList[3]
r = inputList[4]
Box = BoundingBox(width, height)
Box.CalculateBox(x, y, r)
|
import sys
readline = sys.stdin.readline
N = int(readline())
S = readline().rstrip()
ans = 1
for i in range(1,len(S)):
if S[i] != S[i - 1]:
ans += 1
print(ans)
| 0 | null | 84,963,820,162,140 | 41 | 293 |
from bisect import bisect_left
N=int(input())
A=sorted(list(map(int,input().split())))
cnt=0
for i in range(N-1):
for j in range(i+1,N):
a=bisect_left(A,A[i]+A[j])
if j<a:
cnt+=a-j-1
print(cnt)
|
#153-A
H,A = map(int,input().split())
if H % A == 0:
print(H // A)
else:
print( H//A +1)
| 0 | null | 124,243,108,932,140 | 294 | 225 |
from collections import deque
d = deque()
for a in range(int(input())):
com = input().split()
if com[0] == "insert":
d.appendleft(com[1])
elif com[0] == "delete":
if com[1] in d:
d.remove(com[1])
elif com[0] == "deleteFirst":
d.popleft()
elif com[0] == "deleteLast":
d.pop()
else:
break
print(*d)
|
H, A = [int(x) for x in input().split()]
if H % A == 0:
print(H//A)
else:
print(H//A + 1)
| 0 | null | 38,453,679,824,670 | 20 | 225 |
while True:
l = input().split()
h = int(l[0])
w = int(l[1])
if h == 0 and w ==0:
break
flag = 0
for i in range(h*(w+1)):
if (i+1) % (w+1) == 0:
print("")
if w % 2 == 0:
flag += 1
if i == h*(w+1)-1:
print("")
else:
if flag % 2 == 0:
print("#", end="")
flag += 1
else:
print(".", end="")
flag += 1
|
n=int(input())
a=list(map(int,input().split()))
M=10**9+7
cnt=[0]*n
ans=1
for i in range(n):
if a[i]==0:
cnt[a[i]]+=1
else:
ans*=(cnt[a[i]-1]-cnt[a[i]])
cnt[a[i]]+=1
ans%=M
for i in range(cnt[0]):
ans*=3-i
ans%=M
print(ans)
| 0 | null | 65,296,896,143,810 | 51 | 268 |
num = input()
lst = []
for x in num:
lst.append(int(x))
total = sum(lst)
if total % 9 == 0:
print('Yes')
else:
print('No')
|
n = input()
sum=0
for i in n :
sum += int(i)
if sum%9 == 0 : print("Yes")
else : print("No")
| 1 | 4,362,186,955,528 | null | 87 | 87 |
s=str(input())
s=list(s)
if s[len(s)-1]=="s":
print("".join(s)+"es")
else:
print("".join(s)+"s")
|
class Main:
S = input()
if S[-1] == 's':
print(S+'es')
else :
print(S+'s')
| 1 | 2,382,114,446,800 | null | 71 | 71 |
import os, sys, re, math
C = input()
print(chr(ord(C) + 1))
|
s = input()
n = len(s)
for i in range(n//2):
if s[i]!=s[n-i-1] :
print("No")
exit()
n1 = (n-1)//2
for i in range(n1//2):
if s[i]!=s[n1-i-1] :
print("No")
exit()
n2 = (n+3)//2
for i in range(n-n2):
if s[i]!=s[n-i-1] :
print("No")
exit()
print("Yes")
| 0 | null | 69,454,987,206,528 | 239 | 190 |
H1,M1,H2,M2,K = map(int,input().split())
print((H2-H1)*60+(M2-M1)-K if (M2-M1) >= 0 else (H2-H1)*60+(M2-M1)-K)
|
d=raw_input().split(" ")
l=list(map(int,d))
if(l[2]>0 and l[3]>0):
if(l[0]>=(l[2]+l[4])):
if(l[1]>=(l[3]+l[4])):
print "Yes"
else:
print "No"
else:
print "No"
else:
print "No"
| 0 | null | 9,248,490,055,928 | 139 | 41 |
import sys
def input():
return sys.stdin.readline()[:-1]
def main():
N = int(input())
P = []
for k in range(1,1+int((N-1)**(1/2))):
if (N-1)%k == 0:
P.append((N-1)//k)
P.append(k)
P = set(P)
ans = len(P)
for k in range(2,1+int(N**(1/2))):
if N%k == 0:
t = N//k
while t%k == 0:
t //= k
if t%k == 1:
ans += 1
print(ans)
if __name__ == '__main__':
main()
|
array = list(map(int, input().split()))
array.sort()
print("{} {} {}".format(array[0], array[1], array[2]))
| 0 | null | 21,039,980,624,700 | 183 | 40 |
H, W = list(map(int, input().split()))
while H != 0 or W != 0 :
print('#' * W)
for i in range(H-2) :
print('#', end = '')
print('.' * (W - 2), end = '')
print('#')
print('#' * W)
print()
H, W = list(map(int, input().split()))
|
def solve(string):
x, k, d = map(int, string.split())
x = abs(x)
if k % 2:
x = min(x - d, x + d, key=abs)
k -= 1
k, d = k // 2, d * 2
if x < k * d:
return str(min(x % d, abs((x % d) - d)))
else:
return str(x - k * d)
if __name__ == '__main__':
import sys
print(solve(sys.stdin.read().strip()))
| 0 | null | 3,047,521,065,638 | 50 | 92 |
n = int(input())
arm = []
for i in range(n):
x , l = map(int,input().split())
arm.append([x,l])
arm.sort()
dp = [[0,0] for i in range(n)]
dp[0][1] = arm[0][0] + arm[0][1]
for i in range(1,n):
if dp[i-1][1] <= arm[i][0] -arm[i][1]:
dp[i][0] = dp[i-1][0]
dp[i][1] = arm[i][0] + arm[i][1]
else:
dp[i][0] = dp[i-1][0] + 1
dp[i][1] = min(arm[i][0] + arm[i][1],dp[i-1][1])
print(n-dp[n-1][0])
|
import sys
N = int(sys.stdin.readline().rstrip())
sec = []
for _ in range(N):
x, l = map(int, sys.stdin.readline().rstrip().split())
sec.append((x - l, x + l))
sec = sorted(sec, key=lambda x: x[1])
r = -float("inf")
ans = 0
for s, t in sec:
if r <= s:
ans += 1
r = t
print(ans)
| 1 | 89,561,000,286,534 | null | 237 | 237 |
H, A = map(int, input().split())
ans = (H // A) + ( 1 if (H % A) != 0 else 0)
print(ans)
|
hp, attack = map(int, input().split())
print(hp // attack if hp % attack == 0 else hp // attack + 1)
| 1 | 76,910,855,523,524 | null | 225 | 225 |
import sys
input = sys.stdin.readline
import math
def read():
N, K = map(int, input().strip().split())
A = list(map(int, input().strip().split()))
return N, K, A
def solve(N, K, A):
d = [0 for i in range(N+1)]
for k in range(K):
for i in range(N):
d[i] = 0
for i in range(N):
l = max(0, i-A[i])
r = min(N, i+1+A[i])
d[l] += 1
d[r] -= 1
terminate = True
v = 0
for i in range(N):
v += d[i]
A[i] = v
if terminate and A[i] < N:
terminate = False
if terminate:
break
print(*[a for a in A])
if __name__ == '__main__':
inputs = read()
outputs = solve(*inputs)
if outputs is not None:
print("%s" % str(outputs))
|
while True:
try:a,b=map(int,input().split())
except:break
if a=="" or b==":":
break
c=a+b
ans=0
if c>=0 and c<=9:
ans=1
if c>=10 and c<=99:
ans=2
if c>=100 and c<=999:
ans=3
if c>=1000 and c<=9999:
ans=4
if c>=10000 and c<=99999:
ans=5
if c>=100000 and c<=999999:
ans=6
if c>=1000000 and c<=9999999:
ans=7
print(ans)
| 0 | null | 7,686,249,350,428 | 132 | 3 |
# -*- coding:utf-8 -*-
def solve():
N = int(input())
"""
■ 解法
N = p^{e1} * p^{e2} * p^{e3} ...
と因数分解できるとき、
z = p_i^{1}, p_i^{2}, ...
としていくのが最適なので、それを数えていく
(例) N = 2^2 * 3^2 * 5 * 7
のとき、
2,3,5,7の4回割れる。(6で割る必要はない)
■ 計算量
素因数分解するのに、O(√N)
割れる回数を計算するのはたかだか素因数分解するより少ないはずなので、
全体としてはO(√N+α)くらいでしょ(適当)
"""
def prime_factor(n):
"""素因数分解する"""
i = 2
ans = {}
while i*i <= n:
while n%i == 0:
if not i in ans:
ans[i] = 0
ans[i] += 1
n //= i
i += 1
if n != 1:
ans[n] = 1
return ans
pf = prime_factor(N)
ans = 0
for key, value in pf.items():
i = 1
while value-i >= 0:
value -= i
ans += 1
i += 1
print(ans)
if __name__ == "__main__":
solve()
|
a,b,c = map(int, raw_input().split())
if a > b:
temp = a
a = b
b = temp
if b > c:
temp = b
b = c
c = temp
if a > b:
temp = a
a = b
b = temp
print a,b,c
| 0 | null | 8,712,325,446,132 | 136 | 40 |
def main():
n = int(input())
a = [0,0]
for i in range(1, n+1):
a[0] += 1
a[1] = a[1] + 1 if i % 2 != 0 else a[1]
print(a[1] / a[0])
if __name__ == '__main__':
main()
|
import itertools
n = int(input())
p = list(map(int, input().split()))
q = tuple(map(int, input().split()))
srt = sorted(p.copy())
cnt = 1
cnt1 = 0
cnt2 = 0
for i in itertools.permutations(srt, n):
if i == tuple(p):
cnt1 = cnt
if i == q:
cnt2 = cnt
cnt += 1
print(abs(cnt1 - cnt2))
| 0 | null | 138,890,987,195,982 | 297 | 246 |
a,b,c,d=map(int,input().split())
while True:
c=c-b
if c<=0:
break
a=a-d
if a<=0:
break
if a>c:
print('Yes')
else:
print('No')
|
n = int(input())
S = input().split()
q = int(input())
T = input().split()
count = 0
for i in T:
if i in S:
count += 1
print(count)
| 0 | null | 14,905,400,421,230 | 164 | 22 |
N = int(input())
A = list(map(int, input().split()))
numbers = []
s = A[0]
for i in range(1, N):
s = s ^ A[i]
for i in range(N):
numbers.append(s ^ A[i])
print(*numbers)
|
N = int(input())
aaa = [int(i) for i in input().split()]
sumxor = 0
for a in aaa:
sumxor = sumxor^a
bbb = [a^sumxor for a in aaa]
print(" ".join([str(b) for b in bbb]))
| 1 | 12,512,379,644,340 | null | 123 | 123 |
from collections import deque
n, q = [int(_) for _ in input().split()]
processes = deque([tuple(input().split()) for i in range(n)])
time = 0
while processes:
process = processes.popleft()
if int(process[1]) <= q:
time += int(process[1])
print(process[0], time)
else:
time += q
processes.append((process[0], int(process[1]) - q))
|
# Template 1.0
import sys, re
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx): return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))
toret = {}
for tup in temp:
toret[tup[0]] = tup[1]
return toret
def sortDictWithKey(passedDic):
return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
'''
1,2,3,4,5,6,7,8,9,10,11,12,21,22,23,32,33,34,43,44,45,54,55,56,65,66,67,76,77,78,87,88,89,98,99,100 (36)
101,110,111,112,121,122,123,210,211,212,221,222,223,232,233,234,
1
10
11
12
100
101
110
111
112
121
122
123
1000
1001
1002
'''
#precomp:
nums = []
def precomp(i):
temp = str(i)
x=[-1,0,1]
for j in range(3):
foo = int(temp[-1])+x[j]
if(foo>=0 and foo<=9):
toadd = int(temp+str(foo))
if (i > 3234566667):
return
nums.append(toadd)
precomp(toadd)
for i in range(1, 10):
nums.append(i)
precomp(i)
nums.sort()
k = INT()
print(nums[k-1])
# k = INT()
| 0 | null | 19,925,038,407,620 | 19 | 181 |
import sys
import os
import math
import bisect
import itertools
import collections
import heapq
import queue
import array
# 時々使う
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque
# 再帰の制限設定
sys.setrecursionlimit(10000000)
def ii(): return int(sys.stdin.buffer.readline().rstrip())
def il(): return list(map(int, sys.stdin.buffer.readline().split()))
def fl(): return list(map(float, sys.stdin.buffer.readline().split()))
def iln(n): return [int(sys.stdin.buffer.readline().rstrip())
for _ in range(n)]
def iss(): return sys.stdin.buffer.readline().decode().rstrip()
def sl(): return list(map(str, sys.stdin.buffer.readline().decode().split()))
def isn(n): return [sys.stdin.buffer.readline().decode().rstrip()
for _ in range(n)]
def lcm(x, y): return (x * y) // math.gcd(x, y)
MOD = 10 ** 9 + 7
INF = float('inf')
def main():
if os.getenv("LOCAL"):
sys.stdin = open("input.txt", "r")
N = ii()
D = [il() for _ in range(N)]
for i in range(N - 2):
for j in range(i, i + 3):
if D[j][0] != D[j][1]:
break
else:
print('Yes')
exit()
else:
print('No')
if __name__ == '__main__':
main()
|
n = int(input())
xy = [map(int, input().split()) for _ in range(n)]
x, y = [list(i) for i in zip(*xy)]
count = 0
buf = 0
for xi, yi in zip(x, y):
if xi == yi:
buf += 1
else:
if buf > count:
count = buf
buf = 0
if buf > count:
count = buf
if count >= 3:
print('Yes')
else:
print('No')
| 1 | 2,464,198,906,890 | null | 72 | 72 |
n, k = map(int,input().split())
a = list(map(int,input().split()))
l = [0]*n
i=0
cnt=0
while l[i]==0:
l[i] = a[i]
i = a[i]-1
cnt += 1
start = i+1
i = 0
pre = 0
while i+1!=start:
i = a[i]-1
pre += 1
loop = cnt-pre
if pre+loop<k:
k=(k-pre)%loop+pre
i = 0
for _ in range(k):
i = a[i]-1
print(i+1)
|
n, k = map(int,input().split())
a = list(map(int, input().split()))
dst = [1] #今まで行った町(最初も含む)のリスト
dsts = set(dst) #今まで行った町(最初も含む)のset
twn = 1 #テレポーター転送先
for _ in range(k):
if a[twn - 1] in dsts: #テレポーター転送先が今まで行った町setに入っていたら(そこから先の転送はループする)
index = dst.index(a[twn - 1]) #今まで行った町リストでのテレポーター転送先のindex取得
ld = len(dst[:index]) #ループする前の長さとループ部分の周期を求める
cyc = len(dst[index:])
print(dst[(ld - 1) + (k + 1 - ld) % cyc] if (k + 1 - ld) % cyc != 0 else dst[-1])
exit()
else: #テレポーター転送先が今まで行った町setに入っていなかったら
dst.append(a[twn - 1]) #入っていなかったら今まで行った町リストに追加
dsts.add(a[twn - 1])
twn = a[twn - 1] #テレポーター転送先の更新
print(dst[-1])
| 1 | 22,634,251,348,342 | null | 150 | 150 |
n = int(input())
s = input()
if n%2 != 0 or s[:n//2] != s[n//2:]:
print("No")
else:
print("Yes")
|
n = int(input())
s = input()
if n % 2 != 0:
print("No")
else:
h = n // 2
print("Yes" if s[0:h] == s[h:] else "No")
| 1 | 146,636,246,138,860 | null | 279 | 279 |
s, t = input().split()
a, b = map(int, input().split())
u = input()
if s == u:
x = a - 1
y = b
else:
x = a
y = b - 1
print(x, y)
|
S,T,A,B,U = open(0).read().split()
if S==U:
print(int(A)-1,B)
else:
print(A,int(B)-1)
| 1 | 72,211,037,639,666 | null | 220 | 220 |
if __name__ == "__main__":
n, k = map(int, input().split())
p = 10**9 + 7
answer = 0
nCi = 1
n_1Ci = 1
for i in range(min(k + 1, n)):
answer += nCi * n_1Ci
answer %= p
deno = pow(i + 1, p - 2, p)
nCi *= (n - i) * deno
nCi %= p
n_1Ci *= (n - i - 1) * deno
n_1Ci %= p
print(answer)
|
input()
xs=reversed(input().split())
print(" ".join(xs))
| 0 | null | 33,977,396,618,450 | 215 | 53 |
# C - Replacing Integer
n,k = map(int,input().split())
m = n % k
l = map(abs,[m-k,m,m+k])
print(min(l))
|
N,K=map(int,input().split())
m=N//K
print(min(abs(N-m*K),abs(N-(m+1)*K)))
| 1 | 39,447,115,588,298 | null | 180 | 180 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.