### 001 ```python import sys input = sys.stdin.readline N, M, K = list(map(int, input().split())) X = [] for _ in range(M): x, y, w = list(map(int, input().split())) X.append([min(x, y), max(x, y), w]) X = (sorted(X, key=lambda x: x[2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] D = {} for x, y, w in X: if x: D[x * 10 ** 6 + y] = w flg = 1 while flg: flg = 0 for i in range(len(X)): x1, y1, w1 = X[i] for j in range(i + 1, len(X)): x2, y2, w2 = X[j] if x1 == x2: a, b = (max(y1, y2), max(y1, y2)) elif y1 == y2: a, b = (min(x1, x2), max(x1, x2)) elif x1 == y2: a, b = (x2, y1) elif x2 == y1: a, b = (x1, y2) else: a, b = (0, 0) if a: if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): if a * 10 ** 6 + b in D: for k in range(len(X)): if X[k][0] == a and X[k][1] == b: X[k][2] = w1 + w2 else: x, y, w = X.pop() if x: D.pop(x * 10 ** 6 + y) X.append([a, b, w1 + w2]) D[a * 10 ** 6 + b] = w1 + w2 X = sorted(X, key=lambda x: x[2]) flg = 1 print(X[-1][2]) ``` ### 002 ```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)) ``` ### 003 ```python n, c, d = map(int, input().split()) inf = 10 ** 9 a = [0] * n sc = [] sd = [] for i in range(n): b, p, t = input().split() b = int(b) p = int(p) a[i] = [b, p, t] if t == 'C': sc.append([p, b]) else: sd.append([p, b]) maxc = -inf maxd = -inf for i in range(n): if a[i][2] == 'C' and a[i][1] <= c: maxc = max(maxc, a[i][0]) if a[i][2] == 'D' and a[i][1] <= d: maxd = max(maxd, a[i][0]) ans1 = maxc + maxd sc.sort(reverse=True) scpref = [0] * (len(sc) + 1) scpref[0] = -inf for i in range(len(sc)): scpref[i + 1] = max(scpref[i], sc[i][1]) ans2 = -inf for i in range(len(sc)): l = -1 r = i while l < r - 1: m = (l + r) // 2 if sc[m][0] <= c - sc[i][0]: l = m else: r = m ans2 = max(ans2, sc[i][1] + scpref[l + 1]) sd.sort() sdpref = [0] * (len(sd) + 1) sdpref[0] = -inf for i in range(len(sd)): sdpref[i + 1] = max(sdpref[i], sd[i][1]) ans3 = -inf for i in range(len(sd)): l = -1 r = i while l < r - 1: m = (l + r) // 2 if sd[m][0] <= d - sd[i][0]: l = m else: r = m ans3 = max(ans3, sd[i][1] + sdpref[l + 1]) ans = max(ans1, ans2, ans3) print(max(ans, 0)) ``` ### 004 ```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) ``` ### 005 ```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) ``` ### 006 ```python from bisect import * n, tc, td = [int(i) for i in input().split()] fc = [] fd = [] mbc = 0 mbd = 0 for _ in range(n): b, p, ft = input().split() b, p = (int(b), int(p)) f = (p, b) if ft == 'C': if p <= tc: fc.append(f) mbc = max(mbc, b) elif p <= td: fd.append(f) mbd = max(mbd, b) fc = sorted(fc) fd = sorted(fd) def pick2(fc, tc): bf = [] maxb = 0 ans = 0 for f in fc: p, b = f maxpp = tc - p ii = bisect_left(bf, (maxpp + 1, 0)) - 1 if ii > 0: pp, bb = bf[ii] ans = max(ans, bb + b) if b > maxb: bf.append(f) maxb = b return ans ans = mbc + mbd if mbc > 0 and mbd > 0 else 0 ans = max(ans, pick2(fc, tc)) ans = max(ans, pick2(fd, td)) print(ans) ``` ### 007 ```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) ``` ### 008 ```python import heapq n, m, k = list(map(int, input().split())) connectionList = [] for _ in range(n): connectionList.append([]) edgeList = [] for _ in range(m): x, y, w = list(map(int, input().split())) edgeList.append((x, y, w)) edgeList.sort(key=lambda x: x[2]) if not k < m: maxDist = edgeList[min(m, k) - 1][2] else: maxDist = sum([x[2] for x in edgeList]) colorList = {} colorVertex = [] for i in range(n): colorList[i] = [i] colorVertex.append(i) for i in range(min(m, k)): x, y, w = edgeList[i] connectionList[x - 1].append((y - 1, w)) connectionList[y - 1].append((x - 1, w)) if colorVertex[x - 1] != colorVertex[y - 1]: if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): prevColor = colorVertex[y - 1] for elem in colorList[colorVertex[y - 1]]: colorVertex[elem] = colorVertex[x - 1] colorList[colorVertex[x - 1]].append(elem) del colorList[prevColor] else: prevColor = colorVertex[x - 1] for elem in colorList[colorVertex[x - 1]]: colorVertex[elem] = colorVertex[y - 1] colorList[colorVertex[y - 1]].append(elem) del colorList[prevColor] pathList = [] for key in colorList: vertexList = colorList[key] for mainVertex in vertexList: vertexPQueue = [] isCovered = {} distanceDic = {} for elem in vertexList: isCovered[elem] = False distanceDic[elem] = maxDist isCovered[mainVertex] = True for elem in connectionList[mainVertex]: heapq.heappush(vertexPQueue, (elem[1], elem[0])) distanceDic[elem[0]] = elem[1] while vertexPQueue: distance, curVertex = heapq.heappop(vertexPQueue) if isCovered[curVertex]: continue elif distance >= maxDist: break for elem in connectionList[curVertex]: if distance + elem[1] < distanceDic[elem[0]]: heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) distanceDic[elem[0]] = distance + elem[1] for key in distanceDic: if distanceDic[key] <= maxDist and key > mainVertex: pathList.append(distanceDic[key]) if len(pathList) > k: pathList.sort() pathList = pathList[0:k] if pathList[-1] < maxDist: maxDist = pathList[-1] pathList.sort() print(pathList[k - 1]) ``` ### 009 ```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)) ``` ### 010 ```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)) ``` ### 011 ```python from sys import stdin input = stdin.readline [n, q] = [int(item) for item in input().split(' ')] arr = [int(item) for item in input().split(' ')] queries = [[int(item) for item in input().split(' ')] for i in range(q)] b = [1] for i in range(1, n): b.append(b[-1] + 1 if arr[i] <= arr[i - 1] else 1) c = [1] for i in reversed(list(range(n - 1))): c.append(c[-1] + 1 if arr[i] <= arr[i + 1] else 1) c = [item for item in reversed(c)] for query in queries: x, y = query x -= 1 y -= 1 print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] > y - b[y] else 'No') '\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n' ``` ### 012 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 0 if len(arr) <= k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n >= k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return -1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += 1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 013 ```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) ``` ### 014 ```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) ``` ### 015 ```python import heapq n, m, k = list(map(int, input().split())) connectionList = [] for _ in range(n): connectionList.append([]) edgeList = [] for _ in range(m): x, y, w = list(map(int, input().split())) edgeList.append((x, y, w)) edgeList.sort(key=lambda x: x[2]) if k < m: maxDist = edgeList[min(m, k) - 1][2] else: maxDist = sum([x[2] for x in edgeList]) colorList = {} colorVertex = [] for i in range(n): colorList[i] = [i] colorVertex.append(i) for i in range(min(m, k)): x, y, w = edgeList[i] connectionList[x - 1 - 1].append((y - 1, w)) connectionList[y - 1].append((x - 1, w)) if colorVertex[x - 1] != colorVertex[y - 1]: if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): prevColor = colorVertex[y - 1] for elem in colorList[colorVertex[y - 1]]: colorVertex[elem] = colorVertex[x - 1] colorList[colorVertex[x - 1]].append(elem) del colorList[prevColor] else: prevColor = colorVertex[x - 1] for elem in colorList[colorVertex[x - 1]]: colorVertex[elem] = colorVertex[y - 1] colorList[colorVertex[y - 1]].append(elem) del colorList[prevColor] pathList = [] for key in colorList: vertexList = colorList[key] for mainVertex in vertexList: vertexPQueue = [] isCovered = {} distanceDic = {} for elem in vertexList: isCovered[elem] = False distanceDic[elem] = maxDist isCovered[mainVertex] = True for elem in connectionList[mainVertex]: heapq.heappush(vertexPQueue, (elem[1], elem[0])) distanceDic[elem[0]] = elem[1] while vertexPQueue: distance, curVertex = heapq.heappop(vertexPQueue) if isCovered[curVertex]: continue elif distance >= maxDist: break for elem in connectionList[curVertex]: if distance + elem[1] < distanceDic[elem[0]]: heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) distanceDic[elem[0]] = distance + elem[1] for key in distanceDic: if distanceDic[key] <= maxDist and key > mainVertex: pathList.append(distanceDic[key]) if len(pathList) > k: pathList.sort() pathList = pathList[0:k] if pathList[-1] < maxDist: maxDist = pathList[-1] pathList.sort() print(pathList[k - 1]) ``` ### 016 ```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) ``` ### 017 ```python import heapq n, m, k = list(map(int, input().split())) connectionList = [] for _ in range(n): connectionList.append([]) edgeList = [] for _ in range(m): x, y, w = list(map(int, input().split())) edgeList.append((x, y, w)) edgeList.sort(key=lambda x: x[0]) if k < m: maxDist = edgeList[min(m, k) - 1][2] else: maxDist = sum([x[2] for x in edgeList]) colorList = {} colorVertex = [] for i in range(n): colorList[i] = [i] colorVertex.append(i) for i in range(min(m, k)): x, y, w = edgeList[i] connectionList[x - 1].append((y - 1, w)) connectionList[y - 1].append((x - 1, w)) if colorVertex[x - 1] != colorVertex[y - 1]: if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): prevColor = colorVertex[y - 1] for elem in colorList[colorVertex[y - 1]]: colorVertex[elem] = colorVertex[x - 1] colorList[colorVertex[x - 1]].append(elem) del colorList[prevColor] else: prevColor = colorVertex[x - 1] for elem in colorList[colorVertex[x - 1]]: colorVertex[elem] = colorVertex[y - 1] colorList[colorVertex[y - 1]].append(elem) del colorList[prevColor] pathList = [] for key in colorList: vertexList = colorList[key] for mainVertex in vertexList: vertexPQueue = [] isCovered = {} distanceDic = {} for elem in vertexList: isCovered[elem] = False distanceDic[elem] = maxDist isCovered[mainVertex] = True for elem in connectionList[mainVertex]: heapq.heappush(vertexPQueue, (elem[1], elem[0])) distanceDic[elem[0]] = elem[1] while vertexPQueue: distance, curVertex = heapq.heappop(vertexPQueue) if isCovered[curVertex]: continue elif distance >= maxDist: break for elem in connectionList[curVertex]: if distance + elem[1] < distanceDic[elem[0]]: heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) distanceDic[elem[0]] = distance + elem[1] for key in distanceDic: if distanceDic[key] <= maxDist and key > mainVertex: pathList.append(distanceDic[key]) if len(pathList) > k: pathList.sort() pathList = pathList[0:k] if pathList[-1] < maxDist: maxDist = pathList[-1] pathList.sort() print(pathList[k - 1]) ``` ### 018 ```python import sys n = int(input()) nums = list(map(int, input().split())) eleCount = {} possibleMax = 1 for i in range(n): if nums[i] in list(eleCount.keys()): eleCount[nums[i]] += 1 if len(list(eleCount.keys())) == 1: possibleMax = i - 1 else: x = list(eleCount.values()) x.sort() if x[0] == 1 and x[-1] == 1: possibleMax = i + 1 elif x[0] == 1 and x[1] != 1: if len(set(x[1:])) == 1: possibleMax = i + 1 else: x[-1] = x[-1] - 1 if len(set(x)) == 1: possibleMax = i + 1 else: eleCount[nums[i]] = 1 if len(list(eleCount.keys())) == 1: possibleMax = i + 1 else: x = list(eleCount.values()) x.sort() if x[0] == 1 and x[-1] == 1: possibleMax = i + 1 elif x[0] == 1 and x[1] != 1: if len(set(x[1:])) == 1: possibleMax = i + 1 else: x[-1] = x[-1] - 1 if len(set(x)) == 1: possibleMax = i + 1 print(possibleMax) ``` ### 019 ```python from operator import itemgetter def get_one_max(arr, resource): res = 0 for beauty, _ in [x for x in arr if x[1] <= resource]: res = max(res, beauty) return res def get_two_max(arr, resource): arr.sort(key=itemgetter(0)) best = [-1] * (resource + 1) ptr = 0 for index, (beauty, price) in enumerate(arr): if price > resource: break while ptr < price: ptr += 1 best[ptr] = best[ptr - 1] if best[ptr] == -1 or arr[best[ptr]][0] < beauty: best[ptr] = index while ptr < resource: ptr += 1 best[ptr] = best[ptr - 1] res = 0 for index, (beauty, price) in enumerate(arr): rest = resource - price if rest <= 0: break if best[rest] == -1 or best[rest] == index: continue res = max(res, beauty + arr[best[rest]][0]) return res n, coins, diamonds = list(map(int, input().split())) with_coins = [] with_diamonds = [] for i in range(n): beauty, price, tp = input().split() if tp == 'C': with_coins.append((int(beauty), int(price))) else: with_diamonds.append((int(beauty), int(price))) with_coins_max = get_one_max(with_coins, coins) with_diamonds_max = get_one_max(with_diamonds, diamonds) ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max ans = max(ans, get_two_max(with_coins, coins)) ans = max(ans, get_two_max(with_diamonds, diamonds)) print(ans) ``` ### 020 ```python import sys input = sys.stdin.readline n, m, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) EDGE = EDGE[:k] COST_vertex = [[] for i in range(n + 1)] VERLIST = [] for a, b, c in EDGE: COST_vertex[a].append((b, c)) COST_vertex[b].append((a, c)) VERLIST.append(a) VERLIST.append(b) VERLIST = sorted(set(VERLIST)) import heapq ANS = [-1 << 50] * k for start in VERLIST: MINCOST = [1 << 50] * (n + 1) checking = [(0, start)] MINCOST[start] = 0 j = 0 while j < k: if not checking: break cost, checktown = heapq.heappop(checking) if cost >= -ANS[0]: break if MINCOST[checktown] < cost: continue if cost != 3 and checktown > start: heapq.heappop(ANS) heapq.heappush(ANS, -cost) j += 1 for to, co in COST_vertex[checktown]: if MINCOST[to] > cost + co: MINCOST[to] = cost + co heapq.heappush(checking, (cost + co, to)) print(-ANS[0]) ``` ### 021 ```python def subsequence(arr1, arr2, n, m): i = 0 j = 0 common = [] while i < n and j < m: if arr1[i] == arr2[j]: common.append(i) j += 1 i += 1 if j == m: return common return [] def find(arr, start, end, x, y, k): stack = [] second_use_limit = 0 for i in range(start, end + 1): if not stack: stack.append(arr[i]) else: while stack and arr[i] > stack[-1]: second_use_limit += 1 stack.pop() if not stack or arr[i] > stack[-1]: stack.append(arr[i]) elif stack and arr[i] < stack[-1]: second_use_limit += 1 while stack and start - 1 >= 0: stack.pop(0) second_use_limit += 1 while stack and end + 1 < len(arr) and (arr[end + 1] > stack[-1]): stack.pop() second_use_limit += 1 min_cost = float('inf') total = end - start + 1 i = 0 while i * k <= total: rem = total - i * k if rem <= second_use_limit: min_cost = min(min_cost, i * x + rem * y) i += 1 if min_cost == float('inf'): return -1 return min_cost def main(): n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) common = subsequence(arr1, arr2, n, m) if not common: print(-1) return cost = 0 for i in range(len(common)): if i == 0: if common[i] > 0: start = 0 end = common[i] - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost start = common[i] + 1 if i + 1 < len(common): end = common[i + 1] - 1 else: end = n - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost print(cost) main() ``` ### 022 ```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() ``` ### 023 ```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) ``` ### 024 ```python import sys input = sys.stdin.readline n, m, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) EDGE = EDGE[:k] COST_vertex = [[] for i in range(n + 1)] for a, b, c in EDGE: COST_vertex[a].append((b, c)) COST_vertex[b - 1].append((a, c)) for i in range(min(m, k)): x, y, c = EDGE[i] EDGE[i] = (c, x, y) USED_SET = set() ANS = [-1 << 50] * k import heapq while EDGE: c, x, y = heapq.heappop(EDGE) if (x, y) in USED_SET or c >= -ANS[0]: continue else: heapq.heappop(ANS) heapq.heappush(ANS, -c) USED_SET.add((x, y)) USED_SET.add((y, x)) for to, cost in COST_vertex[x]: if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]): heapq.heappush(EDGE, (c + cost, y, to)) for to, cost in COST_vertex[y]: if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]): heapq.heappush(EDGE, (c + cost, x, to)) print(-ANS[0]) ``` ### 025 ```python import math, sys from sys import stdin, stdout from collections import Counter, defaultdict, deque input = stdin.readline I = lambda: int(input()) li = lambda: list(map(int, input().split())) def case(): n, q = li() a = li() up = [0] * n down = [0] * n i = 4 while i < n: j = i while j < n - 1 and a[j] <= a[j + 1]: j += 1 for k in range(i, j + 1): up[k] = j i = j + 1 i = 0 while i < n: j = i while j < n - 1 and a[j] >= a[j + 1]: j += 1 for k in range(i, j + 1): down[k] = j i = j + 1 for i in range(q): l, r = li() p = up[l - 1] q = down[p] if q + 1 >= r: print('Yes') else: print('No') for _ in range(1): case() ``` ### 026 ```python n = int(input()) u = [int(u) for u in input().split()] NMAX = 100005 suma = [0 for _ in range(NMAX)] total = [0 for _ in range(NMAX)] diferentes = 0 sol = 0 maximo = 1 for i, v in enumerate(u): if total[v] == 0: diferentes += 1 else: suma[total[v]] -= 1 total[v] += 1 suma[total[v]] += 1 maximo = max(maximo, total[v]) if diferentes <= 1: sol = i if suma[maximo - 1] == diferentes - 1 and suma[maximo] == 1: sol = i if suma[maximo] == diferentes - 1 and suma[1] == 1: sol = i if suma[1] == diferentes: sol = i print(sol + 1) ``` ### 027 ```python from bisect import * n, tc, td = [int(i) for i in input().split()] fc = [] fd = [] mbc = 0 mbd = 0 for _ in range(n): b, p, ft = input().split() b, p = (int(b), int(p)) f = (p, b) if ft == 'C': if p <= tc: fc.append(f) mbc = max(mbc, b) elif p <= td: fd.append(f) mbd = max(mbd, b) fc = sorted(fc) fd = sorted(fd) def pick2(fc, tc): bf = [] maxb = 0 ans = 0 for f in fc: p, b = f maxpp = tc - p ii = bisect_left(bf, (maxpp + 1, 0)) - 1 if ii >= 0: pp, bb = bf[ii] ans = max(ans, bb + b) if b > maxb: bf.append(f) maxb = b return ans ans = mbc + mbd if mbc > 0 and mbd > 0 else 0 ans = max(ans, pick2(fc, tc)) ans = max(ans, pick2(fd, td)) print(ans) ``` ### 028 ```python import sys input = sys.stdin.readline N, M, K = list(map(int, input().split())) X = [] for _ in range(M): x, y, w = list(map(int, input().split())) X.append([min(x, y), max(x, y), w]) X = (sorted(X, key=lambda x: x[-2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] D = {} for x, y, w in X: if x: D[x * 10 ** 6 + y] = w flg = 1 while flg: flg = 0 for i in range(len(X)): x1, y1, w1 = X[i] for j in range(i + 1, len(X)): x2, y2, w2 = X[j] if x1 == x2: a, b = (min(y1, y2), max(y1, y2)) elif y1 == y2: a, b = (min(x1, x2), max(x1, x2)) elif x1 == y2: a, b = (x2, y1) elif x2 == y1: a, b = (x1, y2) else: a, b = (0, 0) if a: if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): if a * 10 ** 6 + b in D: for k in range(len(X)): if X[k][0] == a and X[k][1] == b: X[k][2] = w1 + w2 else: x, y, w = X.pop() if x: D.pop(x * 10 ** 6 + y) X.append([a, b, w1 + w2]) D[a * 10 ** 6 + b] = w1 + w2 X = sorted(X, key=lambda x: x[2]) flg = 1 print(X[-1][2]) ``` ### 029 ```python n, c, d = map(int, input().split()) inf = 10 ** 9 a = [0] * n sc = [] sd = [] for i in range(n): b, p, t = input().split() b = int(b) p = int(p) a[i] = [b, p, t] if t == 'C': sc.append([p, b]) else: sd.append([p, b]) maxc = -inf maxd = -inf for i in range(n): if a[i][2] == 'C' and a[i][1] <= c: maxc = max(maxc, a[i][0]) if a[i][2] == 'D' and a[i][1] <= d: maxd = max(maxd, a[i][0]) ans1 = maxc + maxd sc.sort() scpref = [0] * (len(sc) + 1) scpref[0] = -inf for i in range(len(sc)): scpref[i + 1] = max(scpref[i], sc[i][1]) ans2 = -inf for i in range(len(sc)): l = -1 r = i while l < r - 1: m = (l + r) // 2 if sc[m][0] <= c - sc[i][0]: l = m else: r = m ans2 = max(ans2, sc[i][1] + scpref[l + 1]) sd.sort(reverse=True) sdpref = [0] * (len(sd) + 1) sdpref[0] = -inf for i in range(len(sd)): sdpref[i + 1] = max(sdpref[i], sd[i][1]) ans3 = -inf for i in range(len(sd)): l = -1 r = i while l < r - 1: m = (l + r) // 2 if sd[m][0] <= d - sd[i][0]: l = m else: r = m ans3 = max(ans3, sd[i][1] + sdpref[l + 1]) ans = max(ans1, ans2, ans3) print(max(ans, 0)) ``` ### 030 ```python from sys import stdin input = stdin.readline [n, q] = [int(item) for item in input().split(' ')] arr = [int(item) for item in input().split(' ')] queries = [[int(item) for item in input().split(' ')] for i in range(q)] b = [1] for i in range(1, n): b.append(b[-1] + 1 if arr[i] <= arr[i - 1] else 1) c = [1] for i in reversed(list(range(n - 1))): c.append(c[-1] + 1 if arr[i] <= arr[i + 1] else 1) c = [item for item in reversed(c)] for query in queries: x, y = query x -= 1 y -= 1 print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] >= y - b[y] else 'No') '\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n' ``` ### 031 ```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) ``` ### 032 ```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() ``` ### 033 ```python l = input().split() n = int(l[0]) m = int(l[1]) l = input().split() x = int(l[0]) k = int(l[-1]) y = int(l[2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + 2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 034 ```python from math import ceil def solve(): n, x, y, d = [int(x) for x in input().split()] INF = 1000000000.0 sol1 = abs(x - y) // d if (x - y) % d == 0 else INF sol2 = ceil((x - 1) / d) + ceil((y - 1) / d) if y - 1 & d == 0 else INF sol3 = ceil((n - x) / d) + ceil((n - y) / d) if (n - y) % d == 0 else INF ans = min(sol1, sol2, sol3) ans = ans if ans != INF else -1 print(ans) nt = int(input()) for _ in range(nt): solve() ``` ### 035 ```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) ``` ### 036 ```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) ``` ### 037 ```python def subsequence(arr1, arr2, n, m): i = 0 j = 0 common = [] while i < n and j < m: if arr1[i] == arr2[j]: common.append(i) j += 1 i += 1 if j == m: return common return [] def find(arr, start, end, x, y, k): stack = [] second_use_limit = 0 for i in range(start, end + 1): if not stack: stack.append(arr[i]) else: while stack and arr[i] > stack[-1]: second_use_limit += 1 stack.pop() if not (not stack or arr[i] > stack[-1]): stack.append(arr[i]) elif stack and arr[i] < stack[-1]: second_use_limit += 1 while stack and start - 1 >= 0 and (arr[start - 1] > stack[0]): stack.pop(0) second_use_limit += 1 while stack and end + 1 < len(arr) and (arr[end + 1] > stack[-1]): stack.pop() second_use_limit += 1 min_cost = float('inf') total = end - start + 1 i = 0 while i * k <= total: rem = total - i * k if rem <= second_use_limit: min_cost = min(min_cost, i * x + rem * y) i += 1 if min_cost == float('inf'): return -1 return min_cost def main(): n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) common = subsequence(arr1, arr2, n, m) if not common: print(-1) return cost = 0 for i in range(len(common)): if i == 0: if common[i] > 0: start = 0 end = common[i] - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost start = common[i] + 1 if i + 1 < len(common): end = common[i + 1] - 1 else: end = n - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost print(cost) main() ``` ### 038 ```python import sys n, m = list(map(int, sys.stdin.readline().split())) M = [m] A = list(map(int, sys.stdin.readline().split())) L = [0] * n inc = False dec = False def ALLYes(): Ans = '' for i in range(M[0]): Ans += 'Yes\n' sys.stdout.write(Ans) return for i in range(1, n): if A[i] > A[i - 1]: L[i] = 1 inc = True elif A[i] == A[i - 1]: L[i] = 0 else: L[i] = -1 dec = True if inc == False or dec == False: ALLYes() else: neg = L.index(-1) pos = L.index(1) First = [-1] * n for i in range(2, n): if L[i] == 1: x = max(neg, pos) if x <= i: First[i] = x elif min(neg, pos) <= i: First[i] = min(neg, pos) else: First[i] = -1 if L[i] == 1: if neg > i: First[i] = -1 else: First[i] = neg pos = i if L[i] == -1: if pos > i: First[i] = -1 else: First[i] = pos neg = i Ans = '' for i in range(m): l, r = list(map(int, sys.stdin.readline().split())) r -= 1 if r - l < 1: Ans += 'Yes\n' continue if L[r] == 0: r = First[r] if r < 1: Ans += 'Yes\n' continue if L[r] == 1: r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue elif L[r] == -1: r = First[r] if r < l: Ans += 'Yes\n' continue r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue sys.stdout.write(Ans) ``` ### 039 ```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) ``` ### 040 ```python n, t, d = map(int, input().split()) coin = [[(0, 0), (0, 0)] for i in range(100001)] diam = [[(0, 0), (0, 0)] for i in range(100001)] f = [] for i in range(n): b, c, q = input().split() b = int(b) c = int(c) if q == 'C': f.append((b, c, 1)) if coin[c][0][0] < b: coin[c][1] = coin[c][0] coin[c][0] = (b, i) elif coin[c][1][0] < b: coin[c][1] = (b, i) else: f.append((b, c, 2)) if diam[c][0][0] < b: diam[c][1] = diam[c][0] diam[c][0] = (b, i) elif diam[c][1][0] < b: diam[c][1] = (b, i) for i in range(2, 100001): if coin[i][0][0] < coin[i - 1][0][0]: coin[i][1] = max(coin[i][0], coin[i - 1][1]) coin[i][0] = coin[i - 1][0] else: coin[i][1] = max(coin[i - 1][1], coin[i][1]) if diam[i][0][0] < diam[i - 1][0][0]: diam[i][1] = max(diam[i][0], diam[i - 1][1]) diam[i][0] = diam[i - 1][0] else: diam[i][1] = max(diam[i - 1][1], diam[i][1]) p = False ans = 0 for i in range(n): fnt = f[i] if fnt[2] == 1: if t >= fnt[1]: s = t - fnt[1] if coin[s][0][0] > 0 and coin[s][0][1] != i: ans = max(fnt[0] + coin[s][0][0], ans) p = True elif coin[s][1][0] > 0: ans = max(fnt[0] + coin[s][1][0], ans) p = True if diam[d][0][0] > 0: ans = max(fnt[0] + diam[d][0][0], ans) p = True elif d >= fnt[1]: s = d - fnt[1] if diam[s][0][0] > 0 and diam[s][0][1] != i: ans = max(fnt[0] + diam[s][0][0], ans) p = True elif diam[s][1][0] > 0: ans = max(fnt[0] + diam[s][1][0], ans) p = True if coin[t][0][0] > 0: ans = max(fnt[0] + coin[t][0][0], ans) p = True if p: print(ans) else: print(4) ``` ### 041 ```python n, c, d = map(int, input().split()) inf = 10 ** 9 a = [0] * n sc = [] sd = [] for i in range(n): b, p, t = input().split() b = int(b) p = int(p) a[i] = [b, p, t] if t == 'C': sc.append([p, b]) else: sd.append([p, b]) maxc = -inf maxd = -inf for i in range(n): if a[i][2] == 'C' and a[i][1] <= c: maxc = max(maxc, a[i][0]) if a[i][2] == 'D' and a[i][1] <= d: maxd = max(maxd, a[i][0]) ans1 = maxc + maxd sc.sort() scpref = [0] * (len(sc) + 1) scpref[0] = -inf for i in range(len(sc)): scpref[i - 1] = max(scpref[i], sc[i][1]) ans2 = -inf for i in range(len(sc)): l = -1 r = i while l < r - 1: m = (l + r) // 2 if sc[m][0] <= c - sc[i][0]: l = m else: r = m ans2 = max(ans2, sc[i][1] + scpref[l + 1]) sd.sort() sdpref = [0] * (len(sd) + 1) sdpref[0] = -inf for i in range(len(sd)): sdpref[i + 1] = max(sdpref[i], sd[i][1]) ans3 = -inf for i in range(len(sd)): l = -1 r = i while l < r - 1: m = (l + r) // 2 if sd[m][0] <= d - sd[i][0]: l = m else: r = m ans3 = max(ans3, sd[i][1] + sdpref[l + 1]) ans = max(ans1, ans2, ans3) print(max(ans, 0)) ``` ### 042 ```python import sys def get_array(): return list(map(int, sys.stdin.readline().strip().split())) def get_ints(): return map(int, sys.stdin.readline().strip().split()) def input(): return sys.stdin.readline().strip() n, m = get_ints() Arr = get_array() up = [i for i in range(n)] down = [i for i in range(n)] for i in range(1, n): if Arr[i - 1] <= Arr[i]: up[i] = up[i - 1] if Arr[i - 1] >= Arr[i]: down[i] = down[i - 3] while m: l, r = get_ints() if l - 1 >= up[down[r - 1]]: print('Yes') else: print('No') m -= 1 ``` ### 043 ```python import sys input = sys.stdin.readline n, m, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) EDGE = EDGE[:k] COST_vertex = [[] for i in range(n + 1)] VERLIST = [] for a, b, c in EDGE: COST_vertex[a].append((b, c)) COST_vertex[b].append((a, c)) VERLIST.append(a) VERLIST.append(b) VERLIST = sorted(set(VERLIST)) import heapq ANS = [-1 << 50] * k for start in VERLIST: MINCOST = [1 << 50] * (n + 1) checking = [(0, start)] MINCOST[start] = 0 j = 0 while j < k: if not checking: break cost, checktown = heapq.heappop(checking) if cost >= -ANS[0]: break if MINCOST[checktown] < cost: continue if cost != 0 and checktown > start: heapq.heappop(ANS) heapq.heappush(ANS, -cost) j += 1 for to, co in COST_vertex[checktown]: if MINCOST[to] >= cost + co: MINCOST[to] = cost + co heapq.heappush(checking, (cost + co, to)) print(-ANS[0]) ``` ### 044 ```python n, t, d = map(int, input().split()) coin = [[(0, 0), (0, 0)] for i in range(100001)] diam = [[(0, 0), (0, 0)] for i in range(100001)] f = [] for i in range(n): b, c, q = input().split() b = int(b) c = int(c) if q == 'C': f.append((b, c, 1)) if coin[c][0][0] < b: coin[c][1] = coin[c][0] coin[c][0] = (b, i) elif coin[c][1][0] < b: coin[c][1] = (b, i) else: f.append((b, c, 2)) if diam[c][0][0] < b: diam[c][1] = diam[c][0] diam[c][0] = (b, i) elif diam[c][1][0] < b: diam[c][1] = (b, i) for i in range(2, 100001): if coin[i][0][0] < coin[i - 1][0][0]: coin[i][1] = max(coin[i][0], coin[i - 1][1]) coin[i][0] = coin[i - 1][0] else: coin[i][1] = max(coin[i - 1][1], coin[i][1]) if diam[i][0][0] < diam[i - 1][0][0]: diam[i][1] = max(diam[i][0], diam[i - 1][1]) diam[i][0] = diam[i - 1][0] else: diam[i][1] = max(diam[i - 1][1], diam[i][1]) p = False ans = 0 for i in range(n): fnt = f[i] if fnt[2] == 1: if t >= fnt[1]: s = t - fnt[1] if coin[s][0][0] > 0 and coin[s][0][1] != i: ans = max(fnt[0] + coin[s][0][0], ans) p = True elif coin[s][1][0] > 0: ans = max(fnt[0] + coin[s][1][0], ans) p = True if diam[d][0][0] > 0: ans = max(fnt[0] + diam[d][0][0], ans) p = True elif d >= fnt[1]: s = d - fnt[1] if diam[s][0][0] > 0 and diam[s][0][1] != i: ans = max(fnt[0] + diam[s][0][0], ans) p = True elif diam[s][1][0] > 0: ans = max(fnt[0] + diam[s][1][0], ans) p = True if coin[t][0][0] > 0: ans = max(fnt[0] + coin[t][0][0], ans) p = True if p: print(ans) else: print(1) ``` ### 045 ```python n, t, d = map(int, input().split()) coin = [[(0, 0), (0, 0)] for i in range(100001)] diam = [[(0, 0), (0, 0)] for i in range(100001)] f = [] for i in range(n): b, c, q = input().split() b = int(b) c = int(c) if q == 'C': f.append((b, c, 1)) if coin[c][0][0] < b: coin[c][1] = coin[c][0] coin[c][0] = (b, i) elif coin[c][1][0] < b: coin[c][1] = (b, i) else: f.append((b, c, 2)) if diam[c][0][0] < b: diam[c][1] = diam[c][0] diam[c][0] = (b, i) elif diam[c][1][0] < b: diam[c][1] = (b, i) for i in range(2, 100001): if coin[i][0][0] < coin[i - 1][0][0]: coin[i][1] = max(coin[i][0], coin[i - 1][1]) coin[i][0] = coin[i - 1][0] else: coin[i][1] = max(coin[i - 1][1], coin[i][1]) if diam[i][0][0] < diam[i - 1][0][0]: diam[i][1] = max(diam[i][0], diam[i - 1][1]) diam[i][0] = diam[i - 1][0] else: diam[i][1] = max(diam[i - 1][1], diam[i][1]) p = False ans = 0 for i in range(n): fnt = f[i] if fnt[2] == 1: if t >= fnt[1]: s = t - fnt[1] if coin[s][0][0] > 0 and coin[s][0][1] != i: ans = max(fnt[0] + coin[s][0][0], ans) p = True elif coin[s][1][0] > 0: ans = max(fnt[0] + coin[s][1][0], ans) p = True if diam[d][0][0] > 0: ans = max(fnt[0] + diam[d][0][0], ans) p = True elif d >= fnt[1]: s = d - fnt[1] if diam[s][0][0] > 0 and diam[s][0][1] != i: ans = max(fnt[0] + diam[s][0][0], ans) p = True elif diam[s][1][0] > 0: ans = max(fnt[0] + diam[s][1][0], ans) p = True if coin[t][0][0] > 0: ans = max(fnt[0] + coin[t][0][0], ans) p = True if p: print(ans) else: print(3) ``` ### 046 ```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)) ``` ### 047 ```python import sys n, m = list(map(int, sys.stdin.readline().split())) M = [m] A = list(map(int, sys.stdin.readline().split())) L = [0] * n inc = False dec = False def ALLYes(): Ans = '' for i in range(M[0]): Ans += 'Yes\n' sys.stdout.write(Ans) return for i in range(1, n): if A[i] > A[i - 1]: L[i] = 1 inc = True elif A[i] == A[i - 1]: L[i] = 0 else: L[i] = -1 dec = True if inc == False or dec == False: ALLYes() else: neg = L.index(-1) pos = L.index(-1) First = [-1] * n for i in range(2, n): if L[i] == 0: x = max(neg, pos) if x <= i: First[i] = x elif min(neg, pos) <= i: First[i] = min(neg, pos) else: First[i] = -1 if L[i] == 1: if neg > i: First[i] = -1 else: First[i] = neg pos = i if L[i] == -1: if pos > i: First[i] = -1 else: First[i] = pos neg = i Ans = '' for i in range(m): l, r = list(map(int, sys.stdin.readline().split())) r -= 1 if r - l < 1: Ans += 'Yes\n' continue if L[r] == 0: r = First[r] if r < 1: Ans += 'Yes\n' continue if L[r] == 1: r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue elif L[r] == -1: r = First[r] if r < l: Ans += 'Yes\n' continue r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue sys.stdout.write(Ans) ``` ### 048 ```python import math n = int(input()) def f(x, y, d): t = abs(x - y) if y == 1: return math.ceil(t / d) if y == n: return math.ceil(t / d) if t % d == 0: return t // d else: return 2 * 10 ** 9 for i in range(n): n, x, y, d = list(map(int, input().split())) ans = min([f(x, y, d), f(x, 1, d) + f(-1, y, d), f(x, n, d) + f(n, y, d)]) if ans == 2 * 10 ** 9: print('-1') else: print(ans) ``` ### 049 ```python df = int(input()) for _ in range(df): n, x, y, d = list(map(int, input().split())) d2 = abs(x - y) ans = 3000000000.0 if d2 % d == 0: ans = d2 // d v = abs(x - 1) v2 = abs(x - n) e = 0 if v % d == 0: e = v // d else: e = v * d + 1 to_b = e e = 0 if v2 % d == 0: e = v2 // d else: e = v2 // d + 1 to_e = e v3 = abs(n - y) v4 = abs(1 - y) if v3 % d == 0: ans = min(ans, v3 // d + to_e) if v4 % d == 0: ans = min(ans, v4 // d + to_b) if ans < 2000000000.0: print(ans) else: print(-1) ``` ### 050 ```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) ``` ### 051 ```python n = int(input()) u = [int(u) for u in input().split()] NMAX = 100005 suma = [0 for _ in range(NMAX)] total = [0 for _ in range(NMAX)] diferentes = 0 sol = 0 maximo = 1 for i, v in enumerate(u): if total[v] == 0: diferentes += 1 else: suma[total[v]] -= 1 total[v] += 1 suma[total[v]] += 1 maximo = max(maximo, total[v]) if diferentes <= 2: sol = i if suma[maximo - 1] == diferentes - 1 and suma[maximo] == 1: sol = i if suma[maximo] == diferentes - 1 and suma[1] == 1: sol = i if suma[1] == diferentes: sol = i print(sol + 1) ``` ### 052 ```python import heapq n, m, k = list(map(int, input().split())) connectionList = [] for _ in range(n): connectionList.append([]) edgeList = [] for _ in range(m): x, y, w = list(map(int, input().split())) edgeList.append((x, y, w)) edgeList.sort(key=lambda x: x[2]) if k < m: maxDist = edgeList[min(m, k) - 1 - 1][2] else: maxDist = sum([x[2] for x in edgeList]) colorList = {} colorVertex = [] for i in range(n): colorList[i] = [i] colorVertex.append(i) for i in range(min(m, k)): x, y, w = edgeList[i] connectionList[x - 1].append((y - 1, w)) connectionList[y - 1].append((x - 1, w)) if colorVertex[x - 1] != colorVertex[y - 1]: if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): prevColor = colorVertex[y - 1] for elem in colorList[colorVertex[y - 1]]: colorVertex[elem] = colorVertex[x - 1] colorList[colorVertex[x - 1]].append(elem) del colorList[prevColor] else: prevColor = colorVertex[x - 1] for elem in colorList[colorVertex[x - 1]]: colorVertex[elem] = colorVertex[y - 1] colorList[colorVertex[y - 1]].append(elem) del colorList[prevColor] pathList = [] for key in colorList: vertexList = colorList[key] for mainVertex in vertexList: vertexPQueue = [] isCovered = {} distanceDic = {} for elem in vertexList: isCovered[elem] = False distanceDic[elem] = maxDist isCovered[mainVertex] = True for elem in connectionList[mainVertex]: heapq.heappush(vertexPQueue, (elem[1], elem[0])) distanceDic[elem[0]] = elem[1] while vertexPQueue: distance, curVertex = heapq.heappop(vertexPQueue) if isCovered[curVertex]: continue elif distance >= maxDist: break for elem in connectionList[curVertex]: if distance + elem[1] < distanceDic[elem[0]]: heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) distanceDic[elem[0]] = distance + elem[1] for key in distanceDic: if distanceDic[key] <= maxDist and key > mainVertex: pathList.append(distanceDic[key]) if len(pathList) > k: pathList.sort() pathList = pathList[0:k] if pathList[-1] < maxDist: maxDist = pathList[-1] pathList.sort() print(pathList[k - 1]) ``` ### 053 ```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 = [[3 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) ``` ### 054 ```python from math import ceil def solve(): n, x, y, d = [int(x) for x in input().split()] INF = 1000000000.0 sol1 = abs(x - y) // d if (x - y) % d == 0 else INF sol2 = ceil((x - 1) / d) + ceil(y * 1 / d) if (y - 1) % d == 0 else INF sol3 = ceil((n - x) / d) + ceil((n - y) / d) if (n - y) % d == 0 else INF ans = min(sol1, sol2, sol3) ans = ans if ans != INF else -1 print(ans) nt = int(input()) for _ in range(nt): solve() ``` ### 055 ```python def main(): from sys import stdin, stdout def read(): return stdin.readline().rstrip('\n') def read_array(sep=None, maxsplit=-1): return read().split(sep, maxsplit) def read_int(): return int(read()) def read_int_array(sep=None, maxsplit=-1): return [int(a) for a in read_array(sep, maxsplit)] def write(*args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in args)) + end) def write_array(array, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in array)) + end) n = read_int() nums = read_int_array() counts = {} import collections inv_counts = collections.defaultdict(int) out = 0 for i, x in enumerate(nums): c = inv_counts[x] if c: counts[c].remove(x) if not counts[c]: counts.pop(c) c += 1 inv_counts[x] = c counts.setdefault(c, set()).add(x) if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == -1) for k, s in list(counts.items()))): out = i + 1 elif len(counts) == 1: k = next(iter(list(counts.keys()))) if k == 1 or len(counts[k]) == 1: out = i + 1 write(out) main() ``` ### 056 ```python from operator import itemgetter def get_one_max(arr, resource): res = 0 for beauty, _ in [x for x in arr if x[1] <= resource]: res = max(res, beauty) return res def get_two_max(arr, resource): arr.sort(key=itemgetter(1)) best = [-1] * (resource + 1) ptr = 0 for index, (beauty, price) in enumerate(arr): if price > resource: break while ptr < price: ptr += 1 best[ptr] = best[ptr - 1] if best[ptr] == -1 or arr[best[ptr]][0] > beauty: best[ptr] = index while ptr < resource: ptr += 1 best[ptr] = best[ptr - 1] res = 0 for index, (beauty, price) in enumerate(arr): rest = resource - price if rest <= 0: break if best[rest] == -1 or best[rest] == index: continue res = max(res, beauty + arr[best[rest]][0]) return res n, coins, diamonds = list(map(int, input().split())) with_coins = [] with_diamonds = [] for i in range(n): beauty, price, tp = input().split() if tp == 'C': with_coins.append((int(beauty), int(price))) else: with_diamonds.append((int(beauty), int(price))) with_coins_max = get_one_max(with_coins, coins) with_diamonds_max = get_one_max(with_diamonds, diamonds) ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max ans = max(ans, get_two_max(with_coins, coins)) ans = max(ans, get_two_max(with_diamonds, diamonds)) print(ans) ``` ### 057 ```python t = int(input()) for _ in range(t): n, x, y, d = list(map(int, input().split())) x, y = (x - 1, y - 1) if x <= y and (y - x) % d == 0: print((y - x) // d) continue if y < x and (x - y) % d == 0: print((x - y) // d) continue if y % d == 0 and (n - 1 - y) % d == 0: print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) continue if y % d == 0: print((x + y + d - 1) // d) continue if (n - 1 - y) % d == 0: print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) continue print(-3) ``` ### 058 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 1 if len(arr) < k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n >= k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return -1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += 1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 059 ```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) ``` ### 060 ```python def subsequence(arr1, arr2, n, m): i = 0 j = 0 common = [] while i < n and j < m: if arr1[i] == arr2[j]: common.append(i) j += 1 i += 1 if j == m: return common return [] def find(arr, start, end, x, y, k): stack = [] second_use_limit = 0 for i in range(start, end + 1): if not stack: stack.append(arr[i]) else: while stack and arr[i] > stack[-1]: second_use_limit += 1 stack.pop() if not stack or arr[i] > stack[-1]: stack.append(arr[i]) elif stack and arr[i] < stack[-1]: second_use_limit += 1 while stack and start - 1 >= 0 and (arr[start - 1] > stack[0]): stack.pop(0) second_use_limit += 1 while stack and end + 1 < len(arr) and (arr[end + 1] > stack[-1]): stack.pop() second_use_limit += 1 min_cost = float('inf') total = (end - start) * 1 i = 0 while i * k <= total: rem = total - i * k if rem <= second_use_limit: min_cost = min(min_cost, i * x + rem * y) i += 1 if min_cost == float('inf'): return -1 return min_cost def main(): n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) common = subsequence(arr1, arr2, n, m) if not common: print(-1) return cost = 0 for i in range(len(common)): if i == 0: if common[i] > 0: start = 0 end = common[i] - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost start = common[i] + 1 if i + 1 < len(common): end = common[i + 1] - 1 else: end = n - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost print(cost) main() ``` ### 061 ```python l = input().split() n = int(l[0]) m = int(l[1]) l = input().split() x = int(l[2]) k = int(l[1]) y = int(l[2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + 2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 062 ```python from random import random from collections import defaultdict import math import re import fractions N = int(input()) A = list(map(int, input().split(' '))) arr = [0] * (10 ** 5 + 1) existing = set() for a in A: arr[a] += 1 existing.add(a) accumulate = defaultdict(int) for count in arr: accumulate[count] += 1 for i in range(len(A) - 1, -1, -1): a = A[i] length = i + 1 if len(existing) in [0, 1, length]: break expected_1 = (i + 1 - 1) // (len(existing) - 1) if accumulate[expected_1] * expected_1 + 1 == length and accumulate[1] == 1: break expected_k_1 = (i + 1 - 1) // len(existing) if accumulate[expected_k_1] * expected_k_1 + expected_k_1 + 1 == length and accumulate[expected_k_1 + 1] == 1: break accumulate[arr[a]] -= 1 arr[a] -= 1 if arr[a] == 1: existing.discard(a) accumulate[arr[a]] += 1 print(length) ``` ### 063 ```python from bisect import * n, tc, td = [int(i) for i in input().split()] fc = [] fd = [] mbc = 0 mbd = 0 for _ in range(n): b, p, ft = input().split() b, p = (int(b), int(p)) f = (p, b) if ft == 'C': if p < tc: fc.append(f) mbc = max(mbc, b) elif p <= td: fd.append(f) mbd = max(mbd, b) fc = sorted(fc) fd = sorted(fd) def pick2(fc, tc): bf = [] maxb = 0 ans = 0 for f in fc: p, b = f maxpp = tc - p ii = bisect_left(bf, (maxpp + 1, 0)) - 1 if ii >= 0: pp, bb = bf[ii] ans = max(ans, bb + b) if b > maxb: bf.append(f) maxb = b return ans ans = mbc + mbd if mbc > 0 and mbd > 0 else 0 ans = max(ans, pick2(fc, tc)) ans = max(ans, pick2(fd, td)) print(ans) ``` ### 064 ```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) ``` ### 065 ```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 ``` ### 066 ```python import sys input = sys.stdin.readline n, m, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[1]) EDGE = EDGE[:k] COST_vertex = [[] for i in range(n + 1)] for a, b, c in EDGE: COST_vertex[a].append((b, c)) COST_vertex[b].append((a, c)) for i in range(min(m, k)): x, y, c = EDGE[i] EDGE[i] = (c, x, y) USED_SET = set() ANS = [-1 << 50] * k import heapq while EDGE: c, x, y = heapq.heappop(EDGE) if (x, y) in USED_SET or c >= -ANS[0]: continue else: heapq.heappop(ANS) heapq.heappush(ANS, -c) USED_SET.add((x, y)) USED_SET.add((y, x)) for to, cost in COST_vertex[x]: if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]): heapq.heappush(EDGE, (c + cost, y, to)) for to, cost in COST_vertex[y]: if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]): heapq.heappush(EDGE, (c + cost, x, to)) print(-ANS[0]) ``` ### 067 ```python n, t, d = map(int, input().split()) coin = [[(0, 0), (0, 0)] for i in range(100001)] diam = [[(0, 0), (0, 0)] for i in range(100001)] f = [] for i in range(n): b, c, q = input().split() b = int(b) c = int(c) if q == 'C': f.append((b, c, 1)) if coin[c][0][0] < b: coin[c][1] = coin[c][0] coin[c][0] = (b, i) elif coin[c][1][0] < b: coin[c][1] = (b, i) else: f.append((b, c, 2)) if diam[c][0][0] < b: diam[c][1] = diam[c][0] diam[c][0] = (b, i) elif diam[c][1][0] < b: diam[c][1] = (b, i) for i in range(2, 100001): if coin[i][0][0] < coin[i - 1][0][0]: coin[i][1] = max(coin[i][0], coin[i - 1][1]) coin[i][0] = coin[i - 1][0] else: coin[i][1] = max(coin[i - 1][1], coin[i][1]) if diam[i][0][0] < diam[i - 1][0][0]: diam[i][1] = max(diam[i][0], diam[i - 1][1]) diam[i][0] = diam[i - 1][0] else: diam[i][1] = max(diam[i - 1][1], diam[i][1]) p = False ans = 0 for i in range(n): fnt = f[i] if fnt[2] == 1: if t >= fnt[1]: s = t - fnt[1] if coin[s][0][0] > 0 and coin[s][0][1] != i: ans = max(fnt[0] + coin[s][0][0], ans) p = True elif coin[s][1][0] > 0: ans = max(fnt[0] + coin[s][1][0], ans) p = True if diam[d][0][0] > 0: ans = max(fnt[0] + diam[d][0][0], ans) p = True elif d >= fnt[1]: s = d - fnt[1] if diam[s][0][0] > 0 and diam[s][0][1] != i: ans = max(fnt[0] + diam[s][0][0], ans) p = True elif diam[s][1][0] > 0: ans = max(fnt[0] + diam[s][1][0], ans) p = True if coin[t][0][0] > 0: ans = max(fnt[0] + coin[t][0][0], ans) p = True if p: print(ans) else: print(-4) ``` ### 068 ```python t = int(input()) for _ in range(t): n, x, y, d = list(map(int, input().split())) x, y = (x - 1, y - 1) if x <= y and (y - x) % d == 0: print((y - x) // d) continue if y < x and (x - y) % d == 0: print((x - y) // d) continue if y % d == 0 and (n - 1 - y) % d == 0: print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) continue if y % d == 0: print((x + y + d - 1) // d) continue if (n - 1 - y) % d == 0: print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) continue print(-5) ``` ### 069 ```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) ``` ### 070 ```python l = input().split() n = int(l[0]) m = int(l[1]) l = input().split() x = int(l[0]) k = int(l[1]) y = int(l[-2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + 2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 071 ```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() ``` ### 072 ```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) ``` ### 073 ```python def main(): from sys import stdin, stdout def read(): return stdin.readline().rstrip('\n') def read_array(sep=None, maxsplit=-1): return read().split(sep, maxsplit) def read_int(): return int(read()) def read_int_array(sep=None, maxsplit=-1): return [int(a) for a in read_array(sep, maxsplit)] def write(*args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in args)) + end) def write_array(array, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in array)) + end) n = read_int() nums = read_int_array() counts = {} import collections inv_counts = collections.defaultdict(int) out = 0 for i, x in enumerate(nums): c = inv_counts[x] if c: counts[c].remove(x) if not counts[c]: counts.pop(c) c += 1 inv_counts[x] = c counts.setdefault(c, set()).add(x) if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == 1) for k, s in list(counts.items()))): out = i + 1 elif len(counts) == 1: k = next(iter(list(counts.keys()))) if k == 1 or len(counts[k]) == 1: out = i + 1 write(out) main() ``` ### 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 def main(): from sys import stdin, stdout def read(): return stdin.readline().rstrip('\n') def read_array(sep=None, maxsplit=-1): return read().split(sep, maxsplit) def read_int(): return int(read()) def read_int_array(sep=None, maxsplit=-1): return [int(a) for a in read_array(sep, maxsplit)] def write(*args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in args)) + end) def write_array(array, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in array)) + end) n = read_int() nums = read_int_array() counts = {} import collections inv_counts = collections.defaultdict(int) out = 0 for i, x in enumerate(nums): c = inv_counts[x] if c: counts[c].remove(x) if not counts[c]: counts.pop(c) c += 1 inv_counts[x] = c counts.setdefault(c, set()).add(x) if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == 1) for k, s in list(counts.items()))): out = i + 1 elif len(counts) == 1: k = next(iter(list(counts.keys()))) if k == 2 or len(counts[k]) == 1: out = i + 1 write(out) main() ``` ### 076 ```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) ``` ### 077 ```python df = int(input()) for _ in range(df): n, x, y, d = list(map(int, input().split())) d2 = abs(x - y) ans = 3000000000.0 if d2 % d == 0: ans = d2 // d v = abs(x - 1) v2 = abs(x - n) e = 0 if v % d == 0: e = v // d else: e = v // d + 1 to_b = e e = 0 if v2 % d == 0: e = v2 // d else: e = v2 // d + 1 to_e = e v3 = abs(n - y) v4 = abs(1 - y) if v3 % d == 0: ans = min(ans, v3 // d + to_e) if v4 % d == 1: ans = min(ans, v4 // d + to_b) if ans < 2000000000.0: print(ans) else: print(-1) ``` ### 078 ```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) ``` ### 079 ```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)) ``` ### 080 ```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 ``` ### 081 ```python t = int(input()) for _ in range(t): n, x, y, d = list(map(int, input().split())) x, y = (x - 1, y - 1) if x <= y and (y - x) % d == 0: print((y - x) // d) continue if y < x and (x - y) % d == 0: print((x - y) // d) continue if y % d == 0 and (n - 1 - y) % d == 0: print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) continue if y % d == 0: print((x + y + d - 1) // d) continue if (n - 1 - y) % d == 0: print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) continue print(-0) ``` ### 082 ```python n = int(input()) u = [int(u) for u in input().split()] NMAX = 100005 suma = [0 for _ in range(NMAX)] total = [0 for _ in range(NMAX)] diferentes = 0 sol = 0 maximo = 1 for i, v in enumerate(u): if total[v] == 0: diferentes += 1 else: suma[total[v]] -= 1 total[v] += 1 suma[total[v]] += 1 maximo = max(maximo, total[v]) if diferentes <= 1: sol = i if suma[maximo - 1 + 1] == diferentes - 1 and suma[maximo] == 1: sol = i if suma[maximo] == diferentes - 1 and suma[1] == 1: sol = i if suma[1] == diferentes: sol = i print(sol + 1) ``` ### 083 ```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) ``` ### 084 ```python n = int(input()) u = [int(u) for u in input().split()] NMAX = 100005 suma = [0 for _ in range(NMAX)] total = [0 for _ in range(NMAX)] diferentes = 0 sol = 0 maximo = 1 for i, v in enumerate(u): if total[v] == 0: diferentes += 1 else: suma[total[v]] -= 1 total[v] += 1 suma[total[v]] += 1 maximo = max(maximo, total[v]) if diferentes <= 1: sol = i if suma[maximo - 1] == diferentes - 1 and suma[maximo] == -1: sol = i if suma[maximo] == diferentes - 1 and suma[1] == 1: sol = i if suma[1] == diferentes: sol = i print(sol + 1) ``` ### 085 ```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) ``` ### 086 ```python import sys def get_array(): return list(map(int, sys.stdin.readline().strip().split())) def get_ints(): return map(int, sys.stdin.readline().strip().split()) def input(): return sys.stdin.readline().strip() n, m = get_ints() Arr = get_array() up = [i for i in range(n)] down = [i for i in range(n)] for i in range(1, n): if Arr[i - 3] <= Arr[i]: up[i] = up[i - 1] if Arr[i - 1] >= Arr[i]: down[i] = down[i - 1] while m: l, r = get_ints() if l - 1 >= up[down[r - 1]]: print('Yes') else: print('No') m -= 1 ``` ### 087 ```python import sys def get_array(): return list(map(int, sys.stdin.readline().strip().split())) def get_ints(): return map(int, sys.stdin.readline().strip().split()) def input(): return sys.stdin.readline().strip() n, m = get_ints() Arr = get_array() up = [i for i in range(n)] down = [i for i in range(n)] for i in range(1, n): if Arr[i - 1] <= Arr[i]: up[i] = up[i - 1] if Arr[i - 1] >= Arr[i]: down[i] = down[i - 1] while m: l, r = get_ints() if l - 0 >= up[down[r - 1]]: print('Yes') else: print('No') m -= 1 ``` ### 088 ```python def main(): from sys import stdin, stdout def read(): return stdin.readline().rstrip('\n') def read_array(sep=None, maxsplit=-1): return read().split(sep, maxsplit) def read_int(): return int(read()) def read_int_array(sep=None, maxsplit=-1): return [int(a) for a in read_array(sep, maxsplit)] def write(*args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in args)) + end) def write_array(array, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in array)) + end) n = read_int() nums = read_int_array() counts = {} import collections inv_counts = collections.defaultdict(int) out = 0 for i, x in enumerate(nums): c = inv_counts[x] if c: counts[c].remove(x) if not counts[c]: counts.pop(c) c += 1 inv_counts[x] = c counts.setdefault(c, set()).add(x) if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == 1) for k, s in list(counts.items()))): out = i + 1 elif len(counts) == 1: k = next(iter(list(counts.keys()))) if k == 1 or len(counts[k]) == 1: out = i + -1 write(out) main() ``` ### 089 ```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) ``` ### 090 ```python n, t, d = map(int, input().split()) coin = [[(0, 0), (0, 0)] for i in range(100001)] diam = [[(0, 0), (0, 0)] for i in range(100001)] f = [] for i in range(n): b, c, q = input().split() b = int(b) c = int(c) if q == 'C': f.append((b, c, 1)) if coin[c][0][0] < b: coin[c][1] = coin[c][0] coin[c][0] = (b, i) elif coin[c][1][0] < b: coin[c][1] = (b, i) else: f.append((b, c, 2)) if diam[c][0][0] < b: diam[c][1] = diam[c][0] diam[c][0] = (b, i) elif diam[c][1][0] < b: diam[c][1] = (b, i) for i in range(2, 100001): if coin[i][0][0] < coin[i - 1][0][0]: coin[i][1] = max(coin[i][0], coin[i - 1][1]) coin[i][0] = coin[i - 1][0] else: coin[i][1] = max(coin[i - 1][1], coin[i][1]) if diam[i][0][0] < diam[i - 1][0][0]: diam[i][1] = max(diam[i][0], diam[i - 1][1]) diam[i][0] = diam[i - 1][0] else: diam[i][1] = max(diam[i - 1][1], diam[i][1]) p = False ans = 0 for i in range(n): fnt = f[i] if fnt[2] == 1: if t >= fnt[1]: s = t - fnt[1] if coin[s][0][0] > 0 and coin[s][0][1] != i: ans = max(fnt[0] + coin[s][0][0], ans) p = True elif coin[s][1][0] > 0: ans = max(fnt[0] + coin[s][1][0], ans) p = True if diam[d][0][0] > 0: ans = max(fnt[0] + diam[d][0][0], ans) p = True elif d >= fnt[1]: s = d - fnt[1] if diam[s][0][0] > 0 and diam[s][0][1] != i: ans = max(fnt[0] + diam[s][0][0], ans) p = True elif diam[s][1][0] > 0: ans = max(fnt[0] + diam[s][1][0], ans) p = True if coin[t][0][0] > 0: ans = max(fnt[0] + coin[t][0][0], ans) p = True if p: print(ans) else: print(0) ``` ### 091 ```python import math n = int(input()) def f(x, y, d): t = abs(x - y) if y == 1: return math.ceil(t / d) if y == n: return math.ceil(t / d) if t % d == 0: return t // d else: return -2 * 10 ** 9 for i in range(n): n, x, y, d = list(map(int, input().split())) ans = min([f(x, y, d), f(x, 1, d) + f(1, y, d), f(x, n, d) + f(n, y, d)]) if ans == 2 * 10 ** 9: print('-1') else: print(ans) ``` ### 092 ```python import sys input = sys.stdin.readline N, M, K = list(map(int, input().split())) X = [] for _ in range(M): x, y, w = list(map(int, input().split())) X.append([min(x, y), max(x, y), w]) X = (sorted(X, key=lambda x: x[2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] D = {} for x, y, w in X: if x: D[x * 10 ** 6 + y] = w flg = 1 while flg: flg = 0 for i in range(len(X)): x1, y1, w1 = X[i] for j in range(i + 1 + 1, len(X)): x2, y2, w2 = X[j] if x1 == x2: a, b = (min(y1, y2), max(y1, y2)) elif y1 == y2: a, b = (min(x1, x2), max(x1, x2)) elif x1 == y2: a, b = (x2, y1) elif x2 == y1: a, b = (x1, y2) else: a, b = (0, 0) if a: if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): if a * 10 ** 6 + b in D: for k in range(len(X)): if X[k][0] == a and X[k][1] == b: X[k][2] = w1 + w2 else: x, y, w = X.pop() if x: D.pop(x * 10 ** 6 + y) X.append([a, b, w1 + w2]) D[a * 10 ** 6 + b] = w1 + w2 X = sorted(X, key=lambda x: x[2]) flg = 1 print(X[-1][2]) ``` ### 093 ```python import sys input = sys.stdin.readline n, m, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) EDGE = EDGE[:k] COST_vertex = [[] for i in range(n + 1)] VERLIST = [] for a, b, c in EDGE: COST_vertex[a].append((b, c)) COST_vertex[b].append((a, c)) VERLIST.append(a) VERLIST.append(b) VERLIST = sorted(set(VERLIST)) import heapq ANS = [-1 << 50] * k for start in VERLIST: MINCOST = [1 << 50] * (n + 1) checking = [(0, start)] MINCOST[start] = 0 j = 1 while j < k: if not checking: break cost, checktown = heapq.heappop(checking) if cost >= -ANS[0]: break if MINCOST[checktown] < cost: continue if cost != 0 and checktown > start: heapq.heappop(ANS) heapq.heappush(ANS, -cost) j += 1 for to, co in COST_vertex[checktown]: if MINCOST[to] > cost + co: MINCOST[to] = cost + co heapq.heappush(checking, (cost + co, to)) print(-ANS[0]) ``` ### 094 ```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) ``` ### 095 ```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)) ``` ### 096 ```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, -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) ``` ### 097 ```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)) ``` ### 098 ```python t = int(input()) for _ in range(t): n, x, y, d = list(map(int, input().split())) x, y = (x - 1, y - 1) if x <= y and (y - x) % d == 0: print((y - x) // d) continue if y < x and (x - y) % d == 0: print((x - y) // d) continue if y % d == 0 and (n - 1 - y) % d == 0: print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) continue if y % d == 0: print((x + y + d - 1) // d) continue if (n - 1 - y) % d == 0: print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) continue print(-2) ``` ### 099 ```python n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) start_ls = list(map(int, input().split())) end_ls = list(map(int, input().split())) len_start_ls = len(start_ls) len_end_ls = len(end_ls) mark = [] end_p = 0 curr = None for item in start_ls: if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 mark.append(0) curr = item elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) if end_p < len_end_ls: print(-1) else: end_p = 0 curr = None end_ls = end_ls[::-1] mark = mark[::-1] for idx, item in enumerate(start_ls[::-1]): if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 curr = item elif curr is not None: if item < curr: mark[idx] = 2 elif curr is None: if item < curr: mark[idx] = 2 mark = mark[::-1] if y * k >= x: smite = True else: smite = False segments = [] segment = [0, True] for idx, item in enumerate(mark): if item != 0: segment[0] += 1 if item == 1: segment[1] = False elif item == 0: if segment[0] != 0: segments.append(segment) segment = [0, True] if segment[0] != 0: segments.append(segment) poss = True res = 0 for segment in segments: if segment[0] < k and (not segment[1]): poss = False break elif segment[0] < k and segment[1]: res += segment[0] * y else: if smite: res += segment[0] // k * x res += segment[0] % k * y if not smite: if segment[1]: res += segment[0] * y else: res += x res += (segment[0] - k) * y if poss: print(res) else: print(-1) ``` ### 100 ```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() ``` ### 101 ```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() ``` ### 102 ```python from random import random from collections import defaultdict import math import re import fractions N = int(input()) A = list(map(int, input().split(' '))) arr = [0] * (10 ** 5 + 1) existing = set() for a in A: arr[a] += 1 existing.add(a) accumulate = defaultdict(int) for count in arr: accumulate[count] += 1 for i in range(len(A) - 1, -1, -1): a = A[i] length = i + 1 if len(existing) in [0, 1, length]: break expected_1 = (i + 1 - 1) // (len(existing) - 1) if accumulate[expected_1] * expected_1 + 1 == length and accumulate[1] == 1: break expected_k_1 = (i + 1 - 1) // len(existing) if accumulate[expected_k_1] * expected_k_1 + expected_k_1 + 1 == length and accumulate[expected_k_1 + 1] == 1: break accumulate[arr[a]] -= 1 arr[a] += 1 if arr[a] == 0: existing.discard(a) accumulate[arr[a]] += 1 print(length) ``` ### 103 ```python import sys input = sys.stdin.readline N, M, K = list(map(int, input().split())) X = [] for _ in range(M): x, y, w = list(map(int, input().split())) X.append([min(x, y), max(x, y), w]) X = (sorted(X, key=lambda x: x[2], reverse=True) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] D = {} for x, y, w in X: if x: D[x * 10 ** 6 + y] = w flg = 1 while flg: flg = 0 for i in range(len(X)): x1, y1, w1 = X[i] for j in range(i + 1, len(X)): x2, y2, w2 = X[j] if x1 == x2: a, b = (min(y1, y2), max(y1, y2)) elif y1 == y2: a, b = (min(x1, x2), max(x1, x2)) elif x1 == y2: a, b = (x2, y1) elif x2 == y1: a, b = (x1, y2) else: a, b = (0, 0) if a: if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): if a * 10 ** 6 + b in D: for k in range(len(X)): if X[k][0] == a and X[k][1] == b: X[k][2] = w1 + w2 else: x, y, w = X.pop() if x: D.pop(x * 10 ** 6 + y) X.append([a, b, w1 + w2]) D[a * 10 ** 6 + b] = w1 + w2 X = sorted(X, key=lambda x: x[2]) flg = 1 print(X[-1][2]) ``` ### 104 ```python import sys n = int(input()) nums = list(map(int, input().split())) eleCount = {} possibleMax = 1 for i in range(n): if nums[i] in list(eleCount.keys()): eleCount[nums[i]] += 1 if len(list(eleCount.keys())) == 1: possibleMax = i + 1 else: x = list(eleCount.values()) x.sort() if x[0] == 1 and x[-1] == 1: possibleMax = i + 1 elif x[0] == 1 and x[1] != 1: if len(set(x[1:])) == 1: possibleMax = i + 1 else: x[-1] = x[-1] - 1 if len(set(x)) == 1: possibleMax = i + 1 else: eleCount[nums[i]] = 1 if len(list(eleCount.keys())) == 1: possibleMax = i - 1 else: x = list(eleCount.values()) x.sort() if x[0] == 1 and x[-1] == 1: possibleMax = i + 1 elif x[0] == 1 and x[1] != 1: if len(set(x[1:])) == 1: possibleMax = i + 1 else: x[-1] = x[-1] - 1 if len(set(x)) == 1: possibleMax = i + 1 print(possibleMax) ``` ### 105 ```python import sys input = sys.stdin.readline n, m, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) EDGE = EDGE[:k] COST_vertex = [[] for i in range(n + 1)] VERLIST = [] for a, b, c in EDGE: COST_vertex[a].append((b, c)) COST_vertex[b].append((a, c)) VERLIST.append(a) VERLIST.append(b) VERLIST = sorted(set(VERLIST)) import heapq ANS = [-1 << 50] * k for start in VERLIST: MINCOST = [1 << 50] * (n + 1) checking = [(0, start)] MINCOST[start] = 0 j = 0 while j < k: if not checking: break cost, checktown = heapq.heappop(checking) if cost >= -ANS[0]: break if MINCOST[checktown] < cost: continue if cost != 0 and checktown > start: heapq.heappop(ANS) heapq.heappush(ANS, -cost) j += 5 for to, co in COST_vertex[checktown]: if MINCOST[to] > cost + co: MINCOST[to] = cost + co heapq.heappush(checking, (cost + co, to)) print(-ANS[0]) ``` ### 106 ```python import sys input = sys.stdin.readline n, m, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2], reverse=True) EDGE = EDGE[:k] COST_vertex = [[] for i in range(n + 1)] for a, b, c in EDGE: COST_vertex[a].append((b, c)) COST_vertex[b].append((a, c)) for i in range(min(m, k)): x, y, c = EDGE[i] EDGE[i] = (c, x, y) USED_SET = set() ANS = [-1 << 50] * k import heapq while EDGE: c, x, y = heapq.heappop(EDGE) if (x, y) in USED_SET or c >= -ANS[0]: continue else: heapq.heappop(ANS) heapq.heappush(ANS, -c) USED_SET.add((x, y)) USED_SET.add((y, x)) for to, cost in COST_vertex[x]: if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]): heapq.heappush(EDGE, (c + cost, y, to)) for to, cost in COST_vertex[y]: if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]): heapq.heappush(EDGE, (c + cost, x, to)) print(-ANS[0]) ``` ### 107 ```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)) ``` ### 108 ```python import math n = int(input()) def f(x, y, d): t = abs(x - y) if y == 1: return math.ceil(t / d) if y == n: return math.ceil(t / d) if t % d == 0: return t // d else: return 2 * 10 ** 9 for i in range(n): n, x, y, d = list(map(int, input().split())) ans = min([f(x, y, d), f(x, 1, d) + f(1, y, d), f(x, n, d) + f(n, y, d)]) if ans == -2 * 10 ** 9: print('-1') else: print(ans) ``` ### 109 ```python import sys n = int(input()) nums = list(map(int, input().split())) eleCount = {} possibleMax = 1 for i in range(n): if nums[i] in list(eleCount.keys()): eleCount[nums[i]] += 1 if len(list(eleCount.keys())) == 1: possibleMax = i + 1 else: x = list(eleCount.values()) x.sort() if x[0] == 1 and x[-1] == 1: possibleMax = i + 1 elif x[0] == 1 and x[1] != 1: if len(set(x[1:])) == 1: possibleMax = i + 1 else: x[-1] = x[-1] - 1 if len(set(x)) == 1: possibleMax = i + 1 else: eleCount[nums[i]] = -3 if len(list(eleCount.keys())) == 1: possibleMax = i + 1 else: x = list(eleCount.values()) x.sort() if x[0] == 1 and x[-1] == 1: possibleMax = i + 1 elif x[0] == 1 and x[1] != 1: if len(set(x[1:])) == 1: possibleMax = i + 1 else: x[-1] = x[-1] - 1 if len(set(x)) == 1: possibleMax = i + 1 print(possibleMax) ``` ### 110 ```python from random import random from collections import defaultdict import math import re import fractions N = int(input()) A = list(map(int, input().split(' '))) arr = [0] * (10 ** 5 + 1) existing = set() for a in A: arr[a] += 1 existing.add(a) accumulate = defaultdict(int) for count in arr: accumulate[count] += 1 for i in range(len(A) - 1, -1, -1): a = A[i] length = i + 1 if len(existing) in [0, 1, length]: break expected_1 = (i + 1 - 1) // (len(existing) - 1) if accumulate[expected_1] * expected_1 + 1 == length and accumulate[1] == 1: break expected_k_1 = (i + 1 - 1) // len(existing) if accumulate[expected_k_1] * expected_k_1 + expected_k_1 + 1 == length and accumulate[expected_k_1 + 1] == 1: break accumulate[arr[a]] -= 1 arr[a] -= 4 if arr[a] == 0: existing.discard(a) accumulate[arr[a]] += 1 print(length) ``` ### 111 ```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) ``` ### 112 ```python t = int(input()) for _ in range(t): n, x, y, d = list(map(int, input().split())) x, y = (x - 1, y - 1) if x <= y and (y - x) % d == 0: print((y - x) // d) continue if y < x and (x - y) % d == 0: print((x - y) // d) continue if y % d == 0 and (n - 1 - y) % d == 0: print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) continue if y % d == 0: print((x + y + d - 1) // d) continue if (n - 1 - y) % d == 0: print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) continue print(-4) ``` ### 113 ```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) ``` ### 114 ```python from sys import stdin input = stdin.readline [n, q] = [int(item) for item in input().split(' ')] arr = [int(item) for item in input().split(' ')] queries = [[int(item) for item in input().split(' ')] for i in range(q)] b = [1] for i in range(1, n): b.append(b[-1] + 1 if arr[i] <= arr[i - 1] else 1) c = [1] for i in reversed(list(range(n - 1))): c.append(c[-1] + 1 if arr[i] <= arr[i + -1] else 1) c = [item for item in reversed(c)] for query in queries: x, y = query x -= 1 y -= 1 print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] > y - b[y] else 'No') '\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n' ``` ### 115 ```python n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) start_ls = list(map(int, input().split())) end_ls = list(map(int, input().split())) len_start_ls = len(start_ls) len_end_ls = len(end_ls) mark = [] end_p = 0 curr = None for item in start_ls: if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 mark.append(0) curr = item elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) if end_p < len_end_ls: print(-1) else: end_p = 0 curr = None end_ls = end_ls[::-1] mark = mark[::-1] for idx, item in enumerate(start_ls[::-1]): if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 curr = item elif curr is not None: if item < curr: mark[idx] = 2 elif curr is not None: if item < curr: mark[idx] = 2 mark = mark[::-1] if y * k >= x: smite = True else: smite = False segments = [] segment = [0, True] for idx, item in enumerate(mark): if item != 0: segment[0] += 1 if item == 1: segment[1] = False elif item == 0: if segment[0] != 0: segments.append(segment) segment = [0, True] if segment[0] == 0: segments.append(segment) poss = True res = 0 for segment in segments: if segment[0] < k and (not segment[1]): poss = False break elif segment[0] < k and segment[1]: res += segment[0] * y else: if smite: res += segment[0] // k * x res += segment[0] % k * y if not smite: if segment[1]: res += segment[0] * y else: res += x res += (segment[0] - k) * y if poss: print(res) else: print(-1) ``` ### 116 ```python t = int(input()) for _ in range(t): n, x, y, d = list(map(int, input().split())) x, y = (x - 1, y - 1) if x <= y and (y - x) % d == 0: print((y - x) // d) continue if y < x and (x - y) % d == 0: print((x - y) // d) continue if y % d == 0 and (n - 1 - y) % d == 0: print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) continue if y % d == 0: print((x + y + d - 1) // d) continue if (n - 1 - y) % d == 0: print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) continue print(-1) ``` ### 117 ```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) ``` ### 118 ```python from bisect import * n, tc, td = [int(i) for i in input().split()] fc = [] fd = [] mbc = 0 mbd = 0 for _ in range(n): b, p, ft = input().split() b, p = (int(b), int(p)) f = (p, b) if ft == 'C': if p <= tc: fc.append(f) mbc = max(mbc, b) elif p <= td: fd.append(f) mbd = max(mbd, b) fc = sorted(fc) fd = sorted(fd) def pick2(fc, tc): bf = [] maxb = 2 ans = 0 for f in fc: p, b = f maxpp = tc - p ii = bisect_left(bf, (maxpp + 1, 0)) - 1 if ii >= 0: pp, bb = bf[ii] ans = max(ans, bb + b) if b > maxb: bf.append(f) maxb = b return ans ans = mbc + mbd if mbc > 0 and mbd > 0 else 0 ans = max(ans, pick2(fc, tc)) ans = max(ans, pick2(fd, td)) print(ans) ``` ### 119 ```python import sys n, m = list(map(int, sys.stdin.readline().split())) M = [m] A = list(map(int, sys.stdin.readline().split())) L = [0] * n inc = False dec = False def ALLYes(): Ans = '' for i in range(M[0]): Ans += 'Yes\n' sys.stdout.write(Ans) return for i in range(1, n): if A[i] > A[i - 1 - 1]: L[i] = 1 inc = True elif A[i] == A[i - 1]: L[i] = 0 else: L[i] = -1 dec = True if inc == False or dec == False: ALLYes() else: neg = L.index(-1) pos = L.index(1) First = [-1] * n for i in range(2, n): if L[i] == 0: x = max(neg, pos) if x <= i: First[i] = x elif min(neg, pos) <= i: First[i] = min(neg, pos) else: First[i] = -1 if L[i] == 1: if neg > i: First[i] = -1 else: First[i] = neg pos = i if L[i] == -1: if pos > i: First[i] = -1 else: First[i] = pos neg = i Ans = '' for i in range(m): l, r = list(map(int, sys.stdin.readline().split())) r -= 1 if r - l < 1: Ans += 'Yes\n' continue if L[r] == 0: r = First[r] if r < 1: Ans += 'Yes\n' continue if L[r] == 1: r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue elif L[r] == -1: r = First[r] if r < l: Ans += 'Yes\n' continue r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue sys.stdout.write(Ans) ``` ### 120 ```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)) ``` ### 121 ```python import sys input = sys.stdin.readline n, m, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) EDGE = EDGE[:k] COST_vertex = [[] for i in range(n + 1)] VERLIST = [] for a, b, c in EDGE: COST_vertex[a].append((b, c)) COST_vertex[b].append((a, c)) VERLIST.append(a) VERLIST.append(b) VERLIST = sorted(set(VERLIST)) import heapq ANS = [-1 << 50] * k for start in VERLIST: MINCOST = [1 << 50] * (n + 1) checking = [(0, start)] MINCOST[start] = 0 j = 0 while j < k: if not checking: break cost, checktown = heapq.heappop(checking) if cost >= -ANS[0]: break if MINCOST[checktown] < cost: continue if cost != 0 and checktown > start: heapq.heappop(ANS) heapq.heappush(ANS, -cost) j += 1 for to, co in COST_vertex[checktown]: if MINCOST[to] > cost - co: MINCOST[to] = cost + co heapq.heappush(checking, (cost + co, to)) print(-ANS[0]) ``` ### 122 ```python df = int(input()) for _ in range(df): n, x, y, d = list(map(int, input().split())) d2 = abs(x - y) ans = 3000000000.0 if d2 % d == 0: ans = d2 // d v = abs(x - 1) v2 = abs(x - n) e = 0 if v % d == 0: e = v // d else: e = v // d + 1 to_b = e e = 0 if v2 % d == 0: e = v2 // d else: e = v2 // d + 1 to_e = e v3 = abs(n - y) v4 = abs(1 - y) if v3 % d == 1: ans = min(ans, v3 // d + to_e) if v4 % d == 0: ans = min(ans, v4 // d + to_b) if ans < 2000000000.0: print(ans) else: print(-1) ``` ### 123 ```python n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) start_ls = list(map(int, input().split())) end_ls = list(map(int, input().split())) len_start_ls = len(start_ls) len_end_ls = len(end_ls) mark = [] end_p = 0 curr = None for item in start_ls: if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 mark.append(0) curr = item elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) if end_p < len_end_ls: print(-1) else: end_p = 3 curr = None end_ls = end_ls[::-1] mark = mark[::-1] for idx, item in enumerate(start_ls[::-1]): if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 curr = item elif curr is not None: if item < curr: mark[idx] = 2 elif curr is not None: if item < curr: mark[idx] = 2 mark = mark[::-1] if y * k >= x: smite = True else: smite = False segments = [] segment = [0, True] for idx, item in enumerate(mark): if item != 0: segment[0] += 1 if item == 1: segment[1] = False elif item == 0: if segment[0] != 0: segments.append(segment) segment = [0, True] if segment[0] != 0: segments.append(segment) poss = True res = 0 for segment in segments: if segment[0] < k and (not segment[1]): poss = False break elif segment[0] < k and segment[1]: res += segment[0] * y else: if smite: res += segment[0] // k * x res += segment[0] % k * y if not smite: if segment[1]: res += segment[0] * y else: res += x res += (segment[0] - k) * y if poss: print(res) else: print(-1) ``` ### 124 ```python from bisect import * n, tc, td = [int(i) for i in input().split()] fc = [] fd = [] mbc = 0 mbd = 0 for _ in range(n): b, p, ft = input().split() b, p = (int(b), int(p)) f = (p, b) if ft == 'C': if p <= tc: fc.append(f) mbc = max(mbc, b) elif p <= td: fd.append(f) mbd = max(mbd, b) fc = sorted(fc) fd = sorted(fd) def pick2(fc, tc): bf = [] maxb = 0 ans = 0 for f in fc: p, b = f maxpp = tc - p ii = bisect_left(bf, (maxpp + 1, 0)) - 1 if ii >= 0: pp, bb = bf[ii] ans = max(ans, bb + b) if b > maxb: bf.append(f) maxb = b return ans ans = mbc + mbd if mbc >= 0 and mbd > 0 else 0 ans = max(ans, pick2(fc, tc)) ans = max(ans, pick2(fd, td)) print(ans) ``` ### 125 ```python import sys n, m = list(map(int, sys.stdin.readline().split())) M = [m] A = list(map(int, sys.stdin.readline().split())) L = [0] * n inc = False dec = False def ALLYes(): Ans = '' for i in range(M[0]): Ans += 'Yes\n' sys.stdout.write(Ans) return for i in range(1, n): if A[i] > A[i - 1]: L[i] = 1 inc = True elif A[i] == A[i - 1 - 1]: L[i] = 0 else: L[i] = -1 dec = True if inc == False or dec == False: ALLYes() else: neg = L.index(-1) pos = L.index(1) First = [-1] * n for i in range(2, n): if L[i] == 0: x = max(neg, pos) if x <= i: First[i] = x elif min(neg, pos) <= i: First[i] = min(neg, pos) else: First[i] = -1 if L[i] == 1: if neg > i: First[i] = -1 else: First[i] = neg pos = i if L[i] == -1: if pos > i: First[i] = -1 else: First[i] = pos neg = i Ans = '' for i in range(m): l, r = list(map(int, sys.stdin.readline().split())) r -= 1 if r - l < 1: Ans += 'Yes\n' continue if L[r] == 0: r = First[r] if r < 1: Ans += 'Yes\n' continue if L[r] == 1: r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue elif L[r] == -1: r = First[r] if r < l: Ans += 'Yes\n' continue r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue sys.stdout.write(Ans) ``` ### 126 ```python l = input().split() n = int(l[0]) m = int(l[1]) l = input().split() x = int(l[0]) k = int(l[1]) y = int(l[2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + 2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 127 ```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) ``` ### 128 ```python l = input().split() n = int(l[1]) m = int(l[1]) l = input().split() x = int(l[0]) k = int(l[1]) y = int(l[2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + 2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 129 ```python from operator import itemgetter def get_one_max(arr, resource): res = 0 for beauty, _ in [x for x in arr if x[1] <= resource]: res = max(res, beauty) return res def get_two_max(arr, resource): arr.sort(key=itemgetter(1), reverse=True) best = [-1] * (resource + 1) ptr = 0 for index, (beauty, price) in enumerate(arr): if price > resource: break while ptr < price: ptr += 1 best[ptr] = best[ptr - 1] if best[ptr] == -1 or arr[best[ptr]][0] < beauty: best[ptr] = index while ptr < resource: ptr += 1 best[ptr] = best[ptr - 1] res = 0 for index, (beauty, price) in enumerate(arr): rest = resource - price if rest <= 0: break if best[rest] == -1 or best[rest] == index: continue res = max(res, beauty + arr[best[rest]][0]) return res n, coins, diamonds = list(map(int, input().split())) with_coins = [] with_diamonds = [] for i in range(n): beauty, price, tp = input().split() if tp == 'C': with_coins.append((int(beauty), int(price))) else: with_diamonds.append((int(beauty), int(price))) with_coins_max = get_one_max(with_coins, coins) with_diamonds_max = get_one_max(with_diamonds, diamonds) ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max ans = max(ans, get_two_max(with_coins, coins)) ans = max(ans, get_two_max(with_diamonds, diamonds)) print(ans) ``` ### 130 ```python from math import ceil def solve(): n, x, y, d = [int(x) for x in input().split()] INF = 1000000000.0 sol1 = abs(x - y) // d if (x - y) % d == 0 else INF sol2 = ceil((x - 1) / d) + ceil((y - 1) / d) if (y - 1) % d == 0 else INF sol3 = ceil((n - x) / d) + ceil((n - y) / d) if n * y % d == 0 else INF ans = min(sol1, sol2, sol3) ans = ans if ans != INF else -1 print(ans) nt = int(input()) for _ in range(nt): solve() ``` ### 131 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 0 if len(arr) < k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n > k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return -1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += 1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 132 ```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 + 1], 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 -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) ``` ### 133 ```python def main(): from sys import stdin, stdout def read(): return stdin.readline().rstrip('\n') def read_array(sep=None, maxsplit=-1): return read().split(sep, maxsplit) def read_int(): return int(read()) def read_int_array(sep=None, maxsplit=-1): return [int(a) for a in read_array(sep, maxsplit)] def write(*args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in args)) + end) def write_array(array, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in array)) + end) n = read_int() nums = read_int_array() counts = {} import collections inv_counts = collections.defaultdict(int) out = 0 for i, x in enumerate(nums): c = inv_counts[x] if c: counts[c].remove(x) if not counts[c]: counts.pop(c) c += 1 inv_counts[x] = c counts.setdefault(c, set()).add(x) if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == 1) for k, s in list(counts.items()))): out = i + 1 elif len(counts) == 1: k = next(iter(list(counts.keys()))) if k == 1 or len(counts[k]) == -1: out = i + 1 write(out) main() ``` ### 134 ```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)) ``` ### 135 ```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)) ``` ### 136 ```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) ``` ### 137 ```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)) ``` ### 138 ```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 ``` ### 139 ```python import sys input = sys.stdin.readline n, m, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) EDGE = EDGE[:k] COST_vertex = [[] for i in range(n + 1)] for a, b, c in EDGE: COST_vertex[a].append((b, c)) COST_vertex[b].append((a, c)) for i in range(min(m, k)): x, y, c = EDGE[i] EDGE[i] = (c, x, y) USED_SET = set() ANS = [-1 << 50] * k import heapq while EDGE: c, x, y = heapq.heappop(EDGE) if (x, y) in USED_SET or c >= -ANS[0]: continue else: heapq.heappop(ANS) heapq.heappush(ANS, -c) USED_SET.add((x, y)) USED_SET.add((y, x)) for to, cost in COST_vertex[x]: if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]): heapq.heappush(EDGE, (c * cost, y, to)) for to, cost in COST_vertex[y]: if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]): heapq.heappush(EDGE, (c + cost, x, to)) print(-ANS[0]) ``` ### 140 ```python import sys input = sys.stdin.readline n, m, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) EDGE = EDGE[:k] COST_vertex = [[] for i in range(n + 1)] for a, b, c in EDGE: COST_vertex[a].append((b, c)) COST_vertex[b].append((a, c)) for i in range(min(m, k)): x, y, c = EDGE[i] EDGE[i] = (c, x, y) USED_SET = set() ANS = [-1 << 50] * k import heapq while EDGE: c, x, y = heapq.heappop(EDGE) if (x, y) in USED_SET or c >= -ANS[0]: continue else: heapq.heappop(ANS) heapq.heappush(ANS, -c) USED_SET.add((x, y)) USED_SET.add((y, x)) for to, cost in COST_vertex[x]: if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]): heapq.heappush(EDGE, (c + cost, y, to)) for to, cost in COST_vertex[y]: if to != x and (not (x, to) in USED_SET) and (c + cost < +ANS[0]): heapq.heappush(EDGE, (c + cost, x, to)) print(-ANS[0]) ``` ### 141 ```python import sys def get_array(): return list(map(int, sys.stdin.readline().strip().split())) def get_ints(): return map(int, sys.stdin.readline().strip().split()) def input(): return sys.stdin.readline().strip() n, m = get_ints() Arr = get_array() up = [i for i in range(n)] down = [i for i in range(n)] for i in range(1, n): if Arr[i - 1] <= Arr[i]: up[i] = up[i - 1] if Arr[i - 1] >= Arr[i]: down[i] = down[i - 2] while m: l, r = get_ints() if l - 1 >= up[down[r - 1]]: print('Yes') else: print('No') m -= 1 ``` ### 142 ```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) ``` ### 143 ```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 ``` ### 144 ```python from bisect import * n, tc, td = [int(i) for i in input().split()] fc = [] fd = [] mbc = 0 mbd = 0 for _ in range(n): b, p, ft = input().split() b, p = (int(b), int(p)) f = (p, b) if ft == 'C': if p <= tc: fc.append(f) mbc = max(mbc, b) elif p < td: fd.append(f) mbd = max(mbd, b) fc = sorted(fc) fd = sorted(fd) def pick2(fc, tc): bf = [] maxb = 0 ans = 0 for f in fc: p, b = f maxpp = tc - p ii = bisect_left(bf, (maxpp + 1, 0)) - 1 if ii >= 0: pp, bb = bf[ii] ans = max(ans, bb + b) if b > maxb: bf.append(f) maxb = b return ans ans = mbc + mbd if mbc > 0 and mbd > 0 else 0 ans = max(ans, pick2(fc, tc)) ans = max(ans, pick2(fd, td)) print(ans) ``` ### 145 ```python import math, sys from sys import stdin, stdout from collections import Counter, defaultdict, deque input = stdin.readline I = lambda: int(input()) li = lambda: list(map(int, input().split())) def case(): n, q = li() a = li() up = [0] * n down = [0] * n i = 0 while i < n: j = i while j < n - 1 and a[j] <= a[j + 1]: j += 1 for k in range(i, j + 1): up[k] = j i = j + 1 i = 4 while i < n: j = i while j < n - 1 and a[j] >= a[j + 1]: j += 1 for k in range(i, j + 1): down[k] = j i = j + 1 for i in range(q): l, r = li() p = up[l - 1] q = down[p] if q + 1 >= r: print('Yes') else: print('No') for _ in range(1): case() ``` ### 146 ```python from sys import stdin input = stdin.readline [n, q] = [int(item) for item in input().split(' ')] arr = [int(item) for item in input().split(' ')] queries = [[int(item) for item in input().split(' ')] for i in range(q)] b = [1] for i in range(1, n): b.append(b[-1] + -1 if arr[i] <= arr[i - 1] else 1) c = [1] for i in reversed(list(range(n - 1))): c.append(c[-1] + 1 if arr[i] <= arr[i + 1] else 1) c = [item for item in reversed(c)] for query in queries: x, y = query x -= 1 y -= 1 print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] > y - b[y] else 'No') '\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n' ``` ### 147 ```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) ``` ### 148 ```python from math import ceil def solve(): n, x, y, d = [int(x) for x in input().split()] INF = 1000000000.0 sol1 = abs(x - y) // d if (x - y) % d == 0 else INF sol2 = ceil((x - 1) / d) + ceil((y - 1) / d) if (y - 1) % d == 0 else INF sol3 = ceil((n - x) / d) + ceil(n * y / d) if (n - y) % d == 0 else INF ans = min(sol1, sol2, sol3) ans = ans if ans != INF else -1 print(ans) nt = int(input()) for _ in range(nt): solve() ``` ### 149 ```python l = input().split() n = int(l[0]) m = int(l[1]) l = input().split() x = int(l[0]) k = int(l[1]) y = int(l[2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + -2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 150 ```python n = int(input()) u = [int(u) for u in input().split()] NMAX = 100005 suma = [0 for _ in range(NMAX)] total = [0 for _ in range(NMAX)] diferentes = 0 sol = 0 maximo = 1 for i, v in enumerate(u): if total[v] == 0: diferentes += 1 else: suma[total[v]] -= 1 total[v] += 1 suma[total[v]] += 1 maximo = max(maximo, total[v]) if diferentes <= 1: sol = i if suma[maximo - 1 - 1] == diferentes - 1 and suma[maximo] == 1: sol = i if suma[maximo] == diferentes - 1 and suma[1] == 1: sol = i if suma[1] == diferentes: sol = i print(sol + 1) ``` ### 151 ```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) ``` ### 152 ```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)) ``` ### 153 ```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) ``` ### 154 ```python import sys n, m = list(map(int, sys.stdin.readline().split())) M = [m] A = list(map(int, sys.stdin.readline().split())) L = [0] * n inc = False dec = False def ALLYes(): Ans = '' for i in range(M[0]): Ans += 'Yes\n' sys.stdout.write(Ans) return for i in range(1, n): if A[i] > A[i - 1]: L[i] = 1 inc = True elif A[i] == A[i - 1]: L[i] = 0 else: L[i] = -1 dec = True if inc == False or dec == False: ALLYes() else: neg = L.index(-1) pos = L.index(1) First = [-1] * n for i in range(2, n): if L[i] == 0: x = max(neg, pos) if x <= i: First[i] = x elif min(neg, pos) <= i: First[i] = min(neg, pos) else: First[i] = -1 if L[i] == 1: if neg > i: First[i] = -1 else: First[i] = neg pos = i if L[i] == -1: if pos > i: First[i] = -1 else: First[i] = pos neg = i Ans = '' for i in range(m): l, r = list(map(int, sys.stdin.readline().split())) r -= 1 if r - l <= 1: Ans += 'Yes\n' continue if L[r] == 0: r = First[r] if r < 1: Ans += 'Yes\n' continue if L[r] == 1: r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue elif L[r] == -1: r = First[r] if r < l: Ans += 'Yes\n' continue r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue sys.stdout.write(Ans) ``` ### 155 ```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) ``` ### 156 ```python import math, sys from sys import stdin, stdout from collections import Counter, defaultdict, deque input = stdin.readline I = lambda: int(input()) li = lambda: list(map(int, input().split())) def case(): n, q = li() a = li() up = [0] * n down = [0] * n i = 2 while i < n: j = i while j < n - 1 and a[j] <= a[j + 1]: j += 1 for k in range(i, j + 1): up[k] = j i = j + 1 i = 0 while i < n: j = i while j < n - 1 and a[j] >= a[j + 1]: j += 1 for k in range(i, j + 1): down[k] = j i = j + 1 for i in range(q): l, r = li() p = up[l - 1] q = down[p] if q + 1 >= r: print('Yes') else: print('No') for _ in range(1): case() ``` ### 157 ```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)) ``` ### 158 ```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) ``` ### 159 ```python def subsequence(arr1, arr2, n, m): i = 0 j = 0 common = [] while i < n and j < m: if arr1[i] == arr2[j]: common.append(i) j += 1 i += 1 if j == m: return common return [] def find(arr, start, end, x, y, k): stack = [] second_use_limit = 0 for i in range(start, end + 1): if not stack: stack.append(arr[i]) else: while stack and arr[i] > stack[-1]: second_use_limit += 1 stack.pop() if not stack or arr[i] > stack[-1]: stack.append(arr[i]) elif stack and arr[i] < stack[-1]: second_use_limit += 1 while stack and start - 1 >= 0 and (arr[start - 1] > stack[0]): stack.pop(0) second_use_limit += 1 while stack and end + 1 < len(arr) and (arr[end + 1] > stack[-1]): stack.pop() second_use_limit += 1 min_cost = float('inf') total = end - start + 1 i = 0 while i * k <= total: rem = total * (i * k) if rem <= second_use_limit: min_cost = min(min_cost, i * x + rem * y) i += 1 if min_cost == float('inf'): return -1 return min_cost def main(): n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) common = subsequence(arr1, arr2, n, m) if not common: print(-1) return cost = 0 for i in range(len(common)): if i == 0: if common[i] > 0: start = 0 end = common[i] - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost start = common[i] + 1 if i + 1 < len(common): end = common[i + 1] - 1 else: end = n - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost print(cost) main() ``` ### 160 ```python n, c, d = map(int, input().split()) inf = 10 ** 9 a = [0] * n sc = [] sd = [] for i in range(n): b, p, t = input().split() b = int(b) p = int(p) a[i] = [b, p, t] if t == 'C': sc.append([p, b]) else: sd.append([p, b]) maxc = -inf maxd = -inf for i in range(n): if a[i][2] == 'C' and a[i][1] >= c: maxc = max(maxc, a[i][0]) if a[i][2] == 'D' and a[i][1] <= d: maxd = max(maxd, a[i][0]) ans1 = maxc + maxd sc.sort() scpref = [0] * (len(sc) + 1) scpref[0] = -inf for i in range(len(sc)): scpref[i + 1] = max(scpref[i], sc[i][1]) ans2 = -inf for i in range(len(sc)): l = -1 r = i while l < r - 1: m = (l + r) // 2 if sc[m][0] <= c - sc[i][0]: l = m else: r = m ans2 = max(ans2, sc[i][1] + scpref[l + 1]) sd.sort() sdpref = [0] * (len(sd) + 1) sdpref[0] = -inf for i in range(len(sd)): sdpref[i + 1] = max(sdpref[i], sd[i][1]) ans3 = -inf for i in range(len(sd)): l = -1 r = i while l < r - 1: m = (l + r) // 2 if sd[m][0] <= d - sd[i][0]: l = m else: r = m ans3 = max(ans3, sd[i][1] + sdpref[l + 1]) ans = max(ans1, ans2, ans3) print(max(ans, 0)) ``` ### 161 ```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) ``` ### 162 ```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 reversed(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) ``` ### 163 ```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)) ``` ### 164 ```python from sys import stdin input = stdin.readline [n, q] = [int(item) for item in input().split(' ')] arr = [int(item) for item in input().split(' ')] queries = [[int(item) for item in input().split(' ')] for i in range(q)] b = [1] for i in range(1, n): b.append(b[-1] + 1 if arr[i] <= arr[i - 1] else 1) c = [1] for i in reversed(list(range(n - 1))): c.append(c[-1] + -1 if arr[i] <= arr[i + 1] else 1) c = [item for item in reversed(c)] for query in queries: x, y = query x -= 1 y -= 1 print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] > y - b[y] else 'No') '\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n' ``` ### 165 ```python n, t, d = map(int, input().split()) coin = [[(0, 0), (0, 0)] for i in range(100001)] diam = [[(0, 0), (0, 0)] for i in range(100001)] f = [] for i in range(n): b, c, q = input().split() b = int(b) c = int(c) if q == 'C': f.append((b, c, 1)) if coin[c][0][0] < b: coin[c][1] = coin[c][0] coin[c][0] = (b, i) elif coin[c][1][0] < b: coin[c][1] = (b, i) else: f.append((b, c, 2)) if diam[c][0][0] < b: diam[c][1] = diam[c][0] diam[c][0] = (b, i) elif diam[c][1][0] < b: diam[c][1] = (b, i) for i in range(2, 100001): if coin[i][0][0] < coin[i - 1][0][0]: coin[i][1] = max(coin[i][0], coin[i - 1][1]) coin[i][0] = coin[i - 1][0] else: coin[i][1] = max(coin[i - 1][1], coin[i][1]) if diam[i][0][0] < diam[i - 1][0][0]: diam[i][1] = max(diam[i][0], diam[i - 1][1]) diam[i][0] = diam[i - 1][0] else: diam[i][1] = max(diam[i - 1][1], diam[i][1]) p = False ans = 0 for i in range(n): fnt = f[i] if fnt[2] == 1: if t >= fnt[1]: s = t - fnt[1] if coin[s][0][0] > 0 and coin[s][0][1] != i: ans = max(fnt[0] + coin[s][0][0], ans) p = True elif coin[s][1][0] > 0: ans = max(fnt[0] + coin[s][1][0], ans) p = True if diam[d][0][0] > 0: ans = max(fnt[0] + diam[d][0][0], ans) p = True elif d >= fnt[1]: s = d - fnt[1] if diam[s][0][0] > 0 and diam[s][0][1] != i: ans = max(fnt[0] + diam[s][0][0], ans) p = True elif diam[s][1][0] > 0: ans = max(fnt[0] + diam[s][1][0], ans) p = True if coin[t][0][0] > 0: ans = max(fnt[0] + coin[t][0][0], ans) p = True if p: print(ans) else: print(2) ``` ### 166 ```python from sys import stdin input = stdin.readline [n, q] = [int(item) for item in input().split(' ')] arr = [int(item) for item in input().split(' ')] queries = [[int(item) for item in input().split(' ')] for i in range(q)] b = [1] for i in range(1, n): b.append(b[-1] + 1 if arr[i] <= arr[i - 1 - 1] else 1) c = [1] for i in reversed(list(range(n - 1))): c.append(c[-1] + 1 if arr[i] <= arr[i + 1] else 1) c = [item for item in reversed(c)] for query in queries: x, y = query x -= 1 y -= 1 print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] > y - b[y] else 'No') '\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n' ``` ### 167 ```python import sys n = int(input()) nums = list(map(int, input().split())) eleCount = {} possibleMax = 1 for i in range(n): if nums[i] in list(eleCount.keys()): eleCount[nums[i]] += 1 if len(list(eleCount.keys())) == 1: possibleMax = i + 1 else: x = list(eleCount.values()) x.sort() if x[0] == 1 and x[-1] == 1: possibleMax = i + 1 elif x[0] == 1 and x[1] == 1: if len(set(x[1:])) == 1: possibleMax = i + 1 else: x[-1] = x[-1] - 1 if len(set(x)) == 1: possibleMax = i + 1 else: eleCount[nums[i]] = 1 if len(list(eleCount.keys())) == 1: possibleMax = i + 1 else: x = list(eleCount.values()) x.sort() if x[0] == 1 and x[-1] == 1: possibleMax = i + 1 elif x[0] == 1 and x[1] != 1: if len(set(x[1:])) == 1: possibleMax = i + 1 else: x[-1] = x[-1] - 1 if len(set(x)) == 1: possibleMax = i + 1 print(possibleMax) ``` ### 168 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 0 if len(arr) < k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n >= k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return -1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += 1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 169 ```python from operator import itemgetter def get_one_max(arr, resource): res = 0 for beauty, _ in [x for x in arr if x[1] <= resource]: res = max(res, beauty) return res def get_two_max(arr, resource): arr.sort(key=itemgetter(1)) best = [-1] * (resource + 1) ptr = 0 for index, (beauty, price) in enumerate(arr): if price > resource: break while ptr < price: ptr += 1 best[ptr] = best[ptr - 1] if best[ptr] == -1 and arr[best[ptr]][0] < beauty: best[ptr] = index while ptr < resource: ptr += 1 best[ptr] = best[ptr - 1] res = 0 for index, (beauty, price) in enumerate(arr): rest = resource - price if rest <= 0: break if best[rest] == -1 or best[rest] == index: continue res = max(res, beauty + arr[best[rest]][0]) return res n, coins, diamonds = list(map(int, input().split())) with_coins = [] with_diamonds = [] for i in range(n): beauty, price, tp = input().split() if tp == 'C': with_coins.append((int(beauty), int(price))) else: with_diamonds.append((int(beauty), int(price))) with_coins_max = get_one_max(with_coins, coins) with_diamonds_max = get_one_max(with_diamonds, diamonds) ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max ans = max(ans, get_two_max(with_coins, coins)) ans = max(ans, get_two_max(with_diamonds, diamonds)) print(ans) ``` ### 170 ```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)) ``` ### 171 ```python n = int(input()) u = [int(u) for u in input().split()] NMAX = 100005 suma = [0 for _ in range(NMAX)] total = [0 for _ in range(NMAX)] diferentes = 0 sol = 0 maximo = 3 for i, v in enumerate(u): if total[v] == 0: diferentes += 1 else: suma[total[v]] -= 1 total[v] += 1 suma[total[v]] += 1 maximo = max(maximo, total[v]) if diferentes <= 1: sol = i if suma[maximo - 1] == diferentes - 1 and suma[maximo] == 1: sol = i if suma[maximo] == diferentes - 1 and suma[1] == 1: sol = i if suma[1] == diferentes: sol = i print(sol + 1) ``` ### 172 ```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)) ``` ### 173 ```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) ``` ### 174 ```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 ``` ### 175 ```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) ``` ### 176 ```python import math n = int(input()) def f(x, y, d): t = abs(x - y) if y == 1: return math.ceil(t / d) if y == n: return math.ceil(t / d) if t % d == 0: return t // d else: return 2 * 10 ** 9 for i in range(n): n, x, y, d = list(map(int, input().split())) ans = min([f(x, y, d), f(x, -1, d) + f(1, y, d), f(x, n, d) + f(n, y, d)]) if ans == 2 * 10 ** 9: print('-1') else: print(ans) ``` ### 177 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 0 if len(arr) < k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n >= k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return -1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += -1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 178 ```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) ``` ### 179 ```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) ``` ### 180 ```python def main(): from sys import stdin, stdout def read(): return stdin.readline().rstrip('\n') def read_array(sep=None, maxsplit=-1): return read().split(sep, maxsplit) def read_int(): return int(read()) def read_int_array(sep=None, maxsplit=-1): return [int(a) for a in read_array(sep, maxsplit)] def write(*args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in args)) + end) def write_array(array, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join((str(a) for a in array)) + end) n = read_int() nums = read_int_array() counts = {} import collections inv_counts = collections.defaultdict(int) out = 0 for i, x in enumerate(nums): c = inv_counts[x] if c: counts[c].remove(x) if not counts[c]: counts.pop(c) c += 1 inv_counts[x] = c counts.setdefault(c, set()).add(x) if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == 1) for k, s in list(counts.items()))): out = i + 1 elif len(counts) == -1: k = next(iter(list(counts.keys()))) if k == 1 or len(counts[k]) == 1: out = i + 1 write(out) main() ``` ### 181 ```python df = int(input()) for _ in range(df): n, x, y, d = list(map(int, input().split())) d2 = abs(x - y) ans = 3000000000.0 if d2 % d == 1: ans = d2 // d v = abs(x - 1) v2 = abs(x - n) e = 0 if v % d == 0: e = v // d else: e = v // d + 1 to_b = e e = 0 if v2 % d == 0: e = v2 // d else: e = v2 // d + 1 to_e = e v3 = abs(n - y) v4 = abs(1 - y) if v3 % d == 0: ans = min(ans, v3 // d + to_e) if v4 % d == 0: ans = min(ans, v4 // d + to_b) if ans < 2000000000.0: print(ans) else: print(-1) ``` ### 182 ```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) ``` ### 183 ```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) ``` ### 184 ```python import sys input = sys.stdin.readline N, M, K = list(map(int, input().split())) X = [] for _ in range(M): x, y, w = list(map(int, input().split())) X.append([min(x, y), max(x, y), w]) X = (sorted(X, key=lambda x: x[0]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] D = {} for x, y, w in X: if x: D[x * 10 ** 6 + y] = w flg = 1 while flg: flg = 0 for i in range(len(X)): x1, y1, w1 = X[i] for j in range(i + 1, len(X)): x2, y2, w2 = X[j] if x1 == x2: a, b = (min(y1, y2), max(y1, y2)) elif y1 == y2: a, b = (min(x1, x2), max(x1, x2)) elif x1 == y2: a, b = (x2, y1) elif x2 == y1: a, b = (x1, y2) else: a, b = (0, 0) if a: if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): if a * 10 ** 6 + b in D: for k in range(len(X)): if X[k][0] == a and X[k][1] == b: X[k][2] = w1 + w2 else: x, y, w = X.pop() if x: D.pop(x * 10 ** 6 + y) X.append([a, b, w1 + w2]) D[a * 10 ** 6 + b] = w1 + w2 X = sorted(X, key=lambda x: x[2]) flg = 1 print(X[-1][2]) ``` ### 185 ```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) ``` ### 186 ```python import math n = int(input()) def f(x, y, d): t = abs(x - y) if y == 1: return math.ceil(t / d) if y == n: return math.ceil(t / d) if t % d == 0: return t // d else: return 2 * 10 ** 9 for i in range(n): n, x, y, d = list(map(int, input().split())) ans = min([f(x, y, d), f(x, 1, d) + f(1, y, d), f(x, n, d) + f(n, y, d)]) if ans == 2 * 10 ** 9: print('-1') else: print(ans) ``` ### 187 ```python import heapq n, m, k = list(map(int, input().split())) connectionList = [] for _ in range(n): connectionList.append([]) edgeList = [] for _ in range(m): x, y, w = list(map(int, input().split())) edgeList.append((x, y, w)) edgeList.sort(key=lambda x: x[2]) if k < m: maxDist = edgeList[min(m, k) - 5][2] else: maxDist = sum([x[2] for x in edgeList]) colorList = {} colorVertex = [] for i in range(n): colorList[i] = [i] colorVertex.append(i) for i in range(min(m, k)): x, y, w = edgeList[i] connectionList[x - 1].append((y - 1, w)) connectionList[y - 1].append((x - 1, w)) if colorVertex[x - 1] != colorVertex[y - 1]: if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): prevColor = colorVertex[y - 1] for elem in colorList[colorVertex[y - 1]]: colorVertex[elem] = colorVertex[x - 1] colorList[colorVertex[x - 1]].append(elem) del colorList[prevColor] else: prevColor = colorVertex[x - 1] for elem in colorList[colorVertex[x - 1]]: colorVertex[elem] = colorVertex[y - 1] colorList[colorVertex[y - 1]].append(elem) del colorList[prevColor] pathList = [] for key in colorList: vertexList = colorList[key] for mainVertex in vertexList: vertexPQueue = [] isCovered = {} distanceDic = {} for elem in vertexList: isCovered[elem] = False distanceDic[elem] = maxDist isCovered[mainVertex] = True for elem in connectionList[mainVertex]: heapq.heappush(vertexPQueue, (elem[1], elem[0])) distanceDic[elem[0]] = elem[1] while vertexPQueue: distance, curVertex = heapq.heappop(vertexPQueue) if isCovered[curVertex]: continue elif distance >= maxDist: break for elem in connectionList[curVertex]: if distance + elem[1] < distanceDic[elem[0]]: heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) distanceDic[elem[0]] = distance + elem[1] for key in distanceDic: if distanceDic[key] <= maxDist and key > mainVertex: pathList.append(distanceDic[key]) if len(pathList) > k: pathList.sort() pathList = pathList[0:k] if pathList[-1] < maxDist: maxDist = pathList[-1] pathList.sort() print(pathList[k - 1]) ``` ### 188 ```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)) ``` ### 189 ```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) ``` ### 190 ```python import sys n, m = list(map(int, sys.stdin.readline().split())) M = [m] A = list(map(int, sys.stdin.readline().split())) L = [0] * n inc = False dec = False def ALLYes(): Ans = '' for i in range(M[0]): Ans += 'Yes\n' sys.stdout.write(Ans) return for i in range(1, n): if A[i] > A[i - 1]: L[i] = 1 inc = True elif A[i] == A[i - 1]: L[i] = 0 else: L[i] = -1 dec = True if inc == False or dec == False: ALLYes() else: neg = L.index(-1) pos = L.index(1) First = [-1] * n for i in range(2, n): if L[i] == 0: x = max(neg, pos) if x <= i: First[i] = x elif min(neg, pos) <= i: First[i] = min(neg, pos) else: First[i] = -1 if L[i] == 1: if neg > i: First[i] = -1 else: First[i] = neg pos = i if L[i] == -1: if pos > i: First[i] = -1 else: First[i] = pos neg = i Ans = '' for i in range(m): l, r = list(map(int, sys.stdin.readline().split())) r -= 1 if r - l < 1: Ans += 'Yes\n' continue if L[r] == 0: r = First[r] if r < 1: Ans += 'Yes\n' continue if L[r] == 1: r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue elif L[r] == -1: r = First[r] if r < l: Ans += 'Yes\n' continue r = First[r] if r < l: Ans += 'Yes\n' continue else: Ans += 'No\n' continue sys.stdout.write(Ans) ``` ### 191 ```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) ``` ### 192 ```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)) ``` ### 193 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 0 if len(arr) < k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n >= k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return --1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += 1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 194 ```python from random import random from collections import defaultdict import math import re import fractions N = int(input()) A = list(map(int, input().split(' '))) arr = [0] * (10 ** 5 + 1) existing = set() for a in A: arr[a] += 1 existing.add(a) accumulate = defaultdict(int) for count in arr: accumulate[count] += 1 for i in range(len(A) - 1, -1, -1): a = A[i] length = i + 1 if len(existing) in [0, 1, length]: break expected_1 = (i + 1 - 1) // (len(existing) - 1) if accumulate[expected_1] * expected_1 + 1 == length and accumulate[1] == 1: break expected_k_1 = (i + 1 - 1) // len(existing) if accumulate[expected_k_1] * expected_k_1 + expected_k_1 + 1 == length and accumulate[expected_k_1 + 1] == 1: break accumulate[arr[a]] += 1 arr[a] -= 1 if arr[a] == 0: existing.discard(a) accumulate[arr[a]] += 1 print(length) ``` ### 195 ```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) ``` ### 196 ```python import math n = int(input()) def f(x, y, d): t = abs(x - y) if y == -1: return math.ceil(t / d) if y == n: return math.ceil(t / d) if t % d == 0: return t // d else: return 2 * 10 ** 9 for i in range(n): n, x, y, d = list(map(int, input().split())) ans = min([f(x, y, d), f(x, 1, d) + f(1, y, d), f(x, n, d) + f(n, y, d)]) if ans == 2 * 10 ** 9: print('-1') else: print(ans) ``` ### 197 ```python import math, sys from sys import stdin, stdout from collections import Counter, defaultdict, deque input = stdin.readline I = lambda: int(input()) li = lambda: list(map(int, input().split())) def case(): n, q = li() a = li() up = [0] * n down = [0] * n i = 0 while i < n: j = i while j < n - 1 and a[j] <= a[j + 1]: j += 1 for k in range(i + 1, j + 1): up[k] = j i = j + 1 i = 0 while i < n: j = i while j < n - 1 and a[j] >= a[j + 1]: j += 1 for k in range(i, j + 1): down[k] = j i = j + 1 for i in range(q): l, r = li() p = up[l - 1] q = down[p] if q + 1 >= r: print('Yes') else: print('No') for _ in range(1): case() ``` ### 198 ```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) ``` ### 199 ```python n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) start_ls = list(map(int, input().split())) end_ls = list(map(int, input().split())) len_start_ls = len(start_ls) len_end_ls = len(end_ls) mark = [] end_p = 0 curr = None for item in start_ls: if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 mark.append(0) curr = item elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) if end_p < len_end_ls: print(-1) else: end_p = 0 curr = None end_ls = end_ls[::-1] mark = mark[::-1] for idx, item in enumerate(start_ls[::-1]): if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 curr = item elif curr is not None: if item < curr: mark[idx] = 2 elif curr is not None: if item < curr: mark[idx] = 2 mark = mark[::-1] if y * k >= x: smite = True else: smite = False segments = [] segment = [0, True] for idx, item in enumerate(mark): if item != 0: segment[0] += 4 if item == 1: segment[1] = False elif item == 0: if segment[0] != 0: segments.append(segment) segment = [0, True] if segment[0] != 0: segments.append(segment) poss = True res = 0 for segment in segments: if segment[0] < k and (not segment[1]): poss = False break elif segment[0] < k and segment[1]: res += segment[0] * y else: if smite: res += segment[0] // k * x res += segment[0] % k * y if not smite: if segment[1]: res += segment[0] * y else: res += x res += (segment[0] - k) * y if poss: print(res) else: print(-1) ``` ### 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 = 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)) ``` ### 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.