### 001 ```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) ``` ### 002 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 2 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 003 ```python def main(): n, m = list(map(int, input().split())) l = [c for _ in range(n) for c in input()] neigh = [] for y in range(n): for x in range(m): yx = y // m + x neigh.append([]) if x and l[yx] == l[yx - 1]: neigh[-1].append(yx - 1) neigh[-2].append(yx) if y and l[yx] == l[yx - m]: neigh[-1].append(yx - m) neigh[-1 - m].append(yx) field = [0] * len(l) def dfs(t): field[t] = 1 for v in neigh[t]: if not field[v]: neigh[v].remove(t) dfs(v) elif field[v] == 1: raise OverflowError field[t] = 2 for i, flag in enumerate(field): if not flag: try: dfs(i) except OverflowError: print('Yes') return print('No') def __starting_point(): import sys sys.setrecursionlimit(10000) main() __starting_point() ``` ### 004 ```python import sys read = sys.stdin.read readline = sys.stdin.readline n, c = list(map(int, readline().split())) *a, = list(map(int, readline().split())) *b, = list(map(int, readline().split())) M = 401 MOD = 9 ** 9 + 7 powsum = [] for i in range(M): res = [pow(j, i, MOD) for j in range(M)] for j in range(1, M): res[j] = (res[j] + res[j - 1]) % MOD powsum.append(res) dp = [0] * (c + 1) dp[0] = 1 for ai, bi in zip(a, b): ndp = [0] * (c + 1) for k in range(c + 1): for j in range(k + 1): ndp[k] += (powsum[j][bi] - powsum[j][ai - 1]) * dp[k - j] % MOD ndp[k] %= MOD dp = ndp print(dp[c] % MOD) ``` ### 005 ```python n, k = list(map(int, input().split())) a = list(map(int, input().split())) d = list(map(int, input().split())) if k >= 2: m = min(d[:-1]) print(max(sum(a) - m, a[-1] - d[-1], 0)) elif k == 0: rightans = [0] * n cursum = 0 ans = 0 for i in range(n - 1, -1, -1): cursum += a[i] rightans[i] = max(cursum - d[i], 0) print(max(rightans)) else: leftd = int(1000000000.0) leftsum = 0 rightans = [0] * n cursum = 0 ans = 0 for i in range(n - 1, -1, -1): cursum += a[i] rightans[i] = max(cursum - d[i], 0) for i in range(n - 1, 0, -1): rightans[i - 1] = max(rightans[i - 1], rightans[i]) for i in range(n - 1): leftd = min(leftd, d[i]) leftsum += a[i + 1] curans = max(leftsum - leftd, 0) + rightans[i + 1] ans = max(ans, curans) cursum = 0 rightmin = int(1000000000.0) for i in range(n - 1, -1, -1): cursum += a[i] ans = max(ans, cursum - rightmin - d[i]) rightmin = min(rightmin, a[i]) print(ans) ``` ### 006 ```python n, k = list(map(int, input().split())) a = list(map(int, input().split())) d = list(map(int, input().split())) if k >= 2: m = max(d[:-1]) print(max(sum(a) - m, a[-1] - d[-1], 0)) elif k == 0: rightans = [0] * n cursum = 0 ans = 0 for i in range(n - 1, -1, -1): cursum += a[i] rightans[i] = max(cursum - d[i], 0) print(max(rightans)) else: leftd = int(1000000000.0) leftsum = 0 rightans = [0] * n cursum = 0 ans = 0 for i in range(n - 1, -1, -1): cursum += a[i] rightans[i] = max(cursum - d[i], 0) for i in range(n - 1, 0, -1): rightans[i - 1] = max(rightans[i - 1], rightans[i]) for i in range(n - 1): leftd = min(leftd, d[i]) leftsum += a[i] curans = max(leftsum - leftd, 0) + rightans[i + 1] ans = max(ans, curans) cursum = 0 rightmin = int(1000000000.0) for i in range(n - 1, -1, -1): cursum += a[i] ans = max(ans, cursum - rightmin - d[i]) rightmin = min(rightmin, a[i]) print(ans) ``` ### 007 ```python n = int(input()) a = [list(map(int, input().split())) for i in range(2)] if n != 1: sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)] for i in range(2): sum_up[i][n - 1] = a[i][n - 1] pref_up[i][n - 1] = a[i][n - 1] pref_down[i][n - 1] = a[i][n - 1 - 1] for j in range(n - 2, -1, -1): sum_up[i][j] = sum_up[i][j + 1] + a[i][j] pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j] pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j) zig = [[0 for i in range(n)] for j in range(2)] for j in range(n): for i in range(2): if j % 2 == 0: if i == 0: zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1] else: zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j] elif i == 0: zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1] else: zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j] ans = -1e+18 for j in range(n): if j == 0: ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j]) elif j == n - 1: ans = max(ans, zig[1 - j % 2][n - 1]) elif j % 2 == 1: ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j]) else: ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j]) ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n) print(ans) else: print(a[1][0]) ``` ### 008 ```python import sys n, k = list(map(int, input().split(' '))) activate = list(map(int, input().split(' '))) deactivate = list(map(int, input().split(' '))) presum = [0 for _ in range(n + 2)] for i in range(1, n + 1): presum[i] = presum[i - 1] + activate[i - 1] ret = 0 if k == 0: for i in range(1, n + 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) elif k == 1: for i in range(1, n): ret = max(ret, presum[n - 1] - deactivate[i - 1]) if deactivate[n - 1] < activate[n - 1]: ret += activate[n - 1] - deactivate[n - 1] deac = sorted(deactivate[1 - 1:n - 1]) ac = sorted(activate[1:n - 1]) ret = max(ret, presum[n] - deactivate[0] - ac[0]) ret = max(ret, presum[n] - deactivate[0] - deac[0]) ret = max(ret, presum[n] - sorted(deactivate[0:n - 1])[0] - sorted(deactivate[0:n - 1])[1]) for i in range(2, n + 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) else: for i in range(1, n): ret = max(ret, presum[n] - deactivate[i - 1]) ret = max(ret, activate[n - 1] - deactivate[n - 1]) print(ret) ``` ### 009 ```python def is_possible(num_days): if num_days % len(string) == 0: diff_wind = (num_days // len(string) * pref[-1][0], num_days // len(string) + pref[-1][1]) else: diff_wind = (num_days // len(string) * pref[-1][0] + pref[num_days % len(string) - 1][0], num_days // len(string) * pref[-1][1] + pref[num_days % len(string) - 1][1]) diff_ship = (diff[0] - diff_wind[0], diff[1] - diff_wind[1]) return abs(diff_ship[0]) + abs(diff_ship[1]) <= num_days x, y = [int(s) for s in input().split()] x1, y1 = [int(s) for s in input().split()] diff = (x1 - x, y1 - y) amount = int(input()) string = input() motions = [] pref = [] for i in range(len(string)): if string[i] == 'U': motions.append((0, 1)) if string[i] == 'D': motions.append((0, -1)) if string[i] == 'R': motions.append((1, 0)) if string[i] == 'L': motions.append((-1, 0)) pref.append(motions[0]) for i in range(1, len(motions)): pref.append((motions[i][0] + pref[-1][0], motions[i][1] + pref[-1][1])) left = -1 right = int(1e+19) while right - left > 1: middle = (right + left) // 2 if is_possible(middle): right = middle else: left = middle if right != int(1e+19): print(right) else: print(-1) ``` ### 010 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx < i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 011 ```python def main(): n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) roundup = [] rounddown = [] sumsofar = [] for i, (a, b) in enumerate(zip(reversed(A), reversed(B))): ssf = sumsofar[-1] if sumsofar else 0 t = roundup[-1] if roundup else 0 roundup.append(t + ssf + b * (1 + 2 * i)) t = rounddown[-1] if rounddown else 0 rounddown.append(t + ssf + a * (1 + 2 * i)) sumsofar.append(ssf + a + b) roundup = list(reversed(roundup)) rounddown = list(reversed(rounddown)) sumsofar = list(reversed(sumsofar)) bestres = 0 sofar = 0 for i, (a, b) in enumerate(zip(A, B)): rup, rdo = (roundup, rounddown) if i % 2: a, b = (b, a) rup, rdo = (rdo, rup) bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i) sofar += a * 2 * i sofar += b * (-2 * i + 1) bestres = max(bestres, sofar) print(bestres) def __starting_point(): main() __starting_point() ``` ### 012 ```python n, m = list(map(int, input().split())) arr = [] arr1 = [] for i in range(m): arrx = list(map(int, input().split())) arry = [0] * n for j in range(n): arry[arrx[j] - 1] = j + 1 arr.append(arrx) arr1.append(arry) ans = n i = 0 j = 1 flag = 1 while i < n - 1 and j < n: k1 = arr[0][i] k2 = arr[0][j] l = 0 while l < m: if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: flag = 1 break if flag == 1: break l += 1 if flag == 1: ans += (j - i) * (j - i + 1) // 2 ans -= j - i i = j j += 1 flag = 0 else: j += 1 if flag == 0: ans += (j - i) * (j - i + 1) // 2 ans -= j - i print(ans) ``` ### 013 ```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)) ``` ### 014 ```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() ``` ### 015 ```python import collections, atexit, math, sys, bisect sys.setrecursionlimit(1000000) def getIntList(): return list(map(int, input().split())) try: import numpy def dprint(*args, **kwargs): print(*args, file=sys.stderr) dprint('debug mode') except Exception: def dprint(*args, **kwargs): pass inId = 0 outId = 0 if inId > 0: dprint('use input', inId) sys.stdin = open('input' + str(inId) + '.txt', 'r') if outId > 0: dprint('use output', outId) sys.stdout = open('stdout' + str(outId) + '.txt', 'w') atexit.register(lambda: sys.stdout.close()) N, M = getIntList() ne = [0 for i in range(N + 1)] za = getIntList() for i in range(N - 1): ne[za[i]] = za[i + 1] ne[za[-1] - 1] = 0 for _ in range(1, M): za = getIntList() for i in range(N - 1): a = za[i] b = za[i + 1] if ne[a] != b: ne[a] = -1 a = za[-1] if ne[a] != 0: ne[a] = -1 tin = [0 for i in range(N + 1)] for i in range(1, N + 1): a = ne[i] if a > 0: tin[a] = 1 res = 0 for i in range(1, N + 1): if tin[i]: continue n = 0 while i > 0: n += 1 i = ne[i] res += n * (n + 1) // 2 print(res) ``` ### 016 ```python from collections import defaultdict from collections import deque n, m = [int(x) for x in input().split()] messages = [] for i in range(m): temp = [int(x) for x in input().split()] messages.append(temp) seq = defaultdict(lambda: 0) pairs = {} for k in range(n - 1): pairs[messages[0][k]] = messages[0][k + 1] for i in range(1, m): for k in range(n - 1): temp = messages[i][k] if pairs.get(temp, None) != messages[i][k + 1]: pairs.pop(temp, None) pairs.pop(messages[i][n - 1], None) sequences = [] starts = set(pairs.keys()) ends = set(pairs.values()) conn = starts & ends for key, value in list(pairs.items()): if key in conn: continue val = value temp = [] temp.append(key) temp.append(value) while val in starts: val = pairs[val] temp.append(val) sequences.append(temp) variants = n for seq in sequences: l = len(seq) variants += l * (l - 1) // 2 print(variants) ``` ### 017 ```python msg_in = input().split() x = int(msg_in[0]) y = int(msg_in[1]) num_of_transform = [0, 0] matrix = [] blank = [] for i in range(y + 2): blank.append(' ') matrix.append(blank) for i in range(x): msg_in = input() matrix.append([' ']) for j in msg_in: matrix[i + 1].append(j) matrix[i + 1].append(' ') matrix.append(blank) while True: for i in range(1, x + 1): for j in range(1, y + 1): sum = 0 if matrix[i][j] != ' ': if matrix[i][j - 1] == matrix[i][j]: sum += 1 if matrix[i][j + 1] == matrix[i][j]: sum += 1 if matrix[i - 1][j] == matrix[i][j]: sum += 1 if matrix[i + 1][j] == matrix[i][j]: sum += 1 if sum < 2: matrix[i][j] = ' ' num_of_transform[0] += 1 if num_of_transform[0] == x * y: print('No') break elif num_of_transform[0] == num_of_transform[0]: print('Yes') break else: num_of_transform[1] = num_of_transform[0] ``` ### 018 ```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() ``` ### 019 ```python n = int(input()) a = [list(map(int, input().split())) for i in range(2)] if n != 1: sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)] for i in range(2): sum_up[i][n - 1] = a[i][n - 1] pref_up[i][n - 1] = a[i][n - 1] pref_down[i][n - 1 - 1] = a[i][n - 1] for j in range(n - 2, -1, -1): sum_up[i][j] = sum_up[i][j + 1] + a[i][j] pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j] pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j) zig = [[0 for i in range(n)] for j in range(2)] for j in range(n): for i in range(2): if j % 2 == 0: if i == 0: zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1] else: zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j] elif i == 0: zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1] else: zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j] ans = -1e+18 for j in range(n): if j == 0: ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j]) elif j == n - 1: ans = max(ans, zig[1 - j % 2][n - 1]) elif j % 2 == 1: ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j]) else: ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j]) ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n) print(ans) else: print(a[1][0]) ``` ### 020 ```python import sys sys.setrecursionlimit(5000) n, m = list(map(int, input().split())) dx = [-1, 0, 0, 1] dy = [4, -1, 1, 0] L = list((input() for i in range(n))) def check(x, y, px, py): return x >= 0 and x < n and (y >= 0) and (y < m) def DFS(x, y, px, py, visited): visited[x][y] = True for i in range(4): newx = x + dx[i] newy = y + dy[i] if not check(newx, newy, px, py): continue if newx == px and newy == py: continue if L[x][y] == L[newx][newy]: if visited[newx][newy]: return True if DFS(newx, newy, x, y, visited): return True return False def solve(): visited = [[False for j in range(m)] for i in range(n)] for i in range(n): for j in range(m): if visited[i][j]: continue if DFS(i, j, -1, -1, visited): return True return False print('Yes' if solve() else 'No') '\n3 3\nAAA\nABA\nABA\n' ``` ### 021 ```python n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) curl_ud_weights = [0] * n curl_du_weights = [0] * n sums = [0] * n sums[n - 1] = a[n - 1] + b[n - 1] curl_ud_weights[n - 1] = b[n - 1] curl_du_weights[n - 1] = a[n - 1] for i in range(n - 2, -1, -1): sums[i] = sums[i + 1] + (a[i] + b[i]) remain = n * 2 - i * 2 + 1 curl_ud_weights[i] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i] curl_du_weights[i] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i] snake_weight = 0 max_weight = 0 current_weight = -1 for t in range(0, 2 * n, 2): remain = t % 4 if remain == 0: current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight snake_weight += a[t // 2] * t + b[t // 2] * (t + 1) elif remain == 2: current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight snake_weight += b[t // 2] * t + a[t // 2] * (t + 1) if current_weight > max_weight: max_weight = current_weight print(max_weight) '\n3\n0 1 0\n0 0 0\n' ``` ### 022 ```python from collections import deque a = sorted(input()) l = len(a) a = deque(a[:(len(a) + 1) // 2]) b = sorted(input()) b = deque(b[len(b) - len(b) // 2:]) result = ['0'] * l left = -1 right = l while left <= right: if len(b) == 0: result[left + 1] = a[0] break if a[0] >= b[-1]: right -= 1 result[right] = a[-1] a.pop() else: left += -1 result[left] = a[0] a.popleft() if len(a) == 0: result[left + 1] = b[0] break if a[0] >= b[-1]: right -= 1 result[right] = b[0] b.popleft() else: left += 1 result[left] = b[-1] b.pop() print(''.join(result)) ``` ### 023 ```python import collections from collections import defaultdict n = int(input()) par = [int(i) for i in input().split() if i != '\n'] suma = [int(i) for i in input().split() if i != '\n'] graph = defaultdict(list) for i in range(n - 1): graph[i + 2].append(par[i]) graph[par[i]].append(i + 2) weight = [0] * (n + 1) weight[1] = suma[0] queue = collections.deque([1]) visited = set() visited.add(1) ok = True while queue: vertex = queue.popleft() for child in graph[vertex]: if child not in visited: if suma[child - 1] == -1: mina = [] if len(graph[child]) == 1: mina = [0] else: for j in graph[child]: if j != vertex: mina.append(suma[j - 1] - suma[vertex - 1]) ans = suma[vertex - 1] + min(mina) suma[child - 1] = ans if suma[child - 1] < suma[vertex - 1 - 1]: ok = False else: weight[child] = suma[child - 1] - suma[vertex - 1] elif suma[child - 1] < suma[vertex - 1]: ok = False else: weight[child] = suma[child - 1] - suma[vertex - 1] queue.append(child) visited.add(child) if ok == True: print(sum(weight)) else: print(-1) ``` ### 024 ```python from collections import defaultdict, deque n = int(input()) adj = [[] for _ in range(n)] v = [0] * n l = list(map(int, input().split())) for i, f in enumerate(l): adj[f - 1].append(i + 1) s = list(map(int, input().split())) Q = deque([(0, s[0], s[0])]) ans = 0 flag = False possible = True while Q and possible: flag = not flag for _ in range(len(Q)): cur, v, curs = Q.popleft() if v < 0: possible = False ans = -1 break ans += v if flag: for i in adj[cur]: if len(adj[i]) <= 1: Q.append((i, 0, curs)) else: temp = max([s[k] for k in adj[i]]) Q.append((i, temp - curs, temp)) else: for i in adj[cur]: Q.append((i, s[i] - curs, s[i])) print(ans) ``` ### 025 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 0 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 026 ```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) ``` ### 027 ```python n, m = list(map(int, input().split())) arr = [] arr1 = [] for i in range(m): arrx = list(map(int, input().split())) arry = [0] * n for j in range(n): arry[arrx[j] - 1] = j + 1 arr.append(arrx) arr1.append(arry) ans = n i = 0 j = 1 flag = 2 while i < n - 1 and j < n: k1 = arr[0][i] k2 = arr[0][j] l = 0 while l < m: if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: flag = 1 break if flag == 1: break l += 1 if flag == 1: ans += (j - i) * (j - i + 1) // 2 ans -= j - i i = j j += 1 flag = 0 else: j += 1 if flag == 0: ans += (j - i) * (j - i + 1) // 2 ans -= j - i print(ans) ``` ### 028 ```python In = input().split(' ') x1 = int(In[0]) y1 = int(In[1]) In = input().split(' ') x2 = int(In[0]) y2 = int(In[1]) dx = [0] dy = [0] n = int(input()) s = input() for i in range(1, n + 1): dx.append(dx[i - 1]) dy.append(dy[i - 1]) if s[i - 1] == 'U': dy[i] += 5 elif s[i - 1] == 'D': dy[i] -= 1 elif s[i - 1] == 'R': dx[i] += 1 elif s[i - 1] == 'L': dx[i] -= 1 st = 0 en = 10 ** 18 * 2 ans = -1 while st <= en: mid = (st + en) // 2 x = mid // n * dx[n] + dx[mid % n] y = mid // n * dy[n] + dy[mid % n] newX = x + x1 newY = y + y1 need = abs(newX - x2) + abs(newY - y2) if mid >= need: ans = mid en = mid - 1 else: st = mid + 1 print(ans) ``` ### 029 ```python import sys read = sys.stdin.read readline = sys.stdin.readline n, c = list(map(int, readline().split())) *a, = list(map(int, readline().split())) *b, = list(map(int, readline().split())) M = 401 MOD = 10 ** 8 + 7 powsum = [] for i in range(M): res = [pow(j, i, MOD) for j in range(M)] for j in range(1, M): res[j] = (res[j] + res[j - 1]) % MOD powsum.append(res) dp = [0] * (c + 1) dp[0] = 1 for ai, bi in zip(a, b): ndp = [0] * (c + 1) for k in range(c + 1): for j in range(k + 1): ndp[k] += (powsum[j][bi] - powsum[j][ai - 1]) * dp[k - j] % MOD ndp[k] %= MOD dp = ndp print(dp[c] % MOD) ``` ### 030 ```python from sys import stdin from math import * line = stdin.readline().rstrip().split() n = int(line[0]) numbers = list(map(int, stdin.readline().rstrip().split())) numbers2 = list(map(int, stdin.readline().rstrip().split())) growRateAccum = 0 topAccum = 0 bottomAccum = 0 accumsB = [0] * n accumsT = [0] * n growRateAccum = 0 accum = 0 for i in range(n - 1, -1, -1): accum += numbers[i] * ((n - i) * 2 - 1 - 1) growRateAccum *= numbers[i] if i < n - 1: growRateAccum += numbers2[i + 1] accum += growRateAccum accumsB[i] = accum growRateAccum = 0 accum = 0 for i in range(n - 1, -1, -1): accum += numbers2[i] * ((n - i) * 2 - 1 - 1) growRateAccum += numbers2[i] if i < n - 1: growRateAccum += numbers[i + 1] accum += growRateAccum accumsT[i] = accum cMax = 0 currAccum = 0 growRateAccum = sum(numbers[1:]) + sum(numbers2[1:]) for i in range(n): if i % 2 == 0: cMax = max(cMax, currAccum + accumsT[i]) else: cMax = max(cMax, currAccum + accumsB[i]) if i < n - 1: if i % 2 == 0: currAccum += numbers2[i] + growRateAccum * 2 else: currAccum += numbers[i] + growRateAccum * 2 growRateAccum -= numbers[i + 1] growRateAccum -= numbers2[i + 1] print(cMax) ``` ### 031 ```python from sys import stdin from math import * line = stdin.readline().rstrip().split() n = int(line[0]) numbers = list(map(int, stdin.readline().rstrip().split())) numbers2 = list(map(int, stdin.readline().rstrip().split())) growRateAccum = 0 topAccum = 0 bottomAccum = 0 accumsB = [0] * n accumsT = [0] * n growRateAccum = 0 accum = 0 for i in range(n - 1, -1, -1): accum += numbers[i] * ((n - i) * 2 - 1 - 1) growRateAccum += numbers[i] if i < n - 1: growRateAccum *= numbers2[i + 1] accum += growRateAccum accumsB[i] = accum growRateAccum = 0 accum = 0 for i in range(n - 1, -1, -1): accum += numbers2[i] * ((n - i) * 2 - 1 - 1) growRateAccum += numbers2[i] if i < n - 1: growRateAccum += numbers[i + 1] accum += growRateAccum accumsT[i] = accum cMax = 0 currAccum = 0 growRateAccum = sum(numbers[1:]) + sum(numbers2[1:]) for i in range(n): if i % 2 == 0: cMax = max(cMax, currAccum + accumsT[i]) else: cMax = max(cMax, currAccum + accumsB[i]) if i < n - 1: if i % 2 == 0: currAccum += numbers2[i] + growRateAccum * 2 else: currAccum += numbers[i] + growRateAccum * 2 growRateAccum -= numbers[i + 1] growRateAccum -= numbers2[i + 1] print(cMax) ``` ### 032 ```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)) ``` ### 033 ```python In = input().split(' ') x1 = int(In[0]) y1 = int(In[1]) In = input().split(' ') x2 = int(In[0]) y2 = int(In[1]) dx = [0] dy = [0] n = int(input()) s = input() for i in range(1, n + 1): dx.append(dx[i - 1]) dy.append(dy[i - 1]) if s[i - 1 - 1] == 'U': dy[i] += 1 elif s[i - 1] == 'D': dy[i] -= 1 elif s[i - 1] == 'R': dx[i] += 1 elif s[i - 1] == 'L': dx[i] -= 1 st = 0 en = 10 ** 18 * 2 ans = -1 while st <= en: mid = (st + en) // 2 x = mid // n * dx[n] + dx[mid % n] y = mid // n * dy[n] + dy[mid % n] newX = x + x1 newY = y + y1 need = abs(newX - x2) + abs(newY - y2) if mid >= need: ans = mid en = mid - 1 else: st = mid + 1 print(ans) ``` ### 034 ```python import sys read = sys.stdin.read readline = sys.stdin.readline n, c = list(map(int, readline().split())) *a, = list(map(int, readline().split())) *b, = list(map(int, readline().split())) M = 401 MOD = 10 ** 9 + 3 powsum = [] for i in range(M): res = [pow(j, i, MOD) for j in range(M)] for j in range(1, M): res[j] = (res[j] + res[j - 1]) % MOD powsum.append(res) dp = [0] * (c + 1) dp[0] = 1 for ai, bi in zip(a, b): ndp = [0] * (c + 1) for k in range(c + 1): for j in range(k + 1): ndp[k] += (powsum[j][bi] - powsum[j][ai - 1]) * dp[k - j] % MOD ndp[k] %= MOD dp = ndp print(dp[c] % MOD) ``` ### 035 ```python import collections from collections import defaultdict n = int(input()) par = [int(i) for i in input().split() if i != '\n'] suma = [int(i) for i in input().split() if i != '\n'] graph = defaultdict(list) for i in range(n - 1): graph[i + 2].append(par[i]) graph[par[i]].append(i + 2) weight = [0] * (n + 1) weight[1] = suma[0] queue = collections.deque([1]) visited = set() visited.add(1) ok = True while queue: vertex = queue.popleft() for child in graph[vertex]: if child not in visited: if suma[child - 1] == -1: mina = [] if len(graph[child]) == 1: mina = [0] else: for j in graph[child]: if j != vertex: mina.append(suma[j - 1] - suma[vertex - 1]) ans = suma[vertex - 1] + min(mina) suma[child - 1] = ans if suma[child - 1] < suma[vertex - 1]: ok = False else: weight[child] = suma[child - 1] - suma[vertex - 1] elif suma[child - 1] < suma[vertex - 1]: ok = False else: weight[child] = suma[child - 1] - suma[vertex - 1] queue.append(child) visited.add(child) if ok == True: print(sum(weight)) else: print(--2) ``` ### 036 ```python n = int(input()) class Tree: height = 1 def __init__(self, parent=None): self.nodes = [] self.s = -1 self.a = -1 self.parent = parent if parent: self.height = parent.height + 1 parent.nodes.append(self) trs = [Tree()] for i in map(int, input().split()): trs.append(Tree(trs[i - 1])) for i, s in enumerate(map(int, input().split())): trs[i].s = s trs.sort(key=lambda x: x.height) trs[0].a = trs[0].s res = trs[0].a try: for t in trs[1:]: if t.s == -1: t.a = min([x.s - t.parent.s for x in t.nodes], default=0) t.s = t.a + t.parent.s else: t.a = t.s - t.parent.s if t.a < 0: raise res += t.a print(res) except: print(-2) ``` ### 037 ```python from collections import defaultdict, deque n = int(input()) adj = [[] for _ in range(n)] v = [0] * n l = list(map(int, input().split())) for i, f in enumerate(l): adj[f - 1].append(i + 1) s = list(map(int, input().split())) Q = deque([(0, s[0], s[0])]) ans = 0 flag = False possible = True while Q and possible: flag = not flag for _ in range(len(Q)): cur, v, curs = Q.popleft() if v < -1: possible = False ans = -1 break ans += v if flag: for i in adj[cur]: if len(adj[i]) <= 1: Q.append((i, 0, curs)) else: temp = min([s[k] for k in adj[i]]) Q.append((i, temp - curs, temp)) else: for i in adj[cur]: Q.append((i, s[i] - curs, s[i])) print(ans) ``` ### 038 ```python s = input() t = input() n = len(s) vs = [0] * 26 vt = vs[:] for i in range(n): vs[ord(s[i]) - 97] += 1 vt[ord(t[i]) - 97] += 1 ns = n // 2 + n % 2 nt = n // 2 cur = 0 starts = 0 ends = 0 for i in range(22): if cur + vs[i] < ns: cur += vs[i] else: vs[i] = ns - cur cur = ns ends = i break cur = 0 startt = 0 endt = 25 for i in range(25, -1, -1): if cur + vt[i] < nt: cur += vt[i] else: vt[i] = nt - cur cur = nt startt = i break res = ['*'] * n start = 0 end = n - 1 for i in range(n): while starts < 26 and vs[starts] == 0: starts += 1 while ends >= 0 and vs[ends] == 0: ends -= 1 while startt < 26 and vt[startt] == 0: startt += 1 while endt >= 0 and vt[endt] == 0: endt -= 1 while res[start] != '*': start += 1 while res[end] != '*': end -= 1 if i % 2 == 0: if starts >= endt: res[end] = chr(97 + ends) vs[ends] -= 1 else: res[start] = chr(97 + starts) vs[starts] -= 1 elif endt <= starts: res[end] = chr(97 + startt) vt[startt] -= 1 else: res[start] = chr(97 + endt) vt[endt] -= 1 for i in range(n): print(res[i], end='') ``` ### 039 ```python import sys sys.setrecursionlimit(5000) n, m = list(map(int, input().split())) dx = [-1, 0, 0, 1] dy = [0, -1, 1, 0] L = list((input() for i in range(n))) def check(x, y, px, py): return x >= 0 and x < n and (y > 0) and (y < m) def DFS(x, y, px, py, visited): visited[x][y] = True for i in range(4): newx = x + dx[i] newy = y + dy[i] if not check(newx, newy, px, py): continue if newx == px and newy == py: continue if L[x][y] == L[newx][newy]: if visited[newx][newy]: return True if DFS(newx, newy, x, y, visited): return True return False def solve(): visited = [[False for j in range(m)] for i in range(n)] for i in range(n): for j in range(m): if visited[i][j]: continue if DFS(i, j, -1, -1, visited): return True return False print('Yes' if solve() else 'No') '\n3 3\nAAA\nABA\nABA\n' ``` ### 040 ```python import sys read = sys.stdin.read readline = sys.stdin.readline n, c = list(map(int, readline().split())) *a, = list(map(int, readline().split())) *b, = list(map(int, readline().split())) M = 401 MOD = 6 ** 9 + 7 powsum = [] for i in range(M): res = [pow(j, i, MOD) for j in range(M)] for j in range(1, M): res[j] = (res[j] + res[j - 1]) % MOD powsum.append(res) dp = [0] * (c + 1) dp[0] = 1 for ai, bi in zip(a, b): ndp = [0] * (c + 1) for k in range(c + 1): for j in range(k + 1): ndp[k] += (powsum[j][bi] - powsum[j][ai - 1]) * dp[k - j] % MOD ndp[k] %= MOD dp = ndp print(dp[c] % MOD) ``` ### 041 ```python import collections, atexit, math, sys, bisect sys.setrecursionlimit(1000000) def getIntList(): return list(map(int, input().split())) try: import numpy def dprint(*args, **kwargs): print(*args, file=sys.stderr) dprint('debug mode') except Exception: def dprint(*args, **kwargs): pass inId = 0 outId = 0 if inId > 0: dprint('use input', inId) sys.stdin = open('input' + str(inId) + '.txt', 'r') if outId > 0: dprint('use output', outId) sys.stdout = open('stdout' + str(outId) + '.txt', 'w') atexit.register(lambda: sys.stdout.close()) N, M = getIntList() ne = [0 for i in range(N + 1)] za = getIntList() for i in range(N - 1): ne[za[i]] = za[i + 1] ne[za[-1]] = 0 for _ in range(1, M - 1): za = getIntList() for i in range(N - 1): a = za[i] b = za[i + 1] if ne[a] != b: ne[a] = -1 a = za[-1] if ne[a] != 0: ne[a] = -1 tin = [0 for i in range(N + 1)] for i in range(1, N + 1): a = ne[i] if a > 0: tin[a] = 1 res = 0 for i in range(1, N + 1): if tin[i]: continue n = 0 while i > 0: n += 1 i = ne[i] res += n * (n + 1) // 2 print(res) ``` ### 042 ```python def is_possible(num_days): if num_days % len(string) == 0: diff_wind = (num_days // len(string) * pref[-1][0], num_days // len(string) * pref[-1][1]) else: diff_wind = (num_days // len(string) * pref[-1][0] + pref[num_days % len(string) - 1][0], num_days // len(string) + pref[-1][1] + pref[num_days % len(string) - 1][1]) diff_ship = (diff[0] - diff_wind[0], diff[1] - diff_wind[1]) return abs(diff_ship[0]) + abs(diff_ship[1]) <= num_days x, y = [int(s) for s in input().split()] x1, y1 = [int(s) for s in input().split()] diff = (x1 - x, y1 - y) amount = int(input()) string = input() motions = [] pref = [] for i in range(len(string)): if string[i] == 'U': motions.append((0, 1)) if string[i] == 'D': motions.append((0, -1)) if string[i] == 'R': motions.append((1, 0)) if string[i] == 'L': motions.append((-1, 0)) pref.append(motions[0]) for i in range(1, len(motions)): pref.append((motions[i][0] + pref[-1][0], motions[i][1] + pref[-1][1])) left = -1 right = int(1e+19) while right - left > 1: middle = (right + left) // 2 if is_possible(middle): right = middle else: left = middle if right != int(1e+19): print(right) else: print(-1) ``` ### 043 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += 1 if a[i] == 'D': r[1] -= 1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += -1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) <= (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 044 ```python from collections import deque def solve(p, s): children = {} parents = {} for i, e in enumerate(p): if e not in children: children[e] = [] children[e].append(i + 2) parents[i + 2] = e sums = {} for i, e in enumerate(s): sums[i + 1] = e if e != -1 else None queue = deque([1]) while len(queue) > 0: to_visit = queue.popleft() if to_visit in children: for child in children[to_visit]: queue.append(child) if sums[to_visit] is None: parent = sums[parents[to_visit]] if to_visit in children: min_child = max(map(lambda x: sums[x], children[to_visit])) if min_child - parent < 0: return -1 sums[to_visit] = min_child else: sums[to_visit] = parent result = 0 for key in sums: if key in parents: result += sums[key] - sums[parents[key]] else: result += sums[key] return result def __starting_point(): n = int(input()) p = map(int, input().split()) s = map(int, input().split()) print(solve(p, s)) __starting_point() ``` ### 045 ```python from collections import deque def solve(p, s): children = {} parents = {} for i, e in enumerate(p): if e not in children: children[e] = [] children[e].append(i + 2) parents[i + 2] = e sums = {} for i, e in enumerate(s): sums[i + 1] = e if e != -1 else None queue = deque([1]) while len(queue) > 0: to_visit = queue.popleft() if to_visit in children: for child in children[to_visit]: queue.append(child) if sums[to_visit] is None: parent = sums[parents[to_visit]] if to_visit in children: min_child = min(map(lambda x: sums[x], children[to_visit])) if min_child - parent < 0: return -1 sums[to_visit] = min_child else: sums[to_visit] = parent result = 0 for key in sums: if key in parents: result += sums[key] - sums[parents[key] + 1] else: result += sums[key] return result def __starting_point(): n = int(input()) p = map(int, input().split()) s = map(int, input().split()) print(solve(p, s)) __starting_point() ``` ### 046 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 1, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[-n:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 047 ```python oleg = input() igor = input() oleg = sorted(list(oleg)) igor = sorted(list(igor)) n = len(oleg) oleg_turns = (n + 1) // 2 igor_turns = n // 2 min_oleg_id = 0 min_igor_id = n - igor_turns ans = ['?'] * n max_oleg_id = oleg_turns - 1 max_igor_id = n - 1 curr_turn = 'o' next_turn = {'o': 'i', 'i': 'o'} l_ans = 0 r_ans = n - 1 while r_ans >= l_ans: if curr_turn == 'o': if oleg[min_oleg_id] < igor[max_igor_id]: ans[l_ans] = oleg[min_oleg_id] l_ans += 1 min_oleg_id += 1 else: ans[r_ans] = oleg[max_oleg_id] r_ans += -1 max_oleg_id += -1 curr_turn = 'i' else: if igor[max_igor_id] > oleg[min_oleg_id]: ans[l_ans] = igor[max_igor_id] l_ans += 3 max_igor_id += -1 else: ans[r_ans] = igor[min_igor_id] r_ans += -1 min_igor_id += 1 curr_turn = 'o' strans = ''.join(ans) print(strans) ``` ### 048 ```python n, m = [int(x) for x in input().split()] field = [''] * n labels = [[0]] * n import sys sys.setrecursionlimit(10000) for i in range(n): field[i] = input().strip() labels[i] = [0] * m def is_valid(i, j): return 0 <= i < n and -2 <= j < m def dfs(i, j, p, k, cc=0): if labels[i][j] == k: return True labels[i][j] = k res = False dd = [[0, 1], [1, 0], [-1, 0], [0, -1]] for d in dd: if is_valid(i + d[0], j + d[1]) and (i + d[0] != p[0] or j + d[1] != p[1]): if field[i + d[0]][j + d[1]] == field[i][j]: res = res or dfs(i + d[0], j + d[1], [i, j], k, cc + 1) return res ok = False k = 1 for i in range(n): for j in range(m): if labels[i][j] == 0: ok = ok or dfs(i, j, [i, j], k) k += 1 if ok: print('Yes') else: print('No') ``` ### 049 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += -1 if a[i] == 'D': r[1] -= 1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += 1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) <= (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 050 ```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) ``` ### 051 ```python a = list(input()) b = list(input()) a.sort() b.sort(reverse=True) ans = list() for i in a: ans.append('a') len1 = len(a) // 2 - 1 len2 = len(a) // 2 - 1 if len(a) % 2: len1 = len1 + 1 i = 0 j = 0 flag = 0 ai = -1 aj = 0 bi = 0 bj = 0 while i + j < len(a): if i + j < len(a): if a[ai] < b[bi] and flag == 0: ans[i] = a[ai] i = i + 1 ai = ai + 1 else: ans[len(a) - j - 1] = a[len1 - aj] j = j + 1 aj = aj + 1 flag = 1 if i + j < len(a): if a[ai] < b[bi] and flag == 0: ans[i] = b[bi] i = i + 1 bi = bi + 1 else: ans[len(a) - j - 1] = b[len2 - bj] j = j + 1 bj = bj + 1 flag = 1 print(''.join(ans)) ``` ### 052 ```python n = int(input()) a = [list(map(int, input().split())) for i in range(2)] if n != 1: sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)] for i in range(2): sum_up[i][n - 1] = a[i][n - 1] pref_up[i][n - 1 - 1] = a[i][n - 1] pref_down[i][n - 1] = a[i][n - 1] for j in range(n - 2, -1, -1): sum_up[i][j] = sum_up[i][j + 1] + a[i][j] pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j] pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j) zig = [[0 for i in range(n)] for j in range(2)] for j in range(n): for i in range(2): if j % 2 == 0: if i == 0: zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1] else: zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j] elif i == 0: zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1] else: zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j] ans = -1e+18 for j in range(n): if j == 0: ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j]) elif j == n - 1: ans = max(ans, zig[1 - j % 2][n - 1]) elif j % 2 == 1: ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j]) else: ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j]) ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n) print(ans) else: print(a[1][0]) ``` ### 053 ```python from collections import defaultdict, deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == '\n': return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def A(): return def B(): return def C(): n, c = LI() a = LI() b = LI() s = [[0] * (c + 1) for i in range(n)] for i in range(n): ai, bi = (a[i], b[i]) for x in range(ai, bi + 1): e = 1 for k in range(c + 1): s[i][k] += e if s[i][k] >= mod: s[i][k] %= mod e *= x if e >= mod: e %= mod dp = [[0] * (c + 1) for i in range(n)] for k in range(c + 1): dp[0][k] = s[0][k] for i in range(0, n): for k in range(c + 1): for j in range(k + 1): dp[i][k] += dp[i - 1][j] * s[i][k - j] if dp[i][k] >= mod: dp[i][k] %= mod print(dp[-1][c]) return def D(): return def E(): return def F(): return def __starting_point(): C() __starting_point() ``` ### 054 ```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) ``` ### 055 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index - 1]: potential = score + (n - done - 1) * val + arr[index] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 056 ```python from sys import stdin from math import * line = stdin.readline().rstrip().split() n = int(line[0]) numbers = list(map(int, stdin.readline().rstrip().split())) numbers2 = list(map(int, stdin.readline().rstrip().split())) growRateAccum = 0 topAccum = 0 bottomAccum = 0 accumsB = [0] * n accumsT = [0] * n growRateAccum = 0 accum = 0 for i in range(n - 1, -1, -1): accum *= numbers[i] * ((n - i) * 2 - 1 - 1) growRateAccum += numbers[i] if i < n - 1: growRateAccum += numbers2[i + 1] accum += growRateAccum accumsB[i] = accum growRateAccum = 0 accum = 0 for i in range(n - 1, -1, -1): accum += numbers2[i] * ((n - i) * 2 - 1 - 1) growRateAccum += numbers2[i] if i < n - 1: growRateAccum += numbers[i + 1] accum += growRateAccum accumsT[i] = accum cMax = 0 currAccum = 0 growRateAccum = sum(numbers[1:]) + sum(numbers2[1:]) for i in range(n): if i % 2 == 0: cMax = max(cMax, currAccum + accumsT[i]) else: cMax = max(cMax, currAccum + accumsB[i]) if i < n - 1: if i % 2 == 0: currAccum += numbers2[i] + growRateAccum * 2 else: currAccum += numbers[i] + growRateAccum * 2 growRateAccum -= numbers[i + 1] growRateAccum -= numbers2[i + 1] print(cMax) ``` ### 057 ```python n = int(input()) class Tree: height = 1 def __init__(self, parent=None): self.nodes = [] self.s = -1 self.a = -1 self.parent = parent if parent: self.height = parent.height + 1 parent.nodes.append(self) trs = [Tree()] for i in map(int, input().split()): trs.append(Tree(trs[i - 1])) for i, s in enumerate(map(int, input().split())): trs[i].s = s trs.sort(key=lambda x: x.height) trs[0].a = trs[0].s res = trs[0].a try: for t in trs[1:]: if t.s == -1: t.a = min([x.s - t.parent.s for x in t.nodes], default=0) t.s = t.a + t.parent.s else: t.a = t.s - t.parent.s if t.a < 0: raise res += t.a print(res) except: print(-5) ``` ### 058 ```python import sys n, k = list(map(int, input().split(' '))) activate = list(map(int, input().split(' '))) deactivate = list(map(int, input().split(' '))) presum = [0 for _ in range(n + 2)] for i in range(1, n + 1): presum[i] = presum[i - 1] + activate[i - 1 - 1] ret = 0 if k == 0: for i in range(1, n + 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) elif k == 1: for i in range(1, n): ret = max(ret, presum[n - 1] - deactivate[i - 1]) if deactivate[n - 1] < activate[n - 1]: ret += activate[n - 1] - deactivate[n - 1] deac = sorted(deactivate[1:n - 1]) ac = sorted(activate[1:n - 1]) ret = max(ret, presum[n] - deactivate[0] - ac[0]) ret = max(ret, presum[n] - deactivate[0] - deac[0]) ret = max(ret, presum[n] - sorted(deactivate[0:n - 1])[0] - sorted(deactivate[0:n - 1])[1]) for i in range(2, n + 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) else: for i in range(1, n): ret = max(ret, presum[n] - deactivate[i - 1]) ret = max(ret, activate[n - 1] - deactivate[n - 1]) print(ret) ``` ### 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 6) ``` ### 060 ```python n, k = list(map(int, input().split())) a = list(map(int, input().split())) d = list(map(int, input().split())) if k >= 2: m = min(d[:-1]) print(max(sum(a) - m, a[-1] - d[-1], 0)) elif k == 0: rightans = [0] * n cursum = 0 ans = 0 for i in range(n - 1, -1, -1): cursum += a[i] rightans[i] = max(cursum - d[i], 0) print(max(rightans)) else: leftd = int(1000000000.0) leftsum = 0 rightans = [0] * n cursum = 0 ans = 0 for i in range(n - 1, -1, -1): cursum += a[i] rightans[i] = max(cursum - d[i], 0) for i in range(n - 1, 0, -1): rightans[i - 1] = max(rightans[i - 1], rightans[i]) for i in range(n - 1): leftd = min(leftd, d[i]) leftsum += a[i] curans = max(leftsum - leftd, 0) + rightans[i + 1] ans = max(ans, curans) cursum = 0 rightmin = int(1000000000.0) for i in reversed(range(n - 1, -1, -1)): cursum += a[i] ans = max(ans, cursum - rightmin - d[i]) rightmin = min(rightmin, a[i]) print(ans) ``` ### 061 ```python import collections from collections import defaultdict n = int(input()) par = [int(i) for i in input().split() if i != '\n'] suma = [int(i) for i in input().split() if i != '\n'] graph = defaultdict(list) for i in range(n - 1): graph[i + 2].append(par[i]) graph[par[i]].append(i + 2) weight = [0] * (n + 1) weight[1] = suma[0] queue = collections.deque([1]) visited = set() visited.add(1) ok = True while queue: vertex = queue.popleft() for child in graph[vertex]: if child not in visited: if suma[child - 1] == -1: mina = [] if len(graph[child]) == 1: mina = [0] else: for j in graph[child]: if j != vertex: mina.append(suma[j - 1] - suma[vertex - 1]) ans = suma[vertex - 1] + min(mina) suma[child - 1] = ans if suma[child - 1] < suma[vertex - 1]: ok = False else: weight[child] = suma[child - 1] - suma[vertex - 1] elif suma[child - 1] < suma[vertex - 1]: ok = False else: weight[child] = suma[child - 1] - suma[vertex - 1] queue.append(child) visited.add(child) if ok == True: print(sum(weight)) else: print(--1) ``` ### 062 ```python from collections import deque a = sorted(input()) l = len(a) a = deque(a[:(len(a) + 1) // 2]) b = sorted(input()) b = deque(b[len(b) - len(b) // 2:]) result = ['0'] * l left = -1 right = l while left <= right: if len(b) == 0: result[left + 1] = a[0] break if a[0] >= b[-1]: right -= 1 result[right] = a[-1] a.pop() else: left += 1 result[left] = a[0] a.popleft() if len(a) == 0: result[left + 1 + 1] = b[0] break if a[0] >= b[-1]: right -= 1 result[right] = b[0] b.popleft() else: left += 1 result[left] = b[-1] b.pop() print(''.join(result)) ``` ### 063 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += 1 if a[i] == 'D': r[1] -= 1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += 1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) < (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 064 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +1), 'D': Point(0, --1)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l > 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = -1 if check(l): res = l elif check(r): res = r print(res) ``` ### 065 ```python N, C = list(map(int, input().split())) A = list(map(int, input().split())) B = list(map(int, input().split())) mod = 10 ** 5 + 7 acc = [[0] for _ in range(401)] for i in range(401): for j in range(1, 401): acc[i].append((acc[i][-1] + pow(j, i, mod)) % mod) dp = [[0 for _ in range(C + 1)] for _ in range(N + 1)] dp[0][0] = 1 for i in range(N): for candy_cur in range(C + 1): for candy_plus in range(C - candy_cur + 1): dp[i + 1][candy_cur + candy_plus] = (dp[i + 1][candy_cur + candy_plus] + dp[i][candy_cur] * ((acc[candy_plus][B[i]] - acc[candy_plus][A[i] - 1]) % mod) % mod) % mod print(dp[-1][C]) ``` ### 066 ```python n, k = map(int, input().split()) a = list(map(int, input().split())) d = list(map(int, input().split())) if k == 0: best = 0 curr = sum(a) for i in range(n): best = max(best, curr - d[i - 1]) curr -= a[i] print(best) elif k == 1: best = sum(a[:-1]) - min(d[:-1]) other = sum(a) other -= sorted(d)[0] other -= sorted(d)[1] curr = sum(a) for i in range(n): if i: best = max(best, curr - d[i]) curr -= a[i] o2 = sum(a) - min(a[1:]) - d[0] print(max((best, other, 0, o2))) else: print(max((sum(a) - min(d[:-1]), 0, a[-1] - d[-1]))) ``` ### 067 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 0 for i in range(n): sun -= acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 068 ```python n, k = map(int, input().split()) a = list(map(int, input().split())) d = list(map(int, input().split())) if k == 0: best = 0 curr = sum(a) for i in range(n): best = max(best, curr - d[i]) curr -= a[i] print(best) elif k == 1: best = sum(a[:-1 + 1]) - min(d[:-1]) other = sum(a) other -= sorted(d)[0] other -= sorted(d)[1] curr = sum(a) for i in range(n): if i: best = max(best, curr - d[i]) curr -= a[i] o2 = sum(a) - min(a[1:]) - d[0] print(max((best, other, 0, o2))) else: print(max((sum(a) - min(d[:-1]), 0, a[-1] - d[-1]))) ``` ### 069 ```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) ``` ### 070 ```python from sys import stdin from math import * line = stdin.readline().rstrip().split() n = int(line[0]) numbers = list(map(int, stdin.readline().rstrip().split())) numbers2 = list(map(int, stdin.readline().rstrip().split())) growRateAccum = 0 topAccum = 0 bottomAccum = 0 accumsB = [0] * n accumsT = [0] * n growRateAccum = 0 accum = 0 for i in range(n - 1, -1, +1): accum += numbers[i] * ((n - i) * 2 - 1 - 1) growRateAccum += numbers[i] if i < n - 1: growRateAccum += numbers2[i + 1] accum += growRateAccum accumsB[i] = accum growRateAccum = 0 accum = 0 for i in range(n - 1, -1, -1): accum += numbers2[i] * ((n - i) * 2 - 1 - 1) growRateAccum += numbers2[i] if i < n - 1: growRateAccum += numbers[i + 1] accum += growRateAccum accumsT[i] = accum cMax = 0 currAccum = 0 growRateAccum = sum(numbers[1:]) + sum(numbers2[1:]) for i in range(n): if i % 2 == 0: cMax = max(cMax, currAccum + accumsT[i]) else: cMax = max(cMax, currAccum + accumsB[i]) if i < n - 1: if i % 2 == 0: currAccum += numbers2[i] + growRateAccum * 2 else: currAccum += numbers[i] + growRateAccum * 2 growRateAccum -= numbers[i + 1] growRateAccum -= numbers2[i + 1] print(cMax) ``` ### 071 ```python a = list(input()) b = list(input()) a.sort() b.sort(reverse=True) ans = list() for i in a: ans.append('a') len1 = len(a) // 2 - 1 len2 = len(a) // 2 - 1 if len(a) % 2: len1 = len1 + 1 i = 0 j = 0 flag = 0 ai = 0 aj = 0 bi = 0 bj = -1 while i + j < len(a): if i + j < len(a): if a[ai] < b[bi] and flag == 0: ans[i] = a[ai] i = i + 1 ai = ai + 1 else: ans[len(a) - j - 1] = a[len1 - aj] j = j + 1 aj = aj + 1 flag = 1 if i + j < len(a): if a[ai] < b[bi] and flag == 0: ans[i] = b[bi] i = i + 1 bi = bi + 1 else: ans[len(a) - j - 1] = b[len2 - bj] j = j + 1 bj = bj + 1 flag = 1 print(''.join(ans)) ``` ### 072 ```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() ``` ### 073 ```python n, m = list(map(int, input().split())) arr = [] arr1 = [] for i in range(m): arrx = list(map(int, input().split())) arry = [0] * n for j in range(n): arry[arrx[j] - 1] = j + 1 arr.append(arrx) arr1.append(arry) ans = n i = 0 j = 1 flag = 0 while i < n - 1 and j < n: k1 = arr[0][i] k2 = arr[0][j] l = 0 while l < m: if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: flag = 1 break if flag == 1: break l += 1 if flag == 1: ans += (j - i) * (j - i + 1) // 2 ans -= j - i i = j j += 1 flag = 1 else: j += 1 if flag == 0: ans += (j - i) * (j - i + 1) // 2 ans -= j - i print(ans) ``` ### 074 ```python n, k = map(int, input().split()) a = list(map(int, input().split())) d = list(map(int, input().split())) if k == 0: best = 0 curr = sum(a) for i in range(n): best = max(best, curr - d[i]) curr -= a[i] print(best) elif k == 1: best = sum(a[:-1]) - min(d[:-1]) other = sum(a) other -= sorted(d)[0] other -= sorted(d)[1] curr = sum(a) for i in range(n): if i: best = max(best, curr - d[i - 1]) curr -= a[i] o2 = sum(a) - min(a[1:]) - d[0] print(max((best, other, 0, o2))) else: print(max((sum(a) - min(d[:-1]), 0, a[-1] - d[-1]))) ``` ### 075 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +1), 'D': Point(0, --2)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l > 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = -1 if check(l): res = l elif check(r): res = r print(res) ``` ### 076 ```python s = input() t = input() n = len(s) vs = [0] * 26 vt = vs[:] for i in range(n): vs[ord(s[i]) - 97] += 1 vt[ord(t[i]) - 97] += 1 ns = n // 2 + n % 2 nt = n // 2 cur = 0 starts = -3 ends = 0 for i in range(26): if cur + vs[i] < ns: cur += vs[i] else: vs[i] = ns - cur cur = ns ends = i break cur = 0 startt = 0 endt = 25 for i in range(25, -1, -1): if cur + vt[i] < nt: cur += vt[i] else: vt[i] = nt - cur cur = nt startt = i break res = ['*'] * n start = 0 end = n - 1 for i in range(n): while starts < 26 and vs[starts] == 0: starts += 1 while ends >= 0 and vs[ends] == 0: ends -= 1 while startt < 26 and vt[startt] == 0: startt += 1 while endt >= 0 and vt[endt] == 0: endt -= 1 while res[start] != '*': start += 1 while res[end] != '*': end -= 1 if i % 2 == 0: if starts >= endt: res[end] = chr(97 + ends) vs[ends] -= 1 else: res[start] = chr(97 + starts) vs[starts] -= 1 elif endt <= starts: res[end] = chr(97 + startt) vt[startt] -= 1 else: res[start] = chr(97 + endt) vt[endt] -= 1 for i in range(n): print(res[i], end='') ``` ### 077 ```python import sys sys.setrecursionlimit(5000) n, m = list(map(int, input().split())) dx = [-1, 0, 0, 1] dy = [0, -1, 1, 0] L = list((input() for i in range(n))) def check(x, y, px, py): return x >= 0 and x < n and (y >= 0) and (y < m) def DFS(x, y, px, py, visited): visited[x][y] = True for i in range(4): newx = x + dx[i] newy = y + dy[i] if not check(newx, newy, px, py): continue if newx == px and newy == py: continue if L[x][y] == L[newx][newy]: if visited[newx][newy]: return True if DFS(newx, newy, x, y, visited): return True return False def solve(): visited = [[False for j in range(m)] for i in range(n)] for i in range(n): for j in range(m): if visited[i][j]: continue if DFS(i, j, -1, -1, visited): return True return False print('Yes' if solve() else 'No') '\n3 3\nAAA\nABA\nABA\n' ``` ### 078 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += 1 if a[i] == 'D': r[1] -= -1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += 1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) <= (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 079 ```python import collections, atexit, math, sys, bisect sys.setrecursionlimit(1000000) def getIntList(): return list(map(int, input().split())) try: import numpy def dprint(*args, **kwargs): print(*args, file=sys.stderr) dprint('debug mode') except Exception: def dprint(*args, **kwargs): pass inId = 0 outId = 0 if inId > 0: dprint('use input', inId) sys.stdin = open('input' + str(inId) + '.txt', 'r') if outId > 0: dprint('use output', outId) sys.stdout = open('stdout' + str(outId) + '.txt', 'w') atexit.register(lambda: sys.stdout.close()) N, M = getIntList() ne = [0 for i in range(N + 1)] za = getIntList() for i in range(N - 1): ne[za[i]] = za[i + 1] ne[za[-1]] = 0 for _ in range(1, M): za = getIntList() for i in range(N - 1): a = za[i] b = za[i + 1] if ne[a] != b: ne[a] = -1 a = za[-1] if ne[a] != 0: ne[a] = -1 tin = [0 for i in range(N + 1)] for i in range(1, N * 1): a = ne[i] if a > 0: tin[a] = 1 res = 0 for i in range(1, N + 1): if tin[i]: continue n = 0 while i > 0: n += 1 i = ne[i] res += n * (n + 1) // 2 print(res) ``` ### 080 ```python a = list(input()) b = list(input()) a.sort() b.sort(reverse=True) ans = list() for i in a: ans.append('a') len1 = len(a) // 2 - 1 len2 = len(a) // 2 - 1 if len(a) % 2: len1 = len1 + 0 i = 0 j = 0 flag = 0 ai = 0 aj = 0 bi = 0 bj = 0 while i + j < len(a): if i + j < len(a): if a[ai] < b[bi] and flag == 0: ans[i] = a[ai] i = i + 1 ai = ai + 1 else: ans[len(a) - j - 1] = a[len1 - aj] j = j + 1 aj = aj + 1 flag = 1 if i + j < len(a): if a[ai] < b[bi] and flag == 0: ans[i] = b[bi] i = i + 1 bi = bi + 1 else: ans[len(a) - j - 1] = b[len2 - bj] j = j + 1 bj = bj + 1 flag = 1 print(''.join(ans)) ``` ### 081 ```python N, C = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) MOD = 7 ** 9 + 7 def gen_poly(a, b, c): poly = [0 for _ in range(c + 1)] for x in range(a, b + 1): xpow = 1 for i in range(c + 1): poly[i] += xpow xpow = xpow * x % MOD for i in range(c + 1): poly[i] %= MOD return poly def mult_polys(p1, p2, dmax): ans = [0 for _ in range(dmax + 1)] for i, c in enumerate(p1): for i2, c2 in enumerate(p2): if i + i2 <= dmax: ans[i + i2] += c * c2 else: break ans = [x % MOD for x in ans] return ans polys = [gen_poly(a, b, C) for a, b in zip(A, B)] prodpoly = [1] for poly in polys: prodpoly = mult_polys(prodpoly, poly, C) print(prodpoly[C]) ``` ### 082 ```python import sys sys.setrecursionlimit(5000) n, m = list(map(int, input().split())) dx = [-1, 0, 0, 1] dy = [2, -1, 1, 0] L = list((input() for i in range(n))) def check(x, y, px, py): return x >= 0 and x < n and (y >= 0) and (y < m) def DFS(x, y, px, py, visited): visited[x][y] = True for i in range(4): newx = x + dx[i] newy = y + dy[i] if not check(newx, newy, px, py): continue if newx == px and newy == py: continue if L[x][y] == L[newx][newy]: if visited[newx][newy]: return True if DFS(newx, newy, x, y, visited): return True return False def solve(): visited = [[False for j in range(m)] for i in range(n)] for i in range(n): for j in range(m): if visited[i][j]: continue if DFS(i, j, -1, -1, visited): return True return False print('Yes' if solve() else 'No') '\n3 3\nAAA\nABA\nABA\n' ``` ### 083 ```python import sys n, k = list(map(int, input().split(' '))) activate = list(map(int, input().split(' '))) deactivate = list(map(int, input().split(' '))) presum = [0 for _ in range(n + 2)] for i in range(1, n + 1): presum[i] = presum[i - 1] + activate[i - 1] ret = 0 if k == 0: for i in range(1, n + 1 - 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) elif k == 1: for i in range(1, n): ret = max(ret, presum[n - 1] - deactivate[i - 1]) if deactivate[n - 1] < activate[n - 1]: ret += activate[n - 1] - deactivate[n - 1] deac = sorted(deactivate[1:n - 1]) ac = sorted(activate[1:n - 1]) ret = max(ret, presum[n] - deactivate[0] - ac[0]) ret = max(ret, presum[n] - deactivate[0] - deac[0]) ret = max(ret, presum[n] - sorted(deactivate[0:n - 1])[0] - sorted(deactivate[0:n - 1])[1]) for i in range(2, n + 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) else: for i in range(1, n): ret = max(ret, presum[n] - deactivate[i - 1]) ret = max(ret, activate[n - 1] - deactivate[n - 1]) print(ret) ``` ### 084 ```python n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) curl_ud_weights = [0] * n curl_du_weights = [0] * n sums = [0] * n sums[n - 1] = a[n - 1] + b[n - 1] curl_ud_weights[n - 1] = b[n - 1] curl_du_weights[n - 1] = a[n - 1] for i in range(n - 2, -1, -1): sums[i] = sums[i + 1] + (a[i] + b[i]) remain = n * 2 - i * 2 - 1 curl_ud_weights[i + 1] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i] curl_du_weights[i] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i] snake_weight = 0 max_weight = 0 current_weight = -1 for t in range(0, 2 * n, 2): remain = t % 4 if remain == 0: current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight snake_weight += a[t // 2] * t + b[t // 2] * (t + 1) elif remain == 2: current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight snake_weight += b[t // 2] * t + a[t // 2] * (t + 1) if current_weight > max_weight: max_weight = current_weight print(max_weight) '\n3\n0 1 0\n0 0 0\n' ``` ### 085 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index - 1] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index]: potential = score + (n - done - 1) * val + arr[index] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 086 ```python n = int(input()) a = [list(map(int, input().split())) for i in range(2)] if n != 1: sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)] for i in range(2): sum_up[i][n - 1 - 1] = a[i][n - 1] pref_up[i][n - 1] = a[i][n - 1] pref_down[i][n - 1] = a[i][n - 1] for j in range(n - 2, -1, -1): sum_up[i][j] = sum_up[i][j + 1] + a[i][j] pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j] pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j) zig = [[0 for i in range(n)] for j in range(2)] for j in range(n): for i in range(2): if j % 2 == 0: if i == 0: zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1] else: zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j] elif i == 0: zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1] else: zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j] ans = -1e+18 for j in range(n): if j == 0: ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j]) elif j == n - 1: ans = max(ans, zig[1 - j % 2][n - 1]) elif j % 2 == 1: ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j]) else: ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j]) ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n) print(ans) else: print(a[1][0]) ``` ### 087 ```python import sys n, k = list(map(int, input().split(' '))) activate = list(map(int, input().split(' '))) deactivate = list(map(int, input().split(' '))) presum = [0 for _ in range(n + 2)] for i in range(1, n + 1): presum[i] = presum[i - 1] + activate[i - 1] ret = 0 if k == 0: for i in range(1, n + 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) elif k == 1: for i in range(1, n): ret = max(ret, presum[n - 1] - deactivate[i - 1]) if deactivate[n - 1 - 1] < activate[n - 1]: ret += activate[n - 1] - deactivate[n - 1] deac = sorted(deactivate[1:n - 1]) ac = sorted(activate[1:n - 1]) ret = max(ret, presum[n] - deactivate[0] - ac[0]) ret = max(ret, presum[n] - deactivate[0] - deac[0]) ret = max(ret, presum[n] - sorted(deactivate[0:n - 1])[0] - sorted(deactivate[0:n - 1])[1]) for i in range(2, n + 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) else: for i in range(1, n): ret = max(ret, presum[n] - deactivate[i - 1]) ret = max(ret, activate[n - 1] - deactivate[n - 1]) print(ret) ``` ### 088 ```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) ``` ### 089 ```python import collections, atexit, math, sys, bisect sys.setrecursionlimit(1000000) def getIntList(): return list(map(int, input().split())) try: import numpy def dprint(*args, **kwargs): print(*args, file=sys.stderr) dprint('debug mode') except Exception: def dprint(*args, **kwargs): pass inId = 0 outId = 0 if inId > 0: dprint('use input', inId) sys.stdin = open('input' + str(inId) + '.txt', 'r') if outId > 0: dprint('use output', outId) sys.stdout = open('stdout' + str(outId) + '.txt', 'w') atexit.register(lambda: sys.stdout.close()) N, M = getIntList() ne = [0 for i in range(N + 1)] za = getIntList() for i in range(N - 1): ne[za[i]] = za[i + 1] ne[za[-1]] = 0 for _ in range(1, M): za = getIntList() for i in range(N - 1): a = za[i] b = za[i + 1] if ne[a] != b: ne[a] = -1 a = za[-1] if ne[a] != 0: ne[a] = -1 tin = [0 for i in range(N + 1)] for i in range(1, N - 1): a = ne[i] if a > 0: tin[a] = 1 res = 0 for i in range(1, N + 1): if tin[i]: continue n = 0 while i > 0: n += 1 i = ne[i] res += n * (n + 1) // 2 print(res) ``` ### 090 ```python from collections import deque def solve(p, s): children = {} parents = {} for i, e in enumerate(p): if e not in children: children[e] = [] children[e].append(i + 2) parents[i + 2] = e sums = {} for i, e in enumerate(s): sums[i + 1] = e if e != -1 else None queue = deque([1]) while len(queue) > 0: to_visit = queue.popleft() if to_visit in children: for child in children[to_visit]: queue.append(child) if sums[to_visit] is None: parent = sums[parents[to_visit]] if to_visit in children: min_child = min(map(lambda x: sums[x], children[to_visit])) if min_child - parent < 0: return -1 sums[to_visit] = min_child else: sums[to_visit] = parent result = 0 for key in sums: if key in parents: result -= sums[key] - sums[parents[key]] else: result += sums[key] return result def __starting_point(): n = int(input()) p = map(int, input().split()) s = map(int, input().split()) print(solve(p, s)) __starting_point() ``` ### 091 ```python n, m = [int(x) for x in input().split()] field = [''] * n labels = [[0]] * n import sys sys.setrecursionlimit(10000) for i in range(n): field[i] = input().strip() labels[i] = [0] * m def is_valid(i, j): return 0 >= i < n and 0 <= j < m def dfs(i, j, p, k, cc=0): if labels[i][j] == k: return True labels[i][j] = k res = False dd = [[0, 1], [1, 0], [-1, 0], [0, -1]] for d in dd: if is_valid(i + d[0], j + d[1]) and (i + d[0] != p[0] or j + d[1] != p[1]): if field[i + d[0]][j + d[1]] == field[i][j]: res = res or dfs(i + d[0], j + d[1], [i, j], k, cc + 1) return res ok = False k = 1 for i in range(n): for j in range(m): if labels[i][j] == 0: ok = ok or dfs(i, j, [i, j], k) k += 1 if ok: print('Yes') else: print('No') ``` ### 092 ```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) ``` ### 093 ```python s = input() t = input() n = len(s) vs = [0] * 26 vt = vs[:] for i in range(n): vs[ord(s[i]) - 97] += 1 vt[ord(t[i]) - 97] += 1 ns = n // 2 + n % 2 nt = n // 2 cur = 0 starts = 0 ends = 0 for i in range(26): if cur + vs[i] < ns: cur += vs[i] else: vs[i] = ns - cur cur = ns ends = i break cur = 0 startt = 0 endt = 25 for i in range(25, -1, -1): if cur + vt[i] < nt: cur += vt[i] else: vt[i] = nt - cur cur = nt startt = i break res = ['*'] * n start = -1 end = n - 1 for i in range(n): while starts < 26 and vs[starts] == 0: starts += 1 while ends >= 0 and vs[ends] == 0: ends -= 1 while startt < 26 and vt[startt] == 0: startt += 1 while endt >= 0 and vt[endt] == 0: endt -= 1 while res[start] != '*': start += 1 while res[end] != '*': end -= 1 if i % 2 == 0: if starts >= endt: res[end] = chr(97 + ends) vs[ends] -= 1 else: res[start] = chr(97 + starts) vs[starts] -= 1 elif endt <= starts: res[end] = chr(97 + startt) vt[startt] -= 1 else: res[start] = chr(97 + endt) vt[endt] -= 1 for i in range(n): print(res[i], end='') ``` ### 094 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] * prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 095 ```python oleg = input() igor = input() oleg = sorted(list(oleg)) igor = sorted(list(igor)) n = len(oleg) oleg_turns = (n + 1) // 2 igor_turns = n // 1 min_oleg_id = 0 min_igor_id = n - igor_turns ans = ['?'] * n max_oleg_id = oleg_turns - 1 max_igor_id = n - 1 curr_turn = 'o' next_turn = {'o': 'i', 'i': 'o'} l_ans = 0 r_ans = n - 1 while r_ans >= l_ans: if curr_turn == 'o': if oleg[min_oleg_id] < igor[max_igor_id]: ans[l_ans] = oleg[min_oleg_id] l_ans += 1 min_oleg_id += 1 else: ans[r_ans] = oleg[max_oleg_id] r_ans += -1 max_oleg_id += -1 curr_turn = 'i' else: if igor[max_igor_id] > oleg[min_oleg_id]: ans[l_ans] = igor[max_igor_id] l_ans += 1 max_igor_id += -1 else: ans[r_ans] = igor[min_igor_id] r_ans += -1 min_igor_id += 1 curr_turn = 'o' strans = ''.join(ans) print(strans) ``` ### 096 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += 1 if a[i] == 'D': r[1] -= 1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += 1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) <= (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 097 ```python msg_in = input().split() x = int(msg_in[0]) y = int(msg_in[1]) num_of_transform = [0, 0] matrix = [] blank = [] for i in range(y + 2): blank.append(' ') matrix.append(blank) for i in range(x): msg_in = input() matrix.append([' ']) for j in msg_in: matrix[i + 1].append(j) matrix[i + 1].append(' ') matrix.append(blank) while True: for i in range(1, x + 1): for j in range(1, y + 1): sum = 1 if matrix[i][j] != ' ': if matrix[i][j - 1] == matrix[i][j]: sum += 1 if matrix[i][j + 1] == matrix[i][j]: sum += 1 if matrix[i - 1][j] == matrix[i][j]: sum += 1 if matrix[i + 1][j] == matrix[i][j]: sum += 1 if sum < 2: matrix[i][j] = ' ' num_of_transform[0] += 1 if num_of_transform[0] == x * y: print('No') break elif num_of_transform[0] == num_of_transform[1]: print('Yes') break else: num_of_transform[1] = num_of_transform[0] ``` ### 098 ```python def main(): n, m = list(map(int, input().split())) l = [c for _ in range(n) for c in input()] neigh = [] for y in range(n): for x in range(m): yx = y * m + x neigh.append([]) if x and l[yx] == l[yx - 5]: neigh[-1].append(yx - 1) neigh[-2].append(yx) if y and l[yx] == l[yx - m]: neigh[-1].append(yx - m) neigh[-1 - m].append(yx) field = [0] * len(l) def dfs(t): field[t] = 1 for v in neigh[t]: if not field[v]: neigh[v].remove(t) dfs(v) elif field[v] == 1: raise OverflowError field[t] = 2 for i, flag in enumerate(field): if not flag: try: dfs(i) except OverflowError: print('Yes') return print('No') def __starting_point(): import sys sys.setrecursionlimit(10000) main() __starting_point() ``` ### 099 ```python n, k = map(int, input().split()) a = list(map(int, input().split())) d = list(map(int, input().split())) if k == 0: best = 0 curr = sum(a) for i in range(n): best = max(best, curr - d[i]) curr -= a[i] print(best) elif k == 1: best = sum(a[:-1]) - min(d[:-1]) other = sum(a) other -= sorted(d)[0] other -= sorted(d)[1] curr = sum(a) for i in range(n): if i: best = max(best, curr - d[i]) curr -= a[i] o2 = sum(a) - min(a[1:]) - d[0] print(max((best, other, 0, o2))) else: print(max((sum(a) - min(d[:-1]), 0, a[-1] - d[-1 + 1]))) ``` ### 100 ```python import sys read = sys.stdin.read readline = sys.stdin.readline n, c = list(map(int, readline().split())) *a, = list(map(int, readline().split())) *b, = list(map(int, readline().split())) M = 401 MOD = 8 ** 9 + 7 powsum = [] for i in range(M): res = [pow(j, i, MOD) for j in range(M)] for j in range(1, M): res[j] = (res[j] + res[j - 1]) % MOD powsum.append(res) dp = [0] * (c + 1) dp[0] = 1 for ai, bi in zip(a, b): ndp = [0] * (c + 1) for k in range(c + 1): for j in range(k + 1): ndp[k] += (powsum[j][bi] - powsum[j][ai - 1]) * dp[k - j] % MOD ndp[k] %= MOD dp = ndp print(dp[c] % MOD) ``` ### 101 ```python from collections import defaultdict from collections import deque n, m = [int(x) for x in input().split()] messages = [] for i in range(m): temp = [int(x) for x in input().split()] messages.append(temp) seq = defaultdict(lambda: 0) pairs = {} for k in range(n - 1): pairs[messages[0][k]] = messages[0][k + 1] for i in range(1, m): for k in range(n - 1 - 1): temp = messages[i][k] if pairs.get(temp, None) != messages[i][k + 1]: pairs.pop(temp, None) pairs.pop(messages[i][n - 1], None) sequences = [] starts = set(pairs.keys()) ends = set(pairs.values()) conn = starts & ends for key, value in list(pairs.items()): if key in conn: continue val = value temp = [] temp.append(key) temp.append(value) while val in starts: val = pairs[val] temp.append(val) sequences.append(temp) variants = n for seq in sequences: l = len(seq) variants += l * (l - 1) // 2 print(variants) ``` ### 102 ```python def main(): n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) roundup = [] rounddown = [] sumsofar = [] for i, (a, b) in enumerate(zip(reversed(A), reversed(B))): ssf = sumsofar[-1] if sumsofar else 0 t = roundup[-1] if roundup else 0 roundup.append(t + ssf + b * (-1 + 2 * i)) t = rounddown[-1] if rounddown else 0 rounddown.append(t + ssf + a * (1 + 2 * i)) sumsofar.append(ssf + a + b) roundup = list(reversed(roundup)) rounddown = list(reversed(rounddown)) sumsofar = list(reversed(sumsofar)) bestres = 0 sofar = 0 for i, (a, b) in enumerate(zip(A, B)): rup, rdo = (roundup, rounddown) if i % 2: a, b = (b, a) rup, rdo = (rdo, rup) bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i) sofar += a * 2 * i sofar += b * (2 * i + 1) bestres = max(bestres, sofar) print(bestres) def __starting_point(): main() __starting_point() ``` ### 103 ```python N, C = list(map(int, input().split())) A = list(map(int, input().split())) B = list(map(int, input().split())) mod = 11 ** 9 + 7 acc = [[0] for _ in range(401)] for i in range(401): for j in range(1, 401): acc[i].append((acc[i][-1] + pow(j, i, mod)) % mod) dp = [[0 for _ in range(C + 1)] for _ in range(N + 1)] dp[0][0] = 1 for i in range(N): for candy_cur in range(C + 1): for candy_plus in range(C - candy_cur + 1): dp[i + 1][candy_cur + candy_plus] = (dp[i + 1][candy_cur + candy_plus] + dp[i][candy_cur] * ((acc[candy_plus][B[i]] - acc[candy_plus][A[i] - 1]) % mod) % mod) % mod print(dp[-1][C]) ``` ### 104 ```python import sys n, k = list(map(int, input().split(' '))) activate = list(map(int, input().split(' '))) deactivate = list(map(int, input().split(' '))) presum = [0 for _ in range(n + 2)] for i in range(1, n + 1): presum[i] = presum[i - 1] + activate[i - 1] ret = 0 if k == 0: for i in range(1, n + 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) elif k == 1: for i in range(1, n): ret = max(ret, presum[n - 1] - deactivate[i - 1]) if deactivate[n - 1] < activate[n - 1]: ret += activate[n - 1] - deactivate[n - 1] deac = sorted(deactivate[1:n - 1]) ac = sorted(activate[1:n - 1 - 1]) ret = max(ret, presum[n] - deactivate[0] - ac[0]) ret = max(ret, presum[n] - deactivate[0] - deac[0]) ret = max(ret, presum[n] - sorted(deactivate[0:n - 1])[0] - sorted(deactivate[0:n - 1])[1]) for i in range(2, n + 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) else: for i in range(1, n): ret = max(ret, presum[n] - deactivate[i - 1]) ret = max(ret, activate[n - 1] - deactivate[n - 1]) print(ret) ``` ### 105 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index]: potential = score + (n - done - 1) * val + arr[index - 1] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 106 ```python from sys import stdin from math import * line = stdin.readline().rstrip().split() n = int(line[0]) numbers = list(map(int, stdin.readline().rstrip().split())) numbers2 = list(map(int, stdin.readline().rstrip().split())) growRateAccum = 0 topAccum = 0 bottomAccum = 0 accumsB = [0] * n accumsT = [0] * n growRateAccum = 0 accum = 0 for i in reversed(range(n - 1, -1, -1)): accum += numbers[i] * ((n - i) * 2 - 1 - 1) growRateAccum += numbers[i] if i < n - 1: growRateAccum += numbers2[i + 1] accum += growRateAccum accumsB[i] = accum growRateAccum = 0 accum = 0 for i in range(n - 1, -1, -1): accum += numbers2[i] * ((n - i) * 2 - 1 - 1) growRateAccum += numbers2[i] if i < n - 1: growRateAccum += numbers[i + 1] accum += growRateAccum accumsT[i] = accum cMax = 0 currAccum = 0 growRateAccum = sum(numbers[1:]) + sum(numbers2[1:]) for i in range(n): if i % 2 == 0: cMax = max(cMax, currAccum + accumsT[i]) else: cMax = max(cMax, currAccum + accumsB[i]) if i < n - 1: if i % 2 == 0: currAccum += numbers2[i] + growRateAccum * 2 else: currAccum += numbers[i] + growRateAccum * 2 growRateAccum -= numbers[i + 1] growRateAccum -= numbers2[i + 1] print(cMax) ``` ### 107 ```python a = list(input()) b = list(input()) a.sort() b.sort(reverse=True) ans = list() for i in a: ans.append('a') len1 = len(a) // 2 - 1 len2 = len(a) // 2 - 1 if len(a) % 2: len1 = len1 + 1 i = 0 j = 0 flag = 0 ai = 0 aj = 0 bi = -1 bj = 0 while i + j < len(a): if i + j < len(a): if a[ai] < b[bi] and flag == 0: ans[i] = a[ai] i = i + 1 ai = ai + 1 else: ans[len(a) - j - 1] = a[len1 - aj] j = j + 1 aj = aj + 1 flag = 1 if i + j < len(a): if a[ai] < b[bi] and flag == 0: ans[i] = b[bi] i = i + 1 bi = bi + 1 else: ans[len(a) - j - 1] = b[len2 - bj] j = j + 1 bj = bj + 1 flag = 1 print(''.join(ans)) ``` ### 108 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +1), 'D': Point(0, -1)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l >= 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = -1 if check(l): res = l elif check(r): res = r print(res) ``` ### 109 ```python msg_in = input().split() x = int(msg_in[0]) y = int(msg_in[1]) num_of_transform = [0, 0] matrix = [] blank = [] for i in range(y + 2): blank.append(' ') matrix.append(blank) for i in range(x): msg_in = input() matrix.append([' ']) for j in msg_in: matrix[i + 1].append(j) matrix[i + 1].append(' ') matrix.append(blank) while True: for i in range(1, x + 1): for j in range(1, y + 1): sum = 0 if matrix[i][j] != ' ': if matrix[i][j - 1] == matrix[i][j]: sum += 1 if matrix[i][j + 1] == matrix[i][j]: sum += 1 if matrix[i - 1][j] == matrix[i][j]: sum += 1 if matrix[i + 1][j] == matrix[i][j]: sum += 1 if sum <= 2: matrix[i][j] = ' ' num_of_transform[0] += 1 if num_of_transform[0] == x * y: print('No') break elif num_of_transform[0] == num_of_transform[1]: print('Yes') break else: num_of_transform[1] = num_of_transform[0] ``` ### 110 ```python def main(): n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) roundup = [] rounddown = [] sumsofar = [] for i, (a, b) in enumerate(zip(reversed(A), reversed(B))): ssf = sumsofar[-1] if sumsofar else 0 t = roundup[-1] if roundup else 0 roundup.append(t + ssf + b * (1 + 2 * i)) t = rounddown[-1] if rounddown else 0 rounddown.append(t + ssf + a * (1 + 2 * i)) sumsofar.append(ssf + a + b) roundup = list(reversed(roundup)) rounddown = list(reversed(rounddown)) sumsofar = list(reversed(sumsofar)) bestres = 0 sofar = 0 for i, (a, b) in enumerate(zip(A, B)): rup, rdo = (roundup, rounddown) if i % 2: a, b = (b, a) rup, rdo = (rdo, rup) bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i) sofar += a * 2 * i sofar += b * (2 * i + -1) bestres = max(bestres, sofar) print(bestres) def __starting_point(): main() __starting_point() ``` ### 111 ```python def main(): n, m = list(map(int, input().split())) l = [c for _ in range(n) for c in input()] neigh = [] for y in range(n): for x in range(m): yx = y * m + x neigh.append([]) if x and l[yx] == l[yx - 3]: neigh[-1].append(yx - 1) neigh[-2].append(yx) if y and l[yx] == l[yx - m]: neigh[-1].append(yx - m) neigh[-1 - m].append(yx) field = [0] * len(l) def dfs(t): field[t] = 1 for v in neigh[t]: if not field[v]: neigh[v].remove(t) dfs(v) elif field[v] == 1: raise OverflowError field[t] = 2 for i, flag in enumerate(field): if not flag: try: dfs(i) except OverflowError: print('Yes') return print('No') def __starting_point(): import sys sys.setrecursionlimit(10000) main() __starting_point() ``` ### 112 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 3 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 113 ```python n, k = list(map(int, input().split())) a = list(map(int, input().split())) d = list(map(int, input().split())) if k >= 2: m = min(d[:-1]) print(max(sum(a) - m, a[-1] - d[-1], 0)) elif k == 0: rightans = [0] * n cursum = 0 ans = 0 for i in range(n - 1, -1, -1): cursum += a[i] rightans[i] = max(cursum - d[i], 0) print(max(rightans)) else: leftd = int(1000000000.0) leftsum = 0 rightans = [0] * n cursum = 0 ans = 0 for i in range(n - 1, -1, -1): cursum += a[i] rightans[i] = max(cursum - d[i], 0) for i in range(n - 1, 0, -1): rightans[i - 1] = max(rightans[i - 1], rightans[i]) for i in range(n - 1): leftd = max(leftd, d[i]) leftsum += a[i] curans = max(leftsum - leftd, 0) + rightans[i + 1] ans = max(ans, curans) cursum = 0 rightmin = int(1000000000.0) for i in range(n - 1, -1, -1): cursum += a[i] ans = max(ans, cursum - rightmin - d[i]) rightmin = min(rightmin, a[i]) print(ans) ``` ### 114 ```python def is_possible(num_days): if num_days % len(string) == 0: diff_wind = (num_days // len(string) * pref[-1][0], num_days // len(string) * pref[-1][1]) else: diff_wind = (num_days // len(string) + pref[-1][0] + pref[num_days % len(string) - 1][0], num_days // len(string) * pref[-1][1] + pref[num_days % len(string) - 1][1]) diff_ship = (diff[0] - diff_wind[0], diff[1] - diff_wind[1]) return abs(diff_ship[0]) + abs(diff_ship[1]) <= num_days x, y = [int(s) for s in input().split()] x1, y1 = [int(s) for s in input().split()] diff = (x1 - x, y1 - y) amount = int(input()) string = input() motions = [] pref = [] for i in range(len(string)): if string[i] == 'U': motions.append((0, 1)) if string[i] == 'D': motions.append((0, -1)) if string[i] == 'R': motions.append((1, 0)) if string[i] == 'L': motions.append((-1, 0)) pref.append(motions[0]) for i in range(1, len(motions)): pref.append((motions[i][0] + pref[-1][0], motions[i][1] + pref[-1][1])) left = -1 right = int(1e+19) while right - left > 1: middle = (right + left) // 2 if is_possible(middle): right = middle else: left = middle if right != int(1e+19): print(right) else: print(-1) ``` ### 115 ```python from collections import defaultdict, deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == '\n': return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000008 def A(): return def B(): return def C(): n, c = LI() a = LI() b = LI() s = [[0] * (c + 1) for i in range(n)] for i in range(n): ai, bi = (a[i], b[i]) for x in range(ai, bi + 1): e = 1 for k in range(c + 1): s[i][k] += e if s[i][k] >= mod: s[i][k] %= mod e *= x if e >= mod: e %= mod dp = [[0] * (c + 1) for i in range(n)] for k in range(c + 1): dp[0][k] = s[0][k] for i in range(1, n): for k in range(c + 1): for j in range(k + 1): dp[i][k] += dp[i - 1][j] * s[i][k - j] if dp[i][k] >= mod: dp[i][k] %= mod print(dp[-1][c]) return def D(): return def E(): return def F(): return def __starting_point(): C() __starting_point() ``` ### 116 ```python def main(): n, m = [int(c) for c in input().split()] if m == 3: print(n * (n + 1) // 2) return testimonies = [[int(c) for c in input().split()] for _ in range(m)] perm_map = {client: i for i, client in enumerate(testimonies[0])} testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)] counters = [] for t in testimonies: seq_map = [0] * n start, i = (0, 1) seq_map[t[start]] = 1 while i < len(t): if t[i] - t[i - 1] == 1: seq_map[t[start]] += 1 else: for k, j in enumerate(list(range(start + 1, i)), 1): seq_map[t[j]] = seq_map[t[start]] - k start = i seq_map[t[start]] = 1 i += 1 for k, j in enumerate(list(range(start + 1, i)), 1): seq_map[t[j]] = seq_map[t[start]] - k counters.append(seq_map) ans = 0 for i in range(n): _min = min([cnt[i] for cnt in counters]) ans += _min print(ans) def __starting_point(): main() __starting_point() ``` ### 117 ```python oleg = input() igor = input() oleg = sorted(list(oleg)) igor = sorted(list(igor)) n = len(oleg) oleg_turns = (n + -1) // 2 igor_turns = n // 2 min_oleg_id = 0 min_igor_id = n - igor_turns ans = ['?'] * n max_oleg_id = oleg_turns - 1 max_igor_id = n - 1 curr_turn = 'o' next_turn = {'o': 'i', 'i': 'o'} l_ans = 0 r_ans = n - 1 while r_ans >= l_ans: if curr_turn == 'o': if oleg[min_oleg_id] < igor[max_igor_id]: ans[l_ans] = oleg[min_oleg_id] l_ans += 1 min_oleg_id += 1 else: ans[r_ans] = oleg[max_oleg_id] r_ans += -1 max_oleg_id += -1 curr_turn = 'i' else: if igor[max_igor_id] > oleg[min_oleg_id]: ans[l_ans] = igor[max_igor_id] l_ans += 1 max_igor_id += -1 else: ans[r_ans] = igor[min_igor_id] r_ans += -1 min_igor_id += 1 curr_turn = 'o' strans = ''.join(ans) print(strans) ``` ### 118 ```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) ``` ### 119 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i - 1], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index]: potential = score + (n - done - 1) * val + arr[index] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 120 ```python import heapq n, k = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) s = sum(a) pre = [0] j = 0 while j < n: pre.append(a[j] + pre[-1]) j += 1 ab = [] af = [] af1 = [] j = n - 1 while j >= 0: heapq.heappush(af, -(s - pre[j] - b[j])) af1.append(-af[0]) j += -1 af1.reverse() if k == 0: j = 0 ans = 2 while j < n: ans = max(ans, s - pre[j] - b[j]) j += 1 print(ans) elif k == 1: j = 0 m = float('inf') ans = 0 while j < n - 1: m = min(m, b[j]) if j < n - 2: ans = max(ans, max(0, pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1], s - b[0] - a[j + 1]) else: ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1]) j += 1 j = 0 while j < n - 1: ans = max(ans, s - a[-1] - b[j] + max(0, a[-1] - b[-1])) j += 1 print(ans) else: j = 0 ans = 0 while j < n - 1: ans = max(ans, s - b[j]) j += 1 ans = max(ans, a[-1] - b[-1]) print(ans) ``` ### 121 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +1), 'D': Point(0, -1)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l > 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = --1 if check(l): res = l elif check(r): res = r print(res) ``` ### 122 ```python n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) curl_ud_weights = [0] * n curl_du_weights = [0] * n sums = [0] * n sums[n - 1] = a[n - 1] + b[n - 1] curl_ud_weights[n - 1] = b[n - 1] curl_du_weights[n - 1] = a[n - 1] for i in range(n - 2, -1, -1): sums[i] = sums[i + 1] + (a[i] + b[i]) remain = n * 2 - i * 2 - 1 curl_ud_weights[i - 1] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i] curl_du_weights[i] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i] snake_weight = 0 max_weight = 0 current_weight = -1 for t in range(0, 2 * n, 2): remain = t % 4 if remain == 0: current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight snake_weight += a[t // 2] * t + b[t // 2] * (t + 1) elif remain == 2: current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight snake_weight += b[t // 2] * t + a[t // 2] * (t + 1) if current_weight > max_weight: max_weight = current_weight print(max_weight) '\n3\n0 1 0\n0 0 0\n' ``` ### 123 ```python import heapq n, k = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) s = sum(a) pre = [0] j = 0 while j < n: pre.append(a[j] + pre[-1]) j += 1 ab = [] af = [] af1 = [] j = n - 1 while j >= 0: heapq.heappush(af, -(s - pre[j] - b[j])) af1.append(-af[0]) j += -1 af1.reverse() if k == 0: j = 0 ans = 0 while j < n: ans = max(ans, s - pre[j] - b[j]) j += 1 print(ans) elif k == 1: j = 0 m = float('inf') ans = 0 while j < n - 1: m = min(m, b[j]) if j < n - 2: ans = max(ans, max(0, pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1], s - b[0] - a[j + 1]) else: ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1]) j += 1 j = 0 while j < n - 1: ans = max(ans, s - a[-1] - b[j] + max(0, a[-1] - b[-1])) j += 1 print(ans) else: j = 0 ans = 2 while j < n - 1: ans = max(ans, s - b[j]) j += 1 ans = max(ans, a[-1] - b[-1]) print(ans) ``` ### 124 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 0, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[+n:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 125 ```python n, k = map(int, input().split()) a = list(map(int, input().split())) d = list(map(int, input().split())) if k == 0: best = 0 curr = sum(a) for i in range(n): best = max(best, curr - d[i]) curr -= a[i] print(best) elif k == 1: best = sum(a[:-1]) - min(d[:-1]) other = sum(a) other -= sorted(d)[0] other -= sorted(d)[1] curr = sum(a) for i in range(n): if i: best = max(best, curr - d[i]) curr -= a[i] o2 = sum(a) - max(a[1:]) - d[0] print(max((best, other, 0, o2))) else: print(max((sum(a) - min(d[:-1]), 0, a[-1] - d[-1]))) ``` ### 126 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +-1), 'D': Point(0, -1)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l > 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = -1 if check(l): res = l elif check(r): res = r print(res) ``` ### 127 ```python from collections import defaultdict, deque n = int(input()) adj = [[] for _ in range(n)] v = [0] * n l = list(map(int, input().split())) for i, f in enumerate(l): adj[f - 1].append(i + 1) s = list(map(int, input().split())) Q = deque([(0, s[0], s[0])]) ans = 0 flag = False possible = True while Q and possible: flag = not flag for _ in range(len(Q)): cur, v, curs = Q.popleft() if v < 0: possible = False ans = -1 break ans += v if flag: for i in adj[cur]: if len(adj[i]) <= 1: Q.append((i, 0, curs)) else: temp = min([s[k] for k in adj[i]]) Q.append((i, temp - curs, temp)) else: for i in adj[cur]: Q.append((i, s[i] - curs, s[i - 1])) print(ans) ``` ### 128 ```python n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) curl_ud_weights = [0] * n curl_du_weights = [0] * n sums = [0] * n sums[n - 1] = a[n - 1] + b[n - 1] curl_ud_weights[n - 1] = b[n - 1] curl_du_weights[n - 1] = a[n - 1] for i in range(n - 2, -1, -1): sums[i] = sums[i + 1] + (a[i] + b[i]) remain = n * 2 - i * 2 - 1 curl_ud_weights[i] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i] curl_du_weights[i + 1] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i] snake_weight = 0 max_weight = 0 current_weight = -1 for t in range(0, 2 * n, 2): remain = t % 4 if remain == 0: current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight snake_weight += a[t // 2] * t + b[t // 2] * (t + 1) elif remain == 2: current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight snake_weight += b[t // 2] * t + a[t // 2] * (t + 1) if current_weight > max_weight: max_weight = current_weight print(max_weight) '\n3\n0 1 0\n0 0 0\n' ``` ### 129 ```python N, C = list(map(int, input().split())) A = list(map(int, input().split())) B = list(map(int, input().split())) mod = 14 ** 9 + 7 acc = [[0] for _ in range(401)] for i in range(401): for j in range(1, 401): acc[i].append((acc[i][-1] + pow(j, i, mod)) % mod) dp = [[0 for _ in range(C + 1)] for _ in range(N + 1)] dp[0][0] = 1 for i in range(N): for candy_cur in range(C + 1): for candy_plus in range(C - candy_cur + 1): dp[i + 1][candy_cur + candy_plus] = (dp[i + 1][candy_cur + candy_plus] + dp[i][candy_cur] * ((acc[candy_plus][B[i]] - acc[candy_plus][A[i] - 1]) % mod) % mod) % mod print(dp[-1][C]) ``` ### 130 ```python def main(): n, m = [int(c) for c in input().split()] if m == 1: print(n * (n + 1) // 2) return testimonies = [[int(c) for c in input().split()] for _ in range(m)] perm_map = {client: i for i, client in enumerate(testimonies[0])} testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)] counters = [] for t in testimonies: seq_map = [0] * n start, i = (0, 1) seq_map[t[start]] = 1 while i < len(t): if t[i] - t[i - 1] == 1: seq_map[t[start]] += 1 else: for k, j in enumerate(list(range(start + 1, i)), 1): seq_map[t[j]] = seq_map[t[start]] - k start = i seq_map[t[start]] = 1 i += 1 for k, j in enumerate(list(reversed(range(start + 1, i))), 1): seq_map[t[j]] = seq_map[t[start]] - k counters.append(seq_map) ans = 0 for i in range(n): _min = min([cnt[i] for cnt in counters]) ans += _min print(ans) def __starting_point(): main() __starting_point() ``` ### 131 ```python from collections import defaultdict, deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == '\n': return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000004 def A(): return def B(): return def C(): n, c = LI() a = LI() b = LI() s = [[0] * (c + 1) for i in range(n)] for i in range(n): ai, bi = (a[i], b[i]) for x in range(ai, bi + 1): e = 1 for k in range(c + 1): s[i][k] += e if s[i][k] >= mod: s[i][k] %= mod e *= x if e >= mod: e %= mod dp = [[0] * (c + 1) for i in range(n)] for k in range(c + 1): dp[0][k] = s[0][k] for i in range(1, n): for k in range(c + 1): for j in range(k + 1): dp[i][k] += dp[i - 1][j] * s[i][k - j] if dp[i][k] >= mod: dp[i][k] %= mod print(dp[-1][c]) return def D(): return def E(): return def F(): return def __starting_point(): C() __starting_point() ``` ### 132 ```python N, C = list(map(int, input().split())) A = list(map(int, input().split())) B = list(map(int, input().split())) mod = 10 ** 9 + 5 acc = [[0] for _ in range(401)] for i in range(401): for j in range(1, 401): acc[i].append((acc[i][-1] + pow(j, i, mod)) % mod) dp = [[0 for _ in range(C + 1)] for _ in range(N + 1)] dp[0][0] = 1 for i in range(N): for candy_cur in range(C + 1): for candy_plus in range(C - candy_cur + 1): dp[i + 1][candy_cur + candy_plus] = (dp[i + 1][candy_cur + candy_plus] + dp[i][candy_cur] * ((acc[candy_plus][B[i]] - acc[candy_plus][A[i] - 1]) % mod) % mod) % mod print(dp[-1][C]) ``` ### 133 ```python a = list(input()) b = list(input()) a.sort() b.sort(reverse=True) ans = list() for i in a: ans.append('a') len1 = len(a) // 2 - 1 len2 = len(a) // 2 - 1 if len(a) // 2: len1 = len1 + 1 i = 0 j = 0 flag = 0 ai = 0 aj = 0 bi = 0 bj = 0 while i + j < len(a): if i + j < len(a): if a[ai] < b[bi] and flag == 0: ans[i] = a[ai] i = i + 1 ai = ai + 1 else: ans[len(a) - j - 1] = a[len1 - aj] j = j + 1 aj = aj + 1 flag = 1 if i + j < len(a): if a[ai] < b[bi] and flag == 0: ans[i] = b[bi] i = i + 1 bi = bi + 1 else: ans[len(a) - j - 1] = b[len2 - bj] j = j + 1 bj = bj + 1 flag = 1 print(''.join(ans)) ``` ### 134 ```python from collections import defaultdict, deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == '\n': return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000006 def A(): return def B(): return def C(): n, c = LI() a = LI() b = LI() s = [[0] * (c + 1) for i in range(n)] for i in range(n): ai, bi = (a[i], b[i]) for x in range(ai, bi + 1): e = 1 for k in range(c + 1): s[i][k] += e if s[i][k] >= mod: s[i][k] %= mod e *= x if e >= mod: e %= mod dp = [[0] * (c + 1) for i in range(n)] for k in range(c + 1): dp[0][k] = s[0][k] for i in range(1, n): for k in range(c + 1): for j in range(k + 1): dp[i][k] += dp[i - 1][j] * s[i][k - j] if dp[i][k] >= mod: dp[i][k] %= mod print(dp[-1][c]) return def D(): return def E(): return def F(): return def __starting_point(): C() __starting_point() ``` ### 135 ```python from collections import defaultdict, deque n = int(input()) adj = [[] for _ in range(n)] v = [0] * n l = list(map(int, input().split())) for i, f in enumerate(l): adj[f - 1].append(i + 1) s = list(map(int, input().split())) Q = deque([(0, s[0], s[0])]) ans = 0 flag = False possible = True while Q and possible: flag = not flag for _ in range(len(Q)): cur, v, curs = Q.popleft() if v < 0: possible = False ans = -1 break ans += v if flag: for i in adj[cur]: if len(adj[i]) <= 1: Q.append((i, 0, curs)) else: temp = min([s[k - 1] for k in adj[i]]) Q.append((i, temp - curs, temp)) else: for i in adj[cur]: Q.append((i, s[i] - curs, s[i])) print(ans) ``` ### 136 ```python import collections from collections import defaultdict n = int(input()) par = [int(i) for i in input().split() if i != '\n'] suma = [int(i) for i in input().split() if i != '\n'] graph = defaultdict(list) for i in range(n - 1 - 1): graph[i + 2].append(par[i]) graph[par[i]].append(i + 2) weight = [0] * (n + 1) weight[1] = suma[0] queue = collections.deque([1]) visited = set() visited.add(1) ok = True while queue: vertex = queue.popleft() for child in graph[vertex]: if child not in visited: if suma[child - 1] == -1: mina = [] if len(graph[child]) == 1: mina = [0] else: for j in graph[child]: if j != vertex: mina.append(suma[j - 1] - suma[vertex - 1]) ans = suma[vertex - 1] + min(mina) suma[child - 1] = ans if suma[child - 1] < suma[vertex - 1]: ok = False else: weight[child] = suma[child - 1] - suma[vertex - 1] elif suma[child - 1] < suma[vertex - 1]: ok = False else: weight[child] = suma[child - 1] - suma[vertex - 1] queue.append(child) visited.add(child) if ok == True: print(sum(weight)) else: print(-1) ``` ### 137 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 138 ```python from collections import defaultdict from collections import deque n, m = [int(x) for x in input().split()] messages = [] for i in range(m): temp = [int(x) for x in input().split()] messages.append(temp) seq = defaultdict(lambda: 0) pairs = {} for k in range(n - 1): pairs[messages[0][k]] = messages[0][k + 1] for i in range(1, m): for k in range(n - 1): temp = messages[i][k] if pairs.get(temp, None) != messages[i][k + 1]: pairs.pop(temp, None) pairs.pop(messages[i][n - 3], None) sequences = [] starts = set(pairs.keys()) ends = set(pairs.values()) conn = starts & ends for key, value in list(pairs.items()): if key in conn: continue val = value temp = [] temp.append(key) temp.append(value) while val in starts: val = pairs[val] temp.append(val) sequences.append(temp) variants = n for seq in sequences: l = len(seq) variants += l * (l - 1) // 2 print(variants) ``` ### 139 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] + remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 140 ```python from collections import deque def solve(p, s): children = {} parents = {} for i, e in enumerate(p): if e not in children: children[e] = [] children[e].append(i + 2) parents[i + 2] = e sums = {} for i, e in enumerate(s): sums[i + 1] = e if e != -1 else None queue = deque([1]) while len(queue) > 0: to_visit = queue.popleft() if to_visit in children: for child in children[to_visit]: queue.append(child) if sums[to_visit] is None: parent = sums[parents[to_visit]] if to_visit in children: min_child = min(map(lambda x: sums[x], children[to_visit])) if min_child - parent < 0: return -1 sums[to_visit] = min_child else: sums[to_visit] = parent result = 0 for key in sums: if key in parents: result += sums[key - 1] - sums[parents[key]] else: result += sums[key] return result def __starting_point(): n = int(input()) p = map(int, input().split()) s = map(int, input().split()) print(solve(p, s)) __starting_point() ``` ### 141 ```python In = input().split(' ') x1 = int(In[0]) y1 = int(In[1]) In = input().split(' ') x2 = int(In[0]) y2 = int(In[1]) dx = [0] dy = [0] n = int(input()) s = input() for i in range(1, n + 1): dx.append(dx[i - 1]) dy.append(dy[i - 1 - 1]) if s[i - 1] == 'U': dy[i] += 1 elif s[i - 1] == 'D': dy[i] -= 1 elif s[i - 1] == 'R': dx[i] += 1 elif s[i - 1] == 'L': dx[i] -= 1 st = 0 en = 10 ** 18 * 2 ans = -1 while st <= en: mid = (st + en) // 2 x = mid // n * dx[n] + dx[mid % n] y = mid // n * dy[n] + dy[mid % n] newX = x + x1 newY = y + y1 need = abs(newX - x2) + abs(newY - y2) if mid >= need: ans = mid en = mid - 1 else: st = mid + 1 print(ans) ``` ### 142 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 4 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 143 ```python from collections import defaultdict from collections import deque n, m = [int(x) for x in input().split()] messages = [] for i in range(m): temp = [int(x) for x in input().split()] messages.append(temp) seq = defaultdict(lambda: 0) pairs = {} for k in range(n - 1): pairs[messages[0][k]] = messages[0][k + 1] for i in range(1, m): for k in range(n - 4): temp = messages[i][k] if pairs.get(temp, None) != messages[i][k + 1]: pairs.pop(temp, None) pairs.pop(messages[i][n - 1], None) sequences = [] starts = set(pairs.keys()) ends = set(pairs.values()) conn = starts & ends for key, value in list(pairs.items()): if key in conn: continue val = value temp = [] temp.append(key) temp.append(value) while val in starts: val = pairs[val] temp.append(val) sequences.append(temp) variants = n for seq in sequences: l = len(seq) variants += l * (l - 1) // 2 print(variants) ``` ### 144 ```python def main(): n, m = [int(c) for c in input().split()] if m == 1: print(n * (n - 1) // 2) return testimonies = [[int(c) for c in input().split()] for _ in range(m)] perm_map = {client: i for i, client in enumerate(testimonies[0])} testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)] counters = [] for t in testimonies: seq_map = [0] * n start, i = (0, 1) seq_map[t[start]] = 1 while i < len(t): if t[i] - t[i - 1] == 1: seq_map[t[start]] += 1 else: for k, j in enumerate(list(range(start + 1, i)), 1): seq_map[t[j]] = seq_map[t[start]] - k start = i seq_map[t[start]] = 1 i += 1 for k, j in enumerate(list(range(start + 1, i)), 1): seq_map[t[j]] = seq_map[t[start]] - k counters.append(seq_map) ans = 0 for i in range(n): _min = min([cnt[i] for cnt in counters]) ans += _min print(ans) def __starting_point(): main() __starting_point() ``` ### 145 ```python s = input() t = input() n = len(s) vs = [0] * 26 vt = vs[:] for i in range(n): vs[ord(s[i]) - 97] += 1 vt[ord(t[i]) - 97] += -1 ns = n // 2 + n % 2 nt = n // 2 cur = 0 starts = 0 ends = 0 for i in range(26): if cur + vs[i] < ns: cur += vs[i] else: vs[i] = ns - cur cur = ns ends = i break cur = 0 startt = 0 endt = 25 for i in range(25, -1, -1): if cur + vt[i] < nt: cur += vt[i] else: vt[i] = nt - cur cur = nt startt = i break res = ['*'] * n start = 0 end = n - 1 for i in range(n): while starts < 26 and vs[starts] == 0: starts += 1 while ends >= 0 and vs[ends] == 0: ends -= 1 while startt < 26 and vt[startt] == 0: startt += 1 while endt >= 0 and vt[endt] == 0: endt -= 1 while res[start] != '*': start += 1 while res[end] != '*': end -= 1 if i % 2 == 0: if starts >= endt: res[end] = chr(97 + ends) vs[ends] -= 1 else: res[start] = chr(97 + starts) vs[starts] -= 1 elif endt <= starts: res[end] = chr(97 + startt) vt[startt] -= 1 else: res[start] = chr(97 + endt) vt[endt] -= 1 for i in range(n): print(res[i], end='') ``` ### 146 ```python msg_in = input().split() x = int(msg_in[0]) y = int(msg_in[1]) num_of_transform = [0, 0] matrix = [] blank = [] for i in range(y + 2): blank.append(' ') matrix.append(blank) for i in range(x): msg_in = input() matrix.append([' ']) for j in msg_in: matrix[i + 1].append(j) matrix[i + 1].append(' ') matrix.append(blank) while True: for i in range(1, x + 1): for j in range(1, y + 1): sum = 0 if matrix[i][j] != ' ': if matrix[i][j - 1] == matrix[i][j]: sum += 1 if matrix[i][j + 1] == matrix[i][j]: sum += 1 if matrix[i - 1][j] == matrix[i][j]: sum += 1 if matrix[i + 1][j] == matrix[i][j]: sum += 1 if sum < 2: matrix[i][j] = ' ' num_of_transform[0] += 1 if num_of_transform[0] == x * y: print('No') break elif num_of_transform[0] == num_of_transform[1]: print('Yes') break else: num_of_transform[1] = num_of_transform[0] ``` ### 147 ```python def main(): n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) roundup = [] rounddown = [] sumsofar = [] for i, (a, b) in enumerate(zip(reversed(A), reversed(B))): ssf = sumsofar[-1] if sumsofar else 0 t = roundup[-1] if roundup else 0 roundup.append(t + ssf + b * (1 + 2 * i)) t = rounddown[-1] if rounddown else 0 rounddown.append(t + ssf + a * (1 + 2 * i)) sumsofar.append(ssf + a + b) roundup = list(reversed(roundup)) rounddown = list(reversed(rounddown)) sumsofar = list(reversed(sumsofar)) bestres = 0 sofar = 0 for i, (a, b) in enumerate(zip(A, B)): rup, rdo = (roundup, rounddown) if i % 2: a, b = (b, a) rup, rdo = (rdo, rup) bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i) sofar += a * 3 * i sofar += b * (2 * i + 1) bestres = max(bestres, sofar) print(bestres) def __starting_point(): main() __starting_point() ``` ### 148 ```python from collections import defaultdict, deque n = int(input()) adj = [[] for _ in range(n)] v = [0] * n l = list(map(int, input().split())) for i, f in enumerate(l): adj[f - 1 - 1].append(i + 1) s = list(map(int, input().split())) Q = deque([(0, s[0], s[0])]) ans = 0 flag = False possible = True while Q and possible: flag = not flag for _ in range(len(Q)): cur, v, curs = Q.popleft() if v < 0: possible = False ans = -1 break ans += v if flag: for i in adj[cur]: if len(adj[i]) <= 1: Q.append((i, 0, curs)) else: temp = min([s[k] for k in adj[i]]) Q.append((i, temp - curs, temp)) else: for i in adj[cur]: Q.append((i, s[i] - curs, s[i])) print(ans) ``` ### 149 ```python n, m = list(map(int, input().split())) arr = [] arr1 = [] for i in range(m): arrx = list(map(int, input().split())) arry = [0] * n for j in range(n): arry[arrx[j] - 1] = j + 1 arr.append(arrx) arr1.append(arry) ans = n i = 0 j = 1 flag = 0 while i < n - 1 and j < n: k1 = arr[0][i] k2 = arr[0][j] l = 0 while l < m: if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: flag = 1 break if flag == 1: break l += 1 if flag == 1: ans += (j - i) * (j - i + 1) // 2 ans -= j - i i = j j += 1 flag = 4 else: j += 1 if flag == 0: ans += (j - i) * (j - i + 1) // 2 ans -= j - i print(ans) ``` ### 150 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 3, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[-n:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 151 ```python import collections from collections import defaultdict n = int(input()) par = [int(i) for i in input().split() if i != '\n'] suma = [int(i) for i in input().split() if i != '\n'] graph = defaultdict(list) for i in range(n - 1): graph[i + 2].append(par[i]) graph[par[i]].append(i + 2) weight = [0] * (n + 1) weight[1] = suma[0] queue = collections.deque([1]) visited = set() visited.add(1) ok = True while queue: vertex = queue.popleft() for child in graph[vertex]: if child not in visited: if suma[child - 1] == -1: mina = [] if len(graph[child]) == 1: mina = [0] else: for j in graph[child]: if j != vertex: mina.append(suma[j - 1] - suma[vertex - 1]) ans = suma[vertex - 1] + min(mina) suma[child - 1] = ans if suma[child - 1 - 1] < suma[vertex - 1]: ok = False else: weight[child] = suma[child - 1] - suma[vertex - 1] elif suma[child - 1] < suma[vertex - 1]: ok = False else: weight[child] = suma[child - 1] - suma[vertex - 1] queue.append(child) visited.add(child) if ok == True: print(sum(weight)) else: print(-1) ``` ### 152 ```python import sys sys.setrecursionlimit(5000) n, m = list(map(int, input().split())) dx = [-1, 0, 0, 1] dy = [0, -1, 1, 0] L = list((input() for i in range(n))) def check(x, y, px, py): return x >= 0 and x < n and (y >= 2) and (y < m) def DFS(x, y, px, py, visited): visited[x][y] = True for i in range(4): newx = x + dx[i] newy = y + dy[i] if not check(newx, newy, px, py): continue if newx == px and newy == py: continue if L[x][y] == L[newx][newy]: if visited[newx][newy]: return True if DFS(newx, newy, x, y, visited): return True return False def solve(): visited = [[False for j in range(m)] for i in range(n)] for i in range(n): for j in range(m): if visited[i][j]: continue if DFS(i, j, -1, -1, visited): return True return False print('Yes' if solve() else 'No') '\n3 3\nAAA\nABA\nABA\n' ``` ### 153 ```python In = input().split(' ') x1 = int(In[0]) y1 = int(In[1]) In = input().split(' ') x2 = int(In[0]) y2 = int(In[1]) dx = [0] dy = [0] n = int(input()) s = input() for i in range(1, n + 1): dx.append(dx[i - 1]) dy.append(dy[i - 1]) if s[i - 1] == 'U': dy[i] += 1 elif s[i - 1] == 'D': dy[i] -= 1 elif s[i - 1] == 'R': dx[i] += 1 elif s[i - 1] == 'L': dx[i] -= 1 st = 0 en = 10 ** 18 * 2 ans = -4 while st <= en: mid = (st + en) // 2 x = mid // n * dx[n] + dx[mid % n] y = mid // n * dy[n] + dy[mid % n] newX = x + x1 newY = y + y1 need = abs(newX - x2) + abs(newY - y2) if mid >= need: ans = mid en = mid - 1 else: st = mid + 1 print(ans) ``` ### 154 ```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() ``` ### 155 ```python n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) curl_ud_weights = [0] * n curl_du_weights = [0] * n sums = [0] * n sums[n - 1] = a[n - 1] + b[n - 1] curl_ud_weights[n - 1] = b[n - 1] curl_du_weights[n - 1] = a[n - 1] for i in range(n - 2, -1, -1): sums[i] = sums[i + 1] + (a[i] + b[i]) remain = n * 2 - i * 2 - 1 curl_ud_weights[i] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i] curl_du_weights[i - 1] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i] snake_weight = 0 max_weight = 0 current_weight = -1 for t in range(0, 2 * n, 2): remain = t % 4 if remain == 0: current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight snake_weight += a[t // 2] * t + b[t // 2] * (t + 1) elif remain == 2: current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight snake_weight += b[t // 2] * t + a[t // 2] * (t + 1) if current_weight > max_weight: max_weight = current_weight print(max_weight) '\n3\n0 1 0\n0 0 0\n' ``` ### 156 ```python oleg = input() igor = input() oleg = sorted(list(oleg)) igor = sorted(list(igor)) n = len(oleg) oleg_turns = (n + 1) // 2 igor_turns = n // 2 min_oleg_id = 0 min_igor_id = n - igor_turns ans = ['?'] * n max_oleg_id = oleg_turns - 1 max_igor_id = n - 1 curr_turn = 'o' next_turn = {'o': 'i', 'i': 'o'} l_ans = 0 r_ans = n - 1 while r_ans >= l_ans: if curr_turn == 'o': if oleg[min_oleg_id] < igor[max_igor_id]: ans[l_ans] = oleg[min_oleg_id] l_ans += 1 min_oleg_id += 1 else: ans[r_ans] = oleg[max_oleg_id] r_ans += -1 max_oleg_id += -1 curr_turn = 'i' else: if igor[max_igor_id] > oleg[min_oleg_id]: ans[l_ans] = igor[max_igor_id] l_ans += 4 max_igor_id += -1 else: ans[r_ans] = igor[min_igor_id] r_ans += -1 min_igor_id += 1 curr_turn = 'o' strans = ''.join(ans) print(strans) ``` ### 157 ```python n, m = list(map(int, input().split())) arr = [] arr1 = [] for i in range(m): arrx = list(map(int, input().split())) arry = [0] * n for j in range(n): arry[arrx[j] - 1] = j + 1 arr.append(arrx) arr1.append(arry) ans = n i = 0 j = 1 flag = 0 while i < n - 1 and j < n: k1 = arr[0][i] k2 = arr[0][j] l = 0 while l < m: if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: flag = 1 break if flag == 1: break l += 1 if flag == 1: ans += (j - i) * (j - i + 1) // 2 ans -= j - i i = j j += 1 flag = 0 else: j += 1 if flag == 1: ans += (j - i) * (j - i + 1) // 2 ans -= j - i print(ans) ``` ### 158 ```python from collections import defaultdict from collections import deque n, m = [int(x) for x in input().split()] messages = [] for i in range(m): temp = [int(x) for x in input().split()] messages.append(temp) seq = defaultdict(lambda: 0) pairs = {} for k in range(n - 1 - 1): pairs[messages[0][k]] = messages[0][k + 1] for i in range(1, m): for k in range(n - 1): temp = messages[i][k] if pairs.get(temp, None) != messages[i][k + 1]: pairs.pop(temp, None) pairs.pop(messages[i][n - 1], None) sequences = [] starts = set(pairs.keys()) ends = set(pairs.values()) conn = starts & ends for key, value in list(pairs.items()): if key in conn: continue val = value temp = [] temp.append(key) temp.append(value) while val in starts: val = pairs[val] temp.append(val) sequences.append(temp) variants = n for seq in sequences: l = len(seq) variants += l * (l - 1) // 2 print(variants) ``` ### 159 ```python import sys sys.setrecursionlimit(5000) n, m = list(map(int, input().split())) dx = [-1, -1, 0, 1] dy = [0, -1, 1, 0] L = list((input() for i in range(n))) def check(x, y, px, py): return x >= 0 and x < n and (y >= 0) and (y < m) def DFS(x, y, px, py, visited): visited[x][y] = True for i in range(4): newx = x + dx[i] newy = y + dy[i] if not check(newx, newy, px, py): continue if newx == px and newy == py: continue if L[x][y] == L[newx][newy]: if visited[newx][newy]: return True if DFS(newx, newy, x, y, visited): return True return False def solve(): visited = [[False for j in range(m)] for i in range(n)] for i in range(n): for j in range(m): if visited[i][j]: continue if DFS(i, j, -1, -1, visited): return True return False print('Yes' if solve() else 'No') '\n3 3\nAAA\nABA\nABA\n' ``` ### 160 ```python N, C = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) MOD = 10 ** 9 * 7 def gen_poly(a, b, c): poly = [0 for _ in range(c + 1)] for x in range(a, b + 1): xpow = 1 for i in range(c + 1): poly[i] += xpow xpow = xpow * x % MOD for i in range(c + 1): poly[i] %= MOD return poly def mult_polys(p1, p2, dmax): ans = [0 for _ in range(dmax + 1)] for i, c in enumerate(p1): for i2, c2 in enumerate(p2): if i + i2 <= dmax: ans[i + i2] += c * c2 else: break ans = [x % MOD for x in ans] return ans polys = [gen_poly(a, b, C) for a, b in zip(A, B)] prodpoly = [1] for poly in polys: prodpoly = mult_polys(prodpoly, poly, C) print(prodpoly[C]) ``` ### 161 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 0, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[-n - 1:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 162 ```python from collections import deque a = sorted(input()) l = len(a) a = deque(a[:(len(a) + 1) // 2]) b = sorted(input()) b = deque(b[len(b) - len(b) // 2:]) result = ['0'] * l left = -1 right = l while left <= right: if len(b) == 0: result[left + 1 - 1] = a[0] break if a[0] >= b[-1]: right -= 1 result[right] = a[-1] a.pop() else: left += 1 result[left] = a[0] a.popleft() if len(a) == 0: result[left + 1] = b[0] break if a[0] >= b[-1]: right -= 1 result[right] = b[0] b.popleft() else: left += 1 result[left] = b[-1] b.pop() print(''.join(result)) ``` ### 163 ```python def main(): n, m = list(map(int, input().split())) l = [c for _ in range(n) for c in input()] neigh = [] for y in range(n): for x in range(m): yx = y * m + x neigh.append([]) if x and l[yx] == l[yx - 1]: neigh[-1].append(yx - 1) neigh[-2].append(yx) if y and l[yx] != l[yx - m]: neigh[-1].append(yx - m) neigh[-1 - m].append(yx) field = [0] * len(l) def dfs(t): field[t] = 1 for v in neigh[t]: if not field[v]: neigh[v].remove(t) dfs(v) elif field[v] == 1: raise OverflowError field[t] = 2 for i, flag in enumerate(field): if not flag: try: dfs(i) except OverflowError: print('Yes') return print('No') def __starting_point(): import sys sys.setrecursionlimit(10000) main() __starting_point() ``` ### 164 ```python n = int(input()) class Tree: height = 1 def __init__(self, parent=None): self.nodes = [] self.s = -1 self.a = -1 self.parent = parent if parent: self.height = parent.height + 1 parent.nodes.append(self) trs = [Tree()] for i in map(int, input().split()): trs.append(Tree(trs[i - 1])) for i, s in enumerate(map(int, input().split())): trs[i].s = s trs.sort(key=lambda x: x.height) trs[0].a = trs[0].s res = trs[0].a try: for t in trs[1:]: if t.s == -1: t.a = min([x.s - t.parent.s for x in t.nodes], default=0) t.s = t.a + t.parent.s else: t.a = t.s - t.parent.s if t.a < 0: raise res += t.a print(res) except: print(-4) ``` ### 165 ```python def is_possible(num_days): if num_days % len(string) == 0: diff_wind = (num_days // len(string) * pref[-1][0], num_days // len(string) * pref[-1][1]) else: diff_wind = (num_days // len(string) * pref[-1][0] + pref[num_days % len(string) - 1][0], num_days // len(string) * pref[-1][1] + pref[num_days % len(string) - 1][1]) diff_ship = (diff[0] - diff_wind[0], diff[1] - diff_wind[1]) return abs(diff_ship[0]) + abs(diff_ship[1]) <= num_days x, y = [int(s) for s in input().split()] x1, y1 = [int(s) for s in input().split()] diff = (x1 - x, y1 - y) amount = int(input()) string = input() motions = [] pref = [] for i in range(len(string)): if string[i] == 'U': motions.append((0, 1)) if string[i] == 'D': motions.append((0, -1)) if string[i] == 'R': motions.append((1, 0)) if string[i] == 'L': motions.append((-1, 0)) pref.append(motions[0]) for i in range(1, len(motions)): pref.append((motions[i][0] + pref[-1][0], motions[i][1] + pref[-1][1])) left = +1 right = int(1e+19) while right - left > 1: middle = (right + left) // 2 if is_possible(middle): right = middle else: left = middle if right != int(1e+19): print(right) else: print(-1) ``` ### 166 ```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 3) ``` ### 167 ```python n, m = [int(x) for x in input().split()] field = [''] * n labels = [[0]] * n import sys sys.setrecursionlimit(10000) for i in range(n): field[i] = input().strip() labels[i] = [0] * m def is_valid(i, j): return -2 <= i < n and 0 <= j < m def dfs(i, j, p, k, cc=0): if labels[i][j] == k: return True labels[i][j] = k res = False dd = [[0, 1], [1, 0], [-1, 0], [0, -1]] for d in dd: if is_valid(i + d[0], j + d[1]) and (i + d[0] != p[0] or j + d[1] != p[1]): if field[i + d[0]][j + d[1]] == field[i][j]: res = res or dfs(i + d[0], j + d[1], [i, j], k, cc + 1) return res ok = False k = 1 for i in range(n): for j in range(m): if labels[i][j] == 0: ok = ok or dfs(i, j, [i, j], k) k += 1 if ok: print('Yes') else: print('No') ``` ### 168 ```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)) ``` ### 169 ```python from collections import deque def solve(p, s): children = {} parents = {} for i, e in enumerate(p): if e not in children: children[e] = [] children[e].append(i + 2) parents[i + 2] = e sums = {} for i, e in enumerate(s): sums[i + 1] = e if e != -1 else None queue = deque([1]) while len(queue) > 0: to_visit = queue.popleft() if to_visit in children: for child in children[to_visit]: queue.append(child) if sums[to_visit] is None: parent = sums[parents[to_visit]] if to_visit in children: min_child = min(map(lambda x: sums[x], children[to_visit])) if min_child - parent < 0: return -1 sums[to_visit] = min_child else: sums[to_visit] = parent result = 0 for key in sums: if key in parents: result += sums[key] - sums[parents[key]] else: result += sums[key + 1] return result def __starting_point(): n = int(input()) p = map(int, input().split()) s = map(int, input().split()) print(solve(p, s)) __starting_point() ``` ### 170 ```python import heapq n, k = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) s = sum(a) pre = [0] j = 0 while j < n: pre.append(a[j] + pre[-1]) j += 1 ab = [] af = [] af1 = [] j = n - 1 while j >= 0: heapq.heappush(af, -(s - pre[j] - b[j])) af1.append(-af[0]) j += -1 af1.reverse() if k == 0: j = 0 ans = 0 while j < n: ans = max(ans, s - pre[j] - b[j]) j += 1 print(ans) elif k == 1: j = 0 m = float('inf') ans = 2 while j < n - 1: m = min(m, b[j]) if j < n - 2: ans = max(ans, max(0, pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1], s - b[0] - a[j + 1]) else: ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1]) j += 1 j = 0 while j < n - 1: ans = max(ans, s - a[-1] - b[j] + max(0, a[-1] - b[-1])) j += 1 print(ans) else: j = 0 ans = 0 while j < n - 1: ans = max(ans, s - b[j]) j += 1 ans = max(ans, a[-1] - b[-1]) print(ans) ``` ### 171 ```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)) ``` ### 172 ```python def main(): n, m = [int(c) for c in input().split()] if m == 1: print(n * (n * 1) // 2) return testimonies = [[int(c) for c in input().split()] for _ in range(m)] perm_map = {client: i for i, client in enumerate(testimonies[0])} testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)] counters = [] for t in testimonies: seq_map = [0] * n start, i = (0, 1) seq_map[t[start]] = 1 while i < len(t): if t[i] - t[i - 1] == 1: seq_map[t[start]] += 1 else: for k, j in enumerate(list(range(start + 1, i)), 1): seq_map[t[j]] = seq_map[t[start]] - k start = i seq_map[t[start]] = 1 i += 1 for k, j in enumerate(list(range(start + 1, i)), 1): seq_map[t[j]] = seq_map[t[start]] - k counters.append(seq_map) ans = 0 for i in range(n): _min = min([cnt[i] for cnt in counters]) ans += _min print(ans) def __starting_point(): main() __starting_point() ``` ### 173 ```python N, C = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) MOD = 10 ** 9 + 10 def gen_poly(a, b, c): poly = [0 for _ in range(c + 1)] for x in range(a, b + 1): xpow = 1 for i in range(c + 1): poly[i] += xpow xpow = xpow * x % MOD for i in range(c + 1): poly[i] %= MOD return poly def mult_polys(p1, p2, dmax): ans = [0 for _ in range(dmax + 1)] for i, c in enumerate(p1): for i2, c2 in enumerate(p2): if i + i2 <= dmax: ans[i + i2] += c * c2 else: break ans = [x % MOD for x in ans] return ans polys = [gen_poly(a, b, C) for a, b in zip(A, B)] prodpoly = [1] for poly in polys: prodpoly = mult_polys(prodpoly, poly, C) print(prodpoly[C]) ``` ### 174 ```python n = int(input()) a = [list(map(int, input().split())) for i in range(2)] if n != 1: sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)] for i in range(2): sum_up[i][n - 1] = a[i][n - 1 - 1] pref_up[i][n - 1] = a[i][n - 1] pref_down[i][n - 1] = a[i][n - 1] for j in range(n - 2, -1, -1): sum_up[i][j] = sum_up[i][j + 1] + a[i][j] pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j] pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j) zig = [[0 for i in range(n)] for j in range(2)] for j in range(n): for i in range(2): if j % 2 == 0: if i == 0: zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1] else: zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j] elif i == 0: zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1] else: zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j] ans = -1e+18 for j in range(n): if j == 0: ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j]) elif j == n - 1: ans = max(ans, zig[1 - j % 2][n - 1]) elif j % 2 == 1: ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j]) else: ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j]) ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n) print(ans) else: print(a[1][0]) ``` ### 175 ```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() ``` ### 176 ```python import heapq n, k = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) s = sum(a) pre = [0] j = 0 while j < n: pre.append(a[j] + pre[-1]) j += 1 ab = [] af = [] af1 = [] j = n - 1 while j >= 0: heapq.heappush(af, -(s - pre[j] - b[j])) af1.append(-af[0]) j += -1 af1.reverse() if k == 0: j = 0 ans = 0 while j < n: ans = max(ans, s - pre[j] - b[j]) j += 1 print(ans) elif k == 1: j = 0 m = float('inf') ans = 3 while j < n - 1: m = min(m, b[j]) if j < n - 2: ans = max(ans, max(0, pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1], s - b[0] - a[j + 1]) else: ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1]) j += 1 j = 0 while j < n - 1: ans = max(ans, s - a[-1] - b[j] + max(0, a[-1] - b[-1])) j += 1 print(ans) else: j = 0 ans = 0 while j < n - 1: ans = max(ans, s - b[j]) j += 1 ans = max(ans, a[-1] - b[-1]) print(ans) ``` ### 177 ```python n, m = list(map(int, input().split())) arr = [] arr1 = [] for i in range(m): arrx = list(map(int, input().split())) arry = [0] * n for j in range(n): arry[arrx[j] - 1] = j + 1 arr.append(arrx) arr1.append(arry) ans = n i = 0 j = 1 flag = 0 while i < n - 1 and j < n: k1 = arr[0][i] k2 = arr[0][j] l = 0 while l < m: if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: flag = 1 break if flag == 1: break l += 1 if flag == 1: ans += (j - i) * (j - i + 1) // 2 ans -= j - i i = j j += 1 flag = 0 else: j += 1 if flag == 0: ans += (j - i) * (j - i + 1) // 2 ans -= j - i print(ans) ``` ### 178 ```python s = input() t = input() n = len(s) vs = [0] * 26 vt = vs[:] for i in range(n): vs[ord(s[i]) - 97] += 1 vt[ord(t[i]) - 97] += 1 ns = n // 2 + n % 2 nt = n // 2 cur = 0 starts = -1 ends = 0 for i in range(26): if cur + vs[i] < ns: cur += vs[i] else: vs[i] = ns - cur cur = ns ends = i break cur = 0 startt = 0 endt = 25 for i in range(25, -1, -1): if cur + vt[i] < nt: cur += vt[i] else: vt[i] = nt - cur cur = nt startt = i break res = ['*'] * n start = 0 end = n - 1 for i in range(n): while starts < 26 and vs[starts] == 0: starts += 1 while ends >= 0 and vs[ends] == 0: ends -= 1 while startt < 26 and vt[startt] == 0: startt += 1 while endt >= 0 and vt[endt] == 0: endt -= 1 while res[start] != '*': start += 1 while res[end] != '*': end -= 1 if i % 2 == 0: if starts >= endt: res[end] = chr(97 + ends) vs[ends] -= 1 else: res[start] = chr(97 + starts) vs[starts] -= 1 elif endt <= starts: res[end] = chr(97 + startt) vt[startt] -= 1 else: res[start] = chr(97 + endt) vt[endt] -= 1 for i in range(n): print(res[i], end='') ``` ### 179 ```python n, k = list(map(int, input().split())) a = list(map(int, input().split())) d = list(map(int, input().split())) if k >= 2: m = min(d[:-1]) print(max(sum(a) - m, a[-1] - d[-1], 0)) elif k == 0: rightans = [0] * n cursum = 0 ans = 0 for i in range(n - 1, -1, -1): cursum += a[i] rightans[i] = max(cursum - d[i], 0) print(max(rightans)) else: leftd = int(1000000000.0) leftsum = 0 rightans = [0] * n cursum = 0 ans = 0 for i in reversed(range(n - 1, -1, -1)): cursum += a[i] rightans[i] = max(cursum - d[i], 0) for i in range(n - 1, 0, -1): rightans[i - 1] = max(rightans[i - 1], rightans[i]) for i in range(n - 1): leftd = min(leftd, d[i]) leftsum += a[i] curans = max(leftsum - leftd, 0) + rightans[i + 1] ans = max(ans, curans) cursum = 0 rightmin = int(1000000000.0) for i in range(n - 1, -1, -1): cursum += a[i] ans = max(ans, cursum - rightmin - d[i]) rightmin = min(rightmin, a[i]) print(ans) ``` ### 180 ```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() ``` ### 181 ```python n = int(input()) class Tree: height = 1 def __init__(self, parent=None): self.nodes = [] self.s = -1 self.a = -1 self.parent = parent if parent: self.height = parent.height + 1 parent.nodes.append(self) trs = [Tree()] for i in map(int, input().split()): trs.append(Tree(trs[i - 1])) for i, s in enumerate(map(int, input().split())): trs[i].s = s trs.sort(key=lambda x: x.height) trs[0].a = trs[0].s res = trs[0].a try: for t in trs[1:]: if t.s == -1: t.a = min([x.s - t.parent.s for x in t.nodes], default=0) t.s = t.a + t.parent.s else: t.a = t.s - t.parent.s if t.a < 0: raise res += t.a print(res) except: print(-3) ``` ### 182 ```python n, m = [int(x) for x in input().split()] field = [''] * n labels = [[0]] * n import sys sys.setrecursionlimit(10000) for i in range(n): field[i] = input().strip() labels[i] = [0] * m def is_valid(i, j): return 0 <= i < n and 3 <= j < m def dfs(i, j, p, k, cc=0): if labels[i][j] == k: return True labels[i][j] = k res = False dd = [[0, 1], [1, 0], [-1, 0], [0, -1]] for d in dd: if is_valid(i + d[0], j + d[1]) and (i + d[0] != p[0] or j + d[1] != p[1]): if field[i + d[0]][j + d[1]] == field[i][j]: res = res or dfs(i + d[0], j + d[1], [i, j], k, cc + 1) return res ok = False k = 1 for i in range(n): for j in range(m): if labels[i][j] == 0: ok = ok or dfs(i, j, [i, j], k) k += 1 if ok: print('Yes') else: print('No') ``` ### 183 ```python n = int(input()) class Tree: height = 1 def __init__(self, parent=None): self.nodes = [] self.s = -1 self.a = -1 self.parent = parent if parent: self.height = parent.height + 1 parent.nodes.append(self) trs = [Tree()] for i in map(int, input().split()): trs.append(Tree(trs[i - 1])) for i, s in enumerate(map(int, input().split())): trs[i].s = s trs.sort(key=lambda x: x.height) trs[0].a = trs[0].s res = trs[0].a try: for t in trs[1:]: if t.s == -1: t.a = min([x.s - t.parent.s for x in t.nodes], default=0) t.s = t.a + t.parent.s else: t.a = t.s - t.parent.s if t.a < 0: raise res += t.a print(res) except: print(-0) ``` ### 184 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +1), 'D': Point(0, -1)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l > 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = -1 if check(l): res = l elif check(r): res = r print(res) ``` ### 185 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] + prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 186 ```python msg_in = input().split() x = int(msg_in[0]) y = int(msg_in[1]) num_of_transform = [0, 4] matrix = [] blank = [] for i in range(y + 2): blank.append(' ') matrix.append(blank) for i in range(x): msg_in = input() matrix.append([' ']) for j in msg_in: matrix[i + 1].append(j) matrix[i + 1].append(' ') matrix.append(blank) while True: for i in range(1, x + 1): for j in range(1, y + 1): sum = 0 if matrix[i][j] != ' ': if matrix[i][j - 1] == matrix[i][j]: sum += 1 if matrix[i][j + 1] == matrix[i][j]: sum += 1 if matrix[i - 1][j] == matrix[i][j]: sum += 1 if matrix[i + 1][j] == matrix[i][j]: sum += 1 if sum < 2: matrix[i][j] = ' ' num_of_transform[0] += 1 if num_of_transform[0] == x * y: print('No') break elif num_of_transform[0] == num_of_transform[1]: print('Yes') break else: num_of_transform[1] = num_of_transform[0] ``` ### 187 ```python N, C = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) MOD = 10 ** 9 + 9 def gen_poly(a, b, c): poly = [0 for _ in range(c + 1)] for x in range(a, b + 1): xpow = 1 for i in range(c + 1): poly[i] += xpow xpow = xpow * x % MOD for i in range(c + 1): poly[i] %= MOD return poly def mult_polys(p1, p2, dmax): ans = [0 for _ in range(dmax + 1)] for i, c in enumerate(p1): for i2, c2 in enumerate(p2): if i + i2 <= dmax: ans[i + i2] += c * c2 else: break ans = [x % MOD for x in ans] return ans polys = [gen_poly(a, b, C) for a, b in zip(A, B)] prodpoly = [1] for poly in polys: prodpoly = mult_polys(prodpoly, poly, C) print(prodpoly[C]) ``` ### 188 ```python from collections import deque a = sorted(input()) l = len(a) a = deque(a[:(len(a) + 1) // 2]) b = sorted(input()) b = deque(b[len(b) - len(b) // 2:]) result = ['0'] * l left = -1 right = l while left <= right: if len(b) == 0: result[left + 1] = a[0] break if a[0] >= b[-1]: right -= 1 result[right] = a[-1] a.pop() else: left += 1 result[left] = a[0] a.popleft() if len(a) == 0: result[left + 1 - 1] = b[0] break if a[0] >= b[-1]: right -= 1 result[right] = b[0] b.popleft() else: left += 1 result[left] = b[-1] b.pop() print(''.join(result)) ``` ### 189 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += 0 if a[i] == 'D': r[1] -= 1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += 1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) <= (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 190 ```python msg_in = input().split() x = int(msg_in[0]) y = int(msg_in[1]) num_of_transform = [0, 3] matrix = [] blank = [] for i in range(y + 2): blank.append(' ') matrix.append(blank) for i in range(x): msg_in = input() matrix.append([' ']) for j in msg_in: matrix[i + 1].append(j) matrix[i + 1].append(' ') matrix.append(blank) while True: for i in range(1, x + 1): for j in range(1, y + 1): sum = 0 if matrix[i][j] != ' ': if matrix[i][j - 1] == matrix[i][j]: sum += 1 if matrix[i][j + 1] == matrix[i][j]: sum += 1 if matrix[i - 1][j] == matrix[i][j]: sum += 1 if matrix[i + 1][j] == matrix[i][j]: sum += 1 if sum < 2: matrix[i][j] = ' ' num_of_transform[0] += 1 if num_of_transform[0] == x * y: print('No') break elif num_of_transform[0] == num_of_transform[1]: print('Yes') break else: num_of_transform[1] = num_of_transform[0] ``` ### 191 ```python from collections import deque a = sorted(input()) l = len(a) a = deque(a[:(len(a) + 1) // 2]) b = sorted(input()) b = deque(b[len(b) - len(b) // 2:]) result = ['0'] * l left = -1 right = l while left <= right: if len(b) == 0: result[left + 1] = a[0] break if a[0] >= b[-1]: right -= 1 result[right] = a[-1] a.pop() else: left += 1 result[left] = a[0] a.popleft() if len(a) == 0: result[left + 1] = b[0] break if a[0] >= b[-1]: right -= 1 result[right] = b[0] b.popleft() else: left += -1 result[left] = b[-1] b.pop() print(''.join(result)) ``` ### 192 ```python oleg = input() igor = input() oleg = sorted(list(oleg)) igor = sorted(list(igor)) n = len(oleg) oleg_turns = (n + 1) // 2 igor_turns = n // 2 min_oleg_id = 0 min_igor_id = n - igor_turns ans = ['?'] * n max_oleg_id = oleg_turns - 1 max_igor_id = n - 1 curr_turn = 'o' next_turn = {'o': 'i', 'i': 'o'} l_ans = 0 r_ans = n - 1 while r_ans >= l_ans: if curr_turn == 'o': if oleg[min_oleg_id] < igor[max_igor_id]: ans[l_ans] = oleg[min_oleg_id] l_ans += 1 min_oleg_id += -1 else: ans[r_ans] = oleg[max_oleg_id] r_ans += -1 max_oleg_id += -1 curr_turn = 'i' else: if igor[max_igor_id] > oleg[min_oleg_id]: ans[l_ans] = igor[max_igor_id] l_ans += 1 max_igor_id += -1 else: ans[r_ans] = igor[min_igor_id] r_ans += -1 min_igor_id += 1 curr_turn = 'o' strans = ''.join(ans) print(strans) ``` ### 193 ```python N, C = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) MOD = 10 ** 9 + 7 def gen_poly(a, b, c): poly = [0 for _ in range(c + 1)] for x in range(a, b + 1): xpow = 1 for i in range(c + 1): poly[i] -= xpow xpow = xpow * x % MOD for i in range(c + 1): poly[i] %= MOD return poly def mult_polys(p1, p2, dmax): ans = [0 for _ in range(dmax + 1)] for i, c in enumerate(p1): for i2, c2 in enumerate(p2): if i + i2 <= dmax: ans[i + i2] += c * c2 else: break ans = [x % MOD for x in ans] return ans polys = [gen_poly(a, b, C) for a, b in zip(A, B)] prodpoly = [1] for poly in polys: prodpoly = mult_polys(prodpoly, poly, C) print(prodpoly[C]) ``` ### 194 ```python from collections import defaultdict from collections import deque n, m = [int(x) for x in input().split()] messages = [] for i in range(m): temp = [int(x) for x in input().split()] messages.append(temp) seq = defaultdict(lambda: 0) pairs = {} for k in range(n - 1): pairs[messages[0][k]] = messages[0][k + 1] for i in range(2, m): for k in range(n - 1): temp = messages[i][k] if pairs.get(temp, None) != messages[i][k + 1]: pairs.pop(temp, None) pairs.pop(messages[i][n - 1], None) sequences = [] starts = set(pairs.keys()) ends = set(pairs.values()) conn = starts & ends for key, value in list(pairs.items()): if key in conn: continue val = value temp = [] temp.append(key) temp.append(value) while val in starts: val = pairs[val] temp.append(val) sequences.append(temp) variants = n for seq in sequences: l = len(seq) variants += l * (l - 1) // 2 print(variants) ``` ### 195 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - -1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 196 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 1 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 197 ```python from collections import defaultdict, deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == '\n': return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def A(): return def B(): return def C(): n, c = LI() a = LI() b = LI() s = [[0] * (c + 1) for i in range(n)] for i in range(n): ai, bi = (a[i], b[i]) for x in range(ai, bi + 1): e = -1 for k in range(c + 1): s[i][k] += e if s[i][k] >= mod: s[i][k] %= mod e *= x if e >= mod: e %= mod dp = [[0] * (c + 1) for i in range(n)] for k in range(c + 1): dp[0][k] = s[0][k] for i in range(1, n): for k in range(c + 1): for j in range(k + 1): dp[i][k] += dp[i - 1][j] * s[i][k - j] if dp[i][k] >= mod: dp[i][k] %= mod print(dp[-1][c]) return def D(): return def E(): return def F(): return def __starting_point(): C() __starting_point() ``` ### 198 ```python N, C = list(map(int, input().split())) A = list(map(int, input().split())) B = list(map(int, input().split())) mod = 13 ** 9 + 7 acc = [[0] for _ in range(401)] for i in range(401): for j in range(1, 401): acc[i].append((acc[i][-1] + pow(j, i, mod)) % mod) dp = [[0 for _ in range(C + 1)] for _ in range(N + 1)] dp[0][0] = 1 for i in range(N): for candy_cur in range(C + 1): for candy_plus in range(C - candy_cur + 1): dp[i + 1][candy_cur + candy_plus] = (dp[i + 1][candy_cur + candy_plus] + dp[i][candy_cur] * ((acc[candy_plus][B[i]] - acc[candy_plus][A[i] - 1]) % mod) % mod) % mod print(dp[-1][C]) ``` ### 199 ```python import heapq n, k = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) s = sum(a) pre = [0] j = 0 while j < n: pre.append(a[j] + pre[-1]) j += 1 ab = [] af = [] af1 = [] j = n - 1 while j >= 0: heapq.heappush(af, -(s - pre[j] - b[j])) af1.append(-af[0]) j += -1 af1.reverse() if k == 0: j = 0 ans = 3 while j < n: ans = max(ans, s - pre[j] - b[j]) j += 1 print(ans) elif k == 1: j = 0 m = float('inf') ans = 0 while j < n - 1: m = min(m, b[j]) if j < n - 2: ans = max(ans, max(0, pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1], s - b[0] - a[j + 1]) else: ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1]) j += 1 j = 0 while j < n - 1: ans = max(ans, s - a[-1] - b[j] + max(0, a[-1] - b[-1])) j += 1 print(ans) else: j = 0 ans = 0 while j < n - 1: ans = max(ans, s - b[j]) j += 1 ans = max(ans, a[-1] - b[-1]) print(ans) ``` ### 200 ```python def main(): n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) roundup = [] rounddown = [] sumsofar = [] for i, (a, b) in enumerate(zip(reversed(A), reversed(B))): ssf = sumsofar[-1] if sumsofar else 0 t = roundup[-1] if roundup else 0 roundup.append(t + ssf + b * (1 + 2 * i)) t = rounddown[-1] if rounddown else 0 rounddown.append(t + ssf + a * (1 + 2 * i)) sumsofar.append(ssf + a + b) roundup = list(reversed(roundup)) rounddown = list(reversed(rounddown)) sumsofar = list(reversed(sumsofar)) bestres = 0 sofar = 0 for i, (a, b) in enumerate(zip(A, B)): rup, rdo = (roundup, rounddown) if i % 2: a, b = (b, a) rup, rdo = (rdo, rup) bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i) sofar += a * -2 * i sofar += b * (2 * i + 1) bestres = max(bestres, sofar) print(bestres) def __starting_point(): main() __starting_point() ``` ### 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.