id
stringlengths 24
27
| content
stringlengths 37
384k
| max_stars_repo_path
stringlengths 51
51
|
---|---|---|
condefects-python_data_401 | import collections,sys,math,functools,operator,itertools,bisect,heapq,decimal,string,time,random
#sys.setrecursionlimit(10**9)
#sys.set_int_max_str_digits(0
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
group_members = collections.defaultdict(list)
for member in range(self.n):
group_members[self.find(member)].append(member)
return group_members
def __str__(self):
return ''.join(f'{r}: {m}' for r, m in self.all_group_members().items())
input = sys.stdin.readline
#n = int(input())
#alist = list(map(int,input().split()))
#alist = []
#s = input()
n,m,k = map(int,input().split())
if k % 2 == 1:
exit(print('No'))
edge = [[] for i in range(n)]
uf = UnionFind(n)
c = collections.defaultdict(int)
for i in range(m):
u,v = map(int,input().split())
u-=1
v-=1
if uf.same(u,v) == True:
continue
uf.union(u,v)
c[(u,v)] = i
edge[u].append(v)
edge[v].append(u)
#for i in range(n):
# alist.append(list(map(int,input().split())))
ans = []
lamp = [0 for i in range(n)]
l = 0
p = [-1 for i in range(n)]
for i in range(n):
if i != uf.find(i):
continue
d = collections.deque()
d.append(~i)
d.append(i)
if l == k:
break
while d:
if l == k:
break
now = d.pop()
if now < 0:
now = ~now
if now == 0:
continue
if lamp[now] == 0:
if l < k:
l -= lamp[now] + lamp[p[now]]
lamp[now] ^= 1
lamp[p[now]] ^= 1
l += lamp[now] + lamp[p[now]]
ans.append((now,p[now]))
else:
for j in edge[now]:
if j == p[now]:
continue
p[j] = now
d.append(~j)
d.append(j)
if l != k:
print('No')
else:
assert sum(lamp) == k
print('Yes')
print(len(ans))
for i,j in ans:
print(c[min(i,j),max(i,j)]+1,end=' ')
import collections,sys,math,functools,operator,itertools,bisect,heapq,decimal,string,time,random
#sys.setrecursionlimit(10**9)
#sys.set_int_max_str_digits(0
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
group_members = collections.defaultdict(list)
for member in range(self.n):
group_members[self.find(member)].append(member)
return group_members
def __str__(self):
return ''.join(f'{r}: {m}' for r, m in self.all_group_members().items())
input = sys.stdin.readline
#n = int(input())
#alist = list(map(int,input().split()))
#alist = []
#s = input()
n,m,k = map(int,input().split())
if k % 2 == 1:
exit(print('No'))
edge = [[] for i in range(n)]
uf = UnionFind(n)
c = collections.defaultdict(int)
for i in range(m):
u,v = map(int,input().split())
u-=1
v-=1
if uf.same(u,v) == True:
continue
uf.union(u,v)
c[(u,v)] = i
edge[u].append(v)
edge[v].append(u)
#for i in range(n):
# alist.append(list(map(int,input().split())))
ans = []
lamp = [0 for i in range(n)]
l = 0
p = [-1 for i in range(n)]
for i in range(n):
if i != uf.find(i):
continue
d = collections.deque()
d.append(~i)
d.append(i)
if l == k:
break
while d:
if l == k:
break
now = d.pop()
if now < 0:
now = ~now
if now == i:
continue
if lamp[now] == 0:
if l < k:
l -= lamp[now] + lamp[p[now]]
lamp[now] ^= 1
lamp[p[now]] ^= 1
l += lamp[now] + lamp[p[now]]
ans.append((now,p[now]))
else:
for j in edge[now]:
if j == p[now]:
continue
p[j] = now
d.append(~j)
d.append(j)
if l != k:
print('No')
else:
assert sum(lamp) == k
print('Yes')
print(len(ans))
for i,j in ans:
print(c[min(i,j),max(i,j)]+1,end=' ') | ConDefects/ConDefects/Code/abc345_f/Python/52944760 |
condefects-python_data_402 | import sys
sys.setrecursionlimit(10**7)
N, M, K = map(int, input().split())
G = [[] for _ in range(N)]
for i in range(M):
u, v = map(int, input().split())
u -= 1
v -= 1
G[u].append((v, i+1))
G[v].append((u, i+1))
vis = [0]*N
lig = [0]*N
cnt = 0
ans = []
flg = False
def dfs(now, pre=-1, edge=-1):
global cnt
vis[now] = 1
for nxt, e in G[now]:
if vis[nxt] == 0:
vis[nxt] = 1
dfs(nxt, now, e)
if pre != -1 and lig[now] == 0 and cnt < K:
lig[now] = 1
cnt += 1
if lig[pre] == 0:
lig[pre] = 1
cnt += 1
else:
lig[pre] = 0
cnt -= 1
ans.append(edge)
if cnt == K:
global flg
flg = True
# print(now, lig)
for i in range(N):
if vis[i] == 0 and cnt < K:
dfs(i)
if flg:
print('Yes')
print(len(ans))
print(*ans)
else:
print('No')
import sys
sys.setrecursionlimit(10**7)
N, M, K = map(int, input().split())
G = [[] for _ in range(N)]
for i in range(M):
u, v = map(int, input().split())
u -= 1
v -= 1
G[u].append((v, i+1))
G[v].append((u, i+1))
vis = [0]*N
lig = [0]*N
cnt = 0
ans = []
flg = False
def dfs(now, pre=-1, edge=-1):
global cnt
vis[now] = 1
for nxt, e in G[now]:
if vis[nxt] == 0:
vis[nxt] = 1
dfs(nxt, now, e)
if pre != -1 and lig[now] == 0 and cnt < K:
lig[now] = 1
cnt += 1
if lig[pre] == 0:
lig[pre] = 1
cnt += 1
else:
lig[pre] = 0
cnt -= 1
ans.append(edge)
if cnt == K:
global flg
flg = True
# print(now, lig)
for i in range(N):
if vis[i] == 0 and cnt < K:
dfs(i)
if flg or K==0:
print('Yes')
print(len(ans))
print(*ans)
else:
print('No')
| ConDefects/ConDefects/Code/abc345_f/Python/51504279 |
condefects-python_data_403 | N = int(input())
D = list(map(int, input().split()))
ans = 0
for i in range(1, N+1):
m = list(str(i))
for j in range(1, D[i-1]):
d = list(str(j))
if len(set(m + d)) == 1:
ans += 1
print(ans)
N = int(input())
D = list(map(int, input().split()))
ans = 0
for i in range(1, N+1):
m = list(str(i))
for j in range(1, D[i-1]+1):
d = list(str(j))
if len(set(m + d)) == 1:
ans += 1
print(ans) | ConDefects/ConDefects/Code/abc328_b/Python/54943660 |
condefects-python_data_404 | N = int(input())
D = list(map(int,input().split()))
ans = 0
for x in range(1,N+1):
for y in range(1,D[x-1]+1):
x = str(x)
a = list(x)
a = list(map(int,a))
y = str(y)
b = list(y)
b = list(map(int,b))
a = set(a)
b = set(b)
a = list(a)
b = list(b)
print(a,b)
a = list(a)
b = list(b)
if len(a) == 1 and len(b) == 1 and a == b:
ans += 1
print(ans)
N = int(input())
D = list(map(int,input().split()))
ans = 0
for x in range(1,N+1):
for y in range(1,D[x-1]+1):
x = str(x)
a = list(x)
a = list(map(int,a))
y = str(y)
b = list(y)
b = list(map(int,b))
a = set(a)
b = set(b)
a = list(a)
b = list(b)
#print(a,b)
a = list(a)
b = list(b)
if len(a) == 1 and len(b) == 1 and a == b:
ans += 1
print(ans)
| ConDefects/ConDefects/Code/abc328_b/Python/54688793 |
condefects-python_data_405 | N=int(input())
D=input().split()
ans=0
for Mon in range(1,N+1):
Mlist=list(str(Mon))
for Day in range(1,int(D[Mon-1])):
Dlist=list(str(Day))
if len(Mlist)==1 and len(Dlist)==1 and Mlist[0]==Dlist[0]:
ans+=1
# print(Mon,Day)
if len(Mlist)==1 and len(Dlist)==2 and Mlist[0]==Dlist[0]==Dlist[1]:
ans+=1
# print(Mon,Day)
if len(Mlist)==2 and len(Dlist)==1 and Mlist[0]==Mlist[1]==Dlist[0]:
ans+=1
# print(Mon,Day)
if len(Mlist)==2 and len(Dlist)==2 and Mlist[0]==Mlist[1]==Dlist[0]==Dlist[1]:
ans+=1
# print(Mon,Day)
print(ans)
N=int(input())
D=input().split()
ans=0
for Mon in range(1,N+1):
Mlist=list(str(Mon))
for Day in range(1,int(D[Mon-1])+1):
Dlist=list(str(Day))
if len(Mlist)==1 and len(Dlist)==1 and Mlist[0]==Dlist[0]:
ans+=1
# print(Mon,Day)
if len(Mlist)==1 and len(Dlist)==2 and Mlist[0]==Dlist[0]==Dlist[1]:
ans+=1
# print(Mon,Day)
if len(Mlist)==2 and len(Dlist)==1 and Mlist[0]==Mlist[1]==Dlist[0]:
ans+=1
# print(Mon,Day)
if len(Mlist)==2 and len(Dlist)==2 and Mlist[0]==Mlist[1]==Dlist[0]==Dlist[1]:
ans+=1
# print(Mon,Day)
print(ans) | ConDefects/ConDefects/Code/abc328_b/Python/54743139 |
condefects-python_data_406 | INT =lambda: int(input())
MI = lambda: map(int,input().split())
MI_DEC = lambda: map(lambda x: int(x) -1, input().split())
LI = lambda: list(map(int, input().split()))
def main() -> None:
n = INT()
s = LI()
count = 0
for m in range(n):
for d in range(1, s[m]):
if len(set(str(m+1)+str(d))) == 1:
count += 1
print(count)
if __name__ == '__main__':
main()
INT =lambda: int(input())
MI = lambda: map(int,input().split())
MI_DEC = lambda: map(lambda x: int(x) -1, input().split())
LI = lambda: list(map(int, input().split()))
def main() -> None:
n = INT()
s = LI()
count = 0
for m in range(n):
for d in range(1, s[m]+1):
if len(set(str(m+1)+str(d))) == 1:
count += 1
print(count)
if __name__ == '__main__':
main() | ConDefects/ConDefects/Code/abc328_b/Python/54041860 |
condefects-python_data_407 | INT =lambda: int(input())
MI = lambda: map(int,input().split())
MI_DEC = lambda: map(lambda x: int(x) -1, input().split())
LI = lambda: list(map(int, input().split()))
def main() -> None:
n = INT()
s = LI()
count = 0
for m, di in enumerate(s, start=1):
for d in range(1, di):
ss = set(str(m)).union(set(str(d)))
if len(ss) == 1:
count += 1
print(count)
if __name__ == '__main__':
main()
INT =lambda: int(input())
MI = lambda: map(int,input().split())
MI_DEC = lambda: map(lambda x: int(x) -1, input().split())
LI = lambda: list(map(int, input().split()))
def main() -> None:
n = INT()
s = LI()
count = 0
for m, di in enumerate(s, start=1):
for d in range(1, di+1):
ss = set(str(m)).union(set(str(d)))
if len(ss) == 1:
count += 1
print(count)
if __name__ == '__main__':
main() | ConDefects/ConDefects/Code/abc328_b/Python/54041719 |
condefects-python_data_408 | N=int(input())
D=list(map(int,input().split()))
count=0
for i in range(1,N+1):
j=i%10
if i==j or i==j*10+j:
for k in range(D[i-1]):
if k==j or k==j*10+j:
count=count+1
print(count)
N=int(input())
D=list(map(int,input().split()))
count=0
for i in range(1,N+1):
j=i%10
if i==j or i==j*10+j:
for k in range(1,D[i-1]+1):
if k==j or k==j*10+j:
count=count+1
print(count)
| ConDefects/ConDefects/Code/abc328_b/Python/54961220 |
condefects-python_data_409 | from heapq import heappush, heappop, heapify
import sys
from collections import defaultdict, deque,Counter
from math import ceil, floor, sqrt, factorial,gcd
from itertools import permutations, combinations,product #順列,組み合わせ,重複順列
from bisect import bisect_left, bisect_right
from copy import deepcopy
from functools import lru_cache #@lru_cache(maxsize=None)
from fractions import Fraction
from copy import deepcopy
sys.setrecursionlimit(10**6)
# input = sys.stdin.readline
vector1 = [[0, -1], [1, 0], [0, 1], [-1, 0]]
vector2 = [[0, 1], [1, 0], [-1, 0], [0, -1],
[1,-1], [-1, 1], [1, 1], [-1, -1]]
def main():
inf = 1 << 40
N,K,P = map(int,input().split())
dp = defaultdict(lambda : inf)
dp[tuple([0]*K)] = 0
for _ in range(N):
r = list(map(int,input().split()))
c = r[0]
array = r[1:]
newdp = defaultdict(lambda:inf)
for key in dp:
newdp[key] = min(newdp[key],dp[key])
tmp = list(key)
for i in range(K):
tmp[i] = min(P,tmp[i] + array[i])
tmp = tuple(tmp)
newdp[tmp] = min(dp[key]+c,newdp[tmp])
dp = newdp
if dp[tuple([P]*K)] == 1 <<30:
print(-1)
else:
print(dp[tuple([P]*K)])
if __name__ == '__main__':
main()
from heapq import heappush, heappop, heapify
import sys
from collections import defaultdict, deque,Counter
from math import ceil, floor, sqrt, factorial,gcd
from itertools import permutations, combinations,product #順列,組み合わせ,重複順列
from bisect import bisect_left, bisect_right
from copy import deepcopy
from functools import lru_cache #@lru_cache(maxsize=None)
from fractions import Fraction
from copy import deepcopy
sys.setrecursionlimit(10**6)
# input = sys.stdin.readline
vector1 = [[0, -1], [1, 0], [0, 1], [-1, 0]]
vector2 = [[0, 1], [1, 0], [-1, 0], [0, -1],
[1,-1], [-1, 1], [1, 1], [-1, -1]]
def main():
inf = 1 << 40
N,K,P = map(int,input().split())
dp = defaultdict(lambda : inf)
dp[tuple([0]*K)] = 0
for _ in range(N):
r = list(map(int,input().split()))
c = r[0]
array = r[1:]
newdp = defaultdict(lambda:inf)
for key in dp:
newdp[key] = min(newdp[key],dp[key])
tmp = list(key)
for i in range(K):
tmp[i] = min(P,tmp[i] + array[i])
tmp = tuple(tmp)
newdp[tmp] = min(dp[key]+c,newdp[tmp])
dp = newdp
if dp[tuple([P]*K)] == inf:
print(-1)
else:
print(dp[tuple([P]*K)])
if __name__ == '__main__':
main()
| ConDefects/ConDefects/Code/abc322_e/Python/53004931 |
condefects-python_data_410 | from itertools import product
N,K,P=map(int,input().split())
dp=[10**18]*(P+1)**K
dp[0]=0
for i in range(N):
I=list(map(int,input().split()))
for p in product(reversed(range(P+1)),repeat=K):
pn=[0]*K
for j in range(K):
pn[j]=min(P,p[j]+I[j+1])
pi=0
for pp in p:
pi*=(P+1)
pi+=pp
pni=0
for pp in pn:
pni*=(P+1)
pni+=pp
dp[pni]=min(dp[pni],dp[pi]+I[0])
print(dp[-1] if dp[-1]<10**10 else -1)
from itertools import product
N,K,P=map(int,input().split())
dp=[10**18]*(P+1)**K
dp[0]=0
for i in range(N):
I=list(map(int,input().split()))
for p in product(reversed(range(P+1)),repeat=K):
pn=[0]*K
for j in range(K):
pn[j]=min(P,p[j]+I[j+1])
pi=0
for pp in p:
pi*=(P+1)
pi+=pp
pni=0
for pp in pn:
pni*=(P+1)
pni+=pp
dp[pni]=min(dp[pni],dp[pi]+I[0])
print(dp[-1] if dp[-1]<10**18 else -1) | ConDefects/ConDefects/Code/abc322_e/Python/53314219 |
condefects-python_data_411 | # 5進数で考える
N = int(input()) - 1
rems = []
while N > 0:
quotient = N // 5
remainder = N % 5
rems.append(remainder)
N = quotient
converted = rems[::-1]
converted = ''.join([str(c * 2) for c in converted])
print(converted)
# 5進数で考える
N = int(input()) - 1
if N == 0:
print(0)
rems = []
while N > 0:
quotient = N // 5
remainder = N % 5
rems.append(remainder)
N = quotient
converted = rems[::-1]
converted = ''.join([str(c * 2) for c in converted])
print(converted)
| ConDefects/ConDefects/Code/abc336_c/Python/54629693 |
condefects-python_data_412 | N = int(input())
import numpy as np
print(np.base_repr(N-1,5)*2)
N = int(input())
import numpy as np
print(int(np.base_repr(N-1,5))*2) | ConDefects/ConDefects/Code/abc336_c/Python/54442370 |
condefects-python_data_413 | def base10int(value, base):
if int(value / base): return base10int(int(value / base), base) + str(value % base)
return str(value % base)
def dbl(x): return str(2*int(x))
print("".join(list(map(dbl, base10int(int(input()), 5)))))
def base10int(value, base):
if int(value / base): return base10int(int(value / base), base) + str(value % base)
return str(value % base)
def dbl(x): return str(2*int(x))
print("".join(list(map(dbl, base10int(int(input())-1, 5))))) | ConDefects/ConDefects/Code/abc336_c/Python/54444134 |
condefects-python_data_414 | n = int(input()) - 1
goodint = []
while n != 0:
goodint.append(n % 5)
n //= 5
goodint = goodint[::-1]
new_list = []
for i in goodint:
print(2*i, end = "")
n = int(input()) - 1
goodint = []
if n == 0:
print(0)
while n != 0:
goodint.append(n % 5)
n //= 5
goodint = goodint[::-1]
new_list = []
for i in goodint:
print(2*i, end = "") | ConDefects/ConDefects/Code/abc336_c/Python/54915792 |
condefects-python_data_415 | n,m = map(int,input().split())
a = [input() for _ in range(n)]
for i in range(n-9):
for j in range(m-9+1):
if (all(row[j:j+4] == "###." for row in a[i:i+3]) and
a[i+3][j:j+4] == "...." and a[i+5][j+5:j+9] =="...." and
all(row[j+5:j+9] == ".###" for row in a[i+6:i+9])):
print(i+1,j+1)
n,m = map(int,input().split())
a = [input() for _ in range(n)]
for i in range(n-9+1):
for j in range(m-9+1):
if (all(row[j:j+4] == "###." for row in a[i:i+3]) and
a[i+3][j:j+4] == "...." and a[i+5][j+5:j+9] =="...." and
all(row[j+5:j+9] == ".###" for row in a[i+6:i+9])):
print(i+1,j+1) | ConDefects/ConDefects/Code/abc312_b/Python/45967113 |
condefects-python_data_416 | """
y 軸の小さい方から大きい方に遷移
とりあえずy軸でソート
i -> j に遷移できるか
T_j - T_i >= Y_j - Y_i + |X_j - X_i|
であればOK
T_j - Y_j >= T_i - Y_i + |X_j - X_i|
Z_i = T_i - Y_i
Z_j >= Z_i + |X_j - X_i|
dp[i] := 時刻 T_i に(X_i, Y_i) にいるときの合計の最大値
(Z, X) を持って range tree ?
区間が三角形なんだよな
45度回転でできるか?
"""
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from bisect import bisect_left
class SegTree:
def __init__(self, n, e, ope, lst=[]):
self.N0 = 2 ** (n - 1).bit_length()
self.e = e
self.ope = ope
self.data = [e] * (2 * self.N0)
if lst:
for i in range(n):
self.data[self.N0 + i] = lst[i]
for i in range(self.N0 - 1, 0, -1):
self.data[i] = self.ope(self.data[2 * i], self.data[2 * i + 1])
def build(self):
for i in range(self.N0 - 1, 0, -1):
self.data[i] = self.ope(self.data[2 * i], self.data[2 * i + 1])
def update(self, i, x): #a_iの値をxに更新
i += self.N0
self.data[i] = x
while i > 1:
i >>= 1
self.data[i] = self.ope(self.data[2 * i], self.data[2 * i + 1])
def add(self, i, x):
self.update(i, x + self.get(i))
def set(self, i, x):
self.data[self.N0 + i] = x
def query(self, l, r): #区間[l, r)での演算結果
if r <= l:
return self.e
lres = self.e
rres = self.e
l += self.N0
r += self.N0
while l < r:
if l & 1:
lres = self.ope(lres, self.data[l])
l += 1
if r & 1:
r -= 1
rres = self.ope(self.data[r], rres)
l >>= 1
r >>= 1
return self.ope(lres, rres)
def get(self, i): #a_iの値を返す
return self.data[self.N0 + i]
class RangeTree:
def __init__(self, e, ope, inflog=32):
self.e = e
self.ope = ope
self.ps = []
self.inflog = inflog
self.inf = 1 << self.inflog
self.mask = (self.inf) - 1
def add_point(self, x, y):
self.ps.append((x << self.inflog) | y)
def _merge(self, A, B):
ret = []
al = len(A)
bl = len(B)
ap = 0
bp = 0
while ap < al and bp < bl:
if A[ap] < B[bp]:
ret.append(A[ap])
ap += 1
elif A[ap] == B[bp]:
ret.append(A[ap])
ap += 1
bp += 1
else:
ret.append(B[bp])
bp += 1
if ap == al:
ret += B[bp:]
else:
ret += A[ap:]
return ret
def build(self):
self.ps = sorted(set(self.ps))
self.n = len(self.ps)
self.ys = [[] for _ in range(2 * self.n)]
for i in range(self.n):
self.ys[i + self.n].append(self.ps[i] & self.mask)
for i in range(self.n - 1, -1, -1):
self.ys[i] = self._merge(self.ys[i << 1], self.ys[(i << 1) | 1])
self.le = [0] * (2 * self.n + 1)
for i in range(1, 2 * self.n + 1):
self.le[i] = self.le[i - 1] + len(self.ys[i - 1])
self.seg = SegTree(self.le[-1], self.e, self.ope)
def _idx(self, x):
return bisect_left(self.ps, x << self.inflog)
def _idy(self, i, y):
return bisect_left(self.ys[i], y) + self.le[i]
def upd(self, x, y, w):
i = bisect_left(self.ps, (x << self.inflog) | y)
i += self.n
while i > 0:
bef = self.seg.get(self._idy(i, y))
if w > bef:
self.seg.update(self._idy(i, y), w)
i >>= 1
def add_init(self, xyw):
plus = [0] * (self.le[-1])
for x, y, w in xyw:
i = bisect_left(self.ps, (x << self.inflog) | y)
i += self.n
while i > 0:
plus[self._idy(i, y)] += w
i >>= 1
for i, p in enumerate(plus):
if p != 0:
self.seg.add(i, p)
def query(self, l, d, r, u):
L = self.e
R = self.e
a = self._idx(l) + self.n
b = self._idx(r) + self.n
while a < b:
if a & 1:
L = self.ope(L, self.seg.query(self._idy(a, d), self._idy(a, u)))
a += 1
if b & 1:
b -= 1
R = self.ope(self.seg.query(self._idy(b, d), self._idy(b, u)), R)
a >>= 1
b >>= 1
return self.ope(L, R)
n = int(input())
points = [list(map(int, input().split())) for _ in range(n)]
points.sort(key=lambda x:(x[2], x[0]))
inf = 1 << 40
Z = [0]
X = [0]
A = [0]
for t, x, y, a in points:
z = t - y
Z.append(z + x)
X.append(z - x)
A.append(a)
Z_se = set(Z)
X_se = set(X)
dic = {z:i for i, z in enumerate(sorted(Z_se))}
Z = [dic[z] for z in Z]
dic = {x:i for i, x in enumerate(sorted(X_se))}
X = [dic[x] for x in X]
rt = RangeTree(-inf, max, 33)
for z, x in zip(Z, X):
rt.add_point(z, x)
rt.build()
rt.upd(0, 0, 0)
ans = 0
for z, x, a in zip(Z[1:], X[1:], A[1:]):
ma = rt.query(0, 0, z + 1, x + 1)
ma += a
rt.upd(z, x, ma)
ans = max(ans, ma)
print(ans)
"""
y 軸の小さい方から大きい方に遷移
とりあえずy軸でソート
i -> j に遷移できるか
T_j - T_i >= Y_j - Y_i + |X_j - X_i|
であればOK
T_j - Y_j >= T_i - Y_i + |X_j - X_i|
Z_i = T_i - Y_i
Z_j >= Z_i + |X_j - X_i|
dp[i] := 時刻 T_i に(X_i, Y_i) にいるときの合計の最大値
(Z, X) を持って range tree ?
区間が三角形なんだよな
45度回転でできるか?
"""
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from bisect import bisect_left
class SegTree:
def __init__(self, n, e, ope, lst=[]):
self.N0 = 2 ** (n - 1).bit_length()
self.e = e
self.ope = ope
self.data = [e] * (2 * self.N0)
if lst:
for i in range(n):
self.data[self.N0 + i] = lst[i]
for i in range(self.N0 - 1, 0, -1):
self.data[i] = self.ope(self.data[2 * i], self.data[2 * i + 1])
def build(self):
for i in range(self.N0 - 1, 0, -1):
self.data[i] = self.ope(self.data[2 * i], self.data[2 * i + 1])
def update(self, i, x): #a_iの値をxに更新
i += self.N0
self.data[i] = x
while i > 1:
i >>= 1
self.data[i] = self.ope(self.data[2 * i], self.data[2 * i + 1])
def add(self, i, x):
self.update(i, x + self.get(i))
def set(self, i, x):
self.data[self.N0 + i] = x
def query(self, l, r): #区間[l, r)での演算結果
if r <= l:
return self.e
lres = self.e
rres = self.e
l += self.N0
r += self.N0
while l < r:
if l & 1:
lres = self.ope(lres, self.data[l])
l += 1
if r & 1:
r -= 1
rres = self.ope(self.data[r], rres)
l >>= 1
r >>= 1
return self.ope(lres, rres)
def get(self, i): #a_iの値を返す
return self.data[self.N0 + i]
class RangeTree:
def __init__(self, e, ope, inflog=32):
self.e = e
self.ope = ope
self.ps = []
self.inflog = inflog
self.inf = 1 << self.inflog
self.mask = (self.inf) - 1
def add_point(self, x, y):
self.ps.append((x << self.inflog) | y)
def _merge(self, A, B):
ret = []
al = len(A)
bl = len(B)
ap = 0
bp = 0
while ap < al and bp < bl:
if A[ap] < B[bp]:
ret.append(A[ap])
ap += 1
elif A[ap] == B[bp]:
ret.append(A[ap])
ap += 1
bp += 1
else:
ret.append(B[bp])
bp += 1
if ap == al:
ret += B[bp:]
else:
ret += A[ap:]
return ret
def build(self):
self.ps = sorted(set(self.ps))
self.n = len(self.ps)
self.ys = [[] for _ in range(2 * self.n)]
for i in range(self.n):
self.ys[i + self.n].append(self.ps[i] & self.mask)
for i in range(self.n - 1, -1, -1):
self.ys[i] = self._merge(self.ys[i << 1], self.ys[(i << 1) | 1])
self.le = [0] * (2 * self.n + 1)
for i in range(1, 2 * self.n + 1):
self.le[i] = self.le[i - 1] + len(self.ys[i - 1])
self.seg = SegTree(self.le[-1], self.e, self.ope)
def _idx(self, x):
return bisect_left(self.ps, x << self.inflog)
def _idy(self, i, y):
return bisect_left(self.ys[i], y) + self.le[i]
def upd(self, x, y, w):
i = bisect_left(self.ps, (x << self.inflog) | y)
i += self.n
while i > 0:
bef = self.seg.get(self._idy(i, y))
if w > bef:
self.seg.update(self._idy(i, y), w)
i >>= 1
def add_init(self, xyw):
plus = [0] * (self.le[-1])
for x, y, w in xyw:
i = bisect_left(self.ps, (x << self.inflog) | y)
i += self.n
while i > 0:
plus[self._idy(i, y)] += w
i >>= 1
for i, p in enumerate(plus):
if p != 0:
self.seg.add(i, p)
def query(self, l, d, r, u):
L = self.e
R = self.e
a = self._idx(l) + self.n
b = self._idx(r) + self.n
while a < b:
if a & 1:
L = self.ope(L, self.seg.query(self._idy(a, d), self._idy(a, u)))
a += 1
if b & 1:
b -= 1
R = self.ope(self.seg.query(self._idy(b, d), self._idy(b, u)), R)
a >>= 1
b >>= 1
return self.ope(L, R)
n = int(input())
points = [list(map(int, input().split())) for _ in range(n)]
points.sort(key=lambda x:(x[2], x[0]))
inf = 1 << 40
Z = [0]
X = [0]
A = [0]
for t, x, y, a in points:
z = t - y
Z.append(z + x)
X.append(z - x)
A.append(a)
Z_se = set(Z)
X_se = set(X)
dic = {z:i for i, z in enumerate(sorted(Z_se))}
Z = [dic[z] for z in Z]
dic = {x:i for i, x in enumerate(sorted(X_se))}
X = [dic[x] for x in X]
rt = RangeTree(-inf, max, 33)
for z, x in zip(Z, X):
rt.add_point(z, x)
rt.build()
rt.upd(Z[0], X[0], 0)
ans = 0
for z, x, a in zip(Z[1:], X[1:], A[1:]):
ma = rt.query(0, 0, z + 1, x + 1)
ma += a
rt.upd(z, x, ma)
ans = max(ans, ma)
print(ans) | ConDefects/ConDefects/Code/abc266_h/Python/34423081 |
condefects-python_data_417 | n=int(input())
A=list(map(int,input().split()))
ans = [0]
for i in range(n):
for j in range(len(ans)):
ans[j] += A[i]
ans[j] %= 360
ans.append(0)
ans = sorted(ans)
ans.append(360)
Ma = 0
for i in range(n):
Ma = max(Ma, ans[i+1]-ans[i])
print(Ma)
n=int(input())
A=list(map(int,input().split()))
ans = [0]
for i in range(n):
for j in range(len(ans)):
ans[j] += A[i]
ans[j] %= 360
ans.append(0)
ans = sorted(ans)
ans.append(360)
Ma = 0
for i in range(n+1):
Ma = max(Ma, ans[i+1]-ans[i])
print(Ma)
| ConDefects/ConDefects/Code/abc238_b/Python/45497591 |
condefects-python_data_418 | #素因数分解を行う関数
#fc=[[prime,cnt], [prime, cnt]...]の二次元配列を返す
def factorization(n):
now_num = n
prime_cnt_list = []
for i in range(2, n + 1):
if i * i > now_num:
break
if now_num % i:
continue
cnt = 0
while not now_num % i:
now_num //= i
cnt += 1
prime_cnt_list.append((i, cnt))
if now_num != 1:
prime_cnt_list.append((now_num, 1))
return prime_cnt_list
N = int(input())
ans = 0
for i in range(1, N+1):
fc = factorization(i)
odd = 1 #iに対してかけると平方数となる数を
for p, cnt in fc:
if cnt % 2 == 1:
odd *= p
for j in range(1, N+1):
if odd*j*j <= N:
break
ans += 1
print(ans)
#素因数分解を行う関数
#fc=[[prime,cnt], [prime, cnt]...]の二次元配列を返す
def factorization(n):
now_num = n
prime_cnt_list = []
for i in range(2, n + 1):
if i * i > now_num:
break
if now_num % i:
continue
cnt = 0
while not now_num % i:
now_num //= i
cnt += 1
prime_cnt_list.append((i, cnt))
if now_num != 1:
prime_cnt_list.append((now_num, 1))
return prime_cnt_list
N = int(input())
ans = 0
for i in range(1, N+1):
fc = factorization(i)
odd = 1 #iに対してかけると平方数となる数を
for p, cnt in fc:
if cnt % 2 == 1:
odd *= p
for j in range(1, N+1):
if odd*j*j > N:
break
ans += 1
print(ans)
| ConDefects/ConDefects/Code/abc254_d/Python/53475713 |
condefects-python_data_419 | n=int(input())
def pf(n):
a,f={},2
while f*f<=n:
if n%f:f+=1
else:a[f]=a.get(f,0)+1;n//=f
if n>1:a[n]=a.get(n,0)+1
return a
s=[i*i for i in range(1,n)if i*i<=n]
ans=0
for i in range(1,n+1):
a=1
for k,v in pf(i).items():
if v%2:
a*=k
for j in s:
if a*j<=n:
ans+=1
else:
break
print(ans)
n=int(input())
def pf(n):
a,f={},2
while f*f<=n:
if n%f:f+=1
else:a[f]=a.get(f,0)+1;n//=f
if n>1:a[n]=a.get(n,0)+1
return a
s=[i*i for i in range(1,n+1)if i*i<=n]
ans=0
for i in range(1,n+1):
a=1
for k,v in pf(i).items():
if v%2:
a*=k
for j in s:
if a*j<=n:
ans+=1
else:
break
print(ans) | ConDefects/ConDefects/Code/abc254_d/Python/51493507 |
condefects-python_data_420 | N = int(input())
#素因数分解を行う関数
#fc=[[prime,cnt], [prime, cnt]...]の二次元配列を返す
def factorization(n):
now_num = n
prime_cnt_list = []
for i in range(2, n + 1):
if i * i > now_num:
break
if now_num % i:
continue
cnt = 0
while not now_num % i:
now_num //= i
cnt += 1
prime_cnt_list.append((i, cnt))
if now_num != 1:
prime_cnt_list.append((now_num, 1))
return prime_cnt_list
ans = 0
for i in range(1,N+1):
fc = factorization(i)
num = 1
for p,cnt in fc:
if cnt % 2 == 1: num*=p
for k in range(1,N):
if num*k*k>N: break
ans += 1
print(ans)
N = int(input())
#素因数分解を行う関数
#fc=[[prime,cnt], [prime, cnt]...]の二次元配列を返す
def factorization(n):
now_num = n
prime_cnt_list = []
for i in range(2, n + 1):
if i * i > now_num:
break
if now_num % i:
continue
cnt = 0
while not now_num % i:
now_num //= i
cnt += 1
prime_cnt_list.append((i, cnt))
if now_num != 1:
prime_cnt_list.append((now_num, 1))
return prime_cnt_list
ans = 0
for i in range(1,N+1):
fc = factorization(i)
num = 1
for p,cnt in fc:
if cnt % 2 == 1: num*=p
for k in range(1,N+1):
if num*k*k>N: break
ans += 1
print(ans) | ConDefects/ConDefects/Code/abc254_d/Python/52216169 |
condefects-python_data_421 | N,M=map(int,input().split())
G=[[] for _ in range(N)]
for _ in range(M):
u,v=map(int,input().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
seen=set()
cnt=0
for i in range(N):
if(i not in seen):
stack=[i]
cnt+=1
while stack:
x=stack.pop()
if(x in seen):
continue
seen.add(x)
for j in G[i]:
if (j not in seen):
stack.append(j)
print(cnt)
N,M=map(int,input().split())
G=[[] for _ in range(N)]
for _ in range(M):
u,v=map(int,input().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
seen=set()
cnt=0
for i in range(N):
if(i not in seen):
stack=[i]
cnt+=1
while stack:
x=stack.pop()
if(x in seen):
continue
seen.add(x)
for j in G[x]:
if (j not in seen):
stack.append(j)
print(cnt) | ConDefects/ConDefects/Code/abc284_c/Python/54471713 |
condefects-python_data_422 | from collections import Counter
n = int(input())
p = list(map(int, input().split()))
ans = 0
candidate = [0]*(n)
new = [0]*(n)
for i in range(n):
for j in range(3):
candidate[(p[i]+j-1+i)%n] += 1
for i in range(n):
ans = max(ans, candidate[i])
print(ans)
from collections import Counter
n = int(input())
p = list(map(int, input().split()))
ans = 0
candidate = [0]*(n)
new = [0]*(n)
for i in range(n):
for j in range(3):
candidate[(p[i]+j-1-i+n)%n] += 1
for i in range(n):
ans = max(ans, candidate[i])
print(ans) | ConDefects/ConDefects/Code/abc268_c/Python/45122098 |
condefects-python_data_423 | a = int(input())
# a, b = map(int, input().split())
if a % 4 == 2:
print(a)
elif a % 4 == 1:
print(a + 1)
elif a % 4 == 3:
print(a + 3)
a = int(input())
# a, b = map(int, input().split())
if a % 4 == 2:
print(a)
elif a % 4 == 1:
print(a + 1)
elif a % 4 == 3:
print(a + 3)
elif a % 4 == 0:
print(a + 2) | ConDefects/ConDefects/Code/abc262_a/Python/45968075 |
condefects-python_data_424 | class Factorial():
def __init__(self, MOD):
self.mod = MOD
self._factorial = [1]
self._size = 1
self._factorial_inv = [1]
self._size_inv = 1
def __call__(self, n):
'''n! % mod '''
return self.fact(n)
def fact(self, n):
'''n! % mod '''
if n >= self.mod:
return 0
self.make(n)
return self._factorial[n]
def fact_inv(self, n):
'''n!^-1 % mod '''
if n >= self.mod:
raise ValueError('Modinv is not exist! arg={}'.format(n))
self.make_inv(n)
return self._factorial_inv[n]
def comb(self, n, r):
''' nCr % mod '''
if n < 0 or r < 0 or n < r:
return 0
t = self.fact_inv(n-r)*self.fact_inv(r) % self.mod
return self(n)*t % self.mod
def comb_with_repetition(self, n, r):
''' nHr % mod '''
t = self.fact_inv(n-1)*self.fact_inv(r) % self.mod
return self(n+r-1)*t % self.mod
def perm(self, n, r):
''' nPr % mod '''
if n < 0 or r < 0 or n < r:
return 0
return self(n)*self.fact_inv(n-r) % self.mod
@staticmethod
def xgcd(a, b):
''' return (g, x, y) such that a*x + b*y = g = gcd(a, b) '''
x0, x1, y0, y1 = 0, 1, 1, 0
while a != 0:
(q, a), b = divmod(b, a), a
y0, y1 = y1, y0 - q * y1
x0, x1 = x1, x0 - q * x1
return b, x0, y0
#modinv(a)はax≡1(modp)となるxをreturnする。
#ax≡y(modp)となるxは上のreturnのy倍
def modinv(self, n):
g, x, _ = self.xgcd(n, self.mod)
if g != 1:
raise ValueError('Modinv is not exist! arg={}'.format(n))
return x % self.mod
def make(self, n):
if n >= self.mod:
n = self.mod
if self._size < n+1:
for i in range(self._size, n+1):
self._factorial.append(self._factorial[i-1]*i % self.mod)
self._size = n+1
def make_inv(self, n):
if n >= self.mod:
n = self.mod
self.make(n)
if self._size_inv < n+1:
for i in range(self._size_inv, n+1):
self._factorial_inv.append(self.modinv(self._factorial[i]))
self._size_inv = n+1
MOD = 998244353
f = Factorial(MOD)
H, W, K = map(int, input().split())
def popcount(x):
res = 0
while x > 0:
res += x & 1
x >>= 1
return res
ans = 0
for h in range(1, H+1):
for w in range(1, W+1):
add = 0
for bit in range(1<<4):
x = h
y = w
if (bit>>0) & 1:x -= 1
if (bit>>1) & 1:x -= 1
if (bit>>2) & 1:y -= 1
if (bit>>3) & 1:y -= 1
if popcount(bit) % 2 == 1:
add -= f.comb(x*y, K)
else:
add += f.comb(x*y, K)
ans += add * (H-h+1) * (W-w+1) * h * w
ans %= MOD
ans *= pow(f.comb(H*W, K), MOD-2, MOD)
ans %= MOD
print(ans)
class Factorial():
def __init__(self, MOD):
self.mod = MOD
self._factorial = [1]
self._size = 1
self._factorial_inv = [1]
self._size_inv = 1
def __call__(self, n):
'''n! % mod '''
return self.fact(n)
def fact(self, n):
'''n! % mod '''
if n >= self.mod:
return 0
self.make(n)
return self._factorial[n]
def fact_inv(self, n):
'''n!^-1 % mod '''
if n >= self.mod:
raise ValueError('Modinv is not exist! arg={}'.format(n))
self.make_inv(n)
return self._factorial_inv[n]
def comb(self, n, r):
''' nCr % mod '''
if n < 0 or r < 0 or n < r:
return 0
t = self.fact_inv(n-r)*self.fact_inv(r) % self.mod
return self(n)*t % self.mod
def comb_with_repetition(self, n, r):
''' nHr % mod '''
t = self.fact_inv(n-1)*self.fact_inv(r) % self.mod
return self(n+r-1)*t % self.mod
def perm(self, n, r):
''' nPr % mod '''
if n < 0 or r < 0 or n < r:
return 0
return self(n)*self.fact_inv(n-r) % self.mod
@staticmethod
def xgcd(a, b):
''' return (g, x, y) such that a*x + b*y = g = gcd(a, b) '''
x0, x1, y0, y1 = 0, 1, 1, 0
while a != 0:
(q, a), b = divmod(b, a), a
y0, y1 = y1, y0 - q * y1
x0, x1 = x1, x0 - q * x1
return b, x0, y0
#modinv(a)はax≡1(modp)となるxをreturnする。
#ax≡y(modp)となるxは上のreturnのy倍
def modinv(self, n):
g, x, _ = self.xgcd(n, self.mod)
if g != 1:
raise ValueError('Modinv is not exist! arg={}'.format(n))
return x % self.mod
def make(self, n):
if n >= self.mod:
n = self.mod
if self._size < n+1:
for i in range(self._size, n+1):
self._factorial.append(self._factorial[i-1]*i % self.mod)
self._size = n+1
def make_inv(self, n):
if n >= self.mod:
n = self.mod
self.make(n)
if self._size_inv < n+1:
for i in range(self._size_inv, n+1):
self._factorial_inv.append(self.modinv(self._factorial[i]))
self._size_inv = n+1
MOD = 998244353
f = Factorial(MOD)
H, W, K = map(int, input().split())
def popcount(x):
res = 0
while x > 0:
res += x & 1
x >>= 1
return res
ans = 0
for h in range(1, H+1):
for w in range(1, W+1):
add = 0
for bit in range(1<<4):
x = h
y = w
if (bit>>0) & 1:x -= 1
if (bit>>1) & 1:x -= 1
if (bit>>2) & 1:y -= 1
if (bit>>3) & 1:y -= 1
if x <= 0 or y <= 0:
continue
if popcount(bit) % 2 == 1:
add -= f.comb(x*y, K)
else:
add += f.comb(x*y, K)
ans += add * (H-h+1) * (W-w+1) * h * w
ans %= MOD
ans *= pow(f.comb(H*W, K), MOD-2, MOD)
ans %= MOD
print(ans)
| ConDefects/ConDefects/Code/abc297_f/Python/47953762 |
condefects-python_data_425 | # https://atcoder.jp/contests/abc297/tasks/abc297_f
height, width, num_blocks = map(int, input().split())
MOD = 998244353
n = 10**6
def g(h, w):
return cmb(h*w, num_blocks, MOD)
def f(h, w):
expected = g(h, w) - 2*g(h-1, w) - 2*g(h, w-1) + g(h-2, w) + g(h, w-2) + 4*g(h-1, w-1) - 2*g(h-2, w-1) - 2*g(h-1, w-2) + g(h-2, w-2)
expected %= MOD
return expected
def cmb(n, r, p):
if (r < 0) or (n < r):
return 0
r = min(r, n - r)
return fact[n] * factinv[r] % p * factinv[n-r] % p
fact = [1, 1] # fact[n] = (n! mod MOD)
factinv = [1, 1] # factinv[n] = ((n!)^(-1) mod MOD)
inv = [0, 1] # factinv 計算用
for i in range(2, n + 1):
fact.append((fact[-1] * i) % MOD)
inv.append((-inv[MOD % i] * (MOD // i)) % MOD)
factinv.append((factinv[-1] * inv[-1]) % MOD)
ans = 0
for h in range(1, height+1):
for w in range(1, width+1):
if h*w < num_blocks: continue
ans += (height - h + 1)*(width - w + 1)*f(h, w)%MOD*h*w
ans %= MOD
ans *= pow(g(height, width), -1, MOD)
ans %= MOD
print(ans)
# https://atcoder.jp/contests/abc297/tasks/abc297_f
height, width, num_blocks = map(int, input().split())
MOD = 998244353
n = 10**6
def g(h, w):
if h < 0 or w < 0:
return 0
return cmb(h*w, num_blocks, MOD)
def f(h, w):
expected = g(h, w) - 2*g(h-1, w) - 2*g(h, w-1) + g(h-2, w) + g(h, w-2) + 4*g(h-1, w-1) - 2*g(h-2, w-1) - 2*g(h-1, w-2) + g(h-2, w-2)
expected %= MOD
return expected
def cmb(n, r, p):
if (r < 0) or (n < r):
return 0
r = min(r, n - r)
return fact[n] * factinv[r] % p * factinv[n-r] % p
fact = [1, 1] # fact[n] = (n! mod MOD)
factinv = [1, 1] # factinv[n] = ((n!)^(-1) mod MOD)
inv = [0, 1] # factinv 計算用
for i in range(2, n + 1):
fact.append((fact[-1] * i) % MOD)
inv.append((-inv[MOD % i] * (MOD // i)) % MOD)
factinv.append((factinv[-1] * inv[-1]) % MOD)
ans = 0
for h in range(1, height+1):
for w in range(1, width+1):
if h*w < num_blocks: continue
ans += (height - h + 1)*(width - w + 1)*f(h, w)%MOD*h*w
ans %= MOD
ans *= pow(g(height, width), -1, MOD)
ans %= MOD
print(ans)
| ConDefects/ConDefects/Code/abc297_f/Python/49316217 |
condefects-python_data_426 | from itertools import accumulate
T=int(input())
for _ in range(T):
D,K,X=map(int,input().split())
tmp=[1]
for i in range(D):
tmp.append(pow(K,i+1))
tmp=list(accumulate(tmp))
for i in range(D+1):
if tmp[i]>=X: id=i; break
ans=10**20
for i in range(id,D+1):
if i<D: tmp2=1
else: tmp2=0
amari=tmp[i]-X
for j in range(id-1,-1,-1):
if amari==0: break
tmp2+=min(K,amari//tmp[j])
amari-=tmp[j]*min(K,amari//tmp[j])
ans=min(ans,tmp2)
print(ans)
from itertools import accumulate
T=int(input())
for _ in range(T):
D,K,X=map(int,input().split())
tmp=[1]
for i in range(D):
tmp.append(pow(K,i+1))
tmp=list(accumulate(tmp))
for i in range(D+1):
if tmp[i]>=X: id=i; break
ans=10**20
for i in range(id,D+1):
if i<D: tmp2=1
else: tmp2=0
amari=tmp[i]-X
for j in range(i-1,-1,-1):
if amari==0: break
tmp2+=min(K,amari//tmp[j])
amari-=tmp[j]*min(K,amari//tmp[j])
ans=min(ans,tmp2)
print(ans) | ConDefects/ConDefects/Code/abc290_g/Python/39049178 |
condefects-python_data_427 | import math
import sys
sys.setrecursionlimit(500_000)
from collections import defaultdict
def solve1(x, k, tmp, d):
m = len(tmp)
ans = 0 if len(tmp) == d + 2 else 1
#print(f'ans={ans}, tmp={tmp}, d={d}')
rest = tmp[m - 1] - x
if rest < 0:
return float('inf')
j = m - 2
while rest > 0:
x = tmp[j]
j -= 1
if x <= rest:
v = rest // x
ans += v
rest = rest % x
return ans
def solve(d, k, x):
d1 = 0
tmp = [0]
ans = float('inf')
while tmp[-1] < x:
tmp.append(tmp[-1] + k ** d1)
ans = min(ans, solve1(x, k, tmp, d))
d1 += 1
return ans
t = int(input())
for _ in range(t):
d, k, x = list(map(int, input().split()))
print(solve(d, k, x))
import math
import sys
sys.setrecursionlimit(500_000)
from collections import defaultdict
def solve1(x, k, tmp, d):
m = len(tmp)
ans = 0 if len(tmp) == d + 2 else 1
#print(f'ans={ans}, tmp={tmp}, d={d}')
rest = tmp[m - 1] - x
if rest < 0:
return float('inf')
j = m - 2
while rest > 0:
x = tmp[j]
j -= 1
if x <= rest:
v = rest // x
ans += v
rest = rest % x
return ans
def solve(d, k, x):
d1 = 0
tmp = [0]
ans = float('inf')
while len(tmp) <= d + 2:
tmp.append(tmp[-1] + k ** d1)
ans = min(ans, solve1(x, k, tmp, d))
d1 += 1
return ans
t = int(input())
for _ in range(t):
d, k, x = list(map(int, input().split()))
print(solve(d, k, x)) | ConDefects/ConDefects/Code/abc290_g/Python/39047205 |
condefects-python_data_428 | from collections import deque
N, M = map(int, input().split())
relations = [[] for _ in range(N)]
queue = deque([])
cnt = [0 for _ in range(N)]
U = [None] * M
V = [None] * M
for i in range(M):
U[i], V[i] = map(int, input().split())
relations[V[i]-1].append(U[i]-1)
cnt[V[i]-1] += 1
for i in range(N):
if cnt[i] == 0:
queue.append(i)
ans = set([n for n in range(N)])
while queue:
tmp = queue.popleft()
ans.discard(tmp)
for r in relations[tmp]:
cnt[r] -= 1
if cnt[r] == 0:
queue.append(r)
print(len(ans))
from collections import deque
N, M = map(int, input().split())
relations = [[] for _ in range(N)]
queue = deque([])
cnt = [0 for _ in range(N)]
U = [None] * M
V = [None] * M
for i in range(M):
U[i], V[i] = map(int, input().split())
relations[V[i]-1].append(U[i]-1)
cnt[U[i]-1] += 1
for i in range(N):
if cnt[i] == 0:
queue.append(i)
ans = set([n for n in range(N)])
while queue:
tmp = queue.popleft()
ans.discard(tmp)
for r in relations[tmp]:
cnt[r] -= 1
if cnt[r] == 0:
queue.append(r)
print(len(ans))
| ConDefects/ConDefects/Code/abc245_f/Python/45811431 |
condefects-python_data_429 | # D - Unicyclic Components
from collections import defaultdict
def main():
N, M = map(int, input().split())
lib = UnionFind(N)
vertexes = set()
cnt = defaultdict(int)
for _ in range(M):
u, v = map(int, input().split())
lib.unite(u, v)
vertexes.add(u)
vertexes.add(v)
cnt[u] += 1
cnt[v] += 1
groups = lib.get_groups(vertexes)
matches = True
for group in groups:
n = len(group)
m = 0
for v in group:
m += cnt[v]
if n != m//2:
matches = False
if matches:
print('Yes')
else:
print('No')
class UnionFind:
def __init__(self, n):
# n で頂点数を受け取る
# 頂点番号が連番ではない場合、最大の頂点番号を渡してもOK
# 頂点番号は1から始まることが多いので、n頂点の場合、n+1でリストを作成しておく
# [summary]インスタンス変数を宣言
# 各頂点の親の番号(自身が根の場合は -1)
# 最初は、どの頂点も根であるとして初期化
self.par = [-1] * (n + 1)
# 各頂点の属するグループの頂点数
self.size = [1] * (n + 1)
# 頂点をグループ分けするときに使う
self.groups = dict()
# サイクル(閉路)を検出するためのフラグ
self.cycled = False
def root(self, x):
# [summary]根を求める
# その過程で、経路圧縮を行う(par[x]には、根が格納される)
if self.par[x] == -1:
# xが根の場合は、直接xを返す
return x
else:
# xの親par[x]を根に張り替える
# (ここで代入しておくことで、後の繰り返しを避けられる)
# 各頂点の親子関係を知りたい場合は、この行をコメントアウト
self.par[x] = self.root(self.par[x])
return self.root(self.par[x])
def is_same(self, x, y):
# [summary]xとyが同じグループに属するかどうか
if self.root(x) == self.root(y):
return True
def unite(self, x, y):
# [summary]xを含むグループと yを含むグループを併合する
# x,yを それぞれ根まで移動する
x = self.root(x)
y = self.root(y)
if x == y:
# すでに同じグループのときは 何もしない
# すでに同じグループに属しているのに
# また辺をつないだら、閉路が発生する
# (実装上は、実際に辺をつなぐ訳ではなく
# フラグをオンにするだけ)
self.cycled = True
else:
# union by size(y側のサイズが小さくなるようにする)
if self.size[x] < self.size[y]:
x, y = y, x
# yをxの子にする
self.par[y] = x
self.size[x] += self.size[y]
def detects_cycle(self):
return self.cycled
def get_size(self, x):
# [summary]xを含むグループの頂点数
return self.size[self.root(x)]
def get_groups(self, vertexes):
# [summary]各頂点をグループ分けして、"[1,2,4], [3,5]"のような
# グループ分けされた頂点番号の集合を返す
self.__break_into_groups(vertexes)
return self.groups.values()
def __break_into_groups(self, vertexes):
# [summary]各頂点をグループ分けする
for v in vertexes:
r = self.root(v)
if not r in self.groups.keys():
self.groups[r] = [v]
else:
self.groups[r].append(v)
if __name__ == '__main__':
main()
# D - Unicyclic Components
from collections import defaultdict
def main():
N, M = map(int, input().split())
lib = UnionFind(N)
vertexes = set()
cnt = defaultdict(int)
for _ in range(M):
u, v = map(int, input().split())
lib.unite(u, v)
vertexes.add(u)
vertexes.add(v)
cnt[u] += 1
cnt[v] += 1
groups = lib.get_groups(range(1, N+1))
matches = True
for group in groups:
n = len(group)
m = 0
for v in group:
m += cnt[v]
if n != m//2:
matches = False
if matches:
print('Yes')
else:
print('No')
class UnionFind:
def __init__(self, n):
# n で頂点数を受け取る
# 頂点番号が連番ではない場合、最大の頂点番号を渡してもOK
# 頂点番号は1から始まることが多いので、n頂点の場合、n+1でリストを作成しておく
# [summary]インスタンス変数を宣言
# 各頂点の親の番号(自身が根の場合は -1)
# 最初は、どの頂点も根であるとして初期化
self.par = [-1] * (n + 1)
# 各頂点の属するグループの頂点数
self.size = [1] * (n + 1)
# 頂点をグループ分けするときに使う
self.groups = dict()
# サイクル(閉路)を検出するためのフラグ
self.cycled = False
def root(self, x):
# [summary]根を求める
# その過程で、経路圧縮を行う(par[x]には、根が格納される)
if self.par[x] == -1:
# xが根の場合は、直接xを返す
return x
else:
# xの親par[x]を根に張り替える
# (ここで代入しておくことで、後の繰り返しを避けられる)
# 各頂点の親子関係を知りたい場合は、この行をコメントアウト
self.par[x] = self.root(self.par[x])
return self.root(self.par[x])
def is_same(self, x, y):
# [summary]xとyが同じグループに属するかどうか
if self.root(x) == self.root(y):
return True
def unite(self, x, y):
# [summary]xを含むグループと yを含むグループを併合する
# x,yを それぞれ根まで移動する
x = self.root(x)
y = self.root(y)
if x == y:
# すでに同じグループのときは 何もしない
# すでに同じグループに属しているのに
# また辺をつないだら、閉路が発生する
# (実装上は、実際に辺をつなぐ訳ではなく
# フラグをオンにするだけ)
self.cycled = True
else:
# union by size(y側のサイズが小さくなるようにする)
if self.size[x] < self.size[y]:
x, y = y, x
# yをxの子にする
self.par[y] = x
self.size[x] += self.size[y]
def detects_cycle(self):
return self.cycled
def get_size(self, x):
# [summary]xを含むグループの頂点数
return self.size[self.root(x)]
def get_groups(self, vertexes):
# [summary]各頂点をグループ分けして、"[1,2,4], [3,5]"のような
# グループ分けされた頂点番号の集合を返す
self.__break_into_groups(vertexes)
return self.groups.values()
def __break_into_groups(self, vertexes):
# [summary]各頂点をグループ分けする
for v in vertexes:
r = self.root(v)
if not r in self.groups.keys():
self.groups[r] = [v]
else:
self.groups[r].append(v)
if __name__ == '__main__':
main() | ConDefects/ConDefects/Code/abc292_d/Python/44987159 |
condefects-python_data_430 | import math
# import heapq
import sys
sys.setrecursionlimit(10**6)
# n,m,k = map(int, input().split())
# n = int(input())
n,q = map(int, input().split())
if q==2:
print(int(math.log(n,2)))
exit()
P = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
r = 0
while q!=P[r]:
r+=1
l = (r+1)//2
P = P[:r+1]
for i in range(0,l,2):
c = P[i]
P[i] = P[r-i]
P[r-i] = c
p,pp = P[0:l],P[l:]
p.sort()
pp.sort()
def rep(k,c,a,b):
for i in range(k,len(a)):
s = c*a[i]
if s<=n:
b.append(s)
rep(i,s,a,b)
else:
break
l,ll = [],[]
rep(0,1,p,l)
rep(0,1,pp,ll)
ll.sort()
ans=len(ll)+1
for x in l:
lo,hi=-1,len(ll)+1
s=0
while lo+1<hi:
mid = (lo+hi)//2
# print(x,mid)
if x*ll[mid]<=n:
s=mid+1
lo=mid
else:
hi=mid
# print(x,s)
ans+=s+1
print(ans)
import math
# import heapq
import sys
sys.setrecursionlimit(10**6)
# n,m,k = map(int, input().split())
# n = int(input())
n,q = map(int, input().split())
if q==2:
print(int(math.log(n,2))+1)
exit()
P = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
r = 0
while q!=P[r]:
r+=1
l = (r+1)//2
P = P[:r+1]
for i in range(0,l,2):
c = P[i]
P[i] = P[r-i]
P[r-i] = c
p,pp = P[0:l],P[l:]
p.sort()
pp.sort()
def rep(k,c,a,b):
for i in range(k,len(a)):
s = c*a[i]
if s<=n:
b.append(s)
rep(i,s,a,b)
else:
break
l,ll = [],[]
rep(0,1,p,l)
rep(0,1,pp,ll)
ll.sort()
ans=len(ll)+1
for x in l:
lo,hi=-1,len(ll)+1
s=0
while lo+1<hi:
mid = (lo+hi)//2
# print(x,mid)
if x*ll[mid]<=n:
s=mid+1
lo=mid
else:
hi=mid
# print(x,s)
ans+=s+1
print(ans)
| ConDefects/ConDefects/Code/abc300_g/Python/45084922 |
condefects-python_data_431 | from collections import *
import sys
import heapq
import bisect
import itertools
from functools import lru_cache
from types import GeneratorType
from fractions import Fraction
import math
import copy
sys.setrecursionlimit(int(1e7))
# @lru_cache(maxsize=None) # CPython特化
# @bootstrap # PyPy特化(こっちのほうが速い) yield dfs(), yield Noneを忘れずに
def bootstrap(f, stack=[]): # yield
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
dxdy1 = ((0, 1), (0, -1), (1, 0), (-1, 0)) # 上下左右
dxdy2 = ((0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)) # 8方向すべて
dxdy3 = ((0, 1), (1, 0)) # 右 or 下
dxdy4 = ((1, 1), (1, -1), (-1, 1), (-1, -1)) # 斜め
INF = float("inf")
_INF = 1 << 60
MOD = 998244353
mod = 998244353
MOD2 = 10**9 + 7
mod2 = 10**9 + 7
# memo : len([a,b,...,z])==26
# memo : 2^20 >= 10^6
# 小数の計算を避ける : x/y -> (x*big)//y ex:big=10**9
# @:小さい文字, ~:大きい文字,None: 空の文字列
# ユークリッドの互除法:gcd(x,y)=gcd(x,y-x)
input = lambda: sys.stdin.readline().rstrip()
mi = lambda: map(int, input().split())
li = lambda: list(mi())
ii = lambda: int(input())
py = lambda: print("Yes")
pn = lambda: print("No")
pf = lambda: print("First")
ps = lambda: print("Second")
# https://raw.githubusercontent.com/shakayami/ACL-for-python/master/segtree.py
class segtree:
n = 1
size = 1
log = 2
d = [0]
op = None
e = 10**15
def __init__(self, V, OP, E):
self.n = len(V)
self.op = OP
self.e = E
self.log = (self.n - 1).bit_length()
self.size = 1 << self.log
self.d = [E for i in range(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, x):
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):
assert 0 <= p and p < self.n
return self.d[p + self.size]
def prod(self, l, r):
assert 0 <= l and l <= r and r <= self.n
sml = self.e
smr = self.e
l += self.size
r += self.size
while l < r:
if l & 1:
sml = self.op(sml, self.d[l])
l += 1
if r & 1:
smr = self.op(self.d[r - 1], smr)
r -= 1
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.d[1]
def max_right(self, l, 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 1:
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, f):
assert 0 <= r and r <= self.n
assert f(self.e)
if r == 0:
return 0
r += self.size
sm = self.e
while 1:
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):
self.d[k] = self.op(self.d[2 * k], self.d[2 * k + 1])
def __str__(self):
return str([self.get(i) for i in range(self.n)])
def get_list(self):
return [self.get(i) for i in range(self.n)] # オリジナルで追加
N, Q = mi()
A = li()
B = li()
AA = []
BB = []
for i in range(N - 1):
AA.append(A[i + 1] - A[i])
BB.append(B[i + 1] - B[i])
seg1 = segtree(AA, math.gcd, 0) # Vの要素とEの値は同じにする #10**9 -> INF
seg2 = segtree(BB, math.gcd, 0)
for _ in range(Q):
h1, h2, w1, w2 = mi()
h1 -= 1
h2 -= 1
w1 -= 1
w2 -= 1
print(math.gcd(A[h1] + B[w1]), seg1.prod(h1, h2), seg2.prod(w1, w2))
from collections import *
import sys
import heapq
import bisect
import itertools
from functools import lru_cache
from types import GeneratorType
from fractions import Fraction
import math
import copy
sys.setrecursionlimit(int(1e7))
# @lru_cache(maxsize=None) # CPython特化
# @bootstrap # PyPy特化(こっちのほうが速い) yield dfs(), yield Noneを忘れずに
def bootstrap(f, stack=[]): # yield
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
dxdy1 = ((0, 1), (0, -1), (1, 0), (-1, 0)) # 上下左右
dxdy2 = ((0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)) # 8方向すべて
dxdy3 = ((0, 1), (1, 0)) # 右 or 下
dxdy4 = ((1, 1), (1, -1), (-1, 1), (-1, -1)) # 斜め
INF = float("inf")
_INF = 1 << 60
MOD = 998244353
mod = 998244353
MOD2 = 10**9 + 7
mod2 = 10**9 + 7
# memo : len([a,b,...,z])==26
# memo : 2^20 >= 10^6
# 小数の計算を避ける : x/y -> (x*big)//y ex:big=10**9
# @:小さい文字, ~:大きい文字,None: 空の文字列
# ユークリッドの互除法:gcd(x,y)=gcd(x,y-x)
input = lambda: sys.stdin.readline().rstrip()
mi = lambda: map(int, input().split())
li = lambda: list(mi())
ii = lambda: int(input())
py = lambda: print("Yes")
pn = lambda: print("No")
pf = lambda: print("First")
ps = lambda: print("Second")
# https://raw.githubusercontent.com/shakayami/ACL-for-python/master/segtree.py
class segtree:
n = 1
size = 1
log = 2
d = [0]
op = None
e = 10**15
def __init__(self, V, OP, E):
self.n = len(V)
self.op = OP
self.e = E
self.log = (self.n - 1).bit_length()
self.size = 1 << self.log
self.d = [E for i in range(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, x):
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):
assert 0 <= p and p < self.n
return self.d[p + self.size]
def prod(self, l, r):
assert 0 <= l and l <= r and r <= self.n
sml = self.e
smr = self.e
l += self.size
r += self.size
while l < r:
if l & 1:
sml = self.op(sml, self.d[l])
l += 1
if r & 1:
smr = self.op(self.d[r - 1], smr)
r -= 1
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.d[1]
def max_right(self, l, 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 1:
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, f):
assert 0 <= r and r <= self.n
assert f(self.e)
if r == 0:
return 0
r += self.size
sm = self.e
while 1:
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):
self.d[k] = self.op(self.d[2 * k], self.d[2 * k + 1])
def __str__(self):
return str([self.get(i) for i in range(self.n)])
def get_list(self):
return [self.get(i) for i in range(self.n)] # オリジナルで追加
N, Q = mi()
A = li()
B = li()
AA = []
BB = []
for i in range(N - 1):
AA.append(A[i + 1] - A[i])
BB.append(B[i + 1] - B[i])
seg1 = segtree(AA, math.gcd, 0) # Vの要素とEの値は同じにする #10**9 -> INF
seg2 = segtree(BB, math.gcd, 0)
for _ in range(Q):
h1, h2, w1, w2 = mi()
h1 -= 1
h2 -= 1
w1 -= 1
w2 -= 1
print(math.gcd(A[h1] + B[w1], seg1.prod(h1, h2), seg2.prod(w1, w2))) | ConDefects/ConDefects/Code/abc254_f/Python/48945628 |
condefects-python_data_432 |
class SegTree:
def __init__(self,lis,segfunc,ide_ele):
self.lis=lis
self.segfunc=segfunc
self.ide_ele=ide_ele
self.n=len(lis)
nb=bin(self.n)[2:]
if self.n==1<<len(nb)-1:
self.leaves=1<<len(nb)-1
else:
self.leaves=1<<(len(nb))
self.array=[self.ide_ele for _ in range(self.leaves*2)]
for i in range(self.n):
self.update(i,self.lis[i])
def update(self,ind,x):#加算ではなく更新
now=ind+self.leaves
self.array[now]=x
while now>=2:
if now%2:
self.array[now//2]=self.segfunc(self.array[now],self.array[now-1])
else:
self.array[now//2]=self.segfunc(self.array[now],self.array[now+1])
now//=2
def query(self,left,right): #半開区間
calc_ind=[]
stack=[(1,0,self.leaves)]
while len(stack):
now,n_l,n_r=stack.pop()
if n_r<left or n_l>=right:
continue
elif n_l<left or n_r>right:
if 2*now+1<len(self.array):
stack.append((2*now,n_l,(n_r+n_l)//2))
stack.append((2*now+1,(n_r+n_l)//2,n_r))
continue
else:
calc_ind.append(now)
val=self.ide_ele
for i in calc_ind:
val=self.segfunc(self.array[i],val)
return val
from math import gcd
N,Q=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=[]
D=[]
for i in range(N-1):
C.append(A[i+1]-A[i])
D.append(B[i+1]-B[i])
segC=SegTree(C,gcd,0)
segD=SegTree(D,gcd,0)
for _ in range(Q):
h1,h2,w1,w2=map(lambda s: int(s)-1 , input().split())
Cgcd=segC.query(h1,h2)
Dgcd=segD.query(w1,w2)
print(gcd(Cgcd,A[h1]+B[w1]))
class SegTree:
def __init__(self,lis,segfunc,ide_ele):
self.lis=lis
self.segfunc=segfunc
self.ide_ele=ide_ele
self.n=len(lis)
nb=bin(self.n)[2:]
if self.n==1<<len(nb)-1:
self.leaves=1<<len(nb)-1
else:
self.leaves=1<<(len(nb))
self.array=[self.ide_ele for _ in range(self.leaves*2)]
for i in range(self.n):
self.update(i,self.lis[i])
def update(self,ind,x):#加算ではなく更新
now=ind+self.leaves
self.array[now]=x
while now>=2:
if now%2:
self.array[now//2]=self.segfunc(self.array[now],self.array[now-1])
else:
self.array[now//2]=self.segfunc(self.array[now],self.array[now+1])
now//=2
def query(self,left,right): #半開区間
calc_ind=[]
stack=[(1,0,self.leaves)]
while len(stack):
now,n_l,n_r=stack.pop()
if n_r<left or n_l>=right:
continue
elif n_l<left or n_r>right:
if 2*now+1<len(self.array):
stack.append((2*now,n_l,(n_r+n_l)//2))
stack.append((2*now+1,(n_r+n_l)//2,n_r))
continue
else:
calc_ind.append(now)
val=self.ide_ele
for i in calc_ind:
val=self.segfunc(self.array[i],val)
return val
from math import gcd
N,Q=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=[]
D=[]
for i in range(N-1):
C.append(A[i+1]-A[i])
D.append(B[i+1]-B[i])
segC=SegTree(C,gcd,0)
segD=SegTree(D,gcd,0)
for _ in range(Q):
h1,h2,w1,w2=map(lambda s: int(s)-1 , input().split())
Cgcd=segC.query(h1,h2)
Dgcd=segD.query(w1,w2)
print(gcd(Cgcd,Dgcd,A[h1]+B[w1]))
| ConDefects/ConDefects/Code/abc254_f/Python/49680019 |
condefects-python_data_433 | INF = 1 << 62
def gcd(a, b):
if b == 0: return a
else: return gcd(b, a%b)
from atcoder.segtree import SegTree
def op(data1, data2):
return gcd(data1, data2)
# opの単位元 op(data1, e) = data1
e = 0
import bisect, heapq, sys, math, copy, itertools, decimal
from collections import defaultdict, deque
sys.setrecursionlimit(10**7)
def INT(): return int(input())
def MI(): return map(int, input().split())
def MS(): return map(str, input().split())
def LI(): return list(map(int, input().split()))
def LS(): return list(map(str, input().split()))
def pr_line(itr): print(*itr, sep='\n')
def pr_mtx(matrix): [print(*row) for row in matrix]
INF = float('inf')
N, Q = MI()
A = LI()
B = LI()
AA = [A[i+1] - A[i] for i in range(N-1)]
BB = [B[i+1] - B[i] for i in range(N-1)]
segA = SegTree(op, e, AA)
segB = SegTree(op, e, BB)
ans = []
for _ in range(Q):
h1, h2, w1, w2 = list(map(lambda x:x-1, LI()))
ans.append(gcd(A[h1] + B[w1], gcd(segA.prod(h1, h2), segB.prod(w1, w2))))
pr_line(ans)
INF = 1 << 62
def gcd(a, b):
if b == 0: return a
else: return gcd(b, a%b)
from atcoder.segtree import SegTree
def op(data1, data2):
return math.gcd(data1, data2)
# opの単位元 op(data1, e) = data1
e = 0
import bisect, heapq, sys, math, copy, itertools, decimal
from collections import defaultdict, deque
sys.setrecursionlimit(10**7)
def INT(): return int(input())
def MI(): return map(int, input().split())
def MS(): return map(str, input().split())
def LI(): return list(map(int, input().split()))
def LS(): return list(map(str, input().split()))
def pr_line(itr): print(*itr, sep='\n')
def pr_mtx(matrix): [print(*row) for row in matrix]
INF = float('inf')
N, Q = MI()
A = LI()
B = LI()
AA = [A[i+1] - A[i] for i in range(N-1)]
BB = [B[i+1] - B[i] for i in range(N-1)]
segA = SegTree(op, e, AA)
segB = SegTree(op, e, BB)
ans = []
for _ in range(Q):
h1, h2, w1, w2 = list(map(lambda x:x-1, LI()))
ans.append(gcd(A[h1] + B[w1], gcd(segA.prod(h1, h2), segB.prod(w1, w2))))
pr_line(ans)
| ConDefects/ConDefects/Code/abc254_f/Python/51937981 |
condefects-python_data_434 | a = list(map(int, input().split()))
a.sort()
if a[2] > sum(a) * 2:
print(-1)
elif a[0] == 0 and a[1] < a[2]:
print(-1)
else:
print(a[2])
a = list(map(int, input().split()))
a.sort()
if a[2] * 2 > sum(a):
print(-1)
elif a[0] == 0 and a[1] < a[2]:
print(-1)
else:
print(a[2]) | ConDefects/ConDefects/Code/arc143_a/Python/43789022 |
condefects-python_data_435 | l = list(map(int, input().split()))
l.sort()
if(l[0] > l[1] + l[2]): print("-1")
else: print(l[2])
l = list(map(int, input().split()))
l.sort()
if(l[2] > l[1] + l[0]): print("-1")
else: print(l[2]) | ConDefects/ConDefects/Code/arc143_a/Python/43960988 |
condefects-python_data_436 | A,B,C=map(int,input().split())
max_A=max(A,B,C)
sum_B=A+B+C
if sum_B-max_A>=max_A:
print(sum_B//2)
else:
print(-1)
A,B,C=map(int,input().split())
max_A=max(A,B,C)
sum_B=A+B+C
if sum_B-max_A>=max_A:
print(max_A)
else:
print(-1) | ConDefects/ConDefects/Code/arc143_a/Python/45280588 |
condefects-python_data_437 | arr = input().split(' ')
arr = sorted(arr)
if int(arr[0]) + int(arr[1]) >= int(arr[2]):
print(arr[2])
else:
print("-1")
arr = map(int, input().split(' '))
arr = sorted(arr)
if int(arr[0]) + int(arr[1]) >= int(arr[2]):
print(arr[2])
else:
print("-1")
| ConDefects/ConDefects/Code/arc143_a/Python/45042880 |
condefects-python_data_438 | A, B, C = map(int, input().split())
L = [A, B, C]
L.sort()
if L[0] + L[1] < L[2]:
print(-1)
else:
# A = B
d = L[1] - L[0]
L[1] -= d
L[2] -= d
cnt = d
cnt += (L[2] - L[0]) * 2
cnt += L[2] - L[0]
print(cnt)
A, B, C = map(int, input().split())
L = [A, B, C]
L.sort()
if L[0] + L[1] < L[2]:
print(-1)
else:
# A = B
d = L[1] - L[0]
L[1] -= d
L[2] -= d
cnt = d
cnt += (L[2] - L[0]) * 2
cnt += L[0] - (L[2] - L[0])
print(cnt) | ConDefects/ConDefects/Code/arc143_a/Python/43296021 |
condefects-python_data_439 | x,y,z = map(int, input().split())
print(-1 if x == y == 0 and z == 1 or x == z == 0 and y == 1 or y == z == 0 and x == 1 else max(x, y, z))
x,y,z = map(int, input().split())
print(-1 if x > y + z or y > x + z or z > x + y else max(x, y, z)) | ConDefects/ConDefects/Code/arc143_a/Python/45053784 |
condefects-python_data_440 | num = sorted(list(map(int, input().split())))
n = num[1] - (num[2]-num[0])
if n < 0:
print(-1)
else:
print(num[2]-num[1]+num[0])
num = sorted(list(map(int, input().split())))
n = num[1] - (num[2]-num[0])
if n < 0:
print(-1)
else:
print(num[2])
| ConDefects/ConDefects/Code/arc143_a/Python/44847102 |
condefects-python_data_441 | a, b, c = map(int, input().split())
al = [a, b, c]
al.sort()
diff = al[2] - al[1]
if a < diff:
print(-1)
else:
ans = 0
# 大きいのと真ん中を合わせる
al[0] -= diff
al[2] -= diff
ans += diff
# 小さいのに合わせる
diff = al[1] - al[0]
ans += diff
ans += al[0]
print(ans)
a, b, c = map(int, input().split())
al = [a, b, c]
al.sort()
diff = al[2] - al[1]
if al[0] < diff:
print(-1)
else:
ans = 0
# 大きいのと真ん中を合わせる
al[0] -= diff
al[2] -= diff
ans += diff
# 小さいのに合わせる
diff = al[1] - al[0]
ans += diff
ans += al[0]
print(ans)
| ConDefects/ConDefects/Code/arc143_a/Python/44409934 |
condefects-python_data_442 | from collections import *
import heapq
import bisect
INF = float("inf")
MOD = 998244353
mod = 998244353
X = list(input())
num = [0]
for x in X:
num.append(num[-1] + int(x))
num.reverse()
L = len(num)
ans = []
for i in range(L - 1):
k = num[i]
p, r = divmod(k, 10)
ans.append(str(r))
num[i + 1] += p
ans.reverse()
print("".join(ans))
from collections import *
import heapq
import bisect
INF = float("inf")
MOD = 998244353
mod = 998244353
X = list(input())
num = [0]
for x in X:
num.append(num[-1] + int(x))
num.reverse()
L = len(num)
ans = []
for i in range(L - 1):
k = num[i]
p, r = divmod(k, 10)
ans.append(str(r))
num[i + 1] += p
if num[L - 1] != 0:
ans.append(str(num[L - 1]))
ans.reverse()
print("".join(ans))
| ConDefects/ConDefects/Code/abc233_e/Python/45254335 |
condefects-python_data_443 | n, x, y, z = map(int, input().split())
a = [(ai, -i - 1) for i, ai in enumerate(map(int, input().split()))]
b = [(bi, -i - 1) for i, bi in enumerate(map(int, input().split()))]
total = sorted([(ai[0] + bi[0], ai[1]) for ai, bi in zip(a, b)], reverse=True)
a.sort(reverse=True)
b.sort(reverse=True)
ans = set()
for i in range(x):
ans.add(-a[i][1])
j = 0
for i in range(n):
if j == y:
break
if -b[i][1] in ans:
continue
j += 1
ans.add(-b[i][1])
j = 0
for i in range(n):
if j == z:
break
if -total[i][1] in ans:
continue
j += 1
ans.add(-total[i][1])
print(*ans, sep='\n')
n, x, y, z = map(int, input().split())
a = [(ai, -i - 1) for i, ai in enumerate(map(int, input().split()))]
b = [(bi, -i - 1) for i, bi in enumerate(map(int, input().split()))]
total = sorted([(ai[0] + bi[0], ai[1]) for ai, bi in zip(a, b)], reverse=True)
a.sort(reverse=True)
b.sort(reverse=True)
ans = set()
for i in range(x):
ans.add(-a[i][1])
j = 0
for i in range(n):
if j == y:
break
if -b[i][1] in ans:
continue
j += 1
ans.add(-b[i][1])
j = 0
for i in range(n):
if j == z:
break
if -total[i][1] in ans:
continue
j += 1
ans.add(-total[i][1])
print(*sorted(ans), sep='\n')
| ConDefects/ConDefects/Code/abc260_b/Python/53041244 |
condefects-python_data_444 | N, X, Y, Z = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
Li1 = []
for i in range(X):
AM = A.index(max(A))
Li1.append(AM+1)
A[AM], B[AM] = -10, -10
for i in range(Y):
BM = B.index(max(B))
Li1.append(BM+1)
A[BM], B[BM] = -10, -10
C = []
for i in range(len(A)):
C.append(A[i] + B[i])
for i in range(Z):
CM = C.index(max(C))
Li1.append(CM+1)
C[CM] = -10
print(*set(Li1), sep="\n")
N, X, Y, Z = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
Li1 = []
for i in range(X):
AM = A.index(max(A))
Li1.append(AM+1)
A[AM], B[AM] = -10, -10
for i in range(Y):
BM = B.index(max(B))
Li1.append(BM+1)
A[BM], B[BM] = -10, -10
C = []
for i in range(len(A)):
C.append(A[i] + B[i])
for i in range(Z):
CM = C.index(max(C))
Li1.append(CM+1)
C[CM] = -10
print(*sorted(Li1), sep="\n") | ConDefects/ConDefects/Code/abc260_b/Python/53719611 |
condefects-python_data_445 | abc="abcdefghijklnmopqrstuvwxyz"
print(abc[int(input())-97])
abc="abcdefghijklmnopqrstuvwxyz"
print(abc[int(input())-97]) | ConDefects/ConDefects/Code/abc252_a/Python/45686937 |
condefects-python_data_446 | N = int(input())
G = []
G1 = [0 for i in range(N+1)]
for u in range(3,N+1):
print('?',1,u)
d = int(input())
G1[u] = d
G2 = [0 for i in range(N+1)]
for u in range(3,N+1):
print('?',2,u)
d = int(input())
G2[u] = d
d = 10**9
for u in range(3,N+1):
dd = G1[u] + G2[u]
d = min(d,dd)
if d == 3:
X = []
for u in range(3,N+1):
if G1[u] + G2[u] == 3:
X.append(u)
if len(X) != 2:
d = 1
else:
u,v = X[0],X[1]
print('?',u,v)
dd = input()
if dd != 1:
d = 1
print('!',d)
exit()
N = int(input())
G = []
G1 = [0 for i in range(N+1)]
for u in range(3,N+1):
print('?',1,u)
d = int(input())
G1[u] = d
G2 = [0 for i in range(N+1)]
for u in range(3,N+1):
print('?',2,u)
d = int(input())
G2[u] = d
d = 10**9
for u in range(3,N+1):
dd = G1[u] + G2[u]
d = min(d,dd)
if d == 3:
X = []
for u in range(3,N+1):
if G1[u] + G2[u] == 3:
X.append(u)
if len(X) != 2:
d = 1
else:
u,v = X[0],X[1]
print('?',u,v)
dd = int(input())
if dd != 1:
d = 1
print('!',d)
exit() | ConDefects/ConDefects/Code/arc142_c/Python/43034425 |
condefects-python_data_447 | from sys import stdout
mi = 10 ** 15
a = []
n = int(input())
for i in range(3,n+1):
print("?",1,i)
stdout.flush()
d1 = int(input())
print("?",2,i)
stdout.flush()
d2 = int(input())
mi = min(mi,d1+d2)
if d1+d2 == 3:
a.append(i)
if mi == 3 and len(a) == 2:
print("?",a[0],a[1])
stdout.flush()
dd = int(input())
if dd == 1:
ans = 3
else:
ans = 1
else:
ans = mi
print("!",ans)
stdout.flush()
from sys import stdout
mi = 10 ** 15
a = []
n = int(input())
for i in range(3,n+1):
print("?",1,i)
stdout.flush()
d1 = int(input())
print("?",2,i)
stdout.flush()
d2 = int(input())
mi = min(mi,d1+d2)
if d1+d2 == 3:
a.append(i)
if mi == 3 and len(a) == 2:
print("?",a[0],a[1])
stdout.flush()
dd = int(input())
if dd == 1:
ans = 3
else:
ans = 1
elif mi == 3:
ans = 1
else:
ans = mi
print("!",ans)
stdout.flush()
| ConDefects/ConDefects/Code/arc142_c/Python/40122562 |
condefects-python_data_448 | import collections,sys,math,functools,operator,itertools,bisect,heapq,decimal,string,time,random
#sys.setrecursionlimit(10**9)
n = int(input())
#alist = list(map(int,input().split()))
#alist = []
#s = input()
#n,m = map(int,input().split())
#for i in range(n):
# alist.append(list(map(int,input().split())))
dist = [10000]*(n+1)
ans = 1000000
ans2 = -1000000
for i in range(3,n+1):
print('?',i,1)
x = int(input())
print('?',i,2)
y = int(input())
ans = min(ans,x+y)
dist[i] = x+y
z = min(dist)
q = []
for i in range(3,n+1):
if z == dist[i]:
q.append(i)
if ans == 3:
if len(q) == 2:
print('?',q[0],q[1])
if int(input()) == 1:
ans = 3
else:
ans = 1
else:
ans = 3
print('!',ans)
import collections,sys,math,functools,operator,itertools,bisect,heapq,decimal,string,time,random
#sys.setrecursionlimit(10**9)
n = int(input())
#alist = list(map(int,input().split()))
#alist = []
#s = input()
#n,m = map(int,input().split())
#for i in range(n):
# alist.append(list(map(int,input().split())))
dist = [10000]*(n+1)
ans = 1000000
ans2 = -1000000
for i in range(3,n+1):
print('?',i,1)
x = int(input())
print('?',i,2)
y = int(input())
ans = min(ans,x+y)
dist[i] = x+y
z = min(dist)
q = []
for i in range(3,n+1):
if z == dist[i]:
q.append(i)
if ans == 3:
if len(q) == 2:
print('?',q[0],q[1])
if int(input()) == 1:
ans = 3
else:
ans = 1
else:
ans = 1
print('!',ans)
| ConDefects/ConDefects/Code/arc142_c/Python/43030313 |
condefects-python_data_449 |
N=int(input())
d=[]
for i in range(N-2):
print("?", 1, i+3)
d.append(int(input()))
for i in range(N-2):
print("?",2,i+3)
d.append(int(input()))
ans=[]
for i in range(N-2):
ans.append([d[i]+d[i+N-2],i+1])
ans.sort()
if ans[0][0]!=3:
print("!",ans[0][0])
elif ans[1][0]==3:
print("?",ans[0][1],ans[1][1])
n=int(input())
if n==1:
print("!",3)
else:
print("!",1)
else:
print("!",1)
N=int(input())
d=[]
for i in range(N-2):
print("?", 1, i+3)
d.append(int(input()))
for i in range(N-2):
print("?",2,i+3)
d.append(int(input()))
ans=[]
for i in range(N-2):
ans.append([d[i]+d[i+N-2],i+1])
ans.sort()
if ans[0][0]!=3:
print("!",ans[0][0])
elif ans[1][0]==3:
print("?",ans[0][1]+2,ans[1][1]+2)
n=int(input())
if n==1:
print("!",3)
else:
print("!",1)
else:
print("!",1) | ConDefects/ConDefects/Code/arc142_c/Python/44895895 |
condefects-python_data_450 | N = int(input())
def question(u, v):
print('?', u, v)
d = int(input())
return d
INF = 1<<62
G = [[] for _ in range(N)]
dist0 = [INF] * N
dist0[0] = 0
dist1 = [INF] * N
dist1[1] = 0
for i in range(2, N):
dist0[i] = question(1, i+1)
dist1[i] = question(2, i+1)
cnt = 0
x = []
mn_dist = INF
for i in range(N):
mn_dist = min(mn_dist, dist0[i] + dist1[i])
if dist0[i]+dist1[i] == 3:
cnt += 1
x.append(i)
if mn_dist != 3:
print('!', mn_dist)
else:
if cnt != 2:
print('!', 1)
else:
d = question(x[0], x[1])
if d == 1:
print('!', mn_dist)
else:
print('!', 1)
N = int(input())
def question(u, v):
print('?', u, v)
d = int(input())
return d
INF = 1<<62
G = [[] for _ in range(N)]
dist0 = [INF] * N
dist0[0] = 0
dist1 = [INF] * N
dist1[1] = 0
for i in range(2, N):
dist0[i] = question(1, i+1)
dist1[i] = question(2, i+1)
cnt = 0
x = []
mn_dist = INF
for i in range(N):
mn_dist = min(mn_dist, dist0[i] + dist1[i])
if dist0[i]+dist1[i] == 3:
cnt += 1
x.append(i)
if mn_dist != 3:
print('!', mn_dist)
else:
if cnt != 2:
print('!', 1)
else:
d = question(x[0]+1, x[1]+1)
if d == 1:
print('!', mn_dist)
else:
print('!', 1) | ConDefects/ConDefects/Code/arc142_c/Python/40185010 |
condefects-python_data_451 | n = 10
s = [input()for i in range(n)]
a,b,c,d = 100, 0, 100, 0
for i in range(n):
for j in range(n):
if s[i][j]=='#':
if a>i : a=i
if b<i : B=i
if c>j : c=j
if d<j : d=j
print(a+1,b+1)
print(c+1,d+1)
n = 10
s = [input()for i in range(n)]
a,b,c,d = 100, 0, 100, 0
for i in range(n):
for j in range(n):
if s[i][j]=='#':
if a>i : a=i
if b<i : b=i
if c>j : c=j
if d<j : d=j
print(a+1,b+1)
print(c+1,d+1) | ConDefects/ConDefects/Code/abc269_b/Python/45961458 |
condefects-python_data_452 | s=input()
if s=="Monday":
print(5)
if s=="Tuesday":
print(4)
if s=="Wednesday":
print(3)
if s=="Thursday":
print(2)
if s=="Friay":
print(1)
s=input()
if s=="Monday":
print(5)
if s=="Tuesday":
print(4)
if s=="Wednesday":
print(3)
if s=="Thursday":
print(2)
if s=="Friday":
print(1)
| ConDefects/ConDefects/Code/abc267_a/Python/45943869 |
condefects-python_data_453 | n,a,b,*D = map(int,open(0).read().split())
s = sum(D)
p,q = abs(a),abs(b)
if p+q>s or (s+p+q)%2:
print("No")
exit()
x,y = (s+p+q)//2,(s+p-q)//2
dp = [0]*(n+1)
dp[0] = 1
for i in range(n):
dp[i+1] = dp[i]|dp[i]<<D[i]
if not dp[n]>>x&dp[n]>>y&1:
print("No")
exit()
L = []
for i in range(n)[::-1]:
s,t = (dp[i]>>x&1)^1,(dp[i]>>y&1)^1
L.append("DLRU"[s*2+t])
if s:
x -= D[i]
if t:
y -= D[i]
ans = "".join(L[::-1])
if a < 0:
ans = ans.translate(str.maketrans({"L":"R","R":"L"}))
if b < 0:
ans = ans.translate(str.maketrans({"U":"D","D":"U"}))
print("Yes")
print(ans)
n,a,b,*D = map(int,open(0).read().split())
s = sum(D)
p,q = abs(a),abs(b)
if p+q>s or (s+p+q)%2:
print("No")
exit()
x,y = (s+p+q)//2,(s+p-q)//2
dp = [0]*(n+1)
dp[0] = 1
for i in range(n):
dp[i+1] = dp[i]|dp[i]<<D[i]
if not dp[n]>>x&dp[n]>>y&1:
print("No")
exit()
L = []
for i in range(n)[::-1]:
s,t = (dp[i]>>x&1)^1,(dp[i]>>y&1)^1
L.append("LDUR"[s*2+t])
if s:
x -= D[i]
if t:
y -= D[i]
ans = "".join(L[::-1])
if a < 0:
ans = ans.translate(str.maketrans({"L":"R","R":"L"}))
if b < 0:
ans = ans.translate(str.maketrans({"U":"D","D":"U"}))
print("Yes")
print(ans) | ConDefects/ConDefects/Code/abc221_g/Python/26339941 |
condefects-python_data_454 | n, a, b, *d = map(int, open(0).read().split())
s = sum(d)
x = a+b+s
y = b-a+s
res = ""
if x >= 0 <= y and x & 1 == 0:
x >>= 1
y >>= 1
dp = [1]
for j in d:
dp += dp[-1] << j | dp[-1],
if dp[n] >> x & 1 and dp[n] >> y & 1:
while n:
n -= 1
i = ~dp[n] >> x & 1
j = ~dp[n] >> y & 1
res += "DLRU"[2*i+j]
x -= i * d[n]
y -= j * d[n]
print(res and "Yes" or "No",res)
n, a, b, *d = map(int, open(0).read().split())
s = sum(d)
x = a+b+s
y = b-a+s
res = ""
if x >= 0 <= y and x & 1 == 0:
x >>= 1
y >>= 1
dp = [1]
for j in d:
dp += dp[-1] << j | dp[-1],
if dp[n] >> x & 1 and dp[n] >> y & 1:
while n:
n -= 1
i = ~dp[n] >> x & 1
j = ~dp[n] >> y & 1
res += "DLRU"[2*i+j]
x -= i * d[n]
y -= j * d[n]
print(res and "Yes" or "No",res[::-1])
| ConDefects/ConDefects/Code/abc221_g/Python/40740321 |
condefects-python_data_455 | # Python3/Pypy3テンプレート集
#ライブラリ-------------------------------------------------------------------
from bisect import *
import heapq
import collections
from collections import deque
from queue import Queue
from itertools import groupby
import itertools
import math
import array
import string
import copy
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
from functools import reduce
from operator import and_, or_, xor
#便利スクリプト---------------------------------------------------------------
INF = 10**20
mod = 998244353
MOD = 10**9+7
def YesNo(b): print("Yes") if b else print("No")
def YESNO(b): print("YES") if b else print("NO")
#標準入力---------------------------------------------------------------------
import sys
sys.setrecursionlimit(10 ** 5 + 10000)
input = sys.stdin.readline ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LIS(): return list(map(int, SI()))
def LA(f): return list(map(f, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return input().strip('\n')
def MS(): return input().split()
def LS(): return list(input().strip('\n'))
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def LMS(rows_number): return [MS() for _ in range(rows_number)]
#関数------------------------------------------------------------------------
###標準ライブラリ###
def ceil(a,b): #切り捨て
return (a+b-1)//b
def inv(a,p): #aのpを法とする逆元(aとpは互いに素)
return pow(a,p-2,p)%p
def transpose(A): #二次元配列の転置
A_t = []
for i in range(len(A[0])) :
tmp = []
for v in A :
tmp.append(v[i])
A_t.append(tmp)
return A_t
def rotate_matrix(A): #グリッドを時計回りに90度回転
return transpose(A[::-1])
def removeDuplicates_2D(A): #二次元配列の重複削除
return list(map(list, set(map(tuple, A))))
def convert(S,c): # グリッドをの 黒 マスの点集合に変換する | S: グリッド c:黒マスがなにか(ex #,1)
s = set()
h = len(S)
w = len(S[0])
for i in range(h):
for j in range(w):
if S[i][j] == c:
s.add((i, j))
return s
def normalize(s): # グリッドの # マスの点集合を与えると最小の x 座標と最小の y 座標がともに 0 となるように平行移動して返す
mi = min(i for (i, j) in s)
mj = min(j for (i, j) in s)
return set((i - mi, j - mj) for (i, j) in s)
def cumulativeSum_1D(A): #配列Aの累積和
return list(itertools.accumulate(A))
def cumulativeSum_2D(S): #二次元配列Sの累積和 => 二次元リスト
h = len(S)
w = len(S[0])
CS = [[0 for _ in range(w)]for _ in range(h)]
CCS = [[0 for _ in range(w)]for _ in range(h)]
for i in range(h):
for j in range(w):
if(j==0):
CS[i][0] = S[i][0]
else:
CS[i][j] = CS[i][j-1] + S[i][j]
for i in range(h):
for j in range(w):
if(i==0):
CCS[0][j] = CS[0][j]
else:
CCS[i][j] = CCS[i-1][j] + CS[i][j]
return CCS
def string_to_runLength(S: str): #文字列/リストからラングレス圧縮
grouped = groupby(S)
res = []
for k, v in grouped:
res.append((k, int(len(list(v)))))
return res
def runLength_to_string(L: "list[tuple]"): #ラングレス圧縮から文字列 => 文字だけ
res = ""
for c, n in L:
res += c * int(n)
return res
def bfs(i,G): # i:始点
n = len(G)
dist = [-1] * n
pre = [-1] * n
que = deque()
dist[i] = 0
que.append(i)
while not len(que)==0:
v = que.popleft()
for next_v in G[v]:
if dist[next_v] != -1:
continue
dist[next_v] = dist[v] + 1
pre[next_v] = v
que.append(next_v)
return dist,pre
def bfs01(s, G): # i:始点 => dist
N = len(G)
dist = [INF] * N
S = deque([s])
T = deque()
dist[s] = 0
d = 0
while S:
while S:
v = S.popleft()
for c, w in G[v]:
if d+c < dist[w]:
dist[w] = d+c
if c:
T.append(w)
else:
S.append(w)
S, T = T, S
d += 1
return dist
def dijkstra(s,G): #s:始点 => cost,pre | G:タプルの中身(コスト,行先)
n = len(G)
hq = [(0, s)]
heapq.heapify(hq)
cost = [INF]*n
cost[s]= 0
pre = [-1] * n
while hq:
c,v = heapq.heappop(hq)
if c > cost[v]:
continue
for d,u in G[v]:
tmp = d+cost[v]
if tmp < cost[u]:
cost[u] = tmp
pre[u] = v
heapq.heappush(hq,(tmp,u))
return cost, pre
def coordinates(A): # 変換表(元の値 : 座標圧縮の値),変換表2(座標圧縮の値: 元の値), 圧縮後配列
B = sorted(set(A))
C = { v: i for i, v in enumerate(B) }
D = { i: v for i, v in enumerate(B) }
E = list(map(lambda v: C[v], A))
return C, D, E
def eng_L(): return list(string.ascii_lowercase)
def ENG_L(): return list(string.ascii_uppercase)
def bit_len(n): #bit長
return n.bit_length()
def bit_cnt(n): # bitにしたときの1の数
cnt = 0
for i in range(bit_len(n)+1):
cnt += n>>i & 1
return cnt
def idx_le(A, x): # x 以下の最大の要素位置 / なければ "No"
return bisect_right(A, x)-1 if bisect_right(A, x)-1 != -1 else "No"
def idx_lt(A, x): # x 未満の最大の要素位置 / なければ "No"
return bisect_left(A, x)-1 if bisect_right(A, x)-1 != -1 else "No"
def idx_ge(A, x): # x 以上の最小の要素位置 / なければ "No"
return bisect_left(A, x) if bisect_left(A, x) != len(A) else "No"
def idx_gt(A, x): # x 超過の最小の要素位置 / なければ "No"
return bisect_right(A, x) if bisect_right(A, x) != len(A) else "No"
def cnt_le(A, x): # x 以下の要素の個数
if(idx_le(A, x) == "No"): return 0
return idx_le(A, x) + 1
def cnt_lt(A, x): # x 未満の要素の個数
if(idx_lt(A, x) == "No"): return 0
return idx_lt(A, x) + 1
def cnt_ge(A, x): # x 以上の要素の個数
return len(A) - cnt_lt(A, x)
def cnt_gt(A, x): # x 超過の要素の個数
return len(A) - cnt_le(A, x)
###数学ライブラリ###
def allAND(A): # 配列Aの総AND
return reduce(and_, A)
def allOR(A): # 配列Aの総OR
return reduce(or_, A)
def allXOR(A): # 配列Aの総XOR
return reduce(xor, A)
def allGCD(A): # 配列Aの総GCD
if(len(A)==1):
return A[0]
g = math.gcd(A[0],A[1])
for i in range(1,len(A)):
g = math.gcd(g, A[i])
return g
def mex(A): #配列Aのmexを求める
B = set()
for a in A:
if(a>=0):
B.add(a)
B = list(B)
B.sort()
if(len(B)==0):
return 0
if(B[0]!=0):
return 0
m = 0
for i in range(1,len(B)):
if(B[i]==B[i-1]+1):
m +=1
else:
break
return m +1
def gcd(a,b): #aとbの最大公約数を求める
return math.gcd(a,b)
def lcm(a,b): #aとbの最小公倍数を求める
return a*b//gcd(a,b)
def extgcd(a, b): # a,b =>ax+by=gcd(a,b)を満たす(g,x,y) a,bが互いに素のとき、xはaのbを法とする逆元
if b:
d, y, x = extgcd(b, a % b)
y -= (a // b)*x
return d, x, y
return a, 1, 0
def fact_L(n,mod): # [0!, 1! ..., n!] を返す
fact = [1]
p = 1
for i in range(1,n+1):
p *= i
p %= mod
fact.append(p)
return fact
def bitCount_L(n): # n以下のそれぞれのbitカウントを返す
bitcount = [0] * (n+1)
for i in range(1,n+1):
bitcount[i] = bitcount[i//2] + i%2
return bitcount
def factorial(n, m=0): #nの階乗 | m:mod(デフォなし)
if(n<0):
return -1
elif(n==0):
return 1
P = 1
for i in range(1,n+1):
P *= i
if(m==0):
continue
P %= m
return P
def nPr(n, r, m=0): #順列nPr
if(n<=0 or r<0 or n<r):
return -1
if(r==0):
return 1
P = 1
for i in range(n,n-r,-1):
P *= i
if(m==0):
continue
P %= m
return P
def nCr(n, r, m=0): #組み合わせnCr
if(n<r):
return 0
if(n==r):
return 1
if(n<=0 or r<0 or n<r):
return -1
N = 1
for i in range(r):
N *= n-i
if(m==0):
continue
N %= m
R = factorial(r)
return N//R
def nCrm(n,r,m=mod): #逆元を用いた組み合わせnCr%mod
if(n<r):
return 0
if(n==r):
return 1
if(n<=0 or r<0 or n<r):
return -1
over=1
for i in range(n-r+1,n+1):
over *= i
over %= m
under=1
for i in range(1,r+1):
under *= i
under %= m
return over*pow(under,m-2,m)%m
def is_prime(n): #素数判定 => True/False
if n == 2:
return 1
if n == 1 or n%2 == 0:
return 0
m = n - 1
lsb = m & -m
s = lsb.bit_length()-1
d = m // lsb
test_numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
for a in test_numbers:
if a == n:
continue
x = pow(a,d,n)
r = 0
if x == 1:
continue
while x != m:
x = pow(x,2,n)
r += 1
if x == 1 or r == s:
return 0
return 1
def prime_L(n): #n以下の素数のリスト
is_prime = [True] * (n + 1)
is_prime[0] = False
is_prime[1] = False
for i in range(2, int(n**0.5) + 1):
if not is_prime[i]:
continue
for j in range(i * 2, n + 1, i):
is_prime[j] = False
return [i for i in range(n + 1) if is_prime[i]]
def find_prime_factor(n):
if n%2 == 0:
return 2
m = int(n**0.125)+1
for c in range(1,n):
f = lambda a: (pow(a,2,n)+c)%n
y = 0
g = q = r = 1
k = 0
while g == 1:
x = y
while k < 3*r//4:
y = f(y)
k += 1
while k < r and g == 1:
ys = y
for _ in range(min(m, r-k)):
y = f(y)
q = q*abs(x-y)%n
g = math.gcd(q,n)
k += m
k = r
r *= 2
if g == n:
g = 1
y = ys
while g == 1:
y = f(y)
g = math.gcd(abs(x-y),n)
if g == n:
continue
if is_prime(g):
return g
elif is_prime(n//g):
return n//g
else:
return find_prime_factor(g)
def primeFactorization_2L(n): #2以上の整数n => [[素因数, 指数], ...]の2次元リスト
if(n<=10**6):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1:
arr.append([temp, 1])
if arr==[]:
arr.append([n, 1])
return arr
else:
res = {}
while not is_prime(n) and n > 1:
p = find_prime_factor(n)
s = 0
while n%p == 0:
n //= p
s += 1
res[p] = s
if n > 1:
res[n] = 1
R = []
for r in res:
R.append([r,res[r]])
R.sort()
return R
def divisor_L(n): #nまでの約数のリスト
if(n==1):
return [1]
if(n<=10**6):
lower_divisors , upper_divisors = [], []
i = 1
while i*i <= n:
if n % i == 0:
lower_divisors.append(i)
if i != n // i:
upper_divisors.append(n//i)
i += 1
return lower_divisors + upper_divisors[::-1]
else:
L = primeFactorization_2L(n)
E = [[]for i in range(len(L))]
for i in range(len(L)):
for j in range(L[i][1]+1):
E[i].append(L[i][0]**j)
D = []
for p in list(itertools.product(*E)):
s = 1
for v in p:
s *= v
D.append(s)
D.sort()
return D
def floorsqrt(n): # N => ⌊√N⌋
# only for n <= 10 ** 18
ok = 10 ** 9 + 10
ng = 0
while ok - ng > 1:
t = (ok + ng) // 2
if t * t > n: ok = t
else: ng = t
return ng
def decimal_to_nAry(num_10,n): #10進数からn進数へ変換する(n<=36) |int型 => str型
str_n = []
while num_10:
if num_10%n >= 10:
str_n.append(chr(num_10%n+55))
else:
str_n.append(str(num_10%n))
num_10 //= n
return "".join(str_n[::-1])
def nAry_to_decimal(X,n): #n進数から10進数へ変換する(n<=36) | str型 => int型
num = 0
X = X.upper()
X = list(X)
for i in range(len(X)):
if(("0"<=X[i]<="9")==False):
X[i] = str(ord(X[i]) - 55)
for i in range(1,len(X)+1):
num += int(X[-i]) * pow(n, (i-1))
return num
def roundOff(x,d): #四捨五入する x:対象の数字, d:四捨五入する位(正|負) => float型の数値
return float(Decimal(x).quantize(Decimal(f"1E{d}"), rounding=ROUND_HALF_UP))
###幾何ライブラリ###
def dsin(d): #度数法でsinを計算する
return math.sin(math.radians(d))
def dcos(d): #度数法でcosを計算する
return math.cos(math.radians(d))
def rotate(x,y,d,cx=0,cy=0): #P(x,y)をA(cx,cy)を中心としてに反時計回りにd°回転 => [x,y]
nx = (x-cx)*dcos(d)-(y-cy)*dsin(d)
ny = (x-cx)*dsin(d)+(y-cy)*dcos(d)
return [nx+cx,ny+cy]
def findAngle(O,A,B): #∠AOBを求める(弧度法)
s = [A[0]-O[0],A[1]-O[1]]
t = [B[0]-O[0],B[1]-O[1]]
u = s[0]*t[0]+s[1]*t[1]
l = (s[0]**2+s[1]**2)**(1/2) * (t[0]**2+t[1]**2)**(1/2)
v = u/l
t = math.degrees(math.acos(v))
return t
def outerProduct(Av,Bv): #二次元ベクトルの外積(=符号付面積)を求める(a×b)
return Av[0]*Bv[1] - Bv[0]*Av[1]
def CCW(O,A,B): #Oを中心として、Aから見たAとBの位置関係を求める。
# -1: 時計回り, 0: 一直線上, 1: 反時計回り
s = [A[0]-O[0],A[1]-O[1]]
t = [B[0]-O[0],B[1]-O[1]]
op = outerProduct(s,t)
if(op > 0): return 1
if(op < 0): return -1
if(op == 0): return 0
def matrixMultiplication_2D(a,b,m): #行列の掛け算(a×b) m:mod
I,J,K,L = len(a),len(b[0]),len(b),len(a[0])
if(L!=K):
return -1
c = [[0] * J for _ in range(I)]
for i in range(I) :
for j in range(J) :
for k in range(K) :
c[i][j] += a[i][k] * b[k][j]
c[i][j] %= m
return c
def matrixExponentiation_2D(x,n,m): #行列の累乗 (x^n) m:mod
y = [[0] * len(x) for _ in range(len(x))]
for i in range(len(x)):
y[i][i] = 1
while n > 0:
if n & 1:
y = matrixMultiplication_2D(x,y,m)
x = matrixMultiplication_2D(x,x,m)
n >>= 1
return y
def twoCircles(A,B): #二つの円の半径の位置関係 | 引数はそれぞれ[x,y(=座標),r(=半径)]
# 1 : 一方の円が他方の円を完全に含み、2 つの円は接していない
# 2 : 一方の円が他方の円を完全に含み、2 つの円は接している
# 3 : 2 つの円が互いに交差する
# 4 : 2 つの円の内部に共通部分は存在しないが、2 つの円は接している
# 5 : 2 つの円の内部に共通部分は存在せず、2 つの円は接していない
x1 = A[0]
x2 = B[0]
y1 = A[1]
y2 = B[1]
r1 = A[2]
r2 = B[2]
d = abs((x1-x2)+1j*(y1-y2))
if(abs(r2-r1)>d):
return 1
elif(abs(r2-r1)==d):
return 2
elif(r1+r2>d):
return 3
elif(r1+r2==d):
return 4
elif(r1+r2<d):
return 5
###デバッグ用ライブラリ###
def TS(_str): #変数/リストに格納されている値を確認
print('{}: {}'.format(_str, eval(_str)))
def T2d(A): #二次元配列の確認用
for a in A:
print(*a)
def T3d(A): #三次元配列の確認用
for a in A:
T2d(a)
BR()
def BR(): #横線で区切りを入れる
print("---")
#クラス----------------------------------------------------------------------
#カンニングペーパー-----------------------------------------------------------
'''
###標準ライブラリ###
ceil(a,b): #切り捨て
inv(a,p): #xのpを法とする逆元
transpose(A): #二次元配列の転置
rotate_matrix(A): #グリッドを時計回りに90度回転
removeDuplicates_2D(A): #二次元配列の重複削除
convert(S, c): # グリッドをの 黒 マスの点集合に変換する | S: グリッド c:黒マスがなにか(ex #,1)
normalize(s): # グリッドの # マスの点集合を与えると最小の x 座標と最小の y 座標がともに 0 となるように平行移動して返す
例)normalize(convert(h,w,A))
cumulativeSum_1D(A) #配列Aの累積和
cumulativeSum_2D(S): #二次元配列Sの累積和 => 二次元リスト
string_to_runLength(S: str) #文字列/リストからラングレス圧縮 => [(文字,個数), ...]の二次元リスト
runLength_to_string(L: "list[tuple]") #ラングレス圧縮 => 文字列
bfs(i,G) # i:始点 => dist,pre
bfs01(i,G) # i:始点 => dist
dijkstra(s,G): #s:始点 => cost,pre | G:タプルの中身(コスト,行先)
coordinates(A) # 変換表(元の値 : 座標圧縮の値),変換表2(座標圧縮の値: 元の値), 圧縮後配列
eng_L() #英小文字のリスト
ENG_L() #英大文字のリスト
bit_len(n): #bit長
bit_cnt(n): # bitにしたときの1の数
idx_le(A, x) # x 以下の最大の要素位置 / なければ "No"
idx_lt(A, x) # x 未満の最大の要素位置 / なければ "No"
idx_ge(A, x) # x 以上の最小の要素位置 / なければ "No"
idx_gt(A, x) # x 超過の最小の要素位置 / なければ "No"
cnt_le(A, x) # x 以下の要素の個数
cnt_lt(A, x) # x 未満の要素の個数
cnt_ge(A, x) # x 以上の要素の個数
cnt_gt(A, x) # x 超過の要素の個数
###数学ライブラリ###
allAND(A): # 配列Aの総AND
allOR(A): # 配列Aの総OR
allXOR(A): # 配列Aの総XOR
allGCD(A): # 配列Aの総GCD
mex(A) #配列Aのmexを求める
gcd(a,b) #aとbの最大公約数を求める
lcm(a,b) #aとbの最小公倍数を求める
extgcd(a, b): # a,b =>ax+by=gcd(a,b)を満たす(g,x,y) a,bが互いに素のとき、xはaのbを法とする逆元
fact_L(n,mod): # [0!, 1! ..., n!] を返す
bitCount_L(n): # n以下のそれぞれのbitカウントを返す
factorial(n,m) #nの階乗 | m:mod(デフォなし)
nPr(n,r,m) #順列nPr | m:mod(デフォなし)
nCr(n,r,m) #組み合わせ,nCr | m:mod(デフォなし)
nCrm(n,r,m) #逆元を用いた組み合わせnCr%mod
divisor_L(n) #nの約数のリスト
is_prime(n) #素数判定 => True/False
prime_L(n) #nまでの素数のリスト
primeFactorization_2L(n) #2以上の整数n => [[素因数, 指数], ...]の2次元リスト
floorsqrt(n): # N => ⌊√N⌋
decimal_to_nAry(num_10,n) #10進数からn進数へ変換する(n<=36) |int型 => str型
nAry_to_decimal(num_n,n) #n進数から10進数へ変換する(n<=36) | str型 => int型
roundOff(x,d): #四捨五入する x:対象の数字, d:四捨五入する位(正|負) => float型の数値
###幾何ライブラリ###
dsin(d): #度数法でsinを計算する
dcos(d): #度数法でcosを計算する
rotate(x,y,d,cx,cy): #P(x,y)をA(cx,cy)を中心としてに反時計回りにd°回転(デフォ原点) => [x,y]
findAngle(O,A,B) #∠AOBを求める(弧度法) | 引数はそれぞれ[x,y(=座標)]
outerProduct(Av,Bv) #二次元ベクトルの外積(=符号付面積)を求める(a×b) | 引数はそれぞれ[x,y(=座標)]
CCW(O,A,B) #Oを中心として、Aから見たAとBの位置関係
=> -1:時計回り, 0:一直線上, 1:反時計回り | 引数はそれぞれ[x,y(=座標)]
matrixMultiplication_2D(a,b,m) #行列の掛け算(a×b) m:mod | 引数は二次元リスト
matrixExponentiation_2D(x,n m)#行列の累乗 (x^n) m:mod | 引数は二次元リスト
twoCircles(A,B): #二つの円の半径の位置関係 | 引数はそれぞれ[x,y(=座標),r(=半径)]
=> 1, 2, 3, 4, 5 各数字に対応する位置関係の説明は上記参照
###デバッグ用ライブラリ###
TS(_str) # 変数/リストに格納されている値を確認 => 〇〇:××
T2d(A): # 二次元配列の確認用
T3d(A): # 三次元配列の確認用
BR() # 横線で区切りを入れる
###文法チートシート###
|S|<x => "0"*(x-|S|) + S : str(n).zfill(x)
全部大文字に変換:str.upper()
全部小文字に変換:str.lower()
先頭のみ大文字に変換:str.capitalize()
各単語の先頭のみ大文字に変換(タイトルケース):str.title()
大文字と小文字を入れ替える:str.swapcase()
文字 → ASCIIコード ord(s)
ASCIIコード → 文字 chr(x)
ASCII表
65:A ~ 90:Z
97:a ~ 122:z
'''
#PyPyで再帰関数を用いる場合はコメントを外す----------------------------------
# import pypyjit
# pypyjit.set_param('max_unroll_recursion=-1')
#----------------------------------------------------------------------------
N,K = MI()
S = input()
ans = []
for i in range(len(S)):
if S[i] == "o" and ans.count("o") <= K-1:
ans.append("o")
else:
ans.append("x")
print("".join(ans))
# Python3/Pypy3テンプレート集
#ライブラリ-------------------------------------------------------------------
from bisect import *
import heapq
import collections
from collections import deque
from queue import Queue
from itertools import groupby
import itertools
import math
import array
import string
import copy
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
from functools import reduce
from operator import and_, or_, xor
#便利スクリプト---------------------------------------------------------------
INF = 10**20
mod = 998244353
MOD = 10**9+7
def YesNo(b): print("Yes") if b else print("No")
def YESNO(b): print("YES") if b else print("NO")
#標準入力---------------------------------------------------------------------
import sys
sys.setrecursionlimit(10 ** 5 + 10000)
input = sys.stdin.readline ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LIS(): return list(map(int, SI()))
def LA(f): return list(map(f, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return input().strip('\n')
def MS(): return input().split()
def LS(): return list(input().strip('\n'))
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def LMS(rows_number): return [MS() for _ in range(rows_number)]
#関数------------------------------------------------------------------------
###標準ライブラリ###
def ceil(a,b): #切り捨て
return (a+b-1)//b
def inv(a,p): #aのpを法とする逆元(aとpは互いに素)
return pow(a,p-2,p)%p
def transpose(A): #二次元配列の転置
A_t = []
for i in range(len(A[0])) :
tmp = []
for v in A :
tmp.append(v[i])
A_t.append(tmp)
return A_t
def rotate_matrix(A): #グリッドを時計回りに90度回転
return transpose(A[::-1])
def removeDuplicates_2D(A): #二次元配列の重複削除
return list(map(list, set(map(tuple, A))))
def convert(S,c): # グリッドをの 黒 マスの点集合に変換する | S: グリッド c:黒マスがなにか(ex #,1)
s = set()
h = len(S)
w = len(S[0])
for i in range(h):
for j in range(w):
if S[i][j] == c:
s.add((i, j))
return s
def normalize(s): # グリッドの # マスの点集合を与えると最小の x 座標と最小の y 座標がともに 0 となるように平行移動して返す
mi = min(i for (i, j) in s)
mj = min(j for (i, j) in s)
return set((i - mi, j - mj) for (i, j) in s)
def cumulativeSum_1D(A): #配列Aの累積和
return list(itertools.accumulate(A))
def cumulativeSum_2D(S): #二次元配列Sの累積和 => 二次元リスト
h = len(S)
w = len(S[0])
CS = [[0 for _ in range(w)]for _ in range(h)]
CCS = [[0 for _ in range(w)]for _ in range(h)]
for i in range(h):
for j in range(w):
if(j==0):
CS[i][0] = S[i][0]
else:
CS[i][j] = CS[i][j-1] + S[i][j]
for i in range(h):
for j in range(w):
if(i==0):
CCS[0][j] = CS[0][j]
else:
CCS[i][j] = CCS[i-1][j] + CS[i][j]
return CCS
def string_to_runLength(S: str): #文字列/リストからラングレス圧縮
grouped = groupby(S)
res = []
for k, v in grouped:
res.append((k, int(len(list(v)))))
return res
def runLength_to_string(L: "list[tuple]"): #ラングレス圧縮から文字列 => 文字だけ
res = ""
for c, n in L:
res += c * int(n)
return res
def bfs(i,G): # i:始点
n = len(G)
dist = [-1] * n
pre = [-1] * n
que = deque()
dist[i] = 0
que.append(i)
while not len(que)==0:
v = que.popleft()
for next_v in G[v]:
if dist[next_v] != -1:
continue
dist[next_v] = dist[v] + 1
pre[next_v] = v
que.append(next_v)
return dist,pre
def bfs01(s, G): # i:始点 => dist
N = len(G)
dist = [INF] * N
S = deque([s])
T = deque()
dist[s] = 0
d = 0
while S:
while S:
v = S.popleft()
for c, w in G[v]:
if d+c < dist[w]:
dist[w] = d+c
if c:
T.append(w)
else:
S.append(w)
S, T = T, S
d += 1
return dist
def dijkstra(s,G): #s:始点 => cost,pre | G:タプルの中身(コスト,行先)
n = len(G)
hq = [(0, s)]
heapq.heapify(hq)
cost = [INF]*n
cost[s]= 0
pre = [-1] * n
while hq:
c,v = heapq.heappop(hq)
if c > cost[v]:
continue
for d,u in G[v]:
tmp = d+cost[v]
if tmp < cost[u]:
cost[u] = tmp
pre[u] = v
heapq.heappush(hq,(tmp,u))
return cost, pre
def coordinates(A): # 変換表(元の値 : 座標圧縮の値),変換表2(座標圧縮の値: 元の値), 圧縮後配列
B = sorted(set(A))
C = { v: i for i, v in enumerate(B) }
D = { i: v for i, v in enumerate(B) }
E = list(map(lambda v: C[v], A))
return C, D, E
def eng_L(): return list(string.ascii_lowercase)
def ENG_L(): return list(string.ascii_uppercase)
def bit_len(n): #bit長
return n.bit_length()
def bit_cnt(n): # bitにしたときの1の数
cnt = 0
for i in range(bit_len(n)+1):
cnt += n>>i & 1
return cnt
def idx_le(A, x): # x 以下の最大の要素位置 / なければ "No"
return bisect_right(A, x)-1 if bisect_right(A, x)-1 != -1 else "No"
def idx_lt(A, x): # x 未満の最大の要素位置 / なければ "No"
return bisect_left(A, x)-1 if bisect_right(A, x)-1 != -1 else "No"
def idx_ge(A, x): # x 以上の最小の要素位置 / なければ "No"
return bisect_left(A, x) if bisect_left(A, x) != len(A) else "No"
def idx_gt(A, x): # x 超過の最小の要素位置 / なければ "No"
return bisect_right(A, x) if bisect_right(A, x) != len(A) else "No"
def cnt_le(A, x): # x 以下の要素の個数
if(idx_le(A, x) == "No"): return 0
return idx_le(A, x) + 1
def cnt_lt(A, x): # x 未満の要素の個数
if(idx_lt(A, x) == "No"): return 0
return idx_lt(A, x) + 1
def cnt_ge(A, x): # x 以上の要素の個数
return len(A) - cnt_lt(A, x)
def cnt_gt(A, x): # x 超過の要素の個数
return len(A) - cnt_le(A, x)
###数学ライブラリ###
def allAND(A): # 配列Aの総AND
return reduce(and_, A)
def allOR(A): # 配列Aの総OR
return reduce(or_, A)
def allXOR(A): # 配列Aの総XOR
return reduce(xor, A)
def allGCD(A): # 配列Aの総GCD
if(len(A)==1):
return A[0]
g = math.gcd(A[0],A[1])
for i in range(1,len(A)):
g = math.gcd(g, A[i])
return g
def mex(A): #配列Aのmexを求める
B = set()
for a in A:
if(a>=0):
B.add(a)
B = list(B)
B.sort()
if(len(B)==0):
return 0
if(B[0]!=0):
return 0
m = 0
for i in range(1,len(B)):
if(B[i]==B[i-1]+1):
m +=1
else:
break
return m +1
def gcd(a,b): #aとbの最大公約数を求める
return math.gcd(a,b)
def lcm(a,b): #aとbの最小公倍数を求める
return a*b//gcd(a,b)
def extgcd(a, b): # a,b =>ax+by=gcd(a,b)を満たす(g,x,y) a,bが互いに素のとき、xはaのbを法とする逆元
if b:
d, y, x = extgcd(b, a % b)
y -= (a // b)*x
return d, x, y
return a, 1, 0
def fact_L(n,mod): # [0!, 1! ..., n!] を返す
fact = [1]
p = 1
for i in range(1,n+1):
p *= i
p %= mod
fact.append(p)
return fact
def bitCount_L(n): # n以下のそれぞれのbitカウントを返す
bitcount = [0] * (n+1)
for i in range(1,n+1):
bitcount[i] = bitcount[i//2] + i%2
return bitcount
def factorial(n, m=0): #nの階乗 | m:mod(デフォなし)
if(n<0):
return -1
elif(n==0):
return 1
P = 1
for i in range(1,n+1):
P *= i
if(m==0):
continue
P %= m
return P
def nPr(n, r, m=0): #順列nPr
if(n<=0 or r<0 or n<r):
return -1
if(r==0):
return 1
P = 1
for i in range(n,n-r,-1):
P *= i
if(m==0):
continue
P %= m
return P
def nCr(n, r, m=0): #組み合わせnCr
if(n<r):
return 0
if(n==r):
return 1
if(n<=0 or r<0 or n<r):
return -1
N = 1
for i in range(r):
N *= n-i
if(m==0):
continue
N %= m
R = factorial(r)
return N//R
def nCrm(n,r,m=mod): #逆元を用いた組み合わせnCr%mod
if(n<r):
return 0
if(n==r):
return 1
if(n<=0 or r<0 or n<r):
return -1
over=1
for i in range(n-r+1,n+1):
over *= i
over %= m
under=1
for i in range(1,r+1):
under *= i
under %= m
return over*pow(under,m-2,m)%m
def is_prime(n): #素数判定 => True/False
if n == 2:
return 1
if n == 1 or n%2 == 0:
return 0
m = n - 1
lsb = m & -m
s = lsb.bit_length()-1
d = m // lsb
test_numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
for a in test_numbers:
if a == n:
continue
x = pow(a,d,n)
r = 0
if x == 1:
continue
while x != m:
x = pow(x,2,n)
r += 1
if x == 1 or r == s:
return 0
return 1
def prime_L(n): #n以下の素数のリスト
is_prime = [True] * (n + 1)
is_prime[0] = False
is_prime[1] = False
for i in range(2, int(n**0.5) + 1):
if not is_prime[i]:
continue
for j in range(i * 2, n + 1, i):
is_prime[j] = False
return [i for i in range(n + 1) if is_prime[i]]
def find_prime_factor(n):
if n%2 == 0:
return 2
m = int(n**0.125)+1
for c in range(1,n):
f = lambda a: (pow(a,2,n)+c)%n
y = 0
g = q = r = 1
k = 0
while g == 1:
x = y
while k < 3*r//4:
y = f(y)
k += 1
while k < r and g == 1:
ys = y
for _ in range(min(m, r-k)):
y = f(y)
q = q*abs(x-y)%n
g = math.gcd(q,n)
k += m
k = r
r *= 2
if g == n:
g = 1
y = ys
while g == 1:
y = f(y)
g = math.gcd(abs(x-y),n)
if g == n:
continue
if is_prime(g):
return g
elif is_prime(n//g):
return n//g
else:
return find_prime_factor(g)
def primeFactorization_2L(n): #2以上の整数n => [[素因数, 指数], ...]の2次元リスト
if(n<=10**6):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1:
arr.append([temp, 1])
if arr==[]:
arr.append([n, 1])
return arr
else:
res = {}
while not is_prime(n) and n > 1:
p = find_prime_factor(n)
s = 0
while n%p == 0:
n //= p
s += 1
res[p] = s
if n > 1:
res[n] = 1
R = []
for r in res:
R.append([r,res[r]])
R.sort()
return R
def divisor_L(n): #nまでの約数のリスト
if(n==1):
return [1]
if(n<=10**6):
lower_divisors , upper_divisors = [], []
i = 1
while i*i <= n:
if n % i == 0:
lower_divisors.append(i)
if i != n // i:
upper_divisors.append(n//i)
i += 1
return lower_divisors + upper_divisors[::-1]
else:
L = primeFactorization_2L(n)
E = [[]for i in range(len(L))]
for i in range(len(L)):
for j in range(L[i][1]+1):
E[i].append(L[i][0]**j)
D = []
for p in list(itertools.product(*E)):
s = 1
for v in p:
s *= v
D.append(s)
D.sort()
return D
def floorsqrt(n): # N => ⌊√N⌋
# only for n <= 10 ** 18
ok = 10 ** 9 + 10
ng = 0
while ok - ng > 1:
t = (ok + ng) // 2
if t * t > n: ok = t
else: ng = t
return ng
def decimal_to_nAry(num_10,n): #10進数からn進数へ変換する(n<=36) |int型 => str型
str_n = []
while num_10:
if num_10%n >= 10:
str_n.append(chr(num_10%n+55))
else:
str_n.append(str(num_10%n))
num_10 //= n
return "".join(str_n[::-1])
def nAry_to_decimal(X,n): #n進数から10進数へ変換する(n<=36) | str型 => int型
num = 0
X = X.upper()
X = list(X)
for i in range(len(X)):
if(("0"<=X[i]<="9")==False):
X[i] = str(ord(X[i]) - 55)
for i in range(1,len(X)+1):
num += int(X[-i]) * pow(n, (i-1))
return num
def roundOff(x,d): #四捨五入する x:対象の数字, d:四捨五入する位(正|負) => float型の数値
return float(Decimal(x).quantize(Decimal(f"1E{d}"), rounding=ROUND_HALF_UP))
###幾何ライブラリ###
def dsin(d): #度数法でsinを計算する
return math.sin(math.radians(d))
def dcos(d): #度数法でcosを計算する
return math.cos(math.radians(d))
def rotate(x,y,d,cx=0,cy=0): #P(x,y)をA(cx,cy)を中心としてに反時計回りにd°回転 => [x,y]
nx = (x-cx)*dcos(d)-(y-cy)*dsin(d)
ny = (x-cx)*dsin(d)+(y-cy)*dcos(d)
return [nx+cx,ny+cy]
def findAngle(O,A,B): #∠AOBを求める(弧度法)
s = [A[0]-O[0],A[1]-O[1]]
t = [B[0]-O[0],B[1]-O[1]]
u = s[0]*t[0]+s[1]*t[1]
l = (s[0]**2+s[1]**2)**(1/2) * (t[0]**2+t[1]**2)**(1/2)
v = u/l
t = math.degrees(math.acos(v))
return t
def outerProduct(Av,Bv): #二次元ベクトルの外積(=符号付面積)を求める(a×b)
return Av[0]*Bv[1] - Bv[0]*Av[1]
def CCW(O,A,B): #Oを中心として、Aから見たAとBの位置関係を求める。
# -1: 時計回り, 0: 一直線上, 1: 反時計回り
s = [A[0]-O[0],A[1]-O[1]]
t = [B[0]-O[0],B[1]-O[1]]
op = outerProduct(s,t)
if(op > 0): return 1
if(op < 0): return -1
if(op == 0): return 0
def matrixMultiplication_2D(a,b,m): #行列の掛け算(a×b) m:mod
I,J,K,L = len(a),len(b[0]),len(b),len(a[0])
if(L!=K):
return -1
c = [[0] * J for _ in range(I)]
for i in range(I) :
for j in range(J) :
for k in range(K) :
c[i][j] += a[i][k] * b[k][j]
c[i][j] %= m
return c
def matrixExponentiation_2D(x,n,m): #行列の累乗 (x^n) m:mod
y = [[0] * len(x) for _ in range(len(x))]
for i in range(len(x)):
y[i][i] = 1
while n > 0:
if n & 1:
y = matrixMultiplication_2D(x,y,m)
x = matrixMultiplication_2D(x,x,m)
n >>= 1
return y
def twoCircles(A,B): #二つの円の半径の位置関係 | 引数はそれぞれ[x,y(=座標),r(=半径)]
# 1 : 一方の円が他方の円を完全に含み、2 つの円は接していない
# 2 : 一方の円が他方の円を完全に含み、2 つの円は接している
# 3 : 2 つの円が互いに交差する
# 4 : 2 つの円の内部に共通部分は存在しないが、2 つの円は接している
# 5 : 2 つの円の内部に共通部分は存在せず、2 つの円は接していない
x1 = A[0]
x2 = B[0]
y1 = A[1]
y2 = B[1]
r1 = A[2]
r2 = B[2]
d = abs((x1-x2)+1j*(y1-y2))
if(abs(r2-r1)>d):
return 1
elif(abs(r2-r1)==d):
return 2
elif(r1+r2>d):
return 3
elif(r1+r2==d):
return 4
elif(r1+r2<d):
return 5
###デバッグ用ライブラリ###
def TS(_str): #変数/リストに格納されている値を確認
print('{}: {}'.format(_str, eval(_str)))
def T2d(A): #二次元配列の確認用
for a in A:
print(*a)
def T3d(A): #三次元配列の確認用
for a in A:
T2d(a)
BR()
def BR(): #横線で区切りを入れる
print("---")
#クラス----------------------------------------------------------------------
#カンニングペーパー-----------------------------------------------------------
'''
###標準ライブラリ###
ceil(a,b): #切り捨て
inv(a,p): #xのpを法とする逆元
transpose(A): #二次元配列の転置
rotate_matrix(A): #グリッドを時計回りに90度回転
removeDuplicates_2D(A): #二次元配列の重複削除
convert(S, c): # グリッドをの 黒 マスの点集合に変換する | S: グリッド c:黒マスがなにか(ex #,1)
normalize(s): # グリッドの # マスの点集合を与えると最小の x 座標と最小の y 座標がともに 0 となるように平行移動して返す
例)normalize(convert(h,w,A))
cumulativeSum_1D(A) #配列Aの累積和
cumulativeSum_2D(S): #二次元配列Sの累積和 => 二次元リスト
string_to_runLength(S: str) #文字列/リストからラングレス圧縮 => [(文字,個数), ...]の二次元リスト
runLength_to_string(L: "list[tuple]") #ラングレス圧縮 => 文字列
bfs(i,G) # i:始点 => dist,pre
bfs01(i,G) # i:始点 => dist
dijkstra(s,G): #s:始点 => cost,pre | G:タプルの中身(コスト,行先)
coordinates(A) # 変換表(元の値 : 座標圧縮の値),変換表2(座標圧縮の値: 元の値), 圧縮後配列
eng_L() #英小文字のリスト
ENG_L() #英大文字のリスト
bit_len(n): #bit長
bit_cnt(n): # bitにしたときの1の数
idx_le(A, x) # x 以下の最大の要素位置 / なければ "No"
idx_lt(A, x) # x 未満の最大の要素位置 / なければ "No"
idx_ge(A, x) # x 以上の最小の要素位置 / なければ "No"
idx_gt(A, x) # x 超過の最小の要素位置 / なければ "No"
cnt_le(A, x) # x 以下の要素の個数
cnt_lt(A, x) # x 未満の要素の個数
cnt_ge(A, x) # x 以上の要素の個数
cnt_gt(A, x) # x 超過の要素の個数
###数学ライブラリ###
allAND(A): # 配列Aの総AND
allOR(A): # 配列Aの総OR
allXOR(A): # 配列Aの総XOR
allGCD(A): # 配列Aの総GCD
mex(A) #配列Aのmexを求める
gcd(a,b) #aとbの最大公約数を求める
lcm(a,b) #aとbの最小公倍数を求める
extgcd(a, b): # a,b =>ax+by=gcd(a,b)を満たす(g,x,y) a,bが互いに素のとき、xはaのbを法とする逆元
fact_L(n,mod): # [0!, 1! ..., n!] を返す
bitCount_L(n): # n以下のそれぞれのbitカウントを返す
factorial(n,m) #nの階乗 | m:mod(デフォなし)
nPr(n,r,m) #順列nPr | m:mod(デフォなし)
nCr(n,r,m) #組み合わせ,nCr | m:mod(デフォなし)
nCrm(n,r,m) #逆元を用いた組み合わせnCr%mod
divisor_L(n) #nの約数のリスト
is_prime(n) #素数判定 => True/False
prime_L(n) #nまでの素数のリスト
primeFactorization_2L(n) #2以上の整数n => [[素因数, 指数], ...]の2次元リスト
floorsqrt(n): # N => ⌊√N⌋
decimal_to_nAry(num_10,n) #10進数からn進数へ変換する(n<=36) |int型 => str型
nAry_to_decimal(num_n,n) #n進数から10進数へ変換する(n<=36) | str型 => int型
roundOff(x,d): #四捨五入する x:対象の数字, d:四捨五入する位(正|負) => float型の数値
###幾何ライブラリ###
dsin(d): #度数法でsinを計算する
dcos(d): #度数法でcosを計算する
rotate(x,y,d,cx,cy): #P(x,y)をA(cx,cy)を中心としてに反時計回りにd°回転(デフォ原点) => [x,y]
findAngle(O,A,B) #∠AOBを求める(弧度法) | 引数はそれぞれ[x,y(=座標)]
outerProduct(Av,Bv) #二次元ベクトルの外積(=符号付面積)を求める(a×b) | 引数はそれぞれ[x,y(=座標)]
CCW(O,A,B) #Oを中心として、Aから見たAとBの位置関係
=> -1:時計回り, 0:一直線上, 1:反時計回り | 引数はそれぞれ[x,y(=座標)]
matrixMultiplication_2D(a,b,m) #行列の掛け算(a×b) m:mod | 引数は二次元リスト
matrixExponentiation_2D(x,n m)#行列の累乗 (x^n) m:mod | 引数は二次元リスト
twoCircles(A,B): #二つの円の半径の位置関係 | 引数はそれぞれ[x,y(=座標),r(=半径)]
=> 1, 2, 3, 4, 5 各数字に対応する位置関係の説明は上記参照
###デバッグ用ライブラリ###
TS(_str) # 変数/リストに格納されている値を確認 => 〇〇:××
T2d(A): # 二次元配列の確認用
T3d(A): # 三次元配列の確認用
BR() # 横線で区切りを入れる
###文法チートシート###
|S|<x => "0"*(x-|S|) + S : str(n).zfill(x)
全部大文字に変換:str.upper()
全部小文字に変換:str.lower()
先頭のみ大文字に変換:str.capitalize()
各単語の先頭のみ大文字に変換(タイトルケース):str.title()
大文字と小文字を入れ替える:str.swapcase()
文字 → ASCIIコード ord(s)
ASCIIコード → 文字 chr(x)
ASCII表
65:A ~ 90:Z
97:a ~ 122:z
'''
#PyPyで再帰関数を用いる場合はコメントを外す----------------------------------
# import pypyjit
# pypyjit.set_param('max_unroll_recursion=-1')
#----------------------------------------------------------------------------
N,K = MI()
S = input()
ans = []
for i in range(len(S)-1):
if S[i] == "o" and ans.count("o") <= K-1:
ans.append("o")
else:
ans.append("x")
print("".join(ans))
| ConDefects/ConDefects/Code/abc290_b/Python/45736394 |
condefects-python_data_456 | n, k = map(int, input().split())
s = input()
ans_list = []
cnt = 0
for i in range(n):
if s[i] == 'o':
cnt += 1
if cnt >= k:
ans_list.append('x')
else:
ans_list.append('o')
else:
ans_list.append(s[i])
print(*ans_list, sep = '')
n, k = map(int, input().split())
s = input()
ans_list = []
cnt = 0
for i in range(n):
if s[i] == 'o':
cnt += 1
if cnt > k:
ans_list.append('x')
else:
ans_list.append('o')
else:
ans_list.append(s[i])
print(*ans_list, sep = '') | ConDefects/ConDefects/Code/abc290_b/Python/46158106 |
condefects-python_data_457 | # B
N, K = map(int, input().split())
S = input()
#N, K = 10, 3
#S = "oxxoxooxox"
#print(S)
cnt = 0
s = ""
for i in S:
#print(i)
if i == "o" and cnt < 3:
cnt += 1
s = s + i
elif i == "o":
s = s + "x"
if i == "x":
s = s + "x"
print(s)
# B
N, K = map(int, input().split())
S = input()
#N, K = 10, 3
#S = "oxxoxooxox"
#print(S)
cnt = 0
s = ""
for i in S:
#print(i)
if i == "o" and cnt < K:
cnt += 1
s = s + i
elif i == "o":
s = s + "x"
if i == "x":
s = s + "x"
print(s) | ConDefects/ConDefects/Code/abc290_b/Python/46211702 |
condefects-python_data_458 | import bisect
import collections
import functools
import heapq
import itertools
import math
import operator
import string
import sys
import typing
readline = sys.stdin.readline
LS = lambda: readline()
LI = lambda: int(readline())
LLS = lambda: readline().split()
LL = lambda: list(map(int, readline().split()))
a, b, c, d = LL()
def cntItvMod(l, r, div, mod):
if l > r:
return cntItvMod(r, l, div, mod)
l, r = l - mod, r - mod
rd = r // div * div
ld = ((l - 1) // div) * div
return (rd - ld) // div
xodd = cntItvMod(a, c - 1, 2, 1)
xeven = cntItvMod(a, c - 1, 2, 0)
yodd = cntItvMod(b, d - 1, 2, 1)
yeven = cntItvMod(b, d - 1, 2, 0)
half = xodd * yeven + xeven * yodd
m0 = cntItvMod(a, c - 1, 4, 0)
m1 = cntItvMod(a - 1, c - 2, 4, 1)
sq = (m0 * yeven + m1 * yodd) * 2
print(half + sq)
import bisect
import collections
import functools
import heapq
import itertools
import math
import operator
import string
import sys
import typing
readline = sys.stdin.readline
LS = lambda: readline()
LI = lambda: int(readline())
LLS = lambda: readline().split()
LL = lambda: list(map(int, readline().split()))
a, b, c, d = LL()
def cntItvMod(l, r, div, mod):
if l > r:
return cntItvMod(r, l, div, mod)
l, r = l - mod, r - mod
rd = r // div * div
ld = ((l - 1) // div) * div
return (rd - ld) // div
xodd = cntItvMod(a, c - 1, 2, 1)
xeven = cntItvMod(a, c - 1, 2, 0)
yodd = cntItvMod(b, d - 1, 2, 1)
yeven = cntItvMod(b, d - 1, 2, 0)
half = xodd * yeven + xeven * yodd
m0 = cntItvMod(a, c - 1, 4, 0)
m1 = cntItvMod(a, c - 1, 4, 1)
sq = (m0 * yeven + m1 * yodd) * 2
print(half + sq)
| ConDefects/ConDefects/Code/abc354_d/Python/54708447 |
condefects-python_data_459 | A, B, C, D = map(int, input().split())
p = [1, 2, 1, 0, 1, 2, 1, 0]
P = p[A%4+(B+1)%2:A%4+(B+1)%2+4]
S = ((C - A) // 4) * 4 + sum(P[:(C-A)%4])
Q = p[A%4+B%2:A%4+B%2+4]
T = ((C - A) // 4) * 4 + sum(Q[:(C-A)%4])
ans = (S+T) * ((D-B) // 2) + ((D - B) % 2) * ((D%2)*S + ((D+1)%2)*T)
print(ans)
A, B, C, D = map(int, input().split())
p = [1, 2, 1, 0, 1, 2, 1, 0]
P = p[A%4+(B+1)%2:A%4+(B+1)%2+4]
S = ((C - A) // 4) * 4 + sum(P[:(C-A)%4])
Q = p[A%4+B%2:A%4+B%2+4]
T = ((C - A) // 4) * 4 + sum(Q[:(C-A)%4])
ans = (S+T) * ((D-B) // 2) + ((D - B) % 2) * S
print(ans)
| ConDefects/ConDefects/Code/abc354_d/Python/55158845 |
condefects-python_data_460 | import sys
import time
import math
import bisect
import heapq
import itertools
from collections import defaultdict
from collections import deque
cur_time = time.perf_counter()
sys.setrecursionlimit( 10 ** 8 )
INF = sys.maxsize
NUL = -1
MOD = 998244353
dy=[0,1,0,-1]
dx=[1,0,-1,0]
def searchL( ls, x ):return bisect.bisect_left( ls, x )
def searchR( ls, x ):return bisect.bisect_right( ls, x )
def factorial( i ): return math.factorial( i )
permIte = itertools.permutations
combIte = itertools.combinations
def arr1( size0, init=0 ):return [init]*size0
def arr2( size0, size1, init=0 ):return [[init]*size1 for _ in range(size0)] if 0<=size1 else [[] for _ in range(size0)]
def arr3( size0, size1, size2, init=0 ):return [[[init]*size2 for _ in range(size1)] for _ in range(size0)] if 0<=size2 else [[[] for _ in range(size1)] for _ in range(size0)]
def arr4( size0, size1, size2, size3, init=0 ):return [[[init]*size2 for _ in range(size1)] for _ in range(size0)] if 0<=size2 else [[[] for _ in range(size1)] for _ in range(size0)]
def ini1( a, init ):
for i in range(len(a)):a[i]=init
def ini2( a, init ):
for i in range(len(a)):ini1(a[i],init)
def ini3( a, init ):
for i in range(len(a)):ini2(a[i],init)
def cp2( arr2 ):return [i[:] for i in arr2]
def cp3( arr3 ):return [cp2(i) for i in arr3]
def joinInt( a ): return ' '.join( [ str(i) for i in a ] )
def readStr():return input()
def readStrX():return [ i for i in input().split() ]
def readStrY(n):return [ input() for i in range( n ) ]
def readStrXY(n):return [ [ i for i in input().split() ] for _ in range( n ) ]
def readChr():return list(input())
def readChrY(n):return [ list(input()) for i in range( n ) ]
def readInt():return int(input())
def readIntX():return [ int(i) for i in input().split() ]
def readIntY(n):return [ int(input()) for i in range( n ) ]
def readIntXY(n):return [ [ int(i) for i in input().split() ] for _ in range( n ) ]
UA=1,2,1,0,4
DA=2,1,0,1,4
US=[1,2,1,0]
DS=[2,1,0,1]
A,B,C,D=readIntX()
hq=(D-B)//2
wq=(C-A)//4
h0,h1=B%2,D%2
if h0==1 and h1==1:
h0,h1=0,0
w0,w1=A%4,C%4
SU=4*wq
SD=4*wq
if w0!=0:
for i in range(w0,4):
SU+=US[i]
SD+=DS[i]
if w1!=0:
for i in range(0,w1):
SU+=US[i]
SD+=DS[i]
ans=hq*(SU+SD)
if h0==1:
ans+=SU
if h1==1:
ans+=SD
print(ans)
import sys
import time
import math
import bisect
import heapq
import itertools
from collections import defaultdict
from collections import deque
cur_time = time.perf_counter()
sys.setrecursionlimit( 10 ** 8 )
INF = sys.maxsize
NUL = -1
MOD = 998244353
dy=[0,1,0,-1]
dx=[1,0,-1,0]
def searchL( ls, x ):return bisect.bisect_left( ls, x )
def searchR( ls, x ):return bisect.bisect_right( ls, x )
def factorial( i ): return math.factorial( i )
permIte = itertools.permutations
combIte = itertools.combinations
def arr1( size0, init=0 ):return [init]*size0
def arr2( size0, size1, init=0 ):return [[init]*size1 for _ in range(size0)] if 0<=size1 else [[] for _ in range(size0)]
def arr3( size0, size1, size2, init=0 ):return [[[init]*size2 for _ in range(size1)] for _ in range(size0)] if 0<=size2 else [[[] for _ in range(size1)] for _ in range(size0)]
def arr4( size0, size1, size2, size3, init=0 ):return [[[init]*size2 for _ in range(size1)] for _ in range(size0)] if 0<=size2 else [[[] for _ in range(size1)] for _ in range(size0)]
def ini1( a, init ):
for i in range(len(a)):a[i]=init
def ini2( a, init ):
for i in range(len(a)):ini1(a[i],init)
def ini3( a, init ):
for i in range(len(a)):ini2(a[i],init)
def cp2( arr2 ):return [i[:] for i in arr2]
def cp3( arr3 ):return [cp2(i) for i in arr3]
def joinInt( a ): return ' '.join( [ str(i) for i in a ] )
def readStr():return input()
def readStrX():return [ i for i in input().split() ]
def readStrY(n):return [ input() for i in range( n ) ]
def readStrXY(n):return [ [ i for i in input().split() ] for _ in range( n ) ]
def readChr():return list(input())
def readChrY(n):return [ list(input()) for i in range( n ) ]
def readInt():return int(input())
def readIntX():return [ int(i) for i in input().split() ]
def readIntY(n):return [ int(input()) for i in range( n ) ]
def readIntXY(n):return [ [ int(i) for i in input().split() ] for _ in range( n ) ]
UA=1,2,1,0,4
DA=2,1,0,1,4
US=[1,2,1,0]
DS=[2,1,0,1]
A,B,C,D=readIntX()
hq=(D-B)//2
wq=C//4-(A+3)//4
h0,h1=B%2,D%2
if h0==1 and h1==1:
h0,h1=0,0
w0,w1=A%4,C%4
SU=4*wq
SD=4*wq
if w0!=0:
for i in range(w0,4):
SU+=US[i]
SD+=DS[i]
if w1!=0:
for i in range(0,w1):
SU+=US[i]
SD+=DS[i]
ans=hq*(SU+SD)
if h0==1:
ans+=SU
if h1==1:
ans+=SD
print(ans)
| ConDefects/ConDefects/Code/abc354_d/Python/54915651 |
condefects-python_data_461 | S=input()
for s in S:
if s=='R':
print('Yes')
elif s=='M':
print('No')
S=input()
for s in S:
if s=='R':
print('Yes')
break
elif s=='M':
print('No')
break | ConDefects/ConDefects/Code/abc360_a/Python/55163956 |
condefects-python_data_462 | S = input()
if S == 'RSM' or 'RMS' or 'SRM':
print('Yes')
else:
print('No')
S = input()
if S == 'RSM' or S == 'RMS' or S == 'SRM':
print('Yes')
else:
print('No') | ConDefects/ConDefects/Code/abc360_a/Python/55164870 |
condefects-python_data_463 | def resolve():
S = str(input())
if (S[2] == "M") or (S[:1] == "RM"):
print ("Yes")
else:
print("No")
resolve()
def resolve():
S = str(input())
if S.index("R") < S.index("M"):
print ("Yes")
else:
print("No")
resolve() | ConDefects/ConDefects/Code/abc360_a/Python/55156972 |
condefects-python_data_464 | s = input()
d = {}
n = 1
for i in s:
d[i] = n
n += 1
if d['R'] > d['M']:
print('NO')
else:
print('Yes')
s = input()
d = {}
n = 1
for i in s:
d[i] = n
n += 1
if d['R'] > d['M']:
print('No')
else:
print('Yes') | ConDefects/ConDefects/Code/abc360_a/Python/55149517 |
condefects-python_data_465 | S = input()
for i in range(len(S)):
if S[i] == 'R':
R_index = i
elif S[i] == 'S':
S_index = i
if R_index < S_index:
print("Yes")
else:
print("No")
S = input()
for i in range(len(S)):
if S[i] == 'R':
R_index = i
elif S[i] == 'M':
S_index = i
if R_index < S_index:
print("Yes")
else:
print("No") | ConDefects/ConDefects/Code/abc360_a/Python/55149797 |
condefects-python_data_466 | import io
import sys
import bisect
import math
from itertools import permutations, combinations
from heapq import heappush, heappop
from collections import deque
from collections import defaultdict as dd
sys.setrecursionlimit(10**7+10)
mod = 998244353
_INPUT = """\
31415926535897932384626433832795
"""
def main():
S = input()
n = len(S)
dp1 = [0]*(n+1)
# dp2 = [0]*(n+1)
dp1[n] = 1
dp1[n-1] = 1
for i in range(n-2, 0, -1):
dp1[i] = pow(2, n-1-i, mod)
temp = 0
for i in range(1, n+1):
temp += dp1[i]*pow(10, i-1, mod)
temp %= mod
ans = 0
for i in range(n, 0, -1):
x = int(S[n-i])
ans += x * temp
temp -= dp1[i]*pow(10, i-1, mod)
if i>1:
temp += dp1[i]*pow(10, i-2, mod)
dp1[i-1] += dp1[i]
temp %= mod
ans %= mod
print(ans)
if __name__ == "__main__":
sys.stdin = io.StringIO(_INPUT)
main()
import io
import sys
import bisect
import math
from itertools import permutations, combinations
from heapq import heappush, heappop
from collections import deque
from collections import defaultdict as dd
sys.setrecursionlimit(10**7+10)
mod = 998244353
_INPUT = """\
31415926535897932384626433832795
"""
def main():
S = input()
n = len(S)
dp1 = [0]*(n+1)
# dp2 = [0]*(n+1)
dp1[n] = 1
dp1[n-1] = 1
for i in range(n-2, 0, -1):
dp1[i] = pow(2, n-1-i, mod)
temp = 0
for i in range(1, n+1):
temp += dp1[i]*pow(10, i-1, mod)
temp %= mod
ans = 0
for i in range(n, 0, -1):
x = int(S[n-i])
ans += x * temp
temp -= dp1[i]*pow(10, i-1, mod)
if i>1:
temp += dp1[i]*pow(10, i-2, mod)
dp1[i-1] += dp1[i]
temp %= mod
ans %= mod
print(ans)
if __name__ == "__main__":
# sys.stdin = io.StringIO(_INPUT)
main()
| ConDefects/ConDefects/Code/abc224_f/Python/51168884 |
condefects-python_data_467 | n,m=map(int,input().split())
s=[input() for i in range(n)]
a=0
for i in range(1,(1<<n)-1):
c=[0]*26
for j in range(n):
if (i>>j)&1:
for k in range(26):
c[k]+=chr(k+ord("a")) in s[j]
a=max(a,c.count(m))
print(a)
n,m=map(int,input().split())
s=[input() for i in range(n)]
a=0
for i in range(1,1<<n):
c=[0]*26
for j in range(n):
if (i>>j)&1:
for k in range(26):
c[k]+=chr(k+ord("a")) in s[j]
a=max(a,c.count(m))
print(a) | ConDefects/ConDefects/Code/abc249_c/Python/45110623 |
condefects-python_data_468 | from collections import defaultdict
from itertools import product
N,K=map(int,input().split())
S=[list(input()) for _ in range(N)]
ans=0
for pro in product((1,0),repeat=N):
d=defaultdict(int)
for i in range(N):
if pro[i]==1:
for j in range(len(S[i])):
d[S[i][j]]+=1
check=0
for key,value in d.items():
if value>=K:
check+=1
ans=max(ans,check)
print(ans)
from collections import defaultdict
from itertools import product
N,K=map(int,input().split())
S=[list(input()) for _ in range(N)]
ans=0
for pro in product((1,0),repeat=N):
d=defaultdict(int)
for i in range(N):
if pro[i]==1:
for j in range(len(S[i])):
d[S[i][j]]+=1
check=0
for key,value in d.items():
if value==K:
check+=1
ans=max(ans,check)
print(ans) | ConDefects/ConDefects/Code/abc249_c/Python/44911089 |
condefects-python_data_469 | l,r = map(int, input().split())
s = input()
print(s[:l] + s[l:r+1][::-1] + s[r+1:])
l,r = map(int, input().split())
s = input()
print(s[:l-1] + s[l-1:r][::-1] + s[r:]) | ConDefects/ConDefects/Code/abc233_b/Python/46206186 |
condefects-python_data_470 | import math
from decimal import Decimal
a, b = map(int, input().split())
def f(x):
return Decimal((a / math.sqrt(1 + x)) + (b * x))
# 3分探索する
l = 0
r = 10**40
while r - l > 1:
m1 = (2 * l + r) // 3
m2 = (l + 2 * r) // 3
# print(m1, m2, l, r, f(m1), f(m2))
if f(m1) < f(m2):
r = m2
else:
if l == m1:
l += 1
else:
l = m1
print(l, r)
print(f(l), f(r))
print(min(f(l), f(r)))
import math
from decimal import Decimal
a, b = map(int, input().split())
def f(x):
return Decimal((a / math.sqrt(1 + x)) + (b * x))
# 3分探索する
l = 0
r = 10**40
while r - l > 1:
m1 = (2 * l + r) // 3
m2 = (l + 2 * r) // 3
# print(m1, m2, l, r, f(m1), f(m2))
if f(m1) < f(m2):
r = m2
else:
if l == m1:
l += 1
else:
l = m1
print(min(f(l), f(r))) | ConDefects/ConDefects/Code/abc279_d/Python/44854241 |
condefects-python_data_471 | N = int(input())
a = [list(map(int, input().split())) for _ in range(N)]
a.sort(key=lambda x: abs(x[0]-x[1]))
cnt = 0
for i in range(N):
if a[i][0] > a[i][1]:
cnt += 1
ans = max(a[0]) if cnt & 2 == 0 else min(a[0])
for i in range(1, N):
ans += max(a[i])
print(ans)
N = int(input())
a = [list(map(int, input().split())) for _ in range(N)]
a.sort(key=lambda x: abs(x[0]-x[1]))
cnt = 0
for i in range(N):
if a[i][0] > a[i][1]:
cnt += 1
ans = max(a[0]) if cnt % 2 == 0 else min(a[0])
for i in range(1, N):
ans += max(a[i])
print(ans)
| ConDefects/ConDefects/Code/arc164_c/Python/45053848 |
condefects-python_data_472 | import sys, time, random
from collections import deque, Counter, defaultdict
input = lambda: sys.stdin.readline().rstrip()
ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(mi())
inf = 2 ** 61 - 1
mod = 998244353
def solve():
s = input()
n = len(s)
dp = [inf] * (n + 1)
bdic = defaultdict(lambda: inf)
dic = defaultdict(lambda: inf)
dp[0] = 0
dic[0] = 0
cnt = 0
if s[0] == 'B':
bdic[0] = 0
for i in range(n):
dp[i + 1] = min(dp[i + 1], dp[i] + 1)
if s[i] == 'A':
cnt += 1
else:
cnt -= 2
if s[i] == 'B':
dp[i + 1] = min(dp[i + 1], dic[cnt])
dp[i + 1] = min(dp[i + 1], bdic[cnt])
dic[cnt] = min(dic[cnt], dp[i + 1])
if s[i] == 'B':
bdic[cnt] = min(bdic[cnt], dp[i + 1])
print((n - dp[n]) // 3)
for _ in range(ii()):
solve()
import sys, time, random
from collections import deque, Counter, defaultdict
input = lambda: sys.stdin.readline().rstrip()
ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(mi())
inf = 2 ** 61 - 1
mod = 998244353
def solve():
s = input()
n = len(s)
dp = [inf] * (n + 1)
bdic = defaultdict(lambda: inf)
dic = defaultdict(lambda: inf)
dp[0] = 0
dic[0] = 0
cnt = 0
if s[0] == 'B':
bdic[0] = 0
for i in range(n):
dp[i + 1] = min(dp[i + 1], dp[i] + 1)
if s[i] == 'A':
cnt += 1
else:
cnt -= 2
if s[i] == 'B':
dp[i + 1] = min(dp[i + 1], dic[cnt])
dp[i + 1] = min(dp[i + 1], bdic[cnt])
dic[cnt] = min(dic[cnt], dp[i + 1])
if i + 1 < n and s[i + 1] == 'B':
bdic[cnt] = min(bdic[cnt], dp[i + 1])
print((n - dp[n]) // 3)
for _ in range(ii()):
solve() | ConDefects/ConDefects/Code/agc066_c/Python/52162543 |
condefects-python_data_473 | m,n=map(int,input().split())
x=list(map(int,input().split()))
xi=[0for i in range(m)]
for i in range(m):
xi[x[i]-1]|=(1<<i)
mod=998244353
s=pow(2,m)
t=[[0for i in range(s)]for j in range(n+1)]
pr=[[-1 for i in range(m)]for j in range(s)]
for i in range(s):
for j in range(m):
if i&(1<<j)==0 or(s&(1<<j)!=0 and x[j]==j+1):
c=(i|xi[j])-xi[j]
c=c|(1<<j)
pr[i][j]=c
t[0][0]=1
for i in range(n):
for j in range(s):
if t[i][j]!=0:
for k in range(m):
if pr[j][k]!=-1:
t[i+1][pr[j][k]]=(t[i+1][pr[j][k]]+t[i][j])%mod
print(sum(t[-1])%mod)
m,n=map(int,input().split())
x=list(map(int,input().split()))
xi=[0for i in range(m)]
for i in range(m):
xi[x[i]-1]|=(1<<i)
mod=998244353
s=pow(2,m)
t=[[0for i in range(s)]for j in range(n+1)]
pr=[[-1 for i in range(m)]for j in range(s)]
for i in range(s):
for j in range(m):
if i&(1<<j)==0 or(i&(1<<j)!=0 and x[j]==j+1):
c=(i|xi[j])-xi[j]
c=c|(1<<j)
pr[i][j]=c
t[0][0]=1
for i in range(n):
for j in range(s):
if t[i][j]!=0:
for k in range(m):
if pr[j][k]!=-1:
t[i+1][pr[j][k]]=(t[i+1][pr[j][k]]+t[i][j])%mod
print(sum(t[-1])%mod) | ConDefects/ConDefects/Code/arc179_b/Python/54728093 |
condefects-python_data_474 | # import sys
# sys.setrecursionlimit(10**6)
# sys.set_int_max_str_digits(10**6)
# from scipy.optimize import bisect
# from collections import defaultdict, Counter
# import bisect
# import heapq
mod = 998244353
# ds = [(-1,0),(0,1),(1,0),(0,-1)]
# S = input()
# N = int(input())
M, N = map(int, input().split())
X = list(map(int, input().split()))
dp = [[0 for _ in range(1 << M)] for _ in range(N+1)]
# for j in range(M):
dp[0][(1 << M)-1] = 1
table = [0 for i in range(M)]
for a in range(M):
for b in range(M):
x = X[b]-1
if x == a:
table[a] |= 1 << b
for i in range(N):
for mask in range(1 << M):
for a in range(M):
if mask >> a & 1:
nmask = mask & ~(1 << a)
nmask |= table[a]
dp[i+1][nmask] = (dp[i+1][nmask] + dp[i][mask]) % mod
# print(dp)
ans = sum(dp[-1])
print(ans)
# import sys
# sys.setrecursionlimit(10**6)
# sys.set_int_max_str_digits(10**6)
# from scipy.optimize import bisect
# from collections import defaultdict, Counter
# import bisect
# import heapq
mod = 998244353
# ds = [(-1,0),(0,1),(1,0),(0,-1)]
# S = input()
# N = int(input())
M, N = map(int, input().split())
X = list(map(int, input().split()))
dp = [[0 for _ in range(1 << M)] for _ in range(N+1)]
# for j in range(M):
dp[0][(1 << M)-1] = 1
table = [0 for i in range(M)]
for a in range(M):
for b in range(M):
x = X[b]-1
if x == a:
table[a] |= 1 << b
for i in range(N):
for mask in range(1 << M):
for a in range(M):
if mask >> a & 1:
nmask = mask & ~(1 << a)
nmask |= table[a]
dp[i+1][nmask] = (dp[i+1][nmask] + dp[i][mask]) % mod
# print(dp)
ans = sum(dp[-1]) % mod
print(ans) | ConDefects/ConDefects/Code/arc179_b/Python/54190165 |
condefects-python_data_475 | MOD = 998244353
M,N=map(int,input().split())
X=list(map(int,input().split()))
canadd=[[] for _ in range(M)]
for i in range(M):
canadd[X[i]-1].append(i)
dp=[[0]*2**M for _ in range(N+1)]
dp[0][2**M-1]=1
for i in range(N):
for j in range(2**M):
for k in range(M):
if j&(1<<k):
next=j
next^=(1<<k)
for c in canadd[k]:
next|=(1<<c)
dp[i+1][next]+=dp[i][j]
dp[i+1][next]%=MOD
print(sum(dp[-1]))
MOD = 998244353
M,N=map(int,input().split())
X=list(map(int,input().split()))
canadd=[[] for _ in range(M)]
for i in range(M):
canadd[X[i]-1].append(i)
dp=[[0]*2**M for _ in range(N+1)]
dp[0][2**M-1]=1
for i in range(N):
for j in range(2**M):
for k in range(M):
if j&(1<<k):
next=j
next^=(1<<k)
for c in canadd[k]:
next|=(1<<c)
dp[i+1][next]+=dp[i][j]
dp[i+1][next]%=MOD
print(sum(dp[-1])%MOD) | ConDefects/ConDefects/Code/arc179_b/Python/54198315 |
condefects-python_data_476 | import sys
import numba
import numpy as np
def main() -> None:
readline = sys.stdin.readline
M, N = map(int, readline().split())
xs = np.array(list(n - 1 for n in map(int, readline().split())))
print(numba_main(M, N, xs))
@numba.jit(nopython=True, cache=True)
def numba_main(M: int, N: int, xs: np.ndarray) -> np.int64:
inverse_xs = [0 for m in range(M)]
for i, x in enumerate(xs):
inverse_xs[x] |= 1 << i
transition = [
[
allowed ^ (1 << num) | inverse_xs[num]
for num in range(M)
if (allowed >> num) & 1
]
for allowed in range(2**M)
]
memo = np.zeros((N + 1, 2**M), dtype=np.int64)
memo[0, 2**M - 1] = 1
for prev_length in range(N):
for allowed_curr in range(1, 2**M):
for allowed_next in transition[allowed_curr]:
memo[prev_length + 1, allowed_next] += memo[prev_length, allowed_curr]
memo[prev_length + 1, allowed_next] %= 998244353
return np.sum(memo[N] % 998244353) # type: ignore
if __name__ == "__main__":
main()
import sys
import numba
import numpy as np
def main() -> None:
readline = sys.stdin.readline
M, N = map(int, readline().split())
xs = np.array(list(n - 1 for n in map(int, readline().split())))
print(numba_main(M, N, xs))
@numba.jit(nopython=True, cache=True)
def numba_main(M: int, N: int, xs: np.ndarray) -> np.int64:
inverse_xs = [0 for m in range(M)]
for i, x in enumerate(xs):
inverse_xs[x] |= 1 << i
transition = [
[
allowed ^ (1 << num) | inverse_xs[num]
for num in range(M)
if (allowed >> num) & 1
]
for allowed in range(2**M)
]
memo = np.zeros((N + 1, 2**M), dtype=np.int64)
memo[0, 2**M - 1] = 1
for prev_length in range(N):
for allowed_curr in range(1, 2**M):
for allowed_next in transition[allowed_curr]:
memo[prev_length + 1, allowed_next] += memo[prev_length, allowed_curr]
memo[prev_length + 1, allowed_next] %= 998244353
return np.sum(memo[N]) % 998244353 # type: ignore
if __name__ == "__main__":
main()
| ConDefects/ConDefects/Code/arc179_b/Python/54187921 |
condefects-python_data_477 | MOD = 998244353
n = int(input())
RT_N = int(n ** 0.5) + 1
a = list(map(int, input().split()))
dp_black, dp_white = [0] * n, [0] * n
dp_black[0] = 1
lump = [[0] * n for _ in range(RT_N)]
for i in range(n - 1):
if a[i] < RT_N:
lump[a[i]][i] = (lump[a[i]][i] + dp_black[i]) % MOD
else:
for j in range(i + a[i], a[i], n):
dp_black[j] = (dp_black[j] + dp_black[i]) % MOD
dp_white[i+1] = (dp_black[i] + dp_white[i]) % MOD
for step in range(1, min(RT_N, n - i)):
dp_black[i+step] = (dp_black[i+step] + lump[step][i]) % MOD
lump[step][i+step] = lump[step][i]
print((dp_black[-1] + dp_white[-1]) % MOD)
MOD = 998244353
n = int(input())
RT_N = int(n ** 0.5) + 1
a = list(map(int, input().split()))
dp_black, dp_white = [0] * n, [0] * n
dp_black[0] = 1
lump = [[0] * n for _ in range(RT_N)]
for i in range(n - 1):
if a[i] < RT_N:
lump[a[i]][i] = (lump[a[i]][i] + dp_black[i]) % MOD
else:
for j in range(i + a[i], n, a[i]):
dp_black[j] = (dp_black[j] + dp_black[i]) % MOD
dp_white[i+1] = (dp_black[i] + dp_white[i]) % MOD
for step in range(1, min(RT_N, n - i)):
dp_black[i+step] = (dp_black[i+step] + lump[step][i]) % MOD
lump[step][i+step] = lump[step][i]
print((dp_black[-1] + dp_white[-1]) % MOD) | ConDefects/ConDefects/Code/abc335_f/Python/53563069 |
condefects-python_data_478 | n=int(input())
a=list(map(int,input().split()))
mod=998244353
b=500
dp1=[[0]*(b) for _ in range(n)]
dp2=[0]*n
dp2[0]=1
if a[0]<b:
if a[0]<n:
dp1[a[0]][a[0]]=1
else:
for i in range(1,n//a[0]):
dp2[i*a[0]]=1
for i in range(1,n):
dp2[i]+=sum(dp1[i])
dp2[i]%=mod
for j in range(b):
if i+j<n:
dp1[i+j][j]+=dp1[i][j]
dp1[i+j][j]%=mod
if i+a[i]>=n:
continue
if a[i]<b:
dp1[i+a[i]][a[i]]+=dp2[i]
dp1[i+a[i]][a[i]]%=mod
else:
for j in range(1,(n-i-1)//a[i]+1):
dp2[i+j*a[i]]+=dp2[i]
dp2[i+j*a[i]]%=mod
print(sum(dp2)%mod)
n=int(input())
a=list(map(int,input().split()))
mod=998244353
b=500
dp1=[[0]*(b) for _ in range(n)]
dp2=[0]*n
dp2[0]=1
if a[0]<b:
if a[0]<n:
dp1[a[0]][a[0]]=1
else:
for i in range(1,(n-1)//a[0]+1):
dp2[i*a[0]]=1
for i in range(1,n):
dp2[i]+=sum(dp1[i])
dp2[i]%=mod
for j in range(b):
if i+j<n:
dp1[i+j][j]+=dp1[i][j]
dp1[i+j][j]%=mod
if i+a[i]>=n:
continue
if a[i]<b:
dp1[i+a[i]][a[i]]+=dp2[i]
dp1[i+a[i]][a[i]]%=mod
else:
for j in range(1,(n-i-1)//a[i]+1):
dp2[i+j*a[i]]+=dp2[i]
dp2[i+j*a[i]]%=mod
print(sum(dp2)%mod) | ConDefects/ConDefects/Code/abc335_f/Python/54448133 |
condefects-python_data_479 | a,b,c,d=map(int,input().split())
print("Takahashi" if a*24+b<=c*24+d else "Aoki")
a,b,c,d=map(int,input().split())
print("Takahashi" if a*60+b<=c*60+d else "Aoki") | ConDefects/ConDefects/Code/abc245_a/Python/45264085 |
condefects-python_data_480 | a,b,c,d=map(int,input().split())
if a<c:
print("Takahashi")
if a==c:
if b<=d:
print("Takahashi")
else:
print("Aoki")
else:
print("Aoki")
a,b,c,d=map(int,input().split())
if a<c:
print("Takahashi")
elif a==c:
if b<=d:
print("Takahashi")
else:
print("Aoki")
else:
print("Aoki") | ConDefects/ConDefects/Code/abc245_a/Python/45115746 |
condefects-python_data_481 | #list型で取得
l = list(map(int, input().split()))
m=0
for i in l:
m += i
print(m)
N = int(input())
l = list(map(int, input().split()))
m=0
for i in l:
m += i
print(m) | ConDefects/ConDefects/Code/abc272_a/Python/54282225 |
condefects-python_data_482 | def enum_sum(a: list[int]) -> dict[int, int]:
n = len(a)
s = [0] * (1 << n)
for i in range(n):
for u in range(1 << i):
s[u | 1 << i] = s[u] + a[i]
return {s[u]: u for u in range(1 << n)}
def solve(a: list[int], X: int) -> list[int] | None:
sa = sum(a)
sr = sa + X
if sr & 1:
return None
sr >> 1
n = len(a)
m = n >> 1
b1 = enum_sum(a[:m])
b2 = enum_sum(a[m:])
for s1, u1 in b1.items():
s2 = sr - s1
u2 = b2.get(s2)
if u2 is None:
continue
res = []
for i in range(m):
res.append(u1 >> i & 1)
for i in range(n - m):
res.append(u2 >> i & 1)
return res
return None
def main():
N, X, Y = map(int, input().split())
A = list(map(int, input().split()))
res_y = solve(A[::2], Y)
res_x = solve(A[1::2], X)
if res_y is None or res_x is None:
print("No")
return
print("Yes")
A[::2] = res_y
A[1::2] = res_x
A = [1] + A
res = []
f = 0
for i in range(N):
f ^= 1
res.append("L" if A[i] ^ A[i + 1] ^ f else "R")
print("".join(res))
main()
def enum_sum(a: list[int]) -> dict[int, int]:
n = len(a)
s = [0] * (1 << n)
for i in range(n):
for u in range(1 << i):
s[u | 1 << i] = s[u] + a[i]
return {s[u]: u for u in range(1 << n)}
def solve(a: list[int], X: int) -> list[int] | None:
sa = sum(a)
sr = sa + X
if sr & 1:
return None
sr >>= 1
n = len(a)
m = n >> 1
b1 = enum_sum(a[:m])
b2 = enum_sum(a[m:])
for s1, u1 in b1.items():
s2 = sr - s1
u2 = b2.get(s2)
if u2 is None:
continue
res = []
for i in range(m):
res.append(u1 >> i & 1)
for i in range(n - m):
res.append(u2 >> i & 1)
return res
return None
def main():
N, X, Y = map(int, input().split())
A = list(map(int, input().split()))
res_y = solve(A[::2], Y)
res_x = solve(A[1::2], X)
if res_y is None or res_x is None:
print("No")
return
print("Yes")
A[::2] = res_y
A[1::2] = res_x
A = [1] + A
res = []
f = 0
for i in range(N):
f ^= 1
res.append("L" if A[i] ^ A[i + 1] ^ f else "R")
print("".join(res))
main()
| ConDefects/ConDefects/Code/abc326_f/Python/54719711 |
condefects-python_data_483 | import sys
readline=sys.stdin.readline
def Tonelli_Shanks(N,p):
if pow(N,p>>1,p)==p-1:
retu=None
elif p%4==3:
retu=pow(N,(p+1)//4,p)
else:
for nonresidue in range(1,p):
if pow(nonresidue,p>>1,p)==p-1:
break
pp=p-1
cnt=0
while pp%2==0:
pp//=2
cnt+=1
s=pow(N,pp,p)
retu=pow(N,(pp+1)//2,p)
for i in range(cnt-2,-1,-1):
if pow(s,1<<i,p)==p-1:
s*=pow(nonresidue,p>>1+i,p)
s%=p
retu*=pow(nonresidue,p>>2+i,p)
retu%=p
return retu
def Extended_Euclid(n,m):
stack=[]
while m:
stack.append((n,m))
n,m=m,n%m
if n>=0:
x,y=1,0
else:
x,y=-1,0
for i in range(len(stack)-1,-1,-1):
n,m=stack[i]
x,y=y,x-(n//m)*y
return x,y
class MOD:
def __init__(self,p,e=None):
self.p=p
self.e=e
if self.e==None:
self.mod=self.p
else:
self.mod=self.p**self.e
def Pow(self,a,n):
a%=self.mod
if n>=0:
return pow(a,n,self.mod)
else:
#assert math.gcd(a,self.mod)==1
x=Extended_Euclid(a,self.mod)[0]
return pow(x,-n,self.mod)
def Build_Fact(self,N):
assert N>=0
self.factorial=[1]
if self.e==None:
for i in range(1,N+1):
self.factorial.append(self.factorial[-1]*i%self.mod)
else:
self.cnt=[0]*(N+1)
for i in range(1,N+1):
self.cnt[i]=self.cnt[i-1]
ii=i
while ii%self.p==0:
ii//=self.p
self.cnt[i]+=1
self.factorial.append(self.factorial[-1]*ii%self.mod)
self.factorial_inve=[None]*(N+1)
self.factorial_inve[-1]=self.Pow(self.factorial[-1],-1)
for i in range(N-1,-1,-1):
ii=i+1
while ii%self.p==0:
ii//=self.p
self.factorial_inve[i]=(self.factorial_inve[i+1]*ii)%self.mod
def Build_Inverse(self,N):
self.inverse=[None]*(N+1)
assert self.p>N
self.inverse[1]=1
for n in range(2,N+1):
if n%self.p==0:
continue
a,b=divmod(self.mod,n)
self.inverse[n]=(-a*self.inverse[b])%self.mod
def Inverse(self,n):
return self.inverse[n]
def Fact(self,N):
if N<0:
return 0
retu=self.factorial[N]
if self.e!=None and self.cnt[N]:
retu*=pow(self.p,self.cnt[N],self.mod)%self.mod
retu%=self.mod
return retu
def Fact_Inve(self,N):
if self.e!=None and self.cnt[N]:
return None
return self.factorial_inve[N]
def Comb(self,N,K,divisible_count=False):
if K<0 or K>N:
return 0
retu=self.factorial[N]*self.factorial_inve[K]%self.mod*self.factorial_inve[N-K]%self.mod
if self.e!=None:
cnt=self.cnt[N]-self.cnt[N-K]-self.cnt[K]
if divisible_count:
return retu,cnt
else:
retu*=pow(self.p,cnt,self.mod)
retu%=self.mod
return retu
class Polynomial:
def __init__(self,polynomial,max_degree=-1,eps=0,mod=0):
self.max_degree=max_degree
if self.max_degree!=-1 and len(polynomial)>self.max_degree+1:
self.polynomial=polynomial[:self.max_degree+1]
else:
self.polynomial=polynomial
self.mod=mod
self.eps=eps
def __eq__(self,other):
if type(other)!=Polynomial:
return False
if len(self.polynomial)!=len(other.polynomial):
return False
for i in range(len(self.polynomial)):
if self.eps<abs(self.polynomial[i]-other.polynomial[i]):
return False
return True
def __ne__(self,other):
if type(other)!=Polynomial:
return True
if len(self.polynomial)!=len(other.polynomial):
return True
for i in range(len(self.polynomial)):
if self.eps<abs(self.polynomial[i]-other.polynomial[i]):
return True
return False
def __add__(self,other):
if type(other)==Polynomial:
summ=[0]*max(len(self.polynomial),len(other.polynomial))
for i in range(len(self.polynomial)):
summ[i]+=self.polynomial[i]
for i in range(len(other.polynomial)):
summ[i]+=other.polynomial[i]
if self.mod:
for i in range(len(summ)):
summ[i]%=self.mod
else:
summ=[x for x in self.polynomial] if self.polynomial else [0]
summ[0]+=other
if self.mod:
summ[0]%=self.mod
while summ and abs(summ[-1])<=self.eps:
summ.pop()
summ=Polynomial(summ,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return summ
def __sub__(self,other):
if type(other)==Polynomial:
diff=[0]*max(len(self.polynomial),len(other.polynomial))
for i in range(len(self.polynomial)):
diff[i]+=self.polynomial[i]
for i in range(len(other.polynomial)):
diff[i]-=other.polynomial[i]
if self.mod:
for i in range(len(diff)):
diff[i]%=self.mod
else:
diff=[x for x in self.polynomial] if self.polynomial else [0]
diff[0]-=other
if self.mod:
diff[0]%=self.mod
while diff and abs(diff[-1])<=self.eps:
diff.pop()
diff=Polynomial(diff,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return diff
def __mul__(self,other):
if type(other)==Polynomial:
if self.max_degree==-1:
prod=[0]*(len(self.polynomial)+len(other.polynomial)-1)
for i in range(len(self.polynomial)):
for j in range(len(other.polynomial)):
prod[i+j]+=self.polynomial[i]*other.polynomial[j]
else:
prod=[0]*min(len(self.polynomial)+len(other.polynomial)-1,self.max_degree+1)
for i in range(len(self.polynomial)):
for j in range(min(len(other.polynomial),self.max_degree+1-i)):
prod[i+j]+=self.polynomial[i]*other.polynomial[j]
if self.mod:
for i in range(len(prod)):
prod[i]%=self.mod
else:
if self.mod:
prod=[x*other%self.mod for x in self.polynomial]
else:
prod=[x*other for x in self.polynomial]
while prod and abs(prod[-1])<=self.eps:
prod.pop()
prod=Polynomial(prod,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return prod
def __matmul__(self,other):
assert type(other)==Polynomial
if self.mod:
prod=NTT(self.polynomial,other.polynomial)
else:
prod=FFT(self.polynomial,other.polynomial)
if self.max_degree!=-1 and len(prod)>self.max_degree+1:
prod=prod[:self.max_degree+1]
while prod and abs(prod[-1])<=self.eps:
prod.pop()
prod=Polynomial(prod,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return prod
def __pow__(self,other):
if other==0:
prod=Polynomial([1],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
elif other==1:
prod=Polynomial([x for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
prod=[1]
doub=self.polynomial
if self.mod:
convolve=NTT
convolve_Pow=NTT_Pow
else:
convolve=FFT
convolve_Pow=FFT_Pow
while other>=2:
if other&1:
prod=convolve(prod,doub)
if self.max_degree!=-1:
prod=prod[:self.max_degree+1]
doub=convolve_Pow(doub,2)
if self.max_degree!=-1:
doub=doub[:self.max_degree+1]
other>>=1
prod=convolve(prod,doub)
if self.max_degree!=-1:
prod=prod[:self.max_degree+1]
prod=Polynomial(prod,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return prod
def __truediv__(self,other):
if type(other)==Polynomial:
assert other.polynomial
for n in range(len(other.polynomial)):
if self.eps<abs(other.polynomial[n]):
break
assert len(self.polynomial)>n
for i in range(n):
assert abs(self.polynomial[i])<=self.eps
self_polynomial=self.polynomial[n:]
other_polynomial=other.polynomial[n:]
if self.mod:
inve=MOD(self.mod).Pow(other_polynomial[0],-1)
else:
inve=1/other_polynomial[0]
quot=[]
for i in range(len(self_polynomial)-len(other_polynomial)+1):
if self.mod:
quot.append(self_polynomial[i]*inve%self.mod)
else:
quot.append(self_polynomial[i]*inve)
for j in range(len(other_polynomial)):
self_polynomial[i+j]-=other_polynomial[j]*quot[-1]
if self.mod:
self_polynomial[i+j]%=self.mod
for i in range(max(0,len(self_polynomial)-len(other_polynomial)+1),len(self_polynomial)):
if self.eps<abs(self_polynomial[i]):
assert self.max_degree!=-1
self_polynomial=self_polynomial[-len(other_polynomial)+1:]+[0]*(len(other_polynomial)-1-len(self_polynomial))
while len(quot)<=self.max_degree:
self_polynomial.append(0)
if self.mod:
quot.append(self_polynomial[0]*inve%self.mod)
self_polynomial=[(self_polynomial[i]-other_polynomial[i]*quot[-1])%self.mod for i in range(1,len(self_polynomial))]
else:
quot.append(self_polynomial[0]*inve)
self_polynomial=[(self_polynomial[i]-other_polynomial[i]*quot[-1]) for i in range(1,len(self_polynomial))]
break
quot=Polynomial(quot,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
assert self.eps<abs(other)
if self.mod:
inve=MOD(self.mod).Pow(other,-1)
quot=Polynomial([x*inve%self.mod for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
quot=Polynomial([x/other for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return quot
def __floordiv__(self,other):
assert type(other)==Polynomial
quot=[0]*(len(self.polynomial)-len(other.polynomial)+1)
rema=[x for x in self.polynomial]
if self.mod:
inve=MOD(self.mod).Pow(other.polynomial[-1],-1)
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve%self.mod
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
rema[i+j]%=self.mod
else:
inve=1/other.polynomial[-1]
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
quot=Polynomial(quot,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return quot
def __mod__(self,other):
assert type(other)==Polynomial
quot=[0]*(len(self.polynomial)-len(other.polynomial)+1)
rema=[x for x in self.polynomial]
if self.mod:
inve=MOD(self.mod).Pow(other.polynomial[-1],-1)
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve%self.mod
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
rema[i+j]%=self.mod
else:
inve=1/other.polynomial[-1]
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
while rema and abs(rema[-1])<=self.eps:
rema.pop()
rema=Polynomial(rema,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return rema
def __divmod__(self,other):
assert type(other)==Polynomial
quot=[0]*(len(self.polynomial)-len(other.polynomial)+1)
rema=[x for x in self.polynomial]
if self.mod:
inve=MOD(self.mod).Pow(other.polynomial[-1],-1)
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve%self.mod
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
rema[i+j]%=self.mod
else:
inve=1/other.polynomial[-1]
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
while rema and abs(rema[-1])<=self.eps:
rema.pop()
quot=Polynomial(quot,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
rema=Polynomial(rema,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return quot,rema
def __neg__(self):
if self.mod:
nega=Polynomial([(-x)%self.mod for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
nega=Polynomial([-x for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return nega
def __pos__(self):
posi=Polynomial([x for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return posi
def __bool__(self):
return self.polynomial
def __getitem__(self,n):
if type(n)==int:
if n<=len(self.polynomial)-1:
return self.polynomial[n]
else:
return 0
else:
return Polynomial(polynomial=self.polynomial[n],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
def __setitem__(self,n,a):
if self.mod:
a%=self.mod
if self.max_degree==-1 or n<=self.max_degree:
if n<=len(self.polynomial)-1:
self.polynomial[n]=a
elif self.eps<abs(a):
self.polynomial+=[0]*(n-len(self.polynomial))+[a]
def __iter__(self):
for x in self.polynomial:
yield x
def __call__(self,x):
retu=0
pow_x=1
for i in range(len(self.polynomial)):
retu+=pow_x*self.polynomial[i]
pow_x*=x
if self.mod:
retu%=self.mod
pow_x%=self.mod
return retu
def __str__(self):
return "["+", ".join(map(str,self.polynomial))+"]"
def __len__(self):
return len(self.polynomial)
def differentiate(self):
if self.mod:
differential=[x*i%self.mod for i,x in enumerate(self.polynomial[1:],1)]
else:
differential=[x*i for i,x in enumerate(self.polynomial[1:],1)]
return Polynomial(differential,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
def integrate(self):
if self.mod:
integral=[0]+[x*MOD(mod).Pow(i+1,-1)%self.mod for i,x in enumerate(self.polynomial)]
else:
integral=[0]+[x/(i+1) for i,x in enumerate(self.polynomial)]
while integral and abs(integral[-1])<=self.eps:
integral.pop()
return Polynomial(integral,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
def inverse(self):
assert self.polynomial and self.eps<self.polynomial[0]
assert self.max_degree!=-1
if self.mod:
quot=[MOD(self.mod).Pow(self.polynomial[0],-1)]
if self.mod==998244353:
prim_root=3
prim_root_inve=332748118
else:
prim_root=Primitive_Root(self.mod)
prim_root_inve=MOD(self.mod).Pow(prim_root,-1)
def DFT(polynomial,n,inverse=False):
polynomial=polynomial+[0]*((1<<n)-len(polynomial))
if inverse:
for bit in range(1,n+1):
a=1<<bit-1
x=pow(prim_root,self.mod-1>>bit,self.mod)
U=[1]
for _ in range(a):
U.append(U[-1]*x%self.mod)
for i in range(1<<n-bit):
for j in range(a):
s=i*2*a+j
t=s+a
polynomial[s],polynomial[t]=(polynomial[s]+polynomial[t]*U[j])%self.mod,(polynomial[s]-polynomial[t]*U[j])%self.mod
x=pow((self.mod+1)//2,n,self.mod)
for i in range(1<<n):
polynomial[i]*=x
polynomial[i]%=self.mod
else:
for bit in range(n,0,-1):
a=1<<bit-1
x=pow(prim_root_inve,self.mod-1>>bit,self.mod)
U=[1]
for _ in range(a):
U.append(U[-1]*x%self.mod)
for i in range(1<<n-bit):
for j in range(a):
s=i*2*a+j
t=s+a
polynomial[s],polynomial[t]=(polynomial[s]+polynomial[t])%self.mod,U[j]*(polynomial[s]-polynomial[t])%self.mod
return polynomial
else:
quot=[1/self.polynomial[0]]
def DFT(polynomial,n,inverse=False):
N=len(polynomial)
if inverse:
primitive_root=[math.cos(-i*2*math.pi/(1<<n))+math.sin(-i*2*math.pi/(1<<n))*1j for i in range(1<<n)]
else:
primitive_root=[math.cos(i*2*math.pi/(1<<n))+math.sin(i*2*math.pi/(1<<n))*1j for i in range(1<<n)]
polynomial=polynomial+[0]*((1<<n)-N)
if inverse:
for bit in range(1,n+1):
a=1<<bit-1
for i in range(1<<n-bit):
for j in range(a):
s=i*2*a+j
t=s+a
polynomial[s],polynomial[t]=polynomial[s]+polynomial[t]*primitive_root[j<<n-bit],polynomial[s]-polynomial[t]*primitive_root[j<<n-bit]
for i in range(1<<n):
polynomial[i]=round((polynomial[i]/(1<<n)).real)
else:
for bit in range(n,0,-1):
a=1<<bit-1
for i in range(1<<n-bit):
for j in range(a):
s=i*2*a+j
t=s+a
polynomial[s],polynomial[t]=polynomial[s]+polynomial[t],primitive_root[j<<n-bit]*(polynomial[s]-polynomial[t])
return polynomial
for n in range(self.max_degree.bit_length()):
prev=quot
DFT_prev=DFT(prev,n+1)
if self.mod:
quot=[x*y%self.mod for x,y in zip(DFT_prev,DFT(self.polynomial[:1<<n+1],n+1))]
else:
quot=[x*y for x,y in zip(DFT_prev,DFT(self.polynomial[:1<<n+1],n+1))]
quot=DFT([0]*(1<<n)+DFT(quot,n+1,inverse=True)[1<<n:],n+1)
if self.mod:
quot=[(-x*y)%self.mod for x,y in zip(DFT_prev,quot)]
else:
quot=[-x*y for x,y in zip(DFT_prev,quot)]
quot=prev+DFT(quot,n+1,inverse=True)[1<<n:]
quot=quot[:self.max_degree+1]
quot=Polynomial(quot,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return quot
def log(self):
assert self.max_degree!=-1
assert self.polynomial and abs(self.polynomial[0]-1)<=self.eps
log=self.inverse()
if self.mod:
log=Polynomial(NTT(self.differentiate().polynomial,log.polynomial),max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
log=Polynomial(FFT(self.differentiate().polynomial,log.polynomial),max_degree=self.max_degree,eps=self.eps,mod=self.mod)
log=log.integrate()
return log
def Newton(self,n0,f,differentiated_f=None):
newton=[n0]
while len(newton)<self.max_degree+1:
prev=newton
if differentiated_f==None:
newton=f(prev,self.polynomial)
else:
newton=f(prev)
for i in range(min(len(self.polynomial),len(newton))):
newton[i]-=self.polynomial[i]
newton[i]%=self.mod
if self.mod:
newton=NTT(newton,Polynomial(differentiated_f(prev),max_degree=len(newton)-1,eps=self.eps,mod=self.mod).inverse().polynomial)[:len(newton)]
else:
newton=FFT(newton,Polynomial(differentiated_f(prev),max_degree=len(newton)-1,eps=self.eps,mod=self.mod).inverse().polynomial)[:len(newton)]
for i in range(len(newton)):
newton[i]=-newton[i]
newton[i]%=self.mod
for i in range(len(prev)):
newton[i]+=prev[i]
newton[i]%=self.mod
newton=newton[:self.max_degree+1]
while newton and newton[-1]<=self.eps:
newton.pop()
return Polynomial(newton,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
def sqrt(self):
if self.polynomial:
for cnt0 in range(len(self.polynomial)):
if self.polynomial[cnt0]:
break
if cnt0%2:
sqrt=None
else:
if self.mod:
n0=Tonelli_Shanks(self.polynomial[cnt0],self.mod)
else:
if self.polynomial[cnt0]>=self.eps:
n0=self.polynomial[cnt0]**.5
if n0==None:
sqrt=None
else:
def f(prev):
if self.mod:
return NTT_Pow(prev,2)+[0]
else:
return FFT_Pow(prev,2)+[0]
def differentiated_f(prev):
retu=[0]*(2*len(prev)-1)
for i in range(len(prev)):
retu[i]+=2*prev[i]
if self.mod:
retu[i]%self.mod
return retu
sqrt=[0]*(cnt0//2)+Polynomial(self.polynomial[cnt0:],max_degree=self.max_degree-cnt0//2,mod=self.mod).Newton(n0,f,differentiated_f).polynomial
sqrt=Polynomial(sqrt,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
sqrt=Polynomial([],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return sqrt
def exp(self):
assert not self.polynomial or abs(self.polynomial[0])<=self.eps
def f(prev,poly):
newton=Polynomial(prev,max_degree=2*len(prev)-1,eps=self.eps,mod=self.mod).log().polynomial
newton+=[0]*(2*len(prev)-len(newton))
for i in range(min(len(poly),len(newton))):
newton[i]-=poly[i]
if self.mod:
for i in range(len(newton)):
newton[i]%=self.mod
if self.mod:
return NTT(prev,newton)[:2*len(prev)]
else:
return FFT(prev,newton)[:2*len(prev)]
return Polynomial(self.polynomial,max_degree=self.max_degree,mod=self.mod).Newton(1,f)
def Degree(self):
return len(self.polynomial)-1
def Hadamard(polynomial,n,mod=0,inverse=False):
polynomial_=[x for x in polynomial]+[0]*((1<<n)-len(polynomial))
for bit in range(n):
for i in range(1<<n):
ii=i^(1<<bit)
if i>ii:
continue
polynomial_[i],polynomial_[ii]=polynomial_[i]+polynomial_[ii],polynomial_[i]-polynomial_[ii]
if mod:
polynomial_[i]%=mod
polynomial_[ii]%=mod
if inverse:
if mod:
inve_2=pow((mod+1)//2,n)
for i in range(1<<n):
polynomial_[i]*=inve_2
polynomial_[i]%=mod
else:
pow_2=pow(2,n)
for i in range(1<<n):
polynomial_[i]/=pow_2
return polynomial_
def XOR_Convolution(polynomial0,polynomial1,mod=0):
n=(max(len(polynomial0),len(polynomial1))-1).bit_length()
Hadamard_polynomial0=Hadamard(polynomial0,n,mod=mod)
Hadamard_polynomial1=Hadamard(polynomial1,n,mod=mod)
if mod:
convolution=[x*y%mod for x,y in zip(Hadamard_polynomial0,Hadamard_polynomial1)]
else:
convolution=[x*y for x,y in zip(Hadamard_polynomial0,Hadamard_polynomial1)]
convolution=Hadamard(convolution,n,mod=mod,inverse=True)
return convolution
def Bostan_Mori(poly_nume,poly_deno,N,mod=0,convolve=None):
if type(poly_nume)==Polynomial:
poly_nume=poly_nume.polynomial
if type(poly_deno)==Polynomial:
poly_deno=poly_deno.polynomial
if convolve==None:
def convolve(poly_nume,poly_deno):
conv=[0]*(len(poly_nume)+len(poly_deno)-1)
for i in range(len(poly_nume)):
for j in range(len(poly_deno)):
x=poly_nume[i]*poly_deno[j]
if mod:
x%=mod
conv[i+j]+=x
if mod:
for i in range(len(conv)):
conv[i]%=mod
return conv
while N:
poly_deno_=[-x if i%2 else x for i,x in enumerate(poly_deno)]
if N%2:
poly_nume=convolve(poly_nume,poly_deno_)[1::2]
else:
poly_nume=convolve(poly_nume,poly_deno_)[::2]
poly_deno=convolve(poly_deno,poly_deno_)[::2]
if mod:
for i in range(len(poly_nume)):
poly_nume[i]%=mod
for i in range(len(poly_deno)):
poly_deno[i]%=mod
N//=2
return poly_nume[0]
#mod = 998244353
imag = 911660635
iimag = 86583718
rate2 = (911660635, 509520358, 369330050, 332049552, 983190778, 123842337, 238493703, 975955924, 603855026, 856644456, 131300601,
842657263, 730768835, 942482514, 806263778, 151565301, 510815449, 503497456, 743006876, 741047443, 56250497, 867605899)
irate2 = (86583718, 372528824, 373294451, 645684063, 112220581, 692852209, 155456985, 797128860, 90816748, 860285882, 927414960,
354738543, 109331171, 293255632, 535113200, 308540755, 121186627, 608385704, 438932459, 359477183, 824071951, 103369235)
rate3 = (372528824, 337190230, 454590761, 816400692, 578227951, 180142363, 83780245, 6597683, 70046822, 623238099,
183021267, 402682409, 631680428, 344509872, 689220186, 365017329, 774342554, 729444058, 102986190, 128751033, 395565204)
irate3 = (509520358, 929031873, 170256584, 839780419, 282974284, 395914482, 444904435, 72135471, 638914820, 66769500,
771127074, 985925487, 262319669, 262341272, 625870173, 768022760, 859816005, 914661783, 430819711, 272774365, 530924681)
def butterfly(a):
n = len(a)
h = (n - 1).bit_length()
len_ = 0
while len_ < h:
if h - len_ == 1:
p = 1 << (h - len_ - 1)
rot = 1
for s in range(1 << len_):
offset = s << (h - len_)
for i in range(p):
l = a[i + offset]
r = a[i + offset + p] * rot % mod
a[i + offset] = (l + r) % mod
a[i + offset + p] = (l - r) % mod
if s + 1 != 1 << len_:
rot *= rate2[(~s & -~s).bit_length() - 1]
rot %= mod
len_ += 1
else:
p = 1 << (h - len_ - 2)
rot = 1
for s in range(1 << len_):
rot2 = rot * rot % mod
rot3 = rot2 * rot % mod
offset = s << (h - len_)
for i in range(p):
a0 = a[i + offset]
a1 = a[i + offset + p] * rot
a2 = a[i + offset + p * 2] * rot2
a3 = a[i + offset + p * 3] * rot3
a1na3imag = (a1 - a3) % mod * imag
a[i + offset] = (a0 + a2 + a1 + a3) % mod
a[i + offset + p] = (a0 + a2 - a1 - a3) % mod
a[i + offset + p * 2] = (a0 - a2 + a1na3imag) % mod
a[i + offset + p * 3] = (a0 - a2 - a1na3imag) % mod
if s + 1 != 1 << len_:
rot *= rate3[(~s & -~s).bit_length() - 1]
rot %= mod
len_ += 2
def butterfly_inv(a):
n = len(a)
h = (n - 1).bit_length()
len_ = h
while len_:
if len_ == 1:
p = 1 << (h - len_)
irot = 1
for s in range(1 << (len_ - 1)):
offset = s << (h - len_ + 1)
for i in range(p):
l = a[i + offset]
r = a[i + offset + p]
a[i + offset] = (l + r) % mod
a[i + offset + p] = (l - r) * irot % mod
if s + 1 != (1 << (len_ - 1)):
irot *= irate2[(~s & -~s).bit_length() - 1]
irot %= mod
len_ -= 1
else:
p = 1 << (h - len_)
irot = 1
for s in range(1 << (len_ - 2)):
irot2 = irot * irot % mod
irot3 = irot2 * irot % mod
offset = s << (h - len_ + 2)
for i in range(p):
a0 = a[i + offset]
a1 = a[i + offset + p]
a2 = a[i + offset + p * 2]
a3 = a[i + offset + p * 3]
a2na3iimag = (a2 - a3) * iimag % mod
a[i + offset] = (a0 + a1 + a2 + a3) % mod
a[i + offset + p] = (a0 - a1 + a2na3iimag) * irot % mod
a[i + offset + p * 2] = (a0 + a1 - a2 - a3) * irot2 % mod
a[i + offset + p * 3] = (a0 - a1 - a2na3iimag) * irot3 % mod
if s + 1 != (1 << (len_ - 2)):
irot *= irate3[(~s & -~s).bit_length() - 1]
irot %= mod
len_ -= 2
def integrate(a):
a=a.copy()
n = len(a)
assert n > 0
a.pop()
a.insert(0, 0)
inv = [1, 1]
for i in range(2, n):
inv.append(-inv[mod%i] * (mod//i) % mod)
a[i] = a[i] * inv[i] % mod
return a
def differentiate(a):
n = len(a)
assert n > 0
for i in range(2, n):
a[i] = a[i] * i % mod
a.pop(0)
a.append(0)
return a
def convolution_naive(a, b):
n = len(a)
m = len(b)
ans = [0] * (n + m - 1)
if n < m:
for j in range(m):
for i in range(n):
ans[i + j] = (ans[i + j] + a[i] * b[j]) % mod
else:
for i in range(n):
for j in range(m):
ans[i + j] = (ans[i + j] + a[i] * b[j]) % mod
return ans
def convolution_ntt(a, b):
a = a.copy()
b = b.copy()
n = len(a)
m = len(b)
z = 1 << (n + m - 2).bit_length()
a += [0] * (z - n)
butterfly(a)
b += [0] * (z - m)
butterfly(b)
for i in range(z):
a[i] = a[i] * b[i] % mod
butterfly_inv(a)
a = a[:n + m - 1]
iz = pow(z, mod - 2, mod)
for i in range(n + m - 1):
a[i] = a[i] * iz % mod
return a
def convolution_square(a):
a = a.copy()
n = len(a)
z = 1 << (2 * n - 2).bit_length()
a += [0] * (z - n)
butterfly(a)
for i in range(z):
a[i] = a[i] * a[i] % mod
butterfly_inv(a)
a = a[:2 * n - 1]
iz = pow(z, mod - 2, mod)
for i in range(2 * n - 1):
a[i] = a[i] * iz % mod
return a
def convolution(a, b):
"""It calculates (+, x) convolution in mod 998244353.
Given two arrays a[0], a[1], ..., a[n - 1] and b[0], b[1], ..., b[m - 1],
it calculates the array c of length n + m - 1, defined by
> c[i] = sum(a[j] * b[i - j] for j in range(i + 1)) % 998244353.
It returns an empty list if at least one of a and b are empty.
Complexity
----------
> O(n log n), where n = len(a) + len(b).
"""
n = len(a)
m = len(b)
if n == 0 or m == 0:
return []
if min(n, m) <= 60:
return convolution_naive(a, b)
if a is b:
return convolution_square(a)
return convolution_ntt(a, b)
def inverse(a):
n = len(a)
assert n > 0 and a[0] != 0
res = [pow(a[0], mod - 2, mod)]
m = 1
while m < n:
f = a[:min(n,2*m)] + [0]*(2*m-min(n,2*m))
g = res + [0]*m
butterfly(f)
butterfly(g)
for i in range(2*m):
f[i] = f[i] * g[i] % mod
butterfly_inv(f)
f = f[m:] + [0]*m
butterfly(f)
for i in range(2*m):
f[i] = f[i] * g[i] % mod
butterfly_inv(f)
iz = pow(2*m, mod-2, mod)
iz = (-iz*iz) % mod
for i in range(m):
f[i] = f[i] * iz % mod
res += f[:m]
m <<= 1
return res[:n]
def log(a):
a = a.copy()
n = len(a)
assert n > 0 and a[0] == 1
a_inv = inverse(a)
a=differentiate(a)
a = convolution(a, a_inv)[:n]
a=integrate(a)
return a
def exp(a):
a = a.copy()
n = len(a)
assert n > 0 and a[0] == 0
g = [1]
a[0] = 1
h_drv = a.copy()
h_drv=differentiate(h_drv)
m = 1
while m < n:
f_fft = a[:m] + [0] * m
butterfly(f_fft)
if m > 1:
_f = [f_fft[i] * g_fft[i] % mod for i in range(m)]
butterfly_inv(_f)
_f = _f[m // 2:] + [0] * (m // 2)
butterfly(_f)
for i in range(m):
_f[i] = _f[i] * g_fft[i] % mod
butterfly_inv(_f)
_f = _f[:m//2]
iz = pow(m, mod - 2, mod)
iz *= -iz
iz %= mod
for i in range(m//2):
_f[i] = _f[i] * iz % mod
g.extend(_f)
t = a[:m]
t=differentiate(t)
r = h_drv[:m - 1]
r.append(0)
butterfly(r)
for i in range(m):
r[i] = r[i] * f_fft[i] % mod
butterfly_inv(r)
im = pow(-m, mod - 2, mod)
for i in range(m):
r[i] = r[i] * im % mod
for i in range(m):
t[i] = (t[i] + r[i]) % mod
t = [t[-1]] + t[:-1]
t += [0] * m
butterfly(t)
g_fft = g + [0] * (2 * m - len(g))
butterfly(g_fft)
for i in range(2 * m):
t[i] = t[i] * g_fft[i] % mod
butterfly_inv(t)
t = t[:m]
i2m = pow(2 * m, mod - 2, mod)
for i in range(m):
t[i] = t[i] * i2m % mod
v = a[m:min(n, 2 * m)]
v += [0] * (m - len(v))
t = [0] * (m - 1) + t + [0]
t=integrate(t)
for i in range(m):
v[i] = (v[i] - t[m + i]) % mod
v += [0] * m
butterfly(v)
for i in range(2 * m):
v[i] = v[i] * f_fft[i] % mod
butterfly_inv(v)
v = v[:m]
i2m = pow(2 * m, mod - 2, mod)
for i in range(m):
v[i] = v[i] * i2m % mod
for i in range(min(n - m, m)):
a[m + i] = v[i]
m *= 2
return a
def power(a,k):
n = len(a)
assert n>0
if k==0:
return [1]+[0]*(n-1)
l = 0
while l < len(a) and not a[l]:
l += 1
if l * k >= n:
return [0] * n
ic = pow(a[l], mod - 2, mod)
pc = pow(a[l], k, mod)
a = log([a[i] * ic % mod for i in range(l, len(a))])
for i in range(len(a)):
a[i] = a[i] * k % mod
a = exp(a)
for i in range(len(a)):
a[i] = a[i] * pc % mod
a = [0] * (l * k) + a[:n - l * k]
return a
def sqrt(a):
if len(a) == 0:
return []
if a[0] == 0:
for d in range(1, len(a)):
if a[d]:
if d & 1:
return None
if len(a) - 1 < d // 2:
break
res=sqrt(a[d:]+[0]*(d//2))
if res == None:
return None
res = [0]*(d//2)+res
return res
return [0]*len(a)
sqr = Tonelli_Shanks(a[0],mod)
if sqr == None:
return None
T = [0] * (len(a))
T[0] = sqr
res = T.copy()
T[0] = pow(sqr,mod-2,mod) #T:res^{-1}
m = 1
two_inv = (mod + 1) // 2
F = [sqr]
while m <= len(a) - 1:
for i in range(m):
F[i] *= F[i]
F[i] %= mod
butterfly_inv(F)
iz = pow(m, mod-2, mod)
for i in range(m):
F[i] = F[i] * iz % mod
delta = [0] * (2 * m)
for i in range(m):
delta[i + m] = F[i] - a[i] - (a[i + m] if i+m<len(a) else 0)
butterfly(delta)
G = [0] * (2 * m)
for i in range(m):
G[i] = T[i]
butterfly(G)
for i in range(2 * m):
delta[i] *= G[i]
delta[i] %= mod
butterfly_inv(delta)
iz = pow(2*m, mod-2, mod)
for i in range(2*m):
delta[i] = delta[i] * iz % mod
for i in range(m, min(2 * m, len(a))):
res[i] = -delta[i] * two_inv%mod
res[i]%=mod
if 2 * m > len(a) - 1:
break
F = res[:2 * m]
butterfly(F)
eps = [F[i] * G[i] % mod for i in range(2 * m)]
butterfly_inv(eps)
for i in range(m):
eps[i] = 0
iz = pow(2*m, mod-2, mod)
for i in range(m,2*m):
eps[i] = eps[i] * iz % mod
butterfly(eps)
for i in range(2 * m):
eps[i] *= G[i]
eps[i] %= mod
butterfly_inv(eps)
for i in range(m, 2 * m):
T[i] = -eps[i]*iz
T[i]%=mod
iz = iz*iz % mod
m <<= 1
return res
def taylor_shift(a,c):
a=a.copy()
n=len(a)
MD=MOD(mod)
MD.Build_Fact(n-1)
for i in range(n):
a[i]*=MD.Fact(i)
a[i]%=mod
C=[1]
for i in range(1,n):
C.append(C[-1]*c%mod)
for i in range(n):
C[i]*=MD.Fact_Inve(i)
C[i]%=mod
a=convolution(a,C[::-1])[n-1:]
for i in range(n):
a[i]*=MD.Fact_Inve(i)
a[i]%=mod
return a
def division_modulus(f,g):
n=len(f)
m=len(g)
while m and g[m-1]==0:
m-=1
assert m
if n>=m:
fR=f[::-1][:n-m+1]
gR=g[:m][::-1][:n-m+1]+[0]*max(0,n-m+1-m)
qR=convolution(fR,inverse(gR))[:n-m+1]
q=qR[::-1]
r=[(f[i]-x)%mod for i,x in enumerate(convolution(g,q)[:m-1])]
while r and r[-1]==0:
r.pop()
else:
q,r=[],f.copy()
return q,r
def multipoint_evaluation(f, x):
n = len(x)
sz = 1 << (n - 1).bit_length()
g = [[1] for _ in range(2 * sz)]
for i in range(n):
g[i + sz] = [-x[i], 1]
for i in range(1, sz)[::-1]:
g[i] = convolution(g[2 * i],g[2 * i + 1])
g[1] =division_modulus(f,g[1])[1]
for i in range(2, 2 * sz):
g[i]=division_modulus(g[i>>1],g[i])[1]
res = [g[i + sz][0] if g[i+sz] else 0 for i in range(n)]
return res
N,A=map(int,readline().split())
mod=998244353
MD=MOD(mod)
MD.Build_Fact(N)
f=[1]
for i in range(1,N+1):
f.append(f[i-1]*(A-i+1)%mod)
for i in range(N+1):
f[i]*=MD.Fact_Inve(i)
f[i]%=mod
ans_lst=[None]*N
ans_lst[0]=A
def solve(l,r,poly):
if l==r:
return [1]
if l+1==r:
ans_lst[l-1]=poly[0]
return [1,ans_lst[l-1]]
mid=(l+r)//2
P=solve(l,mid,poly[:mid-l])
P=convolution(P,solve(mid,r,convolution(poly,P)[mid-l:r-l]))
return P
solve(2,N+1,f[2:N+1])
ans=ans_lst[N-1]
print(ans)
import sys
readline=sys.stdin.readline
def Tonelli_Shanks(N,p):
if pow(N,p>>1,p)==p-1:
retu=None
elif p%4==3:
retu=pow(N,(p+1)//4,p)
else:
for nonresidue in range(1,p):
if pow(nonresidue,p>>1,p)==p-1:
break
pp=p-1
cnt=0
while pp%2==0:
pp//=2
cnt+=1
s=pow(N,pp,p)
retu=pow(N,(pp+1)//2,p)
for i in range(cnt-2,-1,-1):
if pow(s,1<<i,p)==p-1:
s*=pow(nonresidue,p>>1+i,p)
s%=p
retu*=pow(nonresidue,p>>2+i,p)
retu%=p
return retu
def Extended_Euclid(n,m):
stack=[]
while m:
stack.append((n,m))
n,m=m,n%m
if n>=0:
x,y=1,0
else:
x,y=-1,0
for i in range(len(stack)-1,-1,-1):
n,m=stack[i]
x,y=y,x-(n//m)*y
return x,y
class MOD:
def __init__(self,p,e=None):
self.p=p
self.e=e
if self.e==None:
self.mod=self.p
else:
self.mod=self.p**self.e
def Pow(self,a,n):
a%=self.mod
if n>=0:
return pow(a,n,self.mod)
else:
#assert math.gcd(a,self.mod)==1
x=Extended_Euclid(a,self.mod)[0]
return pow(x,-n,self.mod)
def Build_Fact(self,N):
assert N>=0
self.factorial=[1]
if self.e==None:
for i in range(1,N+1):
self.factorial.append(self.factorial[-1]*i%self.mod)
else:
self.cnt=[0]*(N+1)
for i in range(1,N+1):
self.cnt[i]=self.cnt[i-1]
ii=i
while ii%self.p==0:
ii//=self.p
self.cnt[i]+=1
self.factorial.append(self.factorial[-1]*ii%self.mod)
self.factorial_inve=[None]*(N+1)
self.factorial_inve[-1]=self.Pow(self.factorial[-1],-1)
for i in range(N-1,-1,-1):
ii=i+1
while ii%self.p==0:
ii//=self.p
self.factorial_inve[i]=(self.factorial_inve[i+1]*ii)%self.mod
def Build_Inverse(self,N):
self.inverse=[None]*(N+1)
assert self.p>N
self.inverse[1]=1
for n in range(2,N+1):
if n%self.p==0:
continue
a,b=divmod(self.mod,n)
self.inverse[n]=(-a*self.inverse[b])%self.mod
def Inverse(self,n):
return self.inverse[n]
def Fact(self,N):
if N<0:
return 0
retu=self.factorial[N]
if self.e!=None and self.cnt[N]:
retu*=pow(self.p,self.cnt[N],self.mod)%self.mod
retu%=self.mod
return retu
def Fact_Inve(self,N):
if self.e!=None and self.cnt[N]:
return None
return self.factorial_inve[N]
def Comb(self,N,K,divisible_count=False):
if K<0 or K>N:
return 0
retu=self.factorial[N]*self.factorial_inve[K]%self.mod*self.factorial_inve[N-K]%self.mod
if self.e!=None:
cnt=self.cnt[N]-self.cnt[N-K]-self.cnt[K]
if divisible_count:
return retu,cnt
else:
retu*=pow(self.p,cnt,self.mod)
retu%=self.mod
return retu
class Polynomial:
def __init__(self,polynomial,max_degree=-1,eps=0,mod=0):
self.max_degree=max_degree
if self.max_degree!=-1 and len(polynomial)>self.max_degree+1:
self.polynomial=polynomial[:self.max_degree+1]
else:
self.polynomial=polynomial
self.mod=mod
self.eps=eps
def __eq__(self,other):
if type(other)!=Polynomial:
return False
if len(self.polynomial)!=len(other.polynomial):
return False
for i in range(len(self.polynomial)):
if self.eps<abs(self.polynomial[i]-other.polynomial[i]):
return False
return True
def __ne__(self,other):
if type(other)!=Polynomial:
return True
if len(self.polynomial)!=len(other.polynomial):
return True
for i in range(len(self.polynomial)):
if self.eps<abs(self.polynomial[i]-other.polynomial[i]):
return True
return False
def __add__(self,other):
if type(other)==Polynomial:
summ=[0]*max(len(self.polynomial),len(other.polynomial))
for i in range(len(self.polynomial)):
summ[i]+=self.polynomial[i]
for i in range(len(other.polynomial)):
summ[i]+=other.polynomial[i]
if self.mod:
for i in range(len(summ)):
summ[i]%=self.mod
else:
summ=[x for x in self.polynomial] if self.polynomial else [0]
summ[0]+=other
if self.mod:
summ[0]%=self.mod
while summ and abs(summ[-1])<=self.eps:
summ.pop()
summ=Polynomial(summ,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return summ
def __sub__(self,other):
if type(other)==Polynomial:
diff=[0]*max(len(self.polynomial),len(other.polynomial))
for i in range(len(self.polynomial)):
diff[i]+=self.polynomial[i]
for i in range(len(other.polynomial)):
diff[i]-=other.polynomial[i]
if self.mod:
for i in range(len(diff)):
diff[i]%=self.mod
else:
diff=[x for x in self.polynomial] if self.polynomial else [0]
diff[0]-=other
if self.mod:
diff[0]%=self.mod
while diff and abs(diff[-1])<=self.eps:
diff.pop()
diff=Polynomial(diff,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return diff
def __mul__(self,other):
if type(other)==Polynomial:
if self.max_degree==-1:
prod=[0]*(len(self.polynomial)+len(other.polynomial)-1)
for i in range(len(self.polynomial)):
for j in range(len(other.polynomial)):
prod[i+j]+=self.polynomial[i]*other.polynomial[j]
else:
prod=[0]*min(len(self.polynomial)+len(other.polynomial)-1,self.max_degree+1)
for i in range(len(self.polynomial)):
for j in range(min(len(other.polynomial),self.max_degree+1-i)):
prod[i+j]+=self.polynomial[i]*other.polynomial[j]
if self.mod:
for i in range(len(prod)):
prod[i]%=self.mod
else:
if self.mod:
prod=[x*other%self.mod for x in self.polynomial]
else:
prod=[x*other for x in self.polynomial]
while prod and abs(prod[-1])<=self.eps:
prod.pop()
prod=Polynomial(prod,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return prod
def __matmul__(self,other):
assert type(other)==Polynomial
if self.mod:
prod=NTT(self.polynomial,other.polynomial)
else:
prod=FFT(self.polynomial,other.polynomial)
if self.max_degree!=-1 and len(prod)>self.max_degree+1:
prod=prod[:self.max_degree+1]
while prod and abs(prod[-1])<=self.eps:
prod.pop()
prod=Polynomial(prod,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return prod
def __pow__(self,other):
if other==0:
prod=Polynomial([1],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
elif other==1:
prod=Polynomial([x for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
prod=[1]
doub=self.polynomial
if self.mod:
convolve=NTT
convolve_Pow=NTT_Pow
else:
convolve=FFT
convolve_Pow=FFT_Pow
while other>=2:
if other&1:
prod=convolve(prod,doub)
if self.max_degree!=-1:
prod=prod[:self.max_degree+1]
doub=convolve_Pow(doub,2)
if self.max_degree!=-1:
doub=doub[:self.max_degree+1]
other>>=1
prod=convolve(prod,doub)
if self.max_degree!=-1:
prod=prod[:self.max_degree+1]
prod=Polynomial(prod,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return prod
def __truediv__(self,other):
if type(other)==Polynomial:
assert other.polynomial
for n in range(len(other.polynomial)):
if self.eps<abs(other.polynomial[n]):
break
assert len(self.polynomial)>n
for i in range(n):
assert abs(self.polynomial[i])<=self.eps
self_polynomial=self.polynomial[n:]
other_polynomial=other.polynomial[n:]
if self.mod:
inve=MOD(self.mod).Pow(other_polynomial[0],-1)
else:
inve=1/other_polynomial[0]
quot=[]
for i in range(len(self_polynomial)-len(other_polynomial)+1):
if self.mod:
quot.append(self_polynomial[i]*inve%self.mod)
else:
quot.append(self_polynomial[i]*inve)
for j in range(len(other_polynomial)):
self_polynomial[i+j]-=other_polynomial[j]*quot[-1]
if self.mod:
self_polynomial[i+j]%=self.mod
for i in range(max(0,len(self_polynomial)-len(other_polynomial)+1),len(self_polynomial)):
if self.eps<abs(self_polynomial[i]):
assert self.max_degree!=-1
self_polynomial=self_polynomial[-len(other_polynomial)+1:]+[0]*(len(other_polynomial)-1-len(self_polynomial))
while len(quot)<=self.max_degree:
self_polynomial.append(0)
if self.mod:
quot.append(self_polynomial[0]*inve%self.mod)
self_polynomial=[(self_polynomial[i]-other_polynomial[i]*quot[-1])%self.mod for i in range(1,len(self_polynomial))]
else:
quot.append(self_polynomial[0]*inve)
self_polynomial=[(self_polynomial[i]-other_polynomial[i]*quot[-1]) for i in range(1,len(self_polynomial))]
break
quot=Polynomial(quot,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
assert self.eps<abs(other)
if self.mod:
inve=MOD(self.mod).Pow(other,-1)
quot=Polynomial([x*inve%self.mod for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
quot=Polynomial([x/other for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return quot
def __floordiv__(self,other):
assert type(other)==Polynomial
quot=[0]*(len(self.polynomial)-len(other.polynomial)+1)
rema=[x for x in self.polynomial]
if self.mod:
inve=MOD(self.mod).Pow(other.polynomial[-1],-1)
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve%self.mod
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
rema[i+j]%=self.mod
else:
inve=1/other.polynomial[-1]
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
quot=Polynomial(quot,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return quot
def __mod__(self,other):
assert type(other)==Polynomial
quot=[0]*(len(self.polynomial)-len(other.polynomial)+1)
rema=[x for x in self.polynomial]
if self.mod:
inve=MOD(self.mod).Pow(other.polynomial[-1],-1)
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve%self.mod
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
rema[i+j]%=self.mod
else:
inve=1/other.polynomial[-1]
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
while rema and abs(rema[-1])<=self.eps:
rema.pop()
rema=Polynomial(rema,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return rema
def __divmod__(self,other):
assert type(other)==Polynomial
quot=[0]*(len(self.polynomial)-len(other.polynomial)+1)
rema=[x for x in self.polynomial]
if self.mod:
inve=MOD(self.mod).Pow(other.polynomial[-1],-1)
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve%self.mod
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
rema[i+j]%=self.mod
else:
inve=1/other.polynomial[-1]
for i in range(len(self.polynomial)-len(other.polynomial),-1,-1):
quot[i]=rema[i+len(other.polynomial)-1]*inve
for j in range(len(other.polynomial)):
rema[i+j]-=quot[i]*other.polynomial[j]
while rema and abs(rema[-1])<=self.eps:
rema.pop()
quot=Polynomial(quot,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
rema=Polynomial(rema,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return quot,rema
def __neg__(self):
if self.mod:
nega=Polynomial([(-x)%self.mod for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
nega=Polynomial([-x for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return nega
def __pos__(self):
posi=Polynomial([x for x in self.polynomial],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return posi
def __bool__(self):
return self.polynomial
def __getitem__(self,n):
if type(n)==int:
if n<=len(self.polynomial)-1:
return self.polynomial[n]
else:
return 0
else:
return Polynomial(polynomial=self.polynomial[n],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
def __setitem__(self,n,a):
if self.mod:
a%=self.mod
if self.max_degree==-1 or n<=self.max_degree:
if n<=len(self.polynomial)-1:
self.polynomial[n]=a
elif self.eps<abs(a):
self.polynomial+=[0]*(n-len(self.polynomial))+[a]
def __iter__(self):
for x in self.polynomial:
yield x
def __call__(self,x):
retu=0
pow_x=1
for i in range(len(self.polynomial)):
retu+=pow_x*self.polynomial[i]
pow_x*=x
if self.mod:
retu%=self.mod
pow_x%=self.mod
return retu
def __str__(self):
return "["+", ".join(map(str,self.polynomial))+"]"
def __len__(self):
return len(self.polynomial)
def differentiate(self):
if self.mod:
differential=[x*i%self.mod for i,x in enumerate(self.polynomial[1:],1)]
else:
differential=[x*i for i,x in enumerate(self.polynomial[1:],1)]
return Polynomial(differential,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
def integrate(self):
if self.mod:
integral=[0]+[x*MOD(mod).Pow(i+1,-1)%self.mod for i,x in enumerate(self.polynomial)]
else:
integral=[0]+[x/(i+1) for i,x in enumerate(self.polynomial)]
while integral and abs(integral[-1])<=self.eps:
integral.pop()
return Polynomial(integral,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
def inverse(self):
assert self.polynomial and self.eps<self.polynomial[0]
assert self.max_degree!=-1
if self.mod:
quot=[MOD(self.mod).Pow(self.polynomial[0],-1)]
if self.mod==998244353:
prim_root=3
prim_root_inve=332748118
else:
prim_root=Primitive_Root(self.mod)
prim_root_inve=MOD(self.mod).Pow(prim_root,-1)
def DFT(polynomial,n,inverse=False):
polynomial=polynomial+[0]*((1<<n)-len(polynomial))
if inverse:
for bit in range(1,n+1):
a=1<<bit-1
x=pow(prim_root,self.mod-1>>bit,self.mod)
U=[1]
for _ in range(a):
U.append(U[-1]*x%self.mod)
for i in range(1<<n-bit):
for j in range(a):
s=i*2*a+j
t=s+a
polynomial[s],polynomial[t]=(polynomial[s]+polynomial[t]*U[j])%self.mod,(polynomial[s]-polynomial[t]*U[j])%self.mod
x=pow((self.mod+1)//2,n,self.mod)
for i in range(1<<n):
polynomial[i]*=x
polynomial[i]%=self.mod
else:
for bit in range(n,0,-1):
a=1<<bit-1
x=pow(prim_root_inve,self.mod-1>>bit,self.mod)
U=[1]
for _ in range(a):
U.append(U[-1]*x%self.mod)
for i in range(1<<n-bit):
for j in range(a):
s=i*2*a+j
t=s+a
polynomial[s],polynomial[t]=(polynomial[s]+polynomial[t])%self.mod,U[j]*(polynomial[s]-polynomial[t])%self.mod
return polynomial
else:
quot=[1/self.polynomial[0]]
def DFT(polynomial,n,inverse=False):
N=len(polynomial)
if inverse:
primitive_root=[math.cos(-i*2*math.pi/(1<<n))+math.sin(-i*2*math.pi/(1<<n))*1j for i in range(1<<n)]
else:
primitive_root=[math.cos(i*2*math.pi/(1<<n))+math.sin(i*2*math.pi/(1<<n))*1j for i in range(1<<n)]
polynomial=polynomial+[0]*((1<<n)-N)
if inverse:
for bit in range(1,n+1):
a=1<<bit-1
for i in range(1<<n-bit):
for j in range(a):
s=i*2*a+j
t=s+a
polynomial[s],polynomial[t]=polynomial[s]+polynomial[t]*primitive_root[j<<n-bit],polynomial[s]-polynomial[t]*primitive_root[j<<n-bit]
for i in range(1<<n):
polynomial[i]=round((polynomial[i]/(1<<n)).real)
else:
for bit in range(n,0,-1):
a=1<<bit-1
for i in range(1<<n-bit):
for j in range(a):
s=i*2*a+j
t=s+a
polynomial[s],polynomial[t]=polynomial[s]+polynomial[t],primitive_root[j<<n-bit]*(polynomial[s]-polynomial[t])
return polynomial
for n in range(self.max_degree.bit_length()):
prev=quot
DFT_prev=DFT(prev,n+1)
if self.mod:
quot=[x*y%self.mod for x,y in zip(DFT_prev,DFT(self.polynomial[:1<<n+1],n+1))]
else:
quot=[x*y for x,y in zip(DFT_prev,DFT(self.polynomial[:1<<n+1],n+1))]
quot=DFT([0]*(1<<n)+DFT(quot,n+1,inverse=True)[1<<n:],n+1)
if self.mod:
quot=[(-x*y)%self.mod for x,y in zip(DFT_prev,quot)]
else:
quot=[-x*y for x,y in zip(DFT_prev,quot)]
quot=prev+DFT(quot,n+1,inverse=True)[1<<n:]
quot=quot[:self.max_degree+1]
quot=Polynomial(quot,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return quot
def log(self):
assert self.max_degree!=-1
assert self.polynomial and abs(self.polynomial[0]-1)<=self.eps
log=self.inverse()
if self.mod:
log=Polynomial(NTT(self.differentiate().polynomial,log.polynomial),max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
log=Polynomial(FFT(self.differentiate().polynomial,log.polynomial),max_degree=self.max_degree,eps=self.eps,mod=self.mod)
log=log.integrate()
return log
def Newton(self,n0,f,differentiated_f=None):
newton=[n0]
while len(newton)<self.max_degree+1:
prev=newton
if differentiated_f==None:
newton=f(prev,self.polynomial)
else:
newton=f(prev)
for i in range(min(len(self.polynomial),len(newton))):
newton[i]-=self.polynomial[i]
newton[i]%=self.mod
if self.mod:
newton=NTT(newton,Polynomial(differentiated_f(prev),max_degree=len(newton)-1,eps=self.eps,mod=self.mod).inverse().polynomial)[:len(newton)]
else:
newton=FFT(newton,Polynomial(differentiated_f(prev),max_degree=len(newton)-1,eps=self.eps,mod=self.mod).inverse().polynomial)[:len(newton)]
for i in range(len(newton)):
newton[i]=-newton[i]
newton[i]%=self.mod
for i in range(len(prev)):
newton[i]+=prev[i]
newton[i]%=self.mod
newton=newton[:self.max_degree+1]
while newton and newton[-1]<=self.eps:
newton.pop()
return Polynomial(newton,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
def sqrt(self):
if self.polynomial:
for cnt0 in range(len(self.polynomial)):
if self.polynomial[cnt0]:
break
if cnt0%2:
sqrt=None
else:
if self.mod:
n0=Tonelli_Shanks(self.polynomial[cnt0],self.mod)
else:
if self.polynomial[cnt0]>=self.eps:
n0=self.polynomial[cnt0]**.5
if n0==None:
sqrt=None
else:
def f(prev):
if self.mod:
return NTT_Pow(prev,2)+[0]
else:
return FFT_Pow(prev,2)+[0]
def differentiated_f(prev):
retu=[0]*(2*len(prev)-1)
for i in range(len(prev)):
retu[i]+=2*prev[i]
if self.mod:
retu[i]%self.mod
return retu
sqrt=[0]*(cnt0//2)+Polynomial(self.polynomial[cnt0:],max_degree=self.max_degree-cnt0//2,mod=self.mod).Newton(n0,f,differentiated_f).polynomial
sqrt=Polynomial(sqrt,max_degree=self.max_degree,eps=self.eps,mod=self.mod)
else:
sqrt=Polynomial([],max_degree=self.max_degree,eps=self.eps,mod=self.mod)
return sqrt
def exp(self):
assert not self.polynomial or abs(self.polynomial[0])<=self.eps
def f(prev,poly):
newton=Polynomial(prev,max_degree=2*len(prev)-1,eps=self.eps,mod=self.mod).log().polynomial
newton+=[0]*(2*len(prev)-len(newton))
for i in range(min(len(poly),len(newton))):
newton[i]-=poly[i]
if self.mod:
for i in range(len(newton)):
newton[i]%=self.mod
if self.mod:
return NTT(prev,newton)[:2*len(prev)]
else:
return FFT(prev,newton)[:2*len(prev)]
return Polynomial(self.polynomial,max_degree=self.max_degree,mod=self.mod).Newton(1,f)
def Degree(self):
return len(self.polynomial)-1
def Hadamard(polynomial,n,mod=0,inverse=False):
polynomial_=[x for x in polynomial]+[0]*((1<<n)-len(polynomial))
for bit in range(n):
for i in range(1<<n):
ii=i^(1<<bit)
if i>ii:
continue
polynomial_[i],polynomial_[ii]=polynomial_[i]+polynomial_[ii],polynomial_[i]-polynomial_[ii]
if mod:
polynomial_[i]%=mod
polynomial_[ii]%=mod
if inverse:
if mod:
inve_2=pow((mod+1)//2,n)
for i in range(1<<n):
polynomial_[i]*=inve_2
polynomial_[i]%=mod
else:
pow_2=pow(2,n)
for i in range(1<<n):
polynomial_[i]/=pow_2
return polynomial_
def XOR_Convolution(polynomial0,polynomial1,mod=0):
n=(max(len(polynomial0),len(polynomial1))-1).bit_length()
Hadamard_polynomial0=Hadamard(polynomial0,n,mod=mod)
Hadamard_polynomial1=Hadamard(polynomial1,n,mod=mod)
if mod:
convolution=[x*y%mod for x,y in zip(Hadamard_polynomial0,Hadamard_polynomial1)]
else:
convolution=[x*y for x,y in zip(Hadamard_polynomial0,Hadamard_polynomial1)]
convolution=Hadamard(convolution,n,mod=mod,inverse=True)
return convolution
def Bostan_Mori(poly_nume,poly_deno,N,mod=0,convolve=None):
if type(poly_nume)==Polynomial:
poly_nume=poly_nume.polynomial
if type(poly_deno)==Polynomial:
poly_deno=poly_deno.polynomial
if convolve==None:
def convolve(poly_nume,poly_deno):
conv=[0]*(len(poly_nume)+len(poly_deno)-1)
for i in range(len(poly_nume)):
for j in range(len(poly_deno)):
x=poly_nume[i]*poly_deno[j]
if mod:
x%=mod
conv[i+j]+=x
if mod:
for i in range(len(conv)):
conv[i]%=mod
return conv
while N:
poly_deno_=[-x if i%2 else x for i,x in enumerate(poly_deno)]
if N%2:
poly_nume=convolve(poly_nume,poly_deno_)[1::2]
else:
poly_nume=convolve(poly_nume,poly_deno_)[::2]
poly_deno=convolve(poly_deno,poly_deno_)[::2]
if mod:
for i in range(len(poly_nume)):
poly_nume[i]%=mod
for i in range(len(poly_deno)):
poly_deno[i]%=mod
N//=2
return poly_nume[0]
#mod = 998244353
imag = 911660635
iimag = 86583718
rate2 = (911660635, 509520358, 369330050, 332049552, 983190778, 123842337, 238493703, 975955924, 603855026, 856644456, 131300601,
842657263, 730768835, 942482514, 806263778, 151565301, 510815449, 503497456, 743006876, 741047443, 56250497, 867605899)
irate2 = (86583718, 372528824, 373294451, 645684063, 112220581, 692852209, 155456985, 797128860, 90816748, 860285882, 927414960,
354738543, 109331171, 293255632, 535113200, 308540755, 121186627, 608385704, 438932459, 359477183, 824071951, 103369235)
rate3 = (372528824, 337190230, 454590761, 816400692, 578227951, 180142363, 83780245, 6597683, 70046822, 623238099,
183021267, 402682409, 631680428, 344509872, 689220186, 365017329, 774342554, 729444058, 102986190, 128751033, 395565204)
irate3 = (509520358, 929031873, 170256584, 839780419, 282974284, 395914482, 444904435, 72135471, 638914820, 66769500,
771127074, 985925487, 262319669, 262341272, 625870173, 768022760, 859816005, 914661783, 430819711, 272774365, 530924681)
def butterfly(a):
n = len(a)
h = (n - 1).bit_length()
len_ = 0
while len_ < h:
if h - len_ == 1:
p = 1 << (h - len_ - 1)
rot = 1
for s in range(1 << len_):
offset = s << (h - len_)
for i in range(p):
l = a[i + offset]
r = a[i + offset + p] * rot % mod
a[i + offset] = (l + r) % mod
a[i + offset + p] = (l - r) % mod
if s + 1 != 1 << len_:
rot *= rate2[(~s & -~s).bit_length() - 1]
rot %= mod
len_ += 1
else:
p = 1 << (h - len_ - 2)
rot = 1
for s in range(1 << len_):
rot2 = rot * rot % mod
rot3 = rot2 * rot % mod
offset = s << (h - len_)
for i in range(p):
a0 = a[i + offset]
a1 = a[i + offset + p] * rot
a2 = a[i + offset + p * 2] * rot2
a3 = a[i + offset + p * 3] * rot3
a1na3imag = (a1 - a3) % mod * imag
a[i + offset] = (a0 + a2 + a1 + a3) % mod
a[i + offset + p] = (a0 + a2 - a1 - a3) % mod
a[i + offset + p * 2] = (a0 - a2 + a1na3imag) % mod
a[i + offset + p * 3] = (a0 - a2 - a1na3imag) % mod
if s + 1 != 1 << len_:
rot *= rate3[(~s & -~s).bit_length() - 1]
rot %= mod
len_ += 2
def butterfly_inv(a):
n = len(a)
h = (n - 1).bit_length()
len_ = h
while len_:
if len_ == 1:
p = 1 << (h - len_)
irot = 1
for s in range(1 << (len_ - 1)):
offset = s << (h - len_ + 1)
for i in range(p):
l = a[i + offset]
r = a[i + offset + p]
a[i + offset] = (l + r) % mod
a[i + offset + p] = (l - r) * irot % mod
if s + 1 != (1 << (len_ - 1)):
irot *= irate2[(~s & -~s).bit_length() - 1]
irot %= mod
len_ -= 1
else:
p = 1 << (h - len_)
irot = 1
for s in range(1 << (len_ - 2)):
irot2 = irot * irot % mod
irot3 = irot2 * irot % mod
offset = s << (h - len_ + 2)
for i in range(p):
a0 = a[i + offset]
a1 = a[i + offset + p]
a2 = a[i + offset + p * 2]
a3 = a[i + offset + p * 3]
a2na3iimag = (a2 - a3) * iimag % mod
a[i + offset] = (a0 + a1 + a2 + a3) % mod
a[i + offset + p] = (a0 - a1 + a2na3iimag) * irot % mod
a[i + offset + p * 2] = (a0 + a1 - a2 - a3) * irot2 % mod
a[i + offset + p * 3] = (a0 - a1 - a2na3iimag) * irot3 % mod
if s + 1 != (1 << (len_ - 2)):
irot *= irate3[(~s & -~s).bit_length() - 1]
irot %= mod
len_ -= 2
def integrate(a):
a=a.copy()
n = len(a)
assert n > 0
a.pop()
a.insert(0, 0)
inv = [1, 1]
for i in range(2, n):
inv.append(-inv[mod%i] * (mod//i) % mod)
a[i] = a[i] * inv[i] % mod
return a
def differentiate(a):
n = len(a)
assert n > 0
for i in range(2, n):
a[i] = a[i] * i % mod
a.pop(0)
a.append(0)
return a
def convolution_naive(a, b):
n = len(a)
m = len(b)
ans = [0] * (n + m - 1)
if n < m:
for j in range(m):
for i in range(n):
ans[i + j] = (ans[i + j] + a[i] * b[j]) % mod
else:
for i in range(n):
for j in range(m):
ans[i + j] = (ans[i + j] + a[i] * b[j]) % mod
return ans
def convolution_ntt(a, b):
a = a.copy()
b = b.copy()
n = len(a)
m = len(b)
z = 1 << (n + m - 2).bit_length()
a += [0] * (z - n)
butterfly(a)
b += [0] * (z - m)
butterfly(b)
for i in range(z):
a[i] = a[i] * b[i] % mod
butterfly_inv(a)
a = a[:n + m - 1]
iz = pow(z, mod - 2, mod)
for i in range(n + m - 1):
a[i] = a[i] * iz % mod
return a
def convolution_square(a):
a = a.copy()
n = len(a)
z = 1 << (2 * n - 2).bit_length()
a += [0] * (z - n)
butterfly(a)
for i in range(z):
a[i] = a[i] * a[i] % mod
butterfly_inv(a)
a = a[:2 * n - 1]
iz = pow(z, mod - 2, mod)
for i in range(2 * n - 1):
a[i] = a[i] * iz % mod
return a
def convolution(a, b):
"""It calculates (+, x) convolution in mod 998244353.
Given two arrays a[0], a[1], ..., a[n - 1] and b[0], b[1], ..., b[m - 1],
it calculates the array c of length n + m - 1, defined by
> c[i] = sum(a[j] * b[i - j] for j in range(i + 1)) % 998244353.
It returns an empty list if at least one of a and b are empty.
Complexity
----------
> O(n log n), where n = len(a) + len(b).
"""
n = len(a)
m = len(b)
if n == 0 or m == 0:
return []
if min(n, m) <= 60:
return convolution_naive(a, b)
if a is b:
return convolution_square(a)
return convolution_ntt(a, b)
def inverse(a):
n = len(a)
assert n > 0 and a[0] != 0
res = [pow(a[0], mod - 2, mod)]
m = 1
while m < n:
f = a[:min(n,2*m)] + [0]*(2*m-min(n,2*m))
g = res + [0]*m
butterfly(f)
butterfly(g)
for i in range(2*m):
f[i] = f[i] * g[i] % mod
butterfly_inv(f)
f = f[m:] + [0]*m
butterfly(f)
for i in range(2*m):
f[i] = f[i] * g[i] % mod
butterfly_inv(f)
iz = pow(2*m, mod-2, mod)
iz = (-iz*iz) % mod
for i in range(m):
f[i] = f[i] * iz % mod
res += f[:m]
m <<= 1
return res[:n]
def log(a):
a = a.copy()
n = len(a)
assert n > 0 and a[0] == 1
a_inv = inverse(a)
a=differentiate(a)
a = convolution(a, a_inv)[:n]
a=integrate(a)
return a
def exp(a):
a = a.copy()
n = len(a)
assert n > 0 and a[0] == 0
g = [1]
a[0] = 1
h_drv = a.copy()
h_drv=differentiate(h_drv)
m = 1
while m < n:
f_fft = a[:m] + [0] * m
butterfly(f_fft)
if m > 1:
_f = [f_fft[i] * g_fft[i] % mod for i in range(m)]
butterfly_inv(_f)
_f = _f[m // 2:] + [0] * (m // 2)
butterfly(_f)
for i in range(m):
_f[i] = _f[i] * g_fft[i] % mod
butterfly_inv(_f)
_f = _f[:m//2]
iz = pow(m, mod - 2, mod)
iz *= -iz
iz %= mod
for i in range(m//2):
_f[i] = _f[i] * iz % mod
g.extend(_f)
t = a[:m]
t=differentiate(t)
r = h_drv[:m - 1]
r.append(0)
butterfly(r)
for i in range(m):
r[i] = r[i] * f_fft[i] % mod
butterfly_inv(r)
im = pow(-m, mod - 2, mod)
for i in range(m):
r[i] = r[i] * im % mod
for i in range(m):
t[i] = (t[i] + r[i]) % mod
t = [t[-1]] + t[:-1]
t += [0] * m
butterfly(t)
g_fft = g + [0] * (2 * m - len(g))
butterfly(g_fft)
for i in range(2 * m):
t[i] = t[i] * g_fft[i] % mod
butterfly_inv(t)
t = t[:m]
i2m = pow(2 * m, mod - 2, mod)
for i in range(m):
t[i] = t[i] * i2m % mod
v = a[m:min(n, 2 * m)]
v += [0] * (m - len(v))
t = [0] * (m - 1) + t + [0]
t=integrate(t)
for i in range(m):
v[i] = (v[i] - t[m + i]) % mod
v += [0] * m
butterfly(v)
for i in range(2 * m):
v[i] = v[i] * f_fft[i] % mod
butterfly_inv(v)
v = v[:m]
i2m = pow(2 * m, mod - 2, mod)
for i in range(m):
v[i] = v[i] * i2m % mod
for i in range(min(n - m, m)):
a[m + i] = v[i]
m *= 2
return a
def power(a,k):
n = len(a)
assert n>0
if k==0:
return [1]+[0]*(n-1)
l = 0
while l < len(a) and not a[l]:
l += 1
if l * k >= n:
return [0] * n
ic = pow(a[l], mod - 2, mod)
pc = pow(a[l], k, mod)
a = log([a[i] * ic % mod for i in range(l, len(a))])
for i in range(len(a)):
a[i] = a[i] * k % mod
a = exp(a)
for i in range(len(a)):
a[i] = a[i] * pc % mod
a = [0] * (l * k) + a[:n - l * k]
return a
def sqrt(a):
if len(a) == 0:
return []
if a[0] == 0:
for d in range(1, len(a)):
if a[d]:
if d & 1:
return None
if len(a) - 1 < d // 2:
break
res=sqrt(a[d:]+[0]*(d//2))
if res == None:
return None
res = [0]*(d//2)+res
return res
return [0]*len(a)
sqr = Tonelli_Shanks(a[0],mod)
if sqr == None:
return None
T = [0] * (len(a))
T[0] = sqr
res = T.copy()
T[0] = pow(sqr,mod-2,mod) #T:res^{-1}
m = 1
two_inv = (mod + 1) // 2
F = [sqr]
while m <= len(a) - 1:
for i in range(m):
F[i] *= F[i]
F[i] %= mod
butterfly_inv(F)
iz = pow(m, mod-2, mod)
for i in range(m):
F[i] = F[i] * iz % mod
delta = [0] * (2 * m)
for i in range(m):
delta[i + m] = F[i] - a[i] - (a[i + m] if i+m<len(a) else 0)
butterfly(delta)
G = [0] * (2 * m)
for i in range(m):
G[i] = T[i]
butterfly(G)
for i in range(2 * m):
delta[i] *= G[i]
delta[i] %= mod
butterfly_inv(delta)
iz = pow(2*m, mod-2, mod)
for i in range(2*m):
delta[i] = delta[i] * iz % mod
for i in range(m, min(2 * m, len(a))):
res[i] = -delta[i] * two_inv%mod
res[i]%=mod
if 2 * m > len(a) - 1:
break
F = res[:2 * m]
butterfly(F)
eps = [F[i] * G[i] % mod for i in range(2 * m)]
butterfly_inv(eps)
for i in range(m):
eps[i] = 0
iz = pow(2*m, mod-2, mod)
for i in range(m,2*m):
eps[i] = eps[i] * iz % mod
butterfly(eps)
for i in range(2 * m):
eps[i] *= G[i]
eps[i] %= mod
butterfly_inv(eps)
for i in range(m, 2 * m):
T[i] = -eps[i]*iz
T[i]%=mod
iz = iz*iz % mod
m <<= 1
return res
def taylor_shift(a,c):
a=a.copy()
n=len(a)
MD=MOD(mod)
MD.Build_Fact(n-1)
for i in range(n):
a[i]*=MD.Fact(i)
a[i]%=mod
C=[1]
for i in range(1,n):
C.append(C[-1]*c%mod)
for i in range(n):
C[i]*=MD.Fact_Inve(i)
C[i]%=mod
a=convolution(a,C[::-1])[n-1:]
for i in range(n):
a[i]*=MD.Fact_Inve(i)
a[i]%=mod
return a
def division_modulus(f,g):
n=len(f)
m=len(g)
while m and g[m-1]==0:
m-=1
assert m
if n>=m:
fR=f[::-1][:n-m+1]
gR=g[:m][::-1][:n-m+1]+[0]*max(0,n-m+1-m)
qR=convolution(fR,inverse(gR))[:n-m+1]
q=qR[::-1]
r=[(f[i]-x)%mod for i,x in enumerate(convolution(g,q)[:m-1])]
while r and r[-1]==0:
r.pop()
else:
q,r=[],f.copy()
return q,r
def multipoint_evaluation(f, x):
n = len(x)
sz = 1 << (n - 1).bit_length()
g = [[1] for _ in range(2 * sz)]
for i in range(n):
g[i + sz] = [-x[i], 1]
for i in range(1, sz)[::-1]:
g[i] = convolution(g[2 * i],g[2 * i + 1])
g[1] =division_modulus(f,g[1])[1]
for i in range(2, 2 * sz):
g[i]=division_modulus(g[i>>1],g[i])[1]
res = [g[i + sz][0] if g[i+sz] else 0 for i in range(n)]
return res
N,A=map(int,readline().split())
mod=998244353
MD=MOD(mod)
MD.Build_Fact(N)
f=[1]
for i in range(1,N+1):
f.append(f[i-1]*(A-i+1)%mod)
for i in range(N+1):
f[i]*=MD.Fact_Inve(i)
f[i]%=mod
ans_lst=[None]*N
ans_lst[0]=A%mod
def solve(l,r,poly):
if l==r:
return [1]
if l+1==r:
ans_lst[l-1]=poly[0]
return [1,ans_lst[l-1]]
mid=(l+r)//2
P=solve(l,mid,poly[:mid-l])
P=convolution(P,solve(mid,r,convolution(poly,P)[mid-l:r-l]))
return P
solve(2,N+1,f[2:N+1])
ans=ans_lst[N-1]
print(ans) | ConDefects/ConDefects/Code/abc281_h/Python/41260093 |
condefects-python_data_484 | from collections import deque
class Dinic:
def __init__(self, n):
self.n = n
self.links = [[] for _ in range(n)]
self.depth = None
self.progress = None
def add_link(self, _from, to, cap):
self.links[_from].append([cap, to, len(self.links[to])])
self.links[to].append([0, _from, len(self.links[_from]) - 1])
def bfs(self, s):
depth = [-1] * self.n
depth[s] = 0
q = deque([s])
while q:
v = q.popleft()
for cap, to, rev in self.links[v]:
if cap > 0 and depth[to] < 0:
depth[to] = depth[v] + 1
q.append(to)
self.depth = depth
def dfs(self, v, t, flow):
if v == t:
return flow
links_v = self.links[v]
for i in range(self.progress[v], len(links_v)):
self.progress[v] = i
cap, to, rev = link = links_v[i]
if cap == 0 or self.depth[v] >= self.depth[to]:
continue
d = self.dfs(to, t, min(flow, cap))
if d == 0:
continue
link[0] -= d
self.links[to][rev][0] += d
return d
return 0
def max_flow(self, s, t):
flow = 0
while True:
self.bfs(s)
if self.depth[t] < 0:
return flow
self.progress = [0] * self.n
current_flow = self.dfs(s, t, float('inf'))
while current_flow > 0:
flow += current_flow
current_flow = self.dfs(s, t, float('inf'))
N,M=map(int,input().split())
win=[0]*(N+1)
lose=[0]*(N+1)
used={}
for i in range(M):
a,b=map(int,input().split())
win[a]+=1
lose[b]+=1
if a>b:
a,b=b,a
used[a*N+b]=1
x=max(win)
result=[]
count=N*(N-1)//2-M
z=sum(win)
for i in range(1,N+1):
rest=N-1-win[i]-lose[i]
y=win[i]+rest
x=0
for j in range(1,N+1):
if j==i:
continue
x=max(x,win[j])
if y<=x:
continue
r=N**2
Z=Dinic(r+N+2)
e=0
for p in range(1,N):
for q in range(i+1,N+1):
if p==i or q==i:
continue
if p*N+q in used:
continue
Z.add_link(0,p*N+q,1)
e+=1
Z.add_link(p*N+q,r+p,1)
Z.add_link(p*N+q,r+q,1)
for p in range(1,N+1):
Z.add_link(r+p,r+N+1,y-1-win[p])
c=Z.max_flow(0,r+N+1)
if c==e:
result.append(i)
print(*result)
from collections import deque
class Dinic:
def __init__(self, n):
self.n = n
self.links = [[] for _ in range(n)]
self.depth = None
self.progress = None
def add_link(self, _from, to, cap):
self.links[_from].append([cap, to, len(self.links[to])])
self.links[to].append([0, _from, len(self.links[_from]) - 1])
def bfs(self, s):
depth = [-1] * self.n
depth[s] = 0
q = deque([s])
while q:
v = q.popleft()
for cap, to, rev in self.links[v]:
if cap > 0 and depth[to] < 0:
depth[to] = depth[v] + 1
q.append(to)
self.depth = depth
def dfs(self, v, t, flow):
if v == t:
return flow
links_v = self.links[v]
for i in range(self.progress[v], len(links_v)):
self.progress[v] = i
cap, to, rev = link = links_v[i]
if cap == 0 or self.depth[v] >= self.depth[to]:
continue
d = self.dfs(to, t, min(flow, cap))
if d == 0:
continue
link[0] -= d
self.links[to][rev][0] += d
return d
return 0
def max_flow(self, s, t):
flow = 0
while True:
self.bfs(s)
if self.depth[t] < 0:
return flow
self.progress = [0] * self.n
current_flow = self.dfs(s, t, float('inf'))
while current_flow > 0:
flow += current_flow
current_flow = self.dfs(s, t, float('inf'))
N,M=map(int,input().split())
win=[0]*(N+1)
lose=[0]*(N+1)
used={}
for i in range(M):
a,b=map(int,input().split())
win[a]+=1
lose[b]+=1
if a>b:
a,b=b,a
used[a*N+b]=1
x=max(win)
result=[]
count=N*(N-1)//2-M
z=sum(win)
for i in range(1,N+1):
rest=N-1-win[i]-lose[i]
y=win[i]+rest
x=0
for j in range(1,N+1):
if j==i:
continue
x=max(x,win[j])
if y<=x:
continue
r=N**2
Z=Dinic(r+N+2)
e=0
for p in range(1,N):
for q in range(p+1,N+1):
if p==i or q==i:
continue
if p*N+q in used:
continue
Z.add_link(0,p*N+q,1)
e+=1
Z.add_link(p*N+q,r+p,1)
Z.add_link(p*N+q,r+q,1)
for p in range(1,N+1):
Z.add_link(r+p,r+N+1,y-1-win[p])
c=Z.max_flow(0,r+N+1)
if c==e:
result.append(i)
print(*result) | ConDefects/ConDefects/Code/abc241_g/Python/46189922 |
condefects-python_data_485 | s = '??????????????(????????(??????)?????????(?(??)'
n = len(s)
mod = 998244353
dp = [[0 for i in range(3001)] for i in range(3000)]
if s[0] == ')':
print(0)
else:
dp[0][1] = 1
for i in range(1,n):
for j in range(i+2):
if s[i] == '(':
if j-1 >= 0:
dp[i][j] = dp[i-1][j-1]
elif s[i] == ')':
if j+1 <= i:
dp[i][j] = dp[i-1][j+1]
else:
if j-1 >= 0:
dp[i][j] = dp[i-1][j-1]
if j+1 <= i:
dp[i][j] = (dp[i][j] + dp[i-1][j+1])%mod
print(dp[n-1][0])
s = input()
n = len(s)
mod = 998244353
dp = [[0 for i in range(3001)] for i in range(3000)]
if s[0] == ')':
print(0)
else:
dp[0][1] = 1
for i in range(1,n):
for j in range(i+2):
if s[i] == '(':
if j-1 >= 0:
dp[i][j] = dp[i-1][j-1]
elif s[i] == ')':
if j+1 <= i:
dp[i][j] = dp[i-1][j+1]
else:
if j-1 >= 0:
dp[i][j] = dp[i-1][j-1]
if j+1 <= i:
dp[i][j] = (dp[i][j] + dp[i-1][j+1])%mod
print(dp[n-1][0]) | ConDefects/ConDefects/Code/abc312_d/Python/54754384 |
condefects-python_data_486 | # D - Count Bracket Sequences
import math
def main():
S = input()
n = len(S)
dp = [[0] * (n+1) for _ in range(n+1)]
dp[0][0] = 1
mod = 998244353
for i in range(n):
for j in range(i+1):
half = math.ceil((i+1)/2)
if S[i] == '(' or S[i] == '?':
if j+1 >= half:
dp[i+1][j+1] += dp[i][j]
dp[i+1][j+1] %= mod
if S[i] == '' or S[i] == '?':
if j >= half:
dp[i+1][j] += dp[i][j]
dp[i+1][j] %= mod
if n % 2 == 0:
print(dp[n][n//2])
else:
print(0)
if __name__ == '__main__':
main()
# D - Count Bracket Sequences
import math
def main():
S = input()
n = len(S)
dp = [[0] * (n+1) for _ in range(n+1)]
dp[0][0] = 1
mod = 998244353
for i in range(n):
for j in range(i+1):
half = math.ceil((i+1)/2)
if S[i] == '(' or S[i] == '?':
if j+1 >= half:
dp[i+1][j+1] += dp[i][j]
dp[i+1][j+1] %= mod
if S[i] == ')' or S[i] == '?':
if j >= half:
dp[i+1][j] += dp[i][j]
dp[i+1][j] %= mod
if n % 2 == 0:
print(dp[n][n//2])
else:
print(0)
if __name__ == '__main__':
main() | ConDefects/ConDefects/Code/abc312_d/Python/52032093 |
condefects-python_data_487 | #!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def solve(a):
a1 = []
n1 = len(a)
for i in range(1, n1):
a1.append(a[0] ^ a[i])
basis = []
for elem in a1:
elemcpy = elem
for elem2 in basis:
if elemcpy ^ elem2 < elemcpy:
elemcpy = elemcpy ^ elem2
if elemcpy != 0:
basis.append(elemcpy)
basis.sort(reverse=True)
maxx = 0
for elem in basis:
if elem ^ maxx > maxx:
maxx = elem ^ maxx
return maxx
def main():
n = int(input())
a = list(map(int,input().split()))
maxx = 0
if n % 2 == 0 and n % 4 == 2:
for i in range(n):
b = []
for j in range(n):
if j != i:
b.append(a[j])
maxx = max(solve(b), maxx)
else:
maxx = solve(a)
print(maxx)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def solve(a):
a1 = []
n1 = len(a)
for i in range(1, n1):
a1.append(a[0] ^ a[i])
basis = []
for elem in a1:
elemcpy = elem
for elem2 in basis:
if elemcpy ^ elem2 < elemcpy:
elemcpy = elemcpy ^ elem2
if elemcpy != 0:
basis.append(elemcpy)
basis.sort(reverse=True)
maxx = 0
for elem in basis:
if elem ^ maxx > maxx:
maxx = elem ^ maxx
return maxx
def main():
n = int(input())
a = list(map(int,input().split()))
maxx = 0
if n % 2 == 0 and n % 4 == 2 and n != 2:
for i in range(n):
b = []
for j in range(n):
if j != i:
b.append(a[j])
maxx = max(solve(b), maxx)
else:
maxx = solve(a)
print(maxx)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main() | ConDefects/ConDefects/Code/arc173_e/Python/51134374 |
condefects-python_data_488 | import bisect
import copy
import decimal
import fractions
import heapq
import itertools
import math
import random
import sys
import time
from collections import Counter,deque,defaultdict
from functools import lru_cache,reduce
from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max
def _heappush_max(heap,item):
heap.append(item)
heapq._siftdown_max(heap, 0, len(heap)-1)
def _heappushpop_max(heap, item):
if heap and item < heap[0]:
item, heap[0] = heap[0], item
heapq._siftup_max(heap, 0)
return item
from math import gcd as GCD
read=sys.stdin.read
readline=sys.stdin.readline
readlines=sys.stdin.readlines
write=sys.stdout.write
#import pypyjit
#pypyjit.set_param('max_unroll_recursion=-1')
#sys.set_int_max_str_digits(10**9)
def XOR_Basis(lst):
xor_basis=[]
triangulation=[]
for i,x in enumerate(lst):
xx=x
for j,xb in enumerate(triangulation):
if xx>xx^xb:
xx=xx^xb
if xx:
xor_basis.append(x)
for j in range(len(triangulation)):
if triangulation[j]^xx<triangulation[j]:
triangulation[j]^=xx
triangulation.append(xx)
return xor_basis,triangulation
N=int(input())
A=list(map(int,input().split()))
ans=0
if N==2:
print(A[0]^A[1])
exit()
B=62
for i in range(N):
A[i]|=1<<B
_,tria=XOR_Basis(A)
tria.sort()
b=tria.pop()^1<<B
xor=0
for x in tria[::-1]:
xor=max(xor,xor^x)
if N%4==2:
a=0
for i in range(N):
a^=A[i]
if a==xor and tria and len(tria)==N-1:
xor^=tria[-1]
ans=max(ans,xor)
print(ans)
import bisect
import copy
import decimal
import fractions
import heapq
import itertools
import math
import random
import sys
import time
from collections import Counter,deque,defaultdict
from functools import lru_cache,reduce
from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max
def _heappush_max(heap,item):
heap.append(item)
heapq._siftdown_max(heap, 0, len(heap)-1)
def _heappushpop_max(heap, item):
if heap and item < heap[0]:
item, heap[0] = heap[0], item
heapq._siftup_max(heap, 0)
return item
from math import gcd as GCD
read=sys.stdin.read
readline=sys.stdin.readline
readlines=sys.stdin.readlines
write=sys.stdout.write
#import pypyjit
#pypyjit.set_param('max_unroll_recursion=-1')
#sys.set_int_max_str_digits(10**9)
def XOR_Basis(lst):
xor_basis=[]
triangulation=[]
for i,x in enumerate(lst):
xx=x
for j,xb in enumerate(triangulation):
if xx>xx^xb:
xx=xx^xb
if xx:
xor_basis.append(x)
for j in range(len(triangulation)):
if triangulation[j]^xx<triangulation[j]:
triangulation[j]^=xx
triangulation.append(xx)
return xor_basis,triangulation
N=int(input())
A=list(map(int,input().split()))
ans=0
if N==2:
print(A[0]^A[1])
exit()
B=62
for i in range(N):
A[i]|=1<<B
_,tria=XOR_Basis(A)
tria.sort()
b=tria.pop()^1<<B
xor=0
for x in tria[::-1]:
xor=max(xor,xor^x)
if N%4==2:
a=0
for i in range(N):
a^=A[i]
if a==xor and tria and len(tria)==N-1:
xor^=tria[0]
ans=max(ans,xor)
print(ans) | ConDefects/ConDefects/Code/arc173_e/Python/51138423 |
condefects-python_data_489 | N,T,M=map(int,input().split())
#たかだか10人しかいません
hate=set()
for _ in range(M):
a,b=map(int,input().split())
hate.add((a,b))
hate.add((b,a))
def f(now):
if now==N:
#nowをNから波及させていくが、そのとき、ちゃんとteamsがTになっていれば1を返すようにする。
return 1 if len(teams)==T else 0
ans=0
for i in range(len(teams)):
if len(teams[i])>0:
for t in teams[i]:
if (now,t) in hate:
#相性悪い人がいる場合
break
else:
#いない場合
teams[i].add(now)
ans+=f(now+1)
teams[i].remove(now)
if len(teams)<T:
teams.append(set([now]))
ans+=f(now+1)
teams.pop()
return ans
teams=[]
print(f(0))
N,T,M=map(int,input().split())
#たかだか10人しかいません
hate=set()
for _ in range(M):
a,b=map(lambda x:int(x)-1,input().split())
hate.add((a,b))
hate.add((b,a))
def f(now):
if now==N:
#nowをNから波及させていくが、そのとき、ちゃんとteamsがTになっていれば1を返すようにする。
return 1 if len(teams)==T else 0
ans=0
for i in range(len(teams)):
if len(teams[i])>0:
for t in teams[i]:
if (now,t) in hate:
#相性悪い人がいる場合
break
else:
#いない場合
teams[i].add(now)
ans+=f(now+1)
teams[i].remove(now)
if len(teams)<T:
teams.append(set([now]))
ans+=f(now+1)
teams.pop()
return ans
teams=[]
print(f(0)) | ConDefects/ConDefects/Code/abc310_d/Python/53176077 |
condefects-python_data_490 | # import
import sys
import itertools
import bisect
import math
from collections import *
from pprint import pprint
from functools import cache
import heapq
# alias
DD = defaultdict
BSL = bisect.bisect_left
BSR = bisect.bisect_right
# config
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
# input template
def II(): return int(input())
def IS(): return input()[:-1]
def MI(): return map(int,input().split())
def LM(): return list(MI())
def LL(n): return [LM() for _ in range(n)]
def LS(n,remove_br=False): return [list(input())[:-1] if remove_br else list(input()) for _ in range(n)]
def MI_1(): return map(lambda x:int(x)-1,input().split())
def LM_1(): return list(MI_1())
def LL_1(n): return [LM_1() for _ in range(n)]
# functions
def bit_count(num):
length = num.bit_length()
res = 0
for i in range(length):
if num >> i & 1:
res += 1
return res
def DB(*x):
global DEBUG_MODE
if DEBUG_MODE: print(*x)
def expand_table(table, h_mag, w_mag):
#引数の二次元配列などをタイルのように繰り替えしたものを返す.
res = []
for row in table:
res.append(row*w_mag)
return res*h_mag
def safe_sqrt(N):
#[平方根]の誤差が怖いとき用.
rough = int(N**0.5)
left = rough - 10
right = rough + 10
while left != right:
mid = (left+right+1)//2
if mid**2 <= N:
left = mid
else:
right = mid - 1
return left
def sigma_LinearFunc(bound_included1, bound_included2, coeff1, coeff0):
"""
coeff1*x + coeff0
の x = [left, right] の和を求める.
"""
left = min(bound_included1, bound_included2)
right = max(bound_included1, bound_included2)
return coeff0*(right-left+1) + coeff1*(left+right)*(right-left+1)//2
def find_divisors(n):
divisors_small = []
divisors_big = []
i = 1
while i * i <= n:
if n % i == 0:
divisors_small.append(i)
# iと一致しない場合、n/iも約数
if i != n // i:
divisors_big.append(n // i)
i += 1
return divisors_small + divisors_big[::-1]
#classes
"""
・使い方
s=SortedSet() : 引数にイテラブル渡せる.
s.a: SortedSetの中身を返す。
len(s), x in s, x not in s: リストと同じ要領で使える。
s.add(x): xを追加してTrueを返す。ただしxがすでにs内にある場合、xは追加せずにFalseを返す。
s.discard(x): xを削除してTrueを返す。ただしxがs内にない場合、何もせずにFalseを返す。
s.lt(x): xより小さい最大の要素を返す。もし存在しないなら、Noneを返す。
s.le(x): x 以下の 最大の要素を返す。もし存在しないなら、Noneを返す。
s.gt(x): xより大きい最小の要素を返す。もし存在しないなら、Noneを返す。
s.ge(x): x 以上の 最小の要素を返す。もし存在しないなら、Noneを返す。
s.index(x): xより小さい要素の数を返す。
s.index_right(x): x以下の要素の数を返す。
"""
# https://github.com/tatyam-prime/SortedSet/blob/main/SortedSet.py
import math
from bisect import bisect_left, bisect_right
from typing import Generic, Iterable, Iterator, List, Tuple, TypeVar, Optional
T = TypeVar('T')
class SortedSet(Generic[T]):
BUCKET_RATIO = 16
SPLIT_RATIO = 24
def __init__(self, a: Iterable[T] = []) -> None:
"Make a new SortedSet from iterable. / O(N) if sorted and unique / O(N log N)"
a = list(a)
n = self.size = len(a)
if any(a[i] > a[i + 1] for i in range(n - 1)):
a.sort()
if any(a[i] >= a[i + 1] for i in range(n - 1)):
a, b = [], a
for x in b:
if not a or a[-1] != x:
a.append(x)
bucket_size = int(math.ceil(math.sqrt(n / self.BUCKET_RATIO)))
self.a = [a[n * i // bucket_size : n * (i + 1) // bucket_size] for i in range(bucket_size)]
def __iter__(self) -> Iterator[T]:
for i in self.a:
for j in i: yield j
def __reversed__(self) -> Iterator[T]:
for i in reversed(self.a):
for j in reversed(i): yield j
def __eq__(self, other) -> bool:
return list(self) == list(other)
def __len__(self) -> int:
return self.size
def __repr__(self) -> str:
return "SortedSet" + str(self.a)
def __str__(self) -> str:
s = str(list(self))
return "{" + s[1 : len(s) - 1] + "}"
def _position(self, x: T) -> Tuple[List[T], int, int]:
"return the bucket, index of the bucket and position in which x should be. self must not be empty."
for i, a in enumerate(self.a):
if x <= a[-1]: break
return (a, i, bisect_left(a, x))
def __contains__(self, x: T) -> bool:
if self.size == 0: return False
a, _, i = self._position(x)
return i != len(a) and a[i] == x
def add(self, x: T) -> bool:
"Add an element and return True if added. / O(√N)"
if self.size == 0:
self.a = [[x]]
self.size = 1
return True
a, b, i = self._position(x)
if i != len(a) and a[i] == x: return False
a.insert(i, x)
self.size += 1
if len(a) > len(self.a) * self.SPLIT_RATIO:
mid = len(a) >> 1
self.a[b:b+1] = [a[:mid], a[mid:]]
return True
def _pop(self, a: List[T], b: int, i: int) -> T:
ans = a.pop(i)
self.size -= 1
if not a: del self.a[b]
return ans
def discard(self, x: T) -> bool:
"Remove an element and return True if removed. / O(√N)"
if self.size == 0: return False
a, b, i = self._position(x)
if i == len(a) or a[i] != x: return False
self._pop(a, b, i)
return True
def lt(self, x: T) -> Optional[T]:
"Find the largest element < x, or None if it doesn't exist."
for a in reversed(self.a):
if a[0] < x:
return a[bisect_left(a, x) - 1]
def le(self, x: T) -> Optional[T]:
"Find the largest element <= x, or None if it doesn't exist."
for a in reversed(self.a):
if a[0] <= x:
return a[bisect_right(a, x) - 1]
def gt(self, x: T) -> Optional[T]:
"Find the smallest element > x, or None if it doesn't exist."
for a in self.a:
if a[-1] > x:
return a[bisect_right(a, x)]
def ge(self, x: T) -> Optional[T]:
"Find the smallest element >= x, or None if it doesn't exist."
for a in self.a:
if a[-1] >= x:
return a[bisect_left(a, x)]
def __getitem__(self, i: int) -> T:
"Return the i-th element."
if i < 0:
for a in reversed(self.a):
i += len(a)
if i >= 0: return a[i]
else:
for a in self.a:
if i < len(a): return a[i]
i -= len(a)
raise IndexError
def pop(self, i: int = -1) -> T:
"Pop and return the i-th element."
if i < 0:
for b, a in enumerate(reversed(self.a)):
i += len(a)
if i >= 0: return self._pop(a, ~b, i)
else:
for b, a in enumerate(self.a):
if i < len(a): return self._pop(a, b, i)
i -= len(a)
raise IndexError
def index(self, x: T) -> int:
"Count the number of elements < x."
ans = 0
for a in self.a:
if a[-1] >= x:
return ans + bisect_left(a, x)
ans += len(a)
return ans
def index_right(self, x: T) -> int:
"Count the number of elements <= x."
ans = 0
for a in self.a:
if a[-1] > x:
return ans + bisect_right(a, x)
ans += len(a)
return ans
"""
個数付きなSortedSetがほしいとき.
(num, cnt)を要素としたSSを管理すると良い場合がある.
その時、numを一個追加、一個消去、存在判定が大変なので,
メソッド化した.
"""
def exist(self, x):
ret = self.gt((x,0))
if ret is None:
return False
elif ret[0] == x:
return True
else:
return False
def increment(self, x):
if not self.exist(x):
self.add((x,1))
else:
num, cnt = self.gt((x,0))
self.discard((x,cnt))
self.add((x,cnt+1))
def decrement(self, x):
num, cnt = self.gt((x,0))
if cnt == 1:
self.discard((x,cnt))
else:
self.discard((x,cnt))
self.add((x,cnt-1))
# well-used const
# clockwise from top.
DIRECTION_4 = [[-1,0],[0,1],[1,0],[0,-1]]
DIRECTION_8 = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]]
DIRECTION_URDL_TABLE = {'U':(-1,0), 'R':(0,1), 'D':(1,0), 'L':(0,-1)}
DIRECTION_URDL_COORD_PLANE = {'U':(0,1), 'R':(1,0), 'D':(0,-1), 'L':(-1,0)}
MOD = 998244353
INF = float("inf")
LOWER_ALPS = "abcdefghijklmnopqrstuvwxyz"
UPPER_ALPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ALL_ALPS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
# user config
############
DEBUG_MODE=0
############
import copy
N, T, M = MI()
AB = LL_1(M)
fbdn_set = set()
for a,b in AB:
fbdn_set.add((a,b))
avail = [set(range(N)) for _ in range(N)]
for i in range(N):
avail[i].discard(i)
for a,b in AB:
avail[a].discard(b)
avail[b].discard(a)
DB(avail)
def rec(v, rest, cnt):
global T, ans
DB(v, rest, cnt)
if not rest and cnt < T:
return
if cnt == T:
if not rest:
ans += 1
return
if v == N:
return
if v not in rest:
rec(v+1, rest, cnt)
return
rest.discard(v)
S = rest & avail[v]
S_arr = list(S)
L = len(S)
for bit in range(2**L):
flg = False
for i in range(L):
for j in range(i+1,L):
if bit >> i & 1 and bit >> j & 1 and (int(S_arr[i]), int(S_arr[j])) in fbdn_set:
flg = True
break
else:
continue
break
if flg:
continue
rest_copy = copy.copy(rest)
for i in range(L):
if bit >> i & 1:
rest_copy.discard(S_arr[i])
rec(v+1, rest_copy, cnt+1)
ans = 0
rec(0, set(range(N)), 0)
print(ans)
# import
import sys
import itertools
import bisect
import math
from collections import *
from pprint import pprint
from functools import cache
import heapq
# alias
DD = defaultdict
BSL = bisect.bisect_left
BSR = bisect.bisect_right
# config
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
# input template
def II(): return int(input())
def IS(): return input()[:-1]
def MI(): return map(int,input().split())
def LM(): return list(MI())
def LL(n): return [LM() for _ in range(n)]
def LS(n,remove_br=False): return [list(input())[:-1] if remove_br else list(input()) for _ in range(n)]
def MI_1(): return map(lambda x:int(x)-1,input().split())
def LM_1(): return list(MI_1())
def LL_1(n): return [LM_1() for _ in range(n)]
# functions
def bit_count(num):
length = num.bit_length()
res = 0
for i in range(length):
if num >> i & 1:
res += 1
return res
def DB(*x):
global DEBUG_MODE
if DEBUG_MODE: print(*x)
def expand_table(table, h_mag, w_mag):
#引数の二次元配列などをタイルのように繰り替えしたものを返す.
res = []
for row in table:
res.append(row*w_mag)
return res*h_mag
def safe_sqrt(N):
#[平方根]の誤差が怖いとき用.
rough = int(N**0.5)
left = rough - 10
right = rough + 10
while left != right:
mid = (left+right+1)//2
if mid**2 <= N:
left = mid
else:
right = mid - 1
return left
def sigma_LinearFunc(bound_included1, bound_included2, coeff1, coeff0):
"""
coeff1*x + coeff0
の x = [left, right] の和を求める.
"""
left = min(bound_included1, bound_included2)
right = max(bound_included1, bound_included2)
return coeff0*(right-left+1) + coeff1*(left+right)*(right-left+1)//2
def find_divisors(n):
divisors_small = []
divisors_big = []
i = 1
while i * i <= n:
if n % i == 0:
divisors_small.append(i)
# iと一致しない場合、n/iも約数
if i != n // i:
divisors_big.append(n // i)
i += 1
return divisors_small + divisors_big[::-1]
#classes
"""
・使い方
s=SortedSet() : 引数にイテラブル渡せる.
s.a: SortedSetの中身を返す。
len(s), x in s, x not in s: リストと同じ要領で使える。
s.add(x): xを追加してTrueを返す。ただしxがすでにs内にある場合、xは追加せずにFalseを返す。
s.discard(x): xを削除してTrueを返す。ただしxがs内にない場合、何もせずにFalseを返す。
s.lt(x): xより小さい最大の要素を返す。もし存在しないなら、Noneを返す。
s.le(x): x 以下の 最大の要素を返す。もし存在しないなら、Noneを返す。
s.gt(x): xより大きい最小の要素を返す。もし存在しないなら、Noneを返す。
s.ge(x): x 以上の 最小の要素を返す。もし存在しないなら、Noneを返す。
s.index(x): xより小さい要素の数を返す。
s.index_right(x): x以下の要素の数を返す。
"""
# https://github.com/tatyam-prime/SortedSet/blob/main/SortedSet.py
import math
from bisect import bisect_left, bisect_right
from typing import Generic, Iterable, Iterator, List, Tuple, TypeVar, Optional
T = TypeVar('T')
class SortedSet(Generic[T]):
BUCKET_RATIO = 16
SPLIT_RATIO = 24
def __init__(self, a: Iterable[T] = []) -> None:
"Make a new SortedSet from iterable. / O(N) if sorted and unique / O(N log N)"
a = list(a)
n = self.size = len(a)
if any(a[i] > a[i + 1] for i in range(n - 1)):
a.sort()
if any(a[i] >= a[i + 1] for i in range(n - 1)):
a, b = [], a
for x in b:
if not a or a[-1] != x:
a.append(x)
bucket_size = int(math.ceil(math.sqrt(n / self.BUCKET_RATIO)))
self.a = [a[n * i // bucket_size : n * (i + 1) // bucket_size] for i in range(bucket_size)]
def __iter__(self) -> Iterator[T]:
for i in self.a:
for j in i: yield j
def __reversed__(self) -> Iterator[T]:
for i in reversed(self.a):
for j in reversed(i): yield j
def __eq__(self, other) -> bool:
return list(self) == list(other)
def __len__(self) -> int:
return self.size
def __repr__(self) -> str:
return "SortedSet" + str(self.a)
def __str__(self) -> str:
s = str(list(self))
return "{" + s[1 : len(s) - 1] + "}"
def _position(self, x: T) -> Tuple[List[T], int, int]:
"return the bucket, index of the bucket and position in which x should be. self must not be empty."
for i, a in enumerate(self.a):
if x <= a[-1]: break
return (a, i, bisect_left(a, x))
def __contains__(self, x: T) -> bool:
if self.size == 0: return False
a, _, i = self._position(x)
return i != len(a) and a[i] == x
def add(self, x: T) -> bool:
"Add an element and return True if added. / O(√N)"
if self.size == 0:
self.a = [[x]]
self.size = 1
return True
a, b, i = self._position(x)
if i != len(a) and a[i] == x: return False
a.insert(i, x)
self.size += 1
if len(a) > len(self.a) * self.SPLIT_RATIO:
mid = len(a) >> 1
self.a[b:b+1] = [a[:mid], a[mid:]]
return True
def _pop(self, a: List[T], b: int, i: int) -> T:
ans = a.pop(i)
self.size -= 1
if not a: del self.a[b]
return ans
def discard(self, x: T) -> bool:
"Remove an element and return True if removed. / O(√N)"
if self.size == 0: return False
a, b, i = self._position(x)
if i == len(a) or a[i] != x: return False
self._pop(a, b, i)
return True
def lt(self, x: T) -> Optional[T]:
"Find the largest element < x, or None if it doesn't exist."
for a in reversed(self.a):
if a[0] < x:
return a[bisect_left(a, x) - 1]
def le(self, x: T) -> Optional[T]:
"Find the largest element <= x, or None if it doesn't exist."
for a in reversed(self.a):
if a[0] <= x:
return a[bisect_right(a, x) - 1]
def gt(self, x: T) -> Optional[T]:
"Find the smallest element > x, or None if it doesn't exist."
for a in self.a:
if a[-1] > x:
return a[bisect_right(a, x)]
def ge(self, x: T) -> Optional[T]:
"Find the smallest element >= x, or None if it doesn't exist."
for a in self.a:
if a[-1] >= x:
return a[bisect_left(a, x)]
def __getitem__(self, i: int) -> T:
"Return the i-th element."
if i < 0:
for a in reversed(self.a):
i += len(a)
if i >= 0: return a[i]
else:
for a in self.a:
if i < len(a): return a[i]
i -= len(a)
raise IndexError
def pop(self, i: int = -1) -> T:
"Pop and return the i-th element."
if i < 0:
for b, a in enumerate(reversed(self.a)):
i += len(a)
if i >= 0: return self._pop(a, ~b, i)
else:
for b, a in enumerate(self.a):
if i < len(a): return self._pop(a, b, i)
i -= len(a)
raise IndexError
def index(self, x: T) -> int:
"Count the number of elements < x."
ans = 0
for a in self.a:
if a[-1] >= x:
return ans + bisect_left(a, x)
ans += len(a)
return ans
def index_right(self, x: T) -> int:
"Count the number of elements <= x."
ans = 0
for a in self.a:
if a[-1] > x:
return ans + bisect_right(a, x)
ans += len(a)
return ans
"""
個数付きなSortedSetがほしいとき.
(num, cnt)を要素としたSSを管理すると良い場合がある.
その時、numを一個追加、一個消去、存在判定が大変なので,
メソッド化した.
"""
def exist(self, x):
ret = self.gt((x,0))
if ret is None:
return False
elif ret[0] == x:
return True
else:
return False
def increment(self, x):
if not self.exist(x):
self.add((x,1))
else:
num, cnt = self.gt((x,0))
self.discard((x,cnt))
self.add((x,cnt+1))
def decrement(self, x):
num, cnt = self.gt((x,0))
if cnt == 1:
self.discard((x,cnt))
else:
self.discard((x,cnt))
self.add((x,cnt-1))
# well-used const
# clockwise from top.
DIRECTION_4 = [[-1,0],[0,1],[1,0],[0,-1]]
DIRECTION_8 = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]]
DIRECTION_URDL_TABLE = {'U':(-1,0), 'R':(0,1), 'D':(1,0), 'L':(0,-1)}
DIRECTION_URDL_COORD_PLANE = {'U':(0,1), 'R':(1,0), 'D':(0,-1), 'L':(-1,0)}
MOD = 998244353
INF = float("inf")
LOWER_ALPS = "abcdefghijklmnopqrstuvwxyz"
UPPER_ALPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ALL_ALPS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
# user config
############
DEBUG_MODE=0
############
import copy
N, T, M = MI()
AB = LL_1(M)
fbdn_set = set()
for a,b in AB:
fbdn_set.add((a,b))
avail = [set(range(N)) for _ in range(N)]
for i in range(N):
avail[i].discard(i)
for a,b in AB:
avail[a].discard(b)
avail[b].discard(a)
DB(avail)
def rec(v, rest, cnt):
global T, ans
DB(v, rest, cnt)
if not rest and cnt < T:
return
if cnt == T:
if not rest:
ans += 1
return
if v == N:
return
if v not in rest:
rec(v+1, rest, cnt)
return
rest.discard(v)
S = rest & avail[v]
S_arr = list(S)
L = len(S)
for bit in range(2**L):
flg = False
for i in range(L):
for j in range(i+1,L):
if bit >> i & 1 and bit >> j & 1 and (min(int(S_arr[i]), int(S_arr[j])), max(int(S_arr[i]), int(S_arr[j]))) in fbdn_set:
flg = True
break
else:
continue
break
if flg:
continue
rest_copy = copy.copy(rest)
for i in range(L):
if bit >> i & 1:
rest_copy.discard(S_arr[i])
rec(v+1, rest_copy, cnt+1)
ans = 0
rec(0, set(range(N)), 0)
print(ans) | ConDefects/ConDefects/Code/abc310_d/Python/50903679 |
condefects-python_data_491 | from sys import stdin
input=lambda :stdin.readline()[:-1]
h,w=map(int,input().split())
a=[]
for i in range(h):
b=list(map(int,input().split()))
b=[b[j]*(-1)**(i+j) for j in range(w)]
a.append(b)
p=[0]*h
q=[0]*w
for i in range(h):
for j in range(w):
p[i]+=a[i][j]
q[j]+=a[i][j]
ans=[[0]*w for i in range(h)]
for i in range(h):
for j in range(w):
if p[i]>0 and q[j]>0:
t=min(p[i],q[j])
ans[i][j]=+t
p[i]-=t
q[j]-=t
elif p[i]<0 and q[j]<0:
t=max(p[i],q[j])
ans[i][j]+=t
p[i]-=t
q[j]-=t
for i in range(h):
for j in range(h):
if p[i]>0 and p[j]<0:
t=min(p[i],-p[j])
ans[i][0]+=t
ans[j][0]-=t
p[i]-=t
p[j]+=t
for i in range(w):
for j in range(w):
if q[i]>0 and q[j]<0:
t=min(q[i],-q[j])
ans[0][i]+=t
ans[0][j]-=t
q[i]-=t
q[j]+=t
ans_sum=0
for i in range(h):
for j in range(w):
ans[i][j]*=(-1)**(h+w)
ans_sum+=abs(ans[i][j])
print(ans_sum)
for i in ans:
print(*i)
from sys import stdin
input=lambda :stdin.readline()[:-1]
h,w=map(int,input().split())
a=[]
for i in range(h):
b=list(map(int,input().split()))
b=[b[j]*(-1)**(i+j) for j in range(w)]
a.append(b)
p=[0]*h
q=[0]*w
for i in range(h):
for j in range(w):
p[i]+=a[i][j]
q[j]+=a[i][j]
ans=[[0]*w for i in range(h)]
for i in range(h):
for j in range(w):
if p[i]>0 and q[j]>0:
t=min(p[i],q[j])
ans[i][j]=+t
p[i]-=t
q[j]-=t
elif p[i]<0 and q[j]<0:
t=max(p[i],q[j])
ans[i][j]+=t
p[i]-=t
q[j]-=t
for i in range(h):
for j in range(h):
if p[i]>0 and p[j]<0:
t=min(p[i],-p[j])
ans[i][0]+=t
ans[j][0]-=t
p[i]-=t
p[j]+=t
for i in range(w):
for j in range(w):
if q[i]>0 and q[j]<0:
t=min(q[i],-q[j])
ans[0][i]+=t
ans[0][j]-=t
q[i]-=t
q[j]+=t
ans_sum=0
for i in range(h):
for j in range(w):
ans[i][j]*=(-1)**(i+j)
ans_sum+=abs(ans[i][j])
print(ans_sum)
for i in ans:
print(*i) | ConDefects/ConDefects/Code/arc135_d/Python/29324173 |
condefects-python_data_492 | import sys
input = sys.stdin.readline
H, W = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
rowsum = [0]*H
colsum = [0]*W
for i in range(H):
for j in range(W):
if (i+j) % 2:
A[i][j] *= -1
rowsum[i] += A[i][j]
colsum[j] += A[i][j]
rowidx = list(range(H))
colidx = list(range(W))
rowidx.sort(key=lambda i: rowsum[i], reverse=True)
colidx.sort(key=lambda j: colsum[j], reverse=True)
rowsum.sort(reverse=True)
colsum.sort(reverse=True)
rows = [0]*2
cols = [0]*2
for i in range(H):
if rowsum[i] >= 0:
rows[0] += rowsum[i]
else:
rows[1] -= rowsum[i]
for j in range(W):
if colsum[j] >= 0:
cols[0] += colsum[j]
else:
cols[1] -= colsum[j]
transpose = False
if rows[1] > cols[1]:
transpose = True
H, W = W, H
rowsum, colsum = colsum, rowsum
rowidx, colidx = colidx, rowidx
rows, cols = cols, rows
A = [[A[j][i] for j in range(W)] for i in range(H)]
B = [[0] * W for _ in range(H)]
for i in range(H):
for j in range(W):
B[i][j] = A[rowidx[i]][colidx[j]]
r = H-1
c = W-1
while r >= 0 and c >= 0 and colsum[c] < 0:
if rowsum[r] >= 0 or colsum[c] >= rowsum[r]:
for i in range(r):
x = B[i][c]
if x != 0:
B[i][c] -= x
B[i+1][c] += x
B[i][c-1] += x
B[i+1][c-1] -= x
rowsum[r] -= colsum[c]
c -= 1
else:
for j in range(c):
x = B[r][j]
if x != 0:
B[r][j] -= x
B[r][j+1] += x
B[r-1][j] += x
B[r-1][j+1] -= x
colsum[c] -= rowsum[r]
rowsum[r] = 0
r -= 1
r = H-1
while r >= 0 and c >= 0:
if colsum[c] <= rowsum[r]:
for i in range(r):
x = B[i][c]
if x != 0:
B[i][c] -= x
B[i+1][c] += x
B[i][c-1] += x
B[i+1][c-1] -= x
rowsum[r] -= colsum[c]
c -= 1
else:
for j in range(c):
x = B[r][j]
if x != 0:
B[r][j] -= x
B[r][j+1] += x
B[r-1][j] += x
B[r-1][j+1] -= x
colsum[c] -= rowsum[r]
rowsum[r] = 0
r -= 1
for i in range(H):
for j in range(W):
A[rowidx[i]][colidx[j]] = B[i][j]
if transpose:
H, W = W, H
A = [[A[j][i] for j in range(W)]for i in range(H)]
ans = 0
for i in range(H):
for j in range(W):
ans += abs(A[i][j])
if (i+j) % 2:
A[i][j] *= -1
print(ans)
for row in A:
print(*row)
import sys
input = sys.stdin.readline
H, W = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
rowsum = [0]*H
colsum = [0]*W
for i in range(H):
for j in range(W):
if (i+j) % 2:
A[i][j] *= -1
rowsum[i] += A[i][j]
colsum[j] += A[i][j]
rowidx = list(range(H))
colidx = list(range(W))
rowidx.sort(key=lambda i: rowsum[i], reverse=True)
colidx.sort(key=lambda j: colsum[j], reverse=True)
rowsum.sort(reverse=True)
colsum.sort(reverse=True)
rows = [0]*2
cols = [0]*2
for i in range(H):
if rowsum[i] >= 0:
rows[0] += rowsum[i]
else:
rows[1] -= rowsum[i]
for j in range(W):
if colsum[j] >= 0:
cols[0] += colsum[j]
else:
cols[1] -= colsum[j]
transpose = False
if rows[1] > cols[1]:
transpose = True
H, W = W, H
rowsum, colsum = colsum, rowsum
rowidx, colidx = colidx, rowidx
rows, cols = cols, rows
A = [[A[j][i] for j in range(W)] for i in range(H)]
B = [[0] * W for _ in range(H)]
for i in range(H):
for j in range(W):
B[i][j] = A[rowidx[i]][colidx[j]]
r = H-1
c = W-1
while r >= 0 and c >= 0 and colsum[c] < 0:
if rowsum[r] > 0 or colsum[c] >= rowsum[r]:
for i in range(r):
x = B[i][c]
if x != 0:
B[i][c] -= x
B[i+1][c] += x
B[i][c-1] += x
B[i+1][c-1] -= x
rowsum[r] -= colsum[c]
c -= 1
else:
for j in range(c):
x = B[r][j]
if x != 0:
B[r][j] -= x
B[r][j+1] += x
B[r-1][j] += x
B[r-1][j+1] -= x
colsum[c] -= rowsum[r]
rowsum[r] = 0
r -= 1
r = H-1
while r >= 0 and c >= 0:
if colsum[c] <= rowsum[r]:
for i in range(r):
x = B[i][c]
if x != 0:
B[i][c] -= x
B[i+1][c] += x
B[i][c-1] += x
B[i+1][c-1] -= x
rowsum[r] -= colsum[c]
c -= 1
else:
for j in range(c):
x = B[r][j]
if x != 0:
B[r][j] -= x
B[r][j+1] += x
B[r-1][j] += x
B[r-1][j+1] -= x
colsum[c] -= rowsum[r]
rowsum[r] = 0
r -= 1
for i in range(H):
for j in range(W):
A[rowidx[i]][colidx[j]] = B[i][j]
if transpose:
H, W = W, H
A = [[A[j][i] for j in range(W)]for i in range(H)]
ans = 0
for i in range(H):
for j in range(W):
ans += abs(A[i][j])
if (i+j) % 2:
A[i][j] *= -1
print(ans)
for row in A:
print(*row)
| ConDefects/ConDefects/Code/arc135_d/Python/41408142 |
condefects-python_data_493 | H, W = map(int, input().split())
As = [list(map(int, input().split())) for _ in range(H)]
for i in range(H - 1):
for j in range(W - 1):
tmp = As[i][j]
for di in range(2):
for dj in range(2):
As[i + di][j + dj] -= tmp
def sgn(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
for i in range(H - 1):
parity_i = -1 if (H - 1 - i + 1) % 2 else 1
for j in range(W - 1):
parity_j = -1 if (W - 1 - j + 1) % 2 else 1
elems = {As[i][W - 1] * parity_i, As[H - 1]
[j] * parity_j, As[H - 1][W - 1]}
s = {sgn(e) for e in elems}
if len(s) == 1:
t = s.pop()
delta = min((t * e for e in elems))
As[i][j] -= delta * t * parity_i * parity_j
As[i][W - 1] -= delta * t * parity_i
As[H - 1][j] -= delta * t * parity_j
As[H - 1][W - 1] -= delta * t
s = 0
for row in As:
s += sum((abs(e) for e in row))
print(s)
for row in As:
print(*row)
H, W = map(int, input().split())
As = [list(map(int, input().split())) for _ in range(H)]
for i in range(H - 1):
for j in range(W - 1):
tmp = As[i][j]
for di in range(2):
for dj in range(2):
As[i + di][j + dj] -= tmp
def sgn(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
for i in range(H - 1):
parity_i = -1 if (H - 1 - i + 1) % 2 else 1
for j in range(W - 1):
parity_j = -1 if (W - 1 - j + 1) % 2 else 1
elems = {As[i][W - 1] * parity_i, As[H - 1]
[j] * parity_j}
s = {sgn(e) for e in elems}
if len(s) == 1:
t = s.pop()
delta = min((t * e for e in elems))
As[i][j] -= delta * t * parity_i * parity_j
As[i][W - 1] -= delta * t * parity_i
As[H - 1][j] -= delta * t * parity_j
As[H - 1][W - 1] -= delta * t
s = 0
for row in As:
s += sum((abs(e) for e in row))
print(s)
for row in As:
print(*row)
| ConDefects/ConDefects/Code/arc135_d/Python/29313863 |
condefects-python_data_494 | h, w = map(int, input().split())
field = [list(map(int, input().split())) for _ in range(h)]
for i in range(h - 1):
for j in range(w - 2):
d = field[i][j]
field[i][j] -= d
field[i + 1][j] -= d
field[i][j + 2] += d
field[i + 1][j + 2] += d
for j in range(w - 1):
for i in range(h - 2):
d = field[i][j]
field[i][j] -= d
field[i][j + 1] -= d
field[i + 2][j] += d
field[i + 2][j + 1] += d
d = field[-2][-2]
field[-2][-2] -= d
field[-2][-1] -= d
field[-1][-2] -= d
field[-1][-1] -= d
for i in range(h - 1):
for j in range(w - 1):
di = (h - i) % 2
dj = (w - j) % 2
if di == 0:
if dj == 0:
if field[i][-1] > 0 and field[-1][j] > 0:
d = min(field[i][-1], field[-1][j])
elif field[i][-1] < 0 and field[-1][j] < 0:
d = max(field[i][-1], field[-1][j])
else:
continue
field[i][j] -= d
field[i][-1] -= d
field[-1][j] -= d
field[-1][-1] -= d
else:
if field[i][-1] > 0 and field[-1][j] < 0:
d = max(-field[i][-1], field[-1][j])
elif field[i][-1] < 0 and field[-1][j] > 0:
d = min(-field[i][-1], field[-1][j])
else:
continue
field[i][j] -= d
field[i][-1] += d
field[-1][j] -= d
field[-1][-1] += d
else:
if dj == 0:
if field[i][-1] > 0 and field[-1][j] < 0:
d = min(field[i][-1], -field[-1][j])
elif field[i][-1] < 0 and field[-1][j] > 0:
d = max(field[i][-1], -field[-1][j])
else:
continue
field[i][j] -= d
field[i][-1] -= d
field[-1][j] += d
field[-1][-1] += d
else:
if field[i][-1] > 0 and field[-1][j] > 0:
d = max(-field[i][-1], -field[-1][j])
elif field[i][-1] < 0 and field[-1][j] < 0:
d = min(field[i][-1], field[-1][j])
else:
continue
field[i][j] -= d
field[i][-1] += d
field[-1][j] += d
field[-1][-1] -= d
ans = 0
for i in range(h):
for j in range(w):
ans += abs(field[i][j])
print(ans)
for row in field:
print(*row)
h, w = map(int, input().split())
field = [list(map(int, input().split())) for _ in range(h)]
for i in range(h - 1):
for j in range(w - 2):
d = field[i][j]
field[i][j] -= d
field[i + 1][j] -= d
field[i][j + 2] += d
field[i + 1][j + 2] += d
for j in range(w - 1):
for i in range(h - 2):
d = field[i][j]
field[i][j] -= d
field[i][j + 1] -= d
field[i + 2][j] += d
field[i + 2][j + 1] += d
d = field[-2][-2]
field[-2][-2] -= d
field[-2][-1] -= d
field[-1][-2] -= d
field[-1][-1] -= d
for i in range(h - 1):
for j in range(w - 1):
di = (h - i) % 2
dj = (w - j) % 2
if di == 0:
if dj == 0:
if field[i][-1] > 0 and field[-1][j] > 0:
d = min(field[i][-1], field[-1][j])
elif field[i][-1] < 0 and field[-1][j] < 0:
d = max(field[i][-1], field[-1][j])
else:
continue
field[i][j] -= d
field[i][-1] -= d
field[-1][j] -= d
field[-1][-1] -= d
else:
if field[i][-1] > 0 and field[-1][j] < 0:
d = max(-field[i][-1], field[-1][j])
elif field[i][-1] < 0 and field[-1][j] > 0:
d = min(-field[i][-1], field[-1][j])
else:
continue
field[i][j] -= d
field[i][-1] += d
field[-1][j] -= d
field[-1][-1] += d
else:
if dj == 0:
if field[i][-1] > 0 and field[-1][j] < 0:
d = min(field[i][-1], -field[-1][j])
elif field[i][-1] < 0 and field[-1][j] > 0:
d = max(field[i][-1], -field[-1][j])
else:
continue
field[i][j] -= d
field[i][-1] -= d
field[-1][j] += d
field[-1][-1] += d
else:
if field[i][-1] > 0 and field[-1][j] > 0:
d = max(-field[i][-1], -field[-1][j])
elif field[i][-1] < 0 and field[-1][j] < 0:
d = min(-field[i][-1], -field[-1][j])
else:
continue
field[i][j] -= d
field[i][-1] += d
field[-1][j] += d
field[-1][-1] -= d
ans = 0
for i in range(h):
for j in range(w):
ans += abs(field[i][j])
print(ans)
for row in field:
print(*row)
| ConDefects/ConDefects/Code/arc135_d/Python/29316406 |
condefects-python_data_495 | import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log,sqrt
from atcoder.modint import ModContext, Modint
ModContext(1).context.append(998244353)
sys.setrecursionlimit(1000000)
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
a, N = mi()
ans = 1 << 60
di = defaultdict(int)
def change(x, cnt):
# print(x, cnt)
if di[x] != 0 and di[x] <= cnt:
return
di[x] = cnt
global ans
if x == 1:
ans = min(ans, cnt)
return
if x % a == 0:
change(x // a, cnt + 1)
d = sum(c.isdigit() for c in str(x))
if d == 1:
return
nx = (x % (10 ** (d - 1))) * 10 + x // (10 ** (d-1))
change(nx, cnt + 1)
return
change(N, 0)
if ans == 1 << 60:
print(-1)
else:
print(ans)
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log,sqrt
from atcoder.modint import ModContext, Modint
ModContext(1).context.append(998244353)
sys.setrecursionlimit(1000000)
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
a, N = mi()
ans = 1 << 60
di = defaultdict(int)
def change(x, cnt):
# print(x, cnt)
if di[x] != 0 and di[x] <= cnt:
return
di[x] = cnt
global ans
if x == 1:
ans = min(ans, cnt)
return
if x % a == 0:
change(x // a, cnt + 1)
d = sum(c.isdigit() for c in str(x))
if d == 1:
return
if str(x)[1] == '0':
return
nx = (x % (10 ** (d - 1))) * 10 + x // (10 ** (d-1))
change(nx, cnt + 1)
return
change(N, 0)
if ans == 1 << 60:
print(-1)
else:
print(ans) | ConDefects/ConDefects/Code/abc235_d/Python/45465231 |
condefects-python_data_496 | from sys import stdin, setrecursionlimit
a, n = list(map(int, input().split()))
setrecursionlimit(10 ** 9)
numSet = [10**5] * (10 ** 7)
ans = 10 ** 10
def numSrch(c, moves):
global numSet
# print(c, numSet[c], moves)
if c == 1:
global ans
ans = min(ans, moves)
return
elif numSet[c] > moves:
# print(c)
numSet[c] = moves
if c % a == 0:
c1 = int(c//a)
if numSet[c1] > moves+1:
numSrch(c1, moves+1)
if c > 11:
c2 = str(c)
c2 = "".join([c2[1:], c2[0]])
# print(c, c2)
c2 = int(c2)
if numSet[c2] > moves+1:
numSrch(c2, moves+1)
numSrch(n, 0)
if ans == 10 ** 10:
ans = -1
print(ans)
from sys import stdin, setrecursionlimit
a, n = list(map(int, input().split()))
setrecursionlimit(10 ** 9)
numSet = [10**5] * (10 ** 7)
ans = 10 ** 10
def numSrch(c, moves):
global numSet
# print(c, numSet[c], moves)
if c == 1:
global ans
ans = min(ans, moves)
return
elif numSet[c] > moves:
# print(c)
numSet[c] = moves
if c % a == 0:
c1 = int(c//a)
if numSet[c1] > moves+1:
numSrch(c1, moves+1)
if c > 11:
c2 = str(c)
c2 = "".join([c2[1:], c2[0]])
# print(c, c2)
c2 = int(c2)
if len(str(c2)) == len(str(c)) and numSet[c2] > moves+1:
numSrch(c2, moves+1)
numSrch(n, 0)
if ans == 10 ** 10:
ans = -1
print(ans) | ConDefects/ConDefects/Code/abc235_d/Python/44415594 |
condefects-python_data_497 | from queue import Queue
a,N=map(int,input().split())
def rot(N):
M=str(N)
return int(M[1:]+M[0])
d=[10**3]*10**len(str(N))
d[N]=0
q=Queue()
q.put(N)
while not q.empty():
M=q.get()
if M==1:
break
if M%a==0 and d[M//a]>d[M]+1:
d[M//a]=d[M]+1
q.put(M//a)
if d[rot(M)]>d[M]+1:
d[rot(M)]=d[M]+1
q.put(rot(M))
print(d[1] if d[1]!=10**3 else -1)
from queue import Queue
a,N=map(int,input().split())
def rot(N):
M=str(N)
return int(M[1:]+M[0])
d=[10**3]*10**len(str(N))
d[N]=0
q=Queue()
q.put(N)
while not q.empty():
M=q.get()
if M==1:
break
if M%a==0 and d[M//a]>d[M]+1:
d[M//a]=d[M]+1
q.put(M//a)
if len(str(M))==len(str(rot(M))) and d[rot(M)]>d[M]+1:
d[rot(M)]=d[M]+1
q.put(rot(M))
print(d[1] if d[1]!=10**3 else -1) | ConDefects/ConDefects/Code/abc235_d/Python/44598432 |
condefects-python_data_498 | a,n = map(int,input().split())
nums =[-1]*(10**6)
from collections import deque
q = deque()
q.append(a)
nums[a] = 1
while q:
x = q.popleft()
y = x*a
if y<10**6 and nums[y] ==-1:
nums[y] = nums[x]+1
q.append(y)
if x>9:
X = str(x)
Z = X[-1]+X[:-1]
z = int(Z)
if z<10**6 and nums[z] ==-1:
nums[z] = nums[x]+1
q.append(z)
print(nums[n])
a,n = map(int,input().split())
nums =[-1]*(10**6)
from collections import deque
q = deque()
q.append(a)
nums[a] = 1
while q:
x = q.popleft()
y = x*a
if y<10**6 and nums[y] ==-1:
nums[y] = nums[x]+1
q.append(y)
if x>9 and x%10 !=0:
X = str(x)
Z = X[-1]+X[:-1]
z = int(Z)
if z<10**6 and nums[z] ==-1:
nums[z] = nums[x]+1
q.append(z)
print(nums[n])
| ConDefects/ConDefects/Code/abc235_d/Python/46231153 |
condefects-python_data_499 | N, C = map(int, input().split())
A = list(map(int, input().split()))
ruiseki_sei = [0]*(N+1)
ruiseki_hu = [0]*(N+1)
sum = 0
for i in range(N):
sum += A[i]
for i in range(1,N+1):
ruiseki_sei[i] = ruiseki_sei[i-1] + A[i-1]
if ruiseki_sei[i] <= 0:
ruiseki_sei[i] = 0
tmp = max(ruiseki_sei)
for i in range(1,N+1):
ruiseki_hu[i] = ruiseki_hu[i-1] + A[i-1]
if ruiseki_hu[i] >= 0:
ruiseki_hu[i] = 0
tmp2 = min(ruiseki_hu)
if C > 0:
print(sum + tmp*(C-1))
else:
print(sum + 2*tmp2*C)
N, C = map(int, input().split())
A = list(map(int, input().split()))
ruiseki_sei = [0]*(N+1)
ruiseki_hu = [0]*(N+1)
sum = 0
for i in range(N):
sum += A[i]
for i in range(1,N+1):
ruiseki_sei[i] = ruiseki_sei[i-1] + A[i-1]
if ruiseki_sei[i] <= 0:
ruiseki_sei[i] = 0
tmp = max(ruiseki_sei)
for i in range(1,N+1):
ruiseki_hu[i] = ruiseki_hu[i-1] + A[i-1]
if ruiseki_hu[i] >= 0:
ruiseki_hu[i] = 0
tmp2 = min(ruiseki_hu)
if C > 0:
print(sum + tmp*(C-1))
else:
print(sum + -tmp2 + tmp2*C) | ConDefects/ConDefects/Code/arc174_a/Python/54196806 |
condefects-python_data_500 | N, C = map(int, input().split())
A = list(map(int, input().split()))
S = [0]*(N + 1)
for i in range(N):
S[i + 1] = S[i] + A[i]
INF = 10**18
if C > 1:
m = INF
ans = -INF
for i in range(N):
m = min(m, S[i + 1])
ans = max(ans, S[i + 1] - m)
print(S[N] + ans*(C - 1))
elif C <= 1:
m = 0
ans = INF
for i in range(N):
m = max(m, S[i + 1])
ans = min(ans, S[i + 1] - m)
print(S[N] + ans*(C - 1))
N, C = map(int, input().split())
A = list(map(int, input().split()))
S = [0]*(N + 1)
for i in range(N):
S[i + 1] = S[i] + A[i]
INF = 10**18
if C > 1:
m = 0
ans = -INF
for i in range(N):
m = min(m, S[i + 1])
ans = max(ans, S[i + 1] - m)
print(S[N] + ans*(C - 1))
elif C <= 1:
m = 0
ans = INF
for i in range(N):
m = max(m, S[i + 1])
ans = min(ans, S[i + 1] - m)
print(S[N] + ans*(C - 1)) | ConDefects/ConDefects/Code/arc174_a/Python/53524573 |