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
|
---|---|---|---|---|---|---|
from collections import deque
n, m = map(int ,input().split())
graph = [[] for _ in range(n)]
for i in range(m):
a,b = map(int, input().split())
graph[a-1].append(b-1)
graph[b-1].append(a-1)
v = [0]*n
ans = 0
for i in range(n):
if v[i] == 0:
ans += 1
q = deque()
q.append(i)
v[i] = 1
while q:
node = q.popleft()
for j in graph[node]:
if v[j] == 0:
q.append(j)
v[j] = 1
print(ans-1)
|
class UnionFind():
# 作りたい要素数nで初期化
# 使用するインスタンス変数の初期化
def __init__(self, n):
self.n = n
# root[x]<0ならそのノードが根かつその値が木の要素数
# rootノードでその木の要素数を記録する
self.root = [-1]*(n+1)
# 木をくっつける時にアンバランスにならないように調整する
self.rnk = [0]*(n+1)
# ノードxのrootノードを見つける
def Find_Root(self, x):
if(self.root[x] < 0):
return x
else:
# ここで代入しておくことで、後の繰り返しを避ける
self.root[x] = self.Find_Root(self.root[x])
return self.root[x]
# 木の併合、入力は併合したい各ノード
def Unite(self, x, y):
# 入力ノードのrootノードを見つける
x = self.Find_Root(x)
y = self.Find_Root(y)
# すでに同じ木に属していた場合
if(x == y):
return
# 違う木に属していた場合rnkを見てくっつける方を決める
elif(self.rnk[x] > self.rnk[y]):
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
# rnkが同じ(深さに差がない場合)は1増やす
if(self.rnk[x] == self.rnk[y]):
self.rnk[y] += 1
# xとyが同じグループに属するか判断
def isSameGroup(self, x, y):
return self.Find_Root(x) == self.Find_Root(y)
# ノードxが属する木のサイズを返す
def Count(self, x):
return -self.root[self.Find_Root(x)]
n,m = map(int,input().split())
uf = UnionFind(n)
for i in range(m):
a,b = map(int,input().split())
a -= 1
b -= 1
uf.Unite(a,b)
s = set()
for i in range(n):
s.add(uf.Find_Root(i))
print(len(s)-1)
| 1 | 2,296,323,576,838 | null | 70 | 70 |
from sys import stdin
n = int(stdin.readline().rstrip())
ai = [int(x) for x in stdin.readline().rstrip().split()]
ai.sort()
print("%d %d %d" % (ai[0], ai[n-1], sum(ai)))
|
import math
N=int(input())
l=N*100/108
r=(N+1)*100/108
for i in range(math.ceil(l),math.ceil(r)):
print(i);exit()
print(":(")
| 0 | null | 62,931,600,741,362 | 48 | 265 |
import math
A,B,H,M=map(int,input().split())
C2=A**2+B**2-2*A*B*math.cos((30*H-11*M/2)/180*math.pi)
print(C2**(1/2))
|
# collections.deque is implemented using doubly linked list at C level..
from collections import deque
linkedlist = deque()
for _ in range(int(input())):
input_command = input()
if input_command == 'deleteFirst':
linkedlist.popleft()
elif input_command == 'deleteLast':
linkedlist.pop()
else:
com, num = input_command.split()
if com == 'insert':
linkedlist.appendleft(num)
elif com == 'delete':
try:
linkedlist.remove(num)
except:
pass
print(' '.join(linkedlist))
| 0 | null | 10,072,948,087,456 | 144 | 20 |
from bisect import *
n,m = map(int,input().split())
S = input()
ok = []
for i,s in enumerate(S[::-1]):
if s == '0':
ok.append(i)
now = 0
ans = []
while now != n:
nxt = ok[bisect_right(ok, now + m) - 1]
if nxt == now:
ans = [str(-1)]
break
else:
ans.append(str(nxt - now))
now = nxt
print(' '.join(ans[::-1]))
|
n,m=map(int,input().split())
s=input()[::-1]
ans=[]
now=0
while(now<n):
t=1
for i in reversed(range(1,m+1)):
if now+i>n or s[now+i]=='1':
continue
now=now+i
ans.append(i)
t=0
break
if t:
print(-1)
exit()
ans.reverse()
print(*ans,sep=' ')
| 1 | 139,757,057,175,122 | null | 274 | 274 |
from collections import defaultdict
(h,n),*ab = [list(map(int, s.split())) for s in open(0)]
mxa = max(a for a,b in ab)
dp = defaultdict(lambda: float('inf'))
dp[0] = 0
for i in range(1, h+mxa):
dp[i] = min(dp[i-a] + b for a,b in ab)
print(min(v for k,v in dp.items() if k>=h))
|
H,N=map(int,input().split())
L=[0]*N
for i in range(N):
a,b=map(int,input().split())
L[i]=(a,b)
DP=[float("inf")]*(H+1)
DP[0]=0
for (A,B) in L:
for k in range(1,H+1):
if k>=A:
DP[k]=min(DP[k],DP[k-A]+B)
else:
DP[k]=min(DP[k],B)
print(DP[-1])
| 1 | 80,986,668,819,732 | null | 229 | 229 |
#!/usr/bin/env python3
# encoding:utf-8
import copy
import random
import bisect #bisect_left これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections
from decimal import Decimal # 10進数で考慮できる
mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000
d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))
N = int(input())
anss = [0 for i in range(N + 1)]
for x in range(1, int(math.sqrt(N))):
for y in range(1, int(math.sqrt(N))):
for z in range(1, int(math.sqrt(N))):
tmp = x ** 2 + y ** 2 + z ** 2 + x*y + x*z + y*z
if tmp <= N:
anss[tmp] += 1
for i in range(1, N + 1):
print(anss[i])
|
import math
n = int(input())
max = int(math.sqrt(n) + 1)
L = [0] * (n + 1)
for x in range(1, max):
for y in range(1, max):
for z in range(1, max):
tmp = x * x + y * y + z * z + x * y + y * z + z * x
if tmp > n:
continue
L[tmp] += 1
for i in range(1, n + 1):
print(L[i])
| 1 | 7,972,063,839,308 | null | 106 | 106 |
import math
a, b,h,m = list(map(int, input().split()))
rel_hour = (h*60 + m)/12/60
#print(rel_hour)
arg_hour = 2* math.pi *rel_hour
arg_min = 2*math.pi * m/60
ans = (abs(a**2+b**2-2*a*b*math.cos(arg_hour-arg_min)))**(1/2)
print(ans)
|
il = [int(k) for k in input().split()]
K = il[0]
X = il[1]
if 500 * K >= X:
print("Yes")
else:
print("No")
| 0 | null | 59,043,280,050,132 | 144 | 244 |
from collections import Counter
MOD = 998244353
N = int(input())
D = list(map(int, input().split()))
if D[0] != 0:
print(0)
exit()
C = sorted(Counter(D).most_common(), key=lambda x: x[0])
if C[0][1] > 1:
print(0)
exit()
ans = 1
for i in range(1, len(C)):
if C[i][0] - C[i-1][0] > 1:
print(0)
exit()
ans *= C[i - 1][1] ** C[i][1]
print(ans % MOD)
|
N = int(input())
D = list(map(int, input().split()))
if D[0] != 0:
print(0)
exit()
D = sorted(D)
V = [0]*(D[-1]+1)
for i in range (0, N):
V[D[i]]+=1
if V[0] > 1:
print(0)
exit()
else:
count = 1
for i in range (0, len(V)-1):
if V[i] == 0 and V[i+1] > 0:
print(0)
exit()
else:
count*= V[i]**V[i+1]
print(count%998244353)
| 1 | 154,595,888,701,888 | null | 284 | 284 |
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np
# from numpy import cumsum # accumulate
from fractions import gcd
# from math import gcd
def lcm(x, y):
return x // gcd(x, y) * y
def solve():
a, b = MI()
print(lcm(a, b))
if __name__ == '__main__':
solve()
|
def gcd(a,b):
r = a%b
if r==0:
return b
else:
return gcd(b,r)
def lcm(x,y):
return (x * y) // gcd(x, y)
n,m=map(int, input().split())
print(lcm(n,m))
| 1 | 113,299,947,826,368 | null | 256 | 256 |
tmp = input().split(" ")
N = int(tmp[0])
M = int(tmp[1])
ans = N * (N - 1) / 2 + M * (M - 1) / 2
print(int(ans))
|
import math
def combinations_count(n, r):
return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def main():
n, m = map(int, input().split())
if n < 2:
even = 0
else:
even = combinations_count(n, 2)
if m < 2:
odd = 0
else:
odd = combinations_count(m, 2)
print(even + odd)
if __name__ == "__main__":
main()
| 1 | 45,356,854,800,428 | null | 189 | 189 |
import sys
def input(): return sys.stdin.readline().rstrip()
series = [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]
print(series[int(input())-1])
|
N, K = map(int, input().split(' '))
H = sorted(list(map(int, input().split(' '))), reverse=True)
print(sum(H[K:]))
| 0 | null | 64,545,166,079,320 | 195 | 227 |
H, W, K = map(int, input().split())
Ss = [list(map(int, input().replace("\n", ""))) for _ in range(H)]
cut_yoko_patterns = ["0","1"]
options = ["0","1"]
import copy
for i in range(H-2):
cut_yoko_patterns = [cut_yoko_patterns[i] + options[j] for i in range(len(cut_yoko_patterns)) for j in range(len(options))]
answer = int(1e+5)
for cut_yoko_pattern in cut_yoko_patterns:
yoko_cut_num = cut_yoko_pattern.count("1")
boxs = [0 for _ in range(yoko_cut_num+1)]
box_num = [0 for _ in range(H)]
for i in range(H-1):
if cut_yoko_pattern[i] == "1":
box_num[i+1] = box_num[i] + 1
else:
box_num[i+1] = box_num[i]
tate_cut_num = 0
for j in range(W):
temp_boxs = [0 for _ in range(yoko_cut_num+1)]
for i in range(H):
if Ss[i][j] == 1:
temp_boxs[box_num[i]] += 1
Impossible = False
Should_cut = False
for i in range(yoko_cut_num+1):
if temp_boxs[i] > K:
Impossible = True
elif boxs[i] + temp_boxs[i] > K:
Should_cut = True
if Impossible == True:
break
elif Should_cut ==True:
boxs = copy.deepcopy(temp_boxs)
tate_cut_num += 1
else:
for i in range(yoko_cut_num+1):
boxs[i] += temp_boxs[i]
else:
if tate_cut_num+yoko_cut_num < answer:
answer = tate_cut_num + yoko_cut_num
print(answer)
|
import sys
from io import StringIO
import unittest
import os
# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)
# 実装を行う関数
def resolve(test_def_name=""):
h, w, k = map(int, input().split())
s_s = [list(input()) for i in range(h)]
# パターン数分の情報を作成(横に切る = 最大2^10個)
# 全パターンの・・横に切る回数、と切る場所
side = []
for i in range(1 << h - 1):
cut_cnt = 0
point_s = []
# パターンの桁数分ループ
for j in range(h - 1):
# フラグが立つ(bitが1)の場合の処理を以下に記載。
if i & 1 << j:
cut_cnt += 1
point_s.append(j + 1)
point_s.append(h)
# 得た情報をリストに追加
side.append([point_s, cut_cnt])
## 横切り必須にもかかわらず、横木入りしていないパターンを排除できていない・・と思われる。
x_s_s = list(zip(*s_s))
ans = 999999
for side_cut_point_s, cut_cnt in side:
# 横切りを実施した後の塊を取得
cnt_s = [0 for i in range(cut_cnt + 1)]
for x_s in x_s_s:
start = 0
for cnt, side_cut_point in enumerate(side_cut_point_s):
cnt_s[cnt] += x_s[start: side_cut_point].count("1")
start = side_cut_point
# 切る必要がある場合は切る
if max(cnt_s) > k:
cut_cnt += 1
start = 0
for cnt, side_cut_point in enumerate(side_cut_point_s):
cnt_s[cnt] = x_s[start: side_cut_point].count("1")
start = side_cut_point
if max(cnt_s) > k:
cut_cnt += 99999
ans = min(ans, cut_cnt)
print(ans)
# テストクラス
class TestClass(unittest.TestCase):
def assertIO(self, assert_input, output):
stdout, sat_in = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
resolve(sys._getframe().f_back.f_code.co_name)
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, sat_in
self.assertEqual(out, output)
def test_input_1(self):
test_input = """3 5 4
11100
10001
00111"""
output = """2"""
self.assertIO(test_input, output)
def test_input_2(self):
test_input = """3 5 8
11100
10001
00111"""
output = """0"""
self.assertIO(test_input, output)
def test_input_3(self):
test_input = """4 10 4
1110010010
1000101110
0011101001
1101000111"""
output = """3"""
self.assertIO(test_input, output)
# 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
def test_1original_1(self):
test_input = """10 10 1
1000000000
1000000000
1000000000
1000000000
1000000000
1000000000
1000000000
1000000000
1000000000
1000000000"""
output = """9"""
self.assertIO(test_input, output)
# 実装orテストの呼び出し
if __name__ == "__main__":
if os.environ.get("USERNAME") is None:
# AtCoder提出時の場合
resolve()
else:
# 自PCの場合
unittest.main()
| 1 | 48,420,756,451,770 | null | 193 | 193 |
num = [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]
K = int(input())
N = K - 1
print(num[N])
|
import collections
s=list(input())
a=[0]
s.reverse()
mod=2019
mod10=1
for i in range(len(s)):
x=int(s[i])
y=a[-1]
ans=(x*mod10+y)%mod
a.append(ans)
mod10=(mod10*10)%mod
ans1=0
c = collections.Counter(a)
d=list(c.values())
for r in d:
if r>=2:
ans1+=(r*(r-1))//2
print(ans1)
| 0 | null | 40,304,808,894,880 | 195 | 166 |
import random
class Dice:
def __init__(self, hoge):
self.num = hoge
self.face = {'U': 0, 'W': 3, 'E': 2, 'N': 4, 'S': 1, 'B': 5}
def move(self, direct):
previouse = {k: v for k, v in self.face.items()}
if direct == 'E':
self.face['U'] = previouse['W']
self.face['W'] = previouse['B']
self.face['E'] = previouse['U']
self.face['B'] = previouse['E']
elif direct == 'W':
self.face['U'] = previouse['E']
self.face['W'] = previouse['U']
self.face['E'] = previouse['B']
self.face['B'] = previouse['W']
elif direct == 'N':
self.face['U'] = previouse['S']
self.face['N'] = previouse['U']
self.face['S'] = previouse['B']
self.face['B'] = previouse['N']
elif direct == 'S':
self.face['U'] = previouse['N']
self.face['N'] = previouse['B']
self.face['S'] = previouse['U']
self.face['B'] = previouse['S']
def get_num(self, place):
return self.num[self.face[place]]
if __name__ == '__main__':
dice = Dice([int(x) for x in input().split()])
num_q = int(input())
d = ['E', 'W', 'N', 'S']
for _ in range(num_q):
x, y = [int(x) for x in input().split()]
while True:
rand_num = random.randint(0, 3)
dice.move(d[rand_num])
if dice.get_num('U') == x and dice.get_num('S') == y:
break
print(dice.get_num('E'))
|
# coding: utf-8
# ?????????????????¨????????????
class Dice(object):
def __init__(self):
# ???????????????????????°
# ????????¶???
self.dice = (2, 5), (3, 4), (1, 6) # x, y, z
self.ax = [[0, False], [1, False], [2, False]]
self.axmap = [0, 1, 2]
self.mm = {"N": (0, 2), "S": (2, 0), "E": (1, 2), "W": (2, 1), "R": (0, 1), "L": (1, 0)}
def rotate(self, dir):
def rot(k, r):
# k?????????????????????????????????????????§?§????
# r?????????????????¢???????§????
t = self.axmap[r]
self.axmap[k], self.axmap[r] = t, self.axmap[k]
self.ax[t][1] = not self.ax[t][1]
rot(*self.mm[dir])
def top(self):
z = self.ax[self.axmap[2]]
return self.dice[z[0]][z[1]]
def right(self):
y = self.ax[self.axmap[1]]
return self.dice[y[0]][y[1]]
def front(self):
x = self.ax[self.axmap[0]]
return self.dice[x[0]][x[1]]
if __name__=="__main__":
dice = Dice()
labels = input().split()
q = int(input())
for _ in range(q):
a, b = input().split()
p = labels.index(a) + 1
for _ in range(4):
if p==dice.top():
break
dice.rotate("N")
for _ in range(4):
if p==dice.top():
break
dice.rotate("E")
p = labels.index(b) + 1
for _ in range(4):
if p==dice.front():
break;
dice.rotate("R")
print(labels[dice.right()-1])
| 1 | 259,276,791,228 | null | 34 | 34 |
IDX_TABLE=\
{1:[4,2,3,5],
2:[1,4,6,3],
3:[1,2,6,5],
4:[1,5,6,2],
5:[4,1,3,6],
6:[3,2,4,5]}
nums = ["dummy"] + [int(x) for x in raw_input().split(" ")]
n = int(raw_input())
for i in range(n):
up, front = tuple([int(x) for x in raw_input().split(" ")])
up_idx = nums.index(up)
front_idx = nums.index(front)
ring_list = IDX_TABLE[up_idx]
ring_idx = ring_list.index(front_idx)
print nums[ring_list[(ring_idx+1) % 4]]
|
import sys
from collections import deque
import bisect
def input():
return sys.stdin.readline().rstrip()
def main():
N, K = map(int, input().split())
A = list(map(int, input().split()))
mod = 10 ** 9 + 7
A.sort()
# print(A)
pp = int(bisect.bisect_left(A, 0))
A_minus = deque(A[:pp])
A_plus = deque(A[pp:])
AA = deque([])
AAm = deque([])
if N == K:
ans = 1
for i in A:
ans *= i
ans %= mod
print(ans % mod)
elif K % 2 == 0:
ans = 1
while len(A_minus) >= 2:
a1 = A_minus.popleft()
a2 = A_minus.popleft()
AAm.append(a1 * a2)
while len(A_plus) >= 2:
a1 = A_plus.pop()
a2 = A_plus.pop()
AA.append(a1 * a2)
for i in range(K // 2):
if len(AAm) == 0:
temp = AA.popleft()
elif len(AA) == 0:
temp = AAm.popleft()
elif AAm[0] > AA[0]:
temp = AAm.popleft()
else:
temp = AA.popleft()
ans *= temp
ans %= mod
print(ans % mod)
elif len(A_plus) == 0:
ans = 1
for i in range(K):
ans *= A_minus.pop()
ans %= mod
print(ans % mod)
else:
ans = A_plus.pop()
while len(A_minus) >= 2:
a1 = A_minus.popleft()
a2 = A_minus.popleft()
AAm.append(a1 * a2)
while len(A_plus) >= 2:
a1 = A_plus.pop()
a2 = A_plus.pop()
AA.append(a1 * a2)
for i in range(K // 2):
if len(AAm) == 0:
temp = AA.popleft()
elif len(AA) == 0:
temp = AAm.popleft()
elif AAm[0] > AA[0]:
temp = AAm.popleft()
else:
temp = AA.popleft()
ans *= temp
ans %= mod
print(ans % mod)
if __name__ == "__main__":
main()
| 0 | null | 4,869,287,446,050 | 34 | 112 |
hoge1 = list()
hoge2 = list()
total = 0
for num, c in enumerate(input()):
if c == '\\':
hoge1.append(num)
elif c == '/':
if not hoge1:
continue
last_index = hoge1.pop()
S = num - last_index
if not hoge2:
hoge2.append((last_index, S))
else:
if last_index >= hoge2[-1][0]:
hoge2.append((last_index, S))
else:
new_S = S
for i, j in hoge2[::-1]:
if last_index >= i:
break
else:
new_S += hoge2.pop()[1]
hoge2.append((last_index, new_S))
totals = [x[1] for x in hoge2]
print (sum(totals))
totals.insert(0, len(hoge2))
print (' '.join([str(x) for x in totals]))
|
ary = list(input())
s1 = []
s = 0
s2 = []
cnt = 0
for _ in ary:
if _ == '\\':
s1.append(cnt)
cnt += 1
elif _ == '/':
if s1:
old_cnt = s1.pop()
area = cnt - old_cnt
s += area
while s2:
if old_cnt < s2[-1][0]:
area += s2.pop()[1]
else:
break
s2.append((old_cnt, area))
cnt += 1
else:
cnt += 1
print(s)
print(len(s2), *[_[1] for _ in s2])
| 1 | 58,038,872,122 | null | 21 | 21 |
import sys
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def resolve():
a,b,c=map(int, input().split())
if Decimal(a).sqrt()+Decimal(b).sqrt()<Decimal(c).sqrt():
print('Yes')
else:
print('No')
resolve()
|
# -*- codinf: utf-8 -*-
from collections import deque
N, M = map(int, input().split())
route = [[] for _ in range(N + 1)]
for _ in range(M):
a, b = map(int, input().split())
route[a].append(b)
route[b].append(a)
q = deque([1]) # 頂点を設定して初期化
pre = [None] * (N+1) # 頂点までの最短に進む時の次の頂点のリスト
pre[1] = 0 # 頂点は0
depth = [None] * (N+1) # 頂点からの深さ(最短距離)のリスト
depth[1] = 0 # 頂点の距離は0
while len(q) > 0:
x = q.popleft()
for r in route[x]:
if pre[r] is None:
depth[r] = depth[x] + 1
pre[r] = x
q.append(r)
print("Yes")
for i in range(2, len(pre)):
print(pre[i])
| 0 | null | 35,994,539,386,480 | 197 | 145 |
a = input()
N = int(a)
A = list(map(int,input().split()))
flag = 0
y = 1000
for i in range(1,N):
if A[i-1] < A[i] and flag == 0:
x = y//A[i-1]
y = y % A[i-1]
flag = 1
if (A[i-1] > A[i]) and flag == 1:
y = y + A[i-1]*x
flag = 0
if flag == 1 and i == N-1:
y = y + A[i]*x
print(y)
|
def gcd(a,b):
while b:
a,b = b,a%b
return abs(a)
K=int(input())
#余裕でTLE?
ans=0
for a in range(1, K+1):
for b in range(1, K+1):
for c in range(1, K+1):
temp=a
temp=gcd(temp, b)
temp=gcd(temp, c)
ans+=temp
print(ans)
| 0 | null | 21,306,080,510,748 | 103 | 174 |
#デフォルト
import itertools
from collections import defaultdict
import collections
import math
import sys
sys.setrecursionlimit(200000)
mod = 1000000007
h1, m1, h2, m2, k = map(int, input().split())
minute = ((h2 * 60) + m2) - ((h1 * 60) + m1)
print(minute - k)
|
import math
S = list(map(int, input().split()))
a = (S[2]-S[0])*60+(S[3]-S[1])
b = a - S[4]
if(b>0):
print(b)
else:
print(0)
| 1 | 18,068,290,652,668 | null | 139 | 139 |
from collections import deque
n, m = map(int, input().split())
# dist = [-1 for i in range(n)]
prenodes = [-1 for i in range(n)]
G = [[] for i in range(n)]
ab = []
for i in range(m):
ab.append(list(map(int, input().split())))
for i in range(m):
G[ab[i][0]-1].append(ab[i][1]-1)
G[ab[i][1]-1].append(ab[i][0]-1)
# print(G)
# dist[0] = 0
prenodes[0] = 0
que = deque([0])
while len(que) != 0:
v = que.popleft()
for vi in G[v]:
if prenodes[vi] != -1:
continue
que.append(vi)
# dist[vi] = dist[v] + 1
prenodes[vi] = v
ans = "Yes"
for i in range(n):
if prenodes[i] == -1:
ans = "No"
break
if ans == "No":
print(ans)
else:
print(ans)
for i in range(1, n):
print(prenodes[i]+1)
|
import queue
q = queue.Queue()
bool = True
def bfs():
q.put(0)
while not q.empty():
now = q.get()
for i in nodes[now]:
if dist[i] != -1:
continue
dist[i] = dist[now] + 1
q.put(i)
ans[i] = now
# bool = False
N, M = map(int, input().split())
nodes = [[] for i in range(N)]
idxStock = []
for i in range(M):
a, b = map(int, input().split())
nodes[a - 1].append(b - 1)
nodes[b - 1].append(a - 1)
dist = [-1] * N
ans = [-1] * N
bfs()
if bool:
print("Yes")
for i in range(1, N):
print(ans[i] + 1)
else:
print("No")
| 1 | 20,493,718,730,160 | null | 145 | 145 |
a,b,c = map(int, input().split())
print(str(c)+" "+str(a)+" "+str(b))
|
K = int(input())
A, B = map(int, input().split())
ans = "NG"
for i in range(A, B+1):
if i % K == 0:
ans = "OK"
break
else:
pass
print(ans)
| 0 | null | 32,136,122,870,168 | 178 | 158 |
N, K = list(map(int, input().split()))
H = list(map(int, input().split()))
H.sort()
remain = max(0, N-K)
H = H[:remain]
print(sum(H))
|
cond = map(int, raw_input().split())
a = cond[0]
b = cond[1]
print (a*b),
print (a*2 + b*2)
| 0 | null | 39,739,137,906,752 | 227 | 36 |
while True:
x = [int(z) for z in input().split(" ")]
if x[0] == 0 and x[1] == 0: break
for h in range(0,x[0]):
dot = h % 2
for w in range(0,x[1]):
if (dot == 0 and w % 2 == 0) or (dot == 1 and w % 2 == 1):
print("#", end="")
else:
print(".", end="")
print("\n", end="")
print("")
|
while True:
H, W = map(int, input().split())
if H == W == 0:
break
for i in range(H):
if i % 2 == 0:
if W % 2 != 0:
print("#." * (W // 2) + "#")
continue
print("#." * (W // 2))
else:
if W % 2 != 0:
print(".#" * (W // 2) + ".")
continue
print(".#" * (W // 2))
print()
| 1 | 867,255,323,652 | null | 51 | 51 |
n = int(input())
titles = []
times = []
for i in range(n):
title,m = input().split()
titles.append(title)
times.append(int(m))
print(sum(times[titles.index(input())+1:]))
|
import math
n = int(input())
x = int(n/1.08)
if math.floor(x*1.08) == n:
print (x)
elif math.floor((x-1)*1.08) == n:
print (x-1)
elif math.floor((x+1)*1.08) == n:
print (x+1)
else:
print (":(")
| 0 | null | 111,430,593,850,058 | 243 | 265 |
h,w,k=map(int, input().split())
Black = []
for i in range(h):
c = input()
for j in range(w):
if c[j] == "#":
Black.append((i,j))
# print(Black, len(Black))
ans = 0
for i in range(2 ** h):
for j in range(2 ** w):
a = len(Black)
for b in Black:
if ((i >> b[0]) & 1) or ((j >> b[1]) & 1):
# if b[0] != i - 1 and b[1] != j - 1:
a -= 1
if a == k:
ans += 1
# print(bin(i),bin(j))
print(ans)
|
a = int(raw_input())
h = a / 3600
m = (a % 3600) / 60
s = a % 60
print "{0}:{1}:{2}".format(h, m, s)
| 0 | null | 4,645,930,219,792 | 110 | 37 |
x = not(int(input()))
print(int(x))
|
#import sys
#input = sys.stdin.readline
Q = 10**9+7
def cmb(n,r):
if n-r < r: r = n-r
if r == 0: return 1
denominator = 1 #分母
numerator = 1 #分子
for i in range(r):
numerator *= n-i
numerator %= Q
denominator *= i+1
denominator %= Q
return numerator*pow(denominator, Q-2, Q)%Q
def main():
S = int( input())
ans = 0
for i in range(1, S//3+1):
t = S - i*3
ans += cmb(t+i-1,i-1)
ans %= Q
print(ans)
if __name__ == '__main__':
main()
| 0 | null | 3,126,836,917,600 | 76 | 79 |
def main():
data = input().split()
print( int(data[0]) * int(data[1]))
if __name__ == '__main__':
main()
|
str_num = input()
num_list = str_num.split()
answer = int(num_list[0]) * int(num_list[1])
print(answer)
| 1 | 15,892,244,773,340 | null | 133 | 133 |
results=[]
from sys import stdin
for line in stdin:
a, b = (int(i) for i in line.split())
results.append(len(str(a+b)))
for i in results:
print i
|
# -*- coding: utf-8 -*-
import sys
for s in sys.stdin:
print len(str(int(s.rstrip().split()[0])+int(s.rstrip().split()[1])))
| 1 | 125,144,722 | null | 3 | 3 |
def main():
X,Y = map(int,input().split())
for x in range(101):
for y in range(101):
if x+y==X and 2*x+4*y==Y:
return True
return False
if __name__ == '__main__':
print("Yes" if main() else "No")
|
x,y = map(int,input().split())
a = (4*x-y)/2
b = (-2*x+y)/2
if a%1 == 0 and 0 <= a and b%1 == 0 and 0 <=b:
print("Yes")
else:
print("No")
| 1 | 13,733,359,329,302 | null | 127 | 127 |
def merge(arr, left: int, mid: int, right: int) -> int:
n1 = mid - left
n2 = right - mid
L = [arr[left + i] for i in range(n1)]
R = [arr[mid + i] for i in range(n2)]
L.append(10 ** 9)
R.append(10 ** 9)
i = 0
j = 0
cnt = 0
for k in range(left, right):
cnt += 1
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
return cnt
def merge_sort(arr, left: int, right: int) -> int:
cnt = 0
if left + 1 < right:
mid = (left + right) // 2
cnt += merge_sort(arr, left, mid)
cnt += merge_sort(arr, mid, right)
cnt += merge(arr, left, mid, right)
return cnt
n = int(input())
S = list(map(int, input().split()))
cnt = merge_sort(S, 0, n)
print(*S)
print(cnt)
|
cnt = 0
def merge(A, left, mid, right):
global cnt
L = A[left:mid]
R = A[mid:right]
L.append(10000000000)
R.append(10000000000)
i = 0
j = 0
for k in range(left, right):
if L[i] <= R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
cnt += 1
def mergesort(A, left, right):
if left + 1 < right: #if block size >= 2
mid = int((left + right)/2)
mergesort(A, left, mid)
mergesort(A, mid, right)
merge(A, left, mid, right)
n = int(input())
S = list(map(int,input().split()))
mergesort(S, 0, n)
print(*S)
print(str(cnt))
| 1 | 109,967,737,230 | null | 26 | 26 |
for i in range(1,10):
for j in range(1,10):
a=i*j
print(f'{i}x{j}={a}')
|
for a in range(1,10):
for b in range(1,10): print "%dx%d=%d" %(a,b,a*b)
| 1 | 2,656,514 | null | 1 | 1 |
# coding: utf-8
n = int(input())
A = list(map(int, input().split()))
mini = 1
c = 0
for i in range(n):
mini = i
for j in range(i, n):
if A[j] < A[mini]:
mini = j
A[i], A[mini] = A[mini], A[i]
if mini != i:
c += 1
print(" ".join(map(str, A)))
print(c)
|
N, A, cou = int(input()), [int(temp) for temp in input().split()], 0
for i in range(N) :
minj = i
for j in range(i, N) :
if A[j] < A[minj] :
minj = int(j)
if A[i] != A[minj] :
A[i], A[minj] = int(A[minj]), int(A[i])
cou = cou + 1
print(*A)
print(cou)
| 1 | 19,659,862,908 | null | 15 | 15 |
N, K = map(int, input().split())
A = list(map(int, input().split()))
# 丸太がすべてxの長さ以下になる回数を出し、それがK回以下か判定する
def f(x):
now = 0
for i in range(N):
now += (A[i]-1)//x
return now <= K
l = 0
r = 10**9
while r-l > 1:
mid = (r+l)//2
if f(mid):
r = mid
else:
l = mid
print(r)
|
import numpy as np
import sys
N,K = map(int, input().split())
A = np.array(sys.stdin.readline().split(), np.int64)
maxa = np.max(A)
mina = maxa // (K+1)
while maxa > mina + 1:
mid = (maxa + mina)// 2
div = np.sum(np.ceil(A/mid-1))
if div > K:
mina = mid
else:
maxa = mid
print(maxa)
| 1 | 6,496,269,456,582 | null | 99 | 99 |
from sys import exit
import copy
#import numpy as np
#from collections import deque
d, = map(int, input().split())
c= list(map(int, input().split()))
s=[list(map(int, input().split())) for _ in range(d)]
# t=[int(input()) for _ in range(d)]
sche=[0 for _ in range(d)]
s_tmp=float("inf")*(-1)
for off in range(0,13):
last=[0 for _ in range(26)]
sche=[0 for _ in range(d)]
for day in range(1,d+1):
idx=day-1
d_tmp=float("inf")*(-1)
i_tmp=0
for t in range(26):
delta=0
l_tmp=copy.copy(last)
delta+=s[idx][t]
l_tmp[t]=day
for l in range(26):
delta-=0.5*(off+1)*c[l]*((day-l_tmp[l])+(day+off-l_tmp[l]))
if delta>=d_tmp:
d_tmp=delta
i_tmp=t
sche[idx]=i_tmp+1
# score+=d_tmp
last[i_tmp]=day
# print(score)
# print(i_tmp+1)
score=0
last=[0 for _ in range(26)]
for i in range(1,d+1):
idx=i-1
score+=s[idx][sche[idx]-1]
for l in range(26):
score-=c[l]*(i-last[l])
last[sche[idx]-1]=i
# print(score)
if score>=s_tmp:
s_tmp=score
sche_tmp=copy.copy(sche)
for i in sche_tmp:
print(i)
# print(s_tmp)
|
import numpy as np
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
D = int(readline())
CS = np.array(read().split(), np.int32)
C = CS[:26]
S = CS[26:].reshape((-1, 26))
del CS
last = np.zeros((26, ))
def compute_score(d, mask):
score = -np.sum(C * (d + 1 - last) * mask)
return score
ans = []
#SCORE = 0
for d in range(D):
max_score = -10000000
best_i = 0
for i in range(26):
mask = np.ones((26, ))
mask[i] = 0
score = compute_score(d, mask)
score += S[d][i]
if max_score < score:
max_score = score
best_i = i + 1
ans.append(best_i)
#SCORE += max_score
#print(SCORE)
print('\n'.join(map(str, ans)))
| 1 | 9,693,282,456,348 | null | 113 | 113 |
input()
a = [int(x) for x in input().split(" ")]
print(*a[::-1])
|
n = int(input())
ns = [int(i) for i in input().split()]
ns.reverse()
if len(ns) > n:
del ns[:(len(ns) - n)]
for i in ns:
if i != ns[-1]:
print(i,end=' ')
else:
print(i,end='')
print()
| 1 | 966,370,181,462 | null | 53 | 53 |
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")
|
if __name__ == '__main__':
try:
count = []
result = 0
T = int(input())
for _ in range(T):
x, y = map(int, input().split())
count.append([x, y])
for i in range(T-2):
if count[i][0] == count[i][1] and count[i+1][0] == count[i+1][1] and count[i+2][0] == count[i+2][1]:
print("Yes")
exit(0)
print("No")
except Exception:
pass
| 1 | 2,465,246,264,532 | null | 72 | 72 |
def resolve():
S = input()
for i in range(0, len(S), 2):
if not S[i:i + 2] == "hi":
print("No")
return
else:
print("Yes")
resolve()
|
# -*- coding: utf-8 -*-
# モジュールのインポート
import math
def get_input() -> int:
"""
標準入力を取得する.
Returns:\n
int: 標準入力
"""
S = int(input())
return S
def combinations_count(n: int, r: int) -> int:
"""
組み合わせの総数を取得する.
Args:\n
n (int): 整数
r (int): 整数(r <= n)
Returns:\n
int: 組み合わせの総数
"""
return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def main(S: int) -> None:
"""
メイン処理.
Args:\n
S (int): 整数(1 <= S <= 2000)
"""
# 求解処理
a = S // 3
b = S % 3
ans = 0
while a > 0:
ans += combinations_count(b + a - 1, b)
a -= 1
b += 3
ans %= 10**9 + 7
# 結果出力
print(ans)
if __name__ == "__main__":
# 標準入力を取得
S = get_input()
# メイン処理
main(S)
| 0 | null | 28,435,387,140,928 | 199 | 79 |
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = input()
ans = 0
prevs = [''] * k
for i in range(n//k+1):
#print(i)
#print(prevs)
for j in range(i*k, (i+1)*k):
if j >= n:
break
prevs_i = j%k
prev = prevs[prevs_i]
#print(prev)
if t[j] == 'r':
if prev == 'p':
prevs[prevs_i] = ''
else:
prevs[prevs_i] = 'p'
ans += p
elif t[j] == 's':
if prev == 'r':
prevs[prevs_i] = ''
else:
prevs[prevs_i] = 'r'
ans += r
elif t[j] == 'p':
if prev == 's':
prevs[prevs_i] = ''
else:
prevs[prevs_i] = 's'
ans += s
print(ans)
|
# coding=UTF-8
from collections import deque
from operator import itemgetter
from bisect import bisect_left, bisect
import itertools
import sys
import math
import numpy as np
import time
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
def main():
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = input()
myhand = [None] * n
point = 0
for i in range(n):
if t[i] == "r":
if myhand[i] != "np":
point += p
if i+k < n:
myhand[i+k] = "np"
else:
if i+k < n:
myhand[i + k] = None
elif t[i] == "s":
if myhand[i] != "nr":
point += r
if i+k < n:
myhand[i+k] = "nr"
else:
if i+k < n:
myhand[i + k] = None
elif t[i] == "p":
if myhand[i] != "ns":
point += s
if i+k < n:
myhand[i+k] = "ns"
else:
if i+k < n:
myhand[i + k] = None
print(point)
if __name__ == '__main__':
main()
| 1 | 107,195,177,525,110 | null | 251 | 251 |
a, b, c = map(int, input().split())
if c - (a+b) < 0:
print("No")
exit()
if 4*a*b < c**2 - 2*c*(a+b) + (a+b)**2:
print("Yes")
else:
print("No")
|
N, K = map(int, input().split())
P = list(map(int, input().split()))
score = sum(P[:K])
mmax = score
idx = 0
for i in range(1, N-K+1):
score = score - P[i-1] + P[i+K-1]
if score > mmax:
mmax = score
idx = i
else:
continue
print((K+mmax)/2)
| 0 | null | 63,106,864,958,290 | 197 | 223 |
k=int(input())
def dfs(keta, val):
lunlun.append(val)
if keta==10:
return
for i in range(-1,2):
add=(val%10)+i
if 0<=add<=9:
dfs(keta+1, val*10+add)
lunlun=[]
for i in range(1,10):
dfs(1, i)
lunlun.sort()
print(lunlun[k-1])
|
n, m = map(int, input().split())
ps = [input().split() for i in range(m)]
b = [False] * n
wa = [0] * n
for i in ps:
if b[int(i[0])-1] == False and i[1] == "AC":
b[int(i[0])-1] = True
elif b[int(i[0])-1] == False and i[1] == "WA":
wa[int(i[0])-1] += 1
print(b.count(True),end=" ")
ans = 0
for i in range(n):
if b[i]:
ans += wa[i]
print(ans)
| 0 | null | 66,569,209,569,762 | 181 | 240 |
r = int(input())
pi= 3
ans = r*r*pi / pi
print(int(ans))
|
# 最大の友達集団の人の数ぶんだけグループに分ける必要がある。
# union-findを使用する必要がある。
class UnionFind:
# この時点でそれぞれのノードは自分を親としている
# 初期化時に問題が0の頂点を認めるかに注意すること
def __init__(self, n):
self.N = n
self.parent = [i for i in range(n)]
self.rank = [0 for _ in range(n)]
# xの根を返す関数
def root(self, x):
visited_nodes = []
while True:
p = self.parent[x]
if p == x:
# 縮約
for node in visited_nodes:
self.parent[node] = x
return x
else:
visited_nodes.append(x)
x = p
# 木の結合を行う。親の配下に入る
def unite(self, x, y):
if not self.root(x) == self.root(y):
if self.rank[x] > self.rank[y]:
self.parent[self.root(y)] = self.root(x)
else:
self.parent[self.root(x)] = self.root(y)
if self.rank[x] == self.rank[y]:
self.rank[self.root(y)] += 1
def ifSame(self, x, y):
return self.root(x) == self.root(y)
# 木の根に到達すまでにたどるノードの配列を返す
def printDebugInfo(self):
print([self.root(i) for i in range(self.N)])
N, M = map(int, input().split())
tree = UnionFind(N)
for i in range(M):
A, B = map(int, input().split())
tree.unite(A-1, B-1)
bag = {}
for i in range(N):
boss = tree.root(i)
if not boss in bag.keys():
bag[boss] = 1
else:
bag[boss] += 1
print(max(bag.values()))
| 0 | null | 74,773,303,276,800 | 278 | 84 |
S = list(input())
Q = int(input())
c = 0
w = []
for i in range(Q) :
a = input()
if a[0] == "1" :
c ^= 1
else :
if a[2] == "1" :
if c == 0 :
w.append(a[4])
else :
S.append(a[4])
else :
if c == 0 :
S.append(a[4])
else :
w.append(a[4])
S = w[::-1] + S
print("".join(S) if c == 0 else "".join(S[::-1]))
|
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)
| 1 | 57,218,194,729,498 | null | 204 | 204 |
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)
|
N, K = map(int, input().split())
mod = 10**9 + 7
fact_count = [0 for _ in range(K+1)]
for k in range(1, K+1):
fact_count[k] = K//k
ans = 0
count = [0 for _ in range(K+1)]
for k in range(K, 0, -1):
c = pow(fact_count[k], N, mod)
j = 2*k
l = 2
while(j<=K):
c -= count[j]
l += 1
j = k*l
count[k] = c
c = c*k%mod
ans += c
ans %= mod
print(ans)
| 0 | null | 78,546,712,792,032 | 261 | 176 |
n, m, k =map(int, input().split())
a=list(map(int, input().split()))
b=list(map(int, input().split()))
ta=sum(a)
a.append(0)
tb=0
ans=0
j=0
for i in range(n+1):
ta -= a[n-i]
if ta>k:
continue
while tb + ta<=k:
if j ==m:
ans=max(ans,n-i+j)
break
ans=max(ans,n-i+j)
tb += b[j]
j +=1
print(ans)
|
N = int(input())
if N % 2 == 0 :
print("{}".format(N//2-1))
else:
print("{}".format(N//2))
| 0 | null | 81,938,055,623,292 | 117 | 283 |
N,M = map(int,input().split())
C = list(map(int,input().split()))
INF = float('inf')
dp = [INF] * (N+1)
dp[0] = 0
for i in range(M):
c = C[i]
for j in range(N+1):
if j >= c:
dp[j] = min(dp[j], dp[j-c]+1)
print(dp[N])
|
n,m=map(int,input().split())
c=list(map(int,input().split()))
c.sort()
# print(c) #DB
dp=[[0 for j in range(n+1)] for i in range(m)] # i番目(0<=i<=m-1)までのコインを使用してj円(0<=j<=n)を支払う際の最少の枚数
for j in range(n+1):
dp[0][j]=j
for i in range(1,m):
for j in range(n+1):
if j<c[i]:
dp[i][j]=dp[i-1][j]
else:
dp[i][j]=min(dp[i-1][j],dp[i][j-c[i]]+1)
# print(c[i],dp[i]) #DB
print(dp[m-1][n])
| 1 | 136,986,775,030 | null | 28 | 28 |
a, b= map(int, input().split())
if a<b:print( "a < b")
if a>b:print ("a > b")
if a==b:print ("a == b")
|
a, b = [int(x) for x in input().split(" ")]
if a > b:
ope =">"
elif a < b :
ope ="<"
elif a == b:
ope = "=="
print("a {} b".format(ope))
| 1 | 358,720,135,460 | null | 38 | 38 |
import sys
def input(): return sys.stdin.readline().strip()
def resolve():
x,y=map(int, input().split())
ans=0
if x<=3:
ans+=100000
if x<=2:
ans+=100000
if x==1:
ans+=100000
if y<=3:
ans+=100000
if y<=2:
ans+=100000
if y==1:
ans+=100000
if x==1 and y==1:
ans+=400000
print(ans)
resolve()
|
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
n, m = map(int, input().split())
aa = [0, 300000, 200000, 100000]
ans=0
if n <4:
ans += aa[n]
if m <4:
ans += aa[m]
if n == 1 and m ==1:
ans += 400000
print(ans)
| 1 | 140,317,671,117,792 | null | 275 | 275 |
def merge(A,left,mid,right):
global cnt
L=A[left:mid]
R=A[mid:right]
L.append(float("inf"))
R.append(float("inf"))
i=0
j=0
for k in range(left, right):
cnt+=1
if L[i]<=R[j]:
A[k]=L[i]
i+=1
else:
A[k]=R[j]
j+=1
def mergeSort(A,left,right):
if left+1<right:
mid=(left+right)//2
mergeSort(A,left,mid)
mergeSort(A,mid,right)
merge(A,left,mid,right)
n = int(input())
S=list(map(int,input().split()))
cnt=0
mergeSort(S,0,n)
print(" ".join(map(str,S)))
print(cnt)
|
from collections import deque
d = deque()
for _ in range(int(input())):
a = input()
if "i" == a[0]: d.appendleft(int(a[7:]))
elif "F" == a[6]: d.popleft()
elif "L" == a[6]: d.pop()
else:
try: d.remove(int(a[7:]))
except: pass
print(*d)
| 0 | null | 84,996,553,710 | 26 | 20 |
import sys
args = input()
print(args[:3])
|
import bisect
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a2 = [0] * (n + 1)
b2 = [0] * (m + 1)
for i in range(0, n):
a2[i+1] = a[i] + a2[i]
for i in range(0, m):
b2[i+1] = b[i] + b2[i]
ans = 0
for i in range(n+1):
tmp = bisect.bisect_right(b2, k-a2[i]) - 1
if a2[i] + b2[tmp] <= k and tmp >= 0:
ans = max(ans, i+tmp)
print(ans)
| 0 | null | 12,715,792,174,580 | 130 | 117 |
n, p = map(int, input().split())
if p in (2, 5):
c = 0
for i, x in enumerate(map(int, input()[::-1])):
if x % p == 0:
c += n-i
print(c)
else:
c = [0] * p
y = 0
t = 1
for x in map(int, input()[::-1]):
y = (y + t*x) % p
c[y] += 1
t = (10 * t) % p
print(sum(i * (i-1) // 2 for i in c) + c[0])
|
import sys
N, M = map(int,input().split())
S = input()
S = S[::-1]
i = 0
ans = []
while i < N:
flag = 0
for j in range(M,0,-1):
if i + j <= N and S[i + j] == '0':
i += j
flag = 1
ans.append(j)
break
if flag:
continue
print(-1)
sys.exit()
ans.reverse()
print(*ans)
| 0 | null | 98,547,555,718,568 | 205 | 274 |
n=int(input())
if n%2:
print(0)
else:
c=0
n//=2
while n:
n//=5
c+=n
print(c)
|
import math
n = int(input())
cnt = 0
mod = 10
if n%2 == 1:
print(0)
exit()
while mod<=n:
cnt += n//mod
mod*=5
print(cnt)
| 1 | 116,218,029,755,298 | null | 258 | 258 |
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
import numpy as np
def main():
n = int(input())
if n == 1:
print(1)
sys.exit()
divs = np.arange(1, n + 1)
divs2 = n // divs
divs3 = divs2 * (divs2 + 1) // 2
divs3 = divs3 * divs
r = divs3.sum()
print(r)
if __name__ == '__main__':
main()
|
import numpy as np
N = int(input())
count = 0
for i in range(1, N+1):
count += (N // i) * (i + i * (N//i)) // 2
print(count)
| 1 | 10,967,842,593,188 | null | 118 | 118 |
n = int(input())
def dfs(s):
if len(s) == n:
print(s)
return
for i in range(ord("a"), ord(max(s))+2):
dfs(s+chr(i))
dfs("a")
|
x = list(map(int, input().split()))
for i in range(len(x)):
if x[i] is 0:
print(i+1)
| 0 | null | 33,005,593,643,732 | 198 | 126 |
import math
N,M=map(int,input().split())
def comb(num,k):
if num<2:
return 0
return math.factorial(num)/(math.factorial(k)*math.factorial(num-k))
ans=int(comb(N,2)+comb(M,2))
print(ans)
|
#!/usr/bin/env python3
# Generated by https://github.com/kyuridenamida/atcoder-tools
from typing import *
import collections
import functools
import itertools
import math
import sys
INF = float('inf')
def nPr(n: int, r: int) -> int:
return math.factorial(n) // math.factorial(n - r)
def nCr(n: int, r: int) -> int:
return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def solve(N: int, M: int):
return (nCr(N, 2)if N > 1 else 0) + (nCr(M, 2) if M > 1 else 0)
def main():
sys.setrecursionlimit(10 ** 6)
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
M = int(next(tokens)) # type: int
print(f'{solve(N, M)}')
if __name__ == '__main__':
main()
| 1 | 45,708,652,866,360 | null | 189 | 189 |
import math
n,k = (int(x) for x in input().split())
An = [int(i) for i in input().split()]
left = 0
right = max(An)
def check(x):
chk = 0
for i in range(n):
chk += math.ceil(An[i]/x)-1
return chk
while right-left!=1:
x = (left+right)//2
if check(x)<=k:
right = x
else:
left = x
print(right)
|
import sys
import heapq
import math
def input(): return sys.stdin.readline().rstrip()
def main():
n, k = map(int,input().split())
A = list(map(int,input().split()))
def is_good(mid, key):
kk = 0
for a in A:
kk += -(-a//mid)-1
if kk <= key:
return True
else:
return False
def bi_search(bad, good, key):
while good - bad > 1:
mid = (bad + good)//2
if is_good(mid, key):
good = mid
else:
bad = mid
return good
print(bi_search(0, 1000000000, k))
if __name__=='__main__':
main()
| 1 | 6,527,842,722,390 | null | 99 | 99 |
A,B = map(int, input().split())
ans = A * B
print(ans)
|
k = int(input())
l = []
if 7 % k == 0:
print(1)
exit(0)
l.append(7 % k)
for i in range(1,k):
a = (10 * l[i-1] + 7)
if a % k == 0:
print(i+1)
exit(0)
else:
l.append(a % k)
print(-1)
| 0 | null | 10,882,746,482,610 | 133 | 97 |
import math
N= int(input())
if 360%N==0:
print(int(360/N))
elif 360%N!=0:
a = math.gcd(360,N)
print(int(360/a))
|
import sys
X = int(input())
for i in range(1,1000):
if 360*i % X == 0:
print(360*i//X)
sys.exit()
| 1 | 13,100,642,224,738 | null | 125 | 125 |
def main():
N, K = map(int, input().split())
LR = [list(map(int, input().split())) for _ in range(K)]
MOD = 998244353
dp = [0]*(N+1)
S = [0]*(N+1)
dp[1] = 1
S[1] = 1
for i in range(2, N+1):
for l, r in LR:
if i-l < 0:
continue
else:
dp[i] += S[i-l] - S[max(i-r-1, 0)]
dp[i] %= MOD
S[i] = S[i-1] + dp[i]
print(dp[-1]%MOD)
if __name__ == '__main__':
main()
|
n, k = map(int, input().split())
lr = [list(map(int, input().split())) for _i in range(k)]
mod = 998244353
dp = [0]*(n+1)
dp[1] = 1
for p in range(2, n+1):
for i, j in lr:
dp[p] += dp[max(p-i, 0)] - dp[max(p-j-1, 0)]
dp[p] %= mod
dp[p] += dp[p-1]
print((dp[n]-dp[n-1])%mod)
| 1 | 2,712,908,012,308 | null | 74 | 74 |
x,y = map(int,input().split())
for i in range(x+1):
turu = i
kame = x-i
if 2 * turu + 4 * kame == y:
print("Yes")
break
else :
print("No")
|
n=int(input())
d=list(map(int,input().split()))
mx=max(d)
l=[0]*(10**5)
mx=0
for i in range(n):
if (i==0 and d[i]!=0) or (i!=0 and d[i]==0):
print(0)
exit()
l[d[i]]+=1
mx=max(mx,d[i])
t=1
ans=1
for i in range(1,mx+1):
ans *= t**l[i]
t=l[i]
print(ans%998244353)
| 0 | null | 84,588,027,509,600 | 127 | 284 |
n = int(input())
d = list(map(int, input().split()))
s = 0
for i in range(n):
for j in range(n):
if i != j:
s += d[i]*d[j]
s //= 2
print(s)
|
import itertools
N = int(input())
d = list(map(int, input().split()))
combi = list(itertools.combinations(range(N), 2))
sumD = 0
for x in combi:
sumD += d[x[0]] * d[x[1]]
print(sumD)
| 1 | 168,130,175,994,206 | null | 292 | 292 |
n, m, q = map(int, input().split())
candidate = []
def gen(cur):
if len(cur) == n:
candidate.append(cur)
else:
t = cur[-1]
for tv in range(t, m + 1):
nex = cur[:]
nex.append(tv)
gen(nex)
for i in range(1, m + 1):
arr = [i]
gen(arr)
ask = []
for _ in range(q):
ask.append(list(map(int, input().split())))
ans = 0
for cv in candidate:
tmp = 0
for av in ask:
if cv[av[1] - 1] - cv[av[0] - 1] == av[2]:
tmp += av[3]
ans = max(ans, tmp)
print(ans)
|
li = '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'
li = list(map(int, li.split(',')))
k = int(input())
print(li[k - 1])
| 0 | null | 38,943,086,942,880 | 160 | 195 |
L = input().split()
n = len(L)
A = []
top = -1
for i in range(n):
if L[i] not in {"+","-","*"}:
A.append(int(L[i]))
top += 1
else:
if(L[i] == "+"):
A[top - 1] = A[top - 1] + A[top]
elif(L[i] == "-"):
A[top - 1] = A[top -1] - A[top]
elif(L[i] == "*"):
A[top - 1] = A[top - 1] * A[top]
del A[top]
top -= 1
print(A[top])
|
N = int(input())
res = 0
if N % 2 == 0:
div = N // 2
for i in range(1,30):
res += div // 5**i
print(res)
| 0 | null | 58,056,723,667,332 | 18 | 258 |
N,K = map(int,input().split())
M = list(map(int,input().split()))
M =sorted(M,reverse=True)
print(sum(M[K:]))
|
a = input('')
N = []
num = 0
for i in a:
N.append(i)
for j in range(0,len(N)):
num += int(N[j])
if num%9 == 0:
print('Yes')
else:
print('No')
| 0 | null | 41,689,306,368,372 | 227 | 87 |
(r, c) = [int(i) for i in input().split()]
table = [[0 for j in range(c + 1)]for i in range(r + 1)]
for i in range(r):
tmp = [int(x) for x in input().split()]
for j in range(c + 1):
if not j == c:
table[i][j] = tmp[j]
table[i][c] += table[i][j]
table[r][j] += table[i][j]
for i in range(r + 1):
for j in range(c + 1):
if j == c:
print(table[i][j], end='')
else:
print(table[i][j], '', end='')
print()
|
table = []
r, c = map(int, input().strip().split())
[table.append(input().strip().split()) for i in range(r)]
table.append([])
for j in range(r + 1):
for k in range(c + 1):
if j == r and k != c:
lastrow = sum(map(int, [table[x][k] for x in range(r)]))
table[-1].append(lastrow)
if k == c:
print(sum(map(int, table[j])))
break
print(table[j][k],end=' ')
| 1 | 1,359,496,490,680 | null | 59 | 59 |
import bisect
import sys
def input(): return sys.stdin.readline().rstrip()
n = int(input())
s = list(input())
q = int(input())
char_idx = [[] for _ in range(26)]
for i in range(n):
char_idx[ord(s[i])-ord('a')].append(i)
# print(char_idx)
query = [input().split() for _ in range(q)]
# print(query)
for t, a, b in query:
if t=='1':
i = int(a) - 1
if s[i] == b:
continue
else:
idx = bisect.bisect_left(char_idx[ord(s[i])-ord('a')], i)
if char_idx[ord(s[i])-ord('a')][idx] == i:
del char_idx[ord(s[i])-ord('a')][idx]
bisect.insort_left(char_idx[ord(b)-ord('a')], i)
s[i] = b
else:
l = int(a) - 1
r = int(b) - 1
ans = 0
for i in range(26):
if len(char_idx[i]) == 0:
continue
it = bisect.bisect_left(char_idx[i], l)
if it < len(char_idx[i]) and char_idx[i][it] <= r:
ans += 1
print(ans)
|
def main():
N = int(input())
A = list(map(int, input().split(' ')))
insertion_sort(A, N)
def insertion_sort(A, N):
print(' '.join([str(n) for n in A]))
for i in range(1, N):
v = A[i]
j = i - 1
while j >= 0 and A[j] > v:
A[j+1] = A[j]
j -= 1
A[j+1] = v
print(' '.join([str(n) for n in A]))
return A
if __name__ == '__main__':
main()
| 0 | null | 31,214,415,086,788 | 210 | 10 |
n = int(input())
a = list(map(int, input().split()))
a.sort()
def main(a):
if 0 in a:
ans = 0
else:
ans = 1
for item in a:
ans *= item
if ans > 1000000000000000000:
ans = -1
break
return ans
ans = main(a)
print(ans)
|
input();ans,a=1,[*map(int,input().split())]
if 0 in a:
print(0)
else:
for i in a:
ans*=i
if ans>10**18:
print(-1);break
else:
print(ans)
| 1 | 16,190,769,316,230 | null | 134 | 134 |
from itertools import combinations
n = int(input())
l = list(map(int, input().split()))
comb = list(combinations(range(n), 3))
ans = 0
for i,j,k in comb:
a = l[i]
b = l[j]
c = l[k]
if a == b:
continue
if b == c:
continue
if c == a:
continue
if sum([a,b,c]) <= 2 * max(a,b,c):
continue
ans += 1
print(ans)
|
n = int(input())
arr = list(map(int, input().split()))
ans = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if arr[i] != arr[j] and arr[i] != arr[k] and arr[j] != arr[k]:
if (arr[i] + arr[j]) > arr[k] and (arr[i] + arr[k]) > arr[j] and (arr[j] + arr[k]) > arr[i]:
ans += 1
print(ans)
| 1 | 5,031,481,799,748 | null | 91 | 91 |
n, m = map(int, input().split())
lis = sorted(list(map(int, input().split())), reverse=True)
limit = sum(lis) / (4 * m)
judge = 'Yes'
for i in range(m):
if lis[i] < limit:
judge = 'No'
break
print(judge)
|
# coding=utf-8
import math
def cut_into_three(start: list, end: list) -> list:
x1 = (2*start[0]+end[0])/3
y1 = (2*start[1]+end[1])/3
mid_point1 = [x1, y1]
x2 = (start[0]+2*end[0])/3
y2 = (start[1]+2*end[1])/3
mid_point2 = [x2, y2]
points_list = [start, mid_point1, mid_point2, end]
return points_list
def equil_triangle(point1: list, point2: list) -> list:
cos60 = math.cos(math.pi / 3)
sin60 = math.sin(math.pi / 3)
x = (point2[0] - point1[0])*cos60 - (point2[1]-point1[1])*sin60 + point1[0]
y = (point2[0] - point1[0])*sin60 + (point2[1]-point1[1])*cos60 + point1[1]
return [x, y]
def make_projection(start: list, end: list) -> list:
points_list = cut_into_three(start, end)
projection_point = equil_triangle(points_list[1], points_list[2])
points_list.insert(2, projection_point)
return points_list
def koch_curve(start: list, end: list, number: int) -> list:
if number == 0:
return [start, end]
else:
points_list = make_projection(start, end)
list1 = koch_curve(points_list[0], points_list[1], number-1)
list2 = koch_curve(points_list[1], points_list[2], number-1)
list3 = koch_curve(points_list[2], points_list[3], number-1)
list4 = koch_curve(points_list[3], points_list[4], number-1)
new_points_list = list1 + list2[1:] + list3[1:] + list4[1:]
return new_points_list
if __name__ == '__main__':
n = int(input())
p1 = [0, 0]
p2 = [100, 0]
fractal_points = koch_curve(p1, p2, n)
for i in fractal_points:
print(' '.join(map(str, i)))
| 0 | null | 19,558,945,814,620 | 179 | 27 |
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from collections import defaultdict
def main():
n, x, m = map(int, input().split())
d1 = defaultdict(int)
r = 0
while n:
if d1[x]:
cycle = d1[x] - n
t0 = 0
cycle2 = cycle
while cycle2:
t0 += x
x = x**2 % m
cycle2 -= 1
c, rem = divmod(n, cycle)
r += c * t0
while rem:
r += x
x = x**2 % m
rem -= 1
print(r)
sys.exit()
else:
d1[x] = n
r += x
x = x**2 % m
n -= 1
print(r)
if __name__ == '__main__':
main()
|
N,X,M=map(int,input().split())
modlist=[0]*M
modset=set()
ans=0
for i in range(M):
if X in modset:
startloop=modlist.index(X)
sum_outofloop=sum(modlist[:startloop])
inloop=ans-sum_outofloop
numofloop=(N-startloop)//(i-startloop)
ans=sum_outofloop+numofloop*inloop+sum(modlist[startloop:startloop+((N-startloop)%(i-startloop))])
#print(inloop,i,startloop,sum_outofloop,numofloop,sum(modlist[startloop:startloop+((N-startloop)%(i-startloop))]))
break
else:
modset.add(X)
ans+=X
modlist[i]=X
X**=2
X%=M
if i==N-1:
break
print(ans)
#print(modlist)
| 1 | 2,821,942,392,224 | null | 75 | 75 |
N=int(input())
L=[[10**9]for i in range(N+1)]
for i in range(N):
l=list(map(int,input().split()))
for j in range(l[1]):
L[i+1].append(l[2+j])
#print(L)
for i in range(N+1):
L[i].sort(reverse=True)
#print(L)
ans=[]
for i in range(N+1):
ans.append([0,0])
from collections import deque
Q=deque()
cnt=1
for i in range(N):
Q.append([0,N-i])
for i in range(10**7):
if len(Q)==0:
break
q0,q1=Q.pop()
#print(q0,q1)
if q1!=10**9:
if ans[q1][0]==0:
ans[q1][0]=cnt
cnt+=1
for j in L[q1]:
Q.append([q1,j])
else:
ans[q0][1]=cnt
cnt+=1
#print(ans,Q)
for i in range(1,N+1):
print(i,ans[i][0],ans[i][1])
|
import math
X = int(input())
X -= 1
while True:
flg = 0
X += 1
lim = int(math.sqrt(X))
for i in range(2, lim+1):
if X % i == 0:
flg = 1
break
if flg == 1:
continue
break
print(X)
| 0 | null | 53,069,976,990,316 | 8 | 250 |
import sys
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def resolve():
a,b,c=map(int, input().split())
if Decimal(a).sqrt()+Decimal(b).sqrt()<Decimal(c).sqrt():
print('Yes')
else:
print('No')
resolve()
|
#!/usr/bin/env python3
a, b, c = map(int, input().split())
if a+b>c:
print('No')
exit()
f1 = 4*a*b - 2*a*b + 2*c*a + 2*b*c
f2 = c**2 + b**2 + a**2
if f1 < f2:
print('Yes')
else:
print('No')
| 1 | 51,724,560,419,520 | null | 197 | 197 |
N = int(input())
A = list(map(int, input().split()))
A.append(0)
okane = 1000
kabu = 0
for i in range(N):
if A[i] <= A[i+1]:
buy = okane//A[i]
okane -= buy*A[i]
kabu += buy
if A[i] > A[i+1]:
okane += kabu*A[i]
kabu = 0
print(okane)
|
N = int(input())
A = list(map(int, input().split()))
m = 1000
k = 0
for i in range(N-1):
if A[i] > A[i+1]:
m += k * A[i]
k = 0
elif A[i] < A[i+1]:
m += k * A[i]
k = m // A[i]
m -= k * A[i]
else:
pass
m += (k * A[-1])
print(m)
| 1 | 7,386,685,850,610 | null | 103 | 103 |
from math import gcd
def lcm(a,b):return (a*b)//(gcd(a,b))
def f(x):
cnt=0
while(x%2==0):
cnt+=1
x=x//2
return cnt
n,m=map(int,input().split())
a=list(map(int,input().split()))
a=list(map(lambda x: x//2,a))
t=f(a[0])
for i in range(n):
if(f(a[i])!=t):
print(0)
exit()
a[i]=a[i]//(2**t)
m=m//(2**t)
l=1
for i in range(n):
l=lcm(l,a[i])
if(l>m):
print(0)
exit()
m=m//l
print((m+1)//2)
|
import sys
from fractions import gcd
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
def lcm(a, b):
return a * b // gcd(a, b)
def main():
N, M, *A = map(int, read().split())
A = list({a // 2 for a in A})
power = 1
while all(a % 2 == 0 for a in A):
A = [a // 2 for a in A]
power *= 2
if any(a % 2 == 0 for a in A):
print(0)
return
l = 1
for a in A:
l = lcm(l, a)
l *= power
ans = (M + l) // (2 * l)
print(ans)
return
if __name__ == '__main__':
main()
| 1 | 102,034,823,920,768 | null | 247 | 247 |
def main():
a, b = map(int, input().split())
if 10 > a and 10 > b:
print(a*b)
else:
print("-1")
if __name__ == '__main__':
main()
|
A,B = map(int,input().split())
if A < 10 and B < 10:
answer = A * B
print(answer)
else:
print('-1')
| 1 | 158,017,764,624,160 | null | 286 | 286 |
MOD = int(1e9+7)
N, K = map(int, input().split())
count = [0] * (K+1)
ans = 0
for now in range(K, 0, -1):
count[now] = pow(K // now, N, MOD)
for j in range(2*now ,K+1, now):
count[now] -= count[j]
if count[now] < 0:
count[now] += MOD
ans += now * count[now]
print(ans % MOD)
|
N,K=list(map(int,input().split()))
l=[0]*(K+1)
ans=0
mod=10**9+7
for x in range(K,0,-1):
l[x]=pow((K//x),N,mod)
for y in range(2*x,K+1,x):
l[x]-=l[y]
l[x]=pow(l[x],1,mod)
ans+=l[x]*x
ans=pow(ans,1,mod)
print(ans)
| 1 | 36,713,975,760,308 | null | 176 | 176 |
import sys
X, K, D = map(int, input().split())
X = abs(X)
if X // D >= K:
print(X - K*D)
sys.exit()
K = K - (X // D)
A = X - X//D*D
if K % 2 == 0:
print(A)
else:
print(abs(A - D))
|
print(6-sum([int(input()) for i in range(2)]))
| 0 | null | 58,055,371,241,732 | 92 | 254 |
def main():
n, m = list(map(int, input().split(" ")))
ans = 0
ans += n*(n-1)/2
ans += m*(m-1)/2
print(int(ans))
if __name__ == "__main__":
main()
|
def resolve():
import math
n, m = list(map(int, input().split()))
ans1 = math.factorial(n) // (math.factorial(n-2) * 2) if n > 1 else 0
ans2 = math.factorial(m) // (math.factorial(m-2) * 2) if m > 1 else 0
print(ans1 + ans2)
resolve()
| 1 | 45,744,891,090,948 | null | 189 | 189 |
C = input()
alp = "abcdefghijklmnopqrstuvwxyz"
print(alp[alp.index(C)+1])
|
import sys
from collections import namedtuple, defaultdict
from math import gcd
input = sys.stdin.readline
class Point:
def __init__(self, x, y):
g = gcd(abs(x), abs(y))
x //= g
y //= g
if x < 0:
x *= -1
y *= -1
elif x == 0 and y < 0:
y *= -1
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
def __repr__(self):
return f'({self.x}, {self.y})'
def main():
n = int(input())
p = []
d = defaultdict(lambda: 0)
zeros = 0
for _ in range(n):
x, y = map(int, input().split())
if x == 0 and y == 0:
n -= 1
zeros += 1
continue
p.append(Point(x, y))
d[p[-1]] += 1
MOD = 10 ** 9 + 7
pw = [ pow(2, i, MOD) for i in range(n + 1) ]
ans = 1
tot = 0
for x in d.keys():
if x.x > 0 and x.y >= 0 and Point(-x.y, x.x) in d:
s = d[x]
t = d[Point(-x.y, x.x)]
tot += s + t
value = (pw[s] + pw[t] - 1 + MOD) % MOD
ans = ans * value % MOD
ans = ans * pw[n - tot] % MOD
ans = (ans - 1 + MOD + zeros) % MOD
print(ans)
main()
| 0 | null | 56,630,094,431,072 | 239 | 146 |
n = int(input())
s = input()
def rot(c, r):
base = 65
return chr((ord(c)-base+r)%26+base)
print(''.join([rot(i, n) for i in s]))
|
N = int(input())
S = input()
char = ''
for i in range(len(S)):
char += chr((ord(S[i]) + N - 65) % 26 + 65)
print(char)
| 1 | 134,793,617,133,632 | null | 271 | 271 |
import sys
class UnionFind():
def __init__(self, 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
N, M = map(int, input().split())
uf = UnionFind(N)
for _ in range(M):
a, b = map(lambda x: int(x) - 1, sys.stdin.readline().split())
uf.union(a, b)
print(sum(p < 0 for p in uf.parents) - 1)
|
from collections import defaultdict
def bfs(s):
q = [s]
while q != []:
p = q[0]
del q[0]
for node in adj[p]:
if not visited[node]:
visited[node] = True
q.append(node)
n,m = map(int,input().split())
adj = defaultdict(list)
visited = [False]*(n+1)
comp = 0
for _ in range(m):
a,b = map(int,input().split())
adj[a].append(b)
adj[b].append(a)
for i in range(1,n+1):
if not visited[i]:
comp+=1
bfs(i)
print(comp-1)
| 1 | 2,302,488,294,300 | null | 70 | 70 |
from sys import stdin
n = int(stdin.readline().strip())
a_lst = [int(x) for x in stdin.readline().strip().split()]
pos = len(a_lst) // 2
min_diff = 10000000000000000000
while(True):
left = sum(a_lst[:pos])
right = sum(a_lst[pos:])
diff = right - left
if min_diff > abs(diff): min_diff = abs(diff)
else: break
if diff > 0: pos += 1
elif diff < 0: pos -= 1
print(min_diff)
|
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
# input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools
import queue
from collections import deque
from fractions import Fraction
def main():
a, b , c = map(int, input().split())
if a / c <= b:
print("Yes")
else:
print("No")
if __name__ == '__main__':
main()
| 0 | null | 72,652,504,649,488 | 276 | 81 |
n, k = map(int,input().split())
w = [0]*n
for i in range(n):
w[i] = int(input())
minP = max(max(w), sum(w)//k)
maxP = sum(w)
left = minP
right = maxP
while left < right:
mid = (left + right) // 2
load = 0
cnt_track = 1
flag = 1
for i in range(n):
load += w[i]
if load > mid:
load = w[i]
cnt_track += 1
if cnt_track > k:
flag = 0
break
if flag:
right = mid
else:
left = mid + 1
print(left)
|
setting = input().split();
package_count = int(setting[0]);
truck_count = int(setting[1]);
packages = [];
for i in range(package_count):
packages.append(int(input()));
def allocation():
max_p = sum(packages);
left = 0;
right = max_p;
while left < right:
mid = (left + right) // 2;
load = calculate_load(mid);
if load >= package_count:
right = mid;
else:
left = mid + 1;
return right;
def calculate_load(p):
i = 0;
j = 0;
current_truck_p = p;
while i < package_count and j < truck_count:
if packages[i] <= current_truck_p:
current_truck_p -= packages[i];
i += 1;
else:
j += 1;
current_truck_p = p;
return i;
print(allocation());
| 1 | 87,155,453,052 | null | 24 | 24 |
while True:
a, b, c = input().split()
a = int(a)
c = int(c)
if b == "+":
print(a + c)
elif b == "-":
print(a - c)
elif b == '*':
print(a * c)
elif b == '/':
print(a // c)
else:
break
|
def solver(S,T):
counter = 0
for i in range(len(S)):
Si = S[i]
Ti = T[i]
if Si != Ti:
counter += 1
return counter
S = input()
T = input()
print(solver(S,T))
| 0 | null | 5,565,491,856,480 | 47 | 116 |
S=[i for i in input()]
T=[j for j in input()]
count=0
for a,b in zip(S,T):
if a!=b:
count+=1
print(count)
|
s = input()
t = input()
cnt = 0
word = list(s)
answer = list(t)
for i in range(len(s)):
if word[i] != answer[i]:
cnt+=1
print(cnt)
| 1 | 10,497,327,630,724 | null | 116 | 116 |
n = int(input())
ans = sum(x for x in range(1, n+1) if x % 3 != 0 and x % 5 != 0)
print(ans)
|
# coding: utf-8
import codecs
import sys
sys.stdout = codecs.getwriter("shift_jis")(sys.stdout) # ??????
sys.stdin = codecs.getreader("shift_jis")(sys.stdin) # ??\???
# ??\??¬?????????print??????????????´?????? print(u'?????????') ??¨??????
# ??\??¬?????????input??? input(u'?????????') ??§OK
# ??°?¢???????????????????????????´??????6,7???????????????????????¢??????
"""
DEBUG = 0
if DEBUG == 0:
a = []
for i in range(200):
deglist=[int(x) for x in input().split(" ")]
a.append(deglist)
else:
a = [[5,7],[1,99],[1000,999]]
for i in range(len(a)):
wa = a[i][0] + a[i][1]
print len(str(wa))
"""
while True:
try:
a,b = map(int, raw_input().split())
print len(str(a+b))
except EOFError:
break
| 0 | null | 17,478,895,404,222 | 173 | 3 |
# -*- coding: utf-8 -*-
"""
stackの応用(水たまりの面積)
"""
from collections import deque
S = list(input())
# 総合面積
ans = 0
# 総合面積用スタック(直近の\の位置)
stack1 = deque()
# 個別用スタック(その水たまりを開始する\の位置, その時点での面積)
stack2 = deque()
for i in range(len(S)):
if S[i] == '\\':
stack1.append(i)
# 一番最近いれた\を取り出せば、今回の/と対になる(同じ高さ)
elif S[i] == '/' and stack1:
# 両者の距離がその高さでの面積になる
# (\/が三角形な分-1なのが半開区間だからちょうど合う)
j = stack1.pop()
ans += i - j
# 各水たまりのマージ作業
# stack2から、今回の合併候補を抽出
# (条件:水たまりの開始位置が今回対になってる\より右側にある)
pond = i - j
while stack2 and stack2[-1][0] >= j:
pond += stack2.pop()[1]
# マージした水たまりの情報を詰める
stack2.append([j, pond])
print(ans)
# リスト内包とアンパックできれいにまとまった
print(len(stack2), *[pond for j, pond in stack2])
|
line = input()
stack, edges, pools = [], [], []
for i in range(len(line)):
if line[i] == '\\':
stack.append(i)
elif line[i] == '/' and stack:
j = stack.pop()
tmp = i - j
while edges and edges[-1] > j:
edges.pop()
tmp += pools.pop()
edges.append(j)
pools.append(tmp)
print(sum(pools))
print(len(pools), *pools)
| 1 | 62,482,565,158 | null | 21 | 21 |
def main():
K, N = map(int, input().split())
A = [int(a) for a in input().split()]
maxK=0
for i in range(1,N):
maxK = max(maxK, A[i]-A[i-1])
maxK = max(maxK, K+A[0]-A[N-1])
print(K-maxK)
if __name__=='__main__':
main()
|
k,n = map(int,input().split(" "))
a = list(map(int,input().split(" ")))
m = a[0] + k - a[n-1]
for i in range(n-1):
l = a[i+1] - a[i]
if l > m:
m = l
ans = k - m
print(ans)
| 1 | 43,484,746,670,202 | null | 186 | 186 |
A,V = map(int,input().split())
B,W = map(int,input().split())
T = int(input())
print("YES" if A+T*V>= B+T*W and A-T*V <= B-T*W else "NO")
|
import sys
a, v = map(int, input().split())
b, w = map(int, input().split())
t = int(input())
if (a == b):
print('YES')
sys.exit(0)
if (v <= w):
print('NO')
sys.exit(0)
res = abs(a - b) / (v - w)
if (res > t):
print('NO')
else:
print('YES')
sys.exit(0)
| 1 | 15,122,547,680,820 | null | 131 | 131 |
k = input()
s = input()
print("Yes" if s[:-1] == k else "No")
|
S,T = [input() for _ in range(2)]
print("Yes") if S==T[:-1] else print("No")
| 1 | 21,367,255,090,368 | null | 147 | 147 |
import sys
while True:
n, x = [ int( val ) for val in sys.stdin.readline().split( " " ) ]
if 0 == n and 0 == x:
break
cnt = 0
for i in range( 1, n-1 ):
if x <= i:
break
for j in range( i+1, n ):
if x <= ( i+j ):
break
for k in range( j+1, n+1 ):
s = ( i + j + k )
if x == s:
cnt += 1
break
elif x < s:
break
print( cnt )
|
while True:
[n, x] = map(int, input().split())
if n==0 and x==0:
break
ans = 0
for a in range(1,n-1):
for b in range(a+1,n):
for c in range(b+1,n+1):
if a+b+c==x:
ans += 1
print(ans)
| 1 | 1,285,562,651,180 | null | 58 | 58 |
def main():
n = int(input())
A = list(map(int, input().split()))
B = [0] * (n+1)
if n == 0:
x = A[0]
if x == 1:
print(1)
else:
print(-1)
exit()
# Adが葉の個数、Bdが葉でないものの個数
# A0 + B0 = 1
# Bd ≤ Ad+1 + Bd+1 ≤ 2Bd --> B[d-1] - A[d] ≤ B[d] ≤ 2B[d-1] - A[d]
# Bd ≤ Ad+1 + Ad+2 + · · · + AN = s - (A1 + ... + Ad)
# now_s :葉の数
now_s = sum(A)
s = now_s
for i in range(n+1):
if i == 0:
B[i] = 1 - A[i]
else:
now_s -= A[i]
B[i] = min(now_s, 2 * B[i - 1] - A[i])
#print(A,B,now_s)
if B[i] < 0:
print(-1)
exit()
print(sum(B) + s)
if __name__ == "__main__":
main()
|
from math import ceil
n = int(input())
A = list(map(int,input().split()))[::-1]
mn,mx = A[0], A[0]
step = [[mn,mx]]
for i in range(1, n+1):
mn = ceil(mn/2) + A[i]
mx = mx + A[i]
step.append([mn,mx])
if not mn<=1 and 1<=mx:
print(-1)
else:
step = step[::-1]
A = A[::-1]
now = 1
ans = 1
for i in range(1, n+1):
now = min(step[i][1],
(now-A[i-1])*2)
ans += now
print(ans)
| 1 | 18,851,201,675,084 | null | 141 | 141 |
x, y = map(int, input().split())
answer = 0
for a in [x, y]:
if a == 3:
answer += 100000
elif a == 2:
answer += 200000
elif a == 1:
answer += 300000
else:
pass
if x == 1 and y == 1:
answer += 400000
print(answer)
|
x,y = map(int, input().split())
ans = 0
dic = {1:300000, 2:200000, 3:100000}
if x in dic:
ans = dic[x]
if y in dic:
ans += dic[y]
if x==1 and y==1:
ans += 400000
print(ans)
| 1 | 140,088,276,717,960 | null | 275 | 275 |
D = int(input())
for i in range(D):
print(i%26+1)
|
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
from collections import defaultdict
from heapq import heappop, heappush
import itertools
import random
from decimal import *
input = sys.stdin.readline
def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))
def inputStr(): return input()[:-1]
inf = float('inf')
mod = 1000000007
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
def main():
D = inputInt()
C = inputList()
S = []
for i in range(D):
s = inputList()
S.append(s)
ans = []
for i in range(D):
bestSco = 0
bestI = 1
for j,val in enumerate(S[i]):
tmpAns = ans + [j+1]
tmpSco = findScore(tmpAns, S, C)
if bestSco < tmpSco:
bestSco = tmpSco
bestI = j+1
ans.append(bestI)
for i in ans:
print(i)
def findScore(ans, S, C):
scezhu = [inf for i in range(26)]
sco = 0
for i,val in enumerate(ans):
tmp = S[i][val-1]
scezhu[val-1] = i
mins = 0
for j,vol in enumerate(C):
if scezhu[j] == inf:
mins = mins + (vol * (i+1))
else:
mins = mins + (vol * ((i+1)-(scezhu[j]+1)))
tmp -= mins
sco += tmp
return sco
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
if __name__ == "__main__":
main()
| 1 | 9,687,076,046,908 | null | 113 | 113 |
import sys
input = lambda: sys.stdin.readline().rstrip()
n=int(input())
s=0 ; st=set() ; ans=[[] for i in range(n)] ; v=0
def dfs(g,v):
global s,st,ans
if v in st: return
else: st.add(v)
s+=1
ans[v].append(s)
for i in g[v]:
dfs(g,i)
s+=1
ans[v].append(s)
g=[]
for _ in range(n):
a=[int(i)-1 for i in input().split()]
if a[1]==-1: g.append([])
else: g.append(a[2:])
for i in range(n):
if i in st : continue
else : dfs(g,i)
for i in range(len(ans)):
print(i+1,*ans[i])
|
N=int(input())
L=[[10**9]for i in range(N+1)]
for i in range(N):
l=list(map(int,input().split()))
for j in range(l[1]):
L[i+1].append(l[2+j])
#print(L)
for i in range(N+1):
L[i].sort(reverse=True)
#print(L)
ans=[]
for i in range(N+1):
ans.append([0,0])
from collections import deque
Q=deque()
cnt=1
for i in range(N):
Q.append([0,N-i])
for i in range(10**7):
if len(Q)==0:
break
q0,q1=Q.pop()
#print(q0,q1)
if q1!=10**9:
if ans[q1][0]==0:
ans[q1][0]=cnt
cnt+=1
for j in L[q1]:
Q.append([q1,j])
else:
ans[q0][1]=cnt
cnt+=1
#print(ans,Q)
for i in range(1,N+1):
print(i,ans[i][0],ans[i][1])
| 1 | 2,850,023,518 | null | 8 | 8 |
def main():
K = int(input())
S = input()
mod = pow(10, 9) + 7
N = len(S)
g1 = [1, 1]
g2 = [1, 1]
inv = [0, 1]
for i in range(2, K+N+1):
g1.append((g1[-1] * i) % mod)
inv.append( ( -inv[mod % i] * (mod//i)) % mod )
g2.append((g2[-1] * inv[-1]) % mod)
def combi(n, r):
r = min(r, n-r)
return g1[n]*g2[r]*g2[n-r]%mod
pow25 = [1]
pow26 = [1]
for i in range(K):
pow25.append(pow25[-1] * 25 % mod)
pow26.append(pow26[-1] * 26 % mod)
ans = 0
for i in range(N-1, N+K):
ans += combi(i, N-1) * pow25[i-N+1] % mod * pow26[K-i+N-1] % mod
ans %= mod
return ans
if __name__ == '__main__':
print(main())
|
a, b = map(int, input().split(" "))
print("%d %d %.5f" %(a/b, a%b, a/b))
| 0 | null | 6,717,525,907,302 | 124 | 45 |
import sys
import math
stdin = sys.stdin
def ni(): return int(ns())
def na(): return list(map(int, stdin.readline().split()))
def ns(): return stdin.readline().rstrip() # ignore trailing spaces
N = ni()
AB_array = [na() for _ in range(N)]
# print(AB_array)
plus_dic = {}
minus_dic = {}
ans = 1
fish_count = 0
mod = 10 ** 9 + 7
zero_count = 0
for ab in AB_array:
a, b = ab
if a == 0 and b == 0:
zero_count += 1
continue
fish_count += 1
if a == 0:
vec = (0, 1)
if vec in plus_dic:
plus_dic[vec] += 1
else:
plus_dic[vec] = 1
continue
elif b == 0:
vec = (1, 0)
if vec in minus_dic:
minus_dic[vec] += 1
else:
minus_dic[vec] = 1
continue
c = math.gcd(a, b)
a = a // c
b = b // c
if a < 0:
a *= -1
b *= -1
if b > 0:
vec = (a, b)
if vec in plus_dic:
plus_dic[vec] += 1
else:
plus_dic[vec] = 1
else:
vec = (a, b)
if vec in minus_dic:
minus_dic[vec] += 1
else:
minus_dic[vec] = 1
# print(plus_dic, minus_dic, fish_count)
for k, vp in plus_dic.items():
x, y = k
if (y, -x) in minus_dic:
vm = minus_dic[(y, -x)]
ans = ans * (pow(2, vp, mod) + pow(2, vm, mod) - 1) % mod
fish_count -= (vp + vm)
ans = ans * pow(2, fish_count, mod) % mod
print((ans - 1 + zero_count) % mod)
|
from collections import defaultdict
MOD = (10 ** 9) + 7
assert MOD == 1000000007
def gcd(a, b):
if a % b == 0:
return b
return gcd(b, a % b)
n = int(raw_input())
ns = []
d = defaultdict(int)
zero = 0
for i in xrange(n):
a, b = map(int, raw_input().split())
ns.append((a, b))
if a and b:
s = 1 if a * b >= 0 else -1
g = gcd(abs(a), abs(b))
m1 = (s * abs(a) / g, abs(b) / g)
m2 = (-s * abs(b) / g, abs(a) / g)
elif a == 0 and b == 0:
zero += 1
continue
elif a == 0:
m1 = (1, 0)
m2 = (0, 1)
elif b == 0:
m1 = (0, 1)
m2 = (1, 0)
d[m1] += 1
d[m2] += 0
'''
res = 0
for i in xrange(1 << n):
fs = []
flag = True
for j in xrange(n):
if i & (1 << j):
fs.append(ns[j])
for i, f1 in enumerate(fs):
for f2 in fs[i + 1:]:
(a1, b1) = f1
(a2, b2) = f2
if a1 * a2 + b1 * b2 == 0:
flag = False
break
if not flag:
break
if flag:
res += 1
print res - 1
'''
pre = 1
for k in d.keys():
if k[0] <= 0:
assert (k[1], -k[0]) in d
continue
else:
k1 = k
k2 = (-k[1], k[0])
tot = pow(2, d[k1], MOD) + pow(2, d[k2], MOD) - 1
pre = pre * tot % MOD
print (pre - 1 + zero + MOD) % MOD
| 1 | 20,979,684,366,538 | null | 146 | 146 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Allocation
????????????????????? wi(i=0,1,...n???1) ??? n ??????????????????
????????????????????¢????????????????????????????????????
????????????????????? k ??°?????????????????????????????????
???????????????????????£?¶??????? 0 ?????\??????????????????????????¨?????§???????????????
???????????????????????????????????????????????§????????? P ????¶????????????????????????????
?????§????????? P ?????????????????????????????§??±?????§??????
n???k???wi ???????????????????????§????????????????????????????????????????????????
?????§????????? P ???????°????????±???????????????°????????????????????????????????????
"""
import sys
# ??????????????\????????????
def kenzan(P, w, n, k):
# print("P:{} kosu:{} track:{}".format(P,n,k))
t = 1 # ????????????
s = 0 # ?????????
st = 0
for i in range(n):
x = s + w[i]
# print("max:{} nimotu[{}]:{} + sekisai:{} = {} track:{}".format(P,i,w[i],s,x,t))
if x > P: # ????????????
t += 1
st += s
s = w[i]
# print("next track:{} sekisai:{}".format(t,s))
if t > k: # ??°??°????????????
# print("\ttrack:{}/{} P:{} sekisai:{}".format(t,k,P,st))
return st
else:
s = x
# print("\ttrack:{}/{} P:{} sekisai:{}".format(t,k,P,st))
return 0
def main():
""" ????????? """
n,k = list(map(int,input().split()))
istr = sys.stdin.read()
wi = list(map(int,istr.splitlines()))
# ?????§?????¨???????????¨????°????????±???????
P = 0
total = 0
min = 100000
for w in wi:
if P < w:
P = w
if min > w:
min = w
total += w
na = int(total / n) # ?????????????????????
if total % n > 0:
na += 1
ka = int(total / k) # ???????????????????????????
if total % k > 0:
ka += 1
# ?????? P (??????????????§??????????????????????????????????±?????????????
# print("kosu:{} MAX:{} MIN:{} na:{} ka:{} total:{}".format(n, P, min, na, ka, total))
if P < na:
P = na
if P < ka:
P = ka
z = 0
while P <= total:
st = kenzan(P, wi, n, k)
# print("??????????????°:{} ??????????????°??°:{} ?????????????????§??????:{} ????????????????????????:{} ??????????????????:{} ??????:{}".format(n, k, P, total, st,z))
if st == 0:
a = P - z
b = P
break
z = int((total-st)/k)
if z < 1:
z = 1
P += z
while b - a > 0:
x = int((b - a) / 2)
if x < 1:
a = b
P = x + a
st = kenzan(P, wi, n, k)
# print("P:{} MAX:{} MIN:{} sekisai:{}".format(P, b, a, st))
if st == 0:
b = P
else:
a = P
print(P)
if __name__ == '__main__':
main()
|
from collections import defaultdict
roots = defaultdict(list)
for k in range(2, 10 ** 6 + 1):
ki = k * k
while ki <= 10 ** 12:
roots[ki].append(k)
ki *= k
def factors(n):
fhead = []
ftail = []
for x in range(1, int(n ** 0.5) + 1):
if n % x == 0:
fhead.append(x)
if x * x != n:
ftail.append(n // x)
return fhead + ftail[::-1]
def solve(N):
works = set()
# Answer seems to be anything of the form: N = (K ** i) * (j * K + 1)
# Try every divisor of N as K ** i
for d in factors(N):
# If i == 1, then K == d
k = d
if (N // d) % k == 1:
assert k <= N
works.add(k)
if d == 1:
# If i == 0, then K ** 0 == 1, so K = (N - 1) // j, so anything that is a factor of N - 1 works
works.update(factors(N - 1))
elif d in roots:
# For i >= 2, see if it's in the list of precomputed roots
for k in roots[d]:
if k > N:
break
if (N // d) % k == 1:
works.add(k)
works.discard(1)
return len(works)
(N,) = [int(x) for x in input().split()]
print(solve(N))
if False:
def brute(N, K):
while N >= K:
if N % K == 0:
N = N // K
else:
N = N - K
return N
for N in range(2, 10000):
count = 0
for K in range(2, N + 1):
temp = brute(N, K)
if temp == 1:
print(N, K, temp)
count += 1
print("##########", N, count, solve(N))
assert count == solve(N)
| 0 | null | 20,674,747,282,892 | 24 | 183 |
#! python3
# matrix_multiplication.py
n, m, l = [int(x) for x in input().split(' ')]
mat1 = [[int(x) for x in input().split(' ')] for i in range(n)]
mat2 = [[int(x) for x in input().split(' ')] for j in range(m)]
rst_mat = [[0 for k in range(l)] for i in range(n)]
for i in range(n):
for k in range(l):
for j in range(m):
rst_mat[i][k] += mat1[i][j] * mat2[j][k]
for i in range(n):
print(' '.join([str(x) for x in rst_mat[i]]))
|
h, w, k = map(int, input().split())
S = [list(input()) for _ in range(h)]
ans = S.copy()
index = 1
for i in range(h):
for j in range(w):
if S[i][j] == "#":
ans[i][j] = str(index)
index += 1
for i in range(h):
for j in range(w-1):
if ans[i][j] != "." and ans[i][j+1] == ".":
ans[i][j+1] = ans[i][j]
for i in range(h):
for j in range(w-1, 0, -1):
if ans[i][j] != "." and ans[i][j-1] == ".":
ans[i][j-1] = ans[i][j]
for j in range(w):
for i in range(h-1):
if ans[i][j] != "." and ans[i+1][j] == ".":
ans[i+1][j] = ans[i][j]
for j in range(w):
for i in range(h-1, 0, -1):
if ans[i][j] != "." and ans[i-1][j] == ".":
ans[i-1][j] = ans[i][j]
for l in ans:
print(" ".join(l))
| 0 | null | 72,621,925,459,772 | 60 | 277 |
#!/usr/bin/env python3
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
N = int(input())
A = list(map(int, input().split()))
count = 0
pos = 1
for i, a in enumerate(A):
if a == pos:
pos += 1
else:
count += 1
if count <= N - 1:
print(count)
else:
print(-1)
|
n = int(input())
a = list(map(int, input().split()))
r, cnt = 1, 0
for i in a:
if r == i:
r += 1
else:
cnt += 1
print(cnt) if a.count(1) else print(-1)
| 1 | 114,663,753,545,390 | null | 257 | 257 |
N=int(input())
c=input()
right_r=0
right_w=0
left_r=0
left_w=0
for i in range(N):
if c[i]=='R':
right_r+=1
else:
right_w+=1
ans=right_r
for j in range(N):
cnt=0
if c[j]=='W':
left_w+=1
right_w-=1
else:
left_r+=1
right_r-=1
if right_r<=left_w:
cnt+=right_r
cnt+=left_w-right_r
else:
cnt+=left_w
cnt+=right_r-left_w
if cnt<ans:
ans=cnt
print(ans)
|
n = int(input())
c = list(input())
r = 0
w = 0
for i in range(len(c)):
if(c[i]=="R"):
r += 1
ans = max(r,w)
for i in range(len(c)):
if(c[i]=="R"):
r -= 1
else:
w += 1
now = max(r,w)
ans = min(ans,now)
print(ans)
| 1 | 6,292,523,070,460 | null | 98 | 98 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.