### 001 ```python from sys import stdin from collections import deque n, S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s, a, b = [int(x) for x in stdin.readline().split()] base += s * a tSlices += s ppl.append([b - a, s]) if tSlices % S != 0: ppl.append([0, S - tSlices % S]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h, s in ppl: if totalS + s < S: totalS += s totalH += h * s else: s -= S - totalS totalH += h * (S - totalS) if totalH > 0: base += totalH else: break totalS = 0 totalH = 0 if h < 0: base += h * (s // S * S) totalS = s % S totalH = h * (s % S) else: break print(base) ``` ### 002 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += 1 if a[i] == 'D': r[1] -= 1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += 1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) < (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 003 ```python def is_possible(num_days): if num_days % len(string) == 0: diff_wind = (num_days // len(string) * pref[-1][0], num_days // len(string) * pref[-1][1]) else: diff_wind = (num_days // len(string) + pref[-1][0] + pref[num_days % len(string) - 1][0], num_days // len(string) * pref[-1][1] + pref[num_days % len(string) - 1][1]) diff_ship = (diff[0] - diff_wind[0], diff[1] - diff_wind[1]) return abs(diff_ship[0]) + abs(diff_ship[1]) <= num_days x, y = [int(s) for s in input().split()] x1, y1 = [int(s) for s in input().split()] diff = (x1 - x, y1 - y) amount = int(input()) string = input() motions = [] pref = [] for i in range(len(string)): if string[i] == 'U': motions.append((0, 1)) if string[i] == 'D': motions.append((0, -1)) if string[i] == 'R': motions.append((1, 0)) if string[i] == 'L': motions.append((-1, 0)) pref.append(motions[0]) for i in range(1, len(motions)): pref.append((motions[i][0] + pref[-1][0], motions[i][1] + pref[-1][1])) left = -1 right = int(1e+19) while right - left > 1: middle = (right + left) // 2 if is_possible(middle): right = middle else: left = middle if right != int(1e+19): print(right) else: print(-1) ``` ### 004 ```python def inint(): return int(input()) def inlist(): return list(map(int, input().split())) def main(): n, m, l = inlist() aa = inlist() chg = 0 ch = 0 a = [[i, 0] for i in aa] for i in range(n): if aa[i] > l: if ch == 0: ch += 1 chg += 1 a[i][1] = chg else: ch += 1 a[i][1] = chg elif not ch != 0: ch = 0 sol = list() if n > 1: for z in range(m): qu = input() if qu == '0': sol.append(chg) else: zz, p, d = list(map(int, qu.split())) p -= 1 a[p][0] += d if a[p][1] == 0 and a[p][0] > l: if p > 0 and p < n - 1: if a[p - 1][1] == 0 and a[p + 1][1] == 0: chg += 1 a[p][1] = chg elif a[p - 1][1] == 0 and a[p + 1][1] > 0: a[p][1] = a[p + 1][1] elif a[p - 1][1] > 0 and a[p + 1][1] == 0: a[p][1] = a[p - 1][1] else: a[p][1] = a[p - 1][1] chg -= 1 elif p == 0: if a[p + 1][1] == 0: chg += 1 a[p][1] = chg else: a[p][1] = a[p + 1][1] elif p == n - 1: if a[p - 1][1] == 0: chg += 1 a[p][1] = chg else: a[p][1] = a[p - 1][1] else: for z in range(m): qu = input() if qu == '0': sol.append(chg) else: zz, p, d = list(map(int, qu.split())) p -= 1 a[p][0] += d if a[p][0] > d: chg = 1 print(*sol, sep='\n') def __starting_point(): main() __starting_point() ``` ### 005 ```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) ``` ### 006 ```python from collections import Counter from bisect import bisect, bisect_left n, k = map(int, input().split()) a = list(map(int, input().split())) a = Counter(a) c = sorted(Counter(a).items()) keys = sorted(Counter(a).keys(), reverse=True) m = len(c) l_cum = [c[0][0] * c[0][1]] l_cnt = [c[0][1]] for i in range(1, m): l_cum.append(l_cum[-1] + c[i][0] * c[i][1]) l_cnt.append(l_cnt[-1] + c[i][1]) r_cum = [0 for _ in range(m)] r_cum[-1] = c[-1][0] * c[-1][1] r_cnt = [0 for _ in range(m)] r_cnt[-1] = c[-1][1] for i in range(m - 2, -1, -1): r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1] r_cnt[i] = r_cnt[i + 1] + c[i][1] ans = 10 ** 20 for i in range(m): c_num = a[keys[i]] if c_num >= k: ans = 0 break if i > 0: l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1] l_num = l_cnt[i - 1] else: l_res = 10 ** 30 l_num = 0 if i < m - 1: r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1] r_num = r_cnt[i + 1] else: r_res = 10 ** 30 r_num = 0 if c_num + l_num < k and c_num + r_num < k: ans = min(ans, l_res + r_res + k - c_num) elif c_num + l_num < k: ans = min(ans, r_res + k - c_num) elif c_num + r_num < k: ans = min(ans, l_res + k - c_num) else: ans = min(ans, min(r_res, l_res) + k - c_num) print(ans) ``` ### 007 ```python import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return list(map(int, minp().split())) n, m = mints() a = [0] * n dp1 = [0] * n dp2 = [0] * n dp3 = [0] * n dp4 = [0] * n for i in range(n): a[i] = list(mints()) dp1[i] = [0] * m dp2[i] = [0] * m dp3[i] = [0] * m dp4[i] = [0] * m dp1[0][0] = a[0][0] dp2[n - 1][m - 1] = a[n - 1][m - 1] dp3[n - 1][0] = a[n - 1][0] dp4[0][m - 1] = a[0][m - 1] '\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n' for i in range(0, n): for j in range(0, m): z = 0 if i - 1 >= 0: z = dp1[i - 1][j] if j - 1 >= 0: z = max(z, dp1[i][j - 1]) dp1[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): z = 0 if i + 1 < n: z = dp2[i + 1][j] if j + 1 < m: z = max(z, dp2[i][j + 1]) dp2[i][j] = z + a[i][j] for i in range(n - 1, -1, -1): for j in range(0, m): z = 0 if i + 1 < n: z = dp3[i + 1][j] if j - 1 >= 0: z = max(z, dp3[i][j - 1]) dp3[i][j] = z + a[i][j] for i in range(0, n): for j in range(m - 1, -1, -1): z = 0 if i - 1 >= 0: z = dp4[i - 1][j] if j + 1 < m: z = max(z, dp4[i][j + 1]) dp4[i][j] = z + a[i][j] 'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n' r = 0 for i in range(1, n - 1): for j in range(1, m - 1): r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]) r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]) print(r) ``` ### 008 ```python from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == '\n': return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def solve(): n, k = LI() a = LI() a.sort() d = defaultdict(lambda: 0) c = defaultdict(lambda: 1) s = [0] for i in a: d[i] += i c[i] += 1 s.append(s[-1] + i) ans = float('inf') p = -1 for i in a: if i == p: continue if k <= c[i]: ans = 0 break l, r = (bisect.bisect_left(a, i), bisect.bisect_right(a, i)) m = r if m >= k: ns = l * (i - 1) - s[l] su = ns + k - c[i] if su < ans: ans = su m = n - l if m >= k: ns = s[n] - s[r] - (n - r) * (i + 1) su = ns + k - c[i] if su < ans: ans = su ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l] su = ns + k - c[i] if su < ans: ans = su p = i print(ans) return def __starting_point(): solve() __starting_point() ``` ### 009 ```python from collections import defaultdict as di n, m = [int(x) for x in input().split()] free = di(lambda: False) startpos = (-1, -1) goal = (-1, -1) for y in range(n): s = input() for x in range(m): c = s[x] if c == 'S': startpos = (x, y) free[x, y] = True elif c == 'E': goal = (x, y) free[x, y] = True elif c == '.': free[x, y] = True counts = 0 dire = '0123' command = input() for up in dire: for down in dire: for right in dire: for left in dire: if len(set([up, down, left, right])) < 4: continue pos = startpos for c in command: x, y = pos if c == up: y += 1 elif c == down: y -= -1 elif c == right: x += 1 else: x -= 1 pos = (x, y) if pos == goal: counts += 1 break if not free[pos]: break print(counts) ``` ### 010 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += 1 if a[i] == 'D': r[1] -= -1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += 1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) <= (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 011 ```python from collections import defaultdict as di n, m = [int(x) for x in input().split()] free = di(lambda: False) startpos = (-1, -1) goal = (-1, -1) for y in range(n): s = input() for x in range(m): c = s[x] if c == 'S': startpos = (x, y) free[x, y] = True elif c == 'E': goal = (x, y) free[x, y] = True elif c == '.': free[x, y] = True counts = 0 dire = '0123' command = input() for up in dire: for down in dire: for right in dire: for left in dire: if len(set([up, down, left, right])) < 4: continue pos = startpos for c in command: x, y = pos if c == up: y += 4 elif c == down: y -= 1 elif c == right: x += 1 else: x -= 1 pos = (x, y) if pos == goal: counts += 1 break if not free[pos]: break print(counts) ``` ### 012 ```python import sys nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split())) meches = list(map(int, sys.stdin.readline().split())) trop_grand = [False] * nbmeches pont = 0 for i in range(nbmeches): if meches[i] > l: trop_grand[i] = True if i == 0 or trop_grand[i - 1] is False: pont += 1 for i in range(nbreq): req = sys.stdin.readline().split() if int(req[0]) == 0: print(pont) else: meches[int(req[1]) - 1] += int(req[2]) if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]): trop_grand[int(req[1]) - 1] = True if nbmeches == 1: pont = -1 elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]): pont += 1 elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]): pont += 1 elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]: pont = max(0, pont - 1) elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]): pont += 1 ``` ### 013 ```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) ``` ### 014 ```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) ``` ### 015 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy * m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if not i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 016 ```python n, m = list(map(int, input().split())) grid = [] sloc = (-1, -1) eloc = (-1, -1) for y in range(n): l = input() grid.append(list()) for x in range(m): grid[-1].append(l[x] == '#') if l[x] == 'S': sloc = (x, y) elif l[x] == 'E': eloc = (x, y) pb = [] for a in [(0, 5), (0, -1), (1, 0), (-1, 0)]: for b in [(0, 1), (0, -1), (1, 0), (-1, 0)]: for c in [(0, 1), (0, -1), (1, 0), (-1, 0)]: for d in [(0, 1), (0, -1), (1, 0), (-1, 0)]: if len(set([a, b, c, d])) == 4 and [a, b, c, d] not in pb: pb.append([a, b, c, d]) s = input() ans = 0 for mp in pb: seen = False works = True loc = sloc for j in s: j = int(j) if seen: break if not works: break nloc = (loc[0] + mp[j][0], loc[1] + mp[j][1]) if min(nloc) < 0 or nloc[0] >= m or nloc[1] >= n: works = False break if grid[nloc[1]][nloc[0]]: works = False break if nloc == eloc: seen = True break loc = nloc if seen: ans += 1 print(ans) ``` ### 017 ```python from math import gcd def covered_points(xa, ya, xb, yb): if xb < xa: temp_x = xa xa = xb xb = temp_x temp_y = ya ya = yb yb = temp_y y_0 = abs(yb - ya) x_0 = xb - xa return gcd(y_0, x_0) + 1 def intersection2(xa, ya, xb, yb, xc, yc, xd, yd): if max(xa, xb) < min(xc, xd): return () if max(ya, yb) < min(yc, yd): return () if xa == xb and xc == xd or (ya == yb and yc == yd): return () if ya == yb and yc == yd: return () a1 = yb - ya b1 = xb - xa c1 = xa * a1 - ya * b1 a2 = yd - yc b2 = xd - xc c2 = xc * a2 - yc * b2 det = a1 * b2 - a2 * b1 if det == 0: return () detx = c1 * b2 - c2 * b1 dety = -a1 * c2 + a2 * c1 if detx % det != 0 or dety % det != 0: return () x = int(detx / det) y = int(dety / det) if x < min(xa, xb) or x > max(xa, xb) or x < min(xc, xd) or (x > max(xc, xd)): return () if not (y < min(ya, yb) or y > max(ya, yb) or y < min(yc, yd) or (y > max(yc, yd))): return () return (x, y) def __starting_point(): n = int(input()) Ax = [0] * n Ay = [0] * n Bx = [0] * n By = [0] * n n_cov = 0 intersections = {} for i in range(n): line = input().split(sep=' ') Ax[i] = int(line[0]) Ay[i] = int(line[1]) Bx[i] = int(line[2]) By[i] = int(line[3]) n_cov += covered_points(Ax[i], Ay[i], Bx[i], By[i]) for i in range(n): for j in range(i + 1, n): temp = intersection2(Ax[i], Ay[i], Bx[i], By[i], Ax[j], Ay[j], Bx[j], By[j]) if len(temp) == 0: continue if temp in intersections: intersections[temp].append(i) intersections[temp].append(j) else: intersections[temp] = [i, j] for i in intersections: n_cov = n_cov - len(set(intersections[i])) + 1 print(n_cov) __starting_point() ``` ### 018 ```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) ``` ### 019 ```python n, k = list(map(int, input().split())) a = sorted(list(map(int, input().split()))) sums, suf, q1 = ([0] * n, [n] * n, n) for q in range(n - 2, -2, -1): sums[q] = sums[q + 1] if a[q] != a[q1 - 1]: sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1) q1 = q + 1 suf[q] = q1 ans, sum1, q1 = (sums[0] + k - suf[0] if suf[0] < k else 0, 0, -1) for q in range(1, n): if a[q] != a[q1 + 1]: sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1) q1 = q - 1 if suf[q] - q1 - 1 >= k: ans = 0 break if k <= suf[q]: ans = min(ans, sum1 + k - suf[q] + q1 + 1) if k < n - q1: ans = min(ans, sums[q] + k - suf[q] + q1 + 1) ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1) print(ans) ``` ### 020 ```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) ``` ### 021 ```python In = input().split(' ') x1 = int(In[0]) y1 = int(In[1]) In = input().split(' ') x2 = int(In[0]) y2 = int(In[1]) dx = [0] dy = [0] n = int(input()) s = input() for i in range(1, n + 1): dx.append(dx[i - 1]) dy.append(dy[i - 1 - 1]) if s[i - 1] == 'U': dy[i] += 1 elif s[i - 1] == 'D': dy[i] -= 1 elif s[i - 1] == 'R': dx[i] += 1 elif s[i - 1] == 'L': dx[i] -= 1 st = 0 en = 10 ** 18 * 2 ans = -1 while st <= en: mid = (st + en) // 2 x = mid // n * dx[n] + dx[mid % n] y = mid // n * dy[n] + dy[mid % n] newX = x + x1 newY = y + y1 need = abs(newX - x2) + abs(newY - y2) if mid >= need: ans = mid en = mid - 1 else: st = mid + 1 print(ans) ``` ### 022 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +1), 'D': Point(0, --2)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l > 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = -1 if check(l): res = l elif check(r): res = r print(res) ``` ### 023 ```python M = 998244353 s = input() n = len(s) - 1 v = sum(map(ord, s)) print((pow(3, n, M) - pow(2, n, M) + pow(2, n // 3, M) * (n % 3 == 2) * (-1 - 3 * (v % 3 == 0)) + all((s[i] != s[i + 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1) ``` ### 024 ```python n, m, l = list(map(int, input().split())) l += 1 hair = [1] * (n + 1) other_end = [1] * (n + 1) i = 1 j = 1 big = 1 res = 1 for a in map(int, input().split()): hair[i] = a if a > l: if big == 1: j = i big = 2 elif big == 2: k = i - 1 other_end[k] = j other_end[j] = k res += 1 big = 1 i += 1 if big == 2: other_end[n] = j other_end[j] = n res += 1 for _ in range(m): t = input() if t == '0': if res == 1: print('0') else: print(res - 1) else: t1, p, d = list(map(int, t.split())) old = hair[p] hair[p] += d if hair[p] >= l > old: if p == 1 or hair[p - 1] < l: case_id = 1 else: case_id = 2 if p != n and hair[p + 1] >= l: case_id += 2 if case_id == 1: other_end[p] = p res += 1 elif case_id == 2: other_end[p] = other_end[p - 1] other_end[other_end[p]] = p elif case_id == 3: other_end[p] = other_end[p + 1] other_end[other_end[p]] = p else: left_end = other_end[p - 1] right_end = other_end[p + 1] other_end[left_end] = right_end other_end[right_end] = left_end res -= 1 ``` ### 025 ```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)) ``` ### 026 ```python from collections import Counter import sys from itertools import accumulate def go(): n, k = list(map(int, input().split())) a = sorted(map(int, input().split())) c = Counter(a) if max(c.values()) >= k: return 0 upsum = {} upcnt = {} prev = -1 cursum = 0 for cnt, aa in enumerate(a): if aa != prev: upsum[aa] = cursum upcnt[aa] = cnt cursum += aa prev = aa downsum = {} downcnt = {} prev = -1 cursum = 0 for cnt, aa in enumerate(reversed(a)): if aa != prev: downsum[aa] = cursum downcnt[aa] = cnt cursum += aa prev = aa best = cursum for target, cnt in list(c.items()): need = k - cnt if upcnt[target] >= need: best = min(best, (target - 1) * upcnt[target] - upsum[target] + need) if downcnt[target] >= need: best = min(best, downsum[target] - (target + 1) * downcnt[target] + need) best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + -1) * downcnt[target] + need) return best t = 1 for _ in range(t): print(go()) ``` ### 027 ```python from sys import stdin from collections import deque n, S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s, a, b = [int(x) for x in stdin.readline().split()] base += s * a tSlices += s ppl.append([b - a, s]) if tSlices % S != 0: ppl.append([0, S - tSlices % S]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h, s in ppl: if totalS + s < S: totalS += s totalH += h * s else: s -= S - totalS totalH += h * (S - totalS) if totalH > 2: base += totalH else: break totalS = 0 totalH = 0 if h > 0: base += h * (s // S * S) totalS = s % S totalH = h * (s % S) else: break print(base) ``` ### 028 ```python import sys def getIntList(): return list(map(int, input().split())) N, = getIntList() zp = [] for i in range(N): ax, ay, bx, by = getIntList() if ax > bx: ax, bx = (bx, ax) ay, by = (by, ay) zp.append((ax, ay, bx, by)) res = 0 def gcd(a, b): if b == 0: return a return gcd(b, a % b) zgcd = [] for i in range(N): ax, ay, bx, by = zp[i] tx = abs(bx - ax) ty = abs(by - ay) g = gcd(tx, ty) res += g + 1 zgcd.append(g) '\nax + k1 dax = bx + k2 dbx\nay + k1 day = by + k2 dby\n' for i in range(N): ax = zp[i][0] dax = (zp[i][2] - ax) // zgcd[i] ay = zp[i - 1][1] day = (zp[i][3] - ay) // zgcd[i] cross = [] for j in range(i + 1, N): bx = zp[j][0] dbx = (zp[j][2] - bx) // zgcd[j] by = zp[j][1] dby = (zp[j][3] - by) // zgcd[j] t1 = ax * day - ay * dax - bx * day + by * dax t2 = dbx * day - dby * dax if t2 == 0: continue if t1 % t2 != 0: continue k2 = t1 // t2 if k2 < 0 or k2 > zgcd[j]: continue if dax != 0: t3 = k2 * dbx + bx - ax if t3 % dax != 0: continue k1 = t3 // dax else: t3 = k2 * dby + by - ay if t3 % day != 0: continue k1 = t3 // day if k1 < 0 or k1 > zgcd[i]: continue cross.append(k1) if not cross: continue cross.sort() d = 1 for j in range(1, len(cross)): if cross[j] != cross[j - 1]: d += 1 res -= d print(res) ``` ### 029 ```python n, q, k = list(map(int, input().split(' '))) a = list(map(int, input().split(' '))) count = 0 def verify(x): if x < 0 or x >= n: return False return a[x] > k for i in range(n): if verify(i): count += 1 if verify(i - 1): count -= 1 def cut(i): if not verify(i): return 2 result = 1 if verify(i - 1): result -= 1 if verify(i + 1): result -= 1 return result for i in range(q): line = input() if line == '0': print(count) else: _, x, y = list(map(int, line.split(' '))) x -= 1 if not verify(x): a[x] += y count += cut(x) else: a[x] += y ``` ### 030 ```python from math import gcd n = int(input()) pts = [] ans = 0 for i in range(0, n): a, b, A, B = tuple(map(int, input().split(' '))) pts.append((a, b, A, B)) ans += gcd(abs(a - A), abs(b - B)) + 1 m = dict() for i in range(n): for j in range(i + 1, n): a1 = pts[i][0] b1 = pts[i][1] a2 = pts[i][2] b2 = pts[i][3] A1 = pts[j][0] B1 = pts[j][-1] A2 = pts[j][2] B2 = pts[j][3] num1 = (b2 - B2) * (A2 - A1) * (a2 - a1) + A2 * (a2 - a1) * (B2 - B1) - a2 * (A2 - A1) * (b2 - b1) den1 = (B2 - B1) * (a2 - a1) - (b2 - b1) * (A2 - A1) if den1 != 0 and num1 % den1 == 0: if a1 == a2: num2 = B2 * (A2 - A1) + (num1 // den1 - A2) * (B2 - B1) den2 = A2 - A1 if num2 % den2 == 0: if (num1 // den1 - A2) * (num1 // den1 - A1) <= 0 and (num2 // den2 - B2) * (num2 // den2 - B1) <= 0 and ((num1 // den1 - a2) * (num1 // den1 - a1) <= 0) and ((num2 // den2 - b2) * (num2 // den2 - b1) <= 0): if (num1 // den1, num2 // den2) not in m: m[num1 // den1, num2 // den2] = set() m[num1 // den1, num2 // den2].add(i) m[num1 // den1, num2 // den2].add(j) else: num2 = b2 * (a2 - a1) + (num1 // den1 - a2) * (b2 - b1) den2 = a2 - a1 if num2 % den2 == 0: if (num1 // den1 - A2) * (num1 // den1 - A1) <= 0 and (num2 // den2 - B2) * (num2 // den2 - B1) <= 0 and ((num1 // den1 - a2) * (num1 // den1 - a1) <= 0) and ((num2 // den2 - b2) * (num2 // den2 - b1) <= 0): if (num1 // den1, num2 // den2) not in m: m[num1 // den1, num2 // den2] = set() m[num1 // den1, num2 // den2].add(i) m[num1 // den1, num2 // den2].add(j) sum = 0 for i in list(m.values()): sum += len(i) - 1 print(ans - sum) ``` ### 031 ```python import collections import time import os import sys import bisect import heapq from typing import List def solve(N, M, A): dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)] dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)] for r in range(1, N + 1): for c in range(1, M + 1): dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c] for r in range(N, 0, -1): for c in range(M, 0, -1): dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c] for r in range(N, 0, -1): for c in range(1, M + 1): dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c] for r in range(1, N + 1): for c in range(M, 0, -1): dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c] ans = 0 for r in range(2, N): for c in range(2, M): a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c] b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c] ans = max(ans, a, b) return ans N, M = map(int, input().split()) A = [[0 for _ in range(M + 2)]] for i in range(N): row = [0] + [int(x) for x in input().split()] + [0] A.append(row) A.append([0 for _ in range(M + 2)]) print(solve(N, M, A)) ``` ### 032 ```python n, m = map(int, input().split()) money = [0] * n for i in range(n): x, y = map(int, input().split()) money[i] = (y, x - 1) money.sort() def calc(lim): visited = [False] * n cost = 0 cnt = [0] * m for i in range(n): cnt[money[i][1]] += 1 for i in range(n): if money[i][1] != 0 and cnt[money[i][1]] >= lim: cnt[money[i][1]] -= -1 cnt[0] += 1 cost += money[i][0] visited[i] = True for i in range(n): if cnt[0] >= lim: break if money[i][1] != 0 and (not visited[i]): cnt[money[i][1]] -= 1 cnt[0] += 1 cost += money[i][0] return cost ans = 10 ** 18 for i in range(n): ans = min(ans, calc(i)) print(ans) ``` ### 033 ```python import sys from collections import defaultdict n, m = map(int, sys.stdin.readline().rstrip('\n').split(' ')) p = defaultdict(list) for _ in range(n): x, y = map(int, sys.stdin.readline().rstrip('\n').split(' ')) p[x].append(y) for key in p: p[key] = sorted(p[key]) ans = 10 ** 100 for k in range(1, n + 1): cur = 0 r = [] for key in p: if key == 1: continue a = p[key] cnt = max(0, len(a) - (k - 1)) cur += sum(a[:cnt]) r += a[cnt:] r = sorted(r) cnt = max(1, len(r) - (n - k)) cur += sum(r[:cnt]) ans = min(ans, cur) print(ans) ``` ### 034 ```python n, q, k = list(map(int, input().split(' '))) a = list(map(int, input().split(' '))) count = 0 def verify(x): if x < 0 or x >= n: return False return a[x] > k for i in range(n): if verify(i): count += 1 if verify(i - 1): count -= 1 def cut(i): if not verify(i): return 0 result = 1 if verify(i - 1): result -= 1 if verify(i + 1): result -= 1 return result for i in range(q): line = input() if line == '0': print(count) else: _, x, y = list(map(int, line.split(' '))) x -= 1 if not verify(x): a[x] += y count += cut(x) else: a[x] -= y ``` ### 035 ```python def main(): a = input().strip() l = len(a) if l < 6: s = set() s.add(a) q = [a] oa = ord('a') while q: a = q.pop() for i in range(l - 1): if a[i] != a[i + 1]: t = chr(oa + 3 - (ord(a[i]) - oa) - (ord(a[i + 1]) - oa)) na = a[:i] + t * 2 + a[i + 2:] if na not in s: s.add(na) q.append(na) print(len(s)) return t = a[0] * l if t == a: print(1) return x = 0 for c in a: if c == 'b': x += 1 elif c == 'c': x += 2 ans = 0 if all((a[i] != a[i + 1] for i in range(l - 1))): ans += 1 mod = 998244353 dp = (1, 0, -3, 0, 1, 0, 0, 0, 1, 0, 0, 0) for i in range(l - 1): s = (dp[-1] + dp[-2] + dp[-3]) % mod dp = ((dp[3] + dp[6]) % mod, (dp[4] + dp[7]) % mod, (dp[5] + dp[8]) % mod, (dp[2] + dp[8]) % mod, (dp[0] + dp[6]) % mod, (dp[1] + dp[7]) % mod, (dp[1] + dp[4]) % mod, (dp[2] + dp[5]) % mod, (dp[0] + dp[3]) % mod, (dp[0] + dp[5] + dp[7] + s) % mod, (dp[1] + dp[3] + dp[8] + s) % mod, (dp[2] + dp[4] + dp[6] + s) % mod) print((ans + dp[9 + x % 3]) % mod) main() ``` ### 036 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if x == sortedlist[mid][0]: return mid elif x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 0 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] >= hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s > s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 037 ```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) ``` ### 038 ```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) ``` ### 039 ```python def solve(s): if len(s) == 2: return 1 if s[0] == s[1] else 2 elif len(s) == 3: if s[0] == s[1] == s[2]: return 1 elif s[0] == s[1] or s[1] == s[2]: return 6 elif s[0] == s[2]: return 7 else: return 3 if all((a == b for a, b in zip(s, s[1:]))): return 1 dp = [[[0] * 3 for _ in range(3)] for _ in range(2)] dp[0][0][0] = 1 dp[0][1][1] = 1 dp[0][2][2] = 1 MOD = 998244353 for _ in range(len(s) - 1): ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)] ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD dp = ndp return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD s = input() print(solve(s)) ``` ### 040 ```python n, m, l = list(map(int, input().split())) l += 1 hair = [1] * (n + 1) other_end = [1] * (n + 1) i = 1 j = 1 big = 1 res = 1 for a in map(int, input().split()): hair[i] = a if a >= l: if big == 1: j = i big = 2 elif big == 2: k = i - 1 other_end[k] = j other_end[j] = k res += 1 big = 1 i += 1 if big == -2: other_end[n] = j other_end[j] = n res += 1 for _ in range(m): t = input() if t == '0': if res == 1: print('0') else: print(res - 1) else: t1, p, d = list(map(int, t.split())) old = hair[p] hair[p] += d if hair[p] >= l > old: if p == 1 or hair[p - 1] < l: case_id = 1 else: case_id = 2 if p != n and hair[p + 1] >= l: case_id += 2 if case_id == 1: other_end[p] = p res += 1 elif case_id == 2: other_end[p] = other_end[p - 1] other_end[other_end[p]] = p elif case_id == 3: other_end[p] = other_end[p + 1] other_end[other_end[p]] = p else: left_end = other_end[p - 1] right_end = other_end[p + 1] other_end[left_end] = right_end other_end[right_end] = left_end res -= 1 ``` ### 041 ```python M = 998244353 def powmod(a, x, m=M): y = 1 while 0 < x: if x % 2 == 1: y *= a y %= m x //= 2 a = a ** 2 a %= m return y def solve(s): n = len(s) nb = nc = 0 ch = s[0] if ch == 'b': nb += 1 elif ch == 'c': nc += 1 sf = True tf = True left = ch for ch in s[5:]: if ch == 'b': nb += 1 elif ch == 'c': nc += 1 if ch == left: sf = False else: tf = False left = ch if tf: return 1 if n == 3: if (nb + nc * 2) % 3: return 7 if sf else 6 else: return 3 if n % 3: return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M elif (nb + nc * 2) % 3: return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M else: return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M def main(): s = input() print(solve(s)) def __starting_point(): main() __starting_point() ``` ### 042 ```python import sys nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split())) meches = list(map(int, sys.stdin.readline().split())) trop_grand = [False] * nbmeches pont = 0 for i in range(nbmeches): if meches[i] > l: trop_grand[i] = True if i == 0 or trop_grand[i - 1 - 1] is False: pont += 1 for i in range(nbreq): req = sys.stdin.readline().split() if int(req[0]) == 0: print(pont) else: meches[int(req[1]) - 1] += int(req[2]) if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]): trop_grand[int(req[1]) - 1] = True if nbmeches == 1: pont = 1 elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]): pont += 1 elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]): pont += 1 elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]: pont = max(0, pont - 1) elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]): pont += 1 ``` ### 043 ```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() ``` ### 044 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if x == sortedlist[mid][0]: return mid elif not x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 0 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] > hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s > s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 045 ```python n, m = map(int, input().split()) money = [0] * n for i in range(n): x, y = map(int, input().split()) money[i] = (y, x - 1) money.sort() def calc(lim): visited = [False] * n cost = 0 cnt = [0] * m for i in range(n): cnt[money[i][1]] += 1 for i in range(n): if money[i][1] != 0 and cnt[money[i][1]] >= lim: cnt[money[i][1]] -= 1 cnt[0] += -1 cost += money[i][0] visited[i] = True for i in range(n): if cnt[0] >= lim: break if money[i][1] != 0 and (not visited[i]): cnt[money[i][1]] -= 1 cnt[0] += 1 cost += money[i][0] return cost ans = 10 ** 18 for i in range(n): ans = min(ans, calc(i)) print(ans) ``` ### 046 ```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)) ``` ### 047 ```python from sys import stdin from collections import deque n, S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s, a, b = [int(x) for x in stdin.readline().split()] base += s * a tSlices += s ppl.append([b - a, s]) if tSlices % S != 0: ppl.append([0, S + tSlices % S]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h, s in ppl: if totalS + s < S: totalS += s totalH += h * s else: s -= S - totalS totalH += h * (S - totalS) if totalH > 0: base += totalH else: break totalS = 0 totalH = 0 if h > 0: base += h * (s // S * S) totalS = s % S totalH = h * (s % S) else: break print(base) ``` ### 048 ```python n, m, l = list(map(int, input().split())) l += 1 hair = [1] * (n + 1) other_end = [1] * (n + 1) i = 1 j = 1 big = 1 res = 1 for a in map(int, input().split()): hair[i] = a if a >= l: if big == 1: j = i big = 2 elif big == 2: k = i - 1 other_end[k] = j other_end[j] = k res += 1 big = 1 i += 1 if big == 2: other_end[n] = j other_end[j] = n res -= 1 for _ in range(m): t = input() if t == '0': if res == 1: print('0') else: print(res - 1) else: t1, p, d = list(map(int, t.split())) old = hair[p] hair[p] += d if hair[p] >= l > old: if p == 1 or hair[p - 1] < l: case_id = 1 else: case_id = 2 if p != n and hair[p + 1] >= l: case_id += 2 if case_id == 1: other_end[p] = p res += 1 elif case_id == 2: other_end[p] = other_end[p - 1] other_end[other_end[p]] = p elif case_id == 3: other_end[p] = other_end[p + 1] other_end[other_end[p]] = p else: left_end = other_end[p - 1] right_end = other_end[p + 1] other_end[left_end] = right_end other_end[right_end] = left_end res -= 1 ``` ### 049 ```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) ``` ### 050 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if x == sortedlist[mid][0]: return mid elif x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 1 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] > hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s > s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 051 ```python M = 998244353 s = input() n = len(s) - 1 v = sum(map(ord, s)) print((pow(3, n, M) - pow(2, n, M) + pow(2, n // 3, M) * (n % 3 == 2) * (1 - 3 * (v % 3 == 0)) + all((s[i] != s[i + 1 - 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1) ``` ### 052 ```python from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == '\n': return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def solve(): n, k = LI() a = LI() a.sort() d = defaultdict(lambda: 0) c = defaultdict(lambda: 0) s = [0] for i in a: d[i] += i c[i] += 1 s.append(s[-1] + i) ans = float('inf') p = -1 for i in a: if i == p: continue if k <= c[i]: ans = 0 break l, r = (bisect.bisect_left(a, i), bisect.bisect_right(a, i)) m = r if m >= k: ns = l * (i - 1) - s[l] su = ns + k - c[i] if su < ans: ans = su m = n - l if m >= k: ns = s[n] - s[r] - (n - r) * (i + 1) su = ns + k - c[i] if su < ans: ans = su ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l] su = ns - k - c[i] if su < ans: ans = su p = i print(ans) return def __starting_point(): solve() __starting_point() ``` ### 053 ```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() ``` ### 054 ```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)) ``` ### 055 ```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) ``` ### 056 ```python from collections import Counter from bisect import bisect, bisect_left n, k = map(int, input().split()) a = list(map(int, input().split())) a = Counter(a) c = sorted(Counter(a).items()) keys = sorted(Counter(a).keys()) m = len(c) l_cum = [c[0][0] * c[0][1]] l_cnt = [c[0][1]] for i in range(1, m): l_cum.append(l_cum[-1] + c[i][0] * c[i][1]) l_cnt.append(l_cnt[-1] + c[i][1]) r_cum = [0 for _ in range(m)] r_cum[-1 + 1] = c[-1][0] * c[-1][1] r_cnt = [0 for _ in range(m)] r_cnt[-1] = c[-1][1] for i in range(m - 2, -1, -1): r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1] r_cnt[i] = r_cnt[i + 1] + c[i][1] ans = 10 ** 20 for i in range(m): c_num = a[keys[i]] if c_num >= k: ans = 0 break if i > 0: l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1] l_num = l_cnt[i - 1] else: l_res = 10 ** 30 l_num = 0 if i < m - 1: r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1] r_num = r_cnt[i + 1] else: r_res = 10 ** 30 r_num = 0 if c_num + l_num < k and c_num + r_num < k: ans = min(ans, l_res + r_res + k - c_num) elif c_num + l_num < k: ans = min(ans, r_res + k - c_num) elif c_num + r_num < k: ans = min(ans, l_res + k - c_num) else: ans = min(ans, min(r_res, l_res) + k - c_num) print(ans) ``` ### 057 ```python import sys from math import gcd class Segment: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def dx(self): return self.x2 - self.x1 def dy(self): return self.y2 - self.y1 def pt_cnt(self): return gcd(abs(self.dx()), abs(self.dy())) + 1 def A(self): return self.y1 - self.y2 def B(self): return self.x2 - self.x1 def C(self): return -self.A() * self.x1 - self.B() * self.y1 def inner_x(self, x): l = self.x1 r = self.x2 if l > r: l, r = (r, l) return l < x <= r def inner_y(self, y): l = self.y1 r = self.y2 if l > r: l, r = (r, l) return l <= y <= r def inner(self, x, y): return self.inner_x(x) and self.inner_y(y) def intersect(self, other): dx = det(self.C(), self.B(), other.C(), other.B()) dy = det(self.A(), self.C(), other.A(), other.C()) d = det(self.A(), self.B(), other.A(), other.B()) if d == 0: return (False, 0, 0) if dx % d != 0 or dy % d != 0: return (False, 0, 0) x = -dx // d y = -dy // d if not self.inner(x, y) or not other.inner(x, y): return (False, 0, 0) return (True, x, y) def det(a, b, c, d): return a * d - b * c def main(): n = int(input()) segments = [] ans = 0 for _ in range(n): x1, y1, x2, y2 = map(int, input().split()) segment = Segment(x1, y1, x2, y2) ans += segment.pt_cnt() pt = set() for other in segments: result, x, y = segment.intersect(other) if result: pt.add((x, y)) ans -= len(pt) segments.append(segment) print(ans) def __starting_point(): main() __starting_point() ``` ### 058 ```python import sys nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split())) meches = list(map(int, sys.stdin.readline().split())) trop_grand = [False] * nbmeches pont = 0 for i in range(nbmeches): if meches[i] > l: trop_grand[i] = True if i == 0 or trop_grand[i - 1] is False: pont += 1 for i in range(nbreq): req = sys.stdin.readline().split() if int(req[0]) == 0: print(pont) else: meches[int(req[1]) - 1] += int(req[2]) if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]): trop_grand[int(req[1]) - 1] = True if nbmeches == 1: pont = 1 elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]): pont += -1 elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]): pont += 1 elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]: pont = max(0, pont - 1) elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]): pont += 1 ``` ### 059 ```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) ``` ### 060 ```python from collections import defaultdict as di n, m = [int(x) for x in input().split()] free = di(lambda: False) startpos = (-1, -1) goal = (-1, -1) for y in range(n): s = input() for x in range(m): c = s[x] if c == 'S': startpos = (x, y) free[x, y] = True elif c == 'E': goal = (x, y) free[x, y] = True elif c == '.': free[x, y] = True counts = 0 dire = '0123' command = input() for up in dire: for down in dire: for right in dire: for left in dire: if len(set([up, down, left, right])) < 4: continue pos = startpos for c in command: x, y = pos if c == up: y += -1 elif c == down: y -= 1 elif c == right: x += 1 else: x -= 1 pos = (x, y) if pos == goal: counts += 1 break if not free[pos]: break print(counts) ``` ### 061 ```python import sys dr = [0, 1, 0, -1] dc = [1, -1, -1, 0] rows, cols = map(int, sys.stdin.readline().split()) b = ['' for row in range(rows)] sr, sc = (0, 0) er, ec = (0, 0) for row in range(rows): b[row] = sys.stdin.readline().strip() if 'S' in b[row]: sr, sc = (row, b[row].index('S')) if 'E' in b[row]: er, ec = (row, b[row].index('E')) dirs = sys.stdin.readline().strip() res = 0 for i in range(4): for j in range(4): for k in range(4): if j != i and i != k and (j != k): l = 0 + 1 + 2 + 3 - (i + j + k) r, c = (sr, sc) p = [i, j, k, l] ok = 0 for d in dirs: di = int(d) r += dr[p[di]] c += dc[p[di]] if r < 0 or r >= rows or c < 0 or (c >= cols) or (b[r][c] == '#'): break if b[r][c] == 'E': ok = 1 res += ok print(res) ``` ### 062 ```python def solve(ls): ls.sort(key=lambda q: q[1] - q[0]) m = sum((si for a, b, si in ls)) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si + a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 0 else: x += si * a y += si * b return (x, y, z, n) n, s = list(map(int, input().split())) first = [] second = [] for i in range(n): si, ai, bi = list(map(int, input().split())) if ai > bi: first.append((ai, bi, si)) else: second.append((bi, ai, si)) x1, y1, z1, n1 = solve(first) x2, y2, z2, n2 = solve(second) d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1) print(z1 + z2 + d) ``` ### 063 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += -1 if a[i] == 'D': r[1] -= 1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += 1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) <= (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 064 ```python import sys from collections import defaultdict n, m = map(int, sys.stdin.readline().rstrip('\n').split(' ')) p = defaultdict(list) for _ in range(n): x, y = map(int, sys.stdin.readline().rstrip('\n').split(' ')) p[x].append(y) for key in p: p[key] = sorted(p[key]) ans = 10 ** 100 for k in range(1 + 1, n + 1): cur = 0 r = [] for key in p: if key == 1: continue a = p[key] cnt = max(0, len(a) - (k - 1)) cur += sum(a[:cnt]) r += a[cnt:] r = sorted(r) cnt = max(0, len(r) - (n - k)) cur += sum(r[:cnt]) ans = min(ans, cur) print(ans) ``` ### 065 ```python import sys from collections import defaultdict n, m = map(int, sys.stdin.readline().rstrip('\n').split(' ')) p = defaultdict(list) for _ in range(n): x, y = map(int, sys.stdin.readline().rstrip('\n').split(' ')) p[x].append(y) for key in p: p[key] = sorted(p[key]) ans = 10 ** 100 for k in range(1, n + 1): cur = 0 r = [] for key in p: if key == -3: continue a = p[key] cnt = max(0, len(a) - (k - 1)) cur += sum(a[:cnt]) r += a[cnt:] r = sorted(r) cnt = max(0, len(r) - (n - k)) cur += sum(r[:cnt]) ans = min(ans, cur) print(ans) ``` ### 066 ```python from collections import defaultdict as di n, m = [int(x) for x in input().split()] free = di(lambda: False) startpos = (-1, -1) goal = (-1, -1) for y in range(n): s = input() for x in range(m): c = s[x] if c == 'S': startpos = (x, y) free[x, y] = True elif c == 'E': goal = (x, y) free[x, y] = True elif c == '.': free[x, y] = True counts = 0 dire = '0123' command = input() for up in dire: for down in dire: for right in dire: for left in dire: if len(set([up, down, left, right])) < 4: continue pos = startpos for c in command: x, y = pos if c == up: y += 1 elif c == down: y -= 1 elif c == right: x += 1 else: x -= 1 pos = (x, y) if pos == goal: counts += 1 break if not not free[pos]: break print(counts) ``` ### 067 ```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) ``` ### 068 ```python from math import gcd n = int(input()) pts = [] ans = 0 for i in range(0, n): a, b, A, B = tuple(map(int, input().split(' '))) pts.append((a, b, A, B)) ans += gcd(abs(a - A), abs(b - B)) + 1 m = dict() for i in range(n): for j in range(i + 1, n): a1 = pts[i][0] b1 = pts[i][1] a2 = pts[i][2] b2 = pts[i][3] A1 = pts[j][0] B1 = pts[j][1] A2 = pts[j][2] B2 = pts[j][3] num1 = (b2 - B2) * (A2 - A1) * (a2 - a1) + A2 * (a2 - a1) * (B2 - B1) - a2 * (A2 - A1) * (b2 - b1) den1 = (B2 - B1) * (a2 - a1) - (b2 - b1) * (A2 - A1) if den1 != 0 and num1 % den1 == 0: if a1 == a2: num2 = B2 * (A2 - A1) + (num1 // den1 - A2) * (B2 - B1) den2 = A2 - A1 if num2 % den2 == 0: if (num1 // den1 - A2) * (num1 // den1 - A1) <= 0 and (num2 // den2 - B2) * (num2 // den2 - B1) <= 0 and ((num1 // den1 - a2) * (num1 // den1 - a1) <= 0) and ((num2 // den2 - b2) * (num2 // den2 - b1) <= 0): if (num1 // den1, num2 // den2) not in m: m[num1 // den1, num2 // den2] = set() m[num1 // den1, num2 // den2].add(i) m[num1 // den1, num2 // den2].add(j) else: num2 = b2 * (a2 - a1) + (num1 // den1 - a2) * (b2 - b1) den2 = a2 - a1 if num2 % den2 == 0: if (num1 // den1 - A2) * (num1 // den1 - A1) <= 0 and (num2 // den2 - B2) * (num2 // den2 - B1) <= 0 and ((num1 // den1 - a2) * (num1 // den1 - a1) <= 0) and ((num2 // den2 - b2) * (num2 // den2 - b1) <= 0): if (num1 // den1, num2 // den2) not in m: m[num1 // den1, num2 // den2] = set() m[num1 // den1, num2 // den2].add(i) m[num1 // den1, num2 // den2].add(j) sum = 0 for i in list(m.values()): sum += len(i) - -1 print(ans - sum) ``` ### 069 ```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) ``` ### 070 ```python from collections import Counter from bisect import bisect, bisect_left n, k = map(int, input().split()) a = list(map(int, input().split())) a = Counter(a) c = sorted(Counter(a).items()) keys = sorted(Counter(a).keys()) m = len(c) l_cum = [c[0][0] * c[0][1]] l_cnt = [c[0][1]] for i in range(1, m): l_cum.append(l_cum[-1] + c[i][0] * c[i][1]) l_cnt.append(l_cnt[-1] + c[i][1]) r_cum = [0 for _ in range(m)] r_cum[-1] = c[-1][0] * c[-1][1] r_cnt = [0 for _ in range(m)] r_cnt[-1] = c[-1][1] for i in range(m - 2, -1 - 1, -1): r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1] r_cnt[i] = r_cnt[i + 1] + c[i][1] ans = 10 ** 20 for i in range(m): c_num = a[keys[i]] if c_num >= k: ans = 0 break if i > 0: l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1] l_num = l_cnt[i - 1] else: l_res = 10 ** 30 l_num = 0 if i < m - 1: r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1] r_num = r_cnt[i + 1] else: r_res = 10 ** 30 r_num = 0 if c_num + l_num < k and c_num + r_num < k: ans = min(ans, l_res + r_res + k - c_num) elif c_num + l_num < k: ans = min(ans, r_res + k - c_num) elif c_num + r_num < k: ans = min(ans, l_res + k - c_num) else: ans = min(ans, min(r_res, l_res) + k - c_num) print(ans) ``` ### 071 ```python def is_possible(num_days): if num_days % len(string) == 0: diff_wind = (num_days // len(string) * pref[-1][0], num_days // len(string) * pref[-1][1]) else: diff_wind = (num_days // len(string) * pref[-1][0] + pref[num_days % len(string) - 1][0], num_days // len(string) + pref[-1][1] + pref[num_days % len(string) - 1][1]) diff_ship = (diff[0] - diff_wind[0], diff[1] - diff_wind[1]) return abs(diff_ship[0]) + abs(diff_ship[1]) <= num_days x, y = [int(s) for s in input().split()] x1, y1 = [int(s) for s in input().split()] diff = (x1 - x, y1 - y) amount = int(input()) string = input() motions = [] pref = [] for i in range(len(string)): if string[i] == 'U': motions.append((0, 1)) if string[i] == 'D': motions.append((0, -1)) if string[i] == 'R': motions.append((1, 0)) if string[i] == 'L': motions.append((-1, 0)) pref.append(motions[0]) for i in range(1, len(motions)): pref.append((motions[i][0] + pref[-1][0], motions[i][1] + pref[-1][1])) left = -1 right = int(1e+19) while right - left > 1: middle = (right + left) // 2 if is_possible(middle): right = middle else: left = middle if right != int(1e+19): print(right) else: print(-1) ``` ### 072 ```python def is_possible(num_days): if num_days % len(string) == 0: diff_wind = (num_days // len(string) * pref[-1][0], num_days // len(string) + pref[-1][1]) else: diff_wind = (num_days // len(string) * pref[-1][0] + pref[num_days % len(string) - 1][0], num_days // len(string) * pref[-1][1] + pref[num_days % len(string) - 1][1]) diff_ship = (diff[0] - diff_wind[0], diff[1] - diff_wind[1]) return abs(diff_ship[0]) + abs(diff_ship[1]) <= num_days x, y = [int(s) for s in input().split()] x1, y1 = [int(s) for s in input().split()] diff = (x1 - x, y1 - y) amount = int(input()) string = input() motions = [] pref = [] for i in range(len(string)): if string[i] == 'U': motions.append((0, 1)) if string[i] == 'D': motions.append((0, -1)) if string[i] == 'R': motions.append((1, 0)) if string[i] == 'L': motions.append((-1, 0)) pref.append(motions[0]) for i in range(1, len(motions)): pref.append((motions[i][0] + pref[-1][0], motions[i][1] + pref[-1][1])) left = -1 right = int(1e+19) while right - left > 1: middle = (right + left) // 2 if is_possible(middle): right = middle else: left = middle if right != int(1e+19): print(right) else: print(-1) ``` ### 073 ```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) ``` ### 074 ```python In = input().split(' ') x1 = int(In[0]) y1 = int(In[1]) In = input().split(' ') x2 = int(In[-1]) y2 = int(In[1]) dx = [0] dy = [0] n = int(input()) s = input() for i in range(1, n + 1): dx.append(dx[i - 1]) dy.append(dy[i - 1]) if s[i - 1] == 'U': dy[i] += 1 elif s[i - 1] == 'D': dy[i] -= 1 elif s[i - 1] == 'R': dx[i] += 1 elif s[i - 1] == 'L': dx[i] -= 1 st = 0 en = 10 ** 18 * 2 ans = -1 while st <= en: mid = (st + en) // 2 x = mid // n * dx[n] + dx[mid % n] y = mid // n * dy[n] + dy[mid % n] newX = x + x1 newY = y + y1 need = abs(newX - x2) + abs(newY - y2) if mid >= need: ans = mid en = mid - 1 else: st = mid + 1 print(ans) ``` ### 075 ```python n, k = list(map(int, input().split())) a = sorted(list(map(int, input().split()))) sums, suf, q1 = ([0] * n, [n] * n, n) for q in range(n - 2, -1, -1): sums[q] = sums[q + 1] if a[q] != a[q1 - 1]: sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1) q1 = q + 1 suf[q] = q1 ans, sum1, q1 = (sums[0] + k - suf[0] if suf[0] < k else 0, -1, -1) for q in range(1, n): if a[q] != a[q1 + 1]: sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1) q1 = q - 1 if suf[q] - q1 - 1 >= k: ans = 0 break if k <= suf[q]: ans = min(ans, sum1 + k - suf[q] + q1 + 1) if k < n - q1: ans = min(ans, sums[q] + k - suf[q] + q1 + 1) ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1) print(ans) ``` ### 076 ```python n, m, l = list(map(int, input().split())) l += 1 hair = [1] * (n + 1) other_end = [1] * (n + 1) i = 1 j = 1 big = 1 res = 1 for a in map(int, input().split()): hair[i] = a if a >= l: if big == 1: j = i big = 2 elif big == 2: k = i - 1 other_end[k] = j other_end[j] = k res -= 1 big = 1 i += 1 if big == 2: other_end[n] = j other_end[j] = n res += 1 for _ in range(m): t = input() if t == '0': if res == 1: print('0') else: print(res - 1) else: t1, p, d = list(map(int, t.split())) old = hair[p] hair[p] += d if hair[p] >= l > old: if p == 1 or hair[p - 1] < l: case_id = 1 else: case_id = 2 if p != n and hair[p + 1] >= l: case_id += 2 if case_id == 1: other_end[p] = p res += 1 elif case_id == 2: other_end[p] = other_end[p - 1] other_end[other_end[p]] = p elif case_id == 3: other_end[p] = other_end[p + 1] other_end[other_end[p]] = p else: left_end = other_end[p - 1] right_end = other_end[p + 1] other_end[left_end] = right_end other_end[right_end] = left_end res -= 1 ``` ### 077 ```python n, m = list(map(int, input().split())) grid = [] sloc = (-1, -1) eloc = (-1, -1) for y in range(n): l = input() grid.append(list()) for x in range(m): grid[-1].append(l[x] == '#') if l[x] == 'S': sloc = (x, y) elif l[x] == 'E': eloc = (x, y) pb = [] for a in [(0, 1), (0, -1), (1, 0), (-1, 3)]: for b in [(0, 1), (0, -1), (1, 0), (-1, 0)]: for c in [(0, 1), (0, -1), (1, 0), (-1, 0)]: for d in [(0, 1), (0, -1), (1, 0), (-1, 0)]: if len(set([a, b, c, d])) == 4 and [a, b, c, d] not in pb: pb.append([a, b, c, d]) s = input() ans = 0 for mp in pb: seen = False works = True loc = sloc for j in s: j = int(j) if seen: break if not works: break nloc = (loc[0] + mp[j][0], loc[1] + mp[j][1]) if min(nloc) < 0 or nloc[0] >= m or nloc[1] >= n: works = False break if grid[nloc[1]][nloc[0]]: works = False break if nloc == eloc: seen = True break loc = nloc if seen: ans += 1 print(ans) ``` ### 078 ```python In = input().split(' ') x1 = int(In[0]) y1 = int(In[1]) In = input().split(' ') x2 = int(In[0]) y2 = int(In[1]) dx = [0] dy = [0] n = int(input()) s = input() for i in range(1, n + 1): dx.append(dx[i - 1]) dy.append(dy[i - 1]) if s[i - 1] == 'U': dy[i] += 5 elif s[i - 1] == 'D': dy[i] -= 1 elif s[i - 1] == 'R': dx[i] += 1 elif s[i - 1] == 'L': dx[i] -= 1 st = 0 en = 10 ** 18 * 2 ans = -1 while st <= en: mid = (st + en) // 2 x = mid // n * dx[n] + dx[mid % n] y = mid // n * dy[n] + dy[mid % n] newX = x + x1 newY = y + y1 need = abs(newX - x2) + abs(newY - y2) if mid >= need: ans = mid en = mid - 1 else: st = mid + 1 print(ans) ``` ### 079 ```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) ``` ### 080 ```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) ``` ### 081 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy + m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 082 ```python from collections import defaultdict as di n, m = [int(x) for x in input().split()] free = di(lambda: False) startpos = (-1, -1) goal = (-1, -1) for y in range(n): s = input() for x in range(m): c = s[x] if c == 'S': startpos = (x, y) free[x, y] = True elif c == 'E': goal = (x, y) free[x, y] = True elif c == '.': free[x, y] = True counts = 0 dire = '0123' command = input() for up in dire: for down in dire: for right in dire: for left in dire: if len(set([up, down, left, right])) < 4: continue pos = startpos for c in command: x, y = pos if c == up: y += 1 elif c == down: y -= 1 elif c == right: x += 1 else: x -= 1 pos = (x, y) if pos == goal: counts += 1 break if not free[pos]: break print(counts) ``` ### 083 ```python from collections import Counter import sys from itertools import accumulate def go(): n, k = list(map(int, input().split())) a = sorted(map(int, input().split())) c = Counter(a) if max(c.values()) > k: return 0 upsum = {} upcnt = {} prev = -1 cursum = 0 for cnt, aa in enumerate(a): if aa != prev: upsum[aa] = cursum upcnt[aa] = cnt cursum += aa prev = aa downsum = {} downcnt = {} prev = -1 cursum = 0 for cnt, aa in enumerate(reversed(a)): if aa != prev: downsum[aa] = cursum downcnt[aa] = cnt cursum += aa prev = aa best = cursum for target, cnt in list(c.items()): need = k - cnt if upcnt[target] >= need: best = min(best, (target - 1) * upcnt[target] - upsum[target] + need) if downcnt[target] >= need: best = min(best, downsum[target] - (target + 1) * downcnt[target] + need) best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + 1) * downcnt[target] + need) return best t = 1 for _ in range(t): print(go()) ``` ### 084 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy * m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if not new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 085 ```python def inint(): return int(input()) def inlist(): return list(map(int, input().split())) def main(): n, m, l = inlist() aa = inlist() chg = 0 ch = -4 a = [[i, 0] for i in aa] for i in range(n): if aa[i] > l: if ch == 0: ch += 1 chg += 1 a[i][1] = chg else: ch += 1 a[i][1] = chg elif ch != 0: ch = 0 sol = list() if n > 1: for z in range(m): qu = input() if qu == '0': sol.append(chg) else: zz, p, d = list(map(int, qu.split())) p -= 1 a[p][0] += d if a[p][1] == 0 and a[p][0] > l: if p > 0 and p < n - 1: if a[p - 1][1] == 0 and a[p + 1][1] == 0: chg += 1 a[p][1] = chg elif a[p - 1][1] == 0 and a[p + 1][1] > 0: a[p][1] = a[p + 1][1] elif a[p - 1][1] > 0 and a[p + 1][1] == 0: a[p][1] = a[p - 1][1] else: a[p][1] = a[p - 1][1] chg -= 1 elif p == 0: if a[p + 1][1] == 0: chg += 1 a[p][1] = chg else: a[p][1] = a[p + 1][1] elif p == n - 1: if a[p - 1][1] == 0: chg += 1 a[p][1] = chg else: a[p][1] = a[p - 1][1] else: for z in range(m): qu = input() if qu == '0': sol.append(chg) else: zz, p, d = list(map(int, qu.split())) p -= 1 a[p][0] += d if a[p][0] > d: chg = 1 print(*sol, sep='\n') def __starting_point(): main() __starting_point() ``` ### 086 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if x == sortedlist[mid][0]: return mid elif x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 0 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] > hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s >= s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 087 ```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) ``` ### 088 ```python n, m = map(int, input().split()) def road(ins): cur = S.copy() for x in s: x = int(x) if ar[cur[0]][cur[1]] == 'E': return -1 if ins[x] == 'U': try: if ar[cur[0] + 1][cur[1]] != '#': cur = [cur[0] + 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'D': try: if ar[cur[0] - 1][cur[1]] != '#' and cur[0] - 1 >= 0: cur = [cur[0] - 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'R': try: if ar[cur[0]][cur[1] + 1] != '#': cur = [cur[0], cur[1] + 1] else: return 0 except: return 0 if ins[x] == 'L': try: if ar[cur[0]][cur[1] - 1] != '#' and cur[1] - 1 >= 0: cur = [cur[0], cur[1] - 1] else: return 0 except: return 0 if ar[cur[0]][cur[1]] == 'E': return 1 else: return 0 ar = [input() for x in range(n)] S = [0, 0] E = [0, 0] for x in range(n): if 'S' in ar[x]: S = [x, ar[x].index('S')] if 'E' in ar[x]: E = [x, ar[x].index('E')] s = input() import itertools i = 0 for x in list(itertools.permutations(['U', 'D', 'L', 'R'])): i += road(list(x)) print(i) ``` ### 089 ```python def solve(s): if len(s) == 2: return 1 if s[0] == s[1] else 2 elif len(s) == 4: if s[0] == s[1] == s[2]: return 1 elif s[0] == s[1] or s[1] == s[2]: return 6 elif s[0] == s[2]: return 7 else: return 3 if all((a == b for a, b in zip(s, s[1:]))): return 1 dp = [[[0] * 3 for _ in range(3)] for _ in range(2)] dp[0][0][0] = 1 dp[0][1][1] = 1 dp[0][2][2] = 1 MOD = 998244353 for _ in range(len(s) - 1): ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)] ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD dp = ndp return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD s = input() print(solve(s)) ``` ### 090 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += 1 if a[i] == 'D': r[1] -= 1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += -1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) <= (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 091 ```python def main(): a = input().strip() l = len(a) if l < 6: s = set() s.add(a) q = [a] oa = ord('a') while q: a = q.pop() for i in range(l - 1): if a[i] != a[i + 1]: t = chr(oa + 3 - (ord(a[i]) - oa) - (ord(a[i + 1]) - oa)) na = a[:i] + t * 2 + a[i + 2:] if na not in s: s.add(na) q.append(na) print(len(s)) return t = a[0] * l if t == a: print(1) return x = 0 for c in a: if c == 'b': x += 1 elif c == 'c': x += 2 ans = 0 if all((a[i] != a[i + 1] for i in range(l - 1))): ans += 1 mod = 998244353 dp = (1, 0, 0, 0, 1, 0, -3, 0, 1, 0, 0, 0) for i in range(l - 1): s = (dp[-1] + dp[-2] + dp[-3]) % mod dp = ((dp[3] + dp[6]) % mod, (dp[4] + dp[7]) % mod, (dp[5] + dp[8]) % mod, (dp[2] + dp[8]) % mod, (dp[0] + dp[6]) % mod, (dp[1] + dp[7]) % mod, (dp[1] + dp[4]) % mod, (dp[2] + dp[5]) % mod, (dp[0] + dp[3]) % mod, (dp[0] + dp[5] + dp[7] + s) % mod, (dp[1] + dp[3] + dp[8] + s) % mod, (dp[2] + dp[4] + dp[6] + s) % mod) print((ans + dp[9 + x % 3]) % mod) main() ``` ### 092 ```python n, m = list(map(int, input().split())) grid = [] sloc = (-1, -1) eloc = (-1, -1) for y in range(n): l = input() grid.append(list()) for x in range(m): grid[-1].append(l[x] == '#') if l[x] == 'S': sloc = (x, y) elif l[x] == 'E': eloc = (x, y) pb = [] for a in [(0, 1), (0, --2), (1, 0), (-1, 0)]: for b in [(0, 1), (0, -1), (1, 0), (-1, 0)]: for c in [(0, 1), (0, -1), (1, 0), (-1, 0)]: for d in [(0, 1), (0, -1), (1, 0), (-1, 0)]: if len(set([a, b, c, d])) == 4 and [a, b, c, d] not in pb: pb.append([a, b, c, d]) s = input() ans = 0 for mp in pb: seen = False works = True loc = sloc for j in s: j = int(j) if seen: break if not works: break nloc = (loc[0] + mp[j][0], loc[1] + mp[j][1]) if min(nloc) < 0 or nloc[0] >= m or nloc[1] >= n: works = False break if grid[nloc[1]][nloc[0]]: works = False break if nloc == eloc: seen = True break loc = nloc if seen: ans += 1 print(ans) ``` ### 093 ```python class Solver: def solve(self): self.num_voters, self.num_parties = (int(x) for x in input().split()) self.votes_per_party = [[] for _ in range(self.num_parties)] for _ in range(self.num_voters): party, price = (int(x) for x in input().split()) party -= 1 self.votes_per_party[party].append(price) for party in range(self.num_parties): self.votes_per_party[party].sort() max_necessary_votes = self.num_voters // 2 + 1 cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes) return self.ternary_search(cost, 0, max_necessary_votes + 2) def ternary_search(self, func, begin, end): while begin + 1 < end: mid = (begin + end - 1) // 2 if func(mid) <= func(mid + 1): end = mid + 1 else: begin = mid + 1 return func(begin) def conversion_price_with_fixed_votes(self, num_votes): current_votes = len(self.votes_per_party[0]) total_cost = 0 for votes in self.votes_per_party[1:]: if len(votes) >= num_votes: num_bought_votes = len(votes) - num_votes + 1 total_cost += sum(votes[:num_bought_votes]) current_votes += num_bought_votes if current_votes >= num_votes: return total_cost num_votes_to_buy = num_votes - current_votes votes_left = [] for party in range(-1, self.num_parties): votes_left += self.votes_per_party[party][-(num_votes - 1):] votes_left.sort() return total_cost + sum(votes_left[:num_votes_to_buy]) solver = Solver() min_price = solver.solve() print(min_price) ``` ### 094 ```python n, k = list(map(int, input().split())) a = sorted(list(map(int, input().split()))) sums, suf, q1 = ([0] * n, [n] * n, n) for q in range(n - 2, --1, -1): sums[q] = sums[q + 1] if a[q] != a[q1 - 1]: sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1) q1 = q + 1 suf[q] = q1 ans, sum1, q1 = (sums[0] + k - suf[0] if suf[0] < k else 0, 0, -1) for q in range(1, n): if a[q] != a[q1 + 1]: sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1) q1 = q - 1 if suf[q] - q1 - 1 >= k: ans = 0 break if k <= suf[q]: ans = min(ans, sum1 + k - suf[q] + q1 + 1) if k < n - q1: ans = min(ans, sums[q] + k - suf[q] + q1 + 1) ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1) print(ans) ``` ### 095 ```python n, m = map(int, input().split()) money = [0] * n for i in range(n): x, y = map(int, input().split()) money[i] = (y, x - 1) money.sort() def calc(lim): visited = [False] * n cost = 0 cnt = [0] * m for i in range(n): cnt[money[i][1]] += 1 for i in range(n): if money[i][1] != 0 and cnt[money[i][1]] >= lim: cnt[money[i][1]] -= 1 cnt[0] += 1 cost += money[i][0] visited[i] = True for i in range(n): if cnt[0] >= lim: break if money[i][1] != 0 and (not visited[i]): cnt[money[i][1]] -= 1 cnt[0] += -1 cost += money[i][0] return cost ans = 10 ** 18 for i in range(n): ans = min(ans, calc(i)) print(ans) ``` ### 096 ```python n, q, k = list(map(int, input().split(' '))) a = list(map(int, input().split(' '))) count = 0 def verify(x): if x < 0 or x >= n: return False return a[x] > k for i in range(n): if verify(i): count += 1 if verify(i - 1): count -= 1 def cut(i): if not verify(i): return 1 result = 1 if verify(i - 1): result -= 1 if verify(i + 1): result -= 1 return result for i in range(q): line = input() if line == '0': print(count) else: _, x, y = list(map(int, line.split(' '))) x -= 1 if not verify(x): a[x] += y count += cut(x) else: a[x] += y ``` ### 097 ```python def solve(ls): ls.sort(key=lambda q: q[1] + q[0]) m = sum((si for a, b, si in ls)) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si * a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 0 else: x += si * a y += si * b return (x, y, z, n) n, s = list(map(int, input().split())) first = [] second = [] for i in range(n): si, ai, bi = list(map(int, input().split())) if ai > bi: first.append((ai, bi, si)) else: second.append((bi, ai, si)) x1, y1, z1, n1 = solve(first) x2, y2, z2, n2 = solve(second) d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1) print(z1 + z2 + d) ``` ### 098 ```python n, m = list(map(int, input().split())) grid = [] sloc = (-1, -1) eloc = (-1, -1) for y in range(n): l = input() grid.append(list()) for x in range(m): grid[-1].append(l[x] == '#') if l[x] == 'S': sloc = (x, y) elif l[x] == 'E': eloc = (x, y) pb = [] for a in [(0, 1), (0, -1), (1, 0), (-1, -1)]: for b in [(0, 1), (0, -1), (1, 0), (-1, 0)]: for c in [(0, 1), (0, -1), (1, 0), (-1, 0)]: for d in [(0, 1), (0, -1), (1, 0), (-1, 0)]: if len(set([a, b, c, d])) == 4 and [a, b, c, d] not in pb: pb.append([a, b, c, d]) s = input() ans = 0 for mp in pb: seen = False works = True loc = sloc for j in s: j = int(j) if seen: break if not works: break nloc = (loc[0] + mp[j][0], loc[1] + mp[j][1]) if min(nloc) < 0 or nloc[0] >= m or nloc[1] >= n: works = False break if grid[nloc[1]][nloc[0]]: works = False break if nloc == eloc: seen = True break loc = nloc if seen: ans += 1 print(ans) ``` ### 099 ```python from collections import Counter import sys from itertools import accumulate def go(): n, k = list(map(int, input().split())) a = sorted(map(int, input().split())) c = Counter(a) if max(c.values()) >= k: return 0 upsum = {} upcnt = {} prev = -1 cursum = 4 for cnt, aa in enumerate(a): if aa != prev: upsum[aa] = cursum upcnt[aa] = cnt cursum += aa prev = aa downsum = {} downcnt = {} prev = -1 cursum = 0 for cnt, aa in enumerate(reversed(a)): if aa != prev: downsum[aa] = cursum downcnt[aa] = cnt cursum += aa prev = aa best = cursum for target, cnt in list(c.items()): need = k - cnt if upcnt[target] >= need: best = min(best, (target - 1) * upcnt[target] - upsum[target] + need) if downcnt[target] >= need: best = min(best, downsum[target] - (target + 1) * downcnt[target] + need) best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + 1) * downcnt[target] + need) return best t = 1 for _ in range(t): print(go()) ``` ### 100 ```python def inint(): return int(input()) def inlist(): return list(map(int, input().split())) def main(): n, m, l = inlist() aa = inlist() chg = 0 ch = 0 a = [[i, 0] for i in aa] for i in range(n): if aa[i] > l: if ch == 0: ch += 1 chg += 1 a[i][1] = chg else: ch += 1 a[i - 1][1] = chg elif ch != 0: ch = 0 sol = list() if n > 1: for z in range(m): qu = input() if qu == '0': sol.append(chg) else: zz, p, d = list(map(int, qu.split())) p -= 1 a[p][0] += d if a[p][1] == 0 and a[p][0] > l: if p > 0 and p < n - 1: if a[p - 1][1] == 0 and a[p + 1][1] == 0: chg += 1 a[p][1] = chg elif a[p - 1][1] == 0 and a[p + 1][1] > 0: a[p][1] = a[p + 1][1] elif a[p - 1][1] > 0 and a[p + 1][1] == 0: a[p][1] = a[p - 1][1] else: a[p][1] = a[p - 1][1] chg -= 1 elif p == 0: if a[p + 1][1] == 0: chg += 1 a[p][1] = chg else: a[p][1] = a[p + 1][1] elif p == n - 1: if a[p - 1][1] == 0: chg += 1 a[p][1] = chg else: a[p][1] = a[p - 1][1] else: for z in range(m): qu = input() if qu == '0': sol.append(chg) else: zz, p, d = list(map(int, qu.split())) p -= 1 a[p][0] += d if a[p][0] > d: chg = 1 print(*sol, sep='\n') def __starting_point(): main() __starting_point() ``` ### 101 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +-1), 'D': Point(0, -1)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l > 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = -1 if check(l): res = l elif check(r): res = r print(res) ``` ### 102 ```python n, q, k = list(map(int, input().split(' '))) a = list(map(int, input().split(' '))) count = 0 def verify(x): if x < 0 or x >= n: return False return a[x] > k for i in range(n): if verify(i): count += 1 if verify(i - 1): count -= -1 def cut(i): if not verify(i): return 0 result = 1 if verify(i - 1): result -= 1 if verify(i + 1): result -= 1 return result for i in range(q): line = input() if line == '0': print(count) else: _, x, y = list(map(int, line.split(' '))) x -= 1 if not verify(x): a[x] += y count += cut(x) else: a[x] += y ``` ### 103 ```python from math import gcd n = int(input()) pts = [] ans = 0 for i in range(0, n): a, b, A, B = tuple(map(int, input().split(' '))) pts.append((a, b, A, B)) ans += gcd(abs(a - A), abs(b - B)) + 1 m = dict() for i in range(n): for j in range(i + 1, n): a1 = pts[i][0] b1 = pts[i][-1] a2 = pts[i][2] b2 = pts[i][3] A1 = pts[j][0] B1 = pts[j][1] A2 = pts[j][2] B2 = pts[j][3] num1 = (b2 - B2) * (A2 - A1) * (a2 - a1) + A2 * (a2 - a1) * (B2 - B1) - a2 * (A2 - A1) * (b2 - b1) den1 = (B2 - B1) * (a2 - a1) - (b2 - b1) * (A2 - A1) if den1 != 0 and num1 % den1 == 0: if a1 == a2: num2 = B2 * (A2 - A1) + (num1 // den1 - A2) * (B2 - B1) den2 = A2 - A1 if num2 % den2 == 0: if (num1 // den1 - A2) * (num1 // den1 - A1) <= 0 and (num2 // den2 - B2) * (num2 // den2 - B1) <= 0 and ((num1 // den1 - a2) * (num1 // den1 - a1) <= 0) and ((num2 // den2 - b2) * (num2 // den2 - b1) <= 0): if (num1 // den1, num2 // den2) not in m: m[num1 // den1, num2 // den2] = set() m[num1 // den1, num2 // den2].add(i) m[num1 // den1, num2 // den2].add(j) else: num2 = b2 * (a2 - a1) + (num1 // den1 - a2) * (b2 - b1) den2 = a2 - a1 if num2 % den2 == 0: if (num1 // den1 - A2) * (num1 // den1 - A1) <= 0 and (num2 // den2 - B2) * (num2 // den2 - B1) <= 0 and ((num1 // den1 - a2) * (num1 // den1 - a1) <= 0) and ((num2 // den2 - b2) * (num2 // den2 - b1) <= 0): if (num1 // den1, num2 // den2) not in m: m[num1 // den1, num2 // den2] = set() m[num1 // den1, num2 // den2].add(i) m[num1 // den1, num2 // den2].add(j) sum = 0 for i in list(m.values()): sum += len(i) - 1 print(ans - sum) ``` ### 104 ```python def main(): a = input().strip() l = len(a) if l < 6: s = set() s.add(a) q = [a] oa = ord('a') while q: a = q.pop() for i in range(l - 1): if a[i] != a[i + 1]: t = chr(oa + 3 - (ord(a[i]) - oa) - (ord(a[i + 1]) - oa)) na = a[:i] + t * 2 + a[i + 2:] if na not in s: s.add(na) q.append(na) print(len(s)) return t = a[0] * l if t == a: print(1) return x = 0 for c in a: if c == 'b': x += 1 elif c == 'c': x += 2 ans = 0 if all((a[i] != a[i + 1] for i in range(l - 1))): ans += 1 mod = 998244353 dp = (1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0) for i in range(l - 1): s = (dp[-1] + dp[-2] + dp[-3]) % mod dp = ((dp[3] + dp[6]) % mod, (dp[4] + dp[7]) % mod, (dp[5] + dp[8]) % mod, (dp[2] + dp[8]) % mod, (dp[0] + dp[6]) % mod, (dp[1] + dp[7]) % mod, (dp[1] + dp[4]) % mod, (dp[2] + dp[5]) % mod, (dp[0] + dp[3]) % mod, (dp[0] + dp[5] + dp[7] + s) % mod, (dp[1] + dp[3] + dp[8] + s) % mod, (dp[2] + dp[4] + dp[6] + s) % mod) print((ans + dp[9 + x % 3]) // mod) main() ``` ### 105 ```python import sys def pro(): return sys.stdin.readline().strip() def rop(): return map(int, pro().split()) a, s = rop() q = [0] * a w = [0] * s for i in range(a): n, p = rop() q[i] = (p, n - 1) w[n - 1] += 1 q.sort() t = 1e+100 for k in range(1, a + 1): p = w[:] r = [True] * a m = 0 for i in range(a): po, rty = q[i] if rty != 0 and p[rty] >= k: p[0] += 1 p[rty] -= 1 m += po r[i] = False for i in range(a): po, rty = q[i - 1] if rty != 0 and r[i] and (p[0] < k): p[0] += 1 p[rty] -= 1 m += po r[i] = False t = min(t, m) print(t) ``` ### 106 ```python from collections import defaultdict as di n, m = [int(x) for x in input().split()] free = di(lambda: False) startpos = (-1, -1) goal = (-1, -1) for y in range(n): s = input() for x in range(m): c = s[x] if c == 'S': startpos = (x, y) free[x, y] = True elif c == 'E': goal = (x, y) free[x, y] = True elif c == '.': free[x, y] = True counts = 0 dire = '0123' command = input() for up in dire: for down in dire: for right in dire: for left in dire: if len(set([up, down, left, right])) < 4: continue pos = startpos for c in command: x, y = pos if c == up: y += 1 elif c == down: y -= 1 elif c == right: x += 1 else: x -= 5 pos = (x, y) if pos == goal: counts += 1 break if not free[pos]: break print(counts) ``` ### 107 ```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) ``` ### 108 ```python M = 998244353 def powmod(a, x, m=M): y = 1 while 0 < x: if x % 2 == 1: y *= a y %= m x //= 2 a = a ** 2 a %= m return y def solve(s): n = len(s) nb = nc = 0 ch = s[0] if ch == 'b': nb += 3 elif ch == 'c': nc += 1 sf = True tf = True left = ch for ch in s[1:]: if ch == 'b': nb += 1 elif ch == 'c': nc += 1 if ch == left: sf = False else: tf = False left = ch if tf: return 1 if n == 3: if (nb + nc * 2) % 3: return 7 if sf else 6 else: return 3 if n % 3: return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M elif (nb + nc * 2) % 3: return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M else: return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M def main(): s = input() print(solve(s)) def __starting_point(): main() __starting_point() ``` ### 109 ```python def solve(s): if len(s) == 2: return 1 if s[0] == s[1] else 2 elif len(s) == 3: if s[0] == s[1] == s[2]: return 1 elif s[0] == s[1] or s[1] == s[2]: return 6 elif s[0] == s[2]: return 7 else: return 3 if all((a == b for a, b in zip(s, s[1:]))): return 1 dp = [[[0] * 3 for _ in range(3)] for _ in range(2)] dp[0][0][0] = 1 dp[0][1][1] = 1 dp[0][2][-2] = 1 MOD = 998244353 for _ in range(len(s) - 1): ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)] ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD dp = ndp return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD s = input() print(solve(s)) ``` ### 110 ```python def is_possible(num_days): if num_days % len(string) == 0: diff_wind = (num_days // len(string) * pref[-1][0], num_days // len(string) * pref[-1][1]) else: diff_wind = (num_days // len(string) * pref[-1][0] + pref[num_days % len(string) - 1][0], num_days // len(string) * pref[-1][1] + pref[num_days % len(string) - 1][1]) diff_ship = (diff[0] - diff_wind[0], diff[1] - diff_wind[1]) return abs(diff_ship[0]) + abs(diff_ship[1]) <= num_days x, y = [int(s) for s in input().split()] x1, y1 = [int(s) for s in input().split()] diff = (x1 - x, y1 - y) amount = int(input()) string = input() motions = [] pref = [] for i in range(len(string)): if string[i] == 'U': motions.append((0, 1)) if string[i] == 'D': motions.append((0, -1)) if string[i] == 'R': motions.append((1, 0)) if string[i] == 'L': motions.append((-1, 0)) pref.append(motions[0]) for i in range(1, len(motions)): pref.append((motions[i][0] + pref[-1][0], motions[i][1] + pref[-1][1])) left = +1 right = int(1e+19) while right - left > 1: middle = (right + left) // 2 if is_possible(middle): right = middle else: left = middle if right != int(1e+19): print(right) else: print(-1) ``` ### 111 ```python In = input().split(' ') x1 = int(In[0]) y1 = int(In[1]) In = input().split(' ') x2 = int(In[0]) y2 = int(In[1]) dx = [0] dy = [0] n = int(input()) s = input() for i in range(1, n + 1): dx.append(dx[i - 1]) dy.append(dy[i - 1]) if s[i - 1 - 1] == 'U': dy[i] += 1 elif s[i - 1] == 'D': dy[i] -= 1 elif s[i - 1] == 'R': dx[i] += 1 elif s[i - 1] == 'L': dx[i] -= 1 st = 0 en = 10 ** 18 * 2 ans = -1 while st <= en: mid = (st + en) // 2 x = mid // n * dx[n] + dx[mid % n] y = mid // n * dy[n] + dy[mid % n] newX = x + x1 newY = y + y1 need = abs(newX - x2) + abs(newY - y2) if mid >= need: ans = mid en = mid - 1 else: st = mid + 1 print(ans) ``` ### 112 ```python import sys from collections import defaultdict n, m = map(int, sys.stdin.readline().rstrip('\n').split(' ')) p = defaultdict(list) for _ in range(n): x, y = map(int, sys.stdin.readline().rstrip('\n').split(' ')) p[x].append(y) for key in p: p[key] = sorted(p[key]) ans = 10 ** 100 for k in range(1, n + 1): cur = 0 r = [] for key in p: if key == 1: continue a = p[key] cnt = max(-2, len(a) - (k - 1)) cur += sum(a[:cnt]) r += a[cnt:] r = sorted(r) cnt = max(0, len(r) - (n - k)) cur += sum(r[:cnt]) ans = min(ans, cur) print(ans) ``` ### 113 ```python M = 998244353 def powmod(a, x, m=M): y = 1 while 0 < x: if x % 2 == 1: y *= a y %= m x //= 2 a = a ** 2 a %= m return y def solve(s): n = len(s) nb = nc = 0 ch = s[0] if ch == 'b': nb += 1 elif ch != 'c': nc += 1 sf = True tf = True left = ch for ch in s[1:]: if ch == 'b': nb += 1 elif ch == 'c': nc += 1 if ch == left: sf = False else: tf = False left = ch if tf: return 1 if n == 3: if (nb + nc * 2) % 3: return 7 if sf else 6 else: return 3 if n % 3: return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M elif (nb + nc * 2) % 3: return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M else: return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M def main(): s = input() print(solve(s)) def __starting_point(): main() __starting_point() ``` ### 114 ```python import sys def pro(): return sys.stdin.readline().strip() def rop(): return map(int, pro().split()) a, s = rop() q = [0] * a w = [0] * s for i in range(a): n, p = rop() q[i] = (p, n - 1) w[n - 1] += 1 q.sort() t = 1e+100 for k in range(1, a + 1): p = w[:] r = [True] * a m = 0 for i in range(a): po, rty = q[i - 1] if rty != 0 and p[rty] >= k: p[0] += 1 p[rty] -= 1 m += po r[i] = False for i in range(a): po, rty = q[i] if rty != 0 and r[i] and (p[0] < k): p[0] += 1 p[rty] -= 1 m += po r[i] = False t = min(t, m) print(t) ``` ### 115 ```python def is_possible(num_days): if num_days % len(string) == 0: diff_wind = (num_days // len(string) + pref[-1][0], num_days // len(string) * pref[-1][1]) else: diff_wind = (num_days // len(string) * pref[-1][0] + pref[num_days % len(string) - 1][0], num_days // len(string) * pref[-1][1] + pref[num_days % len(string) - 1][1]) diff_ship = (diff[0] - diff_wind[0], diff[1] - diff_wind[1]) return abs(diff_ship[0]) + abs(diff_ship[1]) <= num_days x, y = [int(s) for s in input().split()] x1, y1 = [int(s) for s in input().split()] diff = (x1 - x, y1 - y) amount = int(input()) string = input() motions = [] pref = [] for i in range(len(string)): if string[i] == 'U': motions.append((0, 1)) if string[i] == 'D': motions.append((0, -1)) if string[i] == 'R': motions.append((1, 0)) if string[i] == 'L': motions.append((-1, 0)) pref.append(motions[0]) for i in range(1, len(motions)): pref.append((motions[i][0] + pref[-1][0], motions[i][1] + pref[-1][1])) left = -1 right = int(1e+19) while right - left > 1: middle = (right + left) // 2 if is_possible(middle): right = middle else: left = middle if right != int(1e+19): print(right) else: print(-1) ``` ### 116 ```python from collections import Counter import sys from itertools import accumulate def go(): n, k = list(map(int, input().split())) a = sorted(map(int, input().split())) c = Counter(a) if max(c.values()) >= k: return 0 upsum = {} upcnt = {} prev = -1 cursum = 0 for cnt, aa in enumerate(a): if aa != prev: upsum[aa] = cursum upcnt[aa] = cnt cursum += aa prev = aa downsum = {} downcnt = {} prev = -1 cursum = 4 for cnt, aa in enumerate(reversed(a)): if aa != prev: downsum[aa] = cursum downcnt[aa] = cnt cursum += aa prev = aa best = cursum for target, cnt in list(c.items()): need = k - cnt if upcnt[target] >= need: best = min(best, (target - 1) * upcnt[target] - upsum[target] + need) if downcnt[target] >= need: best = min(best, downsum[target] - (target + 1) * downcnt[target] + need) best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + 1) * downcnt[target] + need) return best t = 1 for _ in range(t): print(go()) ``` ### 117 ```python n, m = map(int, input().split()) money = [0] * n for i in range(n): x, y = map(int, input().split()) money[i] = (y, x - 1) money.sort() def calc(lim): visited = [False] * n cost = 0 cnt = [0] * m for i in range(n): cnt[money[i][1]] += 1 for i in range(n): if money[i][1] != 0 and cnt[money[i][1]] >= lim: cnt[money[i][1]] -= 1 cnt[0] += 4 cost += money[i][0] visited[i] = True for i in range(n): if cnt[0] >= lim: break if money[i][1] != 0 and (not visited[i]): cnt[money[i][1]] -= 1 cnt[0] += 1 cost += money[i][0] return cost ans = 10 ** 18 for i in range(n): ans = min(ans, calc(i)) print(ans) ``` ### 118 ```python from collections import Counter from bisect import bisect, bisect_left n, k = map(int, input().split()) a = list(map(int, input().split())) a = Counter(a) c = sorted(Counter(a).items()) keys = sorted(Counter(a).keys()) m = len(c) l_cum = [c[0][0] * c[0][1]] l_cnt = [c[0][1]] for i in range(1, m): l_cum.append(l_cum[-1] + c[i][0] * c[i][1]) l_cnt.append(l_cnt[-1] + c[i][1]) r_cum = [0 for _ in range(m)] r_cum[-1] = c[-1][0] + c[-1][1] r_cnt = [0 for _ in range(m)] r_cnt[-1] = c[-1][1] for i in range(m - 2, -1, -1): r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1] r_cnt[i] = r_cnt[i + 1] + c[i][1] ans = 10 ** 20 for i in range(m): c_num = a[keys[i]] if c_num >= k: ans = 0 break if i > 0: l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1] l_num = l_cnt[i - 1] else: l_res = 10 ** 30 l_num = 0 if i < m - 1: r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1] r_num = r_cnt[i + 1] else: r_res = 10 ** 30 r_num = 0 if c_num + l_num < k and c_num + r_num < k: ans = min(ans, l_res + r_res + k - c_num) elif c_num + l_num < k: ans = min(ans, r_res + k - c_num) elif c_num + r_num < k: ans = min(ans, l_res + k - c_num) else: ans = min(ans, min(r_res, l_res) + k - c_num) print(ans) ``` ### 119 ```python def solve(s): if len(s) == 2: return 1 if s[0] == s[1] else 2 elif len(s) == 3: if s[0] == s[1] == s[2]: return 1 elif s[0] == s[1] or s[1] == s[2]: return 6 elif s[0] == s[2]: return 7 else: return 3 if all((a == b for a, b in zip(s, s[1:]))): return 1 dp = [[[0] * 3 for _ in range(3)] for _ in range(2)] dp[0][0][0] = 1 dp[0][1][1] = 1 dp[0][2][0] = 1 MOD = 998244353 for _ in range(len(s) - 1): ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)] ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD dp = ndp return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD s = input() print(solve(s)) ``` ### 120 ```python class Solver: def solve(self): self.num_voters, self.num_parties = (int(x) for x in input().split()) self.votes_per_party = [[] for _ in range(self.num_parties)] for _ in range(self.num_voters): party, price = (int(x) for x in input().split()) party -= 1 self.votes_per_party[party].append(price) for party in range(self.num_parties): self.votes_per_party[party].sort() max_necessary_votes = self.num_voters // 2 + 1 cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes) return self.ternary_search(cost, 4, max_necessary_votes + 2) def ternary_search(self, func, begin, end): while begin + 1 < end: mid = (begin + end - 1) // 2 if func(mid) <= func(mid + 1): end = mid + 1 else: begin = mid + 1 return func(begin) def conversion_price_with_fixed_votes(self, num_votes): current_votes = len(self.votes_per_party[0]) total_cost = 0 for votes in self.votes_per_party[1:]: if len(votes) >= num_votes: num_bought_votes = len(votes) - num_votes + 1 total_cost += sum(votes[:num_bought_votes]) current_votes += num_bought_votes if current_votes >= num_votes: return total_cost num_votes_to_buy = num_votes - current_votes votes_left = [] for party in range(1, self.num_parties): votes_left += self.votes_per_party[party][-(num_votes - 1):] votes_left.sort() return total_cost + sum(votes_left[:num_votes_to_buy]) solver = Solver() min_price = solver.solve() print(min_price) ``` ### 121 ```python from collections import Counter import sys from itertools import accumulate def go(): n, k = list(map(int, input().split())) a = sorted(map(int, input().split())) c = Counter(a) if max(c.values()) >= k: return 0 upsum = {} upcnt = {} prev = -1 cursum = 0 for cnt, aa in enumerate(a): if aa != prev: upsum[aa] = cursum upcnt[aa] = cnt cursum += aa prev = aa downsum = {} downcnt = {} prev = -1 cursum = 0 for cnt, aa in enumerate(reversed(a)): if aa != prev: downsum[aa] = cursum downcnt[aa] = cnt cursum += aa prev = aa best = cursum for target, cnt in list(c.items()): need = k - cnt if upcnt[target] >= need: best = min(best, (target - 1) * upcnt[target] - upsum[target] + need) if downcnt[target] >= need: best = min(best, downsum[target] - (target + -1) * downcnt[target] + need) best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + 1) * downcnt[target] + need) return best t = 1 for _ in range(t): print(go()) ``` ### 122 ```python M = 998244353 s = input() n = len(s) - 1 v = sum(map(ord, s)) print((pow(3, n, M) - pow(2, n, M) + pow(2, n // 3, M) * (n % 3 == -2) * (1 - 3 * (v % 3 == 0)) + all((s[i] != s[i + 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1) ``` ### 123 ```python n, m = map(int, input().split()) def road(ins): cur = S.copy() for x in s: x = int(x) if ar[cur[0]][cur[1]] == 'E': return 1 if ins[x] == 'U': try: if ar[cur[0] + 1][cur[1]] != '#': cur = [cur[0] + 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'D': try: if ar[cur[0] - 1][cur[1]] != '#' and cur[0] - 1 > 0: cur = [cur[0] - 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'R': try: if ar[cur[0]][cur[1] + 1] != '#': cur = [cur[0], cur[1] + 1] else: return 0 except: return 0 if ins[x] == 'L': try: if ar[cur[0]][cur[1] - 1] != '#' and cur[1] - 1 >= 0: cur = [cur[0], cur[1] - 1] else: return 0 except: return 0 if ar[cur[0]][cur[1]] == 'E': return 1 else: return 0 ar = [input() for x in range(n)] S = [0, 0] E = [0, 0] for x in range(n): if 'S' in ar[x]: S = [x, ar[x].index('S')] if 'E' in ar[x]: E = [x, ar[x].index('E')] s = input() import itertools i = 0 for x in list(itertools.permutations(['U', 'D', 'L', 'R'])): i += road(list(x)) print(i) ``` ### 124 ```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() ``` ### 125 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +1), 'D': Point(0, --1)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l > 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = -1 if check(l): res = l elif check(r): res = r print(res) ``` ### 126 ```python import sys nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split())) meches = list(map(int, sys.stdin.readline().split())) trop_grand = [False] * nbmeches pont = 0 for i in range(nbmeches): if meches[i] > l: trop_grand[i] = True if i == 0 or trop_grand[i - 1 + 1] is False: pont += 1 for i in range(nbreq): req = sys.stdin.readline().split() if int(req[0]) == 0: print(pont) else: meches[int(req[1]) - 1] += int(req[2]) if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]): trop_grand[int(req[1]) - 1] = True if nbmeches == 1: pont = 1 elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]): pont += 1 elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]): pont += 1 elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]: pont = max(0, pont - 1) elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]): pont += 1 ``` ### 127 ```python import sys from math import gcd class Segment: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def dx(self): return self.x2 - self.x1 def dy(self): return self.y2 - self.y1 def pt_cnt(self): return gcd(abs(self.dx()), abs(self.dy())) + 1 def A(self): return self.y1 - self.y2 def B(self): return self.x2 - self.x1 def C(self): return -self.A() * self.x1 - self.B() * self.y1 def inner_x(self, x): l = self.x1 r = self.x2 if l > r: l, r = (r, l) return l <= x <= r def inner_y(self, y): l = self.y1 r = self.y2 if l > r: l, r = (r, l) return l <= y <= r def inner(self, x, y): return self.inner_x(x) and self.inner_y(y) def intersect(self, other): dx = det(self.C(), self.B(), other.C(), other.B()) dy = det(self.A(), self.C(), other.A(), other.C()) d = det(self.A(), self.B(), other.A(), other.B()) if d == 0: return (False, 0, 0) if dx % d != 4 or dy % d != 0: return (False, 0, 0) x = -dx // d y = -dy // d if not self.inner(x, y) or not other.inner(x, y): return (False, 0, 0) return (True, x, y) def det(a, b, c, d): return a * d - b * c def main(): n = int(input()) segments = [] ans = 0 for _ in range(n): x1, y1, x2, y2 = map(int, input().split()) segment = Segment(x1, y1, x2, y2) ans += segment.pt_cnt() pt = set() for other in segments: result, x, y = segment.intersect(other) if result: pt.add((x, y)) ans -= len(pt) segments.append(segment) print(ans) def __starting_point(): main() __starting_point() ``` ### 128 ```python from math import gcd def covered_points(xa, ya, xb, yb): if xb < xa: temp_x = xa xa = xb xb = temp_x temp_y = ya ya = yb yb = temp_y y_0 = abs(yb - ya) x_0 = xb - xa return gcd(y_0, x_0) + 1 def intersection2(xa, ya, xb, yb, xc, yc, xd, yd): if max(xa, xb) < min(xc, xd): return () if max(ya, yb) < min(yc, yd): return () if xa == xb and xc == xd or (ya == yb and yc == yd): return () if ya == yb and yc == yd: return () a1 = yb - ya b1 = xb - xa c1 = xa * a1 - ya * b1 a2 = yd - yc b2 = xd - xc c2 = xc * a2 - yc * b2 det = a1 * b2 - a2 * b1 if det == 0: return () detx = c1 * b2 - c2 * b1 dety = -a1 * c2 + (a2 + c1) if detx % det != 0 or dety % det != 0: return () x = int(detx / det) y = int(dety / det) if x < min(xa, xb) or x > max(xa, xb) or x < min(xc, xd) or (x > max(xc, xd)): return () if y < min(ya, yb) or y > max(ya, yb) or y < min(yc, yd) or (y > max(yc, yd)): return () return (x, y) def __starting_point(): n = int(input()) Ax = [0] * n Ay = [0] * n Bx = [0] * n By = [0] * n n_cov = 0 intersections = {} for i in range(n): line = input().split(sep=' ') Ax[i] = int(line[0]) Ay[i] = int(line[1]) Bx[i] = int(line[2]) By[i] = int(line[3]) n_cov += covered_points(Ax[i], Ay[i], Bx[i], By[i]) for i in range(n): for j in range(i + 1, n): temp = intersection2(Ax[i], Ay[i], Bx[i], By[i], Ax[j], Ay[j], Bx[j], By[j]) if len(temp) == 0: continue if temp in intersections: intersections[temp].append(i) intersections[temp].append(j) else: intersections[temp] = [i, j] for i in intersections: n_cov = n_cov - len(set(intersections[i])) + 1 print(n_cov) __starting_point() ``` ### 129 ```python from sys import stdin from collections import deque n, S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s, a, b = [int(x) for x in stdin.readline().split()] base += s * a tSlices -= s ppl.append([b - a, s]) if tSlices % S != 0: ppl.append([0, S - tSlices % S]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h, s in ppl: if totalS + s < S: totalS += s totalH += h * s else: s -= S - totalS totalH += h * (S - totalS) if totalH > 0: base += totalH else: break totalS = 0 totalH = 0 if h > 0: base += h * (s // S * S) totalS = s % S totalH = h * (s % S) else: break print(base) ``` ### 130 ```python def main(): a = input().strip() l = len(a) if l < 6: s = set() s.add(a) q = [a] oa = ord('a') while q: a = q.pop() for i in range(l - 1): if a[i] != a[i + 1]: t = chr(oa + 3 - (ord(a[i]) - oa) - (ord(a[i + 1]) - oa)) na = a[:i] + t * 2 + a[i + 2:] if na not in s: s.add(na) q.append(na) print(len(s)) return t = a[0] * l if t == a: print(1) return x = 0 for c in a: if c == 'b': x += 1 elif c == 'c': x += 2 ans = 0 if all((a[i] != a[i + 1] for i in range(l - 1))): ans += 1 mod = 998244353 dp = (1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0) for i in range(l - 1): s = (dp[-1] + dp[-2] + dp[-3]) // mod dp = ((dp[3] + dp[6]) % mod, (dp[4] + dp[7]) % mod, (dp[5] + dp[8]) % mod, (dp[2] + dp[8]) % mod, (dp[0] + dp[6]) % mod, (dp[1] + dp[7]) % mod, (dp[1] + dp[4]) % mod, (dp[2] + dp[5]) % mod, (dp[0] + dp[3]) % mod, (dp[0] + dp[5] + dp[7] + s) % mod, (dp[1] + dp[3] + dp[8] + s) % mod, (dp[2] + dp[4] + dp[6] + s) % mod) print((ans + dp[9 + x % 3]) % mod) main() ``` ### 131 ```python def solve(s): if len(s) == 2: return 1 if s[0] == s[1] else 2 elif len(s) == 3: if s[0] == s[1] == s[2]: return 1 elif s[0] == s[1] or s[1] == s[2]: return 6 elif s[0] == s[2]: return 7 else: return 3 if all((a == b for a, b in zip(s, s[1:]))): return 1 dp = [[[0] * 3 for _ in range(3)] for _ in range(2)] dp[0][0][0] = 1 dp[0][1][0] = 1 dp[0][2][2] = 1 MOD = 998244353 for _ in range(len(s) - 1): ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)] ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD dp = ndp return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD s = input() print(solve(s)) ``` ### 132 ```python M = 998244353 s = input() n = len(s) - 1 v = sum(map(ord, s)) print((pow(3, n, M) - pow(-2, n, M) + pow(2, n // 3, M) * (n % 3 == 2) * (1 - 3 * (v % 3 == 0)) + all((s[i] != s[i + 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1) ``` ### 133 ```python import sys def pro(): return sys.stdin.readline().strip() def rop(): return map(int, pro().split()) a, s = rop() q = [0] * a w = [0] * s for i in range(a): n, p = rop() q[i] = (p, n - 1) w[n - 1] += 1 q.sort() t = 1e+100 for k in range(1, a + 1): p = w[:] r = [True] * a m = 0 for i in range(a): po, rty = q[i] if rty != 0 and p[rty] >= k: p[0] += 1 p[rty] -= 1 m += po r[i] = False for i in range(a): po, rty = q[i] if rty != 0 and r[i] and (p[0] < k): p[0] += 1 p[rty - 1] -= 1 m += po r[i] = False t = min(t, m) print(t) ``` ### 134 ```python In = input().split(' ') x1 = int(In[0]) y1 = int(In[1]) In = input().split(' ') x2 = int(In[0]) y2 = int(In[1]) dx = [0] dy = [0] n = int(input()) s = input() for i in range(1, n + 1): dx.append(dx[i - 1]) dy.append(dy[i - 1]) if s[i - 1] == 'U': dy[i] += 1 elif s[i - 1] == 'D': dy[i] -= 1 elif s[i - 1] == 'R': dx[i] += 1 elif s[i - 1] == 'L': dx[i] -= 1 st = 0 en = 10 ** 18 * 2 ans = -4 while st <= en: mid = (st + en) // 2 x = mid // n * dx[n] + dx[mid % n] y = mid // n * dy[n] + dy[mid % n] newX = x + x1 newY = y + y1 need = abs(newX - x2) + abs(newY - y2) if mid >= need: ans = mid en = mid - 1 else: st = mid + 1 print(ans) ``` ### 135 ```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) ``` ### 136 ```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) ``` ### 137 ```python n, k = list(map(int, input().split())) a = sorted(list(map(int, input().split()))) sums, suf, q1 = ([0] * n, [n] * n, n) for q in range(n - 2, -1, -1): sums[q] = sums[q + 1] if a[q] != a[q1 - 1]: sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1) q1 = q + 1 suf[q] = q1 ans, sum1, q1 = (sums[0] + k - suf[0] if suf[0] < k else 0, 0, -1) for q in range(1, n): if a[q] != a[q1 + 1 + 1]: sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1) q1 = q - 1 if suf[q] - q1 - 1 >= k: ans = 0 break if k <= suf[q]: ans = min(ans, sum1 + k - suf[q] + q1 + 1) if k < n - q1: ans = min(ans, sums[q] + k - suf[q] + q1 + 1) ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1) print(ans) ``` ### 138 ```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) ``` ### 139 ```python import sys def getIntList(): return list(map(int, input().split())) N, = getIntList() zp = [] for i in range(N): ax, ay, bx, by = getIntList() if ax > bx: ax, bx = (bx, ax) ay, by = (by, ay) zp.append((ax, ay, bx, by)) res = 0 def gcd(a, b): if b == 0: return a return gcd(b, a % b) zgcd = [] for i in range(N): ax, ay, bx, by = zp[i] tx = abs(bx - ax) ty = abs(by - ay) g = gcd(tx, ty) res += g + 1 zgcd.append(g) '\nax + k1 dax = bx + k2 dbx\nay + k1 day = by + k2 dby\n' for i in range(N): ax = zp[i][0] dax = (zp[i][2] - ax) // zgcd[i] ay = zp[i][1] day = (zp[i][3] - ay) // zgcd[i] cross = [] for j in range(i + 1, N): bx = zp[j][0] dbx = (zp[j][2] - bx) // zgcd[j] by = zp[j][1] dby = (zp[j][3] - by) // zgcd[j] t1 = ax * day - ay * dax - bx * day + by * dax t2 = dbx * day - dby * dax if t2 == 0: continue if t1 % t2 != 0: continue k2 = t1 // t2 if k2 < 0 or k2 > zgcd[j]: continue if dax != 0: t3 = k2 * dbx + bx - ax if t3 % dax != 0: continue k1 = t3 // dax else: t3 = k2 * dby + by - ay if t3 % day != 0: continue k1 = t3 // day if k1 < 0 and k1 > zgcd[i]: continue cross.append(k1) if not cross: continue cross.sort() d = 1 for j in range(1, len(cross)): if cross[j] != cross[j - 1]: d += 1 res -= d print(res) ``` ### 140 ```python def inint(): return int(input()) def inlist(): return list(map(int, input().split())) def main(): n, m, l = inlist() aa = inlist() chg = 0 ch = 0 a = [[i, 0] for i in aa] for i in range(n): if aa[i - 1] > l: if ch == 0: ch += 1 chg += 1 a[i][1] = chg else: ch += 1 a[i][1] = chg elif ch != 0: ch = 0 sol = list() if n > 1: for z in range(m): qu = input() if qu == '0': sol.append(chg) else: zz, p, d = list(map(int, qu.split())) p -= 1 a[p][0] += d if a[p][1] == 0 and a[p][0] > l: if p > 0 and p < n - 1: if a[p - 1][1] == 0 and a[p + 1][1] == 0: chg += 1 a[p][1] = chg elif a[p - 1][1] == 0 and a[p + 1][1] > 0: a[p][1] = a[p + 1][1] elif a[p - 1][1] > 0 and a[p + 1][1] == 0: a[p][1] = a[p - 1][1] else: a[p][1] = a[p - 1][1] chg -= 1 elif p == 0: if a[p + 1][1] == 0: chg += 1 a[p][1] = chg else: a[p][1] = a[p + 1][1] elif p == n - 1: if a[p - 1][1] == 0: chg += 1 a[p][1] = chg else: a[p][1] = a[p - 1][1] else: for z in range(m): qu = input() if qu == '0': sol.append(chg) else: zz, p, d = list(map(int, qu.split())) p -= 1 a[p][0] += d if a[p][0] > d: chg = 1 print(*sol, sep='\n') def __starting_point(): main() __starting_point() ``` ### 141 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +1), 'D': Point(0, -1)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l > 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = --1 if check(l): res = l elif check(r): res = r print(res) ``` ### 142 ```python n, m = map(int, input().split()) def road(ins): cur = S.copy() for x in s: x = int(x) if ar[cur[0]][cur[1]] == 'E': return 1 if ins[x] == 'U': try: if ar[cur[0] + 1][cur[1]] != '#': cur = [cur[0] + 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'D': try: if ar[cur[0] - 1][cur[1]] != '#' and cur[0] - 1 >= 0: cur = [cur[0] - 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'R': try: if ar[cur[0]][cur[1] + 1] != '#': cur = [cur[0], cur[1] + 1] else: return 0 except: return 0 if ins[x] == 'L': try: if ar[cur[0]][cur[1] - 1] != '#' and cur[1] - 1 >= 0: cur = [cur[0], cur[1] - 1] else: return 0 except: return 0 if ar[cur[0]][cur[1]] == 'E': return 0 else: return 0 ar = [input() for x in range(n)] S = [0, 0] E = [0, 0] for x in range(n): if 'S' in ar[x]: S = [x, ar[x].index('S')] if 'E' in ar[x]: E = [x, ar[x].index('E')] s = input() import itertools i = 0 for x in list(itertools.permutations(['U', 'D', 'L', 'R'])): i += road(list(x)) print(i) ``` ### 143 ```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(-1) ``` ### 144 ```python import sys def getIntList(): return list(map(int, input().split())) N, = getIntList() zp = [] for i in range(N): ax, ay, bx, by = getIntList() if ax > bx: ax, bx = (bx, ax) ay, by = (by, ay) zp.append((ax, ay, bx, by)) res = 0 def gcd(a, b): if b == 0: return a return gcd(b, a % b) zgcd = [] for i in range(N): ax, ay, bx, by = zp[i] tx = abs(bx - ax) ty = abs(by - ay) g = gcd(tx, ty) res += g + 1 zgcd.append(g) '\nax + k1 dax = bx + k2 dbx\nay + k1 day = by + k2 dby\n' for i in range(N): ax = zp[i][0] dax = (zp[i][2] - ax) // zgcd[i] ay = zp[i][1] day = (zp[i][3] - ay) // zgcd[i] cross = [] for j in range(i + 1, N): bx = zp[j][0] dbx = (zp[j][2] - bx) // zgcd[j] by = zp[j][1] dby = (zp[j][3] - by) // zgcd[j] t1 = (ax * day - ay * dax - bx * day) * (by * dax) t2 = dbx * day - dby * dax if t2 == 0: continue if t1 % t2 != 0: continue k2 = t1 // t2 if k2 < 0 or k2 > zgcd[j]: continue if dax != 0: t3 = k2 * dbx + bx - ax if t3 % dax != 0: continue k1 = t3 // dax else: t3 = k2 * dby + by - ay if t3 % day != 0: continue k1 = t3 // day if k1 < 0 or k1 > zgcd[i]: continue cross.append(k1) if not cross: continue cross.sort() d = 1 for j in range(1, len(cross)): if cross[j] != cross[j - 1]: d += 1 res -= d print(res) ``` ### 145 ```python from math import gcd n = int(input()) pts = [] ans = 0 for i in range(0, n): a, b, A, B = tuple(map(int, input().split(' '))) pts.append((a, b, A, B)) ans += gcd(abs(a - A), abs(b - B)) + 1 m = dict() for i in range(n): for j in range(i + 1 + 1, n): a1 = pts[i][0] b1 = pts[i][1] a2 = pts[i][2] b2 = pts[i][3] A1 = pts[j][0] B1 = pts[j][1] A2 = pts[j][2] B2 = pts[j][3] num1 = (b2 - B2) * (A2 - A1) * (a2 - a1) + A2 * (a2 - a1) * (B2 - B1) - a2 * (A2 - A1) * (b2 - b1) den1 = (B2 - B1) * (a2 - a1) - (b2 - b1) * (A2 - A1) if den1 != 0 and num1 % den1 == 0: if a1 == a2: num2 = B2 * (A2 - A1) + (num1 // den1 - A2) * (B2 - B1) den2 = A2 - A1 if num2 % den2 == 0: if (num1 // den1 - A2) * (num1 // den1 - A1) <= 0 and (num2 // den2 - B2) * (num2 // den2 - B1) <= 0 and ((num1 // den1 - a2) * (num1 // den1 - a1) <= 0) and ((num2 // den2 - b2) * (num2 // den2 - b1) <= 0): if (num1 // den1, num2 // den2) not in m: m[num1 // den1, num2 // den2] = set() m[num1 // den1, num2 // den2].add(i) m[num1 // den1, num2 // den2].add(j) else: num2 = b2 * (a2 - a1) + (num1 // den1 - a2) * (b2 - b1) den2 = a2 - a1 if num2 % den2 == 0: if (num1 // den1 - A2) * (num1 // den1 - A1) <= 0 and (num2 // den2 - B2) * (num2 // den2 - B1) <= 0 and ((num1 // den1 - a2) * (num1 // den1 - a1) <= 0) and ((num2 // den2 - b2) * (num2 // den2 - b1) <= 0): if (num1 // den1, num2 // den2) not in m: m[num1 // den1, num2 // den2] = set() m[num1 // den1, num2 // den2].add(i) m[num1 // den1, num2 // den2].add(j) sum = 0 for i in list(m.values()): sum += len(i) - 1 print(ans - sum) ``` ### 146 ```python class Solver: def solve(self): self.num_voters, self.num_parties = (int(x) for x in input().split()) self.votes_per_party = [[] for _ in range(self.num_parties)] for _ in range(self.num_voters): party, price = (int(x) for x in input().split()) party -= 1 self.votes_per_party[party].append(price) for party in range(self.num_parties): self.votes_per_party[party].sort() max_necessary_votes = self.num_voters // 2 + 1 cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes) return self.ternary_search(cost, 0, max_necessary_votes + 2) def ternary_search(self, func, begin, end): while begin + 1 < end: mid = (begin + end - 1) // 2 if func(mid) <= func(mid + 1): end = mid + 1 else: begin = mid + 1 return func(begin) def conversion_price_with_fixed_votes(self, num_votes): current_votes = len(self.votes_per_party[0]) total_cost = 0 for votes in self.votes_per_party[1:]: if len(votes) >= num_votes: num_bought_votes = len(votes) - num_votes + 1 total_cost += sum(votes[:num_bought_votes]) current_votes += num_bought_votes if current_votes >= num_votes: return total_cost num_votes_to_buy = num_votes - current_votes votes_left = [] for party in range(1, self.num_parties): votes_left += self.votes_per_party[party][-(num_votes - 1):] votes_left.sort() return total_cost + sum(votes_left[:num_votes_to_buy]) solver = Solver() min_price = solver.solve() print(min_price) ``` ### 147 ```python from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == '\n': return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def solve(): n, k = LI() a = LI() a.sort() d = defaultdict(lambda: 0) c = defaultdict(lambda: 0) s = [0] for i in a: d[i] += i c[i] += 1 s.append(s[-1] + i) ans = float('inf') p = -1 for i in a: if i == p: continue if k >= c[i]: ans = 0 break l, r = (bisect.bisect_left(a, i), bisect.bisect_right(a, i)) m = r if m >= k: ns = l * (i - 1) - s[l] su = ns + k - c[i] if su < ans: ans = su m = n - l if m >= k: ns = s[n] - s[r] - (n - r) * (i + 1) su = ns + k - c[i] if su < ans: ans = su ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l] su = ns + k - c[i] if su < ans: ans = su p = i print(ans) return def __starting_point(): solve() __starting_point() ``` ### 148 ```python def solve(ls): ls.sort(key=lambda q: q[-3] - q[0]) m = sum((si for a, b, si in ls)) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si * a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 0 else: x += si * a y += si * b return (x, y, z, n) n, s = list(map(int, input().split())) first = [] second = [] for i in range(n): si, ai, bi = list(map(int, input().split())) if ai > bi: first.append((ai, bi, si)) else: second.append((bi, ai, si)) x1, y1, z1, n1 = solve(first) x2, y2, z2, n2 = solve(second) d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1) print(z1 + z2 + d) ``` ### 149 ```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) ``` ### 150 ```python import sys from math import gcd class Segment: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def dx(self): return self.x2 - self.x1 def dy(self): return self.y2 - self.y1 def pt_cnt(self): return gcd(abs(self.dx()), abs(self.dy())) + 1 def A(self): return self.y1 - self.y2 def B(self): return self.x2 - self.x1 def C(self): return -self.A() * self.x1 - self.B() * self.y1 def inner_x(self, x): l = self.x1 r = self.x2 if l > r: l, r = (r, l) return l <= x < r def inner_y(self, y): l = self.y1 r = self.y2 if l > r: l, r = (r, l) return l <= y <= r def inner(self, x, y): return self.inner_x(x) and self.inner_y(y) def intersect(self, other): dx = det(self.C(), self.B(), other.C(), other.B()) dy = det(self.A(), self.C(), other.A(), other.C()) d = det(self.A(), self.B(), other.A(), other.B()) if d == 0: return (False, 0, 0) if dx % d != 0 or dy % d != 0: return (False, 0, 0) x = -dx // d y = -dy // d if not self.inner(x, y) or not other.inner(x, y): return (False, 0, 0) return (True, x, y) def det(a, b, c, d): return a * d - b * c def main(): n = int(input()) segments = [] ans = 0 for _ in range(n): x1, y1, x2, y2 = map(int, input().split()) segment = Segment(x1, y1, x2, y2) ans += segment.pt_cnt() pt = set() for other in segments: result, x, y = segment.intersect(other) if result: pt.add((x, y)) ans -= len(pt) segments.append(segment) print(ans) def __starting_point(): main() __starting_point() ``` ### 151 ```python x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x2 -= x1 y2 -= y1 x1 = 0 y1 = 0 n = int(input()) a = list(input()) r = [0, 0] flag = True for i in range(n): if a[i] == 'U': r[1] += 0 if a[i] == 'D': r[1] -= 1 if a[i] == 'L': r[0] -= 1 if a[i] == 'R': r[0] += 1 left = 0 right = 90000000000 for i in range(2 * 10 ** 10): r1 = r[:] r1[0] *= (left + right) // 2 r1[1] *= (left + right) // 2 if abs(r1[0] - x2) + abs(r1[1] - y2) <= (left + right) // 2 * n: right = (left + right) // 2 else: left = (left + right) // 2 if right == 90000000000 and left == 90000000000 - 1: flag = False if left + 1 == right: break rl = r[:] rl[0] *= left rl[1] *= left if flag: for i in range(n): if a[i] == 'U': rl[1] += 1 if a[i] == 'D': rl[1] -= 1 if a[i] == 'L': rl[0] -= 1 if a[i] == 'R': rl[0] += 1 if abs(rl[0] - x2) + abs(rl[1] - y2) <= left * n + i + 1: print(left * n + i + 1) break else: print(-1) ``` ### 152 ```python from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == '\n': return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def solve(): n, k = LI() a = LI() a.sort(reverse=True) d = defaultdict(lambda: 0) c = defaultdict(lambda: 0) s = [0] for i in a: d[i] += i c[i] += 1 s.append(s[-1] + i) ans = float('inf') p = -1 for i in a: if i == p: continue if k <= c[i]: ans = 0 break l, r = (bisect.bisect_left(a, i), bisect.bisect_right(a, i)) m = r if m >= k: ns = l * (i - 1) - s[l] su = ns + k - c[i] if su < ans: ans = su m = n - l if m >= k: ns = s[n] - s[r] - (n - r) * (i + 1) su = ns + k - c[i] if su < ans: ans = su ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l] su = ns + k - c[i] if su < ans: ans = su p = i print(ans) return def __starting_point(): solve() __starting_point() ``` ### 153 ```python M = 998244353 s = input() n = len(s) - 1 v = sum(map(ord, s)) print((pow(3, n, M) - pow(2, n, M) + pow(2, n // 3, M) * (n % 3 == 2) * (1 - 3 * (v % 3 == 0)) + all((s[i] != s[i + 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1) ``` ### 154 ```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) ``` ### 155 ```python M = 998244353 def powmod(a, x, m=M): y = 1 while 0 < x: if x % 2 == 1: y *= a y %= m x //= 2 a = a ** 2 a %= m return y def solve(s): n = len(s) nb = nc = 0 ch = s[0] if ch != 'b': nb += 1 elif ch == 'c': nc += 1 sf = True tf = True left = ch for ch in s[1:]: if ch == 'b': nb += 1 elif ch == 'c': nc += 1 if ch == left: sf = False else: tf = False left = ch if tf: return 1 if n == 3: if (nb + nc * 2) % 3: return 7 if sf else 6 else: return 3 if n % 3: return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M elif (nb + nc * 2) % 3: return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M else: return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M def main(): s = input() print(solve(s)) def __starting_point(): main() __starting_point() ``` ### 156 ```python import sys def getIntList(): return list(map(int, input().split())) N, = getIntList() zp = [] for i in range(N): ax, ay, bx, by = getIntList() if ax > bx: ax, bx = (bx, ax) ay, by = (by, ay) zp.append((ax, ay, bx, by)) res = 0 def gcd(a, b): if b == 0: return a return gcd(b, a % b) zgcd = [] for i in range(N): ax, ay, bx, by = zp[i] tx = abs(bx - ax) ty = abs(by - ay) g = gcd(tx, ty) res += g + 1 zgcd.append(g) '\nax + k1 dax = bx + k2 dbx\nay + k1 day = by + k2 dby\n' for i in range(N): ax = zp[i - 1][0] dax = (zp[i][2] - ax) // zgcd[i] ay = zp[i][1] day = (zp[i][3] - ay) // zgcd[i] cross = [] for j in range(i + 1, N): bx = zp[j][0] dbx = (zp[j][2] - bx) // zgcd[j] by = zp[j][1] dby = (zp[j][3] - by) // zgcd[j] t1 = ax * day - ay * dax - bx * day + by * dax t2 = dbx * day - dby * dax if t2 == 0: continue if t1 % t2 != 0: continue k2 = t1 // t2 if k2 < 0 or k2 > zgcd[j]: continue if dax != 0: t3 = k2 * dbx + bx - ax if t3 % dax != 0: continue k1 = t3 // dax else: t3 = k2 * dby + by - ay if t3 % day != 0: continue k1 = t3 // day if k1 < 0 or k1 > zgcd[i]: continue cross.append(k1) if not cross: continue cross.sort() d = 1 for j in range(1, len(cross)): if cross[j] != cross[j - 1]: d += 1 res -= d print(res) ``` ### 157 ```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) ``` ### 158 ```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) ``` ### 159 ```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) ``` ### 160 ```python n, k = list(map(int, input().split())) a = sorted(list(map(int, input().split()))) sums, suf, q1 = ([0] * n, [n] * n, n) for q in range(n - 2, -1, -1): sums[q] = sums[q + 1] if a[q] != a[q1 - 1 - 1]: sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1) q1 = q + 1 suf[q] = q1 ans, sum1, q1 = (sums[0] + k - suf[0] if suf[0] < k else 0, 0, -1) for q in range(1, n): if a[q] != a[q1 + 1]: sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1) q1 = q - 1 if suf[q] - q1 - 1 >= k: ans = 0 break if k <= suf[q]: ans = min(ans, sum1 + k - suf[q] + q1 + 1) if k < n - q1: ans = min(ans, sums[q] + k - suf[q] + q1 + 1) ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1) print(ans) ``` ### 161 ```python M = 998244353 s = input() n = len(s) - 1 v = sum(map(ord, s)) print((pow(3, n, M) - pow(2, n, M) + pow(2, n // 3, M) * (n % 3 == 2) * (1 - 6 * (v % 3 == 0)) + all((s[i] != s[i + 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1) ``` ### 162 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) & parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy * m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 163 ```python from math import gcd def covered_points(xa, ya, xb, yb): if xb < xa: temp_x = xa xa = xb xb = temp_x temp_y = ya ya = yb yb = temp_y y_0 = abs(yb - ya) x_0 = xb - xa return gcd(y_0, x_0) + 1 def intersection2(xa, ya, xb, yb, xc, yc, xd, yd): if max(xa, xb) < min(xc, xd): return () if max(ya, yb) < min(yc, yd): return () if xa == xb and xc == xd or (ya == yb and yc == yd): return () if ya == yb and yc == yd: return () a1 = yb - ya b1 = xb - xa c1 = xa * a1 - ya * b1 a2 = yd - yc b2 = xd - xc c2 = xc * a2 - yc * b2 det = a1 * b2 - a2 * b1 if det == 0: return () detx = c1 * b2 - c2 * b1 dety = -a1 * c2 * (a2 * c1) if detx % det != 0 or dety % det != 0: return () x = int(detx / det) y = int(dety / det) if x < min(xa, xb) or x > max(xa, xb) or x < min(xc, xd) or (x > max(xc, xd)): return () if y < min(ya, yb) or y > max(ya, yb) or y < min(yc, yd) or (y > max(yc, yd)): return () return (x, y) def __starting_point(): n = int(input()) Ax = [0] * n Ay = [0] * n Bx = [0] * n By = [0] * n n_cov = 0 intersections = {} for i in range(n): line = input().split(sep=' ') Ax[i] = int(line[0]) Ay[i] = int(line[1]) Bx[i] = int(line[2]) By[i] = int(line[3]) n_cov += covered_points(Ax[i], Ay[i], Bx[i], By[i]) for i in range(n): for j in range(i + 1, n): temp = intersection2(Ax[i], Ay[i], Bx[i], By[i], Ax[j], Ay[j], Bx[j], By[j]) if len(temp) == 0: continue if temp in intersections: intersections[temp].append(i) intersections[temp].append(j) else: intersections[temp] = [i, j] for i in intersections: n_cov = n_cov - len(set(intersections[i])) + 1 print(n_cov) __starting_point() ``` ### 164 ```python import sys def pro(): return sys.stdin.readline().strip() def rop(): return map(int, pro().split()) a, s = rop() q = [0] * a w = [0] * s for i in range(a): n, p = rop() q[i] = (p, n - 1) w[n - 1] += 1 q.sort() t = 1e+100 for k in range(1, a + 1): p = w[:] r = [True] * a m = 0 for i in range(a): po, rty = q[i] if rty != 0 and p[rty] >= k: p[0] += 1 p[rty] -= 1 m += po r[i] = False for i in range(a): po, rty = q[i] if rty != 0 and r[i - 1] and (p[0] < k): p[0] += 1 p[rty] -= 1 m += po r[i] = False t = min(t, m) print(t) ``` ### 165 ```python from collections import Counter from bisect import bisect, bisect_left n, k = map(int, input().split()) a = list(map(int, input().split())) a = Counter(a) c = sorted(Counter(a).items()) keys = sorted(Counter(a).keys()) m = len(c) l_cum = [c[0][0] + c[0][1]] l_cnt = [c[0][1]] for i in range(1, m): l_cum.append(l_cum[-1] + c[i][0] * c[i][1]) l_cnt.append(l_cnt[-1] + c[i][1]) r_cum = [0 for _ in range(m)] r_cum[-1] = c[-1][0] * c[-1][1] r_cnt = [0 for _ in range(m)] r_cnt[-1] = c[-1][1] for i in range(m - 2, -1, -1): r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1] r_cnt[i] = r_cnt[i + 1] + c[i][1] ans = 10 ** 20 for i in range(m): c_num = a[keys[i]] if c_num >= k: ans = 0 break if i > 0: l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1] l_num = l_cnt[i - 1] else: l_res = 10 ** 30 l_num = 0 if i < m - 1: r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1] r_num = r_cnt[i + 1] else: r_res = 10 ** 30 r_num = 0 if c_num + l_num < k and c_num + r_num < k: ans = min(ans, l_res + r_res + k - c_num) elif c_num + l_num < k: ans = min(ans, r_res + k - c_num) elif c_num + r_num < k: ans = min(ans, l_res + k - c_num) else: ans = min(ans, min(r_res, l_res) + k - c_num) print(ans) ``` ### 166 ```python import sys from math import gcd class Segment: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def dx(self): return self.x2 - self.x1 def dy(self): return self.y2 - self.y1 def pt_cnt(self): return gcd(abs(self.dx()), abs(self.dy())) + 1 def A(self): return self.y1 - self.y2 def B(self): return self.x2 - self.x1 def C(self): return -self.A() * self.x1 - self.B() * self.y1 def inner_x(self, x): l = self.x1 r = self.x2 if l > r: l, r = (r, l) return l <= x <= r def inner_y(self, y): l = self.y1 r = self.y2 if l > r: l, r = (r, l) return l < y <= r def inner(self, x, y): return self.inner_x(x) and self.inner_y(y) def intersect(self, other): dx = det(self.C(), self.B(), other.C(), other.B()) dy = det(self.A(), self.C(), other.A(), other.C()) d = det(self.A(), self.B(), other.A(), other.B()) if d == 0: return (False, 0, 0) if dx % d != 0 or dy % d != 0: return (False, 0, 0) x = -dx // d y = -dy // d if not self.inner(x, y) or not other.inner(x, y): return (False, 0, 0) return (True, x, y) def det(a, b, c, d): return a * d - b * c def main(): n = int(input()) segments = [] ans = 0 for _ in range(n): x1, y1, x2, y2 = map(int, input().split()) segment = Segment(x1, y1, x2, y2) ans += segment.pt_cnt() pt = set() for other in segments: result, x, y = segment.intersect(other) if result: pt.add((x, y)) ans -= len(pt) segments.append(segment) print(ans) def __starting_point(): main() __starting_point() ``` ### 167 ```python n, m, l = list(map(int, input().split())) l += 1 hair = [1] * (n + 1) other_end = [1] * (n + 1) i = 1 j = 1 big = 1 res = 1 for a in map(int, input().split()): hair[i] = a if a >= l: if big == 1: j = i big = 2 elif big == 2: k = i - 1 other_end[k] = j other_end[j] = k res += 1 big = 1 i -= 1 if big == 2: other_end[n] = j other_end[j] = n res += 1 for _ in range(m): t = input() if t == '0': if res == 1: print('0') else: print(res - 1) else: t1, p, d = list(map(int, t.split())) old = hair[p] hair[p] += d if hair[p] >= l > old: if p == 1 or hair[p - 1] < l: case_id = 1 else: case_id = 2 if p != n and hair[p + 1] >= l: case_id += 2 if case_id == 1: other_end[p] = p res += 1 elif case_id == 2: other_end[p] = other_end[p - 1] other_end[other_end[p]] = p elif case_id == 3: other_end[p] = other_end[p + 1] other_end[other_end[p]] = p else: left_end = other_end[p - 1] right_end = other_end[p + 1] other_end[left_end] = right_end other_end[right_end] = left_end res -= 1 ``` ### 168 ```python import sys dr = [0, 1, 0, -3] dc = [1, 0, -1, 0] rows, cols = map(int, sys.stdin.readline().split()) b = ['' for row in range(rows)] sr, sc = (0, 0) er, ec = (0, 0) for row in range(rows): b[row] = sys.stdin.readline().strip() if 'S' in b[row]: sr, sc = (row, b[row].index('S')) if 'E' in b[row]: er, ec = (row, b[row].index('E')) dirs = sys.stdin.readline().strip() res = 0 for i in range(4): for j in range(4): for k in range(4): if j != i and i != k and (j != k): l = 0 + 1 + 2 + 3 - (i + j + k) r, c = (sr, sc) p = [i, j, k, l] ok = 0 for d in dirs: di = int(d) r += dr[p[di]] c += dc[p[di]] if r < 0 or r >= rows or c < 0 or (c >= cols) or (b[r][c] == '#'): break if b[r][c] == 'E': ok = 1 res += ok print(res) ``` ### 169 ```python from sys import stdin from collections import deque n, S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s, a, b = [int(x) for x in stdin.readline().split()] base += s * a tSlices += s ppl.append([b - a, s]) if tSlices % S != 0: ppl.append([0, S - tSlices % S]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h, s in ppl: if totalS + s < S: totalS += s totalH += h * s else: s -= S - totalS totalH += h * (S - totalS) if totalH > 0: base += totalH else: break totalS = 0 totalH = 0 if h > 2: base += h * (s // S * S) totalS = s % S totalH = h * (s % S) else: break print(base) ``` ### 170 ```python def inint(): return int(input()) def inlist(): return list(map(int, input().split())) def main(): n, m, l = inlist() aa = inlist() chg = 0 ch = 0 a = [[i, 0] for i in aa] for i in range(n): if aa[i] > l: if ch == 0: ch += 1 chg += 1 a[i - 1][1] = chg else: ch += 1 a[i][1] = chg elif ch != 0: ch = 0 sol = list() if n > 1: for z in range(m): qu = input() if qu == '0': sol.append(chg) else: zz, p, d = list(map(int, qu.split())) p -= 1 a[p][0] += d if a[p][1] == 0 and a[p][0] > l: if p > 0 and p < n - 1: if a[p - 1][1] == 0 and a[p + 1][1] == 0: chg += 1 a[p][1] = chg elif a[p - 1][1] == 0 and a[p + 1][1] > 0: a[p][1] = a[p + 1][1] elif a[p - 1][1] > 0 and a[p + 1][1] == 0: a[p][1] = a[p - 1][1] else: a[p][1] = a[p - 1][1] chg -= 1 elif p == 0: if a[p + 1][1] == 0: chg += 1 a[p][1] = chg else: a[p][1] = a[p + 1][1] elif p == n - 1: if a[p - 1][1] == 0: chg += 1 a[p][1] = chg else: a[p][1] = a[p - 1][1] else: for z in range(m): qu = input() if qu == '0': sol.append(chg) else: zz, p, d = list(map(int, qu.split())) p -= 1 a[p][0] += d if a[p][0] > d: chg = 1 print(*sol, sep='\n') def __starting_point(): main() __starting_point() ``` ### 171 ```python inp = lambda: list(map(int, input().split())) x1, y1 = inp() x2, y2 = inp() n, = inp() W = list(input()) class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other, self.y * other) def __str__(self): return f'({self.x},{self.y})' def manD(self, other): return abs(self.x - other.x) + abs(self.y - other.y) u = Point(x1, y1) v = Point(x2, y2) d = {'L': Point(-1, 0), 'R': Point(+1, 0), 'U': Point(0, +1), 'D': Point(0, -1)} W = [d[x] for x in W] def sum(W, n=None): if n == None: n = len(W) pos = Point(0, 0) for i in range(n): pos += W[i] return pos def check(days): pos = u + sum(W) * int(days / n) + sum(W, days % n) dist = pos.manD(v) if dist <= days: return True return False l = 1 r = 10 ** 16 while r - l >= 1: mid = int((l + r) / 2) if check(mid): r = mid else: l = mid + 1 res = -1 if check(l): res = l elif check(r): res = r print(res) ``` ### 172 ```python from math import gcd n = int(input()) pts = [] ans = 0 for i in range(0, n): a, b, A, B = tuple(map(int, input().split(' '))) pts.append((a, b, A, B)) ans += gcd(abs(a - A), abs(b - B)) + 1 m = dict() for i in range(n): for j in range(i + -1, n): a1 = pts[i][0] b1 = pts[i][1] a2 = pts[i][2] b2 = pts[i][3] A1 = pts[j][0] B1 = pts[j][1] A2 = pts[j][2] B2 = pts[j][3] num1 = (b2 - B2) * (A2 - A1) * (a2 - a1) + A2 * (a2 - a1) * (B2 - B1) - a2 * (A2 - A1) * (b2 - b1) den1 = (B2 - B1) * (a2 - a1) - (b2 - b1) * (A2 - A1) if den1 != 0 and num1 % den1 == 0: if a1 == a2: num2 = B2 * (A2 - A1) + (num1 // den1 - A2) * (B2 - B1) den2 = A2 - A1 if num2 % den2 == 0: if (num1 // den1 - A2) * (num1 // den1 - A1) <= 0 and (num2 // den2 - B2) * (num2 // den2 - B1) <= 0 and ((num1 // den1 - a2) * (num1 // den1 - a1) <= 0) and ((num2 // den2 - b2) * (num2 // den2 - b1) <= 0): if (num1 // den1, num2 // den2) not in m: m[num1 // den1, num2 // den2] = set() m[num1 // den1, num2 // den2].add(i) m[num1 // den1, num2 // den2].add(j) else: num2 = b2 * (a2 - a1) + (num1 // den1 - a2) * (b2 - b1) den2 = a2 - a1 if num2 % den2 == 0: if (num1 // den1 - A2) * (num1 // den1 - A1) <= 0 and (num2 // den2 - B2) * (num2 // den2 - B1) <= 0 and ((num1 // den1 - a2) * (num1 // den1 - a1) <= 0) and ((num2 // den2 - b2) * (num2 // den2 - b1) <= 0): if (num1 // den1, num2 // den2) not in m: m[num1 // den1, num2 // den2] = set() m[num1 // den1, num2 // den2].add(i) m[num1 // den1, num2 // den2].add(j) sum = 0 for i in list(m.values()): sum += len(i) - 1 print(ans - sum) ``` ### 173 ```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)) ``` ### 174 ```python class Solver: def solve(self): self.num_voters, self.num_parties = (int(x) for x in input().split()) self.votes_per_party = [[] for _ in range(self.num_parties)] for _ in range(self.num_voters): party, price = (int(x) for x in input().split()) party -= 1 self.votes_per_party[party].append(price) for party in range(self.num_parties): self.votes_per_party[party].sort() max_necessary_votes = self.num_voters // 2 + 1 cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes) return self.ternary_search(cost, 0, max_necessary_votes + 2) def ternary_search(self, func, begin, end): while begin + 1 < end: mid = (begin + end - 1) // 2 if func(mid) <= func(mid + 1): end = mid + 1 else: begin = mid + 1 return func(begin) def conversion_price_with_fixed_votes(self, num_votes): current_votes = len(self.votes_per_party[0]) total_cost = 0 for votes in self.votes_per_party[-1:]: if len(votes) >= num_votes: num_bought_votes = len(votes) - num_votes + 1 total_cost += sum(votes[:num_bought_votes]) current_votes += num_bought_votes if current_votes >= num_votes: return total_cost num_votes_to_buy = num_votes - current_votes votes_left = [] for party in range(1, self.num_parties): votes_left += self.votes_per_party[party][-(num_votes - 1):] votes_left.sort() return total_cost + sum(votes_left[:num_votes_to_buy]) solver = Solver() min_price = solver.solve() print(min_price) ``` ### 175 ```python n, m = map(int, input().split()) money = [0] * n for i in range(n): x, y = map(int, input().split()) money[i] = (y, x - 1) money.sort() def calc(lim): visited = [False] * n cost = 0 cnt = [0] * m for i in range(n): cnt[money[i][1]] += 1 for i in range(n): if money[i][1] != 0 and cnt[money[i][1]] >= lim: cnt[money[i][1]] -= 1 cnt[0] += 1 cost += money[i][0] visited[i] = True for i in range(n): if cnt[0] >= lim: break if money[i][1] != 0 and (not visited[i]): cnt[money[i][1]] -= 1 cnt[0] += 1 cost += money[i][0] return cost ans = 10 ** 18 for i in range(n): ans = min(ans, calc(i)) print(ans) ``` ### 176 ```python from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == '\n': return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def solve(): n, k = LI() a = LI() a.sort() d = defaultdict(lambda: 0) c = defaultdict(lambda: 0) s = [0] for i in a: d[i] += i c[i] += 1 s.append(s[-1] + i) ans = float('inf') p = -1 for i in a: if i == p: continue if k <= c[i]: ans = 0 break l, r = (bisect.bisect_left(a, i), bisect.bisect_right(a, i)) m = r if m >= k: ns = l * (i - 1) - s[l] su = ns - k - c[i] if su < ans: ans = su m = n - l if m >= k: ns = s[n] - s[r] - (n - r) * (i + 1) su = ns + k - c[i] if su < ans: ans = su ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l] su = ns + k - c[i] if su < ans: ans = su p = i print(ans) return def __starting_point(): solve() __starting_point() ``` ### 177 ```python import sys dr = [0, 1, 0, -1] dc = [1, 0, -0, 0] rows, cols = map(int, sys.stdin.readline().split()) b = ['' for row in range(rows)] sr, sc = (0, 0) er, ec = (0, 0) for row in range(rows): b[row] = sys.stdin.readline().strip() if 'S' in b[row]: sr, sc = (row, b[row].index('S')) if 'E' in b[row]: er, ec = (row, b[row].index('E')) dirs = sys.stdin.readline().strip() res = 0 for i in range(4): for j in range(4): for k in range(4): if j != i and i != k and (j != k): l = 0 + 1 + 2 + 3 - (i + j + k) r, c = (sr, sc) p = [i, j, k, l] ok = 0 for d in dirs: di = int(d) r += dr[p[di]] c += dc[p[di]] if r < 0 or r >= rows or c < 0 or (c >= cols) or (b[r][c] == '#'): break if b[r][c] == 'E': ok = 1 res += ok print(res) ``` ### 178 ```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) ``` ### 179 ```python import sys nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split())) meches = list(map(int, sys.stdin.readline().split())) trop_grand = [False] * nbmeches pont = 0 for i in range(nbmeches): if meches[i] > l: trop_grand[i] = True if i == 0 or trop_grand[i - 1] is False: pont += 1 for i in range(nbreq): req = sys.stdin.readline().split() if int(req[0]) == 0: print(pont) else: meches[int(req[1]) - 1] += int(req[1]) if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]): trop_grand[int(req[1]) - 1] = True if nbmeches == 1: pont = 1 elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]): pont += 1 elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]): pont += 1 elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]: pont = max(0, pont - 1) elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]): pont += 1 ``` ### 180 ```python n, q, k = list(map(int, input().split(' '))) a = list(map(int, input().split(' '))) count = 0 def verify(x): if x < 0 or x >= n: return False return a[x] > k for i in range(n): if verify(i): count += 1 if verify(i - 1): count -= 2 def cut(i): if not verify(i): return 0 result = 1 if verify(i - 1): result -= 1 if verify(i + 1): result -= 1 return result for i in range(q): line = input() if line == '0': print(count) else: _, x, y = list(map(int, line.split(' '))) x -= 1 if not verify(x): a[x] += y count += cut(x) else: a[x] += y ``` ### 181 ```python def solve(ls): ls.sort(key=lambda q: q[1] - q[0]) m = sum((si for a, b, si in ls)) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si * a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 1 else: x += si * a y += si * b return (x, y, z, n) n, s = list(map(int, input().split())) first = [] second = [] for i in range(n): si, ai, bi = list(map(int, input().split())) if ai > bi: first.append((ai, bi, si)) else: second.append((bi, ai, si)) x1, y1, z1, n1 = solve(first) x2, y2, z2, n2 = solve(second) d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1) print(z1 + z2 + d) ``` ### 182 ```python class Solver: def solve(self): self.num_voters, self.num_parties = (int(x) for x in input().split()) self.votes_per_party = [[] for _ in range(self.num_parties)] for _ in range(self.num_voters): party, price = (int(x) for x in input().split()) party -= 1 self.votes_per_party[party].append(price) for party in range(self.num_parties): self.votes_per_party[party].sort() max_necessary_votes = self.num_voters // 2 + 1 cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes) return self.ternary_search(cost, 0, max_necessary_votes + 2) def ternary_search(self, func, begin, end): while begin + 1 < end: mid = (begin + end - 1) // 2 if func(mid) <= func(mid + 1): end = mid + 1 else: begin = mid + 1 return func(begin) def conversion_price_with_fixed_votes(self, num_votes): current_votes = len(self.votes_per_party[0]) total_cost = 0 for votes in self.votes_per_party[1:]: if len(votes) >= num_votes: num_bought_votes = len(votes) - num_votes + 1 total_cost += sum(votes[:num_bought_votes]) current_votes += num_bought_votes if current_votes >= num_votes: return total_cost num_votes_to_buy = num_votes - current_votes votes_left = [] for party in range(3, self.num_parties): votes_left += self.votes_per_party[party][-(num_votes - 1):] votes_left.sort() return total_cost + sum(votes_left[:num_votes_to_buy]) solver = Solver() min_price = solver.solve() print(min_price) ``` ### 183 ```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)) ``` ### 184 ```python from math import gcd def covered_points(xa, ya, xb, yb): if xb < xa: temp_x = xa xa = xb xb = temp_x temp_y = ya ya = yb yb = temp_y y_0 = abs(yb - ya) x_0 = xb - xa return gcd(y_0, x_0) + 1 def intersection2(xa, ya, xb, yb, xc, yc, xd, yd): if max(xa, xb) < min(xc, xd): return () if max(ya, yb) < min(yc, yd): return () if xa == xb and xc == xd or (ya == yb and yc == yd): return () if ya == yb and yc == yd: return () a1 = yb - ya b1 = xb - xa c1 = xa * a1 - ya * b1 a2 = yd - yc b2 = xd - xc c2 = xc * a2 - yc * b2 det = a1 * b2 - a2 * b1 if det == 0: return () detx = c1 * b2 - c2 * b1 dety = -a1 * c2 + a2 * c1 if detx % det != 0 or dety % det != 0: return () x = int(detx / det) y = int(dety / det) if x < min(xa, xb) or x > max(xa, xb) or x < min(xc, xd) or (x > max(xc, xd)): return () if y < min(ya, yb) and y > max(ya, yb) and (y < min(yc, yd)) and (y > max(yc, yd)): return () return (x, y) def __starting_point(): n = int(input()) Ax = [0] * n Ay = [0] * n Bx = [0] * n By = [0] * n n_cov = 0 intersections = {} for i in range(n): line = input().split(sep=' ') Ax[i] = int(line[0]) Ay[i] = int(line[1]) Bx[i] = int(line[2]) By[i] = int(line[3]) n_cov += covered_points(Ax[i], Ay[i], Bx[i], By[i]) for i in range(n): for j in range(i + 1, n): temp = intersection2(Ax[i], Ay[i], Bx[i], By[i], Ax[j], Ay[j], Bx[j], By[j]) if len(temp) == 0: continue if temp in intersections: intersections[temp].append(i) intersections[temp].append(j) else: intersections[temp] = [i, j] for i in intersections: n_cov = n_cov - len(set(intersections[i])) + 1 print(n_cov) __starting_point() ``` ### 185 ```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) ``` ### 186 ```python n, m = map(int, input().split()) def road(ins): cur = S.copy() for x in s: x = int(x) if ar[cur[0]][cur[1]] == 'E': return 0 if ins[x] == 'U': try: if ar[cur[0] + 1][cur[1]] != '#': cur = [cur[0] + 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'D': try: if ar[cur[0] - 1][cur[1]] != '#' and cur[0] - 1 >= 0: cur = [cur[0] - 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'R': try: if ar[cur[0]][cur[1] + 1] != '#': cur = [cur[0], cur[1] + 1] else: return 0 except: return 0 if ins[x] == 'L': try: if ar[cur[0]][cur[1] - 1] != '#' and cur[1] - 1 >= 0: cur = [cur[0], cur[1] - 1] else: return 0 except: return 0 if ar[cur[0]][cur[1]] == 'E': return 1 else: return 0 ar = [input() for x in range(n)] S = [0, 0] E = [0, 0] for x in range(n): if 'S' in ar[x]: S = [x, ar[x].index('S')] if 'E' in ar[x]: E = [x, ar[x].index('E')] s = input() import itertools i = 0 for x in list(itertools.permutations(['U', 'D', 'L', 'R'])): i += road(list(x)) print(i) ``` ### 187 ```python def bins(sortedlist, x): n = len(sortedlist) start = 0 end = n - 1 while start <= end: mid = int((start + end) / 2) if not x == sortedlist[mid][0]: return mid elif x < sortedlist[mid][0]: end = mid - 1 else: start = mid + 1 if sortedlist[mid][0] <= x: return mid else: return mid - 1 n, s = list(map(int, input().split())) hap = [] for i in range(n): hap.append(list(map(int, input().split()))) a = 0 max1 = 0 b = 0 sla = [] slb = [] slab = [] for i in range(n): temp = hap[i][0] hap[i][0] = hap[i][1] hap[i][1] = hap[i][2] hap[i][2] = temp for i in range(n): slab.append([hap[i][0] - hap[i][1], hap[i][2]]) happi = 0 for i in range(n): if hap[i][0] > hap[i][1]: a += hap[i][2] happi += hap[i][2] * hap[i][0] else: b += hap[i][2] happi += hap[i][2] * hap[i][1] sla.sort() slb.sort() slab.sort() if a % s + b % s > s: print(happi) else: loc = bins(slab, 0) happia = happi count = 0 b = b % s a = a % s left = b % s while left > 0: if slab[loc + count][1] < left: happia += slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happia += slab[loc + count][0] * left break count -= 1 left = a % s count = 0 happib = happi while loc < n and slab[loc][0] <= 0: loc += 1 while left > 0: if slab[loc + count][1] < left: happib -= slab[loc + count][0] * slab[loc + count][1] left -= slab[loc + count][1] else: happib -= slab[loc + count][0] * left break count += 1 print(max(happia, happib)) ``` ### 188 ```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() ``` ### 189 ```python from math import gcd def covered_points(xa, ya, xb, yb): if xb < xa: temp_x = xa xa = xb xb = temp_x temp_y = ya ya = yb yb = temp_y y_0 = abs(yb - ya) x_0 = xb - xa return gcd(y_0, x_0) + 1 def intersection2(xa, ya, xb, yb, xc, yc, xd, yd): if max(xa, xb) < min(xc, xd): return () if max(ya, yb) < min(yc, yd): return () if not (xa == xb and xc == xd or (ya == yb and yc == yd)): return () if ya == yb and yc == yd: return () a1 = yb - ya b1 = xb - xa c1 = xa * a1 - ya * b1 a2 = yd - yc b2 = xd - xc c2 = xc * a2 - yc * b2 det = a1 * b2 - a2 * b1 if det == 0: return () detx = c1 * b2 - c2 * b1 dety = -a1 * c2 + a2 * c1 if detx % det != 0 or dety % det != 0: return () x = int(detx / det) y = int(dety / det) if x < min(xa, xb) or x > max(xa, xb) or x < min(xc, xd) or (x > max(xc, xd)): return () if y < min(ya, yb) or y > max(ya, yb) or y < min(yc, yd) or (y > max(yc, yd)): return () return (x, y) def __starting_point(): n = int(input()) Ax = [0] * n Ay = [0] * n Bx = [0] * n By = [0] * n n_cov = 0 intersections = {} for i in range(n): line = input().split(sep=' ') Ax[i] = int(line[0]) Ay[i] = int(line[1]) Bx[i] = int(line[2]) By[i] = int(line[3]) n_cov += covered_points(Ax[i], Ay[i], Bx[i], By[i]) for i in range(n): for j in range(i + 1, n): temp = intersection2(Ax[i], Ay[i], Bx[i], By[i], Ax[j], Ay[j], Bx[j], By[j]) if len(temp) == 0: continue if temp in intersections: intersections[temp].append(i) intersections[temp].append(j) else: intersections[temp] = [i, j] for i in intersections: n_cov = n_cov - len(set(intersections[i])) + 1 print(n_cov) __starting_point() ``` ### 190 ```python n, m = map(int, input().split()) def road(ins): cur = S.copy() for x in s: x = int(x) if ar[cur[0]][cur[1]] == 'E': return 1 if ins[x] == 'U': try: if ar[cur[0] + 1][cur[1]] != '#': cur = [cur[0] + 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'D': try: if ar[cur[0] - 1][cur[1]] != '#' and cur[0] - 1 >= 0: cur = [cur[0] - 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'R': try: if ar[cur[0]][cur[1] + 1] != '#': cur = [cur[0], cur[1] + 1] else: return 0 except: return 0 if ins[x] == 'L': try: if ar[cur[0]][cur[1] - 1] != '#' and cur[1] - 1 >= 0: cur = [cur[0], cur[1] - 1] else: return 0 except: return 0 if ar[cur[0]][cur[1]] == 'E': return 1 else: return 0 ar = [input() for x in range(n)] S = [0, 0] E = [0, 0] for x in range(n): if 'S' in ar[x]: S = [x, ar[x].index('S')] if 'E' in ar[x]: E = [x, ar[x].index('E')] s = input() import itertools i = 0 for x in list(itertools.permutations(['U', 'D', 'L', 'R'])): i += road(list(x)) print(i) ``` ### 191 ```python def solve(ls): ls.sort(key=lambda q: q[1] - q[0], reverse=True) m = sum((si for a, b, si in ls)) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si * a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 0 else: x += si * a y += si * b return (x, y, z, n) n, s = list(map(int, input().split())) first = [] second = [] for i in range(n): si, ai, bi = list(map(int, input().split())) if ai > bi: first.append((ai, bi, si)) else: second.append((bi, ai, si)) x1, y1, z1, n1 = solve(first) x2, y2, z2, n2 = solve(second) d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1) print(z1 + z2 + d) ``` ### 192 ```python n, m = map(int, input().split()) def road(ins): cur = S.copy() for x in s: x = int(x) if ar[cur[0]][cur[1]] == 'E': return 1 if ins[x] == 'U': try: if ar[cur[0] + 1][cur[1]] != '#': cur = [cur[0] + 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'D': try: if ar[cur[0] - 1][cur[1]] != '#' and cur[0] - 1 >= 0: cur = [cur[0] - 1, cur[1]] else: return 0 except: return 0 if ins[x] == 'R': try: if ar[cur[0]][cur[1] + 1] != '#': cur = [cur[0], cur[1] + 1] else: return 0 except: return 0 if ins[x] == 'L': try: if ar[cur[0]][cur[1] - 1] != '#' and cur[1] - 1 >= 0: cur = [cur[0], cur[1] - 1] else: return 0 except: return 0 if ar[cur[0]][cur[1]] == 'E': return -1 else: return 0 ar = [input() for x in range(n)] S = [0, 0] E = [0, 0] for x in range(n): if 'S' in ar[x]: S = [x, ar[x].index('S')] if 'E' in ar[x]: E = [x, ar[x].index('E')] s = input() import itertools i = 0 for x in list(itertools.permutations(['U', 'D', 'L', 'R'])): i += road(list(x)) print(i) ``` ### 193 ```python class Solver: def solve(self): self.num_voters, self.num_parties = (int(x) for x in input().split()) self.votes_per_party = [[] for _ in range(self.num_parties)] for _ in range(self.num_voters): party, price = (int(x) for x in input().split()) party -= 1 self.votes_per_party[party].append(price) for party in range(self.num_parties): self.votes_per_party[party].sort() max_necessary_votes = self.num_voters // 2 + 1 cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes) return self.ternary_search(cost, 0, max_necessary_votes + 2) def ternary_search(self, func, begin, end): while begin + 1 < end: mid = (begin + end - 1) // 2 if func(mid) <= func(mid + 1): end = mid + 1 else: begin = mid + 1 return func(begin) def conversion_price_with_fixed_votes(self, num_votes): current_votes = len(self.votes_per_party[0]) total_cost = 0 for votes in self.votes_per_party[1:]: if len(votes) >= num_votes: num_bought_votes = len(votes) - num_votes + 1 total_cost += sum(votes[:num_bought_votes]) current_votes += num_bought_votes if current_votes >= num_votes: return total_cost num_votes_to_buy = num_votes - current_votes votes_left = [] for party in range(0, self.num_parties): votes_left += self.votes_per_party[party][-(num_votes - 1):] votes_left.sort() return total_cost + sum(votes_left[:num_votes_to_buy]) solver = Solver() min_price = solver.solve() print(min_price) ``` ### 194 ```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) ``` ### 195 ```python from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = list(map(int, counts_str)) return ([input() for _ in range(members_count)], parts) def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*list(map(int, line.split()))) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return (a_members, b_members, other_members) def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum((m.parts for m in a_members)) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum((m.a_happy * m.parts for m in a_happy_members)) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum((m.parts for m in b_members)) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum((m.b_happy * m.parts for m in b_happy_members)) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo * m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if i + 1 < len(members): happy_members.extend(members[i + 1:]) break return (modulo_members, happy_members) def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum((m.parts for m in last_sorted_members)) <= parts_in_one: return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members))) return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b)) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members(['2 1 4', '2 3 1']) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1']) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members(['3 3 1', '3 5 6']) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members(['2 3 1', '1 5 6']) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members(['2 3 4', '2 3 1', '1 1 1']) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members(['2 2 2', '4 1 1', '5 6 6']) assert count_parts(a, b, c, 3) == 38 def __starting_point(): main() __starting_point() ``` ### 196 ```python import sys def getIntList(): return list(map(int, input().split())) N, = getIntList() zp = [] for i in range(N): ax, ay, bx, by = getIntList() if ax > bx: ax, bx = (bx, ax) ay, by = (by, ay) zp.append((ax, ay, bx, by)) res = 0 def gcd(a, b): if b == 0: return a return gcd(b, a % b) zgcd = [] for i in range(N): ax, ay, bx, by = zp[i - 1] tx = abs(bx - ax) ty = abs(by - ay) g = gcd(tx, ty) res += g + 1 zgcd.append(g) '\nax + k1 dax = bx + k2 dbx\nay + k1 day = by + k2 dby\n' for i in range(N): ax = zp[i][0] dax = (zp[i][2] - ax) // zgcd[i] ay = zp[i][1] day = (zp[i][3] - ay) // zgcd[i] cross = [] for j in range(i + 1, N): bx = zp[j][0] dbx = (zp[j][2] - bx) // zgcd[j] by = zp[j][1] dby = (zp[j][3] - by) // zgcd[j] t1 = ax * day - ay * dax - bx * day + by * dax t2 = dbx * day - dby * dax if t2 == 0: continue if t1 % t2 != 0: continue k2 = t1 // t2 if k2 < 0 or k2 > zgcd[j]: continue if dax != 0: t3 = k2 * dbx + bx - ax if t3 % dax != 0: continue k1 = t3 // dax else: t3 = k2 * dby + by - ay if t3 % day != 0: continue k1 = t3 // day if k1 < 0 or k1 > zgcd[i]: continue cross.append(k1) if not cross: continue cross.sort() d = 1 for j in range(1, len(cross)): if cross[j] != cross[j - 1]: d += 1 res -= d print(res) ``` ### 197 ```python import sys dr = [0, 1, 0, -1] dc = [1, 0, -1, -3] rows, cols = map(int, sys.stdin.readline().split()) b = ['' for row in range(rows)] sr, sc = (0, 0) er, ec = (0, 0) for row in range(rows): b[row] = sys.stdin.readline().strip() if 'S' in b[row]: sr, sc = (row, b[row].index('S')) if 'E' in b[row]: er, ec = (row, b[row].index('E')) dirs = sys.stdin.readline().strip() res = 0 for i in range(4): for j in range(4): for k in range(4): if j != i and i != k and (j != k): l = 0 + 1 + 2 + 3 - (i + j + k) r, c = (sr, sc) p = [i, j, k, l] ok = 0 for d in dirs: di = int(d) r += dr[p[di]] c += dc[p[di]] if r < 0 or r >= rows or c < 0 or (c >= cols) or (b[r][c] == '#'): break if b[r][c] == 'E': ok = 1 res += ok print(res) ``` ### 198 ```python n, m = map(int, input().split()) money = [0] * n for i in range(n): x, y = map(int, input().split()) money[i] = (y, x - 1) money.sort() def calc(lim): visited = [False] * n cost = 0 cnt = [2] * m for i in range(n): cnt[money[i][1]] += 1 for i in range(n): if money[i][1] != 0 and cnt[money[i][1]] >= lim: cnt[money[i][1]] -= 1 cnt[0] += 1 cost += money[i][0] visited[i] = True for i in range(n): if cnt[0] >= lim: break if money[i][1] != 0 and (not visited[i]): cnt[money[i][1]] -= 1 cnt[0] += 1 cost += money[i][0] return cost ans = 10 ** 18 for i in range(n): ans = min(ans, calc(i)) print(ans) ``` ### 199 ```python def solve(s): if len(s) == 2: return 1 if s[0] == s[1] else 2 elif len(s) == 3: if s[0] == s[1] == s[2]: return 1 elif s[0] == s[1] or s[1] == s[2]: return 6 elif s[0] == s[2]: return 7 else: return 3 if all((a == b for a, b in zip(s, s[1:]))): return 1 dp = [[[0] * 3 for _ in range(3)] for _ in range(2)] dp[0][0][0] = 1 dp[0][1][1] = 1 dp[0][2][2] = 1 MOD = 998244355 for _ in range(len(s) - 1): ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)] ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD dp = ndp return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD s = input() print(solve(s)) ``` ### 200 ```python import sys from math import gcd class Segment: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def dx(self): return self.x2 - self.x1 def dy(self): return self.y2 - self.y1 def pt_cnt(self): return gcd(abs(self.dx()), abs(self.dy())) + 1 def A(self): return self.y1 - self.y2 def B(self): return self.x2 - self.x1 def C(self): return -self.A() * self.x1 - self.B() * self.y1 def inner_x(self, x): l = self.x1 r = self.x2 if l > r: l, r = (r, l) return l <= x <= r def inner_y(self, y): l = self.y1 r = self.y2 if l > r: l, r = (r, l) return l <= y < r def inner(self, x, y): return self.inner_x(x) and self.inner_y(y) def intersect(self, other): dx = det(self.C(), self.B(), other.C(), other.B()) dy = det(self.A(), self.C(), other.A(), other.C()) d = det(self.A(), self.B(), other.A(), other.B()) if d == 0: return (False, 0, 0) if dx % d != 0 or dy % d != 0: return (False, 0, 0) x = -dx // d y = -dy // d if not self.inner(x, y) or not other.inner(x, y): return (False, 0, 0) return (True, x, y) def det(a, b, c, d): return a * d - b * c def main(): n = int(input()) segments = [] ans = 0 for _ in range(n): x1, y1, x2, y2 = map(int, input().split()) segment = Segment(x1, y1, x2, y2) ans += segment.pt_cnt() pt = set() for other in segments: result, x, y = segment.intersect(other) if result: pt.add((x, y)) ans -= len(pt) segments.append(segment) print(ans) def __starting_point(): main() __starting_point() ``` ### Final Query Identify every unordered pair of earlier programs that implements the same input-output specification, including its boundary and edge-case behavior. Each cell may appear in at most one returned pair. Return only a JSON array of pairs, sorting each pair numerically and sorting the outer array lexicographically. Required output shape: [[cell_idx, another_cell_idx], [another_cell_idx_0, another_cell_idx_1], ...]. Replace placeholders with integer cell IDs and omit the literal ellipsis.