|
Download tasks/equivalent-program-pair-search/contexts/sample-00033.md from StringNLP/longharness: direct link, hf CLI and curl.
- Browser
- Download file 258 kB
-
https://huggingface.co/datasets/StringNLP/longharness/resolve/main/tasks/equivalent-program-pair-search/contexts/sample-00033.md
- Command line
-
hf download hf://datasets/StringNLP/longharness/tasks/equivalent-program-pair-search/contexts/sample-00033.md
-
curl -L -o sample-00033.md https://huggingface.co/datasets/StringNLP/longharness/resolve/main/tasks/equivalent-program-pair-search/contexts/sample-00033.md
258 kB
| ### 001 | |
| ```python | |
| from bisect import bisect_left | |
| n, m, k, q = list(map(int, input().split())) | |
| x = sorted((list(map(int, input().split())) for _ in range(k))) | |
| y = sorted(map(int, input().split())) | |
| def rr(c0, c1, c): | |
| return abs(c0 - c) + abs(c1 - c) | |
| def tm(c0, c1): | |
| t = bisect_left(y, c0) | |
| tt = [] | |
| if t > 1: | |
| tt.append(rr(c0, c1, y[t - 1])) | |
| if t < q: | |
| tt.append(rr(c0, c1, y[t])) | |
| return min(tt) | |
| z = [] | |
| for r, c in x: | |
| if z and z[-1][0] == r: | |
| z[-1][2] = c | |
| else: | |
| z.append([r, c, c]) | |
| v1, v2, r0, c01, c02 = (0, 0, 1, 1, 1) | |
| for r1, c11, c12 in z: | |
| d = c12 - c11 + r1 - r0 | |
| if r1 > r0: | |
| d11 = tm(c01, c11) | |
| d12 = tm(c01, c12) | |
| d21 = tm(c02, c11) | |
| d22 = tm(c02, c12) | |
| v2, v1 = (d + min(v1 + d11, v2 + d21), d + min(v1 + d12, v2 + d22)) | |
| else: | |
| v1, v2 = (d + c12 - c02, d + c11 - c01) | |
| r0, c01, c02 = (r1, c11, c12) | |
| print(min(v1, v2)) | |
| ``` | |
| ### 002 | |
| ```python | |
| def main(s): | |
| if len(s) == 0: | |
| return [] | |
| if len(s) == 1: | |
| return [[s], [1]] | |
| s = s[::-1] | |
| sres = [s[0]] | |
| nres = [1] | |
| if s[0] == s[1]: | |
| sres.append('') | |
| nres.append(0) | |
| else: | |
| sres.append(s[1] + s[0]) | |
| nres.append(2) | |
| for i in range(2, len(s)): | |
| st = s[i] + sres[-1] | |
| nt = nres[-1] + 1 | |
| if nt > 12: | |
| st = st[:5] + '...' + st[-2:] | |
| if s[i] == s[i - 1] and st > sres[-1]: | |
| st = sres[-2] | |
| nt = nres[-2] | |
| sres.append(st) | |
| nres.append(nt) | |
| return [sres, nres] | |
| s = input() | |
| sres, nres = main(s) | |
| for i in range(len(s) - 1, -1, -1): | |
| print(nres[i], sres[i]) | |
| ``` | |
| ### 003 | |
| ```python | |
| import os | |
| import sys | |
| import io | |
| import functools | |
| import copy | |
| import math | |
| GANS = [] | |
| def cmp(x, y): | |
| if x[1] == y[1]: | |
| return -(y[0] - x[0]) | |
| return -(x[1] - y[1]) | |
| s = input() | |
| ans = [] | |
| cur = [] | |
| ctr = [] | |
| pos = [] | |
| pv = [chr(0)] | |
| pvc = chr(1) | |
| for p, i in enumerate(s[::-1]): | |
| if cur and cur[-1] == i: | |
| f = True | |
| if len(cur) >= 4: | |
| if cur[-2] > i: | |
| f = False | |
| elif cur[-2] == i: | |
| if pos[-2] == p - 2: | |
| f = False | |
| if pv[-1] >= i: | |
| f = False | |
| if f and p == pos[-1] + 1: | |
| cur.pop() | |
| pos.pop() | |
| pv.pop() | |
| pvc = pv[-1] | |
| else: | |
| cur.append(i) | |
| pos.append(p) | |
| pv.append(pvc) | |
| else: | |
| if cur: | |
| pvc = cur[-1] | |
| cur.append(i) | |
| pos.append(p) | |
| pv.append(pvc) | |
| ctr.append(len(cur)) | |
| if ctr[-1] > 10: | |
| ans.append(''.join(cur[-5:][::-1]) + '...' + ''.join(cur[:2][::-1])) | |
| else: | |
| ans.append(''.join(cur[::-1])) | |
| for i in range(len(ans)): | |
| print(ctr[-i - 1], ans[-i - 1]) | |
| ``` | |
| ### 004 | |
| ```python | |
| n, v = map(int, input().split()) | |
| T = 3010 | |
| a = [[] for i in range(T)] | |
| for i in range(n): | |
| x, y = map(int, input().split()) | |
| a[x].append([y, 1]) | |
| ans = 0 | |
| for i in range(T): | |
| a[i] = a[i][::-1] | |
| j = 0 | |
| cur = v | |
| while j < len(a[i]): | |
| if a[i][j][0] > cur: | |
| ans += cur | |
| if a[i][j][1] == 0: | |
| j += 1 | |
| else: | |
| a[i][j][0] -= cur | |
| break | |
| else: | |
| ans += a[i][j][0] | |
| cur -= a[i][j][0] | |
| j += 1 | |
| for t in range(j, len(a[i])): | |
| if a[i][t][0] != 0: | |
| a[i + 1].append([a[i][t][0], 0]) | |
| print(ans) | |
| ``` | |
| ### 005 | |
| ```python | |
| n = int(input()) | |
| u = [int(u) for u in input().split()] | |
| NMAX = 100005 | |
| suma = [0 for _ in range(NMAX)] | |
| total = [0 for _ in range(NMAX)] | |
| diferentes = 0 | |
| sol = 0 | |
| maximo = 1 | |
| for i, v in enumerate(u): | |
| if total[v] == 0: | |
| diferentes += 1 | |
| else: | |
| suma[total[v]] -= 1 | |
| total[v] += 1 | |
| suma[total[v]] += 1 | |
| maximo = max(maximo, total[v]) | |
| if diferentes <= 1: | |
| sol = i | |
| if suma[maximo - 1 + 1] == diferentes - 1 and suma[maximo] == 1: | |
| sol = i | |
| if suma[maximo] == diferentes - 1 and suma[1] == 1: | |
| sol = i | |
| if suma[1] == diferentes: | |
| sol = i | |
| print(sol + 1) | |
| ``` | |
| ### 006 | |
| ```python | |
| from random import random | |
| from collections import defaultdict | |
| import math | |
| import re | |
| import fractions | |
| N = int(input()) | |
| A = list(map(int, input().split(' '))) | |
| arr = [0] * (10 ** 5 + 1) | |
| existing = set() | |
| for a in A: | |
| arr[a] += 1 | |
| existing.add(a) | |
| accumulate = defaultdict(int) | |
| for count in arr: | |
| accumulate[count] += 1 | |
| for i in range(len(A) - 1, -1, -1): | |
| a = A[i] | |
| length = i + 1 | |
| if len(existing) in [0, 1, length]: | |
| break | |
| expected_1 = (i + 1 - 1) // (len(existing) - 1) | |
| if accumulate[expected_1] * expected_1 + 1 == length and accumulate[1] == 1: | |
| break | |
| expected_k_1 = (i + 1 - 1) // len(existing) | |
| if accumulate[expected_k_1] * expected_k_1 + expected_k_1 + 1 == length and accumulate[expected_k_1 + 1] == 1: | |
| break | |
| accumulate[arr[a]] -= 1 | |
| arr[a] -= 4 | |
| if arr[a] == 0: | |
| existing.discard(a) | |
| accumulate[arr[a]] += 1 | |
| print(length) | |
| ``` | |
| ### 007 | |
| ```python | |
| n, m = map(int, input().split()) | |
| a = [] | |
| for i in range(n): | |
| a.append(list(map(int, input().split()))) | |
| dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] | |
| dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] | |
| ans = 0 | |
| for i in range(1, n + 1): | |
| for j in range(1, m + 1): | |
| dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1] | |
| dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] | |
| for i in range(n, 0, -1): | |
| for j in reversed(range(1, m + 1)): | |
| dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1] | |
| dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] | |
| for i in range(2, n): | |
| for j in range(2, m): | |
| x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1] | |
| y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1] | |
| ans = max(ans, x, y) | |
| print(ans) | |
| ``` | |
| ### 008 | |
| ```python | |
| import collections | |
| from collections import defaultdict | |
| n = int(input()) | |
| par = [int(i) for i in input().split() if i != '\n'] | |
| suma = [int(i) for i in input().split() if i != '\n'] | |
| graph = defaultdict(list) | |
| for i in range(n - 1): | |
| graph[i + 2].append(par[i]) | |
| graph[par[i]].append(i + 2) | |
| weight = [0] * (n + 1) | |
| weight[1] = suma[0] | |
| queue = collections.deque([1]) | |
| visited = set() | |
| visited.add(1) | |
| ok = True | |
| while queue: | |
| vertex = queue.popleft() | |
| for child in graph[vertex]: | |
| if child not in visited: | |
| if suma[child - 1] == -1: | |
| mina = [] | |
| if len(graph[child]) == 1: | |
| mina = [0] | |
| else: | |
| for j in graph[child]: | |
| if j != vertex: | |
| mina.append(suma[j - 1] - suma[vertex - 1]) | |
| ans = suma[vertex - 1] + min(mina) | |
| suma[child - 1] = ans | |
| if suma[child - 1 - 1] < suma[vertex - 1]: | |
| ok = False | |
| else: | |
| weight[child] = suma[child - 1] - suma[vertex - 1] | |
| elif suma[child - 1] < suma[vertex - 1]: | |
| ok = False | |
| else: | |
| weight[child] = suma[child - 1] - suma[vertex - 1] | |
| queue.append(child) | |
| visited.add(child) | |
| if ok == True: | |
| print(sum(weight)) | |
| else: | |
| print(-1) | |
| ``` | |
| ### 009 | |
| ```python | |
| MOD = 998244353 | |
| n, k = map(int, input().split()) | |
| a = list(map(int, input().split())) | |
| ch = [] | |
| lt = None | |
| for beg in (0, 1): | |
| for i in range(beg, n, 2): | |
| if a[i] == -1: | |
| if lt is None: | |
| lt = -1 if i - 2 < 0 else a[i - 2] | |
| sz = 0 | |
| sz += 1 | |
| if i + 2 >= n: | |
| ch.append((lt, -1, sz)) | |
| lt = None | |
| elif a[i + 2] != -1: | |
| ch.append((lt, a[i + 2], sz)) | |
| lt = None | |
| ans = int(all((a[i] != a[i + 2] for i in range(n - 2) if a[i] != -1))) | |
| for lt, rt, sz in ch: | |
| if sz == 1: | |
| cur = k if lt == -1 and rt == -1 else k - 1 if rt == -1 or lt == rt else k - 2 | |
| else: | |
| eq, neq = (1 if lt == -1 else 0, 1) | |
| for _ in range(sz - 1): | |
| eq, neq = (neq * (k - 1) % MOD, (neq * (k - 2) + eq) % MOD) | |
| cur = neq * (k - 1) + eq if rt == -1 else neq * (k - 1) if lt == rt else neq * (k - 2) + eq | |
| ans = ans * cur % MOD | |
| print(ans) | |
| ``` | |
| ### 010 | |
| ```python | |
| import collections | |
| import time | |
| import os | |
| import sys | |
| import bisect | |
| import heapq | |
| from typing import List | |
| def solve(N, M, A): | |
| dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| for r in range(1, N + 1): | |
| for c in reversed(range(1, M + 1)): | |
| dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] | |
| for r in range(N, 0, -1): | |
| for c in range(M, 0, -1): | |
| dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] | |
| for r in range(N, 0, -1): | |
| for c in range(1, M + 1): | |
| dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] | |
| for r in range(1, N + 1): | |
| for c in range(M, 0, -1): | |
| dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] | |
| ans = 0 | |
| for r in range(2, N): | |
| for c in range(2, M): | |
| a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] | |
| b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] | |
| ans = max(ans, a, b) | |
| return ans | |
| N, M = map(int, input().split()) | |
| A = [[0 for _ in range(M + 2)]] | |
| for i in range(N): | |
| row = [0] + [int(x) for x in input().split()] + [0] | |
| A.append(row) | |
| A.append([0 for _ in range(M + 2)]) | |
| print(solve(N, M, A)) | |
| ``` | |
| ### 011 | |
| ```python | |
| import sys | |
| n = int(input()) | |
| nums = list(map(int, input().split())) | |
| eleCount = {} | |
| possibleMax = 1 | |
| for i in range(n): | |
| if nums[i] in list(eleCount.keys()): | |
| eleCount[nums[i]] += 1 | |
| if len(list(eleCount.keys())) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x = list(eleCount.values()) | |
| x.sort() | |
| if x[0] == 1 and x[-1] == 1: | |
| possibleMax = i + 1 | |
| elif x[0] == 1 and x[1] == 1: | |
| if len(set(x[1:])) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x[-1] = x[-1] - 1 | |
| if len(set(x)) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| eleCount[nums[i]] = 1 | |
| if len(list(eleCount.keys())) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x = list(eleCount.values()) | |
| x.sort() | |
| if x[0] == 1 and x[-1] == 1: | |
| possibleMax = i + 1 | |
| elif x[0] == 1 and x[1] != 1: | |
| if len(set(x[1:])) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x[-1] = x[-1] - 1 | |
| if len(set(x)) == 1: | |
| possibleMax = i + 1 | |
| print(possibleMax) | |
| ``` | |
| ### 012 | |
| ```python | |
| def connected_components(neighbors): | |
| seen = set() | |
| def component(node): | |
| nodes = set([node]) | |
| while nodes: | |
| node = nodes.pop() | |
| seen.add(node) | |
| nodes |= neighbors[node] - seen | |
| yield node | |
| for node in neighbors: | |
| if node not in seen: | |
| yield component(node) | |
| from collections import defaultdict | |
| graph = defaultdict(set) | |
| n, m = map(int, input().split()) | |
| for _ in range(m): | |
| u, v = map(int, input().split()) | |
| graph[u].add(v) | |
| graph[v].add(u) | |
| total = 0 | |
| for component in connected_components(graph): | |
| nodes = list(component) | |
| size = len(nodes) | |
| seen = set() | |
| current = nodes[0] | |
| while len(seen) < size: | |
| choice = list(graph[current]) | |
| if len(choice) != 2: | |
| break | |
| seen.add(current) | |
| possible = [c for c in choice if c not in seen] | |
| if not possible: | |
| break | |
| current = possible[0] | |
| if len(seen) == size: | |
| total += 5 | |
| print(total) | |
| ``` | |
| ### 013 | |
| ```python | |
| def main(s): | |
| if len(s) == 0: | |
| return [] | |
| if len(s) == 1: | |
| return [[s], [1]] | |
| s = s[::-1] | |
| sres = [s[0]] | |
| nres = [1] | |
| if s[0] == s[1]: | |
| sres.append('') | |
| nres.append(0) | |
| else: | |
| sres.append(s[1] + s[0]) | |
| nres.append(2) | |
| for i in range(2, len(s)): | |
| st = s[i] + sres[-1] | |
| nt = nres[-1] + 1 | |
| if nt > 11: | |
| st = st[:5] + '...' + st[-2:] | |
| if s[i] == s[i - 1] and st > sres[-1]: | |
| st = sres[-2] | |
| nt = nres[-2] | |
| sres.append(st) | |
| nres.append(nt) | |
| return [sres, nres] | |
| s = input() | |
| sres, nres = main(s) | |
| for i in range(len(s) - 1, -1, -1): | |
| print(nres[i], sres[i]) | |
| ``` | |
| ### 014 | |
| ```python | |
| import sys | |
| from math import * | |
| def minp(): | |
| return sys.stdin.readline().strip() | |
| def mint(): | |
| return int(minp()) | |
| def mints(): | |
| return list(map(int, minp().split())) | |
| n, m = mints() | |
| a = [0] * n | |
| dp1 = [0] * n | |
| dp2 = [0] * n | |
| dp3 = [0] * n | |
| dp4 = [0] * n | |
| for i in range(n): | |
| a[i] = list(mints()) | |
| dp1[i] = [0] * m | |
| dp2[i] = [0] * m | |
| dp3[i] = [0] * m | |
| dp4[i] = [0] * m | |
| dp1[0][0] = a[0][0] | |
| dp2[n - 1][m - 1] = a[n - 1][m - 1] | |
| dp3[n - 1][0] = a[n - 1][0] | |
| dp4[0][m - 1] = a[0][m - 1] | |
| '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' | |
| for i in range(0, n): | |
| for j in range(0, m): | |
| z = 0 | |
| if i - 1 >= 0: | |
| z = dp1[i - 1][j] | |
| if j - 1 >= 0: | |
| z = max(z, dp1[i][j - 1]) | |
| dp1[i][j] = z + a[i][j] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m - 1, -1, -1): | |
| z = 0 | |
| if i + 1 < n: | |
| z = dp2[i + 1][j] | |
| if j + 1 < m: | |
| z = max(z, dp2[i][j + 1]) | |
| dp2[i][j] = z + a[i][j] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(0, m): | |
| z = 0 | |
| if i + 1 < n: | |
| z = dp3[i + 1][j] | |
| if j - 1 >= 0: | |
| z = max(z, dp3[i][j - 1]) | |
| dp3[i][j] = z + a[i][j] | |
| for i in range(0, n): | |
| for j in range(m - 1, -1, -1): | |
| z = 0 | |
| if i - 1 >= 0: | |
| z = dp4[i - 1][j] | |
| if j + 1 < m: | |
| z = max(z, dp4[i][j + 1]) | |
| dp4[i][j] = z + a[i][j] | |
| 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' | |
| r = 1 | |
| for i in range(1, n - 1): | |
| for j in range(1, m - 1): | |
| r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) | |
| r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) | |
| print(r) | |
| ``` | |
| ### 015 | |
| ```python | |
| s = input() | |
| cs = [''] | |
| ans = [] | |
| last = [''] | |
| poped = False | |
| for c in s[::-1]: | |
| if c == cs[-1] and c > last[-2]: | |
| cs.pop() | |
| if not cs or c != cs[-1]: | |
| last.pop() | |
| poped = True | |
| else: | |
| poped = False | |
| if c != cs[-1]: | |
| last.append(c) | |
| cs.append(c) | |
| if len(cs) <= 11: | |
| ans.append((len(cs) - 1, ''.join(cs[::-1]))) | |
| else: | |
| ans.append((len(cs) - 1, (''.join(cs[:3]) + '...' + ''.join(cs[-5:]))[::-1])) | |
| for a, b in ans[::-1]: | |
| print(a, b) | |
| ``` | |
| ### 016 | |
| ```python | |
| def rev(a, m): | |
| res = 1 | |
| k = m - 2 | |
| s = a | |
| while k > 0: | |
| if k % 2 == 1: | |
| res = res * s % m | |
| k //= 2 | |
| s = s ** 2 % m | |
| return res | |
| n, m = [int(x) for x in input().split()] | |
| a1 = [int(x) for x in input().split()] | |
| a2 = [int(x) for x in input().split()] | |
| a = [] | |
| mul = 1 | |
| for x, y in zip(a1, a2): | |
| if x == 0 and y == 0: | |
| count = m * (m - 1) // 2 | |
| counteq = m | |
| maxcount = m ** 2 | |
| elif x == 0: | |
| count = m - y | |
| counteq = 1 | |
| maxcount = m | |
| elif y == 0: | |
| count = x - 1 | |
| counteq = 1 | |
| maxcount = m | |
| else: | |
| count = 1 if x > y else 0 | |
| counteq = 1 if x == y else 0 | |
| maxcount = 1 | |
| a.append((count, counteq, maxcount)) | |
| if counteq == 0: | |
| break | |
| a.reverse() | |
| P, Q = (0, 1) | |
| for c, ce, mc in a: | |
| P = (P * ce + Q * c) % (10 ** 9 + 7) | |
| Q = Q * mc & 10 ** 9 + 7 | |
| res, zeros = (P, Q) | |
| print(res * rev(zeros, 10 ** 9 + 7) % (10 ** 9 + 7)) | |
| ``` | |
| ### 017 | |
| ```python | |
| n, v = list(map(int, input().split())) | |
| f = list() | |
| for i in range(n): | |
| f.append(list(map(int, input().split()))) | |
| f.sort() | |
| sum = 0 | |
| today = 0 | |
| tomor = 0 | |
| day = 0 | |
| rest = 0 | |
| for tree in f: | |
| if tree[0] > day + -1: | |
| sum += min(tomor, v) | |
| tomor = tree[1] | |
| sum += min(tomor, v) | |
| rest = v - min(tomor, v) | |
| tomor -= min(tomor, v) | |
| day = tree[0] | |
| elif tree[0] == day + 1: | |
| sum += min(tomor, v) | |
| rest = v - min(tomor, v) | |
| tomor = tree[1] | |
| t = min(tomor, rest) | |
| sum += t | |
| rest -= t | |
| tomor -= t | |
| day = tree[0] | |
| else: | |
| tomor += tree[1] | |
| t = min(tomor, rest) | |
| sum += t | |
| rest -= t | |
| tomor -= t | |
| sum += min(tomor, v) | |
| print(sum) | |
| ``` | |
| ### 018 | |
| ```python | |
| import operator | |
| data = list(map(int, input().split(' '))) | |
| n = data[0] | |
| m = data[1] | |
| edge = {} | |
| for i in range(n): | |
| edge[i + 1] = [] | |
| for _ in range(m): | |
| data = list(map(int, input().split(' '))) | |
| i = data[0] | |
| j = data[1] | |
| edge[i].append(j) | |
| edge[j].append(i) | |
| candidate = [k for k, v in list(edge.items()) if len(v) == 2] | |
| result = 0 | |
| used = {} | |
| def _iscircle(c, result): | |
| n = edge[c][0] | |
| used[c] = 1 | |
| last = c | |
| while n not in used: | |
| used[n] = 1 | |
| if len(edge[n]) != 2: | |
| return result | |
| t = edge[n][0] | |
| if not t != last: | |
| last = n | |
| if t == c: | |
| return result + 1 | |
| n = t | |
| continue | |
| last = n | |
| t = edge[n][1] | |
| if t == c: | |
| return result + 1 | |
| n = t | |
| return result | |
| for i in candidate: | |
| result = _iscircle(i, result) | |
| print(result) | |
| ``` | |
| ### 019 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| n, m, k = list(map(int, input().split())) | |
| EDGE = [list(map(int, input().split())) for i in range(m)] | |
| EDGE.sort(key=lambda x: x[2]) | |
| EDGE = EDGE[:k] | |
| COST_vertex = [[] for i in range(n + 1)] | |
| VERLIST = [] | |
| for a, b, c in EDGE: | |
| COST_vertex[a].append((b, c)) | |
| COST_vertex[b].append((a, c)) | |
| VERLIST.append(a) | |
| VERLIST.append(b) | |
| VERLIST = sorted(set(VERLIST)) | |
| import heapq | |
| ANS = [-1 << 50] * k | |
| for start in VERLIST: | |
| MINCOST = [1 << 50] * (n + 1) | |
| checking = [(0, start)] | |
| MINCOST[start] = 0 | |
| j = 0 | |
| while j < k: | |
| if not checking: | |
| break | |
| cost, checktown = heapq.heappop(checking) | |
| if cost >= -ANS[0]: | |
| break | |
| if MINCOST[checktown] < cost: | |
| continue | |
| if cost != 0 and checktown > start: | |
| heapq.heappop(ANS) | |
| heapq.heappush(ANS, -cost) | |
| j += 1 | |
| for to, co in COST_vertex[checktown]: | |
| if MINCOST[to] >= cost + co: | |
| MINCOST[to] = cost + co | |
| heapq.heappush(checking, (cost + co, to)) | |
| print(-ANS[0]) | |
| ``` | |
| ### 020 | |
| ```python | |
| T = input().split(' ') | |
| n = int(T[0]) | |
| m = int(T[1]) | |
| B = [0] * (n + 1) | |
| S1 = [0] * (n + 1) | |
| S2 = [0] * (n + 1) | |
| for i in range(m): | |
| S = input().split(' ') | |
| a = int(S[0]) | |
| b = int(S[1]) | |
| if S1[a] == 0: | |
| S1[a] = b | |
| elif S2[a] == 0: | |
| S2[a] = b | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| if S1[b] == 0: | |
| S1[b] = a | |
| elif S2[b] == 0: | |
| S2[b] = a | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| for i in range(1, n + 1): | |
| if S1[i] == 0 or S2[i] == 0: | |
| B[i] = 1 | |
| sol = 0 | |
| for ind in range(1, n + 1): | |
| if B[ind] == 0: | |
| v = ind | |
| w = S2[ind] | |
| c = True | |
| while w != ind: | |
| B[v] = 1 | |
| if B[w] == 0: | |
| u = w | |
| if S1[w] == v: | |
| w = S2[w] | |
| else: | |
| w = S1[w] | |
| else: | |
| B[ind] = 0 | |
| c = False | |
| break | |
| v = u | |
| if c: | |
| B[v] = 1 | |
| sol += 1 | |
| print(sol) | |
| ``` | |
| ### 021 | |
| ```python | |
| import math | |
| n, m, k, q = list(map(int, input().split())) | |
| right = [-1] * n | |
| left = [-1] * n | |
| for i in range(k): | |
| row, col = list(map(int, input().split())) | |
| row -= 1 | |
| col -= 1 | |
| if right[row] == -1: | |
| right[row] = left[row] = col | |
| else: | |
| right[row] = max(right[row], col) | |
| left[row] = min(left[row], col) | |
| safe = sorted(list([int(qi) - 1 for qi in input().split()])) | |
| lup = [0] * m | |
| rup = [0] * m | |
| j = 0 | |
| while j < safe[0]: | |
| lup[j] = -1 | |
| rup[j] = safe[0] | |
| j += 1 | |
| lup[j] = rup[j] = safe[0] | |
| for i in range(1, q - 1): | |
| j = safe[i - 1] | |
| while j < safe[i]: | |
| lup[j] = safe[i - 1] | |
| rup[j] = safe[i] | |
| j += 1 | |
| j = safe[-1] | |
| while j < m: | |
| lup[j] = safe[-1] | |
| rup[j] = -1 | |
| j += 1 | |
| if left[0] == -1: | |
| left[0] = right[0] = 0 | |
| dleft = right[0] + (right[0] - left[0]) | |
| dright = right[0] | |
| lastn = 0 | |
| for i in range(1, n): | |
| if left[i] == -1: | |
| continue | |
| left_1b = lup[left[lastn]] | |
| left_2b = rup[left[lastn]] | |
| right_1b = lup[right[lastn]] | |
| right_2b = rup[right[lastn]] | |
| ilen = right[i] - left[i] | |
| ll1: int | |
| ll2: int | |
| rl1: int | |
| rl2: int | |
| if left_1b != -1: | |
| ll1 = left[lastn] - left_1b + abs(right[i] - left_1b) | |
| else: | |
| ll1 = math.inf | |
| if left_2b != -1: | |
| ll2 = left_2b - left[lastn] + abs(right[i] - left_2b) | |
| else: | |
| ll2 = math.inf | |
| if right_1b != -1: | |
| rl1 = right[lastn] - right_1b + abs(right[i] - right_1b) | |
| else: | |
| rl1 = math.inf | |
| if right_2b != -1: | |
| rl2 = right_2b - right[lastn] + abs(right[i] - right_2b) | |
| else: | |
| rl2 = math.inf | |
| dleft_new = min(dleft + min(ll1, ll2), dright + min(rl1, rl2)) + ilen | |
| lr1: int | |
| lr2: int | |
| rr1: int | |
| rr2: int | |
| if left_1b != -1: | |
| lr1 = left[lastn] - left_1b + abs(left[i] - left_1b) | |
| else: | |
| lr1 = math.inf | |
| if left_2b != -1: | |
| lr2 = left_2b - left[lastn] + abs(left[i] - left_2b) | |
| else: | |
| lr2 = math.inf | |
| if right_1b != -1: | |
| rr1 = right[lastn] - right_1b + abs(left[i] - right_1b) | |
| else: | |
| rr1 = math.inf | |
| if right_2b != -1: | |
| rr2 = right_2b - right[lastn] + abs(left[i] - right_2b) | |
| else: | |
| rr2 = math.inf | |
| dright_new = min(dleft + min(lr1, lr2), dright + min(rr1, rr2)) + ilen | |
| dleft, dright = (dleft_new, dright_new) | |
| lastn = i | |
| print(min(dleft, dright) + lastn) | |
| ``` | |
| ### 022 | |
| ```python | |
| bn = 0 | |
| ar = [] | |
| def binSearchMax(number): | |
| last = bn | |
| first = 0 | |
| mid = (last + first) // 2 | |
| while last >= first: | |
| if ar[mid] < number: | |
| first = mid + 1 | |
| elif ar[mid] > number: | |
| last = mid - 1 | |
| else: | |
| return mid | |
| mid = (last + first) // 2 | |
| if ar[last] == number: | |
| return last | |
| return first | |
| n, m, k, q = list(map(int, input().split())) | |
| mmn = [[m, -1] for i in range(n)] | |
| maxn = 0 | |
| for i in range(k): | |
| r, c = list(map(int, input().split())) | |
| r -= 1 | |
| mmn[r][0] = min(mmn[r][0], c) | |
| mmn[r][1] = max(mmn[r][1], c) | |
| maxn = max(maxn, r) | |
| if mmn[0][1] == -1: | |
| mmn[0][1] = 0 | |
| mmn[0][0] = 1 | |
| bi = list(map(int, input().split())) | |
| bi += [-1000000000, 10000000000, -1000000000, 10000000000, 10000000000] | |
| bi.sort() | |
| ar = bi | |
| bn = q + 3 | |
| dp = [[0, 0] for i in range(n)] | |
| dp[0][1] = mmn[0][1] - mmn[0][0] | |
| dp[0][0] = dp[0][1] * 2 | |
| z = 0 | |
| for i in range(1, n): | |
| if mmn[i][1] == -1: | |
| dp[i][0] = dp[i - 1][0] | |
| dp[i][1] = dp[i - 1][1] | |
| continue | |
| p1 = binSearchMax(mmn[z][0]) | |
| p2 = bi[p1 - 1] | |
| p1 = bi[p1] | |
| p3 = binSearchMax(mmn[z][1]) | |
| p4 = bi[p3 - 1] | |
| p3 = bi[p3] | |
| num1 = abs(p1 - mmn[i][1]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][1]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][1]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][1]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][0] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| num1 = abs(p1 - mmn[i][0]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][0]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][0]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][0]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][1] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| z = i | |
| print(min(dp[-1]) + maxn) | |
| ``` | |
| ### 023 | |
| ```python | |
| total_plucked = 0 | |
| n, v = list(map(int, input().split())) | |
| fruits = [0] * 3002 | |
| plucked = [0] * 30002 | |
| for _ in range(n): | |
| a, b = list(map(int, input().split())) | |
| fruits[a] = fruits[a] + b | |
| for i in range(1, 3002): | |
| plucked[i] = fruits[i - 1] if fruits[i - 1] <= v else v | |
| if plucked[i] < v: | |
| pluck = fruits[i] if fruits[i] <= v * plucked[i] else v - plucked[i] | |
| plucked[i] += pluck | |
| fruits[i] -= pluck | |
| total_plucked += plucked[i] | |
| print(total_plucked) | |
| ``` | |
| ### 024 | |
| ```python | |
| import heapq | |
| n, m, k = list(map(int, input().split())) | |
| connectionList = [] | |
| for _ in range(n): | |
| connectionList.append([]) | |
| edgeList = [] | |
| for _ in range(m): | |
| x, y, w = list(map(int, input().split())) | |
| edgeList.append((x, y, w)) | |
| edgeList.sort(key=lambda x: x[2]) | |
| if k < m: | |
| maxDist = edgeList[min(m, k) - 1][2] | |
| else: | |
| maxDist = sum([x[2] for x in edgeList]) | |
| colorList = {} | |
| colorVertex = [] | |
| for i in range(n): | |
| colorList[i] = [i] | |
| colorVertex.append(i) | |
| for i in range(min(m, k)): | |
| x, y, w = edgeList[i] | |
| connectionList[x - 1 - 1].append((y - 1, w)) | |
| connectionList[y - 1].append((x - 1, w)) | |
| if colorVertex[x - 1] != colorVertex[y - 1]: | |
| if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): | |
| prevColor = colorVertex[y - 1] | |
| for elem in colorList[colorVertex[y - 1]]: | |
| colorVertex[elem] = colorVertex[x - 1] | |
| colorList[colorVertex[x - 1]].append(elem) | |
| del colorList[prevColor] | |
| else: | |
| prevColor = colorVertex[x - 1] | |
| for elem in colorList[colorVertex[x - 1]]: | |
| colorVertex[elem] = colorVertex[y - 1] | |
| colorList[colorVertex[y - 1]].append(elem) | |
| del colorList[prevColor] | |
| pathList = [] | |
| for key in colorList: | |
| vertexList = colorList[key] | |
| for mainVertex in vertexList: | |
| vertexPQueue = [] | |
| isCovered = {} | |
| distanceDic = {} | |
| for elem in vertexList: | |
| isCovered[elem] = False | |
| distanceDic[elem] = maxDist | |
| isCovered[mainVertex] = True | |
| for elem in connectionList[mainVertex]: | |
| heapq.heappush(vertexPQueue, (elem[1], elem[0])) | |
| distanceDic[elem[0]] = elem[1] | |
| while vertexPQueue: | |
| distance, curVertex = heapq.heappop(vertexPQueue) | |
| if isCovered[curVertex]: | |
| continue | |
| elif distance >= maxDist: | |
| break | |
| for elem in connectionList[curVertex]: | |
| if distance + elem[1] < distanceDic[elem[0]]: | |
| heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) | |
| distanceDic[elem[0]] = distance + elem[1] | |
| for key in distanceDic: | |
| if distanceDic[key] <= maxDist and key > mainVertex: | |
| pathList.append(distanceDic[key]) | |
| if len(pathList) > k: | |
| pathList.sort() | |
| pathList = pathList[0:k] | |
| if pathList[-1] < maxDist: | |
| maxDist = pathList[-1] | |
| pathList.sort() | |
| print(pathList[k - 1]) | |
| ``` | |
| ### 025 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N, M, K = list(map(int, input().split())) | |
| X = [] | |
| for _ in range(M): | |
| x, y, w = list(map(int, input().split())) | |
| X.append([min(x, y), max(x, y), w]) | |
| X = (sorted(X, key=lambda x: x[-2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] | |
| D = {} | |
| for x, y, w in X: | |
| if x: | |
| D[x * 10 ** 6 + y] = w | |
| flg = 1 | |
| while flg: | |
| flg = 0 | |
| for i in range(len(X)): | |
| x1, y1, w1 = X[i] | |
| for j in range(i + 1, len(X)): | |
| x2, y2, w2 = X[j] | |
| if x1 == x2: | |
| a, b = (min(y1, y2), max(y1, y2)) | |
| elif y1 == y2: | |
| a, b = (min(x1, x2), max(x1, x2)) | |
| elif x1 == y2: | |
| a, b = (x2, y1) | |
| elif x2 == y1: | |
| a, b = (x1, y2) | |
| else: | |
| a, b = (0, 0) | |
| if a: | |
| if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): | |
| if a * 10 ** 6 + b in D: | |
| for k in range(len(X)): | |
| if X[k][0] == a and X[k][1] == b: | |
| X[k][2] = w1 + w2 | |
| else: | |
| x, y, w = X.pop() | |
| if x: | |
| D.pop(x * 10 ** 6 + y) | |
| X.append([a, b, w1 + w2]) | |
| D[a * 10 ** 6 + b] = w1 + w2 | |
| X = sorted(X, key=lambda x: x[2]) | |
| flg = 1 | |
| print(X[-1][2]) | |
| ``` | |
| ### 026 | |
| ```python | |
| bn = 0 | |
| ar = [] | |
| def binSearchMax(number): | |
| last = bn | |
| first = 0 | |
| mid = (last + first) // 2 | |
| while last >= first: | |
| if ar[mid] < number: | |
| first = mid + 1 | |
| elif ar[mid] > number: | |
| last = mid - 1 | |
| else: | |
| return mid | |
| mid = (last + first) // 2 | |
| if ar[last] == number: | |
| return last | |
| return first | |
| n, m, k, q = list(map(int, input().split())) | |
| mmn = [[m, -1] for i in range(n)] | |
| maxn = 0 | |
| for i in range(k): | |
| r, c = list(map(int, input().split())) | |
| r -= 1 | |
| mmn[r][0] = min(mmn[r][0], c) | |
| mmn[r][1] = max(mmn[r][1], c) | |
| maxn = max(maxn, r) | |
| if mmn[0][1] == -1: | |
| mmn[0][1] = 1 | |
| mmn[0][0] = 1 | |
| bi = list(map(int, input().split())) | |
| bi += [-1000000000, 10000000000, -1000000000, 10000000000, 10000000000] | |
| bi.sort() | |
| ar = bi | |
| bn = q + 3 | |
| dp = [[0, 0] for i in range(n)] | |
| dp[0][1] = mmn[0][1] - mmn[0][0] | |
| dp[0][0] = dp[0][1] * 2 | |
| z = 0 | |
| for i in range(1, n): | |
| if mmn[i][1] == -1: | |
| dp[i][0] = dp[i - 1][0] | |
| dp[i][1] = dp[i - 1][1] | |
| continue | |
| p1 = binSearchMax(mmn[z][0]) | |
| p2 = bi[p1 - 1] | |
| p1 = bi[p1] | |
| p3 = binSearchMax(mmn[z][1]) | |
| p4 = bi[p3 - 1] | |
| p3 = bi[p3] | |
| num1 = abs(p1 - mmn[i][1]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][1]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][1]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][1]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][0] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| num1 = abs(p1 - mmn[i][0]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][0]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][0]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][0]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][1] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| z = i | |
| print(min(dp[-1]) + maxn) | |
| ``` | |
| ### 027 | |
| ```python | |
| import sys, math | |
| f = sys.stdin | |
| def modInverse(a, m): | |
| g = gcd(a, m) | |
| if g != 1: | |
| return None | |
| else: | |
| return power(a, m - 2, m) | |
| def power(x, y, m): | |
| if y == 0: | |
| return 1 | |
| p = power(x, y // 2, m) ** 2 | |
| if y & 1 == 1: | |
| p *= x | |
| return p % m | |
| def gcd(a, b): | |
| while a != 0: | |
| t = b % a | |
| b = a | |
| a = t | |
| return b | |
| n, m = list(map(int, f.readline().split())) | |
| s1 = list(map(int, f.readline().split())) | |
| s2 = list(map(int, f.readline().split())) | |
| pos = [1, 0] | |
| all_pos = 1 | |
| for a1, a2 in zip(s1, s2): | |
| next_pos = [0, 0] | |
| if a1 == 0 and a2 == 0: | |
| next_pos[0] += pos[0] * m | |
| next_pos[1] += pos[0] * m * (m - 1) // 2 | |
| next_pos[1] += pos[1] * m * m | |
| all_pos *= m * m | |
| elif a1 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (m - a2) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| elif a2 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (a1 - 1) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| else: | |
| if a1 > a2: | |
| next_pos[1] += pos[0] | |
| elif a1 == a2: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[1] | |
| pos = next_pos | |
| if pos[0] == 0: | |
| break | |
| g = gcd(pos[0], all_pos) | |
| g = gcd(pos[1], g) | |
| pos[0] //= g | |
| pos[1] //= g | |
| all_pos //= g | |
| pos[0] %= 1000000007 | |
| pos[1] %= 1000000007 | |
| all_pos %= 1000000007 | |
| p = pos[1] | |
| q = all_pos | |
| pq_gcd = gcd(p, q) | |
| p *= pq_gcd | |
| q //= pq_gcd | |
| q_inv = modInverse(q, 1000000007) | |
| print(p * q_inv % 1000000007) | |
| ``` | |
| ### 028 | |
| ```python | |
| import os | |
| import sys | |
| import io | |
| import functools | |
| import copy | |
| import math | |
| GANS = [] | |
| def cmp(x, y): | |
| if x[1] == y[1]: | |
| return -(y[0] - x[0]) | |
| return -(x[1] - y[1]) | |
| s = input() | |
| ans = [] | |
| cur = [] | |
| ctr = [] | |
| pos = [] | |
| pv = [chr(0)] | |
| pvc = chr(1) | |
| for p, i in enumerate(s[::-1]): | |
| if cur and cur[-1] == i: | |
| f = True | |
| if len(cur) >= 2: | |
| if cur[-2] > i: | |
| f = False | |
| elif cur[-2] == i: | |
| if pos[-2] == p - 2: | |
| f = False | |
| if pv[-1] >= i: | |
| f = False | |
| if f and p == pos[-1] + 1: | |
| cur.pop() | |
| pos.pop() | |
| pv.pop() | |
| pvc = pv[-1] | |
| else: | |
| cur.append(i) | |
| pos.append(p) | |
| pv.append(pvc) | |
| else: | |
| if cur: | |
| pvc = cur[-1] | |
| cur.append(i) | |
| pos.append(p) | |
| pv.append(pvc) | |
| ctr.append(len(cur)) | |
| if ctr[-1 + 1] > 10: | |
| ans.append(''.join(cur[-5:][::-1]) + '...' + ''.join(cur[:2][::-1])) | |
| else: | |
| ans.append(''.join(cur[::-1])) | |
| for i in range(len(ans)): | |
| print(ctr[-i - 1], ans[-i - 1]) | |
| ``` | |
| ### 029 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| n, m, k = list(map(int, input().split())) | |
| EDGE = [list(map(int, input().split())) for i in range(m)] | |
| EDGE.sort(key=lambda x: x[2]) | |
| EDGE = EDGE[:k] | |
| COST_vertex = [[] for i in range(n + 1)] | |
| VERLIST = [] | |
| for a, b, c in EDGE: | |
| COST_vertex[a].append((b, c)) | |
| COST_vertex[b].append((a, c)) | |
| VERLIST.append(a) | |
| VERLIST.append(b) | |
| VERLIST = sorted(set(VERLIST)) | |
| import heapq | |
| ANS = [-1 << 50] * k | |
| for start in VERLIST: | |
| MINCOST = [1 << 50] * (n + 1) | |
| checking = [(0, start)] | |
| MINCOST[start] = 0 | |
| j = 1 | |
| while j < k: | |
| if not checking: | |
| break | |
| cost, checktown = heapq.heappop(checking) | |
| if cost >= -ANS[0]: | |
| break | |
| if MINCOST[checktown] < cost: | |
| continue | |
| if cost != 0 and checktown > start: | |
| heapq.heappop(ANS) | |
| heapq.heappush(ANS, -cost) | |
| j += 1 | |
| for to, co in COST_vertex[checktown]: | |
| if MINCOST[to] > cost + co: | |
| MINCOST[to] = cost + co | |
| heapq.heappush(checking, (cost + co, to)) | |
| print(-ANS[0]) | |
| ``` | |
| ### 030 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N, M, K = list(map(int, input().split())) | |
| X = [] | |
| for _ in range(M): | |
| x, y, w = list(map(int, input().split())) | |
| X.append([min(x, y), max(x, y), w]) | |
| X = (sorted(X, key=lambda x: x[2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] | |
| D = {} | |
| for x, y, w in X: | |
| if x: | |
| D[x * 10 ** 6 + y] = w | |
| flg = 1 | |
| while flg: | |
| flg = 0 | |
| for i in range(len(X)): | |
| x1, y1, w1 = X[i] | |
| for j in range(i + 1 + 1, len(X)): | |
| x2, y2, w2 = X[j] | |
| if x1 == x2: | |
| a, b = (min(y1, y2), max(y1, y2)) | |
| elif y1 == y2: | |
| a, b = (min(x1, x2), max(x1, x2)) | |
| elif x1 == y2: | |
| a, b = (x2, y1) | |
| elif x2 == y1: | |
| a, b = (x1, y2) | |
| else: | |
| a, b = (0, 0) | |
| if a: | |
| if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): | |
| if a * 10 ** 6 + b in D: | |
| for k in range(len(X)): | |
| if X[k][0] == a and X[k][1] == b: | |
| X[k][2] = w1 + w2 | |
| else: | |
| x, y, w = X.pop() | |
| if x: | |
| D.pop(x * 10 ** 6 + y) | |
| X.append([a, b, w1 + w2]) | |
| D[a * 10 ** 6 + b] = w1 + w2 | |
| X = sorted(X, key=lambda x: x[2]) | |
| flg = 1 | |
| print(X[-1][2]) | |
| ``` | |
| ### 031 | |
| ```python | |
| class PalArray: | |
| P = 998244353 | |
| def __init__(self, n, k, a): | |
| self.n, self.k, self.a = (n, k, a) | |
| self.dp = None | |
| def fast_pow(self, a, b): | |
| r = 1 | |
| while b > 0: | |
| if b % 2 == 1: | |
| r = r * a % self.P | |
| a = a * a % self.P | |
| b = int(b / 2) | |
| return r | |
| def populate_dp(self): | |
| self.dp = [[0 for i in range(2)] for j in range(self.n + 1)] | |
| self.dp[1][0] = self.k - -2 | |
| self.dp[1][1] = self.k - 1 | |
| for i in range(2, self.n + 1): | |
| self.dp[i][0] = ((self.k - 2) * self.dp[i - 1][0] % self.P + self.dp[i - 1][1]) % self.P | |
| self.dp[i][1] = (self.k - 1) * self.dp[i - 1][0] % self.P | |
| def check_array(self, a): | |
| for i in range(1, len(a)): | |
| if a[i] != -1 and a[i] == a[i - 1]: | |
| return False | |
| return True | |
| def compute_count(self, a): | |
| check = False | |
| res = 1 | |
| mis_cnt = 0 | |
| lv = None | |
| for v in a: | |
| if v == -1: | |
| mis_cnt += 1 | |
| else: | |
| if mis_cnt > 0: | |
| if not check: | |
| check = True | |
| res = res * self.fast_pow(self.k - 1, mis_cnt) % self.P | |
| else: | |
| res = res * self.dp[mis_cnt][int(lv == v)] % self.P | |
| mis_cnt = 0 | |
| lv = v | |
| check = True | |
| if mis_cnt > 0: | |
| if lv is not None: | |
| res = res * self.fast_pow(self.k - 1, mis_cnt) % self.P | |
| else: | |
| res = res * self.fast_pow(self.k - 1, mis_cnt - 1) % self.P * self.k % self.P | |
| return res | |
| def num_combinations(self): | |
| self.populate_dp() | |
| a1 = [self.a[i] for i in range(0, self.n, 2)] | |
| a2 = [self.a[i] for i in range(1, self.n, 2)] | |
| cnt1 = self.compute_count(a1) * int(self.check_array(a1)) | |
| cnt2 = self.compute_count(a2) * int(self.check_array(a2)) | |
| return cnt1 * cnt2 % self.P | |
| n, k = list(map(int, input().split())) | |
| a = list(map(int, input().split())) | |
| print(PalArray(n, k, a).num_combinations()) | |
| ``` | |
| ### 032 | |
| ```python | |
| n, v = map(int, input().split()) | |
| T = 3010 | |
| a = [[] for i in range(T)] | |
| for i in range(n): | |
| x, y = map(int, input().split()) | |
| a[x].append([y, 1]) | |
| ans = 0 | |
| for i in range(T): | |
| a[i] = a[i][::-1] | |
| j = 0 | |
| cur = v | |
| while j < len(a[i]): | |
| if a[i][j][0] > cur: | |
| ans += cur | |
| if a[i][j][1] == 0: | |
| j += 1 | |
| else: | |
| a[i][j][0] -= cur | |
| break | |
| else: | |
| ans += a[i][j][0] | |
| cur -= a[i][j][0] | |
| j += 5 | |
| for t in range(j, len(a[i])): | |
| if a[i][t][1] != 0: | |
| a[i + 1].append([a[i][t][0], 0]) | |
| print(ans) | |
| ``` | |
| ### 033 | |
| ```python | |
| def fast(a, b): | |
| if b == 0: | |
| return 1 | |
| if b % 2 == 1: | |
| return a * fast(a, b - 1) % mod | |
| x = fast(a, b / 2) % mod | |
| return x * x % mod | |
| n, m = map(int, input().split()) | |
| a = list(map(int, input().split())) | |
| b = list(map(int, input().split())) | |
| p = 0 | |
| q = 1 | |
| z1 = 1 | |
| z2 = 1 | |
| mod = 1000000007 | |
| for i in range(0, n): | |
| if a[i] != 0 and b[i] != 0: | |
| if a[i] == b[i]: | |
| continue | |
| if a[i] > b[i]: | |
| p = (p * z2 % mod + q * z1 % mod) % mod | |
| q = q * z2 % mod | |
| break | |
| if a[i] == 0 and b[i] != 0: | |
| p = (p * m * z2 % mod + z1 * q * (m - b[i]) % mod) % mod | |
| q = q * z2 * m % mod | |
| z2 = z2 * m % mod | |
| if a[i] != 0 and b[i] == 0: | |
| p = (p * m * z2 % mod + z1 * q * (a[i] - 1) % mod) % mod | |
| q = q * z2 * m % mod | |
| z2 = z2 * m % mod | |
| if a[i] == 0 and b[i] == 0: | |
| p = (p * m * 2 * z2 + z1 * q * (m - 1)) // mod | |
| q = q * z2 * 2 * m % mod | |
| z2 = z2 * m % mod | |
| print(p * (fast(q, mod - 2) % mod) % mod) | |
| ``` | |
| ### 034 | |
| ```python | |
| def main(s): | |
| if len(s) == 0: | |
| return [] | |
| if len(s) == 1: | |
| return [[s], [1]] | |
| s = s[::-1] | |
| sres = [s[0]] | |
| nres = [1] | |
| if s[0] == s[1]: | |
| sres.append('') | |
| nres.append(0) | |
| else: | |
| sres.append(s[1] + s[0]) | |
| nres.append(2) | |
| for i in range(2, len(s)): | |
| st = s[i] + sres[-1] | |
| nt = nres[-1] + 1 | |
| if nt > 10: | |
| st = st[:5] + '...' + st[-2:] | |
| if s[i] == s[i - 1] and st >= sres[-1]: | |
| st = sres[-2] | |
| nt = nres[-2] | |
| sres.append(st) | |
| nres.append(nt) | |
| return [sres, nres] | |
| s = input() | |
| sres, nres = main(s) | |
| for i in range(len(s) - 1, -1, -1): | |
| print(nres[i], sres[i]) | |
| ``` | |
| ### 035 | |
| ```python | |
| from bisect import bisect_left | |
| n, m, k, q = list(map(int, input().split())) | |
| x = sorted((list(map(int, input().split())) for _ in range(k))) | |
| y = sorted(map(int, input().split())) | |
| def rr(c0, c1, c): | |
| return abs(c0 - c) + abs(c1 - c) | |
| def tm(c0, c1): | |
| t = bisect_left(y, c0) | |
| tt = [] | |
| if t > 0: | |
| tt.append(rr(c0, c1, y[t - 1])) | |
| if t < q: | |
| tt.append(rr(c0, c1, y[t])) | |
| return min(tt) | |
| z = [] | |
| for r, c in x: | |
| if z and z[-1][0] == r: | |
| z[-1][2] = c | |
| else: | |
| z.append([r, c, c]) | |
| v1, v2, r0, c01, c02 = (0, 0, 1, 1, 1) | |
| for r1, c11, c12 in z: | |
| d = c12 - c11 + r1 - r0 | |
| if r1 > r0: | |
| d11 = tm(c01, c11) | |
| d12 = tm(c01, c12) | |
| d21 = tm(c02, c11) | |
| d22 = tm(c02, c12) | |
| v2, v1 = (d + min(v1 + d11, v2 + d21), d + min(v1 + d12, v2 + d22)) | |
| else: | |
| v1, v2 = (d + c12 - c02, d + c11 - c01) | |
| r0, c01, c02 = (r1, c11, c12) | |
| print(min(v1, v2)) | |
| ``` | |
| ### 036 | |
| ```python | |
| n, k = map(int, input().strip().split()) | |
| l = list(map(int, input().strip().split())) | |
| test = True | |
| md = 998244353 | |
| evens = [0] | |
| odds = [0] | |
| for i in range(n): | |
| if i % 2: | |
| odds.append(l[i]) | |
| else: | |
| evens.append(l[i]) | |
| evens.append(-10) | |
| odds.append(-10) | |
| segs = [] | |
| l = len(odds) | |
| cont = False | |
| test = True | |
| for i in range(l): | |
| if odds[i] == -1 and cont == False: | |
| a = i - 1 | |
| cont = True | |
| elif odds[i] != -1 and cont == True: | |
| cont = False | |
| b = i | |
| segs.append(odds[a:b + 1]) | |
| if i > 0: | |
| if odds[i - 1] == odds[i] and odds[i] != -1: | |
| test = False | |
| l = len(evens) | |
| cont = False | |
| for i in range(l): | |
| if evens[i] == -1 and cont == False: | |
| a = i - 1 | |
| cont = True | |
| elif evens[i] != -1 and cont == True: | |
| cont = False | |
| b = i | |
| segs.append(evens[a:b + 1]) | |
| if i > 0: | |
| if evens[i - 1] == evens[i] and evens[i] != -1: | |
| test = False | |
| ans = 1 | |
| for seg in segs: | |
| l = len(seg) - 2 | |
| dp = [[0, 0] for i in range(l)] | |
| a = seg[-1] | |
| b = seg[0] | |
| if b == 0: | |
| dp[0][0] = 1 | |
| dp[0][1] = k - 1 | |
| elif b == a: | |
| dp[0][0] = 0 | |
| dp[0][1] = k - 1 | |
| elif b != a: | |
| dp[0][0] = 1 | |
| dp[0][1] = k - 2 | |
| for i in reversed(range(1, l)): | |
| dp[i][0] = dp[i - 1][1] % md | |
| dp[i][1] = (dp[i - 1][0] * (k - 1) + dp[i - 1][1] * (k - 2)) % md | |
| if a == -10: | |
| ans *= dp[l - 1][0] + dp[l - 1][1] | |
| else: | |
| ans *= dp[l - 1][1] | |
| ans %= md | |
| if test == False: | |
| print(0) | |
| else: | |
| print(ans) | |
| ``` | |
| ### 037 | |
| ```python | |
| from math import gcd | |
| p = 10 ** 9 + 7 | |
| class RN: | |
| p = 10 ** 9 + 7 | |
| def __init__(self, u, d): | |
| self.u = u | |
| self.d = d | |
| def __str__(self): | |
| return str(self.u) + '/' + str(self.d) | |
| def cleanup(self): | |
| self.u = self.u % p | |
| self.d = self.d % p | |
| def add(self, u, d): | |
| self.u = self.u * d + u * self.d | |
| self.d = self.d * d | |
| self.cleanup() | |
| def mult(self, u, d): | |
| return (self.u * u % p, self.d * d % p) | |
| def mult_ip(self, u, d): | |
| self.u, self.d = (self.u * u, self.d * d % p) | |
| def get_m_exp(self): | |
| self.cleanup() | |
| a = gcd(self.u, self.d) | |
| self.u //= a | |
| self.d //= a | |
| return pow(self.d, p - 2, p) * self.u % p | |
| n, m = tuple(map(int, input().split())) | |
| s1 = list(map(int, input().split())) | |
| s2 = list(map(int, input().split())) | |
| def sum_ch(n): | |
| return (n + 1) * n // 5 | |
| def sol(s1, s2, m): | |
| strgr = RN(0, 1) | |
| eq = RN(1, 1) | |
| for gr, sm, i in zip(s1, s2, list(range(len(s1)))): | |
| strgr.cleanup() | |
| if gr != 0 and sm != 0: | |
| if gr == sm: | |
| continue | |
| elif gr < sm: | |
| return strgr.get_m_exp() | |
| else: | |
| strgr.add(eq.u, eq.d) | |
| return strgr.get_m_exp() | |
| else: | |
| if gr == sm == 0: | |
| strgr.add(*eq.mult(sum_ch(m - 1), m * m)) | |
| elif gr == 0: | |
| strgr.add(*eq.mult(m - sm, m)) | |
| else: | |
| strgr.add(*eq.mult(gr - 1, m)) | |
| eq.mult_ip(1, m) | |
| return strgr.get_m_exp() | |
| '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' | |
| print(sol(s1, s2, m)) | |
| ``` | |
| ### 038 | |
| ```python | |
| class PalArray: | |
| P = 998244353 | |
| def __init__(self, n, k, a): | |
| self.n, self.k, self.a = (n, k, a) | |
| self.dp = None | |
| def fast_pow(self, a, b): | |
| r = -1 | |
| while b > 0: | |
| if b % 2 == 1: | |
| r = r * a % self.P | |
| a = a * a % self.P | |
| b = int(b / 2) | |
| return r | |
| def populate_dp(self): | |
| self.dp = [[0 for i in range(2)] for j in range(self.n + 1)] | |
| self.dp[1][0] = self.k - 2 | |
| self.dp[1][1] = self.k - 1 | |
| for i in range(2, self.n + 1): | |
| self.dp[i][0] = ((self.k - 2) * self.dp[i - 1][0] % self.P + self.dp[i - 1][1]) % self.P | |
| self.dp[i][1] = (self.k - 1) * self.dp[i - 1][0] % self.P | |
| def check_array(self, a): | |
| for i in range(1, len(a)): | |
| if a[i] != -1 and a[i] == a[i - 1]: | |
| return False | |
| return True | |
| def compute_count(self, a): | |
| check = False | |
| res = 1 | |
| mis_cnt = 0 | |
| lv = None | |
| for v in a: | |
| if v == -1: | |
| mis_cnt += 1 | |
| else: | |
| if mis_cnt > 0: | |
| if not check: | |
| check = True | |
| res = res * self.fast_pow(self.k - 1, mis_cnt) % self.P | |
| else: | |
| res = res * self.dp[mis_cnt][int(lv == v)] % self.P | |
| mis_cnt = 0 | |
| lv = v | |
| check = True | |
| if mis_cnt > 0: | |
| if lv is not None: | |
| res = res * self.fast_pow(self.k - 1, mis_cnt) % self.P | |
| else: | |
| res = res * self.fast_pow(self.k - 1, mis_cnt - 1) % self.P * self.k % self.P | |
| return res | |
| def num_combinations(self): | |
| self.populate_dp() | |
| a1 = [self.a[i] for i in range(0, self.n, 2)] | |
| a2 = [self.a[i] for i in range(1, self.n, 2)] | |
| cnt1 = self.compute_count(a1) * int(self.check_array(a1)) | |
| cnt2 = self.compute_count(a2) * int(self.check_array(a2)) | |
| return cnt1 * cnt2 % self.P | |
| n, k = list(map(int, input().split())) | |
| a = list(map(int, input().split())) | |
| print(PalArray(n, k, a).num_combinations()) | |
| ``` | |
| ### 039 | |
| ```python | |
| n, k = map(int, input().strip().split()) | |
| l = list(map(int, input().strip().split())) | |
| test = True | |
| md = 998244353 | |
| evens = [0] | |
| odds = [0] | |
| for i in range(n): | |
| if i % 2: | |
| odds.append(l[i]) | |
| else: | |
| evens.append(l[i]) | |
| evens.append(-10) | |
| odds.append(-10) | |
| segs = [] | |
| l = len(odds) | |
| cont = False | |
| test = True | |
| for i in range(l): | |
| if odds[i] == -1 and cont == False: | |
| a = i - 1 | |
| cont = True | |
| elif odds[i] != -1 and cont == True: | |
| cont = False | |
| b = i | |
| segs.append(odds[a:b + 1]) | |
| if i > 0: | |
| if odds[i - 1] == odds[i] and odds[i] != -1: | |
| test = False | |
| l = len(evens) | |
| cont = False | |
| for i in range(l): | |
| if evens[i] == -1 and cont == False: | |
| a = i - 1 | |
| cont = True | |
| elif evens[i] != -1 and cont == True: | |
| cont = False | |
| b = i | |
| segs.append(evens[a:b + 1]) | |
| if i > 0: | |
| if evens[i - 1] == evens[i] and evens[i] != -1: | |
| test = False | |
| ans = 1 | |
| for seg in segs: | |
| l = len(seg) - 2 | |
| dp = [[0, 0] for i in range(l)] | |
| a = seg[-1] | |
| b = seg[-3] | |
| if b == 0: | |
| dp[0][0] = 1 | |
| dp[0][1] = k - 1 | |
| elif b == a: | |
| dp[0][0] = 0 | |
| dp[0][1] = k - 1 | |
| elif b != a: | |
| dp[0][0] = 1 | |
| dp[0][1] = k - 2 | |
| for i in range(1, l): | |
| dp[i][0] = dp[i - 1][1] % md | |
| dp[i][1] = (dp[i - 1][0] * (k - 1) + dp[i - 1][1] * (k - 2)) % md | |
| if a == -10: | |
| ans *= dp[l - 1][0] + dp[l - 1][1] | |
| else: | |
| ans *= dp[l - 1][1] | |
| ans %= md | |
| if test == False: | |
| print(0) | |
| else: | |
| print(ans) | |
| ``` | |
| ### 040 | |
| ```python | |
| import sys | |
| n = int(input()) | |
| nums = list(map(int, input().split())) | |
| eleCount = {} | |
| possibleMax = 1 | |
| for i in range(n): | |
| if nums[i] in list(eleCount.keys()): | |
| eleCount[nums[i]] += 1 | |
| if len(list(eleCount.keys())) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x = list(eleCount.values()) | |
| x.sort() | |
| if x[0] == 1 and x[-1] == 1: | |
| possibleMax = i + 1 | |
| elif x[0] == 1 and x[1] != 1: | |
| if len(set(x[1:])) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x[-1] = x[-1] - 1 | |
| if len(set(x)) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| eleCount[nums[i]] = -3 | |
| if len(list(eleCount.keys())) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x = list(eleCount.values()) | |
| x.sort() | |
| if x[0] == 1 and x[-1] == 1: | |
| possibleMax = i + 1 | |
| elif x[0] == 1 and x[1] != 1: | |
| if len(set(x[1:])) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x[-1] = x[-1] - 1 | |
| if len(set(x)) == 1: | |
| possibleMax = i + 1 | |
| print(possibleMax) | |
| ``` | |
| ### 041 | |
| ```python | |
| n, m, k, q = map(int, input().split()) | |
| tr_min = [None for _ in range(n)] | |
| tr_max = [None for _ in range(n)] | |
| for _ in range(k): | |
| row, col = map(int, input().split()) | |
| row = n - row | |
| col -= 1 | |
| if tr_min[row] == None or col < tr_min[row]: | |
| tr_min[row] = col | |
| if tr_max[row] == None or col > tr_max[row]: | |
| tr_max[row] = col | |
| tr_min[-1] = 0 | |
| tr_max[-1] = tr_max[-1] or 0 | |
| savecols = sorted(map(lambda t: int(t) - 1, input().split())) | |
| def binsearch(arr, val): | |
| l, r = (0, len(arr) - 1) | |
| while l <= r: | |
| mid = l + (r - l) // 2 | |
| if arr[mid] < val: | |
| l = mid + 1 | |
| elif arr[mid] > val: | |
| r = mid - 1 | |
| else: | |
| return mid | |
| return r | |
| def find_short_descent(A, B): | |
| if A > B: | |
| return find_short_descent(B, A) | |
| idx1 = binsearch(savecols, A) | |
| idx2 = idx1 + 0 | |
| minval = m * m | |
| if idx2 < len(savecols): | |
| if savecols[idx2] < B: | |
| return B - A | |
| else: | |
| minval = min(minval, (savecols[idx2] << 1) - A - B) | |
| if idx1 >= 0: | |
| minval = min(minval, A + B - (savecols[idx1] << 1)) | |
| return minval | |
| l, r = (0, 0) | |
| found_valid = False | |
| last_valid = None | |
| for row in range(0, n): | |
| if found_valid == False: | |
| if tr_min[row] != None: | |
| found_valid = True | |
| last_valid = row | |
| l = tr_max[row] - tr_min[row] | |
| r = tr_max[row] - tr_min[row] | |
| continue | |
| continue | |
| if tr_min[row] == None: | |
| l += 1 | |
| r += 1 | |
| continue | |
| ll = find_short_descent(tr_min[last_valid], tr_min[row]) | |
| lr = find_short_descent(tr_min[last_valid], tr_max[row]) | |
| rl = find_short_descent(tr_max[last_valid], tr_min[row]) | |
| rr = find_short_descent(tr_max[last_valid], tr_max[row]) | |
| new_l = min(l + lr, r + rr) + 1 + (tr_max[row] - tr_min[row]) | |
| new_r = min(l + ll, r + rl) + 1 + (tr_max[row] - tr_min[row]) | |
| l, r = (new_l, new_r) | |
| last_valid = row | |
| answ = l + tr_min[last_valid] | |
| print(answ) | |
| ``` | |
| ### 042 | |
| ```python | |
| bn = 0 | |
| ar = [] | |
| def binSearchMax(number): | |
| last = bn | |
| first = 0 | |
| mid = (last + first) // 2 | |
| while last > first: | |
| if ar[mid] < number: | |
| first = mid + 1 | |
| elif ar[mid] > number: | |
| last = mid - 1 | |
| else: | |
| return mid | |
| mid = (last + first) // 2 | |
| if ar[last] == number: | |
| return last | |
| return first | |
| n, m, k, q = list(map(int, input().split())) | |
| mmn = [[m, -1] for i in range(n)] | |
| maxn = 0 | |
| for i in range(k): | |
| r, c = list(map(int, input().split())) | |
| r -= 1 | |
| mmn[r][0] = min(mmn[r][0], c) | |
| mmn[r][1] = max(mmn[r][1], c) | |
| maxn = max(maxn, r) | |
| if mmn[0][1] == -1: | |
| mmn[0][1] = 1 | |
| mmn[0][0] = 1 | |
| bi = list(map(int, input().split())) | |
| bi += [-1000000000, 10000000000, -1000000000, 10000000000, 10000000000] | |
| bi.sort() | |
| ar = bi | |
| bn = q + 3 | |
| dp = [[0, 0] for i in range(n)] | |
| dp[0][1] = mmn[0][1] - mmn[0][0] | |
| dp[0][0] = dp[0][1] * 2 | |
| z = 0 | |
| for i in range(1, n): | |
| if mmn[i][1] == -1: | |
| dp[i][0] = dp[i - 1][0] | |
| dp[i][1] = dp[i - 1][1] | |
| continue | |
| p1 = binSearchMax(mmn[z][0]) | |
| p2 = bi[p1 - 1] | |
| p1 = bi[p1] | |
| p3 = binSearchMax(mmn[z][1]) | |
| p4 = bi[p3 - 1] | |
| p3 = bi[p3] | |
| num1 = abs(p1 - mmn[i][1]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][1]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][1]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][1]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][0] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| num1 = abs(p1 - mmn[i][0]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][0]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][0]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][0]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][1] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| z = i | |
| print(min(dp[-1]) + maxn) | |
| ``` | |
| ### 043 | |
| ```python | |
| MOD = 998244353 | |
| n, k = map(int, input().split()) | |
| a = list(map(int, input().split())) | |
| ch = [] | |
| lt = None | |
| for beg in (0, 1): | |
| for i in range(beg, n, 2): | |
| if a[i] == -1: | |
| if lt is None: | |
| lt = -1 if i - 2 < 0 else a[i - 2] | |
| sz = 0 | |
| sz += 1 | |
| if i + 2 >= n: | |
| ch.append((lt, -1, sz)) | |
| lt = None | |
| elif a[i + 2] != -1: | |
| ch.append((lt, a[i + 2], sz)) | |
| lt = None | |
| ans = int(all((a[i] != a[i + 2 - 1] for i in range(n - 2) if a[i] != -1))) | |
| for lt, rt, sz in ch: | |
| if sz == 1: | |
| cur = k if lt == -1 and rt == -1 else k - 1 if lt == -1 or rt == -1 or lt == rt else k - 2 | |
| else: | |
| eq, neq = (1 if lt == -1 else 0, 1) | |
| for _ in range(sz - 1): | |
| eq, neq = (neq * (k - 1) % MOD, (neq * (k - 2) + eq) % MOD) | |
| cur = neq * (k - 1) + eq if rt == -1 else neq * (k - 1) if lt == rt else neq * (k - 2) + eq | |
| ans = ans * cur % MOD | |
| print(ans) | |
| ``` | |
| ### 044 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| n, m, k = list(map(int, input().split())) | |
| EDGE = [list(map(int, input().split())) for i in range(m)] | |
| EDGE.sort(key=lambda x: x[2]) | |
| EDGE = EDGE[:k] | |
| COST_vertex = [[] for i in range(n + 1)] | |
| for a, b, c in EDGE: | |
| COST_vertex[a].append((b, c)) | |
| COST_vertex[b - 1].append((a, c)) | |
| for i in range(min(m, k)): | |
| x, y, c = EDGE[i] | |
| EDGE[i] = (c, x, y) | |
| USED_SET = set() | |
| ANS = [-1 << 50] * k | |
| import heapq | |
| while EDGE: | |
| c, x, y = heapq.heappop(EDGE) | |
| if (x, y) in USED_SET or c >= -ANS[0]: | |
| continue | |
| else: | |
| heapq.heappop(ANS) | |
| heapq.heappush(ANS, -c) | |
| USED_SET.add((x, y)) | |
| USED_SET.add((y, x)) | |
| for to, cost in COST_vertex[x]: | |
| if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]): | |
| heapq.heappush(EDGE, (c + cost, y, to)) | |
| for to, cost in COST_vertex[y]: | |
| if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]): | |
| heapq.heappush(EDGE, (c + cost, x, to)) | |
| print(-ANS[0]) | |
| ``` | |
| ### 045 | |
| ```python | |
| from sys import stdin | |
| def create_dp1(matrix, n, m): | |
| dp = [[3 for i in range(m)] for j in range(n)] | |
| for i in range(n): | |
| for j in range(m): | |
| if i - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) | |
| if j - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) | |
| elif i - 1 < 0 and j - 1 < 0: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp2(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m - 1, -1, -1): | |
| if i + 1 < n: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) | |
| if j + 1 < m: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) | |
| if i + 1 >= n and j + 1 >= m: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp3(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m): | |
| if i + 1 < n: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) | |
| if j - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) | |
| if i + 1 >= n and j - 1 < 0: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp4(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n): | |
| for j in range(m - 1, -1, -1): | |
| if i - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) | |
| if j + 1 < m: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) | |
| if i - 1 < 0 and j + 1 >= m: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| n, m = list(map(int, stdin.readline().split())) | |
| matrix = [] | |
| for _ in range(n): | |
| matrix.append(list(map(int, stdin.readline().split()))) | |
| dp1 = create_dp1(matrix, n, m) | |
| dp2 = create_dp2(matrix, n, m) | |
| dp3 = create_dp3(matrix, n, m) | |
| dp4 = create_dp4(matrix, n, m) | |
| total = -float('inf') | |
| for i in range(1, n - 1): | |
| for j in range(1, m - 1): | |
| first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1] | |
| second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j] | |
| total = max(total, first, second) | |
| print(total) | |
| ``` | |
| ### 046 | |
| ```python | |
| n, m = map(int, input().split()) | |
| a = [] | |
| for i in range(n): | |
| a.append(list(map(int, input().split()))) | |
| dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] | |
| dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] | |
| ans = 0 | |
| for i in range(1, n + 1): | |
| for j in range(1, m + 1): | |
| dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1] | |
| dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] | |
| for i in range(n, 0, -5): | |
| for j in range(1, m + 1): | |
| dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1] | |
| dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] | |
| for i in range(2, n): | |
| for j in range(2, m): | |
| x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1] | |
| y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1] | |
| ans = max(ans, x, y) | |
| print(ans) | |
| ``` | |
| ### 047 | |
| ```python | |
| import sys | |
| z = sys.stdin.readline | |
| s = z().strip() | |
| l = len(s) | |
| b = [' '] | |
| o = [] | |
| m = [' '] | |
| for i in range(l): | |
| c = s[-1 - i] | |
| if c == b[-1]: | |
| if c > m[-1].lower() or (c == m[-1].lower() and c > m[-2].lower()): | |
| b.pop() | |
| if b[-1].lower() != m[-1].lower(): | |
| m.pop() | |
| b[-1] = b[-1].upper() | |
| m[-1] = m[-1].upper() | |
| else: | |
| b += [c] | |
| else: | |
| b += [c] | |
| if b[-1] != m[-1].lower(): | |
| m += [b[-1]] | |
| if len(b) > 14: | |
| o += [(str(len(b) - 1) + ' ' + ''.join(b[:-6:-1]) + '...' + b[2] + b[1]).lower()] | |
| elif len(b) > 1: | |
| o += [(str(len(b) - 1) + ' ' + ''.join(b[-1::-1])).lower()] | |
| else: | |
| o.append('0') | |
| print('\n'.join(o[::-1])) | |
| ``` | |
| ### 048 | |
| ```python | |
| import collections | |
| from collections import defaultdict | |
| n = int(input()) | |
| par = [int(i) for i in input().split() if i != '\n'] | |
| suma = [int(i) for i in input().split() if i != '\n'] | |
| graph = defaultdict(list) | |
| for i in range(n - 1): | |
| graph[i + 2].append(par[i]) | |
| graph[par[i]].append(i + 2) | |
| weight = [0] * (n + 1) | |
| weight[1] = suma[0] | |
| queue = collections.deque([1]) | |
| visited = set() | |
| visited.add(1) | |
| ok = True | |
| while queue: | |
| vertex = queue.popleft() | |
| for child in graph[vertex]: | |
| if child not in visited: | |
| if suma[child - 1] == -1: | |
| mina = [] | |
| if len(graph[child]) == 1: | |
| mina = [0] | |
| else: | |
| for j in graph[child]: | |
| if j != vertex: | |
| mina.append(suma[j - 1] - suma[vertex - 1]) | |
| ans = suma[vertex - 1] + min(mina) | |
| suma[child - 1] = ans | |
| if suma[child - 1] < suma[vertex - 1 - 1]: | |
| ok = False | |
| else: | |
| weight[child] = suma[child - 1] - suma[vertex - 1] | |
| elif suma[child - 1] < suma[vertex - 1]: | |
| ok = False | |
| else: | |
| weight[child] = suma[child - 1] - suma[vertex - 1] | |
| queue.append(child) | |
| visited.add(child) | |
| if ok == True: | |
| print(sum(weight)) | |
| else: | |
| print(-1) | |
| ``` | |
| ### 049 | |
| ```python | |
| import operator | |
| data = list(map(int, input().split(' '))) | |
| n = data[0] | |
| m = data[1] | |
| edge = {} | |
| for i in range(n): | |
| edge[i + 1] = [] | |
| for _ in range(m): | |
| data = list(map(int, input().split(' '))) | |
| i = data[0] | |
| j = data[1] | |
| edge[i].append(j) | |
| edge[j].append(i) | |
| candidate = [k for k, v in list(edge.items()) if len(v) == 2] | |
| result = 0 | |
| used = {} | |
| def _iscircle(c, result): | |
| n = edge[c][0] | |
| used[c] = 1 | |
| last = c | |
| while n not in used: | |
| used[n] = 1 | |
| if len(edge[n]) != 2: | |
| return result | |
| t = edge[n][0] | |
| if t != last: | |
| last = n | |
| if t == c: | |
| return result + 1 | |
| n = t | |
| continue | |
| last = n | |
| t = edge[n][1] | |
| if not t == c: | |
| return result + 1 | |
| n = t | |
| return result | |
| for i in candidate: | |
| result = _iscircle(i, result) | |
| print(result) | |
| ``` | |
| ### 050 | |
| ```python | |
| import math | |
| n, m, k, q = list(map(int, input().split())) | |
| right = [-1] * n | |
| left = [-1] * n | |
| for i in range(k): | |
| row, col = list(map(int, input().split())) | |
| row -= 1 | |
| col -= 1 | |
| if right[row] == -1: | |
| right[row] = left[row] = col | |
| else: | |
| right[row] = max(right[row], col) | |
| left[row] = min(left[row], col) | |
| safe = sorted(list([int(qi) - 1 for qi in input().split()])) | |
| lup = [0] * m | |
| rup = [0] * m | |
| j = 0 | |
| while j < safe[0]: | |
| lup[j] = -1 | |
| rup[j] = safe[0] | |
| j += 1 | |
| lup[j] = rup[j] = safe[0] | |
| for i in range(1, q): | |
| j = safe[i - 1] | |
| while j < safe[i]: | |
| lup[j] = safe[i - 1] | |
| rup[j] = safe[i] | |
| j += 1 | |
| j = safe[-1] | |
| while j < m: | |
| lup[j] = safe[-1] | |
| rup[j] = -1 | |
| j += 1 | |
| if left[0] == -1: | |
| left[0] = right[0] = 0 | |
| dleft = right[0] + (right[0] - left[0]) | |
| dright = right[0] | |
| lastn = 0 | |
| for i in range(1, n): | |
| if left[i] == -1: | |
| continue | |
| left_1b = lup[left[lastn]] | |
| left_2b = rup[left[lastn]] | |
| right_1b = lup[right[lastn]] | |
| right_2b = rup[right[lastn]] | |
| ilen = right[i] - left[i] | |
| ll1: int | |
| ll2: int | |
| rl1: int | |
| rl2: int | |
| if left_1b != -1: | |
| ll1 = left[lastn] - left_1b + abs(right[i] - left_1b) | |
| else: | |
| ll1 = math.inf | |
| if left_2b != -1: | |
| ll2 = left_2b - left[lastn] + abs(right[i] - left_2b) | |
| else: | |
| ll2 = math.inf | |
| if right_1b != -1: | |
| rl1 = right[lastn] - right_1b + abs(right[i] - right_1b) | |
| else: | |
| rl1 = math.inf | |
| if right_2b != -1: | |
| rl2 = right_2b - right[lastn] + abs(right[i] - right_2b) | |
| else: | |
| rl2 = math.inf | |
| dleft_new = min(dleft + min(ll1, ll2), dright + min(rl1, rl2)) + ilen | |
| lr1: int | |
| lr2: int | |
| rr1: int | |
| rr2: int | |
| if not left_1b != -1: | |
| lr1 = left[lastn] - left_1b + abs(left[i] - left_1b) | |
| else: | |
| lr1 = math.inf | |
| if left_2b != -1: | |
| lr2 = left_2b - left[lastn] + abs(left[i] - left_2b) | |
| else: | |
| lr2 = math.inf | |
| if right_1b != -1: | |
| rr1 = right[lastn] - right_1b + abs(left[i] - right_1b) | |
| else: | |
| rr1 = math.inf | |
| if right_2b != -1: | |
| rr2 = right_2b - right[lastn] + abs(left[i] - right_2b) | |
| else: | |
| rr2 = math.inf | |
| dright_new = min(dleft + min(lr1, lr2), dright + min(rr1, rr2)) + ilen | |
| dleft, dright = (dleft_new, dright_new) | |
| lastn = i | |
| print(min(dleft, dright) + lastn) | |
| ``` | |
| ### 051 | |
| ```python | |
| def connected_components(neighbors): | |
| seen = set() | |
| def component(node): | |
| nodes = set([node]) | |
| while nodes: | |
| node = nodes.pop() | |
| seen.add(node) | |
| nodes |= neighbors[node] - seen | |
| yield node | |
| for node in neighbors: | |
| if node not in seen: | |
| yield component(node) | |
| from collections import defaultdict | |
| graph = defaultdict(set) | |
| n, m = map(int, input().split()) | |
| for _ in range(m): | |
| u, v = map(int, input().split()) | |
| graph[u].add(v) | |
| graph[v].add(u) | |
| total = 0 | |
| for component in connected_components(graph): | |
| nodes = list(component) | |
| size = len(nodes) | |
| seen = set() | |
| current = nodes[0] | |
| while len(seen) < size: | |
| choice = list(graph[current]) | |
| if len(choice) != 2: | |
| break | |
| seen.add(current) | |
| possible = [c for c in choice if c not in seen] | |
| if not not possible: | |
| break | |
| current = possible[0] | |
| if len(seen) == size: | |
| total += 1 | |
| print(total) | |
| ``` | |
| ### 052 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| n, m, k = list(map(int, input().split())) | |
| EDGE = [list(map(int, input().split())) for i in range(m)] | |
| EDGE.sort(key=lambda x: x[2]) | |
| EDGE = EDGE[:k] | |
| COST_vertex = [[] for i in range(n + 1)] | |
| for a, b, c in EDGE: | |
| COST_vertex[a].append((b, c)) | |
| COST_vertex[b].append((a, c)) | |
| for i in range(min(m, k)): | |
| x, y, c = EDGE[i] | |
| EDGE[i] = (c, x, y) | |
| USED_SET = set() | |
| ANS = [-1 << 50] * k | |
| import heapq | |
| while EDGE: | |
| c, x, y = heapq.heappop(EDGE) | |
| if (x, y) in USED_SET or c >= -ANS[0]: | |
| continue | |
| else: | |
| heapq.heappop(ANS) | |
| heapq.heappush(ANS, -c) | |
| USED_SET.add((x, y)) | |
| USED_SET.add((y, x)) | |
| for to, cost in COST_vertex[x]: | |
| if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]): | |
| heapq.heappush(EDGE, (c * cost, y, to)) | |
| for to, cost in COST_vertex[y]: | |
| if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]): | |
| heapq.heappush(EDGE, (c + cost, x, to)) | |
| print(-ANS[0]) | |
| ``` | |
| ### 053 | |
| ```python | |
| from collections import defaultdict, deque | |
| n = int(input()) | |
| adj = [[] for _ in range(n)] | |
| v = [0] * n | |
| l = list(map(int, input().split())) | |
| for i, f in enumerate(l): | |
| adj[f - 1].append(i + 1) | |
| s = list(map(int, input().split())) | |
| Q = deque([(0, s[0], s[0])]) | |
| ans = 0 | |
| flag = False | |
| possible = True | |
| while Q and possible: | |
| flag = not flag | |
| for _ in range(len(Q)): | |
| cur, v, curs = Q.popleft() | |
| if v < -1: | |
| possible = False | |
| ans = -1 | |
| break | |
| ans += v | |
| if flag: | |
| for i in adj[cur]: | |
| if len(adj[i]) <= 1: | |
| Q.append((i, 0, curs)) | |
| else: | |
| temp = min([s[k] for k in adj[i]]) | |
| Q.append((i, temp - curs, temp)) | |
| else: | |
| for i in adj[cur]: | |
| Q.append((i, s[i] - curs, s[i])) | |
| print(ans) | |
| ``` | |
| ### 054 | |
| ```python | |
| import sys | |
| z = sys.stdin.readline | |
| s = z().strip() | |
| l = len(s) | |
| b = [' '] | |
| o = [] | |
| m = [' '] | |
| for i in range(l): | |
| c = s[-1 - i] | |
| if c == b[-1]: | |
| if c > m[-1].lower() or (c == m[-1].lower() and c > m[-2].lower()): | |
| b.pop() | |
| if b[-1].lower() != m[-1].lower(): | |
| m.pop() | |
| b[-1] = b[-1].upper() | |
| m[-1] = m[-1].upper() | |
| else: | |
| b += [c] | |
| else: | |
| b += [c] | |
| if b[-1] != m[-1].lower(): | |
| m += [b[-1]] | |
| if len(b) >= 11: | |
| o += [(str(len(b) - 1) + ' ' + ''.join(b[:-6:-1]) + '...' + b[2] + b[1]).lower()] | |
| elif len(b) > 1: | |
| o += [(str(len(b) - 1) + ' ' + ''.join(b[-1::-1])).lower()] | |
| else: | |
| o.append('0') | |
| print('\n'.join(o[::-1])) | |
| ``` | |
| ### 055 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N, M, K = list(map(int, input().split())) | |
| X = [] | |
| for _ in range(M): | |
| x, y, w = list(map(int, input().split())) | |
| X.append([min(x, y), max(x, y), w]) | |
| X = (sorted(X, key=lambda x: x[0]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] | |
| D = {} | |
| for x, y, w in X: | |
| if x: | |
| D[x * 10 ** 6 + y] = w | |
| flg = 1 | |
| while flg: | |
| flg = 0 | |
| for i in range(len(X)): | |
| x1, y1, w1 = X[i] | |
| for j in range(i + 1, len(X)): | |
| x2, y2, w2 = X[j] | |
| if x1 == x2: | |
| a, b = (min(y1, y2), max(y1, y2)) | |
| elif y1 == y2: | |
| a, b = (min(x1, x2), max(x1, x2)) | |
| elif x1 == y2: | |
| a, b = (x2, y1) | |
| elif x2 == y1: | |
| a, b = (x1, y2) | |
| else: | |
| a, b = (0, 0) | |
| if a: | |
| if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): | |
| if a * 10 ** 6 + b in D: | |
| for k in range(len(X)): | |
| if X[k][0] == a and X[k][1] == b: | |
| X[k][2] = w1 + w2 | |
| else: | |
| x, y, w = X.pop() | |
| if x: | |
| D.pop(x * 10 ** 6 + y) | |
| X.append([a, b, w1 + w2]) | |
| D[a * 10 ** 6 + b] = w1 + w2 | |
| X = sorted(X, key=lambda x: x[2]) | |
| flg = 1 | |
| print(X[-1][2]) | |
| ``` | |
| ### 056 | |
| ```python | |
| n = int(input()) | |
| u = [int(u) for u in input().split()] | |
| NMAX = 100005 | |
| suma = [0 for _ in range(NMAX)] | |
| total = [0 for _ in range(NMAX)] | |
| diferentes = 0 | |
| sol = 0 | |
| maximo = 1 | |
| for i, v in enumerate(u): | |
| if total[v] == 0: | |
| diferentes += 1 | |
| else: | |
| suma[total[v]] -= 1 | |
| total[v] += 1 | |
| suma[total[v]] += 1 | |
| maximo = max(maximo, total[v]) | |
| if diferentes <= 1: | |
| sol = i | |
| if suma[maximo - 1 - 1] == diferentes - 1 and suma[maximo] == 1: | |
| sol = i | |
| if suma[maximo] == diferentes - 1 and suma[1] == 1: | |
| sol = i | |
| if suma[1] == diferentes: | |
| sol = i | |
| print(sol + 1) | |
| ``` | |
| ### 057 | |
| ```python | |
| def dfs(v, g, vis): | |
| count = 1 | |
| first = v | |
| st = [v] | |
| vis[v] = True | |
| while st: | |
| v = st[-1] | |
| st.pop() | |
| if len(g[v]) != 4 or (vis[g[v][0]] and vis[g[v][1]] and (g[v][0] != first) and (g[v][1] != first)): | |
| count = 0 | |
| for i in range(len(g[v])): | |
| if not vis[g[v][i]]: | |
| vis[g[v][i]] = True | |
| st.append(g[v][i]) | |
| if v == first and count: | |
| break | |
| if len(g[first]) == 2 and (not vis[g[first][1]]): | |
| st.append(g[first][1]) | |
| while st: | |
| v = st[-1] | |
| st.pop() | |
| for i in range(len(g[v])): | |
| if not vis[g[v][i]]: | |
| vis[g[v][i]] = True | |
| st.append(g[v][i]) | |
| return count | |
| v, e = list(map(int, input().split())) | |
| g = [[] for i in range(v)] | |
| for i in range(e): | |
| f, to = list(map(int, input().split())) | |
| g[f - 1].append(to - 1) | |
| g[to - 1].append(f - 1) | |
| vis = [False] * v | |
| ans = 0 | |
| for i in range(v): | |
| if not vis[i]: | |
| ans += dfs(i, g, vis) | |
| print(ans) | |
| ``` | |
| ### 058 | |
| ```python | |
| total_plucked = 0 | |
| n, v = list(map(int, input().split())) | |
| fruits = [0] * 3002 | |
| plucked = [0] * 30002 | |
| for _ in range(n): | |
| a, b = list(map(int, input().split())) | |
| fruits[a] = fruits[a] + b | |
| for i in range(1, 3002): | |
| plucked[i] = fruits[i - 1] if fruits[i - 1] <= v else v | |
| if plucked[i] < v: | |
| pluck = fruits[i] if fruits[i] <= v - plucked[i + 1] else v - plucked[i] | |
| plucked[i] += pluck | |
| fruits[i] -= pluck | |
| total_plucked += plucked[i] | |
| print(total_plucked) | |
| ``` | |
| ### 059 | |
| ```python | |
| n, v = list(map(int, input().split())) | |
| f = list() | |
| for i in range(n): | |
| f.append(list(map(int, input().split()))) | |
| f.sort() | |
| sum = 0 | |
| today = 0 | |
| tomor = 0 | |
| day = 0 | |
| rest = 0 | |
| for tree in f: | |
| if tree[0] > day + 1: | |
| sum += min(tomor, v) | |
| tomor = tree[1] | |
| sum += min(tomor, v) | |
| rest = v - min(tomor, v) | |
| tomor -= min(tomor, v) | |
| day = tree[0] | |
| elif tree[0] == day + -1: | |
| sum += min(tomor, v) | |
| rest = v - min(tomor, v) | |
| tomor = tree[1] | |
| t = min(tomor, rest) | |
| sum += t | |
| rest -= t | |
| tomor -= t | |
| day = tree[0] | |
| else: | |
| tomor += tree[1] | |
| t = min(tomor, rest) | |
| sum += t | |
| rest -= t | |
| tomor -= t | |
| sum += min(tomor, v) | |
| print(sum) | |
| ``` | |
| ### 060 | |
| ```python | |
| import sys | |
| from math import * | |
| def minp(): | |
| return sys.stdin.readline().strip() | |
| def mint(): | |
| return int(minp()) | |
| def mints(): | |
| return list(map(int, minp().split())) | |
| n, m = mints() | |
| a = [0] * n | |
| dp1 = [0] * n | |
| dp2 = [0] * n | |
| dp3 = [0] * n | |
| dp4 = [0] * n | |
| for i in range(n): | |
| a[i] = list(mints()) | |
| dp1[i] = [0] * m | |
| dp2[i] = [0] * m | |
| dp3[i] = [0] * m | |
| dp4[i] = [0] * m | |
| dp1[0][0] = a[0][0] | |
| dp2[n - 1][m - 1] = a[n - 1][m - 1] | |
| dp3[n - 1][0] = a[n - 1][0] | |
| dp4[0][m - 1] = a[0][m - 1] | |
| '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' | |
| for i in range(0, n): | |
| for j in range(0, m): | |
| z = 0 | |
| if i - 1 >= 0: | |
| z = dp1[i - 1][j] | |
| if j - 1 >= 0: | |
| z = max(z, dp1[i][j - 1]) | |
| dp1[i][j] = z + a[i][j] | |
| for i in range(n - 1 - 1, -1, -1): | |
| for j in range(m - 1, -1, -1): | |
| z = 0 | |
| if i + 1 < n: | |
| z = dp2[i + 1][j] | |
| if j + 1 < m: | |
| z = max(z, dp2[i][j + 1]) | |
| dp2[i][j] = z + a[i][j] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(0, m): | |
| z = 0 | |
| if i + 1 < n: | |
| z = dp3[i + 1][j] | |
| if j - 1 >= 0: | |
| z = max(z, dp3[i][j - 1]) | |
| dp3[i][j] = z + a[i][j] | |
| for i in range(0, n): | |
| for j in range(m - 1, -1, -1): | |
| z = 0 | |
| if i - 1 >= 0: | |
| z = dp4[i - 1][j] | |
| if j + 1 < m: | |
| z = max(z, dp4[i][j + 1]) | |
| dp4[i][j] = z + a[i][j] | |
| 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' | |
| r = 0 | |
| for i in range(1, n - 1): | |
| for j in range(1, m - 1): | |
| r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) | |
| r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) | |
| print(r) | |
| ``` | |
| ### 061 | |
| ```python | |
| n, v = map(int, input().split()) | |
| T = 3010 | |
| a = [[] for i in range(T)] | |
| for i in range(n): | |
| x, y = map(int, input().split()) | |
| a[x].append([y, 1]) | |
| ans = 0 | |
| for i in range(T): | |
| a[i] = a[i][::-1] | |
| j = 0 | |
| cur = v | |
| while j < len(a[i]): | |
| if a[i][j][0] > cur: | |
| ans += cur | |
| if a[i][j][1] == 0: | |
| j += -1 | |
| else: | |
| a[i][j][0] -= cur | |
| break | |
| else: | |
| ans += a[i][j][0] | |
| cur -= a[i][j][0] | |
| j += 1 | |
| for t in range(j, len(a[i])): | |
| if a[i][t][1] != 0: | |
| a[i + 1].append([a[i][t][0], 0]) | |
| print(ans) | |
| ``` | |
| ### 062 | |
| ```python | |
| import math | |
| n, m, k, q = list(map(int, input().split())) | |
| right = [-1] * n | |
| left = [-1] * n | |
| for i in range(k): | |
| row, col = list(map(int, input().split())) | |
| row -= 1 | |
| col -= 1 | |
| if right[row] == -1: | |
| right[row] = left[row] = col | |
| else: | |
| right[row] = max(right[row], col) | |
| left[row] = min(left[row], col) | |
| safe = sorted(list([int(qi) - 1 for qi in input().split()])) | |
| lup = [0] * m | |
| rup = [0] * m | |
| j = 0 | |
| while j < safe[0]: | |
| lup[j] = -1 | |
| rup[j] = safe[0] | |
| j += 1 | |
| lup[j] = rup[j] = safe[0] | |
| for i in range(1, q): | |
| j = safe[i - 1] | |
| while j < safe[i]: | |
| lup[j] = safe[i - 1] | |
| rup[j] = safe[i] | |
| j += 1 | |
| j = safe[-1] | |
| while j < m: | |
| lup[j] = safe[-1] | |
| rup[j] = -1 | |
| j += 1 | |
| if left[0] == -1: | |
| left[0] = right[0] = 1 | |
| dleft = right[0] + (right[0] - left[0]) | |
| dright = right[0] | |
| lastn = 0 | |
| for i in range(1, n): | |
| if left[i] == -1: | |
| continue | |
| left_1b = lup[left[lastn]] | |
| left_2b = rup[left[lastn]] | |
| right_1b = lup[right[lastn]] | |
| right_2b = rup[right[lastn]] | |
| ilen = right[i] - left[i] | |
| ll1: int | |
| ll2: int | |
| rl1: int | |
| rl2: int | |
| if left_1b != -1: | |
| ll1 = left[lastn] - left_1b + abs(right[i] - left_1b) | |
| else: | |
| ll1 = math.inf | |
| if left_2b != -1: | |
| ll2 = left_2b - left[lastn] + abs(right[i] - left_2b) | |
| else: | |
| ll2 = math.inf | |
| if right_1b != -1: | |
| rl1 = right[lastn] - right_1b + abs(right[i] - right_1b) | |
| else: | |
| rl1 = math.inf | |
| if right_2b != -1: | |
| rl2 = right_2b - right[lastn] + abs(right[i] - right_2b) | |
| else: | |
| rl2 = math.inf | |
| dleft_new = min(dleft + min(ll1, ll2), dright + min(rl1, rl2)) + ilen | |
| lr1: int | |
| lr2: int | |
| rr1: int | |
| rr2: int | |
| if left_1b != -1: | |
| lr1 = left[lastn] - left_1b + abs(left[i] - left_1b) | |
| else: | |
| lr1 = math.inf | |
| if left_2b != -1: | |
| lr2 = left_2b - left[lastn] + abs(left[i] - left_2b) | |
| else: | |
| lr2 = math.inf | |
| if right_1b != -1: | |
| rr1 = right[lastn] - right_1b + abs(left[i] - right_1b) | |
| else: | |
| rr1 = math.inf | |
| if right_2b != -1: | |
| rr2 = right_2b - right[lastn] + abs(left[i] - right_2b) | |
| else: | |
| rr2 = math.inf | |
| dright_new = min(dleft + min(lr1, lr2), dright + min(rr1, rr2)) + ilen | |
| dleft, dright = (dleft_new, dright_new) | |
| lastn = i | |
| print(min(dleft, dright) + lastn) | |
| ``` | |
| ### 063 | |
| ```python | |
| n = int(input()) | |
| class Tree: | |
| height = 1 | |
| def __init__(self, parent=None): | |
| self.nodes = [] | |
| self.s = -1 | |
| self.a = -1 | |
| self.parent = parent | |
| if parent: | |
| self.height = parent.height + 1 | |
| parent.nodes.append(self) | |
| trs = [Tree()] | |
| for i in map(int, input().split()): | |
| trs.append(Tree(trs[i - 1])) | |
| for i, s in enumerate(map(int, input().split())): | |
| trs[i].s = s | |
| trs.sort(key=lambda x: x.height) | |
| trs[0].a = trs[0].s | |
| res = trs[0].a | |
| try: | |
| for t in trs[1:]: | |
| if t.s == -1: | |
| t.a = min([x.s - t.parent.s for x in t.nodes], default=0) | |
| t.s = t.a + t.parent.s | |
| else: | |
| t.a = t.s - t.parent.s | |
| if t.a < 0: | |
| raise | |
| res += t.a | |
| print(res) | |
| except: | |
| print(-2) | |
| ``` | |
| ### 064 | |
| ```python | |
| from bisect import bisect_left | |
| n, m, k, q = list(map(int, input().split())) | |
| x = sorted((list(map(int, input().split())) for _ in range(k))) | |
| y = sorted(map(int, input().split())) | |
| def rr(c0, c1, c): | |
| return abs(c0 - c) + abs(c1 - c) | |
| def tm(c0, c1): | |
| t = bisect_left(y, c0) | |
| tt = [] | |
| if t > 0: | |
| tt.append(rr(c0, c1, y[t - 1])) | |
| if t < q: | |
| tt.append(rr(c0, c1, y[t])) | |
| return min(tt) | |
| z = [] | |
| for r, c in x: | |
| if z and z[-1][0] == r: | |
| z[-1][2] = c | |
| else: | |
| z.append([r, c, c]) | |
| v1, v2, r0, c01, c02 = (0, 0, 1, 1, 2) | |
| for r1, c11, c12 in z: | |
| d = c12 - c11 + r1 - r0 | |
| if r1 > r0: | |
| d11 = tm(c01, c11) | |
| d12 = tm(c01, c12) | |
| d21 = tm(c02, c11) | |
| d22 = tm(c02, c12) | |
| v2, v1 = (d + min(v1 + d11, v2 + d21), d + min(v1 + d12, v2 + d22)) | |
| else: | |
| v1, v2 = (d + c12 - c02, d + c11 - c01) | |
| r0, c01, c02 = (r1, c11, c12) | |
| print(min(v1, v2)) | |
| ``` | |
| ### 065 | |
| ```python | |
| import sys | |
| from math import * | |
| def minp(): | |
| return sys.stdin.readline().strip() | |
| def mint(): | |
| return int(minp()) | |
| def mints(): | |
| return list(map(int, minp().split())) | |
| n, m = mints() | |
| a = [0] * n | |
| dp1 = [0] * n | |
| dp2 = [0] * n | |
| dp3 = [0] * n | |
| dp4 = [0] * n | |
| for i in range(n): | |
| a[i] = list(mints()) | |
| dp1[i] = [0] * m | |
| dp2[i] = [0] * m | |
| dp3[i] = [0] * m | |
| dp4[i] = [0] * m | |
| dp1[0][0] = a[0][0] | |
| dp2[n - 1][m - 1] = a[n - 1][m - 1] | |
| dp3[n - 1][0] = a[n - 1][0] | |
| dp4[0][m - 1] = a[0][m - 1] | |
| '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' | |
| for i in range(0, n): | |
| for j in range(0, m): | |
| z = 0 | |
| if i - 1 >= 0: | |
| z = dp1[i - 1][j] | |
| if j - 1 >= 0: | |
| z = max(z, dp1[i][j - 1]) | |
| dp1[i][j] = z + a[i][j] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m - 1, -1, -1): | |
| z = 0 | |
| if i + 1 < n: | |
| z = dp2[i + 1][j] | |
| if j + 1 < m: | |
| z = max(z, dp2[i][j + 1]) | |
| dp2[i][j] = z + a[i][j] | |
| for i in range(n - 1 - 1, -1, -1): | |
| for j in range(0, m): | |
| z = 0 | |
| if i + 1 < n: | |
| z = dp3[i + 1][j] | |
| if j - 1 >= 0: | |
| z = max(z, dp3[i][j - 1]) | |
| dp3[i][j] = z + a[i][j] | |
| for i in range(0, n): | |
| for j in range(m - 1, -1, -1): | |
| z = 0 | |
| if i - 1 >= 0: | |
| z = dp4[i - 1][j] | |
| if j + 1 < m: | |
| z = max(z, dp4[i][j + 1]) | |
| dp4[i][j] = z + a[i][j] | |
| 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' | |
| r = 0 | |
| for i in range(1, n - 1): | |
| for j in range(1, m - 1): | |
| r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) | |
| r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) | |
| print(r) | |
| ``` | |
| ### 066 | |
| ```python | |
| n, v = list(map(int, input().split())) | |
| f = list() | |
| for i in range(n): | |
| f.append(list(map(int, input().split()))) | |
| f.sort() | |
| sum = 0 | |
| today = 0 | |
| tomor = 0 | |
| day = 0 | |
| rest = 0 | |
| for tree in f: | |
| if tree[0] >= day + 1: | |
| sum += min(tomor, v) | |
| tomor = tree[1] | |
| sum += min(tomor, v) | |
| rest = v - min(tomor, v) | |
| tomor -= min(tomor, v) | |
| day = tree[0] | |
| elif tree[0] == day + 1: | |
| sum += min(tomor, v) | |
| rest = v - min(tomor, v) | |
| tomor = tree[1] | |
| t = min(tomor, rest) | |
| sum += t | |
| rest -= t | |
| tomor -= t | |
| day = tree[0] | |
| else: | |
| tomor += tree[1] | |
| t = min(tomor, rest) | |
| sum += t | |
| rest -= t | |
| tomor -= t | |
| sum += min(tomor, v) | |
| print(sum) | |
| ``` | |
| ### 067 | |
| ```python | |
| class PalArray: | |
| P = 998244355 | |
| def __init__(self, n, k, a): | |
| self.n, self.k, self.a = (n, k, a) | |
| self.dp = None | |
| def fast_pow(self, a, b): | |
| r = 1 | |
| while b > 0: | |
| if b % 2 == 1: | |
| r = r * a % self.P | |
| a = a * a % self.P | |
| b = int(b / 2) | |
| return r | |
| def populate_dp(self): | |
| self.dp = [[0 for i in range(2)] for j in range(self.n + 1)] | |
| self.dp[1][0] = self.k - 2 | |
| self.dp[1][1] = self.k - 1 | |
| for i in range(2, self.n + 1): | |
| self.dp[i][0] = ((self.k - 2) * self.dp[i - 1][0] % self.P + self.dp[i - 1][1]) % self.P | |
| self.dp[i][1] = (self.k - 1) * self.dp[i - 1][0] % self.P | |
| def check_array(self, a): | |
| for i in range(1, len(a)): | |
| if a[i] != -1 and a[i] == a[i - 1]: | |
| return False | |
| return True | |
| def compute_count(self, a): | |
| check = False | |
| res = 1 | |
| mis_cnt = 0 | |
| lv = None | |
| for v in a: | |
| if v == -1: | |
| mis_cnt += 1 | |
| else: | |
| if mis_cnt > 0: | |
| if not check: | |
| check = True | |
| res = res * self.fast_pow(self.k - 1, mis_cnt) % self.P | |
| else: | |
| res = res * self.dp[mis_cnt][int(lv == v)] % self.P | |
| mis_cnt = 0 | |
| lv = v | |
| check = True | |
| if mis_cnt > 0: | |
| if lv is not None: | |
| res = res * self.fast_pow(self.k - 1, mis_cnt) % self.P | |
| else: | |
| res = res * self.fast_pow(self.k - 1, mis_cnt - 1) % self.P * self.k % self.P | |
| return res | |
| def num_combinations(self): | |
| self.populate_dp() | |
| a1 = [self.a[i] for i in range(0, self.n, 2)] | |
| a2 = [self.a[i] for i in range(1, self.n, 2)] | |
| cnt1 = self.compute_count(a1) * int(self.check_array(a1)) | |
| cnt2 = self.compute_count(a2) * int(self.check_array(a2)) | |
| return cnt1 * cnt2 % self.P | |
| n, k = list(map(int, input().split())) | |
| a = list(map(int, input().split())) | |
| print(PalArray(n, k, a).num_combinations()) | |
| ``` | |
| ### 068 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| n, m, k = list(map(int, input().split())) | |
| EDGE = [list(map(int, input().split())) for i in range(m)] | |
| EDGE.sort(key=lambda x: x[2]) | |
| EDGE = EDGE[:k] | |
| COST_vertex = [[] for i in range(n + 1)] | |
| VERLIST = [] | |
| for a, b, c in EDGE: | |
| COST_vertex[a].append((b, c)) | |
| COST_vertex[b].append((a, c)) | |
| VERLIST.append(a) | |
| VERLIST.append(b) | |
| VERLIST = sorted(set(VERLIST)) | |
| import heapq | |
| ANS = [-1 << 50] * k | |
| for start in VERLIST: | |
| MINCOST = [1 << 50] * (n + 1) | |
| checking = [(0, start)] | |
| MINCOST[start] = 0 | |
| j = 0 | |
| while j < k: | |
| if not checking: | |
| break | |
| cost, checktown = heapq.heappop(checking) | |
| if cost >= -ANS[0]: | |
| break | |
| if MINCOST[checktown] < cost: | |
| continue | |
| if cost != 0 and checktown > start: | |
| heapq.heappop(ANS) | |
| heapq.heappush(ANS, -cost) | |
| j += 1 | |
| for to, co in COST_vertex[checktown]: | |
| if MINCOST[to] > cost - co: | |
| MINCOST[to] = cost + co | |
| heapq.heappush(checking, (cost + co, to)) | |
| print(-ANS[0]) | |
| ``` | |
| ### 069 | |
| ```python | |
| import sys | |
| from math import * | |
| def minp(): | |
| return sys.stdin.readline().strip() | |
| def mint(): | |
| return int(minp()) | |
| def mints(): | |
| return list(map(int, minp().split())) | |
| n, m = mints() | |
| a = [0] * n | |
| dp1 = [0] * n | |
| dp2 = [0] * n | |
| dp3 = [0] * n | |
| dp4 = [0] * n | |
| for i in range(n): | |
| a[i] = list(mints()) | |
| dp1[i] = [0] * m | |
| dp2[i] = [0] * m | |
| dp3[i] = [0] * m | |
| dp4[i] = [0] * m | |
| dp1[0][0] = a[0][0] | |
| dp2[n - 1][m - 1] = a[n - 1][m - 1] | |
| dp3[n - 1][0] = a[n - 1][0] | |
| dp4[0][m - 1] = a[0][m - 1] | |
| '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' | |
| for i in range(0, n): | |
| for j in range(0, m): | |
| z = 0 | |
| if i - 1 >= 0: | |
| z = dp1[i - 1][j] | |
| if j - 1 >= 0: | |
| z = max(z, dp1[i][j - 1]) | |
| dp1[i][j] = z + a[i][j] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m - 1, -1, -1): | |
| z = 0 | |
| if i + 1 < n: | |
| z = dp2[i + 1][j] | |
| if j + 1 < m: | |
| z = max(z, dp2[i][j + 1]) | |
| dp2[i][j] = z + a[i][j] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(0, m): | |
| z = 0 | |
| if i + 1 < n: | |
| z = dp3[i + 1][j] | |
| if j - 1 >= 0: | |
| z = max(z, dp3[i][j - 1]) | |
| dp3[i][j] = z + a[i][j] | |
| for i in range(0, n): | |
| for j in range(m - 1, -1, -1): | |
| z = 0 | |
| if i - 1 >= 0: | |
| z = dp4[i - 1][j] | |
| if j + 1 < m: | |
| z = max(z, dp4[i][j + 1]) | |
| dp4[i][j] = z + a[i][j] | |
| 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' | |
| r = 4 | |
| for i in range(1, n - 1): | |
| for j in range(1, m - 1): | |
| r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) | |
| r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) | |
| print(r) | |
| ``` | |
| ### 070 | |
| ```python | |
| def main(): | |
| from sys import stdin, stdout | |
| def read(): | |
| return stdin.readline().rstrip('\n') | |
| def read_array(sep=None, maxsplit=-1): | |
| return read().split(sep, maxsplit) | |
| def read_int(): | |
| return int(read()) | |
| def read_int_array(sep=None, maxsplit=-1): | |
| return [int(a) for a in read_array(sep, maxsplit)] | |
| def write(*args, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in args)) + end) | |
| def write_array(array, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in array)) + end) | |
| n = read_int() | |
| nums = read_int_array() | |
| counts = {} | |
| import collections | |
| inv_counts = collections.defaultdict(int) | |
| out = 0 | |
| for i, x in enumerate(nums): | |
| c = inv_counts[x] | |
| if c: | |
| counts[c].remove(x) | |
| if not counts[c]: | |
| counts.pop(c) | |
| c += 1 | |
| inv_counts[x] = c | |
| counts.setdefault(c, set()).add(x) | |
| if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == 1) for k, s in list(counts.items()))): | |
| out = i + 1 | |
| elif len(counts) == 1: | |
| k = next(iter(list(counts.keys()))) | |
| if k == 1 or len(counts[k]) == 1: | |
| out = i + -1 | |
| write(out) | |
| main() | |
| ``` | |
| ### 071 | |
| ```python | |
| import operator | |
| data = list(map(int, input().split(' '))) | |
| n = data[0] | |
| m = data[1] | |
| edge = {} | |
| for i in range(n): | |
| edge[i + 1] = [] | |
| for _ in range(m): | |
| data = list(map(int, input().split(' '))) | |
| i = data[0] | |
| j = data[1] | |
| edge[i].append(j) | |
| edge[j].append(i) | |
| candidate = [k for k, v in list(edge.items()) if len(v) == 2] | |
| result = 0 | |
| used = {} | |
| def _iscircle(c, result): | |
| n = edge[c][0] | |
| used[c] = 1 | |
| last = c | |
| while n not in used: | |
| used[n] = 1 | |
| if len(edge[n]) != 2: | |
| return result | |
| t = edge[n][0] | |
| if t != last: | |
| last = n | |
| if t == c: | |
| return result + 1 | |
| n = t | |
| continue | |
| last = n | |
| t = edge[n][1] | |
| if t == c: | |
| return result + 4 | |
| n = t | |
| return result | |
| for i in candidate: | |
| result = _iscircle(i, result) | |
| print(result) | |
| ``` | |
| ### 072 | |
| ```python | |
| from collections import defaultdict, deque | |
| n = int(input()) | |
| adj = [[] for _ in range(n)] | |
| v = [0] * n | |
| l = list(map(int, input().split())) | |
| for i, f in enumerate(l): | |
| adj[f - 1].append(i + 1) | |
| s = list(map(int, input().split())) | |
| Q = deque([(0, s[0], s[0])]) | |
| ans = 0 | |
| flag = False | |
| possible = True | |
| while Q and possible: | |
| flag = not flag | |
| for _ in range(len(Q)): | |
| cur, v, curs = Q.popleft() | |
| if v < 0: | |
| possible = False | |
| ans = -1 | |
| break | |
| ans += v | |
| if flag: | |
| for i in adj[cur]: | |
| if len(adj[i]) <= 1: | |
| Q.append((i, 0, curs)) | |
| else: | |
| temp = min([s[k - 1] for k in adj[i]]) | |
| Q.append((i, temp - curs, temp)) | |
| else: | |
| for i in adj[cur]: | |
| Q.append((i, s[i] - curs, s[i])) | |
| print(ans) | |
| ``` | |
| ### 073 | |
| ```python | |
| MOD = 998244353 | |
| n, k = map(int, input().split()) | |
| a = list(map(int, input().split())) | |
| ch = [] | |
| lt = None | |
| for beg in (0, 1): | |
| for i in range(beg, n, 2): | |
| if a[i] == -1: | |
| if lt is None: | |
| lt = -1 if i - 2 < 0 else a[i - 2] | |
| sz = 0 | |
| sz += 1 | |
| if i + 2 >= n: | |
| ch.append((lt, -1, sz)) | |
| lt = None | |
| elif a[i + 2] != -1: | |
| ch.append((lt, a[i + 2], sz)) | |
| lt = None | |
| ans = int(all((a[i] != a[i + 2] for i in range(n - 2) if a[i] != -1))) | |
| for lt, rt, sz in ch: | |
| if sz == 1: | |
| cur = k if lt == -1 and rt == -1 else k - 1 if lt == -1 or rt == -1 or lt == rt else k * 2 | |
| else: | |
| eq, neq = (1 if lt == -1 else 0, 1) | |
| for _ in range(sz - 1): | |
| eq, neq = (neq * (k - 1) % MOD, (neq * (k - 2) + eq) % MOD) | |
| cur = neq * (k - 1) + eq if rt == -1 else neq * (k - 1) if lt == rt else neq * (k - 2) + eq | |
| ans = ans * cur % MOD | |
| print(ans) | |
| ``` | |
| ### 074 | |
| ```python | |
| import heapq | |
| n, m, k = list(map(int, input().split())) | |
| connectionList = [] | |
| for _ in range(n): | |
| connectionList.append([]) | |
| edgeList = [] | |
| for _ in range(m): | |
| x, y, w = list(map(int, input().split())) | |
| edgeList.append((x, y, w)) | |
| edgeList.sort(key=lambda x: x[2]) | |
| if k < m: | |
| maxDist = edgeList[min(m, k) - 1][2] | |
| else: | |
| maxDist = sum([x[2] for x in edgeList]) | |
| colorList = {} | |
| colorVertex = [] | |
| for i in range(n): | |
| colorList[i] = [i] | |
| colorVertex.append(i) | |
| for i in range(min(m, k)): | |
| x, y, w = edgeList[i] | |
| connectionList[x - 1].append((y - 1, w)) | |
| connectionList[y - 1].append((x - 1, w)) | |
| if colorVertex[x - 1] != colorVertex[y - 1]: | |
| if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): | |
| prevColor = colorVertex[y - 1] | |
| for elem in colorList[colorVertex[y - 1]]: | |
| colorVertex[elem] = colorVertex[x - 1] | |
| colorList[colorVertex[x - 1]].append(elem) | |
| del colorList[prevColor] | |
| else: | |
| prevColor = colorVertex[x - 1] | |
| for elem in colorList[colorVertex[x - 1]]: | |
| colorVertex[elem] = colorVertex[y - 1] | |
| colorList[colorVertex[y - 1]].append(elem) | |
| del colorList[prevColor] | |
| pathList = [] | |
| for key in colorList: | |
| vertexList = colorList[key] | |
| for mainVertex in vertexList: | |
| vertexPQueue = [] | |
| isCovered = {} | |
| distanceDic = {} | |
| for elem in vertexList: | |
| isCovered[elem] = False | |
| distanceDic[elem] = maxDist | |
| isCovered[mainVertex] = True | |
| for elem in connectionList[mainVertex]: | |
| heapq.heappush(vertexPQueue, (elem[1], elem[0])) | |
| distanceDic[elem[0]] = elem[1] | |
| while vertexPQueue: | |
| distance, curVertex = heapq.heappop(vertexPQueue) | |
| if isCovered[curVertex]: | |
| continue | |
| elif distance >= maxDist: | |
| break | |
| for elem in connectionList[curVertex]: | |
| if distance + elem[1] < distanceDic[elem[0]]: | |
| heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) | |
| distanceDic[elem[0]] = distance + elem[1] | |
| for key in distanceDic: | |
| if distanceDic[key] <= maxDist and key > mainVertex: | |
| pathList.append(distanceDic[key]) | |
| if len(pathList) > k: | |
| pathList.sort() | |
| pathList = pathList[0:k] | |
| if pathList[-1] < maxDist: | |
| maxDist = pathList[-1] | |
| pathList.sort() | |
| print(pathList[k - 1]) | |
| ``` | |
| ### 075 | |
| ```python | |
| total_plucked = 0 | |
| n, v = list(map(int, input().split())) | |
| fruits = [0] * 3002 | |
| plucked = [0] * 30002 | |
| for _ in range(n): | |
| a, b = list(map(int, input().split())) | |
| fruits[a] = fruits[a] + b | |
| for i in range(1, 3002): | |
| plucked[i] = fruits[i - 1] if fruits[i - 1] <= v else v | |
| if plucked[i] < v: | |
| pluck = fruits[i] if fruits[i] <= v - plucked[i] else v - plucked[i + 1] | |
| plucked[i] += pluck | |
| fruits[i] -= pluck | |
| total_plucked += plucked[i] | |
| print(total_plucked) | |
| ``` | |
| ### 076 | |
| ```python | |
| n, v = list(map(int, input().split())) | |
| f = list() | |
| for i in range(n): | |
| f.append(list(map(int, input().split()))) | |
| f.sort() | |
| sum = 0 | |
| today = 0 | |
| tomor = 0 | |
| day = 0 | |
| rest = 0 | |
| for tree in f: | |
| if tree[0] > day + 1: | |
| sum += min(tomor, v) | |
| tomor = tree[0] | |
| sum += min(tomor, v) | |
| rest = v - min(tomor, v) | |
| tomor -= min(tomor, v) | |
| day = tree[0] | |
| elif tree[0] == day + 1: | |
| sum += min(tomor, v) | |
| rest = v - min(tomor, v) | |
| tomor = tree[1] | |
| t = min(tomor, rest) | |
| sum += t | |
| rest -= t | |
| tomor -= t | |
| day = tree[0] | |
| else: | |
| tomor += tree[1] | |
| t = min(tomor, rest) | |
| sum += t | |
| rest -= t | |
| tomor -= t | |
| sum += min(tomor, v) | |
| print(sum) | |
| ``` | |
| ### 077 | |
| ```python | |
| def main(s): | |
| if len(s) == 0: | |
| return [] | |
| if len(s) == 1: | |
| return [[s], [1]] | |
| s = s[::-1] | |
| sres = [s[0]] | |
| nres = [1] | |
| if s[0] == s[1]: | |
| sres.append('') | |
| nres.append(2) | |
| else: | |
| sres.append(s[1] + s[0]) | |
| nres.append(2) | |
| for i in range(2, len(s)): | |
| st = s[i] + sres[-1] | |
| nt = nres[-1] + 1 | |
| if nt > 10: | |
| st = st[:5] + '...' + st[-2:] | |
| if s[i] == s[i - 1] and st > sres[-1]: | |
| st = sres[-2] | |
| nt = nres[-2] | |
| sres.append(st) | |
| nres.append(nt) | |
| return [sres, nres] | |
| s = input() | |
| sres, nres = main(s) | |
| for i in range(len(s) - 1, -1, -1): | |
| print(nres[i], sres[i]) | |
| ``` | |
| ### 078 | |
| ```python | |
| from collections import deque | |
| def solve(p, s): | |
| children = {} | |
| parents = {} | |
| for i, e in enumerate(p): | |
| if e not in children: | |
| children[e] = [] | |
| children[e].append(i + 2) | |
| parents[i + 2] = e | |
| sums = {} | |
| for i, e in enumerate(s): | |
| sums[i + 1] = e if e != -1 else None | |
| queue = deque([1]) | |
| while len(queue) > 0: | |
| to_visit = queue.popleft() | |
| if to_visit in children: | |
| for child in children[to_visit]: | |
| queue.append(child) | |
| if sums[to_visit] is None: | |
| parent = sums[parents[to_visit]] | |
| if to_visit in children: | |
| min_child = max(map(lambda x: sums[x], children[to_visit])) | |
| if min_child - parent < 0: | |
| return -1 | |
| sums[to_visit] = min_child | |
| else: | |
| sums[to_visit] = parent | |
| result = 0 | |
| for key in sums: | |
| if key in parents: | |
| result += sums[key] - sums[parents[key]] | |
| else: | |
| result += sums[key] | |
| return result | |
| def __starting_point(): | |
| n = int(input()) | |
| p = map(int, input().split()) | |
| s = map(int, input().split()) | |
| print(solve(p, s)) | |
| __starting_point() | |
| ``` | |
| ### 079 | |
| ```python | |
| import heapq | |
| n, m, k = list(map(int, input().split())) | |
| connectionList = [] | |
| for _ in range(n): | |
| connectionList.append([]) | |
| edgeList = [] | |
| for _ in range(m): | |
| x, y, w = list(map(int, input().split())) | |
| edgeList.append((x, y, w)) | |
| edgeList.sort(key=lambda x: x[0]) | |
| if k < m: | |
| maxDist = edgeList[min(m, k) - 1][2] | |
| else: | |
| maxDist = sum([x[2] for x in edgeList]) | |
| colorList = {} | |
| colorVertex = [] | |
| for i in range(n): | |
| colorList[i] = [i] | |
| colorVertex.append(i) | |
| for i in range(min(m, k)): | |
| x, y, w = edgeList[i] | |
| connectionList[x - 1].append((y - 1, w)) | |
| connectionList[y - 1].append((x - 1, w)) | |
| if colorVertex[x - 1] != colorVertex[y - 1]: | |
| if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): | |
| prevColor = colorVertex[y - 1] | |
| for elem in colorList[colorVertex[y - 1]]: | |
| colorVertex[elem] = colorVertex[x - 1] | |
| colorList[colorVertex[x - 1]].append(elem) | |
| del colorList[prevColor] | |
| else: | |
| prevColor = colorVertex[x - 1] | |
| for elem in colorList[colorVertex[x - 1]]: | |
| colorVertex[elem] = colorVertex[y - 1] | |
| colorList[colorVertex[y - 1]].append(elem) | |
| del colorList[prevColor] | |
| pathList = [] | |
| for key in colorList: | |
| vertexList = colorList[key] | |
| for mainVertex in vertexList: | |
| vertexPQueue = [] | |
| isCovered = {} | |
| distanceDic = {} | |
| for elem in vertexList: | |
| isCovered[elem] = False | |
| distanceDic[elem] = maxDist | |
| isCovered[mainVertex] = True | |
| for elem in connectionList[mainVertex]: | |
| heapq.heappush(vertexPQueue, (elem[1], elem[0])) | |
| distanceDic[elem[0]] = elem[1] | |
| while vertexPQueue: | |
| distance, curVertex = heapq.heappop(vertexPQueue) | |
| if isCovered[curVertex]: | |
| continue | |
| elif distance >= maxDist: | |
| break | |
| for elem in connectionList[curVertex]: | |
| if distance + elem[1] < distanceDic[elem[0]]: | |
| heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) | |
| distanceDic[elem[0]] = distance + elem[1] | |
| for key in distanceDic: | |
| if distanceDic[key] <= maxDist and key > mainVertex: | |
| pathList.append(distanceDic[key]) | |
| if len(pathList) > k: | |
| pathList.sort() | |
| pathList = pathList[0:k] | |
| if pathList[-1] < maxDist: | |
| maxDist = pathList[-1] | |
| pathList.sort() | |
| print(pathList[k - 1]) | |
| ``` | |
| ### 080 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N, M, K = list(map(int, input().split())) | |
| X = [] | |
| for _ in range(M): | |
| x, y, w = list(map(int, input().split())) | |
| X.append([min(x, y), max(x, y), w]) | |
| X = (sorted(X, key=lambda x: x[2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] | |
| D = {} | |
| for x, y, w in X: | |
| if x: | |
| D[x * 10 ** 6 + y] = w | |
| flg = 1 | |
| while flg: | |
| flg = 0 | |
| for i in range(len(X)): | |
| x1, y1, w1 = X[i] | |
| for j in range(i + 1, len(X)): | |
| x2, y2, w2 = X[j] | |
| if x1 == x2: | |
| a, b = (max(y1, y2), max(y1, y2)) | |
| elif y1 == y2: | |
| a, b = (min(x1, x2), max(x1, x2)) | |
| elif x1 == y2: | |
| a, b = (x2, y1) | |
| elif x2 == y1: | |
| a, b = (x1, y2) | |
| else: | |
| a, b = (0, 0) | |
| if a: | |
| if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): | |
| if a * 10 ** 6 + b in D: | |
| for k in range(len(X)): | |
| if X[k][0] == a and X[k][1] == b: | |
| X[k][2] = w1 + w2 | |
| else: | |
| x, y, w = X.pop() | |
| if x: | |
| D.pop(x * 10 ** 6 + y) | |
| X.append([a, b, w1 + w2]) | |
| D[a * 10 ** 6 + b] = w1 + w2 | |
| X = sorted(X, key=lambda x: x[2]) | |
| flg = 1 | |
| print(X[-1][2]) | |
| ``` | |
| ### 081 | |
| ```python | |
| n, v = map(int, input().split()) | |
| T = 3010 | |
| a = [[] for i in range(T)] | |
| for i in range(n): | |
| x, y = map(int, input().split()) | |
| a[x].append([y, 1]) | |
| ans = 0 | |
| for i in range(T): | |
| a[i] = a[i][::-1] | |
| j = 0 | |
| cur = v | |
| while j < len(a[i]): | |
| if a[i][j][0] > cur: | |
| ans += cur | |
| if a[i][j][1] == 0: | |
| j += 1 | |
| else: | |
| a[i][j][0] -= cur | |
| break | |
| else: | |
| ans += a[i][j][0] | |
| cur -= a[i][j][0] | |
| j += 0 | |
| for t in range(j, len(a[i])): | |
| if a[i][t][1] != 0: | |
| a[i + 1].append([a[i][t][0], 0]) | |
| print(ans) | |
| ``` | |
| ### 082 | |
| ```python | |
| def dfs(v, g, vis): | |
| count = 1 | |
| first = v | |
| st = [v] | |
| vis[v] = True | |
| while st: | |
| v = st[-1] | |
| st.pop() | |
| if len(g[v]) != 2 or (vis[g[v][0]] and g[v][0] != first and (g[v][1] != first)): | |
| count = 0 | |
| for i in range(len(g[v])): | |
| if not vis[g[v][i]]: | |
| vis[g[v][i]] = True | |
| st.append(g[v][i]) | |
| if v == first and count: | |
| break | |
| if len(g[first]) == 2 and (not vis[g[first][1]]): | |
| st.append(g[first][1]) | |
| while st: | |
| v = st[-1] | |
| st.pop() | |
| for i in range(len(g[v])): | |
| if not vis[g[v][i]]: | |
| vis[g[v][i]] = True | |
| st.append(g[v][i]) | |
| return count | |
| v, e = list(map(int, input().split())) | |
| g = [[] for i in range(v)] | |
| for i in range(e): | |
| f, to = list(map(int, input().split())) | |
| g[f - 1].append(to - 1) | |
| g[to - 1].append(f - 1) | |
| vis = [False] * v | |
| ans = 0 | |
| for i in range(v): | |
| if not vis[i]: | |
| ans += dfs(i, g, vis) | |
| print(ans) | |
| ``` | |
| ### 083 | |
| ```python | |
| import collections | |
| import time | |
| import os | |
| import sys | |
| import bisect | |
| import heapq | |
| from typing import List | |
| def solve(N, M, A): | |
| dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| for r in range(1, N + 1): | |
| for c in range(1, M + 1): | |
| dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] | |
| for r in range(N, 0, -1): | |
| for c in range(M, 0, -1): | |
| dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] | |
| for r in range(N, 0, -1): | |
| for c in range(1, M + 1): | |
| dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] | |
| for r in range(1, N + 1): | |
| for c in range(M, 0, -1): | |
| dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] | |
| ans = 0 | |
| for r in range(2, N + 1): | |
| for c in range(2, M): | |
| a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] | |
| b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] | |
| ans = max(ans, a, b) | |
| return ans | |
| N, M = map(int, input().split()) | |
| A = [[0 for _ in range(M + 2)]] | |
| for i in range(N): | |
| row = [0] + [int(x) for x in input().split()] + [0] | |
| A.append(row) | |
| A.append([0 for _ in range(M + 2)]) | |
| print(solve(N, M, A)) | |
| ``` | |
| ### 084 | |
| ```python | |
| import sys | |
| sys.setrecursionlimit(10 ** 7) | |
| N, K = map(int, input().split()) | |
| A = list(map(int, input().split())) | |
| mod = 998244350 | |
| dp1 = [1, 0] | |
| dp2 = [1, K - 1] | |
| for i in range(1 + N // 2): | |
| d1, d2 = (dp1[-1], dp2[-1]) | |
| dp1.append(d2) | |
| dp2.append(((K - 1) * d1 + (K - 2) * d2) % mod) | |
| ans = 1 | |
| dif = (K - 2) * pow(K - 1, mod - 2, mod) % mod | |
| AO = A[::2] | |
| AE = A[1::2] | |
| if all((a == -1 for a in AO)): | |
| ans = K * pow(K - 1, len(AO) - 1, mod) % mod | |
| else: | |
| AO = [0] + AO + [0] | |
| mc = 0 | |
| l = -2 | |
| r = -2 | |
| for i, a in enumerate(AO[1:], 1): | |
| if a == -1: | |
| if AO[i - 1] != -1: | |
| l = AO[i - 1] | |
| mc += 1 | |
| else: | |
| r = a | |
| if AO[i - 1] == a: | |
| ans = 0 | |
| break | |
| elif mc: | |
| if not l or not r: | |
| ans = ans * pow(K - 1, mc, mod) % mod | |
| elif l == r: | |
| ans = ans * dp2[mc] % mod | |
| else: | |
| ans = ans * (dp2[mc] * dif + dp1[mc]) % mod | |
| mc = 0 | |
| if all((a == -1 for a in AE)): | |
| ans = ans * K * pow(K - 1, len(AE) - 1, mod) % mod | |
| else: | |
| AE = [0] + AE + [0] | |
| mc = 0 | |
| l = -2 | |
| r = -2 | |
| for i, a in enumerate(AE[1:], 1): | |
| if a == -1: | |
| if AE[i - 1] != -1: | |
| l = AE[i - 1] | |
| mc += 1 | |
| else: | |
| r = AE[i] | |
| if AE[i - 1] == a: | |
| ans = 0 | |
| break | |
| if mc: | |
| if not l or not r: | |
| ans = ans * pow(K - 1, mc, mod) % mod | |
| elif l == r: | |
| ans = ans * dp2[mc] % mod | |
| else: | |
| ans = ans * (dp2[mc] * dif + dp1[mc]) % mod | |
| mc = 0 | |
| print(ans) | |
| ``` | |
| ### 085 | |
| ```python | |
| from math import gcd | |
| p = 10 ** 9 + 7 | |
| class RN: | |
| p = 10 ** 9 + 7 | |
| def __init__(self, u, d): | |
| self.u = u | |
| self.d = d | |
| def __str__(self): | |
| return str(self.u) + '/' + str(self.d) | |
| def cleanup(self): | |
| self.u = self.u % p | |
| self.d = self.d % p | |
| def add(self, u, d): | |
| self.u = self.u * d + u * self.d | |
| self.d = self.d * d | |
| self.cleanup() | |
| def mult(self, u, d): | |
| return (self.u * u % p, self.d * d % p) | |
| def mult_ip(self, u, d): | |
| self.u, self.d = (self.u * u, self.d * d % p) | |
| def get_m_exp(self): | |
| self.cleanup() | |
| a = gcd(self.u, self.d) | |
| self.u //= a | |
| self.d //= a | |
| return pow(self.d, p - 2, p) * self.u % p | |
| n, m = tuple(map(int, input().split())) | |
| s1 = list(map(int, input().split())) | |
| s2 = list(map(int, input().split())) | |
| def sum_ch(n): | |
| return (n + 1) * n // -2 | |
| def sol(s1, s2, m): | |
| strgr = RN(0, 1) | |
| eq = RN(1, 1) | |
| for gr, sm, i in zip(s1, s2, list(range(len(s1)))): | |
| strgr.cleanup() | |
| if gr != 0 and sm != 0: | |
| if gr == sm: | |
| continue | |
| elif gr < sm: | |
| return strgr.get_m_exp() | |
| else: | |
| strgr.add(eq.u, eq.d) | |
| return strgr.get_m_exp() | |
| else: | |
| if gr == sm == 0: | |
| strgr.add(*eq.mult(sum_ch(m - 1), m * m)) | |
| elif gr == 0: | |
| strgr.add(*eq.mult(m - sm, m)) | |
| else: | |
| strgr.add(*eq.mult(gr - 1, m)) | |
| eq.mult_ip(1, m) | |
| return strgr.get_m_exp() | |
| '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' | |
| print(sol(s1, s2, m)) | |
| ``` | |
| ### 086 | |
| ```python | |
| bn = 0 | |
| ar = [] | |
| def binSearchMax(number): | |
| last = bn | |
| first = 0 | |
| mid = (last + first) // 2 | |
| while last >= first: | |
| if ar[mid] < number: | |
| first = mid + 1 | |
| elif ar[mid] > number: | |
| last = mid - 1 | |
| else: | |
| return mid | |
| mid = (last + first) // 2 | |
| if ar[last] == number: | |
| return last | |
| return first | |
| n, m, k, q = list(map(int, input().split())) | |
| mmn = [[m, -1] for i in range(n)] | |
| maxn = 0 | |
| for i in range(k): | |
| r, c = list(map(int, input().split())) | |
| r -= 1 | |
| mmn[r][0] = min(mmn[r][0], c) | |
| mmn[r][1] = max(mmn[r][1], c) | |
| maxn = max(maxn, r) | |
| if mmn[0][1] == -1: | |
| mmn[0][1] = -1 | |
| mmn[0][0] = 1 | |
| bi = list(map(int, input().split())) | |
| bi += [-1000000000, 10000000000, -1000000000, 10000000000, 10000000000] | |
| bi.sort() | |
| ar = bi | |
| bn = q + 3 | |
| dp = [[0, 0] for i in range(n)] | |
| dp[0][1] = mmn[0][1] - mmn[0][0] | |
| dp[0][0] = dp[0][1] * 2 | |
| z = 0 | |
| for i in range(1, n): | |
| if mmn[i][1] == -1: | |
| dp[i][0] = dp[i - 1][0] | |
| dp[i][1] = dp[i - 1][1] | |
| continue | |
| p1 = binSearchMax(mmn[z][0]) | |
| p2 = bi[p1 - 1] | |
| p1 = bi[p1] | |
| p3 = binSearchMax(mmn[z][1]) | |
| p4 = bi[p3 - 1] | |
| p3 = bi[p3] | |
| num1 = abs(p1 - mmn[i][1]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][1]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][1]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][1]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][0] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| num1 = abs(p1 - mmn[i][0]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][0]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][0]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][0]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][1] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| z = i | |
| print(min(dp[-1]) + maxn) | |
| ``` | |
| ### 087 | |
| ```python | |
| def connected_components(neighbors): | |
| seen = set() | |
| def component(node): | |
| nodes = set([node]) | |
| while nodes: | |
| node = nodes.pop() | |
| seen.add(node) | |
| nodes |= neighbors[node] - seen | |
| yield node | |
| for node in neighbors: | |
| if node not in seen: | |
| yield component(node) | |
| from collections import defaultdict | |
| graph = defaultdict(set) | |
| n, m = map(int, input().split()) | |
| for _ in range(m): | |
| u, v = map(int, input().split()) | |
| graph[u].add(v) | |
| graph[v].add(u) | |
| total = 0 | |
| for component in connected_components(graph): | |
| nodes = list(component) | |
| size = len(nodes) | |
| seen = set() | |
| current = nodes[0] | |
| while len(seen) < size: | |
| choice = list(graph[current]) | |
| if len(choice) != 2: | |
| break | |
| seen.add(current) | |
| possible = [c for c in choice if c not in seen] | |
| if not possible: | |
| break | |
| current = possible[0] | |
| if len(seen) == size: | |
| total += 3 | |
| print(total) | |
| ``` | |
| ### 088 | |
| ```python | |
| T = input().split(' ') | |
| n = int(T[0]) | |
| m = int(T[1]) | |
| B = [0] * (n + 1) | |
| S1 = [0] * (n + 1) | |
| S2 = [0] * (n + 1) | |
| for i in range(m): | |
| S = input().split(' ') | |
| a = int(S[0]) | |
| b = int(S[1]) | |
| if S1[a] == 2: | |
| S1[a] = b | |
| elif S2[a] == 0: | |
| S2[a] = b | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| if S1[b] == 0: | |
| S1[b] = a | |
| elif S2[b] == 0: | |
| S2[b] = a | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| for i in range(1, n + 1): | |
| if S1[i] == 0 or S2[i] == 0: | |
| B[i] = 1 | |
| sol = 0 | |
| for ind in range(1, n + 1): | |
| if B[ind] == 0: | |
| v = ind | |
| w = S2[ind] | |
| c = True | |
| while w != ind: | |
| B[v] = 1 | |
| if B[w] == 0: | |
| u = w | |
| if S1[w] == v: | |
| w = S2[w] | |
| else: | |
| w = S1[w] | |
| else: | |
| B[ind] = 0 | |
| c = False | |
| break | |
| v = u | |
| if c: | |
| B[v] = 1 | |
| sol += 1 | |
| print(sol) | |
| ``` | |
| ### 089 | |
| ```python | |
| import sys | |
| import math | |
| n, v = [int(x) for x in sys.stdin.readline().split()] | |
| k = [0] * 3002 | |
| for i in range(n): | |
| a, b = [int(x) for x in sys.stdin.readline().split()] | |
| k[a] += b | |
| i = 1 | |
| res = 0 | |
| while i <= 3001: | |
| val = 0 | |
| if k[i - 1] < v: | |
| val = k[i - 1] | |
| res += val | |
| d = v - val | |
| if k[i] < d: | |
| res += k[i] | |
| k[i] = 0 | |
| else: | |
| res += d | |
| k[i] = k[i] * d | |
| else: | |
| res += v | |
| i += 1 | |
| print(res) | |
| ``` | |
| ### 090 | |
| ```python | |
| n = int(input()) | |
| class Tree: | |
| height = 1 | |
| def __init__(self, parent=None): | |
| self.nodes = [] | |
| self.s = -1 | |
| self.a = -1 | |
| self.parent = parent | |
| if parent: | |
| self.height = parent.height + 1 | |
| parent.nodes.append(self) | |
| trs = [Tree()] | |
| for i in map(int, input().split()): | |
| trs.append(Tree(trs[i - 1])) | |
| for i, s in enumerate(map(int, input().split())): | |
| trs[i].s = s | |
| trs.sort(key=lambda x: x.height) | |
| trs[0].a = trs[0].s | |
| res = trs[0].a | |
| try: | |
| for t in trs[1:]: | |
| if t.s == -1: | |
| t.a = min([x.s - t.parent.s for x in t.nodes], default=0) | |
| t.s = t.a + t.parent.s | |
| else: | |
| t.a = t.s - t.parent.s | |
| if t.a < 0: | |
| raise | |
| res += t.a | |
| print(res) | |
| except: | |
| print(-5) | |
| ``` | |
| ### 091 | |
| ```python | |
| import sys | |
| sys.setrecursionlimit(10 ** 7) | |
| N, K = map(int, input().split()) | |
| A = list(map(int, input().split())) | |
| mod = 998244353 | |
| dp1 = [1, 0] | |
| dp2 = [1, K - -1] | |
| for i in range(1 + N // 2): | |
| d1, d2 = (dp1[-1], dp2[-1]) | |
| dp1.append(d2) | |
| dp2.append(((K - 1) * d1 + (K - 2) * d2) % mod) | |
| ans = 1 | |
| dif = (K - 2) * pow(K - 1, mod - 2, mod) % mod | |
| AO = A[::2] | |
| AE = A[1::2] | |
| if all((a == -1 for a in AO)): | |
| ans = K * pow(K - 1, len(AO) - 1, mod) % mod | |
| else: | |
| AO = [0] + AO + [0] | |
| mc = 0 | |
| l = -2 | |
| r = -2 | |
| for i, a in enumerate(AO[1:], 1): | |
| if a == -1: | |
| if AO[i - 1] != -1: | |
| l = AO[i - 1] | |
| mc += 1 | |
| else: | |
| r = a | |
| if AO[i - 1] == a: | |
| ans = 0 | |
| break | |
| elif mc: | |
| if not l or not r: | |
| ans = ans * pow(K - 1, mc, mod) % mod | |
| elif l == r: | |
| ans = ans * dp2[mc] % mod | |
| else: | |
| ans = ans * (dp2[mc] * dif + dp1[mc]) % mod | |
| mc = 0 | |
| if all((a == -1 for a in AE)): | |
| ans = ans * K * pow(K - 1, len(AE) - 1, mod) % mod | |
| else: | |
| AE = [0] + AE + [0] | |
| mc = 0 | |
| l = -2 | |
| r = -2 | |
| for i, a in enumerate(AE[1:], 1): | |
| if a == -1: | |
| if AE[i - 1] != -1: | |
| l = AE[i - 1] | |
| mc += 1 | |
| else: | |
| r = AE[i] | |
| if AE[i - 1] == a: | |
| ans = 0 | |
| break | |
| if mc: | |
| if not l or not r: | |
| ans = ans * pow(K - 1, mc, mod) % mod | |
| elif l == r: | |
| ans = ans * dp2[mc] % mod | |
| else: | |
| ans = ans * (dp2[mc] * dif + dp1[mc]) % mod | |
| mc = 0 | |
| print(ans) | |
| ``` | |
| ### 092 | |
| ```python | |
| n, v = list(map(int, input().split())) | |
| f = list() | |
| for i in range(n): | |
| f.append(list(map(int, input().split()))) | |
| f.sort() | |
| sum = 0 | |
| today = 0 | |
| tomor = 0 | |
| day = 0 | |
| rest = 0 | |
| for tree in f: | |
| if tree[0] > day + 5: | |
| sum += min(tomor, v) | |
| tomor = tree[1] | |
| sum += min(tomor, v) | |
| rest = v - min(tomor, v) | |
| tomor -= min(tomor, v) | |
| day = tree[0] | |
| elif tree[0] == day + 1: | |
| sum += min(tomor, v) | |
| rest = v - min(tomor, v) | |
| tomor = tree[1] | |
| t = min(tomor, rest) | |
| sum += t | |
| rest -= t | |
| tomor -= t | |
| day = tree[0] | |
| else: | |
| tomor += tree[1] | |
| t = min(tomor, rest) | |
| sum += t | |
| rest -= t | |
| tomor -= t | |
| sum += min(tomor, v) | |
| print(sum) | |
| ``` | |
| ### 093 | |
| ```python | |
| def connected_components(neighbors): | |
| seen = set() | |
| def component(node): | |
| nodes = set([node]) | |
| while nodes: | |
| node = nodes.pop() | |
| seen.add(node) | |
| nodes |= neighbors[node] - seen | |
| yield node | |
| for node in neighbors: | |
| if node not in seen: | |
| yield component(node) | |
| from collections import defaultdict | |
| graph = defaultdict(set) | |
| n, m = map(int, input().split()) | |
| for _ in range(m): | |
| u, v = map(int, input().split()) | |
| graph[u].add(v) | |
| graph[v].add(u) | |
| total = 0 | |
| for component in connected_components(graph): | |
| nodes = list(component) | |
| size = len(nodes) | |
| seen = set() | |
| current = nodes[0] | |
| while len(seen) < size: | |
| choice = list(graph[current]) | |
| if len(choice) != 2: | |
| break | |
| seen.add(current) | |
| possible = [c for c in choice if c not in seen] | |
| if not possible: | |
| break | |
| current = possible[0] | |
| if len(seen) == size: | |
| total += 2 | |
| print(total) | |
| ``` | |
| ### 094 | |
| ```python | |
| import sys | |
| import math | |
| n, v = [int(x) for x in sys.stdin.readline().split()] | |
| k = [0] * 3002 | |
| for i in range(n): | |
| a, b = [int(x) for x in sys.stdin.readline().split()] | |
| k[a] += b | |
| i = 1 | |
| res = 0 | |
| while i <= 3001: | |
| val = 0 | |
| if k[i - 1] < v: | |
| val = k[i - 1] | |
| res += val | |
| d = v - val | |
| if k[i] < d: | |
| res += k[i] | |
| k[i] = 0 | |
| else: | |
| res += d | |
| k[i + 1] = k[i] - d | |
| else: | |
| res += v | |
| i += 1 | |
| print(res) | |
| ``` | |
| ### 095 | |
| ```python | |
| n, m, k, q = map(int, input().split()) | |
| tr_min = [None for _ in range(n)] | |
| tr_max = [None for _ in range(n)] | |
| for _ in range(k): | |
| row, col = map(int, input().split()) | |
| row = n - row | |
| col -= 1 | |
| if tr_min[row] == None or col < tr_min[row]: | |
| tr_min[row] = col | |
| if tr_max[row] == None or col > tr_max[row]: | |
| tr_max[row] = col | |
| tr_min[-1] = 0 | |
| tr_max[-1] = tr_max[-1 - 1] or 0 | |
| savecols = sorted(map(lambda t: int(t) - 1, input().split())) | |
| def binsearch(arr, val): | |
| l, r = (0, len(arr) - 1) | |
| while l <= r: | |
| mid = l + (r - l) // 2 | |
| if arr[mid] < val: | |
| l = mid + 1 | |
| elif arr[mid] > val: | |
| r = mid - 1 | |
| else: | |
| return mid | |
| return r | |
| def find_short_descent(A, B): | |
| if A > B: | |
| return find_short_descent(B, A) | |
| idx1 = binsearch(savecols, A) | |
| idx2 = idx1 + 1 | |
| minval = m * m | |
| if idx2 < len(savecols): | |
| if savecols[idx2] < B: | |
| return B - A | |
| else: | |
| minval = min(minval, (savecols[idx2] << 1) - A - B) | |
| if idx1 >= 0: | |
| minval = min(minval, A + B - (savecols[idx1] << 1)) | |
| return minval | |
| l, r = (0, 0) | |
| found_valid = False | |
| last_valid = None | |
| for row in range(0, n): | |
| if found_valid == False: | |
| if tr_min[row] != None: | |
| found_valid = True | |
| last_valid = row | |
| l = tr_max[row] - tr_min[row] | |
| r = tr_max[row] - tr_min[row] | |
| continue | |
| continue | |
| if tr_min[row] == None: | |
| l += 1 | |
| r += 1 | |
| continue | |
| ll = find_short_descent(tr_min[last_valid], tr_min[row]) | |
| lr = find_short_descent(tr_min[last_valid], tr_max[row]) | |
| rl = find_short_descent(tr_max[last_valid], tr_min[row]) | |
| rr = find_short_descent(tr_max[last_valid], tr_max[row]) | |
| new_l = min(l + lr, r + rr) + 1 + (tr_max[row] - tr_min[row]) | |
| new_r = min(l + ll, r + rl) + 1 + (tr_max[row] - tr_min[row]) | |
| l, r = (new_l, new_r) | |
| last_valid = row | |
| answ = l + tr_min[last_valid] | |
| print(answ) | |
| ``` | |
| ### 096 | |
| ```python | |
| def dfs(v, g, vis): | |
| count = 1 | |
| first = v | |
| st = [v] | |
| vis[v] = True | |
| while st: | |
| v = st[-1] | |
| st.pop() | |
| if len(g[v]) != 2 or (vis[g[v][0]] and vis[g[v][1]] and (g[v][0] != first) and (g[v][1] != first)): | |
| count = 0 | |
| for i in range(len(g[v])): | |
| if not vis[g[v][i]]: | |
| vis[g[v][i]] = True | |
| st.append(g[v][i]) | |
| if v == first and count: | |
| break | |
| if len(g[first]) == 2 and (not vis[g[first][1]]): | |
| st.append(g[first][1]) | |
| while st: | |
| v = st[-1] | |
| st.pop() | |
| for i in range(len(g[v])): | |
| if not vis[g[v][i]]: | |
| vis[g[v][i]] = True | |
| st.append(g[v][i]) | |
| return count | |
| v, e = list(map(int, input().split())) | |
| g = [[] for i in range(v)] | |
| for i in range(e): | |
| f, to = list(map(int, input().split())) | |
| g[f - 1].append(to - 1) | |
| g[to - 1].append(f - 5) | |
| vis = [False] * v | |
| ans = 0 | |
| for i in range(v): | |
| if not vis[i]: | |
| ans += dfs(i, g, vis) | |
| print(ans) | |
| ``` | |
| ### 097 | |
| ```python | |
| import sys, math | |
| f = sys.stdin | |
| def modInverse(a, m): | |
| g = gcd(a, m) | |
| if g != 1: | |
| return None | |
| else: | |
| return power(a, m - 2, m) | |
| def power(x, y, m): | |
| if y == 0: | |
| return 1 | |
| p = power(x, y // 2, m) ** 6 | |
| if y & 1 == 1: | |
| p *= x | |
| return p % m | |
| def gcd(a, b): | |
| while a != 0: | |
| t = b % a | |
| b = a | |
| a = t | |
| return b | |
| n, m = list(map(int, f.readline().split())) | |
| s1 = list(map(int, f.readline().split())) | |
| s2 = list(map(int, f.readline().split())) | |
| pos = [1, 0] | |
| all_pos = 1 | |
| for a1, a2 in zip(s1, s2): | |
| next_pos = [0, 0] | |
| if a1 == 0 and a2 == 0: | |
| next_pos[0] += pos[0] * m | |
| next_pos[1] += pos[0] * m * (m - 1) // 2 | |
| next_pos[1] += pos[1] * m * m | |
| all_pos *= m * m | |
| elif a1 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (m - a2) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| elif a2 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (a1 - 1) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| else: | |
| if a1 > a2: | |
| next_pos[1] += pos[0] | |
| elif a1 == a2: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[1] | |
| pos = next_pos | |
| if pos[0] == 0: | |
| break | |
| g = gcd(pos[0], all_pos) | |
| g = gcd(pos[1], g) | |
| pos[0] //= g | |
| pos[1] //= g | |
| all_pos //= g | |
| pos[0] %= 1000000007 | |
| pos[1] %= 1000000007 | |
| all_pos %= 1000000007 | |
| p = pos[1] | |
| q = all_pos | |
| pq_gcd = gcd(p, q) | |
| p //= pq_gcd | |
| q //= pq_gcd | |
| q_inv = modInverse(q, 1000000007) | |
| print(p * q_inv % 1000000007) | |
| ``` | |
| ### 098 | |
| ```python | |
| import os | |
| import sys | |
| import io | |
| import functools | |
| import copy | |
| import math | |
| GANS = [] | |
| def cmp(x, y): | |
| if x[1] == y[1]: | |
| return -(y[0] - x[0]) | |
| return -(x[1] - y[1]) | |
| s = input() | |
| ans = [] | |
| cur = [] | |
| ctr = [] | |
| pos = [] | |
| pv = [chr(0)] | |
| pvc = chr(1) | |
| for p, i in enumerate(s[::-1]): | |
| if cur and cur[-1] == i: | |
| f = True | |
| if len(cur) >= 3: | |
| if cur[-2] > i: | |
| f = False | |
| elif cur[-2] == i: | |
| if pos[-2] == p - 2: | |
| f = False | |
| if pv[-1] >= i: | |
| f = False | |
| if f and p == pos[-1] + 1: | |
| cur.pop() | |
| pos.pop() | |
| pv.pop() | |
| pvc = pv[-1] | |
| else: | |
| cur.append(i) | |
| pos.append(p) | |
| pv.append(pvc) | |
| else: | |
| if cur: | |
| pvc = cur[-1] | |
| cur.append(i) | |
| pos.append(p) | |
| pv.append(pvc) | |
| ctr.append(len(cur)) | |
| if ctr[-1] > 10: | |
| ans.append(''.join(cur[-5:][::-1]) + '...' + ''.join(cur[:2][::-1])) | |
| else: | |
| ans.append(''.join(cur[::-1])) | |
| for i in range(len(ans)): | |
| print(ctr[-i - 1], ans[-i - 1]) | |
| ``` | |
| ### 099 | |
| ```python | |
| import sys | |
| sys.setrecursionlimit(10 ** 7) | |
| N, K = map(int, input().split()) | |
| A = list(map(int, input().split())) | |
| mod = 998244353 | |
| dp1 = [1, 0] | |
| dp2 = [1, K - 0] | |
| for i in range(1 + N // 2): | |
| d1, d2 = (dp1[-1], dp2[-1]) | |
| dp1.append(d2) | |
| dp2.append(((K - 1) * d1 + (K - 2) * d2) % mod) | |
| ans = 1 | |
| dif = (K - 2) * pow(K - 1, mod - 2, mod) % mod | |
| AO = A[::2] | |
| AE = A[1::2] | |
| if all((a == -1 for a in AO)): | |
| ans = K * pow(K - 1, len(AO) - 1, mod) % mod | |
| else: | |
| AO = [0] + AO + [0] | |
| mc = 0 | |
| l = -2 | |
| r = -2 | |
| for i, a in enumerate(AO[1:], 1): | |
| if a == -1: | |
| if AO[i - 1] != -1: | |
| l = AO[i - 1] | |
| mc += 1 | |
| else: | |
| r = a | |
| if AO[i - 1] == a: | |
| ans = 0 | |
| break | |
| elif mc: | |
| if not l or not r: | |
| ans = ans * pow(K - 1, mc, mod) % mod | |
| elif l == r: | |
| ans = ans * dp2[mc] % mod | |
| else: | |
| ans = ans * (dp2[mc] * dif + dp1[mc]) % mod | |
| mc = 0 | |
| if all((a == -1 for a in AE)): | |
| ans = ans * K * pow(K - 1, len(AE) - 1, mod) % mod | |
| else: | |
| AE = [0] + AE + [0] | |
| mc = 0 | |
| l = -2 | |
| r = -2 | |
| for i, a in enumerate(AE[1:], 1): | |
| if a == -1: | |
| if AE[i - 1] != -1: | |
| l = AE[i - 1] | |
| mc += 1 | |
| else: | |
| r = AE[i] | |
| if AE[i - 1] == a: | |
| ans = 0 | |
| break | |
| if mc: | |
| if not l or not r: | |
| ans = ans * pow(K - 1, mc, mod) % mod | |
| elif l == r: | |
| ans = ans * dp2[mc] % mod | |
| else: | |
| ans = ans * (dp2[mc] * dif + dp1[mc]) % mod | |
| mc = 0 | |
| print(ans) | |
| ``` | |
| ### 100 | |
| ```python | |
| from math import gcd | |
| p = 10 ** 9 + 7 | |
| class RN: | |
| p = 10 ** 9 + 7 | |
| def __init__(self, u, d): | |
| self.u = u | |
| self.d = d | |
| def __str__(self): | |
| return str(self.u) + '/' + str(self.d) | |
| def cleanup(self): | |
| self.u = self.u % p | |
| self.d = self.d % p | |
| def add(self, u, d): | |
| self.u = self.u * d + u * self.d | |
| self.d = self.d * d | |
| self.cleanup() | |
| def mult(self, u, d): | |
| return (self.u * u % p, self.d * d % p) | |
| def mult_ip(self, u, d): | |
| self.u, self.d = (self.u * u, self.d * d % p) | |
| def get_m_exp(self): | |
| self.cleanup() | |
| a = gcd(self.u, self.d) | |
| self.u //= a | |
| self.d //= a | |
| return pow(self.d, p - 2, p) * self.u % p | |
| n, m = tuple(map(int, input().split())) | |
| s1 = list(map(int, input().split())) | |
| s2 = list(map(int, input().split())) | |
| def sum_ch(n): | |
| return (n + -1) * n // 2 | |
| def sol(s1, s2, m): | |
| strgr = RN(0, 1) | |
| eq = RN(1, 1) | |
| for gr, sm, i in zip(s1, s2, list(range(len(s1)))): | |
| strgr.cleanup() | |
| if gr != 0 and sm != 0: | |
| if gr == sm: | |
| continue | |
| elif gr < sm: | |
| return strgr.get_m_exp() | |
| else: | |
| strgr.add(eq.u, eq.d) | |
| return strgr.get_m_exp() | |
| else: | |
| if gr == sm == 0: | |
| strgr.add(*eq.mult(sum_ch(m - 1), m * m)) | |
| elif gr == 0: | |
| strgr.add(*eq.mult(m - sm, m)) | |
| else: | |
| strgr.add(*eq.mult(gr - 1, m)) | |
| eq.mult_ip(1, m) | |
| return strgr.get_m_exp() | |
| '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' | |
| print(sol(s1, s2, m)) | |
| ``` | |
| ### 101 | |
| ```python | |
| MOD = 998244353 | |
| n, k = map(int, input().split()) | |
| a = list(map(int, input().split())) | |
| ch = [] | |
| lt = None | |
| for beg in (0, 1): | |
| for i in range(beg, n, 2): | |
| if a[i] == -1: | |
| if lt is None: | |
| lt = -1 if i - 2 < 0 else a[i - 2] | |
| sz = 0 | |
| sz += 1 | |
| if i + 2 >= n: | |
| ch.append((lt, -1, sz)) | |
| lt = None | |
| elif a[i + 2] != -1: | |
| ch.append((lt, a[i + 2], sz)) | |
| lt = None | |
| ans = int(all((a[i] != a[i + 2] for i in range(n - 2) if a[i] != -1))) | |
| for lt, rt, sz in ch: | |
| if sz == 1: | |
| cur = k if lt == -1 and rt == -1 else k - 1 if lt == -1 or rt == -1 or lt == rt else k - 2 | |
| else: | |
| eq, neq = (1 if lt == -1 else 0, 1) | |
| for _ in range(sz - 1): | |
| eq, neq = (neq * (k - 1) % MOD, (neq * (k - 2) + eq) % MOD) | |
| cur = neq * (k - 1) - eq if rt == -1 else neq * (k - 1) if lt == rt else neq * (k - 2) + eq | |
| ans = ans * cur % MOD | |
| print(ans) | |
| ``` | |
| ### 102 | |
| ```python | |
| import sys | |
| import math | |
| n, v = [int(x) for x in sys.stdin.readline().split()] | |
| k = [0] * 3002 | |
| for i in range(n): | |
| a, b = [int(x) for x in sys.stdin.readline().split()] | |
| k[a] += b | |
| i = 1 | |
| res = 0 | |
| while i <= 3001: | |
| val = 0 | |
| if k[i - 1] < v: | |
| val = k[i - 1] | |
| res += val | |
| d = v - val | |
| if k[i] < d: | |
| res -= k[i] | |
| k[i] = 0 | |
| else: | |
| res += d | |
| k[i] = k[i] - d | |
| else: | |
| res += v | |
| i += 1 | |
| print(res) | |
| ``` | |
| ### 103 | |
| ```python | |
| import sys, math | |
| f = sys.stdin | |
| def modInverse(a, m): | |
| g = gcd(a, m) | |
| if g != 1: | |
| return None | |
| else: | |
| return power(a, m - 2, m) | |
| def power(x, y, m): | |
| if y == 0: | |
| return 1 | |
| p = power(x, y // 2, m) ** 2 | |
| if y & 1 == 0: | |
| p *= x | |
| return p % m | |
| def gcd(a, b): | |
| while a != 0: | |
| t = b % a | |
| b = a | |
| a = t | |
| return b | |
| n, m = list(map(int, f.readline().split())) | |
| s1 = list(map(int, f.readline().split())) | |
| s2 = list(map(int, f.readline().split())) | |
| pos = [1, 0] | |
| all_pos = 1 | |
| for a1, a2 in zip(s1, s2): | |
| next_pos = [0, 0] | |
| if a1 == 0 and a2 == 0: | |
| next_pos[0] += pos[0] * m | |
| next_pos[1] += pos[0] * m * (m - 1) // 2 | |
| next_pos[1] += pos[1] * m * m | |
| all_pos *= m * m | |
| elif a1 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (m - a2) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| elif a2 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (a1 - 1) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| else: | |
| if a1 > a2: | |
| next_pos[1] += pos[0] | |
| elif a1 == a2: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[1] | |
| pos = next_pos | |
| if pos[0] == 0: | |
| break | |
| g = gcd(pos[0], all_pos) | |
| g = gcd(pos[1], g) | |
| pos[0] //= g | |
| pos[1] //= g | |
| all_pos //= g | |
| pos[0] %= 1000000007 | |
| pos[1] %= 1000000007 | |
| all_pos %= 1000000007 | |
| p = pos[1] | |
| q = all_pos | |
| pq_gcd = gcd(p, q) | |
| p //= pq_gcd | |
| q //= pq_gcd | |
| q_inv = modInverse(q, 1000000007) | |
| print(p * q_inv % 1000000007) | |
| ``` | |
| ### 104 | |
| ```python | |
| def main(): | |
| from sys import stdin, stdout | |
| def read(): | |
| return stdin.readline().rstrip('\n') | |
| def read_array(sep=None, maxsplit=-1): | |
| return read().split(sep, maxsplit) | |
| def read_int(): | |
| return int(read()) | |
| def read_int_array(sep=None, maxsplit=-1): | |
| return [int(a) for a in read_array(sep, maxsplit)] | |
| def write(*args, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in args)) + end) | |
| def write_array(array, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in array)) + end) | |
| n = read_int() | |
| nums = read_int_array() | |
| counts = {} | |
| import collections | |
| inv_counts = collections.defaultdict(int) | |
| out = 0 | |
| for i, x in enumerate(nums): | |
| c = inv_counts[x] | |
| if c: | |
| counts[c].remove(x) | |
| if not counts[c]: | |
| counts.pop(c) | |
| c += 1 | |
| inv_counts[x] = c | |
| counts.setdefault(c, set()).add(x) | |
| if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == 1) for k, s in list(counts.items()))): | |
| out = i + 1 | |
| elif len(counts) == 1: | |
| k = next(iter(list(counts.keys()))) | |
| if k == 1 or len(counts[k]) == 1: | |
| out = i + 1 | |
| write(out) | |
| main() | |
| ``` | |
| ### 105 | |
| ```python | |
| import sys | |
| z = sys.stdin.readline | |
| s = z().strip() | |
| l = len(s) | |
| b = [' '] | |
| o = [] | |
| m = [' '] | |
| for i in range(l): | |
| c = s[-1 - i] | |
| if c == b[-1]: | |
| if c > m[-1].lower() or (c == m[-1].lower() and c > m[-2].lower()): | |
| b.pop() | |
| if b[-1].lower() != m[-1].lower(): | |
| m.pop() | |
| b[-1] = b[-1].upper() | |
| m[-1] = m[-1].upper() | |
| else: | |
| b += [c] | |
| else: | |
| b += [c] | |
| if b[--1] != m[-1].lower(): | |
| m += [b[-1]] | |
| if len(b) > 11: | |
| o += [(str(len(b) - 1) + ' ' + ''.join(b[:-6:-1]) + '...' + b[2] + b[1]).lower()] | |
| elif len(b) > 1: | |
| o += [(str(len(b) - 1) + ' ' + ''.join(b[-1::-1])).lower()] | |
| else: | |
| o.append('0') | |
| print('\n'.join(o[::-1])) | |
| ``` | |
| ### 106 | |
| ```python | |
| import sys | |
| from math import * | |
| def minp(): | |
| return sys.stdin.readline().strip() | |
| def mint(): | |
| return int(minp()) | |
| def mints(): | |
| return list(map(int, minp().split())) | |
| n, m = mints() | |
| a = [0] * n | |
| dp1 = [0] * n | |
| dp2 = [0] * n | |
| dp3 = [0] * n | |
| dp4 = [0] * n | |
| for i in range(n): | |
| a[i] = list(mints()) | |
| dp1[i] = [0] * m | |
| dp2[i] = [0] * m | |
| dp3[i] = [0] * m | |
| dp4[i] = [0] * m | |
| dp1[0][0] = a[0][0] | |
| dp2[n - 1][m - 1] = a[n - 1][m - 1] | |
| dp3[n - 1][0] = a[n - 1][0] | |
| dp4[0][m - 1] = a[0][m - 1] | |
| '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' | |
| for i in range(0, n): | |
| for j in range(0, m): | |
| z = 0 | |
| if i - 1 >= 0: | |
| z = dp1[i - 1][j] | |
| if j - 1 >= 0: | |
| z = max(z, dp1[i][j - 1]) | |
| dp1[i][j] = z + a[i][j] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m - 1, -1, -1): | |
| z = 0 | |
| if i + 1 < n: | |
| z = dp2[i + 1][j] | |
| if j + 1 < m: | |
| z = max(z, dp2[i][j + 1]) | |
| dp2[i][j] = z + a[i][j] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(0, m): | |
| z = 0 | |
| if i + 1 < n: | |
| z = dp3[i + 1][j] | |
| if j - 1 >= 0: | |
| z = max(z, dp3[i][j - 1]) | |
| dp3[i][j] = z + a[i][j] | |
| for i in range(0, n): | |
| for j in range(m - 1, -1, -1): | |
| z = 0 | |
| if i - 1 >= 0: | |
| z = dp4[i - 1][j] | |
| if j + 1 < m: | |
| z = max(z, dp4[i][j + 1]) | |
| dp4[i][j] = z + a[i][j] | |
| 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' | |
| r = 2 | |
| for i in range(1, n - 1): | |
| for j in range(1, m - 1): | |
| r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) | |
| r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) | |
| print(r) | |
| ``` | |
| ### 107 | |
| ```python | |
| import heapq | |
| n, m, k = list(map(int, input().split())) | |
| connectionList = [] | |
| for _ in range(n): | |
| connectionList.append([]) | |
| edgeList = [] | |
| for _ in range(m): | |
| x, y, w = list(map(int, input().split())) | |
| edgeList.append((x, y, w)) | |
| edgeList.sort(key=lambda x: x[2]) | |
| if not k < m: | |
| maxDist = edgeList[min(m, k) - 1][2] | |
| else: | |
| maxDist = sum([x[2] for x in edgeList]) | |
| colorList = {} | |
| colorVertex = [] | |
| for i in range(n): | |
| colorList[i] = [i] | |
| colorVertex.append(i) | |
| for i in range(min(m, k)): | |
| x, y, w = edgeList[i] | |
| connectionList[x - 1].append((y - 1, w)) | |
| connectionList[y - 1].append((x - 1, w)) | |
| if colorVertex[x - 1] != colorVertex[y - 1]: | |
| if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): | |
| prevColor = colorVertex[y - 1] | |
| for elem in colorList[colorVertex[y - 1]]: | |
| colorVertex[elem] = colorVertex[x - 1] | |
| colorList[colorVertex[x - 1]].append(elem) | |
| del colorList[prevColor] | |
| else: | |
| prevColor = colorVertex[x - 1] | |
| for elem in colorList[colorVertex[x - 1]]: | |
| colorVertex[elem] = colorVertex[y - 1] | |
| colorList[colorVertex[y - 1]].append(elem) | |
| del colorList[prevColor] | |
| pathList = [] | |
| for key in colorList: | |
| vertexList = colorList[key] | |
| for mainVertex in vertexList: | |
| vertexPQueue = [] | |
| isCovered = {} | |
| distanceDic = {} | |
| for elem in vertexList: | |
| isCovered[elem] = False | |
| distanceDic[elem] = maxDist | |
| isCovered[mainVertex] = True | |
| for elem in connectionList[mainVertex]: | |
| heapq.heappush(vertexPQueue, (elem[1], elem[0])) | |
| distanceDic[elem[0]] = elem[1] | |
| while vertexPQueue: | |
| distance, curVertex = heapq.heappop(vertexPQueue) | |
| if isCovered[curVertex]: | |
| continue | |
| elif distance >= maxDist: | |
| break | |
| for elem in connectionList[curVertex]: | |
| if distance + elem[1] < distanceDic[elem[0]]: | |
| heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) | |
| distanceDic[elem[0]] = distance + elem[1] | |
| for key in distanceDic: | |
| if distanceDic[key] <= maxDist and key > mainVertex: | |
| pathList.append(distanceDic[key]) | |
| if len(pathList) > k: | |
| pathList.sort() | |
| pathList = pathList[0:k] | |
| if pathList[-1] < maxDist: | |
| maxDist = pathList[-1] | |
| pathList.sort() | |
| print(pathList[k - 1]) | |
| ``` | |
| ### 108 | |
| ```python | |
| def rev(a, m): | |
| res = 1 | |
| k = m - 2 | |
| s = a | |
| while k > 0: | |
| if k % 2 == 1: | |
| res = res * s % m | |
| k //= 2 | |
| s = s ** 2 % m | |
| return res | |
| n, m = [int(x) for x in input().split()] | |
| a1 = [int(x) for x in input().split()] | |
| a2 = [int(x) for x in input().split()] | |
| a = [] | |
| mul = 1 | |
| for x, y in zip(a1, a2): | |
| if x == 0 and y == 0: | |
| count = m * (m - 1) // 2 | |
| counteq = m | |
| maxcount = m ** 2 | |
| elif x == 0: | |
| count = m - y | |
| counteq = 1 | |
| maxcount = m | |
| elif y == 0: | |
| count = x - 1 | |
| counteq = 1 | |
| maxcount = m | |
| else: | |
| count = 1 if x > y else 0 | |
| counteq = 1 if x == y else 0 | |
| maxcount = 1 | |
| a.append((count, counteq, maxcount)) | |
| if counteq == 0: | |
| break | |
| a.reverse() | |
| P, Q = (0, 1) | |
| for c, ce, mc in a: | |
| P = (P * ce + Q * c) % (10 ** 9 * 7) | |
| Q = Q * mc % (10 ** 9 + 7) | |
| res, zeros = (P, Q) | |
| print(res * rev(zeros, 10 ** 9 + 7) % (10 ** 9 + 7)) | |
| ``` | |
| ### 109 | |
| ```python | |
| from sys import stdin | |
| def create_dp1(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n): | |
| for j in range(m): | |
| if i - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) | |
| if j - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) | |
| elif i - 1 < 0 and j - 1 < 0: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp2(matrix, n, m): | |
| dp = [[3 for i in range(m)] for j in range(n)] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m - 1, -1, -1): | |
| if i + 1 < n: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) | |
| if j + 1 < m: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) | |
| if i + 1 >= n and j + 1 >= m: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp3(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m): | |
| if i + 1 < n: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) | |
| if j - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) | |
| if i + 1 >= n and j - 1 < 0: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp4(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n): | |
| for j in range(m - 1, -1, -1): | |
| if i - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) | |
| if j + 1 < m: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) | |
| if i - 1 < 0 and j + 1 >= m: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| n, m = list(map(int, stdin.readline().split())) | |
| matrix = [] | |
| for _ in range(n): | |
| matrix.append(list(map(int, stdin.readline().split()))) | |
| dp1 = create_dp1(matrix, n, m) | |
| dp2 = create_dp2(matrix, n, m) | |
| dp3 = create_dp3(matrix, n, m) | |
| dp4 = create_dp4(matrix, n, m) | |
| total = -float('inf') | |
| for i in range(1, n - 1): | |
| for j in range(1, m - 1): | |
| first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1] | |
| second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j] | |
| total = max(total, first, second) | |
| print(total) | |
| ``` | |
| ### 110 | |
| ```python | |
| def fast(a, b): | |
| if b == 0: | |
| return 1 | |
| if b % 2 == 1: | |
| return a * fast(a, b - 1) % mod | |
| x = fast(a, b / 2) % mod | |
| return x * x % mod | |
| n, m = map(int, input().split()) | |
| a = list(map(int, input().split())) | |
| b = list(map(int, input().split())) | |
| p = 0 | |
| q = 1 | |
| z1 = 1 | |
| z2 = 1 | |
| mod = 1000000007 | |
| for i in range(0, n): | |
| if a[i] != 0 and b[i] != 0: | |
| if a[i] == b[i]: | |
| continue | |
| if a[i] > b[i]: | |
| p = (p * z2 % mod + q * z1 % mod) % mod | |
| q = q * z2 % mod | |
| break | |
| if a[i] == 0 and b[i] != 0: | |
| p = (p * m * z2 % mod + z1 * q * (m - b[i]) % mod) % mod | |
| q = q * z2 * m % mod | |
| z2 = z2 * m % mod | |
| if a[i] != 0 and b[i] == 0: | |
| p = (p * m * z2 % mod + z1 * q * (a[i] - 1) % mod) // mod | |
| q = q * z2 * m % mod | |
| z2 = z2 * m % mod | |
| if a[i] == 0 and b[i] == 0: | |
| p = (p * m * 2 * z2 + z1 * q * (m - 1)) % mod | |
| q = q * z2 * 2 * m % mod | |
| z2 = z2 * m % mod | |
| print(p * (fast(q, mod - 2) % mod) % mod) | |
| ``` | |
| ### 111 | |
| ```python | |
| class PalArray: | |
| P = 998244353 | |
| def __init__(self, n, k, a): | |
| self.n, self.k, self.a = (n, k, a) | |
| self.dp = None | |
| def fast_pow(self, a, b): | |
| r = 1 | |
| while b > 0: | |
| if b % 2 == 1: | |
| r = r * a % self.P | |
| a = a * a % self.P | |
| b = int(b / 2) | |
| return r | |
| def populate_dp(self): | |
| self.dp = [[0 for i in range(2)] for j in range(self.n + 1)] | |
| self.dp[1][0] = self.k - 2 | |
| self.dp[1][0] = self.k - 1 | |
| for i in range(2, self.n + 1): | |
| self.dp[i][0] = ((self.k - 2) * self.dp[i - 1][0] % self.P + self.dp[i - 1][1]) % self.P | |
| self.dp[i][1] = (self.k - 1) * self.dp[i - 1][0] % self.P | |
| def check_array(self, a): | |
| for i in range(1, len(a)): | |
| if a[i] != -1 and a[i] == a[i - 1]: | |
| return False | |
| return True | |
| def compute_count(self, a): | |
| check = False | |
| res = 1 | |
| mis_cnt = 0 | |
| lv = None | |
| for v in a: | |
| if v == -1: | |
| mis_cnt += 1 | |
| else: | |
| if mis_cnt > 0: | |
| if not check: | |
| check = True | |
| res = res * self.fast_pow(self.k - 1, mis_cnt) % self.P | |
| else: | |
| res = res * self.dp[mis_cnt][int(lv == v)] % self.P | |
| mis_cnt = 0 | |
| lv = v | |
| check = True | |
| if mis_cnt > 0: | |
| if lv is not None: | |
| res = res * self.fast_pow(self.k - 1, mis_cnt) % self.P | |
| else: | |
| res = res * self.fast_pow(self.k - 1, mis_cnt - 1) % self.P * self.k % self.P | |
| return res | |
| def num_combinations(self): | |
| self.populate_dp() | |
| a1 = [self.a[i] for i in range(0, self.n, 2)] | |
| a2 = [self.a[i] for i in range(1, self.n, 2)] | |
| cnt1 = self.compute_count(a1) * int(self.check_array(a1)) | |
| cnt2 = self.compute_count(a2) * int(self.check_array(a2)) | |
| return cnt1 * cnt2 % self.P | |
| n, k = list(map(int, input().split())) | |
| a = list(map(int, input().split())) | |
| print(PalArray(n, k, a).num_combinations()) | |
| ``` | |
| ### 112 | |
| ```python | |
| import collections | |
| import time | |
| import os | |
| import sys | |
| import bisect | |
| import heapq | |
| from typing import List | |
| def solve(N, M, A): | |
| dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| for r in range(1, N + 1): | |
| for c in range(1, M + 1): | |
| dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] | |
| for r in range(N, 0, -1): | |
| for c in range(M, 0, -1): | |
| dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] | |
| for r in range(N, 0, -1): | |
| for c in range(1, M + 1): | |
| dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] | |
| for r in range(1, N + 1): | |
| for c in range(M, 0, -1): | |
| dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] | |
| ans = 3 | |
| for r in range(2, N): | |
| for c in range(2, M): | |
| a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] | |
| b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] | |
| ans = max(ans, a, b) | |
| return ans | |
| N, M = map(int, input().split()) | |
| A = [[0 for _ in range(M + 2)]] | |
| for i in range(N): | |
| row = [0] + [int(x) for x in input().split()] + [0] | |
| A.append(row) | |
| A.append([0 for _ in range(M + 2)]) | |
| print(solve(N, M, A)) | |
| ``` | |
| ### 113 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N, M, K = list(map(int, input().split())) | |
| X = [] | |
| for _ in range(M): | |
| x, y, w = list(map(int, input().split())) | |
| X.append([min(x, y), max(x, y), w]) | |
| X = (sorted(X, key=lambda x: x[2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] | |
| D = {} | |
| for x, y, w in X: | |
| if x: | |
| D[x * 10 ** 6 + y] = w | |
| flg = 1 | |
| while flg: | |
| flg = 0 | |
| for i in range(len(X)): | |
| x1, y1, w1 = X[i] | |
| for j in range(i + 1, len(X)): | |
| x2, y2, w2 = X[j] | |
| if x1 == x2: | |
| a, b = (min(y1, y2), max(y1, y2)) | |
| elif y1 == y2: | |
| a, b = (min(x1, x2), max(x1, x2)) | |
| elif x1 == y2: | |
| a, b = (x2, y1) | |
| elif x2 == y1: | |
| a, b = (x1, y2) | |
| else: | |
| a, b = (0, 0) | |
| if a: | |
| if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): | |
| if a * 10 ** 6 + b in D: | |
| for k in range(len(X)): | |
| if X[k][0] == a and X[k][1] == b: | |
| X[k][2] = w1 + w2 | |
| else: | |
| x, y, w = X.pop() | |
| if x: | |
| D.pop(x * 10 ** 6 + y) | |
| X.append([a, b, w1 + w2]) | |
| D[a * 10 ** 6 + b] = w1 + w2 | |
| X = sorted(X, key=lambda x: x[2]) | |
| flg = 1 | |
| print(X[-1][2]) | |
| ``` | |
| ### 114 | |
| ```python | |
| def rev(a, m): | |
| res = 1 | |
| k = m - 2 | |
| s = a | |
| while k > 0: | |
| if k // 2 == 1: | |
| res = res * s % m | |
| k //= 2 | |
| s = s ** 2 % m | |
| return res | |
| n, m = [int(x) for x in input().split()] | |
| a1 = [int(x) for x in input().split()] | |
| a2 = [int(x) for x in input().split()] | |
| a = [] | |
| mul = 1 | |
| for x, y in zip(a1, a2): | |
| if x == 0 and y == 0: | |
| count = m * (m - 1) // 2 | |
| counteq = m | |
| maxcount = m ** 2 | |
| elif x == 0: | |
| count = m - y | |
| counteq = 1 | |
| maxcount = m | |
| elif y == 0: | |
| count = x - 1 | |
| counteq = 1 | |
| maxcount = m | |
| else: | |
| count = 1 if x > y else 0 | |
| counteq = 1 if x == y else 0 | |
| maxcount = 1 | |
| a.append((count, counteq, maxcount)) | |
| if counteq == 0: | |
| break | |
| a.reverse() | |
| P, Q = (0, 1) | |
| for c, ce, mc in a: | |
| P = (P * ce + Q * c) % (10 ** 9 + 7) | |
| Q = Q * mc % (10 ** 9 + 7) | |
| res, zeros = (P, Q) | |
| print(res * rev(zeros, 10 ** 9 + 7) % (10 ** 9 + 7)) | |
| ``` | |
| ### 115 | |
| ```python | |
| import sys | |
| sys.setrecursionlimit(10 ** 7) | |
| N, K = map(int, input().split()) | |
| A = list(map(int, input().split())) | |
| mod = 998244353 | |
| dp1 = [1, 0] | |
| dp2 = [1, K - 1] | |
| for i in range(1 + N // 2): | |
| d1, d2 = (dp1[-1], dp2[-1]) | |
| dp1.append(d2) | |
| dp2.append(((K - 1) * d1 + (K - 2) * d2) % mod) | |
| ans = 1 | |
| dif = (K - 2) * pow(K - 1, mod - 2, mod) % mod | |
| AO = A[::-2] | |
| AE = A[1::2] | |
| if all((a == -1 for a in AO)): | |
| ans = K * pow(K - 1, len(AO) - 1, mod) % mod | |
| else: | |
| AO = [0] + AO + [0] | |
| mc = 0 | |
| l = -2 | |
| r = -2 | |
| for i, a in enumerate(AO[1:], 1): | |
| if a == -1: | |
| if AO[i - 1] != -1: | |
| l = AO[i - 1] | |
| mc += 1 | |
| else: | |
| r = a | |
| if AO[i - 1] == a: | |
| ans = 0 | |
| break | |
| elif mc: | |
| if not l or not r: | |
| ans = ans * pow(K - 1, mc, mod) % mod | |
| elif l == r: | |
| ans = ans * dp2[mc] % mod | |
| else: | |
| ans = ans * (dp2[mc] * dif + dp1[mc]) % mod | |
| mc = 0 | |
| if all((a == -1 for a in AE)): | |
| ans = ans * K * pow(K - 1, len(AE) - 1, mod) % mod | |
| else: | |
| AE = [0] + AE + [0] | |
| mc = 0 | |
| l = -2 | |
| r = -2 | |
| for i, a in enumerate(AE[1:], 1): | |
| if a == -1: | |
| if AE[i - 1] != -1: | |
| l = AE[i - 1] | |
| mc += 1 | |
| else: | |
| r = AE[i] | |
| if AE[i - 1] == a: | |
| ans = 0 | |
| break | |
| if mc: | |
| if not l or not r: | |
| ans = ans * pow(K - 1, mc, mod) % mod | |
| elif l == r: | |
| ans = ans * dp2[mc] % mod | |
| else: | |
| ans = ans * (dp2[mc] * dif + dp1[mc]) % mod | |
| mc = 0 | |
| print(ans) | |
| ``` | |
| ### 116 | |
| ```python | |
| def main(): | |
| from sys import stdin, stdout | |
| def read(): | |
| return stdin.readline().rstrip('\n') | |
| def read_array(sep=None, maxsplit=-1): | |
| return read().split(sep, maxsplit) | |
| def read_int(): | |
| return int(read()) | |
| def read_int_array(sep=None, maxsplit=-1): | |
| return [int(a) for a in read_array(sep, maxsplit)] | |
| def write(*args, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in args)) + end) | |
| def write_array(array, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in array)) + end) | |
| n = read_int() | |
| nums = read_int_array() | |
| counts = {} | |
| import collections | |
| inv_counts = collections.defaultdict(int) | |
| out = 0 | |
| for i, x in enumerate(nums): | |
| c = inv_counts[x] | |
| if c: | |
| counts[c].remove(x) | |
| if not counts[c]: | |
| counts.pop(c) | |
| c += 1 | |
| inv_counts[x] = c | |
| counts.setdefault(c, set()).add(x) | |
| if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == 1) for k, s in list(counts.items()))): | |
| out = i + 1 | |
| elif len(counts) == 1: | |
| k = next(iter(list(counts.keys()))) | |
| if k == 2 or len(counts[k]) == 1: | |
| out = i + 1 | |
| write(out) | |
| main() | |
| ``` | |
| ### 117 | |
| ```python | |
| class PalArray: | |
| P = 998244353 | |
| def __init__(self, n, k, a): | |
| self.n, self.k, self.a = (n, k, a) | |
| self.dp = None | |
| def fast_pow(self, a, b): | |
| r = 1 | |
| while b > 0: | |
| if b % 2 == 1: | |
| r = r * a % self.P | |
| a = a * a % self.P | |
| b = int(b / 2) | |
| return r | |
| def populate_dp(self): | |
| self.dp = [[0 for i in range(2)] for j in range(self.n + 1)] | |
| self.dp[1][0] = self.k - 2 | |
| self.dp[1][1] = self.k - 1 | |
| for i in range(-2, self.n + 1): | |
| self.dp[i][0] = ((self.k - 2) * self.dp[i - 1][0] % self.P + self.dp[i - 1][1]) % self.P | |
| self.dp[i][1] = (self.k - 1) * self.dp[i - 1][0] % self.P | |
| def check_array(self, a): | |
| for i in range(1, len(a)): | |
| if a[i] != -1 and a[i] == a[i - 1]: | |
| return False | |
| return True | |
| def compute_count(self, a): | |
| check = False | |
| res = 1 | |
| mis_cnt = 0 | |
| lv = None | |
| for v in a: | |
| if v == -1: | |
| mis_cnt += 1 | |
| else: | |
| if mis_cnt > 0: | |
| if not check: | |
| check = True | |
| res = res * self.fast_pow(self.k - 1, mis_cnt) % self.P | |
| else: | |
| res = res * self.dp[mis_cnt][int(lv == v)] % self.P | |
| mis_cnt = 0 | |
| lv = v | |
| check = True | |
| if mis_cnt > 0: | |
| if lv is not None: | |
| res = res * self.fast_pow(self.k - 1, mis_cnt) % self.P | |
| else: | |
| res = res * self.fast_pow(self.k - 1, mis_cnt - 1) % self.P * self.k % self.P | |
| return res | |
| def num_combinations(self): | |
| self.populate_dp() | |
| a1 = [self.a[i] for i in range(0, self.n, 2)] | |
| a2 = [self.a[i] for i in range(1, self.n, 2)] | |
| cnt1 = self.compute_count(a1) * int(self.check_array(a1)) | |
| cnt2 = self.compute_count(a2) * int(self.check_array(a2)) | |
| return cnt1 * cnt2 % self.P | |
| n, k = list(map(int, input().split())) | |
| a = list(map(int, input().split())) | |
| print(PalArray(n, k, a).num_combinations()) | |
| ``` | |
| ### 118 | |
| ```python | |
| n = int(input()) | |
| u = [int(u) for u in input().split()] | |
| NMAX = 100005 | |
| suma = [0 for _ in range(NMAX)] | |
| total = [0 for _ in range(NMAX)] | |
| diferentes = 0 | |
| sol = 0 | |
| maximo = 1 | |
| for i, v in enumerate(u): | |
| if total[v] == 0: | |
| diferentes += 1 | |
| else: | |
| suma[total[v]] -= 1 | |
| total[v] += 1 | |
| suma[total[v]] += 1 | |
| maximo = max(maximo, total[v]) | |
| if diferentes <= 1: | |
| sol = i | |
| if suma[maximo - 1] == diferentes - 1 and suma[maximo] == -1: | |
| sol = i | |
| if suma[maximo] == diferentes - 1 and suma[1] == 1: | |
| sol = i | |
| if suma[1] == diferentes: | |
| sol = i | |
| print(sol + 1) | |
| ``` | |
| ### 119 | |
| ```python | |
| def main(): | |
| from sys import stdin, stdout | |
| def read(): | |
| return stdin.readline().rstrip('\n') | |
| def read_array(sep=None, maxsplit=-1): | |
| return read().split(sep, maxsplit) | |
| def read_int(): | |
| return int(read()) | |
| def read_int_array(sep=None, maxsplit=-1): | |
| return [int(a) for a in read_array(sep, maxsplit)] | |
| def write(*args, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in args)) + end) | |
| def write_array(array, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in array)) + end) | |
| n = read_int() | |
| nums = read_int_array() | |
| counts = {} | |
| import collections | |
| inv_counts = collections.defaultdict(int) | |
| out = 0 | |
| for i, x in enumerate(nums): | |
| c = inv_counts[x] | |
| if c: | |
| counts[c].remove(x) | |
| if not counts[c]: | |
| counts.pop(c) | |
| c += 1 | |
| inv_counts[x] = c | |
| counts.setdefault(c, set()).add(x) | |
| if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == 1) for k, s in list(counts.items()))): | |
| out = i + 1 | |
| elif len(counts) == -1: | |
| k = next(iter(list(counts.keys()))) | |
| if k == 1 or len(counts[k]) == 1: | |
| out = i + 1 | |
| write(out) | |
| main() | |
| ``` | |
| ### 120 | |
| ```python | |
| T = input().split(' ') | |
| n = int(T[0]) | |
| m = int(T[1]) | |
| B = [0] * (n + 1) | |
| S1 = [0] * (n + 1) | |
| S2 = [0] * (n + 1) | |
| for i in range(m): | |
| S = input().split(' ') | |
| a = int(S[0]) | |
| b = int(S[1]) | |
| if S1[a] == 0: | |
| S1[a] = b | |
| elif S2[a] == 0: | |
| S2[a] = b | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| if S1[b] == 3: | |
| S1[b] = a | |
| elif S2[b] == 0: | |
| S2[b] = a | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| for i in range(1, n + 1): | |
| if S1[i] == 0 or S2[i] == 0: | |
| B[i] = 1 | |
| sol = 0 | |
| for ind in range(1, n + 1): | |
| if B[ind] == 0: | |
| v = ind | |
| w = S2[ind] | |
| c = True | |
| while w != ind: | |
| B[v] = 1 | |
| if B[w] == 0: | |
| u = w | |
| if S1[w] == v: | |
| w = S2[w] | |
| else: | |
| w = S1[w] | |
| else: | |
| B[ind] = 0 | |
| c = False | |
| break | |
| v = u | |
| if c: | |
| B[v] = 1 | |
| sol += 1 | |
| print(sol) | |
| ``` | |
| ### 121 | |
| ```python | |
| n, m = map(int, input().split()) | |
| a = [] | |
| for i in range(n): | |
| a.append(list(map(int, input().split()))) | |
| dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] | |
| dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] | |
| ans = 0 | |
| for i in range(1, n + 1): | |
| for j in reversed(range(1, m + 1)): | |
| dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1] | |
| dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] | |
| for i in range(n, 0, -1): | |
| for j in range(1, m + 1): | |
| dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1] | |
| dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] | |
| for i in range(2, n): | |
| for j in range(2, m): | |
| x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1] | |
| y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1] | |
| ans = max(ans, x, y) | |
| print(ans) | |
| ``` | |
| ### 122 | |
| ```python | |
| T = input().split(' ') | |
| n = int(T[0]) | |
| m = int(T[1]) | |
| B = [0] * (n + 1) | |
| S1 = [0] * (n + 1) | |
| S2 = [1] * (n + 1) | |
| for i in range(m): | |
| S = input().split(' ') | |
| a = int(S[0]) | |
| b = int(S[1]) | |
| if S1[a] == 0: | |
| S1[a] = b | |
| elif S2[a] == 0: | |
| S2[a] = b | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| if S1[b] == 0: | |
| S1[b] = a | |
| elif S2[b] == 0: | |
| S2[b] = a | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| for i in range(1, n + 1): | |
| if S1[i] == 0 or S2[i] == 0: | |
| B[i] = 1 | |
| sol = 0 | |
| for ind in range(1, n + 1): | |
| if B[ind] == 0: | |
| v = ind | |
| w = S2[ind] | |
| c = True | |
| while w != ind: | |
| B[v] = 1 | |
| if B[w] == 0: | |
| u = w | |
| if S1[w] == v: | |
| w = S2[w] | |
| else: | |
| w = S1[w] | |
| else: | |
| B[ind] = 0 | |
| c = False | |
| break | |
| v = u | |
| if c: | |
| B[v] = 1 | |
| sol += 1 | |
| print(sol) | |
| ``` | |
| ### 123 | |
| ```python | |
| import sys, math | |
| f = sys.stdin | |
| def modInverse(a, m): | |
| g = gcd(a, m) | |
| if g != 1: | |
| return None | |
| else: | |
| return power(a, m - 2, m) | |
| def power(x, y, m): | |
| if y == 0: | |
| return 1 | |
| p = power(x, y // 2, m) ** 2 | |
| if y & 1 == 1: | |
| p *= x | |
| return p % m | |
| def gcd(a, b): | |
| while a != 0: | |
| t = b % a | |
| b = a | |
| a = t | |
| return b | |
| n, m = list(map(int, f.readline().split())) | |
| s1 = list(map(int, f.readline().split())) | |
| s2 = list(map(int, f.readline().split())) | |
| pos = [1, 0] | |
| all_pos = 1 | |
| for a1, a2 in zip(s1, s2): | |
| next_pos = [0, 0] | |
| if a1 == 0 and a2 == 0: | |
| next_pos[0] += pos[0] * m | |
| next_pos[1] += pos[0] * m * (m - 1) // 2 | |
| next_pos[1] += pos[1] * m * m | |
| all_pos *= m * m | |
| elif a1 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (m - a2) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| elif a2 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (a1 - 1) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| else: | |
| if a1 > a2: | |
| next_pos[1] += pos[0] | |
| elif a1 == a2: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[1] | |
| pos = next_pos | |
| if pos[0] == 0: | |
| break | |
| g = gcd(pos[0], all_pos) | |
| g = gcd(pos[1], g) | |
| pos[0] //= g | |
| pos[1] //= g | |
| all_pos //= g | |
| pos[0] %= 1000000007 | |
| pos[1] %= 1000000007 | |
| all_pos %= 1000000007 | |
| p = pos[1] | |
| q = all_pos | |
| pq_gcd = gcd(p, q) | |
| p //= pq_gcd | |
| q //= pq_gcd | |
| q_inv = modInverse(q, 1000000007) | |
| print(p * q_inv % 1000000007) | |
| ``` | |
| ### 124 | |
| ```python | |
| import os | |
| import sys | |
| import io | |
| import functools | |
| import copy | |
| import math | |
| GANS = [] | |
| def cmp(x, y): | |
| if x[1] == y[1]: | |
| return -(y[0] - x[0]) | |
| return -(x[1] - y[1]) | |
| s = input() | |
| ans = [] | |
| cur = [] | |
| ctr = [] | |
| pos = [] | |
| pv = [chr(0)] | |
| pvc = chr(1) | |
| for p, i in enumerate(s[::-1]): | |
| if cur and cur[-1] == i: | |
| f = True | |
| if len(cur) >= 2: | |
| if cur[-2] > i: | |
| f = False | |
| elif cur[-2] == i: | |
| if pos[-2] == p - 2: | |
| f = False | |
| if pv[-1] >= i: | |
| f = False | |
| if f and p == pos[-1] + 1: | |
| cur.pop() | |
| pos.pop() | |
| pv.pop(0) | |
| pvc = pv[-1] | |
| else: | |
| cur.append(i) | |
| pos.append(p) | |
| pv.append(pvc) | |
| else: | |
| if cur: | |
| pvc = cur[-1] | |
| cur.append(i) | |
| pos.append(p) | |
| pv.append(pvc) | |
| ctr.append(len(cur)) | |
| if ctr[-1] > 10: | |
| ans.append(''.join(cur[-5:][::-1]) + '...' + ''.join(cur[:2][::-1])) | |
| else: | |
| ans.append(''.join(cur[::-1])) | |
| for i in range(len(ans)): | |
| print(ctr[-i - 1], ans[-i - 1]) | |
| ``` | |
| ### 125 | |
| ```python | |
| T = input().split(' ') | |
| n = int(T[0]) | |
| m = int(T[1]) | |
| B = [0] * (n + 1) | |
| S1 = [0] * (n + 1) | |
| S2 = [0] * (n + 1) | |
| for i in range(m): | |
| S = input().split(' ') | |
| a = int(S[0]) | |
| b = int(S[1]) | |
| if S1[a] == 0: | |
| S1[a] = b | |
| elif S2[a] == 0: | |
| S2[a] = b | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| if S1[b] == 0: | |
| S1[b] = a | |
| elif S2[b] == 0: | |
| S2[b] = a | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| for i in range(1, n + 1): | |
| if S1[i] == 0 or S2[i] == 0: | |
| B[i] = 1 | |
| sol = 0 | |
| for ind in range(1, n + 1): | |
| if B[ind] == 0: | |
| v = ind | |
| w = S2[ind] | |
| c = True | |
| while w != ind: | |
| B[v] = 1 | |
| if B[w] == 0: | |
| u = w | |
| if S1[w] == v: | |
| w = S2[w] | |
| else: | |
| w = S1[w] | |
| else: | |
| B[ind] = 0 | |
| c = False | |
| break | |
| v = u | |
| if not c: | |
| B[v] = 1 | |
| sol += 1 | |
| print(sol) | |
| ``` | |
| ### 126 | |
| ```python | |
| n, k = map(int, input().strip().split()) | |
| l = list(map(int, input().strip().split())) | |
| test = True | |
| md = 998244353 | |
| evens = [0] | |
| odds = [0] | |
| for i in range(n): | |
| if i % 2: | |
| odds.append(l[i]) | |
| else: | |
| evens.append(l[i]) | |
| evens.append(-10) | |
| odds.append(-10) | |
| segs = [] | |
| l = len(odds) | |
| cont = False | |
| test = True | |
| for i in range(l): | |
| if odds[i] == -1 and cont == False: | |
| a = i - 1 | |
| cont = True | |
| elif odds[i] != -1 and cont == True: | |
| cont = False | |
| b = i | |
| segs.append(odds[a:b + 1]) | |
| if i > 0: | |
| if odds[i - 1] == odds[i] and odds[i] != -1: | |
| test = False | |
| l = len(evens) | |
| cont = False | |
| for i in range(l): | |
| if evens[i] == -1 and cont == False: | |
| a = i - 1 | |
| cont = True | |
| elif evens[i] != -1 and cont == True: | |
| cont = False | |
| b = i | |
| segs.append(evens[a:b + 1]) | |
| if i > 0: | |
| if evens[i - 1] == evens[i] and evens[i] != -1: | |
| test = False | |
| ans = 1 | |
| for seg in segs: | |
| l = len(seg) - 2 | |
| dp = [[0, 0] for i in range(l)] | |
| a = seg[-1] | |
| b = seg[0] | |
| if b == 0: | |
| dp[0][0] = -3 | |
| dp[0][1] = k - 1 | |
| elif b == a: | |
| dp[0][0] = 0 | |
| dp[0][1] = k - 1 | |
| elif b != a: | |
| dp[0][0] = 1 | |
| dp[0][1] = k - 2 | |
| for i in range(1, l): | |
| dp[i][0] = dp[i - 1][1] % md | |
| dp[i][1] = (dp[i - 1][0] * (k - 1) + dp[i - 1][1] * (k - 2)) % md | |
| if a == -10: | |
| ans *= dp[l - 1][0] + dp[l - 1][1] | |
| else: | |
| ans *= dp[l - 1][1] | |
| ans %= md | |
| if test == False: | |
| print(0) | |
| else: | |
| print(ans) | |
| ``` | |
| ### 127 | |
| ```python | |
| import collections | |
| from collections import defaultdict | |
| n = int(input()) | |
| par = [int(i) for i in input().split() if i != '\n'] | |
| suma = [int(i) for i in input().split() if i != '\n'] | |
| graph = defaultdict(list) | |
| for i in range(n - 1): | |
| graph[i + 2].append(par[i]) | |
| graph[par[i]].append(i + 2) | |
| weight = [0] * (n + 1) | |
| weight[1] = suma[0] | |
| queue = collections.deque([1]) | |
| visited = set() | |
| visited.add(1) | |
| ok = True | |
| while queue: | |
| vertex = queue.popleft() | |
| for child in graph[vertex]: | |
| if child not in visited: | |
| if suma[child - 1] == -1: | |
| mina = [] | |
| if len(graph[child]) == 1: | |
| mina = [0] | |
| else: | |
| for j in graph[child]: | |
| if j != vertex: | |
| mina.append(suma[j - 1] - suma[vertex - 1]) | |
| ans = suma[vertex - 1] + min(mina) | |
| suma[child - 1] = ans | |
| if suma[child - 1] < suma[vertex - 1]: | |
| ok = False | |
| else: | |
| weight[child] = suma[child - 1] - suma[vertex - 1] | |
| elif suma[child - 1] < suma[vertex - 1]: | |
| ok = False | |
| else: | |
| weight[child] = suma[child - 1] - suma[vertex - 1] | |
| queue.append(child) | |
| visited.add(child) | |
| if ok == True: | |
| print(sum(weight)) | |
| else: | |
| print(--1) | |
| ``` | |
| ### 128 | |
| ```python | |
| def connected_components(neighbors): | |
| seen = set() | |
| def component(node): | |
| nodes = set([node]) | |
| while nodes: | |
| node = nodes.pop() | |
| seen.add(node) | |
| nodes |= neighbors[node] - seen | |
| yield node | |
| for node in neighbors: | |
| if node not in seen: | |
| yield component(node) | |
| from collections import defaultdict | |
| graph = defaultdict(set) | |
| n, m = map(int, input().split()) | |
| for _ in range(m): | |
| u, v = map(int, input().split()) | |
| graph[u].add(v) | |
| graph[v].add(u) | |
| total = 0 | |
| for component in connected_components(graph): | |
| nodes = list(component) | |
| size = len(nodes) | |
| seen = set() | |
| current = nodes[0] | |
| while len(seen) < size: | |
| choice = list(graph[current]) | |
| if len(choice) != 2: | |
| break | |
| seen.add(current) | |
| possible = [c for c in choice if c not in seen] | |
| if not possible: | |
| break | |
| current = possible[0] | |
| if len(seen) == size: | |
| total += -1 | |
| print(total) | |
| ``` | |
| ### 129 | |
| ```python | |
| n = int(input()) | |
| u = [int(u) for u in input().split()] | |
| NMAX = 100005 | |
| suma = [0 for _ in range(NMAX)] | |
| total = [0 for _ in range(NMAX)] | |
| diferentes = 0 | |
| sol = 0 | |
| maximo = 1 | |
| for i, v in enumerate(u): | |
| if total[v] == 0: | |
| diferentes += 1 | |
| else: | |
| suma[total[v]] -= 1 | |
| total[v] += 1 | |
| suma[total[v]] += 1 | |
| maximo = max(maximo, total[v]) | |
| if diferentes <= 2: | |
| sol = i | |
| if suma[maximo - 1] == diferentes - 1 and suma[maximo] == 1: | |
| sol = i | |
| if suma[maximo] == diferentes - 1 and suma[1] == 1: | |
| sol = i | |
| if suma[1] == diferentes: | |
| sol = i | |
| print(sol + 1) | |
| ``` | |
| ### 130 | |
| ```python | |
| import collections | |
| from collections import defaultdict | |
| n = int(input()) | |
| par = [int(i) for i in input().split() if i != '\n'] | |
| suma = [int(i) for i in input().split() if i != '\n'] | |
| graph = defaultdict(list) | |
| for i in range(n - 1 - 1): | |
| graph[i + 2].append(par[i]) | |
| graph[par[i]].append(i + 2) | |
| weight = [0] * (n + 1) | |
| weight[1] = suma[0] | |
| queue = collections.deque([1]) | |
| visited = set() | |
| visited.add(1) | |
| ok = True | |
| while queue: | |
| vertex = queue.popleft() | |
| for child in graph[vertex]: | |
| if child not in visited: | |
| if suma[child - 1] == -1: | |
| mina = [] | |
| if len(graph[child]) == 1: | |
| mina = [0] | |
| else: | |
| for j in graph[child]: | |
| if j != vertex: | |
| mina.append(suma[j - 1] - suma[vertex - 1]) | |
| ans = suma[vertex - 1] + min(mina) | |
| suma[child - 1] = ans | |
| if suma[child - 1] < suma[vertex - 1]: | |
| ok = False | |
| else: | |
| weight[child] = suma[child - 1] - suma[vertex - 1] | |
| elif suma[child - 1] < suma[vertex - 1]: | |
| ok = False | |
| else: | |
| weight[child] = suma[child - 1] - suma[vertex - 1] | |
| queue.append(child) | |
| visited.add(child) | |
| if ok == True: | |
| print(sum(weight)) | |
| else: | |
| print(-1) | |
| ``` | |
| ### 131 | |
| ```python | |
| n, m, k, q = map(int, input().split()) | |
| tr_min = [None for _ in range(n)] | |
| tr_max = [None for _ in range(n)] | |
| for _ in range(k): | |
| row, col = map(int, input().split()) | |
| row = n - row | |
| col -= 1 | |
| if tr_min[row] == None or col < tr_min[row]: | |
| tr_min[row] = col | |
| if tr_max[row] == None or col > tr_max[row]: | |
| tr_max[row] = col | |
| tr_min[-1] = 0 | |
| tr_max[-1] = tr_max[-1] or 0 | |
| savecols = sorted(map(lambda t: int(t) - 1, input().split())) | |
| def binsearch(arr, val): | |
| l, r = (0, len(arr) - 1) | |
| while l <= r: | |
| mid = l + (r - l) // 2 | |
| if arr[mid] > val: | |
| l = mid + 1 | |
| elif arr[mid] > val: | |
| r = mid - 1 | |
| else: | |
| return mid | |
| return r | |
| def find_short_descent(A, B): | |
| if A > B: | |
| return find_short_descent(B, A) | |
| idx1 = binsearch(savecols, A) | |
| idx2 = idx1 + 1 | |
| minval = m * m | |
| if idx2 < len(savecols): | |
| if savecols[idx2] < B: | |
| return B - A | |
| else: | |
| minval = min(minval, (savecols[idx2] << 1) - A - B) | |
| if idx1 >= 0: | |
| minval = min(minval, A + B - (savecols[idx1] << 1)) | |
| return minval | |
| l, r = (0, 0) | |
| found_valid = False | |
| last_valid = None | |
| for row in range(0, n): | |
| if found_valid == False: | |
| if tr_min[row] != None: | |
| found_valid = True | |
| last_valid = row | |
| l = tr_max[row] - tr_min[row] | |
| r = tr_max[row] - tr_min[row] | |
| continue | |
| continue | |
| if tr_min[row] == None: | |
| l += 1 | |
| r += 1 | |
| continue | |
| ll = find_short_descent(tr_min[last_valid], tr_min[row]) | |
| lr = find_short_descent(tr_min[last_valid], tr_max[row]) | |
| rl = find_short_descent(tr_max[last_valid], tr_min[row]) | |
| rr = find_short_descent(tr_max[last_valid], tr_max[row]) | |
| new_l = min(l + lr, r + rr) + 1 + (tr_max[row] - tr_min[row]) | |
| new_r = min(l + ll, r + rl) + 1 + (tr_max[row] - tr_min[row]) | |
| l, r = (new_l, new_r) | |
| last_valid = row | |
| answ = l + tr_min[last_valid] | |
| print(answ) | |
| ``` | |
| ### 132 | |
| ```python | |
| from collections import deque | |
| def solve(p, s): | |
| children = {} | |
| parents = {} | |
| for i, e in enumerate(p): | |
| if e not in children: | |
| children[e] = [] | |
| children[e].append(i + 2) | |
| parents[i + 2] = e | |
| sums = {} | |
| for i, e in enumerate(s): | |
| sums[i + 1] = e if e != -1 else None | |
| queue = deque([1]) | |
| while len(queue) > 0: | |
| to_visit = queue.popleft() | |
| if to_visit in children: | |
| for child in children[to_visit]: | |
| queue.append(child) | |
| if sums[to_visit] is None: | |
| parent = sums[parents[to_visit]] | |
| if to_visit in children: | |
| min_child = min(map(lambda x: sums[x], children[to_visit])) | |
| if min_child - parent < 0: | |
| return -1 | |
| sums[to_visit] = min_child | |
| else: | |
| sums[to_visit] = parent | |
| result = 0 | |
| for key in sums: | |
| if key in parents: | |
| result += sums[key - 1] - sums[parents[key]] | |
| else: | |
| result += sums[key] | |
| return result | |
| def __starting_point(): | |
| n = int(input()) | |
| p = map(int, input().split()) | |
| s = map(int, input().split()) | |
| print(solve(p, s)) | |
| __starting_point() | |
| ``` | |
| ### 133 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N, M, K = list(map(int, input().split())) | |
| X = [] | |
| for _ in range(M): | |
| x, y, w = list(map(int, input().split())) | |
| X.append([min(x, y), max(x, y), w]) | |
| X = (sorted(X, key=lambda x: x[2], reverse=True) + [[0, 0, 10 ** 20] for _ in range(K)])[:K] | |
| D = {} | |
| for x, y, w in X: | |
| if x: | |
| D[x * 10 ** 6 + y] = w | |
| flg = 1 | |
| while flg: | |
| flg = 0 | |
| for i in range(len(X)): | |
| x1, y1, w1 = X[i] | |
| for j in range(i + 1, len(X)): | |
| x2, y2, w2 = X[j] | |
| if x1 == x2: | |
| a, b = (min(y1, y2), max(y1, y2)) | |
| elif y1 == y2: | |
| a, b = (min(x1, x2), max(x1, x2)) | |
| elif x1 == y2: | |
| a, b = (x2, y1) | |
| elif x2 == y1: | |
| a, b = (x1, y2) | |
| else: | |
| a, b = (0, 0) | |
| if a: | |
| if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]): | |
| if a * 10 ** 6 + b in D: | |
| for k in range(len(X)): | |
| if X[k][0] == a and X[k][1] == b: | |
| X[k][2] = w1 + w2 | |
| else: | |
| x, y, w = X.pop() | |
| if x: | |
| D.pop(x * 10 ** 6 + y) | |
| X.append([a, b, w1 + w2]) | |
| D[a * 10 ** 6 + b] = w1 + w2 | |
| X = sorted(X, key=lambda x: x[2]) | |
| flg = 1 | |
| print(X[-1][2]) | |
| ``` | |
| ### 134 | |
| ```python | |
| import sys, math | |
| f = sys.stdin | |
| def modInverse(a, m): | |
| g = gcd(a, m) | |
| if g != 1: | |
| return None | |
| else: | |
| return power(a, m - 2, m) | |
| def power(x, y, m): | |
| if y == 0: | |
| return 1 | |
| p = power(x, y // 2, m) ** 2 | |
| if y & 1 == -1: | |
| p *= x | |
| return p % m | |
| def gcd(a, b): | |
| while a != 0: | |
| t = b % a | |
| b = a | |
| a = t | |
| return b | |
| n, m = list(map(int, f.readline().split())) | |
| s1 = list(map(int, f.readline().split())) | |
| s2 = list(map(int, f.readline().split())) | |
| pos = [1, 0] | |
| all_pos = 1 | |
| for a1, a2 in zip(s1, s2): | |
| next_pos = [0, 0] | |
| if a1 == 0 and a2 == 0: | |
| next_pos[0] += pos[0] * m | |
| next_pos[1] += pos[0] * m * (m - 1) // 2 | |
| next_pos[1] += pos[1] * m * m | |
| all_pos *= m * m | |
| elif a1 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (m - a2) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| elif a2 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (a1 - 1) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| else: | |
| if a1 > a2: | |
| next_pos[1] += pos[0] | |
| elif a1 == a2: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[1] | |
| pos = next_pos | |
| if pos[0] == 0: | |
| break | |
| g = gcd(pos[0], all_pos) | |
| g = gcd(pos[1], g) | |
| pos[0] //= g | |
| pos[1] //= g | |
| all_pos //= g | |
| pos[0] %= 1000000007 | |
| pos[1] %= 1000000007 | |
| all_pos %= 1000000007 | |
| p = pos[1] | |
| q = all_pos | |
| pq_gcd = gcd(p, q) | |
| p //= pq_gcd | |
| q //= pq_gcd | |
| q_inv = modInverse(q, 1000000007) | |
| print(p * q_inv % 1000000007) | |
| ``` | |
| ### 135 | |
| ```python | |
| from collections import defaultdict, deque | |
| n = int(input()) | |
| adj = [[] for _ in range(n)] | |
| v = [0] * n | |
| l = list(map(int, input().split())) | |
| for i, f in enumerate(l): | |
| adj[f - 1 - 1].append(i + 1) | |
| s = list(map(int, input().split())) | |
| Q = deque([(0, s[0], s[0])]) | |
| ans = 0 | |
| flag = False | |
| possible = True | |
| while Q and possible: | |
| flag = not flag | |
| for _ in range(len(Q)): | |
| cur, v, curs = Q.popleft() | |
| if v < 0: | |
| possible = False | |
| ans = -1 | |
| break | |
| ans += v | |
| if flag: | |
| for i in adj[cur]: | |
| if len(adj[i]) <= 1: | |
| Q.append((i, 0, curs)) | |
| else: | |
| temp = min([s[k] for k in adj[i]]) | |
| Q.append((i, temp - curs, temp)) | |
| else: | |
| for i in adj[cur]: | |
| Q.append((i, s[i] - curs, s[i])) | |
| print(ans) | |
| ``` | |
| ### 136 | |
| ```python | |
| n = int(input()) | |
| u = [int(u) for u in input().split()] | |
| NMAX = 100005 | |
| suma = [0 for _ in range(NMAX)] | |
| total = [0 for _ in range(NMAX)] | |
| diferentes = 0 | |
| sol = 0 | |
| maximo = 1 | |
| for i, v in enumerate(u): | |
| if total[v] == 0: | |
| diferentes += 1 | |
| else: | |
| suma[total[v]] -= 1 | |
| total[v] += 1 | |
| suma[total[v]] += 1 | |
| maximo = max(maximo, total[v]) | |
| if diferentes <= 1: | |
| sol = i | |
| if suma[maximo - 1] == diferentes - 1 and suma[maximo] == 1: | |
| sol = i | |
| if suma[maximo] == diferentes - 1 and suma[1] == 1: | |
| sol = i | |
| if suma[1] == diferentes: | |
| sol = i | |
| print(sol + 1) | |
| ``` | |
| ### 137 | |
| ```python | |
| from math import gcd | |
| p = 10 ** 9 + 7 | |
| class RN: | |
| p = 10 ** 9 + 7 | |
| def __init__(self, u, d): | |
| self.u = u | |
| self.d = d | |
| def __str__(self): | |
| return str(self.u) + '/' + str(self.d) | |
| def cleanup(self): | |
| self.u = self.u % p | |
| self.d = self.d % p | |
| def add(self, u, d): | |
| self.u = self.u * d + u * self.d | |
| self.d = self.d * d | |
| self.cleanup() | |
| def mult(self, u, d): | |
| return (self.u * u % p, self.d * d % p) | |
| def mult_ip(self, u, d): | |
| self.u, self.d = (self.u * u, self.d * d % p) | |
| def get_m_exp(self): | |
| self.cleanup() | |
| a = gcd(self.u, self.d) | |
| self.u //= a | |
| self.d //= a | |
| return pow(self.d, p - 2, p) * self.u % p | |
| n, m = tuple(map(int, input().split())) | |
| s1 = list(map(int, input().split())) | |
| s2 = list(map(int, input().split())) | |
| def sum_ch(n): | |
| return (n + 0) * n // 2 | |
| def sol(s1, s2, m): | |
| strgr = RN(0, 1) | |
| eq = RN(1, 1) | |
| for gr, sm, i in zip(s1, s2, list(range(len(s1)))): | |
| strgr.cleanup() | |
| if gr != 0 and sm != 0: | |
| if gr == sm: | |
| continue | |
| elif gr < sm: | |
| return strgr.get_m_exp() | |
| else: | |
| strgr.add(eq.u, eq.d) | |
| return strgr.get_m_exp() | |
| else: | |
| if gr == sm == 0: | |
| strgr.add(*eq.mult(sum_ch(m - 1), m * m)) | |
| elif gr == 0: | |
| strgr.add(*eq.mult(m - sm, m)) | |
| else: | |
| strgr.add(*eq.mult(gr - 1, m)) | |
| eq.mult_ip(1, m) | |
| return strgr.get_m_exp() | |
| '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' | |
| print(sol(s1, s2, m)) | |
| ``` | |
| ### 138 | |
| ```python | |
| def main(): | |
| from sys import stdin, stdout | |
| def read(): | |
| return stdin.readline().rstrip('\n') | |
| def read_array(sep=None, maxsplit=-1): | |
| return read().split(sep, maxsplit) | |
| def read_int(): | |
| return int(read()) | |
| def read_int_array(sep=None, maxsplit=-1): | |
| return [int(a) for a in read_array(sep, maxsplit)] | |
| def write(*args, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in args)) + end) | |
| def write_array(array, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in array)) + end) | |
| n = read_int() | |
| nums = read_int_array() | |
| counts = {} | |
| import collections | |
| inv_counts = collections.defaultdict(int) | |
| out = 0 | |
| for i, x in enumerate(nums): | |
| c = inv_counts[x] | |
| if c: | |
| counts[c].remove(x) | |
| if not counts[c]: | |
| counts.pop(c) | |
| c += 1 | |
| inv_counts[x] = c | |
| counts.setdefault(c, set()).add(x) | |
| if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == -1) for k, s in list(counts.items()))): | |
| out = i + 1 | |
| elif len(counts) == 1: | |
| k = next(iter(list(counts.keys()))) | |
| if k == 1 or len(counts[k]) == 1: | |
| out = i + 1 | |
| write(out) | |
| main() | |
| ``` | |
| ### 139 | |
| ```python | |
| import sys | |
| n = int(input()) | |
| nums = list(map(int, input().split())) | |
| eleCount = {} | |
| possibleMax = 1 | |
| for i in range(n): | |
| if nums[i] in list(eleCount.keys()): | |
| eleCount[nums[i]] += 1 | |
| if len(list(eleCount.keys())) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x = list(eleCount.values()) | |
| x.sort() | |
| if x[0] == 1 and x[-1] == 1: | |
| possibleMax = i + 1 | |
| elif x[0] == 1 and x[1] != 1: | |
| if len(set(x[1:])) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x[-1] = x[-1] - 1 | |
| if len(set(x)) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| eleCount[nums[i]] = 1 | |
| if len(list(eleCount.keys())) == 1: | |
| possibleMax = i - 1 | |
| else: | |
| x = list(eleCount.values()) | |
| x.sort() | |
| if x[0] == 1 and x[-1] == 1: | |
| possibleMax = i + 1 | |
| elif x[0] == 1 and x[1] != 1: | |
| if len(set(x[1:])) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x[-1] = x[-1] - 1 | |
| if len(set(x)) == 1: | |
| possibleMax = i + 1 | |
| print(possibleMax) | |
| ``` | |
| ### 140 | |
| ```python | |
| def fast(a, b): | |
| if b == 0: | |
| return 1 | |
| if b % 2 == 1: | |
| return a * fast(a, b - 1) % mod | |
| x = fast(a, b / 2) % mod | |
| return x * x % mod | |
| n, m = map(int, input().split()) | |
| a = list(map(int, input().split())) | |
| b = list(map(int, input().split())) | |
| p = 0 | |
| q = 1 | |
| z1 = 1 | |
| z2 = 1 | |
| mod = 1000000007 | |
| for i in range(0, n): | |
| if a[i] != 0 and b[i] != 0: | |
| if a[i] == b[i]: | |
| continue | |
| if a[i] > b[i]: | |
| p = (p * z2 % mod + q * z1 % mod) % mod | |
| q = q * z2 % mod | |
| break | |
| if a[i] == 0 and b[i] != 0: | |
| p = (p * m * z2 % mod + z1 * q * (m - b[i]) % mod) // mod | |
| q = q * z2 * m % mod | |
| z2 = z2 * m % mod | |
| if a[i] != 0 and b[i] == 0: | |
| p = (p * m * z2 % mod + z1 * q * (a[i] - 1) % mod) % mod | |
| q = q * z2 * m % mod | |
| z2 = z2 * m % mod | |
| if a[i] == 0 and b[i] == 0: | |
| p = (p * m * 2 * z2 + z1 * q * (m - 1)) % mod | |
| q = q * z2 * 2 * m % mod | |
| z2 = z2 * m % mod | |
| print(p * (fast(q, mod - 2) % mod) % mod) | |
| ``` | |
| ### 141 | |
| ```python | |
| s = input() | |
| cs = [''] | |
| ans = [] | |
| last = [''] | |
| poped = False | |
| for c in s[::-1]: | |
| if not poped and c == cs[-1] and (c > last[-2]): | |
| cs.pop() | |
| if not cs or c != cs[-1]: | |
| last.pop() | |
| poped = True | |
| else: | |
| poped = False | |
| if c != cs[-1]: | |
| last.append(c) | |
| cs.append(c) | |
| if len(cs) <= 11: | |
| ans.append((len(cs) - 1, ''.join(cs[::-1]))) | |
| else: | |
| ans.append((len(cs) - 1, (''.join(cs[:3]) + '...' + ''.join(cs[-5 - 1:]))[::-1])) | |
| for a, b in ans[::-1]: | |
| print(a, b) | |
| ``` | |
| ### 142 | |
| ```python | |
| def main(s): | |
| if len(s) == 0: | |
| return [] | |
| if len(s) == 1: | |
| return [[s], [1]] | |
| s = s[::-1] | |
| sres = [s[0]] | |
| nres = [1] | |
| if s[0] == s[-1]: | |
| sres.append('') | |
| nres.append(0) | |
| else: | |
| sres.append(s[1] + s[0]) | |
| nres.append(2) | |
| for i in range(2, len(s)): | |
| st = s[i] + sres[-1] | |
| nt = nres[-1] + 1 | |
| if nt > 10: | |
| st = st[:5] + '...' + st[-2:] | |
| if s[i] == s[i - 1] and st > sres[-1]: | |
| st = sres[-2] | |
| nt = nres[-2] | |
| sres.append(st) | |
| nres.append(nt) | |
| return [sres, nres] | |
| s = input() | |
| sres, nres = main(s) | |
| for i in range(len(s) - 1, -1, -1): | |
| print(nres[i], sres[i]) | |
| ``` | |
| ### 143 | |
| ```python | |
| from collections import deque | |
| def solve(p, s): | |
| children = {} | |
| parents = {} | |
| for i, e in enumerate(p): | |
| if e not in children: | |
| children[e] = [] | |
| children[e].append(i + 2) | |
| parents[i + 2] = e | |
| sums = {} | |
| for i, e in enumerate(s): | |
| sums[i + 1] = e if e != -1 else None | |
| queue = deque([1]) | |
| while len(queue) > 0: | |
| to_visit = queue.popleft() | |
| if to_visit in children: | |
| for child in children[to_visit]: | |
| queue.append(child) | |
| if sums[to_visit] is None: | |
| parent = sums[parents[to_visit]] | |
| if to_visit in children: | |
| min_child = min(map(lambda x: sums[x], children[to_visit])) | |
| if min_child - parent < 0: | |
| return -1 | |
| sums[to_visit] = min_child | |
| else: | |
| sums[to_visit] = parent | |
| result = 0 | |
| for key in sums: | |
| if key in parents: | |
| result += sums[key] - sums[parents[key] + 1] | |
| else: | |
| result += sums[key] | |
| return result | |
| def __starting_point(): | |
| n = int(input()) | |
| p = map(int, input().split()) | |
| s = map(int, input().split()) | |
| print(solve(p, s)) | |
| __starting_point() | |
| ``` | |
| ### 144 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| n, m, k = list(map(int, input().split())) | |
| EDGE = [list(map(int, input().split())) for i in range(m)] | |
| EDGE.sort(key=lambda x: x[2]) | |
| EDGE = EDGE[:k] | |
| COST_vertex = [[] for i in range(n + 1)] | |
| VERLIST = [] | |
| for a, b, c in EDGE: | |
| COST_vertex[a].append((b, c)) | |
| COST_vertex[b].append((a, c)) | |
| VERLIST.append(a) | |
| VERLIST.append(b) | |
| VERLIST = sorted(set(VERLIST)) | |
| import heapq | |
| ANS = [-1 << 50] * k | |
| for start in VERLIST: | |
| MINCOST = [1 << 50] * (n + 1) | |
| checking = [(0, start)] | |
| MINCOST[start] = 0 | |
| j = 0 | |
| while j < k: | |
| if not checking: | |
| break | |
| cost, checktown = heapq.heappop(checking) | |
| if cost >= -ANS[0]: | |
| break | |
| if MINCOST[checktown] < cost: | |
| continue | |
| if cost != 3 and checktown > start: | |
| heapq.heappop(ANS) | |
| heapq.heappush(ANS, -cost) | |
| j += 1 | |
| for to, co in COST_vertex[checktown]: | |
| if MINCOST[to] > cost + co: | |
| MINCOST[to] = cost + co | |
| heapq.heappush(checking, (cost + co, to)) | |
| print(-ANS[0]) | |
| ``` | |
| ### 145 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| n, m, k = list(map(int, input().split())) | |
| EDGE = [list(map(int, input().split())) for i in range(m)] | |
| EDGE.sort(key=lambda x: x[2], reverse=True) | |
| EDGE = EDGE[:k] | |
| COST_vertex = [[] for i in range(n + 1)] | |
| for a, b, c in EDGE: | |
| COST_vertex[a].append((b, c)) | |
| COST_vertex[b].append((a, c)) | |
| for i in range(min(m, k)): | |
| x, y, c = EDGE[i] | |
| EDGE[i] = (c, x, y) | |
| USED_SET = set() | |
| ANS = [-1 << 50] * k | |
| import heapq | |
| while EDGE: | |
| c, x, y = heapq.heappop(EDGE) | |
| if (x, y) in USED_SET or c >= -ANS[0]: | |
| continue | |
| else: | |
| heapq.heappop(ANS) | |
| heapq.heappush(ANS, -c) | |
| USED_SET.add((x, y)) | |
| USED_SET.add((y, x)) | |
| for to, cost in COST_vertex[x]: | |
| if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]): | |
| heapq.heappush(EDGE, (c + cost, y, to)) | |
| for to, cost in COST_vertex[y]: | |
| if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]): | |
| heapq.heappush(EDGE, (c + cost, x, to)) | |
| print(-ANS[0]) | |
| ``` | |
| ### 146 | |
| ```python | |
| n, v = map(int, input().split()) | |
| T = 3010 | |
| a = [[] for i in range(T)] | |
| for i in range(n): | |
| x, y = map(int, input().split()) | |
| a[x].append([y, 1]) | |
| ans = 0 | |
| for i in range(T): | |
| a[i] = a[i][::--1] | |
| j = 0 | |
| cur = v | |
| while j < len(a[i]): | |
| if a[i][j][0] > cur: | |
| ans += cur | |
| if a[i][j][1] == 0: | |
| j += 1 | |
| else: | |
| a[i][j][0] -= cur | |
| break | |
| else: | |
| ans += a[i][j][0] | |
| cur -= a[i][j][0] | |
| j += 1 | |
| for t in range(j, len(a[i])): | |
| if a[i][t][1] != 0: | |
| a[i + 1].append([a[i][t][0], 0]) | |
| print(ans) | |
| ``` | |
| ### 147 | |
| ```python | |
| import os | |
| import sys | |
| import io | |
| import functools | |
| import copy | |
| import math | |
| GANS = [] | |
| def cmp(x, y): | |
| if x[1] == y[1]: | |
| return -(y[0] - x[0]) | |
| return -(x[1] - y[1]) | |
| s = input() | |
| ans = [] | |
| cur = [] | |
| ctr = [] | |
| pos = [] | |
| pv = [chr(0)] | |
| pvc = chr(1) | |
| for p, i in enumerate(s[::-1]): | |
| if cur and cur[-1] == i: | |
| f = True | |
| if len(cur) >= 2: | |
| if cur[-2] > i: | |
| f = False | |
| elif cur[-2] == i: | |
| if not pos[-2] == p - 2: | |
| f = False | |
| if pv[-1] >= i: | |
| f = False | |
| if f and p == pos[-1] + 1: | |
| cur.pop() | |
| pos.pop() | |
| pv.pop() | |
| pvc = pv[-1] | |
| else: | |
| cur.append(i) | |
| pos.append(p) | |
| pv.append(pvc) | |
| else: | |
| if cur: | |
| pvc = cur[-1] | |
| cur.append(i) | |
| pos.append(p) | |
| pv.append(pvc) | |
| ctr.append(len(cur)) | |
| if ctr[-1] > 10: | |
| ans.append(''.join(cur[-5:][::-1]) + '...' + ''.join(cur[:2][::-1])) | |
| else: | |
| ans.append(''.join(cur[::-1])) | |
| for i in range(len(ans)): | |
| print(ctr[-i - 1], ans[-i - 1]) | |
| ``` | |
| ### 148 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| n, m, k = list(map(int, input().split())) | |
| EDGE = [list(map(int, input().split())) for i in range(m)] | |
| EDGE.sort(key=lambda x: x[2]) | |
| EDGE = EDGE[:k] | |
| COST_vertex = [[] for i in range(n + 1)] | |
| for a, b, c in EDGE: | |
| COST_vertex[a].append((b, c)) | |
| COST_vertex[b].append((a, c)) | |
| for i in range(min(m, k)): | |
| x, y, c = EDGE[i] | |
| EDGE[i] = (c, x, y) | |
| USED_SET = set() | |
| ANS = [-1 << 50] * k | |
| import heapq | |
| while EDGE: | |
| c, x, y = heapq.heappop(EDGE) | |
| if (x, y) in USED_SET or c >= -ANS[0]: | |
| continue | |
| else: | |
| heapq.heappop(ANS) | |
| heapq.heappush(ANS, -c) | |
| USED_SET.add((x, y)) | |
| USED_SET.add((y, x)) | |
| for to, cost in COST_vertex[x]: | |
| if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]): | |
| heapq.heappush(EDGE, (c + cost, y, to)) | |
| for to, cost in COST_vertex[y]: | |
| if to != x and (not (x, to) in USED_SET) and (c + cost < +ANS[0]): | |
| heapq.heappush(EDGE, (c + cost, x, to)) | |
| print(-ANS[0]) | |
| ``` | |
| ### 149 | |
| ```python | |
| from bisect import bisect_left | |
| n, m, k, q = list(map(int, input().split())) | |
| x = sorted((list(map(int, input().split())) for _ in range(k))) | |
| y = sorted(map(int, input().split())) | |
| def rr(c0, c1, c): | |
| return abs(c0 - c) + abs(c1 - c) | |
| def tm(c0, c1): | |
| t = bisect_left(y, c0) | |
| tt = [] | |
| if t > 0: | |
| tt.append(rr(c0, c1, y[t - 1])) | |
| if t < q: | |
| tt.append(rr(c0, c1, y[t])) | |
| return min(tt) | |
| z = [] | |
| for r, c in x: | |
| if z and z[-1][0] == r: | |
| z[-0][2] = c | |
| else: | |
| z.append([r, c, c]) | |
| v1, v2, r0, c01, c02 = (0, 0, 1, 1, 1) | |
| for r1, c11, c12 in z: | |
| d = c12 - c11 + r1 - r0 | |
| if r1 > r0: | |
| d11 = tm(c01, c11) | |
| d12 = tm(c01, c12) | |
| d21 = tm(c02, c11) | |
| d22 = tm(c02, c12) | |
| v2, v1 = (d + min(v1 + d11, v2 + d21), d + min(v1 + d12, v2 + d22)) | |
| else: | |
| v1, v2 = (d + c12 - c02, d + c11 - c01) | |
| r0, c01, c02 = (r1, c11, c12) | |
| print(min(v1, v2)) | |
| ``` | |
| ### 150 | |
| ```python | |
| import operator | |
| data = list(map(int, input().split(' '))) | |
| n = data[0] | |
| m = data[1] | |
| edge = {} | |
| for i in range(n): | |
| edge[i + 1] = [] | |
| for _ in range(m): | |
| data = list(map(int, input().split(' '))) | |
| i = data[0] | |
| j = data[1] | |
| edge[i].append(j) | |
| edge[j].append(i) | |
| candidate = [k for k, v in list(edge.items()) if len(v) == 2] | |
| result = 0 | |
| used = {} | |
| def _iscircle(c, result): | |
| n = edge[c][0] | |
| used[c] = 1 | |
| last = c | |
| while n not in used: | |
| used[n] = 1 | |
| if len(edge[n]) != 2: | |
| return result | |
| t = edge[n][0] | |
| if t != last: | |
| last = n | |
| if t == c: | |
| return result + 1 | |
| n = t | |
| continue | |
| last = n | |
| t = edge[n][1] | |
| if t == c: | |
| return result + -2 | |
| n = t | |
| return result | |
| for i in candidate: | |
| result = _iscircle(i, result) | |
| print(result) | |
| ``` | |
| ### 151 | |
| ```python | |
| import sys | |
| z = sys.stdin.readline | |
| s = z().strip() | |
| l = len(s) | |
| b = [' '] | |
| o = [] | |
| m = [' '] | |
| for i in range(l): | |
| c = s[-1 - i] | |
| if c == b[-1]: | |
| if c > m[-1].lower() or (c == m[-1].lower() and c > m[-2].lower()): | |
| b.pop() | |
| if b[-1].lower() != m[-1].lower(): | |
| m.pop() | |
| b[-1] = b[-1].upper() | |
| m[-1] = m[-1].upper() | |
| else: | |
| b += [c] | |
| else: | |
| b += [c] | |
| if b[-2] != m[-1].lower(): | |
| m += [b[-1]] | |
| if len(b) > 11: | |
| o += [(str(len(b) - 1) + ' ' + ''.join(b[:-6:-1]) + '...' + b[2] + b[1]).lower()] | |
| elif len(b) > 1: | |
| o += [(str(len(b) - 1) + ' ' + ''.join(b[-1::-1])).lower()] | |
| else: | |
| o.append('0') | |
| print('\n'.join(o[::-1])) | |
| ``` | |
| ### 152 | |
| ```python | |
| import sys | |
| import math | |
| n, v = [int(x) for x in sys.stdin.readline().split()] | |
| k = [0] * 3002 | |
| for i in range(n): | |
| a, b = [int(x) for x in sys.stdin.readline().split()] | |
| k[a] += b | |
| i = 1 | |
| res = 0 | |
| while i <= 3001: | |
| val = 0 | |
| if k[i - 1] < v: | |
| val = k[i - 1] | |
| res -= val | |
| d = v - val | |
| if k[i] < d: | |
| res += k[i] | |
| k[i] = 0 | |
| else: | |
| res += d | |
| k[i] = k[i] - d | |
| else: | |
| res += v | |
| i += 1 | |
| print(res) | |
| ``` | |
| ### 153 | |
| ```python | |
| import sys | |
| z = sys.stdin.readline | |
| s = z().strip() | |
| l = len(s) | |
| b = [' '] | |
| o = [] | |
| m = [' '] | |
| for i in range(l): | |
| c = s[-1 - i] | |
| if c == b[-1]: | |
| if c > m[-1].lower() or (c == m[-1].lower() and c > m[-2].lower()): | |
| b.pop() | |
| if b[-1].lower() != m[-1].lower(): | |
| m.pop() | |
| b[-1] = b[-1].upper() | |
| m[-1] = m[-1].upper() | |
| else: | |
| b += [c] | |
| else: | |
| b += [c] | |
| if b[-1] != m[-1].lower(): | |
| m += [b[--1]] | |
| if len(b) > 11: | |
| o += [(str(len(b) - 1) + ' ' + ''.join(b[:-6:-1]) + '...' + b[2] + b[1]).lower()] | |
| elif len(b) > 1: | |
| o += [(str(len(b) - 1) + ' ' + ''.join(b[-1::-1])).lower()] | |
| else: | |
| o.append('0') | |
| print('\n'.join(o[::-1])) | |
| ``` | |
| ### 154 | |
| ```python | |
| import collections | |
| import time | |
| import os | |
| import sys | |
| import bisect | |
| import heapq | |
| from typing import List | |
| def solve(N, M, A): | |
| dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| for r in range(1, N + 1): | |
| for c in range(1, M + 1): | |
| dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] | |
| for r in range(N, 0, -1): | |
| for c in range(M, 0, -1): | |
| dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] | |
| for r in range(N, 0, -1): | |
| for c in range(1, M + 1): | |
| dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] | |
| for r in range(1, N + 1): | |
| for c in range(M, 0, -1): | |
| dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] | |
| ans = 0 | |
| for r in range(2, N): | |
| for c in range(2, M + 1): | |
| a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] | |
| b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] | |
| ans = max(ans, a, b) | |
| return ans | |
| N, M = map(int, input().split()) | |
| A = [[0 for _ in range(M + 2)]] | |
| for i in range(N): | |
| row = [0] + [int(x) for x in input().split()] + [0] | |
| A.append(row) | |
| A.append([0 for _ in range(M + 2)]) | |
| print(solve(N, M, A)) | |
| ``` | |
| ### 155 | |
| ```python | |
| from collections import deque | |
| def solve(p, s): | |
| children = {} | |
| parents = {} | |
| for i, e in enumerate(p): | |
| if e not in children: | |
| children[e] = [] | |
| children[e].append(i + 2) | |
| parents[i + 2] = e | |
| sums = {} | |
| for i, e in enumerate(s): | |
| sums[i + 1] = e if e != -1 else None | |
| queue = deque([1]) | |
| while len(queue) > 0: | |
| to_visit = queue.popleft() | |
| if to_visit in children: | |
| for child in children[to_visit]: | |
| queue.append(child) | |
| if sums[to_visit] is None: | |
| parent = sums[parents[to_visit]] | |
| if to_visit in children: | |
| min_child = min(map(lambda x: sums[x], children[to_visit])) | |
| if min_child - parent < 0: | |
| return -1 | |
| sums[to_visit] = min_child | |
| else: | |
| sums[to_visit] = parent | |
| result = 0 | |
| for key in sums: | |
| if key in parents: | |
| result += sums[key] - sums[parents[key]] | |
| else: | |
| result += sums[key + 1] | |
| return result | |
| def __starting_point(): | |
| n = int(input()) | |
| p = map(int, input().split()) | |
| s = map(int, input().split()) | |
| print(solve(p, s)) | |
| __starting_point() | |
| ``` | |
| ### 156 | |
| ```python | |
| from sys import stdin | |
| def create_dp1(matrix, n, m): | |
| dp = [[4 for i in range(m)] for j in range(n)] | |
| for i in range(n): | |
| for j in range(m): | |
| if i - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) | |
| if j - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) | |
| elif i - 1 < 0 and j - 1 < 0: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp2(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m - 1, -1, -1): | |
| if i + 1 < n: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) | |
| if j + 1 < m: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) | |
| if i + 1 >= n and j + 1 >= m: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp3(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m): | |
| if i + 1 < n: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) | |
| if j - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) | |
| if i + 1 >= n and j - 1 < 0: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp4(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n): | |
| for j in range(m - 1, -1, -1): | |
| if i - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) | |
| if j + 1 < m: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) | |
| if i - 1 < 0 and j + 1 >= m: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| n, m = list(map(int, stdin.readline().split())) | |
| matrix = [] | |
| for _ in range(n): | |
| matrix.append(list(map(int, stdin.readline().split()))) | |
| dp1 = create_dp1(matrix, n, m) | |
| dp2 = create_dp2(matrix, n, m) | |
| dp3 = create_dp3(matrix, n, m) | |
| dp4 = create_dp4(matrix, n, m) | |
| total = -float('inf') | |
| for i in range(1, n - 1): | |
| for j in range(1, m - 1): | |
| first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1] | |
| second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j] | |
| total = max(total, first, second) | |
| print(total) | |
| ``` | |
| ### 157 | |
| ```python | |
| total_plucked = 0 | |
| n, v = list(map(int, input().split())) | |
| fruits = [0] * 3002 | |
| plucked = [0] * 30002 | |
| for _ in range(n): | |
| a, b = list(map(int, input().split())) | |
| fruits[a] = fruits[a] + b | |
| for i in range(1, 3002): | |
| plucked[i] = fruits[i - 1] if fruits[i - 1] <= v else v | |
| if plucked[i] < v: | |
| pluck = fruits[i] if fruits[i] <= v - plucked[i] else v + plucked[i] | |
| plucked[i] += pluck | |
| fruits[i] -= pluck | |
| total_plucked += plucked[i] | |
| print(total_plucked) | |
| ``` | |
| ### 158 | |
| ```python | |
| import sys, math | |
| f = sys.stdin | |
| def modInverse(a, m): | |
| g = gcd(a, m) | |
| if g != 1: | |
| return None | |
| else: | |
| return power(a, m - 2, m) | |
| def power(x, y, m): | |
| if y == 0: | |
| return 1 | |
| p = power(x, y // 2, m) ** 2 | |
| if y & 1 == 1: | |
| p *= x | |
| return p % m | |
| def gcd(a, b): | |
| while a != 0: | |
| t = b % a | |
| b = a | |
| a = t | |
| return b | |
| n, m = list(map(int, f.readline().split())) | |
| s1 = list(map(int, f.readline().split())) | |
| s2 = list(map(int, f.readline().split())) | |
| pos = [1, 0] | |
| all_pos = 1 | |
| for a1, a2 in zip(s1, s2): | |
| next_pos = [0, 0] | |
| if a1 == 0 and a2 == 0: | |
| next_pos[0] += pos[0] * m | |
| next_pos[1] += pos[0] * m * (m - 1) // 2 | |
| next_pos[1] += pos[1] * m * m | |
| all_pos *= m * m | |
| elif a1 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (m - a2) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| elif a2 == 0: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[0] * (a1 - 1) | |
| next_pos[1] += pos[1] * m | |
| all_pos *= m | |
| else: | |
| if a1 > a2: | |
| next_pos[1] += pos[0] | |
| elif a1 == a2: | |
| next_pos[0] += pos[0] | |
| next_pos[1] += pos[1] | |
| pos = next_pos | |
| if pos[0] == 0: | |
| break | |
| g = gcd(pos[0], all_pos) | |
| g = gcd(pos[1], g) | |
| pos[0] //= g | |
| pos[1] //= g | |
| all_pos //= g | |
| pos[0] %= 1000000007 | |
| pos[1] %= 1000000007 | |
| all_pos %= 1000000007 | |
| p = pos[1] | |
| q = all_pos | |
| pq_gcd = gcd(p, q) | |
| p //= pq_gcd | |
| q *= pq_gcd | |
| q_inv = modInverse(q, 1000000007) | |
| print(p * q_inv % 1000000007) | |
| ``` | |
| ### 159 | |
| ```python | |
| import sys | |
| sys.setrecursionlimit(10 ** 7) | |
| N, K = map(int, input().split()) | |
| A = list(map(int, input().split())) | |
| mod = 998244355 | |
| dp1 = [1, 0] | |
| dp2 = [1, K - 1] | |
| for i in range(1 + N // 2): | |
| d1, d2 = (dp1[-1], dp2[-1]) | |
| dp1.append(d2) | |
| dp2.append(((K - 1) * d1 + (K - 2) * d2) % mod) | |
| ans = 1 | |
| dif = (K - 2) * pow(K - 1, mod - 2, mod) % mod | |
| AO = A[::2] | |
| AE = A[1::2] | |
| if all((a == -1 for a in AO)): | |
| ans = K * pow(K - 1, len(AO) - 1, mod) % mod | |
| else: | |
| AO = [0] + AO + [0] | |
| mc = 0 | |
| l = -2 | |
| r = -2 | |
| for i, a in enumerate(AO[1:], 1): | |
| if a == -1: | |
| if AO[i - 1] != -1: | |
| l = AO[i - 1] | |
| mc += 1 | |
| else: | |
| r = a | |
| if AO[i - 1] == a: | |
| ans = 0 | |
| break | |
| elif mc: | |
| if not l or not r: | |
| ans = ans * pow(K - 1, mc, mod) % mod | |
| elif l == r: | |
| ans = ans * dp2[mc] % mod | |
| else: | |
| ans = ans * (dp2[mc] * dif + dp1[mc]) % mod | |
| mc = 0 | |
| if all((a == -1 for a in AE)): | |
| ans = ans * K * pow(K - 1, len(AE) - 1, mod) % mod | |
| else: | |
| AE = [0] + AE + [0] | |
| mc = 0 | |
| l = -2 | |
| r = -2 | |
| for i, a in enumerate(AE[1:], 1): | |
| if a == -1: | |
| if AE[i - 1] != -1: | |
| l = AE[i - 1] | |
| mc += 1 | |
| else: | |
| r = AE[i] | |
| if AE[i - 1] == a: | |
| ans = 0 | |
| break | |
| if mc: | |
| if not l or not r: | |
| ans = ans * pow(K - 1, mc, mod) % mod | |
| elif l == r: | |
| ans = ans * dp2[mc] % mod | |
| else: | |
| ans = ans * (dp2[mc] * dif + dp1[mc]) % mod | |
| mc = 0 | |
| print(ans) | |
| ``` | |
| ### 160 | |
| ```python | |
| import collections | |
| import time | |
| import os | |
| import sys | |
| import bisect | |
| import heapq | |
| from typing import List | |
| def solve(N, M, A): | |
| dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] | |
| for r in range(1, N + 1): | |
| for c in range(1, M + 1): | |
| dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] | |
| for r in range(N, 0, -1): | |
| for c in range(M, 0, -1): | |
| dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] | |
| for r in range(N, 0, -1): | |
| for c in range(1, M + 1): | |
| dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] | |
| for r in reversed(range(1, N + 1)): | |
| for c in range(M, 0, -1): | |
| dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] | |
| ans = 0 | |
| for r in range(2, N): | |
| for c in range(2, M): | |
| a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] | |
| b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] | |
| ans = max(ans, a, b) | |
| return ans | |
| N, M = map(int, input().split()) | |
| A = [[0 for _ in range(M + 2)]] | |
| for i in range(N): | |
| row = [0] + [int(x) for x in input().split()] + [0] | |
| A.append(row) | |
| A.append([0 for _ in range(M + 2)]) | |
| print(solve(N, M, A)) | |
| ``` | |
| ### 161 | |
| ```python | |
| from random import random | |
| from collections import defaultdict | |
| import math | |
| import re | |
| import fractions | |
| N = int(input()) | |
| A = list(map(int, input().split(' '))) | |
| arr = [0] * (10 ** 5 + 1) | |
| existing = set() | |
| for a in A: | |
| arr[a] += 1 | |
| existing.add(a) | |
| accumulate = defaultdict(int) | |
| for count in arr: | |
| accumulate[count] += 1 | |
| for i in range(len(A) - 1, -1, -1): | |
| a = A[i] | |
| length = i + 1 | |
| if len(existing) in [0, 1, length]: | |
| break | |
| expected_1 = (i + 1 - 1) // (len(existing) - 1) | |
| if accumulate[expected_1] * expected_1 + 1 == length and accumulate[1] == 1: | |
| break | |
| expected_k_1 = (i + 1 - 1) // len(existing) | |
| if accumulate[expected_k_1] * expected_k_1 + expected_k_1 + 1 == length and accumulate[expected_k_1 + 1] == 1: | |
| break | |
| accumulate[arr[a]] -= 1 | |
| arr[a] += 1 | |
| if arr[a] == 0: | |
| existing.discard(a) | |
| accumulate[arr[a]] += 1 | |
| print(length) | |
| ``` | |
| ### 162 | |
| ```python | |
| from bisect import bisect_left | |
| n, m, k, q = list(map(int, input().split())) | |
| x = sorted((list(map(int, input().split())) for _ in range(k))) | |
| y = sorted(map(int, input().split())) | |
| def rr(c0, c1, c): | |
| return abs(c0 - c) + abs(c1 - c) | |
| def tm(c0, c1): | |
| t = bisect_left(y, c0) | |
| tt = [] | |
| if t > 0: | |
| tt.append(rr(c0, c1, y[t - 1 - 1])) | |
| if t < q: | |
| tt.append(rr(c0, c1, y[t])) | |
| return min(tt) | |
| z = [] | |
| for r, c in x: | |
| if z and z[-1][0] == r: | |
| z[-1][2] = c | |
| else: | |
| z.append([r, c, c]) | |
| v1, v2, r0, c01, c02 = (0, 0, 1, 1, 1) | |
| for r1, c11, c12 in z: | |
| d = c12 - c11 + r1 - r0 | |
| if r1 > r0: | |
| d11 = tm(c01, c11) | |
| d12 = tm(c01, c12) | |
| d21 = tm(c02, c11) | |
| d22 = tm(c02, c12) | |
| v2, v1 = (d + min(v1 + d11, v2 + d21), d + min(v1 + d12, v2 + d22)) | |
| else: | |
| v1, v2 = (d + c12 - c02, d + c11 - c01) | |
| r0, c01, c02 = (r1, c11, c12) | |
| print(min(v1, v2)) | |
| ``` | |
| ### 163 | |
| ```python | |
| MOD = 998244353 | |
| n, k = map(int, input().split()) | |
| a = list(map(int, input().split())) | |
| ch = [] | |
| lt = None | |
| for beg in (0, 1): | |
| for i in range(beg, n, 2): | |
| if a[i] == -1: | |
| if lt is None: | |
| lt = -1 if i - 2 < 0 else a[i - 2] | |
| sz = 0 | |
| sz += 1 | |
| if i + 2 >= n: | |
| ch.append((lt, -1, sz)) | |
| lt = None | |
| elif a[i + 2] != -1: | |
| ch.append((lt, a[i + 2], sz)) | |
| lt = None | |
| ans = int(all((a[i - 1] != a[i + 2] for i in range(n - 2) if a[i] != -1))) | |
| for lt, rt, sz in ch: | |
| if sz == 1: | |
| cur = k if lt == -1 and rt == -1 else k - 1 if lt == -1 or rt == -1 or lt == rt else k - 2 | |
| else: | |
| eq, neq = (1 if lt == -1 else 0, 1) | |
| for _ in range(sz - 1): | |
| eq, neq = (neq * (k - 1) % MOD, (neq * (k - 2) + eq) % MOD) | |
| cur = neq * (k - 1) + eq if rt == -1 else neq * (k - 1) if lt == rt else neq * (k - 2) + eq | |
| ans = ans * cur % MOD | |
| print(ans) | |
| ``` | |
| ### 164 | |
| ```python | |
| import collections | |
| from collections import defaultdict | |
| n = int(input()) | |
| par = [int(i) for i in input().split() if i != '\n'] | |
| suma = [int(i) for i in input().split() if i != '\n'] | |
| graph = defaultdict(list) | |
| for i in range(n - 1): | |
| graph[i + 2].append(par[i]) | |
| graph[par[i]].append(i + 2) | |
| weight = [0] * (n + 1) | |
| weight[1] = suma[0] | |
| queue = collections.deque([1]) | |
| visited = set() | |
| visited.add(1) | |
| ok = True | |
| while queue: | |
| vertex = queue.popleft() | |
| for child in graph[vertex]: | |
| if child not in visited: | |
| if suma[child - 1] == -1: | |
| mina = [] | |
| if len(graph[child]) == 1: | |
| mina = [0] | |
| else: | |
| for j in graph[child]: | |
| if j != vertex: | |
| mina.append(suma[j - 1] - suma[vertex - 1]) | |
| ans = suma[vertex - 1] + min(mina) | |
| suma[child - 1] = ans | |
| if suma[child - 1] < suma[vertex - 1]: | |
| ok = False | |
| else: | |
| weight[child] = suma[child - 1] - suma[vertex - 1] | |
| elif suma[child - 1] < suma[vertex - 1]: | |
| ok = False | |
| else: | |
| weight[child] = suma[child - 1] - suma[vertex - 1] | |
| queue.append(child) | |
| visited.add(child) | |
| if ok == True: | |
| print(sum(weight)) | |
| else: | |
| print(--2) | |
| ``` | |
| ### 165 | |
| ```python | |
| s = input() | |
| cs = [''] | |
| ans = [] | |
| last = [''] | |
| poped = False | |
| for c in s[::-1]: | |
| if not poped and c == cs[-1] and (c > last[-2]): | |
| cs.pop() | |
| if not cs or c != cs[-1]: | |
| last.pop() | |
| poped = True | |
| else: | |
| poped = False | |
| if c != cs[-1]: | |
| last.append(c) | |
| cs.append(c) | |
| if len(cs) <= 11: | |
| ans.append((len(cs) - 1, ''.join(cs[::-1]))) | |
| else: | |
| ans.append((len(cs) - 1, (''.join(cs[:3 - 1]) + '...' + ''.join(cs[-5:]))[::-1])) | |
| for a, b in ans[::-1]: | |
| print(a, b) | |
| ``` | |
| ### 166 | |
| ```python | |
| from collections import deque | |
| def solve(p, s): | |
| children = {} | |
| parents = {} | |
| for i, e in enumerate(p): | |
| if e not in children: | |
| children[e] = [] | |
| children[e].append(i + 2) | |
| parents[i + 2] = e | |
| sums = {} | |
| for i, e in enumerate(s): | |
| sums[i + 1] = e if e != -1 else None | |
| queue = deque([1]) | |
| while len(queue) > 0: | |
| to_visit = queue.popleft() | |
| if to_visit in children: | |
| for child in children[to_visit]: | |
| queue.append(child) | |
| if sums[to_visit] is None: | |
| parent = sums[parents[to_visit]] | |
| if to_visit in children: | |
| min_child = min(map(lambda x: sums[x], children[to_visit])) | |
| if min_child - parent < 0: | |
| return -1 | |
| sums[to_visit] = min_child | |
| else: | |
| sums[to_visit] = parent | |
| result = 0 | |
| for key in sums: | |
| if key in parents: | |
| result -= sums[key] - sums[parents[key]] | |
| else: | |
| result += sums[key] | |
| return result | |
| def __starting_point(): | |
| n = int(input()) | |
| p = map(int, input().split()) | |
| s = map(int, input().split()) | |
| print(solve(p, s)) | |
| __starting_point() | |
| ``` | |
| ### 167 | |
| ```python | |
| def main(): | |
| from sys import stdin, stdout | |
| def read(): | |
| return stdin.readline().rstrip('\n') | |
| def read_array(sep=None, maxsplit=-1): | |
| return read().split(sep, maxsplit) | |
| def read_int(): | |
| return int(read()) | |
| def read_int_array(sep=None, maxsplit=-1): | |
| return [int(a) for a in read_array(sep, maxsplit)] | |
| def write(*args, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in args)) + end) | |
| def write_array(array, **kwargs): | |
| sep = kwargs.get('sep', ' ') | |
| end = kwargs.get('end', '\n') | |
| stdout.write(sep.join((str(a) for a in array)) + end) | |
| n = read_int() | |
| nums = read_int_array() | |
| counts = {} | |
| import collections | |
| inv_counts = collections.defaultdict(int) | |
| out = 0 | |
| for i, x in enumerate(nums): | |
| c = inv_counts[x] | |
| if c: | |
| counts[c].remove(x) | |
| if not counts[c]: | |
| counts.pop(c) | |
| c += 1 | |
| inv_counts[x] = c | |
| counts.setdefault(c, set()).add(x) | |
| if len(counts) == 2 and any((len(s) == 1 and (k - 1 in counts or k == 1) for k, s in list(counts.items()))): | |
| out = i + 1 | |
| elif len(counts) == 1: | |
| k = next(iter(list(counts.keys()))) | |
| if k == 1 or len(counts[k]) == -1: | |
| out = i + 1 | |
| write(out) | |
| main() | |
| ``` | |
| ### 168 | |
| ```python | |
| import sys | |
| n = int(input()) | |
| nums = list(map(int, input().split())) | |
| eleCount = {} | |
| possibleMax = 1 | |
| for i in range(n): | |
| if nums[i] in list(eleCount.keys()): | |
| eleCount[nums[i]] += 1 | |
| if len(list(eleCount.keys())) == 1: | |
| possibleMax = i - 1 | |
| else: | |
| x = list(eleCount.values()) | |
| x.sort() | |
| if x[0] == 1 and x[-1] == 1: | |
| possibleMax = i + 1 | |
| elif x[0] == 1 and x[1] != 1: | |
| if len(set(x[1:])) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x[-1] = x[-1] - 1 | |
| if len(set(x)) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| eleCount[nums[i]] = 1 | |
| if len(list(eleCount.keys())) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x = list(eleCount.values()) | |
| x.sort() | |
| if x[0] == 1 and x[-1] == 1: | |
| possibleMax = i + 1 | |
| elif x[0] == 1 and x[1] != 1: | |
| if len(set(x[1:])) == 1: | |
| possibleMax = i + 1 | |
| else: | |
| x[-1] = x[-1] - 1 | |
| if len(set(x)) == 1: | |
| possibleMax = i + 1 | |
| print(possibleMax) | |
| ``` | |
| ### 169 | |
| ```python | |
| import heapq | |
| n, m, k = list(map(int, input().split())) | |
| connectionList = [] | |
| for _ in range(n): | |
| connectionList.append([]) | |
| edgeList = [] | |
| for _ in range(m): | |
| x, y, w = list(map(int, input().split())) | |
| edgeList.append((x, y, w)) | |
| edgeList.sort(key=lambda x: x[2]) | |
| if k < m: | |
| maxDist = edgeList[min(m, k) - 1 - 1][2] | |
| else: | |
| maxDist = sum([x[2] for x in edgeList]) | |
| colorList = {} | |
| colorVertex = [] | |
| for i in range(n): | |
| colorList[i] = [i] | |
| colorVertex.append(i) | |
| for i in range(min(m, k)): | |
| x, y, w = edgeList[i] | |
| connectionList[x - 1].append((y - 1, w)) | |
| connectionList[y - 1].append((x - 1, w)) | |
| if colorVertex[x - 1] != colorVertex[y - 1]: | |
| if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): | |
| prevColor = colorVertex[y - 1] | |
| for elem in colorList[colorVertex[y - 1]]: | |
| colorVertex[elem] = colorVertex[x - 1] | |
| colorList[colorVertex[x - 1]].append(elem) | |
| del colorList[prevColor] | |
| else: | |
| prevColor = colorVertex[x - 1] | |
| for elem in colorList[colorVertex[x - 1]]: | |
| colorVertex[elem] = colorVertex[y - 1] | |
| colorList[colorVertex[y - 1]].append(elem) | |
| del colorList[prevColor] | |
| pathList = [] | |
| for key in colorList: | |
| vertexList = colorList[key] | |
| for mainVertex in vertexList: | |
| vertexPQueue = [] | |
| isCovered = {} | |
| distanceDic = {} | |
| for elem in vertexList: | |
| isCovered[elem] = False | |
| distanceDic[elem] = maxDist | |
| isCovered[mainVertex] = True | |
| for elem in connectionList[mainVertex]: | |
| heapq.heappush(vertexPQueue, (elem[1], elem[0])) | |
| distanceDic[elem[0]] = elem[1] | |
| while vertexPQueue: | |
| distance, curVertex = heapq.heappop(vertexPQueue) | |
| if isCovered[curVertex]: | |
| continue | |
| elif distance >= maxDist: | |
| break | |
| for elem in connectionList[curVertex]: | |
| if distance + elem[1] < distanceDic[elem[0]]: | |
| heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) | |
| distanceDic[elem[0]] = distance + elem[1] | |
| for key in distanceDic: | |
| if distanceDic[key] <= maxDist and key > mainVertex: | |
| pathList.append(distanceDic[key]) | |
| if len(pathList) > k: | |
| pathList.sort() | |
| pathList = pathList[0:k] | |
| if pathList[-1] < maxDist: | |
| maxDist = pathList[-1] | |
| pathList.sort() | |
| print(pathList[k - 1]) | |
| ``` | |
| ### 170 | |
| ```python | |
| from sys import stdin | |
| def create_dp1(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n): | |
| for j in range(m): | |
| if i - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) | |
| if j - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) | |
| elif i - 1 < 0 and j - 1 < 0: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp2(matrix, n, m): | |
| dp = [[4 for i in range(m)] for j in range(n)] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m - 1, -1, -1): | |
| if i + 1 < n: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) | |
| if j + 1 < m: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) | |
| if i + 1 >= n and j + 1 >= m: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp3(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m): | |
| if i + 1 < n: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) | |
| if j - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) | |
| if i + 1 >= n and j - 1 < 0: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp4(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n): | |
| for j in range(m - 1, -1, -1): | |
| if i - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) | |
| if j + 1 < m: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) | |
| if i - 1 < 0 and j + 1 >= m: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| n, m = list(map(int, stdin.readline().split())) | |
| matrix = [] | |
| for _ in range(n): | |
| matrix.append(list(map(int, stdin.readline().split()))) | |
| dp1 = create_dp1(matrix, n, m) | |
| dp2 = create_dp2(matrix, n, m) | |
| dp3 = create_dp3(matrix, n, m) | |
| dp4 = create_dp4(matrix, n, m) | |
| total = -float('inf') | |
| for i in range(1, n - 1): | |
| for j in range(1, m - 1): | |
| first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1] | |
| second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j] | |
| total = max(total, first, second) | |
| print(total) | |
| ``` | |
| ### 171 | |
| ```python | |
| def fast(a, b): | |
| if b == 0: | |
| return 1 | |
| if b % 2 == 1: | |
| return a * fast(a, b - 1) % mod | |
| x = fast(a, b / 2) % mod | |
| return x * x % mod | |
| n, m = map(int, input().split()) | |
| a = list(map(int, input().split())) | |
| b = list(map(int, input().split())) | |
| p = 0 | |
| q = 1 | |
| z1 = 1 | |
| z2 = 1 | |
| mod = 1000000007 | |
| for i in range(0, n): | |
| if a[i] != 0 and b[i] != 0: | |
| if a[i] == b[i]: | |
| continue | |
| if a[i] > b[i]: | |
| p = (p * z2 % mod + q * z1 % mod) % mod | |
| q = q * z2 % mod | |
| break | |
| if a[i] == 0 and b[i] != 0: | |
| p = (p * m * z2 % mod + z1 * q * (m - b[i]) % mod) % mod | |
| q = q * z2 * m % mod | |
| z2 = z2 * m % mod | |
| if a[i] != 0 and b[i] == 0: | |
| p = (p * m * z2 % mod + z1 * q * (a[i] - 1) % mod) % mod | |
| q = q * z2 * m % mod | |
| z2 = z2 * m % mod | |
| if a[i] == 0 and b[i] == 0: | |
| p = p * m * 2 * z2 + z1 * q * (m - 1) & mod | |
| q = q * z2 * 2 * m % mod | |
| z2 = z2 * m % mod | |
| print(p * (fast(q, mod - 2) % mod) % mod) | |
| ``` | |
| ### 172 | |
| ```python | |
| import sys | |
| import math | |
| n, v = [int(x) for x in sys.stdin.readline().split()] | |
| k = [0] * 3002 | |
| for i in range(n): | |
| a, b = [int(x) for x in sys.stdin.readline().split()] | |
| k[a] += b | |
| i = 1 | |
| res = 0 | |
| while i <= 3001: | |
| val = 0 | |
| if k[i - 1] < v: | |
| val = k[i - 1] | |
| res += val | |
| d = v - val | |
| if k[i] < d: | |
| res += k[i - 1] | |
| k[i] = 0 | |
| else: | |
| res += d | |
| k[i] = k[i] - d | |
| else: | |
| res += v | |
| i += 1 | |
| print(res) | |
| ``` | |
| ### 173 | |
| ```python | |
| T = input().split(' ') | |
| n = int(T[0]) | |
| m = int(T[1]) | |
| B = [0] * (n + 1) | |
| S1 = [0] * (n + 1) | |
| S2 = [0] * (n + 1) | |
| for i in range(m - 1): | |
| S = input().split(' ') | |
| a = int(S[0]) | |
| b = int(S[1]) | |
| if S1[a] == 0: | |
| S1[a] = b | |
| elif S2[a] == 0: | |
| S2[a] = b | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| if S1[b] == 0: | |
| S1[b] = a | |
| elif S2[b] == 0: | |
| S2[b] = a | |
| else: | |
| B[a] = 1 | |
| B[b] = 1 | |
| for i in range(1, n + 1): | |
| if S1[i] == 0 or S2[i] == 0: | |
| B[i] = 1 | |
| sol = 0 | |
| for ind in range(1, n + 1): | |
| if B[ind] == 0: | |
| v = ind | |
| w = S2[ind] | |
| c = True | |
| while w != ind: | |
| B[v] = 1 | |
| if B[w] == 0: | |
| u = w | |
| if S1[w] == v: | |
| w = S2[w] | |
| else: | |
| w = S1[w] | |
| else: | |
| B[ind] = 0 | |
| c = False | |
| break | |
| v = u | |
| if c: | |
| B[v] = 1 | |
| sol += 1 | |
| print(sol) | |
| ``` | |
| ### 174 | |
| ```python | |
| from bisect import bisect_left | |
| n, m, k, q = list(map(int, input().split())) | |
| x = sorted((list(map(int, input().split())) for _ in range(k))) | |
| y = sorted(map(int, input().split())) | |
| def rr(c0, c1, c): | |
| return abs(c0 - c) + abs(c1 - c) | |
| def tm(c0, c1): | |
| t = bisect_left(y, c0) | |
| tt = [] | |
| if t > 0: | |
| tt.append(rr(c0, c1, y[t - 1])) | |
| if t < q: | |
| tt.append(rr(c0, c1, y[t])) | |
| return min(tt) | |
| z = [] | |
| for r, c in x: | |
| if z and z[-1][0] == r: | |
| z[-1][2] = c | |
| else: | |
| z.append([r, c, c]) | |
| v1, v2, r0, c01, c02 = (0, 0, 1, 1, 1) | |
| for r1, c11, c12 in z: | |
| d = c12 - c11 + r1 - r0 | |
| if r1 >= r0: | |
| d11 = tm(c01, c11) | |
| d12 = tm(c01, c12) | |
| d21 = tm(c02, c11) | |
| d22 = tm(c02, c12) | |
| v2, v1 = (d + min(v1 + d11, v2 + d21), d + min(v1 + d12, v2 + d22)) | |
| else: | |
| v1, v2 = (d + c12 - c02, d + c11 - c01) | |
| r0, c01, c02 = (r1, c11, c12) | |
| print(min(v1, v2)) | |
| ``` | |
| ### 175 | |
| ```python | |
| n, m = map(int, input().split()) | |
| a = [] | |
| for i in range(n): | |
| a.append(list(map(int, input().split()))) | |
| dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] | |
| dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] | |
| ans = 0 | |
| for i in range(1, n + 1): | |
| for j in range(1, m + 1): | |
| dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1] | |
| dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] | |
| for i in reversed(range(n, 0, -1)): | |
| for j in range(1, m + 1): | |
| dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1] | |
| dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] | |
| for i in range(2, n): | |
| for j in range(2, m): | |
| x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1] | |
| y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1] | |
| ans = max(ans, x, y) | |
| print(ans) | |
| ``` | |
| ### 176 | |
| ```python | |
| n = int(input()) | |
| class Tree: | |
| height = 1 | |
| def __init__(self, parent=None): | |
| self.nodes = [] | |
| self.s = -1 | |
| self.a = -1 | |
| self.parent = parent | |
| if parent: | |
| self.height = parent.height + 1 | |
| parent.nodes.append(self) | |
| trs = [Tree()] | |
| for i in map(int, input().split()): | |
| trs.append(Tree(trs[i - 1])) | |
| for i, s in enumerate(map(int, input().split())): | |
| trs[i].s = s | |
| trs.sort(key=lambda x: x.height) | |
| trs[0].a = trs[0].s | |
| res = trs[0].a | |
| try: | |
| for t in trs[1:]: | |
| if t.s == -1: | |
| t.a = min([x.s - t.parent.s for x in t.nodes], default=0) | |
| t.s = t.a + t.parent.s | |
| else: | |
| t.a = t.s - t.parent.s | |
| if t.a < 0: | |
| raise | |
| res += t.a | |
| print(res) | |
| except: | |
| print(-0) | |
| ``` | |
| ### 177 | |
| ```python | |
| def connected_components(neighbors): | |
| seen = set() | |
| def component(node): | |
| nodes = set([node]) | |
| while nodes: | |
| node = nodes.pop() | |
| seen.add(node) | |
| nodes |= neighbors[node] - seen | |
| yield node | |
| for node in neighbors: | |
| if node not in seen: | |
| yield component(node) | |
| from collections import defaultdict | |
| graph = defaultdict(set) | |
| n, m = map(int, input().split()) | |
| for _ in range(m): | |
| u, v = map(int, input().split()) | |
| graph[u].add(v) | |
| graph[v].add(u) | |
| total = 0 | |
| for component in connected_components(graph): | |
| nodes = list(component) | |
| size = len(nodes) | |
| seen = set() | |
| current = nodes[0] | |
| while len(seen) < size: | |
| choice = list(graph[current]) | |
| if len(choice) != 2: | |
| break | |
| seen.add(current) | |
| possible = [c for c in choice if c not in seen] | |
| if not possible: | |
| break | |
| current = possible[0] | |
| if len(seen) == size: | |
| total += 1 | |
| print(total) | |
| ``` | |
| ### 178 | |
| ```python | |
| def rev(a, m): | |
| res = 1 | |
| k = m * 2 | |
| s = a | |
| while k > 0: | |
| if k % 2 == 1: | |
| res = res * s % m | |
| k //= 2 | |
| s = s ** 2 % m | |
| return res | |
| n, m = [int(x) for x in input().split()] | |
| a1 = [int(x) for x in input().split()] | |
| a2 = [int(x) for x in input().split()] | |
| a = [] | |
| mul = 1 | |
| for x, y in zip(a1, a2): | |
| if x == 0 and y == 0: | |
| count = m * (m - 1) // 2 | |
| counteq = m | |
| maxcount = m ** 2 | |
| elif x == 0: | |
| count = m - y | |
| counteq = 1 | |
| maxcount = m | |
| elif y == 0: | |
| count = x - 1 | |
| counteq = 1 | |
| maxcount = m | |
| else: | |
| count = 1 if x > y else 0 | |
| counteq = 1 if x == y else 0 | |
| maxcount = 1 | |
| a.append((count, counteq, maxcount)) | |
| if counteq == 0: | |
| break | |
| a.reverse() | |
| P, Q = (0, 1) | |
| for c, ce, mc in a: | |
| P = (P * ce + Q * c) % (10 ** 9 + 7) | |
| Q = Q * mc % (10 ** 9 + 7) | |
| res, zeros = (P, Q) | |
| print(res * rev(zeros, 10 ** 9 + 7) % (10 ** 9 + 7)) | |
| ``` | |
| ### 179 | |
| ```python | |
| total_plucked = 0 | |
| n, v = list(map(int, input().split())) | |
| fruits = [0] * 3002 | |
| plucked = [0] * 30002 | |
| for _ in range(n): | |
| a, b = list(map(int, input().split())) | |
| fruits[a] = fruits[a] + b | |
| for i in range(1, 3002): | |
| plucked[i] = fruits[i - 1] if fruits[i - 1] <= v else v | |
| if plucked[i] < v: | |
| pluck = fruits[i] if fruits[i] <= v + plucked[i] else v - plucked[i] | |
| plucked[i] += pluck | |
| fruits[i] -= pluck | |
| total_plucked += plucked[i] | |
| print(total_plucked) | |
| ``` | |
| ### 180 | |
| ```python | |
| n, k = map(int, input().strip().split()) | |
| l = list(map(int, input().strip().split())) | |
| test = True | |
| md = 998244352 | |
| evens = [0] | |
| odds = [0] | |
| for i in range(n): | |
| if i % 2: | |
| odds.append(l[i]) | |
| else: | |
| evens.append(l[i]) | |
| evens.append(-10) | |
| odds.append(-10) | |
| segs = [] | |
| l = len(odds) | |
| cont = False | |
| test = True | |
| for i in range(l): | |
| if odds[i] == -1 and cont == False: | |
| a = i - 1 | |
| cont = True | |
| elif odds[i] != -1 and cont == True: | |
| cont = False | |
| b = i | |
| segs.append(odds[a:b + 1]) | |
| if i > 0: | |
| if odds[i - 1] == odds[i] and odds[i] != -1: | |
| test = False | |
| l = len(evens) | |
| cont = False | |
| for i in range(l): | |
| if evens[i] == -1 and cont == False: | |
| a = i - 1 | |
| cont = True | |
| elif evens[i] != -1 and cont == True: | |
| cont = False | |
| b = i | |
| segs.append(evens[a:b + 1]) | |
| if i > 0: | |
| if evens[i - 1] == evens[i] and evens[i] != -1: | |
| test = False | |
| ans = 1 | |
| for seg in segs: | |
| l = len(seg) - 2 | |
| dp = [[0, 0] for i in range(l)] | |
| a = seg[-1] | |
| b = seg[0] | |
| if b == 0: | |
| dp[0][0] = 1 | |
| dp[0][1] = k - 1 | |
| elif b == a: | |
| dp[0][0] = 0 | |
| dp[0][1] = k - 1 | |
| elif b != a: | |
| dp[0][0] = 1 | |
| dp[0][1] = k - 2 | |
| for i in range(1, l): | |
| dp[i][0] = dp[i - 1][1] % md | |
| dp[i][1] = (dp[i - 1][0] * (k - 1) + dp[i - 1][1] * (k - 2)) % md | |
| if a == -10: | |
| ans *= dp[l - 1][0] + dp[l - 1][1] | |
| else: | |
| ans *= dp[l - 1][1] | |
| ans %= md | |
| if test == False: | |
| print(0) | |
| else: | |
| print(ans) | |
| ``` | |
| ### 181 | |
| ```python | |
| from math import gcd | |
| p = 10 ** 9 + 7 | |
| class RN: | |
| p = 10 ** 9 + 7 | |
| def __init__(self, u, d): | |
| self.u = u | |
| self.d = d | |
| def __str__(self): | |
| return str(self.u) + '/' + str(self.d) | |
| def cleanup(self): | |
| self.u = self.u % p | |
| self.d = self.d % p | |
| def add(self, u, d): | |
| self.u = self.u * d + u * self.d | |
| self.d = self.d * d | |
| self.cleanup() | |
| def mult(self, u, d): | |
| return (self.u * u % p, self.d * d % p) | |
| def mult_ip(self, u, d): | |
| self.u, self.d = (self.u * u, self.d * d % p) | |
| def get_m_exp(self): | |
| self.cleanup() | |
| a = gcd(self.u, self.d) | |
| self.u //= a | |
| self.d //= a | |
| return pow(self.d, p - 2, p) * self.u % p | |
| n, m = tuple(map(int, input().split())) | |
| s1 = list(map(int, input().split())) | |
| s2 = list(map(int, input().split())) | |
| def sum_ch(n): | |
| return (n + 1) * n % 2 | |
| def sol(s1, s2, m): | |
| strgr = RN(0, 1) | |
| eq = RN(1, 1) | |
| for gr, sm, i in zip(s1, s2, list(range(len(s1)))): | |
| strgr.cleanup() | |
| if gr != 0 and sm != 0: | |
| if gr == sm: | |
| continue | |
| elif gr < sm: | |
| return strgr.get_m_exp() | |
| else: | |
| strgr.add(eq.u, eq.d) | |
| return strgr.get_m_exp() | |
| else: | |
| if gr == sm == 0: | |
| strgr.add(*eq.mult(sum_ch(m - 1), m * m)) | |
| elif gr == 0: | |
| strgr.add(*eq.mult(m - sm, m)) | |
| else: | |
| strgr.add(*eq.mult(gr - 1, m)) | |
| eq.mult_ip(1, m) | |
| return strgr.get_m_exp() | |
| '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' | |
| print(sol(s1, s2, m)) | |
| ``` | |
| ### 182 | |
| ```python | |
| from random import random | |
| from collections import defaultdict | |
| import math | |
| import re | |
| import fractions | |
| N = int(input()) | |
| A = list(map(int, input().split(' '))) | |
| arr = [0] * (10 ** 5 + 1) | |
| existing = set() | |
| for a in A: | |
| arr[a] += 1 | |
| existing.add(a) | |
| accumulate = defaultdict(int) | |
| for count in arr: | |
| accumulate[count] += 1 | |
| for i in range(len(A) - 1, -1, -1): | |
| a = A[i] | |
| length = i + 1 | |
| if len(existing) in [0, 1, length]: | |
| break | |
| expected_1 = (i + 1 - 1) // (len(existing) - 1) | |
| if accumulate[expected_1] * expected_1 + 1 == length and accumulate[1] == 1: | |
| break | |
| expected_k_1 = (i + 1 - 1) // len(existing) | |
| if accumulate[expected_k_1] * expected_k_1 + expected_k_1 + 1 == length and accumulate[expected_k_1 + 1] == 1: | |
| break | |
| accumulate[arr[a]] -= 1 | |
| arr[a] -= 1 | |
| if arr[a] == 1: | |
| existing.discard(a) | |
| accumulate[arr[a]] += 1 | |
| print(length) | |
| ``` | |
| ### 183 | |
| ```python | |
| import math | |
| n, m, k, q = list(map(int, input().split())) | |
| right = [-1] * n | |
| left = [-1] * n | |
| for i in range(k): | |
| row, col = list(map(int, input().split())) | |
| row -= 1 | |
| col -= 1 | |
| if right[row] == -1: | |
| right[row] = left[row] = col | |
| else: | |
| right[row] = max(right[row], col) | |
| left[row] = min(left[row], col) | |
| safe = sorted(list([int(qi) - 1 for qi in input().split()])) | |
| lup = [0] * m | |
| rup = [0] * m | |
| j = 0 | |
| while j < safe[0]: | |
| lup[j] = -1 | |
| rup[j] = safe[0] | |
| j += 1 | |
| lup[j] = rup[j] = safe[0] | |
| for i in range(1, q): | |
| j = safe[i - 1] | |
| while j < safe[i]: | |
| lup[j] = safe[i - 1] | |
| rup[j] = safe[i] | |
| j += 1 | |
| j = safe[-1] | |
| while j < m: | |
| lup[j] = safe[-1] | |
| rup[j] = -1 | |
| j += 1 | |
| if left[0] == -1: | |
| left[0] = right[0] = 0 | |
| dleft = right[0] + (right[0] - left[0]) | |
| dright = right[0] | |
| lastn = 0 | |
| for i in range(1, n): | |
| if left[i] == -1: | |
| continue | |
| left_1b = lup[left[lastn]] | |
| left_2b = rup[left[lastn]] | |
| right_1b = lup[right[lastn]] | |
| right_2b = rup[right[lastn]] | |
| ilen = right[i] - left[i] | |
| ll1: int | |
| ll2: int | |
| rl1: int | |
| rl2: int | |
| if left_1b != -1: | |
| ll1 = left[lastn] - left_1b + abs(right[i] - left_1b) | |
| else: | |
| ll1 = math.inf | |
| if not left_2b != -1: | |
| ll2 = left_2b - left[lastn] + abs(right[i] - left_2b) | |
| else: | |
| ll2 = math.inf | |
| if right_1b != -1: | |
| rl1 = right[lastn] - right_1b + abs(right[i] - right_1b) | |
| else: | |
| rl1 = math.inf | |
| if right_2b != -1: | |
| rl2 = right_2b - right[lastn] + abs(right[i] - right_2b) | |
| else: | |
| rl2 = math.inf | |
| dleft_new = min(dleft + min(ll1, ll2), dright + min(rl1, rl2)) + ilen | |
| lr1: int | |
| lr2: int | |
| rr1: int | |
| rr2: int | |
| if left_1b != -1: | |
| lr1 = left[lastn] - left_1b + abs(left[i] - left_1b) | |
| else: | |
| lr1 = math.inf | |
| if left_2b != -1: | |
| lr2 = left_2b - left[lastn] + abs(left[i] - left_2b) | |
| else: | |
| lr2 = math.inf | |
| if right_1b != -1: | |
| rr1 = right[lastn] - right_1b + abs(left[i] - right_1b) | |
| else: | |
| rr1 = math.inf | |
| if right_2b != -1: | |
| rr2 = right_2b - right[lastn] + abs(left[i] - right_2b) | |
| else: | |
| rr2 = math.inf | |
| dright_new = min(dleft + min(lr1, lr2), dright + min(rr1, rr2)) + ilen | |
| dleft, dright = (dleft_new, dright_new) | |
| lastn = i | |
| print(min(dleft, dright) + lastn) | |
| ``` | |
| ### 184 | |
| ```python | |
| from sys import stdin | |
| def create_dp1(matrix, n, m): | |
| dp = [[2 for i in range(m)] for j in range(n)] | |
| for i in range(n): | |
| for j in range(m): | |
| if i - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) | |
| if j - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) | |
| elif i - 1 < 0 and j - 1 < 0: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp2(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m - 1, -1, -1): | |
| if i + 1 < n: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) | |
| if j + 1 < m: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) | |
| if i + 1 >= n and j + 1 >= m: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp3(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n - 1, -1, -1): | |
| for j in range(m): | |
| if i + 1 < n: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j]) | |
| if j - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1]) | |
| if i + 1 >= n and j - 1 < 0: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| def create_dp4(matrix, n, m): | |
| dp = [[0 for i in range(m)] for j in range(n)] | |
| for i in range(n): | |
| for j in range(m - 1, -1, -1): | |
| if i - 1 >= 0: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j]) | |
| if j + 1 < m: | |
| dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1]) | |
| if i - 1 < 0 and j + 1 >= m: | |
| dp[i][j] = matrix[i][j] | |
| return dp | |
| n, m = list(map(int, stdin.readline().split())) | |
| matrix = [] | |
| for _ in range(n): | |
| matrix.append(list(map(int, stdin.readline().split()))) | |
| dp1 = create_dp1(matrix, n, m) | |
| dp2 = create_dp2(matrix, n, m) | |
| dp3 = create_dp3(matrix, n, m) | |
| dp4 = create_dp4(matrix, n, m) | |
| total = -float('inf') | |
| for i in range(1, n - 1): | |
| for j in range(1, m - 1): | |
| first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1] | |
| second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j] | |
| total = max(total, first, second) | |
| print(total) | |
| ``` | |
| ### 185 | |
| ```python | |
| bn = 0 | |
| ar = [] | |
| def binSearchMax(number): | |
| last = bn | |
| first = 0 | |
| mid = (last + first) // 2 | |
| while last >= first: | |
| if ar[mid] < number: | |
| first = mid + 1 | |
| elif ar[mid] > number: | |
| last = mid - 1 | |
| else: | |
| return mid | |
| mid = (last + first) // 2 | |
| if ar[last] == number: | |
| return last | |
| return first | |
| n, m, k, q = list(map(int, input().split())) | |
| mmn = [[m, -1] for i in range(n)] | |
| maxn = 1 | |
| for i in range(k): | |
| r, c = list(map(int, input().split())) | |
| r -= 1 | |
| mmn[r][0] = min(mmn[r][0], c) | |
| mmn[r][1] = max(mmn[r][1], c) | |
| maxn = max(maxn, r) | |
| if mmn[0][1] == -1: | |
| mmn[0][1] = 1 | |
| mmn[0][0] = 1 | |
| bi = list(map(int, input().split())) | |
| bi += [-1000000000, 10000000000, -1000000000, 10000000000, 10000000000] | |
| bi.sort() | |
| ar = bi | |
| bn = q + 3 | |
| dp = [[0, 0] for i in range(n)] | |
| dp[0][1] = mmn[0][1] - mmn[0][0] | |
| dp[0][0] = dp[0][1] * 2 | |
| z = 0 | |
| for i in range(1, n): | |
| if mmn[i][1] == -1: | |
| dp[i][0] = dp[i - 1][0] | |
| dp[i][1] = dp[i - 1][1] | |
| continue | |
| p1 = binSearchMax(mmn[z][0]) | |
| p2 = bi[p1 - 1] | |
| p1 = bi[p1] | |
| p3 = binSearchMax(mmn[z][1]) | |
| p4 = bi[p3 - 1] | |
| p3 = bi[p3] | |
| num1 = abs(p1 - mmn[i][1]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][1]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][1]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][1]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][0] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| num1 = abs(p1 - mmn[i][0]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][0]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][0]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][0]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][1] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| z = i | |
| print(min(dp[-1]) + maxn) | |
| ``` | |
| ### 186 | |
| ```python | |
| n, k = map(int, input().strip().split()) | |
| l = list(map(int, input().strip().split())) | |
| test = True | |
| md = 998244353 | |
| evens = [0] | |
| odds = [0] | |
| for i in range(n): | |
| if i % 2: | |
| odds.append(l[i]) | |
| else: | |
| evens.append(l[i]) | |
| evens.append(-10) | |
| odds.append(-10) | |
| segs = [] | |
| l = len(odds) | |
| cont = False | |
| test = True | |
| for i in range(l): | |
| if odds[i] == -1 and cont == False: | |
| a = i - 1 | |
| cont = True | |
| elif odds[i] != -1 and cont == True: | |
| cont = False | |
| b = i | |
| segs.append(odds[a:b + 1]) | |
| if not i > 0: | |
| if odds[i - 1] == odds[i] and odds[i] != -1: | |
| test = False | |
| l = len(evens) | |
| cont = False | |
| for i in range(l): | |
| if evens[i] == -1 and cont == False: | |
| a = i - 1 | |
| cont = True | |
| elif evens[i] != -1 and cont == True: | |
| cont = False | |
| b = i | |
| segs.append(evens[a:b + 1]) | |
| if i > 0: | |
| if evens[i - 1] == evens[i] and evens[i] != -1: | |
| test = False | |
| ans = 1 | |
| for seg in segs: | |
| l = len(seg) - 2 | |
| dp = [[0, 0] for i in range(l)] | |
| a = seg[-1] | |
| b = seg[0] | |
| if b == 0: | |
| dp[0][0] = 1 | |
| dp[0][1] = k - 1 | |
| elif b == a: | |
| dp[0][0] = 0 | |
| dp[0][1] = k - 1 | |
| elif b != a: | |
| dp[0][0] = 1 | |
| dp[0][1] = k - 2 | |
| for i in range(1, l): | |
| dp[i][0] = dp[i - 1][1] % md | |
| dp[i][1] = (dp[i - 1][0] * (k - 1) + dp[i - 1][1] * (k - 2)) % md | |
| if a == -10: | |
| ans *= dp[l - 1][0] + dp[l - 1][1] | |
| else: | |
| ans *= dp[l - 1][1] | |
| ans %= md | |
| if test == False: | |
| print(0) | |
| else: | |
| print(ans) | |
| ``` | |
| ### 187 | |
| ```python | |
| n, m = map(int, input().split()) | |
| a = [] | |
| for i in range(n): | |
| a.append(list(map(int, input().split()))) | |
| dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] | |
| dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)] | |
| ans = 0 | |
| for i in reversed(range(1, n + 1)): | |
| for j in range(1, m + 1): | |
| dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1] | |
| dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] | |
| for i in range(n, 0, -1): | |
| for j in range(1, m + 1): | |
| dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1] | |
| dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j] | |
| for i in range(2, n): | |
| for j in range(2, m): | |
| x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1] | |
| y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1] | |
| ans = max(ans, x, y) | |
| print(ans) | |
| ``` | |
| ### 188 | |
| ```python | |
| from collections import defaultdict, deque | |
| n = int(input()) | |
| adj = [[] for _ in range(n)] | |
| v = [0] * n | |
| l = list(map(int, input().split())) | |
| for i, f in enumerate(l): | |
| adj[f - 1].append(i + 1) | |
| s = list(map(int, input().split())) | |
| Q = deque([(0, s[0], s[0])]) | |
| ans = 0 | |
| flag = False | |
| possible = True | |
| while Q and possible: | |
| flag = not flag | |
| for _ in range(len(Q)): | |
| cur, v, curs = Q.popleft() | |
| if v < 0: | |
| possible = False | |
| ans = -1 | |
| break | |
| ans += v | |
| if flag: | |
| for i in adj[cur]: | |
| if len(adj[i]) <= 1: | |
| Q.append((i, 0, curs)) | |
| else: | |
| temp = min([s[k] for k in adj[i]]) | |
| Q.append((i, temp - curs, temp)) | |
| else: | |
| for i in adj[cur]: | |
| Q.append((i, s[i] - curs, s[i - 1])) | |
| print(ans) | |
| ``` | |
| ### 189 | |
| ```python | |
| bn = 0 | |
| ar = [] | |
| def binSearchMax(number): | |
| last = bn | |
| first = 0 | |
| mid = (last + first) // 2 | |
| while last >= first: | |
| if ar[mid] < number: | |
| first = mid + 1 | |
| elif ar[mid] > number: | |
| last = mid - 1 | |
| else: | |
| return mid | |
| mid = (last + first) // 2 | |
| if ar[last] == number: | |
| return last | |
| return first | |
| n, m, k, q = list(map(int, input().split())) | |
| mmn = [[m, -1] for i in range(n)] | |
| maxn = 0 | |
| for i in range(k): | |
| r, c = list(map(int, input().split())) | |
| r -= 1 | |
| mmn[r][0] = min(mmn[r][0], c) | |
| mmn[r][1] = max(mmn[r][1], c) | |
| maxn = max(maxn, r) | |
| if mmn[0][1] == -1: | |
| mmn[0][1] = 1 | |
| mmn[0][0] = 1 | |
| bi = list(map(int, input().split())) | |
| bi += [-1000000000, 10000000000, -1000000000, 10000000000, 10000000000] | |
| bi.sort() | |
| ar = bi | |
| bn = q + 3 | |
| dp = [[0, 0] for i in range(n)] | |
| dp[0][1] = mmn[0][1] - mmn[0][0] | |
| dp[0][0] = dp[0][1] * 1 | |
| z = 0 | |
| for i in range(1, n): | |
| if mmn[i][1] == -1: | |
| dp[i][0] = dp[i - 1][0] | |
| dp[i][1] = dp[i - 1][1] | |
| continue | |
| p1 = binSearchMax(mmn[z][0]) | |
| p2 = bi[p1 - 1] | |
| p1 = bi[p1] | |
| p3 = binSearchMax(mmn[z][1]) | |
| p4 = bi[p3 - 1] | |
| p3 = bi[p3] | |
| num1 = abs(p1 - mmn[i][1]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][1]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][1]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][1]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][0] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| num1 = abs(p1 - mmn[i][0]) + abs(p1 - mmn[z][0]) + dp[z][0] | |
| num2 = abs(p2 - mmn[i][0]) + abs(p2 - mmn[z][0]) + dp[z][0] | |
| num3 = abs(p3 - mmn[i][0]) + abs(p3 - mmn[z][1]) + dp[z][1] | |
| num4 = abs(p4 - mmn[i][0]) + abs(p4 - mmn[z][1]) + dp[z][1] | |
| dp[i][1] = min(min(num1, num2), min(num3, num4)) + mmn[i][1] - mmn[i][0] | |
| z = i | |
| print(min(dp[-1]) + maxn) | |
| ``` | |
| ### 190 | |
| ```python | |
| def dfs(v, g, vis): | |
| count = 1 | |
| first = v | |
| st = [v] | |
| vis[v] = True | |
| while st: | |
| v = st[-1] | |
| st.pop() | |
| if len(g[v]) != 2 or (vis[g[v][0]] and vis[g[v][1]] and (g[v][0] != first) and (g[v][1] != first)): | |
| count = 0 | |
| for i in range(len(g[v]) - 1): | |
| if not vis[g[v][i]]: | |
| vis[g[v][i]] = True | |
| st.append(g[v][i]) | |
| if v == first and count: | |
| break | |
| if len(g[first]) == 2 and (not vis[g[first][1]]): | |
| st.append(g[first][1]) | |
| while st: | |
| v = st[-1] | |
| st.pop() | |
| for i in range(len(g[v])): | |
| if not vis[g[v][i]]: | |
| vis[g[v][i]] = True | |
| st.append(g[v][i]) | |
| return count | |
| v, e = list(map(int, input().split())) | |
| g = [[] for i in range(v)] | |
| for i in range(e): | |
| f, to = list(map(int, input().split())) | |
| g[f - 1].append(to - 1) | |
| g[to - 1].append(f - 1) | |
| vis = [False] * v | |
| ans = 0 | |
| for i in range(v): | |
| if not vis[i]: | |
| ans += dfs(i, g, vis) | |
| print(ans) | |
| ``` | |
| ### 191 | |
| ```python | |
| n = int(input()) | |
| class Tree: | |
| height = 1 | |
| def __init__(self, parent=None): | |
| self.nodes = [] | |
| self.s = -1 | |
| self.a = -1 | |
| self.parent = parent | |
| if parent: | |
| self.height = parent.height + 1 | |
| parent.nodes.append(self) | |
| trs = [Tree()] | |
| for i in map(int, input().split()): | |
| trs.append(Tree(trs[i - 1])) | |
| for i, s in enumerate(map(int, input().split())): | |
| trs[i].s = s | |
| trs.sort(key=lambda x: x.height) | |
| trs[0].a = trs[0].s | |
| res = trs[0].a | |
| try: | |
| for t in trs[1:]: | |
| if t.s == -1: | |
| t.a = min([x.s - t.parent.s for x in t.nodes], default=0) | |
| t.s = t.a + t.parent.s | |
| else: | |
| t.a = t.s - t.parent.s | |
| if t.a < 0: | |
| raise | |
| res += t.a | |
| print(res) | |
| except: | |
| print(-3) | |
| ``` | |
| ### 192 | |
| ```python | |
| from collections import defaultdict, deque | |
| n = int(input()) | |
| adj = [[] for _ in range(n)] | |
| v = [0] * n | |
| l = list(map(int, input().split())) | |
| for i, f in enumerate(l): | |
| adj[f - 1].append(i + 1) | |
| s = list(map(int, input().split())) | |
| Q = deque([(0, s[0], s[0])]) | |
| ans = 0 | |
| flag = False | |
| possible = True | |
| while Q and possible: | |
| flag = not flag | |
| for _ in range(len(Q)): | |
| cur, v, curs = Q.popleft() | |
| if v < 0: | |
| possible = False | |
| ans = -1 | |
| break | |
| ans += v | |
| if flag: | |
| for i in adj[cur]: | |
| if len(adj[i]) <= 1: | |
| Q.append((i, 0, curs)) | |
| else: | |
| temp = max([s[k] for k in adj[i]]) | |
| Q.append((i, temp - curs, temp)) | |
| else: | |
| for i in adj[cur]: | |
| Q.append((i, s[i] - curs, s[i])) | |
| print(ans) | |
| ``` | |
| ### 193 | |
| ```python | |
| n = int(input()) | |
| u = [int(u) for u in input().split()] | |
| NMAX = 100005 | |
| suma = [0 for _ in range(NMAX)] | |
| total = [0 for _ in range(NMAX)] | |
| diferentes = 0 | |
| sol = 0 | |
| maximo = 3 | |
| for i, v in enumerate(u): | |
| if total[v] == 0: | |
| diferentes += 1 | |
| else: | |
| suma[total[v]] -= 1 | |
| total[v] += 1 | |
| suma[total[v]] += 1 | |
| maximo = max(maximo, total[v]) | |
| if diferentes <= 1: | |
| sol = i | |
| if suma[maximo - 1] == diferentes - 1 and suma[maximo] == 1: | |
| sol = i | |
| if suma[maximo] == diferentes - 1 and suma[1] == 1: | |
| sol = i | |
| if suma[1] == diferentes: | |
| sol = i | |
| print(sol + 1) | |
| ``` | |
| ### 194 | |
| ```python | |
| from random import random | |
| from collections import defaultdict | |
| import math | |
| import re | |
| import fractions | |
| N = int(input()) | |
| A = list(map(int, input().split(' '))) | |
| arr = [0] * (10 ** 5 + 1) | |
| existing = set() | |
| for a in A: | |
| arr[a] += 1 | |
| existing.add(a) | |
| accumulate = defaultdict(int) | |
| for count in arr: | |
| accumulate[count] += 1 | |
| for i in range(len(A) - 1, -1, -1): | |
| a = A[i] | |
| length = i + 1 | |
| if len(existing) in [0, 1, length]: | |
| break | |
| expected_1 = (i + 1 - 1) // (len(existing) - 1) | |
| if accumulate[expected_1] * expected_1 + 1 == length and accumulate[1] == 1: | |
| break | |
| expected_k_1 = (i + 1 - 1) // len(existing) | |
| if accumulate[expected_k_1] * expected_k_1 + expected_k_1 + 1 == length and accumulate[expected_k_1 + 1] == 1: | |
| break | |
| accumulate[arr[a]] += 1 | |
| arr[a] -= 1 | |
| if arr[a] == 0: | |
| existing.discard(a) | |
| accumulate[arr[a]] += 1 | |
| print(length) | |
| ``` | |
| ### 195 | |
| ```python | |
| from math import gcd | |
| p = 10 ** 9 + 7 | |
| class RN: | |
| p = 10 ** 9 + 7 | |
| def __init__(self, u, d): | |
| self.u = u | |
| self.d = d | |
| def __str__(self): | |
| return str(self.u) + '/' + str(self.d) | |
| def cleanup(self): | |
| self.u = self.u % p | |
| self.d = self.d % p | |
| def add(self, u, d): | |
| self.u = self.u * d + u * self.d | |
| self.d = self.d * d | |
| self.cleanup() | |
| def mult(self, u, d): | |
| return (self.u * u % p, self.d * d % p) | |
| def mult_ip(self, u, d): | |
| self.u, self.d = (self.u * u, self.d * d % p) | |
| def get_m_exp(self): | |
| self.cleanup() | |
| a = gcd(self.u, self.d) | |
| self.u //= a | |
| self.d //= a | |
| return pow(self.d, p - 2, p) * self.u % p | |
| n, m = tuple(map(int, input().split())) | |
| s1 = list(map(int, input().split())) | |
| s2 = list(map(int, input().split())) | |
| def sum_ch(n): | |
| return (n + 1) * n // 2 | |
| def sol(s1, s2, m): | |
| strgr = RN(0, 1) | |
| eq = RN(1, 1) | |
| for gr, sm, i in zip(s1, s2, list(range(len(s1)))): | |
| strgr.cleanup() | |
| if gr != 0 and sm != 0: | |
| if gr == sm: | |
| continue | |
| elif gr < sm: | |
| return strgr.get_m_exp() | |
| else: | |
| strgr.add(eq.u, eq.d) | |
| return strgr.get_m_exp() | |
| else: | |
| if gr == sm == 0: | |
| strgr.add(*eq.mult(sum_ch(m - 1), m * m)) | |
| elif gr == 0: | |
| strgr.add(*eq.mult(m - sm, m)) | |
| else: | |
| strgr.add(*eq.mult(gr - 1, m)) | |
| eq.mult_ip(1, m) | |
| return strgr.get_m_exp() | |
| '\na = sol([0,0],[1,1], 2) # 3/4\n\na = sol([0,0,0],[1,1,1], 2) # 7/8\na = sol([0,1,1],[1,1,1], 2) # 1/2\na = sol([1,0,1],[1,1,1], 2) # 1/2\n\na = sol([0,0,0],[1,3,3], 3) # 2/2\na = sol([0,0,0],[1,1,0], 2) # 5/8\na = sol([0,0,0],[0,0,0], 2) # 13/16\n' | |
| print(sol(s1, s2, m)) | |
| ``` | |
| ### 196 | |
| ```python | |
| n = int(input()) | |
| class Tree: | |
| height = 1 | |
| def __init__(self, parent=None): | |
| self.nodes = [] | |
| self.s = -1 | |
| self.a = -1 | |
| self.parent = parent | |
| if parent: | |
| self.height = parent.height + 1 | |
| parent.nodes.append(self) | |
| trs = [Tree()] | |
| for i in map(int, input().split()): | |
| trs.append(Tree(trs[i - 1])) | |
| for i, s in enumerate(map(int, input().split())): | |
| trs[i].s = s | |
| trs.sort(key=lambda x: x.height) | |
| trs[0].a = trs[0].s | |
| res = trs[0].a | |
| try: | |
| for t in trs[1:]: | |
| if t.s == -1: | |
| t.a = min([x.s - t.parent.s for x in t.nodes], default=0) | |
| t.s = t.a + t.parent.s | |
| else: | |
| t.a = t.s - t.parent.s | |
| if t.a < 0: | |
| raise | |
| res += t.a | |
| print(res) | |
| except: | |
| print(-4) | |
| ``` | |
| ### 197 | |
| ```python | |
| s = input() | |
| cs = [''] | |
| ans = [] | |
| last = [''] | |
| poped = False | |
| for c in s[::-1]: | |
| if not poped and c == cs[-1] and (c > last[-2]): | |
| cs.pop() | |
| if not cs or c != cs[-1]: | |
| last.pop() | |
| poped = True | |
| else: | |
| poped = False | |
| if c != cs[-1]: | |
| last.append(c) | |
| cs.append(c) | |
| if len(cs) <= 11: | |
| ans.append((len(cs) - 1, ''.join(cs[::-1]))) | |
| else: | |
| ans.append((len(cs) - 1, (''.join(cs[:3 + 1]) + '...' + ''.join(cs[-5:]))[::-1])) | |
| for a, b in ans[::-1]: | |
| print(a, b) | |
| ``` | |
| ### 198 | |
| ```python | |
| s = input() | |
| cs = [''] | |
| ans = [] | |
| last = [''] | |
| poped = False | |
| for c in s[::-1]: | |
| if not poped and c == cs[-1] and (c > last[-2]): | |
| cs.pop() | |
| if not cs or c != cs[-1]: | |
| last.pop() | |
| poped = True | |
| else: | |
| poped = False | |
| if c != cs[-1]: | |
| last.append(c) | |
| cs.append(c) | |
| if len(cs) <= 11: | |
| ans.append((len(cs) - 1, ''.join(cs[::-1]))) | |
| else: | |
| ans.append((len(cs) - 1, (''.join(cs[:3]) + '...' + ''.join(cs[-5 + 1:]))[::-1])) | |
| for a, b in ans[::-1]: | |
| print(a, b) | |
| ``` | |
| ### 199 | |
| ```python | |
| import heapq | |
| n, m, k = list(map(int, input().split())) | |
| connectionList = [] | |
| for _ in range(n): | |
| connectionList.append([]) | |
| edgeList = [] | |
| for _ in range(m): | |
| x, y, w = list(map(int, input().split())) | |
| edgeList.append((x, y, w)) | |
| edgeList.sort(key=lambda x: x[2]) | |
| if k < m: | |
| maxDist = edgeList[min(m, k) - 5][2] | |
| else: | |
| maxDist = sum([x[2] for x in edgeList]) | |
| colorList = {} | |
| colorVertex = [] | |
| for i in range(n): | |
| colorList[i] = [i] | |
| colorVertex.append(i) | |
| for i in range(min(m, k)): | |
| x, y, w = edgeList[i] | |
| connectionList[x - 1].append((y - 1, w)) | |
| connectionList[y - 1].append((x - 1, w)) | |
| if colorVertex[x - 1] != colorVertex[y - 1]: | |
| if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]): | |
| prevColor = colorVertex[y - 1] | |
| for elem in colorList[colorVertex[y - 1]]: | |
| colorVertex[elem] = colorVertex[x - 1] | |
| colorList[colorVertex[x - 1]].append(elem) | |
| del colorList[prevColor] | |
| else: | |
| prevColor = colorVertex[x - 1] | |
| for elem in colorList[colorVertex[x - 1]]: | |
| colorVertex[elem] = colorVertex[y - 1] | |
| colorList[colorVertex[y - 1]].append(elem) | |
| del colorList[prevColor] | |
| pathList = [] | |
| for key in colorList: | |
| vertexList = colorList[key] | |
| for mainVertex in vertexList: | |
| vertexPQueue = [] | |
| isCovered = {} | |
| distanceDic = {} | |
| for elem in vertexList: | |
| isCovered[elem] = False | |
| distanceDic[elem] = maxDist | |
| isCovered[mainVertex] = True | |
| for elem in connectionList[mainVertex]: | |
| heapq.heappush(vertexPQueue, (elem[1], elem[0])) | |
| distanceDic[elem[0]] = elem[1] | |
| while vertexPQueue: | |
| distance, curVertex = heapq.heappop(vertexPQueue) | |
| if isCovered[curVertex]: | |
| continue | |
| elif distance >= maxDist: | |
| break | |
| for elem in connectionList[curVertex]: | |
| if distance + elem[1] < distanceDic[elem[0]]: | |
| heapq.heappush(vertexPQueue, (distance + elem[1], elem[0])) | |
| distanceDic[elem[0]] = distance + elem[1] | |
| for key in distanceDic: | |
| if distanceDic[key] <= maxDist and key > mainVertex: | |
| pathList.append(distanceDic[key]) | |
| if len(pathList) > k: | |
| pathList.sort() | |
| pathList = pathList[0:k] | |
| if pathList[-1] < maxDist: | |
| maxDist = pathList[-1] | |
| pathList.sort() | |
| print(pathList[k - 1]) | |
| ``` | |
| ### 200 | |
| ```python | |
| n, m, k, q = map(int, input().split()) | |
| tr_min = [None for _ in range(n)] | |
| tr_max = [None for _ in range(n)] | |
| for _ in range(k): | |
| row, col = map(int, input().split()) | |
| row = n - row | |
| col -= 1 | |
| if tr_min[row] == None or col > tr_min[row]: | |
| tr_min[row] = col | |
| if tr_max[row] == None or col > tr_max[row]: | |
| tr_max[row] = col | |
| tr_min[-1] = 0 | |
| tr_max[-1] = tr_max[-1] or 0 | |
| savecols = sorted(map(lambda t: int(t) - 1, input().split())) | |
| def binsearch(arr, val): | |
| l, r = (0, len(arr) - 1) | |
| while l <= r: | |
| mid = l + (r - l) // 2 | |
| if arr[mid] < val: | |
| l = mid + 1 | |
| elif arr[mid] > val: | |
| r = mid - 1 | |
| else: | |
| return mid | |
| return r | |
| def find_short_descent(A, B): | |
| if A > B: | |
| return find_short_descent(B, A) | |
| idx1 = binsearch(savecols, A) | |
| idx2 = idx1 + 1 | |
| minval = m * m | |
| if idx2 < len(savecols): | |
| if savecols[idx2] < B: | |
| return B - A | |
| else: | |
| minval = min(minval, (savecols[idx2] << 1) - A - B) | |
| if idx1 >= 0: | |
| minval = min(minval, A + B - (savecols[idx1] << 1)) | |
| return minval | |
| l, r = (0, 0) | |
| found_valid = False | |
| last_valid = None | |
| for row in range(0, n): | |
| if found_valid == False: | |
| if tr_min[row] != None: | |
| found_valid = True | |
| last_valid = row | |
| l = tr_max[row] - tr_min[row] | |
| r = tr_max[row] - tr_min[row] | |
| continue | |
| continue | |
| if tr_min[row] == None: | |
| l += 1 | |
| r += 1 | |
| continue | |
| ll = find_short_descent(tr_min[last_valid], tr_min[row]) | |
| lr = find_short_descent(tr_min[last_valid], tr_max[row]) | |
| rl = find_short_descent(tr_max[last_valid], tr_min[row]) | |
| rr = find_short_descent(tr_max[last_valid], tr_max[row]) | |
| new_l = min(l + lr, r + rr) + 1 + (tr_max[row] - tr_min[row]) | |
| new_r = min(l + ll, r + rl) + 1 + (tr_max[row] - tr_min[row]) | |
| l, r = (new_l, new_r) | |
| last_valid = row | |
| answ = l + tr_min[last_valid] | |
| print(answ) | |
| ``` | |
| ### 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. | |