Dataset Preview
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed because of a cast error
Error code: DatasetGenerationCastError Exception: DatasetGenerationCastError Message: An error occurred while generating the dataset All the data files must have the same columns, but at some point there are 1 new columns ({'bad_solution'}) and 1 missing columns ({'output'}). This happened while the json dataset builder was generating data using hf://datasets/Roxygr/code_repair-1/questions.jsonl (at revision 892f5689b9e9b0f8f20f2ba4edfbb823d48aa0c9) Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations) Traceback: Traceback (most recent call last): File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2013, in _prepare_split_single writer.write_table(table) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 585, in write_table pa_table = table_cast(pa_table, self._schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2302, in table_cast return cast_table_to_schema(table, schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2256, in cast_table_to_schema raise CastError( datasets.table.CastError: Couldn't cast id: int64 bad_solution: string to {'id': Value(dtype='int64', id=None), 'output': Value(dtype='string', id=None)} because column names don't match During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1396, in compute_config_parquet_and_info_response parquet_operations = convert_to_parquet(builder) File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1045, in convert_to_parquet builder.download_and_prepare( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1029, in download_and_prepare self._download_and_prepare( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1124, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1884, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2015, in _prepare_split_single raise DatasetGenerationCastError.from_cast_error( datasets.exceptions.DatasetGenerationCastError: An error occurred while generating the dataset All the data files must have the same columns, but at some point there are 1 new columns ({'bad_solution'}) and 1 missing columns ({'output'}). This happened while the json dataset builder was generating data using hf://datasets/Roxygr/code_repair-1/questions.jsonl (at revision 892f5689b9e9b0f8f20f2ba4edfbb823d48aa0c9) Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
id
int64 | output
string |
---|---|
1 |
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from collections import defaultdict
def main():
n, *a = map(int, read().split())
maxa = max(a) + 1 # aはint配列
d = [i for i in range(maxa)]
for p0 in range(2, maxa):
if p0 == d[p0]:
for p1 in range(p0 ** 2, maxa, p0):
if d[p1] % p0 == 0:
d[p1] = p0
def factorization(f): # f > maxaだとエラー
l = []
t = f
while True:
if t == d[t]:
l.append(d[t])
break
else:
l.append(d[t])
t = t // d[t]
return l
if all([i == 1 for i in a]):
print('pairwise coprime')
d1 = defaultdict(int)
for ae in a:
t1 = set(factorization(ae))
for t1e in t1:
d1[t1e] += 1
d1v = tuple(d1.values())
if all([i == 1 for i in d1v]):
print('pairwise coprime')
elif max(d1v) == n:
print('not coprime')
else:
print('setwise coprime')
if __name__ == '__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
2 |
from bisect import bisect_right
import math
N,D,A = map(int,input().split())
X = sorted([list(map(int,input().split())) for _ in range(N)],key=lambda x:x[0])
X.insert(0,[-1,-1])
def update(m,i,j,a): #ノード値の更新 i<=x<j
l,r = T[m][0]
if r<=i or l>=j:
return
if i<=l and r<=j:
T[m][1] -= a*(r-l)
else:
update(2*m,i,j,a)
update(2*m+1,i,j,a)
def find(m,i): #node[i]の評価
l,r = T[m][0]
if l==i and r==i+1:
return T[m][1]
if l<=i and r>=i+1:
T[2*m][1] += T[m][1]//2
T[2*m+1][1] += T[m][1]//2
T[m][1] = 0
l1,r1 = T[2*m][0]
if l1<=i and r1>=i+1:
return find(2*m,i)
else:
return find(2*m+1,i)
k = 0
n = N
while 2**k<N:
k += 1
N = 2**k #一番下の層のノード数
T = [[] for _ in range(2*N)] #木の初期化 意図は1-origin
for i in range(N,2*N):
T[i] = [[i-(N-1),i-(N-1)+1],X[i-(N-1)][1] if i-(N-1)<n+1 else 0] #区間の右端は含まない
m = N//2
while m>0:
for i in range(m,2*m):
T[i] = [[T[2*i][0][0],T[2*i+1][0][1]],0] #各ノードは区間とノードの値を持つ.
m = m//2 #ルートはT[1]
Pos = [X[i][0] for i in range(n+1)]
cur = 1
cnt = 0
while cur<n+1:
x = X[cur][0]+D
k = math.ceil(X[cur][1]/A)
indr = bisect_right(Pos,x+D)
cnt += k
update(1,cur,indr,k*A)
flag = 0
for i in range(cur,n+1):
X[i][1] = find(1,i)
if X[i][1]>0:
cur = i
flag = 1
break
if flag==0:break
print(cnt)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
3 |
def _main(N, M, K, A, B):
sum_k = 0.0
a_index = 0
A_len = len(A)
b_index = 0
B_len = len(B)
while sum_k < K:
current_a = A[a_index] if a_index < A_len else None
current_b = B[b_index] if b_index < B_len else None
if current_a is None and current_b is None:
break
has_a = current_b is None and current_a is not None
has_b = current_b is not None and current_a is None
if has_a:
if K < sum_k + current_a:
break
sum_k += current_a
a_index += 1
elif has_b:
if K < sum_k + current_b:
break
sum_k += current_b
b_index += 1
elif current_a < current_b:
if K < sum_k + current_a:
break
sum_k += current_a
a_index += 1
else:
if K < sum_k + current_b:
break
sum_k += current_b
b_index += 1
print(a_index + b_index)
if __name__ == "__main__":
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
_main(N, M, K, A, B)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
4 |
def calc(n, N, x):
m, M = -1, -1
L, R = 0, 10**18
while L+1 < R:
P = (L+R)//2
if n <= x*P:
R = P
else:
L = P
if n <= x*R <= N:
m = x*R
L, R = 0, 10**18
while L+1 < R:
P = (L+R)//2
if N < x*P:
R = P
else:
L = P
if n <= x*L <= N:
M = x*L + (x-1)
return m, M
def main():
k = int(input())
a = list(map(int, input().split()))
f = True
m, M = 2, 2
for i in reversed(range(k)):
m, M = calc(m, M, a[i])
if m == -1 or M == -1:
f = False
break
if f:
print(m, M)
else:
print(-1)
if __name__ == "__main__":
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
5 |
import sys
def chk(i,j):
tmp=[p[i][k] for k in range(M)]
tmp[j]=p[i][j]+1
for k in range(M-1,-1,-1):
if tmp[k] > p[i+x[j]][k] :
p[i+x[j]]=[tmp[k] for k in range(M)]
return
N,M=map(int,input().split())
x=[0,2,5,5,4,5,6,3,7,6]
a=list(map(int,input().split()))
a.sort()
b=[]
for i in range(M):
for j in range(M):
if x[a[j]]==x[a[i]]: tmp=j
b.append(a[tmp])
a=list(set(b))
a.sort()
M=len(a)
x=[ x[a[i]] for i in range(M) ]
p=[[-100 for j in range(M)] for i in range(N+10)]
p[0]=[0 for j in range(M)]
for i in range(N+1):
if sum(p[i])>-1:
for j in range(M-1,-1,-1):
if sum(p[i])+1>sum(p[i+x[j]]):
p[i+x[j]] = [ p[i][k] for k in range(M) ]
p[i+x[j]][j]=p[i][j]+1
elif sum(p[i])+1==sum(p[i+x[j]]):
chk(i,j)
for i in range(M-1,-1,-1):
for j in range(p[N][i]):
print(a[i],end="")
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
6 |
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, defaultdict
# 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 # cumsum
# from bisect import bisect_left, bisect_right
from math import gcd
def solve():
N = II()
A = LI()
mx = 1000003
D = [1] * mx
for i in range(2, mx):
if D[i] != 1:
continue
for j in range(i, mx, i):
if D[j] == 1:
D[j] = i
# print(D)
# print(D[4], D[6], D[35])
g = A[0]
# dct = defaultdict(int)
# flag = True
C = [0] * mx
for a in A:
g = gcd(g, a)
# print(a, D[a])
# if D[a] != 1:
# if dct[D[a]] > 0:
# flag = False
# dct[D[a]] += 1
d = D[a]
C[d] += 1
# print(dct, flag, g)
# flag = False
if all(C[i] <= 1 for i in range(2, len(C))):
flag = True
else:
flag = False
if g == 1:
if flag:
print('pairwise coprime')
else:
print('setwise coprime')
else:
print('not coprime')
if __name__ == '__main__':
solve()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
7 |
from typing import List
def FUNC(numbers: List[float], threshold: float) -> bool:
""" Check if in given list of numbers, are any two numbers closer to each other than
given threshold.
>>> FUNC([1.0, 2.0, 3.0], 0.5)
False
>>> FUNC([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)
True
"""
for idx, elem in enumerate(numbers):
for idx2, elem2 in enumerate(numbers):
if idx != idx2:
distance = elem - elem2
if distance < threshold:
return True
return False
|
8 |
def main():
import sys
H, W = map(int, sys.stdin.readline().split())
A = [list(map(int, sys.stdin.readline().split())) for i in range(H)]
B = [list(map(int, sys.stdin.readline().split())) for i in range(H)]
X = [[None] * W for i in range(H)]
for h in range(H):
for w in range(W):
X[h][w] = abs(A[h][w] - B[h][w])
dp = {}
dp[0] = set()
dp[0].add(X[0][0])
dp[0].add(-X[0][0])
for h in range(H):
for w in range(W):
if h == 0 and w == 0:
continue
x = X[h][w]
s = set()
if W * h + w > W - 1:
for d in dp[W * (h - 1) + w]:
if d + x <= ((H - h) + (W - w)) * 79:
s.add(d + x)
if d - x >= -((H - h) + (W - w)) * 79:
s.add(d - x)
if (W * h + w) % W != 0:
for d in dp[W * h + w - 1]:
if d + x <= ((H - h) + (W - w)) * 79:
s.add(d + x)
if d - x >= -((H - h) + (W - w)) * 79:
s.add(d - x)
dp[W * h + w] = s
ans = min([abs(s) for s in dp[W * H - 1]])
print(ans)
if __name__ == '__main__':
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
9 |
import sys
from bisect import bisect_left
sys.setrecursionlimit(10**7)
def lmi(): return list(map(int, input().split()))
h, w = lmi()
s = [input() for i in range(h)]
a = [[] for i in range(h)]
al = [[] for i in range(h)]
b = [[] for i in range(w)]
bl = [[] for i in range(w)]
for i in range(h):
k = 0
for j in range(w):
if s[i][j] == '.':
k += 1
if j == w-1:
a[i].append(k)
al[i].append(j)
else:
if j != 0:
a[i].append(k)
al[i].append(j-1)
k = 0
for i in range(w):
k = 0
for j in range(h):
if s[j][i] == '.':
k += 1
if j == h-1:
b[i].append(k)
bl[i].append(j)
else:
if j != 0:
b[i].append(k)
bl[i].append(j-1)
k = 0
'''
print(a)
print(al)
print(b)
print(bl)
'''
ans = 0
for i in range(h):
for j in range(w):
if s[i][j] == '.':
c = a[i][bisect_left(al[i], j)]
d = b[j][bisect_left(bl[j], i)]
#print(c,d)
ans = max(ans, c+d-1)
print(ans)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
10 |
def main():
H, W = map(int, input().split()) # 横に2個
state = [[0 if a == '.' else 1 for a in list(input())] for _ in range(H)]
checked = [[False for _ in range(W+1)] for _ in range(H+1)]
qs = []
for h in range(H):
for w in range(W):
if state[h][w] == 1:
qs.append([h, w])
checked[h][w] = True
for h in range(H+1):
checked[h][W] = True
for w in range(W+1):
checked[H][w] = True
c = 0
while qs:
qqs = []
for h,w in qs:
checked[h][w] = True
if 0 < h and not checked[h-1][w]:
qqs.append([h-1, w])
if h < H-1 and not checked[h+1][w]:
qqs.append([h+1, w])
if 0 < w and not checked[h][w-1]:
qqs.append([h, w-1])
if w < W-1 and not checked[h][w+1]:
qqs.append([h, w+1])
if not qqs:
break
c += 1
qs = qqs
print(c)
if __name__=='__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
11 |
import sys
import numpy as np
from numba import njit
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
INF = 10**9 + 1
N, M = map(int, readline().split())
data = np.array(read().split(), np.int64)
A = data[::3]
B = data[1::3]
C = data[2::3]
D = A[N:]
E = B[N:]
F = C[N:]
A = A[:N]
B = B[:N]
C = C[:N]
X = np.unique(np.concatenate([A, B, D, [0, -INF, INF]]))
Y = np.unique(np.concatenate([C, E, F, [0, -INF, INF]]))
DX = X[1:] - X[:-1]
DY = Y[1:] - Y[:-1]
A = np.searchsorted(X, A)
B = np.searchsorted(X, B)
C = np.searchsorted(X, C)
D = np.searchsorted(X, D)
E = np.searchsorted(X, E)
F = np.searchsorted(X, F)
H, W = len(X), len(Y)
N = H * W
@njit
def set_ng(A, B, C, D, E, F):
p = 0
ng = np.zeros((N, 4), np.bool_)
for i in range(len(A)):
a, b, c = A[i], B[i], C[i]
for x in range(a, b):
v = x * W + c
ng[v][1] = 1
ng[v - 1][0] = 1
for i in range(len(D)):
d, e, f = D[i], E[i], F[i]
for y in range(e, f):
v = d * W + y
ng[v][3] = 1
ng[v - W][2] = 1
return ng
ng = set_ng(A, B, C, D, E, F)
x0, y0 = np.searchsorted(X, 0), np.searchsorted(Y, 0)
v0 = x0 * W + y0
@njit
def solve():
visited = np.zeros(N, np.bool_)
visited[v0] = 1
stack = np.empty(N, np.int32)
p = 0
ret = 0
def area(x):
x, y = divmod(x, W)
return DX[x] * DY[y]
def push(x):
nonlocal p, ret
stack[p] = x
visited[x] = 1
ret += area(x)
p += 1
def pop():
nonlocal p
p -= 1
return stack[p]
push(v0)
move = [1, -1, W, -W]
while p:
v = pop()
for i in range(4):
if ng[v][i]:
continue
w = v + move[i]
if visited[w]:
continue
x, y = divmod(w, W)
if x == 0 or x == H - 1 or y == 0 or y == W - 1:
return 0
push(w)
return ret
x = solve()
if x == 0:
print('INF')
else:
print(x)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
12 |
#!/usr/bin/env python3
# vim: set fileencoding=utf-8
# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation
"""Module docstring
"""
import functools
import heapq
import itertools
import logging
import math
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
from typing import Dict, List, Optional, Set, Tuple
def solve(values: List[int], nb: int) -> int:
seen = {}
cur = 0
move = 0
while move < nb and cur not in seen:
seen[cur] = move
move += 1
cur = values[cur] - 1
if move == nb:
return cur
cycle_length = move - seen[cur]
_nb_cycles, rest = divmod(nb - move, cycle_length)
LOG.debug((cur, cycle_length, move, seen))
for _ in range(rest):
cur = values[cur] - 1
return cur + 1
def do_job():
"Do the work"
LOG.debug("Start working")
N, K = map(int, input().split())
values = list(map(int, input().split()))
assert len(values) == N
result = solve(values, K)
print(result)
def print_output(testcase: int, result) -> None:
"Formats and print result"
if result is None:
result = "IMPOSSIBLE"
print("Case #{}: {}".format(testcase + 1, result))
# 6 digits float precision {:.6f} (6 is the default value)
# print("Case #{}: {:f}".format(testcase + 1, result))
def configure_log() -> None:
"Configure the log output"
log_formatter = logging.Formatter("%(lineno)d - " "%(message)s")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(log_formatter)
LOG.addHandler(handler)
LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
LOG = logging.getLogger("template")
configure_log()
def main(argv=None):
"Program wrapper."
if argv is None:
argv = sys.argv[1:]
parser = ArgumentParser()
parser.add_argument(
"-v",
"--verbose",
dest="verbose",
action="store_true",
default=False,
help="run as verbose mode",
)
args = parser.parse_args(argv)
if args.verbose:
LOG.setLevel(logging.DEBUG)
do_job()
return 0
if __name__ == "__main__":
import doctest
doctest.testmod()
sys.exit(main())
class memoized:
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
value = self.func(*args)
self.cache[args] = value
return value
except TypeError:
# uncachable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
def __repr__(self):
"""Return the function's docstring."""
return self.func.__doc__
def __get__(self, obj, objtype):
"""Support instance methods."""
return functools.partial(self.__call__, obj)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
13 |
def submit():
n = int(input())
alist = list(map(int, input().split()))
blist = list(map(int, input().split()))
# 順番にグリーディ
a = alist.copy()
b = blist.copy()
score_a = 0
for i in range(0, n):
if a[i] < b[i]:
score_a += a[i]
b[i] -= a[i]
a[i] = 0
else:
score_a += b[i]
a[i] -= b[i]
b[i] = 0
if a[i + 1] < b[i]:
score_a += a[i + 1]
b[i] -= a[i + 1]
a[i + 1] = 0
else:
score_a += b[i]
a[i + 1] -= b[i]
b[i] = 0
# 逆順にグリーディ
a = alist.copy()
a.reverse()
b = alist.copy()
b.reverse()
score_b = 0
for i in range(0, n):
if a[i] < b[i]:
score_b += a[i]
b[i] -= a[i]
a[i] = 0
else:
score_b += b[i]
a[i] -= b[i]
b[i] = 0
if a[i + 1] < b[i]:
score_b += a[i + 1]
b[i] -= a[i + 1]
a[i + 1] = 0
else:
score_b += b[i]
a[i + 1] -= b[i]
b[i] = 0
print(max(score_a, score_b))
if __name__ == '__main__':
submit()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
14 |
""" B
https://atcoder.jp/contests/abc175/tasks/abc175_b
"""
import sys
import math
from functools import reduce
from bisect import bisect_left
def readString():
return sys.stdin.readline()
def readInteger():
return int(readString())
def readStringSet(n):
return sys.stdin.readline().split(" ")[:n]
def readIntegerSet(n):
return list(map(int, readStringSet(n)))
def readIntegerMatrix(n, m):
return [readIntegerSet(m) for _ in range(0, n)]
def main(T, S):
best = sys.maxsize
for i in range(len(T)-len(S)):
s = T[i:i+len(S)]
count = 0
for j in range(len(S)):
if s[j] != S[j]:
count += 1
if best > count:
best = count
return best
if __name__ == "__main__":
_T = readString().rstrip()
_S = readString().rstrip()
print(main(_T, _S))
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
15 |
from collections import deque,defaultdict
import bisect
N = int(input())
S = [input() for i in range(N)]
def bend(s):
res = 0
k = 0
for th in s:
if th == '(':
k += 1
else:
k -= 1
res = min(k,res)
return res
species = [(bend(s),s.count('(')-s.count(')')) for s in S]
ups = [(b,u) for b,u in species if u > 0]
flats = [(b,u) for b,u in species if u == 0]
downs = [(b,u) for b,u in species if u < 0]
ups.sort()
downs.sort()
high = 0
for b,u in ups[::-1]:
if high + b < 0:
print('No')
exit()
high += u
for b,u in flats:
if high + b < 0:
print('No')
exit()
for b,u in downs[::-1]:
if high + b < 0:
print('No')
exit()
high += u
if high == 0:
print('Yes')
else:
print('No')
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
16 |
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
import copy
def input():
return sys.stdin.readline()[:-1]
def ruiseki(lst):
return [0]+list(accumulate(lst))
mod=pow(10,9)+7
n=int(input())
s=input()
q=int(input())
query=[list(input().split()) for i in range(q)]
lst={}
for i in range(n):
if not s[i] in lst:
lst[s[i]]=[i]
else:
lst[s[i]].append(i)
erase={}
insert={}
# print(lst)
al=[chr(ord('a') + i) for i in range(26)]
for i in range(q):
if query[i][0]=="1":
one,i2,c=query[i]
if not s[i] in erase:
erase[s[i]]=[int(i2)]
else:
erase[s[i]].append(int(i2))
if not c in insert:
insert[c]=[int(i2)]
else:
insert[c].append(int(i2))
else:
two,l,r=query[i]
ans=0
l=int(l)
r=int(r)
for i in range(26):
tmp=0
if al[i] in lst:
tmp+=bisect.bisect_right(lst[al[i]],r-1)-bisect.bisect_left(lst[al[i]],l-1)
if al[i] in erase:
tmp-=bisect.bisect_right(erase[al[i]],r-1)-bisect.bisect_left(erase[al[i]],l-1)
if al[i] in insert:
tmp+=bisect.bisect_right(insert[al[i]],r-1)-bisect.bisect_left(insert[al[i]],l-1)
if tmp>0:
ans+=1
print(ans)
# print(erase)
# print(insert)
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
17 |
n,a,b=map(int,input().split())
mod=10**9+7
J=pow(2,n)%mod
def find_power(n,mod):
# 0!からn!までのびっくりを出してくれる関数(ただし、modで割った値に対してである)
powlist=[0]*(n+1)
powlist[0]=1
powlist[1]=1
for i in range(2,n+1):
powlist[i]=powlist[i-1]*i%(mod)
return powlist
def find_inv_power(n):
#0!からn!までの逆元を素数10**9+7で割ったあまりリストを作る関数
powlist=find_power(n,10**9+7)
check=powlist[-1]
first=1
uselist=[0]*(n+1)
secondlist=[0]*30
secondlist[0]=check
secondlist[1]=check**2
for i in range(28):
secondlist[i+2]=(secondlist[i+1]**2)%(10**9+7)
a=format(10**9+5,"b")
for j in range(30):
if a[29-j]=="1":
first=(first*secondlist[j])%(10**9+7)
uselist[n]=first
for i in range(n,0,-1):
uselist[i-1]=(uselist[i]*i)%(10**9+7)
return uselist
C=find_inv_power(2*10**5+100)
if True:
c=1
for i in range(a):
c*=(n-i)
c=c%mod
c=c*C[a]
c=c%mod
d=1
for i in range(b):
d*=(n-i)
d=d%mod
d=d%mod
d=d*C[b]
print((J-c-d)%mod)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
18 |
import sys
import math
from collections import defaultdict, deque, Counter
from copy import deepcopy
from bisect import bisect, bisect_right, bisect_left
from heapq import heapify, heappop, heappush
input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return tuple(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]
def main():
N = I()
mylist = LI()
max_num = max(mylist)
max_num2 = round(math.sqrt(max_num))
D = [True]* (max_num+1)
mylist = set(mylist)
setwise = True
pairwise = True
for i in range(2, max_num2+1):
temp = 0
if D[i]:
for j in range(i, max_num+1, i):
D[j] = False
if j in mylist:
temp+=1
if temp == N:
print("not coprime")
sys.exit()
if temp >= 2:
pairwise = False
if pairwise:
print("pairwise coprime")
else:
print("setwise coprime")
if __name__ == "__main__":
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
19 |
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
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
sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(input())
def read_int_n():
return list(map(int, input().split()))
def read_float():
return float(input())
def read_float_n():
return list(map(float, input().split()))
def read_str():
return input().strip()
def read_str_n():
return list(map(str, input().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
def dc(n, m):
return -(-n // m)
@mt
def slv(H, N, AB):
dp = [INF] * (H+1)
dp[0] = 0
for a, b in AB:
for h, bb in enumerate(dp):
if bb == INF:
continue
n = min(H, h+a)
dp[n] = min(dp[n], bb+b)
return dp[-1]
def main():
H, N = read_int_n()
AB = [read_int_n() for _ in range(N)]
print(slv(H, N, AB))
# H = 10**4
# N = 10
# AB = [[random.randint(1, 100), random.randint(1, 100)] for _ in range(N)]
# print(slv(H, N, AB))
if __name__ == '__main__':
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
20 |
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
a, b = MAP()
# x = a * 0.92
# y = b / 0.90
# print(x, y)
x1 = a / 0.08
y1 = b /0.1
x2 = (a+1) / 0.08
y2 = (b+1) /0.1
if ceil(y1) <= int(x1) < y2:
ans = int(x1)
print(ans)
elif ceil(x1) <= int(y1) < x2:
ans = int(y1)
print(ans)
else:
print(-1)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
21 |
# /usr/bin/python3
# -*- coding: utf-8 -*-
from queue import Queue
from queue import LifoQueue as Stack
from math import sqrt
from fractions import gcd
from itertools import permutations
def lcm(a, b):
return (a*b) // gcd(a,b)
def intinput():
return int(input())
def mulinputs():
return map(int,input().split())
def lineinputs(func=intinput):
datas = []
while True:
try:
datas.append(func())
except EOFError:
break
return datas
N = intinput()
# S = input()
# A, B, C, D, E, F = mulinputs()
datas = list(mulinputs())
# datas = lineinputs(input)
M = 1001000
cnt = 0
l = len(datas)
for i in range(0,N):
is_clear = True
for j in range(0,(i+1)>>1):
dp0 = datas[2*j] if 2*j < l else M
dp1 = datas[2*j+1] if 2*j < l else M
if dp0 < datas[i]:
is_clear = False
break
if dp1 < datas[i]:
is_clear = False
break
if is_clear:
cnt += 1
# 出力
print(cnt)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
22 |
import sys
input = sys.stdin.readline
import math
INF = 1e+11
A,B,Q=map(int, input().split())
s = [[0] for _ in range(A+2)]
t = [[0] for _ in range(B+2)]
s[0]=-INF
t[0]=-INF
for i in range(A):
s[i+1]=int(input())
for i in range(B):
t[i+1]=int(input())
s[A+1]=INF
t[B+1]=INF
x = [int(input()) for _ in range(Q)]
def BySearch(a,x):
right = len(a)-1
left = 0
while right - left > 1:
tmp = (right+left)//2
if a[tmp] <= x:
left = tmp
else:
right = tmp
if abs(a[right]-x) < abs(a[left]-x): return right
else: return left
for i in range(Q):
ans = INF
for j in range(2):
if j == 0:
a = s
b = t
else:
a = t
b = s
ax = a[BySearch(a,x[i])]
bx = b[BySearch(b,ax)]
ans = min(abs(ax-x[i])+abs(bx-ax),ans)
print(ans)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
23 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
class Node(object):
def __init__(self):
self.edges = set()
self.distance = 1
def main():
N = int(input())
nodes = [Node() for _ in range(N)]
if N == 0:
print('Second', flush=True)
return
elif N == 1:
print('First', flush=True)
return
for _ in range(N - 1):
a, b = map(int, input().split())
nodes[a - 1].edges.add(nodes[b - 1])
nodes[b - 1].edges.add(nodes[a - 1])
leaves = collections.deque(n for n in nodes if len(n.edges) == 1)
while True:
leaf = leaves.pop()
parent = leaf.edges.pop()
if len(parent.edges) == 1:
size = leaf.distance + parent.distance
break
parent.distance = max(parent.distance, leaf.distance + 1)
parent.edges.remove(leaf)
if len(parent.edges) == 1:
leaves.append(parent)
if size % 3 == 2:
print('Second', flush=True)
else:
print('First', flush=True)
if __name__ == '__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
24 |
from collections import Counter
def find_key_from_value(input_dict, target_value):
return [key for key, value in input_dict.items() if value == target_value][0]
N = int(input())
V= list(map(int,input().split()))
eve, odd = Counter([V[i] for i in range(0,N,2)]), Counter([V[i] for i in range(1,N,2)])
eve_key = find_key_from_value(eve, max(eve.values()))
odd_key = find_key_from_value(odd, max(odd.values()))
if eve_key == odd_key: print(eve[eve_key])
else: print(N-eve[eve_key]-odd[odd_key])
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
25 |
def rev(a):
L = []
for i in range(N):
L.append(a % 3)
a //= 3
return int("".join(map(str, L)), 3)
def salsa():
lazy[0] *= -1
def rumba():
i = 0
for k in range(N):
if lazy[i] < 0:
lazy[3*i+1] *= -1
lazy[3*i+2] *= -1
lazy[3*i+3] *= -1
lazy[i] = 1
value[3*i+1] ^= 3
value[3*i+2] ^= 3
value[3*i+3] ^= 3
value[3*i+1] += 1
value[3*i+2] += 1
value[3*i+3] += 1
value[3*i+1] %= 3
value[3*i+2] %= 3
value[3*i+3] %= 3
i = 3 * i + (1 if value[3*i+1] == 0 else 2 if value[3*i+2] == 0 else 3)
def calcall():
a = 1
i = 0
for k in range(1, N + 1):
for _ in range(3 ** k):
i += 1
if lazy[(i-1)//3] < 0:
lazy[i] *= -1
if value[i]: value[i] ^= 3
value[i] = value[i] * a + value[(i-1) // 3]
a *= 3
N = int(input())
NN = 3 ** (N + 1) // 2
value = [(i-1) % 3 if i else 0 for i in range(NN)]
lazy = [1 for i in range(NN)]
for t in input():
if t == "R":
rumba()
else:
salsa()
calcall()
ANS = [0] * (3 ** N)
for i in range(3 ** N):
ANS[rev(i)] = value[i + (NN - 1) // 3]
print(*ANS)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
26 |
from typing import List
def FUNC(paren_string: str) -> List[str]:
""" Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
separate those group into separate strings and return the list of those.
Separate groups are balanced (each open brace is properly closed) and not nested within each other
Ignore any spaces in the input string.
>>> FUNC('( ) (( )) (( )( ))')
['()', '(())', '(()())']
"""
result = []
current_string = []
current_depth = 0
for c in paren_string:
if c == '(':
current_depth += 1
current_string.append(c)
elif c == ')':
current_depth -= 1
current_string.append(c)
if current_depth < 0:
result.append(''.join(current_string))
current_string.clear()
return result
|
27 |
from collections import defaultdict
def solve():
n = int(input())
v = list(map(int, input().split()))
evens = v[::2]
odds = v[1::2]
d_even, d_odd = defaultdict(int), defaultdict(int)
for e in evens:
d_even[e] += 1
for o in odds:
d_odd[o] += 1
# if top_e != top_o:
# (e1, o1)
# else:
# (e1, o2) or (e2, o1)
d_even = sorted(d_even.items(), key=lambda x: x[1])
d_odd = sorted(d_odd.items(), key=lambda x: x[1])
if d_even[0][0] != d_odd[0][0]:
return n - (d_even[0][1] + d_odd[0][1])
else:
if len(d_even) == len(d_odd) == 1:
return n // 2
if len(d_odd) > 1 and len(d_even) > 1:
cand1 = d_even[0][1] + d_odd[1][1]
cand2 = d_even[1][1] + d_odd[0][1]
c = max(cand1, cand2)
elif len(d_odd) > 1:
c = d_even[0][1] + d_odd[1][1]
elif len(d_even) > 1:
c = d_even[1][1] + d_odd[0][1]
else:
return n // 2
return n - c
if __name__ == "__main__":
print(solve())
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
28 |
def FUNC(number: float) -> float:
""" Given a positive floating point number, it can be decomposed into
and integer part (largest integer smaller than given number) and decimals
(leftover part always smaller than 1).
Return the decimal part of the number.
>>> FUNC(3.5)
0.5
"""
return number % 1.0 + 1.0
|
29 |
import heapq
class pqheap:
def __init__(self):
self.p = list()
self.q = list()
def insert(self,x):
heapq.heappush(self.p, x)
return
def erase(self,x):
heapq.heappush(self.q, x)
return
def minimum(self):
while self.q and self.p[0] == self.q[0]:
heapq.heappop(self.p)
heapq.heappop(self.q)
return self.p[0]
#print(a)
def main(a,b):
for i in range(n):
if b[i]<=a[i]:
pass
else:
print(-1)
exit()
pq=pqheap()
[pq.insert([-x,i]) for i,x in enumerate(a)]
ans=0
while len(pq.p)>len(pq.q):
m=pq.minimum()
pq.erase(m)
v,i=m
v=-v
vv=v
v-=b[i]
tmp=a[(i-1)%n]+a[(i+1)%n]
ans+=v//tmp
v%=tmp
v+=b[i]
a[i]=v
if v==b[i]:continue
elif vv<=v or v<b[i]:
print(-1)
exit()
pq.insert([-v,i])
print(ans)
if __name__=='__main__':
n=int(input())
b=list(map(int,input().split()))
a=list(map(int,input().split()))
main(a,b)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
30 |
import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def II(): return int(sys.stdin.readline())
def LS(): return list(map(list, sys.stdin.readline().split()))
def S(): return sys.stdin.readline()[:-1]
def main():
n = II()
s = S()
inf = n + 2
m = [[0 for i in range(n)] for i in range(n)]
first = [[inf for i in range(n)] for i in range(n)]
# set 1st index value
lcs = 0
for i, c in enumerate(s):
# print(c, s[0])
if c == s[0]:
m[i][0] = 1
first[i][0] = i
if i != 0:
lcs = 1
for i in range(1, n):
for j in range(1, n):
if i <= j:
continue
if s[i] == s[j]:
if first[i-1][j-1] > j:
m[i][j] = m[i-1][j-1] + 1
lcs = max(m[i][j], lcs)
if first[i-1][j-1] == inf:
first[i][j] = i
else:
first[i][j] = first[i-1][j-1]
else:
m[i][j] = 0
# print(m)
print(lcs)
if __name__ == '__main__':
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
31 |
from typing import List
def FUNC(operations: List[int]) -> bool:
""" You're given a list of deposit and withdrawal operations on a bank account that starts with
zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
at that point function should return True. Otherwise it should return False.
>>> FUNC([1, 2, 3])
False
>>> FUNC([1, 2, -4, 5])
True
"""
balance = 0
for op in operations:
balance += op
if balance == 0:
return True
return False
|
32 |
# coding: utf-8
import sys
from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import combinations, product
#import bisect# lower_bound etc
#import numpy as np
#import queue# queue,get(), queue.put()
def run():
N = int(input())
current = 0
ways = []
dic = {'(': 1, ')': -1}
for _ in range(N):
S = input()
go = 0
max_depth = 0
for s in S:
go += dic[s]
max_depth = min(max_depth, go)
ways.append((go, max_depth))
ways = sorted(ways, key=lambda x:x[0], reverse=True)
while ways:
done = False
for idx, (go, max_depth) in enumerate(ways):
if current + max_depth >= 0:
if go < 0:
break
current += go
del ways[idx]
done = True
if not done:
break
ways = [(-a, b) for a, b in ways]
ways = sorted(ways, key = itemgetter(1,0))
while ways and current >= 0:
done = False
for idx, (go, max_depth) in enumerate(ways):
if go <= 0:
print('No')
return None
if current + max_depth >= 0:
current -= go
del ways[idx]
done = True
if not done:
print('No')
return None
if current == 0:
print('Yes')
else:
print('No')
if __name__ == "__main__":
run()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
33 |
from typing import List
def FUNC(numbers: List[float]) -> float:
""" For a given list of input numbers, calculate Mean Absolute Deviation
around the mean of this dataset.
Mean Absolute Deviation is the average absolute difference between each
element and a centerpoint (mean in this case):
MAD = average | x - x_mean |
>>> FUNC([1.0, 2.0, 3.0, 4.0])
1.0
"""
mean = sum(numbers) / len(numbers)
return sum(abs(x - mean) for x in numbers) / mean
|
34 |
#!/usr/bin/env python3
from collections import defaultdict
from heapq import heappush, heappop
import sys
import bisect
sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
# INF = sys.maxsize
INF = 10 ** 10
# INF = float("inf")
def dp(*x): # debugprint
print(*x)
f = open(sys.argv[1])
input = f.buffer.readline
N, M = map(int, input().split())
vlines = defaultdict(list)
hlines = defaultdict(list)
vticks = {0}
hticks = {0}
for i in range(N):
A, B, C = map(int, input().split())
vlines[C].append((A, B))
hticks.add(C)
vticks.update((A, B))
for i in range(M):
D, E, F = map(int, input().split())
hlines[D].append((E, F))
vticks.add(D)
hticks.update((E, F))
vticks = [-INF] + list(sorted(vticks)) + [INF]
hticks = [-INF] + list(sorted(hticks)) + [INF]
def up(y):
return vticks[bisect.bisect_left(vticks, y) - 1]
def down(y):
return vticks[bisect.bisect_left(vticks, y) + 1]
def left(x):
return hticks[bisect.bisect_left(hticks, x) - 1]
def right(x):
return hticks[bisect.bisect_left(hticks, x) + 1]
def area(x, y):
i = bisect.bisect_left(hticks, x)
width = hticks[i + 1] - hticks[i]
j = bisect.bisect_left(vticks, y)
height = vticks[j + 1] - vticks[j]
return width * height
total_area = 0
visited = set()
def visit(x, y):
global total_area
if (x, y) in visited:
return
# dp("visited: x,y", x, y)
a = area(x, y)
total_area += a
visited.add((x, y))
# visit neighbors
l = left(x)
if (l, y) not in visited:
for a, b in vlines[x]:
if a <= y < b:
# blocked
break
else:
# can move left
to_visit.append((l, y))
u = up(y)
if (x, u) not in visited:
for a, b in hlines[y]:
if a <= x < b:
# blocked
break
else:
# can move up
to_visit.append((x, u))
r = right(x)
if (r, y) not in visited:
for a, b in vlines[r]:
if a <= y < b:
# blocked
break
else:
# can move left
to_visit.append((r, y))
d = down(y)
if (x, d) not in visited:
for a, b in hlines[d]:
if a <= x < b:
# blocked
break
else:
# can move up
to_visit.append((x, d))
# for y in [up(0), 0]:
# for x in [left(0), 0]:
# visit(x, y)
# print(total_area)
to_visit = [(0, 0)]
while to_visit:
x, y = to_visit.pop()
if x == INF or x == -INF or y == INF or y == -INF:
print("INF")
break
visit(x, y)
else:
print(total_area)
def _test():
import doctest
doctest.testmod()
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
35 |
# E
N=int(input())
A=list(map(int,input().split()))
def gcd(a,b):
if a>b:
a,b=b,a
while a%b:
a,b=b,(a%b)
return b
def fast_factorization_init(N):
res=list(range(N))
for i in range(2,N):
if i*i>N:
break
for j in range(i*i,N,i):
if res[j]==j:
res[j]=i
if res[i]<i:
continue
return res
min_factors=fast_factorization_init(10**6+10)
def fast_factorization(n):
res=[]
while n>1:
res.append(min_factors[n])
n//=min_factors[n]
return res
res2=1
P=[]
for i in range(N):
if i!=0:
res1=gcd(A[i],res1)
else:
res1=A[0]
fact=fast_factorization(A[i])
if res2!=0:
for p in P:
if A[i]%p==0:
res2=0
break
for p in fact:
P.append(p)
if res2==1:
print('pairwise coprime')
elif res1==1:
print('setwise coprime')
else:
print('not coprime')
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
36 |
from heapq import heappush, heappop
from collections import defaultdict
N, K = map(int, input().split())
TD = [list(map(int, input().split())) for _ in range(N)]
DT = [[d, t] for t, d in TD]
DT.sort(reverse = True)
#print(DT)
h_in = []
cnt = defaultdict(int)
tmp = []
kiso = 0
for d, t in DT:
if cnt[t] == 0:
heappush(h_in, [d, t])
kiso += d
else:
tmp.append([d, t])
cnt[t] += 1
tmp = tmp[::-1]
len_h_in = len(h_in)
if len_h_in < K:
d = K - len_h_in
for i in range(d):
heappush(h_in, tmp[i])
kiso += tmp[i][0]
kind = 0
for k, v in list(cnt.items()):
if v:
kind += 1
#print(kiso, kind)
#print(h_in)
#print(tmp)
answer = kiso + kind ** 2
tmp = tmp[::-1]
while tmp:
out_d, out_t = tmp.pop()
in_d, in_t = heappop(h_in)
kiso += out_d - in_d
cnt[in_t] -= 1
if cnt[in_t] == 0: kind -= 1
cnt[out_t] += 1
if cnt[out_t] == 1: kind += 1
heappush(h_in, [out_d, out_t])
answer = max(answer, kiso + kind ** 2)
print(answer)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
37 |
n, k = [0] * 2
a = []
def format_input(filename = None):
global n, k
global a
if filename == None:
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
elif filename == '__random__':
from random import randint as rng
n = rng(2, 2 * 10**5)
k = rng(1, 10**18)
a = [rng(1, n) for i in range(n)]
print(n, k)
print(' '.join(list(map(str, a))))
def get_answer():
loop = [1]
start = -1
while start == -1:
node = a[loop[-1]-1]
if loop.count(node) > 0:
start = loop.index(node)
else:
loop.append(node)
l = len(loop)
if k >= l:
answer = loop[(k - l) % (l - start) + start]
else:
answer = loop[k]
return answer
if __name__ == '__main__':
format_input()
ans = get_answer()
print(ans)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
38 |
#####segfunc#####
def segfunc(x, y):
if x[0]>y[0]:
return y
elif x[0]<y[0]:
return x
elif x[1]>y[1]:
return y
else:
return x
#################
#####ide_ele#####
ide_ele = (float("inf"),-1)
#################
class SegTree:
"""
init(init_val, ide_ele): 配列init_valで初期化 O(N)
update(k, x): k番目の値をxに更新 O(logN)
query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
"""
def __init__(self, init_val, segfunc, ide_ele):
"""
init_val: 配列の初期値
segfunc: 区間にしたい操作
ide_ele: 単位元
n: 要素数
num: n以上の最小の2のべき乗
tree: セグメント木(1-index)
"""
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
# 配列の値を葉にセット
for i in range(n):
self.tree[self.num + i] = init_val[i]
# 構築していく
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
"""
k番目の値をxに更新
k: index(0-index)
x: update value
"""
k += self.num
self.tree[k][0] += x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
"""
[l, r)のsegfuncしたものを得る
l: index(0-index)
r: index(0-index)
"""
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
import sys
input=sys.stdin.readline
N,M=map(int,input().split())
s=input()
A=[[0,i] for i in range(N)]
B=[[0,i] for i in range(N)]
edge=[[] for i in range(N)]
for i in range(M):
a,b=map(int,input().split())
a-=1;b-=1
edge[a].append(b)
edge[b].append(a)
if s[a]=="A":
A[b][0]+=1
else:
B[b][0]+=1
if s[b]=="A":
A[a][0]+=1
else:
B[a][0]+=1
Acheck=SegTree(A,segfunc,ide_ele)
Bcheck=SegTree(B,segfunc,ide_ele)
ban=set([])
while True:
a,index=Acheck.query(0,N)
b,index2=Bcheck.query(0,N)
if a==0:
ban.add(index)
Acheck.update(index,float("inf"))
Bcheck.update(index,float("inf"))
for v in edge[index]:
if s[index]=="A":
Acheck.update(v,-1)
else:
Bcheck.update(v,-1)
elif b==0:
ban.add(index2)
Acheck.update(index2,float("inf"))
Bcheck.update(index2,float("inf"))
for v in edge[index2]:
if s[index2]=="A":
Acheck.update(v,-1)
else:
Bcheck.update(v,-1)
else:
break
check=set([i for i in range(N)])
if ban==check:
print("No")
else:
print("Yes")
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
39 |
#!/usr/bin/env python3
import sys
def factoring(n: int):
factors = []
p = 1
while p * p <= n:
if n % p == 0:
factors.append(p)
if n != p * p:
factors.append(n // p)
p += 1
return factors
def solve(N: int, M: int):
if N == 1:
print(M)
return
F = factoring(M)
F.sort()
print(F)
for f in F:
if f >= N:
print(M // f)
break
return
# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)
def main():
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
solve(N, M)
if __name__ == '__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
40 |
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
def input():
return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
ns = []
while len(ns) < rantime:
n = random.randint(ran1, ran2)
if not n in ns:
ns.append(n)
return sorted(ns)
def rand_query(ran1, ran2, rantime):
r_query = []
while len(r_query) < rantime:
n_q = rand_ints_nodup(ran1, ran2, 2)
if not n_q in r_query:
r_query.append(n_q)
return sorted(r_query)
from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
from heapq import heapify, heappop, heappush
from math import sqrt
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right
import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7
#############
# Main Code #
#############
H, W = getNM()
Ch, Cw = getNM()
Dh, Dw = getNM()
maze = [input() for i in range(H)]
Ch -= 1
Cw -= 1
Dh -= 1
Dw -= 1
# ワープを最低で何回使うか
# 上下左右2つ向こうまでの範囲内でワープできる
# 隣接する'.'が領域
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
pos = deque([[Ch, Cw]])
dp = [[-1] * W for i in range(H)]
dp[Ch][Cw] = 0
while len(pos) > 0:
y, x = pos.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
# 歩いて移動
if 0 <= nx < W and 0 <= ny < H and maze[ny][nx] == "." and (dp[ny][nx] == -1 or dp[y][x] < dp[ny][nx]):
# 0-1 bfs
# 先頭に置く
pos.appendleft([ny, nx])
dp[ny][nx] = dp[y][x]
# ワープ
for i in range(-2, 3):
for j in range(-2, 3):
wy = y + i
wx = x + j
# 歩いて移動不可能でないと使わない
if 0 <= wx < W and 0 <= wy < H and maze[wy][wx] == "." and dp[wy][wx] == -1:
pos.append([wy, wx])
dp[wy][wx] = dp[y][x] + 1
print(dp[Dh][Dw])
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
41 |
class SegmentTree:
def __init__(self,siz,v = 0):
self.n = 1
self.v = v
while self.n < siz: self.n *= 2
self.node = [self.v]*(2*self.n-1)
def merge(self,x,y): return x | y
def update(self,i,x):
i += self.n-1
self.node[i] = x
while i > 0:
i = (i-1)//2
self.node[i] = self.merge(self.node[i*2+1],self.node[i*2+2])
def query(self,a,b):
vl = vr = self.v
a += self.n-1
b += self.n-1
while a < b:
if a & 1 == 0: vl = self.merge(vl,self.node[a])
if b & 1 == 0: vr = self.merge(vr,self.node[b-1])
a //= 2
b = (b-1)//2
return self.merge(vl,vr)
n = int(input())
st = SegmentTree(n)
s = list(input())
def f(c): return 1<<(ord(c) - ord("a"))
for i in range(n): st.update(i,f(s[i]))
q = int(input())
for _ in range(q):
typ,x,y = input().split()
if typ == "1":
i,c = int(x)-1,y
if s[i] == c: continue
st.update(i,f(c))
s[i] = c
else:
l,r = int(x)-1,int(y)
print(bin(st.query(l,r)).count("1"))
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
42 |
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7
DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
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 main():
x, y = LI()
if x > y:
if x >= 0:
ans = 1 + abs(x+y)
else:
ans = 1 + (-y) - (-x) + 1
else:
ans = y - x
print(ans)
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
43 |
import sys
input=sys.stdin.readline
import collections
def main():
N = int(input())
Q = [collections.deque(map(int, input().split())) for _ in range(N)]
games = N*(N-1)//2
days = 0
while True:
gamed = [0 for _ in range(N)]
b = False
for i in range(len(Q)):
if gamed[i] > 0 or len(Q[i]) == 0:
continue
j = Q[i][0] - 1
if gamed[j] > 0 or len(Q[j]) == 0:
continue
if Q[j][0] == i+1:
# print("game:", j+1, i+1, days)
Q[i].popleft()
Q[j].popleft()
gamed[i] = 1
gamed[j] = 1
games -= 1
b = True
continue
days += 1
if not b:
print(-1)
return
if games == 0:
break
print(days)
if __name__ == '__main__':
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
44 |
from math import factorial as fact
import math
import sys
import itertools
import numpy as np
from collections import Counter
import datetime
#入力:N(int:整数)
def input1():
return int(input())
#入力:N,M(int:整数)
def input2():
return map(int,input().split())
#入力:[n1,n2,...nk](int:整数配列)
def input_array():
return list(map(int,input().split()))
def keta(N):
return len(str(N))
def input_daytime(input_time):
time,distance=input_time.split()
t=time.split(":")
se=str(t[-1]).split(".")
dt1 = datetime.timedelta(hours=int(t[0]),minutes=int(t[1]),seconds=int(se[0]),milliseconds=int(se[1]))
return dt1
def combinations(n,r):
return list(itertools.combinations(range(n),r))
def all_sets(num_list):
subsets=[]
for i in range(2,len(num_list) + 1):
for c in combinations(num_list, i):
subsets.append(c)
return subsets
#公約数の列挙
def ch(x1):
cf=[]
for i in range(2,math.sqrt(x1)+1):
if x1 % i==0:
cf.append(i)
return cf
def CountOneRoots(x,y):
#x:縦,y:横
return fact(x+y)/fact(x)/fact(y)
# 素因数分解
def factorization(n):
tmp=n
count=0
for i in range(2,int(n**0.5)+2):
if tmp%i==0:
cnt=0
while tmp%i==0:
cnt+=1
tmp//=i
count+=1
if tmp!=1:
count+=1
return count
def fl(a,b,x):
return math.floor(a*x/b)-a*math.floor(x/b)
# n,m,q = input2()
# abcd=[]
# A=[0]*n
# for i in range(q):
# abcd.append(input_array())
a,b,n=input2()
if b>n:
b_ans=fl(a,b,n)
else:
b_ans=fl(a,b,b-1)
for i in range(0,n,b):
ans=fl(a,b,i)
# print(i)
if ans> b_ans:
b_ans=ans
if i<n:
ans=fl(a,b,n)
if ans> b_ans:
b_ans=ans
print(b_ans)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
45 |
from typing import List
def FUNC(numbers: List[int], delimeter: int) -> List[int]:
""" Insert a number 'delimeter' between every two consecutive elements of input list `numbers'
>>> FUNC([], 4)
[]
>>> FUNC([1, 2, 3], 4)
[1, 4, 2, 4, 3]
"""
if not numbers:
return []
result = []
for n in numbers[:-1]:
result.append(n)
result.append(delimeter)
return result
|
46 |
import math
def main():
N,D,A = map(int, input().split())
X,H = [0]*N,[0]*N
tmp = [(0,0) for _ in range(N)]
for i in range(N):
tmp[i] = list(map(int, input().split()))
tmp[i][0] -= 1
# 座標順になるようにソートしておく
tmp = sorted(tmp, key=lambda x:x[0])
for i,l in enumerate(tmp): (X[i],H[i]) = l
# 座標X[i]のモンスターはceil(H[i]/A)回攻撃すれば倒せる
# N=5, D=2
# 0 1 2 3 4 5 6 7 8 9 10
# 0 5 0 2 0 0 3 3 0 0 4 (倒すのに必要な回数; 全部0にすれば終了)
# 0 0 0 0 0 0 3 3 0 0 4 (座標3で5回爆破したあと)
# 0 0 0 0 0 0 0 0 0 0 1 (座標8で3回爆破したあと)
# 0 0 0 0 0 0 0 0 0 0 0 (座標10で1回爆破したあと)
# ->よって5+3+1=9回が最小回数..?
ans = 0
for i in range(N):
if sum(H)<=0: break
if H[i]>0:
# X[i]+Dで爆破を行う
bomb = math.ceil(H[i]/A)
ans += bomb
for j,p in enumerate(X[i:]):
if p<X[i]+2*D+1:
H[i+j] = max(0,H[i+j]-A*bomb)
else:
break
print(ans)
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
47 |
from typing import List
def FUNC(paren_string: str) -> List[int]:
""" Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
For each of the group, output the deepest level of nesting of parentheses.
E.g. (()()) has maximum two levels of nesting while ((())) has three.
>>> FUNC('(()()) ((())) () ((())()())')
[2, 3, 1, 3]
"""
def FUNC(s):
depth = 0
max_depth = 0
for c in s:
if c == '(':
depth += 1
max_depth = max(depth, max_depth)
else:
max_depth -= 1
return max_depth
return [FUNC(x) for x in paren_string.split(' ') if x]
|
48 |
N, M = map(int, input().split())
A = list(map(int, input().split()))
def dfs(choices, s, cost, i):
if i == len(choices):
return -1
if cost == 0:
return int(s)
if cost < 0:
return -1
tmp1 = dfs(
choices,
s + str(choices[i][0]),
cost - choices[i][1],
i
)
if i+1 == len(choices):
tmp2 = -1
else:
tmp2 = dfs(
choices,
s,
cost,
i + 1
)
ret = max(tmp1, tmp2)
return ret
match = [-100,2,5,5,4,5,6,3,7,6]
choices = []
for i in A:
choices.append([i, match[i]])
choices.sort(reverse=True)
ans = dfs(choices, '', N, 0)
print(ans)
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
49 |
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == "\n":
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
def solve():
n,m,v,p = LI()
a = LI()
a.sort()
l = -1
r = n-1
print(a)
while l+1 < r:
i = (l+r) >> 1
A = a[i]+m
ri = bisect.bisect_right(a,A)
j = n-ri
if j >= p:
l = i
continue
li = bisect.bisect_right(a,a[i])
res = v-j-li
if res <= 0:
r = i
continue
res -= (p-j-1)
s = 0
for j in range(li,ri-(p-j-1)):
s += A-a[j]
if s >= res*m:
r = i
else:
l = i
print(n-r)
return
#Solve
if __name__ == "__main__":
solve()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
50 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(pow(10, 6))
from collections import defaultdict
def main():
n, m = map(int, input().split())
a = []
for _ in range(n):
a.append(list(map(int, input().split())))
sports = [1 for _ in range(m)]
ans = 10**18
for _ in range(m-1):
sdic = defaultdict(lambda: 0)
for _al in a:
for _a in _al:
if sports[_a-1] == 1:
sdic[_a] += 1
break
tmp = list(sorted(sdic.items(), key=lambda x: x[1]))[-1]
ans = min(ans, tmp[1])
sports[tmp[0]-1] = 0
print(ans)
if __name__ == '__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
51 |
import sys
readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readints():return list(map(int,readline().split()))
h,w = readints()
start = readints()
start = (start[0]-1)*w + start[1]-1
goal = readints()
goal = (goal[0]-1)*w + goal[1]-1
maze = [readstr() for i in range(h)]
dist = [10**10]*(h*w)
a = [[]for i in range(2)]
i = 0
a[i].append(start)
dist[start] = 0
while a[0] or a[1]:
p = a[i].pop()
y = p//w
x = p%w
for dy in range(-2,3):
for dx in range(-2,3):
if 0<=y+dy<h and 0<=x+dx<w and maze[y+dy][x+dx]=='.':
q = (y+dy)*w + x+dx
if dist[q]<=dist[p]:
continue
if abs(dy)+abs(dx)==1:
a[i].append(q)
dist[q] = dist[p]
else:
a[i-1].append(q)
dist[q] = dist[p] + 1
if not a[i]:
i = [1,0][i]
print(-1 if dist[goal]==10**10 else dist[goal])
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
52 |
from bisect import bisect_left
def main():
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(1, n):
a[i] += a[i - 1]
for i in range(1, m):
b[i] += b[i - 1]
answer = 0
if a[-1] + b[-1] <= k:
print(n + m)
else:
for i in range(n):
l = bisect_left(b, k - a[i])
if l == m or (l == 0 and b[l] + a[i] != k):
continue
diff = 1 if b[l] + a[i] == k else 0
answer = max(answer, i + 1 + l + diff)
print(answer)
if __name__ == '__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
53 |
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
def input():
return sys.stdin.readline().rstrip()
def main():
N=int(input())
d={}
c=0
edge1=[[] for _ in range(N*(N-1)//2)]
edge2=[[] for _ in range(N*(N-1)//2)]
for i in range(N):
l=list(map(lambda x: int(x)-1,input().split()))
prev=-1
for x in l:
a=min(i,x)*10**3+max(i,x)
if a in d:
z=d[a]
if prev!=-1:
edge1[prev].append(z)
edge2[z].append(prev)
prev=z
else:
d[a]=c
if prev!=-1:
edge1[prev].append(c)
edge2[c].append(prev)
c+=1
prev=d[a]
que=deque()
days=[-1]*(N*(N-1)//2)
for i,l in enumerate(edge2):
if not l:
que.append(i)
days[i]=1
while que:
v=que.popleft()
for x in edge1[v]:
if days[x]==-1:
que.append(x)
days[x]=max(days[x],days[v]+1)
print(max(days))
if __name__ == '__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
54 |
import sys,random
from math import gcd
input=sys.stdin.readline
n=int(input())
*a,=map(int, input().split())
random.shuffle(a)
tmp=a[0]
for i in range(1,n):
tmp=gcd(tmp,a[i])
if tmp>1:
print('not coprime')
exit()
# pairwize coprime なら素因数が2度現れることはない
def f(x):
res=set()
for i in range(2,int(x**(1/2))+3):
if x%i==0:
while x%i==0:
x//=i
res.add(i)
if x>1:
res.add(x)
return res,x
tmp=set()
tmp2=set()
for ai in a:
for p in tmp:
if ai%p==0:
print('setwise coprime')
exit()
pp,x=f(ai)
tmp|=pp
if x>1 and x in tmp2:
print('setwise coprime')
exit()
tmp.add(x)
print('pairwise coprime')
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
55 |
from itertools import accumulate,chain
import sys
sys.setrecursionlimit(10000000)
MOD = 10**9+7
# mを法とするときのa^n
def modpow(a,n,m):
res = 1
t = a
while n:
if n%2:
res = (res*t)%m
t = (t*t)%m
n //= 2
return res
# factorio = tuple(chain((1,),accumulate(range(1,N+1), func=lambda x,y: (x*y)%MOD)))
def solve(N,adj,edges):
factorio = [1]*(N+1)
t = 1
for i in range(1,N+1):
t *= i
t %= MOD
factorio[i] = t
patterns = dict()
childrens = dict()
def rec(a,b):
if (a,b) not in patterns:
prod = 1 # product of patterns
d = 1 # denominator of multinomial coefficient
n = 0 # total childrens
for c in adj[b]:
if a == c:
continue
rec(b,c)
prod *= patterns[(b,c)]
prod %= MOD
d *= factorio[childrens[(b,c)]]
d %= MOD
n += childrens[(b,c)]
patterns[(a,b)] = (prod*factorio[n]*modpow(d,MOD-2, MOD))%MOD
childrens[(a,b)] = n+1
for a,b in edges:
rec(a,b)
rec(b,a)
for k in range(N):
rec(-1,k)
print(patterns[(-1,k)])
if __name__ == '__main__':
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
m = map(int, read().split())
edges = tuple((a-1,b-1) for a,b in zip(m, m))
adj = [list() for _ in range(N)]
for a,b in edges:
adj[a].append(b)
adj[b].append(a)
solve(N,adj,edges)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
56 |
def main():
from bisect import bisect_right
N, M = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
def calc(x):
tmp = 0
for a in A:
tmp += N - bisect_right(A, x - a - 0.5)
return tmp
l = 0
r = 3 * 10 ** 5
while r - l > 1:
mid = (l + r) // 2
if calc(mid) >= M:
l = mid
else:
r = mid
B = [0] * (N + 1)
for i in range(N):
B[i + 1] = B[i] + A[i]
ans = 0
for a in A:
tmp = bisect_right(A, r - a - 0.5)
M -= (N - tmp)
ans += a * (N - tmp) + (B[-1] - B[tmp])
ans += M * l
print (ans)
if __name__ == '__main__':
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
57 |
from fractions import gcd
# from datetime import date, timedelta
from heapq import*
import math
from collections import defaultdict, Counter, deque
from bisect import *
import itertools
import fractions
import sys
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
# input = sys.stdin.readline
def main():
n, a, b, c, d = map(int, input().split())
s = list(input())
if c < d:
for i in range(b, d):
if s[i] == "#" and s[i + 1] == "#":
print("No")
exit()
for i in range(a, c):
if s[i] == "#" and s[i + 1] == "#":
print("No")
exit()
print("Yes")
else:
f=True
for i in range(b, d):
if s[i-1] == "." and s[i] == "." and s[i+1] == ".":
f = False
break
if f:
print("No")
exit()
for i in range(a, c):
if s[i] == "#" and s[i + 1] == "#":
print("No")
exit()
print("Yes")
if __name__ == '__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
58 |
from typing import List
def FUNC(strings: List[str], substring: str) -> List[str]:
""" Filter an input list of strings only for ones that contain given substring
>>> FUNC([], 'a')
[]
>>> FUNC(['abc', 'bacd', 'cde', 'array'], 'a')
['abc', 'bacd', 'array']
"""
return [x for x in strings if x in substring]
|
59 |
def main():
_range = range
h, w = map(int, input().split())
s = [input() + '#' for _ in _range(h)]
s.append('#' * (w + 1))
t = [[-1] * w for _ in _range(h + 1)]
tstart = [-1] * (w + 1)
for i in _range(h + 1):
ystart = -1
si = s[i]
ti = t[i]
for j in _range(w + 1):
if si[j] == '#':
if ystart != -1:
for k in _range(ystart, j):
ti[k] += j - ystart
ystart = -1
if tstart[j] != -1:
for k in _range(tstart[j], i):
t[k][j] += i - tstart[j]
tstart[j] = -1
else:
if ystart == -1:
ystart = j
if tstart[j] == -1:
tstart[j] = i
print(max(map(max, t)))
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
60 |
n = int(input())
s = list(map(str, input().strip()))
seed = 13331
mod = 10 ** 9 + 7
lsd = [1] * 6000
hs = [1] * 6000
hs[0] = ord(s[0]) - ord('a')
for i in range(1, n):
lsd[i] = lsd[i - 1] * seed % mod
hs[i] = (hs[i - 1] * seed + ord(s[i]) - ord('a')) % mod
def check(x):
from collections import defaultdict
g = defaultdict(int)
for i in range(n - x + 1):
if i:
t = (hs[i + x - 1] - hs[i - 1] * lsd[x]) % mod
else:
t = hs[i + x - 1]
# print(i,t)
if not g[t]:
g[t] = i+1
elif g[t] + x - 1 <= i:
return True
return False
l = 0
r = n
while l < r - 1:
m = (l + r) // 2
if check(m):
l = m
else:
r = m - 1
if check(r):
print(r)
else:
print(l)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
61 |
def kakaka():
a = list(map(int, input().split()))
b = map(int, input().split())
c = int(input())
def start_process():
return
def main():
all_num, inst_num = map(int, input().split())
data = list(input())
data_la = []
ans_0, ans_1 = 0, 0
for i in range(all_num):
if data[i] == '1':
ans_1 += 1
if ans_0 > 0:
data_la.append(ans_0)
ans_0 = 0
else:
ans_0 += 1
if ans_1 > 0:
data_la.append(ans_1)
ans_1 = 0
if ans_1 > 0:
data_la.append(ans_1)
elif ans_0 > 0:
data_la.append(ans_0)
ans = 0
ans_data = 0
count_0 = 0
if data[0] == '0':
flg = 0
flg_hajime = 0
else:
flg= 1
flg_hajime = 1
# print(data_la)
if len(data_la) <= 2:
print(sum(data_la))
else:
pre_data1, pre_data2 = data_la[0], data_la[1]
pre_data1_ind, pre_data2_ind = 0, 1
for i in range(len(data_la)):
if i % 2 == flg:
count_0 += 1
if count_0 == inst_num + 1:
if flg_hajime:
ans = ans - pre_data1 - pre_data2
pre_data1_ind += 2
pre_data2_ind += 2
if pre_data1_ind >= len(data_la):
pre_data1 = 0
else:
pre_data1 = data_la[pre_data1_ind]
if pre_data2_ind >= len(data_la):
pre_data2 = 0
else:
pre_data2 = data_la[pre_data1_ind]
else:
ans = ans - pre_data1
pre_data1_ind += 1
pre_data2_ind += 1
if pre_data1_ind >= len(data_la):
pre_data1 = 0
else:
pre_data1 = data_la[pre_data1_ind]
if pre_data2_ind >= len(data_la):
pre_data2 = 0
else:
pre_data2 = data_la[pre_data2_ind]
flg_hajime = 1
count_0 -= 1
ans += data_la[i]
# print(ans)
if ans_data < ans:
ans_data = ans
print(ans_data)
if __name__ == '__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
62 |
from pprint import pprint
import queue
def solve(n, a, b):
state = queue.Queue()
state.put((0, b[:]))
while not state.empty():
count, b_tmp = state.get()
# print("next:" + str(count))
# pprint(b_tmp)
for i, b_i in enumerate(b_tmp):
i_a = (i - 1 + n) % n
i_c = (i + 1) % n
b_cand = b_i - b_tmp[i_a] - b_tmp[i_c]
if b_cand >= a[i]:
b_next = b_tmp[:]
b_next[i] = b_cand
if b_next == a:
return count + 1
# print(count + 1)
state.put((count + 1, b_next))
return -1
if __name__ == '__main__':
n = int(input().strip())
a = list(map(int, input().strip().split(" ")))
b = list(map(int, input().strip().split(" ")))
print(solve(n, a, b))
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
63 |
import sys
input = sys.stdin.readline
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def sieve_optimized(limit):
# Preprocessing step takes O(N log log N) time complexity.
n = limit
# Filimitd all primes upto n (including n)
sievebound = (n-1)//2
sieve = [-1]*(sievebound + 1)
# sieve[0] = True
crosslimit = (int(sievebound**0.5) - 1)
for i in range(1, crosslimit + 1):
if sieve[i] == -1:
for j in range(2*i*(i+1), sievebound + 1, 2*i+1):
sieve[j] = 2*i + 1
return sieve
def factorization(n, sieve):
# Factorisaton query takes O(log N) time after preprocessing.
divs = [1]
while n!=1:
if n&1:
div = sieve[(n-1)//2]
if div == -1:
divs.append(n)
break
else:
n //= div
divs.append(div)
else:
n >>= 1
divs.append(2)
return divs
maxnum = 10**6 + 10
sieve = sieve_optimized(maxnum)
n = int(input())
nums = list(map(int, input().split()))
seen = dict()
for i in nums:
factors = factorization(i, sieve)
if len(factors) <= 1: continue
for f in set(factors[1:]):
if f in seen:
seen[f] += 1
else:
seen[f] = 1
maxval = max(seen.values())
if maxval == n:
print('not coprime')
elif 1 < maxval < n:
print('setwise coprime')
else:
print('pairwise coprime')
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
64 |
import sys
from collections import deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())
def main():
N = in_n()
s = in_s()
red = deque()
white = deque()
for i in range(N):
if s[i] == 'R':
red.append(i)
else:
white.append(i)
if len(red) == 0:
print(1)
exit()
if len(white) == 0:
print(0)
exit()
cnt = 0
while True:
if len(red) == 0 or len(white) == 0:
break
if white[0] > red[-1]:
break
white.popleft()
red.pop()
cnt += 1
print(cnt)
if __name__ == '__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
65 |
def solve(n, m, work_list):
# 1-origin
dp = [[0] * (m + 1) for i in range(n + 1)]
# time O(N log(N))
work_list.sort()
# time O(NM)
for key, value in enumerate(work_list, 1):
work_day, work_value = value[0], value[1]
prev_key = key - 1
for day in range(1, m + 1):
prev_day = day - 1
dp[key][day] = dp[prev_key][day]
if day >= work_day:
dp[key][day] = max(dp[key][day], dp[prev_key][prev_day] + work_value)
return dp[n][m]
def main():
n, m = map(int, input().split())
work_list = []
# time O(N)
for i in range(n):
work = list(map(int, input().split()))
if work[0] > m:
continue
work_list.append(work)
ans = solve(n, m, work_list)
print(ans)
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
66 |
def main():
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
N = int(input())
A = [int(x) for x in input().strip().split()]
maxA = max(A)
prime = [i % 2 != 0 for i in range(maxA+1)]
prime[2] = True
f = [False] * (maxA+1)
for i in range(3, int(maxA**.5)+1):
if prime[i] == False:
continue
p = i * 2
while p <= maxA:
prime[p] = False
p += i
def gcd(x, y):
if y == 0:
return x
return gcd(y, x % y)
pairwise_coprime = A[0]
setwise_coprime = A[0]
for An in A[1:]:
setwise_coprime = gcd(setwise_coprime, An)
if setwise_coprime == 1:
break
for An in A:
if An == 1:
continue
# print('An = {}'.format(An))
if f[An]:
break
elif prime[An]:
f[An] = True
else:
for i in range(2, An // 2 + 1):
if prime[An]:
if f[An]:
if setwise_coprime == 1:
print('setwise coprime')
return
else:
print('not coprime')
return
else:
f[An] = True
break
if f[An]:
if setwise_coprime == 1:
print('setwise coprime')
return
else:
print('not coprime')
return
elif An % i == 0:
# print('i={}'.format(i))
if f[i]:
if setwise_coprime == 1:
print('setwise coprime')
return
else:
print('not coprime')
return
f[i] = True
while An % i == 0:
An //= i
if An == 1:
break
# print(f)
print('pairwise coprime')
if __name__ == '__main__':
main()
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
67 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
#from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
#from math import floor, ceil
#from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
#inf = 10**17
#mod = 10**9 + 7
n,k=MI()
s=input()
print(s)
l=0
r=0
if s[0]=="L":
l=1
if s[-1]=="R":
r=1
state=""
count=0
for i in range(n):
u=s[i:i+1]
#print(state)
#print(u)
if state=="":
if u=="R":
state="R"
elif state=="R":
if u=="L":
state=""
count+=1
else:
state="R"
#print(count)
#print(l+r)
unhappy=2*count+l+r
if l+r==0:
if k>=count:
unhappy=1
elif k==count-1:
unhappy=2
else:
unhappy-=2*(k-1)
elif l+r==1:
if k>=count:
unhappy=1
else:
unhappy-=2*k
elif l+r==2:
if k>=count+1:
unhappy=1
elif k==count:
unhappy=2
else:
unhappy-=2*k
#print(unhappy)
print(n-unhappy)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
68 |
from typing import List, Tuple
def FUNC(numbers: List[int]) -> Tuple[int, int]:
""" For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.
Empty sum should be equal to 0 and empty product should be equal to 1.
>>> FUNC([])
(0, 1)
>>> FUNC([1, 2, 3, 4])
(10, 24)
"""
sum_value = 0
prod_value = 0
for n in numbers:
sum_value += n
prod_value *= n
return sum_value, prod_value
|
69 |
class RollingHash:
def __init__(self, s):
b1, b2 = 1007, 2009
self.mod1, self.mod2 = 10**9+7, 10**9+9
self.size = len(s)
self.string = s
self.hash1 = self.make_hashtable(b1, mod1)
self.hash2 = self.make_hashtable(b2, mod2)
self.pow1 = self.make_powtable(b1, mod1)
self.pow2 = self.make_powtable(b2, mod2)
def make_hashtable(self, B, MOD):
hashtable = [0] * (self.size+1)
for i in range(1, self.size+1):
hashtable[i] = (hashtable[i-1] * B + ord(self.string[i-1]))%MOD
return hashtable
def make_powtable(self, B, MOD):
power = [0] * (self.size+1)
power[0] = 1
for i in range(1, self.size+1):
power[i] = (B * power[i-1])%MOD
return power
def get_hash(self, l, length):
r = length+l-1
l -= 1
h1 = (self.hash1[r]-self.hash1[l]*self.pow1[r-l])%self.mod1
h2 = (self.hash2[r]-self.hash2[l]*self.pow2[r-l])%self.mod2
return (h1, h2)
from collections import defaultdict
def solve1():
N = int(input())
S = input()
size = len(S)
hash_table = RollingHash(S)
ans = 0
for i in range(1, N+1):
for j in range(i+1, N+1):
if S[i-1]!=S[j-1]:continue
left = 1
right = min(j-i, size-j+1)+1
while right-left>1:
m = (left+right)//2
if hash_table.get_hash(i, m)==hash_table.get_hash(j, m):
left = m
else:
right = m
ans = max(ans, left)
print(ans)
def solve2():
N = int(input())
S = input()
size = len(S)
hash_table = RollingHash(S)
def check(m):
d = defaultdict(lambda :10**20)
for i in range(1, size-m+2):
h = hash_table.get_hash(i, m)
d[h] = min(d[h], i)
if (i-d[h])>=m:
return True
return False
left, right = 0, size//2 + 1
while right-left>1:
m = (right+left)//2
if check(m):
left = m
else:
right = m
print(left)
if __name__ == "__main__":
# solve1()
solve2()
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
70 |
def get_cache(chars, start, end, cache=dict()):
pair = (start, end)
block = cache.get(pair)
if block is not None:
return block
else:
block = chars[start:end]
cache[pair] = block
return block
def get_skip(chars, previous_start, previous_end, cache=dict()):
pair = (previous_start, previous_end)
if pair in cache:
return cache[pair]
skip = len(chars)
previous_len = previous_end - previous_start
if previous_end + previous_len < len(chars):
previous = get_cache(chars, previous_start, previous_end)
suspicious_end = previous_end + previous_len
suspicious = get_cache(chars, previous_end, previous_end + previous_len)
if previous == suspicious:
skip = suspicious_end
cache[pair] = skip
return skip
def count_k(chars):
cache = dict()
stack = []
previous_start = 0
previous_end = 0
max_k = 1
current = 1
while True:
skip = get_skip(chars, previous_start, previous_end)
while current < len(chars):
if current == skip:
current += 1
continue
pair = (previous_end, current)
if pair in cache:
k = cache[pair]
if max_k < k:
max_k = k
else:
current = len(chars)
else:
stack.append((previous_start, previous_end, current, max_k))
previous_start = previous_end
previous_end = current
current = current + 1
max_k = 1
break
current += 1
else:
if previous_end + 1 != len(chars):
max_k += 1
cache[(previous_start, previous_end)] = max_k
if len(stack) == 0:
break
_previous_start, _previous_end, _current, _max_k = stack.pop()
assert _current == previous_end
assert _previous_end == previous_start
if _max_k < max_k:
_max_k = max_k
previous_start = _previous_start
previous_end = _previous_end
current = _current
max_k = _max_k
return max_k
s = input()
print(count_k(list(s)))
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
71 |
N,K = list(map(int,input().split()))
sys.setrecursionlimit(10**10)
A = input()
A = list(A)
A = list(map(int,A))
def serch_right(x,K,t):
global count0,count1
if x<0 or len(A)<=x:
return count1
if A[x]==0:
if t == 0:
t=0
count1 +=1
elif t==1 :
if count0==K:
return count1
t=0
count1 +=1
count0 +=1
else:
t=1
count1+=1
count1 = serch_right(x+1,K,t)
return count1
def serch_left(x,A):
global count2
if x<0 or len(A)<=x or A[x]==0:
return count2
if A[x]==1:
count2 +=1
count2 = serch_left(x-1,A)
return count2
count =0
count0 =0
count1 =0
for i in range(len(A)):
if A[i]==0 and (A[i-1]!=0 or i == 0):
count2 = 0
count1 =0
count0 =0
t = 1
count1 = serch_right(i,K,t)
count2 = serch_left(i-1,A)
count1 = count1 + count2
count = max(count1,count)
print(max(count,1))
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
72 |
from typing import List, Tuple
def FUNC(numbers: List[int]) -> List[int]:
""" From a given list of integers, generate a list of rolling maximum element found until given moment
in the sequence.
>>> FUNC([1, 2, 3, 2, 3, 4, 2])
[1, 2, 3, 3, 3, 4, 4]
"""
running_max = None
result = []
for n in numbers:
if running_max is None:
running_max = n
else:
running_max = max(numbers)
result.append(running_max)
return result
|
73 |
#単位元を設定
ide = 0
class SegmentTree:
def __init__(self,n):
#セグ木の頂点はindex == 1から。index == 0は無視すること。
#つまり、STtable[0]は無視。頂点はSTtable[1]。
self.n = n
tmp = 0
while True:
if 2 ** tmp >= self.n:
break
tmp += 1
self.STtable = [ide] * (2*2**tmp)
self.STtable_size = len(self.STtable)
def update(self,i,a):
#更新のためのインデックスの指定は0_indexedで。
a_bit = 1 << ord(a)-97
i += self.STtable_size//2
self.STtable[i] = a_bit
while i > 0:
i //= 2
self.STtable[i] = self.STtable[i*2] | self.STtable[i*2+1]
def find(self,a,b,k=1,l=0,r=None):
#kは頂点番号。初期値は1にすること。
#[a,b)の最小を返す。
#[l,r)からです。
#初期値のrは、self.STtable_size//2にすると、ちょうど要素数と同じ値になって[l,r)のrになる。
#問題に適するように範囲を指定するように注意。大体[l,r]で指定されている。
if r == None:
r = self.STtable_size//2
if a >= r or b <= l:
return ide
elif a <= l and b >= r:
return self.STtable[k]
else:
mid = (l+r)//2
if b <= mid:
return self.find(a,b,2*k,l,mid)
elif a >= mid:
return self.find(a,b,2*k+1,mid,r)
else:
v1 = self.find(a,mid,2*k,l,mid)
v2 = self.find(mid,b,2*k+1,mid,r)
return v1 | v2
N = int(input())
solve = SegmentTree(N)
S = input()
for i in range(N):
solve.update(i,S[i])
Q = int(input())
ans = []
for _ in range(Q):
a,b,c = map(str, input().split())
if a == '1':
solve.update(int(b)-1,c)
else:
tmp = solve.find(int(b)-1,int(c))
cnt = 0
for i in range(26):
if tmp >> i & 1 == 1:
cnt += 1
ans.append(cnt)
for a in ans:
print(a)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
74 |
def FUNC(string: str) -> bool:
""" Test if given string is a palindrome """
return string == string[::-1]
def FUNC(string: str) -> str:
""" Find the shortest palindrome that begins with a supplied string.
Algorithm idea is simple:
- Find the longest postfix of supplied string that is a palindrome.
- Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
>>> FUNC('')
''
>>> FUNC('cat')
'catac'
>>> FUNC('cata')
'catac'
"""
if not string:
return ''
beginning_of_suffix = 0
while not FUNC(string):
beginning_of_suffix += 1
return string + string[:beginning_of_suffix][::-1]
|
75 |
N = int(input())
A = list(map(int, input().split()))
N = len(A) // 3
A = A[:3*N]
#print(N, A)
A.append(0)
A.append(0)
ans = 0
def ind(a, b):
t = sorted((a, b))
return t[0] * (N+1) + t[1]
def inv(i):
b = i % (N+1)
a = i // (N + 1)
return a, b
dp = [-1] * (N+1)**2
dp[ind(A[0],A[1])] = 0
dp1 = [-1] * (N+1)
dp1[A[0]] = 0
dp1[A[1]] = 0
ans = 0
for i in range(0, N):
a = A[2+3*i]
b = A[2+3*i+1]
c = A[2+3*i+2]
#print(a,b,c)
if a == b == c:
ans+=1
continue
dp_new = {}
for x, y, z in [(a, b, c), (b, c, a), (c, a, b)]:
# choose 1 (x), leave y, z
i = ind(y,z)
if i not in dp_new:
dp_new[i] = 0
if dp[ind(x, x)] >= 0:
dp_new[i] = max(dp_new[i], dp[ind(x, x)] + 1)
# choose 2 (x, y), leave t, z
for t in range(1, N+1):
i = ind(t,z)
# Not making three
dp_new[i] = dp1[t]
# Making three (x==y)
if x == y:
if dp[ind(t, x)] >= 0:
dp_new[i] = dp[ind(t, x)] + 1
#print({inv(i):v for i, v in dp_new.items() })
for i, s in dp_new.items():
dp[i] = max(dp[i], s)
ta, tb = inv(i)
dp1[ta] = max(dp1[ta], s)
dp1[tb] = max(dp1[tb], s)
#print(doubles)
print(ans + max(dp))
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
76 |
import collections
from scipy.sparse.csgraph import floyd_warshall
import sys
sys.setrecursionlimit(10**8)
n=int(input())
arr=[input() for _ in range(n)]
g=[[] for _ in range(n)]
for i in range(n):
for j in range(n):
if i==j:
continue
if arr[i][j]=='1':
g[i].append(j)
colors=[0]*n
def dfs(v,color):
colors[v]=color
for u in g[v]:
if colors[u]==color:
return False
if colors[u]==0 and not dfs(u,-color):
return False
return True
def is_bipartite():
return dfs(0,1)
if is_bipartite()==False:
print(-1)
exit()
ans=0
for v in range(n):
q=collections.deque()
q.append((v,1))
checked=[0]*n
anss=[]
while len(q)!=0:
tmp,depth=q.popleft()
anss.append(depth)
checked[tmp]=1
for v in g[tmp]:
if checked[v]==0:
q.append((v,depth+1))
ans=max(ans,max(anss))
print(ans)
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
77 |
from math import gcd
def pairwise_coprime(a):
check = [set() for _ in range(10 ** 6 + 10)]
for i, aa in enumerate(a):
now = aa
while now % 2 == 0:
if i > 0 and len(check[2]) > 0 and i not in check[2]:
return False
now //= 2
check[2].add(i)
f = 3
while f * f <= now:
if now % f == 0:
if i > 0 and len(check[f]) > 0 and i not in check[f]:
return False
now //= f
check[f].add(i)
else:
f += 2
if now != 1:
check[now].add(i)
return True
def main():
n = int(input())
a = list(map(int, input().split()))
ac_gcd = [a[-1] for _ in range(n)]
for i in range(n - 2, -1, -1):
ac_gcd[i] = gcd(a[i], ac_gcd[i + 1])
is_pc = pairwise_coprime(a)
if is_pc:
print("pairwise coprime")
elif ac_gcd[0] == 1:
print("setwise coprime")
else:
print("not coprime")
if __name__ == '__main__':
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
78 |
#!/usr/bin/env python3
INF = 10**7
import sys
input = sys.stdin.readline
from collections import*
def bfs(sx, sy, gx, gy, c):
q = deque([(sx, sy)])
dist = [[INF] * W for _ in range(H)]
dist[sx][sy] = 0
while q:
x, y = q.popleft()
if (x, y) == (gx, gy): return dist[gx][gy]
for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:
if 0<=nx<H and 0<=ny<W and dist[nx][ny] > dist[x][y]:
if c[nx][ny] == ".":
dist[nx][ny] = dist[x][y]
q.appendleft((nx, ny))
for nx in range(x-2, x+3):
for ny in range(y-2, y+3):
if 0<=nx<H and 0<=ny<W and dist[nx][ny] > dist[x][y]:
if c[nx][ny] == ".":
dist[nx][ny] = dist[x][y] + 1
q.append((nx, ny))
return -1
H, W = map(int, input().split())
cx, cy = map(int, input().split())
dx, dy = map(int, input().split())
ans = bfs(cx - 1, cy - 1, dx - 1, dy - 1, [input()[:-1] for _ in range(H)])
print(ans if ans != INF else -1)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
79 |
from collections import deque
H,W = map(int,input().split())
maze = []
for i in range(H):
maze.append(input())
q = deque()
saitan = [1000000]*H*W
start = []
sumi= []
for i in range(H):
for k in range(W):
if maze[i][k] == '#':
start.append(i*W+k)
for i in start:
q.append(i)
sumi.append(i)
saitan[i] = 0
#print(start)
def bfs(h,w,q,Sumi,Saitan):
dx = [1,-1,0,0]
dy = [0,0,1,-1]
while len(q)>0:
j = q.popleft()
y = int(j/w)
x = j%w
#print(saitan)
for k in range(4):
my = y + dy[k]
mx = x + dx[k]
#print(sx,sy,j,x,y,mx,my)
if not((0 <=my <= h-1) and (0 <= mx <= w-1)):
#print('q')
continue
if (my*w + mx) in Sumi:
#print('b')
continue
if saitan[(my*w + mx)] <= saitan[y*w + x] + 1:
#print('c')
continue
saitan[(my*w + mx)] = saitan[y*w + x] + 1
q.append(my*w + mx)
Sumi.append(my*w + mx)
return max(saitan)
print(bfs(H,W,q,sumi,saitan))
#print(saitan)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
80 |
#!/usr/bin/env python3
import sys
from collections import deque
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def main():
n, m, k = MI()
a = deque(LI())
b = deque(LI())
read = []
isAll = False
while sum(read) <= k:
if len(a) == 0 and len(b) == 0:
isAll = True
break
if len(a) == 0 or a[0] >= b[0]:
b_top = b.popleft()
read.append(b_top)
continue
if len(b) == 0 or a[0] < b[0]:
a_top = a.popleft()
read.append(a_top)
continue
if isAll:
print(len(read))
else:
print(len(read) - 1)
# oj t -c "pypy3 main.py"
# acc s main.py -- --guess-python-interpreter pypy
main()
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
81 |
from typing import List
def FUNC(a: str, b: str) -> str:
""" Input are two strings a and b consisting only of 1s and 0s.
Perform binary XOR on these inputs and return result also as a string.
>>> FUNC('010', '110')
'100'
"""
def FUNC(i, j):
if i == j:
return '1'
else:
return '0'
return ''.join(FUNC(x, y) for x, y in zip(a, b))
|
82 |
from typing import List, Optional
def FUNC(strings: List[str]) -> Optional[str]:
""" Out of list of strings, return the FUNC one. Return the first one in case of multiple
strings of the same length. Return None in case the input list is empty.
>>> FUNC([])
>>> FUNC(['a', 'b', 'c'])
'a'
>>> FUNC(['a', 'bb', 'ccc'])
'ccc'
"""
if not strings:
return None
maxlen = max(len(x) for x in strings)
for s in strings:
if len(s) > maxlen:
return s
|
83 |
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf,comb
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT() : return int(input())
def MAP() : return map(int,input().split())
def LIST() : return list(MAP())
h, w = MAP()
a = []
b = []
c = []
for i in range(h):
a.append(input())
for j in range(w):
if a[i][j] == '#':
b.append([i, j])
else:
c.append([i, j])
ans = 0
for x in c:
tmp = inf
for y in b:
tmp = min(tmp, abs(x[0]-y[0])+abs(x[1]-y[1]))
if tmp <= ans:
break
ans = max(ans, tmp)
print(ans)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
84 |
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
def main():
H,W,K = map(int, readline().split())
S = [list(map(int, readline().strip())) for j in range(H)]
print(H,W,S)
white = 0
for line in S:
white += sum(line)
if white <= K:
print(0)
exit()
Pdb().set_trace()
# 横線の決め方を全探索
ans = 10**5
#yに横線Patternごとの列合計を作成
#入力例1のPattern[bin(2)]場合、y=[[1,1,1,0,0], [1,0,1,1,2]]
for pattern in range(2**(H-1)):
# 初期化
impossible = False
x = 0
ly = bin(pattern).count("1")
y = [S[0]]
line = 0
for i in range(1,H):
if (pattern >> i-1) & 1:
line += 1
y.append(S[i])
else:
y[line] = [y[line][j] + S[i][j] for j in range(W)]
# 各列の値を加算していく
count = [0]*(ly + 1)
for j in range(W):
for i in range(line+1):
if y[i][j] > K :
impossible = True
break
count[i] += y[i][j]
#print("横Pattern{} 縦列まで {} カウント数{} 縦線の数{}".format(i, j, count[i], x))
#横Patten毎にj列までのホワイトチョコ合計数をカウント、
#カウント>Kとなったら、縦線数を+1、その列値でカウント数を初期化
if count[i] > K:
x += 1
for i in range(line+1):
count[i] = y[i][j]
break
#x縦線の数 + ly横線の数がAnsより大きくなったらBreak
if x + ly > ans or impossible:
impossible = True
break
if impossible:
x = 10**6
#x縦線の数 + ly横線の数がAnsより小さくなったらAnsを更新
ans = min(ans, x + ly)
print(ans)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
85 |
def examA():
N, A, B = LI()
if (A-B)%2==0:
ans = "Alice"
else:
ans = "Borys"
print(ans)
return
def examB():
K = I()
A = LI()
cur = 2
for i in range(K-1,-1,-1):
a = A[i]
if A[i]>cur:
print(-1)
exit()
cur = (cur//a+1)*a-1
# print(cur)
maxA = cur; cur = 2
for i in range(K-1,-1,-1):
a = A[i]
if cur<=a:
cur = a
else:
cur = a*(cur//a+1)
minA = cur
print(minA,maxA)
return
import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
mod = 10**9 + 7
inf = float('inf')
if __name__ == '__main__':
examB()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
86 |
from collections import defaultdict
N = int(input())
L = [list(map(lambda x:int(x)-1, input().split())) for _ in range(N)]
def make_hash(a, b):
a, b = min(a, b), max(a, b)
return N*a+b
def un_hash(n):
a = n//N
b = n % N
return a, b
from_to = defaultdict(lambda: set())
pointed = defaultdict(int)
pointing = defaultdict(int)
for i in range(N):
for node_from, node_to in zip(L[i], L[i][1:]):
from_to[make_hash(i, node_to)].add(make_hash(i, node_from))
pointed[make_hash(i, node_to)] += 1
pointing[make_hash(i, node_from)] += 1
START = set()
DST = set()
for i in range(N):
for j in range(i+1, N):
h = make_hash(i, j)
pointed_i = pointed[h]
pointing_i = pointing[h]
if pointed_i == 0:
START.add(h)
if pointing_i == 0:
DST.add(h)
if len(START) == 0 or len(DST) == 0:
print(-1)
else:
Q = [[v, 1] for v in DST]
dist = 1
while Q:
q, d = Q.pop()
for nex in from_to[q]:
Q.append([nex, d+1])
dist = d+1
print(dist)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
87 |
def main():
import sys
sys.setrecursionlimit(1000000)
N = int(input())
A = [[]]
for _ in range(N):
A.append([0]+list(map(int,input().split())))
#AR[i][j] => iにとって選手jとの試合が何番目か
AR = [[]]
for i in range(1,N+1):
AR.append([0]*(N+1))
for j in range(1,N):
b = A[i][j]
AR[i][b] = j
edges = {}
for i in range(1,N+1):
for j in range(i+1,N+1):
edges[(i,j)] = []
jForI = AR[i][j]
if jForI < N-1:
nxForI = A[i][jForI+1]
edges[(i,j)].append((min(i,nxForI),max(i,nxForI)))
iForJ = AR[j][i]
if iForJ < N-1:
nxForJ = A[j][iForJ+1]
edges[(i,j)].append((min(j,nxForJ),max(j,nxForJ)))
steps = {}
def dfs(i,j):
#iとjの試合を1日目とし、試合終了まで何日かかるかを返す。
if (i,j) not in steps:
steps[(i,j)] = 0
res = 1
for a,b in edges[(i,j)]:
res = max(res,dfs(a,b)+1)
steps[(i,j)] = res
elif steps[(i,j)] == 0:
print(-1)
exit()
return steps[(i,j)]
ans = 0
for i in range(1,N+1):
for j in range(i+1,N+1):
ans = max(ans,dfs(i,j))
print(ans)
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
88 |
char_num = int(input())
char_length = 10
chars = []
for i in range(char_num):
chars.append(input())
class CharArrange:
def __init__(self, char):
self.char = char
def char_run(self):
list_char = self.str2ord_list(self.char)
for pos in range(1, len(list_char)):
self.insert_sort(list_char, pos, list_char[pos])
self.char = self.ordList2Str(list_char)
def order_run(self, chars):
for i, char in enumerate(chars):
chars[i] = self.ord_list2ord_concat(self.str2ord_list(char))
for pos in range(len(chars)):
self.insert_sort(chars, pos, chars[pos])
self.ord_chars = chars
def str2ord_list(self, char):
return list(map(ord, char))
def ordList2Str(self, ordList):
return ''.join(list(map(chr, ordList)))
def ord_list2ord_concat(self, ord_list):
self.ord_concat = ''
for ord_num in ord_list:
self.ord_concat += str(ord_num)
return int(self.ord_concat)
def insert_sort(self, A, pos, value):
i = pos - 1
while (i >= 0 and A[i] > value):
A[i+1] = A[i]
i = i - 1
A[i+1] = value
return A
for i, char in enumerate(chars):
CA = CharArrange(char)
CA.char_run()
chars[i] = CA.char
CA.order_run(chars)
ord_chars = CA.ord_chars
counter = 0
for i in range(len(ord_chars) - 1):
k = i + 1
while (ord_chars[i] == ord_chars[k]):
counter += 1
if k == len(ord_chars) - 1:
break
else:
k += 1
print(counter)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
89 |
import copy
from heapq import heappop, heapify, heappush
import math
N, K = map(int, input().split())
A = [int(i) for i in input().split()]
F = [int(i) for i in input().split()]
ans = 0
A.sort(reverse=True)
F.sort()
s = []
for i in range(N):
s.append([A[i]*F[i], A[i], F[i]])
s.sort(reverse=True, key=lambda x: x[0])
def f(l, T):
cur = 0
num = 0
S = copy.deepcopy(l)
while cur <= K:
if len(S) == 0:
break
a, b, c = S[num]
if a <= T:
break
cur += math.ceil((a - T)/c)
num += 1
if cur <= K:
return True
else:
return False
ok, ng = s[0][0], -1
while abs(ok-ng) > 1:
mid = (ok+ng)//2
if f(s, mid) == True:
ok = mid
else:
ng = mid
print(ok)
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
90 |
def FUNC(a: int, b: int) -> int:
""" Return a greatest common divisor of two integers a and b
>>> FUNC(3, 5)
1
>>> FUNC(25, 15)
5
"""
while b:
a, b = b, a % b
return b
|
91 |
#!/usr/bin/env python3
import collections as cl
import sys
def II():
return int(sys.stdin.readline())
def MI():
return map(int, sys.stdin.readline().split())
def LI():
return list(map(int, sys.stdin.readline().split()))
def main():
N = II()
targets = LI()
MAX_INT = max(targets) + 1
targets = set(targets)
is_pw = True
for i in range(2, MAX_INT):
origin = i
kosuu = 0
while origin <= MAX_INT:
if origin in targets:
kosuu += 1
origin += i
if kosuu <= 1:
continue
elif kosuu < N:
is_pw = False
else:
print("not coprime")
return
if is_pw:
print("pairwise coprime")
return
print("setwise coprime")
main()
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
92 |
import sys
input = sys.stdin.readline
def main():
H,W = map(int,input().split())
CH,CW = map(int,input().split())
DH,DW = map(int,input().split())
S=[None]*H
for i in range(H):
S[i] = input()
from collections import deque
def cango_step(x,y):
cand =[]
if x+1<=H-1:
cand.append((x+1,y))
if x-1>=0:
cand.append((x-1,y))
if y+1<=W-1:
cand.append((x,y+1))
if y-1>=0:
cand.append((x,y-1))
return cand
def cango_warp(x,y):
cand = [(i,j)
for i in range(x-2,x+3) for j in range(y-2,y+3)
if 0<=i and i<=H-1 and 0<=j and j<=W-1]
return cand
been = [[False]*W for _ in range(H)]
rooms=dict()
i_room=-1
for x in range(H):
for y in range(W):
if S[x][y]=="." and not been[x][y]:
i_room+=1
been[x][y]=True
q = deque([(-1,-1,x,y)])
rooms[(x,y)]=i_room
while q:
x_old,y_old,x_now,y_now = q.popleft()
cand = cango_step(x_now,y_now)
#print(x_old,y_old,x_now,y_now,time)
if x_now==CH-1 and y_now==CW-1:
start_warp = i_room
if x_now==DH-1 and y_now==DW-1:
end_warp = i_room
for x_new,y_new in cand:
if not been[x_new][y_new] and S[x_new][y_new]==".":
q.append((x_now,y_now,x_new,y_new))
been[x_new][y_new]=True
# room.append((x_new,y_new))
rooms[(x_new,y_new)]=i_room
# rooms.append(room)
if start_warp==end_warp:
print(0)
else:
#ワープで行けるほかの部屋をtree入れる
n_rooms = i_room+1
tree=[[] for _ in range(n_rooms)]
for k,v in rooms.items():
cango = set(rooms[togo] for togo in cango_warp(*k) if S[togo[0]][togo[1]]=="." )
for c in cango:
if c!=v:
tree[c].append(v)
tree[v].append(c)
#print(v,cango)
for i in range(len(tree)):
tree[i] = set(tree[i])
q = deque([(-1,start_warp,0)]) #これでもよい
been=[False]*n_rooms
been[start_warp]=True
reach=False
while q:
parent,x,time = q.popleft()
if x==end_warp:
reach=True
break
for y in tree[x]:
if not been[y]:
q.append((x,y,time+1))#子ノードを追加
been[y]=True
#print(parent,x,q,time)
if reach:
print(time)
else:
print(-1)
main()
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
93 |
# -*- coding: utf-8 -*-
import sys
from collections import deque
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7
N = INT()
A = [deque()]
for i in range(N):
A.append(deque(LIST()))
cnt = N*(N-1)//2
day = 0
while cnt > 0:
prev = cnt
skip = [False] * (N+1)
for i in range(1, N+1):
if len(A[i]) and not skip[i]:
a = A[i][0]
if len(A[a]) and not skip[a]:
b = A[a][0]
if i == b:
A[i].popleft()
A[a].popleft()
cnt -= 1
skip[i] = skip[a] = True
if prev == cnt:
print(-1)
exit()
day += 1
if day > 200000:
print(N*(N-1)//2)
exit()
print(day)
Fix bugs of Time Limit Exceeded in the above code block.
##Your response must contain only the python code to solve this problem.
|
94 |
import sys
from collections import deque
sys.setrecursionlimit(4100000)
def inputs(num_of_input):
ins = [input() for i in range(num_of_input)]
return ins
def solve(inputs):
head = int(inputs[0][:2])
tail = int(inputs[0][2:])
YY = 1
BOTH = 2
NA = -1
head_type = NA
tail_type = NA
if head == 0:
head_type = NA
elif head > 12:
head_type = YY
else:
head_type = BOTH
if tail == 0:
tail_type = NA
elif tail > 12:
tail_type = YY
else:
tail_type = BOTH
if head_type == NA or tail_type == NA:
return "NA"
if head_type == YY and tail_type == YY:
return "NA"
if head_type == BOTH and tail_type == BOTH:
return "AMBIGUOUS"
if head_type == YY:
return "YYMM"
if tail_type == YY:
return "MMYY"
def string_to_int(string):
return list(map(lambda x: int(x), string.split()))
if __name__ == "__main__":
ret = solve(inputs(1))
print(ret)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
95 |
from typing import List
def FUNC(string: str) -> List[str]:
""" Return list of all prefixes from shortest to longest of the input string
>>> FUNC('abc')
['a', 'ab', 'abc']
"""
result = []
for i in range(len(string)-1):
result.append(string[:i+1])
return result
|
96 |
def FUNC(n: int) -> str:
""" Return a string containing space-delimited numbers starting from 0 upto n inclusive.
>>> FUNC(0)
'0'
>>> FUNC(5)
'0 1 2 3 4 5'
"""
return ' '.join([str(x) for x in range(n)])
|
97 |
import sys
import numpy as np
import math
def ReadInputNum():
input_num=[]
for i in range(5):
input_num.append(int(input()))
return tuple(input_num)
def CheckRangeInput(*argv):
for num in argv:
if num<=123 and isinstance(num,int):
pass
# print("good")
else:
print("input"+ num +"is unexpected.")
sys.exit()
def SumTotalTime(Tuple_Input):
list_input=list(Tuple_Input)
# print(list_input)
list_tmp=np.array(list_input)
amari=(list_tmp-1)%10
amari=amari.tolist()
# print(amari)
last_one=min(amari)
# print(last_one)
last_one=list_input.pop(amari.index(last_one))
print(last_one)
print(list_input)
out_put=0
for i in list_input:
out_put += math.ceil(i/10)*10
# print(out_put)
print(out_put+last_one)
A,B,C,D,E = ReadInputNum()
CheckRangeInput(A,B,C,D,E)
tuple_input = (A,B,C,D,E)
SumTotalTime(tuple_input)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
98 |
from copy import copy
n = int(input())
a = list(map(int, input().split()))
ok, ng = n, 0
while ok-ng > 1:
x = (ok+ng)//2
#d = defaultdict(int)
d = dict()
last = 0
valid = True
if x == 1:
for i in range(n-1):
if a[i] >= a[i+1]:
valid = False
break
if valid:
ok = x
else:
ng = x
continue
for i in range(n-1):
dels = []
if a[i] < a[i+1]:
last = a[i+1]
elif a[i] > a[i+1]:
#dels = []
for k in d.keys():
if k > last:
dels.append(k)
if a[i+1] > last:
d[a[i+1]] = 1
else:
j = a[i+1]
while j in d:
if d[j] != x-1 or j <= 0:
break
else:
dels,append(j)
j -= 1
if j in d:
d[j] += 1
else:
d[j] = 1
last = a[i+1]
elif a[i] == a[i+1]:
#dels = []
for k in d.keys():
if k > last:
dels.append(k)
j = a[i+1]
while j in d:
if d[j] != x-1 or j <= 0:
break
else:
dels.append(j)
j -= 1
if j in d:
d[j] += 1
else:
d[j] = 1
last = a[i+1]
for k in dels:
del d[k]
if 0 in d:
valid = False
break
if valid:
ok = x
else:
ng = x
print(ok)
Fix bugs of Runtime Error in the above code block.
##Your response must contain only the python code to solve this problem.
|
99 |
import sys
from collections import deque, defaultdict
import copy
import bisect
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 9)
H, W = list(map(int, input().split()))
grid = []
for i in range(H):
grid.append(input()[0:W])
num_yoko = [[0 for i in range(W)] for j in range(H)]
num_tate = [[0 for i in range(W)] for j in range(H)]
for i in range(H):
for j in range(W):
if grid[i][j] == '.':
if j == 0:
num_yoko[i][j] = 1
else:
num_yoko[i][j] = num_yoko[i][j - 1] + 1
if i == 0:
num_tate[i][j] = 1
else:
num_tate[i][j] = num_tate[i - 1][j] + 1
for i in range(H - 1, -1, -1):
for j in range(W - 1, -1, -1):
if grid[i][j] == '.':
if j != W - 1:
if num_yoko[i][j + 1] != 0:
num_yoko[i][j] = num_yoko[i][j + 1]
if i != H - 1:
if num_tate[i + 1][j] != 0:
num_tate[i][j] = num_tate[i + 1][j]
num_max = 0
for i in range(H - 1):
for j in range(W - 1):
if num_yoko[i][j] + num_tate[i][j] > num_max:
num_max = num_yoko[i][j] + num_tate[i][j]
print(num_max - 1)
Fix bugs of Wrong Answer in the above code block.
##Your response must contain only the python code to solve this problem.
|
100 |
def FUNC(string: str) -> int:
""" Given a string, find out how many distinct characters (regardless of case) does it consist of
>>> FUNC('xyzXYZ')
3
>>> FUNC('Jerry')
4
"""
return len(set(string))
|
End of preview.
README.md exists but content is empty.
- Downloads last month
- 4