text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
"Correct Solution:
```
class CSR:
def __init__(self, n: int, edges: list):
self.start = [0] * (n + 1)
self.elist = [0] * len(edges)
for e in edges:
self.start[e[0] + 1] += 1
for i in range(1, n + 1):
self.start[i] += self.start[i - 1]
counter = self.start[::] # copy
for e in edges:
self.elist[counter[e[0]]] = e[1]
counter[e[0]] += 1
class SccGraph:
def __init__(self, n: int = 0):
self.__n = n
self.__edges = []
def __len__(self):
return self.__n
def add_edge(self, s: int, t: int):
assert 0 <= s < self.__n and 0 <= t < self.__n
self.__edges.append([s, t])
def scc_ids(self):
g = CSR(self.__n, self.__edges)
now_ord = group_num = 0
visited = []
low = [0] * self.__n
order = [-1] * self.__n
ids = [0] * self.__n
parent = [-1] * self.__n
for root in range(self.__n):
if order[root] == -1:
stack = [root, root]
while stack:
v = stack.pop()
if order[v] == -1:
visited.append(v)
low[v] = order[v] = now_ord
now_ord += 1
for i in range(g.start[v], g.start[v + 1]):
t = g.elist[i]
if order[t] == -1:
stack += [t, t]
parent[t] = v
else:
low[v] = min(low[v], order[t])
else:
if low[v] == order[v]:
while True:
u = visited.pop()
order[u] = self.__n
ids[u] = group_num
if u == v:
break
group_num += 1
if parent[v] != -1:
low[parent[v]] = min(low[parent[v]], low[v])
for i, x in enumerate(ids):
ids[i] = group_num - 1 - x
return group_num, ids
def scc(self):
"""
強連結成分のリストを返す。この時、リストはトポロジカルソートされている
[[強連結成分のリスト], [強連結成分のリスト], ...]
"""
group_num, ids = self.scc_ids()
counts = [0] * group_num
for x in ids:
counts[x] += 1
groups = [[] for _ in range(group_num)]
for i, x in enumerate(ids):
groups[x].append(i)
return groups
class TwoSAT():
def __init__(self, n):
self.n = n
self.res = [0]*self.n
self.scc = SccGraph(2*n)
def add_clause(self, i, f, j, g):
# assert 0 <= i < self.n
# assert 0 <= j < self.n
self.scc.add_edge(2*i + (not f), 2*j + g)
self.scc.add_edge(2*j + (not g), 2*i + f)
def satisfiable(self):
"""
条件を足す割当が存在するかどうかを判定する。割当が存在するならばtrue、そうでないならfalseを返す。
"""
group_num, ids = self.scc.scc_ids()
for i in range(self.n):
if ids[2*i] == ids[2*i + 1]: return False
self.res[i] = (ids[2*i] < ids[2*i+1])
return True
def result(self):
"""
最後に呼んだ satisfiable の、クローズを満たす割当を返す。
"""
return self.res
#############################################################################
import sys
input = sys.stdin.buffer.readline
N, D = map(int, input().split())
XY = []
for _ in range(N):
X, Y = map(int, input().split())
XY.append((X, Y))
ts = TwoSAT(N)
for i in range(N-1):
x0, y0 = XY[i]
for j in range(i+1, N):
x1, y1 = XY[j]
if abs(x0 - x1) < D:
ts.add_clause(i, 1, j, 1)
if abs(x0 - y1) < D:
ts.add_clause(i, 1, j, 0)
if abs(y0 - x1) < D:
ts.add_clause(i, 0, j, 1)
if abs(y0 - y1) < D:
ts.add_clause(i, 0, j, 0)
if ts.satisfiable():
print('Yes')
print('\n'.join(map(str, (xy[r] for r, xy in zip(ts.result(), XY)))))
else:
print('No')
```
| 15,700 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
"Correct Solution:
```
#-------最強ライブラリ2-SAT(Python)------
#最強ライブラリSCC(Python)が必要
class two_sat:
def __init__(s):
s._n = 0
s.scc = scc_graph(0)
def __init__(s, n):
s._n = n
s._answer = [False] * n
s.scc = scc_graph(2 * n)
# クローズを足す
# クローズってなに
def add_clause(s, i, f, j, g):
s.scc.add_edge(2 * i + (not f), 2 * j + (g))
s.scc.add_edge(2 * j + (not g), 2 * i + (f))
# 判定
# O(n + m)
def satisfiable(s):
id = s.scc.scc_ids()[1]
for i in range(s._n):
if id[2 * i] == id[2 * i + 1]: return False
s._answer[i] = id[2 * i] < id[2 * i + 1]
return True
# クローズを満たす割当を返す
# satisfiableがTrueとなった後に呼ばないと意味ない
# O(1だよね?)
def answer(s): return s._answer
#-------最強ライブラリここまで------
#-------最強ライブラリSCC(Python)ver25252------
import copy
import sys
sys.setrecursionlimit(1000000)
class csr:
# start 頂点iまでの頂点が、矢元として現れた回数
# elist 矢先のリストを矢元の昇順にしたもの
def __init__(s, n, edges):
s.start = [0] * (n + 1)
s.elist = [[] for _ in range(len(edges))]
for e in edges:
s.start[e[0] + 1] += 1
for i in range(1, n + 1):
s.start[i] += s.start[i - 1]
counter = copy.deepcopy(s.start)
for e in edges:
s.elist[counter[e[0]]] = e[1]
counter[e[0]] += 1
class scc_graph:
edges = []
# n 頂点数
def __init__(s, n): s._n = n
def num_vertices(s): return s._n
# 辺を追加 frm 矢元 to 矢先
# O(1)
def add_edge(s, frm, to): s.edges.append([frm, [to]])
# グループの個数と各頂点のグループidを返す
def scc_ids(s):
g = csr(s._n, s.edges)
now_ord = group_num = 0
visited = []
low = [0] * s._n
ord = [-1] * s._n
ids = [0] * s._n
# 再帰関数
def dfs(self, v, now_ord, group_num):
low[v] = ord[v] = now_ord
now_ord += 1
visited.append(v)
for i in range(g.start[v], g.start[v + 1]):
to = g.elist[i][0]
if ord[to] == -1:
now_ord, group_num = self(self, to, now_ord, group_num)
low[v] = min(low[v], low[to])
else:
low[v] = min(low[v], ord[to])
if low[v] == ord[v]:
while True:
u = visited.pop()
ord[u] = s._n
ids[u] = group_num
if u == v: break
group_num += 1
return now_ord, group_num
for i in range(s._n):
if ord[i] == -1: now_ord, group_num = dfs(dfs, i, now_ord, group_num)
for i in range(s._n):
ids[i] = group_num - 1 - ids[i]
return [group_num, ids]
# 強連結成分となっている頂点のリストのリスト トポロジカルソート済み
# O(n + m)
def scc(s):
ids = s.scc_ids()
group_num = ids[0]
counts = [0] * group_num
for x in ids[1]: counts[x] += 1
groups = [[] for _ in range(group_num)]
for i in range(s._n):
groups[ids[1][i]].append(i)
return groups
#-------最強ライブラリここまで------
def main():
input = sys.stdin.readline
N, D = list(map(int, input().split()))
XY = [list(map(int, input().split())) for _ in range(N)]
ts = two_sat(N)
for i in range(N):
for j in range(i + 1, N):
xi, yi = XY[i]
xj, yj = XY[j]
# 距離がD未満の組み合わせに関して、
# 少なくとも一つは使用しない
# → 少なくとも一つは別の座標を使用する
# というルールを追加する
if (abs(xi - xj) < D):
ts.add_clause(i, False, j, False)
if (abs(xi - yj) < D):
ts.add_clause(i, False, j, True)
if (abs(yi - xj) < D):
ts.add_clause(i, True, j, False)
if (abs(yi - yj) < D):
ts.add_clause(i, True, j, True)
if not ts.satisfiable():
print("No")
exit()
print("Yes")
answer = ts.answer()
for i in range(N):
x, y = XY[i]
if answer[i]:
print(x)
else:
print(y)
main()
```
| 15,701 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
"Correct Solution:
```
from itertools import product
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 6 + 100)
class StronglyConnectedComponets:
def __init__(self, n: int) -> None:
self.n = n
self.edges = [[] for _ in range(n)]
self.rev_edeges = [[] for _ in range(n)]
self.vs = []
self.order = [0] * n
self.used = [False] * n
def add_edge(self, from_v: int, to_v: int) -> None:
self.edges[from_v].append(to_v)
self.rev_edeges[to_v].append(from_v)
def dfs(self, v: int) -> None:
self.used[v] = True
for child in self.edges[v]:
if not self.used[child]:
self.dfs(child)
self.vs.append(v)
def rdfs(self, v: int, k: int) -> None:
self.used[v] = True
self.order[v] = k
for child in self.rev_edeges[v]:
if not self.used[child]:
self.rdfs(child, k)
def run(self) -> int:
self.used = [False] * self.n
self.vs.clear()
for v in range(self.n):
if not self.used[v]:
self.dfs(v)
self.used = [False] * self.n
k = 0
for v in reversed(self.vs):
if not self.used[v]:
self.rdfs(v, k)
k += 1
return k
class TwoSat(StronglyConnectedComponets):
def __init__(self, num_var: int) -> None:
super().__init__(2 * num_var + 1)
self.num_var = num_var
self.ans = []
def add_constraint(self, a: int, b: int) -> None:
super().add_edge(self._neg(a), self._pos(b))
super().add_edge(self._neg(b), self._pos(a))
def _pos(self, v: int) -> int:
return v if v > 0 else self.num_var - v
def _neg(self, v: int) -> int:
return self.num_var + v if v > 0 else -v
def run(self) -> bool:
super().run()
self.ans.clear()
for i in range(self.num_var):
if self.order[i + 1] == self.order[i + self.num_var + 1]:
return False
self.ans.append(self.order[i + 1] > self.order[i + self.num_var + 1])
return True
def main() -> None:
N, D = map(int, input().split())
flags = [tuple(int(x) for x in input().split()) for _ in range(N)]
# (X_i, Y_i) -> (i, -i) (i=1, ..., N) と考える
sat = TwoSat(N)
# 節 a, b の距離が D 以下の場合,
# a -> -b つまり -a or -b が成立しなければならない
for i, (x_i, y_i) in enumerate(flags, 1):
for j, (x_j, y_j) in enumerate(flags[i:], i+1):
if abs(x_i - x_j) < D:
sat.add_constraint(-i, -j)
if abs(y_i - x_j) < D:
sat.add_constraint(i, -j)
if abs(x_i - y_j) < D:
sat.add_constraint(-i, j)
if abs(y_i - y_j) < D:
sat.add_constraint(i, j)
if sat.run():
print("Yes")
print(*[x_i if sat.ans[i] else y_i for i, (x_i, y_i) in enumerate(flags)], sep="\n")
else:
print("No")
if __name__ == "__main__":
main()
```
| 15,702 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
"Correct Solution:
```
# AC Library Python版
# Author Koki_tkg
'''
internal_type_traits以外は翻訳しました。
practiceは一応全部ACしていますが,
practiceで使っていない関数などの動作は未確認なので保証はしません。
また,C++版をほぼそのまま書き換えているので速度は出ません。 (2020/09/13 by Koki_tkg)
'''
# --------------------<< Library Start >>-------------------- #
# convolution.py
class convolution:
def __init__(self, a: list, b: list, mod: int):
self.a, self.b = a, b
self.n, self.m = len(a), len(b)
self.MOD = mod
self.g = primitive_root_constexpr(self.MOD)
def convolution(self) -> list:
n, m = self.n, self.m
a, b = self.a, self.b
if not n or not m: return []
if min(n, m) <= 60:
if n < m:
n, m = m, n
a, b = b, a
ans = [0] * (n + m - 1)
for i in range(n):
for j in range(m):
ans[i + j] += a[i] * b[j] % self.MOD
ans[i + j] %= self.MOD
return ans
z = 1 << ceil_pow2(n + m - 1)
a = self.resize(a, z)
a = self.butterfly(a)
b = self.resize(b, z)
b = self.butterfly(b)
for i in range(z): a[i] = a[i] * b[i] % self.MOD
a = self.butterfly_inv(a)
a = a[:n + m - 1]
iz = self.inv(z)
a = [x * iz % self.MOD for x in a]
return a
def butterfly(self, a: list) -> list:
n = len(a)
h = ceil_pow2(n)
first = True
sum_e = [0] * 30
m = self.MOD
if first:
first = False
es, ies = [0] * 30, [0] * 30
cnt2 = bsf(m - 1)
e = self.mypow(self.g, (m - 1) >> cnt2); ie = self.inv(e)
for i in range(cnt2, 1, -1):
es[i - 2] = e
ies[i - 2] = ie
e = e * e % m
ie = ie * ie % m
now = 1
for i in range(cnt2 - 2):
sum_e[i] = es[i] * now % m
now = now * ies[i] % m
for ph in range(1, h + 1):
w = 1 << (ph - 1); p = 1 << (h - ph)
now = 1
for s in range(w):
offset = s << (h - ph + 1)
for i in range(p):
l = a[i + offset] % m
r = a[i + offset + p] * now % m
a[i + offset] = (l + r) % m
a[i + offset + p] = (l - r) % m
now = now * sum_e[bsf(~s)] % m
return a
def butterfly_inv(self, a: list) -> list:
n = len(a)
h = ceil_pow2(n)
first = True
sum_ie = [0] * 30
m = self.MOD
if first:
first = False
es, ies = [0] * 30, [0] * 30
cnt2 = bsf(m - 1)
e = self.mypow(self.g, (m - 1) >> cnt2); ie = self.inv(e)
for i in range(cnt2, 1, -1):
es[i - 2] = e
ies[i - 2] = ie
e = e * e % m
ie = ie * ie % m
now = 1
for i in range(cnt2 - 2):
sum_ie[i] = ies[i] * now % m
now = es[i] * now % m
for ph in range(h, 0, -1):
w = 1 << (ph - 1); p = 1 << (h - ph)
inow = 1
for s in range(w):
offset = s << (h - ph + 1)
for i in range(p):
l = a[i + offset] % m
r = a[i + offset + p] % m
a[i + offset] = (l + r) % m
a[i + offset + p] = (m + l - r) * inow % m
inow = sum_ie[bsf(~s)] * inow % m
return a
@staticmethod
def resize(array: list, sz: int) -> list:
new_array = array + [0] * (sz - len(array))
return new_array
def inv(self, x: int):
if is_prime_constexpr(self.MOD):
assert x
return self.mypow(x, self.MOD - 2)
else:
eg = inv_gcd(x)
assert eg[0] == 1
return eg[1]
def mypow(self, x: int, n: int) -> int:
assert 0 <= n
r = 1; m = self.MOD
while n:
if n & 1: r = r * x % m
x = x * x % m
n >>= 1
return r
# dsu.py
class dsu:
def __init__(self, n: int):
self._n = n
self.parent_or_size = [-1] * self._n
def merge(self, a: int, b: int) -> int:
assert 0 <= a and a < self._n
assert 0 <= b and a < self._n
x = self.leader(a); y = self.leader(b)
if x == y: return x
if -self.parent_or_size[x] < -self.parent_or_size[y]: x, y = y, x
self.parent_or_size[x] += self.parent_or_size[y]
self.parent_or_size[y] = x
return x
def same(self, a: int, b: int) -> bool:
assert 0 <= a and a < self._n
assert 0 <= b and a < self._n
return self.leader(a) == self.leader(b)
def leader(self, a: int) -> int:
assert 0 <= a and a < self._n
if self.parent_or_size[a] < 0: return a
self.parent_or_size[a] = self.leader(self.parent_or_size[a])
return self.parent_or_size[a]
def size(self, a: int) -> int:
assert 0 <= a and a < self._n
return -self.parent_or_size[self.leader(a)]
def groups(self):
leader_buf = [0] * self._n; group_size = [0] * self._n
for i in range(self._n):
leader_buf[i] = self.leader(i)
group_size[leader_buf[i]] += 1
result = [[] for _ in range(self._n)]
for i in range(self._n):
result[leader_buf[i]].append(i)
result = [v for v in result if v]
return result
# fenwicktree.py
class fenwick_tree:
def __init__(self, n):
self._n = n
self.data = [0] * n
def add(self, p: int, x: int):
assert 0 <= p and p <= self._n
p += 1
while p <= self._n:
self.data[p - 1] += x
p += p & -p
def sum(self, l: int, r: int) -> int:
assert 0 <= l and l <= r and r <= self._n
return self.__sum(r) - self.__sum(l)
def __sum(self, r: int) -> int:
s = 0
while r > 0:
s += self.data[r - 1]
r -= r & -r
return s
# internal_bit.py
def ceil_pow2(n: int) -> int:
x = 0
while (1 << x) < n: x += 1
return x
def bsf(n: int) -> int:
return (n & -n).bit_length() - 1
# internal_math.py
def safe_mod(x: int, m: int) -> int:
x %= m
if x < 0: x += m
return x
class barrett:
def __init__(self, m: int):
self._m = m
self.im = -1 // (m + 1)
def umod(self): return self._m
def mul(self, a: int, b: int) -> int:
z = a
z *= b
x = (z * im) >> 64
v = z - x * self._m
if self._m <= v: v += self._m
return v
def pow_mod_constexpr(x: int, n: int, m: int) -> int:
if m == 1: return 0
_m = m; r = 1; y = safe_mod(x, m)
while n:
if n & 1: r = (r * y) % _m
y = (y * y) % _m
n >>= 1
return r
def is_prime_constexpr(n: int) -> bool:
if n <= 1: return False
if n == 2 or n == 7 or n == 61: return True
if n % 2 == 0: return False
d = n - 1
while d % 2 == 0: d //= 2
for a in [2, 7, 61]:
t = d
y = pow_mod_constexpr(a, t, n)
while t != n - 1 and y != 1 and y != n - 1:
y = y * y % n
t <<= 1
if y != n - 1 and t % 2 == 0: return False
return True
def inv_gcd(self, a: int, b: int) -> tuple:
a = safe_mod(a, b)
if a == 0: return (b, 0)
s = b; t = a; m0 = 0; m1 = 1
while t:
u = s // t
s -= t * u
m0 -= m1 * u
tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp
if m0 < 0: m0 += b // s
return (s, m0)
def primitive_root_constexpr(m: int) -> int:
if m == 2: return 1
if m == 167772161: return 3
if m == 469762049: return 3
if m == 754974721: return 11
if m == 998244353: return 3
divs = [0] * 20
divs[0] = 2
cnt = 1
x = (m - 1) // 2
while x % 2 == 0: x //= 2
i = 3
while i * i <= x:
if x % i == 0:
divs[cnt] = i; cnt += 1
while x % i == 0:
x //= i
i += 2
if x > 1: divs[cnt] = x; cnt += 1
g = 2
while True:
ok = True
for i in range(cnt):
if pow_mod_constexpr(g, (m - 1) // div[i], m) == 1:
ok = False
break
if ok: return g
g += 1
# internal_queue.py
class simple_queue:
def __init__(self):
self.payload = []
self.pos = 0
def size(self): return len(self.payload) - self.pos
def empty(self): return self.pos == len(self.payload)
def push(self, t: int): self.payload.append(t)
def front(self): return self.payload[self.pos]
def clear(self): self.payload.clear(); pos = 0
def pop(self): self.pos += 1
def pop_front(self): self.pos += 1; return self.payload[~-self.pos]
# internal_scc.py
class csr:
def __init__(self, n: int, edges: list):
from copy import deepcopy
self.start = [0] * (n + 1)
self.elist = [[] for _ in range(len(edges))]
for e in edges:
self.start[e[0] + 1] += 1
for i in range(1, n + 1):
self.start[i] += self.start[i - 1]
counter = deepcopy(self.start)
for e in edges:
self.elist[counter[e[0]]] = e[1]; counter[e[0]] += 1
class scc_graph:
# private
edges = []
# public
def __init__(self, n: int):
self._n = n
self.now_ord = 0; self.group_num = 0
def num_vertices(self): return self._n
def add_edge(self, _from: int, _to: int): self.edges.append((_from, [_to]))
def scc_ids(self):
g = csr(self._n, self.edges)
visited = []; low = [0] * self._n; ord = [-1] * self._n; ids = [0] * self._n
def dfs(s, v: int):
low[v] = ord[v] = self.now_ord; self.now_ord += 1
visited.append(v)
for i in range(g.start[v], g.start[v + 1]):
to = g.elist[i][0]
if ord[to] == -1:
s(s, to)
low[v] = min(low[v], low[to])
else:
low[v] = min(low[v], ord[to])
if low[v] == ord[v]:
while True:
u = visited.pop()
ord[u] = self._n
ids[u] = self.group_num
if u == v: break
self.group_num += 1
for i in range(self._n):
if ord[i] == -1: dfs(dfs, i)
for i in range(self._n):
ids[i] = self.group_num - 1 - ids[i]
return (self.group_num, ids)
def scc(self):
ids = self.scc_ids()
group_num = ids[0]
counts = [0] * group_num
for x in ids[1]: counts[x] += 1
groups = [[] for _ in range(group_num)]
for i in range(self._n):
groups[ids[1][i]].append(i)
return groups
# internal_type_traits.py
# lazysegtree.py
'''
def op(l, r): return
def e(): return
def mapping(l, r): return
def composition(l, r): return
def id(): return 0
'''
class lazy_segtree:
def __init__(self, op, e, mapping, composition, id, v: list):
self.op = op; self.e = e; self.mapping = mapping; self.composition = composition; self.id = id
self._n = len(v)
self.log = ceil_pow2(self._n)
self.size = 1 << self.log
self.lz = [self.id()] * self.size
self.d = [self.e()] * (2 * self.size)
for i in range(self._n): self.d[self.size + i] = v[i]
for i in range(self.size - 1, 0, -1): self.__update(i)
def set_(self, p: int, x: int):
assert 0 <= p and p < self._n
p += self.size
for i in range(self.log, 0, -1): self.__push(p >> i)
self.d[p] = x
for i in range(1, self.log + 1): self.__update(p >> 1)
def get(self, p: int):
assert 0 <= p and p < self._n
p += self.size
for i in range(self.log, 0, -1): self.__push(p >> i)
return self.d[p]
def prod(self, l: int, r: int):
assert 0 <= l and l <= r and r <= self._n
if l == r: return self.e()
l += self.size; r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self.__push(l >> i)
if ((r >> i) << i) != r: self.__push(r >> i)
sml, smr = self.e(), self.e()
while l < r:
if l & 1: sml = self.op(sml, self.d[l]); l += 1
if r & 1: r -= 1; smr = self.op(self.d[r], smr)
l >>= 1; r >>= 1
return self.op(sml, smr)
def all_prod(self): return self.d[1]
def apply(self, p: int, f):
assert 0 <= p and p < self._n
p += self.size
for i in range(self.log, 0, -1): self.__push(p >> i)
self.d[p] = self.mapping(f, self.d[p])
for i in range(1, self.log + 1): self.__update(p >> 1)
def apply(self, l: int, r: int, f):
assert 0 <= l and l <= r and r <= self._n
if l == r: return
l += self.size; r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self.__push(l >> i)
if ((r >> i) << i) != r: self.__push((r - 1) >> i)
l2, r2 = l, r
while l < r:
if l & 1: self.__all_apply(l, f); l += 1
if r & 1: r -= 1; self.__all_apply(r, f)
l >>= 1; r >>= 1
l, r = l2, r2
for i in range(1, self.log + 1):
if ((l >> i) << i) != l: self.__update(l >> i)
if ((r >> i) << i) != r: self.__update(r >> i)
def max_right(self, l: int, g):
assert 0 <= l and l <= self._n
if l == self._n: return self._n
l += self.size
for i in range(self.log, 0, -1): self.__push(l >> i)
sm = self.e()
while True:
while l % 2 == 0: l >>= 1
if not g(self.op(sm, self.d[l])):
while l < self.size:
self.__push(l)
l = 2 * l
if g(self.op(sm, self.d[l])):
sm = self.op(sm, self.d[l])
l += 1
return l - self.size
sm = self.op(sm, self.d[l])
l += 1
if (l & -l) == l: break
return self._n
def min_left(self, r: int, g):
assert 0 <= r and r <= self._n
if r == 0: return 0
r += self.size
for i in range(self.log, 0, -1): self.__push(r >> i)
sm = self.e()
while True:
r -= 1
while r > 1 and r % 2: r >>= 1
if not g(self.op(self.d[r], sm)):
while r < self.size:
self.__push(r)
r = 2 * r + 1
if g(self.op(self.d[r], sm)):
sm = self.op(self.d[r], sm)
r -= 1
return r + 1 - self.size
sm = self.op(self.d[r], sm)
if (r & -r) == r: break
return 0
# private
def __update(self, k: int): self.d[k] = self.op(self.d[k * 2], self.d[k * 2 + 1])
def __all_apply(self, k: int, f):
self.d[k] = self.mapping(f, self.d[k])
if k < self.size: self.lz[k] = self.composition(f, self.lz[k])
def __push(self, k: int):
self.__all_apply(2 * k, self.lz[k])
self.__all_apply(2 * k + 1, self.lz[k])
self.lz[k] = self.id()
# math
def pow_mod(x: int, n: int, m: int) -> int:
assert 0 <= n and 1 <= m
if m == 1: return 0
bt = barrett(m)
r = 1; y = safe_mod(x, m)
while n:
if n & 1: r = bt.mul(r, y)
y = bt.mul(y, y)
n >>= 1
return n
def inv_mod(x: int, m: int) -> int:
assert 1 <= m
z = inv_gcd(x, m)
assert z[0] == 1
return z[1]
def crt(r: list, m: list) -> tuple:
assert len(r) == len(m)
n = len(r)
r0 = 0; m0 = 1
for i in range(n):
assert 1 <= m[i]
r1 = safe_mod(r[i], m[i]); m1 = m[i]
if m0 < m1:
r0, r1 = r1, r0
m0, m1 = m1, m0
if m0 % m1 == 0:
if r0 % m1 != r1: return (0, 0)
continue
g, im = inv_gcd(m0, m1)
u1 = m1 // g
if (r1 - r0) % g: return (0, 0)
x = (r1 - r0) // g % u1 * im % u1
r0 += x * m0
m0 *= u1
if r0 < 0: r0 += m0
return (r0, m0)
def floor_sum(n: int, m: int, a: int, b: int) -> int:
ans = 0
if a >= m:
ans += (n - 1) * n * (a // m) // 2
a %= m
if b >= m:
ans += n * (b // m)
bb %= m
y_max = (a * n + b) // m; x_max = (y_max * m - b)
if y_max == 0: return ans
ans += (n - (x_max + a - 1) // a) * y_max
ans += floor_sum(y_max, a, m, (a - x_max % a) % a)
return ans
# maxflow.py
# from collections import deque
class mf_graph:
numeric_limits_max = 10 ** 18
def __init__(self, n: int):
self._n = n
self.g = [[] for _ in range(self._n)]
self.pos = []
def add_edge(self, _from: int, _to: int, cap: int) -> int:
assert 0 <= _from and _from < self._n
assert 0 <= _to and _to < self._n
assert 0 <= cap
m = len(self.pos)
self.pos.append((_from, len(self.g[_from])))
self.g[_from].append(self._edge(_to, len(self.g[_to]), cap))
self.g[_to].append(self._edge(_from, len(self.g[_from]) - 1, 0))
return m
class edge:
def __init__(s, _from: int, _to: int, cap: int, flow: int):
s._from = _from; s._to = _to; s.cap = cap; s.flow = flow
def get_edge(self, i: int) -> edge:
m = len(self.pos)
assert 0 <= i and i < m
_e = self.g[self.pos[i][0]][self.pos[i][1]]
_re = self.g[_e.to][_e.rev]
return self.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap)
def edges(self) -> list:
m = len(self.pos)
result = [self.get_edge(i) for i in range(m)]
return result
def change_edge(self, i: int, new_cap: int, new_flow: int):
m = len(self.pos)
assert 0 <= i and i < m
assert 0 <= new_flow and new_flow <= new_cap
_e = self.g[self.pos[i][0]][self.pos[i][1]]
_re = self.g[_e.to][_e.rev]
_e.cap = new_cap - new_flow
_re.cap = new_flow
def flow(self, s: int, t: int):
return self.flow_(s, t, self.numeric_limits_max)
def flow_(self, s: int, t: int, flow_limit: int) -> int:
assert 0 <= s and s < self._n
assert 0 <= t and t < self._n
level = [0] * self._n; it = [0] * self._n
def bfs():
for i in range(self._n): level[i] = -1
level[s] = 0
que = deque([s])
while que:
v = que.popleft()
for e in self.g[v]:
if e.cap == 0 or level[e.to] >= 0: continue
level[e.to] = level[v] + 1
if e.to == t: return
que.append(e.to)
def dfs(self_, v: int, up: int) -> int:
if v == s: return up
res = 0
level_v = level[v]
for i in range(it[v], len(self.g[v])):
it[v] = i
e = self.g[v][i]
if level_v <= level[e.to] or self.g[e.to][e.rev].cap == 0: continue
d = self_(self_, e.to, min(up - res, self.g[e.to][e.rev].cap))
if d <= 0: continue
self.g[v][i].cap += d
self.g[e.to][e.rev].cap -= d
res += d
if res == up: break
return res
flow = 0
while flow < flow_limit:
bfs()
if level[t] == -1: break
for i in range(self._n): it[i] = 0
while flow < flow_limit:
f = dfs(dfs, t, flow_limit - flow)
if not f: break
flow += f
return flow
def min_cut(self, s: int) -> list:
visited = [False] * self._n
que = deque([s])
while que:
p = que.popleft()
visited[p] = True
for e in self.g[p]:
if e.cap and not visited[e.to]:
visited[e.to] = True
que.append(e.to)
return visited
class _edge:
def __init__(s, to: int, rev: int, cap: int):
s.to = to; s.rev = rev; s.cap = cap
# mincostflow.py
# from heapq import heappop, heappush
class mcf_graph:
numeric_limits_max = 10 ** 18
def __init__(self, n: int):
self._n = n
self.g = [[] for _ in range(n)]
self.pos = []
def add_edge(self, _from: int, _to: int, cap: int, cost: int) -> int:
assert 0 <= _from and _from < self._n
assert 0 <= _to and _to < self._n
m = len(self.pos)
self.pos.append((_from, len(self.g[_from])))
self.g[_from].append(self._edge(_to, len(self.g[_to]), cap, cost))
self.g[_to].append(self._edge(_from, len(self.g[_from]) - 1, 0, -cost))
return m
class edge:
def __init__(s, _from: int, _to: int, cap: int, flow: int, cost: int):
s._from = _from; s._to = _to; s.cap = cap; s.flow = flow; s.cost = cost
def get_edge(self, i: int) -> edge:
m = len(self.pos)
assert 0 <= i and i < m
_e = self.g[self.pos[i][0]][self.pos[i][1]]
_re = self.g[_e.to][_e.rev]
return self.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)
def edges(self) -> list:
m = len(self.pos)
result = [self.get_edge(i) for i in range(m)]
return result
def flow(self, s: int, t: int) -> edge:
return self.flow_(s, t, self.numeric_limits_max)
def flow_(self, s: int, t: int, flow_limit: int) -> edge:
return self.__slope(s, t, flow_limit)[-1]
def slope(self, s: int, t: int) -> list:
return self.slope_(s, t, self.numeric_limits_max)
def slope_(self, s: int, t: int, flow_limit: int) -> list:
return self.__slope(s, t, flow_limit)
def __slope(self, s: int, t: int, flow_limit: int) -> list:
assert 0 <= s and s < self._n
assert 0 <= t and t < self._n
assert s != t
dual = [0] * self._n; dist = [0] * self._n
pv, pe = [-1] * self._n, [-1] * self._n
vis = [False] * self._n
def dual_ref():
for i in range(self._n):
dist[i] = self.numeric_limits_max
pv[i] = -1
pe[i] = -1
vis[i] = False
class Q:
def __init__(s, key: int, to: int):
s.key = key; s.to = to
def __lt__(s, r): return s.key < r.key
que = []
dist[s] = 0
heappush(que, Q(0, s))
while que:
v = heappop(que).to
if vis[v]: continue
vis[v] = True
if v == t: break
for i in range(len(self.g[v])):
e = self.g[v][i]
if vis[e.to] or not e.cap: continue
cost = e.cost - dual[e.to] + dual[v]
if dist[e.to] - dist[v] > cost:
dist[e.to] = dist[v] + cost
pv[e.to] = v
pe[e.to] = i
heappush(que, Q(dist[e.to], e.to))
if not vis[t]: return False
for v in range(self._n):
if not vis[v]: continue
dual[v] -= dist[t] - dist[v]
return True
flow = 0
cost = 0; prev_cost = -1
result = []
result.append((flow, cost))
while flow < flow_limit:
if not dual_ref(): break
c = flow_limit - flow
v = t
while v != s:
c = min(c, self.g[pv[v]][pe[v]].cap)
v = pv[v]
v = t
while v != s:
e = self.g[pv[v]][pe[v]]
e.cap -= c
self.g[v][e.rev].cap += c
v = pv[v]
d = -dual[s]
flow += c
cost += c * d
if prev_cost == d:
result.pop()
result.append((flow, cost))
prev_cost = cost
return result
class _edge:
def __init__(s, to: int, rev: int, cap: int, cost: int):
s.to = to; s.rev = rev; s.cap = cap; s.cost = cost
# modint.py
class Mint:
modint1000000007 = 1000000007
modint998244353 = 998244353
def __init__(self, v: int = 0):
self.m = self.modint1000000007
# self.m = self.modint998244353
self.x = v % self.__umod()
def inv(self):
if is_prime_constexpr(self.__umod()):
assert self.x
return self.pow_(self.__umod() - 2)
else:
eg = inv_gcd(self.x, self.m)
assert eg[0] == 1
return eg[2]
def __str__(self): return str(self.x)
def __le__(self, other): return self.x <= Mint.__get_val(other)
def __lt__(self, other): return self.x < Mint.__get_val(other)
def __ge__(self, other): return self.x >= Mint.__get_val(other)
def __gt(self, other): return self.x > Mint.__get_val(other)
def __eq__(self, other): return self.x == Mint.__get_val(other)
def __iadd__(self, other):
self.x += Mint.__get_val(other)
if self.x >= self.__umod(): self.x -= self.__umod()
return self
def __add__(self, other):
_v = Mint(self.x); _v += other
return _v
def __isub__(self, other):
self.x -= Mint.__get_val(other)
if self.x >= self.__umod(): self.x += self.__umod()
return self
def __sub__(self, other):
_v = Mint(self.x); _v -= other
return _v
def __rsub__(self, other):
_v = Mint(Mint.__get_val(other)); _v -= self
return _v
def __imul__(self, other):
self.x =self.x * Mint.__get_val(other) % self.__umod()
return self
def __mul__(self, other):
_v = Mint(self.x); _v *= other
return _v
def __itruediv__(self, other):
self.x = self.x / Mint.__get_val(other) % self.__umod()
return self
def __truediv__(self, other):
_v = Mint(self.x); _v /= other
return _v
def __rtruediv__(self, other):
_v = Mint(Mint.__get_val(other)); _v /= self
return _v
def __ifloordiv__(self, other):
other = other if isinstance(other, Mint) else Mint(other)
self *= other.inv()
return self
def __floordiv__(self, other):
_v = Mint(self.x); _v //= other
return _v
def __rfloordiv__(self, other):
_v = Mint(Mint.__get_val(other)); _v //= self
return _v
def __pow__(self, other):
_v = Mint(pow(self.x, Mint.__get_val(other), self.__umod()))
return _v
def __rpow__(self, other):
_v = Mint(pow(Mint.__get_val(other), self.x, self.__umod()))
return _v
def __imod__(self, other):
self.x %= Mint.__get_val(other)
return self
def __mod__(self, other):
_v = Mint(self.x); _v %= other
return _v
def __rmod__(self, other):
_v = Mint(Mint.__get_val(other)); _v %= self
return _v
def __ilshift__(self, other):
self.x <<= Mint.__get_val(other)
return self
def __irshift__(self, other):
self.x >>= Mint.__get_val(other)
return self
def __lshift__(self, other):
_v = Mint(self.x); _v <<= other
return _v
def __rshift__(self, other):
_v = Mint(self.x); _v >>= other
return _v
def __rlshift__(self, other):
_v = Mint(Mint.__get_val(other)); _v <<= self
return _v
def __rrshift__(self, other):
_v = Mint(Mint.__get_val(other)); _v >>= self
return _v
__repr__ = __str__
__radd__ = __add__
__rmul__ = __mul__
def __umod(self): return self.m
@staticmethod
def __get_val(val): return val.x if isinstance(val, Mint) else val
def pow_(self, n: int):
assert 0 <= n
x = Mint(self.x); r = 1
while n:
if n & 1: r *= x
x *= x
n >>= 1
return r
def val(self): return self.x
def mod(self): return self.m
def raw(self, v):
x = Mint()
x.x = v
return x
# scc.py
class scc_graph_sub:
# public
def __init__(self, n):
self.internal = scc_graph(n)
def add_edge(self, _from, _to):
n = self.internal.num_vertices()
assert 0 <= _from and _from < n
assert 0 <= _to and _to < n
self.internal.add_edge(_from, _to)
def scc(self): return self.internal.scc()
# segtree.py
'''
def e(): return
def op(l, r): return
def f(): return
'''
class segtree:
def __init__(self, op, e, v: list):
self._n = len(v)
self.log = ceil_pow2(self._n)
self.size = 1 << self.log
self.op = op; self.e = e
self.d = [self.e()] * (self.size * 2)
for i in range(self._n): self.d[self.size + i] = v[i]
for i in range(self.size - 1, 0, -1): self.__update(i)
def set_(self, p: int, x: int):
assert 0 <= p and p < self._n
p += self.size
self.d[p] = x
for i in range(1, self.log + 1): self.__update(p >> i)
def get(self, p: int):
assert 0 <= p and p < self._n
return self.d[p + self.size]
def prod(self, l: int, r: int):
assert 0 <= l and l <= r and r <= self._n
l += self.size; r += self.size
sml, smr = self.e(), self.e()
while l < r:
if l & 1: sml = self.op(sml, self.d[l]); l += 1
if r & 1: r -= 1; smr = self.op(self.d[r], smr)
l >>= 1; r >>= 1
return self.op(sml, smr)
def all_prod(self): return self.d[1]
def max_right(self, l: int, f):
assert 0 <= l and l <= self._n
assert f(self.e())
if l == self._n: return self._n
l += self.size
sm = self.e()
while True:
while l % 2 == 0: l >>= 1
if not f(self.op(sm, self.d[l])):
while l < self.size:
l = 2 * l
if f(self.op(sm, self.d[l])):
sm = self.op(sm, self.d[l])
l += 1
return l - self.size
sm = self.op(sm, self.d[l])
l += 1
if (l & -l) == l: break
return self._n
def min_left(self, r: int, f):
assert 0 <= r and r <= self._n
assert f(self.e())
if r == 0: return 0
r += self.size
sm = self.e()
while True:
r -= 1
while r > 1 and r % 2: r >>= 1
if not f(self.op(self.d[r], sm)):
while r < self.size:
r = 2 * r + 1
if f(self.op(self.d[r], sm)):
sm = self.op(self.d[r], sm)
r -= 1
return r + 1 - self.size
sm = self.op(self.d[r], sm)
if (r & -r) == r: break
return 0
def __update(self, k: int): self.d[k] = self.op(self.d[k * 2], self.d[k * 2 + 1])
# string.py
def sa_native(s: list):
from functools import cmp_to_key
def mycmp(r, l):
if l == r: return -1
while l < n and r < n:
if s[l] != s[r]: return 1 if s[l] < s[r] else -1
l += 1
r += 1
return 1 if l == n else -1
n = len(s)
sa = [i for i in range(n)]
sa.sort(key=cmp_to_key(mycmp))
return sa
def sa_doubling(s: list):
from functools import cmp_to_key
def mycmp(y, x):
if rnk[x] != rnk[y]: return 1 if rnk[x] < rnk[y] else -1
rx = rnk[x + k] if x + k < n else - 1
ry = rnk[y + k] if y + k < n else - 1
return 1 if rx < ry else -1
n = len(s)
sa = [i for i in range(n)]; rnk = s; tmp = [0] * n; k = 1
while k < n:
sa.sort(key=cmp_to_key(mycmp))
tmp[sa[0]] = 0
for i in range(1, n):
tmp[sa[i]] = tmp[sa[i - 1]]
if mycmp(sa[i], sa[i - 1]): tmp[sa[i]] += 1
tmp, rnk = rnk, tmp
k *= 2
return sa
def sa_is(s: list, upper: int):
THRESHOLD_NATIVE = 10
THRESHOLD_DOUBLING = 40
n = len(s)
if n == 0: return []
if n == 1: return [0]
if n == 2:
if s[0] < s[1]:
return [0, 1]
else:
return [1, 0]
if n < THRESHOLD_NATIVE:
return sa_native(s)
if n < THRESHOLD_DOUBLING:
return sa_doubling(s)
sa = [0] * n
ls = [False] * n
for i in range(n - 2, -1, -1):
ls[i] = ls[i + 1] if s[i] == s[i + 1] else s[i] < s[i + 1]
sum_l = [0] * (upper + 1); sum_s = [0] * (upper + 1)
for i in range(n):
if not ls[i]:
sum_s[s[i]] += 1
else:
sum_l[s[i] + 1] += 1
for i in range(upper + 1):
sum_s[i] += sum_l[i]
if i < upper: sum_l[i + 1] += sum_s[i]
def induce(lms: list):
from copy import copy
for i in range(n): sa[i] = -1
buf = copy(sum_s)
for d in lms:
if d == n: continue
sa[buf[s[d]]] = d; buf[s[d]] += 1
buf = copy(sum_l)
sa[buf[s[n - 1]]] = n - 1; buf[s[n - 1]] += 1
for i in range(n):
v = sa[i]
if v >= 1 and not ls[v - 1]:
sa[buf[s[v - 1]]] = v - 1; buf[s[v - 1]] += 1
buf = copy(sum_l)
for i in range(n - 1, -1, -1):
v = sa[i]
if v >= 1 and ls[v - 1]:
buf[s[v - 1] + 1] -= 1; sa[buf[s[v - 1] + 1]] = v - 1
lms_map = [-1] * (n + 1)
m = 0
for i in range(1, n):
if not ls[i - 1] and ls[i]:
lms_map[i] = m; m += 1
lms = [i for i in range(1, n) if not ls[i - 1] and ls[i]]
induce(lms)
if m:
sorted_lms = [v for v in sa if lms_map[v] != -1]
rec_s = [0] * m
rec_upper = 0
rec_s[lms_map[sorted_lms[0]]] = 0
for i in range(1, m):
l = sorted_lms[i - 1]; r = sorted_lms[i]
end_l = lms[lms_map[l] + 1] if lms_map[l] + 1 < m else n
end_r = lms[lms_map[r] + 1] if lms_map[r] + 1 < m else n
same = True
if end_l - l != end_r - r:
same = False
else:
while l < end_l:
if s[l] != s[r]: break
l += 1
r += 1
if l == n or s[l] != s[r]: same = False
if not same: rec_upper += 1
rec_s[lms_map[sorted_lms[i]]] = rec_upper
rec_sa = sa_is(rec_s, rec_upper)
for i in range(m):
sorted_lms[i] = lms[rec_sa[i]]
induce(sorted_lms)
return sa
def suffix_array(s: list, upper: int):
assert 0 <= upper
for d in s:
assert 0 <= d and d <= upper
sa = sa_is(s, upper)
return sa
def suffix_array2(s: list):
from functools import cmp_to_key
n = len(s)
idx = [i for i in range(n)]
idx.sort(key=cmp_to_key(lambda l, r: s[l] < s[r]))
s2 = [0] * n
now = 0
for i in range(n):
if i and s[idx[i - 1]] != s[idx[i]]: now += 1
s2[idx[i]] = now
return sa_is(s2, now)
def suffix_array3(s: str):
n = len(s)
s2 = list(map(ord, s))
return sa_is(s2, 255)
def lcp_array(s: list, sa: list):
n = len(s)
assert n >= 1
rnk = [0] * n
for i in range(n):
rnk[sa[i]] = i
lcp = [0] * (n - 1)
h = 0
for i in range(n):
if h > 0: h -= 1
if rnk[i] == 0: continue
j = sa[rnk[i] - 1]
while j + h < n and i + h < n:
if s[j + h] != s[i + h]: break
h += 1
lcp[rnk[i] - 1] = h
return lcp
def lcp_array2(s: str, sa: list):
n = len(s)
s2 = list(map(ord, s))
return lcp_array(s2, sa)
def z_algorithm(s: list):
n = len(s)
if n == 0: return []
z = [-1] * n
z[0] = 0; j = 0
for i in range(1, n):
k = z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j])
while i + k < n and s[k] == s[i + k]: k += 1
z[i] = k
if j + z[j] < i + z[i]: j = i
z[0] = n
return z
def z_algorithm2(s: str):
n = len(s)
s2 = list(map(ord, s))
return z_algorithm(s2)
# twosat.py
class two_sat:
def __init__(self, n: int):
self._n = n
self.scc = scc_graph(2 * n)
self._answer = [False] * n
def add_clause(self, i: int, f: bool, j: int, g: bool):
assert 0 <= i and i < self._n
assert 0 <= j and j < self._n
self.scc.add_edge(2 * i + (not f), 2 * j + g)
self.scc.add_edge(2 * j + (not g), 2 * i + f)
def satisfiable(self) -> bool:
_id = self.scc.scc_ids()[1]
for i in range(self._n):
if _id[2 * i] == _id[2 * i + 1]: return False
self._answer[i] = _id[2 * i] < _id[2 * i + 1]
return True
def answer(self): return self._answer
# --------------------<< Library End >>-------------------- #
import sys
sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
INF = 10 ** 9
PI = 3.14159265358979323846
def read_str(): return sys.stdin.readline().strip()
def read_int(): return int(sys.stdin.readline().strip())
def read_ints(): return map(int, sys.stdin.readline().strip().split())
def read_ints2(x): return map(lambda num: int(num) - x, sys.stdin.readline().strip().split())
def read_str_list(): return list(sys.stdin.readline().strip().split())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))
def GCD(a: int, b: int) -> int: return b if a%b==0 else GCD(b, a%b)
def LCM(a: int, b: int) -> int: return (a * b) // GCD(a, b)
def Main_A():
n, q = read_ints()
d = dsu(n)
for _ in range(q):
t, u, v = read_ints()
if t == 0:
d.merge(u, v)
else:
print(int(d.same(u, v)))
def Main_B():
n, q = read_ints()
a = read_int_list()
fw = fenwick_tree(n)
for i, x in enumerate(a):
fw.add(i, x)
for _ in range(q):
query = read_int_list()
if query[0] == 0:
fw.add(query[1], query[2])
else:
print(fw.sum(query[1], query[2]))
def Main_C():
for _ in range(read_int()):
n, m, a, b = read_ints()
print(floor_sum(n, m, a, b))
#from collections import deque
def Main_D():
n, m = read_ints()
grid = [list(read_str()) for _ in range(n)]
mf = mf_graph(n * m + 2)
start = n * m
end = start + 1
dir = [(1, 0), (0, 1)]
for y in range(n):
for x in range(m):
if (y + x) % 2 == 0:
mf.add_edge(start, m*y + x, 1)
else:
mf.add_edge(m*y + x, end, 1)
if grid[y][x] == '.':
for dy, dx in dir:
ny = y + dy; nx = x + dx
if ny < n and nx < m and grid[ny][nx] == '.':
f, t = y*m + x, ny*m + nx
if (y + x) % 2: f, t = t, f
mf.add_edge(f, t, 1)
ans = mf.flow(start, end)
for y in range(n):
for x in range(m):
for e in mf.g[y * m + x]:
to, rev, cap = e.to, e.rev, e.cap
ny, nx = divmod(to, m)
if (y + x) % 2 == 0 and cap == 0 and to != start and to != end and (y*m+x) != start and (y*m+x) != end:
if y + 1 == ny: grid[y][x] = 'v'; grid[ny][nx] = '^'
elif y == ny + 1: grid[y][x] = '^'; grid[ny][nx] = 'v'
elif x + 1 == nx: grid[y][x] = '>'; grid[ny][nx] = '<'
elif x == nx + 1: grid[y][x] = '<'; grid[ny][nx] = '>'
print(ans)
print(*[''.join(ret) for ret in grid], sep='\n')
#from heapq import heappop, heappush
def Main_E():
n, k = read_ints()
a = [read_int_list() for _ in range(n)]
mcf = mcf_graph(n * 2 + 2)
s = n * 2
t = n * 2 + 1
for i in range(n):
mcf.add_edge(s, i, k, 0)
mcf.add_edge(i + n, t, k, 0)
mcf.add_edge(s, t, n * k, INF)
for i in range(n):
for j in range(n):
mcf.add_edge(i, n + j, 1, INF - a[i][j])
result = mcf.flow_(s, t, n * k)
print(n * k * INF - result[1])
grid = [['.'] * n for _ in range(n)]
edges = mcf.edges()
for e in edges:
if e._from == s or e._to == t or e.flow == 0: continue
grid[e._from][e._to - n] = 'X'
print(*[''.join(g) for g in grid], sep='\n')
def Main_F():
MOD = 998244353
n, m = read_ints()
a = read_int_list()
b = read_int_list()
a = [x % MOD for x in a]
b = [x % MOD for x in b]
cnv = convolution(a,b,MOD)
ans = cnv.convolution()
print(*ans)
def Main_G():
sys.setrecursionlimit(10 ** 6)
n, m = read_ints()
scc = scc_graph(n)
for _ in range(m):
a, b = read_ints()
scc.add_edge(a, b)
ans = scc.scc()
print(len(ans))
for v in ans:
print(len(v), ' '.join(map(str, v[::-1])))
def Main_H():
n, d = read_ints()
xy = [read_int_list() for _ in range(n)]
tw = two_sat(n)
for i in range(n):
for j in range(i + 1, n):
for x in range(2):
if abs(xy[i][0] - xy[j][0]) < d: tw.add_clause(i, False, j, False)
if abs(xy[i][0] - xy[j][1]) < d: tw.add_clause(i, False, j, True)
if abs(xy[i][1] - xy[j][0]) < d: tw.add_clause(i, True, j, False)
if abs(xy[i][1] - xy[j][1]) < d: tw.add_clause(i, True, j, True)
if not tw.satisfiable():
print('No')
exit()
print('Yes')
ans = tw.answer()
for i, flag in enumerate(ans):
print(xy[i][0] if flag else xy[i][1])
def Main_I():
s = read_str()
sa = suffix_array3(s)
ans = len(s) * (len(s) + 1) // 2
for x in lcp_array2(s, sa):
ans -= x
print(ans)
def Main_J():
def op(l, r): return max(l, r)
def e(): return -1
def f(n): return n < r
n, q = read_ints()
a = read_int_list()
seg = segtree(op, e, a)
query = [(read_ints()) for _ in range(q)]
for i in range(q):
t, l, r = query[i]
if t == 1:
seg.set_(~-l, r)
elif t == 2:
print(seg.prod(~-l, r))
else:
print(seg.max_right(~-l, f) + 1)
def Main_K():
p = 998244353
def op(l, r):
l1, l2 = l >> 32, l % (1 << 32)
r1, r2 = r >> 32, r % (1 << 32)
return (((l1 + r1) % p) << 32) + l2 + r2
def e(): return 0
def mapping(l, r):
l1, l2 = l >> 32, l % (1 << 32)
r1, r2 = r >> 32, r % (1 << 32)
return (((l1 * r1 + l2 * r2) % p) << 32) + r2
def composition(l, r):
l1, l2 = l >> 32, l % (1 << 32)
r1, r2 = r >> 32, r % (1 << 32)
return ((l1 * r1 % p) << 32) + (l1 * r2 + l2) % p
def id(): return 1 << 32
n, q = read_ints()
A = read_int_list()
A = [(x << 32) + 1 for x in A]
seg = lazy_segtree(op, e, mapping, composition, id, A)
ans = []
for _ in range(q):
query = read_int_list()
if query[0] == 0:
l, r, b, c = query[1:]
seg.apply(l, r, (b << 32) + c)
else:
l, r = query[1:]
print(seg.prod(l, r) >> 32)
def Main_L():
def op(l: tuple, r: tuple): return (l[0] + r[0], l[1] + r[1], l[2] + r[2] + l[1] * r[0])
def e(): return (0, 0, 0)
def mapping(l:bool, r: tuple):
if not l: return r
return (r[1], r[0], r[1] * r[0] - r[2])
def composition(l: bool, r: bool): return l ^ r
def id(): return False
n, q = read_ints()
A = read_int_list()
query = [(read_ints()) for _ in range(q)]
a = [(1, 0, 0) if i == 0 else (0, 1, 0) for i in A]
seg = lazy_segtree(op, e, mapping, composition, id, a)
for t, l, r in query:
if t == 1:
seg.apply(~-l, r, True)
else:
print(seg.prod(~-l, r)[2])
if __name__ == '__main__':
Main_H()
```
| 15,703 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
"Correct Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7
# Strongly connected component
# derived from https://atcoder.jp/contests/practice2/submissions/16645774
def get_strongly_connected_components(edges, num_vertex):
"""
edges: {v: [v]}
"""
from collections import defaultdict
reverse_edges = defaultdict(list)
for v1 in edges:
for v2 in edges[v1]:
reverse_edges[v2].append(v1)
terminate_order = []
done = [0] * num_vertex # 0 -> 1 -> 2
count = 0
for i0 in range(num_vertex):
if done[i0]:
continue
queue = [~i0, i0]
# dfs
while queue:
i = queue.pop()
if i < 0:
if done[~i] == 2:
continue
done[~i] = 2
terminate_order.append(~i)
count += 1
continue
if i >= 0:
if done[i]:
continue
done[i] = 1
for j in edges[i]:
if done[j]:
continue
queue.append(~j)
queue.append(j)
done = [0] * num_vertex
result = []
for i0 in terminate_order[::-1]:
if done[i0]:
continue
component = []
queue = [~i0, i0]
while queue:
i = queue.pop()
if i < 0:
if done[~i] == 2:
continue
done[~i] = 2
component.append(~i)
continue
if i >= 0:
if done[i]:
continue
done[i] = 1
for j in reverse_edges[i]:
if done[j]:
continue
queue.append(~j)
queue.append(j)
result.append(component)
return result
def debug(*x):
print(*x, file=sys.stderr)
def solve(N, D, data):
# edges = [[] for i in range(N * 2)]
# edges = []
from collections import defaultdict
edges = defaultdict(list)
def add_then_edge(i, bool_i, j, bool_j):
edges[i * 2 + int(bool_i)].append(j * 2 + int(bool_j))
# edges.append((i * 2 + int(bool_i), j * 2 + int(bool_j)))
for i in range(N):
xi, yi = data[i]
for j in range(i + 1, N):
xj, yj = data[j]
if abs(xi - xj) < D:
add_then_edge(i, 0, j, 1)
add_then_edge(j, 0, i, 1)
if abs(xi - yj) < D:
add_then_edge(i, 0, j, 0)
add_then_edge(j, 1, i, 1)
if abs(yi - xj) < D:
add_then_edge(i, 1, j, 1)
add_then_edge(j, 0, i, 0)
if abs(yi - yj) < D:
add_then_edge(i, 1, j, 0)
add_then_edge(j, 1, i, 0)
scc = get_strongly_connected_components(edges, N * 2)
group_id = [0] * (2 * N)
for i, xs in enumerate(scc):
for x in xs:
group_id[x] = i
ret = [0] * N
for i in range(N):
if group_id[2 * i] == group_id[2 * i + 1]:
print("No")
return
ret[i] = (group_id[2 * i] < group_id[2 * i + 1])
print("Yes")
for i in range(N):
print(data[i][ret[i]])
def main():
# parse input
N, D = map(int, input().split())
data = []
for _i in range(N):
data.append(tuple(map(int, input().split())))
solve(N, D, data)
# tests
T1 = """
3 2
1 4
2 5
0 6
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
Yes
4
2
6
"""
T2 = """
3 3
1 4
2 5
0 6
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
No
"""
def _test():
import doctest
doctest.testmod()
g = globals()
for k in sorted(g):
if k.startswith("TEST_"):
doctest.run_docstring_examples(g[k], g, name=k)
def as_input(s):
"use in test, use given string as input file"
import io
f = io.StringIO(s.strip())
g = globals()
g["input"] = lambda: bytes(f.readline(), "ascii")
g["read"] = lambda: bytes(f.read(), "ascii")
input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
if sys.argv[-1] == "-t":
print("testing")
_test()
sys.exit()
main()
```
| 15,704 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
"Correct Solution:
```
from operator import itemgetter
from itertools import *
from bisect import *
from collections import *
from heapq import *
import sys
sys.setrecursionlimit(10**6)
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 SI(): return sys.stdin.readline()[:-1]
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
int1 = lambda x: int(x)-1
def MI1(): return map(int1, sys.stdin.readline().split())
def LI1(): return list(map(int1, sys.stdin.readline().split()))
p2D = lambda x: print(*x, sep="\n")
dij = [(1, 0), (0, 1), (-1, 0), (0, -1)]
def SCC(to, ot):
n = len(to)
def dfs(u):
for v in to[u]:
if com[v]: continue
com[v] = 1
dfs(v)
top.append(u)
top = []
com = [0]*n
for u in range(n):
if com[u]: continue
com[u] = 1
dfs(u)
def rdfs(u, k):
for v in ot[u]:
if com[v] != -1: continue
com[v] = k
rdfs(v, k)
com = [-1]*n
k = 0
for u in top[::-1]:
if com[u] != -1: continue
com[u] = k
rdfs(u, k)
k += 1
return k, com
class TwoSat:
def __init__(self, n):
# to[v][u]...頂点uの値がvのときの遷移先と反転の有無
self.n = n
self.to = [[] for _ in range(n*2)]
self.ot = [[] for _ in range(n*2)]
self.vals = []
# uがu_val(0 or 1)ならばvはv_val(0 or 1)
def add_edge(self, u, u_val, v, v_val):
self.to[u*2+u_val].append(v*2+v_val)
self.ot[v*2+v_val].append(u*2+u_val)
# 条件を満たすかどうかをboolで返す。構成はself.valsに入る
def satisfy(self):
k, com = SCC(self.to, self.ot)
for u in range(self.n):
if com[u*2]==com[u*2+1]:return False
self.vals.append(com[u*2]<com[u*2+1])
return True
n, d = MI()
xy = LLI(n)
ts = TwoSat(n)
for i in range(n):
x1, y1 = xy[i]
for j in range(i):
x2, y2 = xy[j]
if abs(x1-x2) < d:
ts.add_edge(i, 0, j, 1)
ts.add_edge(j, 0, i, 1)
if abs(x1-y2) < d:
ts.add_edge(i, 0, j, 0)
ts.add_edge(j, 1, i, 1)
if abs(y1-x2) < d:
ts.add_edge(i, 1, j, 1)
ts.add_edge(j, 0, i, 0)
if abs(y1-y2) < d:
ts.add_edge(i, 1, j, 0)
ts.add_edge(j, 1, i, 0)
if ts.satisfy():
print("Yes")
for j,xyi in zip(ts.vals,xy):print(xyi[j])
else:print("No")
```
| 15,705 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
"Correct Solution:
```
mod = 1000000007
eps = 10**-9
def main():
import sys
input = sys.stdin.buffer.readline
from collections import deque
# compressed[v]: 縮約後のグラフで縮約前のvが属する頂点
# num: 縮約後のグラフの頂点数
# 縮約後のグラフの頂点番号はトポロジカル順
def SCC(adj, adj_rev):
N = len(adj) - 1
seen = [0] * (N + 1)
compressed = [0] * (N + 1)
order = []
for v0 in range(1, N + 1):
if seen[v0]:
continue
st = deque()
st.append(v0)
while st:
v = st.pop()
if v < 0:
order.append(-v)
else:
if seen[v]:
continue
seen[v] = 1
st.append(-v)
for u in adj[v]:
st.append(u)
seen = [0] * (N + 1)
num = 0
for v0 in reversed(order):
if seen[v0]:
continue
num += 1
st = deque()
st.append(v0)
seen[v0] = 1
compressed[v0] = num
while st:
v = st.pop()
for u in adj_rev[v]:
if seen[u]:
continue
seen[u] = 1
compressed[u] = num
st.append(u)
return num, compressed
# 縮約後のグラフを構築
# 先にSCC()を実行してnum, compressedを作っておく
def construct(adj, num, compressed):
N = len(adj) - 1
adj_compressed = [set() for _ in range(num + 1)]
for v in range(1, N + 1):
v_cmp = compressed[v]
for u in adj[v]:
u_cmp = compressed[u]
if v_cmp != u_cmp:
adj_compressed[v_cmp].add(u_cmp)
return adj_compressed
class TwoSat:
def __init__(self, N):
self.N = N
self.adj = [[] for _ in range(2 * N + 1)]
self.adj_rev = [[] for _ in range(2 * N + 1)]
self.compressed = None
# (a == a_bool) or (b = b_bool)というクローズを追加
# a, b は1-indexed
def add_clause(self, a, a_bool, b, b_bool):
if not a_bool:
a += self.N
if not b_bool:
b += self.N
if a <= self.N:
self.adj[a + self.N].append(b)
self.adj_rev[b].append(a + self.N)
else:
self.adj[a - self.N].append(b)
self.adj_rev[b].append(a - self.N)
if b <= self.N:
self.adj[b + self.N].append(a)
self.adj_rev[a].append(b + self.N)
else:
self.adj[b - self.N].append(a)
self.adj_rev[a].append(b - self.N)
def satisfiable(self):
_, self.compressed = SCC(self.adj, self.adj_rev)
for i in range(1, self.N + 1):
if self.compressed[i] == self.compressed[i + self.N]:
return False
return True
# 直前に読んだsatisfiableの割り当てを返す
# 長さN+1のbool値の配列を返す
def answer(self):
assert self.compressed is not None
ret = [True] * (self.N + 1)
for i in range(1, self.N + 1):
if self.compressed[i] < self.compressed[i + self.N]:
ret[i] = False
return ret
N, D = map(int, input().split())
X = []
Y = []
for _ in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
TS = TwoSat(N)
for i in range(N):
for j in range(i+1, N):
if abs(X[i] - X[j]) < D:
TS.add_clause(i+1, 0, j+1, 0)
if abs(X[i] - Y[j]) < D:
TS.add_clause(i+1, 0, j+1, 1)
if abs(Y[i] - X[j]) < D:
TS.add_clause(i+1, 1, j+1, 0)
if abs(Y[i] - Y[j]) < D:
TS.add_clause(i+1, 1, j+1, 1)
ok = TS.satisfiable()
if not ok:
print("No")
else:
print("Yes")
ans = TS.answer()
for i in range(N):
if ans[i+1]:
print(X[i])
else:
print(Y[i])
if __name__ == '__main__':
main()
```
| 15,706 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
Submitted Solution:
```
class csr:
def __init__(self, n: int, edges: list):
self.start = [0] * (n + 1)
self.elist = [0] * len(edges)
for e in edges:
self.start[e[0] + 1] += 1
for i in range(1, n + 1):
self.start[i] += self.start[i - 1]
counter = self.start[::]
for e in edges:
self.elist[counter[e[0]]] = e[1]
counter[e[0]] += 1
class internal_scc_graph:
def __init__(self, n: int = 0):
self.__n = n
self.__edges = []
def num_vertices(self):
return self.__n
def add_edge(self, from_: int, to: int):
self.__edges.append([from_, to])
def scc_ids(self):
g = csr(self.__n, self.__edges)
now_ord = 0
group_num = 0
visited = []
low = [0] * self.__n
ord = [-1] * self.__n
ids = [0] * self.__n
parent = [-1] * self.__n
for root in range(self.__n):
if(ord[root] == -1):
stack = []
stack.extend([root] * 2)
while(stack):
v = stack.pop()
if(ord[v] == -1):
visited.append(v)
low[v] = now_ord
ord[v] = now_ord
now_ord += 1
for i in range(g.start[v], g.start[v + 1]):
to = g.elist[i]
if(ord[to] == -1):
stack.extend([to] * 2)
parent[to] = v
else:
low[v] = min(low[v], ord[to])
else:
if(low[v] == ord[v]):
while(True):
u = visited.pop()
ord[u] = self.__n
ids[u] = group_num
if(u == v):
break
group_num += 1
if(parent[v] != -1):
low[parent[v]] = min(low[parent[v]], low[v])
for i, x in enumerate(ids):
ids[i] = group_num - 1 - x
return [group_num, ids]
class two_sat:
def __init__(self, n: int = 0):
self.__n = n
self.__answer = [0] * n
self.__scc = internal_scc_graph(2 * n)
def add_clause(self, i: int, f: bool, j: int, g: bool):
assert (0 <= i) & (i < self.__n)
assert (0 <= j) & (j < self.__n)
self.__scc.add_edge(2 * i + (1 - f), 2 * j + g)
self.__scc.add_edge(2 * j + (1 - g), 2 * i + f)
def satisfiable(self):
id = self.__scc.scc_ids()[1]
for i in range(self.__n):
if(id[2 * i] == id[2 * i + 1]):
return False
self.__answer[i] = (id[2 * i] < id[2 * i + 1])
return True
def answer(self):
return self.__answer
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n,d = map(int,readline().split())
xy = [list(map(int, i.split())) for i in readlines()]
ts = two_sat(n)
for i in range(n-1):
for j in range(i+1,n):
for ii,jj in zip([0,0,1,1],[0,1,0,1]):
if(abs(xy[i][ii] - xy[j][jj]) < d):
ts.add_clause(i, 1-ii, j, 1-jj)
if(ts.satisfiable()):
print('Yes')
else:
print('No')
exit()
ans = []
for i,tf in enumerate(ts.answer()):
ans.append(xy[i][tf])
print('\n'.join(map(str,ans)))
```
Yes
| 15,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**7)
class SCC:
def __init__(self,N):
self.N = N
self.graph = [[] for _ in range(N)]
self.graph_rev = [[] for _ in range(N)]
self.flag = [False]*N
def add_edge(self,start,end):
if start == end:
return
self.graph[start].append(end)
self.graph_rev[end].append(start)
def dfs(self,node,graph):
self.flag[node] = True
for n in graph[node]:
if self.flag[n]:
continue
self.dfs(n,graph)
self.order.append(node)
def first_dfs(self):
self.flag = [False]*self.N
self.order = []
for i in range(self.N):
if self.flag[i] == False:
self.dfs(i,self.graph)
def second_dfs(self):
self.flag = [False]*self.N
self.ans = []
for n in reversed(self.order):
if self.flag[n]:
continue
self.flag[n] = True
self.order = []
self.dfs(n,self.graph_rev)
self.order.reverse()
self.ans.append(self.order)
def scc(self):
self.first_dfs()
self.second_dfs()
return self.ans
class Two_SAT():
def __init__(self,N):
self.N = N
self.e = [[] for _ in range(2*N)]
def add_condition(self,start,bool_start,end,bool_end): # start or end という条件を考える
self.e[start*2+(bool_start^1)].append(end*2+bool_end)
self.e[end*2+(bool_end^1)].append(start*2+bool_start)
def satisfiable(self):
scc = SCC(2*self.N)
for i in range(2*self.N):
for j in self.e[i]:
scc.add_edge(i,j)
C = scc.scc()
I = [0]*(2*self.N)
for i in range(len(C)):
for j in C[i]:
I[j] = i
res = [0]*(2*self.N)
for i in range(self.N):
if I[2*i] == I[2*i+1]:
return (False,res)
if I[2*i] < I[2*i+1]:
res[i] = 1
return (True,res)
def MI(): return map(int,sys.stdin.readline().rstrip().split())
N,D = MI()
TS = Two_SAT(N)
XY = [tuple(MI()) for _ in range(N)]
for i in range(N-1):
x1,y1 = XY[i]
for j in range(i+1,N):
x2,y2 = XY[j]
if abs(x1-x2) < D:
TS.add_condition(i,1,j,1)
if abs(x1-y2) < D:
TS.add_condition(i,1,j,0)
if abs(y1-x2) < D:
TS.add_condition(i,0,j,1)
if abs(y1-y2) < D:
TS.add_condition(i,0,j,0)
# 0:X,1:Y
bl,sa = TS.satisfiable()
if not bl:
print('No')
else:
print('Yes')
print(*[XY[i][sa[i]] for i in range(N)],sep='\n')
```
Yes
| 15,708 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
Submitted Solution:
```
N,D = map(int,input().split())
XY = [tuple(map(int,input().split())) for i in range(N)]
import sys
sys.setrecursionlimit(10**8)
class Scc:
def __init__(self,n):
self.n = n
self.edges = []
def add_edge(self,fr,to):
assert 0 <= fr < self.n
assert 0 <= to < self.n
self.edges.append((fr, to))
def scc(self):
csr_start = [0] * (self.n + 1)
csr_elist = [0] * len(self.edges)
for fr,to in self.edges:
csr_start[fr + 1] += 1
for i in range(1,self.n+1):
csr_start[i] += csr_start[i-1]
counter = csr_start[:]
for fr,to in self.edges:
csr_elist[counter[fr]] = to
counter[fr] += 1
self.now_ord = self.group_num = 0
self.visited = []
self.low = [0] * self.n
self.ord = [-1] * self.n
self.ids = [0] * self.n
def _dfs(v):
self.low[v] = self.ord[v] = self.now_ord
self.now_ord += 1
self.visited.append(v)
for i in range(csr_start[v], csr_start[v+1]):
to = csr_elist[i]
if self.ord[to] == -1:
_dfs(to)
self.low[v] = min(self.low[v], self.low[to])
else:
self.low[v] = min(self.low[v], self.ord[to])
if self.low[v] == self.ord[v]:
while 1:
u = self.visited.pop()
self.ord[u] = self.n
self.ids[u] = self.group_num
if u==v: break
self.group_num += 1
for i in range(self.n):
if self.ord[i] == -1: _dfs(i)
for i in range(self.n):
self.ids[i] = self.group_num - 1 - self.ids[i]
groups = [[] for _ in range(self.group_num)]
for i in range(self.n):
groups[self.ids[i]].append(i)
return groups
class TwoSat:
def __init__(self,n=0):
self.n = n
self.answer = []
self.scc = Scc(2*n)
def add_clause(self, i:int, f:bool, j:int, g:bool):
assert 0 <= i < self.n
assert 0 <= j < self.n
self.scc.add_edge(2*i + (not f), 2*j + g)
self.scc.add_edge(2*j + (not g), 2*i + f)
def satisfiable(self):
g = self.scc.scc()
for i in range(self.n):
if self.scc.ids[2*i] == self.scc.ids[2*i+1]: return False
self.answer.append(self.scc.ids[2*i] < self.scc.ids[2*i+1])
return True
def get_answer(self):
return self.answer
ts = TwoSat(N)
for i in range(N-1):
xi,yi = XY[i]
for j in range(i+1,N):
xj,yj = XY[j]
if abs(xi - xj) < D:
ts.add_clause(i, False, j, False)
if abs(xi - yj) < D:
ts.add_clause(i, False, j, True)
if abs(yi - xj) < D:
ts.add_clause(i, True, j, False)
if abs(yi - yj) < D:
ts.add_clause(i, True, j, True)
if not ts.satisfiable():
print('No')
exit()
print('Yes')
ans = []
for b,(x,y) in zip(ts.get_answer(), XY):
if b:
ans.append(x)
else:
ans.append(y)
print(*ans, sep='\n')
```
Yes
| 15,709 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
class StronglyConnectedComponets:
def __init__(self, n: int) -> None:
self.n = n
self.edges = [[] for _ in range(n)]
self.rev_edeges = [[] for _ in range(n)]
self.vs = []
self.order = [0] * n
self.used = [False] * n
def add_edge(self, from_v: int, to_v: int) -> None:
self.edges[from_v].append(to_v)
self.rev_edeges[to_v].append(from_v)
def dfs(self, v: int) -> None:
self.used[v] = True
for child in self.edges[v]:
if not self.used[child]:
self.dfs(child)
self.vs.append(v)
def rdfs(self, v: int, k: int) -> None:
self.used[v] = True
self.order[v] = k
for child in self.rev_edeges[v]:
if not self.used[child]:
self.rdfs(child, k)
def run(self) -> int:
self.used = [False] * self.n
self.vs.clear()
for v in range(self.n):
if not self.used[v]:
self.dfs(v)
self.used = [False] * self.n
k = 0
for v in reversed(self.vs):
if not self.used[v]:
self.rdfs(v, k)
k += 1
return k
class TwoSat(StronglyConnectedComponets):
def __init__(self, num_var: int) -> None:
super().__init__(2 * num_var + 1)
self.num_var = num_var
self.ans = []
def add_constraint(self, a: int, b: int) -> None:
super().add_edge(self._neg(a), self._pos(b))
super().add_edge(self._neg(b), self._pos(a))
def _pos(self, v: int) -> int:
return v if v > 0 else self.num_var - v
def _neg(self, v: int) -> int:
return self.num_var + v if v > 0 else -v
def run(self) -> bool:
super().run()
self.ans.clear()
for i in range(self.num_var):
if self.order[i + 1] == self.order[i + self.num_var + 1]:
return False
self.ans.append(self.order[i + 1] > self.order[i + self.num_var + 1])
return True
def main() -> None:
N, D = map(int, input().split())
flags = [tuple(int(x) for x in input().split()) for _ in range(N)]
# (X_i, Y_i) -> (i, -i) (i=1, ..., N) と考える
sat = TwoSat(N)
# 節 a, b の距離が D 以下の場合,
# a -> -b つまり -a or -b が成立しなければならない
for i, (x_i, y_i) in enumerate(flags, 1):
for j, (x_j, y_j) in enumerate(flags[i:], i+1):
if abs(x_i - x_j) < D:
sat.add_constraint(-i, -j)
if abs(y_i - x_j) < D:
sat.add_constraint(i, -j)
if abs(x_i - y_j) < D:
sat.add_constraint(-i, j)
if abs(y_i - y_j) < D:
sat.add_constraint(i, j)
if sat.run():
print("Yes")
print(*[x_i if sat.ans[i] else y_i for i, (x_i, y_i) in enumerate(flags)], sep="\n")
else:
print("No")
if __name__ == "__main__":
main()
```
Yes
| 15,710 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
Submitted Solution:
```
import networkx as nx
import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, D = [int(x) for x in input().split()]
XY = [[int(x) for x in input().split()] for i in range(N)]
graph = nx.DiGraph()
# a_i = 0 means choose x, a_i = 1 means choose y
# Store i for a_i==0 and i+N for a_i==1
for i, (x1, y1) in enumerate(XY):
for j in range(N):
if i != j:
x2, y2 = XY[j]
if abs(x1 - x2) < D:
# a_i==0 => a_j==1
graph.add_edge(i, j + N)
if abs(x1 - y2) < D:
# a_i==0 => a_j==0
graph.add_edge(i, j)
if abs(y1 - x2) < D:
# a_i==1 => a_j==1
graph.add_edge(i + N, j + N)
if abs(y1 - y2) < D:
# a_i==1 => a_j==0
graph.add_edge(i + N, j)
SCC = nx.algorithms.components.strongly_connected_components(graph)
assignment = {}
for comp in SCC:
for x in comp:
if (x < N and x + N in comp) or (x >= N and x - N in comp):
print("No")
exit()
if x not in assignment:
assignment[x] = True
assignment[(x + N) % (2 * N)] = False
print("Yes")
for i in range(N):
print(XY[i][0] if assignment[i] else XY[i][1])
```
No
| 15,711 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
Submitted Solution:
```
from collections import deque
class Graph(): #directed
def __init__(self, n):
self.n = n
self.graph = [set() for _ in range(n)]
self.rev = [set() for _ in range(n)]
self.deg = [0 for _ in range(n)]
def add_edge(self, p, q):
self.graph[p].add(q)
self.rev[q].add(p)
self.deg[q] += 1
def topological_sort(self):
deg = self.deg[:]
res = [i for i in range(self.n) if deg[i] == 0]
queue = deque(res)
used = [False for _ in range(self.n)]
while queue:
node = queue.popleft()
for adj in self.graph[node]:
deg[adj] -= 1
if deg[adj] == 0:
queue.append(adj)
res.append(adj)
return res
def strongry_connected(self):
group = [None for _ in range(self.n)]
used = [0 for _ in range(self.n)]
order = []
for s in range(self.n):
if not used[s]:
stack = [s]
used[s] = 1
while stack:
node = stack.pop()
movable = False
for adj in self.graph[node]:
if not used[adj]:
movable = True
used[adj] = 1
stack.append(node)
stack.append(adj)
break
if not movable:
order.append(node)
used = [0 for _ in range(self.n)]
count = 0
for s in order[::-1]:
if not used[s]:
stack = [s]
group[s] = count
while stack:
node = stack.pop()
used[node] = 1
for adj in self.rev[node]:
if not used[adj]:
group[adj] = count
stack.append(adj)
count += 1
return group, count
import sys
input = sys.stdin.buffer.readline
N, D = map(int, input().split())
X = []
Y = []
g = Graph(2 * N)
for _ in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
for i in range(N - 1):
for j in range(i + 1, N):
if abs(X[i] - X[j]) < D:
g.add_edge(i, ~j)
g.add_edge(j, ~i)
if abs(X[i] - Y[j]) < D:
g.add_edge(i, ~j)
g.add_edge(~j, i)
if abs(Y[i] - X[i]) < D:
g.add_edge(~i, j)
g.add_edge(j, ~i)
if abs(Y[i] - Y[j]) < D:
g.add_edge(~i, j)
g.add_edge(~j, i)
group, count = g.strongry_connected()
group_to_node = [[] for _ in range(count)]
for i in range(N):
if group[i] == group[~i]:
print('No')
break
group_to_node[group[i]].append(i)
group_to_node[group[~i]].append(~i)
else:
print('Yes')
comp = Graph(count)
for i in range(2 * N):
for j in g.graph[i]:
if group[i] == group[j]:
continue
comp.add_edge(group[i], group[j])
ts = comp.topological_sort()
res = [None for _ in range(N)]
for i in ts:
for node in group_to_node[i]:
if node >= 0:
if res[node] is None:
res[node] = Y[node]
else:
if res[~node] is None:
res[~node] = X[~node]
for i in range(N):
if res[i] is None:
res[i] = Y[node]
print('\n'.join(map(str, res)))
```
No
| 15,712 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
Submitted Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
n,d = list(map(int, input().split()))
xy = [tuple(map(int, input().split())) for _ in range(n)]
class SAT2:
def __init__(self, n):
self.n = n
self.ns = [[] for _ in range(2*n)]
def add_clause(self, i, f, j, g):
"""(xi==f) and (xj==g)
"""
n = self.n
u0,u1 = (i,i+n) if not f else (i+n,i)
v0,v1 = (j,j+n) if not g else (j+n,j)
self.ns[u1].append(v0)
self.ns[v1].append(u0)
def solve(self):
"""強連結成分分解
トポロジカルソート順の逆順に返す
"""
preorder = {}
lowlink = {}
seen = [False]*(2*self.n)
scc_queue = []
i = 0 # Preorder counter
# ans = [None]*(2*self.n)
count = 1
for source in range(n):
if seen[source]:
continue
queue = [source]
while queue:
v = queue[-1]
if v not in preorder:
i = i + 1
preorder[v] = i
done = True
for w in self.ns[v]:
if w not in preorder:
queue.append(w)
done = False
break
if done:
lowlink[v] = preorder[v]
for w in self.ns[v]:
if seen[w]:
continue
if preorder[w] > preorder[v]:
lowlink[v] = min([lowlink[v], lowlink[w]])
else:
lowlink[v] = min([lowlink[v], preorder[w]])
queue.pop()
if lowlink[v] == preorder[v]:
scc = {v}
while scc_queue and preorder[scc_queue[-1]] > preorder[v]:
k = scc_queue.pop()
scc.add(k)
for v in scc:
seen[v] = count
count += 1
else:
scc_queue.append(v)
ans = [None]*self.n
for i in range(self.n):
if seen[i]==seen[i+self.n]:
return None
elif seen[i]>seen[i+self.n]:
ans[i] = True
else:
ans[i] = False
return ans
solver = SAT2(n)
for i in range(n):
for j in range(i+1,n):
if abs(xy[i][0]-xy[j][0])<d:
solver.add_clause(i,False,j,False)
if abs(xy[i][0]-xy[j][1])<d:
solver.add_clause(i,False,j,True)
if abs(xy[i][1]-xy[j][0])<d:
solver.add_clause(i,True,j,False)
if abs(xy[i][1]-xy[j][1])<d:
solver.add_clause(i,True,j,True)
ans = solver.solve()
if ans is not None:
print("Yes")
write("\n".join(map(str, [xy[i][0 if ans[i] else 1] for i in range(n)])))
else:
print("No")
```
No
| 15,713 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No
Submitted Solution:
```
code = """
# distutils: language=c++
# distutils: include_dirs=[/home/USERNAME/.local/lib/python3.8/site-packages/numpy/core/include, /opt/atcoder-stl]
# cython: boundscheck=False
# cython: wraparound=False
from libcpp.string cimport string
from libcpp.vector cimport vector
from libcpp cimport bool
from libc.stdio cimport getchar, printf
cdef extern from "<atcoder/twosat>" namespace "atcoder":
cdef cppclass two_sat:
two_sat(int n)
void add_clause(int i, bool f, int j, bool g)
bool satisfiable()
vector[bool] answer()
cdef class TwoSat:
cdef two_sat *_thisptr
def __cinit__(self, int n):
self._thisptr = new two_sat(n)
cpdef void add_clause(self, int i, bool f, int j, bool g):
self._thisptr.add_clause(i, f, j, g)
cpdef bool satisfiable(self):
return self._thisptr.satisfiable()
cpdef vector[bool] answer(self):
return self._thisptr.answer()
cpdef inline vector[int] ReadInt(int n):
cdef int b, c
cdef vector[int] *v = new vector[int]()
for i in range(n):
c = 0
while 1:
b = getchar() - 48
if b < 0: break
c = c * 10 + b
v.push_back(c)
return v[0]
cpdef inline vector[string] Read(int n):
cdef char c
cdef vector[string] *vs = new vector[string]()
cdef string *s
for i in range(n):
s = new string()
while 1:
c = getchar()
if c<=32: break
s.push_back(c)
vs.push_back(s[0])
return vs[0]
cpdef inline void PrintLongN(vector[long] l, int n):
for i in range(n): printf("%ld\\n", l[i])
cpdef inline void PrintLong(vector[long] l, int n):
for i in range(n): printf("%ld ", l[i])
"""
import os, sys, getpass
if sys.argv[-1] == 'ONLINE_JUDGE':
code = code.replace("USERNAME", getpass.getuser())
open('atcoder.pyx','w').write(code)
os.system('cythonize -i -3 -b atcoder.pyx')
sys.exit(0)
from atcoder import ReadInt, TwoSat, PrintLongN
def main():
N,D=ReadInt(2)
xy = ReadInt(2*N)
ts=TwoSat(N)
for i in range(N-1):
for j in range(i+1,N):
for k1,k2 in [(0,0),(0,1),(1,0),(1,1)]:
pos1,pos2 = xy[2*i+k1],xy[2*j+k2]
if abs(pos2-pos1)<D:
ts.add_clause(i,k1^1,j,k2^1)
if ts.satisfiable():
print('Yes')
ans = ts.answer()
ans = [xy[2*i+ans[i]] for i in range(N)]
PrintLongN(ans, len(ans))
else:
print('No')
if __name__=="__main__":
main()
```
No
| 15,714 |
Provide a correct Python 3 solution for this coding contest problem.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
"Correct Solution:
```
A,B,N=map(int,input().split())
k = min(B-1,N)
print(int(A*k/B))
```
| 15,715 |
Provide a correct Python 3 solution for this coding contest problem.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
"Correct Solution:
```
a, b, n = [int(x) for x in input().split()]
y = min(b-1, n)
print((a*y)//b)
```
| 15,716 |
Provide a correct Python 3 solution for this coding contest problem.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
"Correct Solution:
```
a,b,n=map(int,input().split())
k=min(n,b-1)
print(int(a*k/b))
```
| 15,717 |
Provide a correct Python 3 solution for this coding contest problem.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
"Correct Solution:
```
A, B, N = list(map(int, input().split()))
x = min(N, B-1)
ans = A*x//B
print(ans)
```
| 15,718 |
Provide a correct Python 3 solution for this coding contest problem.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
"Correct Solution:
```
a,b,c=map(int,input().split())
x=min(b-1,c)
print((a*x)//b - a*(x//b))
```
| 15,719 |
Provide a correct Python 3 solution for this coding contest problem.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
"Correct Solution:
```
A, B, N = map(int,input().split())
max = int(A*min(B-1,N)/B)
print(max)
```
| 15,720 |
Provide a correct Python 3 solution for this coding contest problem.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
"Correct Solution:
```
a, b, n = map(int,input().split())
x = min(b -1, n)
ans = int(a * x/ b)
print(ans)
```
| 15,721 |
Provide a correct Python 3 solution for this coding contest problem.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
"Correct Solution:
```
A, B, N = map(int,input().split())
m = min(B-1,N)
print(int(A*(m/B)))
```
| 15,722 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
Submitted Solution:
```
a,b,n=map(int,input().split())
x=min(n,b-1)
print(int((a*x/b)//1))
```
Yes
| 15,723 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
Submitted Solution:
```
a,b,n=map(int,input().split())
print((a*min(b-1,n)//b))
```
Yes
| 15,724 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
Submitted Solution:
```
A,B,N = map(int,input().split())
n = min(B-1,N)
ans = (A*n)//B
print(ans)
```
Yes
| 15,725 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
Submitted Solution:
```
#abc165d
a,b,n=map(int,input().split())
c=min(b-1,n)
print(a*c//b)
```
Yes
| 15,726 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
Submitted Solution:
```
import math
a, b, n = map(int, input().split())
def f(x):
return (a * x) // b - a * (x // b)
left, right = 0, n
while right > left + 10:
mid1 = (right * 2 + left) / 3
mid2 = (right + left * 2) / 3
if f(mid1) <= f(mid2):
# 上限を下げる(最小値をとるxはもうちょい下めの数だな)
right = mid2
else:
# 下限を上げる(最小値をとるxはもうちょい上めの数だな)
left = mid1
listalt = []
for i in range(int(left), int(right) + 1):
listalt.append(f(i))
listalt.append(f(0))
listalt.append(f(n))
print(max(listalt))
```
No
| 15,727 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
Submitted Solution:
```
import math
A,B,N=map(int,input().split())
han=0
kot=0
i=0
if B-1>=N:
print(math.floor(A*N/B)-A*math.floor(N/B))
i=1
else:
for a in range(B-1,N,2*B):
if han<(math.floor(A*a/B)-A*math.floor(a/B)):
han=(math.floor(A*a/B)-A*math.floor(a/B))
kot=a
if i==0:
print(han)
```
No
| 15,728 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
Submitted Solution:
```
from math import floor
A,B,N = map(int,input().split())
ans = 0
if B <= N:
for x in range(B-1,N+1,B):
ans = max(ans, floor(A*x/B) - A*floor(x/B))
else:
ans = floor((A*N)/B) - A*floor(N/B)
print(ans)
```
No
| 15,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9
Submitted Solution:
```
import math
A,B,N=map(int,input().split())
list=0
for i in range(1,N+1):
if i>B:
list=math.floor(A*i/B)
else:
c=(math.floor((A*i)/B))-(A*(math.floor(i/B)))
if list<c:
list=c
print(list)
```
No
| 15,730 |
Provide a correct Python 3 solution for this coding contest problem.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
"Correct Solution:
```
n=int(input());f=["aabbc","hi..c","hi..d","g.jjd","gffee"];x=list("cdcd");a=[n*["."]for _ in range(n)];z={2:[-1],3:["abb","a.c","ddc"],5:["aabbc","hi..c","hi..d","g.jjd","gffee"],7:["..abc..","..abc..","aax..aa","bbx..bb","cc.yycc","..abc..","..abc.."]}
if n in z:print(*z[n]);exit()
if n%2:
for i in range(5):
for j in range(5):a[-i-1][-j-1]=f[i][j]
n-=5
for i in range(0,n,2):a[i][i],a[i][i+1],a[i+1][i],a[i+1][i+1]=list("aabb")
if n%4:
for i in range(0,n,2):a[i][(i+2)%n],a[i][(i+3)%n],a[i+1][(i+2)%n],a[i+1][(i+3)%n]=x
else:
for i in range(0,n,2):a[n-i-2][i],a[n-i-2][i+1],a[n-i-1][i],a[n-i-1][i+1]=x
for i in a:print("".join(i))
```
| 15,731 |
Provide a correct Python 3 solution for this coding contest problem.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
"Correct Solution:
```
n=int(input())
if n%3==0:
for i in range(n//3):
print("a.."*(n//3))
print("a.."*(n//3))
print(".aa"*(n//3))
elif n%2==0 and n>=4:
x="aacd"+"."*(n-4)
y="bbcd"+"."*(n-4)
for i in range(n//2):
print(x)
print(y)
x=x[2:]+x[:2]
y=y[2:]+y[:2]
elif n>=13:
x="aacd"+"."*(n-13)
y="bbcd"+"."*(n-13)
for i in range((n-9)//2):
print(x+"."*9)
print(y+"."*9)
x=x[2:]+x[:2]
y=y[2:]+y[:2]
for i in range(3):
print("."*(n-9)+"a..a..a..")
print("."*(n-9)+"a..a..a..")
print("."*(n-9)+".aa.aa.aa")
elif n==5:
print("aabba")
print("bc..a")
print("bc..b")
print("a.ddb")
print("abbaa")
elif n==7:
print("aabbcc.")
print("dd.dd.a")
print("..e..ea")
print("..e..eb")
print("dd.dd.b")
print("..e..ec")
print("..e..ec")
elif n==11:
print("aabbcc.....")
print("dd.dd.a....")
print("..e..ea....")
print("..e..eb....")
print("dd.dd.b....")
print("..e..ec....")
print("..e..ec....")
print(".......aacd")
print(".......bbcd")
print(".......cdaa")
print(".......cdbb")
else:
print(-1)
```
| 15,732 |
Provide a correct Python 3 solution for this coding contest problem.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
n = int(input())
pata = ["abb",
"a.c",
"ddc"]
patb = ["abcc",
"abdd",
"eefg",
"hhfg"]
patc = ["abbcc",
"ad..e",
"fd..e",
"f.ggh",
"iijjh"]
patd = [".aabbcc",
"a.ddee.",
"ad....d",
"bd....d",
"be....e",
"ce....e",
"c.ddee."]
pate = [".aabbcc....",
"a.ddee.....",
"ad....d....",
"bd....d....",
"be....e....",
"ce....e....",
"c.ddee.....",
".......abcc",
".......abdd",
".......ccab",
".......ddab"]
cnt = 0
def create_ab(w):
val = [["."] * w for _ in range(w)]
ok = False
for fives in range(200):
if (w - fives * 5) % 4 == 0:
fours = (w - fives * 5) // 4
if fours >= 0:
ok = True
break
if not ok:
return None
t = 0
for i in range(fives):
for i, line in enumerate(patc):
for j, ch in enumerate(line):
val[t+i][t+j] = ch
t += 5
for i in range(fours):
for i, line in enumerate(patb):
for j, ch in enumerate(line):
val[t+i][t+j] = ch
t += 4
ret = []
for line in val:
ret.append("".join([str(item) for item in line]))
return ret
def solve(n):
global cnt
if n % 3 == 0:
repeat = n // 3
for i in range(repeat):
for line in pata:
print(line * repeat)
elif n % 4 == 0:
repeat = n // 4
for i in range(repeat):
for line in patb:
print(line * repeat)
elif n % 5 == 0:
repeat = n // 5
for i in range(repeat):
for line in patc:
print(line * repeat)
elif n % 7 == 0:
repeat = n // 7
for i in range(repeat):
for line in patd:
print(line * repeat)
elif n % 11 == 0:
repeat = n // 11
for i in range(repeat):
for line in pate:
print(line * repeat)
else:
ret = create_ab(n)
if ret:
for line in ret:
print(line)
else:
cnt += 1
print(-1)
solve(n)
```
| 15,733 |
Provide a correct Python 3 solution for this coding contest problem.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
"Correct Solution:
```
n = int(input())
if n == 2:
print(-1)
if n == 3:
print("aa.")
print("..b")
print("..b")
if n == 4:
ans = ["aabc","ddbc","bcaa","bcdd"]
print(*ans,sep="\n")
if n == 5:
ans = ["aabbc","dde.c","..eab","a..ab","accdd"]
print(*ans,sep="\n")
if n == 6:
ans = ["aa.bbc","..de.c","..deff","aabcc.","d.b..a","dcc..a"]
print(*ans,sep="\n")
if n == 7:
ans = ["aab.cc.","..bd..e","ff.d..e","..g.hhi","..gj..i","kllj...","k..mmnn"]
print(*ans,sep="\n")
if n >= 8:
ans = [["." for i in range(n)] for j in range(n)]
ch = [list("aabc"),list("ddbc"),list("bcaa"),list("bcdd")]
x = n//4-1
y = n%4+4
for i in range(x):
for j in range(4):
for k in range(4):
ans[i*4+j][i*4+k] = ch[j][k]
if y == 4:
for j in range(4):
for k in range(4):
ans[x*4+j][x*4+k] = ch[j][k]
elif y == 5:
ch2 = ["aabbc","dde.c","..eab","a..ab","accdd"]
for j in range(5):
for k in range(5):
ans[x*4+j][x*4+k] = ch2[j][k]
elif y == 6:
ch2 = ["aa.bbc","..de.c","..deff","aabcc.","d.b..a","dcc..a"]
for j in range(6):
for k in range(6):
ans[x*4+j][x*4+k] = ch2[j][k]
elif y == 7:
ch2 = ["aab.cc.","..bd..e","ff.d..e","..g.hhi","..gj..i","kllj...","k..mmnn"]
for j in range(7):
for k in range(7):
ans[x*4+j][x*4+k] = ch2[j][k]
for row in ans:
print(*row,sep="")
```
| 15,734 |
Provide a correct Python 3 solution for this coding contest problem.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
"Correct Solution:
```
def GCD(x,y):
if y == 0:
return x
else:
return GCD(y,x%y)
N = int(input())
if N == 2:
print(-1)
exit()
if N == 7:
ans = [".aabbcc",
"c..ddee",
"c..ffgg",
"hij....",
"hij....",
"klm....",
"klm...."]
for i in ans:
print("".join(i))
exit()
if N == 3:
print(".aa")
print("a..")
print("a..")
exit()
four = ["aacd",
"bbcd",
"efgg",
"efhh"]
five = ["aabbc",
"h.iic",
"hj..d",
"gj..d",
"gffee"]
six = ["aacd..",
"bbcd..",
"ef..gg",
"ef..hh",
"..iikl",
"..jjkl"]
ans = [list("."*N) for i in range(N)]
a,b,c = [[0,N//5,0],[0,N//5-1,1],[0,N//5-2,2],[2,N//5-1,0],[1,N//5,0]][N%5]
p = 0
for i in range(a):
for x in range(4):
for y in range(4):
ans[p+x][p+y] = four[x][y]
p += 4
for i in range(b):
for x in range(5):
for y in range(5):
ans[p+x][p+y] = five[x][y]
p += 5
for i in range(c):
for x in range(6):
for y in range(6):
ans[p+x][p+y] = six[x][y]
p += 6
for i in ans:
print("".join(i))
```
| 15,735 |
Provide a correct Python 3 solution for this coding contest problem.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
"Correct Solution:
```
# coding: utf-8
# Your code here!
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
n = int(input())
#n, op = [i for i in readline().split()]
a21 = [["a","a"],["b","b"]]
a22 = [["c","d"],["c","d"]]
a3 = [["a","a","."],[".",".","b"],[".",".","b"]]
a4 = [["q","q","r","s"],["t","t","r","s"],["u","x","v","v"],["u","x","w","w"]]
a5 = [["c","c","d","d","l"],["e","f","f",".","l"],["e",".",".","h","g"],["i",".",".","h","g"],["i","j","j","k","k"]]
a7 = [["c","c","d","d",".",".","e"],[".","f","f",".",".","g","e"],[".",".","h","h",".","g","i"],["j",".",".",".","k",".","i"],["j","l",".",".","k",".","."],["m","l",".",".","n","n","."],["m",".",".","o","o","p","p"]]
if n == 2: print(-1)
else:
if n == 3:
ans = a3
elif n%2 == 0:
ans = [["."]*n for i in range(n)]
for i in range(n//2):
for j in range(2):
for k in range(2):
ans[2*i+j][2*i+k] = a21[j][k]
for i in range(n//2):
for j in range(2):
for k in range(2):
ans[2+2*i+j-n][2*i+k] = a22[j][k]
elif n%4==1:
ans = [["."]*n for i in range(n)]
for i in range(5):
for j in range(5):
ans[i][j] = a5[i][j]
for i in range((n-5)//2):
for j in range(2):
for k in range(2):
ans[5+2*i+j][5+2*i+k] = a21[j][k]
for i in range((n-5)//2):
for j in range(2):
for k in range(2):
c = 5+2+2*i+j
d = 5+2*i+k
if c >= n:
c = 5+j
ans[c][d] = a22[j][k]
elif n%4==3:
ans = [["."]*n for i in range(n)]
for i in range(7):
for j in range(7):
ans[i][j] = a7[i][j]
for i in range((n-7)//2):
for j in range(2):
for k in range(2):
ans[7+2*i+j][7+2*i+k] = a21[j][k]
for i in range((n-7)//2):
for j in range(2):
for k in range(2):
c = 7+2+2*i+j
d = 7+2*i+k
if c >= n:
c = 7+j
ans[c][d] = a22[j][k]
for i in ans:
print(*i,sep="")
```
| 15,736 |
Provide a correct Python 3 solution for this coding contest problem.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
"Correct Solution:
```
n = int(input())
if n % 3 == 0:
m = n // 3
for i in range(m):
print('.' * (3 * i) + 'abb' + '.' * (n - 3 - 3 * i))
print('.' * (3 * i) + 'a.a' + '.' * (n - 3 - 3 * i))
print('.' * (3 * i) + 'bba' + '.' * (n - 3 - 3 * i))
elif n % 4 == 0:
m = n // 4
for i in range(m):
print('.' * (4 * i) + 'abaa' + '.' * (n - 4 - 4 * i))
print('.' * (4 * i) + 'abcc' + '.' * (n - 4 - 4 * i))
print('.' * (4 * i) + 'ccba' + '.' * (n - 4 - 4 * i))
print('.' * (4 * i) + 'aaba' + '.' * (n - 4 - 4 * i))
else:
if n % 3 == 1:
if n >= 10:
print('abaa' + '.' * (n - 4))
print('abcc' + '.' * (n - 4))
print('ccba' + '.' * (n - 4))
print('aaba' + '.' * (n - 4))
m = (n - 4) // 3
for i in range(m):
if i == m - 1:
print('.' * 4 + 'dd.' + '.' * (n - 10) + 'abb')
print('.' * 4 + '..d' + '.' * (n - 10) + 'a.a')
print('.' * 4 + '..d' + '.' * (n - 10) + 'bba')
else:
print('.' * (4 + 3 * i) + 'abbdd.' + '.' * (n - 10 - 3 * i))
print('.' * (4 + 3 * i) + 'a.a..d' + '.' * (n - 10 - 3 * i))
print('.' * (4 + 3 * i) + 'bba..d' + '.' * (n - 10 - 3 * i))
elif n == 7:
print('a.aa..a')
print('ab....a')
print('.b..aab')
print('aabb..b')
print('.b.aacc')
print('aba....')
print('a.a.aa.')
else: # n == 4
print('abaa')
print('abcc')
print('ccba')
print('aaba')
elif n % 3 == 2:
if n >= 14:
m = (n - 8) // 3
print('abaa' + '.' * (n - 4))
print('abcc' + '.' * (n - 4))
print('ccba' + '.' * (n - 4))
print('aaba' + '.' * (n - 4))
print('....abaa' + '.' * (n - 8))
print('....abcc' + '.' * (n - 8))
print('....ccba' + '.' * (n - 8))
print('....aaba' + '.' * (n - 8))
m = (n - 8) // 3
for i in range(m):
if i == m - 1:
print('.' * 8 + 'dd.' + '.' * (n - 14) + 'abb')
print('.' * 8 + '..d' + '.' * (n - 14) + 'a.a')
print('.' * 8 + '..d' + '.' * (n - 14) + 'bba')
else:
print('.' * (8 + 3 * i) + 'abbdd.' + '.' * (n - 14 - 3 * i))
print('.' * (8 + 3 * i) + 'a.a..d' + '.' * (n - 14 - 3 * i))
print('.' * (8 + 3 * i) + 'bba..d' + '.' * (n - 14 - 3 * i))
elif n == 11:
print('a.aa..a' + '....')
print('ab....a' + '....')
print('.b..aab' + '....')
print('aabb..b' + '....')
print('.b.aacc' + '....')
print('aba....' + '....')
print('a.a.aa.' + '....')
print('.' * 7 + 'abaa')
print('.' * 7 + 'abcc')
print('.' * 7 + 'ccba')
print('.' * 7 + 'aaba')
elif n == 8:
print('abaa....')
print('abcc....')
print('ccba....')
print('aaba....')
print('....abaa')
print('....abcc')
print('....ccba')
print('....aaba')
elif n == 5:
print('abbaa')
print('a..bc')
print('bb.bc')
print('a.aab')
print('abb.b')
else:
print(-1)
```
| 15,737 |
Provide a correct Python 3 solution for this coding contest problem.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
"Correct Solution:
```
def join(xs, N):
n = len(xs)
r = ""
s = 0
for i, x in enumerate(xs):
x = x.strip()
t = len(x.split())
S,E="."*s,"."*(N-t-s)
for l in x.split():
r+=S+l+E+"\n"
s += t
return r
s7="""
.bc.a..
.bc.a..
..aabba
aab...a
x.baa..
x..b.aa
aa.b.xx
"""
s6="""
..aabx
d...bx
dla...
.lab..
xx.bxx
ddaall"""
s5="""
aa.bx
d..bx
dee.a
i.rra
ijjxx
"""
s4="""
xyzz
xyrr
zzxy
rrxy"""
s3="""
jj.
..j
..j"""
s=[s4,s5,s6,s7]
N=int(input())
if N<3:
print(-1)
elif N==3:
print(s3.strip())
elif N<=7:
print(s[N-4].strip())
else:
print(join([s[0]]*(N//4-1)+[s[N%4]],N))
```
| 15,738 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
Submitted Solution:
```
n = int(input())
s3=["abb","a.d","ccd"]
s = [["abcc", "abdd", "ddba", "ccba"],
["dccdd", "daa.c", "c..bc", "c..bd", "ddccd"],
["abbc..", "a.ac..", "bba.cc", "a..aab", "a..b.b", ".aabaa"],
["aba....","aba....","bab....","bab....","a..bbaa","a..aabb",".aabbaa"]]
if n == 2:
print(-1)
elif n == 3:
[print(x) for x in s3]
else:
d, m = divmod(n, 4)
d -= 1
m += 4
for i in range(d):
[print("." * 4 * i + x + "." * (4 * (d - i - 1) + m)) for x in s[0]]
[print("." * 4 * d + x) for x in s[m - 4]]
```
Yes
| 15,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
Submitted Solution:
```
import sys
n=int(input())
if n==2:
print(-1)
sys.exit()
if n==3:
print('aa.')
print('..a')
print('..a')
sys.exit()
x=(n//4)-1
y=(n%4)+4
l=[[['a','a','b','c'],['d','d','b','c'],['b','c','a','a'],['b','c','d','d']],[['a','a','b','b','a'],['b','c','c','.','a'],['b','.','.','c','b'],['a','.','.','c','b'],['a','b','b','a','a']],[['a','a','b','c','.','.'],['d','d','b','c','.','.'],['.','.','a','a','b','c'],['.','.','d','d','b','c'],['b','c','.','.','a','a'],['b','c','.','.','d','d']],[['a','a','b','b','c','c','.'],['d','d','.','d','d','.','a'],['.','.','d','.','.','d','a'],['.','.','d','.','.','d','b'],['d','d','.','d','d','.','b'],['.','.','d','.','.','d','c'],['.','.','d','.','.','d','c']]]
if n<8:
for i in range(n):
print(''.join(l[n-4][i]))
sys.exit()
ans=[]
for i in range(n):
ans1=['.']*n
ans.append(ans1)
for i in range(x):
for j in range(4):
for k in range(4):
ans[i*4+j][i*4+k]=l[0][j][k]
for j in range(y):
for k in range(y):
ans[x*4+j][x*4+k]=l[y-4][j][k]
for i in range(n):
print(''.join(ans[i]))
```
Yes
| 15,740 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
Submitted Solution:
```
n=int(input())
if n==2:
print(-1)
else:
x=[]
if n%3==0:
for i in range(n//3):
x.append("."*(3*i)+"a"+"."*(n-3*i-1))
x.append("."*(3*i)+"a"+"."*(n-3*i-1))
x.append("."*(3*i)+".aa"+"."*(n-3*i-3))
elif n%6==1:
for i in range(n//6-1):
x.append("."*(6*i)+".a.b.c"+"."*(n-6*i-6))
x.append("."*(6*i)+".a.b.c"+"."*(n-6*i-6))
x.append("."*(6*i)+"ddg.ll"+"."*(n-6*i-6))
x.append("."*(6*i)+"e.g.kk"+"."*(n-6*i-6))
x.append("."*(6*i)+"e.hhj."+"."*(n-6*i-6))
x.append("."*(6*i)+"ffiij."+"."*(n-6*i-6))
x.append("."*(n-7)+".aab.c.")
x.append("."*(n-7)+"d..b.c.")
x.append("."*(n-7)+"d..eeff")
x.append("."*(n-7)+"g..mm.l")
x.append("."*(n-7)+"gnn...l")
x.append("."*(n-7)+"h...kkj")
x.append("."*(n-7)+"hii...j")
elif n%6==2:
for i in range(n//6-1):
x.append("."*(6*i)+".a.b.c"+"."*(n-6*i-6))
x.append("."*(6*i)+".a.b.c"+"."*(n-6*i-6))
x.append("."*(6*i)+"ddg.ll"+"."*(n-6*i-6))
x.append("."*(6*i)+"e.g.kk"+"."*(n-6*i-6))
x.append("."*(6*i)+"e.hhj."+"."*(n-6*i-6))
x.append("."*(6*i)+"ffiij."+"."*(n-6*i-6))
x.append("."*(n-8)+".a.bb.cc")
x.append("."*(n-8)+".a...m.j")
x.append("."*(n-8)+"..pp.m.j")
x.append("."*(n-8)+"hh..i.o.")
x.append("."*(n-8)+"gg..i.o.")
x.append("."*(n-8)+"..n.ll.k")
x.append("."*(n-8)+"f.n....k")
x.append("."*(n-8)+"f.dd.ee.")
elif n%6==4:
for i in range(n//6):
x.append("."*(6*i)+".a.b.c"+"."*(n-6*i-6))
x.append("."*(6*i)+".a.b.c"+"."*(n-6*i-6))
x.append("."*(6*i)+"ddg.ll"+"."*(n-6*i-6))
x.append("."*(6*i)+"e.g.kk"+"."*(n-6*i-6))
x.append("."*(6*i)+"e.hhj."+"."*(n-6*i-6))
x.append("."*(6*i)+"ffiij."+"."*(n-6*i-6))
x.append("."*(n-4)+"aacb")
x.append("."*(n-4)+"ffcb")
x.append("."*(n-4)+"hgdd")
x.append("."*(n-4)+"hgee")
else:
for i in range(n//6):
x.append("."*(6*i)+".a.b.c"+"."*(n-6*i-6))
x.append("."*(6*i)+".a.b.c"+"."*(n-6*i-6))
x.append("."*(6*i)+"ddg.ll"+"."*(n-6*i-6))
x.append("."*(6*i)+"e.g.kk"+"."*(n-6*i-6))
x.append("."*(6*i)+"e.hhj."+"."*(n-6*i-6))
x.append("."*(6*i)+"ffiij."+"."*(n-6*i-6))
x.append("."*(n-5)+"aabbc")
x.append("."*(n-5)+"g.h.c")
x.append("."*(n-5)+"gjh..")
x.append("."*(n-5)+"dj.ii")
x.append("."*(n-5)+"deeff")
for i in range(n):
print("".join(x[i]))
#また出力が違うやつをやりましたが
```
Yes
| 15,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
Submitted Solution:
```
n = int(input())
if n % 3 == 0:
m = n // 3
for i in range(m):
print('.' * (3 * i) + 'abb' + '.' * (n - 3 - 3 * i))
print('.' * (3 * i) + 'a.a' + '.' * (n - 3 - 3 * i))
print('.' * (3 * i) + 'bba' + '.' * (n - 3 - 3 * i))
else:
if n % 3 == 1:
if n >= 10:
print('abaa' + '.' * (n - 4))
print('abcc' + '.' * (n - 4))
print('ccba' + '.' * (n - 4))
print('aaba' + '.' * (n - 4))
m = (n - 4) // 3
for i in range(m):
if i == m - 1:
print('.' * 4 + 'dd.' + '.' * (n - 10) + 'abb')
print('.' * 4 + '..d' + '.' * (n - 10) + 'a.a')
print('.' * 4 + '..d' + '.' * (n - 10) + 'bba')
else:
print('.' * (4 + 3 * i) + 'abbdd.' + '.' * (n - 10 - 3 * i))
print('.' * (4 + 3 * i) + 'a.a..d' + '.' * (n - 10 - 3 * i))
print('.' * (4 + 3 * i) + 'bba..d' + '.' * (n - 10 - 3 * i))
elif n == 7:
print('a.aa..a')
print('ab....a')
print('.b..aab')
print('aabb..b')
print('.b.aacc')
print('aba....')
print('a.a.aa.')
else: # n == 4
print('abaa')
print('abcc')
print('ccba')
print('aaba')
elif n % 3 == 2:
if n >= 14:
m = (n - 8) // 3
print('abaa' + '.' * (n - 4))
print('abcc' + '.' * (n - 4))
print('ccba' + '.' * (n - 4))
print('aaba' + '.' * (n - 4))
print('....abaa' + '.' * (n - 8))
print('....abcc' + '.' * (n - 8))
print('....ccba' + '.' * (n - 8))
print('....aaba' + '.' * (n - 8))
m = (n - 8) // 3
for i in range(m):
if i == m - 1:
print('.' * 8 + 'dd.' + '.' * (n - 14) + 'abb')
print('.' * 8 + '..d' + '.' * (n - 14) + 'a.a')
print('.' * 8 + '..d' + '.' * (n - 14) + 'bba')
else:
print('.' * (8 + 3 * i) + 'abbdd.' + '.' * (n - 14 - 3 * i))
print('.' * (8 + 3 * i) + 'a.a..d' + '.' * (n - 14 - 3 * i))
print('.' * (8 + 3 * i) + 'bba..d' + '.' * (n - 14 - 3 * i))
elif n == 11:
print('a.aa..a' + '....')
print('ab....a' + '....')
print('.b..aab' + '....')
print('aabb..b' + '....')
print('.b.aacc' + '....')
print('aba....' + '....')
print('a.a.aa.' + '....')
print('.' * 7 + 'abaa')
print('.' * 7 + 'abcc')
print('.' * 7 + 'ccba')
print('.' * 7 + 'aaba')
elif n == 8:
print('abaa....')
print('abcc....')
print('ccba....')
print('aaba....')
print('....abaa')
print('....abcc')
print('....ccba')
print('....aaba')
elif n == 5:
print('abbaa')
print('a..bc')
print('bb.bc')
print('a.aab')
print('abb.b')
else:
print(-1)
```
Yes
| 15,742 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
Submitted Solution:
```
N=int(input())
if N%3==0:
a=["aa."]*(N//3)
b=["..b"]*(N//3)
for i in range(N//3):
print("".join(a))
print("".join(b))
print("".join(b))
else:
print(-1)
```
No
| 15,743 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
Submitted Solution:
```
N = int(input())
ans = [['.']*N for i in range(N)]
if N%3==0:
for i in range(N//3):
ans[i*3][i*3] = 'a'
ans[i*3][i*3+1] = 'a'
ans[i*3][i*3+2] = 'b'
ans[i*3+1][i*3+2] = 'b'
ans[i*3+2][i*3+2] = 'a'
ans[i*3+2][i*3+1] = 'a'
ans[i*3+2][i*3] = 'b'
ans[i*3+1][i*3] = 'b'
for row in ans:
print(''.join(row))
exit()
x = 0
while x <= N:
y = N-x
if y%2==0 and y != 2:
if (y//2)%2:
q = (y-2)//4*3
else:
q = y//4*3
if x==0 or (q%2==0 and q <= x*2//3):
break
x += 3
else:
print(-1)
exit()
if (y//2)%2 == 0:
for i in range(y//2):
for j in range(y//2):
if (i+j)%2==0:
ans[i*2][j*2] = 'a'
ans[i*2][j*2+1] = 'a'
ans[i*2+1][j*2] = 'b'
ans[i*2+1][j*2+1] = 'b'
else:
ans[i*2][j*2] = 'c'
ans[i*2][j*2+1] = 'd'
ans[i*2+1][j*2] = 'c'
ans[i*2+1][j*2+1] = 'd'
else:
for i in range(y//2):
for j in range(y//2):
if i==j: continue
if i<j:
if (i+j)%2==0:
ans[i*2][j*2] = 'a'
ans[i*2][j*2+1] = 'a'
ans[i*2+1][j*2] = 'b'
ans[i*2+1][j*2+1] = 'b'
else:
ans[i*2][j*2] = 'c'
ans[i*2][j*2+1] = 'd'
ans[i*2+1][j*2] = 'c'
ans[i*2+1][j*2+1] = 'd'
else:
if (i+j)%2==0:
ans[i*2][j*2] = 'c'
ans[i*2][j*2+1] = 'd'
ans[i*2+1][j*2] = 'c'
ans[i*2+1][j*2+1] = 'd'
else:
ans[i*2][j*2] = 'a'
ans[i*2][j*2+1] = 'a'
ans[i*2+1][j*2] = 'b'
ans[i*2+1][j*2+1] = 'b'
z = x//3
for i in range(z):
for j in range(i, i+q//2):
j %= z
ans[y+i*3][y+j*3] = 'a'
ans[y+i*3][y+j*3+1] = 'a'
ans[y+i*3][y+j*3+2] = 'b'
ans[y+i*3+1][y+j*3+2] = 'b'
ans[y+i*3+2][y+j*3+2] = 'a'
ans[y+i*3+2][y+j*3+1] = 'a'
ans[y+i*3+2][y+j*3] = 'b'
ans[y+i*3+1][y+j*3] = 'b'
for row in ans:
print(''.join(row))
```
No
| 15,744 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
Submitted Solution:
```
N = int(input())
if N % 3 != 0:
print(-1)
else:
for i in range(N // 3):
line = "aa." * (N // 3)
print(line)
line = "..b" * (N // 3)
print(line)
print(line)
```
No
| 15,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1
Submitted Solution:
```
#
# ⋀_⋀
# (・ω・)
# ./ U ∽ U\
# │* 合 *│
# │* 格 *│
# │* 祈 *│
# │* 願 *│
# │* *│
#  ̄
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,hypot,log #log2ないyp
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A):
for a in A: print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
N=I()
if N%3!=0:
if N%4:
print(-1)
return
if N%4==0:
ans = [["."]*N for _ in range(N)]
for i in range(N):
base = (i//4)*4
if i%4==0:
ans[i][base]="a"
ans[i][base+1]="a"
ans[i][base+2]="c"
ans[i][base+3]="d"
elif i%4==1:
ans[i][base]="b"
ans[i][base+1]="b"
ans[i][base+2]="c"
ans[i][base+3]="d"
elif i%4==2:
ans[i][base]="c"
ans[i][base+1]="d"
ans[i][base+2]="a"
ans[i][base+3]="a"
else:
ans[i][base]="c"
ans[i][base+1]="d"
ans[i][base+2]="b"
ans[i][base+3]="b"
for a in ans:
print(*a,sep="")
return
ans = [["."]*N for _ in range(N)]
for i in range(N):
base = (i//3)*3
if i%3==0:
ans[i][base]="a"
elif i%3==1:
ans[i][base]="a"
else:
ans[i][base+1]="a"
ans[i][base+2]="a"
for a in ans:
print(*a,sep="")
if __name__ == '__main__':
main()
```
No
| 15,746 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
"Correct Solution:
```
def search_rolling_hash(S, T):
base = 1234
mod = 10**9+7
n, m = len(S), len(T)
rolling_hash = [0]*(n-m+1)
rolling_hash[0] = ord(S[0])
b_m = pow(base, m, mod)
T_hash = ord(T[0])
start_index = []
for i in range(1, m):
rolling_hash[0]*=base
rolling_hash[0]+=ord(S[i])
rolling_hash[0]%=mod
T_hash = (T_hash*base+ord(T[i]))%mod
if rolling_hash[0] == T_hash: start_index.append(0)
for i in range(1, ls):
rolling_hash[i] = (rolling_hash[i-1]*base-ord(S[i-1])*b_m+ord(S[i+m-1]))%mod
if rolling_hash[i] == T_hash: start_index.append(i)
return start_index
import sys
s = input()
t = input()
ls, lt = len(s), len(t)
S = s*(lt//ls+2)
index = search_rolling_hash(S, t)
flag = [False]*ls
for i in index:
flag[i] = True
stack = []
inf = float('inf')
cnt = [inf]*ls
for i in range(ls):
if flag[i] == False:
stack.append(i)
cnt[i] = 0
while stack:
x = stack.pop()
y = (x-lt)%ls
if cnt[y] == inf:
cnt[y] = cnt[x]+1
stack.append(y)
ans = max(cnt)
if ans == inf:
print(-1)
else:
print(ans)
```
| 15,747 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
"Correct Solution:
```
S = input()
W = input()
M = len(S)
S *= 3 * (len(W)//len(S)+1)
N = len(W)
def primeFactor(N):
i, n, ret, d, sq = 2, N, {}, 2, 99
while i <= sq:
k = 0
while n % i == 0: n, k, ret[i] = n//i, k+1, k+1
if k > 0 or i == 97: sq = int(n**(1/2)+0.5)
if i < 4: i = i * 2 - 1
else: i, d = i+d, d^6
if n > 1: ret[n] = 1
return ret
def divisors(N):
pf = primeFactor(N)
ret = [1]
for p in pf:
ret_prev = ret
ret = []
for i in range(pf[p]+1):
for r in ret_prev:
ret.append(r * (p ** i))
return sorted(ret)
D = divisors(N)
p = 1
for d in D:
if W[:-d] == W[d:]:
W = W[:d]
p = N//d
N = d
break
W = W[:d]
T = [-1] * (len(W)+1)
ii = 2
jj = 0
T[0] = -1
T[1] = 0
while ii < len(W) + 1:
if W[ii - 1] == W[jj]:
T[ii] = jj + 1
ii += 1
jj += 1
elif jj > 0:
jj = T[jj]
else:
T[ii] = 0
ii += 1
m = 0
def KMP(i0):
global m, i
ret = -1
while m + i < len(S):
if W[i] == S[m + i]:
i += 1
if i == len(W):
t = m
m = m + i - T[i]
if i > 0:
i = T[i]
return t
else:
m = m + i - T[i]
if i > 0:
i = T[i]
return len(S)
i = 0
j = -10**9
c = 0
cmax = 0
f = 0
while m < len(S)-N:
k = KMP(0)
if k == len(S):
break
elif k == N + j:
c += 1
else:
c = 1
f += 1
cmax = max(cmax, c)
j = k
if f == 1:
print(-1)
else:
print(cmax//p)
```
| 15,748 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
"Correct Solution:
```
# -*- coding: utf-8 -*-
import math
import sys
from collections import defaultdict
buff_readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 2**60
class RollingHash():
"""
Original code is https://tjkendev.github.io/procon-library/python/string/rolling_hash.html
"""
class RH():
def __init__(self, s, base, mod):
self.base = base
self.mod = mod
self.rev = pow(base, mod-2, mod)
l = len(s)
self.h = h = [0]*(l+1)
tmp = 0
for i in range(l):
num = ord(s[i])
tmp = (tmp*base + num) % mod
h[i+1] = tmp
self.pw = pw = [1]*(len(s)+1)
v = 1
for i in range(l):
pw[i+1] = v = v * base % mod
def calc(self, l, r):
return (self.h[r] - self.h[l] * self.pw[r-l]) % self.mod
@staticmethod
def gen(a, b, num):
import random
result = set()
while 1:
while 1:
v = random.randint(a, b)//2*2+1
if v not in result:
break
for x in range(3, int(math.sqrt(v))+1, 2):
if v % x == 0:
break
else:
result.add(v)
if len(result) == num:
break
return result
def __init__(self, s, rand=False, num=5):
if rand:
bases = RollingHash.gen(2, 10**3, num)
else:
assert num <= 10
bases = [641, 103, 661, 293, 547, 311, 29, 457, 613, 599][:num]
MOD = 10**9+7
self.rhs = [self.RH(s, b, MOD) for b in bases]
def calc(self, l, r):
return tuple(rh.calc(l, r) for rh in self.rhs)
class UnionFind():
def __init__(self):
self.__table = {}
self.__size = defaultdict(lambda: 1)
self.__rank = defaultdict(lambda: 1)
def __root(self, x):
if x not in self.__table:
self.__table[x] = x
elif x != self.__table[x]:
self.__table[x] = self.__root(self.__table[x])
return self.__table[x]
def same(self, x, y):
return self.__root(x) == self.__root(y)
def union(self, x, y):
x = self.__root(x)
y = self.__root(y)
if x == y:
return False
if self.__rank[x] < self.__rank[y]:
self.__table[x] = y
self.__size[y] += self.__size[x]
else:
self.__table[y] = x
self.__size[x] += self.__size[y]
if self.__rank[x] == self.__rank[y]:
self.__rank[x] += 1
return True
def size(self, x):
return self.__size[self.__root(x)]
def num_of_group(self):
g = 0
for k, v in self.__table.items():
if k == v:
g += 1
return g
def slv(S, T):
lt = len(T)
ls = len(S)
SS = S * (-(-lt // ls) * 2 + 1)
srh = RollingHash(SS, num=2)
th = RollingHash(T, num=2).calc(0, len(T))
ok = []
for i in range(ls+lt):
if srh.calc(i, i+lt) == th:
ok.append(i)
ok = set(ok)
uf = UnionFind()
for i in ok:
if (i + lt) in ok:
if not uf.union(i, (i+lt) % ls):
return -1
ans = 0
for i in ok:
ans = max(ans, uf.size(i))
return ans
def main():
S = input()
T = input()
print(slv(S, T))
if __name__ == '__main__':
main()
```
| 15,749 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations,product#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal
import random
def input():
x=sys.stdin.readline()
return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("## ",*x,file=sys.stderr)
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False):
inds=sorted(range(len(s)), key=lambda k: s[k])
if return_sorted: return inds, [s[i] for i in inds]
return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
K,N,M=len(B),len(A),len(B[0])
return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
N,size=len(v),len(M)
return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
n,m=len(M),len(M[0])
return [[M[j][i] for j in range(n)] for i in range(m)]
def binr(x): return bin(x)[2:]
def bitcount(x): #xは64bit整数
x= x - ((x >> 1) & 0x5555555555555555)
x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
x+= (x >> 8); x+= (x >> 16); x+= (x >> 32)
return x & 0x7f
def main():
mod = 1000000007
#w.sort(key=itemgetter(1),reverse=True) #二個目の要素で降順並び替え
#N = int(input())
#N, K = map(int, input().split())
#A = tuple(map(int, input().split())) #1行ベクトル
#L = tuple(int(input()) for i in range(N)) #改行ベクトル
#S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
class rh:#base,max_n,convertを指定すること
def __init__(self,base=26,max_n=5*10**5):#baseとmaxnを指定すること。baseは偶数(modが奇数)
self.mod=random.randrange(1<<54-1,1<<55-1,2)#奇数、衝突させられないよう乱数で生成
self.base=int(base*0.5+0.5)*2#偶数,英小文字なら26とか
self.max_n=max_n
self.pows1=[1]*(max_n+1)
cur1=1
for i in range(1,max_n+1):
cur1=cur1*base%self.mod
self.pows1[i]=cur1
def convert(self,c): return alp2num(c,False)#大文字の場合Trueにする
def get(self, s):#特定の文字のhash. O(|s|)
n=len(s)
mod=self.mod
si=[self.convert(ss) for ss in s]
h1=0
for i in range(n):h1=(h1+si[i]*self.pows1[n-1-i])%mod
return h1
def get_roll(self, s, k):#ローリングハッシュ,特定の文字の中から長さkのhashをすべて得る,O(|s|)
n=len(s)
si=[self.convert(ss) for ss in s]
mod=self.mod
h1=0
for i in range(k):h1=(h1+si[i%n]*self.pows1[k-1-i])%mod
hs=[0]*n
hs[0]=h1
mbase1=self.pows1[k]
base=self.base
for i in range(1,n):
front=si[i-1];back=si[(i+k-1)%n]
h1=(h1*base-front*mbase1+back)%mod
hs[i]=h1
return hs
s=input()
t=input()
n=len(s)
nt=len(t)
rhs=rh()
has=rhs.get(t)
hass=rhs.get_roll(s,nt)
l=[hass[i]==has for i in range(n)]
ds=[0]*n
for i in range(n):
ci=i
q=deque()
while l[ci] and ds[ci]==0:
q.append(ci)
ci=(ci+nt)%n
if ci==i:
print(-1)
return
tot=ds[ci]
while q:
tot+=1
ci=q.pop()
ds[ci]=tot
print(max(ds))
if __name__ == "__main__":
main()
```
| 15,750 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
"Correct Solution:
```
import sys,queue,math,copy,itertools,bisect,collections,heapq
def main():
MOD = 2**61-1
SI = lambda : sys.stdin.readline().rstrip()
s = SI()
t = SI()
lens = len(s)
lent = len(t)
def cx(x):
return ord(x) - ord('a') + 1
hsh = 0
for x in t:
hsh = (hsh * 26 + cx(x)) % MOD
n = (lens+lent) * 2 + 1
dp = [0] * n
h = 0
ans = 0
for i in range(n):
if i >= lent:
h -= cx(s[(i - lent)%lens]) * pow(26,lent-1,MOD)
h = (h * 26 + cx(s[i % lens])) % MOD
if h == hsh:
if i < lent:
dp[i] = 1
else:
dp[i] = dp[i-lent] + 1
ans = max(ans,dp[i])
if n - ans * lent < lent * 2:
print(-1)
else:
print(ans)
if __name__ == '__main__':
main()
```
| 15,751 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
"Correct Solution:
```
def main():
import sys
input = sys.stdin.readline
S = input().rstrip('\n')
T = input().rstrip('\n')
ns = len(S)
nt = len(T)
mod1 = 1000000007
mod2 = 1000000009
mod3 = 998244353
b1 = 1007
b2 = 2009
b3 = 2999
H1 = 0
H2 = 0
H3 = 0
for i, t in enumerate(T):
t = ord(t)
H1 = ((H1 * b1)%mod1 + t)%mod1
H2 = ((H2 * b2)%mod2 + t)%mod2
H3 = ((H3 * b3)%mod3 + t)%mod3
h1 = 0
h2 = 0
h3 = 0
for i in range(nt):
s = ord(S[i%ns])
h1 = ((h1 * b1) % mod1 + s) % mod1
h2 = ((h2 * b2) % mod2 + s) % mod2
h3 = ((h3 * b3) % mod3 + s) % mod3
idx = []
if h1 == H1 and h2 == H2 and h3 == H3:
idx.append(0)
b1_nt = pow(b1, nt, mod1)
b2_nt = pow(b2, nt, mod2)
b3_nt = pow(b3, nt, mod3)
for i in range(1, ns):
s = ord(S[(i+nt-1)%ns])
s_prev = ord(S[i-1])
h1 = ((h1 * b1) % mod1 - (b1_nt * s_prev)%mod1 + s) % mod1
h2 = ((h2 * b2) % mod2 - (b2_nt * s_prev)%mod2 + s) % mod2
h3 = ((h3 * b3) % mod3 - (b3_nt * s_prev) % mod3 + s) % mod3
if h1 == H1 and h2 == H2 and h3 == H3:
idx.append(i%ns)
if len(idx) == 0:
print(0)
exit()
ans = 1
dic = {}
for i in range(len(idx)):
if (idx[i] - nt)%ns in dic:
tmp = dic[(idx[i]-nt)%ns] + 1
dic[idx[i]] = tmp
ans = max(ans, tmp)
else:
dic[idx[i]] = 1
for i in range(len(idx)):
if (idx[i] - nt)%ns in dic:
tmp = dic[(idx[i]-nt)%ns] + 1
dic[idx[i]] = tmp
ans = max(ans, tmp)
else:
dic[idx[i]] = 1
ans_ = ans
for i in range(len(idx)):
if (idx[i] - nt)%ns in dic:
tmp = dic[(idx[i]-nt)%ns] + 1
dic[idx[i]] = tmp
ans = max(ans, tmp)
else:
dic[idx[i]] = 1
if ans == ans_:
print(ans)
else:
print(-1)
if __name__ == '__main__':
main()
```
| 15,752 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
"Correct Solution:
```
def kmp(s):
n = len(s)
kmp = [0] * (n+1)
kmp[0] = -1
j = -1
for i in range(n):
while j >= 0 and s[i] != s[j]:
j = kmp[j]
j += 1
kmp[i+1] = j
return kmp
from collections import deque
def topological_sort(graph: list, n_v: int) -> list:
# graph[node] = [(cost, to)]
indegree = [0] * n_v # 各頂点の入次数
for i in range(n_v):
for v in graph[i]:
indegree[v] += 1
cand = deque([i for i in range(n_v) if indegree[i] == 0])
res = []
while cand:
v1 = cand.popleft()
res.append(v1)
for v2 in graph[v1]:
indegree[v2] -= 1
if indegree[v2] == 0:
cand.append(v2)
return res
import sys
def main():
input = sys.stdin.readline
s = input().rstrip()
t = input().rstrip()
n0 = len(s)
m = len(t)
s = s * (m // n0 + 2)
res = kmp(t + '*' + s)
res = res[m+2:]
graph = [set() for _ in range(n0)]
for i in range(len(res)):
if res[i] >= m:
graph[(i-m+1)%n0].add( (i + 1) % n0 )
# print(graph)
ts = topological_sort(graph, n0)
if len(ts) != n0:
ans = -1
else:
# print(ts)
ans = 0
path = [0] * n0
for i in range(n0):
ans = max(ans, path[ts[i]])
for j in graph[ts[i]]:
path[j] = path[ts[i]] + 1
print(ans)
main()
```
| 15,753 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
"Correct Solution:
```
def partial_match_table(word):
table = [0] * (len(word) + 1)
table[0] = -1
i, j = 0, 1
while j < len(word):
matched = word[i] == word[j]
if not matched and i > 0:
i = table[i]
else:
if matched:
i += 1
j += 1
table[j] = i
return table
def kmp_search(text, word):
table = partial_match_table(word)
i, p = 0, 0
results = []
while i < len(text) and p < len(word):
if text[i] == word[p]:
i += 1
p += 1
if p == len(word):
p = table[p]
results.append((i-len(word), i))
elif p == 0:
i += 1
else:
p = table[p]
return results
inf = 10**18
s = input().strip()
t = input().strip()
m=(len(t)+len(s)-1+len(s)-1)//len(s)
d = [-1] * (len(s)+1)
for a, b in kmp_search(m*s, t):
a, b = a%len(s)+1, b%len(s)+1
d[a] = b
ls = [-1]*(len(s)+1)
vs = set()
for i in range(1, len(s)+1):
if i in vs:
continue
c = 0
j = i
while True:
vs.add(i)
i = d[i]
if i == -1:
break
c += 1
if i == j:
c = inf
break
if ls[i] != -1:
c += ls[i]
break
if c == inf:
break
ls[j] = c
print(max(ls) if c != inf else -1)
```
| 15,754 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
Submitted Solution:
```
from collections import defaultdict
#法と基数設定
mod1 = 10 ** 9 + 7
base1 = 1007
def getlist():
return list(map(int, input().split()))
class UnionFind:
def __init__(self, n):
self.par = [i for i in range(n + 1)]
self.rank = [0] * (n + 1)
self.size = [1] * (n + 1)
self.judge = "No"
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def same_check(self, x, y):
return self.find(x) == self.find(y)
def union(self, x, y):
x = self.find(x); y = self.find(y)
if self.rank[x] < self.rank[y]:
if self.same_check(x, y) != True:
self.size[y] += self.size[x]
self.size[x] = 0
else:
self.judge = "Yes"
self.par[x] = y
else:
if self.same_check(x, y) != True:
self.size[x] += self.size[y]
self.size[y] = 0
else:
self.judge = "Yes"
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def siz(self, x):
x = self.find(x)
return self.size[x]
#Nの文字からなる文字列AのM文字のハッシュ値を計算
def rollingHash(N, M, A):
mul1 = 1
for i in range(M):
mul1 = (mul1 * base1) % mod1
val1 = 0
for i in range(M):
val1 = val1 * base1 + A[i]
val1 %= mod1
hashList1 = [None] * (N - M + 1)
hashList1[0] = val1
for i in range(N - M):
val1 = (val1 * base1 - A[i] * mul1 + A[i + M]) % mod1
hashList1[i + 1] = val1
return hashList1
#処理内容
def main():
s = list(input())
t = list(input())
N = len(s)
M = len(t)
#sのほうを長く調整
if N < M:
var = int(M // N) + 1
s = s * var
N = N * var
s = s + s
for i in range(2 * N):
s[i] = ord(s[i]) - 97
for i in range(M):
t[i] = ord(t[i]) - 97
sHash1 = rollingHash(2 * N, M, s)
tHash1 = rollingHash(M, M, t)
tHash1 = tHash1[0]
value = "No"
UF = UnionFind(N)
for i in range(N):
j = (i + M) % N
if sHash1[i] == tHash1:
value = "Yes"
if sHash1[j] == tHash1:
UF.union(i, j)
if value == "No":
print(0)
return
if UF.judge == "Yes":
print(-1)
return
for i in range(N):
UF.par[i] = UF.find(i)
ans = 0
for i in range(N):
ans = max(ans, UF.size[i])
print(ans)
if __name__ == '__main__':
main()
```
Yes
| 15,755 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
Submitted Solution:
```
class RollingHash():
def __init__(self,s):
self.length=len(s)
self.base1=1009; self.base2=1013
self.mod1=10**9+7; self.mod2=10**9+9
self.hash1=[0]*(self.length+1); self.hash2=[0]*(self.length+1)
self.pow1=[1]*(self.length+1); self.pow2=[1]*(self.length+1)
for i in range(self.length):
self.hash1[i+1]=(self.hash1[i]+ord(s[i]))*self.base1%self.mod1
self.hash2[i+1]=(self.hash2[i]+ord(s[i]))*self.base2%self.mod2
self.pow1[i+1]=self.pow1[i]*self.base1%self.mod1
self.pow2[i+1]=self.pow2[i]*self.base2%self.mod2
def get(self,l,r):
h1=((self.hash1[r]-self.hash1[l]*self.pow1[r-l])%self.mod1+self.mod1)%self.mod1
h2=((self.hash2[r]-self.hash2[l]*self.pow2[r-l])%self.mod2+self.mod2)%self.mod2
return (h1,h2)
def solve(s,t):
ls=len(s); lt=len(t)
RHs=RollingHash(s*2)
RHt=RollingHash(t)
Judge=[False]*ls
B=RHt.get(0,lt)
for i in range(ls):
if RHs.get(i,i+lt)==B:
Judge[i]=True
ret=0
Visited=[-1]*ls
for i in range(ls) :
if Judge[i] and Visited[i]==-1:
idx=i
cnt=0
while Judge[idx]:
if Visited[idx]!=-1:
cnt+=Visited[idx]
break
cnt+=1
Visited[idx]=1
idx=(idx+lt)%ls
if idx==i:
return -1
Visited[i]=cnt
ret=max(ret,cnt)
return ret
s=input(); t=input()
s*=(len(t)+len(s)-1)//len(s)
print(solve(s,t))
```
Yes
| 15,756 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
Submitted Solution:
```
import collections
class KMP():
def __init__(self, pattern):
self.pattern = pattern
self.n = len(pattern)
self.create_k_table()
def create_k_table(self):
ktable = [-1]*(self.n+1)
j = -1
for i in range(self.n):
while j >= 0 and self.pattern[i] != self.pattern[j]:
j = ktable[j]
j += 1
if i+1 < self.n and self.pattern[i+1] == self.pattern[j]:
ktable[i+1] = ktable[j]
else:
ktable[i+1] = j
self.ktable = ktable
def match(self,s):
n = len(s)
j = 0
ret = [0]*n
for i in range(n):
while j >= 0 and (j == self.n or s[i] != self.pattern[j]):
j = self.ktable[j]
j += 1
if j == self.n:
ret[(i-self.n+1)%n] = 1
return ret
def main():
s = input()
t = input()
n = len(s)
m = len(t)
while len(s) < m + n:
s += s
a = KMP(t)
b = a.match(s)
edges = [[] for i in range(n)]
indegree = [0] * n
for i in range(n):
k = (i+m)%n
if b[i]:
edges[i].append(k)
indegree[k] += 1
def topSort():
q = collections.deque([i for i in range(n) if indegree[i] == 0])
while q:
cur = q.popleft()
res.append(cur)
for nei in edges[cur]:
indegree[nei] -= 1
if indegree[nei] == 0:
q.append(nei)
return len(res) == n
res = []
dp = [0] * n
flag = topSort()
if flag:
for k in range(n):
i = res[k]
for j in edges[i]:
dp[j] = max(dp[j], dp[i] + 1)
ans = max(dp)
else:
ans = -1
return ans
if __name__ == "__main__":
print(main())
```
Yes
| 15,757 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
Submitted Solution:
```
class KMP():
def __init__(self, pattern):
self.pattern = pattern
self.n = len(pattern)
self.create_k_table()
def create_k_table(self):
ktable = [-1]*(self.n+1)
j = -1
for i in range(self.n):
while j >= 0 and self.pattern[i] != self.pattern[j]:
j = ktable[j]
j += 1
if i+1 < self.n and self.pattern[i+1] == self.pattern[j]:
ktable[i+1] = ktable[j]
else:
ktable[i+1] = j
self.ktable = ktable
def match(self,s):
n = len(s)
j = 0
ret = [0]*n
for i in range(n):
while j >= 0 and (j == self.n or s[i] != self.pattern[j]):
j = self.ktable[j]
j += 1
if j == self.n:
ret[(i-self.n+1)%n] = 1
return ret
def main():
s = input()
t = input()
n = len(s)
m = len(t)
k = 1 - (-(m-1)//n)
si = s*k
a = KMP(t)
b = a.match(si)
# edges = [[] for i in range(n)]
# for i in range(n):
# if b[i]:
# edges[i].append((i+m)%n)
#
# def dfs(node):
# if visited[node] == 1:
# return True
# if visited[node] == 2:
# return False
# visited[node] = 1
# for nei in edges[node]:
# if dfs(nei):
# return True
# visited[node] = 2
# res.append(node)
# return False
# visited = [-1] * n
# res = []
# for i in range(n):
# if dfs(i):
# return -1
# dp = [0] * n
# ans = 0
# for i in range(n-1, -1, -1):
# t = res[i]
# for c in edges[t]:
# dp[c] = max(dp[c], dp[t] + 1)
# ans = max(ans, dp[c])
# return ans
visited = [0]*n
loop = False
ans = 0
for i in range(n):
if visited[i]:
continue
visited[i] = 1
cur = i
right = 0
while b[cur]:
nxt = (cur + m) % n
if visited[nxt]:
loop = True
break
visited[nxt] = 1
cur = nxt
right += 1
cur = i
left = 0
while b[(cur-m)%n]:
nxt = (cur-m) % n
if visited[nxt]:
loop = True
break
visited[nxt] = 1
cur = nxt
left += 1
if not loop:
ans = max(ans, right+left)
else:
ans = -1
break
return ans
if __name__ == "__main__":
print(main())
```
Yes
| 15,758 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
Submitted Solution:
```
s = input()
t = input()
def z_algorithm(s):
a = [0] * len(s)
i = 1
j = 0
a[0] = len(s)
while i < len(s):
while i + j < len(s) and s[j] == s[i+j]:
j += 1
a[i] = j
if j == 0:
i += 1
continue
k = 1
while i + k < len(s) and k + a[k] < j:
a[i+k] = a[k]
k += 1
i += k
j -= k
return a
def solve(i, li):
ans = 0
while True:
if visited[i]:
break
if i < 0 or len(li) <= i:
break
if li[i] < len(t):
visited[i] = True
break
if li[i] >= len(t):
visited[i] = True
ans += 1
i += len(t)
return ans
#sを伸ばす
new_s = ""
while True:
new_s += s
if len(new_s) > len(t):
s = new_s
break
s = s*3
li = z_algorithm(t + s)[len(t):]
visited = [False] * len(li)
ans1 = 0
for i in range(len(li)):
ans1 = max(ans1, solve(i, li))
'''
s += s
li = z_algorithm(t + s)[len(t):]
visited = [False] * len(li)
ans2 = 0
for i in range(len(li)):
ans2 = max(ans2, solve(i, li))
if ans1 == ans2:
print(ans1)
else:
print(-1)
'''
print(ans1)
```
No
| 15,759 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
Submitted Solution:
```
import sys,queue,math,copy,itertools,bisect,collections,heapq
def main():
MOD = 2**61-1
SI = lambda : sys.stdin.readline().rstrip()
s = SI()
t = SI()
s = s * 3
lens = len(s)
lent = len(t)
def cx(x):
return ord(x) - ord('a') + 1
hash = 0
for x in t:
hash = (hash * 26 + cx(x)) % MOD
cnt = 0
f = False
h = 0
last_i = 0
ans = 0
for i in range(lens):
if i >= lent:
h -= cx(s[i-lent]) * pow(26,lent-1,MOD)
h = (h * 26 + cx(s[i])) % MOD
if h == hash:
cnt += 1
ans = max(ans,cnt)
last_i = i
else:
if i - last_i >= lent and last_i > 0:
cnt = 0
f = True
if f:
print(ans)
else:
print(-1)
if __name__ == '__main__':
main()
```
No
| 15,760 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
Submitted Solution:
```
S = input()
W = input()
M = len(S)
S *= 6 * (len(W)//len(S)+1)
N = len(W)
def primeFactor(N):
i, n, ret, d, sq = 2, N, {}, 2, 99
while i <= sq:
k = 0
while n % i == 0: n, k, ret[i] = n//i, k+1, k+1
if k > 0 or i == 97: sq = int(n**(1/2)+0.5)
if i < 4: i = i * 2 - 1
else: i, d = i+d, d^6
if n > 1: ret[n] = 1
return ret
def divisors(N):
pf = primeFactor(N)
ret = [1]
for p in pf:
ret_prev = ret
ret = []
for i in range(pf[p]+1):
for r in ret_prev:
ret.append(r * (p ** i))
return sorted(ret)
D = divisors(N)
p = 1
for d in D:
if W[:-d] == W[d:]:
W = W[:d]
p = N//d
N = d
break
W = W[:d]
T = [-1] * (len(W)+1)
ii = 2
jj = 0
T[0] = -1
T[1] = 0
while ii < len(W):
if W[ii - 1] == W[jj]:
T[ii] = jj + 1
ii += 1
jj += 1
elif jj > 0:
jj = T[jj]
else:
T[ii] = 0
ii += 1
def KMP(i0):
ret = -1
m = 0
i = 0
while m + i < len(S) - i0:
if W[i] == S[m + i + i0]:
i += 1
if i == len(W):
return m
else:
m = m + i - T[i]
if i > 0:
i = T[i]
return len(S) - i0
i = 0
c = 0
cmax = 0
s = 0
while s < M:
# print("i =", i)
k = KMP(i)
if k + i == len(S):
break
elif k == len(W) - 1:
c += 1
else:
s = i
c = 1
cmax = max(cmax, c)
i += k + 1
if s < M:
print(-1)
else:
print(cmax//p)
```
No
| 15,761 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0
Submitted Solution:
```
import sys
import random
s = input()
t = input()
sl = len(s)
tl = len(t)
l = 0
r = 1000000//tl + 2
r2 = r
s *= 999999//sl + 1
n = len(s)
base1 = 1007
mod1 = 10**9+7
modTank1 = [3000012541,3000012553,3000012563,3000012649,3000012683,3000012709]
mod1 = modTank1[random.randint(0,5)]
base1 = 1007
mod1 = 10**9+7
hash1 = [0]*(n+1)
power1 = [1]*(n+1)
for i,e in enumerate(s):
hash1[i+1] = (hash1[i]*base1 + ord(e))%mod1
power1[i+1] = (power1[i]*base1)%mod1
def rolling_hash(i, j):
return (hash1[j]-hash1[i]*power1[j-i]%mod1)%mod1
while r - l > 1:
m = l + (r-l)//2
lt = len(t)*m
hash2 = [0]*(lt+1)
power2 = [1]*(lt+1)
for i,e in enumerate(t*m):
hash2[i+1] = (hash2[i]*base1 + ord(e))%mod1
power2[i+1] = (power2[i]*base1)%mod1
r_hash = hash2[-1]%mod1
lt = len(t)*m
flag = 0
for i in range(len(s)-lt+1):
if r_hash == rolling_hash(i, i+lt):
flag = 1
break
if flag == 1:
l = m
else:
r = m
if r == r2:
print(-1)
else:
print(l)
```
No
| 15,762 |
Provide a correct Python 3 solution for this coding contest problem.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
"Correct Solution:
```
def split(n, a, b, remain, ai, ans, width, l=None):
# print(n, a, b, remain, ai, ans, width)
# print(*(f'{c:5d}' for c in ans))
# print(*(f'{c:05b}' for c in ans))
if width == 2:
ans[ai] = a
ans[ai + 1] = b
return
if l is None:
x = a ^ b
y = x & -x # Rightmost Bit at which is different for a and b
l = y.bit_length() - 1
else:
y = 1 << l
remain.remove(l)
i = next(iter(remain))
lb = a ^ (1 << i)
ra = lb ^ y
width >>= 1
split(n, a, a ^ (1 << i), remain, ai, ans, width, i)
split(n, ra, b, remain, ai + width, ans, width)
remain.add(l)
def solve(n, a, b):
if bin(a).count('1') % 2 == bin(b).count('1') % 2:
print('NO')
return
remain = set(range(n))
ans = [0] * (1 << n)
split(n, a, b, remain, 0, ans, 1 << n)
print('YES')
print(*ans)
n, a, b = list(map(int, input().split()))
solve(n, a, b)
```
| 15,763 |
Provide a correct Python 3 solution for this coding contest problem.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
"Correct Solution:
```
import sys
input = sys.stdin.readline
N,A,B = map(int,input().split())
def seq(start,bits):
arr = [0]
for i in bits:
arr += [x^(1<<i) for x in arr[::-1]]
return [x^start for x in arr]
def solve(A,B,rest):
if len(rest) == 1:
return [A,B]
if len(rest) == 2:
i,j = rest
x,y = 1<<i,1<<j
if A^x == B:
return [A,A^y,A^x^y,B]
elif A^y == B:
return [A,A^x,A^x^y,B]
else:
return None
diff_bit = [i for i in rest if (A&(1<<i)) != (B&(1<<i))]
if len(diff_bit) % 2 == 0:
return None
i = diff_bit[0]
rest = [j for j in rest if j != i]
if A^(1<<rest[0])^(1<<i) == B:
rest[0],rest[1] = rest[1],rest[0]
arr = seq(A,rest)
return arr + solve(arr[-1]^(1<<i),B,rest)
rest = list(range(N))
answer = solve(A,B,rest)
if answer is None:
print('NO')
else:
print('YES')
print(' '.join(map(str,answer)))
```
| 15,764 |
Provide a correct Python 3 solution for this coding contest problem.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
"Correct Solution:
```
def main():
n, a, b = map(int, input().split())
if (bin(a).count("1")+bin(b).count("1")) % 2 == 0:
print("NO")
return
print("YES")
def calc(a, b, k):
if k == 1:
return [a, b]
for i in range(k):
if ((a >> i) & 1) ^ ((b >> i) & 1):
break
a2 = (a & (2**i-1))+((a >> (i+1)) << i)
b2 = (b & (2**i-1))+((b >> (i+1)) << i)
a3 = ((a >> i) & 1)
b3 = ((b >> i) & 1)
c = a2 ^ 1
q = calc(a2, c, k-1)
r = calc(c, b2, k-1)
q = [((t >> i) << i+1)+(a3 << i)+(t & (2**i-1)) for t in q]
r = [((t >> i) << i+1)+(b3 << i)+(t & (2**i-1)) for t in r]
return q+r
print(*calc(a, b, n))
main()
```
| 15,765 |
Provide a correct Python 3 solution for this coding contest problem.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
"Correct Solution:
```
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
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 LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def bit(xx):return [format(x,"b") for x in xx]
popcnt=lambda x:bin(x).count("1")
def solve(xx,a,b):
if len(xx)==2:return [a,b]
k=(a^b).bit_length()-1
aa=[]
bb=[]
for x in xx:
if (x>>k&1)==(a>>k&1):aa.append(x)
else:bb.append(x)
i=0
mid=aa[i]
while mid==a or (mid^1<<k)==b or popcnt(a)&1==popcnt(mid)&1:
i+=1
mid=aa[i]
#print(bit(xx),a,b,k,bit(aa),bit(bb),format(mid,"b"))
return solve(aa,a,mid)+solve(bb,mid^1<<k,b)
def main():
n,a,b=MI()
if (popcnt(a)&1)^(popcnt(b)&1)==0:
print("NO")
exit()
print("YES")
print(*solve(list(range(1<<n)),a,b))
main()
```
| 15,766 |
Provide a correct Python 3 solution for this coding contest problem.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
"Correct Solution:
```
import os
import sys
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353
N, A, B = list(map(int, sys.stdin.buffer.readline().split()))
# 解説
# 違うbitの数が奇数なら戻ってこれる
def bitcount(n):
ret = 0
while n > 0:
ret += n & 1
n >>= 1
return ret
# vs = []
# for i in range(1 << N):
# for j in range(i, 1 << N):
# if bitcount(i ^ j) == 1:
# vs.append((i, j))
# plot_graph(vs)
# @lru_cache(maxsize=None)
# @debug
def solve(n, a, b):
if n <= 0:
return []
if bitcount(a ^ b) % 2 == 0:
return []
if n == 1:
return [a, b]
# 奇数
# 違うbitを1つ取り除く
mask = 1
while (a ^ b) & mask == 0:
mask <<= 1
r_mask = mask - 1
l_mask = ~mask - r_mask
na = ((a & l_mask) >> 1) + (a & r_mask)
nb = ((b & l_mask) >> 1) + (b & r_mask)
mid = na ^ 1
ret = []
for r in solve(n - 1, na, mid):
ret.append(((r << 1) & l_mask) + (a & mask) + (r & r_mask))
for r in solve(n - 1, mid, nb):
ret.append(((r << 1) & l_mask) + (b & mask) + (r & r_mask))
return ret
ans = solve(N, A, B)
if ans:
print('YES')
print(*ans)
else:
print('NO')
# for A in range(1 << N):
# for B in range(1 << N):
# ans = solve(N, A, B)
# if ans:
# assert ans[0] == A
# assert ans[-1] == B
# for a, b in zip(ans, ans[1:]):
# assert bitcount(a ^ b) == 1
# assert a < (1 << N)
```
| 15,767 |
Provide a correct Python 3 solution for this coding contest problem.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
"Correct Solution:
```
N, A, B = map(int, input().split())
AB = A ^ B
D = bin(AB)[2:].count('1')
if D % 2 == 0:
print('NO')
else:
print('YES')
C = [0] * (2 ** N)
C[0] = str(A)
P = []
for i in range(N):
if AB % 2:
P = P + [i]
else:
P = [i] + P
AB >>= 1
for i in range(1, 2 ** N):
k = 0
b = i
while b % 2 == 0:
k += 1
b >>= 1
A ^= 1 << P[k]
C[i] = str(A)
k = 0
for i in range(D // 2):
k += 1 / (4 ** (i + 1))
K = int(2 ** N * (1 - k))
C = C[:K-1] + C[K+1:] + C[K-1:K+1][::-1]
print(' '.join(C))
```
| 15,768 |
Provide a correct Python 3 solution for this coding contest problem.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
"Correct Solution:
```
from sys import exit, setrecursionlimit, stderr, stdin
from functools import reduce
from itertools import *
from collections import defaultdict, Counter
from bisect import bisect
setrecursionlimit(10**7)
M = 10 ** 9 + 7
def input():
return stdin.readline().strip()
def read():
return int(input())
def reads():
return [int(x) for x in input().split()]
def bitcount(a, N):
return sum((a & (1 << i)) > 0 for i in range(N))
def topbit(a, N):
return next(i for i in range(N-1, -1, -1) if (a & (1 << i)) > 0)
def swap(x, i, j):
y = x & ~(1 << i) & ~(1 << j)
if (x & (1 << i)) > 0:
y |= 1 << j
if (x & (1 << j)) > 0:
y |= 1 << i
return y
def solve(N, A, B):
if N == 1:
ans = [A & 1, B & 1]
return ans
C = A ^ B
t = topbit(C, N)
AA = swap(A, t, N-1)
BB = swap(B, t, N-1)
D = AA ^ 1
ans = []
if B & (1 << t) > 0:
ans.extend(swap(x, t, N-1) for x in solve(N-1, AA, D))
ans.extend(swap(x, t, N-1) | (1 << t) for x in solve(N-1, D, BB))
else:
ans.extend(swap(x, t, N-1) | (1 << t)for x in solve(N-1, AA, D))
ans.extend(swap(x, t, N-1) for x in solve(N-1, D, BB))
return ans
N, A, B = reads()
if bitcount(A ^ B, N) % 2 == 0:
print("NO"); exit()
print("YES")
print(*solve(N, A, B))
```
| 15,769 |
Provide a correct Python 3 solution for this coding contest problem.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
"Correct Solution:
```
def makep(n, l, mask):
a = l[0] & mask
b = l[-1] & mask
ll = len(l)
diff = a ^ b
for i in range(n):
if(((diff >> i) & 1) != 0):
diff = 1 << i
break
# print("a = {}, b = {}, mask = {}, ll = {}, diff = {}".format(a, b, mask, ll, diff))
for i, elem in enumerate(l[1:-1], 1):
if(i < ll // 2):
l[i] = (l[i] & ~diff) | (a & diff)
else:
l[i] = (l[i] & ~diff) | (b & diff)
# print("l = {}".format(l))
nextbit = mask & ~diff
if(0 != nextbit):
for i in range(n):
if(((nextbit >> i) & 1) != 0):
nextbit = 1 << i
break
l[ll // 2 - 1] = (l[ll // 2 - 1] | (a & ~diff)) ^ nextbit
l[ll // 2 - 0] = (l[ll // 2 - 0] | (a & ~diff)) ^ nextbit
# print("nextbit = {}, ll//2 = {}, l = {}".format(nextbit, ll//2, l))
if(ll > 2):
l[:ll // 2] = makep(n, l[:ll // 2], mask & ~diff)
l[ll // 2:] = makep(n, l[ll // 2:], mask & ~diff)
return(l)
N, A, B = map(int, input().split())
A1num = "{:b}".format(A).count("1")
B1num = "{:b}".format(B).count("1")
if((A1num % 2) == (B1num % 2)):
print("NO")
exit()
print("YES")
p = [0] * (2 ** N)
p[0] = A
p[-1] = B
p = makep(N, p, 2 ** N - 1)
#for i in p:
# print("{:08b}".format(i))
print(" ".join(map(str, p)))
```
| 15,770 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
Submitted Solution:
```
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**5)
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())
# i-bit目とj-bit目を入れ替える
def swap_digit(num:int, i:int, j:int):
if num & (1<<i) and not (num & (1<<j)):
return num - (1<<i) + (1<<j)
elif not (num & (1<<i)) and num & (1<<j):
return num + (1<<i) - (1<<j)
else:
return num
# 2つの数のbitが異なる桁を特定する
def different_digit(n: int, a: int, b: int):
ret = n-1
for digit in range(n-1, -1, -1):
if (a^b) & (1<<digit):
return digit
return ret
# 上位bitから再帰的に決める
def rec(n: int, a: int, b: int):
if n == 1:
return [a,b]
dd = different_digit(n,a,b)
a = swap_digit(a, n-1, dd)
b = swap_digit(b, n-1, dd)
na = a & ((1<<(n-1)) - 1)
nb = b & ((1<<(n-1)) - 1)
first = rec(n-1, na, na^1)
latte = rec(n-1, na^1, nb)
if a & (1<<(n-1)):
ret = list(map(lambda x: x + (1<<(n-1)), first)) + latte
else:
ret = first + list(map(lambda x: x + (1<<(n-1)), latte))
return [swap_digit(reti, n-1, dd) for reti in ret]
n,a,b = li()
if bin(a).count('1') % 2 == bin(b).count('1') % 2:
print("NO")
else:
print("YES")
print(*rec(n,a,b))
```
Yes
| 15,771 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
Submitted Solution:
```
from sys import setrecursionlimit
setrecursionlimit(10 ** 9)
n, a, b = [int(i) for i in input().split()]
if bin(a ^ b).count('1') % 2 == 0:
print('NO')
exit()
def dfs(i, a, b):
if i == 1:
return [a, b]
d = (a ^ b) & -(a ^ b)
ad = ((a & (~d ^ d - 1)) >> 1) + (a & d - 1)
bd = ((b & (~d ^ d - 1)) >> 1) + (b & d - 1)
c = ad ^ 1
res1 = dfs(i - 1, ad, c)
res2 = dfs(i - 1, c, bd)
ans1 = [((r & ~(d - 1)) << 1) + (r & d - 1) + (d & a) for r in res1]
ans2 = [((r & ~(d - 1)) << 1) + (r & d - 1) + (d & b) for r in res2]
return ans1 + ans2
print('YES')
print(*dfs(n, a, b))
```
Yes
| 15,772 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
Submitted Solution:
```
d = ((0, 0), (0, 1), (1, 1), (1, 0))
n, a, b = map(int, input().split())
c = 0
p = a ^ b
z, o = [], []
for i in range(n):
if (p >> i) & 1:
o.append(i)
else:
z.append(i)
if len(o) % 2 == 0:
print('NO')
exit(0)
print('YES')
ans = [0] * pow(2, n)
if n % 2:
i = o.pop()
for j in range(pow(2, n - 1), pow(2, n)):
ans[j] += pow(2, i)
else:
i = o.pop()
j = z.pop()
for k in range(4):
tmp = pow(2, n) // 4
for l in range(tmp):
ans[k * tmp + l] += pow(2, i) * d[k][0] + pow(2, j) * d[k][1]
t = 1
while o:
tmp = pow(2, n) // t // 8
i = o.pop()
j = o.pop()
idx = 0
for l in range(tmp):
if l == 0:
for p in range(4):
for q in range(t):
ans[idx] += d[p][0] * \
pow(2, i) + d[p][1] * pow(2, j)
idx += 1
for p in range(4):
for q in range(t):
ans[idx] += d[p - 1][0] * \
pow(2, i) + d[p - 1][1] * pow(2, j)
idx += 1
else:
for p in range(4):
for q in range(t):
ans[idx] += d[p - 2][0] * \
pow(2, i) + d[p - 2][1] * pow(2, j)
idx += 1
for p in range(4):
for q in range(t):
ans[idx] += d[1 - p][0] * \
pow(2, i) + d[1 - p][1] * pow(2, j)
idx += 1
t *= 4
while z:
tmp = pow(2, n) // t // 8
i = z.pop()
j = z.pop()
idx = 0
for l in range(tmp):
for p in range(4):
for q in range(t):
ans[idx] += d[p][0] * \
pow(2, i) + d[p][1] * pow(2, j)
idx += 1
for p in range(4):
for q in range(t):
ans[idx] += d[3 - p][0] * \
pow(2, i) + d[3 - p][1] * pow(2, j)
idx += 1
t *= 4
print(' '.join(map(lambda x: str(x ^ a), ans)))
# for i in range(pow(2, n) - 1):
# print(ans[i + 1] - ans[i], end=' ')
```
Yes
| 15,773 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
Submitted Solution:
```
def extract(a, i):
return (a>>(i+1) << i) | (a&((1<<i)-1))
def space(a, i):
return ((a>>i) << (i+1)) | (a&((1<<i)-1))
def compose(n, a, b):
if n==1:
return [a, b]
for i in range(n):
if (a>>i&1) ^ (b>>i&1):
x = i
a_bool = (a>>i & 1) << i
b_bool = a_bool ^ (1 << i)
a_dash = extract(a, i)
b_dash = extract(b, i)
c = a_dash ^ 1
break
Q = compose(n-1, a_dash, c)
R = compose(n-1, c, b_dash)
n_Q = [space(i, x)|a_bool for i in Q]
n_R = [space(i, x)|b_bool for i in R]
return n_Q + n_R
n, a, b = map(int, input().split())
cnt = 0
c = a^b
for i in range(n):
cnt += c>>i & 1
if cnt&1:
print("YES")
print(*compose(n, a, b))
else:
print("NO")
```
Yes
| 15,774 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
Submitted Solution:
```
N, A, B = list(map(int, input().split(' ')))
num = format(A^B, 'b').count('1')
if num >= 2**N - 1 or num % 2 == 0:
print('NO')
else:
C = A^B
c = format(A^B, 'b')
p = list()
p.append(A)
for i in range(len(c)):
if int(c[len(c)-1-i]) == 1:
tmp = p[-1] ^ (C & (1 << i))
p.append(tmp)
for i in range(2**N-len(p)):
p.append(p[-2])
print('YES')
for i in range(len(p)):
print(p[i], end=' ')
```
No
| 15,775 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
Submitted Solution:
```
N, A, B = map(int, input().split())
a_str = bin(A)[2:]
b_str = bin(B)[2:]
a_bin = int(a_str)
b_bin = int(b_str)
a = [0] * (N+1)
b = [0] * (N+1)
c = [A] + [0]*(2**N-2) + [B]
# for i in range(len(a_str),2,-1):
# a.append(int(a_str[i-1]))
# for i in range(len(b_str),2,-1):
# b.append(int(b_str[i-1]))
cnta = 0
cntb = 0
while (a_bin):
a[cnta] = a_bin%10
a_bin = a_bin//10
cnta += 1
while (b_bin):
b[cntb] = b_bin%10
b_bin = b_bin//10
cntb += 1
# print(cnta,cntb)
d = A^B
h = 0
while(d):
d &= d-1
h += 1
# print(h)
if (2**N-h)%2 == 0 or h > 2**N-2:
print('NO', end='')
exit()
else:
print('YES')
j = 1
C = A
for i in range(max(cnta, cntb)):
if a[i] != b[i]:
if a[i] == 1:
C -= 2**i
c[j] = C
else:
C += 2**i
c[j] = C
j += 1
for i in range(j,2**N-1,2):
c[j],c[j+1] = c[j-2],c[j-1]
for i in range(2**N):
print(c[i], end=' ')
```
No
| 15,776 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
Submitted Solution:
```
N, A, B = map(int, input().split())
AB = A ^ B
if bin(AB)[2:].count('1') != 1:
print('NO')
else:
print('YES')
C = [0] * (1 << N)
C[0] = str(A)
pos = 0
while AB % 2 == 0:
pos += 1
AB >>= 1
for i in range(1, 1 << N):
k = 0
b = i
while b % 2 == 0:
k += 1
b >>= 1
A ^= 1 << ((pos + k + 1) % N)
C[i] = str(A)
print(' '.join(C))
```
No
| 15,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
Submitted Solution:
```
N,A,B=[int(x) for x in input().split()]
SA=bin(A)[2:]
SB=bin(B)[2:]
mx=max(len(SA),len(SB))
SA=("0"*mx+SA)[-mx:]
SB=("0"*mx+SB)[-mx:]
diff=0
L=[]
for i in range(len(SA)):
if SA[i]!=SB[i]:
L.append(i)
diff+=1
if diff%2==0:
print('NO')
else:
out=str(int(SA,2))+" "
print('YES')
for i in L:
if SA[i]=="1":
SA=SA[:i]+"0"+SA[i+1:]
else:
SA=SA[:i]+"1"+SA[i+1:]
out+=str(int(SA,2))+" "
for j in range(2**N-i-2):
if SA[0]=="0":
SA="1"+SA[1:]
else:
SA="0"+SA[1:]
out+=str(int(SA,2))+" "
print(out.strip())
"""
for t in out.split():
print(("0000"+bin(int(t))[2:])[-3:])
"""
```
No
| 15,778 |
Provide a correct Python 3 solution for this coding contest problem.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
"Correct Solution:
```
n = int(input())
ct = 0
while ct < n:
ct += 111
print(ct)
```
| 15,779 |
Provide a correct Python 3 solution for this coding contest problem.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
"Correct Solution:
```
print(int(111*(1+int((int(input())-1)/111))))
```
| 15,780 |
Provide a correct Python 3 solution for this coding contest problem.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
"Correct Solution:
```
import math
N = int(input())
r = math.ceil(N/111.0)*111
print(r)
```
| 15,781 |
Provide a correct Python 3 solution for this coding contest problem.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
"Correct Solution:
```
print(str((int(input())-1)//111+1)*3)
```
| 15,782 |
Provide a correct Python 3 solution for this coding contest problem.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
"Correct Solution:
```
a = int(input())
while len(set(str(a)))!=1:
a+=1
print(a)
```
| 15,783 |
Provide a correct Python 3 solution for this coding contest problem.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
"Correct Solution:
```
N = int(input())
ans = (((N - 1) // 111) + 1)*111
print(ans)
```
| 15,784 |
Provide a correct Python 3 solution for this coding contest problem.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
"Correct Solution:
```
n = int(input())
while n % 111:
n += 1
print(n)
```
| 15,785 |
Provide a correct Python 3 solution for this coding contest problem.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
"Correct Solution:
```
n = int(input())
print(111 * ((n-1) // 111 + 1))
```
| 15,786 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
Submitted Solution:
```
q,m=divmod(int(input()),111);print((q+1*(m>0))*111)
```
Yes
| 15,787 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
Submitted Solution:
```
N = int(input())
print(111*-(-N//111))
```
Yes
| 15,788 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
Submitted Solution:
```
import math
N = int(input())
print(111*math.ceil(N/111))
```
Yes
| 15,789 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
Submitted Solution:
```
print(111*(1+(int(input())-1)//111))
```
Yes
| 15,790 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
Submitted Solution:
```
N = int(input())
x = 111
for i in range(1,9):
a = 111 *i
if N <= a:
x = a
print (x)
break
```
No
| 15,791 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
Submitted Solution:
```
N = int(input())
repdigit = [111, 222, 333, 444, 555, 666, 777, 888, 999]
for rep in repdigit:
if N >= rep:
print(rep)
break
```
No
| 15,792 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
Submitted Solution:
```
n = int(input())
for i in range(1,9):
if n <= 111*i:
break
print(111*i)
```
No
| 15,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777
Submitted Solution:
```
a=input()
flag=0
for i in range(2):
if a[i]==a[i+1]:
pass
else:
flag+=1
if flag==0:
print(int(a))
else:
w=int(a[0])
c=int(a)
e=1
a=0
for i in range(3):
a+=w*e
e*=10
if c<a:
print(a)
else:
print(2*a)
```
No
| 15,794 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yui loves shopping. She lives in Yamaboshi City and there is a train service in the city. The city can be modelled as a very long number line. Yui's house is at coordinate 0.
There are N shopping centres in the city, located at coordinates x_{1}, x_{2}, ..., x_{N} respectively. There are N + 2 train stations, one located at coordinate 0, one located at coordinate L, and one located at each shopping centre.
At time 0, the train departs from position 0 to the positive direction. The train travels at a constant speed of 1 unit per second. At time L, the train will reach the last station, the station at coordinate L. The train immediately moves in the opposite direction at the same speed. At time 2L, the train will reach the station at coordinate 0 and it immediately moves in the opposite direction again. The process repeats indefinitely.
When the train arrives at a station where Yui is located, Yui can board or leave the train immediately. At time 0, Yui is at the station at coordinate 0.
Yui wants to go shopping in all N shopping centres, in any order, and return home after she finishes her shopping. She needs to shop for t_{i} seconds in the shopping centre at coordinate x_{i}. She must finish her shopping in one shopping centre before moving to the next shopping centre. Yui can immediately start shopping when she reaches a station with a shopping centre and she can immediately board the train when she finishes shopping.
Yui wants to spend the minimum amount of time to finish her shopping. Can you help her determine the minimum number of seconds required to complete her shopping?
Constraints
* 1 \leq N \leq 300000
* 1 \leq L \leq 10^{9}
* 0 < x_{1} < x_{2} < ... < x_{N} < L
* 1 \leq t_{i} \leq 10^{9}
* All values in the input are integers.
Input
Input is given from Standard Input in the following format:
N L
x_{1} x_{2} ... x_{N}
t_{1} t_{2} ... t_{N}
Output
Print the minimum time (in seconds) required for Yui to finish shopping at all N shopping centres and return home.
Examples
Input
2 10
5 8
10 4
Output
40
Input
2 10
5 8
10 5
Output
60
Input
5 100
10 19 28 47 68
200 200 200 200 200
Output
1200
Input
8 1000000000
2018 123456 1719128 1929183 9129198 10100101 77777777 120182018
99999999 1000000000 1000000000 11291341 1 200 1 123812831
Output
14000000000
Submitted Solution:
```
N,L=map(int,input().split())
x=[int(i) for i in input().split()]
t=[int(i) for i in input().split()]
l=[0 for i in range(N)]
for i in range(N):
p=t[i]//L
l[i]+=2*p
if 2*(t[i]-2*p)<=max([2*L-abs(L-2*x[i]),abs(L-2*x[i])]):
l[i]+=1
else:
l[i]+=2
print(int(round(sum(l)+0.5,0))*L)
```
No
| 15,795 |
Provide a correct Python 3 solution for this coding contest problem.
In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographically smallest one.
Constraints
* 1 \leq N,K \leq 3 × 10^5
* N and K are integers.
Input
Input is given from Standard Input in the following format:
K N
Output
Print the (X/2)-th (rounded up to the nearest integer) lexicographically smallest sequence listed in FEIS, with spaces in between, where X is the total number of sequences listed in FEIS.
Examples
Input
3 2
Output
2 1
Input
2 4
Output
1 2 2 2
Input
5 14
Output
3 3 3 3 3 3 3 3 3 3 3 3 2 2
"Correct Solution:
```
K, N = map(int, input().split())
if K % 2 == 0:
ans = [K//2] + [K] * (N-1)
else:
ans = [(K+1)//2] * N
for i in range(N//2):
if ans[-1] == 1:
ans.pop()
else:
ans[-1] -= 1
ans += [K] * (N - len(ans))
print(' '.join(map(str, ans)))
```
| 15,796 |
Provide a correct Python 3 solution for this coding contest problem.
In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographically smallest one.
Constraints
* 1 \leq N,K \leq 3 × 10^5
* N and K are integers.
Input
Input is given from Standard Input in the following format:
K N
Output
Print the (X/2)-th (rounded up to the nearest integer) lexicographically smallest sequence listed in FEIS, with spaces in between, where X is the total number of sequences listed in FEIS.
Examples
Input
3 2
Output
2 1
Input
2 4
Output
1 2 2 2
Input
5 14
Output
3 3 3 3 3 3 3 3 3 3 3 3 2 2
"Correct Solution:
```
N,K=map(int,input().split())
#1 2 3...N
if N%2==0:
L=[str(N)]*K
L[0]=str(N//2)
print(" ".join(L))
exit()
#L[0]=N//2+1
#N//2のずれ?
L=[(N//2)+1]*K
for i in range(K//2):
if L[-1]==1:
L.pop(-1)
elif len(L)!=K:
L[-1]-=1
L+=[N]*(K-len(L))
else:
L[-1]-=1
L=list(map(str,L))
print(" ".join(L))
```
| 15,797 |
Provide a correct Python 3 solution for this coding contest problem.
In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographically smallest one.
Constraints
* 1 \leq N,K \leq 3 × 10^5
* N and K are integers.
Input
Input is given from Standard Input in the following format:
K N
Output
Print the (X/2)-th (rounded up to the nearest integer) lexicographically smallest sequence listed in FEIS, with spaces in between, where X is the total number of sequences listed in FEIS.
Examples
Input
3 2
Output
2 1
Input
2 4
Output
1 2 2 2
Input
5 14
Output
3 3 3 3 3 3 3 3 3 3 3 3 2 2
"Correct Solution:
```
def main():
K,N = map(int,input().split())
if K % 2 == 0:
ans = [K//2]
for i in range(N-1):
ans.append(K)
else:
back = N // 2
mid = K // 2 + 1
ans = [mid for i in range(N)]
for i in range(back):
if ans[-1] == 1:
ans.pop()
else:
ans[-1] -= 1
while len(ans) < N:
ans.append(K)
print(' '.join(map(str, ans)))
if __name__ == '__main__':
main()
```
| 15,798 |
Provide a correct Python 3 solution for this coding contest problem.
In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographically smallest one.
Constraints
* 1 \leq N,K \leq 3 × 10^5
* N and K are integers.
Input
Input is given from Standard Input in the following format:
K N
Output
Print the (X/2)-th (rounded up to the nearest integer) lexicographically smallest sequence listed in FEIS, with spaces in between, where X is the total number of sequences listed in FEIS.
Examples
Input
3 2
Output
2 1
Input
2 4
Output
1 2 2 2
Input
5 14
Output
3 3 3 3 3 3 3 3 3 3 3 3 2 2
"Correct Solution:
```
# seishin.py
K, N = map(int, input().split())
if K % 2 == 0:
print(*[K//2] + [K]*(N-1))
else:
X = [(K+1)//2] * N
for i in range(N//2):
if X[-1] == 1:
X.pop()
else:
X[-1] -= 1
X.extend([K]*(N-len(X)))
print(*X)
```
| 15,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.