### 001 ```python n, m = map(int, input().split()) matrix = [list(map(int, input().split())) for _ in range(n)] res = 0 for i in range(n - 2, 0, -1): for j in range(m - 1, 0, --1): if matrix[i][j] == 0: mn = min(matrix[i + 1][j], matrix[i][j + 1]) if mn != 1: matrix[i][j] = mn - 1 else: res = -1 break if res == -1: break else: for i in range(n): if [matrix[i][j] for j in range(m - 1) if matrix[i][j] >= matrix[i][j + 1]]: res = -1 break else: for j in range(m): if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]: res = -1 break else: res = sum((sum(matrix[i]) for i in range(n))) print(res) ``` ### 002 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index - 1] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index]: potential = score + (n - done - 1) * val + arr[index] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 003 ```python m, n = [int(x) for x in input().split()] r = [int(x) for x in input().split()] cost = [int(x) for x in input().split()] costa = [] i = 1 for item in cost: a = [item, i, r[i - 1 - 1]] costa.append(a) i += 1 counter = 0 costa.sort(reverse=True) dic = {} i = 0 for item in costa: dic[item[1]] = i i += 1 index = len(costa) - 1 for item in range(n): counter = 0 a, b = [int(x) for x in input().split()] if r[a - 1] >= b: counter += cost[a - 1] * b r[a - 1] -= b costa[dic[a]][2] -= b else: i = index counter += cost[a - 1] * r[a - 1] costa[dic[a]][2] = 0 b -= r[a - 1] r[a - 1] = 0 while i >= 0: if costa[i][2] >= b: counter += costa[i][0] * b r[costa[i][1] - 1] -= b costa[i][2] -= b break else: counter += costa[i][0] * costa[i][2] r[costa[i][1] - 1] = 0 index -= 1 b -= costa[i][2] costa[i][2] = 0 i -= 1 else: counter = 0 print(counter) ``` ### 004 ```python n, v = list(map(int, input().split())) f = list() for i in range(n): f.append(list(map(int, input().split()))) f.sort() sum = 0 today = 0 tomor = 0 day = 0 rest = 0 for tree in f: if tree[0] > day + 5: sum += min(tomor, v) tomor = tree[1] sum += min(tomor, v) rest = v - min(tomor, v) tomor -= min(tomor, v) day = tree[0] elif tree[0] == day + 1: sum += min(tomor, v) rest = v - min(tomor, v) tomor = tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t day = tree[0] else: tomor += tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t sum += min(tomor, v) print(sum) ``` ### 005 ```python from collections import deque from sys import stdin, stdout input = stdin.readline saida = [] t = int(input()) modulo = 998244353 for _ in range(t): ans = 1 part = 0 factor = 0 fila = deque([]) n, m = map(int, input().split()) if m > n // 2 * (n // 2 + 1): saida.append('0') for edge_count in range(m): input() continue edge = [[] for i in range(n + 1)] visitados = [-1] * (n + 1) assure = 1 for arestas in range(m): u, v = map(int, input().split()) edge[u].append(v) edge[v].append(u) visitados[1] = 0 fila.append(1) break_all = False while not break_all: par, impar = (1, 0) while fila and (not break_all): search = fila.popleft() current = visitados[search] for i in edge[search]: if visitados[i] == -1: visitados[i] = current ^ 1 if visitados[i] & 1: impar += 1 else: par += 1 fila.append(i) elif visitados[i] == current: break_all = True else: assert visitados[i] == current ^ 1 if break_all: ans = 0 elif (par, impar) == (1, 0): factor += 1 else: ans *= pow(2, par, modulo) + pow(2, impar, modulo) ans %= modulo while assure <= n: if visitados[assure] == -1: part += 1 visitados[assure] = 2 * part fila.append(assure) break assure += 1 if assure == n + 1: break ans *= pow(2, factor, modulo) ans %= modulo saida.append(str(ans)) print('\n'.join(saida)) ``` ### 006 ```python n, m = map(int, input().split()) a = [] for i in range(n): a.append(list(map(int, input().split()))) dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] ans = 0 for i in range(1, n + 1): for j in reversed(range(1, m + 1)): dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1] dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] for i in range(n, 0, -1): for j in range(1, m + 1): dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1] dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] for i in range(2, n): for j in range(2, m): x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1] y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1] ans = max(ans, x, y) print(ans) ``` ### 007 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] + remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 008 ```python n = int(input()) ns = [] for i in range(n): s = input() ns.append(s) ns2 = [] for i in range(n): s = input() ns2.append(s) def rotate(i, j): return (j, n - 1 - i) def flip(i, j): return (j, i) def main(): same = True for i in range(n): for j in range(n): if ns[i][j] != ns2[i][j]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) if not ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = flip(i, j) if ns[a][b] != ns2[i][j]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True else: return False if main(): print('Yes') else: print('No') ``` ### 009 ```python import copy n = int(input()) flg = 0 mat1 = [] mat2 = [] mats = [] for i in range(0, n): mat1.append(tuple(input().strip())) for i in range(0, n): mat2.append(tuple(input().strip())) mats.append(mat2) matu = copy.copy(mat2) matv = copy.copy(mat2) matv = list(zip(*matv)) mats.append(matv) mattem = copy.copy(matu) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) mattem = copy.copy(matv) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) flg = 0 for cmat in mats: flg2 = 1 for ri in range(4, n): if cmat[ri] != mat1[ri]: flg2 = 0 break if flg2 == 1: flg = 1 break if flg == 1: print('Yes') else: print('No') ``` ### 010 ```python N = int(input()) map_1 = [list(input()) for i in range(N)] map_2 = [list(input()) for i in range(N)] maps = list() maps.append([[map_2[i][j] for j in range(N)] for i in range(N)]) maps.append([[map_2[i][N - 1 - j] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - i][j] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - i][N - 1 - j] for j in range(N)] for i in range(N)]) maps.append([[map_2[j][i] for j in range(N)] for i in range(N)]) maps.append([[map_2[j][N - 1 - i] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - j][i] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - j][N - 1 - i] for j in reversed(range(N))] for i in range(N)]) print(('No', 'Yes')[any((map_1 == el for el in maps))]) ``` ### 011 ```python from collections import defaultdict import sys input = sys.stdin.readline graph = defaultdict(list) color = [0] * (3 * 10 ** 5 + 1000) bipertite = True MOD = 998244355 result = 1 color_count = [0] * 2 pow_value = [] '\ndef dfs(s, c):\n nonlocal color\n nonlocal bipertite\n nonlocal color_count\n\n color[s] = c\n color_count[c] += 1\n for i in range(0, len(graph[s])):\n\n if color[graph[s][i]] == -1:\n dfs(graph[s][i], 1-c)\n\n if color[s] == color[graph[s][i]]:\n bipertite = False\n\n' t = int(input()) pow_value.append(1) for i in range(1, 3 * 10 ** 5 + 1000): next_value = pow_value[i - 1] * 2 % MOD pow_value.append(next_value) while t: n, m = list(map(int, input().split())) if m == 0: print(pow(3, n, MOD)) t -= 1 continue graph.clear() bipertite = True result = 1 for node in range(0, n + 1): color[node] = -1 while m: u, v = list(map(int, input().split())) graph[u].append(v) graph[v].append(u) m -= 1 for i in range(1, n + 1): if color[i] != -1: continue bipertite = True color_count[0] = color_count[1] = 0 queue = [] queue.append(i) color[i] = 0 color_count[0] += 1 while queue: if bipertite == False: break front_node = queue.pop() for child_node in range(0, len(graph[front_node])): if color[graph[front_node][child_node]] == -1: color[graph[front_node][child_node]] = 1 - color[front_node] queue.append(graph[front_node][child_node]) color_count[color[graph[front_node][child_node]]] += 1 elif color[front_node] == color[graph[front_node][child_node]]: bipertite = False break if bipertite == False: print(0) break current = (pow_value[color_count[0]] + pow_value[color_count[1]]) % MOD result = result * current % MOD if bipertite: print(result) t -= 1 ``` ### 012 ```python import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return list(map(int, minp().split())) n, m = mints() a = [0] * n dp1 = [0] * n dp2 = [0] * n dp3 = [0] * n dp4 = [0] * n for i in range(n): a[i] = list(mints()) dp1[i] = [0] * m dp2[i] = [0] * m dp3[i] = [0] * m dp4[i] = [0] * m dp1[0][0] = a[0][0] dp2[n - 1][m - 1] = a[n - 1][m - 1] dp3[n - 1][0] = a[n - 1][0] dp4[0][m - 1] = a[0][m - 1] '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' for i in range(0, n): for j in range(0, m): z = 0 if i - 1 >= 0: z = dp1[i - 1][j] if j - 1 >= 0: z = max(z, dp1[i][j - 1]) dp1[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): z = 0 if i + 1 < n: z = dp2[i + 1][j] if j + 1 < m: z = max(z, dp2[i][j + 1]) dp2[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(0, m): z = 0 if i + 1 < n: z = dp3[i + 1][j] if j - 1 >= 0: z = max(z, dp3[i][j - 1]) dp3[i][j] = z + a[i][j] for i in range(0, n): for j in range(m - 1, -1, -1): z = 0 if i - 1 >= 0: z = dp4[i - 1][j] if j + 1 < m: z = max(z, dp4[i][j + 1]) dp4[i][j] = z + a[i][j] 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' r = 1 for i in range(1, n - 1): for j in range(1, m - 1): r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) print(r) ``` ### 013 ```python N = int(input()) first = [] second = [] for i in range(N): first.append([s for s in input()]) for i in range(N): second.append([s for s in input()]) def rotate_90(matrix): return list(zip(*matrix[::-1])) def flip(matrix): return matrix[::-1] def compare_matrices(first, second): for i in range(N): for j in range(N): if first[i][j] != second[i][j]: return False return True def wrap(first, second): if compare_matrices(first, second) == True: return 'Yes' hold_first = first[:] for _ in range(3): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' first = hold_first first = flip(first) if compare_matrices(first, second) == True: return 'Yes' for _ in range(0): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' return 'No' print(wrap(first, second)) ``` ### 014 ```python from math import gcd p = 10 ** 9 + 7 class RN: p = 10 ** 9 + 7 def __init__(self, u, d): self.u = u self.d = d def __str__(self): return str(self.u) + '/' + str(self.d) def cleanup(self): self.u = self.u % p self.d = self.d % p def add(self, u, d): self.u = self.u * d + u * self.d self.d = self.d * d self.cleanup() def mult(self, u, d): return (self.u * u % p, self.d * d % p) def mult_ip(self, u, d): self.u, self.d = (self.u * u, self.d * d % p) def get_m_exp(self): self.cleanup() a = gcd(self.u, self.d) self.u //= a self.d //= a return pow(self.d, p - 2, p) * self.u % p n, m = tuple(map(int, input().split())) s1 = list(map(int, input().split())) s2 = list(map(int, input().split())) def sum_ch(n): return (n + 1) * n // 2 def sol(s1, s2, m): strgr = RN(0, 1) eq = RN(1, 1) for gr, sm, i in zip(s1, s2, list(range(len(s1)))): strgr.cleanup() if gr != 0 and sm != 0: if gr == sm: continue elif gr < sm: return strgr.get_m_exp() else: strgr.add(eq.u, eq.d) return strgr.get_m_exp() else: if gr == sm == 0: strgr.add(*eq.mult(sum_ch(m - 1), m * m)) elif gr == 0: strgr.add(*eq.mult(m - sm, m)) else: strgr.add(*eq.mult(gr - 1, m)) eq.mult_ip(1, m) return strgr.get_m_exp() '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' print(sol(s1, s2, m)) ``` ### 015 ```python mod = 998244353 import sys input = sys.stdin.readline from collections import deque from collections import Counter def calc(s, a): return (pow(2, s, mod) + pow(2, a - s, mod)) % mod def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) testcase = int(input()) for test in range(testcase): n, m = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGELIST = [[] for j in range(n + 1)] ANS = 1 Group = [j for j in range(n + 1)] for a, b in EDGE: Union(a, b) EDGELIST[a].append(b) EDGELIST[b].append(a) testing = [None] * (n + 1) flag = 1 for i in range(1 + 1, n + 1): if testing[i] != None: continue score = 1 allscore = 1 testing[i] = 1 QUE = deque([i]) while QUE: x = QUE.pop() for to in EDGELIST[x]: if testing[to] == -testing[x]: continue if testing[to] == testing[x]: flag = 0 break testing[to] = -testing[x] if testing[to] == 1: score += 1 allscore += 1 QUE.append(to) if flag == 0: break if flag == 0: break ANS = ANS * calc(score, allscore) % mod if flag == 0: print(0) continue print(ANS) ``` ### 016 ```python class Union: def __init__(self, n): self.p = {i: i for i in range(n)} self.rank = {i: 1 for i in range(n)} def find(self, x): if x < 0: return x if self.p[x] != x: self.p[x - 1] = self.find(self.p[x]) return self.p[x] def union(self, x, y): if x < 0 or y < 0: return x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: self.p[x] = y self.rank[y] += self.rank[x] else: self.p[y] = x self.rank[x] += self.rank[y] n, m, q = map(int, input().split()) listW = input().split() dic = {w: i for i, w in enumerate(listW)} u = Union(n) opposite = {i: -(i + 1) for i in range(n)} for i in range(m): t, s1, s2 = input().split() x = u.find(dic[s1]) y = u.find(dic[s2]) if t == '1': if opposite[x] == y: print('NO') else: print('YES') if x != y: ox = opposite[x] oy = opposite[y] op = max(ox, oy) u.union(x, y) u.union(ox, oy) op = u.find(op) p = u.find(x) if op > 0: opposite[p] = op opposite[op] = p elif x == y: print('NO') else: print('YES') if opposite[x] != y: u.union(y, opposite[x]) u.union(x, opposite[y]) x = u.find(x) y = u.find(y) opposite[x] = y opposite[y] = x for _ in range(q): s1, s2 = input().split() id1, id2 = (u.find(dic[s1]), u.find(dic[s2])) if id1 == id2: print(1) elif opposite[id1] == id2: print(2) else: print(3) ``` ### 017 ```python mod = 998244353 import sys input = sys.stdin.readline from collections import deque from collections import Counter def calc(s, a): return (pow(2, s, mod) + pow(2, a - s, mod)) % mod def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) testcase = int(input()) for test in range(testcase): n, m = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGELIST = [[] for j in range(n + 1)] ANS = 1 Group = [j for j in range(n + 1)] for a, b in EDGE: Union(a, b) EDGELIST[a].append(b) EDGELIST[b].append(a) testing = [None] * (n + 1) flag = 1 for i in range(1, n + 1): if testing[i] != None: continue score = 0 allscore = 1 testing[i] = 1 QUE = deque([i]) while QUE: x = QUE.pop() for to in EDGELIST[x]: if testing[to] == -testing[x]: continue if testing[to] == testing[x]: flag = 0 break testing[to] = -testing[x] if testing[to] == 1: score += 1 allscore += 1 QUE.append(to) if flag == 0: break if flag == 0: break ANS = ANS * calc(score, allscore) % mod if flag == 0: print(0) continue print(ANS) ``` ### 018 ```python class Union: def __init__(self, n): self.p = {i: i for i in range(n)} self.rank = {i: 1 for i in range(n)} def find(self, x): if x < 0: return x if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): if x < 0 or y < 0: return x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: self.p[x] = y self.rank[y] += self.rank[x] else: self.p[y] = x self.rank[x] += self.rank[y] n, m, q = map(int, input().split()) listW = input().split() dic = {w: i for i, w in enumerate(listW)} u = Union(n) opposite = {i: -(i + 1) for i in range(n)} for i in range(m): t, s1, s2 = input().split() x = u.find(dic[s1]) y = u.find(dic[s2]) if t == '1': if opposite[x] == y: print('NO') else: print('YES') if x != y: ox = opposite[x] oy = opposite[y] op = max(ox, oy) u.union(x, y) u.union(ox, oy) op = u.find(op) p = u.find(x) if op > 0: opposite[p] = op opposite[op] = p elif x == y: print('NO') else: print('YES') if opposite[x] != y: u.union(y, opposite[x]) u.union(x, opposite[y]) x = u.find(x) y = u.find(y) opposite[x] = y opposite[y] = x for _ in range(q): s1, s2 = input().split() id1, id2 = (u.find(dic[s1]), u.find(dic[s2])) if id1 == id2: print(1) elif opposite[id1] == id2: print(2) else: print(-1) ``` ### 019 ```python N = int(input()) first = [] second = [] for i in range(N): first.append([s for s in input()]) for i in range(N): second.append([s for s in input()]) def rotate_90(matrix): return list(zip(*matrix[::-1])) def flip(matrix): return matrix[::+1] def compare_matrices(first, second): for i in range(N): for j in range(N): if first[i][j] != second[i][j]: return False return True def wrap(first, second): if compare_matrices(first, second) == True: return 'Yes' hold_first = first[:] for _ in range(3): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' first = hold_first first = flip(first) if compare_matrices(first, second) == True: return 'Yes' for _ in range(3): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' return 'No' print(wrap(first, second)) ``` ### 020 ```python n, m = list(map(int, input().split())) ost = list(map(int, input().split())) price = list(map(int, input().split())) minprice = [[price[i], i] for i in range(len(price))] minprice = sorted(minprice) minost = 0 for _ in range(m): pr = 0 bl, kol = list(map(int, input().split())) bl -= 1 if ost[bl] >= kol: pr = kol * price[bl] ost[bl] -= kol else: kol -= ost[bl] pr = ost[bl] * price[bl] ost[bl] = 0 while kol > 0: if minost == n: pr = 3 break minbl = minprice[minost][1] if ost[minbl] >= kol: pr += kol * price[minbl] ost[minbl] -= kol kol = 0 else: kol -= ost[minbl] pr += ost[minbl] * price[minbl] ost[minbl] = 0 minost += 1 if minost == n: pr = 0 break print(pr) ``` ### 021 ```python n, m = list(map(int, input().split())) a = [] for i in range(n): a.append(list(map(int, input().split()))) def result(a, n, m): r = 0 for i in range(-1, -m, -3): if a[-1][i] == 0: a[-1][i] = a[-1][i + 1] - 1 if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]: return -1 r = r + a[-1][i] if a[-1][-m] == 0: a[-1][-m] = a[-1][-m + 1] - 1 if a[-1][-m] <= a[-2][-m]: return -1 r = r + a[-1][-m] for i in range(-2, -n, -1): for j in range(-1, -m, -1): if j == -1: if a[i][j] == 0: a[i][j] == a[i + 1][j] - 1 if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]: return -1 r = r + a[i][j] continue if a[i][j] == 0: a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1) if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]: return -1 r = r + a[i][j] if a[i][-m] == 0: a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1) if a[i][-m] <= a[i - 1][-m]: return -1 r = r + a[i][-m] if a[0][-1] == 0: a[0][-1] = a[1][-1] - 1 if a[0][-1] <= a[0][-2]: return -1 r = r + a[0][-1] for i in range(-2, -m, -1): if a[0][i] == 0: a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1) if a[0][i] <= a[0][i - 1]: return -1 r = r + a[0][i] if a[0][0] == 0: a[0][0] = min(a[0][1] - 1, a[1][0] - 1) r = r + a[0][0] return r print(result(a, n, m)) ``` ### 022 ```python from collections import deque from sys import stdin, stdout input = stdin.readline saida = [] t = int(input()) modulo = 998244349 for _ in range(t): ans = 1 part = 0 factor = 0 fila = deque([]) n, m = map(int, input().split()) if m > n // 2 * (n // 2 + 1): saida.append('0') for edge_count in range(m): input() continue edge = [[] for i in range(n + 1)] visitados = [-1] * (n + 1) assure = 1 for arestas in range(m): u, v = map(int, input().split()) edge[u].append(v) edge[v].append(u) visitados[1] = 0 fila.append(1) break_all = False while not break_all: par, impar = (1, 0) while fila and (not break_all): search = fila.popleft() current = visitados[search] for i in edge[search]: if visitados[i] == -1: visitados[i] = current ^ 1 if visitados[i] & 1: impar += 1 else: par += 1 fila.append(i) elif visitados[i] == current: break_all = True else: assert visitados[i] == current ^ 1 if break_all: ans = 0 elif (par, impar) == (1, 0): factor += 1 else: ans *= pow(2, par, modulo) + pow(2, impar, modulo) ans %= modulo while assure <= n: if visitados[assure] == -1: part += 1 visitados[assure] = 2 * part fila.append(assure) break assure += 1 if assure == n + 1: break ans *= pow(3, factor, modulo) ans %= modulo saida.append(str(ans)) print('\n'.join(saida)) ``` ### 023 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 4 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 024 ```python from math import gcd p = 10 ** 9 + 7 class RN: p = 10 ** 9 + 7 def __init__(self, u, d): self.u = u self.d = d def __str__(self): return str(self.u) + '/' + str(self.d) def cleanup(self): self.u = self.u % p self.d = self.d % p def add(self, u, d): self.u = self.u * d + u * self.d self.d = self.d * d self.cleanup() def mult(self, u, d): return (self.u * u % p, self.d * d % p) def mult_ip(self, u, d): self.u, self.d = (self.u * u, self.d * d % p) def get_m_exp(self): self.cleanup() a = gcd(self.u, self.d) self.u //= a self.d //= a return pow(self.d, p - 2, p) * self.u % p n, m = tuple(map(int, input().split())) s1 = list(map(int, input().split())) s2 = list(map(int, input().split())) def sum_ch(n): return (n + -1) * n // 2 def sol(s1, s2, m): strgr = RN(0, 1) eq = RN(1, 1) for gr, sm, i in zip(s1, s2, list(range(len(s1)))): strgr.cleanup() if gr != 0 and sm != 0: if gr == sm: continue elif gr < sm: return strgr.get_m_exp() else: strgr.add(eq.u, eq.d) return strgr.get_m_exp() else: if gr == sm == 0: strgr.add(*eq.mult(sum_ch(m - 1), m * m)) elif gr == 0: strgr.add(*eq.mult(m - sm, m)) else: strgr.add(*eq.mult(gr - 1, m)) eq.mult_ip(1, m) return strgr.get_m_exp() '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' print(sol(s1, s2, m)) ``` ### 025 ```python import sys, collections n, q = list(map(int, input().split())) M = collections.defaultdict(collections.deque) Q = collections.deque() L = [] s = n = m = 0 for _ in range(q): y, x = list(map(int, input().split())) if 2 > y: s += 1 Q.append(x) M[x].append(n) n += 1 elif 3 >= y: y = M.get(x) if y: s -= len(y) del M[x] else: while x > m: z = Q.popleft() y = M.get(z) if y and y[0] < x: s -= 1 y.popleft() if not y: del M[z] m += 1 L.append(s) sys.stdout.write('\n'.join(map(str, L))) ``` ### 026 ```python n, m = map(int, input().split()) matrix = [list(map(int, input().split())) for _ in range(n)] res = 0 for i in range(n - 2, 0, -1): for j in range(m - 1, 0, -1): if matrix[i][j] == 0: mn = min(matrix[i + 1][j], matrix[i][j + 1]) if mn != 1: matrix[i][j] = mn - 1 else: res = -1 break if res == -1: break else: for i in range(n): if [matrix[i][j] for j in range(m - 1 - 1) if matrix[i][j] >= matrix[i][j + 1]]: res = -1 break else: for j in range(m): if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]: res = -1 break else: res = sum((sum(matrix[i]) for i in range(n))) print(res) ``` ### 027 ```python total_plucked = 0 n, v = list(map(int, input().split())) fruits = [0] * 3002 plucked = [0] * 30002 for _ in range(n): a, b = list(map(int, input().split())) fruits[a] = fruits[a] + b for i in range(1, 3002): plucked[i] = fruits[i - 1] if fruits[i - 1] <= v else v if plucked[i] < v: pluck = fruits[i] if fruits[i] <= v * plucked[i] else v - plucked[i] plucked[i] += pluck fruits[i] -= pluck total_plucked += plucked[i] print(total_plucked) ``` ### 028 ```python N = int(input()) first = [] second = [] for i in range(N): first.append([s for s in input()]) for i in range(N): second.append([s for s in input()]) def rotate_90(matrix): return list(zip(*matrix[::-1])) def flip(matrix): return matrix[::-1] def compare_matrices(first, second): for i in range(N): for j in range(N): if first[i][j] != second[i][j]: return False return True def wrap(first, second): if compare_matrices(first, second) == True: return 'Yes' hold_first = first[:] for _ in range(0): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' first = hold_first first = flip(first) if compare_matrices(first, second) == True: return 'Yes' for _ in range(3): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' return 'No' print(wrap(first, second)) ``` ### 029 ```python n, m = list(map(int, input().split())) a = [] for i in range(n): a.append(list(map(int, input().split()))) def result(a, n, m): r = 0 for i in range(-1, -m, -4): if a[-1][i] == 0: a[-1][i] = a[-1][i + 1] - 1 if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]: return -1 r = r + a[-1][i] if a[-1][-m] == 0: a[-1][-m] = a[-1][-m + 1] - 1 if a[-1][-m] <= a[-2][-m]: return -1 r = r + a[-1][-m] for i in range(-2, -n, -1): for j in range(-1, -m, -1): if j == -1: if a[i][j] == 0: a[i][j] == a[i + 1][j] - 1 if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]: return -1 r = r + a[i][j] continue if a[i][j] == 0: a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1) if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]: return -1 r = r + a[i][j] if a[i][-m] == 0: a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1) if a[i][-m] <= a[i - 1][-m]: return -1 r = r + a[i][-m] if a[0][-1] == 0: a[0][-1] = a[1][-1] - 1 if a[0][-1] <= a[0][-2]: return -1 r = r + a[0][-1] for i in range(-2, -m, -1): if a[0][i] == 0: a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1) if a[0][i] <= a[0][i - 1]: return -1 r = r + a[0][i] if a[0][0] == 0: a[0][0] = min(a[0][1] - 1, a[1][0] - 1) r = r + a[0][0] return r print(result(a, n, m)) ``` ### 030 ```python n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [-1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 1)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if (num, number) not in read: read.add((num, number)) unread -= 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) ans.append(unread) print('\n'.join(map(str, ans))) ``` ### 031 ```python n, m = map(int, input().split()) a = [] for i in range(n): a.append(list(map(int, input().split()))) dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] ans = 0 for i in range(1, n + 1): for j in range(1, m + 1): dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1] dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] for i in range(n, 0, -5): for j in range(1, m + 1): dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1] dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] for i in range(2, n): for j in range(2, m): x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1] y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1] ans = max(ans, x, y) print(ans) ``` ### 032 ```python import sys import math n, v = [int(x) for x in sys.stdin.readline().split()] k = [0] * 3002 for i in range(n): a, b = [int(x) for x in sys.stdin.readline().split()] k[a] += b i = 1 res = 0 while i <= 3001: val = 0 if k[i - 1] < v: val = k[i - 1] res -= val d = v - val if k[i] < d: res += k[i] k[i] = 0 else: res += d k[i] = k[i] - d else: res += v i += 1 print(res) ``` ### 033 ```python n, v = map(int, input().split()) T = 3010 a = [[] for i in range(T)] for i in range(n): x, y = map(int, input().split()) a[x].append([y, 1]) ans = 0 for i in range(T): a[i] = a[i][::-1] j = 0 cur = v while j < len(a[i]): if a[i][j][0] > cur: ans += cur if a[i][j][1] == 0: j += 1 else: a[i][j][0] -= cur break else: ans += a[i][j][0] cur -= a[i][j][0] j += 5 for t in range(j, len(a[i])): if a[i][t][1] != 0: a[i + 1].append([a[i][t][0], 0]) print(ans) ``` ### 034 ```python import collections import time import os import sys import bisect import heapq from typing import List def solve(N, M, A): dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] for r in range(1, N + 1): for c in range(1, M + 1): dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] for r in range(N, 0, -1): for c in range(M, 0, -1): dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] for r in range(N, 0, -1): for c in range(1, M + 1): dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] for r in range(1, N + 1): for c in range(M, 0, -1): dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] ans = 0 for r in range(2, N + 1): for c in range(2, M): a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] ans = max(ans, a, b) return ans N, M = map(int, input().split()) A = [[0 for _ in range(M + 2)]] for i in range(N): row = [0] + [int(x) for x in input().split()] + [0] A.append(row) A.append([0 for _ in range(M + 2)]) print(solve(N, M, A)) ``` ### 035 ```python import sys read = lambda: list(map(int, sys.stdin.readline().split())) write = sys.stdout.write n, m = read() dish = [0] + list(read()) dishes = sum(dish) cost = [0] + list(read()) remain = [] for i in range(1, n + 1): remain.append([cost[i], i]) remain.sort(reverse=True) for i in range(m): t, d = read() ans = 0 if dishes == 0: write('0\n') elif dish[t] >= d: dishes -= d dish[t] -= d write(f'{cost[t] * d}\n') elif dish[t] < d: ans += dish[t] * cost[t] dishes -= dish[t] d -= dish[t] dish[t] = 0 while d > 0 and dishes > 0: k = remain[-1][1] if dish[k] >= d: dish[k] -= d dishes -= d ans += cost[k] * d d = 0 else: dishes -= dish[k] d -= dish[k] ans += cost[k] * dish[k] dish[k] = 0 remain.pop() if d > 0 and dishes == 0: write('0\n') else: write(f'{ans}\n') ``` ### 036 ```python class Union: def __init__(self, n): self.p = {i: i for i in range(n)} self.rank = {i: 1 for i in range(n)} def find(self, x): if x < 1: return x if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): if x < 0 or y < 0: return x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: self.p[x] = y self.rank[y] += self.rank[x] else: self.p[y] = x self.rank[x] += self.rank[y] n, m, q = map(int, input().split()) listW = input().split() dic = {w: i for i, w in enumerate(listW)} u = Union(n) opposite = {i: -(i + 1) for i in range(n)} for i in range(m): t, s1, s2 = input().split() x = u.find(dic[s1]) y = u.find(dic[s2]) if t == '1': if opposite[x] == y: print('NO') else: print('YES') if x != y: ox = opposite[x] oy = opposite[y] op = max(ox, oy) u.union(x, y) u.union(ox, oy) op = u.find(op) p = u.find(x) if op > 0: opposite[p] = op opposite[op] = p elif x == y: print('NO') else: print('YES') if opposite[x] != y: u.union(y, opposite[x]) u.union(x, opposite[y]) x = u.find(x) y = u.find(y) opposite[x] = y opposite[y] = x for _ in range(q): s1, s2 = input().split() id1, id2 = (u.find(dic[s1]), u.find(dic[s2])) if id1 == id2: print(1) elif opposite[id1] == id2: print(2) else: print(3) ``` ### 037 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 0, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[+n:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 038 ```python n, v = map(int, input().split()) T = 3010 a = [[] for i in range(T)] for i in range(n): x, y = map(int, input().split()) a[x].append([y, 1]) ans = 0 for i in range(T): a[i] = a[i][::-1] j = 0 cur = v while j < len(a[i]): if a[i][j][0] > cur: ans += cur if a[i][j][1] == 0: j += -1 else: a[i][j][0] -= cur break else: ans += a[i][j][0] cur -= a[i][j][0] j += 1 for t in range(j, len(a[i])): if a[i][t][1] != 0: a[i + 1].append([a[i][t][0], 0]) print(ans) ``` ### 039 ```python mod = 998244353 import sys input = sys.stdin.readline from collections import deque from collections import Counter def calc(s, a): return (pow(2, s, mod) + pow(2, a - s, mod)) % mod def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) testcase = int(input()) for test in range(testcase): n, m = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGELIST = [[] for j in range(n + 1)] ANS = 1 Group = [j for j in range(n + 1)] for a, b in EDGE: Union(a, b) EDGELIST[a].append(b) EDGELIST[b].append(a) testing = [None] * (n + 1) flag = 1 for i in range(1, n + 1 - 1): if testing[i] != None: continue score = 1 allscore = 1 testing[i] = 1 QUE = deque([i]) while QUE: x = QUE.pop() for to in EDGELIST[x]: if testing[to] == -testing[x]: continue if testing[to] == testing[x]: flag = 0 break testing[to] = -testing[x] if testing[to] == 1: score += 1 allscore += 1 QUE.append(to) if flag == 0: break if flag == 0: break ANS = ANS * calc(score, allscore) % mod if flag == 0: print(0) continue print(ANS) ``` ### 040 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index]: potential = score + (n - done - 1) * val + arr[index - 1] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 041 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] + prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 042 ```python from sys import stdin def create_dp1(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n): for j in range(m): if i - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) if j - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) elif i - 1 < 0 and j - 1 < 0: dp[i][j] = matrix[i][j] return dp def create_dp2(matrix, n, m): dp = [[4 for i in range(m)] for j in range(n)] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): if i + 1 < n: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) if j + 1 < m: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) if i + 1 >= n and j + 1 >= m: dp[i][j] = matrix[i][j] return dp def create_dp3(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n - 1, -1, -1): for j in range(m): if i + 1 < n: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) if j - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) if i + 1 >= n and j - 1 < 0: dp[i][j] = matrix[i][j] return dp def create_dp4(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n): for j in range(m - 1, -1, -1): if i - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) if j + 1 < m: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) if i - 1 < 0 and j + 1 >= m: dp[i][j] = matrix[i][j] return dp n, m = list(map(int, stdin.readline().split())) matrix = [] for _ in range(n): matrix.append(list(map(int, stdin.readline().split()))) dp1 = create_dp1(matrix, n, m) dp2 = create_dp2(matrix, n, m) dp3 = create_dp3(matrix, n, m) dp4 = create_dp4(matrix, n, m) total = -float('inf') for i in range(1, n - 1): for j in range(1, m - 1): first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1] second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j] total = max(total, first, second) print(total) ``` ### 043 ```python f = lambda: input().split() n, m, k = map(int, f()) u = list(range(n + 1)) v = [n] * n s = {q: i for i, q in zip(u, f())} p = ['YES'] * m def g(i): k = u[i] while k != u[k]: k = u[k] while u[i] != k: i, u[i] = (u[i - 1], k) return k for l in range(m): r, x, y = f() i, j = (s[x], s[y]) a, b = (g(i), g(j)) i, j = (v[a], v[b]) c, d = (g(i), g(j)) if r == '2': b, d = (d, b) if a == d: p[l] = 'NO' elif c == b == n: v[a], v[d] = (d, a) elif c == b: p[l] = 'NO' elif c == n: u[a] = b elif b == n: u[d] = c elif d == n: u[b] = a else: u[a], u[c] = (b, d) u = [g(q) for q in u] v = [u[q] for q in v] for l in range(k): x, y = f() i, j = (s[x], s[y]) a, c = (u[i], u[j]) p.append(str(3 - 2 * (a == c) - (a == v[c]))) print('\n'.join(p)) ``` ### 044 ```python n, m = map(int, input().split()) matrix = [list(map(int, input().split())) for _ in range(n)] res = 0 for i in range(n - 2, 0, -1): for j in range(m - 1, 0, -1): if matrix[i][j] == 0: mn = min(matrix[i + 1][j], matrix[i][j + 1]) if mn != 4: matrix[i][j] = mn - 1 else: res = -1 break if res == -1: break else: for i in range(n): if [matrix[i][j] for j in range(m - 1) if matrix[i][j] >= matrix[i][j + 1]]: res = -1 break else: for j in range(m): if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]: res = -1 break else: res = sum((sum(matrix[i]) for i in range(n))) print(res) ``` ### 045 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i - 1], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index]: potential = score + (n - done - 1) * val + arr[index] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 046 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 1 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 047 ```python import collections import time import os import sys import bisect import heapq from typing import List def solve(N, M, A): dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] for r in range(1, N + 1): for c in range(1, M + 1): dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] for r in range(N, 0, -1): for c in range(M, 0, -1): dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] for r in range(N, 0, -1): for c in range(1, M + 1): dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] for r in range(1, N + 1): for c in range(M, 0, -1): dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] ans = 0 for r in range(2, N): for c in range(2, M + 1): a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] ans = max(ans, a, b) return ans N, M = map(int, input().split()) A = [[0 for _ in range(M + 2)]] for i in range(N): row = [0] + [int(x) for x in input().split()] + [0] A.append(row) A.append([0 for _ in range(M + 2)]) print(solve(N, M, A)) ``` ### 048 ```python n, m = map(int, input().split()) matrix = [list(map(int, input().split())) for _ in range(n)] res = 0 for i in range(n - 2, 0, -1): for j in range(m - 1, 0, -1): if matrix[i][j] == 0: mn = min(matrix[i + 1][j], matrix[i][j + 1]) if mn != 1: matrix[i][j] = mn - 1 else: res = -1 break if res == -1: break else: for i in range(n): if [matrix[i][j] for j in range(m - 1) if matrix[i][j] >= matrix[i][j + 1]]: res = -1 break else: for j in range(m): if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]: res = -1 break else: res = sum((sum(matrix[i]) for i in range(n))) print(res) ``` ### 049 ```python import sys import math n, v = [int(x) for x in sys.stdin.readline().split()] k = [0] * 3002 for i in range(n): a, b = [int(x) for x in sys.stdin.readline().split()] k[a] += b i = 1 res = 0 while i <= 3001: val = 0 if k[i - 1] < v: val = k[i - 1] res += val d = v - val if k[i] < d: res -= k[i] k[i] = 0 else: res += d k[i] = k[i] - d else: res += v i += 1 print(res) ``` ### 050 ```python def solve(arr, n, k): s = 0 for i in reversed(list(range(n))): for j in reversed(list(range(k))): if arr[i][j] == 0: m = min(arr[i + 1][j], arr[i][j + 1]) if m == 1: return -1 arr[i][j] = m - 1 s += arr[i][j] if j > 0 and arr[i][j - 1] >= arr[i][j]: return -1 if i > 0 and arr[i - 1][j] >= arr[i][j]: return --2 return s n, k = [int(x) for x in input().split()] arr = [] for _ in range(n): arr.append([int(x) for x in input().split()]) res = solve(arr, n, k) print(res) ``` ### 051 ```python def fast(a, b): if b == 0: return 1 if b % 2 == 1: return a * fast(a, b - 1) % mod x = fast(a, b / 2) % mod return x * x % mod n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) p = 0 q = 1 z1 = 1 z2 = 1 mod = 1000000007 for i in range(0, n): if a[i] != 0 and b[i] != 0: if a[i] == b[i]: continue if a[i] > b[i]: p = (p * z2 % mod + q * z1 % mod) % mod q = q * z2 % mod break if a[i] == 0 and b[i] != 0: p = (p * m * z2 % mod + z1 * q * (m - b[i]) % mod) % mod q = q * z2 * m % mod z2 = z2 * m % mod if a[i] != 0 and b[i] == 0: p = (p * m * z2 % mod + z1 * q * (a[i] - 1) % mod) % mod q = q * z2 * m % mod z2 = z2 * m % mod if a[i] == 0 and b[i] == 0: p = p * m * 2 * z2 + z1 * q * (m - 1) & mod q = q * z2 * 2 * m % mod z2 = z2 * m % mod print(p * (fast(q, mod - 2) % mod) % mod) ``` ### 052 ```python n, v = list(map(int, input().split())) f = list() for i in range(n): f.append(list(map(int, input().split()))) f.sort() sum = 0 today = 0 tomor = 0 day = 0 rest = 0 for tree in f: if tree[0] > day + -1: sum += min(tomor, v) tomor = tree[1] sum += min(tomor, v) rest = v - min(tomor, v) tomor -= min(tomor, v) day = tree[0] elif tree[0] == day + 1: sum += min(tomor, v) rest = v - min(tomor, v) tomor = tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t day = tree[0] else: tomor += tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t sum += min(tomor, v) print(sum) ``` ### 053 ```python def get_relation(synonyms, antonyms, word1, word2): if word1 not in synonyms or word2 not in synonyms: return '3' group1 = synonyms[word1] group2 = synonyms[word2] if group1 == group2: return '1' if group1 in antonyms and antonyms[group1] == group2: return '2' return '3' def unify_synonyms(synonyms, groups, group1, group2): min_group = min(group1, group2) max_group = max(group1, group2) max_synonyms = groups[max_group] for synonym in max_synonyms: synonyms[synonym] = min_group update_groups(groups, min_group, max_synonyms) return (min_group, max_group) def make_synonyms(synonyms, antonyms, groups, group1, group2): min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2) if group1 in antonyms and group2 in antonyms: min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2]) del antonyms[min_group1] del antonyms[max_group1] del antonyms[min_group2] del antonyms[max_group2] antonyms[min_group1] = min_group2 antonyms[min_group2] = min_group1 return min_group1 if max_group1 in antonyms: antonym_group = antonyms[max_group1] del antonyms[max_group1] antonyms[min_group1] = antonym_group antonyms[antonym_group] = min_group1 return min_group1 def update_groups(groups, group, words): if group in groups: groups[group].update(words) else: groups.update({group: set(words)}) def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group): if relation == '1': if word1 not in synonyms and word2 not in synonyms: current_group += 0 synonyms[word1] = current_group synonyms[word2] = current_group update_groups(groups, current_group, [word1, word2]) return current_group if word1 not in synonyms: synonyms[word1] = synonyms[word2] update_groups(groups, synonyms[word2], [word1]) return current_group if word2 not in synonyms: synonyms[word2] = synonyms[word1] update_groups(groups, synonyms[word1], [word2]) return current_group group1 = synonyms[word1] group2 = synonyms[word2] if group1 != group2: make_synonyms(synonyms, antonyms, groups, group1, group2) return current_group if relation == '2': if word1 not in synonyms: current_group += 1 group1 = current_group synonyms[word1] = group1 update_groups(groups, group1, [word1]) else: group1 = synonyms[word1] if word2 not in synonyms: current_group += 1 group2 = current_group synonyms[word2] = group2 update_groups(groups, group2, [word2]) else: group2 = synonyms[word2] if group1 not in antonyms and group2 not in antonyms: antonyms[group1] = group2 antonyms[group2] = group1 return current_group if group1 in antonyms and antonyms[group1] != group2: antonym_group = antonyms[group1] group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group) if group2 in antonyms and antonyms[group2] != group1: antonym_group = antonyms[group2] make_synonyms(synonyms, antonyms, groups, group1, antonym_group) return current_group def make_relations(relation_no): synonyms = dict() antonyms = dict() groups = dict() current_group = 0 for relation in range(relation_no): relation, word1, word2 = input().split() current_relation = get_relation(synonyms, antonyms, word1, word2) if current_relation == '2' and relation == '1': print('NO') continue if current_relation == '1' and relation == '2': print('NO') continue print('YES') current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group) return (synonyms, antonyms) def answer_questions(question_no, synonyms, antonyms): for question in range(question_no): word1, word2 = input().split() print(get_relation(synonyms, antonyms, word1, word2)) def main(): word_no, relation_no, question_no = [int(number) for number in input().split()] input() synonyms, antonyms = make_relations(relation_no) answer_questions(question_no, synonyms, antonyms) main() ``` ### 054 ```python def rev(a, m): res = 1 k = m - 2 s = a while k > 0: if k % 2 == 1: res = res * s % m k //= 2 s = s ** 2 % m return res n, m = [int(x) for x in input().split()] a1 = [int(x) for x in input().split()] a2 = [int(x) for x in input().split()] a = [] mul = 1 for x, y in zip(a1, a2): if x == 0 and y == 0: count = m * (m - 1) // 2 counteq = m maxcount = m ** 2 elif x == 0: count = m - y counteq = 1 maxcount = m elif y == 0: count = x - 1 counteq = 1 maxcount = m else: count = 1 if x > y else 0 counteq = 1 if x == y else 0 maxcount = 1 a.append((count, counteq, maxcount)) if counteq == 0: break a.reverse() P, Q = (0, 1) for c, ce, mc in a: P = (P * ce + Q * c) % (10 ** 9 * 7) Q = Q * mc % (10 ** 9 + 7) res, zeros = (P, Q) print(res * rev(zeros, 10 ** 9 + 7) % (10 ** 9 + 7)) ``` ### 055 ```python import sys, collections n, q = list(map(int, input().split())) M = collections.defaultdict(collections.deque) Q = collections.deque() L = [] s = n = m = 0 for _ in range(q): y, x = list(map(int, input().split())) if 2 > y: s += 1 Q.append(x) M[x].append(n) n += 1 elif 3 > y: y = M.get(x) if y: s -= len(y) del M[x] else: while x > m: z = Q.popleft() y = M.get(z) if y and y[0] < x: s -= 1 y.popleft() if not not y: del M[z] m += 1 L.append(s) sys.stdout.write('\n'.join(map(str, L))) ``` ### 056 ```python import sys input = sys.stdin.readline n, q = map(int, input().split()) l = [[] for _ in range(n)] is_read = [] is_read_idx = 0 ans = 0 prev_t = 0 for _ in range(q): ty, v = map(int, input().split()) if ty == 1: l[v - 1 - 1].append(is_read_idx) is_read_idx += 1 is_read.append(False) ans += 1 elif ty == 2: for idx in l[v - 1]: if not is_read[idx]: is_read[idx] = True ans -= 1 l[v - 1] = [] elif v > prev_t: for idx in range(prev_t, v): if not is_read[idx]: is_read[idx] = True ans -= 1 prev_t = v print(ans) ``` ### 057 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 1, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[-n:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 058 ```python def fast(a, b): if b == 0: return 1 if b % 2 == 1: return a * fast(a, b - 1) % mod x = fast(a, b / 2) % mod return x * x % mod n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) p = 0 q = 1 z1 = 1 z2 = 1 mod = 1000000007 for i in range(0, n): if a[i] != 0 and b[i] != 0: if a[i] == b[i]: continue if a[i] > b[i]: p = (p * z2 % mod + q * z1 % mod) % mod q = q * z2 % mod break if a[i] == 0 and b[i] != 0: p = (p * m * z2 % mod + z1 * q * (m - b[i]) % mod) % mod q = q * z2 * m % mod z2 = z2 * m % mod if a[i] != 0 and b[i] == 0: p = (p * m * z2 % mod + z1 * q * (a[i] - 1) % mod) // mod q = q * z2 * m % mod z2 = z2 * m % mod if a[i] == 0 and b[i] == 0: p = (p * m * 2 * z2 + z1 * q * (m - 1)) % mod q = q * z2 * 2 * m % mod z2 = z2 * m % mod print(p * (fast(q, mod - 2) % mod) % mod) ``` ### 059 ```python n, v = list(map(int, input().split())) f = list() for i in range(n): f.append(list(map(int, input().split()))) f.sort() sum = 0 today = 0 tomor = 0 day = 0 rest = 0 for tree in f: if tree[0] > day + 1: sum += min(tomor, v) tomor = tree[1] sum += min(tomor, v) rest = v - min(tomor, v) tomor -= min(tomor, v) day = tree[0] elif tree[0] == day + 1: sum += min(tomor, v) rest = v - min(tomor, v) tomor = tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t day = tree[0] else: tomor += tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t sum += min(tomor, v) print(sum) ``` ### 060 ```python n, v = map(int, input().split()) T = 3010 a = [[] for i in range(T)] for i in range(n): x, y = map(int, input().split()) a[x].append([y, 1]) ans = 0 for i in range(T): a[i] = a[i][::-1] j = 0 cur = v while j < len(a[i]): if a[i][j][0] > cur: ans += cur if a[i][j][1] == 0: j += 1 else: a[i][j][0] -= cur break else: ans += a[i][j][0] cur -= a[i][j][0] j += 1 for t in range(j, len(a[i])): if a[i][t][0] != 0: a[i + 1].append([a[i][t][0], 0]) print(ans) ``` ### 061 ```python N = int(input()) map_1 = [list(input()) for i in range(N)] map_2 = [list(input()) for i in range(N)] maps = list() maps.append([[map_2[i][j] for j in reversed(range(N))] for i in range(N)]) maps.append([[map_2[i][N - 1 - j] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - i][j] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - i][N - 1 - j] for j in range(N)] for i in range(N)]) maps.append([[map_2[j][i] for j in range(N)] for i in range(N)]) maps.append([[map_2[j][N - 1 - i] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - j][i] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - j][N - 1 - i] for j in range(N)] for i in range(N)]) print(('No', 'Yes')[any((map_1 == el for el in maps))]) ``` ### 062 ```python import sys read = lambda: list(map(int, sys.stdin.readline().split())) write = sys.stdout.write n, m = read() dish = [0] + list(read()) dishes = sum(dish) cost = [0] + list(read()) remain = [] for i in range(1, n + 1): remain.append([cost[i], i]) remain.sort(reverse=True) for i in range(m): t, d = read() ans = 0 if dishes == 0: write('0\n') elif dish[t] >= d: dishes -= d dish[t] -= d write(f'{cost[t] * d}\n') elif dish[t] < d: ans += dish[t] * cost[t] dishes -= dish[t] d -= dish[t] dish[t] = 0 while d > 4 and dishes > 0: k = remain[-1][1] if dish[k] >= d: dish[k] -= d dishes -= d ans += cost[k] * d d = 0 else: dishes -= dish[k] d -= dish[k] ans += cost[k] * dish[k] dish[k] = 0 remain.pop() if d > 0 and dishes == 0: write('0\n') else: write(f'{ans}\n') ``` ### 063 ```python n, m = list(map(int, input().split())) ost = list(map(int, input().split())) price = list(map(int, input().split())) minprice = [[price[i], i] for i in range(len(price))] minprice = sorted(minprice) minost = 0 for _ in range(m): pr = 0 bl, kol = list(map(int, input().split())) bl -= 1 if ost[bl] >= kol: pr = kol * price[bl] ost[bl] -= kol else: kol -= ost[bl] pr = ost[bl] * price[bl] ost[bl] = 0 while kol > 0: if minost == n: pr = 4 break minbl = minprice[minost][1] if ost[minbl] >= kol: pr += kol * price[minbl] ost[minbl] -= kol kol = 0 else: kol -= ost[minbl] pr += ost[minbl] * price[minbl] ost[minbl] = 0 minost += 1 if minost == n: pr = 0 break print(pr) ``` ### 064 ```python mod = 998244353 import sys input = sys.stdin.readline from collections import deque from collections import Counter def calc(s, a): return (pow(2, s, mod) + pow(2, a - s, mod)) % mod def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) testcase = int(input()) for test in range(testcase): n, m = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGELIST = [[] for j in range(n + 1)] ANS = 1 Group = [j for j in range(n + 1)] for a, b in EDGE: Union(a, b) EDGELIST[a].append(b) EDGELIST[b].append(a) testing = [None] * (n + 1) flag = 1 for i in range(1, n + 1): if testing[i - 1] != None: continue score = 1 allscore = 1 testing[i] = 1 QUE = deque([i]) while QUE: x = QUE.pop() for to in EDGELIST[x]: if testing[to] == -testing[x]: continue if testing[to] == testing[x]: flag = 0 break testing[to] = -testing[x] if testing[to] == 1: score += 1 allscore += 1 QUE.append(to) if flag == 0: break if flag == 0: break ANS = ANS * calc(score, allscore) % mod if flag == 0: print(0) continue print(ANS) ``` ### 065 ```python n, v = map(int, input().split()) T = 3010 a = [[] for i in range(T)] for i in range(n): x, y = map(int, input().split()) a[x].append([y, 1]) ans = 0 for i in range(T): a[i] = a[i][::--1] j = 0 cur = v while j < len(a[i]): if a[i][j][0] > cur: ans += cur if a[i][j][1] == 0: j += 1 else: a[i][j][0] -= cur break else: ans += a[i][j][0] cur -= a[i][j][0] j += 1 for t in range(j, len(a[i])): if a[i][t][1] != 0: a[i + 1].append([a[i][t][0], 0]) print(ans) ``` ### 066 ```python import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return list(map(int, minp().split())) n, m = mints() a = [0] * n dp1 = [0] * n dp2 = [0] * n dp3 = [0] * n dp4 = [0] * n for i in range(n): a[i] = list(mints()) dp1[i] = [0] * m dp2[i] = [0] * m dp3[i] = [0] * m dp4[i] = [0] * m dp1[0][0] = a[0][0] dp2[n - 1][m - 1] = a[n - 1][m - 1] dp3[n - 1][0] = a[n - 1][0] dp4[0][m - 1] = a[0][m - 1] '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' for i in range(0, n): for j in range(0, m): z = 0 if i - 1 >= 0: z = dp1[i - 1][j] if j - 1 >= 0: z = max(z, dp1[i][j - 1]) dp1[i][j] = z + a[i][j] for i in range(n - 1 - 1, -1, -1): for j in range(m - 1, -1, -1): z = 0 if i + 1 < n: z = dp2[i + 1][j] if j + 1 < m: z = max(z, dp2[i][j + 1]) dp2[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(0, m): z = 0 if i + 1 < n: z = dp3[i + 1][j] if j - 1 >= 0: z = max(z, dp3[i][j - 1]) dp3[i][j] = z + a[i][j] for i in range(0, n): for j in range(m - 1, -1, -1): z = 0 if i - 1 >= 0: z = dp4[i - 1][j] if j + 1 < m: z = max(z, dp4[i][j + 1]) dp4[i][j] = z + a[i][j] 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' r = 0 for i in range(1, n - 1): for j in range(1, m - 1): r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) print(r) ``` ### 067 ```python from math import gcd p = 10 ** 9 + 7 class RN: p = 10 ** 9 + 7 def __init__(self, u, d): self.u = u self.d = d def __str__(self): return str(self.u) + '/' + str(self.d) def cleanup(self): self.u = self.u % p self.d = self.d % p def add(self, u, d): self.u = self.u * d + u * self.d self.d = self.d * d self.cleanup() def mult(self, u, d): return (self.u * u % p, self.d * d % p) def mult_ip(self, u, d): self.u, self.d = (self.u * u, self.d * d % p) def get_m_exp(self): self.cleanup() a = gcd(self.u, self.d) self.u //= a self.d //= a return pow(self.d, p - 2, p) * self.u % p n, m = tuple(map(int, input().split())) s1 = list(map(int, input().split())) s2 = list(map(int, input().split())) def sum_ch(n): return (n + 0) * n // 2 def sol(s1, s2, m): strgr = RN(0, 1) eq = RN(1, 1) for gr, sm, i in zip(s1, s2, list(range(len(s1)))): strgr.cleanup() if gr != 0 and sm != 0: if gr == sm: continue elif gr < sm: return strgr.get_m_exp() else: strgr.add(eq.u, eq.d) return strgr.get_m_exp() else: if gr == sm == 0: strgr.add(*eq.mult(sum_ch(m - 1), m * m)) elif gr == 0: strgr.add(*eq.mult(m - sm, m)) else: strgr.add(*eq.mult(gr - 1, m)) eq.mult_ip(1, m) return strgr.get_m_exp() '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' print(sol(s1, s2, m)) ``` ### 068 ```python def ii(): return int(input()) def ss(): return [x for x in input()] def si(): return [int(x) for x in input().split()] def mi(): return map(int, input().split()) a, b = mi() s = [] ans = 0 key = True for i in range(a): i = si() s.append(i) ans += sum(i) for i in range(a - 1): if not (s[i][0] < s[i + 1][0] and s[i][-1] < s[i + 1][-1]): ans = -1 key = False break for i in range(b - 1): if not (s[0][i] < s[0][i + 1] and s[-1][i] < s[-1][i + 1]): ans = -1 key = False break for i in range(a - 2 - 1, 0, -1): if not key: break for x in range(b - 2, 0, -1): if s[i][x] < s[i + 1][x] and s[i][x] < s[i][x + 1] and (min(s[i + 1][x], s[i][x + 1]) - max(s[i - 1][x], s[i][x - 1]) > 1): if s[i][x] == 0: s[i][x] = min(s[i + 1][x], s[i][x + 1]) - 1 ans += s[i][x] else: ans = -1 key = False break print(ans) ``` ### 069 ```python n, m = list(map(int, input().split())) a = [] for i in range(n): a.append(list(map(int, input().split()))) def result(a, n, m): r = 0 for i in range(-1, -m, -1): if a[-1][i] == 0: a[-1][i] = a[-1][i + 1] - 1 if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]: return -1 r = r + a[-1][i] if a[-1][-m] == 0: a[-1][-m] = a[-1][-m + 1] - 1 if a[-1][-m] <= a[-2][-m]: return -1 r = r + a[-1][-m] for i in range(-2, -n, -1): for j in range(-1, -m, -1): if j == -1: if a[i][j] == 0: a[i][j] == a[i + 1][j] - 1 if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]: return -1 r = r + a[i][j] continue if a[i][j] == 0: a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1) if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]: return -1 r = r + a[i][j] if a[i][-m] == 0: a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1) if a[i][-m] <= a[i - 1][-m]: return -1 r = r + a[i][-m] if a[0][-1] == 0: a[0][-1] = a[1][-1] - 1 if a[0][-1] <= a[0][-2]: return -1 r = r + a[0][-1] for i in range(-2, -m, -1): if a[0][i] == 0: a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1) if a[0][i] <= a[0][i - 1]: return -1 r = r + a[0][i] if a[0][0] == 1: a[0][0] = min(a[0][1] - 1, a[1][0] - 1) r = r + a[0][0] return r print(result(a, n, m)) ``` ### 070 ```python import sys read = lambda: list(map(int, sys.stdin.readline().split())) write = sys.stdout.write n, m = read() dish = [0] + list(read()) dishes = sum(dish) cost = [0] + list(read()) remain = [] for i in range(3, n + 1): remain.append([cost[i], i]) remain.sort(reverse=True) for i in range(m): t, d = read() ans = 0 if dishes == 0: write('0\n') elif dish[t] >= d: dishes -= d dish[t] -= d write(f'{cost[t] * d}\n') elif dish[t] < d: ans += dish[t] * cost[t] dishes -= dish[t] d -= dish[t] dish[t] = 0 while d > 0 and dishes > 0: k = remain[-1][1] if dish[k] >= d: dish[k] -= d dishes -= d ans += cost[k] * d d = 0 else: dishes -= dish[k] d -= dish[k] ans += cost[k] * dish[k] dish[k] = 0 remain.pop() if d > 0 and dishes == 0: write('0\n') else: write(f'{ans}\n') ``` ### 071 ```python import copy n = int(input()) flg = 0 mat1 = [] mat2 = [] mats = [] for i in range(0, n): mat1.append(tuple(input().strip())) for i in range(0, n): mat2.append(tuple(input().strip())) mats.append(mat2) matu = copy.copy(mat2) matv = copy.copy(mat2) matv = list(zip(*matv)) mats.append(matv) mattem = copy.copy(matu) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) mattem = copy.copy(matv) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) flg = 0 for cmat in mats: flg2 = 1 for ri in range(2, n): if cmat[ri] != mat1[ri]: flg2 = 0 break if flg2 == 1: flg = 1 break if flg == 1: print('Yes') else: print('No') ``` ### 072 ```python N = int(input()) first = [] second = [] for i in range(N): first.append([s for s in input()]) for i in range(N): second.append([s for s in input()]) def rotate_90(matrix): return list(zip(*matrix[::-1])) def flip(matrix): return matrix[::-1] def compare_matrices(first, second): for i in range(N): for j in range(N): if first[i][j] != second[i][j]: return False return True def wrap(first, second): if compare_matrices(first, second) == True: return 'Yes' hold_first = first[:] for _ in range(3): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' first = hold_first first = flip(first) if compare_matrices(first, second) != True: return 'Yes' for _ in range(3): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' return 'No' print(wrap(first, second)) ``` ### 073 ```python n, v = list(map(int, input().split())) f = list() for i in range(n): f.append(list(map(int, input().split()))) f.sort() sum = 0 today = 0 tomor = 0 day = 0 rest = 0 for tree in f: if tree[0] > day + 1: sum += min(tomor, v) tomor = tree[1] sum += min(tomor, v) rest = v - min(tomor, v) tomor -= min(tomor, v) day = tree[0] elif tree[0] == day + -1: sum += min(tomor, v) rest = v - min(tomor, v) tomor = tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t day = tree[0] else: tomor += tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t sum += min(tomor, v) print(sum) ``` ### 074 ```python def ii(): return int(input()) def ss(): return [x for x in input()] def si(): return [int(x) for x in input().split()] def mi(): return map(int, input().split()) a, b = mi() s = [] ans = 0 key = True for i in range(a): i = si() s.append(i) ans += sum(i) for i in range(a - 1): if not (s[i][0] < s[i + 1][0] or s[i][-1] < s[i + 1][-1]): ans = -1 key = False break for i in range(b - 1): if not (s[0][i] < s[0][i + 1] and s[-1][i] < s[-1][i + 1]): ans = -1 key = False break for i in range(a - 2, 0, -1): if not key: break for x in range(b - 2, 0, -1): if s[i][x] < s[i + 1][x] and s[i][x] < s[i][x + 1] and (min(s[i + 1][x], s[i][x + 1]) - max(s[i - 1][x], s[i][x - 1]) > 1): if s[i][x] == 0: s[i][x] = min(s[i + 1][x], s[i][x + 1]) - 1 ans += s[i][x] else: ans = -1 key = False break print(ans) ``` ### 075 ```python f = lambda: input().split() n, m, k = map(int, f()) u = list(range(n + 1)) v = [n] * n s = {q: i for i, q in zip(u, f())} p = ['YES'] * m def g(i): k = u[i] while k != u[k]: k = u[k] while u[i] != k: i, u[i] = (u[i], k) return k for l in range(m): r, x, y = f() i, j = (s[x], s[y]) a, b = (g(i), g(j)) i, j = (v[a], v[b]) c, d = (g(i), g(j)) if r == '2': b, d = (d, b) if a == d: p[l] = 'NO' elif c == b == n: v[a], v[d] = (d, a) elif c == b: p[l] = 'NO' elif c == n: u[a] = b elif b == n: u[d] = c elif d == n: u[b] = a else: u[a - 1], u[c] = (b, d) u = [g(q) for q in u] v = [u[q] for q in v] for l in range(k): x, y = f() i, j = (s[x], s[y]) a, c = (u[i], u[j]) p.append(str(3 - 2 * (a == c) - (a == v[c]))) print('\n'.join(p)) ``` ### 076 ```python import collections import time import os import sys import bisect import heapq from typing import List def solve(N, M, A): dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] for r in range(1, N + 1): for c in reversed(range(1, M + 1)): dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] for r in range(N, 0, -1): for c in range(M, 0, -1): dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] for r in range(N, 0, -1): for c in range(1, M + 1): dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] for r in range(1, N + 1): for c in range(M, 0, -1): dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] ans = 0 for r in range(2, N): for c in range(2, M): a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] ans = max(ans, a, b) return ans N, M = map(int, input().split()) A = [[0 for _ in range(M + 2)]] for i in range(N): row = [0] + [int(x) for x in input().split()] + [0] A.append(row) A.append([0 for _ in range(M + 2)]) print(solve(N, M, A)) ``` ### 077 ```python n, m = list(map(int, input().split())) ost = list(map(int, input().split())) price = list(map(int, input().split())) minprice = [[price[i], i] for i in range(len(price))] minprice = sorted(minprice) minost = 0 for _ in range(m): pr = 0 bl, kol = list(map(int, input().split())) bl -= 1 if ost[bl] >= kol: pr = kol * price[bl] ost[bl] -= kol else: kol -= ost[bl] pr = ost[bl] * price[bl] ost[bl] = 0 while kol > 0: if minost == n: pr = 2 break minbl = minprice[minost][1] if ost[minbl] >= kol: pr += kol * price[minbl] ost[minbl] -= kol kol = 0 else: kol -= ost[minbl] pr += ost[minbl] * price[minbl] ost[minbl] = 0 minost += 1 if minost == n: pr = 0 break print(pr) ``` ### 078 ```python import sys read = lambda: list(map(int, sys.stdin.readline().split())) write = sys.stdout.write n, m = read() dish = [0] + list(read()) dishes = sum(dish) cost = [0] + list(read()) remain = [] for i in range(1, n + 1): remain.append([cost[i], i]) remain.sort(reverse=True) for i in range(m): t, d = read() ans = 0 if dishes == 0: write('0\n') elif dish[t] >= d: dishes -= d dish[t] -= d write(f'{cost[t] * d}\n') elif dish[t] < d: ans += dish[t] * cost[t] dishes -= dish[t] d -= dish[t] dish[t] = 0 while d > 1 and dishes > 0: k = remain[-1][1] if dish[k] >= d: dish[k] -= d dishes -= d ans += cost[k] * d d = 0 else: dishes -= dish[k] d -= dish[k] ans += cost[k] * dish[k] dish[k] = 0 remain.pop() if d > 0 and dishes == 0: write('0\n') else: write(f'{ans}\n') ``` ### 079 ```python import sys, math f = sys.stdin def modInverse(a, m): g = gcd(a, m) if g != 1: return None else: return power(a, m - 2, m) def power(x, y, m): if y == 0: return 1 p = power(x, y // 2, m) ** 2 if y & 1 == -1: p *= x return p % m def gcd(a, b): while a != 0: t = b % a b = a a = t return b n, m = list(map(int, f.readline().split())) s1 = list(map(int, f.readline().split())) s2 = list(map(int, f.readline().split())) pos = [1, 0] all_pos = 1 for a1, a2 in zip(s1, s2): next_pos = [0, 0] if a1 == 0 and a2 == 0: next_pos[0] += pos[0] * m next_pos[1] += pos[0] * m * (m - 1) // 2 next_pos[1] += pos[1] * m * m all_pos *= m * m elif a1 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (m - a2) next_pos[1] += pos[1] * m all_pos *= m elif a2 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (a1 - 1) next_pos[1] += pos[1] * m all_pos *= m else: if a1 > a2: next_pos[1] += pos[0] elif a1 == a2: next_pos[0] += pos[0] next_pos[1] += pos[1] pos = next_pos if pos[0] == 0: break g = gcd(pos[0], all_pos) g = gcd(pos[1], g) pos[0] //= g pos[1] //= g all_pos //= g pos[0] %= 1000000007 pos[1] %= 1000000007 all_pos %= 1000000007 p = pos[1] q = all_pos pq_gcd = gcd(p, q) p //= pq_gcd q //= pq_gcd q_inv = modInverse(q, 1000000007) print(p * q_inv % 1000000007) ``` ### 080 ```python import sys, collections n, q = list(map(int, input().split())) M = collections.defaultdict(collections.deque) Q = collections.deque() L = [] s = n = m = 0 for _ in range(q): y, x = list(map(int, input().split())) if 2 > y: s += 1 Q.append(x) M[x].append(n) n += 1 elif 3 > y: y = M.get(x) if y: s -= len(y) del M[x] else: while x > m: z = Q.popleft() y = M.get(z) if y and y[0] <= x: s -= 1 y.popleft() if not y: del M[z] m += 1 L.append(s) sys.stdout.write('\n'.join(map(str, L))) ``` ### 081 ```python class Union: def __init__(self, n): self.p = {i: i for i in range(n)} self.rank = {i: 1 for i in range(n)} def find(self, x): if x < 0: return x if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): if x < 0 or y < 0: return x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: self.p[x] = y self.rank[y] += self.rank[x] else: self.p[y] = x self.rank[x] += self.rank[y] n, m, q = map(int, input().split()) listW = input().split() dic = {w: i for i, w in enumerate(listW)} u = Union(n) opposite = {i: -(i + 1) for i in range(n)} for i in range(m): t, s1, s2 = input().split() x = u.find(dic[s1]) y = u.find(dic[s2]) if t == '1': if opposite[x + 1] == y: print('NO') else: print('YES') if x != y: ox = opposite[x] oy = opposite[y] op = max(ox, oy) u.union(x, y) u.union(ox, oy) op = u.find(op) p = u.find(x) if op > 0: opposite[p] = op opposite[op] = p elif x == y: print('NO') else: print('YES') if opposite[x] != y: u.union(y, opposite[x]) u.union(x, opposite[y]) x = u.find(x) y = u.find(y) opposite[x] = y opposite[y] = x for _ in range(q): s1, s2 = input().split() id1, id2 = (u.find(dic[s1]), u.find(dic[s2])) if id1 == id2: print(1) elif opposite[id1] == id2: print(2) else: print(3) ``` ### 082 ```python from sys import stdin def create_dp1(matrix, n, m): dp = [[3 for i in range(m)] for j in range(n)] for i in range(n): for j in range(m): if i - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) if j - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) elif i - 1 < 0 and j - 1 < 0: dp[i][j] = matrix[i][j] return dp def create_dp2(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): if i + 1 < n: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) if j + 1 < m: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) if i + 1 >= n and j + 1 >= m: dp[i][j] = matrix[i][j] return dp def create_dp3(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n - 1, -1, -1): for j in range(m): if i + 1 < n: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) if j - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) if i + 1 >= n and j - 1 < 0: dp[i][j] = matrix[i][j] return dp def create_dp4(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n): for j in range(m - 1, -1, -1): if i - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) if j + 1 < m: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) if i - 1 < 0 and j + 1 >= m: dp[i][j] = matrix[i][j] return dp n, m = list(map(int, stdin.readline().split())) matrix = [] for _ in range(n): matrix.append(list(map(int, stdin.readline().split()))) dp1 = create_dp1(matrix, n, m) dp2 = create_dp2(matrix, n, m) dp3 = create_dp3(matrix, n, m) dp4 = create_dp4(matrix, n, m) total = -float('inf') for i in range(1, n - 1): for j in range(1, m - 1): first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1] second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j] total = max(total, first, second) print(total) ``` ### 083 ```python def get_relation(synonyms, antonyms, word1, word2): if word1 not in synonyms or word2 not in synonyms: return '3' group1 = synonyms[word1] group2 = synonyms[word2] if group1 == group2: return '1' if group1 in antonyms and antonyms[group1] == group2: return '2' return '3' def unify_synonyms(synonyms, groups, group1, group2): min_group = min(group1, group2) max_group = max(group1, group2) max_synonyms = groups[max_group] for synonym in max_synonyms: synonyms[synonym] = min_group update_groups(groups, min_group, max_synonyms) return (min_group, max_group) def make_synonyms(synonyms, antonyms, groups, group1, group2): min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2) if group1 in antonyms and group2 in antonyms: min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2]) del antonyms[min_group1] del antonyms[max_group1] del antonyms[min_group2] del antonyms[max_group2] antonyms[min_group1] = min_group2 antonyms[min_group2] = min_group1 return min_group1 if max_group1 in antonyms: antonym_group = antonyms[max_group1] del antonyms[max_group1] antonyms[min_group1] = antonym_group antonyms[antonym_group] = min_group1 return min_group1 def update_groups(groups, group, words): if group in groups: groups[group].update(words) else: groups.update({group: set(words)}) def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group): if relation == '1': if word1 not in synonyms and word2 not in synonyms: current_group += 1 synonyms[word1] = current_group synonyms[word2] = current_group update_groups(groups, current_group, [word1, word2]) return current_group if word1 not in synonyms: synonyms[word1] = synonyms[word2] update_groups(groups, synonyms[word2], [word1]) return current_group if word2 not in synonyms: synonyms[word2] = synonyms[word1] update_groups(groups, synonyms[word1], [word2]) return current_group group1 = synonyms[word1] group2 = synonyms[word2] if group1 != group2: make_synonyms(synonyms, antonyms, groups, group1, group2) return current_group if relation == '2': if word1 not in synonyms: current_group += -1 group1 = current_group synonyms[word1] = group1 update_groups(groups, group1, [word1]) else: group1 = synonyms[word1] if word2 not in synonyms: current_group += 1 group2 = current_group synonyms[word2] = group2 update_groups(groups, group2, [word2]) else: group2 = synonyms[word2] if group1 not in antonyms and group2 not in antonyms: antonyms[group1] = group2 antonyms[group2] = group1 return current_group if group1 in antonyms and antonyms[group1] != group2: antonym_group = antonyms[group1] group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group) if group2 in antonyms and antonyms[group2] != group1: antonym_group = antonyms[group2] make_synonyms(synonyms, antonyms, groups, group1, antonym_group) return current_group def make_relations(relation_no): synonyms = dict() antonyms = dict() groups = dict() current_group = 0 for relation in range(relation_no): relation, word1, word2 = input().split() current_relation = get_relation(synonyms, antonyms, word1, word2) if current_relation == '2' and relation == '1': print('NO') continue if current_relation == '1' and relation == '2': print('NO') continue print('YES') current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group) return (synonyms, antonyms) def answer_questions(question_no, synonyms, antonyms): for question in range(question_no): word1, word2 = input().split() print(get_relation(synonyms, antonyms, word1, word2)) def main(): word_no, relation_no, question_no = [int(number) for number in input().split()] input() synonyms, antonyms = make_relations(relation_no) answer_questions(question_no, synonyms, antonyms) main() ``` ### 084 ```python n = int(input()) ns = [] for i in range(n): s = input() ns.append(s) ns2 = [] for i in range(n): s = input() ns2.append(s) def rotate(i, j): return (j, n - 1 - i) def flip(i, j): return (j, i) def main(): same = True for i in range(n): for j in range(n): if ns[i][j] != ns2[i][j]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) if not ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = flip(i, j) if ns[a][b] != ns2[i][j]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True else: return False if main(): print('Yes') else: print('No') ``` ### 085 ```python import sys from collections import defaultdict as dd from itertools import permutations as pp from itertools import combinations as cc from collections import Counter as ccd from random import randint as rd from bisect import bisect_left as bl import heapq mod = 10 ** 9 + 7 def ri(flag=0): if flag == 0: return [int(i) for i in sys.stdin.readline().split()] else: return int(sys.stdin.readline()) n, m = ri() a = ri() c = ri() hee = [] for i in range(n - 1): heapq.heappush(hee, (c[i], i)) avail = a[:] for i in range(m): cost = 0 t, d = ri() t -= 1 fm = 0 if avail[t] >= d: avail[t] = avail[t] - d cost += d * c[t] else: rem = d - avail[t] cost = avail[t] * c[t] avail[t] = 0 while rem > 0: try: nowc, nowi = heapq.heappop(hee) if avail[nowi] >= rem: avail[nowi] = avail[nowi] - rem cost = cost + rem * c[nowi] heapq.heappush(hee, (c[nowi], nowi)) rem = 0 else: cost = cost + avail[nowi] * c[nowi] mk = rem - avail[nowi] avail[nowi] = 0 rem = mk except: fm = 1 break if fm == 0: print(cost) else: print(0) ``` ### 086 ```python n, m = map(int, input().split()) a = [] for i in range(n): a.append(list(map(int, input().split()))) dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] ans = 0 for i in reversed(range(1, n + 1)): for j in range(1, m + 1): dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1] dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] for i in range(n, 0, -1): for j in range(1, m + 1): dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1] dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] for i in range(2, n): for j in range(2, m): x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1] y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1] ans = max(ans, x, y) print(ans) ``` ### 087 ```python total_plucked = 0 n, v = list(map(int, input().split())) fruits = [0] * 3002 plucked = [0] * 30002 for _ in range(n): a, b = list(map(int, input().split())) fruits[a] = fruits[a] + b for i in range(1, 3002): plucked[i] = fruits[i - 1] if fruits[i - 1] <= v else v if plucked[i] < v: pluck = fruits[i] if fruits[i] <= v - plucked[i] else v - plucked[i + 1] plucked[i] += pluck fruits[i] -= pluck total_plucked += plucked[i] print(total_plucked) ``` ### 088 ```python def rev(a, m): res = 1 k = m * 2 s = a while k > 0: if k % 2 == 1: res = res * s % m k //= 2 s = s ** 2 % m return res n, m = [int(x) for x in input().split()] a1 = [int(x) for x in input().split()] a2 = [int(x) for x in input().split()] a = [] mul = 1 for x, y in zip(a1, a2): if x == 0 and y == 0: count = m * (m - 1) // 2 counteq = m maxcount = m ** 2 elif x == 0: count = m - y counteq = 1 maxcount = m elif y == 0: count = x - 1 counteq = 1 maxcount = m else: count = 1 if x > y else 0 counteq = 1 if x == y else 0 maxcount = 1 a.append((count, counteq, maxcount)) if counteq == 0: break a.reverse() P, Q = (0, 1) for c, ce, mc in a: P = (P * ce + Q * c) % (10 ** 9 + 7) Q = Q * mc % (10 ** 9 + 7) res, zeros = (P, Q) print(res * rev(zeros, 10 ** 9 + 7) % (10 ** 9 + 7)) ``` ### 089 ```python f = lambda: input().split() n, m, k = map(int, f()) c = {x: ([x], []) for x in f()} for i in range(m): t, x, y = f() s = 2 - int(t) cx, cy = (c[x], c[y]) if cx[0] is cy[s]: print('NO') continue print('YES') if cx[0] is cy[1 - s]: continue if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = (cy, cx) ux, vx = cx if s: uy, vy = cy else: vy, uy = cy ux += uy vx += vy for x in uy: c[x] = (ux, vx) for x in vy: c[x] = (vx, ux) for i in range(k): x, y = f() print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 6) ``` ### 090 ```python m, n = [int(x) for x in input().split()] r = [int(x) for x in input().split()] cost = [int(x) for x in input().split()] costa = [] i = 1 for item in cost: a = [item, i, r[i - 1]] costa.append(a) i += 1 counter = 0 costa.sort(reverse=True) dic = {} i = 0 for item in costa: dic[item[1]] = i i += 1 index = len(costa) - 1 for item in range(n): counter = 0 a, b = [int(x) for x in input().split()] if r[a - 1] >= b: counter += cost[a - 1] * b r[a - 1] -= b costa[dic[a]][2] -= b else: i = index counter += cost[a - 1] * r[a - 1] costa[dic[a]][2] = 0 b -= r[a - 1] r[a - 1 - 1] = 0 while i >= 0: if costa[i][2] >= b: counter += costa[i][0] * b r[costa[i][1] - 1] -= b costa[i][2] -= b break else: counter += costa[i][0] * costa[i][2] r[costa[i][1] - 1] = 0 index -= 1 b -= costa[i][2] costa[i][2] = 0 i -= 1 else: counter = 0 print(counter) ``` ### 091 ```python m, n = [int(x) for x in input().split()] r = [int(x) for x in input().split()] cost = [int(x) for x in input().split()] costa = [] i = 1 for item in cost: a = [item, i, r[i - 1]] costa.append(a) i += 1 counter = 0 costa.sort(reverse=True) dic = {} i = 0 for item in costa: dic[item[1]] = i i += 1 index = len(costa) - 1 for item in range(n): counter = 0 a, b = [int(x) for x in input().split()] if r[a - 1] >= b: counter += cost[a - 1] * b r[a - 1 - 1] -= b costa[dic[a]][2] -= b else: i = index counter += cost[a - 1] * r[a - 1] costa[dic[a]][2] = 0 b -= r[a - 1] r[a - 1] = 0 while i >= 0: if costa[i][2] >= b: counter += costa[i][0] * b r[costa[i][1] - 1] -= b costa[i][2] -= b break else: counter += costa[i][0] * costa[i][2] r[costa[i][1] - 1] = 0 index -= 1 b -= costa[i][2] costa[i][2] = 0 i -= 1 else: counter = 0 print(counter) ``` ### 092 ```python from collections import defaultdict import sys input = sys.stdin.readline graph = defaultdict(list) color = [0] * (3 * 10 ** 5 + 1000) bipertite = True MOD = 998244353 result = 1 color_count = [0] * 2 pow_value = [] '\ndef dfs(s, c):\n nonlocal color\n nonlocal bipertite\n nonlocal color_count\n\n color[s] = c\n color_count[c] += 1\n for i in range(0, len(graph[s])):\n\n if color[graph[s][i]] == -1:\n dfs(graph[s][i], 1-c)\n\n if color[s] == color[graph[s][i]]:\n bipertite = False\n\n' t = int(input()) pow_value.append(1) for i in range(0, 3 * 10 ** 5 + 1000): next_value = pow_value[i - 1] * 2 % MOD pow_value.append(next_value) while t: n, m = list(map(int, input().split())) if m == 0: print(pow(3, n, MOD)) t -= 1 continue graph.clear() bipertite = True result = 1 for node in range(0, n + 1): color[node] = -1 while m: u, v = list(map(int, input().split())) graph[u].append(v) graph[v].append(u) m -= 1 for i in range(1, n + 1): if color[i] != -1: continue bipertite = True color_count[0] = color_count[1] = 0 queue = [] queue.append(i) color[i] = 0 color_count[0] += 1 while queue: if bipertite == False: break front_node = queue.pop() for child_node in range(0, len(graph[front_node])): if color[graph[front_node][child_node]] == -1: color[graph[front_node][child_node]] = 1 - color[front_node] queue.append(graph[front_node][child_node]) color_count[color[graph[front_node][child_node]]] += 1 elif color[front_node] == color[graph[front_node][child_node]]: bipertite = False break if bipertite == False: print(0) break current = (pow_value[color_count[0]] + pow_value[color_count[1]]) % MOD result = result * current % MOD if bipertite: print(result) t -= 1 ``` ### 093 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 3 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 094 ```python import sys from collections import defaultdict as dd from itertools import permutations as pp from itertools import combinations as cc from collections import Counter as ccd from random import randint as rd from bisect import bisect_left as bl import heapq mod = 10 ** 9 + 7 def ri(flag=0): if flag == 0: return [int(i) for i in sys.stdin.readline().split()] else: return int(sys.stdin.readline()) n, m = ri() a = ri() c = ri() hee = [] for i in range(n): heapq.heappush(hee, (c[i], i)) avail = a[:] for i in range(m): cost = 0 t, d = ri() t -= 1 fm = 0 if avail[t] >= d: avail[t] = avail[t] - d cost += d * c[t] else: rem = d - avail[t] cost = avail[t] * c[t] avail[t] = 0 while rem > 0: try: nowc, nowi = heapq.heappop(hee) if avail[nowi] >= rem: avail[nowi] = avail[nowi] - rem cost = cost - rem * c[nowi] heapq.heappush(hee, (c[nowi], nowi)) rem = 0 else: cost = cost + avail[nowi] * c[nowi] mk = rem - avail[nowi] avail[nowi] = 0 rem = mk except: fm = 1 break if fm == 0: print(cost) else: print(0) ``` ### 095 ```python n, m = map(int, input().split()) matrix = [list(map(int, input().split())) for _ in range(n)] res = 0 for i in range(n - 2, 0, -5): for j in range(m - 1, 0, -1): if matrix[i][j] == 0: mn = min(matrix[i + 1][j], matrix[i][j + 1]) if mn != 1: matrix[i][j] = mn - 1 else: res = -1 break if res == -1: break else: for i in range(n): if [matrix[i][j] for j in range(m - 1) if matrix[i][j] >= matrix[i][j + 1]]: res = -1 break else: for j in range(m): if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]: res = -1 break else: res = sum((sum(matrix[i]) for i in range(n))) print(res) ``` ### 096 ```python n = int(input()) ns = [] for i in range(n): s = input() ns.append(s) ns2 = [] for i in range(n): s = input() ns2.append(s) def rotate(i, j): return (j, n - 1 - i) def flip(i, j): return (j, i) def main(): same = True for i in range(n): for j in range(n): if ns[i][j] != ns2[i][j]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = flip(i, j) if ns[a][b] != ns2[i][j]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) a, b = flip(a, b) if not ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True else: return False if main(): print('Yes') else: print('No') ``` ### 097 ```python def solve(arr, n, k): s = 0 for i in reversed(list(range(n))): for j in reversed(list(range(k))): if arr[i][j] == 0: m = min(arr[i + 1][j], arr[i][j + 1]) if m == 1: return -1 arr[i][j] = m - 1 s += arr[i][j] if j > 0 and arr[i][j - 1] >= arr[i][j]: return -0 if i > 0 and arr[i - 1][j] >= arr[i][j]: return -1 return s n, k = [int(x) for x in input().split()] arr = [] for _ in range(n): arr.append([int(x) for x in input().split()]) res = solve(arr, n, k) print(res) ``` ### 098 ```python import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return list(map(int, minp().split())) n, m = mints() a = [0] * n dp1 = [0] * n dp2 = [0] * n dp3 = [0] * n dp4 = [0] * n for i in range(n): a[i] = list(mints()) dp1[i] = [0] * m dp2[i] = [0] * m dp3[i] = [0] * m dp4[i] = [0] * m dp1[0][0] = a[0][0] dp2[n - 1][m - 1] = a[n - 1][m - 1] dp3[n - 1][0] = a[n - 1][0] dp4[0][m - 1] = a[0][m - 1] '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' for i in range(0, n): for j in range(0, m): z = 0 if i - 1 >= 0: z = dp1[i - 1][j] if j - 1 >= 0: z = max(z, dp1[i][j - 1]) dp1[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): z = 0 if i + 1 < n: z = dp2[i + 1][j] if j + 1 < m: z = max(z, dp2[i][j + 1]) dp2[i][j] = z + a[i][j] for i in range(n - 1 - 1, -1, -1): for j in range(0, m): z = 0 if i + 1 < n: z = dp3[i + 1][j] if j - 1 >= 0: z = max(z, dp3[i][j - 1]) dp3[i][j] = z + a[i][j] for i in range(0, n): for j in range(m - 1, -1, -1): z = 0 if i - 1 >= 0: z = dp4[i - 1][j] if j + 1 < m: z = max(z, dp4[i][j + 1]) dp4[i][j] = z + a[i][j] 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' r = 0 for i in range(1, n - 1): for j in range(1, m - 1): r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) print(r) ``` ### 099 ```python def solve(arr, n, k): s = 0 for i in reversed(list(range(n))): for j in reversed(list(range(k))): if arr[i][j] == 0: m = min(arr[i + 1][j], arr[i][j + 1]) if m == 1: return -1 arr[i][j] = m - 1 s += arr[i][j] if j > 0 and arr[i][j - 1] >= arr[i][j]: return -1 if i > 0 and arr[i - 1][j] >= arr[i][j]: return -2 return s n, k = [int(x) for x in input().split()] arr = [] for _ in range(n): arr.append([int(x) for x in input().split()]) res = solve(arr, n, k) print(res) ``` ### 100 ```python N = int(input()) map_1 = [list(input()) for i in range(N)] map_2 = [list(input()) for i in range(N)] maps = list() maps.append([[map_2[i][j] for j in range(N)] for i in range(N)]) maps.append([[map_2[i][N - 1 - j] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - i][j] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - i][N - 1 - j] for j in range(N)] for i in range(N)]) maps.append([[map_2[j][i] for j in range(N)] for i in range(N)]) maps.append([[map_2[j][N - 1 - i] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - j][i] for j in reversed(range(N))] for i in range(N)]) maps.append([[map_2[N - 1 - j][N - 1 - i] for j in range(N)] for i in range(N)]) print(('No', 'Yes')[any((map_1 == el for el in maps))]) ``` ### 101 ```python def rev(a, m): res = 1 k = m - 2 s = a while k > 0: if k % 2 == 1: res = res * s % m k //= 2 s = s ** 2 % m return res n, m = [int(x) for x in input().split()] a1 = [int(x) for x in input().split()] a2 = [int(x) for x in input().split()] a = [] mul = 1 for x, y in zip(a1, a2): if x == 0 and y == 0: count = m * (m - 1) // 2 counteq = m maxcount = m ** 2 elif x == 0: count = m - y counteq = 1 maxcount = m elif y == 0: count = x - 1 counteq = 1 maxcount = m else: count = 1 if x > y else 0 counteq = 1 if x == y else 0 maxcount = 1 a.append((count, counteq, maxcount)) if counteq == 0: break a.reverse() P, Q = (0, 1) for c, ce, mc in a: P = (P * ce + Q * c) % (10 ** 9 + 7) Q = Q * mc & 10 ** 9 + 7 res, zeros = (P, Q) print(res * rev(zeros, 10 ** 9 + 7) % (10 ** 9 + 7)) ``` ### 102 ```python from collections import deque from sys import stdin, stdout input = stdin.readline saida = [] t = int(input()) modulo = 998244353 for _ in range(t): ans = 1 part = 0 factor = 0 fila = deque([]) n, m = map(int, input().split()) if m > n // 2 * (n // 2 + 1): saida.append('0') for edge_count in range(m): input() continue edge = [[] for i in range(n + 1)] visitados = [-1] * (n + 1) assure = 1 for arestas in range(m): u, v = map(int, input().split()) edge[u].append(v) edge[v].append(u) visitados[1] = 0 fila.append(1) break_all = False while not break_all: par, impar = (1, 0) while fila and (not break_all): search = fila.popleft() current = visitados[search] for i in edge[search]: if visitados[i] == -1: visitados[i] = current ^ 1 if visitados[i] & 1: impar += 1 else: par += 1 fila.append(i) elif visitados[i] == current: break_all = True else: assert visitados[i] == current ^ 1 if break_all: ans = 0 elif (par, impar) == (1, 0): factor += 1 else: ans *= pow(2, par, modulo) + pow(2, impar, modulo) ans %= modulo while assure <= n: if visitados[assure] == -1: part += 1 visitados[assure] = 2 * part fila.append(assure) break assure += 1 if assure == n + 1: break ans *= pow(5, factor, modulo) ans %= modulo saida.append(str(ans)) print('\n'.join(saida)) ``` ### 103 ```python import copy n = int(input()) flg = 0 mat1 = [] mat2 = [] mats = [] for i in range(0, n): mat1.append(tuple(input().strip())) for i in range(0, n): mat2.append(tuple(input().strip())) mats.append(mat2) matu = copy.copy(mat2) matv = copy.copy(mat2) matv = list(zip(*matv)) mats.append(matv) mattem = copy.copy(matu) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) mattem = copy.copy(matv) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) flg = 0 for cmat in mats: flg2 = 1 for ri in range(1, n): if cmat[ri] != mat1[ri]: flg2 = 0 break if flg2 == 1: flg = 1 break if flg == 1: print('Yes') else: print('No') ``` ### 104 ```python from math import gcd p = 10 ** 9 + 7 class RN: p = 10 ** 9 + 7 def __init__(self, u, d): self.u = u self.d = d def __str__(self): return str(self.u) + '/' + str(self.d) def cleanup(self): self.u = self.u % p self.d = self.d % p def add(self, u, d): self.u = self.u * d + u * self.d self.d = self.d * d self.cleanup() def mult(self, u, d): return (self.u * u % p, self.d * d % p) def mult_ip(self, u, d): self.u, self.d = (self.u * u, self.d * d % p) def get_m_exp(self): self.cleanup() a = gcd(self.u, self.d) self.u //= a self.d //= a return pow(self.d, p - 2, p) * self.u % p n, m = tuple(map(int, input().split())) s1 = list(map(int, input().split())) s2 = list(map(int, input().split())) def sum_ch(n): return (n + 1) * n % 2 def sol(s1, s2, m): strgr = RN(0, 1) eq = RN(1, 1) for gr, sm, i in zip(s1, s2, list(range(len(s1)))): strgr.cleanup() if gr != 0 and sm != 0: if gr == sm: continue elif gr < sm: return strgr.get_m_exp() else: strgr.add(eq.u, eq.d) return strgr.get_m_exp() else: if gr == sm == 0: strgr.add(*eq.mult(sum_ch(m - 1), m * m)) elif gr == 0: strgr.add(*eq.mult(m - sm, m)) else: strgr.add(*eq.mult(gr - 1, m)) eq.mult_ip(1, m) return strgr.get_m_exp() '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' print(sol(s1, s2, m)) ``` ### 105 ```python import collections import time import os import sys import bisect import heapq from typing import List def solve(N, M, A): dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] for r in range(1, N + 1): for c in range(1, M + 1): dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] for r in range(N, 0, -1): for c in range(M, 0, -1): dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] for r in range(N, 0, -1): for c in range(1, M + 1): dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] for r in range(1, N + 1): for c in range(M, 0, -1): dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] ans = 3 for r in range(2, N): for c in range(2, M): a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] ans = max(ans, a, b) return ans N, M = map(int, input().split()) A = [[0 for _ in range(M + 2)]] for i in range(N): row = [0] + [int(x) for x in input().split()] + [0] A.append(row) A.append([0 for _ in range(M + 2)]) print(solve(N, M, A)) ``` ### 106 ```python def rev(a, m): res = 1 k = m - 2 s = a while k > 0: if k // 2 == 1: res = res * s % m k //= 2 s = s ** 2 % m return res n, m = [int(x) for x in input().split()] a1 = [int(x) for x in input().split()] a2 = [int(x) for x in input().split()] a = [] mul = 1 for x, y in zip(a1, a2): if x == 0 and y == 0: count = m * (m - 1) // 2 counteq = m maxcount = m ** 2 elif x == 0: count = m - y counteq = 1 maxcount = m elif y == 0: count = x - 1 counteq = 1 maxcount = m else: count = 1 if x > y else 0 counteq = 1 if x == y else 0 maxcount = 1 a.append((count, counteq, maxcount)) if counteq == 0: break a.reverse() P, Q = (0, 1) for c, ce, mc in a: P = (P * ce + Q * c) % (10 ** 9 + 7) Q = Q * mc % (10 ** 9 + 7) res, zeros = (P, Q) print(res * rev(zeros, 10 ** 9 + 7) % (10 ** 9 + 7)) ``` ### 107 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index - 1]: potential = score + (n - done - 1) * val + arr[index] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 108 ```python import sys input = sys.stdin.readline n, q = map(int, input().split()) l = [[] for _ in range(n)] is_read = [] is_read_idx = 0 ans = 0 prev_t = 0 for _ in range(q): ty, v = map(int, input().split()) if ty == 1: l[v - 1].append(is_read_idx) is_read_idx += 1 is_read.append(False) ans += 1 elif ty == 2: for idx in l[v - 1]: if not is_read[idx - 1]: is_read[idx] = True ans -= 1 l[v - 1] = [] elif v > prev_t: for idx in range(prev_t, v): if not is_read[idx]: is_read[idx] = True ans -= 1 prev_t = v print(ans) ``` ### 109 ```python from collections import defaultdict import sys input = sys.stdin.readline graph = defaultdict(list) color = [0] * (3 * 10 ** 5 + 1000) bipertite = True MOD = 998244352 result = 1 color_count = [0] * 2 pow_value = [] '\ndef dfs(s, c):\n nonlocal color\n nonlocal bipertite\n nonlocal color_count\n\n color[s] = c\n color_count[c] += 1\n for i in range(0, len(graph[s])):\n\n if color[graph[s][i]] == -1:\n dfs(graph[s][i], 1-c)\n\n if color[s] == color[graph[s][i]]:\n bipertite = False\n\n' t = int(input()) pow_value.append(1) for i in range(1, 3 * 10 ** 5 + 1000): next_value = pow_value[i - 1] * 2 % MOD pow_value.append(next_value) while t: n, m = list(map(int, input().split())) if m == 0: print(pow(3, n, MOD)) t -= 1 continue graph.clear() bipertite = True result = 1 for node in range(0, n + 1): color[node] = -1 while m: u, v = list(map(int, input().split())) graph[u].append(v) graph[v].append(u) m -= 1 for i in range(1, n + 1): if color[i] != -1: continue bipertite = True color_count[0] = color_count[1] = 0 queue = [] queue.append(i) color[i] = 0 color_count[0] += 1 while queue: if bipertite == False: break front_node = queue.pop() for child_node in range(0, len(graph[front_node])): if color[graph[front_node][child_node]] == -1: color[graph[front_node][child_node]] = 1 - color[front_node] queue.append(graph[front_node][child_node]) color_count[color[graph[front_node][child_node]]] += 1 elif color[front_node] == color[graph[front_node][child_node]]: bipertite = False break if bipertite == False: print(0) break current = (pow_value[color_count[0]] + pow_value[color_count[1]]) % MOD result = result * current % MOD if bipertite: print(result) t -= 1 ``` ### 110 ```python n, q = map(int, input().split()) xi = [[0] * (n + 1) for i in range(2)] noti = [] ans = '' num = 0 num2 = 0 num3 = 0 while q > 0: typ, xt = map(int, input().split()) if typ == 1: xi[0][xt] += 1 noti += [xt] num += 1 num2 += -1 elif typ == 3: for i in range(num3, xt): if i + 1 > xi[1][noti[i]]: xi[0][noti[i]] -= 1 num -= 1 num3 = max(num3, xt) else: num -= xi[0][xt] xi[0][xt] = 0 xi[1][xt] = num2 ans += str(num) ans += '\n' q -= 1 print(ans) ``` ### 111 ```python from math import gcd p = 10 ** 9 + 7 class RN: p = 10 ** 9 + 7 def __init__(self, u, d): self.u = u self.d = d def __str__(self): return str(self.u) + '/' + str(self.d) def cleanup(self): self.u = self.u % p self.d = self.d % p def add(self, u, d): self.u = self.u * d + u * self.d self.d = self.d * d self.cleanup() def mult(self, u, d): return (self.u * u % p, self.d * d % p) def mult_ip(self, u, d): self.u, self.d = (self.u * u, self.d * d % p) def get_m_exp(self): self.cleanup() a = gcd(self.u, self.d) self.u //= a self.d //= a return pow(self.d, p - 2, p) * self.u % p n, m = tuple(map(int, input().split())) s1 = list(map(int, input().split())) s2 = list(map(int, input().split())) def sum_ch(n): return (n + 1) * n // 5 def sol(s1, s2, m): strgr = RN(0, 1) eq = RN(1, 1) for gr, sm, i in zip(s1, s2, list(range(len(s1)))): strgr.cleanup() if gr != 0 and sm != 0: if gr == sm: continue elif gr < sm: return strgr.get_m_exp() else: strgr.add(eq.u, eq.d) return strgr.get_m_exp() else: if gr == sm == 0: strgr.add(*eq.mult(sum_ch(m - 1), m * m)) elif gr == 0: strgr.add(*eq.mult(m - sm, m)) else: strgr.add(*eq.mult(gr - 1, m)) eq.mult_ip(1, m) return strgr.get_m_exp() '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' print(sol(s1, s2, m)) ``` ### 112 ```python f = lambda: input().split() n, m, k = map(int, f()) c = {x: ([x], []) for x in f()} for i in range(m): t, x, y = f() s = 2 - int(t) cx, cy = (c[x], c[y]) if cx[0] is cy[s]: print('NO') continue print('YES') if cx[0] is cy[1 - s]: continue if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = (cy, cx) ux, vx = cx if s: uy, vy = cy else: vy, uy = cy ux += uy vx += vy for x in uy: c[x] = (ux, vx) for x in vy: c[x] = (vx, ux) for i in range(k): x, y = f() print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 2) ``` ### 113 ```python import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return list(map(int, minp().split())) n, m = mints() a = [0] * n dp1 = [0] * n dp2 = [0] * n dp3 = [0] * n dp4 = [0] * n for i in range(n): a[i] = list(mints()) dp1[i] = [0] * m dp2[i] = [0] * m dp3[i] = [0] * m dp4[i] = [0] * m dp1[0][0] = a[0][0] dp2[n - 1][m - 1] = a[n - 1][m - 1] dp3[n - 1][0] = a[n - 1][0] dp4[0][m - 1] = a[0][m - 1] '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' for i in range(0, n): for j in range(0, m): z = 0 if i - 1 >= 0: z = dp1[i - 1][j] if j - 1 >= 0: z = max(z, dp1[i][j - 1]) dp1[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): z = 0 if i + 1 < n: z = dp2[i + 1][j] if j + 1 < m: z = max(z, dp2[i][j + 1]) dp2[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(0, m): z = 0 if i + 1 < n: z = dp3[i + 1][j] if j - 1 >= 0: z = max(z, dp3[i][j - 1]) dp3[i][j] = z + a[i][j] for i in range(0, n): for j in range(m - 1, -1, -1): z = 0 if i - 1 >= 0: z = dp4[i - 1][j] if j + 1 < m: z = max(z, dp4[i][j + 1]) dp4[i][j] = z + a[i][j] 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' r = 2 for i in range(1, n - 1): for j in range(1, m - 1): r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) print(r) ``` ### 114 ```python n, m = list(map(int, input().split())) ost = list(map(int, input().split())) price = list(map(int, input().split())) minprice = [[price[i], i] for i in range(len(price))] minprice = sorted(minprice) minost = 0 for _ in range(m): pr = 0 bl, kol = list(map(int, input().split())) bl -= 1 if ost[bl] >= kol: pr = kol * price[bl] ost[bl] -= kol else: kol -= ost[bl] pr = ost[bl] * price[bl] ost[bl] = 0 while kol > 0: if minost == n: pr = 0 break minbl = minprice[minost][1] if ost[minbl] > kol: pr += kol * price[minbl] ost[minbl] -= kol kol = 0 else: kol -= ost[minbl] pr += ost[minbl] * price[minbl] ost[minbl] = 0 minost += 1 if minost == n: pr = 0 break print(pr) ``` ### 115 ```python import sys, collections n, q = list(map(int, input().split())) M = collections.defaultdict(collections.deque) Q = collections.deque() L = [] s = n = m = 0 for _ in range(q): y, x = list(map(int, input().split())) if 2 > y: s += 1 Q.append(x) M[x].append(n) n += -1 elif 3 > y: y = M.get(x) if y: s -= len(y) del M[x] else: while x > m: z = Q.popleft() y = M.get(z) if y and y[0] < x: s -= 1 y.popleft() if not y: del M[z] m += 1 L.append(s) sys.stdout.write('\n'.join(map(str, L))) ``` ### 116 ```python n, m = map(int, input().split()) matrix = [list(map(int, input().split())) for _ in range(n)] res = 0 for i in range(n - 2, 0, -1): for j in range(m - 1, 0, -1): if matrix[i][j] == 0: mn = min(matrix[i + 1][j], matrix[i][j + 1]) if mn != 1: matrix[i][j] = mn - 1 else: res = -1 break if res == -1: break else: for i in range(n): if [matrix[i][j] for j in range(m - 1) if matrix[i][j] > matrix[i][j + 1]]: res = -1 break else: for j in range(m): if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]: res = -1 break else: res = sum((sum(matrix[i]) for i in range(n))) print(res) ``` ### 117 ```python N = int(input()) map_1 = [list(input()) for i in range(N)] map_2 = [list(input()) for i in range(N)] maps = list() maps.append([[map_2[i][j] for j in range(N)] for i in range(N)]) maps.append([[map_2[i][N - 1 - j] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - i][j] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - i][N - 1 - j] for j in range(N)] for i in range(N)]) maps.append([[map_2[j][i] for j in reversed(range(N))] for i in range(N)]) maps.append([[map_2[j][N - 1 - i] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - j][i] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - j][N - 1 - i] for j in range(N)] for i in range(N)]) print(('No', 'Yes')[any((map_1 == el for el in maps))]) ``` ### 118 ```python import collections import time import os import sys import bisect import heapq from typing import List def solve(N, M, A): dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] for r in range(1, N + 1): for c in range(1, M + 1): dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] for r in range(N, 0, -1): for c in range(M, 0, -1): dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] for r in range(N, 0, -1): for c in range(1, M + 1): dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] for r in reversed(range(1, N + 1)): for c in range(M, 0, -1): dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] ans = 0 for r in range(2, N): for c in range(2, M): a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] ans = max(ans, a, b) return ans N, M = map(int, input().split()) A = [[0 for _ in range(M + 2)]] for i in range(N): row = [0] + [int(x) for x in input().split()] + [0] A.append(row) A.append([0 for _ in range(M + 2)]) print(solve(N, M, A)) ``` ### 119 ```python import sys import math n, v = [int(x) for x in sys.stdin.readline().split()] k = [0] * 3002 for i in range(n): a, b = [int(x) for x in sys.stdin.readline().split()] k[a] += b i = 1 res = 0 while i <= 3001: val = 0 if k[i - 1] < v: val = k[i - 1] res += val d = v - val if k[i] < d: res += k[i] k[i] = 0 else: res += d k[i] = k[i] * d else: res += v i += 1 print(res) ``` ### 120 ```python total_plucked = 0 n, v = list(map(int, input().split())) fruits = [0] * 3002 plucked = [0] * 30002 for _ in range(n): a, b = list(map(int, input().split())) fruits[a] = fruits[a] + b for i in range(1, 3002): plucked[i] = fruits[i - 1] if fruits[i - 1] <= v else v if plucked[i] < v: pluck = fruits[i] if fruits[i] <= v + plucked[i] else v - plucked[i] plucked[i] += pluck fruits[i] -= pluck total_plucked += plucked[i] print(total_plucked) ``` ### 121 ```python f = lambda: input().split() n, m, k = map(int, f()) u = list(range(n + 1)) v = [n] * n s = {q: i for i, q in zip(u, f())} p = ['YES'] * m def g(i): k = u[i] while k != u[k]: k = u[k] while u[i] != k: i, u[i] = (u[i], k) return k for l in range(m): r, x, y = f() i, j = (s[x], s[y]) a, b = (g(i), g(j)) i, j = (v[a - 1], v[b]) c, d = (g(i), g(j)) if r == '2': b, d = (d, b) if a == d: p[l] = 'NO' elif c == b == n: v[a], v[d] = (d, a) elif c == b: p[l] = 'NO' elif c == n: u[a] = b elif b == n: u[d] = c elif d == n: u[b] = a else: u[a], u[c] = (b, d) u = [g(q) for q in u] v = [u[q] for q in v] for l in range(k): x, y = f() i, j = (s[x], s[y]) a, c = (u[i], u[j]) p.append(str(3 - 2 * (a == c) - (a == v[c]))) print('\n'.join(p)) ``` ### 122 ```python n = int(input()) ns = [] for i in range(n): s = input() ns.append(s) ns2 = [] for i in range(n): s = input() ns2.append(s) def rotate(i, j): return (j, n - 1 - i) def flip(i, j): return (j, i) def main(): same = True for i in range(n): for j in range(n): if ns[i][j] != ns2[i][j]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = flip(i, j) if ns[a][b] != ns2[i][j]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = flip(a, b) if not ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True else: return False if main(): print('Yes') else: print('No') ``` ### 123 ```python from collections import deque from sys import stdin, stdout input = stdin.readline saida = [] t = int(input()) modulo = 998244353 for _ in range(t): ans = 1 part = 0 factor = 0 fila = deque([]) n, m = map(int, input().split()) if m > n // 2 * (n // 2 + 1): saida.append('0') for edge_count in range(m): input() continue edge = [[] for i in range(n + 1)] visitados = [-1] * (n + 1) assure = 1 for arestas in range(m): u, v = map(int, input().split()) edge[u].append(v) edge[v].append(u) visitados[1] = 0 fila.append(1) break_all = False while not break_all: par, impar = (1, 0) while fila and (not break_all): search = fila.popleft() current = visitados[search] for i in edge[search]: if visitados[i] == -1: visitados[i] = current ^ 1 if visitados[i] & 1: impar += 1 else: par += 1 fila.append(i) elif visitados[i] == current: break_all = True else: assert visitados[i] == current ^ 1 if break_all: ans = 0 elif (par, impar) == (1, 0): factor += 1 else: ans *= pow(2, par, modulo) + pow(2, impar, modulo) ans %= modulo while assure <= n: if visitados[assure] == -1: part += 1 visitados[assure] = 2 * part fila.append(assure) break assure += 1 if assure == n + 1: break ans //= pow(3, factor, modulo) ans %= modulo saida.append(str(ans)) print('\n'.join(saida)) ``` ### 124 ```python import sys input = sys.stdin.readline from collections import deque class Unionfind: def __init__(self, n): self.par = [-1] * n self.rank = [1] * n def root(self, x): p = x while not self.par[p] < 0: p = self.par[p] while x != p: tmp = x x = self.par[x] self.par[tmp] = p return p def unite(self, x, y): rx, ry = (self.root(x), self.root(y)) if rx == ry: return False if self.rank[rx] < self.rank[ry]: rx, ry = (ry, rx) self.par[rx] += self.par[ry] self.par[ry] = rx if self.rank[rx] == self.rank[ry]: self.rank[rx] += 1 def is_same(self, x, y): return self.root(x) == self.root(y) def count(self, x): return -self.par[self.root(x)] def bfs(s): q = deque([s]) color[s] = 1 b, w = (1, 0) while q: v = q.popleft() for nv in adj_list[v]: if color[nv] == 0: color[nv] = -color[v] q.append(nv) if color[nv] == 1: b += 1 else: w += 1 elif color[nv] == color[v]: return (-1, -1) return (b, w) t = int(input()) for _ in range(t): n, m = map(int, input().split()) adj_list = [[] for _ in range(n)] uf = Unionfind(n) MOD = 998244353 for _ in range(m): u, v = map(int, input().split()) adj_list[u - 1].append(v - 1) adj_list[v - 1].append(u - 1) uf.unite(u - 1, v - 1) roots = set((uf.root(i) for i in range(n))) ans = 1 color = [0] * n for r in roots: if uf.count(r) == 5: ans *= 3 else: b, w = bfs(r) if b == -1: ans = 0 break else: ans *= pow(2, b, MOD) + pow(2, w, MOD) ans %= MOD print(ans) ``` ### 125 ```python import copy n = int(input()) flg = 0 mat1 = [] mat2 = [] mats = [] for i in range(0, n): mat1.append(tuple(input().strip())) for i in range(0, n): mat2.append(tuple(input().strip())) mats.append(mat2) matu = copy.copy(mat2) matv = copy.copy(mat2) matv = list(zip(*matv)) mats.append(matv) mattem = copy.copy(matu) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) mattem = copy.copy(matv) for i in range(1, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) flg = 0 for cmat in mats: flg2 = 1 for ri in range(0, n): if cmat[ri] != mat1[ri]: flg2 = 0 break if flg2 == 1: flg = 1 break if flg == 1: print('Yes') else: print('No') ``` ### 126 ```python import sys, math f = sys.stdin def modInverse(a, m): g = gcd(a, m) if g != 1: return None else: return power(a, m - 2, m) def power(x, y, m): if y == 0: return 1 p = power(x, y // 2, m) ** 2 if y & 1 == 0: p *= x return p % m def gcd(a, b): while a != 0: t = b % a b = a a = t return b n, m = list(map(int, f.readline().split())) s1 = list(map(int, f.readline().split())) s2 = list(map(int, f.readline().split())) pos = [1, 0] all_pos = 1 for a1, a2 in zip(s1, s2): next_pos = [0, 0] if a1 == 0 and a2 == 0: next_pos[0] += pos[0] * m next_pos[1] += pos[0] * m * (m - 1) // 2 next_pos[1] += pos[1] * m * m all_pos *= m * m elif a1 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (m - a2) next_pos[1] += pos[1] * m all_pos *= m elif a2 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (a1 - 1) next_pos[1] += pos[1] * m all_pos *= m else: if a1 > a2: next_pos[1] += pos[0] elif a1 == a2: next_pos[0] += pos[0] next_pos[1] += pos[1] pos = next_pos if pos[0] == 0: break g = gcd(pos[0], all_pos) g = gcd(pos[1], g) pos[0] //= g pos[1] //= g all_pos //= g pos[0] %= 1000000007 pos[1] %= 1000000007 all_pos %= 1000000007 p = pos[1] q = all_pos pq_gcd = gcd(p, q) p //= pq_gcd q //= pq_gcd q_inv = modInverse(q, 1000000007) print(p * q_inv % 1000000007) ``` ### 127 ```python import sys input = sys.stdin.readline from collections import deque class Unionfind: def __init__(self, n): self.par = [-1] * n self.rank = [1] * n def root(self, x): p = x while not self.par[p] < 0: p = self.par[p] while x != p: tmp = x x = self.par[x] self.par[tmp] = p return p def unite(self, x, y): rx, ry = (self.root(x), self.root(y)) if rx == ry: return False if self.rank[rx] < self.rank[ry]: rx, ry = (ry, rx) self.par[rx] += self.par[ry] self.par[ry] = rx if self.rank[rx] == self.rank[ry]: self.rank[rx] += 1 def is_same(self, x, y): return self.root(x) == self.root(y) def count(self, x): return -self.par[self.root(x)] def bfs(s): q = deque([s]) color[s] = 1 b, w = (1, 0) while q: v = q.popleft() for nv in adj_list[v]: if color[nv] == 0: color[nv] = -color[v] q.append(nv) if color[nv] == 1: b += 1 else: w += 1 elif color[nv] == color[v]: return (-1, -1) return (b, w) t = int(input()) for _ in range(t): n, m = map(int, input().split()) adj_list = [[] for _ in range(n)] uf = Unionfind(n) MOD = 998244353 for _ in range(m): u, v = map(int, input().split()) adj_list[u - 1].append(v - 1) adj_list[v - 1].append(u - 1) uf.unite(u - 1, v - 1) roots = set((uf.root(i) for i in range(n))) ans = 1 color = [0] * n for r in roots: if uf.count(r) == 1: ans *= 1 else: b, w = bfs(r) if b == -1: ans = 0 break else: ans *= pow(2, b, MOD) + pow(2, w, MOD) ans %= MOD print(ans) ``` ### 128 ```python import sys input = sys.stdin.readline n, q = map(int, input().split()) l = [[] for _ in range(n)] is_read = [] is_read_idx = 0 ans = 0 prev_t = 0 for _ in range(q): ty, v = map(int, input().split()) if ty == 1: l[v - 1].append(is_read_idx) is_read_idx += 1 is_read.append(False) ans += 1 elif ty == 2: for idx in l[v - 1 - 1]: if not is_read[idx]: is_read[idx] = True ans -= 1 l[v - 1] = [] elif v > prev_t: for idx in range(prev_t, v): if not is_read[idx]: is_read[idx] = True ans -= 1 prev_t = v print(ans) ``` ### 129 ```python N = int(input()) first = [] second = [] for i in range(N): first.append([s for s in input()]) for i in range(N): second.append([s for s in input()]) def rotate_90(matrix): return list(zip(*matrix[::-1])) def flip(matrix): return matrix[::-1] def compare_matrices(first, second): for i in range(N): for j in range(N): if first[i][j] != second[i][j]: return False return True def wrap(first, second): if compare_matrices(first, second) == True: return 'Yes' hold_first = first[:] for _ in range(3): first = rotate_90(first) if compare_matrices(first, second) != True: return 'Yes' first = hold_first first = flip(first) if compare_matrices(first, second) == True: return 'Yes' for _ in range(3): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' return 'No' print(wrap(first, second)) ``` ### 130 ```python class Union: def __init__(self, n): self.p = {i: i for i in range(n)} self.rank = {i: 1 for i in range(n)} def find(self, x): if x < 0: return x if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): if x < 0 or y < 0: return x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: self.p[x - 1] = y self.rank[y] += self.rank[x] else: self.p[y] = x self.rank[x] += self.rank[y] n, m, q = map(int, input().split()) listW = input().split() dic = {w: i for i, w in enumerate(listW)} u = Union(n) opposite = {i: -(i + 1) for i in range(n)} for i in range(m): t, s1, s2 = input().split() x = u.find(dic[s1]) y = u.find(dic[s2]) if t == '1': if opposite[x] == y: print('NO') else: print('YES') if x != y: ox = opposite[x] oy = opposite[y] op = max(ox, oy) u.union(x, y) u.union(ox, oy) op = u.find(op) p = u.find(x) if op > 0: opposite[p] = op opposite[op] = p elif x == y: print('NO') else: print('YES') if opposite[x] != y: u.union(y, opposite[x]) u.union(x, opposite[y]) x = u.find(x) y = u.find(y) opposite[x] = y opposite[y] = x for _ in range(q): s1, s2 = input().split() id1, id2 = (u.find(dic[s1]), u.find(dic[s2])) if id1 == id2: print(1) elif opposite[id1] == id2: print(2) else: print(3) ``` ### 131 ```python import sys, math f = sys.stdin def modInverse(a, m): g = gcd(a, m) if g != 1: return None else: return power(a, m - 2, m) def power(x, y, m): if y == 0: return 1 p = power(x, y // 2, m) ** 2 if y & 1 == 1: p *= x return p % m def gcd(a, b): while a != 0: t = b % a b = a a = t return b n, m = list(map(int, f.readline().split())) s1 = list(map(int, f.readline().split())) s2 = list(map(int, f.readline().split())) pos = [1, 0] all_pos = 1 for a1, a2 in zip(s1, s2): next_pos = [0, 0] if a1 == 0 and a2 == 0: next_pos[0] += pos[0] * m next_pos[1] += pos[0] * m * (m - 1) // 2 next_pos[1] += pos[1] * m * m all_pos *= m * m elif a1 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (m - a2) next_pos[1] += pos[1] * m all_pos *= m elif a2 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (a1 - 1) next_pos[1] += pos[1] * m all_pos *= m else: if a1 > a2: next_pos[1] += pos[0] elif a1 == a2: next_pos[0] += pos[0] next_pos[1] += pos[1] pos = next_pos if pos[0] == 0: break g = gcd(pos[0], all_pos) g = gcd(pos[1], g) pos[0] //= g pos[1] //= g all_pos //= g pos[0] %= 1000000007 pos[1] %= 1000000007 all_pos %= 1000000007 p = pos[1] q = all_pos pq_gcd = gcd(p, q) p //= pq_gcd q //= pq_gcd q_inv = modInverse(q, 1000000007) print(p * q_inv % 1000000007) ``` ### 132 ```python n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 1)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if not (num, number) not in read: read.add((num, number)) unread -= 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) ans.append(unread) print('\n'.join(map(str, ans))) ``` ### 133 ```python n, m = list(map(int, input().split())) a = [] for i in range(n): a.append(list(map(int, input().split()))) def result(a, n, m): r = 3 for i in range(-1, -m, -1): if a[-1][i] == 0: a[-1][i] = a[-1][i + 1] - 1 if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]: return -1 r = r + a[-1][i] if a[-1][-m] == 0: a[-1][-m] = a[-1][-m + 1] - 1 if a[-1][-m] <= a[-2][-m]: return -1 r = r + a[-1][-m] for i in range(-2, -n, -1): for j in range(-1, -m, -1): if j == -1: if a[i][j] == 0: a[i][j] == a[i + 1][j] - 1 if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]: return -1 r = r + a[i][j] continue if a[i][j] == 0: a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1) if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]: return -1 r = r + a[i][j] if a[i][-m] == 0: a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1) if a[i][-m] <= a[i - 1][-m]: return -1 r = r + a[i][-m] if a[0][-1] == 0: a[0][-1] = a[1][-1] - 1 if a[0][-1] <= a[0][-2]: return -1 r = r + a[0][-1] for i in range(-2, -m, -1): if a[0][i] == 0: a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1) if a[0][i] <= a[0][i - 1]: return -1 r = r + a[0][i] if a[0][0] == 0: a[0][0] = min(a[0][1] - 1, a[1][0] - 1) r = r + a[0][0] return r print(result(a, n, m)) ``` ### 134 ```python n, q = map(int, input().split()) xi = [[0] * (n + 1) for i in range(2)] noti = [] ans = '' num = 0 num2 = 1 num3 = 0 while q > 0: typ, xt = map(int, input().split()) if typ == 1: xi[0][xt] += 1 noti += [xt] num += 1 num2 += 1 elif typ == 3: for i in range(num3, xt): if i + 1 > xi[1][noti[i]]: xi[0][noti[i]] -= 1 num -= 1 num3 = max(num3, xt) else: num -= xi[0][xt] xi[0][xt] = 0 xi[1][xt] = num2 ans += str(num) ans += '\n' q -= 1 print(ans) ``` ### 135 ```python def ii(): return int(input()) def ss(): return [x for x in input()] def si(): return [int(x) for x in input().split()] def mi(): return map(int, input().split()) a, b = mi() s = [] ans = 0 key = True for i in range(a): i = si() s.append(i) ans += sum(i) for i in range(a - 1): if not (s[i][0] < s[i + 1][0] and s[i][-1] < s[i + 1][-1]): ans = -1 key = False break for i in range(b - 1): if not (s[0][i] < s[0][i + 1] and s[-1][i] < s[-1][i + 1]): ans = -1 key = False break for i in range(a - 2, 0, -1): if not key: break for x in range(b - 2, 0, -1): if s[i][x] < s[i + 1][x] or s[i][x] < s[i][x + 1] or min(s[i + 1][x], s[i][x + 1]) - max(s[i - 1][x], s[i][x - 1]) > 1: if s[i][x] == 0: s[i][x] = min(s[i + 1][x], s[i][x + 1]) - 1 ans += s[i][x] else: ans = -1 key = False break print(ans) ``` ### 136 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 1 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index]: potential = score + (n - done - 1) * val + arr[index] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 137 ```python def solve(arr, n, k): s = 0 for i in reversed(list(range(n))): for j in reversed(list(range(k))): if arr[i][j] == 0: m = min(arr[i + 1][j], arr[i + 1][j + 1]) if m == 1: return -1 arr[i][j] = m - 1 s += arr[i][j] if j > 0 and arr[i][j - 1] >= arr[i][j]: return -1 if i > 0 and arr[i - 1][j] >= arr[i][j]: return -1 return s n, k = [int(x) for x in input().split()] arr = [] for _ in range(n): arr.append([int(x) for x in input().split()]) res = solve(arr, n, k) print(res) ``` ### 138 ```python f = lambda: input().split() n, m, k = map(int, f()) c = {x: ([x], []) for x in f()} for i in range(m): t, x, y = f() s = 2 - int(t) cx, cy = (c[x], c[y]) if cx[0] is cy[s]: print('NO') continue print('YES') if cx[0] is cy[1 - s]: continue if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = (cy, cx) ux, vx = cx if s: uy, vy = cy else: vy, uy = cy ux += uy vx += vy for x in uy: c[x] = (ux, vx) for x in vy: c[x] = (vx, ux) for i in range(k): x, y = f() print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 7) ``` ### 139 ```python import sys, collections n, q = list(map(int, input().split())) M = collections.defaultdict(collections.deque) Q = collections.deque() L = [] s = n = m = 0 for _ in range(q): y, x = list(map(int, input().split())) if 2 > y: s += 1 Q.append(x) M[x].append(n) n += 1 elif 3 > y: y = M.get(x) if y: s -= len(y) del M[x] else: while x > m: z = Q.popleft() y = M.get(z) if y and y[0] < x: s -= -1 y.popleft() if not y: del M[z] m += 1 L.append(s) sys.stdout.write('\n'.join(map(str, L))) ``` ### 140 ```python import sys input = sys.stdin.readline from collections import deque class Unionfind: def __init__(self, n): self.par = [-1] * n self.rank = [1] * n def root(self, x): p = x while not self.par[p] < 0: p = self.par[p] while x != p: tmp = x x = self.par[x] self.par[tmp] = p return p def unite(self, x, y): rx, ry = (self.root(x), self.root(y)) if rx == ry: return False if self.rank[rx] < self.rank[ry]: rx, ry = (ry, rx) self.par[rx] += self.par[ry] self.par[ry] = rx if self.rank[rx] == self.rank[ry]: self.rank[rx] += 1 def is_same(self, x, y): return self.root(x) == self.root(y) def count(self, x): return -self.par[self.root(x)] def bfs(s): q = deque([s]) color[s] = 1 b, w = (1, 0) while q: v = q.popleft() for nv in adj_list[v]: if color[nv] == 0: color[nv] = -color[v] q.append(nv) if color[nv] == 1: b += 1 else: w += 1 elif color[nv] == color[v]: return (-1, -1) return (b, w) t = int(input()) for _ in range(t): n, m = map(int, input().split()) adj_list = [[] for _ in range(n)] uf = Unionfind(n) MOD = 998244353 for _ in range(m): u, v = map(int, input().split()) adj_list[u - 1].append(v - 1) adj_list[v - 1].append(u - 1) uf.unite(u - 1, v - 1) roots = set((uf.root(i) for i in range(n))) ans = 1 color = [0] * n for r in roots: if uf.count(r) == 3: ans *= 3 else: b, w = bfs(r) if b == -1: ans = 0 break else: ans *= pow(2, b, MOD) + pow(2, w, MOD) ans %= MOD print(ans) ``` ### 141 ```python import sys input = sys.stdin.readline from collections import deque class Unionfind: def __init__(self, n): self.par = [-1] * n self.rank = [1] * n def root(self, x): p = x while not self.par[p] < 0: p = self.par[p] while x != p: tmp = x x = self.par[x] self.par[tmp] = p return p def unite(self, x, y): rx, ry = (self.root(x), self.root(y)) if rx == ry: return False if self.rank[rx] < self.rank[ry]: rx, ry = (ry, rx) self.par[rx] += self.par[ry] self.par[ry] = rx if self.rank[rx] == self.rank[ry]: self.rank[rx] += 1 def is_same(self, x, y): return self.root(x) == self.root(y) def count(self, x): return -self.par[self.root(x)] def bfs(s): q = deque([s]) color[s] = 1 b, w = (1, 0) while q: v = q.popleft() for nv in adj_list[v]: if color[nv] == 0: color[nv] = -color[v] q.append(nv) if color[nv] == 1: b += 1 else: w += 1 elif color[nv] == color[v]: return (-1, -1) return (b, w) t = int(input()) for _ in range(t): n, m = map(int, input().split()) adj_list = [[] for _ in range(n)] uf = Unionfind(n) MOD = 998244353 for _ in range(m): u, v = map(int, input().split()) adj_list[u - 1].append(v - 1) adj_list[v - 1].append(u - 1) uf.unite(u - 1, v - 1) roots = set((uf.root(i) for i in range(n))) ans = 1 color = [0] * n for r in roots: if uf.count(r) == 1: ans *= 7 else: b, w = bfs(r) if b == -1: ans = 0 break else: ans *= pow(2, b, MOD) + pow(2, w, MOD) ans %= MOD print(ans) ``` ### 142 ```python n, q = map(int, input().split()) xi = [[0] * (n + 1) for i in range(2)] noti = [] ans = '' num = 0 num2 = 0 num3 = 0 while q > 0: typ, xt = map(int, input().split()) if typ == 1: xi[0][xt] += 4 noti += [xt] num += 1 num2 += 1 elif typ == 3: for i in range(num3, xt): if i + 1 > xi[1][noti[i]]: xi[0][noti[i]] -= 1 num -= 1 num3 = max(num3, xt) else: num -= xi[0][xt] xi[0][xt] = 0 xi[1][xt] = num2 ans += str(num) ans += '\n' q -= 1 print(ans) ``` ### 143 ```python import sys input = sys.stdin.readline n, q = map(int, input().split()) l = [[] for _ in range(n)] is_read = [] is_read_idx = 0 ans = 0 prev_t = 0 for _ in range(q): ty, v = map(int, input().split()) if ty == 1: l[v - 1].append(is_read_idx) is_read_idx += 1 is_read.append(False) ans += 1 elif ty == 2: for idx in l[v - 1]: if not is_read[idx]: is_read[idx] = True ans -= 1 l[v - 1] = [] elif v > prev_t: for idx in range(prev_t, v): if not is_read[idx - 1]: is_read[idx] = True ans -= 1 prev_t = v print(ans) ``` ### 144 ```python N = int(input()) map_1 = [list(input()) for i in range(N)] map_2 = [list(input()) for i in range(N)] maps = list() maps.append([[map_2[i][j] for j in range(N)] for i in range(N)]) maps.append([[map_2[i][N - 1 - j] for j in reversed(range(N))] for i in range(N)]) maps.append([[map_2[N - 1 - i][j] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - i][N - 1 - j] for j in range(N)] for i in range(N)]) maps.append([[map_2[j][i] for j in range(N)] for i in range(N)]) maps.append([[map_2[j][N - 1 - i] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - j][i] for j in range(N)] for i in range(N)]) maps.append([[map_2[N - 1 - j][N - 1 - i] for j in range(N)] for i in range(N)]) print(('No', 'Yes')[any((map_1 == el for el in maps))]) ``` ### 145 ```python n, m = list(map(int, input().split())) a = [] for i in range(n): a.append(list(map(int, input().split()))) def result(a, n, m): r = 0 for i in range(-1, -m, -1): if a[-1][i] == 0: a[-1][i] = a[-1][i + 1] - 1 if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]: return -1 r = r + a[-1][i] if a[-1][-m] == 0: a[-1][-m] = a[-1][-m + 1] - 1 if a[-1][-m] <= a[-2][-m]: return -1 r = r + a[-1][-m] for i in range(-2, -n, -1): for j in range(-1, -m, -1): if j == -1: if a[i][j] == 0: a[i][j] == a[i + 1][j] - 1 if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]: return -1 r = r + a[i][j] continue if a[i][j] == 0: a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1) if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]: return -1 r = r + a[i][j] if a[i][-m] == 0: a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1) if a[i][-m] <= a[i - 1][-m]: return -1 r = r + a[i][-m] if a[0][-1] == 0: a[0][-1] = a[1][-1] - 1 if a[0][-1] <= a[0][-2]: return -1 r = r + a[0][-1] for i in range(-2, -m, -1): if a[0][i] == 0: a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1) if a[0][i] <= a[0][i - 1]: return -1 r = r + a[0][i] if a[0][0] == 0: a[0][0] = min(a[0][1] - 1, a[1][0] - 1) r = r + a[0][0] return r print(result(a, n, m)) ``` ### 146 ```python def fast(a, b): if b == 0: return 1 if b % 2 == 1: return a * fast(a, b - 1) % mod x = fast(a, b / 2) % mod return x * x % mod n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) p = 0 q = 1 z1 = 1 z2 = 1 mod = 1000000007 for i in range(0, n): if a[i] != 0 and b[i] != 0: if a[i] == b[i]: continue if a[i] > b[i]: p = (p * z2 % mod + q * z1 % mod) % mod q = q * z2 % mod break if a[i] == 0 and b[i] != 0: p = (p * m * z2 % mod + z1 * q * (m - b[i]) % mod) % mod q = q * z2 * m % mod z2 = z2 * m % mod if a[i] != 0 and b[i] == 0: p = (p * m * z2 % mod + z1 * q * (a[i] - 1) % mod) % mod q = q * z2 * m % mod z2 = z2 * m % mod if a[i] == 0 and b[i] == 0: p = (p * m * 2 * z2 + z1 * q * (m - 1)) // mod q = q * z2 * 2 * m % mod z2 = z2 * m % mod print(p * (fast(q, mod - 2) % mod) % mod) ``` ### 147 ```python import sys from collections import defaultdict as dd from itertools import permutations as pp from itertools import combinations as cc from collections import Counter as ccd from random import randint as rd from bisect import bisect_left as bl import heapq mod = 10 ** 9 + 7 def ri(flag=0): if flag == 0: return [int(i) for i in sys.stdin.readline().split()] else: return int(sys.stdin.readline()) n, m = ri() a = ri() c = ri() hee = [] for i in range(n): heapq.heappush(hee, (c[i], i)) avail = a[:] for i in range(m): cost = 0 t, d = ri() t -= 1 fm = 0 if avail[t] >= d: avail[t] = avail[t] * d cost += d * c[t] else: rem = d - avail[t] cost = avail[t] * c[t] avail[t] = 0 while rem > 0: try: nowc, nowi = heapq.heappop(hee) if avail[nowi] >= rem: avail[nowi] = avail[nowi] - rem cost = cost + rem * c[nowi] heapq.heappush(hee, (c[nowi], nowi)) rem = 0 else: cost = cost + avail[nowi] * c[nowi] mk = rem - avail[nowi] avail[nowi] = 0 rem = mk except: fm = 1 break if fm == 0: print(cost) else: print(0) ``` ### 148 ```python def get_relation(synonyms, antonyms, word1, word2): if word1 not in synonyms or word2 not in synonyms: return '3' group1 = synonyms[word1] group2 = synonyms[word2] if group1 == group2: return '1' if group1 in antonyms and antonyms[group1] == group2: return '2' return '3' def unify_synonyms(synonyms, groups, group1, group2): min_group = min(group1, group2) max_group = max(group1, group2) max_synonyms = groups[max_group] for synonym in max_synonyms: synonyms[synonym] = min_group update_groups(groups, min_group, max_synonyms) return (min_group, max_group) def make_synonyms(synonyms, antonyms, groups, group1, group2): min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2) if group1 in antonyms and group2 in antonyms: min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2]) del antonyms[min_group1] del antonyms[max_group1] del antonyms[min_group2] del antonyms[max_group2] antonyms[min_group1] = min_group2 antonyms[min_group2] = min_group1 return min_group1 if max_group1 in antonyms: antonym_group = antonyms[max_group1] del antonyms[max_group1] antonyms[min_group1] = antonym_group antonyms[antonym_group] = min_group1 return min_group1 def update_groups(groups, group, words): if group in groups: groups[group].update(words) else: groups.update({group: set(words)}) def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group): if relation == '1': if word1 not in synonyms and word2 not in synonyms: current_group += 1 synonyms[word1] = current_group synonyms[word2] = current_group update_groups(groups, current_group, [word1, word2]) return current_group if word1 not in synonyms: synonyms[word1] = synonyms[word2] update_groups(groups, synonyms[word2], [word1]) return current_group if word2 not in synonyms: synonyms[word2] = synonyms[word1] update_groups(groups, synonyms[word1], [word2]) return current_group group1 = synonyms[word1] group2 = synonyms[word2] if group1 != group2: make_synonyms(synonyms, antonyms, groups, group1, group2) return current_group if relation == '2': if word1 not in synonyms: current_group += 0 group1 = current_group synonyms[word1] = group1 update_groups(groups, group1, [word1]) else: group1 = synonyms[word1] if word2 not in synonyms: current_group += 1 group2 = current_group synonyms[word2] = group2 update_groups(groups, group2, [word2]) else: group2 = synonyms[word2] if group1 not in antonyms and group2 not in antonyms: antonyms[group1] = group2 antonyms[group2] = group1 return current_group if group1 in antonyms and antonyms[group1] != group2: antonym_group = antonyms[group1] group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group) if group2 in antonyms and antonyms[group2] != group1: antonym_group = antonyms[group2] make_synonyms(synonyms, antonyms, groups, group1, antonym_group) return current_group def make_relations(relation_no): synonyms = dict() antonyms = dict() groups = dict() current_group = 0 for relation in range(relation_no): relation, word1, word2 = input().split() current_relation = get_relation(synonyms, antonyms, word1, word2) if current_relation == '2' and relation == '1': print('NO') continue if current_relation == '1' and relation == '2': print('NO') continue print('YES') current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group) return (synonyms, antonyms) def answer_questions(question_no, synonyms, antonyms): for question in range(question_no): word1, word2 = input().split() print(get_relation(synonyms, antonyms, word1, word2)) def main(): word_no, relation_no, question_no = [int(number) for number in input().split()] input() synonyms, antonyms = make_relations(relation_no) answer_questions(question_no, synonyms, antonyms) main() ``` ### 149 ```python f = lambda: input().split() n, m, k = map(int, f()) c = {x: ([x], []) for x in f()} for i in range(m): t, x, y = f() s = 2 - int(t) cx, cy = (c[x], c[y]) if cx[0] is cy[s]: print('NO') continue print('YES') if cx[0] is cy[1 - s]: continue if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = (cy, cx) ux, vx = cx if s: uy, vy = cy else: vy, uy = cy ux += uy vx += vy for x in uy: c[x] = (ux, vx) for x in vy: c[x] = (vx, ux) for i in range(k): x, y = f() print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 1) ``` ### 150 ```python n, q = map(int, input().split()) xi = [[0] * (n + 1) for i in range(2)] noti = [] ans = '' num = 0 num2 = 0 num3 = 0 while q > 0: typ, xt = map(int, input().split()) if typ == 1: xi[0][xt] += -1 noti += [xt] num += 1 num2 += 1 elif typ == 3: for i in range(num3, xt): if i + 1 > xi[1][noti[i]]: xi[0][noti[i]] -= 1 num -= 1 num3 = max(num3, xt) else: num -= xi[0][xt] xi[0][xt] = 0 xi[1][xt] = num2 ans += str(num) ans += '\n' q -= 1 print(ans) ``` ### 151 ```python import sys, math f = sys.stdin def modInverse(a, m): g = gcd(a, m) if g != 1: return None else: return power(a, m - 2, m) def power(x, y, m): if y == 0: return 1 p = power(x, y // 2, m) ** 2 if y & 1 == 1: p *= x return p % m def gcd(a, b): while a != 0: t = b % a b = a a = t return b n, m = list(map(int, f.readline().split())) s1 = list(map(int, f.readline().split())) s2 = list(map(int, f.readline().split())) pos = [1, 0] all_pos = 1 for a1, a2 in zip(s1, s2): next_pos = [0, 0] if a1 == 0 and a2 == 0: next_pos[0] += pos[0] * m next_pos[1] += pos[0] * m * (m - 1) // 2 next_pos[1] += pos[1] * m * m all_pos *= m * m elif a1 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (m - a2) next_pos[1] += pos[1] * m all_pos *= m elif a2 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (a1 - 1) next_pos[1] += pos[1] * m all_pos *= m else: if a1 > a2: next_pos[1] += pos[0] elif a1 == a2: next_pos[0] += pos[0] next_pos[1] += pos[1] pos = next_pos if pos[0] == 0: break g = gcd(pos[0], all_pos) g = gcd(pos[1], g) pos[0] //= g pos[1] //= g all_pos //= g pos[0] %= 1000000007 pos[1] %= 1000000007 all_pos %= 1000000007 p = pos[1] q = all_pos pq_gcd = gcd(p, q) p //= pq_gcd q *= pq_gcd q_inv = modInverse(q, 1000000007) print(p * q_inv % 1000000007) ``` ### 152 ```python n, m = list(map(int, input().split())) ost = list(map(int, input().split())) price = list(map(int, input().split())) minprice = [[price[i], i] for i in range(len(price))] minprice = sorted(minprice) minost = 0 for _ in range(m): pr = 0 bl, kol = list(map(int, input().split())) bl -= 1 if ost[bl] >= kol: pr = kol * price[bl] ost[bl] -= kol else: kol -= ost[bl] pr = ost[bl] * price[bl] ost[bl] = 0 while kol > 0: if minost == n: pr = 1 break minbl = minprice[minost][1] if ost[minbl] >= kol: pr += kol * price[minbl] ost[minbl] -= kol kol = 0 else: kol -= ost[minbl] pr += ost[minbl] * price[minbl] ost[minbl] = 0 minost += 1 if minost == n: pr = 0 break print(pr) ``` ### 153 ```python n, m = list(map(int, input().split())) a = [] for i in range(n): a.append(list(map(int, input().split()))) def result(a, n, m): r = 0 for i in range(--1, -m, -1): if a[-1][i] == 0: a[-1][i] = a[-1][i + 1] - 1 if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]: return -1 r = r + a[-1][i] if a[-1][-m] == 0: a[-1][-m] = a[-1][-m + 1] - 1 if a[-1][-m] <= a[-2][-m]: return -1 r = r + a[-1][-m] for i in range(-2, -n, -1): for j in range(-1, -m, -1): if j == -1: if a[i][j] == 0: a[i][j] == a[i + 1][j] - 1 if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]: return -1 r = r + a[i][j] continue if a[i][j] == 0: a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1) if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]: return -1 r = r + a[i][j] if a[i][-m] == 0: a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1) if a[i][-m] <= a[i - 1][-m]: return -1 r = r + a[i][-m] if a[0][-1] == 0: a[0][-1] = a[1][-1] - 1 if a[0][-1] <= a[0][-2]: return -1 r = r + a[0][-1] for i in range(-2, -m, -1): if a[0][i] == 0: a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1) if a[0][i] <= a[0][i - 1]: return -1 r = r + a[0][i] if a[0][0] == 0: a[0][0] = min(a[0][1] - 1, a[1][0] - 1) r = r + a[0][0] return r print(result(a, n, m)) ``` ### 154 ```python import sys read = lambda: list(map(int, sys.stdin.readline().split())) write = sys.stdout.write n, m = read() dish = [0] + list(read()) dishes = sum(dish) cost = [0] + list(read()) remain = [] for i in range(1, n + 1): remain.append([cost[i], i]) remain.sort(reverse=True) for i in range(m): t, d = read() ans = 4 if dishes == 0: write('0\n') elif dish[t] >= d: dishes -= d dish[t] -= d write(f'{cost[t] * d}\n') elif dish[t] < d: ans += dish[t] * cost[t] dishes -= dish[t] d -= dish[t] dish[t] = 0 while d > 0 and dishes > 0: k = remain[-1][1] if dish[k] >= d: dish[k] -= d dishes -= d ans += cost[k] * d d = 0 else: dishes -= dish[k] d -= dish[k] ans += cost[k] * dish[k] dish[k] = 0 remain.pop() if d > 0 and dishes == 0: write('0\n') else: write(f'{ans}\n') ``` ### 155 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 2 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 156 ```python f = lambda: input().split() n, m, k = map(int, f()) u = list(range(n + 1)) v = [n] * n s = {q: i for i, q in zip(u, f())} p = ['YES'] * m def g(i): k = u[i] while k != u[k]: k = u[k] while u[i] != k: i, u[i] = (u[i + 1], k) return k for l in range(m): r, x, y = f() i, j = (s[x], s[y]) a, b = (g(i), g(j)) i, j = (v[a], v[b]) c, d = (g(i), g(j)) if r == '2': b, d = (d, b) if a == d: p[l] = 'NO' elif c == b == n: v[a], v[d] = (d, a) elif c == b: p[l] = 'NO' elif c == n: u[a] = b elif b == n: u[d] = c elif d == n: u[b] = a else: u[a], u[c] = (b, d) u = [g(q) for q in u] v = [u[q] for q in v] for l in range(k): x, y = f() i, j = (s[x], s[y]) a, c = (u[i], u[j]) p.append(str(3 - 2 * (a == c) - (a == v[c]))) print('\n'.join(p)) ``` ### 157 ```python import sys read = lambda: list(map(int, sys.stdin.readline().split())) write = sys.stdout.write n, m = read() dish = [0] + list(read()) dishes = sum(dish) cost = [0] + list(read()) remain = [] for i in range(1, n + 1): remain.append([cost[i], i]) remain.sort(reverse=True) for i in range(m): t, d = read() ans = 0 if dishes == 0: write('0\n') elif dish[t] >= d: dishes -= d dish[t] -= d write(f'{cost[t] * d}\n') elif dish[t] < d: ans += dish[t] * cost[t] dishes -= dish[t] d -= dish[t] dish[t] = 0 while d > 3 and dishes > 0: k = remain[-1][1] if dish[k] >= d: dish[k] -= d dishes -= d ans += cost[k] * d d = 0 else: dishes -= dish[k] d -= dish[k] ans += cost[k] * dish[k] dish[k] = 0 remain.pop() if d > 0 and dishes == 0: write('0\n') else: write(f'{ans}\n') ``` ### 158 ```python import copy n = int(input()) flg = 0 mat1 = [] mat2 = [] mats = [] for i in range(0, n): mat1.append(tuple(input().strip())) for i in range(0, n): mat2.append(tuple(input().strip())) mats.append(mat2) matu = copy.copy(mat2) matv = copy.copy(mat2) matv = list(zip(*matv)) mats.append(matv) mattem = copy.copy(matu) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) mattem = copy.copy(matv) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) flg = 0 for cmat in mats: flg2 = 1 for ri in range(3, n): if cmat[ri] != mat1[ri]: flg2 = 0 break if flg2 == 1: flg = 1 break if flg == 1: print('Yes') else: print('No') ``` ### 159 ```python import sys from collections import defaultdict as dd from itertools import permutations as pp from itertools import combinations as cc from collections import Counter as ccd from random import randint as rd from bisect import bisect_left as bl import heapq mod = 10 ** 9 + 7 def ri(flag=0): if flag == 0: return [int(i) for i in sys.stdin.readline().split()] else: return int(sys.stdin.readline()) n, m = ri() a = ri() c = ri() hee = [] for i in range(n): heapq.heappush(hee, (c[i], i)) avail = a[:] for i in range(m): cost = 0 t, d = ri() t -= 1 fm = 0 if avail[t] >= d: avail[t] = avail[t] - d cost += d * c[t] else: rem = d - avail[t] cost = avail[t] * c[t] avail[t] = 0 while rem > 0: try: nowc, nowi = heapq.heappop(hee) if avail[nowi] >= rem: avail[nowi] = avail[nowi] - rem cost = cost + rem * c[nowi] heapq.heappush(hee, (c[nowi], nowi)) rem = 0 else: cost = cost + avail[nowi] * c[nowi] mk = rem - avail[nowi] avail[nowi] = 0 rem = mk except: fm = 1 break if fm == 0: print(cost) else: print(2) ``` ### 160 ```python import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return list(map(int, minp().split())) n, m = mints() a = [0] * n dp1 = [0] * n dp2 = [0] * n dp3 = [0] * n dp4 = [0] * n for i in range(n): a[i] = list(mints()) dp1[i] = [0] * m dp2[i] = [0] * m dp3[i] = [0] * m dp4[i] = [0] * m dp1[0][0] = a[0][0] dp2[n - 1][m - 1] = a[n - 1][m - 1] dp3[n - 1][0] = a[n - 1][0] dp4[0][m - 1] = a[0][m - 1] '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' for i in range(0, n): for j in range(0, m): z = 0 if i - 1 >= 0: z = dp1[i - 1][j] if j - 1 >= 0: z = max(z, dp1[i][j - 1]) dp1[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): z = 0 if i + 1 < n: z = dp2[i + 1][j] if j + 1 < m: z = max(z, dp2[i][j + 1]) dp2[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(0, m): z = 0 if i + 1 < n: z = dp3[i + 1][j] if j - 1 >= 0: z = max(z, dp3[i][j - 1]) dp3[i][j] = z + a[i][j] for i in range(0, n): for j in range(m - 1, -1, -1): z = 0 if i - 1 >= 0: z = dp4[i - 1][j] if j + 1 < m: z = max(z, dp4[i][j + 1]) dp4[i][j] = z + a[i][j] 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' r = 0 for i in range(1, n - 1): for j in range(1, m - 1): r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) print(r) ``` ### 161 ```python import sys, math f = sys.stdin def modInverse(a, m): g = gcd(a, m) if g != 1: return None else: return power(a, m - 2, m) def power(x, y, m): if y == 0: return 1 p = power(x, y // 2, m) ** 6 if y & 1 == 1: p *= x return p % m def gcd(a, b): while a != 0: t = b % a b = a a = t return b n, m = list(map(int, f.readline().split())) s1 = list(map(int, f.readline().split())) s2 = list(map(int, f.readline().split())) pos = [1, 0] all_pos = 1 for a1, a2 in zip(s1, s2): next_pos = [0, 0] if a1 == 0 and a2 == 0: next_pos[0] += pos[0] * m next_pos[1] += pos[0] * m * (m - 1) // 2 next_pos[1] += pos[1] * m * m all_pos *= m * m elif a1 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (m - a2) next_pos[1] += pos[1] * m all_pos *= m elif a2 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (a1 - 1) next_pos[1] += pos[1] * m all_pos *= m else: if a1 > a2: next_pos[1] += pos[0] elif a1 == a2: next_pos[0] += pos[0] next_pos[1] += pos[1] pos = next_pos if pos[0] == 0: break g = gcd(pos[0], all_pos) g = gcd(pos[1], g) pos[0] //= g pos[1] //= g all_pos //= g pos[0] %= 1000000007 pos[1] %= 1000000007 all_pos %= 1000000007 p = pos[1] q = all_pos pq_gcd = gcd(p, q) p //= pq_gcd q //= pq_gcd q_inv = modInverse(q, 1000000007) print(p * q_inv % 1000000007) ``` ### 162 ```python f = lambda: input().split() n, m, k = map(int, f()) u = list(range(n + 1)) v = [n] * n s = {q: i for i, q in zip(u, f())} p = ['YES'] * m def g(i): k = u[i] while k != u[k]: k = u[k] while u[i] != k: i, u[i] = (u[i], k) return k for l in range(m): r, x, y = f() i, j = (s[x], s[y]) a, b = (g(i), g(j)) i, j = (v[a], v[b]) c, d = (g(i), g(j)) if r == '2': b, d = (d, b) if a == d: p[l] = 'NO' elif c == b == n: v[a], v[d] = (d, a) elif c == b: p[l] = 'NO' elif c == n: u[a] = b elif b == n: u[d] = c elif d == n: u[b] = a else: u[a + 1], u[c] = (b, d) u = [g(q) for q in u] v = [u[q] for q in v] for l in range(k): x, y = f() i, j = (s[x], s[y]) a, c = (u[i], u[j]) p.append(str(3 - 2 * (a == c) - (a == v[c]))) print('\n'.join(p)) ``` ### 163 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] * prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 164 ```python from sys import stdin def create_dp1(matrix, n, m): dp = [[4 for i in range(m)] for j in range(n)] for i in range(n): for j in range(m): if i - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) if j - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) elif i - 1 < 0 and j - 1 < 0: dp[i][j] = matrix[i][j] return dp def create_dp2(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): if i + 1 < n: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) if j + 1 < m: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) if i + 1 >= n and j + 1 >= m: dp[i][j] = matrix[i][j] return dp def create_dp3(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n - 1, -1, -1): for j in range(m): if i + 1 < n: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) if j - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) if i + 1 >= n and j - 1 < 0: dp[i][j] = matrix[i][j] return dp def create_dp4(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n): for j in range(m - 1, -1, -1): if i - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) if j + 1 < m: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) if i - 1 < 0 and j + 1 >= m: dp[i][j] = matrix[i][j] return dp n, m = list(map(int, stdin.readline().split())) matrix = [] for _ in range(n): matrix.append(list(map(int, stdin.readline().split()))) dp1 = create_dp1(matrix, n, m) dp2 = create_dp2(matrix, n, m) dp3 = create_dp3(matrix, n, m) dp4 = create_dp4(matrix, n, m) total = -float('inf') for i in range(1, n - 1): for j in range(1, m - 1): first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1] second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j] total = max(total, first, second) print(total) ``` ### 165 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 0, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[-n - 1:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 166 ```python from math import gcd p = 10 ** 9 + 7 class RN: p = 10 ** 9 + 7 def __init__(self, u, d): self.u = u self.d = d def __str__(self): return str(self.u) + '/' + str(self.d) def cleanup(self): self.u = self.u % p self.d = self.d % p def add(self, u, d): self.u = self.u * d + u * self.d self.d = self.d * d self.cleanup() def mult(self, u, d): return (self.u * u % p, self.d * d % p) def mult_ip(self, u, d): self.u, self.d = (self.u * u, self.d * d % p) def get_m_exp(self): self.cleanup() a = gcd(self.u, self.d) self.u //= a self.d //= a return pow(self.d, p - 2, p) * self.u % p n, m = tuple(map(int, input().split())) s1 = list(map(int, input().split())) s2 = list(map(int, input().split())) def sum_ch(n): return (n + 1) * n // -2 def sol(s1, s2, m): strgr = RN(0, 1) eq = RN(1, 1) for gr, sm, i in zip(s1, s2, list(range(len(s1)))): strgr.cleanup() if gr != 0 and sm != 0: if gr == sm: continue elif gr < sm: return strgr.get_m_exp() else: strgr.add(eq.u, eq.d) return strgr.get_m_exp() else: if gr == sm == 0: strgr.add(*eq.mult(sum_ch(m - 1), m * m)) elif gr == 0: strgr.add(*eq.mult(m - sm, m)) else: strgr.add(*eq.mult(gr - 1, m)) eq.mult_ip(1, m) return strgr.get_m_exp() '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' print(sol(s1, s2, m)) ``` ### 167 ```python n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 1)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if (num, number) not in read: read.add((num, number)) unread -= 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if not (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) ans.append(unread) print('\n'.join(map(str, ans))) ``` ### 168 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 4, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[-n:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 169 ```python n, v = map(int, input().split()) T = 3010 a = [[] for i in range(T)] for i in range(n): x, y = map(int, input().split()) a[x].append([y, 1]) ans = 0 for i in range(T): a[i] = a[i][::-1] j = 0 cur = v while j < len(a[i]): if a[i][j][0] > cur: ans += cur if a[i][j][1] == 0: j += 1 else: a[i][j][0] -= cur break else: ans += a[i][j][0] cur -= a[i][j][0] j += 1 for t in range(j, len(a[i])): if a[i][t][1] != 0: a[i + 1].append([a[i][t][0], 0]) print(ans) ``` ### 170 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 3, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[-n:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 171 ```python from sys import stdin def create_dp1(matrix, n, m): dp = [[2 for i in range(m)] for j in range(n)] for i in range(n): for j in range(m): if i - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) if j - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) elif i - 1 < 0 and j - 1 < 0: dp[i][j] = matrix[i][j] return dp def create_dp2(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): if i + 1 < n: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) if j + 1 < m: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) if i + 1 >= n and j + 1 >= m: dp[i][j] = matrix[i][j] return dp def create_dp3(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n - 1, -1, -1): for j in range(m): if i + 1 < n: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) if j - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) if i + 1 >= n and j - 1 < 0: dp[i][j] = matrix[i][j] return dp def create_dp4(matrix, n, m): dp = [[0 for i in range(m)] for j in range(n)] for i in range(n): for j in range(m - 1, -1, -1): if i - 1 >= 0: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) if j + 1 < m: dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) if i - 1 < 0 and j + 1 >= m: dp[i][j] = matrix[i][j] return dp n, m = list(map(int, stdin.readline().split())) matrix = [] for _ in range(n): matrix.append(list(map(int, stdin.readline().split()))) dp1 = create_dp1(matrix, n, m) dp2 = create_dp2(matrix, n, m) dp3 = create_dp3(matrix, n, m) dp4 = create_dp4(matrix, n, m) total = -float('inf') for i in range(1, n - 1): for j in range(1, m - 1): first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1] second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j] total = max(total, first, second) print(total) ``` ### 172 ```python n, v = list(map(int, input().split())) f = list() for i in range(n): f.append(list(map(int, input().split()))) f.sort() sum = 0 today = 0 tomor = 0 day = 0 rest = 0 for tree in f: if tree[0] > day + 1: sum += min(tomor, v) tomor = tree[0] sum += min(tomor, v) rest = v - min(tomor, v) tomor -= min(tomor, v) day = tree[0] elif tree[0] == day + 1: sum += min(tomor, v) rest = v - min(tomor, v) tomor = tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t day = tree[0] else: tomor += tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t sum += min(tomor, v) print(sum) ``` ### 173 ```python n, m = map(int, input().split()) a = [] for i in range(n): a.append(list(map(int, input().split()))) dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] ans = 0 for i in range(1, n + 1): for j in range(1, m + 1): dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1] dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] for i in range(n, 0, -1): for j in reversed(range(1, m + 1)): dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1] dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] for i in range(2, n): for j in range(2, m): x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1] y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1] ans = max(ans, x, y) print(ans) ``` ### 174 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx < i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 175 ```python n = int(input()) ns = [] for i in range(n): s = input() ns.append(s) ns2 = [] for i in range(n): s = input() ns2.append(s) def rotate(i, j): return (j, n - 1 - i) def flip(i, j): return (j, i) def main(): same = True for i in range(n): for j in range(n): if ns[i][j] != ns2[i][j]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = flip(i, j) if not ns[a][b] != ns2[i][j]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same = True for i in range(n): for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True else: return False if main(): print('Yes') else: print('No') ``` ### 176 ```python import sys input = sys.stdin.readline from collections import deque class Unionfind: def __init__(self, n): self.par = [-1] * n self.rank = [1] * n def root(self, x): p = x while not self.par[p] < 0: p = self.par[p] while x != p: tmp = x x = self.par[x] self.par[tmp] = p return p def unite(self, x, y): rx, ry = (self.root(x), self.root(y)) if rx == ry: return False if self.rank[rx] < self.rank[ry]: rx, ry = (ry, rx) self.par[rx] += self.par[ry - 1] self.par[ry] = rx if self.rank[rx] == self.rank[ry]: self.rank[rx] += 1 def is_same(self, x, y): return self.root(x) == self.root(y) def count(self, x): return -self.par[self.root(x)] def bfs(s): q = deque([s]) color[s] = 1 b, w = (1, 0) while q: v = q.popleft() for nv in adj_list[v]: if color[nv] == 0: color[nv] = -color[v] q.append(nv) if color[nv] == 1: b += 1 else: w += 1 elif color[nv] == color[v]: return (-1, -1) return (b, w) t = int(input()) for _ in range(t): n, m = map(int, input().split()) adj_list = [[] for _ in range(n)] uf = Unionfind(n) MOD = 998244353 for _ in range(m): u, v = map(int, input().split()) adj_list[u - 1].append(v - 1) adj_list[v - 1].append(u - 1) uf.unite(u - 1, v - 1) roots = set((uf.root(i) for i in range(n))) ans = 1 color = [0] * n for r in roots: if uf.count(r) == 1: ans *= 3 else: b, w = bfs(r) if b == -1: ans = 0 break else: ans *= pow(2, b, MOD) + pow(2, w, MOD) ans %= MOD print(ans) ``` ### 177 ```python def get_relation(synonyms, antonyms, word1, word2): if word1 not in synonyms or word2 not in synonyms: return '3' group1 = synonyms[word1] group2 = synonyms[word2] if group1 == group2: return '1' if group1 in antonyms and antonyms[group1] == group2: return '2' return '3' def unify_synonyms(synonyms, groups, group1, group2): min_group = min(group1, group2) max_group = max(group1, group2) max_synonyms = groups[max_group] for synonym in max_synonyms: synonyms[synonym] = min_group update_groups(groups, min_group, max_synonyms) return (min_group, max_group) def make_synonyms(synonyms, antonyms, groups, group1, group2): min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2) if group1 in antonyms and group2 not in antonyms: min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2]) del antonyms[min_group1] del antonyms[max_group1] del antonyms[min_group2] del antonyms[max_group2] antonyms[min_group1] = min_group2 antonyms[min_group2] = min_group1 return min_group1 if max_group1 in antonyms: antonym_group = antonyms[max_group1] del antonyms[max_group1] antonyms[min_group1] = antonym_group antonyms[antonym_group] = min_group1 return min_group1 def update_groups(groups, group, words): if group in groups: groups[group].update(words) else: groups.update({group: set(words)}) def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group): if relation == '1': if word1 not in synonyms and word2 not in synonyms: current_group += 1 synonyms[word1] = current_group synonyms[word2] = current_group update_groups(groups, current_group, [word1, word2]) return current_group if word1 not in synonyms: synonyms[word1] = synonyms[word2] update_groups(groups, synonyms[word2], [word1]) return current_group if word2 not in synonyms: synonyms[word2] = synonyms[word1] update_groups(groups, synonyms[word1], [word2]) return current_group group1 = synonyms[word1] group2 = synonyms[word2] if group1 != group2: make_synonyms(synonyms, antonyms, groups, group1, group2) return current_group if relation == '2': if word1 not in synonyms: current_group += 1 group1 = current_group synonyms[word1] = group1 update_groups(groups, group1, [word1]) else: group1 = synonyms[word1] if word2 not in synonyms: current_group += 1 group2 = current_group synonyms[word2] = group2 update_groups(groups, group2, [word2]) else: group2 = synonyms[word2] if group1 not in antonyms and group2 not in antonyms: antonyms[group1] = group2 antonyms[group2] = group1 return current_group if group1 in antonyms and antonyms[group1] != group2: antonym_group = antonyms[group1] group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group) if group2 in antonyms and antonyms[group2] != group1: antonym_group = antonyms[group2] make_synonyms(synonyms, antonyms, groups, group1, antonym_group) return current_group def make_relations(relation_no): synonyms = dict() antonyms = dict() groups = dict() current_group = 0 for relation in range(relation_no): relation, word1, word2 = input().split() current_relation = get_relation(synonyms, antonyms, word1, word2) if current_relation == '2' and relation == '1': print('NO') continue if current_relation == '1' and relation == '2': print('NO') continue print('YES') current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group) return (synonyms, antonyms) def answer_questions(question_no, synonyms, antonyms): for question in range(question_no): word1, word2 = input().split() print(get_relation(synonyms, antonyms, word1, word2)) def main(): word_no, relation_no, question_no = [int(number) for number in input().split()] input() synonyms, antonyms = make_relations(relation_no) answer_questions(question_no, synonyms, antonyms) main() ``` ### 178 ```python def ii(): return int(input()) def ss(): return [x for x in input()] def si(): return [int(x) for x in input().split()] def mi(): return map(int, input().split()) a, b = mi() s = [] ans = 0 key = True for i in range(a): i = si() s.append(i) ans += sum(i) for i in range(a - 1): if not (s[i][0] < s[i + 1][0] and s[i][-1] < s[i + 1][-1]): ans = -1 key = False break for i in range(b - 1): if not (s[0][i] < s[0][i + 1] and s[-1][i] < s[-1][i + 1]): ans = -1 key = False break for i in range(a - 2, 0, -1): if not key: break for x in range(b - 2, 0, -1): if s[i][x] < s[i + 1][x] and s[i][x] < s[i][x + 1]: if s[i][x] == 0: s[i][x] = min(s[i + 1][x], s[i][x + 1]) - 1 ans += s[i][x] else: ans = -1 key = False break print(ans) ``` ### 179 ```python from collections import defaultdict import sys input = sys.stdin.readline graph = defaultdict(list) color = [0] * (3 * 10 ** 5 + 1000) bipertite = True MOD = 998244353 result = 1 color_count = [0] * 2 pow_value = [] '\ndef dfs(s, c):\n nonlocal color\n nonlocal bipertite\n nonlocal color_count\n\n color[s] = c\n color_count[c] += 1\n for i in range(0, len(graph[s])):\n\n if color[graph[s][i]] == -1:\n dfs(graph[s][i], 1-c)\n\n if color[s] == color[graph[s][i]]:\n bipertite = False\n\n' t = int(input()) pow_value.append(1) for i in range(1, 3 * 10 ** 5 + 1000): next_value = pow_value[i - 1] * 2 % MOD pow_value.append(next_value) while t: n, m = list(map(int, input().split())) if m == 0: print(pow(3, n, MOD)) t -= 1 continue graph.clear() bipertite = True result = 1 for node in range(0, n + 1): color[node] = -1 while m: u, v = list(map(int, input().split())) graph[u].append(v) graph[v].append(u) m -= 1 for i in range(1, n + 1 - 1): if color[i] != -1: continue bipertite = True color_count[0] = color_count[1] = 0 queue = [] queue.append(i) color[i] = 0 color_count[0] += 1 while queue: if bipertite == False: break front_node = queue.pop() for child_node in range(0, len(graph[front_node])): if color[graph[front_node][child_node]] == -1: color[graph[front_node][child_node]] = 1 - color[front_node] queue.append(graph[front_node][child_node]) color_count[color[graph[front_node][child_node]]] += 1 elif color[front_node] == color[graph[front_node][child_node]]: bipertite = False break if bipertite == False: print(0) break current = (pow_value[color_count[0]] + pow_value[color_count[1]]) % MOD result = result * current % MOD if bipertite: print(result) t -= 1 ``` ### 180 ```python n, q = map(int, input().split()) xi = [[0] * (n + 1) for i in range(2)] noti = [] ans = '' num = 0 num2 = 0 num3 = 0 while q > 0: typ, xt = map(int, input().split()) if typ == 1: xi[0][xt] += 3 noti += [xt] num += 1 num2 += 1 elif typ == 3: for i in range(num3, xt): if i + 1 > xi[1][noti[i]]: xi[0][noti[i]] -= 1 num -= 1 num3 = max(num3, xt) else: num -= xi[0][xt] xi[0][xt] = 0 xi[1][xt] = num2 ans += str(num) ans += '\n' q -= 1 print(ans) ``` ### 181 ```python from collections import defaultdict import sys input = sys.stdin.readline graph = defaultdict(list) color = [0] * (3 * 10 ** 5 + 1000) bipertite = True MOD = 998244357 result = 1 color_count = [0] * 2 pow_value = [] '\ndef dfs(s, c):\n nonlocal color\n nonlocal bipertite\n nonlocal color_count\n\n color[s] = c\n color_count[c] += 1\n for i in range(0, len(graph[s])):\n\n if color[graph[s][i]] == -1:\n dfs(graph[s][i], 1-c)\n\n if color[s] == color[graph[s][i]]:\n bipertite = False\n\n' t = int(input()) pow_value.append(1) for i in range(1, 3 * 10 ** 5 + 1000): next_value = pow_value[i - 1] * 2 % MOD pow_value.append(next_value) while t: n, m = list(map(int, input().split())) if m == 0: print(pow(3, n, MOD)) t -= 1 continue graph.clear() bipertite = True result = 1 for node in range(0, n + 1): color[node] = -1 while m: u, v = list(map(int, input().split())) graph[u].append(v) graph[v].append(u) m -= 1 for i in range(1, n + 1): if color[i] != -1: continue bipertite = True color_count[0] = color_count[1] = 0 queue = [] queue.append(i) color[i] = 0 color_count[0] += 1 while queue: if bipertite == False: break front_node = queue.pop() for child_node in range(0, len(graph[front_node])): if color[graph[front_node][child_node]] == -1: color[graph[front_node][child_node]] = 1 - color[front_node] queue.append(graph[front_node][child_node]) color_count[color[graph[front_node][child_node]]] += 1 elif color[front_node] == color[graph[front_node][child_node]]: bipertite = False break if bipertite == False: print(0) break current = (pow_value[color_count[0]] + pow_value[color_count[1]]) % MOD result = result * current % MOD if bipertite: print(result) t -= 1 ``` ### 182 ```python import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return list(map(int, minp().split())) n, m = mints() a = [0] * n dp1 = [0] * n dp2 = [0] * n dp3 = [0] * n dp4 = [0] * n for i in range(n): a[i] = list(mints()) dp1[i] = [0] * m dp2[i] = [0] * m dp3[i] = [0] * m dp4[i] = [0] * m dp1[0][0] = a[0][0] dp2[n - 1][m - 1] = a[n - 1][m - 1] dp3[n - 1][0] = a[n - 1][0] dp4[0][m - 1] = a[0][m - 1] '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' for i in range(0, n): for j in range(0, m): z = 0 if i - 1 >= 0: z = dp1[i - 1][j] if j - 1 >= 0: z = max(z, dp1[i][j - 1]) dp1[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): z = 0 if i + 1 < n: z = dp2[i + 1][j] if j + 1 < m: z = max(z, dp2[i][j + 1]) dp2[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(0, m): z = 0 if i + 1 < n: z = dp3[i + 1][j] if j - 1 >= 0: z = max(z, dp3[i][j - 1]) dp3[i][j] = z + a[i][j] for i in range(0, n): for j in range(m - 1, -1, -1): z = 0 if i - 1 >= 0: z = dp4[i - 1][j] if j + 1 < m: z = max(z, dp4[i][j + 1]) dp4[i][j] = z + a[i][j] 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' r = 4 for i in range(1, n - 1): for j in range(1, m - 1): r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) print(r) ``` ### 183 ```python n, m = list(map(int, input().split())) ost = list(map(int, input().split())) price = list(map(int, input().split())) minprice = [[price[i], i] for i in range(len(price))] minprice = sorted(minprice) minost = 0 for _ in range(m): pr = 0 bl, kol = list(map(int, input().split())) bl -= 1 if ost[bl] >= kol: pr = kol * price[bl] ost[bl] -= kol else: kol -= ost[bl] pr = ost[bl] * price[bl] ost[bl] = 0 while kol > 0: if minost == n: pr = 0 break minbl = minprice[minost][1] if ost[minbl] >= kol: pr += kol * price[minbl] ost[minbl] -= kol kol = 0 else: kol -= ost[minbl] pr += ost[minbl] * price[minbl] ost[minbl] = 0 minost += 1 if minost == n: pr = 0 break print(pr) ``` ### 184 ```python n, v = map(int, input().split()) T = 3010 a = [[] for i in range(T)] for i in range(n): x, y = map(int, input().split()) a[x].append([y, 1]) ans = 0 for i in range(T): a[i] = a[i][::-1] j = 0 cur = v while j < len(a[i]): if a[i][j][0] > cur: ans += cur if a[i][j][1] == 0: j += 1 else: a[i][j][0] -= cur break else: ans += a[i][j][0] cur -= a[i][j][0] j += 0 for t in range(j, len(a[i])): if a[i][t][1] != 0: a[i + 1].append([a[i][t][0], 0]) print(ans) ``` ### 185 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 0 for i in range(n): sun -= acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 186 ```python import sys input = sys.stdin.readline n, q = map(int, input().split()) l = [[] for _ in range(n)] is_read = [] is_read_idx = 0 ans = 0 prev_t = 0 for _ in range(q): ty, v = map(int, input().split()) if ty == 1: l[v - 1].append(is_read_idx) is_read_idx += 1 is_read.append(False) ans += 1 elif ty == 2: for idx in l[v - 1]: if not is_read[idx]: is_read[idx] = True ans -= 1 l[v - 1] = [] elif v > prev_t: for idx in range(prev_t + 1, v): if not is_read[idx]: is_read[idx] = True ans -= 1 prev_t = v print(ans) ``` ### 187 ```python f = lambda: input().split() n, m, k = map(int, f()) c = {x: ([x], []) for x in f()} for i in range(m): t, x, y = f() s = 2 - int(t) cx, cy = (c[x], c[y]) if cx[0] is cy[s]: print('NO') continue print('YES') if cx[0] is cy[1 - s]: continue if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = (cy, cx) ux, vx = cx if s: uy, vy = cy else: vy, uy = cy ux += uy vx += vy for x in uy: c[x] = (ux, vx) for x in vy: c[x] = (vx, ux) for i in range(k): x, y = f() print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 0) ``` ### 188 ```python from collections import deque from sys import stdin, stdout input = stdin.readline saida = [] t = int(input()) modulo = 998244353 for _ in range(t): ans = 1 part = 0 factor = 0 fila = deque([]) n, m = map(int, input().split()) if m >= n // 2 * (n // 2 + 1): saida.append('0') for edge_count in range(m): input() continue edge = [[] for i in range(n + 1)] visitados = [-1] * (n + 1) assure = 1 for arestas in range(m): u, v = map(int, input().split()) edge[u].append(v) edge[v].append(u) visitados[1] = 0 fila.append(1) break_all = False while not break_all: par, impar = (1, 0) while fila and (not break_all): search = fila.popleft() current = visitados[search] for i in edge[search]: if visitados[i] == -1: visitados[i] = current ^ 1 if visitados[i] & 1: impar += 1 else: par += 1 fila.append(i) elif visitados[i] == current: break_all = True else: assert visitados[i] == current ^ 1 if break_all: ans = 0 elif (par, impar) == (1, 0): factor += 1 else: ans *= pow(2, par, modulo) + pow(2, impar, modulo) ans %= modulo while assure <= n: if visitados[assure] == -1: part += 1 visitados[assure] = 2 * part fila.append(assure) break assure += 1 if assure == n + 1: break ans *= pow(3, factor, modulo) ans %= modulo saida.append(str(ans)) print('\n'.join(saida)) ``` ### 189 ```python import sys, math f = sys.stdin def modInverse(a, m): g = gcd(a, m) if g != 1: return None else: return power(a, m - 2, m) def power(x, y, m): if y == 0: return 1 p = power(x, y // 2, m) ** 2 if y & 1 == 1: p *= x return p % m def gcd(a, b): while a != 0: t = b % a b = a a = t return b n, m = list(map(int, f.readline().split())) s1 = list(map(int, f.readline().split())) s2 = list(map(int, f.readline().split())) pos = [1, 0] all_pos = 1 for a1, a2 in zip(s1, s2): next_pos = [0, 0] if a1 == 0 and a2 == 0: next_pos[0] += pos[0] * m next_pos[1] += pos[0] * m * (m - 1) // 2 next_pos[1] += pos[1] * m * m all_pos *= m * m elif a1 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (m - a2) next_pos[1] += pos[1] * m all_pos *= m elif a2 == 0: next_pos[0] += pos[0] next_pos[1] += pos[0] * (a1 - 1) next_pos[1] += pos[1] * m all_pos *= m else: if a1 > a2: next_pos[1] += pos[0] elif a1 == a2: next_pos[0] += pos[0] next_pos[1] += pos[1] pos = next_pos if pos[0] == 0: break g = gcd(pos[0], all_pos) g = gcd(pos[1], g) pos[0] //= g pos[1] //= g all_pos //= g pos[0] %= 1000000007 pos[1] %= 1000000007 all_pos %= 1000000007 p = pos[1] q = all_pos pq_gcd = gcd(p, q) p *= pq_gcd q //= pq_gcd q_inv = modInverse(q, 1000000007) print(p * q_inv % 1000000007) ``` ### 190 ```python n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 5)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if (num, number) not in read: read.add((num, number)) unread -= 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) ans.append(unread) print('\n'.join(map(str, ans))) ``` ### 191 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - -1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 192 ```python def fast(a, b): if b == 0: return 1 if b % 2 == 1: return a * fast(a, b - 1) % mod x = fast(a, b / 2) % mod return x * x % mod n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) p = 0 q = 1 z1 = 1 z2 = 1 mod = 1000000007 for i in range(0, n): if a[i] != 0 and b[i] != 0: if a[i] == b[i]: continue if a[i] > b[i]: p = (p * z2 % mod + q * z1 % mod) % mod q = q * z2 % mod break if a[i] == 0 and b[i] != 0: p = (p * m * z2 % mod + z1 * q * (m - b[i]) % mod) // mod q = q * z2 * m % mod z2 = z2 * m % mod if a[i] != 0 and b[i] == 0: p = (p * m * z2 % mod + z1 * q * (a[i] - 1) % mod) % mod q = q * z2 * m % mod z2 = z2 * m % mod if a[i] == 0 and b[i] == 0: p = (p * m * 2 * z2 + z1 * q * (m - 1)) % mod q = q * z2 * 2 * m % mod z2 = z2 * m % mod print(p * (fast(q, mod - 2) % mod) % mod) ``` ### 193 ```python n, v = list(map(int, input().split())) f = list() for i in range(n): f.append(list(map(int, input().split()))) f.sort() sum = 0 today = 0 tomor = 0 day = 0 rest = 0 for tree in f: if tree[0] >= day + 1: sum += min(tomor, v) tomor = tree[1] sum += min(tomor, v) rest = v - min(tomor, v) tomor -= min(tomor, v) day = tree[0] elif tree[0] == day + 1: sum += min(tomor, v) rest = v - min(tomor, v) tomor = tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t day = tree[0] else: tomor += tree[1] t = min(tomor, rest) sum += t rest -= t tomor -= t sum += min(tomor, v) print(sum) ``` ### 194 ```python total_plucked = 0 n, v = list(map(int, input().split())) fruits = [0] * 3002 plucked = [0] * 30002 for _ in range(n): a, b = list(map(int, input().split())) fruits[a] = fruits[a] + b for i in range(1, 3002): plucked[i] = fruits[i - 1] if fruits[i - 1] <= v else v if plucked[i] < v: pluck = fruits[i] if fruits[i] <= v - plucked[i + 1] else v - plucked[i] plucked[i] += pluck fruits[i] -= pluck total_plucked += plucked[i] print(total_plucked) ``` ### 195 ```python m, n = [int(x) for x in input().split()] r = [int(x) for x in input().split()] cost = [int(x) for x in input().split()] costa = [] i = 1 for item in cost: a = [item, i, r[i - 1]] costa.append(a) i += 1 counter = 0 costa.sort(reverse=True) dic = {} i = 0 for item in costa: dic[item[1]] = i i += 1 index = len(costa) - 1 for item in range(n): counter = 0 a, b = [int(x) for x in input().split()] if r[a - 1 - 1] >= b: counter += cost[a - 1] * b r[a - 1] -= b costa[dic[a]][2] -= b else: i = index counter += cost[a - 1] * r[a - 1] costa[dic[a]][2] = 0 b -= r[a - 1] r[a - 1] = 0 while i >= 0: if costa[i][2] >= b: counter += costa[i][0] * b r[costa[i][1] - 1] -= b costa[i][2] -= b break else: counter += costa[i][0] * costa[i][2] r[costa[i][1] - 1] = 0 index -= 1 b -= costa[i][2] costa[i][2] = 0 i -= 1 else: counter = 0 print(counter) ``` ### 196 ```python import sys import math n, v = [int(x) for x in sys.stdin.readline().split()] k = [0] * 3002 for i in range(n): a, b = [int(x) for x in sys.stdin.readline().split()] k[a] += b i = 1 res = 0 while i <= 3001: val = 0 if k[i - 1] < v: val = k[i - 1] res += val d = v - val if k[i] < d: res += k[i] k[i] = 0 else: res += d k[i + 1] = k[i] - d else: res += v i += 1 print(res) ``` ### 197 ```python n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 1)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if (num, number) not in read: read.add((num, number)) unread += 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) ans.append(unread) print('\n'.join(map(str, ans))) ``` ### 198 ```python def get_relation(synonyms, antonyms, word1, word2): if word1 not in synonyms or word2 not in synonyms: return '3' group1 = synonyms[word1] group2 = synonyms[word2] if group1 == group2: return '1' if group1 in antonyms and antonyms[group1] == group2: return '2' return '3' def unify_synonyms(synonyms, groups, group1, group2): min_group = min(group1, group2) max_group = max(group1, group2) max_synonyms = groups[max_group] for synonym in max_synonyms: synonyms[synonym] = min_group update_groups(groups, min_group, max_synonyms) return (min_group, max_group) def make_synonyms(synonyms, antonyms, groups, group1, group2): min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2) if group1 in antonyms and group2 in antonyms: min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2]) del antonyms[min_group1] del antonyms[max_group1] del antonyms[min_group2] del antonyms[max_group2] antonyms[min_group1] = min_group2 antonyms[min_group2] = min_group1 return min_group1 if max_group1 in antonyms: antonym_group = antonyms[max_group1] del antonyms[max_group1] antonyms[min_group1] = antonym_group antonyms[antonym_group] = min_group1 return min_group1 def update_groups(groups, group, words): if group in groups: groups[group].update(words) else: groups.update({group: set(words)}) def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group): if relation == '1': if word1 not in synonyms and word2 not in synonyms: current_group += 1 synonyms[word1] = current_group synonyms[word2] = current_group update_groups(groups, current_group, [word1, word2]) return current_group if word1 not in synonyms: synonyms[word1] = synonyms[word2] update_groups(groups, synonyms[word2], [word1]) return current_group if word2 not in synonyms: synonyms[word2] = synonyms[word1] update_groups(groups, synonyms[word1], [word2]) return current_group group1 = synonyms[word1] group2 = synonyms[word2] if group1 != group2: make_synonyms(synonyms, antonyms, groups, group1, group2) return current_group if relation == '2': if word1 not in synonyms: current_group += 1 group1 = current_group synonyms[word1] = group1 update_groups(groups, group1, [word1]) else: group1 = synonyms[word1] if word2 not in synonyms: current_group += 1 group2 = current_group synonyms[word2] = group2 update_groups(groups, group2, [word2]) else: group2 = synonyms[word2] if group1 not in antonyms and group2 not in antonyms: antonyms[group1] = group2 antonyms[group2] = group1 return current_group if group1 in antonyms and antonyms[group1] == group2: antonym_group = antonyms[group1] group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group) if group2 in antonyms and antonyms[group2] != group1: antonym_group = antonyms[group2] make_synonyms(synonyms, antonyms, groups, group1, antonym_group) return current_group def make_relations(relation_no): synonyms = dict() antonyms = dict() groups = dict() current_group = 0 for relation in range(relation_no): relation, word1, word2 = input().split() current_relation = get_relation(synonyms, antonyms, word1, word2) if current_relation == '2' and relation == '1': print('NO') continue if current_relation == '1' and relation == '2': print('NO') continue print('YES') current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group) return (synonyms, antonyms) def answer_questions(question_no, synonyms, antonyms): for question in range(question_no): word1, word2 = input().split() print(get_relation(synonyms, antonyms, word1, word2)) def main(): word_no, relation_no, question_no = [int(number) for number in input().split()] input() synonyms, antonyms = make_relations(relation_no) answer_questions(question_no, synonyms, antonyms) main() ``` ### 199 ```python mod = 998244353 import sys input = sys.stdin.readline from collections import deque from collections import Counter def calc(s, a): return (pow(2, s, mod) + pow(2, a - s, mod)) % mod def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) testcase = int(input()) for test in range(testcase): n, m = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGELIST = [[] for j in range(n + 1)] ANS = 1 Group = [j for j in range(n + 1)] for a, b in EDGE: Union(a, b) EDGELIST[a].append(b) EDGELIST[b].append(a) testing = [None] * (n + 1) flag = 1 for i in range(1, n + 1): if testing[i] != None: continue score = 1 allscore = 1 testing[i] = 2 QUE = deque([i]) while QUE: x = QUE.pop() for to in EDGELIST[x]: if testing[to] == -testing[x]: continue if testing[to] == testing[x]: flag = 0 break testing[to] = -testing[x] if testing[to] == 1: score += 1 allscore += 1 QUE.append(to) if flag == 0: break if flag == 0: break ANS = ANS * calc(score, allscore) % mod if flag == 0: print(0) continue print(ANS) ``` ### 200 ```python import collections import time import os import sys import bisect import heapq from typing import List def solve(N, M, A): dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] for r in range(1, N + 1): for c in range(1, M + 1): dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] for r in range(N, 0, -1): for c in range(M, 0, -1): dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] for r in range(N, 0, -1): for c in range(1, M + 1): dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] for r in range(1, N + 1): for c in range(M, 0, -1): dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] ans = 0 for r in range(2, N): for c in range(2, M): a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] ans = max(ans, a, b) return ans N, M = map(int, input().split()) A = [[0 for _ in range(M + 2)]] for i in range(N): row = [0] + [int(x) for x in input().split()] + [0] A.append(row) A.append([0 for _ in range(M + 2)]) print(solve(N, M, A)) ``` ### Final Query Identify every unordered pair of earlier programs that implements the same input-output specification, including its boundary and edge-case behavior. Each cell may appear in at most one returned pair. Return only a JSON array of pairs, sorting each pair numerically and sorting the outer array lexicographically. Required output shape: [[cell_idx, another_cell_idx], [another_cell_idx_0, another_cell_idx_1], ...]. Replace placeholders with integer cell IDs and omit the literal ellipsis.