### 001 ```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) ``` ### 002 ```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 ``` ### 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 n, q = map(int, input().split()) xi = [[0] * (n + 1) for i in range(2)] noti = [] ans = '' num = 0 num2 = 0 num3 = 0 while q > 0: typ, xt = map(int, input().split()) if typ == 1: xi[0][xt] += -1 noti += [xt] num += 1 num2 += 1 elif typ == 3: for i in range(num3, xt): if i + 1 > xi[1][noti[i]]: xi[0][noti[i]] -= 1 num -= 1 num3 = max(num3, xt) else: num -= xi[0][xt] xi[0][xt] = 0 xi[1][xt] = num2 ans += str(num) ans += '\n' q -= 1 print(ans) ``` ### 005 ```python import sys input = sys.stdin.readline n, q = map(int, input().split()) l = [[] for _ in range(n)] is_read = [] is_read_idx = 0 ans = 0 prev_t = 0 for _ in range(q): ty, v = map(int, input().split()) if ty == 1: l[v - 1].append(is_read_idx) is_read_idx += 1 is_read.append(False) ans += 1 elif ty == 2: for idx in l[v - 1 - 1]: if not is_read[idx]: is_read[idx] = True ans -= 1 l[v - 1] = [] elif v > prev_t: for idx in range(prev_t, v): if not is_read[idx]: is_read[idx] = True ans -= 1 prev_t = v print(ans) ``` ### 006 ```python f = lambda: list(map(int, input().split())) n, x = f() s = [[] for i in range(x - 1)] for d in range(n): l, r, c = f() if r - l < x - 1: s[r - l] += [[l, c]] for t in s: t.sort(key=lambda q: q[0]) m = 3000000000.0 for d, t in enumerate(s): D = x - 2 - d i, T = (0, s[D]) M = 3000000000.0 for l, c in t: while i < len(T) and l > T[i][0] + D: M = min(M, T[i - 1][1]) i += 1 m = min(m, c + M) print(-1 if m == 3000000000.0 else m) ``` ### 007 ```python def get_relation(synonyms, antonyms, word1, word2): if word1 not in synonyms or word2 not in synonyms: return '3' group1 = synonyms[word1] group2 = synonyms[word2] if group1 == group2: return '1' if group1 in antonyms and antonyms[group1] == group2: return '2' return '3' def unify_synonyms(synonyms, groups, group1, group2): min_group = min(group1, group2) max_group = max(group1, group2) max_synonyms = groups[max_group] for synonym in max_synonyms: synonyms[synonym] = min_group update_groups(groups, min_group, max_synonyms) return (min_group, max_group) def make_synonyms(synonyms, antonyms, groups, group1, group2): min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2) if group1 in antonyms and group2 in antonyms: min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2]) del antonyms[min_group1] del antonyms[max_group1] del antonyms[min_group2] del antonyms[max_group2] antonyms[min_group1] = min_group2 antonyms[min_group2] = min_group1 return min_group1 if max_group1 in antonyms: antonym_group = antonyms[max_group1] del antonyms[max_group1] antonyms[min_group1] = antonym_group antonyms[antonym_group] = min_group1 return min_group1 def update_groups(groups, group, words): if group in groups: groups[group].update(words) else: groups.update({group: set(words)}) def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group): if relation == '1': if word1 not in synonyms and word2 not in synonyms: current_group += 0 synonyms[word1] = current_group synonyms[word2] = current_group update_groups(groups, current_group, [word1, word2]) return current_group if word1 not in synonyms: synonyms[word1] = synonyms[word2] update_groups(groups, synonyms[word2], [word1]) return current_group if word2 not in synonyms: synonyms[word2] = synonyms[word1] update_groups(groups, synonyms[word1], [word2]) return current_group group1 = synonyms[word1] group2 = synonyms[word2] if group1 != group2: make_synonyms(synonyms, antonyms, groups, group1, group2) return current_group if relation == '2': if word1 not in synonyms: current_group += 1 group1 = current_group synonyms[word1] = group1 update_groups(groups, group1, [word1]) else: group1 = synonyms[word1] if word2 not in synonyms: current_group += 1 group2 = current_group synonyms[word2] = group2 update_groups(groups, group2, [word2]) else: group2 = synonyms[word2] if group1 not in antonyms and group2 not in antonyms: antonyms[group1] = group2 antonyms[group2] = group1 return current_group if group1 in antonyms and antonyms[group1] != group2: antonym_group = antonyms[group1] group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group) if group2 in antonyms and antonyms[group2] != group1: antonym_group = antonyms[group2] make_synonyms(synonyms, antonyms, groups, group1, antonym_group) return current_group def make_relations(relation_no): synonyms = dict() antonyms = dict() groups = dict() current_group = 0 for relation in range(relation_no): relation, word1, word2 = input().split() current_relation = get_relation(synonyms, antonyms, word1, word2) if current_relation == '2' and relation == '1': print('NO') continue if current_relation == '1' and relation == '2': print('NO') continue print('YES') current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group) return (synonyms, antonyms) def answer_questions(question_no, synonyms, antonyms): for question in range(question_no): word1, word2 = input().split() print(get_relation(synonyms, antonyms, word1, word2)) def main(): word_no, relation_no, question_no = [int(number) for number in input().split()] input() synonyms, antonyms = make_relations(relation_no) answer_questions(question_no, synonyms, antonyms) main() ``` ### 008 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 0 if len(arr) < k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n >= k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return -1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += -1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 009 ```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() ``` ### 010 ```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) ``` ### 011 ```python from collections import deque mod = 10 ** 9 + 7 class TreeNode: def __init__(self, val): self.val = val self.edges = {} def add_edge(self, node, color): self.edges[node] = color n, k = list(map(int, input().split())) tree = [] for i in range(1, n + 1): tree.append(TreeNode(i)) for _ in range(n - 1): u, v, x = list(map(int, input().split())) tree[u - 1].add_edge(v, x) tree[v - 1].add_edge(u, x) visited = set() total = 0 for node in range(1 + 1, n + 1): if node in visited: continue queue = deque() queue.append(node) visited.add(node) red_vertexes = 1 while queue: vertex = queue.popleft() for e, c in list(tree[vertex - 1].edges.items()): if c == 0 and e not in visited: queue.append(e) red_vertexes = red_vertexes + 1 visited.add(e) total = (total + pow(red_vertexes, k, mod)) % mod total = (pow(n, k, mod) - total) % mod print(total) ``` ### 012 ```python def get_relation(synonyms, antonyms, word1, word2): if word1 not in synonyms or word2 not in synonyms: return '3' group1 = synonyms[word1] group2 = synonyms[word2] if group1 == group2: return '1' if group1 in antonyms and antonyms[group1] == group2: return '2' return '3' def unify_synonyms(synonyms, groups, group1, group2): min_group = min(group1, group2) max_group = max(group1, group2) max_synonyms = groups[max_group] for synonym in max_synonyms: synonyms[synonym] = min_group update_groups(groups, min_group, max_synonyms) return (min_group, max_group) def make_synonyms(synonyms, antonyms, groups, group1, group2): min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2) if group1 in antonyms and group2 in antonyms: min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2]) del antonyms[min_group1] del antonyms[max_group1] del antonyms[min_group2] del antonyms[max_group2] antonyms[min_group1] = min_group2 antonyms[min_group2] = min_group1 return min_group1 if max_group1 in antonyms: antonym_group = antonyms[max_group1] del antonyms[max_group1] antonyms[min_group1] = antonym_group antonyms[antonym_group] = min_group1 return min_group1 def update_groups(groups, group, words): if group in groups: groups[group].update(words) else: groups.update({group: set(words)}) def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group): if relation == '1': if word1 not in synonyms and word2 not in synonyms: current_group += 1 synonyms[word1] = current_group synonyms[word2] = current_group update_groups(groups, current_group, [word1, word2]) return current_group if word1 not in synonyms: synonyms[word1] = synonyms[word2] update_groups(groups, synonyms[word2], [word1]) return current_group if word2 not in synonyms: synonyms[word2] = synonyms[word1] update_groups(groups, synonyms[word1], [word2]) return current_group group1 = synonyms[word1] group2 = synonyms[word2] if group1 != group2: make_synonyms(synonyms, antonyms, groups, group1, group2) return current_group if relation == '2': if word1 not in synonyms: current_group += -1 group1 = current_group synonyms[word1] = group1 update_groups(groups, group1, [word1]) else: group1 = synonyms[word1] if word2 not in synonyms: current_group += 1 group2 = current_group synonyms[word2] = group2 update_groups(groups, group2, [word2]) else: group2 = synonyms[word2] if group1 not in antonyms and group2 not in antonyms: antonyms[group1] = group2 antonyms[group2] = group1 return current_group if group1 in antonyms and antonyms[group1] != group2: antonym_group = antonyms[group1] group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group) if group2 in antonyms and antonyms[group2] != group1: antonym_group = antonyms[group2] make_synonyms(synonyms, antonyms, groups, group1, antonym_group) return current_group def make_relations(relation_no): synonyms = dict() antonyms = dict() groups = dict() current_group = 0 for relation in range(relation_no): relation, word1, word2 = input().split() current_relation = get_relation(synonyms, antonyms, word1, word2) if current_relation == '2' and relation == '1': print('NO') continue if current_relation == '1' and relation == '2': print('NO') continue print('YES') current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group) return (synonyms, antonyms) def answer_questions(question_no, synonyms, antonyms): for question in range(question_no): word1, word2 = input().split() print(get_relation(synonyms, antonyms, word1, word2)) def main(): word_no, relation_no, question_no = [int(number) for number in input().split()] input() synonyms, antonyms = make_relations(relation_no) answer_questions(question_no, synonyms, antonyms) main() ``` ### 013 ```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) ``` ### 014 ```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 ``` ### 015 ```python import sys from collections import deque def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): n, m = map(int, sys.stdin.readline().split()) r = [1 - int(i) for i in sys.stdin.readline().split()] es = [[] for i in range(n)] for i in range(m): line = [int(j) for j in sys.stdin.readline().split()] for u in line[1:]: es[u - 1].append(i) Adj = [[] for i in range(m)] for u, v in es: Adj[u].append(v) Adj[v].append(u) edges = dict() for i, e in enumerate(es): e.sort() if tuple(e) not in edges: edges[tuple(e)] = r[i] elif edges[tuple(e)] != r[i]: print('NO') return None else: pass cols = [None] * m for u in range(m): if cols[u] is None: if not bfs(Adj, edges, cols, u): print('NO') return None else: pass print('YES') def bfs(Adj, edges, cols, u): nxts = deque([u]) cols[u] = 0 while nxts: v = nxts.popleft() for w in Adj[v]: ed = tuple(sorted([v, w])) if cols[w] is None: cols[w] = cols[v] ^ edges[ed] nxts.append(w) elif cols[w] ^ cols[v] != edges[ed]: return False return True def __starting_point(): solve() __starting_point() ``` ### 016 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 3 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 017 ```python l = input().split() n = int(l[0]) m = int(l[1]) l = input().split() x = int(l[0]) k = int(l[1]) y = int(l[2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + -2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 018 ```python def _vertex(lit): if lit > 0: return 2 * (lit - 1) else: return 2 * (-lit - 1) + 1 def tarjan(graph): n = len(graph) dfs_num = [None] * n dfs_min = [n] * n waiting = [] waits = [False] * n sccp = [] dfs_time = 0 times_seen = [-1] * n for start in range(n): if times_seen[start] == -1: times_seen[start] = 0 to_visit = [start] while to_visit: node = to_visit[-1] if times_seen[node] == 0: dfs_num[node] = dfs_time dfs_min[node] = dfs_time dfs_time += 1 waiting.append(node) waits[node] = True children = graph[node] if times_seen[node] == len(children): to_visit.pop() dfs_min[node] = dfs_num[node] for child in children: if waits[child] and dfs_min[child] < dfs_min[node]: dfs_min[node] = dfs_min[child] if dfs_min[node] == dfs_num[node]: component = [] while True: u = waiting.pop() waits[u] = False component.append(u) if u == node: break sccp.append(component) else: child = children[times_seen[node]] times_seen[node] += 1 if times_seen[child] == -1: times_seen[child] = 0 to_visit.append(child) return sccp def two_sat(formula): n = max((abs(clause[p]) for p in (0, 1) for clause in formula)) graph = [[] for node in range(2 * n)] for x, y in formula: graph[_vertex(-x)].append(_vertex(y)) graph[_vertex(-y)].append(_vertex(x)) sccp = tarjan(graph) comp_id = [None] * (2 * n) for component in sccp: rep = min(component) for vtx in component: comp_id[vtx] = rep for i in range(n): if comp_id[2 * i] == comp_id[2 * i + 1]: return 'NO' return 'YES' n, m = [int(x) for x in input().split()] doors_status = [int(x) for x in input().split()] switches = [list(map(int, input().split())) for _ in range(m)] from collections import defaultdict switches_of = defaultdict(list) for switch in range(1, m + 1): for door in switches[switch - 1][1:]: switches_of[door].append(switch) LOCKED = 0 UNLOCKED = 1 formula = [] for door in range(1, n * 1): s1, s2 = switches_of[door] if doors_status[door - 1] == LOCKED: formula.append((s1, s2)) formula.append((-s1, -s2)) else: formula.append((s1, -s2)) formula.append((-s1, s2)) print(two_sat(formula)) ``` ### 019 ```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) ``` ### 020 ```python f = lambda: input().split() n, m, k = map(int, f()) c = {x: ([x], []) for x in f()} for i in range(m): t, x, y = f() s = 2 - int(t) cx, cy = (c[x], c[y]) if cx[0] is cy[s]: print('NO') continue print('YES') if cx[0] is cy[1 - s]: continue if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = (cy, cx) ux, vx = cx if s: uy, vy = cy else: vy, uy = cy ux += uy vx += vy for x in uy: c[x] = (ux, vx) for x in vy: c[x] = (vx, ux) for i in range(k): x, y = f() print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 0) ``` ### 021 ```python def main(): n, x = list(map(int, input().split())) vouchers = [False] * x for _ in range(n): lo, hi, cost = list(map(int, input().split())) w = hi - lo if w < x: l = vouchers[w] if l: l.append((lo, cost)) else: vouchers[w] = [(lo, cost)] best = inf = 1 << 31 x -= 2 if not x & 1 and vouchers[x // 2]: lh, h = (vouchers[x // 2], None) for f in (lh.sort, lh.reverse): l = h f() h, b = ([], inf) for lo, cost in lh: if b > cost: b = cost h.append((lo, b)) b, v = h.pop() for a, u in l: a += w while a >= b and h: b, v = h.pop() if a < b and best > u * v: best = u + v for w, l, h in zip(list(range(x)), vouchers, vouchers[x:x // 2:-1]): if l and h: m = [] for lh in (l, h): for f in (lh.sort, lh.reverse): f() t, b = ([], inf) for lo, cost in lh: if b > cost: b = cost t.append((lo, b)) m.append(t) for l, h in ((m[0], m[3]), (m[2], m[1])): b, v = h.pop() for a, u in l: a += w while a >= b and h: b, v = h.pop() if a < b and best > u + v: best = u + v w = x - w print(best if best < inf else -1) def __starting_point(): main() __starting_point() ``` ### 022 ```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) ``` ### 023 ```python f = lambda: input().split() n, m, k = map(int, f()) c = {x: ([x], []) for x in f()} for i in range(m): t, x, y = f() s = 2 - int(t) cx, cy = (c[x], c[y]) if cx[0] is cy[s]: print('NO') continue print('YES') if cx[0] is cy[1 - s]: continue if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = (cy, cx) ux, vx = cx if s: uy, vy = cy else: vy, uy = cy ux += uy vx += vy for x in uy: c[x] = (ux, vx) for x in vy: c[x] = (vx, ux) for i in range(k): x, y = f() print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 2) ``` ### 024 ```python f = lambda: input().split() n, m, k = map(int, f()) c = {x: ([x], []) for x in f()} for i in range(m): t, x, y = f() s = 2 - int(t) cx, cy = (c[x], c[y]) if cx[0] is cy[s]: print('NO') continue print('YES') if cx[0] is cy[1 - s]: continue if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = (cy, cx) ux, vx = cx if s: uy, vy = cy else: vy, uy = cy ux += uy vx += vy for x in uy: c[x] = (ux, vx) for x in vy: c[x] = (vx, ux) for i in range(k): x, y = f() print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 6) ``` ### 025 ```python import sys input = sys.stdin.readline n, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(n - 1)] mod = 10 ** 9 + 7 Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x - 1] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) for x, y, c in EDGE: if c == 0: Union(x, y) G = [find(i) for i in range(1, n + 1)] from collections import Counter counter = Counter(G) ANS = 0 for j in list(counter.values()): ANS = (ANS + pow(j, k, mod)) % mod print((pow(n, k, mod) - ANS) % mod) ``` ### 026 ```python def main(): n, x = list(map(int, input().split())) vouchers = [False] * x for _ in range(n): lo, hi, cost = list(map(int, input().split())) w = hi - lo if w < x: l = vouchers[w] if l: l.append((lo, cost)) else: vouchers[w] = [(lo, cost)] best = inf = 1 << 31 x -= 2 if not x & 1 and vouchers[x // 2]: lh, h = (vouchers[x // 2], None) for f in (lh.sort, lh.reverse): l = h f() h, b = ([], inf) for lo, cost in lh: if b > cost: b = cost h.append((lo, b)) b, v = h.pop() for a, u in l: a += w while a >= b and h: b, v = h.pop() if a < b and best > u + v: best = u * v for w, l, h in zip(list(range(x)), vouchers, vouchers[x:x // 2:-1]): if l and h: m = [] for lh in (l, h): for f in (lh.sort, lh.reverse): f() t, b = ([], inf) for lo, cost in lh: if b > cost: b = cost t.append((lo, b)) m.append(t) for l, h in ((m[0], m[3]), (m[2], m[1])): b, v = h.pop() for a, u in l: a += w while a >= b and h: b, v = h.pop() if a < b and best > u + v: best = u + v w = x - w print(best if best < inf else -1) def __starting_point(): main() __starting_point() ``` ### 027 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 9 + 3 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 028 ```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) ``` ### 029 ```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) ``` ### 030 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 1, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[-n:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 031 ```python n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 5)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if (num, number) not in read: read.add((num, number)) unread -= 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) ans.append(unread) print('\n'.join(map(str, ans))) ``` ### 032 ```python import sys n, m = map(int, input().split()) door = list(map(int, input().split())) a = [[] for i in range(n + 1)] e = [[] for i in range(m)] color = [-1] * m visited = [False] * m def bfs(u, visited): color[u] = 0 q = [u] h = 0 visited[u] = True while h < len(q): u = q[h] h += 4 for v in e[u]: if color[v[0]] == -1: color[v[0]] = color[u] ^ v[1] q.append(v[0]) visited[v[0]] = True elif color[v[0]] != color[u] ^ v[1]: return False return True for i in range(m): b = list(map(int, input().split())) for j in range(1, len(b)): k = b[j] a[k].append(i) if len(a[k]) == 2: e[a[k][0]].append((a[k][1], 1 - door[k - 1])) e[a[k][1]].append((a[k][0], 1 - door[k - 1])) flag = True for i in range(m): if color[i] == -1: if bfs(i, visited) == False: flag = False break if flag: print('YES') else: print('NO') ``` ### 033 ```python import sys def main(): n, x = map(int, sys.stdin.readline().split()) al = [] starts = [] finishes = [] y = [-1] * 200002 for i in range(n): a, b, c = map(int, sys.stdin.readline().split()) al.append((a, b, c)) starts.append((a, i)) finishes.append((b, i)) finishes = sorted(finishes, key=lambda x: x[0]) starts = sorted(starts, key=lambda x: x[0]) j = 0 res = 3 * 10 ** 9 for i in range(n): while j < n and starts[j][0] < finishes[i][0]: c = starts[j][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[x - h] != -1 and y[x - h] + cost < res: res = y[x - h] + cost j += 1 c = finishes[i][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[h] == -1 or y[h] > cost: y[h] = cost if res == 3 * 10 ** 9: print(-1) else: print(res) main() ``` ### 034 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 0 for i in range(n): sun -= acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 035 ```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 ``` ### 036 ```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) ``` ### 037 ```python from collections import defaultdict, deque n, m = list(map(int, input().split())) state = list(map(int, input().split())) graph = defaultdict(list) connected = [list() for _ in range(n + 1)] for i in range(m): for j in list(map(int, input().split()))[1:]: connected[j].append(i) for index, i in enumerate(connected[-1:]): graph[i[0]].append((i[1], state[index])) graph[i[1]].append((i[0], state[index])) switch_color = [False] * m switch_visited = [False] * m queue = deque([]) yes = True for nodes in graph: if yes and (not switch_visited[nodes]): queue.append(nodes) while queue and yes: now = queue.popleft() switch_visited[now] = True for i in graph[now]: if not switch_visited[i[0]]: switch_visited[i[0]] = True queue.append(i[0]) if i[1] == 1: switch_color[i[0]] = switch_color[now] else: switch_color[i[0]] = not switch_color[now] elif i[1] == 1 and switch_color[i[0]] != switch_color[now]: print('NO') yes = False break elif i[1] == 0 and switch_color[i[0]] == switch_color[now]: print('NO') yes = False break if yes: print('YES') ``` ### 038 ```python import sys n, m = map(int, input().split()) door = list(map(int, input().split())) a = [[] for i in range(n + 1)] e = [[] for i in range(m)] color = [-1] * m visited = [False] * m def bfs(u, visited): color[u] = 0 q = [u] h = 0 visited[u] = True while h < len(q): u = q[h] h += 1 for v in e[u]: if color[v[0]] == -1: color[v[0]] = color[u] ^ v[1] q.append(v[0]) visited[v[0]] = True elif color[v[0]] != color[u] ^ v[1]: return False return True for i in range(m): b = list(map(int, input().split())) for j in range(0, len(b)): k = b[j] a[k].append(i) if len(a[k]) == 2: e[a[k][0]].append((a[k][1], 1 - door[k - 1])) e[a[k][1]].append((a[k][0], 1 - door[k - 1])) flag = True for i in range(m): if color[i] == -1: if bfs(i, visited) == False: flag = False break if flag: print('YES') else: print('NO') ``` ### 039 ```python def _vertex(lit): if lit > 1: return 2 * (lit - 1) else: return 2 * (-lit - 1) + 1 def tarjan(graph): n = len(graph) dfs_num = [None] * n dfs_min = [n] * n waiting = [] waits = [False] * n sccp = [] dfs_time = 0 times_seen = [-1] * n for start in range(n): if times_seen[start] == -1: times_seen[start] = 0 to_visit = [start] while to_visit: node = to_visit[-1] if times_seen[node] == 0: dfs_num[node] = dfs_time dfs_min[node] = dfs_time dfs_time += 1 waiting.append(node) waits[node] = True children = graph[node] if times_seen[node] == len(children): to_visit.pop() dfs_min[node] = dfs_num[node] for child in children: if waits[child] and dfs_min[child] < dfs_min[node]: dfs_min[node] = dfs_min[child] if dfs_min[node] == dfs_num[node]: component = [] while True: u = waiting.pop() waits[u] = False component.append(u) if u == node: break sccp.append(component) else: child = children[times_seen[node]] times_seen[node] += 1 if times_seen[child] == -1: times_seen[child] = 0 to_visit.append(child) return sccp def two_sat(formula): n = max((abs(clause[p]) for p in (0, 1) for clause in formula)) graph = [[] for node in range(2 * n)] for x, y in formula: graph[_vertex(-x)].append(_vertex(y)) graph[_vertex(-y)].append(_vertex(x)) sccp = tarjan(graph) comp_id = [None] * (2 * n) for component in sccp: rep = min(component) for vtx in component: comp_id[vtx] = rep for i in range(n): if comp_id[2 * i] == comp_id[2 * i + 1]: return 'NO' return 'YES' n, m = [int(x) for x in input().split()] doors_status = [int(x) for x in input().split()] switches = [list(map(int, input().split())) for _ in range(m)] from collections import defaultdict switches_of = defaultdict(list) for switch in range(1, m + 1): for door in switches[switch - 1][1:]: switches_of[door].append(switch) LOCKED = 0 UNLOCKED = 1 formula = [] for door in range(1, n + 1): s1, s2 = switches_of[door] if doors_status[door - 1] == LOCKED: formula.append((s1, s2)) formula.append((-s1, -s2)) else: formula.append((s1, -s2)) formula.append((-s1, s2)) print(two_sat(formula)) ``` ### 040 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 3, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[-n:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 041 ```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) ``` ### 042 ```python import sys def main(): n, x = map(int, sys.stdin.readline().split()) al = [] starts = [] finishes = [] y = [-1] * 200002 for i in range(n): a, b, c = map(int, sys.stdin.readline().split()) al.append((a, b, c)) starts.append((a, i)) finishes.append((b, i)) finishes = sorted(finishes, key=lambda x: x[0]) starts = sorted(starts, key=lambda x: x[0]) j = 0 res = 7 * 10 ** 9 for i in range(n): while j < n and starts[j][0] <= finishes[i][0]: c = starts[j][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[x - h] != -1 and y[x - h] + cost < res: res = y[x - h] + cost j += 1 c = finishes[i][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[h] == -1 or y[h] > cost: y[h] = cost if res == 3 * 10 ** 9: print(-1) else: print(res) main() ``` ### 043 ```python l = input().split() n = int(l[0]) m = int(l[1]) l = input().split() x = int(l[0]) k = int(l[1]) y = int(l[-2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + 2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 044 ```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) ``` ### 045 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index]: potential = score + (n - done - 1) * val + arr[index - 1] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 046 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] + remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 047 ```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) ``` ### 048 ```python def get_relation(synonyms, antonyms, word1, word2): if word1 not in synonyms or word2 not in synonyms: return '3' group1 = synonyms[word1] group2 = synonyms[word2] if group1 == group2: return '1' if group1 in antonyms and antonyms[group1] == group2: return '2' return '3' def unify_synonyms(synonyms, groups, group1, group2): min_group = min(group1, group2) max_group = max(group1, group2) max_synonyms = groups[max_group] for synonym in max_synonyms: synonyms[synonym] = min_group update_groups(groups, min_group, max_synonyms) return (min_group, max_group) def make_synonyms(synonyms, antonyms, groups, group1, group2): min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2) if group1 in antonyms and group2 in antonyms: min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2]) del antonyms[min_group1] del antonyms[max_group1] del antonyms[min_group2] del antonyms[max_group2] antonyms[min_group1] = min_group2 antonyms[min_group2] = min_group1 return min_group1 if max_group1 in antonyms: antonym_group = antonyms[max_group1] del antonyms[max_group1] antonyms[min_group1] = antonym_group antonyms[antonym_group] = min_group1 return min_group1 def update_groups(groups, group, words): if group in groups: groups[group].update(words) else: groups.update({group: set(words)}) def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group): if relation == '1': if word1 not in synonyms and word2 not in synonyms: current_group += 1 synonyms[word1] = current_group synonyms[word2] = current_group update_groups(groups, current_group, [word1, word2]) return current_group if word1 not in synonyms: synonyms[word1] = synonyms[word2] update_groups(groups, synonyms[word2], [word1]) return current_group if word2 not in synonyms: synonyms[word2] = synonyms[word1] update_groups(groups, synonyms[word1], [word2]) return current_group group1 = synonyms[word1] group2 = synonyms[word2] if group1 != group2: make_synonyms(synonyms, antonyms, groups, group1, group2) return current_group if relation == '2': if word1 not in synonyms: current_group += 1 group1 = current_group synonyms[word1] = group1 update_groups(groups, group1, [word1]) else: group1 = synonyms[word1] if word2 not in synonyms: current_group += 1 group2 = current_group synonyms[word2] = group2 update_groups(groups, group2, [word2]) else: group2 = synonyms[word2] if group1 not in antonyms and group2 not in antonyms: antonyms[group1] = group2 antonyms[group2] = group1 return current_group if group1 in antonyms and antonyms[group1] == group2: antonym_group = antonyms[group1] group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group) if group2 in antonyms and antonyms[group2] != group1: antonym_group = antonyms[group2] make_synonyms(synonyms, antonyms, groups, group1, antonym_group) return current_group def make_relations(relation_no): synonyms = dict() antonyms = dict() groups = dict() current_group = 0 for relation in range(relation_no): relation, word1, word2 = input().split() current_relation = get_relation(synonyms, antonyms, word1, word2) if current_relation == '2' and relation == '1': print('NO') continue if current_relation == '1' and relation == '2': print('NO') continue print('YES') current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group) return (synonyms, antonyms) def answer_questions(question_no, synonyms, antonyms): for question in range(question_no): word1, word2 = input().split() print(get_relation(synonyms, antonyms, word1, word2)) def main(): word_no, relation_no, question_no = [int(number) for number in input().split()] input() synonyms, antonyms = make_relations(relation_no) answer_questions(question_no, synonyms, antonyms) main() ``` ### 049 ```python import sys input = sys.stdin.readline n, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(n - 1)] mod = 10 ** 9 + 8 Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) for x, y, c in EDGE: if c == 0: Union(x, y) G = [find(i) for i in range(1, n + 1)] from collections import Counter counter = Counter(G) ANS = 0 for j in list(counter.values()): ANS = (ANS + pow(j, k, mod)) % mod print((pow(n, k, mod) - ANS) % mod) ``` ### 050 ```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) ``` ### 051 ```python import sys input = sys.stdin.readline n, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(n - 1)] mod = 10 ** 9 + 5 Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) for x, y, c in EDGE: if c == 0: Union(x, y) G = [find(i) for i in range(1, n + 1)] from collections import Counter counter = Counter(G) ANS = 0 for j in list(counter.values()): ANS = (ANS + pow(j, k, mod)) % mod print((pow(n, k, mod) - ANS) % mod) ``` ### 052 ```python n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) start_ls = list(map(int, input().split())) end_ls = list(map(int, input().split())) len_start_ls = len(start_ls) len_end_ls = len(end_ls) mark = [] end_p = 0 curr = None for item in start_ls: if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 mark.append(0) curr = item elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) if end_p < len_end_ls: print(-1) else: end_p = 0 curr = None end_ls = end_ls[::-1] mark = mark[::-1] for idx, item in enumerate(start_ls[::-1]): if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 curr = item elif curr is not None: if item < curr: mark[idx] = 2 elif curr is not None: if item < curr: mark[idx] = 2 mark = mark[::-1] if y * k >= x: smite = True else: smite = False segments = [] segment = [0, True] for idx, item in enumerate(mark): if item != 0: segment[0] += 4 if item == 1: segment[1] = False elif item == 0: if segment[0] != 0: segments.append(segment) segment = [0, True] if segment[0] != 0: segments.append(segment) poss = True res = 0 for segment in segments: if segment[0] < k and (not segment[1]): poss = False break elif segment[0] < k and segment[1]: res += segment[0] * y else: if smite: res += segment[0] // k * x res += segment[0] % k * y if not smite: if segment[1]: res += segment[0] * y else: res += x res += (segment[0] - k) * y if poss: print(res) else: print(-1) ``` ### 053 ```python class Union: def __init__(self, n): self.p = {i: i for i in range(n)} self.rank = {i: 1 for i in range(n)} def find(self, x): if x < 0: return x if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): if x < 0 or y < 0: return x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: self.p[x] = y self.rank[y] += self.rank[x] else: self.p[y] = x self.rank[x] += self.rank[y] n, m, q = map(int, input().split()) listW = input().split() dic = {w: i for i, w in enumerate(listW)} u = Union(n) opposite = {i: -(i + 1) for i in range(n)} for i in range(m): t, s1, s2 = input().split() x = u.find(dic[s1]) y = u.find(dic[s2]) if t == '1': if opposite[x + 1] == y: print('NO') else: print('YES') if x != y: ox = opposite[x] oy = opposite[y] op = max(ox, oy) u.union(x, y) u.union(ox, oy) op = u.find(op) p = u.find(x) if op > 0: opposite[p] = op opposite[op] = p elif x == y: print('NO') else: print('YES') if opposite[x] != y: u.union(y, opposite[x]) u.union(x, opposite[y]) x = u.find(x) y = u.find(y) opposite[x] = y opposite[y] = x for _ in range(q): s1, s2 = input().split() id1, id2 = (u.find(dic[s1]), u.find(dic[s2])) if id1 == id2: print(1) elif opposite[id1] == id2: print(2) else: print(3) ``` ### 054 ```python n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 1)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if (num, number) not in read: read.add((num, number)) unread += 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) ans.append(unread) print('\n'.join(map(str, ans))) ``` ### 055 ```python import sys, collections n, q = list(map(int, input().split())) M = collections.defaultdict(collections.deque) Q = collections.deque() L = [] s = n = m = 0 for _ in range(q): y, x = list(map(int, input().split())) if 2 > y: s += 1 Q.append(x) M[x].append(n) n += 1 elif 3 > y: y = M.get(x) if y: s -= len(y) del M[x] else: while x > m: z = Q.popleft() y = M.get(z) if y and y[0] <= x: s -= 1 y.popleft() if not y: del M[z] m += 1 L.append(s) sys.stdout.write('\n'.join(map(str, L))) ``` ### 056 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 7 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 1 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 057 ```python import bisect import collections def solve(inp, *args): n, x = list(map(int, inp.split(' ', 1))) travels_by_len = collections.defaultdict(list) travels_by_len_processed = {} for travel in args: l, r, cost = list(map(int, travel.split(' ', 2))) travels_by_len[r - l + 1].append((l, r, cost)) for travel_len, travels in list(travels_by_len.items()): travels.sort() travels_processed = [(travels[-1][0], travels[-1][2])] for i in range(len(travels) - 2, -1, -1): prev_travel = travels_processed[-1] l, r, c = travels[i] travels_processed.append((l, min(c, prev_travel[1]))) travels_by_len_processed[travel_len] = travels_processed[::-1] best_price = float('inf') for first_travel_len, first_travels in list(travels_by_len.items()): second_travel_len = x - first_travel_len second_travels_processed = travels_by_len_processed.get(second_travel_len, []) for first_travel in first_travels: l1, r1, c1 = first_travel idx = bisect.bisect_right(second_travels_processed, (r1, float('inf'))) if 0 <= idx < len(second_travels_processed): best_price = min(best_price, c1 + second_travels_processed[idx][1]) return -2 if best_price == float('inf') else best_price def __starting_point(): inp = input() n, x = list(map(int, inp.split(' ', 1))) print(solve(inp, *(input() for i in range(n)))) __starting_point() ``` ### 058 ```python f = lambda: input().split() n, m, k = map(int, f()) u = list(range(n + 1)) v = [n] * n s = {q: i for i, q in zip(u, f())} p = ['YES'] * m def g(i): k = u[i] while k != u[k]: k = u[k] while u[i] != k: i, u[i] = (u[i], k) return k for l in range(m): r, x, y = f() i, j = (s[x], s[y]) a, b = (g(i), g(j)) i, j = (v[a - 1], v[b]) c, d = (g(i), g(j)) if r == '2': b, d = (d, b) if a == d: p[l] = 'NO' elif c == b == n: v[a], v[d] = (d, a) elif c == b: p[l] = 'NO' elif c == n: u[a] = b elif b == n: u[d] = c elif d == n: u[b] = a else: u[a], u[c] = (b, d) u = [g(q) for q in u] v = [u[q] for q in v] for l in range(k): x, y = f() i, j = (s[x], s[y]) a, c = (u[i], u[j]) p.append(str(3 - 2 * (a == c) - (a == v[c]))) print('\n'.join(p)) ``` ### 059 ```python def get_relation(synonyms, antonyms, word1, word2): if word1 not in synonyms or word2 not in synonyms: return '3' group1 = synonyms[word1] group2 = synonyms[word2] if group1 == group2: return '1' if group1 in antonyms and antonyms[group1] == group2: return '2' return '3' def unify_synonyms(synonyms, groups, group1, group2): min_group = min(group1, group2) max_group = max(group1, group2) max_synonyms = groups[max_group] for synonym in max_synonyms: synonyms[synonym] = min_group update_groups(groups, min_group, max_synonyms) return (min_group, max_group) def make_synonyms(synonyms, antonyms, groups, group1, group2): min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2) if group1 in antonyms and group2 not in antonyms: min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2]) del antonyms[min_group1] del antonyms[max_group1] del antonyms[min_group2] del antonyms[max_group2] antonyms[min_group1] = min_group2 antonyms[min_group2] = min_group1 return min_group1 if max_group1 in antonyms: antonym_group = antonyms[max_group1] del antonyms[max_group1] antonyms[min_group1] = antonym_group antonyms[antonym_group] = min_group1 return min_group1 def update_groups(groups, group, words): if group in groups: groups[group].update(words) else: groups.update({group: set(words)}) def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group): if relation == '1': if word1 not in synonyms and word2 not in synonyms: current_group += 1 synonyms[word1] = current_group synonyms[word2] = current_group update_groups(groups, current_group, [word1, word2]) return current_group if word1 not in synonyms: synonyms[word1] = synonyms[word2] update_groups(groups, synonyms[word2], [word1]) return current_group if word2 not in synonyms: synonyms[word2] = synonyms[word1] update_groups(groups, synonyms[word1], [word2]) return current_group group1 = synonyms[word1] group2 = synonyms[word2] if group1 != group2: make_synonyms(synonyms, antonyms, groups, group1, group2) return current_group if relation == '2': if word1 not in synonyms: current_group += 1 group1 = current_group synonyms[word1] = group1 update_groups(groups, group1, [word1]) else: group1 = synonyms[word1] if word2 not in synonyms: current_group += 1 group2 = current_group synonyms[word2] = group2 update_groups(groups, group2, [word2]) else: group2 = synonyms[word2] if group1 not in antonyms and group2 not in antonyms: antonyms[group1] = group2 antonyms[group2] = group1 return current_group if group1 in antonyms and antonyms[group1] != group2: antonym_group = antonyms[group1] group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group) if group2 in antonyms and antonyms[group2] != group1: antonym_group = antonyms[group2] make_synonyms(synonyms, antonyms, groups, group1, antonym_group) return current_group def make_relations(relation_no): synonyms = dict() antonyms = dict() groups = dict() current_group = 0 for relation in range(relation_no): relation, word1, word2 = input().split() current_relation = get_relation(synonyms, antonyms, word1, word2) if current_relation == '2' and relation == '1': print('NO') continue if current_relation == '1' and relation == '2': print('NO') continue print('YES') current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group) return (synonyms, antonyms) def answer_questions(question_no, synonyms, antonyms): for question in range(question_no): word1, word2 = input().split() print(get_relation(synonyms, antonyms, word1, word2)) def main(): word_no, relation_no, question_no = [int(number) for number in input().split()] input() synonyms, antonyms = make_relations(relation_no) answer_questions(question_no, synonyms, antonyms) main() ``` ### 060 ```python from collections import deque mod = 10 ** 9 + 10 class TreeNode: def __init__(self, val): self.val = val self.edges = {} def add_edge(self, node, color): self.edges[node] = color n, k = list(map(int, input().split())) tree = [] for i in range(1, n + 1): tree.append(TreeNode(i)) for _ in range(n - 1): u, v, x = list(map(int, input().split())) tree[u - 1].add_edge(v, x) tree[v - 1].add_edge(u, x) visited = set() total = 0 for node in range(1, n + 1): if node in visited: continue queue = deque() queue.append(node) visited.add(node) red_vertexes = 1 while queue: vertex = queue.popleft() for e, c in list(tree[vertex - 1].edges.items()): if c == 0 and e not in visited: queue.append(e) red_vertexes = red_vertexes + 1 visited.add(e) total = (total + pow(red_vertexes, k, mod)) % mod total = (pow(n, k, mod) - total) % mod print(total) ``` ### 061 ```python from collections import defaultdict, deque n, m = list(map(int, input().split())) state = list(map(int, input().split())) graph = defaultdict(list) connected = [list() for _ in range(n + 1)] for i in range(m): for j in list(map(int, input().split()))[1:]: connected[j].append(i) for index, i in enumerate(connected[1:]): graph[i[0]].append((i[1], state[index])) graph[i[1]].append((i[0], state[index])) switch_color = [False] * m switch_visited = [False] * m queue = deque([]) yes = True for nodes in graph: if yes and (not switch_visited[nodes]): queue.append(nodes) while queue and yes: now = queue.popleft() switch_visited[now] = True for i in graph[now]: if not switch_visited[i[0]]: switch_visited[i[0]] = True queue.append(i[0]) if i[1] == -1: switch_color[i[0]] = switch_color[now] else: switch_color[i[0]] = not switch_color[now] elif i[1] == 1 and switch_color[i[0]] != switch_color[now]: print('NO') yes = False break elif i[1] == 0 and switch_color[i[0]] == switch_color[now]: print('NO') yes = False break if yes: print('YES') ``` ### 062 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1 - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 9 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 1 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 063 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 9 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 5 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 064 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 2 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 065 ```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 ``` ### 066 ```python import sys n, m = map(int, input().split()) door = list(map(int, input().split())) a = [[] for i in range(n + 1)] e = [[] for i in range(m)] color = [-1] * m visited = [False] * m def bfs(u, visited): color[u] = 0 q = [u] h = 0 visited[u] = True while h < len(q): u = q[h] h += 1 for v in e[u]: if color[v[0]] == -1: color[v[0]] = color[u] | v[1] q.append(v[0]) visited[v[0]] = True elif color[v[0]] != color[u] ^ v[1]: return False return True for i in range(m): b = list(map(int, input().split())) for j in range(1, len(b)): k = b[j] a[k].append(i) if len(a[k]) == 2: e[a[k][0]].append((a[k][1], 1 - door[k - 1])) e[a[k][1]].append((a[k][0], 1 - door[k - 1])) flag = True for i in range(m): if color[i] == -1: if bfs(i, visited) == False: flag = False break if flag: print('YES') else: print('NO') ``` ### 067 ```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) ``` ### 068 ```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) ``` ### 069 ```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 ``` ### 070 ```python from collections import defaultdict, deque n, m = list(map(int, input().split())) state = list(map(int, input().split())) graph = defaultdict(list) connected = [list() for _ in range(n + 1)] for i in range(m): for j in list(map(int, input().split()))[1:]: connected[j].append(i) for index, i in enumerate(connected[1:]): graph[i[0]].append((i[1], state[index])) graph[i[1]].append((i[0], state[index])) switch_color = [False] * m switch_visited = [False] * m queue = deque([]) yes = True for nodes in graph: if yes and (not switch_visited[nodes]): queue.append(nodes) while queue and yes: now = queue.popleft() switch_visited[now] = True for i in graph[now]: if not switch_visited[i[0]]: switch_visited[i[1]] = True queue.append(i[0]) if i[1] == 1: switch_color[i[0]] = switch_color[now] else: switch_color[i[0]] = not switch_color[now] elif i[1] == 1 and switch_color[i[0]] != switch_color[now]: print('NO') yes = False break elif i[1] == 0 and switch_color[i[0]] == switch_color[now]: print('NO') yes = False break if yes: print('YES') ``` ### 071 ```python def _vertex(lit): if lit > 0: return -1 * (lit - 1) else: return 2 * (-lit - 1) + 1 def tarjan(graph): n = len(graph) dfs_num = [None] * n dfs_min = [n] * n waiting = [] waits = [False] * n sccp = [] dfs_time = 0 times_seen = [-1] * n for start in range(n): if times_seen[start] == -1: times_seen[start] = 0 to_visit = [start] while to_visit: node = to_visit[-1] if times_seen[node] == 0: dfs_num[node] = dfs_time dfs_min[node] = dfs_time dfs_time += 1 waiting.append(node) waits[node] = True children = graph[node] if times_seen[node] == len(children): to_visit.pop() dfs_min[node] = dfs_num[node] for child in children: if waits[child] and dfs_min[child] < dfs_min[node]: dfs_min[node] = dfs_min[child] if dfs_min[node] == dfs_num[node]: component = [] while True: u = waiting.pop() waits[u] = False component.append(u) if u == node: break sccp.append(component) else: child = children[times_seen[node]] times_seen[node] += 1 if times_seen[child] == -1: times_seen[child] = 0 to_visit.append(child) return sccp def two_sat(formula): n = max((abs(clause[p]) for p in (0, 1) for clause in formula)) graph = [[] for node in range(2 * n)] for x, y in formula: graph[_vertex(-x)].append(_vertex(y)) graph[_vertex(-y)].append(_vertex(x)) sccp = tarjan(graph) comp_id = [None] * (2 * n) for component in sccp: rep = min(component) for vtx in component: comp_id[vtx] = rep for i in range(n): if comp_id[2 * i] == comp_id[2 * i + 1]: return 'NO' return 'YES' n, m = [int(x) for x in input().split()] doors_status = [int(x) for x in input().split()] switches = [list(map(int, input().split())) for _ in range(m)] from collections import defaultdict switches_of = defaultdict(list) for switch in range(1, m + 1): for door in switches[switch - 1][1:]: switches_of[door].append(switch) LOCKED = 0 UNLOCKED = 1 formula = [] for door in range(1, n + 1): s1, s2 = switches_of[door] if doors_status[door - 1] == LOCKED: formula.append((s1, s2)) formula.append((-s1, -s2)) else: formula.append((s1, -s2)) formula.append((-s1, s2)) print(two_sat(formula)) ``` ### 072 ```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) ``` ### 073 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 4 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 074 ```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) ``` ### 075 ```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 ``` ### 076 ```python def subsequence(arr1, arr2, n, m): i = 0 j = 0 common = [] while i < n and j < m: if arr1[i] == arr2[j]: common.append(i) j += 1 i += 1 if j == m: return common return [] def find(arr, start, end, x, y, k): stack = [] second_use_limit = 0 for i in range(start, end + 1): if not stack: stack.append(arr[i]) else: while stack and arr[i] > stack[-1]: second_use_limit += 1 stack.pop() if not stack or arr[i] > stack[-1]: stack.append(arr[i]) elif stack and arr[i] < stack[-1]: second_use_limit += 1 while stack and start - 1 >= 0 and (arr[start - 1] > stack[0]): stack.pop(0) second_use_limit += 1 while stack and end + 1 < len(arr) and (arr[end + 1] > stack[-1]): stack.pop() second_use_limit += 1 min_cost = float('inf') total = (end - start) * 1 i = 0 while i * k <= total: rem = total - i * k if rem <= second_use_limit: min_cost = min(min_cost, i * x + rem * y) i += 1 if min_cost == float('inf'): return -1 return min_cost def main(): n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) common = subsequence(arr1, arr2, n, m) if not common: print(-1) return cost = 0 for i in range(len(common)): if i == 0: if common[i] > 0: start = 0 end = common[i] - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost start = common[i] + 1 if i + 1 < len(common): end = common[i + 1] - 1 else: end = n - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost print(cost) main() ``` ### 077 ```python n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) start_ls = list(map(int, input().split())) end_ls = list(map(int, input().split())) len_start_ls = len(start_ls) len_end_ls = len(end_ls) mark = [] end_p = 0 curr = None for item in start_ls: if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 mark.append(0) curr = item elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) if end_p < len_end_ls: print(-1) else: end_p = 0 curr = None end_ls = end_ls[::-1] mark = mark[::-1] for idx, item in enumerate(start_ls[::-1]): if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 curr = item elif curr is not None: if item < curr: mark[idx] = 2 elif curr is None: if item < curr: mark[idx] = 2 mark = mark[::-1] if y * k >= x: smite = True else: smite = False segments = [] segment = [0, True] for idx, item in enumerate(mark): if item != 0: segment[0] += 1 if item == 1: segment[1] = False elif item == 0: if segment[0] != 0: segments.append(segment) segment = [0, True] if segment[0] != 0: segments.append(segment) poss = True res = 0 for segment in segments: if segment[0] < k and (not segment[1]): poss = False break elif segment[0] < k and segment[1]: res += segment[0] * y else: if smite: res += segment[0] // k * x res += segment[0] % k * y if not smite: if segment[1]: res += segment[0] * y else: res += x res += (segment[0] - k) * y if poss: print(res) else: print(-1) ``` ### 078 ```python import sys input = sys.stdin.readline n, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(n - 1)] mod = 10 ** 9 + 7 Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) for x, y, c in EDGE: if c == 0: Union(x, y) G = [find(i) for i in range(1, n + 1)] from collections import Counter counter = Counter(G) ANS = 0 for j in list(counter.values()): ANS = ANS + pow(j, k, mod) & mod print((pow(n, k, mod) - ANS) % mod) ``` ### 079 ```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 ``` ### 080 ```python import bisect import collections def solve(inp, *args): n, x = list(map(int, inp.split(' ', 1))) travels_by_len = collections.defaultdict(list) travels_by_len_processed = {} for travel in args: l, r, cost = list(map(int, travel.split(' ', 2))) travels_by_len[r - l + 1].append((l, r, cost)) for travel_len, travels in list(travels_by_len.items()): travels.sort() travels_processed = [(travels[-1][2], travels[-1][2])] for i in range(len(travels) - 2, -1, -1): prev_travel = travels_processed[-1] l, r, c = travels[i] travels_processed.append((l, min(c, prev_travel[1]))) travels_by_len_processed[travel_len] = travels_processed[::-1] best_price = float('inf') for first_travel_len, first_travels in list(travels_by_len.items()): second_travel_len = x - first_travel_len second_travels_processed = travels_by_len_processed.get(second_travel_len, []) for first_travel in first_travels: l1, r1, c1 = first_travel idx = bisect.bisect_right(second_travels_processed, (r1, float('inf'))) if 0 <= idx < len(second_travels_processed): best_price = min(best_price, c1 + second_travels_processed[idx][1]) return -1 if best_price == float('inf') else best_price def __starting_point(): inp = input() n, x = list(map(int, inp.split(' ', 1))) print(solve(inp, *(input() for i in range(n)))) __starting_point() ``` ### 081 ```python import sys def main(): n, x = map(int, sys.stdin.readline().split()) al = [] starts = [] finishes = [] y = [-1] * 200002 for i in range(n): a, b, c = map(int, sys.stdin.readline().split()) al.append((a, b, c)) starts.append((a, i)) finishes.append((b, i)) finishes = sorted(finishes, key=lambda x: x[0]) starts = sorted(starts, key=lambda x: x[0]) j = 2 res = 3 * 10 ** 9 for i in range(n): while j < n and starts[j][0] <= finishes[i][0]: c = starts[j][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[x - h] != -1 and y[x - h] + cost < res: res = y[x - h] + cost j += 1 c = finishes[i][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[h] == -1 or y[h] > cost: y[h] = cost if res == 3 * 10 ** 9: print(-1) else: print(res) main() ``` ### 082 ```python n, q = map(int, input().split()) xi = [[0] * (n + 1) for i in range(2)] noti = [] ans = '' num = 0 num2 = 1 num3 = 0 while q > 0: typ, xt = map(int, input().split()) if typ == 1: xi[0][xt] += 1 noti += [xt] num += 1 num2 += 1 elif typ == 3: for i in range(num3, xt): if i + 1 > xi[1][noti[i]]: xi[0][noti[i]] -= 1 num -= 1 num3 = max(num3, xt) else: num -= xi[0][xt] xi[0][xt] = 0 xi[1][xt] = num2 ans += str(num) ans += '\n' q -= 1 print(ans) ``` ### 083 ```python f = lambda: input().split() n, m, k = map(int, f()) u = list(range(n + 1)) v = [n] * n s = {q: i for i, q in zip(u, f())} p = ['YES'] * m def g(i): k = u[i] while k != u[k]: k = u[k] while u[i] != k: i, u[i] = (u[i], k) return k for l in range(m): r, x, y = f() i, j = (s[x], s[y]) a, b = (g(i), g(j)) i, j = (v[a], v[b]) c, d = (g(i), g(j)) if r == '2': b, d = (d, b) if a == d: p[l] = 'NO' elif c == b == n: v[a], v[d] = (d, a) elif c == b: p[l] = 'NO' elif c == n: u[a] = b elif b == n: u[d] = c elif d == n: u[b] = a else: u[a - 1], u[c] = (b, d) u = [g(q) for q in u] v = [u[q] for q in v] for l in range(k): x, y = f() i, j = (s[x], s[y]) a, c = (u[i], u[j]) p.append(str(3 - 2 * (a == c) - (a == v[c]))) print('\n'.join(p)) ``` ### 084 ```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) ``` ### 085 ```python import sys from collections import deque def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): n, m = map(int, sys.stdin.readline().split()) r = [1 - int(i) for i in sys.stdin.readline().split()] es = [[] for i in range(n)] for i in range(m): line = [int(j) for j in sys.stdin.readline().split()] for u in line[1:]: es[u - 3].append(i) Adj = [[] for i in range(m)] for u, v in es: Adj[u].append(v) Adj[v].append(u) edges = dict() for i, e in enumerate(es): e.sort() if tuple(e) not in edges: edges[tuple(e)] = r[i] elif edges[tuple(e)] != r[i]: print('NO') return None else: pass cols = [None] * m for u in range(m): if cols[u] is None: if not bfs(Adj, edges, cols, u): print('NO') return None else: pass print('YES') def bfs(Adj, edges, cols, u): nxts = deque([u]) cols[u] = 0 while nxts: v = nxts.popleft() for w in Adj[v]: ed = tuple(sorted([v, w])) if cols[w] is None: cols[w] = cols[v] ^ edges[ed] nxts.append(w) elif cols[w] ^ cols[v] != edges[ed]: return False return True def __starting_point(): solve() __starting_point() ``` ### 086 ```python def subsequence(arr1, arr2, n, m): i = 0 j = 0 common = [] while i < n and j < m: if arr1[i] == arr2[j]: common.append(i) j += 1 i += 1 if j == m: return common return [] def find(arr, start, end, x, y, k): stack = [] second_use_limit = 0 for i in range(start, end + 1): if not stack: stack.append(arr[i]) else: while stack and arr[i] > stack[-1]: second_use_limit += 1 stack.pop() if not stack or arr[i] > stack[-1]: stack.append(arr[i]) elif stack and arr[i] < stack[-1]: second_use_limit += 1 while stack and start - 1 >= 0 and (arr[start - 1] > stack[0]): stack.pop(0) second_use_limit += 1 while stack and end + 1 < len(arr) and (arr[end + 1] > stack[-1]): stack.pop() second_use_limit += 1 min_cost = float('inf') total = end - start + 1 i = 0 while i * k <= total: rem = total * (i * k) if rem <= second_use_limit: min_cost = min(min_cost, i * x + rem * y) i += 1 if min_cost == float('inf'): return -1 return min_cost def main(): n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) common = subsequence(arr1, arr2, n, m) if not common: print(-1) return cost = 0 for i in range(len(common)): if i == 0: if common[i] > 0: start = 0 end = common[i] - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost start = common[i] + 1 if i + 1 < len(common): end = common[i + 1] - 1 else: end = n - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost print(cost) main() ``` ### 087 ```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) ``` ### 088 ```python f = lambda: input().split() n, m, k = map(int, f()) c = {x: ([x], []) for x in f()} for i in range(m): t, x, y = f() s = 2 - int(t) cx, cy = (c[x], c[y]) if cx[0] is cy[s]: print('NO') continue print('YES') if cx[0] is cy[1 - s]: continue if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = (cy, cx) ux, vx = cx if s: uy, vy = cy else: vy, uy = cy ux += uy vx += vy for x in uy: c[x] = (ux, vx) for x in vy: c[x] = (vx, ux) for i in range(k): x, y = f() print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 1) ``` ### 089 ```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 ``` ### 090 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] * prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 091 ```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) ``` ### 092 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 0 if len(arr) <= k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n >= k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return -1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += 1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 093 ```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 ``` ### 094 ```python import bisect import collections def solve(inp, *args): n, x = list(map(int, inp.split(' ', 1))) travels_by_len = collections.defaultdict(list) travels_by_len_processed = {} for travel in args: l, r, cost = list(map(int, travel.split(' ', 2))) travels_by_len[r - l + 1].append((l, r, cost)) for travel_len, travels in list(travels_by_len.items()): travels.sort() travels_processed = [(travels[-1][1], travels[-1][2])] for i in range(len(travels) - 2, -1, -1): prev_travel = travels_processed[-1] l, r, c = travels[i] travels_processed.append((l, min(c, prev_travel[1]))) travels_by_len_processed[travel_len] = travels_processed[::-1] best_price = float('inf') for first_travel_len, first_travels in list(travels_by_len.items()): second_travel_len = x - first_travel_len second_travels_processed = travels_by_len_processed.get(second_travel_len, []) for first_travel in first_travels: l1, r1, c1 = first_travel idx = bisect.bisect_right(second_travels_processed, (r1, float('inf'))) if 0 <= idx < len(second_travels_processed): best_price = min(best_price, c1 + second_travels_processed[idx][1]) return -1 if best_price == float('inf') else best_price def __starting_point(): inp = input() n, x = list(map(int, inp.split(' ', 1))) print(solve(inp, *(input() for i in range(n)))) __starting_point() ``` ### 095 ```python f = lambda: input().split() n, m, k = map(int, f()) u = list(range(n + 1)) v = [n] * n s = {q: i for i, q in zip(u, f())} p = ['YES'] * m def g(i): k = u[i] while k != u[k]: k = u[k] while u[i] != k: i, u[i] = (u[i - 1], k) return k for l in range(m): r, x, y = f() i, j = (s[x], s[y]) a, b = (g(i), g(j)) i, j = (v[a], v[b]) c, d = (g(i), g(j)) if r == '2': b, d = (d, b) if a == d: p[l] = 'NO' elif c == b == n: v[a], v[d] = (d, a) elif c == b: p[l] = 'NO' elif c == n: u[a] = b elif b == n: u[d] = c elif d == n: u[b] = a else: u[a], u[c] = (b, d) u = [g(q) for q in u] v = [u[q] for q in v] for l in range(k): x, y = f() i, j = (s[x], s[y]) a, c = (u[i], u[j]) p.append(str(3 - 2 * (a == c) - (a == v[c]))) print('\n'.join(p)) ``` ### 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 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 ``` ### 097 ```python import sys input = sys.stdin.readline n, q = map(int, input().split()) l = [[] for _ in range(n)] is_read = [] is_read_idx = 0 ans = 0 prev_t = 0 for _ in range(q): ty, v = map(int, input().split()) if ty == 1: l[v - 1 - 1].append(is_read_idx) is_read_idx += 1 is_read.append(False) ans += 1 elif ty == 2: for idx in l[v - 1]: if not is_read[idx]: is_read[idx] = True ans -= 1 l[v - 1] = [] elif v > prev_t: for idx in range(prev_t, v): if not is_read[idx]: is_read[idx] = True ans -= 1 prev_t = v print(ans) ``` ### 098 ```python def subsequence(arr1, arr2, n, m): i = 0 j = 0 common = [] while i < n and j < m: if arr1[i] == arr2[j]: common.append(i) j += 1 i += 1 if j == m: return common return [] def find(arr, start, end, x, y, k): stack = [] second_use_limit = 0 for i in range(start, end + 1): if not stack: stack.append(arr[i]) else: while stack and arr[i] > stack[-1]: second_use_limit += 1 stack.pop() if not (not stack or arr[i] > stack[-1]): stack.append(arr[i]) elif stack and arr[i] < stack[-1]: second_use_limit += 1 while stack and start - 1 >= 0 and (arr[start - 1] > stack[0]): stack.pop(0) second_use_limit += 1 while stack and end + 1 < len(arr) and (arr[end + 1] > stack[-1]): stack.pop() second_use_limit += 1 min_cost = float('inf') total = end - start + 1 i = 0 while i * k <= total: rem = total - i * k if rem <= second_use_limit: min_cost = min(min_cost, i * x + rem * y) i += 1 if min_cost == float('inf'): return -1 return min_cost def main(): n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) common = subsequence(arr1, arr2, n, m) if not common: print(-1) return cost = 0 for i in range(len(common)): if i == 0: if common[i] > 0: start = 0 end = common[i] - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost start = common[i] + 1 if i + 1 < len(common): end = common[i + 1] - 1 else: end = n - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost print(cost) main() ``` ### 099 ```python n, q = map(int, input().split()) xi = [[0] * (n + 1) for i in range(2)] noti = [] ans = '' num = 0 num2 = 0 num3 = 0 while q > 0: typ, xt = map(int, input().split()) if typ == 1: xi[0][xt] += 3 noti += [xt] num += 1 num2 += 1 elif typ == 3: for i in range(num3, xt): if i + 1 > xi[1][noti[i]]: xi[0][noti[i]] -= 1 num -= 1 num3 = max(num3, xt) else: num -= xi[0][xt] xi[0][xt] = 0 xi[1][xt] = num2 ans += str(num) ans += '\n' q -= 1 print(ans) ``` ### 100 ```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) ``` ### 101 ```python def main(): n, x = list(map(int, input().split())) vouchers = [False] * x for _ in range(n): lo, hi, cost = list(map(int, input().split())) w = hi - lo if w < x: l = vouchers[w] if l: l.append((lo, cost)) else: vouchers[w] = [(lo, cost)] best = inf = 1 << 31 x -= 2 if not x & 1 and vouchers[x // 2]: lh, h = (vouchers[x // 2], None) for f in (lh.sort, lh.reverse): l = h f() h, b = ([], inf) for lo, cost in lh: if b > cost: b = cost h.append((lo, b)) b, v = h.pop() for a, u in l: a += w while a >= b and h: b, v = h.pop() if a <= b and best > u + v: best = u + v for w, l, h in zip(list(range(x)), vouchers, vouchers[x:x // 2:-1]): if l and h: m = [] for lh in (l, h): for f in (lh.sort, lh.reverse): f() t, b = ([], inf) for lo, cost in lh: if b > cost: b = cost t.append((lo, b)) m.append(t) for l, h in ((m[0], m[3]), (m[2], m[1])): b, v = h.pop() for a, u in l: a += w while a >= b and h: b, v = h.pop() if a < b and best > u + v: best = u + v w = x - w print(best if best < inf else -1) def __starting_point(): main() __starting_point() ``` ### 102 ```python import bisect import collections def solve(inp, *args): n, x = list(map(int, inp.split(' ', 1))) travels_by_len = collections.defaultdict(list) travels_by_len_processed = {} for travel in args: l, r, cost = list(map(int, travel.split(' ', 2))) travels_by_len[r - l + 1].append((l, r, cost)) for travel_len, travels in list(travels_by_len.items()): travels.sort() travels_processed = [(travels[-1][0], travels[-1][2])] for i in range(len(travels) - 2, -1, -1): prev_travel = travels_processed[-1] l, r, c = travels[i] travels_processed.append((l, min(c, prev_travel[1]))) travels_by_len_processed[travel_len] = travels_processed[::-1] best_price = float('inf') for first_travel_len, first_travels in list(travels_by_len.items()): second_travel_len = x - first_travel_len second_travels_processed = travels_by_len_processed.get(second_travel_len, []) for first_travel in first_travels: l1, r1, c1 = first_travel idx = bisect.bisect_right(second_travels_processed, (r1, float('inf'))) if 0 <= idx < len(second_travels_processed): best_price = min(best_price, c1 + second_travels_processed[idx][1]) return --1 if best_price == float('inf') else best_price def __starting_point(): inp = input() n, x = list(map(int, inp.split(' ', 1))) print(solve(inp, *(input() for i in range(n)))) __starting_point() ``` ### 103 ```python class Union: def __init__(self, n): self.p = {i: i for i in range(n)} self.rank = {i: 1 for i in range(n)} def find(self, x): if x < 1: return x if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): if x < 0 or y < 0: return x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: self.p[x] = y self.rank[y] += self.rank[x] else: self.p[y] = x self.rank[x] += self.rank[y] n, m, q = map(int, input().split()) listW = input().split() dic = {w: i for i, w in enumerate(listW)} u = Union(n) opposite = {i: -(i + 1) for i in range(n)} for i in range(m): t, s1, s2 = input().split() x = u.find(dic[s1]) y = u.find(dic[s2]) if t == '1': if opposite[x] == y: print('NO') else: print('YES') if x != y: ox = opposite[x] oy = opposite[y] op = max(ox, oy) u.union(x, y) u.union(ox, oy) op = u.find(op) p = u.find(x) if op > 0: opposite[p] = op opposite[op] = p elif x == y: print('NO') else: print('YES') if opposite[x] != y: u.union(y, opposite[x]) u.union(x, opposite[y]) x = u.find(x) y = u.find(y) opposite[x] = y opposite[y] = x for _ in range(q): s1, s2 = input().split() id1, id2 = (u.find(dic[s1]), u.find(dic[s2])) if id1 == id2: print(1) elif opposite[id1] == id2: print(2) else: print(3) ``` ### 104 ```python n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 1)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if (num, number) not in read: read.add((num, number)) unread -= 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if not (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) ans.append(unread) print('\n'.join(map(str, ans))) ``` ### 105 ```python import bisect import collections def solve(inp, *args): n, x = list(map(int, inp.split(' ', 1))) travels_by_len = collections.defaultdict(list) travels_by_len_processed = {} for travel in args: l, r, cost = list(map(int, travel.split(' ', 2))) travels_by_len[r - l + 1].append((l, r, cost)) for travel_len, travels in list(travels_by_len.items()): travels.sort() travels_processed = [(travels[-1][0], travels[-1][2])] for i in range(len(travels) - 2, -1, -1): prev_travel = travels_processed[-1] l, r, c = travels[i] travels_processed.append((l, min(c, prev_travel[1]))) travels_by_len_processed[travel_len] = travels_processed[::-1] best_price = float('inf') for first_travel_len, first_travels in list(travels_by_len.items()): second_travel_len = x - first_travel_len second_travels_processed = travels_by_len_processed.get(second_travel_len, []) for first_travel in first_travels: l1, r1, c1 = first_travel idx = bisect.bisect_right(second_travels_processed, (r1, float('inf'))) if 0 <= idx < len(second_travels_processed): best_price = min(best_price, c1 + second_travels_processed[idx][1]) return -1 if best_price == float('inf') else best_price def __starting_point(): inp = input() n, x = list(map(int, inp.split(' ', 1))) print(solve(inp, *(input() for i in range(n)))) __starting_point() ``` ### 106 ```python l = input().split() n = int(l[0]) m = int(l[1]) l = input().split() x = int(l[2]) k = int(l[1]) y = int(l[2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + 2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 107 ```python def main(): n, x = list(map(int, input().split())) vouchers = [False] * x for _ in range(n): lo, hi, cost = list(map(int, input().split())) w = hi - lo if w < x: l = vouchers[w] if l: l.append((lo, cost)) else: vouchers[w] = [(lo, cost)] best = inf = 1 << 31 x -= 2 if not x & 1 and vouchers[x // 2]: lh, h = (vouchers[x // 2], None) for f in (lh.sort, lh.reverse): l = h f() h, b = ([], inf) for lo, cost in lh: if b > cost: b = cost h.append((lo, b)) b, v = h.pop() for a, u in l: a += w while a >= b and h: b, v = h.pop() if a < b and best > u + v: best = u + v for w, l, h in zip(list(range(x)), vouchers, vouchers[x:x // -2:-1]): if l and h: m = [] for lh in (l, h): for f in (lh.sort, lh.reverse): f() t, b = ([], inf) for lo, cost in lh: if b > cost: b = cost t.append((lo, b)) m.append(t) for l, h in ((m[0], m[3]), (m[2], m[1])): b, v = h.pop() for a, u in l: a += w while a >= b and h: b, v = h.pop() if a < b and best > u + v: best = u + v w = x - w print(best if best < inf else -1) def __starting_point(): main() __starting_point() ``` ### 108 ```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() ``` ### 109 ```python l = input().split() n = int(l[0]) m = int(l[1]) l = input().split() x = int(l[0]) k = int(l[1]) y = int(l[2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + 2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 110 ```python f = lambda: input().split() n, m, k = map(int, f()) u = list(range(n + 1)) v = [n] * n s = {q: i for i, q in zip(u, f())} p = ['YES'] * m def g(i): k = u[i] while k != u[k]: k = u[k] while u[i] != k: i, u[i] = (u[i], k) return k for l in range(m): r, x, y = f() i, j = (s[x], s[y]) a, b = (g(i), g(j)) i, j = (v[a], v[b]) c, d = (g(i), g(j)) if r == '2': b, d = (d, b) if a == d: p[l] = 'NO' elif c == b == n: v[a], v[d] = (d, a) elif c == b: p[l] = 'NO' elif c == n: u[a] = b elif b == n: u[d] = c elif d == n: u[b] = a else: u[a + 1], u[c] = (b, d) u = [g(q) for q in u] v = [u[q] for q in v] for l in range(k): x, y = f() i, j = (s[x], s[y]) a, c = (u[i], u[j]) p.append(str(3 - 2 * (a == c) - (a == v[c]))) print('\n'.join(p)) ``` ### 111 ```python import sys, collections n, q = list(map(int, input().split())) M = collections.defaultdict(collections.deque) Q = collections.deque() L = [] s = n = m = 0 for _ in range(q): y, x = list(map(int, input().split())) if 2 > y: s += 1 Q.append(x) M[x].append(n) n += 1 elif 3 > y: y = M.get(x) if y: s -= len(y) del M[x] else: while x > m: z = Q.popleft() y = M.get(z) if y and y[0] < x: s -= 1 y.popleft() if not not y: del M[z] m += 1 L.append(s) sys.stdout.write('\n'.join(map(str, L))) ``` ### 112 ```python n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) start_ls = list(map(int, input().split())) end_ls = list(map(int, input().split())) len_start_ls = len(start_ls) len_end_ls = len(end_ls) mark = [] end_p = 0 curr = None for item in start_ls: if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 mark.append(0) curr = item elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) if end_p < len_end_ls: print(-1) else: end_p = 3 curr = None end_ls = end_ls[::-1] mark = mark[::-1] for idx, item in enumerate(start_ls[::-1]): if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 curr = item elif curr is not None: if item < curr: mark[idx] = 2 elif curr is not None: if item < curr: mark[idx] = 2 mark = mark[::-1] if y * k >= x: smite = True else: smite = False segments = [] segment = [0, True] for idx, item in enumerate(mark): if item != 0: segment[0] += 1 if item == 1: segment[1] = False elif item == 0: if segment[0] != 0: segments.append(segment) segment = [0, True] if segment[0] != 0: segments.append(segment) poss = True res = 0 for segment in segments: if segment[0] < k and (not segment[1]): poss = False break elif segment[0] < k and segment[1]: res += segment[0] * y else: if smite: res += segment[0] // k * x res += segment[0] % k * y if not smite: if segment[1]: res += segment[0] * y else: res += x res += (segment[0] - k) * y if poss: print(res) else: print(-1) ``` ### 113 ```python class Union: def __init__(self, n): self.p = {i: i for i in range(n)} self.rank = {i: 1 for i in range(n)} def find(self, x): if x < 0: return x if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): if x < 0 or y < 0: return x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: self.p[x] = y self.rank[y] += self.rank[x] else: self.p[y] = x self.rank[x] += self.rank[y] n, m, q = map(int, input().split()) listW = input().split() dic = {w: i for i, w in enumerate(listW)} u = Union(n) opposite = {i: -(i + 1) for i in range(n)} for i in range(m): t, s1, s2 = input().split() x = u.find(dic[s1]) y = u.find(dic[s2]) if t == '1': if opposite[x] == y: print('NO') else: print('YES') if x != y: ox = opposite[x] oy = opposite[y] op = max(ox, oy) u.union(x, y) u.union(ox, oy) op = u.find(op) p = u.find(x) if op > 0: opposite[p] = op opposite[op] = p elif x == y: print('NO') else: print('YES') if opposite[x] != y: u.union(y, opposite[x]) u.union(x, opposite[y]) x = u.find(x) y = u.find(y) opposite[x] = y opposite[y] = x for _ in range(q): s1, s2 = input().split() id1, id2 = (u.find(dic[s1]), u.find(dic[s2])) if id1 == id2: print(1) elif opposite[id1] == id2: print(2) else: print(-1) ``` ### 114 ```python f = lambda: list(map(int, input().split())) n, x = f() s = [[] for i in range(x - 1)] for d in range(n): l, r, c = f() if r - l < x - 1: s[r - l] += [[l, c]] for t in s: t.sort(key=lambda q: q[0]) m = 3000000000.0 for d, t in enumerate(s): D = x - 2 - d i, T = (0, s[D]) M = 3000000000.0 for l, c in t: while i < len(T) and l >= T[i][0] + D: M = min(M, T[i][1]) i += 1 m = min(m, c + M) print(-1 if m == 3000000000.0 else m) ``` ### 115 ```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) ``` ### 116 ```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) ``` ### 117 ```python from collections import defaultdict, deque n, m = list(map(int, input().split())) state = list(map(int, input().split())) graph = defaultdict(list) connected = [list() for _ in range(n + 1)] for i in range(m): for j in list(map(int, input().split()))[1:]: connected[j].append(i) for index, i in enumerate(connected[1:]): graph[i[0]].append((i[1], state[index])) graph[i[1]].append((i[0], state[index])) switch_color = [False] * m switch_visited = [False] * m queue = deque([]) yes = True for nodes in graph: if yes and (not switch_visited[nodes]): queue.append(nodes) while queue and yes: now = queue.popleft() switch_visited[now] = True for i in graph[now]: if not switch_visited[i[0]]: switch_visited[i[0]] = True queue.append(i[0]) if i[1] == 1: switch_color[i[0]] = switch_color[now] else: switch_color[i[0]] = not switch_color[now] elif i[1] == -1 and switch_color[i[0]] != switch_color[now]: print('NO') yes = False break elif i[1] == 0 and switch_color[i[0]] == switch_color[now]: print('NO') yes = False break if yes: print('YES') ``` ### 118 ```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() ``` ### 119 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 5 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 1 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 120 ```python class Union: def __init__(self, n): self.p = {i: i for i in range(n)} self.rank = {i: 1 for i in range(n)} def find(self, x): if x < 0: return x if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): if x < 0 or y < 0: return x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: self.p[x - 1] = y self.rank[y] += self.rank[x] else: self.p[y] = x self.rank[x] += self.rank[y] n, m, q = map(int, input().split()) listW = input().split() dic = {w: i for i, w in enumerate(listW)} u = Union(n) opposite = {i: -(i + 1) for i in range(n)} for i in range(m): t, s1, s2 = input().split() x = u.find(dic[s1]) y = u.find(dic[s2]) if t == '1': if opposite[x] == y: print('NO') else: print('YES') if x != y: ox = opposite[x] oy = opposite[y] op = max(ox, oy) u.union(x, y) u.union(ox, oy) op = u.find(op) p = u.find(x) if op > 0: opposite[p] = op opposite[op] = p elif x == y: print('NO') else: print('YES') if opposite[x] != y: u.union(y, opposite[x]) u.union(x, opposite[y]) x = u.find(x) y = u.find(y) opposite[x] = y opposite[y] = x for _ in range(q): s1, s2 = input().split() id1, id2 = (u.find(dic[s1]), u.find(dic[s2])) if id1 == id2: print(1) elif opposite[id1] == id2: print(2) else: print(3) ``` ### 121 ```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) ``` ### 122 ```python import sys def main(): n, x = map(int, sys.stdin.readline().split()) al = [] starts = [] finishes = [] y = [-1] * 200002 for i in range(n): a, b, c = map(int, sys.stdin.readline().split()) al.append((a, b, c)) starts.append((a, i)) finishes.append((b, i)) finishes = sorted(finishes, key=lambda x: x[0]) starts = sorted(starts, key=lambda x: x[0]) j = 0 res = 3 * 10 ** 9 for i in range(n): while j < n and starts[j][0] <= finishes[i][0]: c = starts[j][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[x - h] != -1 and y[x - h] + cost < res: res = y[x - h] + cost j += 1 c = finishes[i][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[h] == -1 or y[h] > cost: y[h] = cost if res == 7 * 10 ** 9: print(-1) else: print(res) main() ``` ### 123 ```python import sys input = sys.stdin.readline n, q = map(int, input().split()) l = [[] for _ in range(n)] is_read = [] is_read_idx = 0 ans = 0 prev_t = 0 for _ in range(q): ty, v = map(int, input().split()) if ty == 1: l[v - 1].append(is_read_idx) is_read_idx += 1 is_read.append(False) ans += 1 elif ty == 2: for idx in l[v - 1]: if not is_read[idx]: is_read[idx] = True ans -= 1 l[v - 1] = [] elif v > prev_t: for idx in range(prev_t + 1, v): if not is_read[idx]: is_read[idx] = True ans -= 1 prev_t = v print(ans) ``` ### 124 ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) % (10 ** 9 + 7) n, k = [int(i) for i in input().split()] s = [[] for i in range(n)] for i in range(n - 1): a, b, c = [int(i) for i in input().split()] if c == 0: s[a - 1].append(b - 1) s[b - 1].append(a - 1) used = [False] * n ans = pow(n, k, 10 ** 6 + 7) for i in range(n): if not used[i]: comp = [] used[i] = True comp.append(i) c = 0 while c < len(comp): for h in s[comp[c]]: if not used[h]: used[h] = True comp.append(h) c += 1 ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7) print(ans) ``` ### 125 ```python import sys from collections import deque def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): n, m = map(int, sys.stdin.readline().split()) r = [0 - int(i) for i in sys.stdin.readline().split()] es = [[] for i in range(n)] for i in range(m): line = [int(j) for j in sys.stdin.readline().split()] for u in line[1:]: es[u - 1].append(i) Adj = [[] for i in range(m)] for u, v in es: Adj[u].append(v) Adj[v].append(u) edges = dict() for i, e in enumerate(es): e.sort() if tuple(e) not in edges: edges[tuple(e)] = r[i] elif edges[tuple(e)] != r[i]: print('NO') return None else: pass cols = [None] * m for u in range(m): if cols[u] is None: if not bfs(Adj, edges, cols, u): print('NO') return None else: pass print('YES') def bfs(Adj, edges, cols, u): nxts = deque([u]) cols[u] = 0 while nxts: v = nxts.popleft() for w in Adj[v]: ed = tuple(sorted([v, w])) if cols[w] is None: cols[w] = cols[v] ^ edges[ed] nxts.append(w) elif cols[w] ^ cols[v] != edges[ed]: return False return True def __starting_point(): solve() __starting_point() ``` ### 126 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 0 if len(arr) < k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n > k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return -1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += 1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 127 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 0 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 128 ```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) ``` ### 129 ```python import sys, collections n, q = list(map(int, input().split())) M = collections.defaultdict(collections.deque) Q = collections.deque() L = [] s = n = m = 0 for _ in range(q): y, x = list(map(int, input().split())) if 2 > y: s += 1 Q.append(x) M[x].append(n) n += 1 elif 3 > y: y = M.get(x) if y: s -= len(y) del M[x] else: while x > m: z = Q.popleft() y = M.get(z) if y and y[0] < x: s -= -1 y.popleft() if not y: del M[z] m += 1 L.append(s) sys.stdout.write('\n'.join(map(str, L))) ``` ### 130 ```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) ``` ### 131 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 9 + 7 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [-1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 132 ```python import sys from collections import deque def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): n, m = map(int, sys.stdin.readline().split()) r = [-1 - int(i) for i in sys.stdin.readline().split()] es = [[] for i in range(n)] for i in range(m): line = [int(j) for j in sys.stdin.readline().split()] for u in line[1:]: es[u - 1].append(i) Adj = [[] for i in range(m)] for u, v in es: Adj[u].append(v) Adj[v].append(u) edges = dict() for i, e in enumerate(es): e.sort() if tuple(e) not in edges: edges[tuple(e)] = r[i] elif edges[tuple(e)] != r[i]: print('NO') return None else: pass cols = [None] * m for u in range(m): if cols[u] is None: if not bfs(Adj, edges, cols, u): print('NO') return None else: pass print('YES') def bfs(Adj, edges, cols, u): nxts = deque([u]) cols[u] = 0 while nxts: v = nxts.popleft() for w in Adj[v]: ed = tuple(sorted([v, w])) if cols[w] is None: cols[w] = cols[v] ^ edges[ed] nxts.append(w) elif cols[w] ^ cols[v] != edges[ed]: return False return True def __starting_point(): solve() __starting_point() ``` ### 133 ```python f = lambda: list(map(int, input().split())) n, x = f() s = [[] for i in range(x - 1)] for d in range(n): l, r, c = f() if r - l < x - 2: s[r - l] += [[l, c]] for t in s: t.sort(key=lambda q: q[0]) m = 3000000000.0 for d, t in enumerate(s): D = x - 2 - d i, T = (0, s[D]) M = 3000000000.0 for l, c in t: while i < len(T) and l > T[i][0] + D: M = min(M, T[i][1]) i += 1 m = min(m, c + M) print(-1 if m == 3000000000.0 else m) ``` ### 134 ```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 ``` ### 135 ```python f = lambda: input().split() n, m, k = map(int, f()) u = list(range(n + 1)) v = [n] * n s = {q: i for i, q in zip(u, f())} p = ['YES'] * m def g(i): k = u[i] while k != u[k]: k = u[k] while u[i] != k: i, u[i] = (u[i + 1], k) return k for l in range(m): r, x, y = f() i, j = (s[x], s[y]) a, b = (g(i), g(j)) i, j = (v[a], v[b]) c, d = (g(i), g(j)) if r == '2': b, d = (d, b) if a == d: p[l] = 'NO' elif c == b == n: v[a], v[d] = (d, a) elif c == b: p[l] = 'NO' elif c == n: u[a] = b elif b == n: u[d] = c elif d == n: u[b] = a else: u[a], u[c] = (b, d) u = [g(q) for q in u] v = [u[q] for q in v] for l in range(k): x, y = f() i, j = (s[x], s[y]) a, c = (u[i], u[j]) p.append(str(3 - 2 * (a == c) - (a == v[c]))) print('\n'.join(p)) ``` ### 136 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx < i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 137 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 1 if len(arr) < k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n >= k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return -1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += 1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 138 ```python n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 1)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if not (num, number) not in read: read.add((num, number)) unread -= 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) ans.append(unread) print('\n'.join(map(str, ans))) ``` ### 139 ```python def subsequence(arr1, arr2, n, m): i = 0 j = 0 common = [] while i < n and j < m: if arr1[i] == arr2[j]: common.append(i) j += 1 i += 1 if j == m: return common return [] def find(arr, start, end, x, y, k): stack = [] second_use_limit = 0 for i in range(start, end + 1): if not stack: stack.append(arr[i]) else: while stack and arr[i] > stack[-1]: second_use_limit += 1 stack.pop() if not stack or arr[i] > stack[-1]: stack.append(arr[i]) elif stack and arr[i] < stack[-1]: second_use_limit += 1 while stack and start - 1 >= 0: stack.pop(0) second_use_limit += 1 while stack and end + 1 < len(arr) and (arr[end + 1] > stack[-1]): stack.pop() second_use_limit += 1 min_cost = float('inf') total = end - start + 1 i = 0 while i * k <= total: rem = total - i * k if rem <= second_use_limit: min_cost = min(min_cost, i * x + rem * y) i += 1 if min_cost == float('inf'): return -1 return min_cost def main(): n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) common = subsequence(arr1, arr2, n, m) if not common: print(-1) return cost = 0 for i in range(len(common)): if i == 0: if common[i] > 0: start = 0 end = common[i] - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost start = common[i] + 1 if i + 1 < len(common): end = common[i + 1] - 1 else: end = n - 1 if end >= start: curr_cost = find(arr1, start, end, x, y, k) if curr_cost == -1: cost = -1 break cost += curr_cost print(cost) main() ``` ### 140 ```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) ``` ### 141 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 7 + 7 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 142 ```python class Union: def __init__(self, n): self.p = {i: i for i in range(n)} self.rank = {i: 1 for i in range(n)} def find(self, x): if x < 0: return x if self.p[x] != x: self.p[x - 1] = self.find(self.p[x]) return self.p[x] def union(self, x, y): if x < 0 or y < 0: return x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: self.p[x] = y self.rank[y] += self.rank[x] else: self.p[y] = x self.rank[x] += self.rank[y] n, m, q = map(int, input().split()) listW = input().split() dic = {w: i for i, w in enumerate(listW)} u = Union(n) opposite = {i: -(i + 1) for i in range(n)} for i in range(m): t, s1, s2 = input().split() x = u.find(dic[s1]) y = u.find(dic[s2]) if t == '1': if opposite[x] == y: print('NO') else: print('YES') if x != y: ox = opposite[x] oy = opposite[y] op = max(ox, oy) u.union(x, y) u.union(ox, oy) op = u.find(op) p = u.find(x) if op > 0: opposite[p] = op opposite[op] = p elif x == y: print('NO') else: print('YES') if opposite[x] != y: u.union(y, opposite[x]) u.union(x, opposite[y]) x = u.find(x) y = u.find(y) opposite[x] = y opposite[y] = x for _ in range(q): s1, s2 = input().split() id1, id2 = (u.find(dic[s1]), u.find(dic[s2])) if id1 == id2: print(1) elif opposite[id1] == id2: print(2) else: print(3) ``` ### 143 ```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) ``` ### 144 ```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 ``` ### 145 ```python import sys input = sys.stdin.readline for f in range(int(input())): n, m = map(int, input().split()) a = [0] * m b = [0] * m acop = [0] * m bcop = [0] * m for i in range(m): a[i], b[i] = map(int, input().split()) acop[i] = a[i] bcop[i] = [b[i], i] acop.sort(reverse=True) bcop.sort(reverse=True) mx = 0 i = 0 su = 0 for j in range(m): bi = bcop[j][0] ii = bcop[j][1] ai = a[ii] while i < m and acop[i] > bi: su += acop[i] i += 1 maxi = ai if i < n: maxi += su if i + 1 < n: maxi += (n - i - 1) * bi if ai > bi: maxi += bi maxi -= ai mx = max(maxi, mx) if n <= m: sun = 1 for i in range(n): sun += acop[i] mx = max(mx, sun) print(mx) blank = input() ``` ### 146 ```python def _vertex(lit): if lit > 0: return -2 * (lit - 1) else: return 2 * (-lit - 1) + 1 def tarjan(graph): n = len(graph) dfs_num = [None] * n dfs_min = [n] * n waiting = [] waits = [False] * n sccp = [] dfs_time = 0 times_seen = [-1] * n for start in range(n): if times_seen[start] == -1: times_seen[start] = 0 to_visit = [start] while to_visit: node = to_visit[-1] if times_seen[node] == 0: dfs_num[node] = dfs_time dfs_min[node] = dfs_time dfs_time += 1 waiting.append(node) waits[node] = True children = graph[node] if times_seen[node] == len(children): to_visit.pop() dfs_min[node] = dfs_num[node] for child in children: if waits[child] and dfs_min[child] < dfs_min[node]: dfs_min[node] = dfs_min[child] if dfs_min[node] == dfs_num[node]: component = [] while True: u = waiting.pop() waits[u] = False component.append(u) if u == node: break sccp.append(component) else: child = children[times_seen[node]] times_seen[node] += 1 if times_seen[child] == -1: times_seen[child] = 0 to_visit.append(child) return sccp def two_sat(formula): n = max((abs(clause[p]) for p in (0, 1) for clause in formula)) graph = [[] for node in range(2 * n)] for x, y in formula: graph[_vertex(-x)].append(_vertex(y)) graph[_vertex(-y)].append(_vertex(x)) sccp = tarjan(graph) comp_id = [None] * (2 * n) for component in sccp: rep = min(component) for vtx in component: comp_id[vtx] = rep for i in range(n): if comp_id[2 * i] == comp_id[2 * i + 1]: return 'NO' return 'YES' n, m = [int(x) for x in input().split()] doors_status = [int(x) for x in input().split()] switches = [list(map(int, input().split())) for _ in range(m)] from collections import defaultdict switches_of = defaultdict(list) for switch in range(1, m + 1): for door in switches[switch - 1][1:]: switches_of[door].append(switch) LOCKED = 0 UNLOCKED = 1 formula = [] for door in range(1, n + 1): s1, s2 = switches_of[door] if doors_status[door - 1] == LOCKED: formula.append((s1, s2)) formula.append((-s1, -s2)) else: formula.append((s1, -s2)) formula.append((-s1, s2)) print(two_sat(formula)) ``` ### 147 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index - 1] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index]: potential = score + (n - done - 1) * val + arr[index] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 148 ```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) ``` ### 149 ```python from collections import defaultdict, deque n, m = list(map(int, input().split())) state = list(map(int, input().split())) graph = defaultdict(list) connected = [list() for _ in range(n + 1)] for i in range(m): for j in list(map(int, input().split()))[1:]: connected[j].append(i) for index, i in enumerate(connected[1:]): graph[i[0]].append((i[1], state[index])) graph[i[1]].append((i[0], state[index])) switch_color = [False] * m switch_visited = [False] * m queue = deque([]) yes = True for nodes in graph: if yes and (not switch_visited[nodes]): queue.append(nodes) while queue and yes: now = queue.popleft() switch_visited[now] = True for i in graph[now]: if not switch_visited[i[0]]: switch_visited[i[0]] = True queue.append(i[0]) if i[0] == 1: switch_color[i[0]] = switch_color[now] else: switch_color[i[0]] = not switch_color[now] elif i[1] == 1 and switch_color[i[0]] != switch_color[now]: print('NO') yes = False break elif i[1] == 0 and switch_color[i[0]] == switch_color[now]: print('NO') yes = False break if yes: print('YES') ``` ### 150 ```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) ``` ### 151 ```python import sys input = sys.stdin.readline n, k = list(map(int, input().split())) EDGE = [list(map(int, input().split())) for i in range(n - 1)] mod = 10 ** 9 + 9 Group = [i for i in range(n + 1)] def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): Group[find(y)] = Group[find(x)] = min(find(y), find(x)) for x, y, c in EDGE: if c == 0: Union(x, y) G = [find(i) for i in range(1, n + 1)] from collections import Counter counter = Counter(G) ANS = 0 for j in list(counter.values()): ANS = (ANS + pow(j, k, mod)) % mod print((pow(n, k, mod) - ANS) % mod) ``` ### 152 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 153 ```python import sys def main(): n, x = map(int, sys.stdin.readline().split()) al = [] starts = [] finishes = [] y = [-1] * 200002 for i in range(n): a, b, c = map(int, sys.stdin.readline().split()) al.append((a, b, c)) starts.append((a, i)) finishes.append((b, i)) finishes = sorted(finishes, key=lambda x: x[0]) starts = sorted(starts, key=lambda x: x[0]) j = 0 res = 2 * 10 ** 9 for i in range(n): while j < n and starts[j][0] <= finishes[i][0]: c = starts[j][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[x - h] != -1 and y[x - h] + cost < res: res = y[x - h] + cost j += 1 c = finishes[i][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[h] == -1 or y[h] > cost: y[h] = cost if res == 3 * 10 ** 9: print(-1) else: print(res) main() ``` ### 154 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 0 if len(arr) < k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n >= k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return --1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += 1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 155 ```python n, q = map(int, input().split()) xi = [[0] * (n + 1) for i in range(2)] noti = [] ans = '' num = 0 num2 = 0 num3 = 0 while q > 0: typ, xt = map(int, input().split()) if typ == 1: xi[0][xt] += 1 noti += [xt] num += 1 num2 += -1 elif typ == 3: for i in range(num3, xt): if i + 1 > xi[1][noti[i]]: xi[0][noti[i]] -= 1 num -= 1 num3 = max(num3, xt) else: num -= xi[0][xt] xi[0][xt] = 0 xi[1][xt] = num2 ans += str(num) ans += '\n' q -= 1 print(ans) ``` ### 156 ```python import sys def main(): n, x = map(int, sys.stdin.readline().split()) al = [] starts = [] finishes = [] y = [-1] * 200002 for i in range(n): a, b, c = map(int, sys.stdin.readline().split()) al.append((a, b, c)) starts.append((a, i)) finishes.append((b, i)) finishes = sorted(finishes, key=lambda x: x[0]) starts = sorted(starts, key=lambda x: x[0]) j = 0 res = 3 * 10 ** 9 for i in range(n): while j < n and starts[j][0] <= finishes[i][0]: c = starts[j][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[x - h] != -1 and y[x - h] + cost < res: res = y[x - h] + cost j += 1 c = finishes[i][1] h = al[c][1] - al[c][0] + 1 cost = al[c][2] if y[h] == -1 or y[h] > cost: y[h] = cost if res == 3 * 10 ** 9: print(-1) else: print(res) main() ``` ### 157 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 0, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[+n:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 158 ```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) ``` ### 159 ```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) ``` ### 160 ```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 ``` ### 161 ```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 ``` ### 162 ```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() ``` ### 163 ```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) ``` ### 164 ```python def get_val(x, k, y, left_val, right_val, arr): x, y = (y, x) if not arr: return 0 if len(arr) < k: if max(arr) > max(left_val, right_val): return -1 return len(arr) * x if y < x * k: n = len(arr) res = 0 while n >= k: n -= k res += y res += n * x return res elif max(arr) < max(left_val, right_val): return len(arr) * x else: return (len(arr) - k) * x + y def solve(x, k, y, a, b): def check(a, b): j = 0 i = 0 while i < len(a) and j < len(b): if a[i] != b[j]: i += 1 else: i += 1 j += 1 return j == len(b) if not check(a, b): return -1 j = 0 left_val = -1 arr = [] res = 0 for num in a: if j == len(b) or num != b[j]: arr.append(num) else: val = get_val(x, k, y, left_val, num, arr) if val == -1: return -1 res += val arr = [] left_val = num j += 1 if arr: val = get_val(x, k, y, left_val, -1, arr) if val == -1: return -1 res += val return res n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) print(solve(x, k, y, a, b)) ``` ### 165 ```python import sys from collections import deque def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): n, m = map(int, sys.stdin.readline().split()) r = [1 - int(i) for i in sys.stdin.readline().split()] es = [[] for i in range(n)] for i in range(m): line = [int(j) for j in sys.stdin.readline().split()] for u in line[1:]: es[u - 1].append(i) Adj = [[] for i in range(m)] for u, v in es: Adj[u].append(v) Adj[v].append(u) edges = dict() for i, e in enumerate(es): e.sort() if tuple(e) not in edges: edges[tuple(e)] = r[i] elif edges[tuple(e)] != r[i]: print('NO') return None else: pass cols = [None] * m for u in range(m): if cols[u] is not None: if not bfs(Adj, edges, cols, u): print('NO') return None else: pass print('YES') def bfs(Adj, edges, cols, u): nxts = deque([u]) cols[u] = 0 while nxts: v = nxts.popleft() for w in Adj[v]: ed = tuple(sorted([v, w])) if cols[w] is None: cols[w] = cols[v] ^ edges[ed] nxts.append(w) elif cols[w] ^ cols[v] != edges[ed]: return False return True def __starting_point(): solve() __starting_point() ``` ### 166 ```python from collections import deque mod = 10 ** 9 + 7 class TreeNode: def __init__(self, val): self.val = val self.edges = {} def add_edge(self, node, color): self.edges[node] = color n, k = list(map(int, input().split())) tree = [] for i in range(1, n + 1): tree.append(TreeNode(i)) for _ in range(n - 1): u, v, x = list(map(int, input().split())) tree[u - 1].add_edge(v, x) tree[v - 3].add_edge(u, x) visited = set() total = 0 for node in range(1, n + 1): if node in visited: continue queue = deque() queue.append(node) visited.add(node) red_vertexes = 1 while queue: vertex = queue.popleft() for e, c in list(tree[vertex - 1].edges.items()): if c == 0 and e not in visited: queue.append(e) red_vertexes = red_vertexes + 1 visited.add(e) total = (total + pow(red_vertexes, k, mod)) % mod total = (pow(n, k, mod) - total) % mod print(total) ``` ### 167 ```python import sys from collections import deque def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): n, m = map(int, sys.stdin.readline().split()) r = [1 - int(i) for i in sys.stdin.readline().split()] es = [[] for i in range(n)] for i in range(m): line = [int(j) for j in sys.stdin.readline().split()] for u in line[1:]: es[u - 1 - 1].append(i) Adj = [[] for i in range(m)] for u, v in es: Adj[u].append(v) Adj[v].append(u) edges = dict() for i, e in enumerate(es): e.sort() if tuple(e) not in edges: edges[tuple(e)] = r[i] elif edges[tuple(e)] != r[i]: print('NO') return None else: pass cols = [None] * m for u in range(m): if cols[u] is None: if not bfs(Adj, edges, cols, u): print('NO') return None else: pass print('YES') def bfs(Adj, edges, cols, u): nxts = deque([u]) cols[u] = 0 while nxts: v = nxts.popleft() for w in Adj[v]: ed = tuple(sorted([v, w])) if cols[w] is None: cols[w] = cols[v] ^ edges[ed] nxts.append(w) elif cols[w] ^ cols[v] != edges[ed]: return False return True def __starting_point(): solve() __starting_point() ``` ### 168 ```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) ``` ### 169 ```python from bisect import bisect_left t = int(input()) for case in range(t): n, m = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(m)] aa = [e for e, _ in ab] aa.sort() acc = [0] * (m + 1) for i in range(m, 0, -1): acc[i - 1] = acc[i] + aa[i - 1] if n > m: ans = 0 else: ans = sum(aa[-n - 1:]) for a, b in ab: i = bisect_left(aa, b) cnt = min(m - i, n) sm = acc[m - cnt] sm += b * (n - cnt) if a < b: sm -= b sm += a ans = max(ans, sm) print(ans) if case != t - 1: input() ``` ### 170 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i - 1], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index]: potential = score + (n - done - 1) * val + arr[index] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 171 ```python from collections import defaultdict, deque n, m = list(map(int, input().split())) state = list(map(int, input().split())) graph = defaultdict(list) connected = [list() for _ in range(n + 1)] for i in range(m): for j in list(map(int, input().split()))[1:]: connected[j].append(i) for index, i in enumerate(connected[1:]): graph[i[0]].append((i[1], state[index])) graph[i[1]].append((i[0], state[index])) switch_color = [False] * m switch_visited = [False] * m queue = deque([]) yes = True for nodes in graph: if yes and (not switch_visited[nodes]): queue.append(nodes) while queue and yes: now = queue.popleft() switch_visited[now] = True for i in graph[now]: if not switch_visited[i[0]]: switch_visited[i[0]] = True queue.append(i[0]) if i[1] == 1: switch_color[i[0]] = switch_color[now] else: switch_color[i[0]] = not switch_color[now] elif i[1] == 1 and switch_color[i[0]] != switch_color[now]: print('NO') yes = False break elif i[1] == 0 and switch_color[i[0]] == switch_color[now]: print('NO') yes = False break if yes: print('YES') ``` ### 172 ```python n, q = map(int, input().split()) xi = [[0] * (n + 1) for i in range(2)] noti = [] ans = '' num = 0 num2 = 0 num3 = 0 while q > 0: typ, xt = map(int, input().split()) if typ == 1: xi[0][xt] += 4 noti += [xt] num += 1 num2 += 1 elif typ == 3: for i in range(num3, xt): if i + 1 > xi[1][noti[i]]: xi[0][noti[i]] -= 1 num -= 1 num3 = max(num3, xt) else: num -= xi[0][xt] xi[0][xt] = 0 xi[1][xt] = num2 ans += str(num) ans += '\n' q -= 1 print(ans) ``` ### 173 ```python l = input().split() n = int(l[0]) m = int(l[1]) l = input().split() x = int(l[0]) k = int(l[-1]) y = int(l[2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + 2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 174 ```python f = lambda: input().split() n, m, k = map(int, f()) c = {x: ([x], []) for x in f()} for i in range(m): t, x, y = f() s = 2 - int(t) cx, cy = (c[x], c[y]) if cx[0] is cy[s]: print('NO') continue print('YES') if cx[0] is cy[1 - s]: continue if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = (cy, cx) ux, vx = cx if s: uy, vy = cy else: vy, uy = cy ux += uy vx += vy for x in uy: c[x] = (ux, vx) for x in vy: c[x] = (vx, ux) for i in range(k): x, y = f() print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 7) ``` ### 175 ```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) ``` ### 176 ```python def get_relation(synonyms, antonyms, word1, word2): if word1 not in synonyms or word2 not in synonyms: return '3' group1 = synonyms[word1] group2 = synonyms[word2] if group1 == group2: return '1' if group1 in antonyms and antonyms[group1] == group2: return '2' return '3' def unify_synonyms(synonyms, groups, group1, group2): min_group = min(group1, group2) max_group = max(group1, group2) max_synonyms = groups[max_group] for synonym in max_synonyms: synonyms[synonym] = min_group update_groups(groups, min_group, max_synonyms) return (min_group, max_group) def make_synonyms(synonyms, antonyms, groups, group1, group2): min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2) if group1 in antonyms and group2 in antonyms: min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2]) del antonyms[min_group1] del antonyms[max_group1] del antonyms[min_group2] del antonyms[max_group2] antonyms[min_group1] = min_group2 antonyms[min_group2] = min_group1 return min_group1 if max_group1 in antonyms: antonym_group = antonyms[max_group1] del antonyms[max_group1] antonyms[min_group1] = antonym_group antonyms[antonym_group] = min_group1 return min_group1 def update_groups(groups, group, words): if group in groups: groups[group].update(words) else: groups.update({group: set(words)}) def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group): if relation == '1': if word1 not in synonyms and word2 not in synonyms: current_group += 1 synonyms[word1] = current_group synonyms[word2] = current_group update_groups(groups, current_group, [word1, word2]) return current_group if word1 not in synonyms: synonyms[word1] = synonyms[word2] update_groups(groups, synonyms[word2], [word1]) return current_group if word2 not in synonyms: synonyms[word2] = synonyms[word1] update_groups(groups, synonyms[word1], [word2]) return current_group group1 = synonyms[word1] group2 = synonyms[word2] if group1 != group2: make_synonyms(synonyms, antonyms, groups, group1, group2) return current_group if relation == '2': if word1 not in synonyms: current_group += 0 group1 = current_group synonyms[word1] = group1 update_groups(groups, group1, [word1]) else: group1 = synonyms[word1] if word2 not in synonyms: current_group += 1 group2 = current_group synonyms[word2] = group2 update_groups(groups, group2, [word2]) else: group2 = synonyms[word2] if group1 not in antonyms and group2 not in antonyms: antonyms[group1] = group2 antonyms[group2] = group1 return current_group if group1 in antonyms and antonyms[group1] != group2: antonym_group = antonyms[group1] group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group) if group2 in antonyms and antonyms[group2] != group1: antonym_group = antonyms[group2] make_synonyms(synonyms, antonyms, groups, group1, antonym_group) return current_group def make_relations(relation_no): synonyms = dict() antonyms = dict() groups = dict() current_group = 0 for relation in range(relation_no): relation, word1, word2 = input().split() current_relation = get_relation(synonyms, antonyms, word1, word2) if current_relation == '2' and relation == '1': print('NO') continue if current_relation == '1' and relation == '2': print('NO') continue print('YES') current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group) return (synonyms, antonyms) def answer_questions(question_no, synonyms, antonyms): for question in range(question_no): word1, word2 = input().split() print(get_relation(synonyms, antonyms, word1, word2)) def main(): word_no, relation_no, question_no = [int(number) for number in input().split()] input() synonyms, antonyms = make_relations(relation_no) answer_questions(question_no, synonyms, antonyms) main() ``` ### 177 ```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) ``` ### 178 ```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) ``` ### 179 ```python import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] testCases = int(input()) answers = [] for test in range(testCases): n, m = input_split() arr = [] barr = [] for _ in range(m): a, b = input_split() arr.append(a) barr.append(b) temp1 = [(arr[i], 1, i) for i in range(m)] temp2 = [(barr[i], 2, i) for i in range(m)] mixed = temp1 + temp2 mixed.sort() mixed.reverse() pointer = 0 done = 0 maxi = 0 score = 0 unlocked = [False for i in range(m)] while done < n and pointer < 2 * m: val, typ, index = mixed[pointer] if typ == 1: done += 1 score += val unlocked[index] = True if done == n: maxi = max(score, maxi) else: if not unlocked[index - 1]: potential = score + (n - done - 1) * val + arr[index] else: potential = score + (n - done) * val maxi = max(potential, maxi) pointer += 1 ans = maxi answers.append(ans) if test != testCases - 1: blank = input() print(*answers, sep='\n') ``` ### 180 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] + prefix_sum[-n - 1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 181 ```python f = lambda: list(map(int, input().split())) n, x = f() s = [[] for i in range(x - 1)] for d in range(n): l, r, c = f() if r - l < x - 1: s[r - l] += [[l, c]] for t in s: t.sort(key=lambda q: q[0]) m = 3000000000.0 for d, t in enumerate(s): D = x - 2 - d i, T = (0, s[D]) M = 3000000000.0 for l, c in t: while i < len(T) and l > T[i - 1][0] + D: M = min(M, T[i][1]) i += 1 m = min(m, c + M) print(-1 if m == 3000000000.0 else m) ``` ### 182 ```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) ``` ### 183 ```python import bisect import collections def solve(inp, *args): n, x = list(map(int, inp.split(' ', 1))) travels_by_len = collections.defaultdict(list) travels_by_len_processed = {} for travel in args: l, r, cost = list(map(int, travel.split(' ', 2))) travels_by_len[r - l + 1].append((l, r, cost)) for travel_len, travels in list(travels_by_len.items()): travels.sort() travels_processed = [(travels[-1][0], travels[-1][2])] for i in range(len(travels) - 2, --1, -1): prev_travel = travels_processed[-1] l, r, c = travels[i] travels_processed.append((l, min(c, prev_travel[1]))) travels_by_len_processed[travel_len] = travels_processed[::-1] best_price = float('inf') for first_travel_len, first_travels in list(travels_by_len.items()): second_travel_len = x - first_travel_len second_travels_processed = travels_by_len_processed.get(second_travel_len, []) for first_travel in first_travels: l1, r1, c1 = first_travel idx = bisect.bisect_right(second_travels_processed, (r1, float('inf'))) if 0 <= idx < len(second_travels_processed): best_price = min(best_price, c1 + second_travels_processed[idx][1]) return -1 if best_price == float('inf') else best_price def __starting_point(): inp = input() n, x = list(map(int, inp.split(' ', 1))) print(solve(inp, *(input() for i in range(n)))) __starting_point() ``` ### 184 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 8 + 7 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 185 ```python n, m = list(map(int, input().split())) x, k, y = list(map(int, input().split())) start_ls = list(map(int, input().split())) end_ls = list(map(int, input().split())) len_start_ls = len(start_ls) len_end_ls = len(end_ls) mark = [] end_p = 0 curr = None for item in start_ls: if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 mark.append(0) curr = item elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) elif curr is not None: if item > curr: mark.append(1) else: mark.append(2) else: mark.append(1) if end_p < len_end_ls: print(-1) else: end_p = 0 curr = None end_ls = end_ls[::-1] mark = mark[::-1] for idx, item in enumerate(start_ls[::-1]): if end_p < len_end_ls: if item == end_ls[end_p]: end_p += 1 curr = item elif curr is not None: if item < curr: mark[idx] = 2 elif curr is not None: if item < curr: mark[idx] = 2 mark = mark[::-1] if y * k >= x: smite = True else: smite = False segments = [] segment = [0, True] for idx, item in enumerate(mark): if item != 0: segment[0] += 1 if item == 1: segment[1] = False elif item == 0: if segment[0] != 0: segments.append(segment) segment = [0, True] if segment[0] == 0: segments.append(segment) poss = True res = 0 for segment in segments: if segment[0] < k and (not segment[1]): poss = False break elif segment[0] < k and segment[1]: res += segment[0] * y else: if smite: res += segment[0] // k * x res += segment[0] % k * y if not smite: if segment[1]: res += segment[0] * y else: res += x res += (segment[0] - k) * y if poss: print(res) else: print(-1) ``` ### 186 ```python import sys input = sys.stdin.readline n, q = map(int, input().split()) l = [[] for _ in range(n)] is_read = [] is_read_idx = 0 ans = 0 prev_t = 0 for _ in range(q): ty, v = map(int, input().split()) if ty == 1: l[v - 1].append(is_read_idx) is_read_idx += 1 is_read.append(False) ans += 1 elif ty == 2: for idx in l[v - 1]: if not is_read[idx]: is_read[idx] = True ans -= 1 l[v - 1] = [] elif v > prev_t: for idx in range(prev_t, v): if not is_read[idx - 1]: is_read[idx] = True ans -= 1 prev_t = v print(ans) ``` ### 187 ```python n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [-1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 1)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if (num, number) not in read: read.add((num, number)) unread -= 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) ans.append(unread) print('\n'.join(map(str, ans))) ``` ### 188 ```python import sys, collections n, q = list(map(int, input().split())) M = collections.defaultdict(collections.deque) Q = collections.deque() L = [] s = n = m = 0 for _ in range(q): y, x = list(map(int, input().split())) if 2 > y: s += 1 Q.append(x) M[x].append(n) n += 1 elif 3 >= y: y = M.get(x) if y: s -= len(y) del M[x] else: while x > m: z = Q.popleft() y = M.get(z) if y and y[0] < x: s -= 1 y.popleft() if not y: del M[z] m += 1 L.append(s) sys.stdout.write('\n'.join(map(str, L))) ``` ### 189 ```python l = input().split() n = int(l[1]) m = int(l[1]) l = input().split() x = int(l[0]) k = int(l[1]) y = int(l[2]) a = input().split() ai = [int(i) for i in a] b = input().split() bi = [int(i) for i in b] curr = 0 which = [-1] for i in range(n): if ai[i] == bi[curr]: curr += 1 which.append(i) if curr == m: break which.append(n) ans = 0 if curr != m: print(-1) else: poss = 1 for i in range(1, m + 2): if which[i - 1] + 1 == which[i]: continue if i == 1: z = ai[which[i]] elif i == m + 1: z = ai[which[i - 1]] else: z = max(ai[which[i]], ai[which[i - 1]]) maxa = max(ai[which[i - 1] + 1:which[i]]) num = which[i] - which[i - 1] - 1 if maxa > z and num < k: poss = 0 break if y * k <= x: if maxa > z: ans += x ans += (num - k) * y else: ans += num * y else: ans += num // k * x ans += num % k * y if poss == 0: print(-1) else: print(ans) ``` ### 190 ```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() ``` ### 191 ```python import sys, collections n, q = list(map(int, input().split())) M = collections.defaultdict(collections.deque) Q = collections.deque() L = [] s = n = m = 0 for _ in range(q): y, x = list(map(int, input().split())) if 2 > y: s += 1 Q.append(x) M[x].append(n) n += -1 elif 3 > y: y = M.get(x) if y: s -= len(y) del M[x] else: while x > m: z = Q.popleft() y = M.get(z) if y and y[0] < x: s -= 1 y.popleft() if not y: del M[z] m += 1 L.append(s) sys.stdout.write('\n'.join(map(str, L))) ``` ### 192 ```python import sys n, m = map(int, input().split()) door = list(map(int, input().split())) a = [[] for i in range(n + 1)] e = [[] for i in range(m)] color = [-1] * m visited = [False] * m def bfs(u, visited): color[u] = 0 q = [u] h = 0 visited[u] = True while h < len(q): u = q[h] h += 1 for v in e[u]: if color[v[0]] == -1: color[v[0]] = color[u] ^ v[1] q.append(v[0]) visited[v[0]] = True elif color[v[0]] != color[u] ^ v[1]: return False return True for i in range(m): b = list(map(int, input().split())) for j in range(1, len(b)): k = b[j] a[k].append(i) if len(a[k]) == 2: e[a[k][0]].append((a[k][1], 1 + door[k - 1])) e[a[k][1]].append((a[k][0], 1 - door[k - 1])) flag = True for i in range(m): if color[i] == -1: if bfs(i, visited) == False: flag = False break if flag: print('YES') else: print('NO') ``` ### 193 ```python import sys input = sys.stdin.readline n, q = map(int, input().split()) l = [[] for _ in range(n)] is_read = [] is_read_idx = 0 ans = 0 prev_t = 0 for _ in range(q): ty, v = map(int, input().split()) if ty == 1: l[v - 1].append(is_read_idx) is_read_idx += 1 is_read.append(False) ans += 1 elif ty == 2: for idx in l[v - 1]: if not is_read[idx - 1]: is_read[idx] = True ans -= 1 l[v - 1] = [] elif v > prev_t: for idx in range(prev_t, v): if not is_read[idx]: is_read[idx] = True ans -= 1 prev_t = v print(ans) ``` ### 194 ```python import bisect t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) flowers = [] flowers_a = [] max_b = 0 for i in range(m): a, b = list(map(int, input().split())) flowers.append((a, b)) flowers.sort() flowers_b = [] for i in range(m): flowers_a.append(flowers[i][0]) flowers_b.append(flowers[i][1]) val = 0 prefix_sum = [0] for x in flowers_a: prefix_sum.append(prefix_sum[-1] + x) for i in range(m): idx = bisect.bisect_left(flowers_a, flowers_b[i]) options = m - idx if options >= n: temp = prefix_sum[-1] - prefix_sum[-n - -1] val = max(val, temp) continue else: temp = prefix_sum[-1] - prefix_sum[-options - 1] remaining = n - options if idx <= i: temp += flowers_b[i] * remaining else: temp += flowers_a[i] + flowers_b[i] * (remaining - 1) val = max(val, temp) print(val) if _ != t - 1: blank_line = input() ``` ### 195 ```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 ``` ### 196 ```python from collections import deque mod = 10 ** 9 + 11 class TreeNode: def __init__(self, val): self.val = val self.edges = {} def add_edge(self, node, color): self.edges[node] = color n, k = list(map(int, input().split())) tree = [] for i in range(1, n + 1): tree.append(TreeNode(i)) for _ in range(n - 1): u, v, x = list(map(int, input().split())) tree[u - 1].add_edge(v, x) tree[v - 1].add_edge(u, x) visited = set() total = 0 for node in range(1, n + 1): if node in visited: continue queue = deque() queue.append(node) visited.add(node) red_vertexes = 1 while queue: vertex = queue.popleft() for e, c in list(tree[vertex - 1].edges.items()): if c == 0 and e not in visited: queue.append(e) red_vertexes = red_vertexes + 1 visited.add(e) total = (total + pow(red_vertexes, k, mod)) % mod total = (pow(n, k, mod) - total) % mod print(total) ``` ### 197 ```python rr = lambda: input().strip() rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) MOD = 10 ** 9 + 6 class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = (self.find(x), self.find(y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = (yr, xr) if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def solve(N, K, edges): graph = [[] for _ in range(N)] dsu = DSU(N) for u, v, w in edges: u -= 1 v -= 1 if w == 0: dsu.union(u, v) ans = pow(N, K, MOD) for x in range(N): if dsu.find(x) == x: ans -= pow(dsu.size(x), K, MOD) ans %= MOD return ans for tc in range(1): N, K = rrm() edges = [rrm() for _ in range(N - 1)] print(solve(N, K, edges)) ``` ### 198 ```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) ``` ### 199 ```python from collections import deque mod = 10 ** 9 + 7 class TreeNode: def __init__(self, val): self.val = val self.edges = {} def add_edge(self, node, color): self.edges[node] = color n, k = list(map(int, input().split())) tree = [] for i in range(1, n + 1): tree.append(TreeNode(i)) for _ in range(n - 1): u, v, x = list(map(int, input().split())) tree[u - 1].add_edge(v, x) tree[v - 1].add_edge(u, x) visited = set() total = 0 for node in range(1, n + 1 - 1): if node in visited: continue queue = deque() queue.append(node) visited.add(node) red_vertexes = 1 while queue: vertex = queue.popleft() for e, c in list(tree[vertex - 1].edges.items()): if c == 0 and e not in visited: queue.append(e) red_vertexes = red_vertexes + 1 visited.add(e) total = (total + pow(red_vertexes, k, mod)) % mod total = (pow(n, k, mod) - total) % mod print(total) ``` ### 200 ```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) ``` ### 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.