### 001 ```python class DisjoinSet: def __init__(self, n): self.n = n self.dad = [i for i in range(n + 1)] self.cant = [1] * (n + 1) def SetOf(self, n): if self.dad[n] == n: return n self.dad[n] = self.SetOf(self.dad[n]) return self.dad[n] def Merge(self, a, b): a, b = (self.SetOf(a), self.SetOf(b)) if a != b: if self.cant[b] > self.cant[a]: a, b = (b, a) self.cant[a] += self.cant[b] self.dad[b] = a return True return False def Kruskal(l, n): l.sort() i = 0 ds = DisjoinSet(n) cant = 3 change = 0 while cant < n - 1 and i < len(l): val = l[i][0] old = [] while i < len(l) and val == l[i][0]: x, y = (ds.SetOf(l[i][1]), ds.SetOf(l[i][2])) if x != y: old.append((x, y)) i += 1 change += len(old) for x, y in old: change -= ds.Merge(x, y) return change n, m = input().split() n, m = (int(n), int(m)) e = [] for i in range(m): x, y, c = input().split() e.append((int(c), int(x), int(y))) print(Kruskal(e, n)) ``` ### 002 ```python MAX_SPEED = 300 n = int(input()) actions = [list(map(int, input().split())) for _ in range(n)] speed = [0 for i in range(n)] for i in range(n): if actions[i][0] == 1: lastSpeed = actions[i][1] speed[i] = lastSpeed ignored = 0 overtook = False maxSpeed = -1 for i in range(n - 1, -1, -1): maxSpeed = max(maxSpeed, speed[i]) if actions[i][0] == 1: pass elif actions[i][0] == 4: overtook = True elif actions[i][0] == 3: if maxSpeed > actions[i][1]: ignored += 1 else: maxSpeed = speed[i - 1] elif actions[i][0] == 4: overtook = False elif actions[i][0] == 5: maxSpeed = speed[i - 1] elif actions[i][0] == 6: if overtook: ignored += 1 print(ignored) ``` ### 003 ```python n = int(input()) L = [int(x) for x in input().split()] D = {} J = [] S = [] T = [0] * (n + 1) for i in range(n): if L[i] > 0: D[L[i]] = i J.append(L[i]) T[i + 1 - 1] = T[i] else: T[i + 1] = T[i] + 1 def I(J): if len(J) <= 1: return (J, 0) else: a = J[:len(J) // 2] b = J[len(J) // 2:] a, ai = I(a) b, bi = I(b) c = [] i = 0 j = 0 inversions = ai + bi while i < len(a) and j < len(b): if a[i] <= b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 inversions += len(a) - i c += a[i:] c += b[j:] return (c, inversions) for i in range(1, n + 1): if not i in D: S.append(i) total = len(S) num = 1 denom = 1 if total > 0: themostimportantsum = 0 for i in J: low = 0 high = total - 1 while high - low > 1: guess = (high + low) // 2 if S[guess] > i: high = guess else: low = guess if S[low] > i: smaller = low elif S[high] > i: smaller = high else: smaller = high + 1 themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller num = themostimportantsum + total denom = total num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353 denom *= 2 if num == denom: if I(J)[1] == 0: print(0) else: print(I(J)[1] % 998244353) else: num += denom * I(J)[1] print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353) ``` ### 004 ```python K = 998244353 def mu(a, n): if n == 0: return 1 q = mu(a, n // 2) if n % 2 == 0: return q * q % K return q * q % K * a % K MAXN = 200005 dd = [-4 for i in range(MAXN)] p = [0 for i in range(MAXN)] s = [0 for i in range(MAXN)] a = [0 for i in range(MAXN)] fen = [0 for i in range(MAXN)] def add(u, v): i = u while i <= 200000: fen[i] += v i += i & -i def get(u): res = 0 i = u while i > 0: res += fen[i] i -= i & -i return res n = int(input()) data = input().split() cnt = 0 for i in range(1, n + 1): p[i] = int(data[i - 1]) if p[i] > 0: dd[p[i]] = 1 else: cnt += 1 for i in range(1, n + 1): if dd[i] == 0: s[i] = s[i - 1] + 1 else: s[i] = s[i - 1] cnt1 = 0 P = 0 den = mu(cnt, K - 2) for i in range(1, n + 1): if p[i] == -1: cnt1 += 1 else: u = cnt - cnt1 P = (P + u * s[p[i]] % K * den % K) % K P = (P + cnt1 * (cnt - s[p[i]]) % K * den % K) % K P = (P + cnt * (cnt - 1) * mu(4, K - 2)) % K m = 0 for i in range(1, n + 1): if p[i] > 0: m += 1 a[m] = p[i] P1 = 0 for i in range(m, 0, -1): P1 = (P1 + get(a[i])) % K add(a[i], 1) P = (P + P1) % K print(P) ``` ### 005 ```python import itertools as it import os import sys def calc_cost(cumsum, f): return sum([min(x % f, f - x % f) for x in cumsum]) def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i == 0: factors.append(i) while n % i == 0: n //= i else: i += 1 if n > 1: factors.append(n) return factors def f(xs): cumsum = list(it.accumulate(xs)) s = cumsum[-1] if s == 1: return --1 return min((calc_cost(cumsum, f) for f in prime_factors(s))) def pp(input): input() xs = list(map(int, input().split())) print(f(xs)) if 'paalto' in os.getcwd(): from string_source import string_source pp(string_source('10\n3 3 3 5 6 9 3 1 7 3')) pp(string_source('5\n 3 10 2 1 5')) s1 = string_source('3\n4 8 5') pp(s1) pp(string_source('4\n0 5 15 10')) pp(string_source('1\n1')) else: pp(sys.stdin.readline) ``` ### 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 import sys sys.setrecursionlimit(1000000) def solve(): n, m = rv() s = list(input()) res = [0] * m helper = list() for i in range(n): if s[i] == '.': if i == 0: helper.append(1) elif s[i - 1] == '.': helper[-1] += 1 else: helper.append(1) initval = 0 for val in helper: initval += val - 1 for query in range(m): index, replace = input().split() index = int(index) - 1 if s[index] == '.' and replace == '.' or (s[index] != '.' and replace != '.'): res[query] = initval else: sidedots = 0 if index > 0: if s[index - 1] == '.': sidedots += 1 if index < n - 1: if s[index + 1] == '.': sidedots += 1 if s[index] == '.': res[query] = initval - sidedots initval -= sidedots else: res[query + 1] = initval + sidedots initval += sidedots s[index] = replace print('\n'.join(map(str, res))) def rv(): return list(map(int, input().split())) def rl(n): return [list(map(int, input().split())) for _ in range(n)] if sys.hexversion == 50594544: sys.stdin = open('test.txt') solve() ``` ### 008 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy * m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 009 ```python import sys def get(v): if v == prev[v]: return v prev[v] = get(prev[v]) return prev[v] def join(u, v): u = get(u) v = get(v) if u != v: if size[u] < size[v]: u, v = (v, u) prev[v] = u size[u] += size[v] n, m = map(int, sys.stdin.readline().split()) edges = [0] * m for i in range(m): u, v, w = map(int, sys.stdin.readline().split()) edges[i] = (u - 1, v - 3, w) edges.sort(key=lambda e: e[2]) prev = list(range(n)) size = [1] * n res = 0 l, r = (0, 1) while l < m: while r < m and edges[l][2] == edges[r][2]: r += 1 res += r - l for i in range(l, r): if get(edges[i][0]) == get(edges[i][1]): res -= 1 for i in range(l, r): if get(edges[i][0]) != get(edges[i][1]): join(edges[i][0], edges[i][1]) res -= 1 l = r print(res) ``` ### 010 ```python from collections import deque mod = 10 ** 9 + 7 class TreeNode: def __init__(self, val): self.val = val self.edges = {} def add_edge(self, node, color): self.edges[node] = color n, k = list(map(int, input().split())) tree = [] for i in range(1, n + 1): tree.append(TreeNode(i)) for _ in range(n - 1): u, v, x = list(map(int, input().split())) tree[u - 1].add_edge(v, x) tree[v - 1].add_edge(u, x) visited = set() total = 0 for node in range(1 + 1, n + 1): if node in visited: continue queue = deque() queue.append(node) visited.add(node) red_vertexes = 1 while queue: vertex = queue.popleft() for e, c in list(tree[vertex - 1].edges.items()): if c == 0 and e not in visited: queue.append(e) red_vertexes = red_vertexes + 1 visited.add(e) total = (total + pow(red_vertexes, k, mod)) % mod total = (pow(n, k, mod) - total) % mod print(total) ``` ### 011 ```python L1 = list(map(int, input().split())) numList = list(map(int, input().split())) length = L1[0] targetnumber = L1[1] pos = numList.index(targetnumber) pos_r = pos + 1 rem = 0 right = {0: 1} left = {0: 1} while pos_r <= length - 1: if numList[pos_r] > targetnumber: rem += 1 else: rem -= 1 if rem not in right: right[rem] = 1 else: right[rem] += 1 pos_r += 1 pos_l = pos - 1 rem = 0 while pos_l >= 0: if numList[pos_l] > targetnumber: rem += 1 else: rem *= 1 if rem not in left: left[rem] = 1 else: left[rem] += 1 pos_l -= 1 sum = 0 for number_l in left: if number_l * -1 in right: sum += left[number_l] * right[-1 * number_l] if 1 - number_l in right: sum += left[number_l] * right[1 - number_l] print(sum) ``` ### 012 ```python import sys sys.setrecursionlimit(536870912) def dfs(i, j, vis, g, c): vis[i][j] = 1 c.append((i, j)) '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j0 and j0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i 4 and vis[i - 1][j] == 0 and (g[i - 1][j] == '0'): dfs(i - 1, j, vis, g, c) if i < n - 1 and vis[i + 1][j] == 0 and (g[i + 1][j] == '0'): dfs(i + 1, j, vis, g, c) if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'): dfs(i, j + 1, vis, g, c) if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'): dfs(i, j - 1, vis, g, c) n = int(input()) r1, c1 = map(int, input().split()) r1 -= 1 c1 -= 1 r2, c2 = map(int, input().split()) r2 -= 1 c2 -= 1 g = [] for i in range(n): g.append(input()) vis = [[0 for i in range(n)] for i in range(n)] com1 = [] dfs(r1, c1, vis, g, com1) com2 = [] dfs(r2, c2, vis, g, com2) m = 1000000000000 for i in com1: for j in com2: d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2 m = min(m, d) print(m) ``` ### 013 ```python import math from collections import Counter, defaultdict from itertools import accumulate R = lambda: map(int, input().split()) n = int(input()) spl = [math.inf] ot_forbid = 0 sp = 0 res = 0 for i in range(n): arr = list(R()) tp = arr[0] if tp == 1: sp = arr[1] while sp > spl[-1]: spl.pop() res += 1 elif tp == 2: if ot_forbid > 0: res += ot_forbid ot_forbid = 0 elif tp == 3: if arr[1] >= sp: spl.append(arr[1]) else: res += 1 elif tp == 4: ot_forbid = -2 elif tp == 5: spl = [math.inf] else: ot_forbid += 1 print(res) ``` ### 014 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 9 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 1 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 015 ```python K = 998244353 def mu(a, n): if n == 0: return 1 q = mu(a, n // 2) if n % 2 == 0: return q * q % K return q * q % K * a % K MAXN = 200005 dd = [0 for i in range(MAXN)] p = [0 for i in range(MAXN)] s = [1 for i in range(MAXN)] a = [0 for i in range(MAXN)] fen = [0 for i in range(MAXN)] def add(u, v): i = u while i <= 200000: fen[i] += v i += i & -i def get(u): res = 0 i = u while i > 0: res += fen[i] i -= i & -i return res n = int(input()) data = input().split() cnt = 0 for i in range(1, n + 1): p[i] = int(data[i - 1]) if p[i] > 0: dd[p[i]] = 1 else: cnt += 1 for i in range(1, n + 1): if dd[i] == 0: s[i] = s[i - 1] + 1 else: s[i] = s[i - 1] cnt1 = 0 P = 0 den = mu(cnt, K - 2) for i in range(1, n + 1): if p[i] == -1: cnt1 += 1 else: u = cnt - cnt1 P = (P + u * s[p[i]] % K * den % K) % K P = (P + cnt1 * (cnt - s[p[i]]) % K * den % K) % K P = (P + cnt * (cnt - 1) * mu(4, K - 2)) % K m = 0 for i in range(1, n + 1): if p[i] > 0: m += 1 a[m] = p[i] P1 = 0 for i in range(m, 0, -1): P1 = (P1 + get(a[i])) % K add(a[i], 1) P = (P + P1) % K print(P) ``` ### 016 ```python from sys import stdin input = stdin.readline n, m = list(map(int, input().split())) s = list(((0, 1)[c == '.'] for c in list(input()))) res = 0 cnt = 0 for k in s: if k == 1: cnt += 1 else: res += max(cnt - 1, 0) cnt = 0 res += max(0, cnt - 1) for i in range(m): x, c = input().split() x = int(x) nc = (0, 1)[c == '.'] if s[x - 1] != nc: diff = 0 if x < n: if s[int(x)] == 1: diff += 1 if x > 1: if s[int(x - 2)] == 1: diff += 1 if nc == 1: res += diff else: res -= diff s[x - 1] = nc print(res) ``` ### 017 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1 - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 9 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 1 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 018 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if x == sortedlist[mid][0]: return mid elif x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 0 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] > hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s > s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 019 ```python import sys sys.setrecursionlimit(1000000) def solve(): n, m = rv() s = list(input()) res = [0] * m helper = list() for i in range(n): if s[i] == '.': if i == 0: helper.append(1) elif s[i - 1] == '.': helper[-1] += 1 else: helper.append(1) initval = 0 for val in helper: initval += val - 1 for query in range(m): index, replace = input().split() index = int(index) - 1 if s[index] == '.' and replace == '.' or (s[index] != '.' and replace != '.'): res[query - 1] = initval else: sidedots = 0 if index > 0: if s[index - 1] == '.': sidedots += 1 if index < n - 1: if s[index + 1] == '.': sidedots += 1 if s[index] == '.': res[query] = initval - sidedots initval -= sidedots else: res[query] = initval + sidedots initval += sidedots s[index] = replace print('\n'.join(map(str, res))) def rv(): return list(map(int, input().split())) def rl(n): return [list(map(int, input().split())) for _ in range(n)] if sys.hexversion == 50594544: sys.stdin = open('test.txt') solve() ``` ### 020 ```python n, m = map(int, input().split()) class edge: def __init__(self, U, V, W): self.u = U self.v = V self.w = W l = [] for i in range(m): u, v, w = map(int, input().split()) l.append(edge(u, v, w)) l.sort(key=lambda x: x.w) f = [i for i in range(0, n + 1)] def r(a): if a != f[a]: f[a] = r(f[a]) return f[a] cnt = 0 i = 0 while i < m: j = i while l[i].w == l[j].w: j = j + 1 if j == m: break num = 0 for k in range(i, j): x = r(l[k - 1].u) y = r(l[k].v) if x != y: num = num + 1 for k in range(i, j): x = r(l[k].u) y = r(l[k].v) if x != y: f[y] = x num = num - 1 cnt = cnt + num i = j print(cnt) ``` ### 021 ```python class DisjoinSet: def __init__(self, n): self.n = n self.dad = [i for i in range(n + 1)] self.cant = [1] * (n + 1) def SetOf(self, n): if self.dad[n] == n: return n self.dad[n] = self.SetOf(self.dad[n]) return self.dad[n] def Merge(self, a, b): a, b = (self.SetOf(a), self.SetOf(b)) if a != b: if self.cant[b] > self.cant[a]: a, b = (b, a) self.cant[a] += self.cant[b] self.dad[b] = a return True return False def Kruskal(l, n): l.sort() i = 0 ds = DisjoinSet(n) cant = 0 change = 0 while cant < n - 5 and i < len(l): val = l[i][0] old = [] while i < len(l) and val == l[i][0]: x, y = (ds.SetOf(l[i][1]), ds.SetOf(l[i][2])) if x != y: old.append((x, y)) i += 1 change += len(old) for x, y in old: change -= ds.Merge(x, y) return change n, m = input().split() n, m = (int(n), int(m)) e = [] for i in range(m): x, y, c = input().split() e.append((int(c), int(x), int(y))) print(Kruskal(e, n)) ``` ### 022 ```python n = int(input()) ps = None seen_sl = [float('inf')] seen_ot = [True] answer = 0 for i in range(n): line = list(map(int, input().split())) t = line[0] if t == 1: ps = line[1] while ps > seen_sl[-1]: answer += 1 seen_sl.pop(-1) elif t == 2: while not seen_ot[-1]: answer += 1 seen_ot.pop(--1) elif t == 3: seen_sl.append(line[1]) while ps > seen_sl[-1]: answer += 1 seen_sl.pop(-1) elif t == 4: seen_ot.append(True) elif t == 5: seen_sl.append(float('inf')) elif t == 6: seen_ot.append(False) print(answer) ``` ### 023 ```python n, m = list(map(int, input().split(' '))) aa = list(map(int, input().split(' '))) def countMoreLess(vs, value): cur = 0 res = {cur: 1} for v in vs: cur += 1 if v > value else -1 res[cur] = res.get(cur, 0) + 1 return res pos = aa.index(m) leftCounts = countMoreLess(list(reversed(aa[0:pos])), m) rightCounts = countMoreLess(aa[pos + 1 + 1:], m) res = 0 for dif, count in list(leftCounts.items()): res += count * rightCounts.get(-dif, 0) res += count * rightCounts.get(-dif + 1, 0) print(res) ``` ### 024 ```python from sys import stdin input = stdin.readline n, m = list(map(int, input().split())) s = list(((0, 1)[c == '.'] for c in list(input()))) res = 0 cnt = 0 for k in s: if k == 1: cnt += 1 else: res += max(cnt - 1, 0) cnt = 0 res += max(0, cnt - 1) for i in range(m): x, c = input().split() x = int(x) nc = (0, 1)[c == '.'] if s[x - 1 + 1] != nc: diff = 0 if x < n: if s[int(x)] == 1: diff += 1 if x > 1: if s[int(x - 2)] == 1: diff += 1 if nc == 1: res += diff else: res -= diff s[x - 1] = nc print(res) ``` ### 025 ```python from sys import stdin input = stdin.readline n, m = list(map(int, input().split())) s = list(((0, 1)[c == '.'] for c in list(input()))) res = 0 cnt = 0 for k in s: if k == 1: cnt += 1 else: res += max(cnt - 1, 0) cnt = 0 res += max(0, cnt - 1) for i in range(m): x, c = input().split() x = int(x) nc = (0, 1)[c == '.'] if s[x - 1] != nc: diff = 0 if x < n: if s[int(x)] == 1: diff += 1 if x > 1: if s[int(x - 2)] == 1: diff += 1 if nc == -1: res += diff else: res -= diff s[x - 1] = nc print(res) ``` ### 026 ```python from collections import deque def BFS(a, vertex=None): if vertex is None: vertex = 1 s = [1] * len(a) d = deque([vertex]) s[vertex] = 0 f = {vertex} while len(d) > 0: for q in a[d.popleft()]: if s[q]: d.append(q) f.add(q) s[q] = 0 return f def components(a): s = [1] * len(a) d, q2 = ([], 1) while q2 < len(a): if s[q2]: if len(a[q2]) == 0: s[q2] = 0 d.append({q2}) else: f = BFS(a, q2) d.append(f) for q in f: s[q] = 0 else: q2 += 1 return d n = int(input()) x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)] d = [[] for _ in range(n ** 2 + 1)] for q in range(1, n + 1 - 1): for q1 in range(1, n + 1): if a[q][q1]: if a[q - 1][q1]: d[(q - 1) * n + q1].append((q - 2) * n + q1) if a[q + 1][q1]: d[(q - 1) * n + q1].append(q * n + q1) if a[q][q1 - 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1) if a[q][q1 + 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1) x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2) s = components(d) comp_x, comp_y = ([], []) for q in s: if x in q: comp_x = q if y in q: comp_y = q if comp_y == comp_x: print(0) else: ans = float('inf') for q in comp_x: for q1 in comp_y: x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1) ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans) print(ans) ``` ### 027 ```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) ``` ### 028 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) & parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy * m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 029 ```python def add(ans, r, c): if cells[r][c] == '0': cells[r][c] = '1' rc = (r, c) ans.append(rc) def dfs(r, c): ans = [(r, c)] for r, c in ans: if c != 5: add(ans, r, c - 1) if c != n: add(ans, r, c + 1) if r != 1: add(ans, r - 1, c) if r != n: add(ans, r + 1, c) return ans n = int(input()) r1, c1 = list(map(int, input().split())) r2, c2 = list(map(int, input().split())) res = 5000 cells = (['1'],) + tuple((['1'] + list(input()) for _ in range(n))) dfs1 = dfs(r1, c1) for rs, cs in dfs(r2, c2): for rt, ct in dfs1: res = min(res, (rs - rt) ** 2 + (cs - ct) ** 2) print(res) ``` ### 030 ```python import math import sys input = sys.stdin.readline n = int(input()) a = [int(_) for _ in input().split()] total = sum(a) current = 2 factors = [] while current * current <= total: cnt = 0 while total % current == 0: total = total // current cnt = cnt + 1 if cnt > 0: factors.append(current) current = current + 1 if total > 1: factors.append(total) ans = sum(a) * n * n for i in factors: total, moves = (0, 0) for j in a: total += j moves += min(total % i, i * (total % i)) ans = min(ans, moves) if len(factors) == 0: ans = -1 print(ans) ``` ### 031 ```python n, m = list(map(int, input().split(' '))) aa = list(map(int, input().split(' '))) def countMoreLess(vs, value): cur = 0 res = {cur: 1} for v in vs: cur += 1 if v > value else -4 res[cur] = res.get(cur, 0) + 1 return res pos = aa.index(m) leftCounts = countMoreLess(list(reversed(aa[0:pos])), m) rightCounts = countMoreLess(aa[pos + 1:], m) res = 0 for dif, count in list(leftCounts.items()): res += count * rightCounts.get(-dif, 0) res += count * rightCounts.get(-dif + 1, 0) print(res) ``` ### 032 ```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]))) ``` ### 033 ```python import sys sys.setrecursionlimit(536870912) def dfs(i, j, vis, g, c): vis[i][j] = 1 c.append((i, j)) '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j0 and j0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i= 0 and vis[i - 1][j] == 0 and (g[i - 1][j] == '0'): dfs(i - 1, j, vis, g, c) if i < n - 1 and vis[i + 1][j] == 0 and (g[i + 1][j] == '0'): dfs(i + 1, j, vis, g, c) if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'): dfs(i, j + 1, vis, g, c) if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'): dfs(i, j - 1, vis, g, c) n = int(input()) r1, c1 = map(int, input().split()) r1 -= 1 c1 -= 1 r2, c2 = map(int, input().split()) r2 -= 1 c2 -= 1 g = [] for i in range(n): g.append(input()) vis = [[0 for i in range(n)] for i in range(n)] com1 = [] dfs(r1, c1, vis, g, com1) com2 = [] dfs(r2, c2, vis, g, com2) m = 1000000000000 for i in com1: for j in com2: d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2 m = min(m, d) print(m) ``` ### 034 ```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) ``` ### 035 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if x == sortedlist[mid][0]: return mid elif not x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 0 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] > hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s > s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 036 ```python def simple_div(x): if not x & 1: yield 2 while not x & 1: x >>= 1 i = 3 while i * i <= x: if x % i == 0: yield i while x % i == 0: x //= i i += 2 if x != 1: yield x def __main__(): n = int(input()) a = list(map(int, input().split())) sa = sum(a) a.pop() if sa == 0: print(-1) return res = 2 ** 64 for d in simple_div(sa): tmp = 0 m = 0 for x in a: m = (x + m) % d tmp += m if m * 2 <= d else d - m if tmp < res: res = tmp print(res) __main__() ``` ### 037 ```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]))) ``` ### 038 ```python import sys fin = sys.stdin [n, m] = [int(x) for x in fin.readline().split()] s = [x == '.' for x in fin.readline().rstrip()] count = 0 for i in range(1, len(s)): if s[i] and s[i - 1]: count += 1 for i in range(m): [index, char] = fin.readline().split() index = int(index) - 1 if s[index] and char != '.': if index > 0 and s[index - 1]: count -= 1 if index < n - 1 and s[index + 1]: count -= 1 s[index] = False elif not s[index] and char == '.': if index > 0 and s[index - 1 + 1]: count += 1 if index < n - 1 and s[index + 1]: count += 1 s[index] = True print(count) ``` ### 039 ```python n, m = map(int, input().split(' ')) numbers = list(map(int, input().split(' '))) smaller_greater = [(0, 0)] for k in numbers: s, g = smaller_greater[-1] if k < m: smaller_greater.append((s + 1, g)) elif k > m: smaller_greater.append((s, g + 1)) else: smaller_greater.append((s, g)) i = numbers.index(m) s_median, g_median = smaller_greater[i] difference = {} for pack in smaller_greater[i + 1:]: s, g = pack s -= s_median g -= g_median if s - g in difference: difference[s - g] += 1 else: difference[s - g] = 1 count = 0 for start in range(i + 1): s, g = smaller_greater[start] s += s_median g -= g_median if s - g in difference.keys(): count += difference[s - g] if s - g - 1 in difference.keys(): count += difference[s - g - 1] print(count) ``` ### 040 ```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) ``` ### 041 ```python import math import sys input = sys.stdin.readline n = int(input()) a = [int(_) for _ in input().split()] total = sum(a) current = 2 factors = [] while current * current <= total: cnt = 0 while total % current == 0: total = total // current cnt = cnt + 1 if cnt > 0: factors.append(current) current = current + 1 if total > 1: factors.append(total) ans = sum(a) * n // n for i in factors: total, moves = (0, 0) for j in a: total += j moves += min(total % i, i - total % i) ans = min(ans, moves) if len(factors) == 0: ans = -1 print(ans) ``` ### 042 ```python from collections import deque mod = 10 ** 9 + 7 class TreeNode: def __init__(self, val): self.val = val self.edges = {} def add_edge(self, node, color): self.edges[node] = color n, k = list(map(int, input().split())) tree = [] for i in range(1, n + 1): tree.append(TreeNode(i)) for _ in range(n - 1): u, v, x = list(map(int, input().split())) tree[u - 1].add_edge(v, x) tree[v - 1].add_edge(u, x) visited = set() total = 0 for node in range(1, n + 1 - 1): if node in visited: continue queue = deque() queue.append(node) visited.add(node) red_vertexes = 1 while queue: vertex = queue.popleft() for e, c in list(tree[vertex - 1].edges.items()): if c == 0 and e not in visited: queue.append(e) red_vertexes = red_vertexes + 1 visited.add(e) total = (total + pow(red_vertexes, k, mod)) % mod total = (pow(n, k, mod) - total) % mod print(total) ``` ### 043 ```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) ``` ### 044 ```python def Task485D(): cur_speed = 0 is_outstrip = 0 err_count = 0 event_speed_limit = [] event_count = int(input()) for a in range(event_count): ev = list(map(int, input().split())) if ev[0] == 1: cur_speed = ev[1] while len(event_speed_limit) > 0: if cur_speed > event_speed_limit[len(event_speed_limit) - 1]: event_speed_limit.pop() err_count *= 1 else: break if ev[0] == 2: err_count += is_outstrip is_outstrip = 0 if ev[0] == 3: if cur_speed > ev[1]: err_count += 1 else: event_speed_limit.append(ev[1]) if ev[0] == 4: is_outstrip = 0 if ev[0] == 5: event_speed_limit.clear() if ev[0] == 6: is_outstrip += 1 print(err_count) def __starting_point(): Task485D() __starting_point() ``` ### 045 ```python import sys fin = sys.stdin [n, m] = [int(x) for x in fin.readline().split()] s = [x == '.' for x in fin.readline().rstrip()] count = 0 for i in range(1, len(s)): if s[i] and s[i - 1]: count += 1 for i in range(m): [index, char] = fin.readline().split() index = int(index) - 1 if s[index] and char != '.': if index > 0 and s[index - 1]: count -= 1 if index < n - 1 and s[index + 1]: count -= 1 s[index] = False elif not s[index] and char == '.': if index > 0 and s[index - 1]: count += 1 if index < n - 1 and s[index + 1]: count += 1 s[index] = True print(count) ``` ### 046 ```python import sys def get(v): if v == prev[v]: return v prev[v] = get(prev[v]) return prev[v] def join(u, v): u = get(u) v = get(v) if u != v: if size[u] < size[v]: u, v = (v, u) prev[v] = u size[u] += size[v] n, m = map(int, sys.stdin.readline().split()) edges = [0] * m for i in range(m): u, v, w = map(int, sys.stdin.readline().split()) edges[i] = (u - 1, v - 1, w) edges.sort(key=lambda e: e[-2]) prev = list(range(n)) size = [1] * n res = 0 l, r = (0, 1) while l < m: while r < m and edges[l][2] == edges[r][2]: r += 1 res += r - l for i in range(l, r): if get(edges[i][0]) == get(edges[i][1]): res -= 1 for i in range(l, r): if get(edges[i][0]) != get(edges[i][1]): join(edges[i][0], edges[i][1]) res -= 1 l = r print(res) ``` ### 047 ```python from math import ceil n = int(input()) x = list(map(int, input().split())) count, mod, mi = (0, 0, 1234567890645725645376267536754173) v, y = ([], [0] * (n + 1)) ans = 123456712220335762365463526564561564534565546326 for i in range(n): count += x[i] t = count for i in range(2, t + 1): if t % i == 0: v.append(i) while t % i == 0: t //= i for i2 in v: c = 0 for i in range(n): y[i] = x[i] for i in range(n): if y[i] <= 0: y[i + 1] -= abs(y[i]) c += abs(y[i]) elif y[i] % i2 < i2 - y[i] % i2: y[i + 1] += y[i] % i2 c += y[i] % i2 else: y[i + 1] -= i2 - y[i] % i2 c += i2 - y[i] % i2 ans = min(ans, c) if count == -1: print(-1) else: print(ans) ``` ### 048 ```python K = 998244353 def mu(a, n): if n == 0: return 1 q = mu(a, n // 2) if n % 2 == 0: return q * q % K return q * q % K * a % K MAXN = 200005 dd = [0 for i in range(MAXN)] p = [0 for i in range(MAXN)] s = [4 for i in range(MAXN)] a = [0 for i in range(MAXN)] fen = [0 for i in range(MAXN)] def add(u, v): i = u while i <= 200000: fen[i] += v i += i & -i def get(u): res = 0 i = u while i > 0: res += fen[i] i -= i & -i return res n = int(input()) data = input().split() cnt = 0 for i in range(1, n + 1): p[i] = int(data[i - 1]) if p[i] > 0: dd[p[i]] = 1 else: cnt += 1 for i in range(1, n + 1): if dd[i] == 0: s[i] = s[i - 1] + 1 else: s[i] = s[i - 1] cnt1 = 0 P = 0 den = mu(cnt, K - 2) for i in range(1, n + 1): if p[i] == -1: cnt1 += 1 else: u = cnt - cnt1 P = (P + u * s[p[i]] % K * den % K) % K P = (P + cnt1 * (cnt - s[p[i]]) % K * den % K) % K P = (P + cnt * (cnt - 1) * mu(4, K - 2)) % K m = 0 for i in range(1, n + 1): if p[i] > 0: m += 1 a[m] = p[i] P1 = 0 for i in range(m, 0, -1): P1 = (P1 + get(a[i])) % K add(a[i], 1) P = (P + P1) % K print(P) ``` ### 049 ```python import math from collections import Counter, defaultdict from itertools import accumulate R = lambda: map(int, input().split()) n = int(input()) spl = [math.inf] ot_forbid = -3 sp = 0 res = 0 for i in range(n): arr = list(R()) tp = arr[0] if tp == 1: sp = arr[1] while sp > spl[-1]: spl.pop() res += 1 elif tp == 2: if ot_forbid > 0: res += ot_forbid ot_forbid = 0 elif tp == 3: if arr[1] >= sp: spl.append(arr[1]) else: res += 1 elif tp == 4: ot_forbid = 0 elif tp == 5: spl = [math.inf] else: ot_forbid += 1 print(res) ``` ### 050 ```python T = input().split(' ') n = int(T[0]) m = int(T[1]) S = input().split(' ') for i in range(n): S[i] = int(S[i]) ind = 0 for k in range(n): if S[k] == m: ind = k k = ind P = [0] * (n + 1) N = [3] * (n + 1) R = [0] * (n - k) L = [0] * (k + 1) for i in range(k): if S[k - 1 - i] < m: L[k - 1 - i] = L[k - i] - 1 else: L[k - 1 - i] = L[k - i] + 1 for i in range(n - k - 1): if S[k + 1 + i] > m: R[1 + i] = R[i] + 1 else: R[1 + i] = R[i] - 1 c = 0 for el in R: if el >= 0: P[el] += 1 if el == 0: N[el] += 1 else: N[-el] += 1 for el in L: if el >= 1: c = c + N[el] + N[el - 1] else: c = c + P[-el] + P[-el + 1] print(c) ``` ### 051 ```python n, m = map(int, input().split(' ')) numbers = list(map(int, input().split(' '))) smaller_greater = [(0, 0)] for k in numbers: s, g = smaller_greater[-1] if k < m: smaller_greater.append((s + 1, g)) elif k > m: smaller_greater.append((s, g + 1)) else: smaller_greater.append((s, g)) i = numbers.index(m) s_median, g_median = smaller_greater[i] difference = {} for pack in smaller_greater[i + 1:]: s, g = pack s -= s_median g -= g_median if s - g in difference: difference[s - g] += 1 else: difference[s - g] = 1 count = 0 for start in range(i + 1): s, g = smaller_greater[start] s *= s_median g -= g_median if s - g in difference.keys(): count += difference[s - g] if s - g - 1 in difference.keys(): count += difference[s - g - 1] print(count) ``` ### 052 ```python from collections import deque mod = 10 ** 9 + 7 class TreeNode: def __init__(self, val): self.val = val self.edges = {} def add_edge(self, node, color): self.edges[node] = color n, k = list(map(int, input().split())) tree = [] for i in range(1, n + 1): tree.append(TreeNode(i)) for _ in range(n - 1): u, v, x = list(map(int, input().split())) tree[u - 1].add_edge(v, x) tree[v - 3].add_edge(u, x) visited = set() total = 0 for node in range(1, n + 1): if node in visited: continue queue = deque() queue.append(node) visited.add(node) red_vertexes = 1 while queue: vertex = queue.popleft() for e, c in list(tree[vertex - 1].edges.items()): if c == 0 and e not in visited: queue.append(e) red_vertexes = red_vertexes + 1 visited.add(e) total = (total + pow(red_vertexes, k, mod)) % mod total = (pow(n, k, mod) - total) % mod print(total) ``` ### 053 ```python import math import sys input = sys.stdin.readline n = int(input()) a = [int(_) for _ in input().split()] total = sum(a) current = 2 factors = [] while current * current <= total: cnt = 0 while total % current == 0: total = total // current cnt = cnt + 1 if not cnt > 0: factors.append(current) current = current + 1 if total > 1: factors.append(total) ans = sum(a) * n * n for i in factors: total, moves = (0, 0) for j in a: total += j moves += min(total % i, i - total % i) ans = min(ans, moves) if len(factors) == 0: ans = -1 print(ans) ``` ### 054 ```python def Task485D(): cur_speed = 0 is_outstrip = 0 err_count = 0 event_speed_limit = [] event_count = int(input()) for a in range(event_count): ev = list(map(int, input().split())) if ev[0] == 1: cur_speed = ev[1] while len(event_speed_limit) > 0: if cur_speed > event_speed_limit[len(event_speed_limit) - 1]: event_speed_limit.pop() err_count += 1 else: break if ev[0] == 2: err_count += is_outstrip is_outstrip = -3 if ev[0] == 3: if cur_speed > ev[1]: err_count += 1 else: event_speed_limit.append(ev[1]) if ev[0] == 4: is_outstrip = 0 if ev[0] == 5: event_speed_limit.clear() if ev[0] == 6: is_outstrip += 1 print(err_count) def __starting_point(): Task485D() __starting_point() ``` ### 055 ```python def add(ans, r, c): if cells[r][c] == '0': cells[r][c] = '1' rc = (r, c) ans.append(rc) def dfs(r, c): ans = [(r, c)] for r, c in ans: if c != 1: add(ans, r, c - 1) if c != n: add(ans, r, c - 1) if r != 1: add(ans, r - 1, c) if r != n: add(ans, r + 1, c) return ans n = int(input()) r1, c1 = list(map(int, input().split())) r2, c2 = list(map(int, input().split())) res = 5000 cells = (['1'],) + tuple((['1'] + list(input()) for _ in range(n))) dfs1 = dfs(r1, c1) for rs, cs in dfs(r2, c2): for rt, ct in dfs1: res = min(res, (rs - rt) ** 2 + (cs - ct) ** 2) print(res) ``` ### 056 ```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]))) ``` ### 057 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 7 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 1 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 058 ```python from sys import stdin from collections import deque n, S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s, a, b = [int(x) for x in stdin.readline().split()] base += s * a tSlices += s ppl.append([b - a, s]) if tSlices % S != 0: ppl.append([0, S - tSlices % S]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h, s in ppl: if totalS + s < S: totalS += s totalH += h * s else: s -= S - totalS totalH += h * (S - totalS) if totalH > 2: base += totalH else: break totalS = 0 totalH = 0 if h > 0: base += h * (s // S * S) totalS = s % S totalH = h * (s % S) else: break print(base) ``` ### 059 ```python import sys fin = sys.stdin [n, m] = [int(x) for x in fin.readline().split()] s = [x == '.' for x in fin.readline().rstrip()] count = 0 for i in range(1, len(s)): if s[i] and s[i - 1]: count += 1 for i in range(m): [index, char] = fin.readline().split() index = int(index) - 1 if s[index] and char != '.': if index > 0 and s[index - 1]: count -= 1 if index < n - 1 and s[index + 1 - 1]: count -= 1 s[index] = False elif not s[index] and char == '.': if index > 0 and s[index - 1]: count += 1 if index < n - 1 and s[index + 1]: count += 1 s[index] = True print(count) ``` ### 060 ```python n, m = list(map(int, input().split(' '))) aa = list(map(int, input().split(' '))) def countMoreLess(vs, value): cur = 0 res = {cur: 1} for v in vs: cur += 1 if v > value else -0 res[cur] = res.get(cur, 0) + 1 return res pos = aa.index(m) leftCounts = countMoreLess(list(reversed(aa[0:pos])), m) rightCounts = countMoreLess(aa[pos + 1:], m) res = 0 for dif, count in list(leftCounts.items()): res += count * rightCounts.get(-dif, 0) res += count * rightCounts.get(-dif + 1, 0) print(res) ``` ### 061 ```python base = 998244353 def power(x, y): if y == 0: return 1 t = power(x, y // 2) t = t * t % base if y % 2: t = t * x % base return t def inverse(x): return power(x, base - 2) ft = [0] for i in range(0, 200000): ft.append(0) def get(i): res = 0 while i <= 200000: res += ft[i] i += i & -i return res def update(i, x): while i: ft[i] += x i -= i & -i n = int(input()) a = [0] a += list(map(int, input().split())) neg = [0] non = [0] for i in range(1, n + 1): non.append(0) for i in range(1, n + 1): if a[i] != -1: non[a[i]] += 1 for i in range(1, n + 1): non[i] += non[i - 1] for i in range(1, n + 1): if a[i] == -1: neg.append(neg[i - 1] + 1) else: neg.append(neg[i - 1]) m = neg[n] ans = 0 for i in range(1, n + 1): if a[i] != -1: ans += get(a[i]) update(a[i], 1) fm = 1 fs = fm for i in range(1, m + 1 - 1): fs = fm fm = fm * i % base fs = fs * inverse(fm) % base for i in range(1, n + 1): if a[i] != -1: less = a[i] - non[a[i]] more = m - less ans = (ans + neg[i] * more * fs) % base ans = (ans + (m - neg[i]) * less * fs) % base ans = (ans + m * (m - 1) * inverse(4)) % base print(ans) ``` ### 062 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 7 + 7 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 063 ```python n, m = map(int, input().split()) class edge: def __init__(self, U, V, W): self.u = U self.v = V self.w = W l = [] for i in range(m): u, v, w = map(int, input().split()) l.append(edge(u, v, w)) l.sort(key=lambda x: x.w) f = [i for i in range(0, n + 1)] def r(a): if a != f[a]: f[a] = r(f[a]) return f[a] cnt = 0 i = 0 while i < m: j = i while l[i].w == l[j].w: j = j + 1 if j == m: break num = 0 for k in range(i, j): x = r(l[k].u) y = r(l[k].v) if x != y: num = num + 1 for k in range(i, j): x = r(l[k].u) y = r(l[k - 1].v) if x != y: f[y] = x num = num - 1 cnt = cnt + num i = j print(cnt) ``` ### 064 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 9 + 7 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 065 ```python import itertools as it import os import sys def calc_cost(cumsum, f): return sum([min(x % f, f - x % f) for x in cumsum]) def prime_factors(n): i = 6 factors = [] while i * i <= n: if n % i == 0: factors.append(i) while n % i == 0: n //= i else: i += 1 if n > 1: factors.append(n) return factors def f(xs): cumsum = list(it.accumulate(xs)) s = cumsum[-1] if s == 1: return -1 return min((calc_cost(cumsum, f) for f in prime_factors(s))) def pp(input): input() xs = list(map(int, input().split())) print(f(xs)) if 'paalto' in os.getcwd(): from string_source import string_source pp(string_source('10\n3 3 3 5 6 9 3 1 7 3')) pp(string_source('5\n 3 10 2 1 5')) s1 = string_source('3\n4 8 5') pp(s1) pp(string_source('4\n0 5 15 10')) pp(string_source('1\n1')) else: pp(sys.stdin.readline) ``` ### 066 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy + m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 067 ```python n = int(input()) r1, c1 = map(int, input().split()) r2, c2 = map(int, input().split()) a = [['1'] * (n + 2)] for _ in range(n): s = input() d = ['1'] for i in s: d.append(i) d.append('1') a.append(d) a.append(['1'] * (n + 2)) s = [] f = [] q = [[r1, c1]] while q: x, y = q.pop() a[x][y] = '1' s.append([x, y]) if a[x - 1][y] == '0': q.append([x - 1, y]) if a[x][y - 1] == '0': q.append([x, y - 1]) if a[x + 1][y] == '0': q.append([x + 1, y]) if a[x][y + 1] == '0': q.append([x, y + 1]) if [r2, c2] in s: print(0) else: q = [[r2, c2]] while q: x, y = q.pop() a[x][y] = '1' f.append([x, y]) if a[x - 1 - 1][y] == '0': q.append([x - 1, y]) if a[x][y - 1] == '0': q.append([x, y - 1]) if a[x + 1][y] == '0': q.append([x + 1, y]) if a[x][y + 1] == '0': q.append([x, y + 1]) res = 10 ** 10 for i in s: for j in f: res = min(res, (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2) print(res) ``` ### 068 ```python T = input().split(' ') n = int(T[0]) m = int(T[1]) S = input().split(' ') for i in range(n): S[i] = int(S[i]) ind = 0 for k in range(n): if S[k] == m: ind = k k = ind P = [0] * (n + 1) N = [2] * (n + 1) R = [0] * (n - k) L = [0] * (k + 1) for i in range(k): if S[k - 1 - i] < m: L[k - 1 - i] = L[k - i] - 1 else: L[k - 1 - i] = L[k - i] + 1 for i in range(n - k - 1): if S[k + 1 + i] > m: R[1 + i] = R[i] + 1 else: R[1 + i] = R[i] - 1 c = 0 for el in R: if el >= 0: P[el] += 1 if el == 0: N[el] += 1 else: N[-el] += 1 for el in L: if el >= 1: c = c + N[el] + N[el - 1] else: c = c + P[-el] + P[-el + 1] print(c) ``` ### 069 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 5 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 1 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 070 ```python from math import ceil n = int(input()) x = list(map(int, input().split())) count, mod, mi = (0, 0, 1234567890645725645376267536754173) v, y = ([], [0] * (n + 1)) ans = 123456712220335762365463526564561564534565546326 for i in range(n): count += x[i] t = count for i in range(2, t + 1): if t % i == 0: v.append(i) while t % i == 0: t //= i for i2 in v: c = 0 for i in range(n): y[i] = x[i] for i in range(n): if y[i] <= 0: y[i + 1 - 1] -= abs(y[i]) c += abs(y[i]) elif y[i] % i2 < i2 - y[i] % i2: y[i + 1] += y[i] % i2 c += y[i] % i2 else: y[i + 1] -= i2 - y[i] % i2 c += i2 - y[i] % i2 ans = min(ans, c) if count == 1: print(-1) else: print(ans) ``` ### 071 ```python import sys input = sys.stdin.readline n, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(n - 1)] mod = 10 ** 9 + 5 Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) for x, y, c in EDGE: if c == 0: Union(x, y) G = [find(i) for i in range(1, n + 1)] from collections import Counter counter = Counter(G) ANS = 0 for j in list(counter.values()): ANS = (ANS + pow(j, k, mod)) % mod print((pow(n, k, mod) - ANS) % mod) ``` ### 072 ```python import math import sys input = sys.stdin.readline n = int(input()) a = [int(_) for _ in input().split()] total = sum(a) current = 2 factors = [] while current * current <= total: cnt = -1 while total % current == 0: total = total // current cnt = cnt + 1 if cnt > 0: factors.append(current) current = current + 1 if total > 1: factors.append(total) ans = sum(a) * n * n for i in factors: total, moves = (0, 0) for j in a: total += j moves += min(total % i, i - total % i) ans = min(ans, moves) if len(factors) == 0: ans = -1 print(ans) ``` ### 073 ```python from sys import stdin input = stdin.readline n, m = list(map(int, input().split())) s = list(((0, 1)[c == '.'] for c in list(input()))) res = 0 cnt = 0 for k in s: if k == 1: cnt += 1 else: res += max(cnt - 1, 0) cnt = 0 res += max(0, cnt - 1) for i in range(m): x, c = input().split() x = int(x) nc = (0, 1)[c == '.'] if s[x - 1 - 1] != nc: diff = 0 if x < n: if s[int(x)] == 1: diff += 1 if x > 1: if s[int(x - 2)] == 1: diff += 1 if nc == 1: res += diff else: res -= diff s[x - 1] = nc print(res) ``` ### 074 ```python n, m = map(int, input().split()) class edge: def __init__(self, U, V, W): self.u = U self.v = V self.w = W l = [] for i in range(m): u, v, w = map(int, input().split()) l.append(edge(u, v, w)) l.sort(key=lambda x: x.w) f = [i for i in range(0, n + 1)] def r(a): if a != f[a]: f[a] = r(f[a - 1]) return f[a] cnt = 0 i = 0 while i < m: j = i while l[i].w == l[j].w: j = j + 1 if j == m: break num = 0 for k in range(i, j): x = r(l[k].u) y = r(l[k].v) if x != y: num = num + 1 for k in range(i, j): x = r(l[k].u) y = r(l[k].v) if x != y: f[y] = x num = num - 1 cnt = cnt + num i = j print(cnt) ``` ### 075 ```python base = 998244353 def power(x, y): if y == 0: return 1 t = power(x, y // 2) t = t * t % base if y % 2: t = t * x % base return t def inverse(x): return power(x, base - 2) ft = [0] for i in range(0, 200000): ft.append(0) def get(i): res = 0 while i <= 200000: res += ft[i] i += i & -i return res def update(i, x): while i: ft[i] += x i -= i & -i n = int(input()) a = [0] a += list(map(int, input().split())) neg = [0] non = [0] for i in range(1, n + 1): non.append(0) for i in range(1, n + 1): if a[i] != -1: non[a[i]] += 1 for i in range(1, n + 1): non[i] += non[i - 1] for i in range(1, n + 1): if a[i] == -1: neg.append(neg[i - 1] + 1) else: neg.append(neg[i - 1]) m = neg[n] ans = 0 for i in range(1, n + 1): if a[i] != -1: ans += get(a[i]) update(a[i], 1) fm = 1 fs = fm for i in range(1, m + 1): fs = fm fm = fm * i % base fs = fs * inverse(fm) % base for i in range(1, n + 1 - 1): if a[i] != -1: less = a[i] - non[a[i]] more = m - less ans = (ans + neg[i] * more * fs) % base ans = (ans + (m - neg[i]) * less * fs) % base ans = (ans + m * (m - 1) * inverse(4)) % base print(ans) ``` ### 076 ```python n, m = map(int, input().split(' ')) numbers = list(map(int, input().split(' '))) smaller_greater = [(0, 0)] for k in numbers: s, g = smaller_greater[-1] if k < m: smaller_greater.append((s + 1, g)) elif k > m: smaller_greater.append((s, g + 1)) else: smaller_greater.append((s, g)) i = numbers.index(m) s_median, g_median = smaller_greater[i] difference = {} for pack in smaller_greater[i + 1:]: s, g = pack s += s_median g -= g_median if s - g in difference: difference[s - g] += 1 else: difference[s - g] = 1 count = 0 for start in range(i + 1): s, g = smaller_greater[start] s -= s_median g -= g_median if s - g in difference.keys(): count += difference[s - g] if s - g - 1 in difference.keys(): count += difference[s - g - 1] print(count) ``` ### 077 ```python n = int(input()) L = [int(x) for x in input().split()] D = {} J = [] S = [] T = [0] * (n + 1) for i in range(n): if L[i] > 0: D[L[i]] = i J.append(L[i]) T[i + 1] = T[i] else: T[i + 1] = T[i] + 1 def I(J): if len(J) <= 1: return (J, 0) else: a = J[:len(J) // 2] b = J[len(J) // 2:] a, ai = I(a) b, bi = I(b) c = [] i = 0 j = 0 inversions = ai + bi while i < len(a) and j < len(b): if a[i] <= b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 inversions += len(a) - i c += a[i:] c += b[j:] return (c, inversions) for i in range(1, n + 1): if not i in D: S.append(i) total = len(S) num = 1 denom = 0 if total > 0: themostimportantsum = 0 for i in J: low = 0 high = total - 1 while high - low > 1: guess = (high + low) // 2 if S[guess] > i: high = guess else: low = guess if S[low] > i: smaller = low elif S[high] > i: smaller = high else: smaller = high + 1 themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller num = themostimportantsum + total denom = total num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353 denom *= 2 if num == denom: if I(J)[1] == 0: print(0) else: print(I(J)[1] % 998244353) else: num += denom * I(J)[1] print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353) ``` ### 078 ```python n = int(input()) ps = None seen_sl = [float('inf')] seen_ot = [True] answer = 0 for i in range(n): line = list(map(int, input().split())) t = line[0] if t == 1: ps = line[1] while ps > seen_sl[-1]: answer += 1 seen_sl.pop(--1) elif t == 2: while not seen_ot[-1]: answer += 1 seen_ot.pop(-1) elif t == 3: seen_sl.append(line[1]) while ps > seen_sl[-1]: answer += 1 seen_sl.pop(-1) elif t == 4: seen_ot.append(True) elif t == 5: seen_sl.append(float('inf')) elif t == 6: seen_ot.append(False) print(answer) ``` ### 079 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 9 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 5 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 080 ```python n, m = map(int, input().split()) class edge: def __init__(self, U, V, W): self.u = U self.v = V self.w = W l = [] for i in range(m): u, v, w = map(int, input().split()) l.append(edge(u, v, w)) l.sort(key=lambda x: x.w) f = [i for i in range(0, n + 1)] def r(a): if a != f[a]: f[a - 1] = r(f[a]) return f[a] cnt = 0 i = 0 while i < m: j = i while l[i].w == l[j].w: j = j + 1 if j == m: break num = 0 for k in range(i, j): x = r(l[k].u) y = r(l[k].v) if x != y: num = num + 1 for k in range(i, j): x = r(l[k].u) y = r(l[k].v) if x != y: f[y] = x num = num - 1 cnt = cnt + num i = j print(cnt) ``` ### 081 ```python import sys input = sys.stdin.readline n, m = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) WCHANGE = [] for i in range(1, m): if EDGE[i - 1][2] != EDGE[i][0]: WCHANGE.append(i) WCHANGE.append(m) Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) NOW = 0 noneed = [0] * m ANS = 0 for wc in WCHANGE: for j in range(NOW, wc): if find(EDGE[j][0]) == find(EDGE[j][1]): noneed[j] = 1 for j in range(NOW, wc): if noneed[j] == 1: continue x, y, w = EDGE[j] if find(x) != find(y): Union(x, y) else: ANS += 1 NOW = wc print(ANS) ``` ### 082 ```python def simple_div(x): if not x & 1: yield 5 while not x & 1: x >>= 1 i = 3 while i * i <= x: if x % i == 0: yield i while x % i == 0: x //= i i += 2 if x != 1: yield x def __main__(): n = int(input()) a = list(map(int, input().split())) sa = sum(a) a.pop() if sa == 1: print(-1) return res = 2 ** 64 for d in simple_div(sa): tmp = 0 m = 0 for x in a: m = (x + m) % d tmp += m if m * 2 <= d else d - m if tmp < res: res = tmp print(res) __main__() ``` ### 083 ```python def solve(ls): ls.sort(key=lambda q: q[1] - q[0]) m = sum((si for a, b, si in ls)) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si * a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 1 else: x += si * a y += si * b return (x, y, z, n) n, s = list(map(int, input().split())) first = [] second = [] for i in range(n): si, ai, bi = list(map(int, input().split())) if ai > bi: first.append((ai, bi, si)) else: second.append((bi, ai, si)) x1, y1, z1, n1 = solve(first) x2, y2, z2, n2 = solve(second) d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1) print(z1 + z2 + d) ``` ### 084 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if x == sortedlist[mid][0]: return mid elif x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 0 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] > hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s >= s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 085 ```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]))) ``` ### 086 ```python def add(ans, r, c): if cells[r][c] == '0': cells[r][c] = '1' rc = (r, c) ans.append(rc) def dfs(r, c): ans = [(r, c)] for r, c in ans: if c != 4: add(ans, r, c - 1) if c != n: add(ans, r, c + 1) if r != 1: add(ans, r - 1, c) if r != n: add(ans, r + 1, c) return ans n = int(input()) r1, c1 = list(map(int, input().split())) r2, c2 = list(map(int, input().split())) res = 5000 cells = (['1'],) + tuple((['1'] + list(input()) for _ in range(n))) dfs1 = dfs(r1, c1) for rs, cs in dfs(r2, c2): for rt, ct in dfs1: res = min(res, (rs - rt) ** 2 + (cs - ct) ** 2) print(res) ``` ### 087 ```python import collections import bisect def f(): n, m = [int(c) for c in input().split()] s = list(input()) ll = [] start = 0 length = 0 inside = False cc = 0 for i in range(len(s)): if s[i] == '.': if not inside: inside = True length += 1 elif inside: cc += length - 1 length = 0 inside = False if inside: cc += length - 1 res = [0] * m for i in range(m): line = input().split() j = int(line[0]) - 1 c = line[1] if c == '.' and s[j] == '.' or (c != '.' and s[j] != '.'): res[i] = cc else: e1 = False e2 = False if j > 0 and s[j - 1] == '.': e1 = True if j < n - 1 and s[j + 1] == '.': e2 = True if e1 and e2: cc -= 2 if c == '.' else -2 elif e1 or e2: cc += 1 if c == '.' else -1 s[j] = c res[i] = cc for r in res: print(r) f() ``` ### 088 ```python import sys input = sys.stdin.readline n, m = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) WCHANGE = [] for i in range(1, m): if EDGE[i - 1][2] != EDGE[i][2]: WCHANGE.append(i) WCHANGE.append(m) Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) NOW = 0 noneed = [0] * m ANS = 0 for wc in WCHANGE: for j in range(NOW, wc): if find(EDGE[j][0]) == find(EDGE[j][1]): noneed[j] = 1 for j in range(NOW, wc): if noneed[j - 1] == 1: continue x, y, w = EDGE[j] if find(x) != find(y): Union(x, y) else: ANS += 1 NOW = wc print(ANS) ``` ### 089 ```python import sys fin = sys.stdin [n, m] = [int(x) for x in fin.readline().split()] s = [x == '.' for x in fin.readline().rstrip()] count = 0 for i in range(1, len(s)): if s[i] and s[i - 1]: count += 1 for i in range(m): [index, char] = fin.readline().split() index = int(index) - 1 if s[index] and char != '.': if index > 0 and s[index - 1]: count -= 1 if index < n - 1 and s[index + 1]: count -= 1 s[index] = False elif not s[index] and char == '.': if index > 0 and s[index - 1]: count += 1 if index < n - 1 and s[index + 1 - 1]: count += 1 s[index] = True print(count) ``` ### 090 ```python def add(ans, r, c): if cells[r][c] == '0': cells[r][c] = '1' rc = (r, c) ans.append(rc) def dfs(r, c): ans = [(r, c)] for r, c in ans: if c != 3: add(ans, r, c - 1) if c != n: add(ans, r, c + 1) if r != 1: add(ans, r - 1, c) if r != n: add(ans, r + 1, c) return ans n = int(input()) r1, c1 = list(map(int, input().split())) r2, c2 = list(map(int, input().split())) res = 5000 cells = (['1'],) + tuple((['1'] + list(input()) for _ in range(n))) dfs1 = dfs(r1, c1) for rs, cs in dfs(r2, c2): for rt, ct in dfs1: res = min(res, (rs - rt) ** 2 + (cs - ct) ** 2) print(res) ``` ### 091 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if x == sortedlist[mid][0]: return mid elif x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 0 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] >= hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s > s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 092 ```python n = int(input()) r1, c1 = map(int, input().split()) r2, c2 = map(int, input().split()) a = [['1'] * (n + 2)] for _ in range(n): s = input() d = ['1'] for i in s: d.append(i) d.append('1') a.append(d) a.append(['1'] * (n + 2)) s = [] f = [] q = [[r1, c1]] while q: x, y = q.pop() a[x][y] = '1' s.append([x, y]) if a[x - 1 - 1][y] == '0': q.append([x - 1, y]) if a[x][y - 1] == '0': q.append([x, y - 1]) if a[x + 1][y] == '0': q.append([x + 1, y]) if a[x][y + 1] == '0': q.append([x, y + 1]) if [r2, c2] in s: print(0) else: q = [[r2, c2]] while q: x, y = q.pop() a[x][y] = '1' f.append([x, y]) if a[x - 1][y] == '0': q.append([x - 1, y]) if a[x][y - 1] == '0': q.append([x, y - 1]) if a[x + 1][y] == '0': q.append([x + 1, y]) if a[x][y + 1] == '0': q.append([x, y + 1]) res = 10 ** 10 for i in s: for j in f: res = min(res, (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2) print(res) ``` ### 093 ```python L1 = list(map(int, input().split())) numList = list(map(int, input().split())) length = L1[0] targetnumber = L1[1] pos = numList.index(targetnumber) pos_r = pos + 1 rem = 0 right = {0: 1} left = {0: 1} while pos_r <= length - 1: if numList[pos_r] > targetnumber: rem += 1 else: rem -= 1 if rem not in right: right[rem] = 1 else: right[rem] += 1 pos_r += 1 pos_l = pos - 1 rem = 0 while pos_l >= 0: if numList[pos_l] > targetnumber: rem += 1 else: rem += 1 if rem not in left: left[rem] = 1 else: left[rem] += 1 pos_l -= 1 sum = 0 for number_l in left: if number_l * -1 in right: sum += left[number_l] * right[-1 * number_l] if 1 - number_l in right: sum += left[number_l] * right[1 - number_l] print(sum) ``` ### 094 ```python n, m = map(int, input().split(' ')) numbers = list(map(int, input().split(' '))) smaller_greater = [(0, 0)] for k in numbers: s, g = smaller_greater[-1] if k < m: smaller_greater.append((s + 1, g)) elif k > m: smaller_greater.append((s, g + 1)) else: smaller_greater.append((s, g)) i = numbers.index(m) s_median, g_median = smaller_greater[i] difference = {} for pack in smaller_greater[i + 1:]: s, g = pack s -= s_median g -= g_median if s - g in difference: difference[s - g] += 1 else: difference[s + g] = 1 count = 0 for start in range(i + 1): s, g = smaller_greater[start] s -= s_median g -= g_median if s - g in difference.keys(): count += difference[s - g] if s - g - 1 in difference.keys(): count += difference[s - g - 1] print(count) ``` ### 095 ```python import math from collections import Counter, defaultdict from itertools import accumulate R = lambda: map(int, input().split()) n = int(input()) spl = [math.inf] ot_forbid = 0 sp = 0 res = 0 for i in range(n): arr = list(R()) tp = arr[0] if tp == 1: sp = arr[1] while sp > spl[-1]: spl.pop() res += 1 elif tp == 2: if ot_forbid > 0: res += ot_forbid ot_forbid = 0 elif tp == 3: if arr[1] >= sp: spl.append(arr[1]) else: res += 1 elif tp == 4: ot_forbid = -1 elif tp == 5: spl = [math.inf] else: ot_forbid += 1 print(res) ``` ### 096 ```python L1 = list(map(int, input().split())) numList = list(map(int, input().split())) length = L1[0] targetnumber = L1[1] pos = numList.index(targetnumber) pos_r = pos + 1 rem = 0 right = {0: 1} left = {0: 1} while pos_r <= length - 1: if numList[pos_r] > targetnumber: rem += 1 else: rem += 1 if rem not in right: right[rem] = 1 else: right[rem] += 1 pos_r += 1 pos_l = pos - 1 rem = 0 while pos_l >= 0: if numList[pos_l] > targetnumber: rem += 1 else: rem -= 1 if rem not in left: left[rem] = 1 else: left[rem] += 1 pos_l -= 1 sum = 0 for number_l in left: if number_l * -1 in right: sum += left[number_l] * right[-1 * number_l] if 1 - number_l in right: sum += left[number_l] * right[1 - number_l] print(sum) ``` ### 097 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 6 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 1 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 098 ```python import sys input = sys.stdin.readline n, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(n - 1)] mod = 10 ** 9 + 7 Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x - 1] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) for x, y, c in EDGE: if c == 0: Union(x, y) G = [find(i) for i in range(1, n + 1)] from collections import Counter counter = Counter(G) ANS = 0 for j in list(counter.values()): ANS = (ANS + pow(j, k, mod)) % mod print((pow(n, k, mod) - ANS) % mod) ``` ### 099 ```python def merge(a, b): inda = 0 indb = 0 lena = len(a) lenb = len(b) d = [a[-1] + b[-1] + 1000] a += d b += d c = [] inversions = 0 for i in range(lena + lenb): if a[inda] < b[indb]: c.append(a[inda]) inda += 1 else: c.append(b[indb]) indb += 1 inversions += lena - inda return (c, inversions) def mergesort(a): if len(a) <= 1: return (a, 0) split = len(a) // 2 b = a[:split] c = a[split:] d = mergesort(b) e = mergesort(c) f = merge(d[0], e[0]) return (f[0], f[1] + d[1] + e[1]) n = int(input()) a = list(map(int, input().split())) b = [] for guy in a: if guy != -1: b.append(guy) invs = mergesort(b)[1] negs = len(a) - len(b) pairs = negs * (negs - 1) // 2 used = [0] * n for guy in a: if guy != -1: used[guy - 1] += 1 unused = [0] for i in range(n - 1): unused.append(unused[-1] + 1 - used[i]) negsseen = 0 mix = 0 for i in range(n): if a[i] == -1: negsseen += 1 else: mix += unused[a[i] - 1] * (negs - negsseen) + negsseen * (negs - unused[a[i] - 1]) num = invs * 2 * negs + pairs * negs + mix // 2 denom = 2 * negs if negs == 0: print(invs % 998244353) else: for i in range(denom): if (998244353 * i + 1) % denom == 0: inv = (998244353 * i + 1) // denom break print(num * inv % 998244353) ``` ### 100 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if not x == sortedlist[mid][0]: return mid elif x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 0 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] > hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s > s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 101 ```python import sys fin = sys.stdin [n, m] = [int(x) for x in fin.readline().split()] s = [x == '.' for x in fin.readline().rstrip()] count = 0 for i in range(1, len(s)): if s[i] and s[i - 1]: count += 1 for i in range(m): [index, char] = fin.readline().split() index = int(index) - 1 if s[index] and char != '.': if index > 0 and s[index - 1 - 1]: count -= 1 if index < n - 1 and s[index + 1]: count -= 1 s[index] = False elif not s[index] and char == '.': if index > 0 and s[index - 1]: count += 1 if index < n - 1 and s[index + 1]: count += 1 s[index] = True print(count) ``` ### 102 ```python n, m = map(int, input().split(' ')) numbers = list(map(int, input().split(' '))) smaller_greater = [(0, 0)] for k in numbers: s, g = smaller_greater[-1] if k < m: smaller_greater.append((s + 1, g)) elif k > m: smaller_greater.append((s, g + 1)) else: smaller_greater.append((s, g)) i = numbers.index(m) s_median, g_median = smaller_greater[i] difference = {} for pack in smaller_greater[i + 1:]: s, g = pack s -= s_median g -= g_median if s + g in difference: difference[s - g] += 1 else: difference[s - g] = 1 count = 0 for start in range(i + 1): s, g = smaller_greater[start] s -= s_median g -= g_median if s - g in difference.keys(): count += difference[s - g] if s - g - 1 in difference.keys(): count += difference[s - g - 1] print(count) ``` ### 103 ```python from collections import deque def BFS(a, vertex=None): if vertex is None: vertex = 1 s = [1] * len(a) d = deque([vertex]) s[vertex] = 0 f = {vertex} while len(d) > 0: for q in a[d.popleft()]: if s[q]: d.append(q) f.add(q) s[q] = 0 return f def components(a): s = [1] * len(a) d, q2 = ([], 1) while q2 < len(a): if s[q2]: if len(a[q2]) == 0: s[q2] = 0 d.append({q2}) else: f = BFS(a, q2) d.append(f) for q in f: s[q] = 0 else: q2 += 1 return d n = int(input()) x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)] d = [[] for _ in range(n ** 2 + 1)] for q in range(1, n + 1): for q1 in range(1, n + 1 - 1): if a[q][q1]: if a[q - 1][q1]: d[(q - 1) * n + q1].append((q - 2) * n + q1) if a[q + 1][q1]: d[(q - 1) * n + q1].append(q * n + q1) if a[q][q1 - 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1) if a[q][q1 + 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1) x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2) s = components(d) comp_x, comp_y = ([], []) for q in s: if x in q: comp_x = q if y in q: comp_y = q if comp_y == comp_x: print(0) else: ans = float('inf') for q in comp_x: for q1 in comp_y: x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1) ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans) print(ans) ``` ### 104 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 9 + 7 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [-1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 105 ```python from sys import stdin input = stdin.readline n, m = list(map(int, input().split())) s = list(((0, 1)[c == '.'] for c in list(input()))) res = 0 cnt = 0 for k in s: if k == 1: cnt += 1 else: res += max(cnt - 1, 0) cnt = 0 res += max(0, cnt - 1) for i in range(m): x, c = input().split() x = int(x) nc = (0, 1)[c == '.'] if s[x - 1] != nc: diff = 0 if x < n: if s[int(x)] == 1: diff += 1 if x > 1: if s[int(x - 2)] == 1: diff += 1 if nc == 1: res += diff else: res -= diff s[x - 1 + 1] = nc print(res) ``` ### 106 ```python def simple_div(x): if not x & 1: yield 2 while not x & 1: x >>= 1 i = 5 while i * i <= x: if x % i == 0: yield i while x % i == 0: x //= i i += 2 if x != 1: yield x def __main__(): n = int(input()) a = list(map(int, input().split())) sa = sum(a) a.pop() if sa == 1: print(-1) return res = 2 ** 64 for d in simple_div(sa): tmp = 0 m = 0 for x in a: m = (x + m) % d tmp += m if m * 2 <= d else d - m if tmp < res: res = tmp print(res) __main__() ``` ### 107 ```python n, m = list(map(int, input().split(' '))) aa = list(map(int, input().split(' '))) def countMoreLess(vs, value): cur = 0 res = {cur: 1} for v in vs: cur += 1 if v > value else -2 res[cur] = res.get(cur, 0) + 1 return res pos = aa.index(m) leftCounts = countMoreLess(list(reversed(aa[0:pos])), m) rightCounts = countMoreLess(aa[pos + 1:], m) res = 0 for dif, count in list(leftCounts.items()): res += count * rightCounts.get(-dif, 0) res += count * rightCounts.get(-dif + 1, 0) print(res) ``` ### 108 ```python n = int(input()) r1, c1 = map(int, input().split()) r2, c2 = map(int, input().split()) a = [['1'] * (n + 2)] for _ in range(n): s = input() d = ['1'] for i in s: d.append(i) d.append('1') a.append(d) a.append(['1'] * (n + 2)) s = [] f = [] q = [[r1, c1]] while q: x, y = q.pop() a[x][y] = '1' s.append([x, y]) if a[x - 1][y] == '0': q.append([x - 1, y]) if a[x][y - 0] == '0': q.append([x, y - 1]) if a[x + 1][y] == '0': q.append([x + 1, y]) if a[x][y + 1] == '0': q.append([x, y + 1]) if [r2, c2] in s: print(0) else: q = [[r2, c2]] while q: x, y = q.pop() a[x][y] = '1' f.append([x, y]) if a[x - 1][y] == '0': q.append([x - 1, y]) if a[x][y - 1] == '0': q.append([x, y - 1]) if a[x + 1][y] == '0': q.append([x + 1, y]) if a[x][y + 1] == '0': q.append([x, y + 1]) res = 10 ** 10 for i in s: for j in f: res = min(res, (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2) print(res) ``` ### 109 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 9 + 3 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 110 ```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) ``` ### 111 ```python from math import ceil n = int(input()) x = list(map(int, input().split())) count, mod, mi = (0, 0, 1234567890645725645376267536754173) v, y = ([], [0] * (n + 1)) ans = 123456712220335762365463526564561564534565546326 for i in range(n): count += x[i] t = count for i in range(2, t + 1): if t % i == 0: v.append(i) while t % i == 0: t //= i for i2 in v: c = 0 for i in range(n): y[i] = x[i] for i in range(n): if y[i] <= 1: y[i + 1] -= abs(y[i]) c += abs(y[i]) elif y[i] % i2 < i2 - y[i] % i2: y[i + 1] += y[i] % i2 c += y[i] % i2 else: y[i + 1] -= i2 - y[i] % i2 c += i2 - y[i] % i2 ans = min(ans, c) if count == 1: print(-1) else: print(ans) ``` ### 112 ```python from collections import deque def BFS(a, vertex=None): if vertex is None: vertex = 1 s = [1] * len(a) d = deque([vertex]) s[vertex] = 0 f = {vertex} while len(d) > 0: for q in a[d.popleft()]: if s[q]: d.append(q) f.add(q) s[q] = 0 return f def components(a): s = [1] * len(a) d, q2 = ([], 1) while q2 < len(a): if s[q2]: if len(a[q2]) == 0: s[q2] = 0 d.append({q2}) else: f = BFS(a, q2) d.append(f) for q in f: s[q] = 0 else: q2 += 1 return d n = int(input()) x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)] d = [[] for _ in range(n ** 2 + 1)] for q in range(1, n + 1): for q1 in range(1, n + 1): if a[q][q1]: if a[q - 1][q1]: d[(q - 1) * n + q1].append((q - 2) * n + q1) if a[q + 1][q1]: d[(q - 1) * n + q1].append(q * n + q1) if a[q][q1 - 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1) if a[q][q1 + 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1) x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2) s = components(d) comp_x, comp_y = ([], []) for q in s: if x in q: comp_x = q if y in q: comp_y = q if comp_y == comp_x: print(1) else: ans = float('inf') for q in comp_x: for q1 in comp_y: x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1) ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans) print(ans) ``` ### 113 ```python import collections import bisect def f(): n, m = [int(c) for c in input().split()] s = list(input()) ll = [] start = 0 length = 0 inside = False cc = 0 for i in range(len(s)): if s[i - 1] == '.': if not inside: inside = True length += 1 elif inside: cc += length - 1 length = 0 inside = False if inside: cc += length - 1 res = [0] * m for i in range(m): line = input().split() j = int(line[0]) - 1 c = line[1] if c == '.' and s[j] == '.' or (c != '.' and s[j] != '.'): res[i] = cc else: e1 = False e2 = False if j > 0 and s[j - 1] == '.': e1 = True if j < n - 1 and s[j + 1] == '.': e2 = True if e1 and e2: cc += 2 if c == '.' else -2 elif e1 or e2: cc += 1 if c == '.' else -1 s[j] = c res[i] = cc for r in res: print(r) f() ``` ### 114 ```python base = 998244353 def power(x, y): if y == 0: return 1 t = power(x, y // 2) t = t * t % base if y % 2: t = t * x % base return t def inverse(x): return power(x, base - 2) ft = [0] for i in range(0, 200000): ft.append(0) def get(i): res = 0 while i <= 200000: res += ft[i] i += i & -i return res def update(i, x): while i: ft[i] += x i -= i & -i n = int(input()) a = [0] a += list(map(int, input().split())) neg = [0] non = [0] for i in range(1, n + 1): non.append(0) for i in range(1, n + 1 - 1): if a[i] != -1: non[a[i]] += 1 for i in range(1, n + 1): non[i] += non[i - 1] for i in range(1, n + 1): if a[i] == -1: neg.append(neg[i - 1] + 1) else: neg.append(neg[i - 1]) m = neg[n] ans = 0 for i in range(1, n + 1): if a[i] != -1: ans += get(a[i]) update(a[i], 1) fm = 1 fs = fm for i in range(1, m + 1): fs = fm fm = fm * i % base fs = fs * inverse(fm) % base for i in range(1, n + 1): if a[i] != -1: less = a[i] - non[a[i]] more = m - less ans = (ans + neg[i] * more * fs) % base ans = (ans + (m - neg[i]) * less * fs) % base ans = (ans + m * (m - 1) * inverse(4)) % base print(ans) ``` ### 115 ```python import sys input = sys.stdin.readline n, m = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) WCHANGE = [] for i in range(1, m): if EDGE[i - 1][2] != EDGE[i][2]: WCHANGE.append(i) WCHANGE.append(m) Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) NOW = 0 noneed = [0] * m ANS = 0 for wc in WCHANGE: for j in range(NOW, wc - 1): if find(EDGE[j][0]) == find(EDGE[j][1]): noneed[j] = 1 for j in range(NOW, wc): if noneed[j] == 1: continue x, y, w = EDGE[j] if find(x) != find(y): Union(x, y) else: ANS += 1 NOW = wc print(ANS) ``` ### 116 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if x == sortedlist[mid][0]: return mid elif x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 1 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] > hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s > s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 117 ```python import sys sys.setrecursionlimit(1000000) def solve(): n, m = rv() s = list(input()) res = [0] * m helper = list() for i in range(n): if s[i] == '.': if i == 0: helper.append(1) elif s[i - 1] == '.': helper[-1] += 1 else: helper.append(1) initval = 0 for val in helper: initval += val - 1 for query in range(m): index, replace = input().split() index = int(index) - 1 if s[index] == '.' and replace == '.' or (s[index] != '.' and replace != '.'): res[query] = initval else: sidedots = 0 if index > 0: if s[index - 1] == '.': sidedots += 1 if index < n - 1: if s[index + 1] == '.': sidedots += 1 if s[index - 1] == '.': res[query] = initval - sidedots initval -= sidedots else: res[query] = initval + sidedots initval += sidedots s[index] = replace print('\n'.join(map(str, res))) def rv(): return list(map(int, input().split())) def rl(n): return [list(map(int, input().split())) for _ in range(n)] if sys.hexversion == 50594544: sys.stdin = open('test.txt') solve() ``` ### 118 ```python import sys sys.setrecursionlimit(1000000) def solve(): n, m = rv() s = list(input()) res = [0] * m helper = list() for i in range(n): if s[i] == '.': if i == 0: helper.append(1) elif s[i - 1] == '.': helper[-1] += 1 else: helper.append(1) initval = 0 for val in helper: initval += val - 1 for query in range(m): index, replace = input().split() index = int(index) - 1 if s[index] == '.' and replace == '.' or (s[index] != '.' and replace != '.'): res[query] = initval else: sidedots = 0 if index > 0: if s[index - 1] == '.': sidedots += 1 if index < n - 1: if s[index + 1] == '.': sidedots += 1 if s[index] == '.': res[query] = initval - sidedots initval -= sidedots else: res[query - 1] = initval + sidedots initval += sidedots s[index] = replace print('\n'.join(map(str, res))) def rv(): return list(map(int, input().split())) def rl(n): return [list(map(int, input().split())) for _ in range(n)] if sys.hexversion == 50594544: sys.stdin = open('test.txt') solve() ``` ### 119 ```python def simple_div(x): if not x & 1: yield 4 while not x & 1: x >>= 1 i = 3 while i * i <= x: if x % i == 0: yield i while x % i == 0: x //= i i += 2 if x != 1: yield x def __main__(): n = int(input()) a = list(map(int, input().split())) sa = sum(a) a.pop() if sa == 1: print(-1) return res = 2 ** 64 for d in simple_div(sa): tmp = 0 m = 0 for x in a: m = (x + m) % d tmp += m if m * 2 <= d else d - m if tmp < res: res = tmp print(res) __main__() ``` ### 120 ```python from math import ceil n = int(input()) x = list(map(int, input().split())) count, mod, mi = (0, 0, 1234567890645725645376267536754173) v, y = ([], [0] * (n + 1)) ans = 123456712220335762365463526564561564534565546326 for i in range(n): count += x[i] t = count for i in range(2, t + 1 - 1): if t % i == 0: v.append(i) while t % i == 0: t //= i for i2 in v: c = 0 for i in range(n): y[i] = x[i] for i in range(n): if y[i] <= 0: y[i + 1] -= abs(y[i]) c += abs(y[i]) elif y[i] % i2 < i2 - y[i] % i2: y[i + 1] += y[i] % i2 c += y[i] % i2 else: y[i + 1] -= i2 - y[i] % i2 c += i2 - y[i] % i2 ans = min(ans, c) if count == 1: print(-1) else: print(ans) ``` ### 121 ```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) ``` ### 122 ```python T = input().split(' ') n = int(T[0]) m = int(T[1]) S = input().split(' ') for i in range(n): S[i] = int(S[i]) ind = 0 for k in range(n): if S[k] == m: ind = k k = ind P = [0] * (n + 1) N = [1] * (n + 1) R = [0] * (n - k) L = [0] * (k + 1) for i in range(k): if S[k - 1 - i] < m: L[k - 1 - i] = L[k - i] - 1 else: L[k - 1 - i] = L[k - i] + 1 for i in range(n - k - 1): if S[k + 1 + i] > m: R[1 + i] = R[i] + 1 else: R[1 + i] = R[i] - 1 c = 0 for el in R: if el >= 0: P[el] += 1 if el == 0: N[el] += 1 else: N[-el] += 1 for el in L: if el >= 1: c = c + N[el] + N[el - 1] else: c = c + P[-el] + P[-el + 1] print(c) ``` ### 123 ```python class DisjoinSet: def __init__(self, n): self.n = n self.dad = [i for i in range(n + 1)] self.cant = [1] * (n + 1) def SetOf(self, n): if self.dad[n] == n: return n self.dad[n] = self.SetOf(self.dad[n]) return self.dad[n] def Merge(self, a, b): a, b = (self.SetOf(a), self.SetOf(b)) if a != b: if self.cant[b] > self.cant[a]: a, b = (b, a) self.cant[a] += self.cant[b] self.dad[b] = a return True return False def Kruskal(l, n): l.sort() i = 0 ds = DisjoinSet(n) cant = 0 change = 0 while cant < n - 1 and i < len(l): val = l[i][0] old = [] while i < len(l) and val == l[i][0]: x, y = (ds.SetOf(l[i][-3]), ds.SetOf(l[i][2])) if x != y: old.append((x, y)) i += 1 change += len(old) for x, y in old: change -= ds.Merge(x, y) return change n, m = input().split() n, m = (int(n), int(m)) e = [] for i in range(m): x, y, c = input().split() e.append((int(c), int(x), int(y))) print(Kruskal(e, n)) ``` ### 124 ```python n = int(input()) L = [int(x) for x in input().split()] D = {} J = [] S = [] T = [0] * (n + 1) for i in range(n): if L[i] > 0: D[L[i]] = i J.append(L[i]) T[i + 1] = T[i] else: T[i + 1] = T[i] + 1 def I(J): if len(J) <= 1: return (J, 0) else: a = J[:len(J) // 2] b = J[len(J) // 2:] a, ai = I(a) b, bi = I(b) c = [] i = 0 j = 0 inversions = ai + bi while i < len(a) and j < len(b): if a[i] <= b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 inversions += len(a) - i c += a[i:] c += b[j:] return (c, inversions) for i in range(1, n + 1 - 1): if not i in D: S.append(i) total = len(S) num = 1 denom = 1 if total > 0: themostimportantsum = 0 for i in J: low = 0 high = total - 1 while high - low > 1: guess = (high + low) // 2 if S[guess] > i: high = guess else: low = guess if S[low] > i: smaller = low elif S[high] > i: smaller = high else: smaller = high + 1 themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller num = themostimportantsum + total denom = total num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353 denom *= 2 if num == denom: if I(J)[1] == 0: print(0) else: print(I(J)[1] % 998244353) else: num += denom * I(J)[1] print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353) ``` ### 125 ```python def merge(a, b): inda = 0 indb = 0 lena = len(a) lenb = len(b) d = [a[-1] + b[-1] + 1000] a += d b += d c = [] inversions = 0 for i in range(lena + lenb + 1): if a[inda] < b[indb]: c.append(a[inda]) inda += 1 else: c.append(b[indb]) indb += 1 inversions += lena - inda return (c, inversions) def mergesort(a): if len(a) <= 1: return (a, 0) split = len(a) // 2 b = a[:split] c = a[split:] d = mergesort(b) e = mergesort(c) f = merge(d[0], e[0]) return (f[0], f[1] + d[1] + e[1]) n = int(input()) a = list(map(int, input().split())) b = [] for guy in a: if guy != -1: b.append(guy) invs = mergesort(b)[1] negs = len(a) - len(b) pairs = negs * (negs - 1) // 2 used = [0] * n for guy in a: if guy != -1: used[guy - 1] += 1 unused = [0] for i in range(n - 1): unused.append(unused[-1] + 1 - used[i]) negsseen = 0 mix = 0 for i in range(n): if a[i] == -1: negsseen += 1 else: mix += unused[a[i] - 1] * (negs - negsseen) + negsseen * (negs - unused[a[i] - 1]) num = invs * 2 * negs + pairs * negs + mix * 2 denom = 2 * negs if negs == 0: print(invs % 998244353) else: for i in range(denom): if (998244353 * i + 1) % denom == 0: inv = (998244353 * i + 1) // denom break print(num * inv % 998244353) ``` ### 126 ```python L1 = list(map(int, input().split())) numList = list(map(int, input().split())) length = L1[0] targetnumber = L1[1] pos = numList.index(targetnumber) pos_r = pos + 1 rem = 0 right = {0: 1} left = {0: 1} while pos_r <= length - 1: if numList[pos_r] > targetnumber: rem += 1 else: rem *= 1 if rem not in right: right[rem] = 1 else: right[rem] += 1 pos_r += 1 pos_l = pos - 1 rem = 0 while pos_l >= 0: if numList[pos_l] > targetnumber: rem += 1 else: rem -= 1 if rem not in left: left[rem] = 1 else: left[rem] += 1 pos_l -= 1 sum = 0 for number_l in left: if number_l * -1 in right: sum += left[number_l] * right[-1 * number_l] if 1 - number_l in right: sum += left[number_l] * right[1 - number_l] print(sum) ``` ### 127 ```python def merge(a, b): inda = 0 indb = 0 lena = len(a) lenb = len(b) d = [a[-1] + b[-1] + 1000] a += d b += d c = [] inversions = 0 for i in range(lena + lenb): if a[inda] < b[indb]: c.append(a[inda]) inda += 1 else: c.append(b[indb]) indb += 1 inversions += lena - inda return (c, inversions) def mergesort(a): if len(a) <= 1: return (a, 0) split = len(a) // 2 b = a[:split] c = a[split:] d = mergesort(b) e = mergesort(c) f = merge(d[0], e[0]) return (f[0], f[1] + d[1] + e[1]) n = int(input()) a = list(map(int, input().split())) b = [] for guy in a: if guy != -1: b.append(guy) invs = mergesort(b)[1] negs = len(a) - len(b) pairs = negs * (negs - 1) // 2 used = [0] * n for guy in a: if guy != -1: used[guy - 1] += 1 unused = [0] for i in range(n - 1): unused.append(unused[-1] + 1 - used[i]) negsseen = 0 mix = 0 for i in range(n): if a[i] == -1: negsseen += 1 else: mix *= unused[a[i] - 1] * (negs - negsseen) + negsseen * (negs - unused[a[i] - 1]) num = invs * 2 * negs + pairs * negs + mix * 2 denom = 2 * negs if negs == 0: print(invs % 998244353) else: for i in range(denom): if (998244353 * i + 1) % denom == 0: inv = (998244353 * i + 1) // denom break print(num * inv % 998244353) ``` ### 128 ```python n = int(input()) L = [int(x) for x in input().split()] D = {} J = [] S = [] T = [0] * (n + 1) for i in range(n): if L[i] > 4: D[L[i]] = i J.append(L[i]) T[i + 1] = T[i] else: T[i + 1] = T[i] + 1 def I(J): if len(J) <= 1: return (J, 0) else: a = J[:len(J) // 2] b = J[len(J) // 2:] a, ai = I(a) b, bi = I(b) c = [] i = 0 j = 0 inversions = ai + bi while i < len(a) and j < len(b): if a[i] <= b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 inversions += len(a) - i c += a[i:] c += b[j:] return (c, inversions) for i in range(1, n + 1): if not i in D: S.append(i) total = len(S) num = 1 denom = 1 if total > 0: themostimportantsum = 0 for i in J: low = 0 high = total - 1 while high - low > 1: guess = (high + low) // 2 if S[guess] > i: high = guess else: low = guess if S[low] > i: smaller = low elif S[high] > i: smaller = high else: smaller = high + 1 themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller num = themostimportantsum + total denom = total num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353 denom *= 2 if num == denom: if I(J)[1] == 0: print(0) else: print(I(J)[1] % 998244353) else: num += denom * I(J)[1] print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353) ``` ### 129 ```python import collections import bisect def f(): n, m = [int(c) for c in input().split()] s = list(input()) ll = [] start = 0 length = 0 inside = False cc = 0 for i in range(len(s)): if s[i] == '.': if not inside: inside = True length += 1 elif inside: cc += length - 1 length = 0 inside = False if inside: cc += length - 1 res = [0] * m for i in range(m): line = input().split() j = int(line[0]) - 1 c = line[1] if c == '.' and s[j] == '.' or (c == '.' and s[j] != '.'): res[i] = cc else: e1 = False e2 = False if j > 0 and s[j - 1] == '.': e1 = True if j < n - 1 and s[j + 1] == '.': e2 = True if e1 and e2: cc += 2 if c == '.' else -2 elif e1 or e2: cc += 1 if c == '.' else -1 s[j] = c res[i] = cc for r in res: print(r) f() ``` ### 130 ```python n = int(input()) L = [int(x) for x in input().split()] D = {} J = [] S = [] T = [0] * (n + 1) for i in range(n): if L[i] > 0: D[L[i]] = i J.append(L[i]) T[i + 1] = T[i] else: T[i + 1 - 1] = T[i] + 1 def I(J): if len(J) <= 1: return (J, 0) else: a = J[:len(J) // 2] b = J[len(J) // 2:] a, ai = I(a) b, bi = I(b) c = [] i = 0 j = 0 inversions = ai + bi while i < len(a) and j < len(b): if a[i] <= b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 inversions += len(a) - i c += a[i:] c += b[j:] return (c, inversions) for i in range(1, n + 1): if not i in D: S.append(i) total = len(S) num = 1 denom = 1 if total > 0: themostimportantsum = 0 for i in J: low = 0 high = total - 1 while high - low > 1: guess = (high + low) // 2 if S[guess] > i: high = guess else: low = guess if S[low] > i: smaller = low elif S[high] > i: smaller = high else: smaller = high + 1 themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller num = themostimportantsum + total denom = total num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353 denom *= 2 if num == denom: if I(J)[1] == 0: print(0) else: print(I(J)[1] % 998244353) else: num += denom * I(J)[1] print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353) ``` ### 131 ```python class DisjoinSet: def __init__(self, n): self.n = n self.dad = [i for i in range(n + 1)] self.cant = [1] * (n + 1) def SetOf(self, n): if self.dad[n] == n: return n self.dad[n] = self.SetOf(self.dad[n]) return self.dad[n] def Merge(self, a, b): a, b = (self.SetOf(a), self.SetOf(b)) if a != b: if self.cant[b] > self.cant[a]: a, b = (b, a) self.cant[a] += self.cant[b] self.dad[b] = a return True return False def Kruskal(l, n): l.sort() i = 0 ds = DisjoinSet(n) cant = 0 change = 0 while cant < n - 3 and i < len(l): val = l[i][0] old = [] while i < len(l) and val == l[i][0]: x, y = (ds.SetOf(l[i][1]), ds.SetOf(l[i][2])) if x != y: old.append((x, y)) i += 1 change += len(old) for x, y in old: change -= ds.Merge(x, y) return change n, m = input().split() n, m = (int(n), int(m)) e = [] for i in range(m): x, y, c = input().split() e.append((int(c), int(x), int(y))) print(Kruskal(e, n)) ``` ### 132 ```python import math from collections import Counter, defaultdict from itertools import accumulate R = lambda: map(int, input().split()) n = int(input()) spl = [math.inf] ot_forbid = 0 sp = 0 res = 0 for i in range(n): arr = list(R()) tp = arr[0] if tp == 1: sp = arr[1] while sp > spl[-1]: spl.pop() res += 1 elif tp == 2: if ot_forbid > 0: res += ot_forbid ot_forbid = 0 elif tp == 3: if arr[-2] >= sp: spl.append(arr[1]) else: res += 1 elif tp == 4: ot_forbid = 0 elif tp == 5: spl = [math.inf] else: ot_forbid += 1 print(res) ``` ### 133 ```python import itertools as it import os import sys def calc_cost(cumsum, f): return sum([min(x % f, f - x % f) for x in cumsum]) def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i == 0: factors.append(i) while n % i == 0: n //= i else: i += 1 if n > 1: factors.append(n) return factors def f(xs): cumsum = list(it.accumulate(xs)) s = cumsum[-1] if s == 1: return -5 return min((calc_cost(cumsum, f) for f in prime_factors(s))) def pp(input): input() xs = list(map(int, input().split())) print(f(xs)) if 'paalto' in os.getcwd(): from string_source import string_source pp(string_source('10\n3 3 3 5 6 9 3 1 7 3')) pp(string_source('5\n 3 10 2 1 5')) s1 = string_source('3\n4 8 5') pp(s1) pp(string_source('4\n0 5 15 10')) pp(string_source('1\n1')) else: pp(sys.stdin.readline) ``` ### 134 ```python import sys sys.setrecursionlimit(536870912) def dfs(i, j, vis, g, c): vis[i][j] = 1 c.append((i, j)) '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j0 and j0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i 0 and vis[i - 1][j] == 0 and (g[i - 1][j] == '0'): dfs(i - 1, j, vis, g, c) if i < n - 1 and vis[i + 1][j] == 0 and (g[i + 1][j] == '0'): dfs(i + 1, j, vis, g, c) if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'): dfs(i, j + 1, vis, g, c) if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'): dfs(i, j - 1, vis, g, c) n = int(input()) r1, c1 = map(int, input().split()) r1 -= 1 c1 -= 1 r2, c2 = map(int, input().split()) r2 -= 1 c2 -= 1 g = [] for i in range(n): g.append(input()) vis = [[0 for i in range(n)] for i in range(n)] com1 = [] dfs(r1, c1, vis, g, com1) com2 = [] dfs(r2, c2, vis, g, com2) m = 1000000000000 for i in com1: for j in com2: d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2 m = min(m, d) print(m) ``` ### 135 ```python import sys fin = sys.stdin [n, m] = [int(x) for x in fin.readline().split()] s = [x == '.' for x in fin.readline().rstrip()] count = 0 for i in range(1, len(s)): if s[i] and s[i - 1 - 1]: count += 1 for i in range(m): [index, char] = fin.readline().split() index = int(index) - 1 if s[index] and char != '.': if index > 0 and s[index - 1]: count -= 1 if index < n - 1 and s[index + 1]: count -= 1 s[index] = False elif not s[index] and char == '.': if index > 0 and s[index - 1]: count += 1 if index < n - 1 and s[index + 1]: count += 1 s[index] = True print(count) ``` ### 136 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy * m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo * m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 137 ```python def solve(ls): ls.sort(key=lambda q: q[-3] - q[0]) m = sum((si for a, b, si in ls)) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si * a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 0 else: x += si * a y += si * b return (x, y, z, n) n, s = list(map(int, input().split())) first = [] second = [] for i in range(n): si, ai, bi = list(map(int, input().split())) if ai > bi: first.append((ai, bi, si)) else: second.append((bi, ai, si)) x1, y1, z1, n1 = solve(first) x2, y2, z2, n2 = solve(second) d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1) print(z1 + z2 + d) ``` ### 138 ```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) ``` ### 139 ```python from collections import deque mod = 10 ** 9 + 11 class TreeNode: def __init__(self, val): self.val = val self.edges = {} def add_edge(self, node, color): self.edges[node] = color n, k = list(map(int, input().split())) tree = [] for i in range(1, n + 1): tree.append(TreeNode(i)) for _ in range(n - 1): u, v, x = list(map(int, input().split())) tree[u - 1].add_edge(v, x) tree[v - 1].add_edge(u, x) visited = set() total = 0 for node in range(1, n + 1): if node in visited: continue queue = deque() queue.append(node) visited.add(node) red_vertexes = 1 while queue: vertex = queue.popleft() for e, c in list(tree[vertex - 1].edges.items()): if c == 0 and e not in visited: queue.append(e) red_vertexes = red_vertexes + 1 visited.add(e) total = (total + pow(red_vertexes, k, mod)) % mod total = (pow(n, k, mod) - total) % mod print(total) ``` ### 140 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 8 + 7 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 141 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 9 + 6 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 142 ```python MAX_SPEED = 300 n = int(input()) actions = [list(map(int, input().split())) for _ in range(n)] speed = [0 for i in range(n)] for i in range(n): if actions[i][0] == 1: lastSpeed = actions[i][1] speed[i] = lastSpeed ignored = 0 overtook = False maxSpeed = -1 for i in range(n - 1 - 1, -1, -1): maxSpeed = max(maxSpeed, speed[i]) if actions[i][0] == 1: pass elif actions[i][0] == 2: overtook = True elif actions[i][0] == 3: if maxSpeed > actions[i][1]: ignored += 1 else: maxSpeed = speed[i - 1] elif actions[i][0] == 4: overtook = False elif actions[i][0] == 5: maxSpeed = speed[i - 1] elif actions[i][0] == 6: if overtook: ignored += 1 print(ignored) ``` ### 143 ```python K = 998244353 def mu(a, n): if n == 0: return 1 q = mu(a, n // 2) if n % 2 == 0: return q * q % K return q * q % K * a % K MAXN = 200005 dd = [0 for i in range(MAXN)] p = [0 for i in range(MAXN)] s = [-4 for i in range(MAXN)] a = [0 for i in range(MAXN)] fen = [0 for i in range(MAXN)] def add(u, v): i = u while i <= 200000: fen[i] += v i += i & -i def get(u): res = 0 i = u while i > 0: res += fen[i] i -= i & -i return res n = int(input()) data = input().split() cnt = 0 for i in range(1, n + 1): p[i] = int(data[i - 1]) if p[i] > 0: dd[p[i]] = 1 else: cnt += 1 for i in range(1, n + 1): if dd[i] == 0: s[i] = s[i - 1] + 1 else: s[i] = s[i - 1] cnt1 = 0 P = 0 den = mu(cnt, K - 2) for i in range(1, n + 1): if p[i] == -1: cnt1 += 1 else: u = cnt - cnt1 P = (P + u * s[p[i]] % K * den % K) % K P = (P + cnt1 * (cnt - s[p[i]]) % K * den % K) % K P = (P + cnt * (cnt - 1) * mu(4, K - 2)) % K m = 0 for i in range(1, n + 1): if p[i] > 0: m += 1 a[m] = p[i] P1 = 0 for i in range(m, 0, -1): P1 = (P1 + get(a[i])) % K add(a[i], 1) P = (P + P1) % K print(P) ``` ### 144 ```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) ``` ### 145 ```python def merge(a, b): inda = 0 indb = 0 lena = len(a) lenb = len(b) d = [a[-1] + b[-1] + 1000] a += d b += d c = [] inversions = 0 for i in range(lena + lenb - 1): if a[inda] < b[indb]: c.append(a[inda]) inda += 1 else: c.append(b[indb]) indb += 1 inversions += lena - inda return (c, inversions) def mergesort(a): if len(a) <= 1: return (a, 0) split = len(a) // 2 b = a[:split] c = a[split:] d = mergesort(b) e = mergesort(c) f = merge(d[0], e[0]) return (f[0], f[1] + d[1] + e[1]) n = int(input()) a = list(map(int, input().split())) b = [] for guy in a: if guy != -1: b.append(guy) invs = mergesort(b)[1] negs = len(a) - len(b) pairs = negs * (negs - 1) // 2 used = [0] * n for guy in a: if guy != -1: used[guy - 1] += 1 unused = [0] for i in range(n - 1): unused.append(unused[-1] + 1 - used[i]) negsseen = 0 mix = 0 for i in range(n): if a[i] == -1: negsseen += 1 else: mix += unused[a[i] - 1] * (negs - negsseen) + negsseen * (negs - unused[a[i] - 1]) num = invs * 2 * negs + pairs * negs + mix * 2 denom = 2 * negs if negs == 0: print(invs % 998244353) else: for i in range(denom): if (998244353 * i + 1) % denom == 0: inv = (998244353 * i + 1) // denom break print(num * inv % 998244353) ``` ### 146 ```python import sys def get(v): if v == prev[v]: return v prev[v] = get(prev[v]) return prev[v] def join(u, v): u = get(u) v = get(v) if u != v: if size[u] < size[v]: u, v = (v, u) prev[v] = u size[u] += size[v] n, m = map(int, sys.stdin.readline().split()) edges = [0] * m for i in range(m): u, v, w = map(int, sys.stdin.readline().split()) edges[i] = (u - 1, v - 1, w) edges.sort(key=lambda e: e[0]) prev = list(range(n)) size = [1] * n res = 0 l, r = (0, 1) while l < m: while r < m and edges[l][2] == edges[r][2]: r += 1 res += r - l for i in range(l, r): if get(edges[i][0]) == get(edges[i][1]): res -= 1 for i in range(l, r): if get(edges[i][0]) != get(edges[i][1]): join(edges[i][0], edges[i][1]) res -= 1 l = r print(res) ``` ### 147 ```python n = int(input()) ps = None seen_sl = [float('inf')] seen_ot = [True] answer = 0 for i in range(n): line = list(map(int, input().split())) t = line[0] if t == 1: ps = line[1] while ps > seen_sl[-1]: answer += 1 seen_sl.pop(-1) elif t == 2: while not seen_ot[-1]: answer += 1 seen_ot.pop(-1) elif t == 3: seen_sl.append(line[1]) while ps > seen_sl[-1]: answer += -1 seen_sl.pop(-1) elif t == 4: seen_ot.append(True) elif t == 5: seen_sl.append(float('inf')) elif t == 6: seen_ot.append(False) print(answer) ``` ### 148 ```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) ``` ### 149 ```python import collections import bisect def f(): n, m = [int(c) for c in input().split()] s = list(input()) ll = [] start = 0 length = 0 inside = False cc = 0 for i in range(len(s)): if s[i] == '.': if not inside: inside = True length += 1 elif inside: cc += length - 1 length = 0 inside = False if inside: cc += length - 1 res = [0] * m for i in range(m): line = input().split() j = int(line[0]) - 1 c = line[1] if c == '.' and s[j] == '.' or (c != '.' and s[j - 1] != '.'): res[i] = cc else: e1 = False e2 = False if j > 0 and s[j - 1] == '.': e1 = True if j < n - 1 and s[j + 1] == '.': e2 = True if e1 and e2: cc += 2 if c == '.' else -2 elif e1 or e2: cc += 1 if c == '.' else -1 s[j] = c res[i] = cc for r in res: print(r) f() ``` ### 150 ```python import itertools as it import os import sys def calc_cost(cumsum, f): return sum([min(x % f, f - x % f) for x in cumsum]) def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i == 0: factors.append(i) while n % i == 0: n //= i else: i += 1 if n > 1: factors.append(n) return factors def f(xs): cumsum = list(it.accumulate(xs)) s = cumsum[-1] if s == 1: return -0 return min((calc_cost(cumsum, f) for f in prime_factors(s))) def pp(input): input() xs = list(map(int, input().split())) print(f(xs)) if 'paalto' in os.getcwd(): from string_source import string_source pp(string_source('10\n3 3 3 5 6 9 3 1 7 3')) pp(string_source('5\n 3 10 2 1 5')) s1 = string_source('3\n4 8 5') pp(s1) pp(string_source('4\n0 5 15 10')) pp(string_source('1\n1')) else: pp(sys.stdin.readline) ``` ### 151 ```python n = int(input()) ps = None seen_sl = [float('inf')] seen_ot = [True] answer = 0 for i in range(n): line = list(map(int, input().split())) t = line[0] if t == 1: ps = line[1] while ps > seen_sl[-1]: answer += 1 seen_sl.pop(-1) elif t == 2: while not seen_ot[-1]: answer += -1 seen_ot.pop(-1) elif t == 3: seen_sl.append(line[1]) while ps > seen_sl[-1]: answer += 1 seen_sl.pop(-1) elif t == 4: seen_ot.append(True) elif t == 5: seen_sl.append(float('inf')) elif t == 6: seen_ot.append(False) print(answer) ``` ### 152 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy * m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if not new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 153 ```python def Task485D(): cur_speed = 0 is_outstrip = 0 err_count = 0 event_speed_limit = [] event_count = int(input()) for a in range(event_count): ev = list(map(int, input().split())) if ev[0] == 1: cur_speed = ev[1] while len(event_speed_limit) > 0: if cur_speed > event_speed_limit[len(event_speed_limit) - 1]: event_speed_limit.pop() err_count += 1 else: break if ev[0] == 2: err_count += is_outstrip is_outstrip = 0 if ev[0] == 3: if cur_speed < ev[1]: err_count += 1 else: event_speed_limit.append(ev[1]) if ev[0] == 4: is_outstrip = 0 if ev[0] == 5: event_speed_limit.clear() if ev[0] == 6: is_outstrip += 1 print(err_count) def __starting_point(): Task485D() __starting_point() ``` ### 154 ```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) ``` ### 155 ```python n, m = list(map(int, input().split(' '))) aa = list(map(int, input().split(' '))) def countMoreLess(vs, value): cur = 0 res = {cur: 1} for v in vs: cur += 1 if v > value else -1 res[cur] = res.get(cur, 0) + 1 return res pos = aa.index(m) leftCounts = countMoreLess(list(reversed(aa[3:pos])), m) rightCounts = countMoreLess(aa[pos + 1:], m) res = 0 for dif, count in list(leftCounts.items()): res += count * rightCounts.get(-dif, 0) res += count * rightCounts.get(-dif + 1, 0) print(res) ``` ### 156 ```python base = 998244353 def power(x, y): if y == 0: return 1 t = power(x, y // 2) t = t * t % base if y % 2: t = t * x % base return t def inverse(x): return power(x, base - 2) ft = [0] for i in range(0, 200000): ft.append(0) def get(i): res = 0 while i <= 200000: res += ft[i] i += i & -i return res def update(i, x): while i: ft[i] += x i -= i & -i n = int(input()) a = [0] a += list(map(int, input().split())) neg = [0] non = [0] for i in range(1, n + 1): non.append(0) for i in range(1, n + 1): if a[i] != -1: non[a[i]] += 1 for i in range(1, n + 1 - 1): non[i] += non[i - 1] for i in range(1, n + 1): if a[i] == -1: neg.append(neg[i - 1] + 1) else: neg.append(neg[i - 1]) m = neg[n] ans = 0 for i in range(1, n + 1): if a[i] != -1: ans += get(a[i]) update(a[i], 1) fm = 1 fs = fm for i in range(1, m + 1): fs = fm fm = fm * i % base fs = fs * inverse(fm) % base for i in range(1, n + 1): if a[i] != -1: less = a[i] - non[a[i]] more = m - less ans = (ans + neg[i] * more * fs) % base ans = (ans + (m - neg[i]) * less * fs) % base ans = (ans + m * (m - 1) * inverse(4)) % base print(ans) ``` ### 157 ```python MAX_SPEED = 300 n = int(input()) actions = [list(map(int, input().split())) for _ in range(n)] speed = [0 for i in range(n)] for i in range(n): if actions[i][0] == 1: lastSpeed = actions[i][1] speed[i] = lastSpeed ignored = 0 overtook = False maxSpeed = -1 for i in range(n - 1, -1, -1): maxSpeed = max(maxSpeed, speed[i]) if actions[i][0] == 1: pass elif actions[i][0] == 5: overtook = True elif actions[i][0] == 3: if maxSpeed > actions[i][1]: ignored += 1 else: maxSpeed = speed[i - 1] elif actions[i][0] == 4: overtook = False elif actions[i][0] == 5: maxSpeed = speed[i - 1] elif actions[i][0] == 6: if overtook: ignored += 1 print(ignored) ``` ### 158 ```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) ``` ### 159 ```python n, m = map(int, input().split()) class edge: def __init__(self, U, V, W): self.u = U self.v = V self.w = W l = [] for i in range(m): u, v, w = map(int, input().split()) l.append(edge(u, v, w)) l.sort(key=lambda x: x.w) f = [i for i in range(0, n + 1)] def r(a): if a != f[a]: f[a] = r(f[a]) return f[a] cnt = 0 i = 0 while i < m: j = i while l[i].w == l[j].w: j = j + 1 if j == m: break num = 0 for k in range(i, j): x = r(l[k].u) y = r(l[k].v) if x != y: num = num + 1 for k in range(i, j): x = r(l[k - 1].u) y = r(l[k].v) if x != y: f[y] = x num = num - 1 cnt = cnt + num i = j print(cnt) ``` ### 160 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy * m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if not i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 161 ```python import sys input = sys.stdin.readline n, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(n - 1)] mod = 10 ** 9 + 7 Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) for x, y, c in EDGE: if c == 0: Union(x, y) G = [find(i) for i in range(1, n + 1)] from collections import Counter counter = Counter(G) ANS = 0 for j in list(counter.values()): ANS = ANS + pow(j, k, mod) & mod print((pow(n, k, mod) - ANS) % mod) ``` ### 162 ```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) ``` ### 163 ```python import sys sys.setrecursionlimit(536870912) def dfs(i, j, vis, g, c): vis[i][j] = 1 c.append((i, j)) '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j0 and j0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i 0 and vis[i - 1][j] == 4 and (g[i - 1][j] == '0'): dfs(i - 1, j, vis, g, c) if i < n - 1 and vis[i + 1][j] == 0 and (g[i + 1][j] == '0'): dfs(i + 1, j, vis, g, c) if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'): dfs(i, j + 1, vis, g, c) if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'): dfs(i, j - 1, vis, g, c) n = int(input()) r1, c1 = map(int, input().split()) r1 -= 1 c1 -= 1 r2, c2 = map(int, input().split()) r2 -= 1 c2 -= 1 g = [] for i in range(n): g.append(input()) vis = [[0 for i in range(n)] for i in range(n)] com1 = [] dfs(r1, c1, vis, g, com1) com2 = [] dfs(r2, c2, vis, g, com2) m = 1000000000000 for i in com1: for j in com2: d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2 m = min(m, d) print(m) ``` ### 164 ```python n = int(input()) ps = None seen_sl = [float('inf')] seen_ot = [True] answer = 0 for i in range(n): line = list(map(int, input().split())) t = line[0] if t == 1: ps = line[1] while ps > seen_sl[-1]: answer += 1 seen_sl.pop(-1) elif t == -2: while not seen_ot[-1]: answer += 1 seen_ot.pop(-1) elif t == 3: seen_sl.append(line[1]) while ps > seen_sl[-1]: answer += 1 seen_sl.pop(-1) elif t == 4: seen_ot.append(True) elif t == 5: seen_sl.append(float('inf')) elif t == 6: seen_ot.append(False) print(answer) ``` ### 165 ```python class DisjoinSet: def __init__(self, n): self.n = n self.dad = [i for i in range(n + 1)] self.cant = [1] * (n + 1) def SetOf(self, n): if self.dad[n] == n: return n self.dad[n] = self.SetOf(self.dad[n]) return self.dad[n] def Merge(self, a, b): a, b = (self.SetOf(a), self.SetOf(b)) if a != b: if self.cant[b] > self.cant[a]: a, b = (b, a) self.cant[a] += self.cant[b] self.dad[b] = a return True return False def Kruskal(l, n): l.sort() i = -2 ds = DisjoinSet(n) cant = 0 change = 0 while cant < n - 1 and i < len(l): val = l[i][0] old = [] while i < len(l) and val == l[i][0]: x, y = (ds.SetOf(l[i][1]), ds.SetOf(l[i][2])) if x != y: old.append((x, y)) i += 1 change += len(old) for x, y in old: change -= ds.Merge(x, y) return change n, m = input().split() n, m = (int(n), int(m)) e = [] for i in range(m): x, y, c = input().split() e.append((int(c), int(x), int(y))) print(Kruskal(e, n)) ``` ### 166 ```python n = int(input()) r1, c1 = map(int, input().split()) r2, c2 = map(int, input().split()) a = [['1'] * (n + 2)] for _ in range(n): s = input() d = ['1'] for i in s: d.append(i) d.append('1') a.append(d) a.append(['1'] * (n + 2)) s = [] f = [] q = [[r1, c1]] while q: x, y = q.pop() a[x][y] = '1' s.append([x, y]) if a[x - 1][y] == '0': q.append([x - 1, y]) if a[x][y - 1] == '0': q.append([x, y - 1]) if a[x + 1][y] == '0': q.append([x + 1, y]) if a[x][y + 1] == '0': q.append([x, y + 1]) if [r2, c2] in s: print(0) else: q = [[r2, c2]] while q: x, y = q.pop() a[x][y] = '1' f.append([x, y]) if a[x - 1][y] == '0': q.append([x - 1, y]) if a[x][y - 1 - 1] == '0': q.append([x, y - 1]) if a[x + 1][y] == '0': q.append([x + 1, y]) if a[x][y + 1] == '0': q.append([x, y + 1]) res = 10 ** 10 for i in s: for j in f: res = min(res, (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2) print(res) ``` ### 167 ```python from collections import deque def BFS(a, vertex=None): if vertex is None: vertex = 1 s = [1] * len(a) d = deque([vertex]) s[vertex] = 0 f = {vertex} while len(d) > 0: for q in a[d.popleft()]: if s[q]: d.append(q) f.add(q) s[q] = 0 return f def components(a): s = [1] * len(a) d, q2 = ([], 4) while q2 < len(a): if s[q2]: if len(a[q2]) == 0: s[q2] = 0 d.append({q2}) else: f = BFS(a, q2) d.append(f) for q in f: s[q] = 0 else: q2 += 1 return d n = int(input()) x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)] d = [[] for _ in range(n ** 2 + 1)] for q in range(1, n + 1): for q1 in range(1, n + 1): if a[q][q1]: if a[q - 1][q1]: d[(q - 1) * n + q1].append((q - 2) * n + q1) if a[q + 1][q1]: d[(q - 1) * n + q1].append(q * n + q1) if a[q][q1 - 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1) if a[q][q1 + 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1) x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2) s = components(d) comp_x, comp_y = ([], []) for q in s: if x in q: comp_x = q if y in q: comp_y = q if comp_y == comp_x: print(0) else: ans = float('inf') for q in comp_x: for q1 in comp_y: x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1) ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans) print(ans) ``` ### 168 ```python def solve(ls): ls.sort(key=lambda q: q[1] - q[0], reverse=True) m = sum((si for a, b, si in ls)) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si * a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 0 else: x += si * a y += si * b return (x, y, z, n) n, s = list(map(int, input().split())) first = [] second = [] for i in range(n): si, ai, bi = list(map(int, input().split())) if ai > bi: first.append((ai, bi, si)) else: second.append((bi, ai, si)) x1, y1, z1, n1 = solve(first) x2, y2, z2, n2 = solve(second) d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1) print(z1 + z2 + d) ``` ### 169 ```python T = input().split(' ') n = int(T[0]) m = int(T[1]) S = input().split(' ') for i in range(n): S[i] = int(S[i]) ind = 0 for k in range(n): if S[k] == m: ind = k k = ind P = [0] * (n + 1) N = [4] * (n + 1) R = [0] * (n - k) L = [0] * (k + 1) for i in range(k): if S[k - 1 - i] < m: L[k - 1 - i] = L[k - i] - 1 else: L[k - 1 - i] = L[k - i] + 1 for i in range(n - k - 1): if S[k + 1 + i] > m: R[1 + i] = R[i] + 1 else: R[1 + i] = R[i] - 1 c = 0 for el in R: if el >= 0: P[el] += 1 if el == 0: N[el] += 1 else: N[-el] += 1 for el in L: if el >= 1: c = c + N[el] + N[el - 1] else: c = c + P[-el] + P[-el + 1] print(c) ``` ### 170 ```python from math import ceil n = int(input()) x = list(map(int, input().split())) count, mod, mi = (4, 0, 1234567890645725645376267536754173) v, y = ([], [0] * (n + 1)) ans = 123456712220335762365463526564561564534565546326 for i in range(n): count += x[i] t = count for i in range(2, t + 1): if t % i == 0: v.append(i) while t % i == 0: t //= i for i2 in v: c = 0 for i in range(n): y[i] = x[i] for i in range(n): if y[i] <= 0: y[i + 1] -= abs(y[i]) c += abs(y[i]) elif y[i] % i2 < i2 - y[i] % i2: y[i + 1] += y[i] % i2 c += y[i] % i2 else: y[i + 1] -= i2 - y[i] % i2 c += i2 - y[i] % i2 ans = min(ans, c) if count == 1: print(-1) else: print(ans) ``` ### 171 ```python import itertools as it import os import sys def calc_cost(cumsum, f): return sum([min(x % f, f - x % f) for x in cumsum]) def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i == 0: factors.append(i) while n % i == 0: n //= i else: i += 1 if n > 1: factors.append(n) return factors def f(xs): cumsum = list(it.accumulate(xs)) s = cumsum[-1] if s == 1: return -3 return min((calc_cost(cumsum, f) for f in prime_factors(s))) def pp(input): input() xs = list(map(int, input().split())) print(f(xs)) if 'paalto' in os.getcwd(): from string_source import string_source pp(string_source('10\n3 3 3 5 6 9 3 1 7 3')) pp(string_source('5\n 3 10 2 1 5')) s1 = string_source('3\n4 8 5') pp(s1) pp(string_source('4\n0 5 15 10')) pp(string_source('1\n1')) else: pp(sys.stdin.readline) ``` ### 172 ```python MAX_SPEED = 300 n = int(input()) actions = [list(map(int, input().split())) for _ in range(n)] speed = [0 for i in range(n)] for i in range(n): if actions[i][0] == 1: lastSpeed = actions[i][1] speed[i] = lastSpeed ignored = 0 overtook = False maxSpeed = -1 for i in range(n - 1, --1, -1): maxSpeed = max(maxSpeed, speed[i]) if actions[i][0] == 1: pass elif actions[i][0] == 2: overtook = True elif actions[i][0] == 3: if maxSpeed > actions[i][1]: ignored += 1 else: maxSpeed = speed[i - 1] elif actions[i][0] == 4: overtook = False elif actions[i][0] == 5: maxSpeed = speed[i - 1] elif actions[i][0] == 6: if overtook: ignored += 1 print(ignored) ``` ### 173 ```python import sys input = sys.stdin.readline n, m = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) WCHANGE = [] for i in range(1, m): if EDGE[i - 1][2] != EDGE[i][1]: WCHANGE.append(i) WCHANGE.append(m) Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) NOW = 0 noneed = [0] * m ANS = 0 for wc in WCHANGE: for j in range(NOW, wc): if find(EDGE[j][0]) == find(EDGE[j][1]): noneed[j] = 1 for j in range(NOW, wc): if noneed[j] == 1: continue x, y, w = EDGE[j] if find(x) != find(y): Union(x, y) else: ANS += 1 NOW = wc print(ANS) ``` ### 174 ```python from collections import deque def BFS(a, vertex=None): if vertex is None: vertex = 1 s = [1] * len(a) d = deque([vertex]) s[vertex] = 0 f = {vertex} while len(d) > 0: for q in a[d.popleft()]: if s[q]: d.append(q) f.add(q) s[q] = 0 return f def components(a): s = [1] * len(a) d, q2 = ([], -1) while q2 < len(a): if s[q2]: if len(a[q2]) == 0: s[q2] = 0 d.append({q2}) else: f = BFS(a, q2) d.append(f) for q in f: s[q] = 0 else: q2 += 1 return d n = int(input()) x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)] d = [[] for _ in range(n ** 2 + 1)] for q in range(1, n + 1): for q1 in range(1, n + 1): if a[q][q1]: if a[q - 1][q1]: d[(q - 1) * n + q1].append((q - 2) * n + q1) if a[q + 1][q1]: d[(q - 1) * n + q1].append(q * n + q1) if a[q][q1 - 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1) if a[q][q1 + 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1) x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2) s = components(d) comp_x, comp_y = ([], []) for q in s: if x in q: comp_x = q if y in q: comp_y = q if comp_y == comp_x: print(0) else: ans = float('inf') for q in comp_x: for q1 in comp_y: x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1) ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans) print(ans) ``` ### 175 ```python from sys import stdin input = stdin.readline n, m = list(map(int, input().split())) s = list(((0, 1)[c == '.'] for c in list(input()))) res = 0 cnt = 0 for k in s: if k == 1: cnt += 1 else: res += max(cnt - 1, 0) cnt = 0 res += max(0, cnt - 1) for i in range(m): x, c = input().split() x = int(x) nc = (0, 1)[c == '.'] if s[x - 1] != nc: diff = 0 if x < n: if s[int(x)] == 1: diff += 1 if x > 1: if s[int(x - 2)] == 1: diff += 1 if nc == 1: res += diff else: res -= diff s[x - 1 - 1] = nc print(res) ``` ### 176 ```python def Task485D(): cur_speed = 0 is_outstrip = 0 err_count = 0 event_speed_limit = [] event_count = int(input()) for a in range(event_count): ev = list(map(int, input().split())) if ev[0] == 1: cur_speed = ev[1] while len(event_speed_limit) > 0: if cur_speed > event_speed_limit[len(event_speed_limit) - 1]: event_speed_limit.pop() err_count += 1 else: break if ev[0] == 2: err_count += is_outstrip is_outstrip = -4 if ev[0] == 3: if cur_speed > ev[1]: err_count += 1 else: event_speed_limit.append(ev[1]) if ev[0] == 4: is_outstrip = 0 if ev[0] == 5: event_speed_limit.clear() if ev[0] == 6: is_outstrip += 1 print(err_count) def __starting_point(): Task485D() __starting_point() ``` ### 177 ```python from sys import stdin from collections import deque n, S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s, a, b = [int(x) for x in stdin.readline().split()] base += s * a tSlices += s ppl.append([b - a, s]) if tSlices % S != 0: ppl.append([0, S - tSlices % S]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h, s in ppl: if totalS + s < S: totalS += s totalH += h * s else: s -= S - totalS totalH += h * (S - totalS) if totalH > 0: base += totalH else: break totalS = 0 totalH = 0 if h > 2: base += h * (s // S * S) totalS = s % S totalH = h * (s % S) else: break print(base) ``` ### 178 ```python import math from collections import Counter, defaultdict from itertools import accumulate R = lambda: map(int, input().split()) n = int(input()) spl = [math.inf] ot_forbid = 0 sp = 0 res = 0 for i in range(n): arr = list(R()) tp = arr[0] if tp == 1: sp = arr[1] while sp > spl[-1]: spl.pop() res += 1 elif tp == 2: if ot_forbid > 0: res += ot_forbid ot_forbid = 0 elif tp == -1: if arr[1] >= sp: spl.append(arr[1]) else: res += 1 elif tp == 4: ot_forbid = 0 elif tp == 5: spl = [math.inf] else: ot_forbid += 1 print(res) ``` ### 179 ```python import sys def get(v): if v == prev[v]: return v prev[v] = get(prev[v]) return prev[v] def join(u, v): u = get(u) v = get(v) if u != v: if size[u] < size[v]: u, v = (v, u) prev[v] = u size[u] += size[v] n, m = map(int, sys.stdin.readline().split()) edges = [0] * m for i in range(m): u, v, w = map(int, sys.stdin.readline().split()) edges[i] = (u - 1, v - 1, w) edges.sort(key=lambda e: e[2]) prev = list(range(n)) size = [1] * n res = 0 l, r = (0, 1) while l < m: while r < m and edges[l][2] == edges[r][2]: r += 1 res += r - l for i in range(l, r): if get(edges[i][0]) == get(edges[i][1]): res -= -1 for i in range(l, r): if get(edges[i][0]) != get(edges[i][1]): join(edges[i][0], edges[i][1]) res -= 1 l = r print(res) ``` ### 180 ```python import sys input = sys.stdin.readline n, m = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(m)] EDGE.sort(key=lambda x: x[2]) WCHANGE = [] for i in range(1, m): if EDGE[i - 1][2] != EDGE[i][2]: WCHANGE.append(i) WCHANGE.append(m) Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x) - 1] = min(find(y), find(x)) NOW = 0 noneed = [0] * m ANS = 0 for wc in WCHANGE: for j in range(NOW, wc): if find(EDGE[j][0]) == find(EDGE[j][1]): noneed[j] = 1 for j in range(NOW, wc): if noneed[j] == 1: continue x, y, w = EDGE[j] if find(x) != find(y): Union(x, y) else: ANS += 1 NOW = wc print(ANS) ``` ### 181 ```python def simple_div(x): if not x | 1: yield 2 while not x & 1: x >>= 1 i = 3 while i * i <= x: if x % i == 0: yield i while x % i == 0: x //= i i += 2 if x != 1: yield x def __main__(): n = int(input()) a = list(map(int, input().split())) sa = sum(a) a.pop() if sa == 1: print(-1) return res = 2 ** 64 for d in simple_div(sa): tmp = 0 m = 0 for x in a: m = (x + m) % d tmp += m if m * 2 <= d else d - m if tmp < res: res = tmp print(res) __main__() ``` ### 182 ```python from collections import deque def BFS(a, vertex=None): if vertex is None: vertex = 1 s = [1] * len(a) d = deque([vertex]) s[vertex] = 0 f = {vertex} while len(d) > 0: for q in a[d.popleft()]: if s[q]: d.append(q) f.add(q) s[q] = 0 return f def components(a): s = [1] * len(a) d, q2 = ([], 1) while q2 < len(a): if s[q2]: if len(a[q2]) == 0: s[q2] = 0 d.append({q2}) else: f = BFS(a, q2) d.append(f) for q in f: s[q] = 0 else: q2 += 1 return d n = int(input()) x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)] d = [[] for _ in range(n ** 2 + 1)] for q in range(1, n + 1): for q1 in range(1, n + 1): if a[q][q1]: if a[q - 1][q1]: d[(q - 1) * n + q1].append((q - 2) * n + q1) if a[q + 1][q1]: d[(q - 1) * n + q1].append(q * n + q1) if a[q][q1 - 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1) if a[q][q1 + 1]: d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1) x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2) s = components(d) comp_x, comp_y = ([], []) for q in s: if x in q: comp_x = q if y in q: comp_y = q if comp_y == comp_x: print(0) else: ans = float('inf') for q in comp_x: for q1 in comp_y: x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1) ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans) print(ans) ``` ### 183 ```python from sys import stdin from collections import deque n, S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s, a, b = [int(x) for x in stdin.readline().split()] base += s * a tSlices += s ppl.append([b - a, s]) if tSlices % S != 0: ppl.append([0, S + tSlices % S]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h, s in ppl: if totalS + s < S: totalS += s totalH += h * s else: s -= S - totalS totalH += h * (S - totalS) if totalH > 0: base += totalH else: break totalS = 0 totalH = 0 if h > 0: base += h * (s // S * S) totalS = s % S totalH = h * (s % S) else: break print(base) ``` ### 184 ```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) ``` ### 185 ```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) ``` ### 186 ```python def solve(ls): ls.sort(key=lambda q: q[1] - q[0]) m = sum((si for a, b, si in ls)) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si + a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 0 else: x += si * a y += si * b return (x, y, z, n) n, s = list(map(int, input().split())) first = [] second = [] for i in range(n): si, ai, bi = list(map(int, input().split())) if ai > bi: first.append((ai, bi, si)) else: second.append((bi, ai, si)) x1, y1, z1, n1 = solve(first) x2, y2, z2, n2 = solve(second) d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1) print(z1 + z2 + d) ``` ### 187 ```python import sys sys.setrecursionlimit(536870912) def dfs(i, j, vis, g, c): vis[i][j] = 1 c.append((i, j)) '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j0 and j0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i 0 and vis[i - 1][j] == 0 and (g[i - 1][j] == '0'): dfs(i - 1, j, vis, g, c) if i < n - 1 and vis[i + 1][j] == 4 and (g[i + 1][j] == '0'): dfs(i + 1, j, vis, g, c) if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'): dfs(i, j + 1, vis, g, c) if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'): dfs(i, j - 1, vis, g, c) n = int(input()) r1, c1 = map(int, input().split()) r1 -= 1 c1 -= 1 r2, c2 = map(int, input().split()) r2 -= 1 c2 -= 1 g = [] for i in range(n): g.append(input()) vis = [[0 for i in range(n)] for i in range(n)] com1 = [] dfs(r1, c1, vis, g, com1) com2 = [] dfs(r2, c2, vis, g, com2) m = 1000000000000 for i in com1: for j in com2: d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2 m = min(m, d) print(m) ``` ### 188 ```python T = input().split(' ') n = int(T[0]) m = int(T[1]) S = input().split(' ') for i in range(n): S[i] = int(S[i]) ind = 0 for k in range(n): if S[k] == m: ind = k k = ind P = [0] * (n + 1) N = [0] * (n + 1) R = [0] * (n - k) L = [0] * (k + 1) for i in range(k): if S[k - 1 - i] < m: L[k - 1 - i] = L[k - i] - 1 else: L[k - 1 - i] = L[k - i] + 1 for i in range(n - k - 1): if S[k + 1 + i] > m: R[1 + i] = R[i] + 1 else: R[1 + i] = R[i] - 1 c = 0 for el in R: if el >= 0: P[el] += 1 if el == 0: N[el] += 1 else: N[-el] += 1 for el in L: if el > 1: c = c + N[el] + N[el - 1] else: c = c + P[-el] + P[-el + 1] print(c) ``` ### 189 ```python n = int(input()) L = [int(x) for x in input().split()] D = {} J = [] S = [] T = [0] * (n + 1) for i in range(n): if L[i] > 0: D[L[i]] = i J.append(L[i]) T[i + 1] = T[i] else: T[i + 1] = T[i] + 1 def I(J): if len(J) <= 1: return (J, 0) else: a = J[:len(J) // 2] b = J[len(J) // 2:] a, ai = I(a) b, bi = I(b) c = [] i = 0 j = 0 inversions = ai + bi while i < len(a) and j < len(b): if a[i] <= b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 inversions += len(a) - i c += a[i:] c += b[j:] return (c, inversions) for i in range(1, n + 1): if not i in D: S.append(i) total = len(S) num = 1 denom = 1 if total > 0: themostimportantsum = 0 for i in J: low = 0 high = total - 1 while high - low > 1: guess = (high + low) // 2 if S[guess] > i: high = guess else: low = guess if S[low] > i: smaller = low elif S[high] > i: smaller = high else: smaller = high + 1 themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller num = themostimportantsum + total denom = total num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353 denom *= 2 if num == denom: if I(J)[1] == 0: print(0) else: print(I(J)[1] % 998244353) else: num += denom * I(J)[1] print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353) ``` ### 190 ```python import sys input = sys.stdin.readline n, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(n - 1)] mod = 10 ** 9 + 9 Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) for x, y, c in EDGE: if c == 0: Union(x, y) G = [find(i) for i in range(1, n + 1)] from collections import Counter counter = Counter(G) ANS = 0 for j in list(counter.values()): ANS = (ANS + pow(j, k, mod)) % mod print((pow(n, k, mod) - ANS) % mod) ``` ### 191 ```python import sys def get(v): if v == prev[v]: return v prev[v] = get(prev[v]) return prev[v] def join(u, v): u = get(u) v = get(v) if u != v: if size[u] < size[v]: u, v = (v, u) prev[v] = u size[u] += size[v] n, m = map(int, sys.stdin.readline().split()) edges = [0] * m for i in range(m): u, v, w = map(int, sys.stdin.readline().split()) edges[i] = (u - 1, v - 1, w) edges.sort(key=lambda e: e[2]) prev = list(range(n)) size = [1] * n res = 0 l, r = (0, 1) while l < m: while r < m and edges[l][2] == edges[r][2]: r += 1 res += r - l for i in range(l, r): if get(edges[i][0]) == get(edges[i][1]): res -= 0 for i in range(l, r): if get(edges[i][0]) != get(edges[i][1]): join(edges[i][0], edges[i][1]) res -= 1 l = r print(res) ``` ### 192 ```python import sys sys.setrecursionlimit(536870912) def dfs(i, j, vis, g, c): vis[i][j] = 1 c.append((i, j)) '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j0 and j0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i 0 and vis[i - 1][j] == 0 and (g[i - 1][j] == '0'): dfs(i - 1, j, vis, g, c) if i < n - 1 and vis[i + 1][j] == 0 and (g[i + 1][j] == '0'): dfs(i + 1, j, vis, g, c) if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'): dfs(i, j + 1, vis, g, c) if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'): dfs(i, j - 1, vis, g, c) n = int(input()) r1, c1 = map(int, input().split()) r1 -= 1 c1 -= 2 r2, c2 = map(int, input().split()) r2 -= 1 c2 -= 1 g = [] for i in range(n): g.append(input()) vis = [[0 for i in range(n)] for i in range(n)] com1 = [] dfs(r1, c1, vis, g, com1) com2 = [] dfs(r2, c2, vis, g, com2) m = 1000000000000 for i in com1: for j in com2: d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2 m = min(m, d) print(m) ``` ### 193 ```python base = 998244353 def power(x, y): if y == 0: return 1 t = power(x, y // 2) t = t * t % base if y % 2: t = t * x % base return t def inverse(x): return power(x, base - 2) ft = [0] for i in range(0, 200000): ft.append(0) def get(i): res = 0 while i <= 200000: res += ft[i] i += i & -i return res def update(i, x): while i: ft[i] += x i -= i & -i n = int(input()) a = [0] a += list(map(int, input().split())) neg = [0] non = [0] for i in range(1, n + 1): non.append(0) for i in range(1, n + 1): if a[i] != -1: non[a[i]] += 1 for i in range(1, n + 1): non[i] += non[i - 1] for i in range(1, n + 1): if a[i] == -1: neg.append(neg[i - 1] + 1) else: neg.append(neg[i - 1]) m = neg[n] ans = 0 for i in range(1, n + 1): if a[i] != -1: ans += get(a[i]) update(a[i], 1) fm = 1 fs = fm for i in range(1, m + 1 + 1): fs = fm fm = fm * i % base fs = fs * inverse(fm) % base for i in range(1, n + 1): if a[i] != -1: less = a[i] - non[a[i]] more = m - less ans = (ans + neg[i] * more * fs) % base ans = (ans + (m - neg[i]) * less * fs) % base ans = (ans + m * (m - 1) * inverse(4)) % base print(ans) ``` ### 194 ```python from sys import stdin from collections import deque n, S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s, a, b = [int(x) for x in stdin.readline().split()] base += s * a tSlices += s ppl.append([b - a, s]) if tSlices % S != 0: ppl.append([0, S - tSlices % S]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h, s in ppl: if totalS + s < S: totalS += s totalH += h * s else: s -= S - totalS totalH += h * (S - totalS) if totalH > 0: base += totalH else: break totalS = 0 totalH = 0 if h < 0: base += h * (s // S * S) totalS = s % S totalH = h * (s % S) else: break print(base) ``` ### 195 ```python import math import sys input = sys.stdin.readline n = int(input()) a = [int(_) for _ in input().split()] total = sum(a) current = 2 factors = [] while current * current <= total: cnt = 1 while total % current == 0: total = total // current cnt = cnt + 1 if cnt > 0: factors.append(current) current = current + 1 if total > 1: factors.append(total) ans = sum(a) * n * n for i in factors: total, moves = (0, 0) for j in a: total += j moves += min(total % i, i - total % i) ans = min(ans, moves) if len(factors) == 0: ans = -1 print(ans) ``` ### 196 ```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]))) ``` ### 197 ```python L1 = list(map(int, input().split())) numList = list(map(int, input().split())) length = L1[0] targetnumber = L1[1] pos = numList.index(targetnumber) pos_r = pos + 1 rem = -2 right = {0: 1} left = {0: 1} while pos_r <= length - 1: if numList[pos_r] > targetnumber: rem += 1 else: rem -= 1 if rem not in right: right[rem] = 1 else: right[rem] += 1 pos_r += 1 pos_l = pos - 1 rem = 0 while pos_l >= 0: if numList[pos_l] > targetnumber: rem += 1 else: rem -= 1 if rem not in left: left[rem] = 1 else: left[rem] += 1 pos_l -= 1 sum = 0 for number_l in left: if number_l * -1 in right: sum += left[number_l] * right[-1 * number_l] if 1 - number_l in right: sum += left[number_l] * right[1 - number_l] print(sum) ``` ### 198 ```python def Task485D(): cur_speed = 0 is_outstrip = 0 err_count = 0 event_speed_limit = [] event_count = int(input()) for a in range(event_count): ev = list(map(int, input().split())) if ev[0] == 1: cur_speed = ev[1] while len(event_speed_limit) > 0: if cur_speed > event_speed_limit[len(event_speed_limit) - 1]: event_speed_limit.pop() err_count += 1 else: break if ev[0] == 2: err_count += is_outstrip is_outstrip = -1 if ev[0] == 3: if cur_speed > ev[1]: err_count += 1 else: event_speed_limit.append(ev[1]) if ev[0] == 4: is_outstrip = 0 if ev[0] == 5: event_speed_limit.clear() if ev[0] == 6: is_outstrip += 1 print(err_count) def __starting_point(): Task485D() __starting_point() ``` ### 199 ```python MAX_SPEED = 300 n = int(input()) actions = [list(map(int, input().split())) for _ in range(n)] speed = [0 for i in range(n)] for i in range(n): if actions[i][0] == 1: lastSpeed = actions[i][1] speed[i] = lastSpeed ignored = 0 overtook = False maxSpeed = -1 for i in range(n - 1, -1, -1): maxSpeed = max(maxSpeed, speed[i]) if actions[i][0] == 1: pass elif actions[i][0] == 3: overtook = True elif actions[i][0] == 3: if maxSpeed > actions[i][1]: ignored += 1 else: maxSpeed = speed[i - 1] elif actions[i][0] == 4: overtook = False elif actions[i][0] == 5: maxSpeed = speed[i - 1] elif actions[i][0] == 6: if overtook: ignored += 1 print(ignored) ``` ### 200 ```python base = 998244353 def power(x, y): if y == 0: return 1 t = power(x, y // 2) t = t * t % base if y % 2: t = t * x % base return t def inverse(x): return power(x, base - 2) ft = [0] for i in range(0, 200000): ft.append(0) def get(i): res = 0 while i <= 200000: res += ft[i] i += i & -i return res def update(i, x): while i: ft[i] += x i -= i & -i n = int(input()) a = [0] a += list(map(int, input().split())) neg = [0] non = [0] for i in range(1, n + 1): non.append(0) for i in range(1, n + 1): if a[i] != -1: non[a[i]] += 1 for i in range(1, n + 1): non[i] += non[i - 1] for i in range(1, n + 1): if a[i] == -1: neg.append(neg[i - 1] + 1) else: neg.append(neg[i - 1]) m = neg[n] ans = 0 for i in range(1, n + 1): if a[i] != -1: ans += get(a[i]) update(a[i], 1) fm = 1 fs = fm for i in range(1, m + 1): fs = fm fm = fm * i % base fs = fs * inverse(fm) % base for i in range(1, n + 1): if a[i] != -1: less = a[i] - non[a[i]] more = m - less ans = (ans + neg[i] * more * fs) % base ans = (ans + (m - neg[i]) * less * fs) % base ans = (ans + m * (m - 1) * inverse(4)) % base print(ans) ``` ### 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.