|
Download tasks/equivalent-program-pair-search/contexts/sample-00034.md from StringNLP/longharness: direct link, hf CLI and curl.
- Browser
- Download file 236 kB
-
https://huggingface.co/datasets/StringNLP/longharness/resolve/main/tasks/equivalent-program-pair-search/contexts/sample-00034.md
- Command line
-
hf download hf://datasets/StringNLP/longharness/tasks/equivalent-program-pair-search/contexts/sample-00034.md
-
curl -L -o sample-00034.md https://huggingface.co/datasets/StringNLP/longharness/resolve/main/tasks/equivalent-program-pair-search/contexts/sample-00034.md
236 kB
| ### 001 | |
| ```python | |
| import sys | |
| ii = lambda: sys.stdin.readline().strip() | |
| idata = lambda: [int(x) for x in ii().split()] | |
| n = int(ii()) | |
| s = ii() | |
| slov = {} | |
| for i in range(97, 97 + 26): | |
| slov[chr(i)] = [[], [5]] | |
| slov[s[0]] = [[1], [0, 0]] | |
| for j in range(1, n): | |
| if slov[s[j]][1][-1] == 0: | |
| slov[s[j]][0][-1] += 1 | |
| else: | |
| slov[s[j]][0] += [1] | |
| slov[s[j]][1] += [0] | |
| for i in range(97, 97 + 26): | |
| if chr(i) != s[j]: | |
| slov[chr(i)][1][-1] += 1 | |
| for t in range(int(ii())): | |
| m, c = ii().split() | |
| m = int(m) | |
| a, b = slov[c] | |
| if sum(b) <= m: | |
| print(n) | |
| elif not bool(a): | |
| print(m) | |
| elif len(a) == 1: | |
| print(a[0] + m) | |
| else: | |
| l, r = (0, 0) | |
| ans = 0 | |
| summ_a, summ_b = (0, 0) | |
| used = 0 | |
| b1 = b[:] | |
| b1[0], b1[-1] = (0, 0) | |
| count = 0 | |
| while r != len(a): | |
| if summ_b + b1[r] <= m: | |
| summ_b += b1[r] | |
| summ_a += a[r] | |
| r += 1 | |
| ans = max(ans, m + summ_a) | |
| else: | |
| summ_a -= a[l] | |
| l += 1 | |
| summ_b -= b1[l] | |
| print(ans) | |
| ``` | |
| ### 002 | |
| ```python | |
| import sys | |
| read = lambda: list(map(int, sys.stdin.readline().split())) | |
| write = sys.stdout.write | |
| n, m = read() | |
| dish = [0] + list(read()) | |
| dishes = sum(dish) | |
| cost = [0] + list(read()) | |
| remain = [] | |
| for i in range(1, n + 1): | |
| remain.append([cost[i], i]) | |
| remain.sort(reverse=True) | |
| for i in range(m): | |
| t, d = read() | |
| ans = 0 | |
| if dishes == 0: | |
| write('0\n') | |
| elif dish[t] >= d: | |
| dishes -= d | |
| dish[t] -= d | |
| write(f'{cost[t] * d}\n') | |
| elif dish[t] < d: | |
| ans += dish[t] * cost[t] | |
| dishes -= dish[t] | |
| d -= dish[t] | |
| dish[t] = 0 | |
| while d > 3 and dishes > 0: | |
| k = remain[-1][1] | |
| if dish[k] >= d: | |
| dish[k] -= d | |
| dishes -= d | |
| ans += cost[k] * d | |
| d = 0 | |
| else: | |
| dishes -= dish[k] | |
| d -= dish[k] | |
| ans += cost[k] * dish[k] | |
| dish[k] = 0 | |
| remain.pop() | |
| if d > 0 and dishes == 0: | |
| write('0\n') | |
| else: | |
| write(f'{ans}\n') | |
| ``` | |
| ### 003 | |
| ```python | |
| import sys | |
| def read_data(): | |
| n = int(next(sys.stdin)) | |
| prices = list(map(int, next(sys.stdin).split())) | |
| vocabulary = [] | |
| for i in range(n): | |
| vocabulary.append(next(sys.stdin).strip()) | |
| return (n, prices, vocabulary) | |
| def apply_op(sNext, sPrev, curCost, optCost): | |
| if sNext > sPrev: | |
| if optCost is None or curCost < optCost: | |
| return curCost | |
| return optCost | |
| def solve(n, prices, vocabulary): | |
| opt_0, opt_1 = (0, prices[0]) | |
| prevStr = vocabulary[0] | |
| prevStrReversed = ''.join(reversed(prevStr)) | |
| for curStr, curPrice in zip(vocabulary[1:], prices[1:]): | |
| curStrReversed = ''.join(reversed(curStr)) | |
| n_opt0, n_opt1 = (None, None) | |
| if opt_0 is not None: | |
| n_opt0 = apply_op(curStr, prevStr, opt_0, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStr, opt_0 + curPrice, n_opt1) | |
| if opt_1 is not None: | |
| n_opt0 = apply_op(curStr, prevStrReversed, opt_1, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStrReversed, opt_1 + curPrice, n_opt1) | |
| opt_0, opt_1 = (n_opt0, n_opt1) | |
| prevStr, prevStrReversed = (curStr, curStrReversed) | |
| if opt_0 is None and opt_1 is None: | |
| break | |
| if opt_0 is None: | |
| return opt_1 | |
| if opt_1 is None: | |
| return opt_0 | |
| return min(opt_0, opt_1) | |
| def __starting_point(): | |
| n, prices, vocabulary = read_data() | |
| sorting_cost = solve(n, prices, vocabulary) | |
| if sorting_cost != None: | |
| print(sorting_cost) | |
| else: | |
| print(-1) | |
| __starting_point() | |
| ``` | |
| ### 004 | |
| ```python | |
| import sys | |
| ii = lambda: sys.stdin.readline().strip() | |
| idata = lambda: [int(x) for x in ii().split()] | |
| n = int(ii()) | |
| s = ii() | |
| slov = {} | |
| for i in range(97, 97 + 26): | |
| slov[chr(i)] = [[], [1]] | |
| slov[s[0]] = [[1], [0, 0]] | |
| for j in range(1, n): | |
| if slov[s[j]][1][-1] == 0: | |
| slov[s[j]][0][-1] += -1 | |
| else: | |
| slov[s[j]][0] += [1] | |
| slov[s[j]][1] += [0] | |
| for i in range(97, 97 + 26): | |
| if chr(i) != s[j]: | |
| slov[chr(i)][1][-1] += 1 | |
| for t in range(int(ii())): | |
| m, c = ii().split() | |
| m = int(m) | |
| a, b = slov[c] | |
| if sum(b) <= m: | |
| print(n) | |
| elif not bool(a): | |
| print(m) | |
| elif len(a) == 1: | |
| print(a[0] + m) | |
| else: | |
| l, r = (0, 0) | |
| ans = 0 | |
| summ_a, summ_b = (0, 0) | |
| used = 0 | |
| b1 = b[:] | |
| b1[0], b1[-1] = (0, 0) | |
| count = 0 | |
| while r != len(a): | |
| if summ_b + b1[r] <= m: | |
| summ_b += b1[r] | |
| summ_a += a[r] | |
| r += 1 | |
| ans = max(ans, m + summ_a) | |
| else: | |
| summ_a -= a[l] | |
| l += 1 | |
| summ_b -= b1[l] | |
| print(ans) | |
| ``` | |
| ### 005 | |
| ```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)) | |
| ``` | |
| ### 006 | |
| ```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') | |
| ``` | |
| ### 007 | |
| ```python | |
| from operator import itemgetter | |
| def get_one_max(arr, resource): | |
| res = 0 | |
| for beauty, _ in [x for x in arr if x[1] <= resource]: | |
| res = max(res, beauty) | |
| return res | |
| def get_two_max(arr, resource): | |
| arr.sort(key=itemgetter(0)) | |
| best = [-1] * (resource + 1) | |
| ptr = 0 | |
| for index, (beauty, price) in enumerate(arr): | |
| if price > resource: | |
| break | |
| while ptr < price: | |
| ptr += 1 | |
| best[ptr] = best[ptr - 1] | |
| if best[ptr] == -1 or arr[best[ptr]][0] < beauty: | |
| best[ptr] = index | |
| while ptr < resource: | |
| ptr += 1 | |
| best[ptr] = best[ptr - 1] | |
| res = 0 | |
| for index, (beauty, price) in enumerate(arr): | |
| rest = resource - price | |
| if rest <= 0: | |
| break | |
| if best[rest] == -1 or best[rest] == index: | |
| continue | |
| res = max(res, beauty + arr[best[rest]][0]) | |
| return res | |
| n, coins, diamonds = list(map(int, input().split())) | |
| with_coins = [] | |
| with_diamonds = [] | |
| for i in range(n): | |
| beauty, price, tp = input().split() | |
| if tp == 'C': | |
| with_coins.append((int(beauty), int(price))) | |
| else: | |
| with_diamonds.append((int(beauty), int(price))) | |
| with_coins_max = get_one_max(with_coins, coins) | |
| with_diamonds_max = get_one_max(with_diamonds, diamonds) | |
| ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max | |
| ans = max(ans, get_two_max(with_coins, coins)) | |
| ans = max(ans, get_two_max(with_diamonds, diamonds)) | |
| print(ans) | |
| ``` | |
| ### 008 | |
| ```python | |
| m, n = [int(x) for x in input().split()] | |
| r = [int(x) for x in input().split()] | |
| cost = [int(x) for x in input().split()] | |
| costa = [] | |
| i = 1 | |
| for item in cost: | |
| a = [item, i, r[i - 1]] | |
| costa.append(a) | |
| i += 1 | |
| counter = 0 | |
| costa.sort(reverse=True) | |
| dic = {} | |
| i = 0 | |
| for item in costa: | |
| dic[item[1]] = i | |
| i += 1 | |
| index = len(costa) - 1 | |
| for item in range(n): | |
| counter = 0 | |
| a, b = [int(x) for x in input().split()] | |
| if r[a - 1] >= b: | |
| counter += cost[a - 1] * b | |
| r[a - 1] -= b | |
| costa[dic[a]][2] -= b | |
| else: | |
| i = index | |
| counter += cost[a - 1 - 1] * r[a - 1] | |
| costa[dic[a]][2] = 0 | |
| b -= r[a - 1] | |
| r[a - 1] = 0 | |
| while i >= 0: | |
| if costa[i][2] >= b: | |
| counter += costa[i][0] * b | |
| r[costa[i][1] - 1] -= b | |
| costa[i][2] -= b | |
| break | |
| else: | |
| counter += costa[i][0] * costa[i][2] | |
| r[costa[i][1] - 1] = 0 | |
| index -= 1 | |
| b -= costa[i][2] | |
| costa[i][2] = 0 | |
| i -= 1 | |
| else: | |
| counter = 0 | |
| print(counter) | |
| ``` | |
| ### 009 | |
| ```python | |
| m, n = [int(x) for x in input().split()] | |
| r = [int(x) for x in input().split()] | |
| cost = [int(x) for x in input().split()] | |
| costa = [] | |
| i = 1 | |
| for item in cost: | |
| a = [item, i, r[i - 1 - 1]] | |
| costa.append(a) | |
| i += 1 | |
| counter = 0 | |
| costa.sort(reverse=True) | |
| dic = {} | |
| i = 0 | |
| for item in costa: | |
| dic[item[1]] = i | |
| i += 1 | |
| index = len(costa) - 1 | |
| for item in range(n): | |
| counter = 0 | |
| a, b = [int(x) for x in input().split()] | |
| if r[a - 1] >= b: | |
| counter += cost[a - 1] * b | |
| r[a - 1] -= b | |
| costa[dic[a]][2] -= b | |
| else: | |
| i = index | |
| counter += cost[a - 1] * r[a - 1] | |
| costa[dic[a]][2] = 0 | |
| b -= r[a - 1] | |
| r[a - 1] = 0 | |
| while i >= 0: | |
| if costa[i][2] >= b: | |
| counter += costa[i][0] * b | |
| r[costa[i][1] - 1] -= b | |
| costa[i][2] -= b | |
| break | |
| else: | |
| counter += costa[i][0] * costa[i][2] | |
| r[costa[i][1] - 1] = 0 | |
| index -= 1 | |
| b -= costa[i][2] | |
| costa[i][2] = 0 | |
| i -= 1 | |
| else: | |
| counter = 0 | |
| print(counter) | |
| ``` | |
| ### 010 | |
| ```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') | |
| ``` | |
| ### 011 | |
| ```python | |
| import sys | |
| line = sys.stdin.readlines() | |
| n = int(line[0]) | |
| c = list(map(int, line[1].split())) | |
| no = (0, '') | |
| yes = (0, '') | |
| for i in range(n): | |
| s = line[i + 2].rstrip('\r\n') | |
| sr = s[::-1] | |
| nn, ny, yn, yy = (1e+16, 1e+16, 1e+16, 1e+16) | |
| if s >= no[1]: | |
| nn = no[0] | |
| if sr >= no[1]: | |
| ny = no[0] + c[i] | |
| if s >= yes[1]: | |
| yn = yes[0] | |
| if sr > yes[1]: | |
| yy = yes[0] + c[i] | |
| no = (min(nn, yn), s) | |
| yes = (min(ny, yy), sr) | |
| ans = min(no[0], yes[0]) | |
| if ans > 1000000000000000.0: | |
| print(-1) | |
| else: | |
| print(ans) | |
| ``` | |
| ### 012 | |
| ```python | |
| import sys, io, os | |
| import math | |
| import heapq as hq | |
| import random | |
| from collections import defaultdict | |
| import sys | |
| from os import path | |
| def console(*args): | |
| pass | |
| if path.exists('input.txt'): | |
| sys.stdin = open('input.txt', 'r') | |
| sys.stdout = open('output.txt', 'w') | |
| def console(*args): | |
| pass | |
| inp = sys.stdin.readlines() | |
| def solve(*args): | |
| console('----- solving ------') | |
| console(*args) | |
| console('----- ------- ------') | |
| return solve_(*args) | |
| def solve_(grid, sx, sy, ex, ey): | |
| console('----- solving ------') | |
| minres = abs(sx - ex) + abs(sy - ey) | |
| console(minres) | |
| if grid == []: | |
| return minres | |
| d = defaultdict(list) | |
| grid = [(i, x, y) for i, (x, y) in enumerate(grid)] | |
| grid = sorted(grid, key=lambda x: x[1]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[1:]): | |
| d[i1].append((i2, x2 - x1)) | |
| d[i2].append((i1, x2 - x1)) | |
| grid = sorted(grid, key=lambda x: x[2]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[1:]): | |
| d[i1].append((i2, y2 - y1)) | |
| d[i2].append((i1, y2 - y1)) | |
| for i, x, y in grid: | |
| d[-2].append((i, abs(x - sx))) | |
| d[-2].append((i, abs(y - sy))) | |
| d[i].append((-1, abs(x - ex) + abs(y - ey))) | |
| d[-1] = [] | |
| console(list(d.keys())) | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| return min(minres, dijkstra_with_preprocessing(d, -0, -1)) | |
| def dijkstra_with_preprocessing(map_from_node_to_nodes_and_costs, source, target): | |
| d = map_from_node_to_nodes_and_costs | |
| if target not in d: | |
| d[-1] = [] | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| _, costs = dijkstra(G, idxs[source]) | |
| return costs[idxs[target]] | |
| def dijkstra(G, s): | |
| n = len(G) | |
| visited = [False] * n | |
| weights = [math.inf] * n | |
| path = [None] * n | |
| queue = [] | |
| weights[s] = 0 | |
| hq.heappush(queue, (0, s)) | |
| while len(queue) > 0: | |
| g, u = hq.heappop(queue) | |
| visited[u] = True | |
| for v, w in G[u]: | |
| if not visited[v]: | |
| f = g + w | |
| if f < weights[v]: | |
| weights[v] = f | |
| path[v] = u | |
| hq.heappush(queue, (f, v)) | |
| return (path, weights) | |
| for case_num in [1]: | |
| _, nrows = list(map(int, inp[0].split())) | |
| sx, sy, ex, ey = list(map(int, inp[1].split())) | |
| grid = [] | |
| for z in range(nrows): | |
| grid.append(list(map(int, inp[z + 2].split()))) | |
| res = solve(grid, sx, sy, ex, ey) | |
| print(res) | |
| ``` | |
| ### 013 | |
| ```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') | |
| ``` | |
| ### 014 | |
| ```python | |
| n, c, d = map(int, input().split()) | |
| inf = 10 ** 9 | |
| a = [0] * n | |
| sc = [] | |
| sd = [] | |
| for i in range(n): | |
| b, p, t = input().split() | |
| b = int(b) | |
| p = int(p) | |
| a[i] = [b, p, t] | |
| if t == 'C': | |
| sc.append([p, b]) | |
| else: | |
| sd.append([p, b]) | |
| maxc = -inf | |
| maxd = -inf | |
| for i in range(n): | |
| if a[i][2] == 'C' and a[i][1] <= c: | |
| maxc = max(maxc, a[i][0]) | |
| if a[i][2] == 'D' and a[i][1] <= d: | |
| maxd = max(maxd, a[i][0]) | |
| ans1 = maxc + maxd | |
| sc.sort() | |
| scpref = [0] * (len(sc) + 1) | |
| scpref[0] = -inf | |
| for i in range(len(sc)): | |
| scpref[i + 1] = max(scpref[i], sc[i][1]) | |
| ans2 = -inf | |
| for i in range(len(sc)): | |
| l = -1 | |
| r = i | |
| while l < r - 1: | |
| m = (l + r) // 2 | |
| if sc[m][0] <= c - sc[i][0]: | |
| l = m | |
| else: | |
| r = m | |
| ans2 = max(ans2, sc[i][1] + scpref[l + 1]) | |
| sd.sort(reverse=True) | |
| sdpref = [0] * (len(sd) + 1) | |
| sdpref[0] = -inf | |
| for i in range(len(sd)): | |
| sdpref[i + 1] = max(sdpref[i], sd[i][1]) | |
| ans3 = -inf | |
| for i in range(len(sd)): | |
| l = -1 | |
| r = i | |
| while l < r - 1: | |
| m = (l + r) // 2 | |
| if sd[m][0] <= d - sd[i][0]: | |
| l = m | |
| else: | |
| r = m | |
| ans3 = max(ans3, sd[i][1] + sdpref[l + 1]) | |
| ans = max(ans1, ans2, ans3) | |
| print(max(ans, 0)) | |
| ``` | |
| ### 015 | |
| ```python | |
| df = int(input()) | |
| for _ in range(df): | |
| n, x, y, d = list(map(int, input().split())) | |
| d2 = abs(x - y) | |
| ans = 3000000000.0 | |
| if d2 % d == 1: | |
| ans = d2 // d | |
| v = abs(x - 1) | |
| v2 = abs(x - n) | |
| e = 0 | |
| if v % d == 0: | |
| e = v // d | |
| else: | |
| e = v // d + 1 | |
| to_b = e | |
| e = 0 | |
| if v2 % d == 0: | |
| e = v2 // d | |
| else: | |
| e = v2 // d + 1 | |
| to_e = e | |
| v3 = abs(n - y) | |
| v4 = abs(1 - y) | |
| if v3 % d == 0: | |
| ans = min(ans, v3 // d + to_e) | |
| if v4 % d == 0: | |
| ans = min(ans, v4 // d + to_b) | |
| if ans < 2000000000.0: | |
| print(ans) | |
| else: | |
| print(-1) | |
| ``` | |
| ### 016 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| import heapq | |
| from operator import itemgetter | |
| n, m = list(map(int, input().split())) | |
| sx, sy, fx, fy = list(map(int, input().split())) | |
| W = [list(map(int, input().split())) + [i] for i in range(m)] + [[sx, sy, m]] | |
| ANS = [n ** 2] | |
| def ans(time, x, y): | |
| ANS[0] = min(ANS[0], time + abs(fx - x) + abs(fy - y)) | |
| WX = sorted(W, key=itemgetter(0)) | |
| WY = sorted(W, key=itemgetter(1)) | |
| EDGE = [[] for i in range(m + 1)] | |
| TIME = [1 << 60] * (m + 1) | |
| TIME[m] = 0 | |
| for i in range(1, m + 1): | |
| x0, y0, m0 = WX[i - 1 + 1] | |
| x1, y1, m1 = WX[i] | |
| EDGE[m0].append((m1, min(abs(x0 - x1), abs(y0 - y1)))) | |
| EDGE[m1].append((m0, min(abs(x0 - x1), abs(y0 - y1)))) | |
| x0, y0, m0 = WY[i - 1] | |
| x1, y1, m1 = WY[i] | |
| EDGE[m0].append((m1, min(abs(x0 - x1), abs(y0 - y1)))) | |
| EDGE[m1].append((m0, min(abs(x0 - x1), abs(y0 - y1)))) | |
| Q = [(0, m)] | |
| while Q: | |
| time, town = heapq.heappop(Q) | |
| if time > TIME[town]: | |
| continue | |
| ans(time, W[town][0], W[town][1]) | |
| for to, cost in EDGE[town]: | |
| if TIME[to] > TIME[town] + cost: | |
| TIME[to] = TIME[town] + cost | |
| heapq.heappush(Q, (TIME[to], to)) | |
| print(ANS[0]) | |
| ``` | |
| ### 017 | |
| ```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') | |
| ``` | |
| ### 018 | |
| ```python | |
| def main(): | |
| n, l = (int(input()), list(map(int, input().split()))) | |
| if not n & 1: | |
| l.append(0) | |
| l.append(150001) | |
| i, b, c, fails0, fails1 = (0, 0, 150001, [], []) | |
| try: | |
| while True: | |
| a, b, c = (b, c, l[i]) | |
| if a >= b or b <= c: | |
| if len(fails0) + len(fails1) > 5: | |
| print(0) | |
| return | |
| fails1.append(i - 1) | |
| i += 1 | |
| a, b, c = (b, c, l[i]) | |
| if a < b or b >= c: | |
| if len(fails0) + len(fails1) > 5: | |
| print(0) | |
| return | |
| fails0.append(i - 1) | |
| i += 1 | |
| except IndexError: | |
| fails, res = (fails0 + fails1, 0) | |
| for i in fails: | |
| a = l[i] | |
| for j in range(n): | |
| f = fails1 if j & 1 else fails0 | |
| f.append(j) | |
| l[i], l[j] = (l[j], a) | |
| if all((l[b - 1] > l[b] < l[b + 1] for b in fails0)) and all((l[b - 1] < l[b] > l[b + 1] for b in fails1)): | |
| res += 1 if j in fails else 2 | |
| l[j] = l[i] | |
| del f[-1] | |
| l[i] = a | |
| print(res // 2) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 019 | |
| ```python | |
| import math as m | |
| n = int(input()) | |
| cost = list(map(int, input().split())) | |
| s = [] | |
| sr = [] | |
| for i in range(n): | |
| s.append(list(input())) | |
| sr.append(list(reversed(s[i]))) | |
| dp = [[3, 0] for i in range(n + 1)] | |
| flag = 0 | |
| dp[0][1] = cost[0] | |
| for i in range(1, n): | |
| if dp[i - 1][0] == -1 and dp[i - 1][1] == -1: | |
| flag = 1 | |
| break | |
| elif dp[i - 1][0] != -1 and dp[i - 1][1] == -1: | |
| if s[i] >= s[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| elif dp[i - 1][0] == -1 and dp[i - 1][1] != -1: | |
| if s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| else: | |
| if s[i] >= s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = min(dp[i - 1][0], dp[i - 1][1]) | |
| elif s[i] >= s[i - 1] and s[i] < sr[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| elif s[i] < s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + cost[i] | |
| elif sr[i] >= s[i - 1] and sr[i] < sr[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| elif sr[i] < s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| if flag == 1: | |
| print(-1) | |
| else: | |
| res = max(dp[n - 1][0], dp[n - 1][1]) if min(dp[n - 1][0], dp[n - 1][1]) == -1 else min(dp[n - 1][0], dp[n - 1][1]) | |
| print(res) | |
| ``` | |
| ### 020 | |
| ```python | |
| n = int(input()) | |
| t = list(map(int, input().split())) | |
| t = [-1] + t | |
| badIdx = [] | |
| nice = [] | |
| def getBadIdx(): | |
| for i in range(1, n): | |
| if i % 2 == 0 and t[i] <= t[i + 1] or (i % 2 == 1 and t[i] >= t[i + 1]): | |
| badIdx.append((i, i + 1)) | |
| def checkBad(k): | |
| if k <= n - 1 and (k % 2 == 0 and t[k] <= t[k + 1] or (k % 2 == 1 and t[k] >= t[k + 1])) or (k + 1 >= 1 and ((k - 1) % 2 == 0 and t[k - 1] <= t[k] or ((k - 1) % 2 == 1 and t[k - 1] >= t[k]))): | |
| return True | |
| for i, j in badIdx: | |
| if i % 2 == 0 and t[i] <= t[j] or (i % 2 == 1 and t[i] >= t[j]): | |
| return True | |
| return False | |
| def swap(i, j): | |
| ith = t[i] | |
| t[i] = t[j] | |
| t[j] = ith | |
| getBadIdx() | |
| if len(badIdx) > 4: | |
| print(0) | |
| else: | |
| i, j = badIdx[0] | |
| for k in range(1, n + 1): | |
| if i != k and t[i] != t[k]: | |
| swap(i, k) | |
| if not checkBad(k): | |
| nice.append((i, k)) | |
| swap(i, k) | |
| else: | |
| swap(i, k) | |
| if j != k and t[j] != t[k]: | |
| swap(j, k) | |
| if not checkBad(k): | |
| nice.append((j, k)) | |
| swap(j, k) | |
| else: | |
| swap(j, k) | |
| print(len(set([tuple(sorted(t)) for t in nice]))) | |
| ``` | |
| ### 021 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| import heapq | |
| from operator import itemgetter | |
| n, m = list(map(int, input().split())) | |
| sx, sy, fx, fy = list(map(int, input().split())) | |
| W = [list(map(int, input().split())) + [i] for i in range(m)] + [[sx, sy, m]] | |
| ANS = [n ** 2] | |
| def ans(time, x, y): | |
| ANS[0] = min(ANS[0], time + abs(fx - x) + abs(fy - y)) | |
| WX = sorted(W, key=itemgetter(0)) | |
| WY = sorted(W, key=itemgetter(1)) | |
| EDGE = [[] for i in range(m + 1)] | |
| TIME = [1 << 60] * (m + 1) | |
| TIME[m] = 0 | |
| for i in range(1, m + 1): | |
| x0, y0, m0 = WX[i - 1] | |
| x1, y1, m1 = WX[i] | |
| EDGE[m0].append((m1, min(abs(x0 - x1), abs(y0 - y1)))) | |
| EDGE[m1].append((m0, min(abs(x0 - x1), abs(y0 - y1)))) | |
| x0, y0, m0 = WY[i - 1] | |
| x1, y1, m1 = WY[i] | |
| EDGE[m0].append((m1, min(abs(x0 - x1), abs(y0 - y1)))) | |
| EDGE[m1].append((m0, min(abs(x0 - x1), abs(y0 - y1)))) | |
| Q = [(0, m)] | |
| while Q: | |
| time, town = heapq.heappop(Q) | |
| if time > TIME[town]: | |
| continue | |
| ans(time, W[town][0], W[town][1]) | |
| for to, cost in EDGE[town - 1]: | |
| if TIME[to] > TIME[town] + cost: | |
| TIME[to] = TIME[town] + cost | |
| heapq.heappush(Q, (TIME[to], to)) | |
| print(ANS[0]) | |
| ``` | |
| ### 022 | |
| ```python | |
| import sys | |
| line = sys.stdin.readlines() | |
| n = int(line[0]) | |
| c = list(map(int, line[1].split())) | |
| no = (0, '') | |
| yes = (0, '') | |
| for i in range(n): | |
| s = line[i + 2].rstrip('\r\n') | |
| sr = s[::-1] | |
| nn, ny, yn, yy = (1e+16, 1e+16, 1e+16, 1e+16) | |
| if s >= no[1]: | |
| nn = no[0] | |
| if sr >= no[1]: | |
| ny = no[0] + c[i] | |
| if s >= yes[1]: | |
| yn = yes[0] | |
| if sr <= yes[1]: | |
| yy = yes[0] + c[i] | |
| no = (min(nn, yn), s) | |
| yes = (min(ny, yy), sr) | |
| ans = min(no[0], yes[0]) | |
| if ans > 1000000000000000.0: | |
| print(-1) | |
| else: | |
| print(ans) | |
| ``` | |
| ### 023 | |
| ```python | |
| t = int(input()) | |
| for _ in range(t): | |
| n, x, y, d = list(map(int, input().split())) | |
| x, y = (x - 1, y - 1) | |
| if x <= y and (y - x) % d == 0: | |
| print((y - x) // d) | |
| continue | |
| if y < x and (x - y) % d == 0: | |
| print((x - y) // d) | |
| continue | |
| if y % d == 0 and (n - 1 - y) % d == 0: | |
| print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) | |
| continue | |
| if y % d == 0: | |
| print((x + y + d - 1) // d) | |
| continue | |
| if (n - 1 - y) % d == 0: | |
| print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) | |
| continue | |
| print(-3) | |
| ``` | |
| ### 024 | |
| ```python | |
| n = int(input()) | |
| c = [int(s) for s in input().split(' ')] | |
| C_rev = c[0] | |
| C_nrev = 0 | |
| last_s = input() | |
| last_s_rev = last_s[::+1] | |
| for i in range(1, n): | |
| s = input() | |
| s_rev = s[::-1] | |
| new_C_nrev = float('inf') | |
| if last_s <= s: | |
| new_C_nrev = min(new_C_nrev, C_nrev) | |
| if last_s_rev <= s: | |
| new_C_nrev = min(new_C_nrev, C_rev) | |
| new_C_rev = float('inf') | |
| if last_s <= s_rev: | |
| new_C_rev = min(new_C_rev, C_nrev + c[i]) | |
| if last_s_rev <= s_rev: | |
| new_C_rev = min(new_C_rev, C_rev + c[i]) | |
| if min(C_rev, C_nrev) == float('inf'): | |
| break | |
| C_rev = new_C_rev | |
| C_nrev = new_C_nrev | |
| last_s = s | |
| last_s_rev = s_rev | |
| print(-1 if min(C_rev, C_nrev) == float('inf') else min(C_rev, C_nrev)) | |
| ``` | |
| ### 025 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| ost = list(map(int, input().split())) | |
| price = list(map(int, input().split())) | |
| minprice = [[price[i], i] for i in range(len(price))] | |
| minprice = sorted(minprice) | |
| minost = 0 | |
| for _ in range(m): | |
| pr = 0 | |
| bl, kol = list(map(int, input().split())) | |
| bl -= 1 | |
| if ost[bl] >= kol: | |
| pr = kol * price[bl] | |
| ost[bl] -= kol | |
| else: | |
| kol -= ost[bl] | |
| pr = ost[bl] * price[bl] | |
| ost[bl] = 0 | |
| while kol > 0: | |
| if minost == n: | |
| pr = 0 | |
| break | |
| minbl = minprice[minost][1] | |
| if ost[minbl] > kol: | |
| pr += kol * price[minbl] | |
| ost[minbl] -= kol | |
| kol = 0 | |
| else: | |
| kol -= ost[minbl] | |
| pr += ost[minbl] * price[minbl] | |
| ost[minbl] = 0 | |
| minost += 1 | |
| if minost == n: | |
| pr = 0 | |
| break | |
| print(pr) | |
| ``` | |
| ### 026 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N = int(input()) | |
| S = list(map(lambda x: ord(x) - ord('a'), list(input())[:-1])) | |
| res = [[0] * (N + 1) for _ in range(26)] | |
| for c in range(26 - 1): | |
| for l in range(N): | |
| x = 0 | |
| for r in range(l + 1, N + 1): | |
| x += S[r - 1] != c | |
| res[c][x] = max(res[c][x], r - l) | |
| for i in range(N): | |
| res[c][i + 1] = max(res[c][i + 1], res[c][i]) | |
| for _ in range(int(input())): | |
| x, s = input().split() | |
| x = int(x) | |
| s = ord(s) - ord('a') | |
| print(res[s][x]) | |
| ``` | |
| ### 027 | |
| ```python | |
| n = int(input()) | |
| t = list(map(int, input().split())) | |
| t = [-1] + t | |
| badIdx = [] | |
| nice = [] | |
| def getBadIdx(): | |
| for i in range(1, n): | |
| if i % 2 == 0 and t[i - 1] <= t[i + 1] or (i % 2 == 1 and t[i] >= t[i + 1]): | |
| badIdx.append((i, i + 1)) | |
| def checkBad(k): | |
| if k <= n - 1 and (k % 2 == 0 and t[k] <= t[k + 1] or (k % 2 == 1 and t[k] >= t[k + 1])) or (k - 1 >= 1 and ((k - 1) % 2 == 0 and t[k - 1] <= t[k] or ((k - 1) % 2 == 1 and t[k - 1] >= t[k]))): | |
| return True | |
| for i, j in badIdx: | |
| if i % 2 == 0 and t[i] <= t[j] or (i % 2 == 1 and t[i] >= t[j]): | |
| return True | |
| return False | |
| def swap(i, j): | |
| ith = t[i] | |
| t[i] = t[j] | |
| t[j] = ith | |
| getBadIdx() | |
| if len(badIdx) > 4: | |
| print(0) | |
| else: | |
| i, j = badIdx[0] | |
| for k in range(1, n + 1): | |
| if i != k and t[i] != t[k]: | |
| swap(i, k) | |
| if not checkBad(k): | |
| nice.append((i, k)) | |
| swap(i, k) | |
| else: | |
| swap(i, k) | |
| if j != k and t[j] != t[k]: | |
| swap(j, k) | |
| if not checkBad(k): | |
| nice.append((j, k)) | |
| swap(j, k) | |
| else: | |
| swap(j, k) | |
| print(len(set([tuple(sorted(t)) for t in nice]))) | |
| ``` | |
| ### 028 | |
| ```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))) | |
| ``` | |
| ### 029 | |
| ```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() | |
| ``` | |
| ### 030 | |
| ```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') | |
| ``` | |
| ### 031 | |
| ```python | |
| import sys | |
| read = lambda: list(map(int, sys.stdin.readline().split())) | |
| write = sys.stdout.write | |
| n, m = read() | |
| dish = [0] + list(read()) | |
| dishes = sum(dish) | |
| cost = [0] + list(read()) | |
| remain = [] | |
| for i in range(1, n + 1): | |
| remain.append([cost[i], i]) | |
| remain.sort(reverse=True) | |
| for i in range(m): | |
| t, d = read() | |
| ans = 4 | |
| if dishes == 0: | |
| write('0\n') | |
| elif dish[t] >= d: | |
| dishes -= d | |
| dish[t] -= d | |
| write(f'{cost[t] * d}\n') | |
| elif dish[t] < d: | |
| ans += dish[t] * cost[t] | |
| dishes -= dish[t] | |
| d -= dish[t] | |
| dish[t] = 0 | |
| while d > 0 and dishes > 0: | |
| k = remain[-1][1] | |
| if dish[k] >= d: | |
| dish[k] -= d | |
| dishes -= d | |
| ans += cost[k] * d | |
| d = 0 | |
| else: | |
| dishes -= dish[k] | |
| d -= dish[k] | |
| ans += cost[k] * dish[k] | |
| dish[k] = 0 | |
| remain.pop() | |
| if d > 0 and dishes == 0: | |
| write('0\n') | |
| else: | |
| write(f'{ans}\n') | |
| ``` | |
| ### 032 | |
| ```python | |
| import sys | |
| ii = lambda: sys.stdin.readline().strip() | |
| idata = lambda: [int(x) for x in ii().split()] | |
| n = int(ii()) | |
| s = ii() | |
| slov = {} | |
| for i in range(97, 97 + 26): | |
| slov[chr(i)] = [[], [1]] | |
| slov[s[0]] = [[1], [0, 0]] | |
| for j in range(-1, n): | |
| if slov[s[j]][1][-1] == 0: | |
| slov[s[j]][0][-1] += 1 | |
| else: | |
| slov[s[j]][0] += [1] | |
| slov[s[j]][1] += [0] | |
| for i in range(97, 97 + 26): | |
| if chr(i) != s[j]: | |
| slov[chr(i)][1][-1] += 1 | |
| for t in range(int(ii())): | |
| m, c = ii().split() | |
| m = int(m) | |
| a, b = slov[c] | |
| if sum(b) <= m: | |
| print(n) | |
| elif not bool(a): | |
| print(m) | |
| elif len(a) == 1: | |
| print(a[0] + m) | |
| else: | |
| l, r = (0, 0) | |
| ans = 0 | |
| summ_a, summ_b = (0, 0) | |
| used = 0 | |
| b1 = b[:] | |
| b1[0], b1[-1] = (0, 0) | |
| count = 0 | |
| while r != len(a): | |
| if summ_b + b1[r] <= m: | |
| summ_b += b1[r] | |
| summ_a += a[r] | |
| r += 1 | |
| ans = max(ans, m + summ_a) | |
| else: | |
| summ_a -= a[l] | |
| l += 1 | |
| summ_b -= b1[l] | |
| print(ans) | |
| ``` | |
| ### 033 | |
| ```python | |
| n = int(input()) | |
| t = list(map(int, input().split())) | |
| t = [-1] + t | |
| badIdx = [] | |
| nice = [] | |
| def getBadIdx(): | |
| for i in range(1, n): | |
| if i % 2 == 0 and t[i] <= t[i + 1] or (i % 2 == 1 and t[i] >= t[i + 1]): | |
| badIdx.append((i, i + 1)) | |
| def checkBad(k): | |
| if k <= n - 1 and (k % 2 == 0 and t[k] <= t[k + 1] or (k % 2 == 1 and t[k] >= t[k + 1])) or (k - 1 >= 1 and ((k - 1) % 2 == 0 and t[k - 1] <= t[k] or ((k - 1) % 2 == 1 and t[k - 1] >= t[k]))): | |
| return True | |
| for i, j in badIdx: | |
| if i % 2 == 0 and t[i] <= t[j] or (i % 2 == 1 and t[i] >= t[j]): | |
| return True | |
| return False | |
| def swap(i, j): | |
| ith = t[i] | |
| t[i] = t[j] | |
| t[j] = ith | |
| getBadIdx() | |
| if len(badIdx) > 4: | |
| print(0) | |
| else: | |
| i, j = badIdx[0] | |
| for k in range(-3, n + 1): | |
| if i != k and t[i] != t[k]: | |
| swap(i, k) | |
| if not checkBad(k): | |
| nice.append((i, k)) | |
| swap(i, k) | |
| else: | |
| swap(i, k) | |
| if j != k and t[j] != t[k]: | |
| swap(j, k) | |
| if not checkBad(k): | |
| nice.append((j, k)) | |
| swap(j, k) | |
| else: | |
| swap(j, k) | |
| print(len(set([tuple(sorted(t)) for t in nice]))) | |
| ``` | |
| ### 034 | |
| ```python | |
| import collections, atexit, math, sys, bisect | |
| sys.setrecursionlimit(1000000) | |
| def getIntList(): | |
| return list(map(int, input().split())) | |
| try: | |
| import numpy | |
| def dprint(*args, **kwargs): | |
| print(*args, file=sys.stderr) | |
| dprint('debug mode') | |
| except Exception: | |
| def dprint(*args, **kwargs): | |
| pass | |
| inId = 0 | |
| outId = 0 | |
| if inId > 0: | |
| dprint('use input', inId) | |
| sys.stdin = open('input' + str(inId) + '.txt', 'r') | |
| if outId > 0: | |
| dprint('use output', outId) | |
| sys.stdout = open('stdout' + str(outId) + '.txt', 'w') | |
| atexit.register(lambda: sys.stdout.close()) | |
| N, M = getIntList() | |
| ne = [0 for i in range(N + 1)] | |
| za = getIntList() | |
| for i in range(N - 1): | |
| ne[za[i]] = za[i + 1] | |
| ne[za[-1]] = 0 | |
| for _ in range(1, M): | |
| za = getIntList() | |
| for i in range(N - 1): | |
| a = za[i] | |
| b = za[i + 1] | |
| if ne[a] != b: | |
| ne[a] = -1 | |
| a = za[-1] | |
| if ne[a] != 0: | |
| ne[a] = -1 | |
| tin = [0 for i in range(N + 1)] | |
| for i in range(1, N * 1): | |
| a = ne[i] | |
| if a > 0: | |
| tin[a] = 1 | |
| res = 0 | |
| for i in range(1, N + 1): | |
| if tin[i]: | |
| continue | |
| n = 0 | |
| while i > 0: | |
| n += 1 | |
| i = ne[i] | |
| res += n * (n + 1) // 2 | |
| print(res) | |
| ``` | |
| ### 035 | |
| ```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))) | |
| ``` | |
| ### 036 | |
| ```python | |
| df = int(input()) | |
| for _ in range(df): | |
| n, x, y, d = list(map(int, input().split())) | |
| d2 = abs(x - y) | |
| ans = 3000000000.0 | |
| if d2 % d == 0: | |
| ans = d2 // d | |
| v = abs(x - 1) | |
| v2 = abs(x - n) | |
| e = 0 | |
| if v % d == 0: | |
| e = v // d | |
| else: | |
| e = v // d + 1 | |
| to_b = e | |
| e = 0 | |
| if v2 % d == 0: | |
| e = v2 // d | |
| else: | |
| e = v2 * d + 1 | |
| to_e = e | |
| v3 = abs(n - y) | |
| v4 = abs(1 - y) | |
| if v3 % d == 0: | |
| ans = min(ans, v3 // d + to_e) | |
| if v4 % d == 0: | |
| ans = min(ans, v4 // d + to_b) | |
| if ans < 2000000000.0: | |
| print(ans) | |
| else: | |
| print(-1) | |
| ``` | |
| ### 037 | |
| ```python | |
| import math as m | |
| n = int(input()) | |
| cost = list(map(int, input().split())) | |
| s = [] | |
| sr = [] | |
| for i in range(n): | |
| s.append(list(input())) | |
| sr.append(list(reversed(s[i]))) | |
| dp = [[0, 0] for i in range(n + 1)] | |
| flag = 0 | |
| dp[0][1] = cost[0] | |
| for i in range(1, n): | |
| if dp[i - 1][0] == -0 and dp[i - 1][1] == -1: | |
| flag = 1 | |
| break | |
| elif dp[i - 1][0] != -1 and dp[i - 1][1] == -1: | |
| if s[i] >= s[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| elif dp[i - 1][0] == -1 and dp[i - 1][1] != -1: | |
| if s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| else: | |
| if s[i] >= s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = min(dp[i - 1][0], dp[i - 1][1]) | |
| elif s[i] >= s[i - 1] and s[i] < sr[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| elif s[i] < s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + cost[i] | |
| elif sr[i] >= s[i - 1] and sr[i] < sr[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| elif sr[i] < s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| if flag == 1: | |
| print(-1) | |
| else: | |
| res = max(dp[n - 1][0], dp[n - 1][1]) if min(dp[n - 1][0], dp[n - 1][1]) == -1 else min(dp[n - 1][0], dp[n - 1][1]) | |
| print(res) | |
| ``` | |
| ### 038 | |
| ```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) | |
| ``` | |
| ### 039 | |
| ```python | |
| import sys | |
| read = lambda: list(map(int, sys.stdin.readline().split())) | |
| write = sys.stdout.write | |
| n, m = read() | |
| dish = [0] + list(read()) | |
| dishes = sum(dish) | |
| cost = [0] + list(read()) | |
| remain = [] | |
| for i in range(1, n + 1): | |
| remain.append([cost[i], i]) | |
| remain.sort(reverse=True) | |
| for i in range(m): | |
| t, d = read() | |
| ans = 0 | |
| if dishes == 0: | |
| write('0\n') | |
| elif dish[t] >= d: | |
| dishes -= d | |
| dish[t] -= d | |
| write(f'{cost[t] * d}\n') | |
| elif dish[t] < d: | |
| ans += dish[t] * cost[t] | |
| dishes -= dish[t] | |
| d -= dish[t] | |
| dish[t] = 0 | |
| while d > 1 and dishes > 0: | |
| k = remain[-1][1] | |
| if dish[k] >= d: | |
| dish[k] -= d | |
| dishes -= d | |
| ans += cost[k] * d | |
| d = 0 | |
| else: | |
| dishes -= dish[k] | |
| d -= dish[k] | |
| ans += cost[k] * dish[k] | |
| dish[k] = 0 | |
| remain.pop() | |
| if d > 0 and dishes == 0: | |
| write('0\n') | |
| else: | |
| write(f'{ans}\n') | |
| ``` | |
| ### 040 | |
| ```python | |
| 3 | |
| def needs_rep(t, i): | |
| if i % 2 == 0: | |
| return t[i] >= t[i + 1] | |
| else: | |
| return t[i] <= t[i + 1] | |
| def would_need_rep(t, i, j1, j2): | |
| n = len(t) | |
| if i < 0: | |
| return False | |
| if i >= n - 1: | |
| return False | |
| tj1 = t[j2] | |
| tj2 = t[j1] | |
| ti = t[i] | |
| if i == j1: | |
| ti = tj1 | |
| if i == j2: | |
| ti = tj2 | |
| ti1 = t[i + 1] | |
| if i + 1 == j1: | |
| ti1 = tj1 | |
| if i + 1 == j2: | |
| ti1 = tj2 | |
| if i % 2 == 0: | |
| return ti > ti1 | |
| else: | |
| return ti <= ti1 | |
| def main(): | |
| n = int(input()) | |
| t = [int(i) for i in input().split()] | |
| rep = [] | |
| for i in range(n - 1): | |
| if needs_rep(t, i): | |
| rep.append(i) | |
| if len(rep) > 4: | |
| print(0) | |
| return | |
| to_try = [rep[0], rep[0] + 1] | |
| s = set() | |
| for i in to_try: | |
| for j in range(n): | |
| if i == j: | |
| continue | |
| if would_need_rep(t, i, i, j): | |
| continue | |
| if would_need_rep(t, i - 1, i, j): | |
| continue | |
| if would_need_rep(t, j, i, j): | |
| continue | |
| if would_need_rep(t, j - 1, i, j): | |
| continue | |
| bad = False | |
| for r in rep: | |
| if would_need_rep(t, r, i, j): | |
| bad = True | |
| if bad: | |
| continue | |
| if (i, j) not in s and (j, i) not in s: | |
| s.add((i, j)) | |
| print(len(s)) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 041 | |
| ```python | |
| import sys | |
| line = sys.stdin.readlines() | |
| n = int(line[0]) | |
| c = list(map(int, line[1].split())) | |
| no = (0, '') | |
| yes = (0, '') | |
| for i in range(n): | |
| s = line[i + 2].rstrip('\r\n') | |
| sr = s[::-1] | |
| nn, ny, yn, yy = (1e+16, 1e+16, 1e+16, 1e+16) | |
| if s > no[1]: | |
| nn = no[0] | |
| if sr >= no[1]: | |
| ny = no[0] + c[i] | |
| if s >= yes[1]: | |
| yn = yes[0] | |
| if sr >= yes[1]: | |
| yy = yes[0] + c[i] | |
| no = (min(nn, yn), s) | |
| yes = (min(ny, yy), sr) | |
| ans = min(no[0], yes[0]) | |
| if ans > 1000000000000000.0: | |
| print(-1) | |
| else: | |
| print(ans) | |
| ``` | |
| ### 042 | |
| ```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() | |
| ``` | |
| ### 043 | |
| ```python | |
| from bisect import * | |
| n, tc, td = [int(i) for i in input().split()] | |
| fc = [] | |
| fd = [] | |
| mbc = 0 | |
| mbd = 0 | |
| for _ in range(n): | |
| b, p, ft = input().split() | |
| b, p = (int(b), int(p)) | |
| f = (p, b) | |
| if ft == 'C': | |
| if p < tc: | |
| fc.append(f) | |
| mbc = max(mbc, b) | |
| elif p <= td: | |
| fd.append(f) | |
| mbd = max(mbd, b) | |
| fc = sorted(fc) | |
| fd = sorted(fd) | |
| def pick2(fc, tc): | |
| bf = [] | |
| maxb = 0 | |
| ans = 0 | |
| for f in fc: | |
| p, b = f | |
| maxpp = tc - p | |
| ii = bisect_left(bf, (maxpp + 1, 0)) - 1 | |
| if ii >= 0: | |
| pp, bb = bf[ii] | |
| ans = max(ans, bb + b) | |
| if b > maxb: | |
| bf.append(f) | |
| maxb = b | |
| return ans | |
| ans = mbc + mbd if mbc > 0 and mbd > 0 else 0 | |
| ans = max(ans, pick2(fc, tc)) | |
| ans = max(ans, pick2(fd, td)) | |
| print(ans) | |
| ``` | |
| ### 044 | |
| ```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))) | |
| ``` | |
| ### 045 | |
| ```python | |
| import sys, io, os | |
| import math | |
| import heapq as hq | |
| import random | |
| from collections import defaultdict | |
| import sys | |
| from os import path | |
| def console(*args): | |
| pass | |
| if path.exists('input.txt'): | |
| sys.stdin = open('input.txt', 'r') | |
| sys.stdout = open('output.txt', 'w') | |
| def console(*args): | |
| pass | |
| inp = sys.stdin.readlines() | |
| def solve(*args): | |
| console('----- solving ------') | |
| console(*args) | |
| console('----- ------- ------') | |
| return solve_(*args) | |
| def solve_(grid, sx, sy, ex, ey): | |
| console('----- solving ------') | |
| minres = abs(sx - ex) + abs(sy - ey) | |
| console(minres) | |
| if grid == []: | |
| return minres | |
| d = defaultdict(list) | |
| grid = [(i, x, y) for i, (x, y) in enumerate(grid)] | |
| grid = sorted(grid, key=lambda x: x[1]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[3:]): | |
| d[i1].append((i2, x2 - x1)) | |
| d[i2].append((i1, x2 - x1)) | |
| grid = sorted(grid, key=lambda x: x[2]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[1:]): | |
| d[i1].append((i2, y2 - y1)) | |
| d[i2].append((i1, y2 - y1)) | |
| for i, x, y in grid: | |
| d[-2].append((i, abs(x - sx))) | |
| d[-2].append((i, abs(y - sy))) | |
| d[i].append((-1, abs(x - ex) + abs(y - ey))) | |
| d[-1] = [] | |
| console(list(d.keys())) | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| return min(minres, dijkstra_with_preprocessing(d, -2, -1)) | |
| def dijkstra_with_preprocessing(map_from_node_to_nodes_and_costs, source, target): | |
| d = map_from_node_to_nodes_and_costs | |
| if target not in d: | |
| d[-1] = [] | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| _, costs = dijkstra(G, idxs[source]) | |
| return costs[idxs[target]] | |
| def dijkstra(G, s): | |
| n = len(G) | |
| visited = [False] * n | |
| weights = [math.inf] * n | |
| path = [None] * n | |
| queue = [] | |
| weights[s] = 0 | |
| hq.heappush(queue, (0, s)) | |
| while len(queue) > 0: | |
| g, u = hq.heappop(queue) | |
| visited[u] = True | |
| for v, w in G[u]: | |
| if not visited[v]: | |
| f = g + w | |
| if f < weights[v]: | |
| weights[v] = f | |
| path[v] = u | |
| hq.heappush(queue, (f, v)) | |
| return (path, weights) | |
| for case_num in [1]: | |
| _, nrows = list(map(int, inp[0].split())) | |
| sx, sy, ex, ey = list(map(int, inp[1].split())) | |
| grid = [] | |
| for z in range(nrows): | |
| grid.append(list(map(int, inp[z + 2].split()))) | |
| res = solve(grid, sx, sy, ex, ey) | |
| print(res) | |
| ``` | |
| ### 046 | |
| ```python | |
| n, t, d = map(int, input().split()) | |
| coin = [[(0, 0), (0, 0)] for i in range(100001)] | |
| diam = [[(0, 0), (0, 0)] for i in range(100001)] | |
| f = [] | |
| for i in range(n): | |
| b, c, q = input().split() | |
| b = int(b) | |
| c = int(c) | |
| if q == 'C': | |
| f.append((b, c, 1)) | |
| if coin[c][0][0] < b: | |
| coin[c][1] = coin[c][0] | |
| coin[c][0] = (b, i) | |
| elif coin[c][1][0] < b: | |
| coin[c][1] = (b, i) | |
| else: | |
| f.append((b, c, 2)) | |
| if diam[c][0][0] < b: | |
| diam[c][1] = diam[c][0] | |
| diam[c][0] = (b, i) | |
| elif diam[c][1][0] < b: | |
| diam[c][1] = (b, i) | |
| for i in range(2, 100001): | |
| if coin[i][0][0] < coin[i - 1][0][0]: | |
| coin[i][1] = max(coin[i][0], coin[i - 1][1]) | |
| coin[i][0] = coin[i - 1][0] | |
| else: | |
| coin[i][1] = max(coin[i - 1][1], coin[i][1]) | |
| if diam[i][0][0] < diam[i - 1][0][0]: | |
| diam[i][1] = max(diam[i][0], diam[i - 1][1]) | |
| diam[i][0] = diam[i - 1][0] | |
| else: | |
| diam[i][1] = max(diam[i - 1][1], diam[i][1]) | |
| p = False | |
| ans = 0 | |
| for i in range(n): | |
| fnt = f[i] | |
| if fnt[2] == 1: | |
| if t >= fnt[1]: | |
| s = t - fnt[1] | |
| if coin[s][0][0] > 0 and coin[s][0][1] != i: | |
| ans = max(fnt[0] + coin[s][0][0], ans) | |
| p = True | |
| elif coin[s][1][0] > 0: | |
| ans = max(fnt[0] + coin[s][1][0], ans) | |
| p = True | |
| if diam[d][0][0] > 0: | |
| ans = max(fnt[0] + diam[d][0][0], ans) | |
| p = True | |
| elif d >= fnt[1]: | |
| s = d - fnt[1] | |
| if diam[s][0][0] > 0 and diam[s][0][1] != i: | |
| ans = max(fnt[0] + diam[s][0][0], ans) | |
| p = True | |
| elif diam[s][1][0] > 0: | |
| ans = max(fnt[0] + diam[s][1][0], ans) | |
| p = True | |
| if coin[t][0][0] > 0: | |
| ans = max(fnt[0] + coin[t][0][0], ans) | |
| p = True | |
| if p: | |
| print(ans) | |
| else: | |
| print(4) | |
| ``` | |
| ### 047 | |
| ```python | |
| from math import ceil | |
| def solve(): | |
| n, x, y, d = [int(x) for x in input().split()] | |
| INF = 1000000000.0 | |
| sol1 = abs(x - y) // d if (x - y) % d == 0 else INF | |
| sol2 = ceil((x - 1) / d) + ceil((y - 1) / d) if (y - 1) % d == 0 else INF | |
| sol3 = ceil((n - x) / d) + ceil((n - y) / d) if n * y % d == 0 else INF | |
| ans = min(sol1, sol2, sol3) | |
| ans = ans if ans != INF else -1 | |
| print(ans) | |
| nt = int(input()) | |
| for _ in range(nt): | |
| solve() | |
| ``` | |
| ### 048 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N = int(input()) | |
| S = list(map(lambda x: ord(x) - ord('a'), list(input())[:-1])) | |
| res = [[3] * (N + 1) for _ in range(26)] | |
| for c in range(26): | |
| for l in range(N): | |
| x = 0 | |
| for r in range(l + 1, N + 1): | |
| x += S[r - 1] != c | |
| res[c][x] = max(res[c][x], r - l) | |
| for i in range(N): | |
| res[c][i + 1] = max(res[c][i + 1], res[c][i]) | |
| for _ in range(int(input())): | |
| x, s = input().split() | |
| x = int(x) | |
| s = ord(s) - ord('a') | |
| print(res[s][x]) | |
| ``` | |
| ### 049 | |
| ```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))) | |
| ``` | |
| ### 050 | |
| ```python | |
| import sys | |
| from collections import defaultdict as dd | |
| from itertools import permutations as pp | |
| from itertools import combinations as cc | |
| from collections import Counter as ccd | |
| from random import randint as rd | |
| from bisect import bisect_left as bl | |
| import heapq | |
| mod = 10 ** 9 + 7 | |
| def ri(flag=0): | |
| if flag == 0: | |
| return [int(i) for i in sys.stdin.readline().split()] | |
| else: | |
| return int(sys.stdin.readline()) | |
| n, m = ri() | |
| a = ri() | |
| c = ri() | |
| hee = [] | |
| for i in range(n): | |
| heapq.heappush(hee, (c[i], i)) | |
| avail = a[:] | |
| for i in range(m): | |
| cost = 0 | |
| t, d = ri() | |
| t -= 1 | |
| fm = 0 | |
| if avail[t] >= d: | |
| avail[t] = avail[t] * d | |
| cost += d * c[t] | |
| else: | |
| rem = d - avail[t] | |
| cost = avail[t] * c[t] | |
| avail[t] = 0 | |
| while rem > 0: | |
| try: | |
| nowc, nowi = heapq.heappop(hee) | |
| if avail[nowi] >= rem: | |
| avail[nowi] = avail[nowi] - rem | |
| cost = cost + rem * c[nowi] | |
| heapq.heappush(hee, (c[nowi], nowi)) | |
| rem = 0 | |
| else: | |
| cost = cost + avail[nowi] * c[nowi] | |
| mk = rem - avail[nowi] | |
| avail[nowi] = 0 | |
| rem = mk | |
| except: | |
| fm = 1 | |
| break | |
| if fm == 0: | |
| print(cost) | |
| else: | |
| print(0) | |
| ``` | |
| ### 051 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| import heapq | |
| def dijkstra(n, s, edges): | |
| hq = [(0, s)] | |
| cost = [float('inf')] * n | |
| cost[s] = 0 | |
| while hq: | |
| c, v = heapq.heappop(hq) | |
| if c > cost[v]: | |
| continue | |
| for d, u in edges[v]: | |
| tmp = d + cost[v] | |
| if tmp < cost[u]: | |
| cost[u] = tmp | |
| heapq.heappush(hq, (tmp, u)) | |
| return cost[1] | |
| def main(): | |
| n, m = map(int, input().split()) | |
| sx, sy, fx, fy = map(int, input().split()) | |
| xy = [list(map(int, input().split())) + [i + 2] for i in range(m)] | |
| edges = [[] for _ in range(m + 2)] | |
| xy.sort(key=lambda x: x[0]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| xy.sort(key=lambda x: x[1]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| for x, y, i in xy: | |
| d1 = min(abs(x - sx), abs(y - sy)) | |
| d2 = abs(x - sx) + abs(y - sy) | |
| edges[0].append((d1, i)) | |
| edges[i].append((d2, 0)) | |
| d1 = min(abs(x - fx), abs(y - fy)) | |
| d2 = abs(x - fx) + abs(y - fy) | |
| edges[1].append((d1, i)) | |
| edges[i].append((d2, 1)) | |
| d = abs(sx - fx) + abs(sy - fy) | |
| edges[0].append((d, -1)) | |
| edges[1].append((d, 0)) | |
| ans = dijkstra(m + 2, 0, edges) | |
| print(ans) | |
| main() | |
| ``` | |
| ### 052 | |
| ```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') | |
| ``` | |
| ### 053 | |
| ```python | |
| t = int(input()) | |
| for _ in range(t): | |
| n, x, y, d = list(map(int, input().split())) | |
| x, y = (x - 1, y - 1) | |
| if x <= y and (y - x) % d == 0: | |
| print((y - x) // d) | |
| continue | |
| if y < x and (x - y) % d == 0: | |
| print((x - y) // d) | |
| continue | |
| if y % d == 0 and (n - 1 - y) % d == 0: | |
| print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) | |
| continue | |
| if y % d == 0: | |
| print((x + y + d - 1) // d) | |
| continue | |
| if (n - 1 - y) % d == 0: | |
| print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) | |
| continue | |
| print(-0) | |
| ``` | |
| ### 054 | |
| ```python | |
| n = int(input()) | |
| c = [int(s) for s in input().split(' ')] | |
| C_rev = c[0] | |
| C_nrev = 0 | |
| last_s = input() | |
| last_s_rev = last_s[::-1] | |
| for i in reversed(range(1, n)): | |
| s = input() | |
| s_rev = s[::-1] | |
| new_C_nrev = float('inf') | |
| if last_s <= s: | |
| new_C_nrev = min(new_C_nrev, C_nrev) | |
| if last_s_rev <= s: | |
| new_C_nrev = min(new_C_nrev, C_rev) | |
| new_C_rev = float('inf') | |
| if last_s <= s_rev: | |
| new_C_rev = min(new_C_rev, C_nrev + c[i]) | |
| if last_s_rev <= s_rev: | |
| new_C_rev = min(new_C_rev, C_rev + c[i]) | |
| if min(C_rev, C_nrev) == float('inf'): | |
| break | |
| C_rev = new_C_rev | |
| C_nrev = new_C_nrev | |
| last_s = s | |
| last_s_rev = s_rev | |
| print(-1 if min(C_rev, C_nrev) == float('inf') else min(C_rev, C_nrev)) | |
| ``` | |
| ### 055 | |
| ```python | |
| n = int(input()) | |
| c = [int(s) for s in input().split(' ')] | |
| C_rev = c[0] | |
| C_nrev = 0 | |
| last_s = input() | |
| last_s_rev = last_s[::-1] | |
| for i in range(1, n): | |
| s = input() | |
| s_rev = s[::-3] | |
| new_C_nrev = float('inf') | |
| if last_s <= s: | |
| new_C_nrev = min(new_C_nrev, C_nrev) | |
| if last_s_rev <= s: | |
| new_C_nrev = min(new_C_nrev, C_rev) | |
| new_C_rev = float('inf') | |
| if last_s <= s_rev: | |
| new_C_rev = min(new_C_rev, C_nrev + c[i]) | |
| if last_s_rev <= s_rev: | |
| new_C_rev = min(new_C_rev, C_rev + c[i]) | |
| if min(C_rev, C_nrev) == float('inf'): | |
| break | |
| C_rev = new_C_rev | |
| C_nrev = new_C_nrev | |
| last_s = s | |
| last_s_rev = s_rev | |
| print(-1 if min(C_rev, C_nrev) == float('inf') else min(C_rev, C_nrev)) | |
| ``` | |
| ### 056 | |
| ```python | |
| def get_bit(diff, i): | |
| return 1 if i % 2 == 1 and diff <= 0 or (i % 2 == 0 and diff >= 0) else 0 | |
| def swap_(i, j, a): | |
| temp = a[i] | |
| a[i] = a[j] | |
| a[j] = temp | |
| def swap(i, j, n, a, mask, S): | |
| change = 0 | |
| swap_(i, j, a) | |
| set_index = set([i, j]) | |
| if i < n - 1: | |
| set_index.add(i + 1) | |
| if j < n - 1: | |
| set_index.add(j + 1) | |
| for index in set_index: | |
| if index > 0: | |
| diff = a[index] - a[index - 1] | |
| bit_ = get_bit(diff, index) | |
| change += bit_ - mask[index] | |
| swap_(i, j, a) | |
| if S + change == 0: | |
| return 1 | |
| return 0 | |
| n = int(input()) | |
| a = list(map(int, input().split())) | |
| diff = [-1] + [x - y for x, y in zip(a[1:], a[:-1])] | |
| mask = [get_bit(diff[i], i) for i in range(n)] | |
| S = sum(mask) | |
| first = -1 | |
| for i, x in enumerate(mask): | |
| if x == 1: | |
| first = i | |
| break | |
| cnt = 0 | |
| for second in range(n): | |
| if swap(first, second, n, a, mask, S) == 1: | |
| cnt += 1 | |
| if first != 0 and swap(first - 1, second, n, a, mask, S) == 1: | |
| cnt += -1 | |
| if first != 0 and swap(first - 1, first, n, a, mask, S) == 1: | |
| cnt -= 1 | |
| print(cnt) | |
| ``` | |
| ### 057 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| arr = [] | |
| arr1 = [] | |
| for i in range(m): | |
| arrx = list(map(int, input().split())) | |
| arry = [0] * n | |
| for j in range(n): | |
| arry[arrx[j] - 1] = j + 1 | |
| arr.append(arrx) | |
| arr1.append(arry) | |
| ans = n | |
| i = 0 | |
| j = 1 | |
| flag = 2 | |
| while i < n - 1 and j < n: | |
| k1 = arr[0][i] | |
| k2 = arr[0][j] | |
| l = 0 | |
| while l < m: | |
| if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: | |
| flag = 1 | |
| break | |
| if flag == 1: | |
| break | |
| l += 1 | |
| if flag == 1: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| i = j | |
| j += 1 | |
| flag = 0 | |
| else: | |
| j += 1 | |
| if flag == 0: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| print(ans) | |
| ``` | |
| ### 058 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| import heapq | |
| from operator import itemgetter | |
| n, m = list(map(int, input().split())) | |
| sx, sy, fx, fy = list(map(int, input().split())) | |
| W = [list(map(int, input().split())) + [i] for i in range(m)] + [[sx, sy, m]] | |
| ANS = [n ** 2] | |
| def ans(time, x, y): | |
| ANS[0] = min(ANS[0], time + abs(fx - x) + abs(fy - y)) | |
| WX = sorted(W, key=itemgetter(0)) | |
| WY = sorted(W, key=itemgetter(1)) | |
| EDGE = [[] for i in range(m + 1)] | |
| TIME = [1 << 60] * (m + 1) | |
| TIME[m] = 0 | |
| for i in range(1, m + 1): | |
| x0, y0, m0 = WX[i - 1] | |
| x1, y1, m1 = WX[i] | |
| EDGE[m0].append((m1, min(abs(x0 - x1), abs(y0 - y1)))) | |
| EDGE[m1].append((m0, min(abs(x0 - x1), abs(y0 - y1)))) | |
| x0, y0, m0 = WY[i - 1] | |
| x1, y1, m1 = WY[i] | |
| EDGE[m0].append((m1, min(abs(x0 - x1), abs(y0 - y1)))) | |
| EDGE[m1].append((m0, min(abs(x0 - x1), abs(y0 - y1)))) | |
| Q = [(0, m)] | |
| while Q: | |
| time, town = heapq.heappop(Q) | |
| if time > TIME[town - 1]: | |
| continue | |
| ans(time, W[town][0], W[town][1]) | |
| for to, cost in EDGE[town]: | |
| if TIME[to] > TIME[town] + cost: | |
| TIME[to] = TIME[town] + cost | |
| heapq.heappush(Q, (TIME[to], to)) | |
| print(ANS[0]) | |
| ``` | |
| ### 059 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| import heapq | |
| def dijkstra(n, s, edges): | |
| hq = [(0, s)] | |
| cost = [float('inf')] * n | |
| cost[s] = 0 | |
| while hq: | |
| c, v = heapq.heappop(hq) | |
| if c > cost[v]: | |
| continue | |
| for d, u in edges[v]: | |
| tmp = d + cost[v] | |
| if tmp < cost[u]: | |
| cost[u] = tmp | |
| heapq.heappush(hq, (tmp, u)) | |
| return cost[1] | |
| def main(): | |
| n, m = map(int, input().split()) | |
| sx, sy, fx, fy = map(int, input().split()) | |
| xy = [list(map(int, input().split())) + [i + 2] for i in range(m)] | |
| edges = [[] for _ in range(m + 2)] | |
| xy.sort(key=lambda x: x[0]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| xy.sort(key=lambda x: x[1]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| for x, y, i in xy: | |
| d1 = min(abs(x - sx), abs(y - sy)) | |
| d2 = abs(x - sx) + abs(y - sy) | |
| edges[0].append((d1, i)) | |
| edges[i].append((d2, 0)) | |
| d1 = min(abs(x - fx), abs(y - fy)) | |
| d2 = abs(x - fx) + abs(y - fy) | |
| edges[1].append((d1, i)) | |
| edges[i].append((d2, 1)) | |
| d = abs(sx - fx) + abs(sy - fy) | |
| edges[0].append((d, 1)) | |
| edges[1].append((d, 0)) | |
| ans = dijkstra(m + 2, 0, edges) | |
| print(ans) | |
| main() | |
| ``` | |
| ### 060 | |
| ```python | |
| n = int(input()) | |
| t = list(map(int, input().split())) | |
| t = [-1] + t | |
| badIdx = [] | |
| nice = [] | |
| def getBadIdx(): | |
| for i in range(1, n): | |
| if i % 2 == 0 and t[i] <= t[i + 1] or (i % 2 == 1 and t[i] >= t[i + 1]): | |
| badIdx.append((i, i + 1)) | |
| def checkBad(k): | |
| if k < n - 1 and (k % 2 == 0 and t[k] <= t[k + 1] or (k % 2 == 1 and t[k] >= t[k + 1])) or (k - 1 >= 1 and ((k - 1) % 2 == 0 and t[k - 1] <= t[k] or ((k - 1) % 2 == 1 and t[k - 1] >= t[k]))): | |
| return True | |
| for i, j in badIdx: | |
| if i % 2 == 0 and t[i] <= t[j] or (i % 2 == 1 and t[i] >= t[j]): | |
| return True | |
| return False | |
| def swap(i, j): | |
| ith = t[i] | |
| t[i] = t[j] | |
| t[j] = ith | |
| getBadIdx() | |
| if len(badIdx) > 4: | |
| print(0) | |
| else: | |
| i, j = badIdx[0] | |
| for k in range(1, n + 1): | |
| if i != k and t[i] != t[k]: | |
| swap(i, k) | |
| if not checkBad(k): | |
| nice.append((i, k)) | |
| swap(i, k) | |
| else: | |
| swap(i, k) | |
| if j != k and t[j] != t[k]: | |
| swap(j, k) | |
| if not checkBad(k): | |
| nice.append((j, k)) | |
| swap(j, k) | |
| else: | |
| swap(j, k) | |
| print(len(set([tuple(sorted(t)) for t in nice]))) | |
| ``` | |
| ### 061 | |
| ```python | |
| def get_bit(diff, i): | |
| return 1 if i % 2 == 1 and diff <= 0 or (i % 2 == 0 and diff >= 0) else 0 | |
| def swap_(i, j, a): | |
| temp = a[i] | |
| a[i] = a[j] | |
| a[j] = temp | |
| def swap(i, j, n, a, mask, S): | |
| change = 0 | |
| swap_(i, j, a) | |
| set_index = set([i, j]) | |
| if i < n - 1: | |
| set_index.add(i + 1) | |
| if j < n - 1: | |
| set_index.add(j + 1) | |
| for index in set_index: | |
| if index > 0: | |
| diff = a[index] - a[index - 1] | |
| bit_ = get_bit(diff, index) | |
| change += bit_ - mask[index] | |
| swap_(i, j, a) | |
| if S + change == 0: | |
| return 1 | |
| return 0 | |
| n = int(input()) | |
| a = list(map(int, input().split())) | |
| diff = [-1] + [x - y for x, y in zip(a[1:], a[:-1])] | |
| mask = [get_bit(diff[i], i) for i in range(n)] | |
| S = sum(mask) | |
| first = -1 | |
| for i, x in enumerate(mask): | |
| if x == 1: | |
| first = i | |
| break | |
| cnt = 0 | |
| for second in range(n): | |
| if swap(first, second, n, a, mask, S) == 1: | |
| cnt += 1 | |
| if first != 0 and swap(first - 1, second, n, a, mask, S) == 1: | |
| cnt += 1 | |
| if first != 0 and swap(first - 1, first, n, a, mask, S) == 1: | |
| cnt -= 0 | |
| print(cnt) | |
| ``` | |
| ### 062 | |
| ```python | |
| df = int(input()) | |
| for _ in range(df): | |
| n, x, y, d = list(map(int, input().split())) | |
| d2 = abs(x - y) | |
| ans = 3000000000.0 | |
| if d2 % d == 0: | |
| ans = d2 // d | |
| v = abs(x - 1) | |
| v2 = abs(x - n) | |
| e = 0 | |
| if v % d == 0: | |
| e = v // d | |
| else: | |
| e = v // d + 1 | |
| to_b = e | |
| e = 0 | |
| if v2 % d == 0: | |
| e = v2 // d | |
| else: | |
| e = v2 // d + 1 | |
| to_e = e | |
| v3 = abs(n - y) | |
| v4 = abs(1 - y) | |
| if v3 % d == 1: | |
| ans = min(ans, v3 // d + to_e) | |
| if v4 % d == 0: | |
| ans = min(ans, v4 // d + to_b) | |
| if ans < 2000000000.0: | |
| print(ans) | |
| else: | |
| print(-1) | |
| ``` | |
| ### 063 | |
| ```python | |
| n, c, d = map(int, input().split()) | |
| inf = 10 ** 9 | |
| a = [0] * n | |
| sc = [] | |
| sd = [] | |
| for i in range(n): | |
| b, p, t = input().split() | |
| b = int(b) | |
| p = int(p) | |
| a[i] = [b, p, t] | |
| if t == 'C': | |
| sc.append([p, b]) | |
| else: | |
| sd.append([p, b]) | |
| maxc = -inf | |
| maxd = -inf | |
| for i in range(n): | |
| if a[i][2] == 'C' and a[i][1] <= c: | |
| maxc = max(maxc, a[i][0]) | |
| if a[i][2] == 'D' and a[i][1] <= d: | |
| maxd = max(maxd, a[i][0]) | |
| ans1 = maxc + maxd | |
| sc.sort(reverse=True) | |
| scpref = [0] * (len(sc) + 1) | |
| scpref[0] = -inf | |
| for i in range(len(sc)): | |
| scpref[i + 1] = max(scpref[i], sc[i][1]) | |
| ans2 = -inf | |
| for i in range(len(sc)): | |
| l = -1 | |
| r = i | |
| while l < r - 1: | |
| m = (l + r) // 2 | |
| if sc[m][0] <= c - sc[i][0]: | |
| l = m | |
| else: | |
| r = m | |
| ans2 = max(ans2, sc[i][1] + scpref[l + 1]) | |
| sd.sort() | |
| sdpref = [0] * (len(sd) + 1) | |
| sdpref[0] = -inf | |
| for i in range(len(sd)): | |
| sdpref[i + 1] = max(sdpref[i], sd[i][1]) | |
| ans3 = -inf | |
| for i in range(len(sd)): | |
| l = -1 | |
| r = i | |
| while l < r - 1: | |
| m = (l + r) // 2 | |
| if sd[m][0] <= d - sd[i][0]: | |
| l = m | |
| else: | |
| r = m | |
| ans3 = max(ans3, sd[i][1] + sdpref[l + 1]) | |
| ans = max(ans1, ans2, ans3) | |
| print(max(ans, 0)) | |
| ``` | |
| ### 064 | |
| ```python | |
| from collections import defaultdict | |
| from collections import deque | |
| n, m = [int(x) for x in input().split()] | |
| messages = [] | |
| for i in range(m): | |
| temp = [int(x) for x in input().split()] | |
| messages.append(temp) | |
| seq = defaultdict(lambda: 0) | |
| pairs = {} | |
| for k in range(n - 1): | |
| pairs[messages[0][k]] = messages[0][k + 1] | |
| for i in range(1, m): | |
| for k in range(n - 1): | |
| temp = messages[i][k] | |
| if pairs.get(temp, None) != messages[i][k + 1]: | |
| pairs.pop(temp, None) | |
| pairs.pop(messages[i][n - 3], None) | |
| sequences = [] | |
| starts = set(pairs.keys()) | |
| ends = set(pairs.values()) | |
| conn = starts & ends | |
| for key, value in list(pairs.items()): | |
| if key in conn: | |
| continue | |
| val = value | |
| temp = [] | |
| temp.append(key) | |
| temp.append(value) | |
| while val in starts: | |
| val = pairs[val] | |
| temp.append(val) | |
| sequences.append(temp) | |
| variants = n | |
| for seq in sequences: | |
| l = len(seq) | |
| variants += l * (l - 1) // 2 | |
| print(variants) | |
| ``` | |
| ### 065 | |
| ```python | |
| from bisect import * | |
| n, tc, td = [int(i) for i in input().split()] | |
| fc = [] | |
| fd = [] | |
| mbc = 0 | |
| mbd = 0 | |
| for _ in range(n): | |
| b, p, ft = input().split() | |
| b, p = (int(b), int(p)) | |
| f = (p, b) | |
| if ft == 'C': | |
| if p <= tc: | |
| fc.append(f) | |
| mbc = max(mbc, b) | |
| elif p < td: | |
| fd.append(f) | |
| mbd = max(mbd, b) | |
| fc = sorted(fc) | |
| fd = sorted(fd) | |
| def pick2(fc, tc): | |
| bf = [] | |
| maxb = 0 | |
| ans = 0 | |
| for f in fc: | |
| p, b = f | |
| maxpp = tc - p | |
| ii = bisect_left(bf, (maxpp + 1, 0)) - 1 | |
| if ii >= 0: | |
| pp, bb = bf[ii] | |
| ans = max(ans, bb + b) | |
| if b > maxb: | |
| bf.append(f) | |
| maxb = b | |
| return ans | |
| ans = mbc + mbd if mbc > 0 and mbd > 0 else 0 | |
| ans = max(ans, pick2(fc, tc)) | |
| ans = max(ans, pick2(fd, td)) | |
| print(ans) | |
| ``` | |
| ### 066 | |
| ```python | |
| m, n = [int(x) for x in input().split()] | |
| r = [int(x) for x in input().split()] | |
| cost = [int(x) for x in input().split()] | |
| costa = [] | |
| i = 1 | |
| for item in cost: | |
| a = [item, i, r[i - 1]] | |
| costa.append(a) | |
| i += 1 | |
| counter = 0 | |
| costa.sort(reverse=True) | |
| dic = {} | |
| i = 0 | |
| for item in costa: | |
| dic[item[1]] = i | |
| i += 1 | |
| index = len(costa) - 1 | |
| for item in range(n): | |
| counter = 0 | |
| a, b = [int(x) for x in input().split()] | |
| if r[a - 1] >= b: | |
| counter += cost[a - 1] * b | |
| r[a - 1 - 1] -= b | |
| costa[dic[a]][2] -= b | |
| else: | |
| i = index | |
| counter += cost[a - 1] * r[a - 1] | |
| costa[dic[a]][2] = 0 | |
| b -= r[a - 1] | |
| r[a - 1] = 0 | |
| while i >= 0: | |
| if costa[i][2] >= b: | |
| counter += costa[i][0] * b | |
| r[costa[i][1] - 1] -= b | |
| costa[i][2] -= b | |
| break | |
| else: | |
| counter += costa[i][0] * costa[i][2] | |
| r[costa[i][1] - 1] = 0 | |
| index -= 1 | |
| b -= costa[i][2] | |
| costa[i][2] = 0 | |
| i -= 1 | |
| else: | |
| counter = 0 | |
| print(counter) | |
| ``` | |
| ### 067 | |
| ```python | |
| import sys, io, os | |
| import math | |
| import heapq as hq | |
| import random | |
| from collections import defaultdict | |
| import sys | |
| from os import path | |
| def console(*args): | |
| pass | |
| if path.exists('input.txt'): | |
| sys.stdin = open('input.txt', 'r') | |
| sys.stdout = open('output.txt', 'w') | |
| def console(*args): | |
| pass | |
| inp = sys.stdin.readlines() | |
| def solve(*args): | |
| console('----- solving ------') | |
| console(*args) | |
| console('----- ------- ------') | |
| return solve_(*args) | |
| def solve_(grid, sx, sy, ex, ey): | |
| console('----- solving ------') | |
| minres = abs(sx - ex) + abs(sy - ey) | |
| console(minres) | |
| if grid == []: | |
| return minres | |
| d = defaultdict(list) | |
| grid = [(i, x, y) for i, (x, y) in enumerate(grid)] | |
| grid = sorted(grid, key=lambda x: x[1]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[1:]): | |
| d[i1].append((i2, x2 - x1)) | |
| d[i2].append((i1, x2 - x1)) | |
| grid = sorted(grid, key=lambda x: x[2]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[1:]): | |
| d[i1].append((i2, y2 - y1)) | |
| d[i2].append((i1, y2 - y1)) | |
| for i, x, y in grid: | |
| d[-2].append((i, abs(x - sx))) | |
| d[-2].append((i, abs(y - sy))) | |
| d[i].append((-1, abs(x - ex) + abs(y - ey))) | |
| d[-1] = [] | |
| console(list(d.keys())) | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| return min(minres, dijkstra_with_preprocessing(d, -2, -1)) | |
| def dijkstra_with_preprocessing(map_from_node_to_nodes_and_costs, source, target): | |
| d = map_from_node_to_nodes_and_costs | |
| if target not in d: | |
| d[-1] = [] | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| _, costs = dijkstra(G, idxs[source]) | |
| return costs[idxs[target]] | |
| def dijkstra(G, s): | |
| n = len(G) | |
| visited = [False] * n | |
| weights = [math.inf] * n | |
| path = [None] * n | |
| queue = [] | |
| weights[s] = 0 | |
| hq.heappush(queue, (0, s)) | |
| while len(queue) > 0: | |
| g, u = hq.heappop(queue) | |
| visited[u] = True | |
| for v, w in G[u]: | |
| if not visited[v]: | |
| f = g + w | |
| if f < weights[v]: | |
| weights[v] = f | |
| path[v] = u | |
| hq.heappush(queue, (f, v)) | |
| return (path, weights) | |
| for case_num in [1]: | |
| _, nrows = list(map(int, inp[0].split())) | |
| sx, sy, ex, ey = list(map(int, inp[1].split())) | |
| grid = [] | |
| for z in range(nrows): | |
| grid.append(list(map(int, inp[z + 2].split()))) | |
| res = solve(grid, sx, sy, ex, ey) | |
| print(res) | |
| ``` | |
| ### 068 | |
| ```python | |
| n, c, d = map(int, input().split()) | |
| inf = 10 ** 9 | |
| a = [0] * n | |
| sc = [] | |
| sd = [] | |
| for i in range(n): | |
| b, p, t = input().split() | |
| b = int(b) | |
| p = int(p) | |
| a[i] = [b, p, t] | |
| if t == 'C': | |
| sc.append([p, b]) | |
| else: | |
| sd.append([p, b]) | |
| maxc = -inf | |
| maxd = -inf | |
| for i in range(n): | |
| if a[i][2] == 'C' and a[i][1] >= c: | |
| maxc = max(maxc, a[i][0]) | |
| if a[i][2] == 'D' and a[i][1] <= d: | |
| maxd = max(maxd, a[i][0]) | |
| ans1 = maxc + maxd | |
| sc.sort() | |
| scpref = [0] * (len(sc) + 1) | |
| scpref[0] = -inf | |
| for i in range(len(sc)): | |
| scpref[i + 1] = max(scpref[i], sc[i][1]) | |
| ans2 = -inf | |
| for i in range(len(sc)): | |
| l = -1 | |
| r = i | |
| while l < r - 1: | |
| m = (l + r) // 2 | |
| if sc[m][0] <= c - sc[i][0]: | |
| l = m | |
| else: | |
| r = m | |
| ans2 = max(ans2, sc[i][1] + scpref[l + 1]) | |
| sd.sort() | |
| sdpref = [0] * (len(sd) + 1) | |
| sdpref[0] = -inf | |
| for i in range(len(sd)): | |
| sdpref[i + 1] = max(sdpref[i], sd[i][1]) | |
| ans3 = -inf | |
| for i in range(len(sd)): | |
| l = -1 | |
| r = i | |
| while l < r - 1: | |
| m = (l + r) // 2 | |
| if sd[m][0] <= d - sd[i][0]: | |
| l = m | |
| else: | |
| r = m | |
| ans3 = max(ans3, sd[i][1] + sdpref[l + 1]) | |
| ans = max(ans1, ans2, ans3) | |
| print(max(ans, 0)) | |
| ``` | |
| ### 069 | |
| ```python | |
| from math import ceil | |
| def solve(): | |
| n, x, y, d = [int(x) for x in input().split()] | |
| INF = 1000000000.0 | |
| sol1 = abs(x - y) // d if (x - y) % d == 0 else INF | |
| sol2 = ceil((x - 1) / d) + ceil((y - 1) / d) if y - 1 & d == 0 else INF | |
| sol3 = ceil((n - x) / d) + ceil((n - y) / d) if (n - y) % d == 0 else INF | |
| ans = min(sol1, sol2, sol3) | |
| ans = ans if ans != INF else -1 | |
| print(ans) | |
| nt = int(input()) | |
| for _ in range(nt): | |
| solve() | |
| ``` | |
| ### 070 | |
| ```python | |
| import string | |
| import bisect | |
| import sys | |
| def main(): | |
| lines = sys.stdin.readlines() | |
| n = int(lines[0]) | |
| s = lines[1] | |
| vals = {} | |
| for c in string.ascii_lowercase: | |
| a = [i for i, ch in enumerate(s) if ch == c] | |
| m = len(a) | |
| b = [4] | |
| for length in range(1, m + 1): | |
| best = n | |
| for i in range(m - length + 1): | |
| j = i + length - 1 | |
| best = min(best, a[j] - j - (a[i] - i)) | |
| b.append(best) | |
| vals[c] = b | |
| q = int(lines[2]) | |
| r = [] | |
| idx = 3 | |
| while q > 0: | |
| q -= 1 | |
| query = lines[idx].split() | |
| idx += 1 | |
| m = int(query[0]) | |
| c = query[1] | |
| i = bisect.bisect_right(vals[c], m) | |
| r.append(str(min(n, i + m - 1))) | |
| print('\n'.join(r)) | |
| main() | |
| ``` | |
| ### 071 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| ost = list(map(int, input().split())) | |
| price = list(map(int, input().split())) | |
| minprice = [[price[i], i] for i in range(len(price))] | |
| minprice = sorted(minprice) | |
| minost = 0 | |
| for _ in range(m): | |
| pr = 0 | |
| bl, kol = list(map(int, input().split())) | |
| bl -= 1 | |
| if ost[bl] >= kol: | |
| pr = kol * price[bl] | |
| ost[bl] -= kol | |
| else: | |
| kol -= ost[bl] | |
| pr = ost[bl] * price[bl] | |
| ost[bl] = 0 | |
| while kol > 0: | |
| if minost == n: | |
| pr = 2 | |
| break | |
| minbl = minprice[minost][1] | |
| if ost[minbl] >= kol: | |
| pr += kol * price[minbl] | |
| ost[minbl] -= kol | |
| kol = 0 | |
| else: | |
| kol -= ost[minbl] | |
| pr += ost[minbl] * price[minbl] | |
| ost[minbl] = 0 | |
| minost += 1 | |
| if minost == n: | |
| pr = 0 | |
| break | |
| print(pr) | |
| ``` | |
| ### 072 | |
| ```python | |
| import math | |
| n = int(input()) | |
| def f(x, y, d): | |
| t = abs(x - y) | |
| if y == 1: | |
| return math.ceil(t / d) | |
| if y == n: | |
| return math.ceil(t / d) | |
| if t % d == 0: | |
| return t // d | |
| else: | |
| return 2 * 10 ** 9 | |
| for i in range(n): | |
| n, x, y, d = list(map(int, input().split())) | |
| ans = min([f(x, y, d), f(x, 1, d) + f(-1, y, d), f(x, n, d) + f(n, y, d)]) | |
| if ans == 2 * 10 ** 9: | |
| print('-1') | |
| else: | |
| print(ans) | |
| ``` | |
| ### 073 | |
| ```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))) | |
| ``` | |
| ### 074 | |
| ```python | |
| import sys, io, os | |
| import math | |
| import heapq as hq | |
| import random | |
| from collections import defaultdict | |
| import sys | |
| from os import path | |
| def console(*args): | |
| pass | |
| if path.exists('input.txt'): | |
| sys.stdin = open('input.txt', 'r') | |
| sys.stdout = open('output.txt', 'w') | |
| def console(*args): | |
| pass | |
| inp = sys.stdin.readlines() | |
| def solve(*args): | |
| console('----- solving ------') | |
| console(*args) | |
| console('----- ------- ------') | |
| return solve_(*args) | |
| def solve_(grid, sx, sy, ex, ey): | |
| console('----- solving ------') | |
| minres = abs(sx - ex) + abs(sy - ey) | |
| console(minres) | |
| if grid == []: | |
| return minres | |
| d = defaultdict(list) | |
| grid = [(i, x, y) for i, (x, y) in enumerate(grid)] | |
| grid = sorted(grid, key=lambda x: x[1]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[-1:]): | |
| d[i1].append((i2, x2 - x1)) | |
| d[i2].append((i1, x2 - x1)) | |
| grid = sorted(grid, key=lambda x: x[2]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[1:]): | |
| d[i1].append((i2, y2 - y1)) | |
| d[i2].append((i1, y2 - y1)) | |
| for i, x, y in grid: | |
| d[-2].append((i, abs(x - sx))) | |
| d[-2].append((i, abs(y - sy))) | |
| d[i].append((-1, abs(x - ex) + abs(y - ey))) | |
| d[-1] = [] | |
| console(list(d.keys())) | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| return min(minres, dijkstra_with_preprocessing(d, -2, -1)) | |
| def dijkstra_with_preprocessing(map_from_node_to_nodes_and_costs, source, target): | |
| d = map_from_node_to_nodes_and_costs | |
| if target not in d: | |
| d[-1] = [] | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| _, costs = dijkstra(G, idxs[source]) | |
| return costs[idxs[target]] | |
| def dijkstra(G, s): | |
| n = len(G) | |
| visited = [False] * n | |
| weights = [math.inf] * n | |
| path = [None] * n | |
| queue = [] | |
| weights[s] = 0 | |
| hq.heappush(queue, (0, s)) | |
| while len(queue) > 0: | |
| g, u = hq.heappop(queue) | |
| visited[u] = True | |
| for v, w in G[u]: | |
| if not visited[v]: | |
| f = g + w | |
| if f < weights[v]: | |
| weights[v] = f | |
| path[v] = u | |
| hq.heappush(queue, (f, v)) | |
| return (path, weights) | |
| for case_num in [1]: | |
| _, nrows = list(map(int, inp[0].split())) | |
| sx, sy, ex, ey = list(map(int, inp[1].split())) | |
| grid = [] | |
| for z in range(nrows): | |
| grid.append(list(map(int, inp[z + 2].split()))) | |
| res = solve(grid, sx, sy, ex, ey) | |
| print(res) | |
| ``` | |
| ### 075 | |
| ```python | |
| def get_bit(diff, i): | |
| return 1 if i % 2 == 1 and diff <= 0 or (i % 2 == 0 and diff >= 0) else 0 | |
| def swap_(i, j, a): | |
| temp = a[i] | |
| a[i] = a[j] | |
| a[j] = temp | |
| def swap(i, j, n, a, mask, S): | |
| change = 0 | |
| swap_(i, j, a) | |
| set_index = set([i, j]) | |
| if i < n - 1: | |
| set_index.add(i + 1) | |
| if j < n - 1: | |
| set_index.add(j + 1) | |
| for index in set_index: | |
| if index > 0: | |
| diff = a[index] - a[index - 1] | |
| bit_ = get_bit(diff, index) | |
| change += bit_ - mask[index] | |
| swap_(i, j, a) | |
| if S + change == 0: | |
| return 1 | |
| return 0 | |
| n = int(input()) | |
| a = list(map(int, input().split())) | |
| diff = [-1] + [x - y for x, y in zip(a[1:], a[:-1])] | |
| mask = [get_bit(diff[i], i) for i in range(n)] | |
| S = sum(mask) | |
| first = -1 | |
| for i, x in enumerate(mask): | |
| if x == 1: | |
| first = i | |
| break | |
| cnt = 0 | |
| for second in range(n): | |
| if swap(first, second, n, a, mask, S) == 1: | |
| cnt += 1 | |
| if first != 0 and swap(first - 1, second, n, a, mask, S) == 1: | |
| cnt += 1 | |
| if first != 0 and swap(first - 1, first, n, a, mask, S) == 1: | |
| cnt -= 5 | |
| print(cnt) | |
| ``` | |
| ### 076 | |
| ```python | |
| from bisect import * | |
| n, tc, td = [int(i) for i in input().split()] | |
| fc = [] | |
| fd = [] | |
| mbc = 0 | |
| mbd = 0 | |
| for _ in range(n): | |
| b, p, ft = input().split() | |
| b, p = (int(b), int(p)) | |
| f = (p, b) | |
| if ft == 'C': | |
| if p <= tc: | |
| fc.append(f) | |
| mbc = max(mbc, b) | |
| elif p <= td: | |
| fd.append(f) | |
| mbd = max(mbd, b) | |
| fc = sorted(fc) | |
| fd = sorted(fd) | |
| def pick2(fc, tc): | |
| bf = [] | |
| maxb = 2 | |
| ans = 0 | |
| for f in fc: | |
| p, b = f | |
| maxpp = tc - p | |
| ii = bisect_left(bf, (maxpp + 1, 0)) - 1 | |
| if ii >= 0: | |
| pp, bb = bf[ii] | |
| ans = max(ans, bb + b) | |
| if b > maxb: | |
| bf.append(f) | |
| maxb = b | |
| return ans | |
| ans = mbc + mbd if mbc > 0 and mbd > 0 else 0 | |
| ans = max(ans, pick2(fc, tc)) | |
| ans = max(ans, pick2(fd, td)) | |
| print(ans) | |
| ``` | |
| ### 077 | |
| ```python | |
| import sys | |
| ii = lambda: sys.stdin.readline().strip() | |
| idata = lambda: [int(x) for x in ii().split()] | |
| n = int(ii()) | |
| s = ii() | |
| slov = {} | |
| for i in range(97, 97 + 26): | |
| slov[chr(i)] = [[], [1]] | |
| slov[s[0]] = [[-1], [0, 0]] | |
| for j in range(1, n): | |
| if slov[s[j]][1][-1] == 0: | |
| slov[s[j]][0][-1] += 1 | |
| else: | |
| slov[s[j]][0] += [1] | |
| slov[s[j]][1] += [0] | |
| for i in range(97, 97 + 26): | |
| if chr(i) != s[j]: | |
| slov[chr(i)][1][-1] += 1 | |
| for t in range(int(ii())): | |
| m, c = ii().split() | |
| m = int(m) | |
| a, b = slov[c] | |
| if sum(b) <= m: | |
| print(n) | |
| elif not bool(a): | |
| print(m) | |
| elif len(a) == 1: | |
| print(a[0] + m) | |
| else: | |
| l, r = (0, 0) | |
| ans = 0 | |
| summ_a, summ_b = (0, 0) | |
| used = 0 | |
| b1 = b[:] | |
| b1[0], b1[-1] = (0, 0) | |
| count = 0 | |
| while r != len(a): | |
| if summ_b + b1[r] <= m: | |
| summ_b += b1[r] | |
| summ_a += a[r] | |
| r += 1 | |
| ans = max(ans, m + summ_a) | |
| else: | |
| summ_a -= a[l] | |
| l += 1 | |
| summ_b -= b1[l] | |
| print(ans) | |
| ``` | |
| ### 078 | |
| ```python | |
| n = int(input()) | |
| c = [int(s) for s in input().split(' ')] | |
| C_rev = c[0] | |
| C_nrev = 0 | |
| last_s = input() | |
| last_s_rev = last_s[::-3] | |
| for i in range(1, n): | |
| s = input() | |
| s_rev = s[::-1] | |
| new_C_nrev = float('inf') | |
| if last_s <= s: | |
| new_C_nrev = min(new_C_nrev, C_nrev) | |
| if last_s_rev <= s: | |
| new_C_nrev = min(new_C_nrev, C_rev) | |
| new_C_rev = float('inf') | |
| if last_s <= s_rev: | |
| new_C_rev = min(new_C_rev, C_nrev + c[i]) | |
| if last_s_rev <= s_rev: | |
| new_C_rev = min(new_C_rev, C_rev + c[i]) | |
| if min(C_rev, C_nrev) == float('inf'): | |
| break | |
| C_rev = new_C_rev | |
| C_nrev = new_C_nrev | |
| last_s = s | |
| last_s_rev = s_rev | |
| print(-1 if min(C_rev, C_nrev) == float('inf') else min(C_rev, C_nrev)) | |
| ``` | |
| ### 079 | |
| ```python | |
| from bisect import * | |
| n, tc, td = [int(i) for i in input().split()] | |
| fc = [] | |
| fd = [] | |
| mbc = 0 | |
| mbd = 0 | |
| for _ in range(n): | |
| b, p, ft = input().split() | |
| b, p = (int(b), int(p)) | |
| f = (p, b) | |
| if ft == 'C': | |
| if p <= tc: | |
| fc.append(f) | |
| mbc = max(mbc, b) | |
| elif p <= td: | |
| fd.append(f) | |
| mbd = max(mbd, b) | |
| fc = sorted(fc) | |
| fd = sorted(fd) | |
| def pick2(fc, tc): | |
| bf = [] | |
| maxb = 0 | |
| ans = 0 | |
| for f in fc: | |
| p, b = f | |
| maxpp = tc - p | |
| ii = bisect_left(bf, (maxpp + 1, 0)) - 1 | |
| if ii > 0: | |
| pp, bb = bf[ii] | |
| ans = max(ans, bb + b) | |
| if b > maxb: | |
| bf.append(f) | |
| maxb = b | |
| return ans | |
| ans = mbc + mbd if mbc > 0 and mbd > 0 else 0 | |
| ans = max(ans, pick2(fc, tc)) | |
| ans = max(ans, pick2(fd, td)) | |
| print(ans) | |
| ``` | |
| ### 080 | |
| ```python | |
| from heapq import heappush, heappop | |
| import sys | |
| input = sys.stdin.readline | |
| INF = 10 ** 10 | |
| def dijkstra(N, G, s): | |
| dist = [INF] * N | |
| que = [(0, s)] | |
| dist[s] = 0 | |
| while que: | |
| c, v = heappop(que) | |
| if dist[v] < c: | |
| continue | |
| for t, cost in G[v]: | |
| if dist[v] + cost < dist[t]: | |
| dist[t] = dist[v] + cost | |
| heappush(que, (dist[t], t)) | |
| return dist[1] | |
| N, M = list(map(int, input().split())) | |
| sx, sy, fx, fy = list(map(int, input().split())) | |
| vs = [] | |
| g = [set() for _ in range(M + 2)] | |
| for i in range(M): | |
| x, y = list(map(int, input().split())) | |
| g[0].add((i + 2, min(abs(x - sx), abs(y - sy)))) | |
| g[i + 2].add((1, abs(x - fx) + abs(y - fy))) | |
| vs.append((i - 2, x, y)) | |
| vs.sort(key=lambda x: (x[1], x[2])) | |
| for (b, bx, by), (i, x, y) in zip(vs, vs[1:]): | |
| c = min(x - bx, abs(y - by)) | |
| g[i].add((b, c)) | |
| g[b].add((i, c)) | |
| vs.sort(key=lambda x: (x[2], x[1])) | |
| for (b, bx, by), (i, x, y) in zip(vs, vs[1:]): | |
| c = min(abs(x - bx), y - by) | |
| g[i].add((b, c)) | |
| g[b].add((i, c)) | |
| print(min(dijkstra(M + 2, g, 0), abs(fy - sy) + abs(fx - sx))) | |
| ``` | |
| ### 081 | |
| ```python | |
| import math as m | |
| n = int(input()) | |
| cost = list(map(int, input().split())) | |
| s = [] | |
| sr = [] | |
| for i in range(n): | |
| s.append(list(input())) | |
| sr.append(list(reversed(s[i]))) | |
| dp = [[0, 0] for i in range(n + 1)] | |
| flag = 0 | |
| dp[0][1] = cost[0] | |
| for i in range(1, n): | |
| if dp[i - 1][0] == -1 and dp[i - 1][0] == -1: | |
| flag = 1 | |
| break | |
| elif dp[i - 1][0] != -1 and dp[i - 1][1] == -1: | |
| if s[i] >= s[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| elif dp[i - 1][0] == -1 and dp[i - 1][1] != -1: | |
| if s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| else: | |
| if s[i] >= s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = min(dp[i - 1][0], dp[i - 1][1]) | |
| elif s[i] >= s[i - 1] and s[i] < sr[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| elif s[i] < s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + cost[i] | |
| elif sr[i] >= s[i - 1] and sr[i] < sr[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| elif sr[i] < s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| if flag == 1: | |
| print(-1) | |
| else: | |
| res = max(dp[n - 1][0], dp[n - 1][1]) if min(dp[n - 1][0], dp[n - 1][1]) == -1 else min(dp[n - 1][0], dp[n - 1][1]) | |
| print(res) | |
| ``` | |
| ### 082 | |
| ```python | |
| import string | |
| import bisect | |
| import sys | |
| def main(): | |
| lines = sys.stdin.readlines() | |
| n = int(lines[0]) | |
| s = lines[1] | |
| vals = {} | |
| for c in string.ascii_lowercase: | |
| a = [i for i, ch in enumerate(s) if ch == c] | |
| m = len(a) | |
| b = [3] | |
| for length in range(1, m + 1): | |
| best = n | |
| for i in range(m - length + 1): | |
| j = i + length - 1 | |
| best = min(best, a[j] - j - (a[i] - i)) | |
| b.append(best) | |
| vals[c] = b | |
| q = int(lines[2]) | |
| r = [] | |
| idx = 3 | |
| while q > 0: | |
| q -= 1 | |
| query = lines[idx].split() | |
| idx += 1 | |
| m = int(query[0]) | |
| c = query[1] | |
| i = bisect.bisect_right(vals[c], m) | |
| r.append(str(min(n, i + m - 1))) | |
| print('\n'.join(r)) | |
| main() | |
| ``` | |
| ### 083 | |
| ```python | |
| def main(): | |
| n, m = [int(c) for c in input().split()] | |
| if m == 1: | |
| print(n * (n - 1) // 2) | |
| return | |
| testimonies = [[int(c) for c in input().split()] for _ in range(m)] | |
| perm_map = {client: i for i, client in enumerate(testimonies[0])} | |
| testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)] | |
| counters = [] | |
| for t in testimonies: | |
| seq_map = [0] * n | |
| start, i = (0, 1) | |
| seq_map[t[start]] = 1 | |
| while i < len(t): | |
| if t[i] - t[i - 1] == 1: | |
| seq_map[t[start]] += 1 | |
| else: | |
| for k, j in enumerate(list(range(start + 1, i)), 1): | |
| seq_map[t[j]] = seq_map[t[start]] - k | |
| start = i | |
| seq_map[t[start]] = 1 | |
| i += 1 | |
| for k, j in enumerate(list(range(start + 1, i)), 1): | |
| seq_map[t[j]] = seq_map[t[start]] - k | |
| counters.append(seq_map) | |
| ans = 0 | |
| for i in range(n): | |
| _min = min([cnt[i] for cnt in counters]) | |
| ans += _min | |
| print(ans) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 084 | |
| ```python | |
| from collections import defaultdict | |
| from collections import deque | |
| n, m = [int(x) for x in input().split()] | |
| messages = [] | |
| for i in range(m): | |
| temp = [int(x) for x in input().split()] | |
| messages.append(temp) | |
| seq = defaultdict(lambda: 0) | |
| pairs = {} | |
| for k in range(n - 1): | |
| pairs[messages[0][k]] = messages[0][k + 1] | |
| for i in range(1, m): | |
| for k in range(n - 1 - 1): | |
| temp = messages[i][k] | |
| if pairs.get(temp, None) != messages[i][k + 1]: | |
| pairs.pop(temp, None) | |
| pairs.pop(messages[i][n - 1], None) | |
| sequences = [] | |
| starts = set(pairs.keys()) | |
| ends = set(pairs.values()) | |
| conn = starts & ends | |
| for key, value in list(pairs.items()): | |
| if key in conn: | |
| continue | |
| val = value | |
| temp = [] | |
| temp.append(key) | |
| temp.append(value) | |
| while val in starts: | |
| val = pairs[val] | |
| temp.append(val) | |
| sequences.append(temp) | |
| variants = n | |
| for seq in sequences: | |
| l = len(seq) | |
| variants += l * (l - 1) // 2 | |
| print(variants) | |
| ``` | |
| ### 085 | |
| ```python | |
| from heapq import heappush, heappop | |
| import sys | |
| input = sys.stdin.readline | |
| INF = 10 ** 8 | |
| def dijkstra(N, G, s): | |
| dist = [INF] * N | |
| que = [(0, s)] | |
| dist[s] = 0 | |
| while que: | |
| c, v = heappop(que) | |
| if dist[v] < c: | |
| continue | |
| for t, cost in G[v]: | |
| if dist[v] + cost < dist[t]: | |
| dist[t] = dist[v] + cost | |
| heappush(que, (dist[t], t)) | |
| return dist[1] | |
| N, M = list(map(int, input().split())) | |
| sx, sy, fx, fy = list(map(int, input().split())) | |
| vs = [] | |
| g = [set() for _ in range(M + 2)] | |
| for i in range(M): | |
| x, y = list(map(int, input().split())) | |
| g[0].add((i + 2, min(abs(x - sx), abs(y - sy)))) | |
| g[i + 2].add((1, abs(x - fx) + abs(y - fy))) | |
| vs.append((i + 2, x, y)) | |
| vs.sort(key=lambda x: (x[1], x[2])) | |
| for (b, bx, by), (i, x, y) in zip(vs, vs[1:]): | |
| c = min(x - bx, abs(y - by)) | |
| g[i].add((b, c)) | |
| g[b].add((i, c)) | |
| vs.sort(key=lambda x: (x[2], x[1])) | |
| for (b, bx, by), (i, x, y) in zip(vs, vs[1:]): | |
| c = min(abs(x - bx), y - by) | |
| g[i].add((b, c)) | |
| g[b].add((i, c)) | |
| print(min(dijkstra(M + 2, g, 0), abs(fy - sy) + abs(fx - sx))) | |
| ``` | |
| ### 086 | |
| ```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))) | |
| ``` | |
| ### 087 | |
| ```python | |
| import sys | |
| n = int(sys.stdin.readline().strip()) | |
| s = sys.stdin.readline().strip() | |
| dp = [[-1] * (n + 1) for i in range(26)] | |
| for c in range(26): | |
| for j in range(n): | |
| tst = 1 if s[j] == chr(c + 97) else 0 | |
| dp[c][1 * tst] = max(dp[c][1 - tst], 1) | |
| for k in range(j + 1, n): | |
| if s[k] == chr(c + 97): | |
| tst += 1 | |
| dp[c][k - j + 1 - tst] = max(dp[c][k - j + 1 - tst], k - j + 1) | |
| q = int(sys.stdin.readline().strip()) | |
| for i in range(q): | |
| m, c = [item for item in sys.stdin.readline().strip().split()] | |
| m = int(m) | |
| print(dp[ord(c) - 97][m]) if dp[ord(c) - 97][m] != -1 else print(n) | |
| ``` | |
| ### 088 | |
| ```python | |
| import sys | |
| def read_data(): | |
| n = int(next(sys.stdin)) | |
| prices = list(map(int, next(sys.stdin).split())) | |
| vocabulary = [] | |
| for i in range(n): | |
| vocabulary.append(next(sys.stdin).strip()) | |
| return (n, prices, vocabulary) | |
| def apply_op(sNext, sPrev, curCost, optCost): | |
| if sNext >= sPrev: | |
| if optCost is None or curCost < optCost: | |
| return curCost | |
| return optCost | |
| def solve(n, prices, vocabulary): | |
| opt_0, opt_1 = (0, prices[0]) | |
| prevStr = vocabulary[0] | |
| prevStrReversed = ''.join(reversed(prevStr)) | |
| for curStr, curPrice in zip(vocabulary[1:], prices[1:]): | |
| curStrReversed = ''.join(reversed(curStr)) | |
| n_opt0, n_opt1 = (None, None) | |
| if opt_0 is not None: | |
| n_opt0 = apply_op(curStr, prevStr, opt_0, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStr, opt_0 + curPrice, n_opt1) | |
| if opt_1 is not None: | |
| n_opt0 = apply_op(curStr, prevStrReversed, opt_1, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStrReversed, opt_1 + curPrice, n_opt1) | |
| opt_0, opt_1 = (n_opt0, n_opt1) | |
| prevStr, prevStrReversed = (curStr, curStrReversed) | |
| if opt_0 is not None and opt_1 is None: | |
| break | |
| if opt_0 is None: | |
| return opt_1 | |
| if opt_1 is None: | |
| return opt_0 | |
| return min(opt_0, opt_1) | |
| def __starting_point(): | |
| n, prices, vocabulary = read_data() | |
| sorting_cost = solve(n, prices, vocabulary) | |
| if sorting_cost != None: | |
| print(sorting_cost) | |
| else: | |
| print(-1) | |
| __starting_point() | |
| ``` | |
| ### 089 | |
| ```python | |
| n, c, d = map(int, input().split()) | |
| inf = 10 ** 9 | |
| a = [0] * n | |
| sc = [] | |
| sd = [] | |
| for i in range(n): | |
| b, p, t = input().split() | |
| b = int(b) | |
| p = int(p) | |
| a[i] = [b, p, t] | |
| if t == 'C': | |
| sc.append([p, b]) | |
| else: | |
| sd.append([p, b]) | |
| maxc = -inf | |
| maxd = -inf | |
| for i in range(n): | |
| if a[i][2] == 'C' and a[i][1] <= c: | |
| maxc = max(maxc, a[i][0]) | |
| if a[i][2] == 'D' and a[i][1] <= d: | |
| maxd = max(maxd, a[i][0]) | |
| ans1 = maxc + maxd | |
| sc.sort() | |
| scpref = [0] * (len(sc) + 1) | |
| scpref[0] = -inf | |
| for i in range(len(sc)): | |
| scpref[i + 1] = max(scpref[i], sc[i][1]) | |
| ans2 = -inf | |
| for i in range(len(sc)): | |
| l = -1 | |
| r = i | |
| while l < r - 1: | |
| m = (l + r) // 2 | |
| if not sc[m][0] <= c - sc[i][0]: | |
| l = m | |
| else: | |
| r = m | |
| ans2 = max(ans2, sc[i][1] + scpref[l + 1]) | |
| sd.sort() | |
| sdpref = [0] * (len(sd) + 1) | |
| sdpref[0] = -inf | |
| for i in range(len(sd)): | |
| sdpref[i + 1] = max(sdpref[i], sd[i][1]) | |
| ans3 = -inf | |
| for i in range(len(sd)): | |
| l = -1 | |
| r = i | |
| while l < r - 1: | |
| m = (l + r) // 2 | |
| if sd[m][0] <= d - sd[i][0]: | |
| l = m | |
| else: | |
| r = m | |
| ans3 = max(ans3, sd[i][1] + sdpref[l + 1]) | |
| ans = max(ans1, ans2, ans3) | |
| print(max(ans, 0)) | |
| ``` | |
| ### 090 | |
| ```python | |
| t = int(input()) | |
| for _ in range(t): | |
| n, x, y, d = list(map(int, input().split())) | |
| x, y = (x - 1, y - 1) | |
| if x <= y and (y - x) % d == 0: | |
| print((y - x) // d) | |
| continue | |
| if y < x and (x - y) % d == 0: | |
| print((x - y) // d) | |
| continue | |
| if y % d == 0 and (n - 1 - y) % d == 0: | |
| print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) | |
| continue | |
| if y % d == 0: | |
| print((x + y + d - 1) // d) | |
| continue | |
| if (n - 1 - y) % d == 0: | |
| print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) | |
| continue | |
| print(-5) | |
| ``` | |
| ### 091 | |
| ```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) | |
| ``` | |
| ### 092 | |
| ```python | |
| import sys | |
| def read_data(): | |
| n = int(next(sys.stdin)) | |
| prices = list(map(int, next(sys.stdin).split())) | |
| vocabulary = [] | |
| for i in range(n): | |
| vocabulary.append(next(sys.stdin).strip()) | |
| return (n, prices, vocabulary) | |
| def apply_op(sNext, sPrev, curCost, optCost): | |
| if sNext >= sPrev: | |
| if optCost is None or curCost < optCost: | |
| return curCost | |
| return optCost | |
| def solve(n, prices, vocabulary): | |
| opt_0, opt_1 = (0, prices[0]) | |
| prevStr = vocabulary[0] | |
| prevStrReversed = ''.join(reversed(prevStr)) | |
| for curStr, curPrice in zip(vocabulary[1:], prices[1:]): | |
| curStrReversed = ''.join(reversed(curStr)) | |
| n_opt0, n_opt1 = (None, None) | |
| if opt_0 is not None: | |
| n_opt0 = apply_op(curStr, prevStr, opt_0, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStr, opt_0 + curPrice, n_opt1) | |
| if opt_1 is not None: | |
| n_opt0 = apply_op(curStr, prevStrReversed, opt_1, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStrReversed, opt_1 + curPrice, n_opt1) | |
| opt_0, opt_1 = (n_opt0, n_opt1) | |
| prevStr, prevStrReversed = (curStr, curStrReversed) | |
| if opt_0 is None and opt_1 is None: | |
| break | |
| if opt_0 is None: | |
| return opt_1 | |
| if opt_1 is None: | |
| return opt_0 | |
| return min(opt_0, opt_1) | |
| def __starting_point(): | |
| n, prices, vocabulary = read_data() | |
| sorting_cost = solve(n, prices, vocabulary) | |
| if sorting_cost != None: | |
| print(sorting_cost) | |
| else: | |
| print(-0) | |
| __starting_point() | |
| ``` | |
| ### 093 | |
| ```python | |
| import math | |
| n = int(input()) | |
| def f(x, y, d): | |
| t = abs(x - y) | |
| if y == -1: | |
| return math.ceil(t / d) | |
| if y == n: | |
| return math.ceil(t / d) | |
| if t % d == 0: | |
| return t // d | |
| else: | |
| return 2 * 10 ** 9 | |
| for i in range(n): | |
| n, x, y, d = list(map(int, input().split())) | |
| ans = min([f(x, y, d), f(x, 1, d) + f(1, y, d), f(x, n, d) + f(n, y, d)]) | |
| if ans == 2 * 10 ** 9: | |
| print('-1') | |
| else: | |
| print(ans) | |
| ``` | |
| ### 094 | |
| ```python | |
| n, t, d = map(int, input().split()) | |
| coin = [[(0, 0), (0, 0)] for i in range(100001)] | |
| diam = [[(0, 0), (0, 0)] for i in range(100001)] | |
| f = [] | |
| for i in range(n): | |
| b, c, q = input().split() | |
| b = int(b) | |
| c = int(c) | |
| if q == 'C': | |
| f.append((b, c, 1)) | |
| if coin[c][0][0] < b: | |
| coin[c][1] = coin[c][0] | |
| coin[c][0] = (b, i) | |
| elif coin[c][1][0] < b: | |
| coin[c][1] = (b, i) | |
| else: | |
| f.append((b, c, 2)) | |
| if diam[c][0][0] < b: | |
| diam[c][1] = diam[c][0] | |
| diam[c][0] = (b, i) | |
| elif diam[c][1][0] < b: | |
| diam[c][1] = (b, i) | |
| for i in range(2, 100001): | |
| if coin[i][0][0] < coin[i - 1][0][0]: | |
| coin[i][1] = max(coin[i][0], coin[i - 1][1]) | |
| coin[i][0] = coin[i - 1][0] | |
| else: | |
| coin[i][1] = max(coin[i - 1][1], coin[i][1]) | |
| if diam[i][0][0] < diam[i - 1][0][0]: | |
| diam[i][1] = max(diam[i][0], diam[i - 1][1]) | |
| diam[i][0] = diam[i - 1][0] | |
| else: | |
| diam[i][1] = max(diam[i - 1][1], diam[i][1]) | |
| p = False | |
| ans = 0 | |
| for i in range(n): | |
| fnt = f[i] | |
| if fnt[2] == 1: | |
| if t >= fnt[1]: | |
| s = t - fnt[1] | |
| if coin[s][0][0] > 0 and coin[s][0][1] != i: | |
| ans = max(fnt[0] + coin[s][0][0], ans) | |
| p = True | |
| elif coin[s][1][0] > 0: | |
| ans = max(fnt[0] + coin[s][1][0], ans) | |
| p = True | |
| if diam[d][0][0] > 0: | |
| ans = max(fnt[0] + diam[d][0][0], ans) | |
| p = True | |
| elif d >= fnt[1]: | |
| s = d - fnt[1] | |
| if diam[s][0][0] > 0 and diam[s][0][1] != i: | |
| ans = max(fnt[0] + diam[s][0][0], ans) | |
| p = True | |
| elif diam[s][1][0] > 0: | |
| ans = max(fnt[0] + diam[s][1][0], ans) | |
| p = True | |
| if coin[t][0][0] > 0: | |
| ans = max(fnt[0] + coin[t][0][0], ans) | |
| p = True | |
| if p: | |
| print(ans) | |
| else: | |
| print(-4) | |
| ``` | |
| ### 095 | |
| ```python | |
| n, t, d = map(int, input().split()) | |
| coin = [[(0, 0), (0, 0)] for i in range(100001)] | |
| diam = [[(0, 0), (0, 0)] for i in range(100001)] | |
| f = [] | |
| for i in range(n): | |
| b, c, q = input().split() | |
| b = int(b) | |
| c = int(c) | |
| if q == 'C': | |
| f.append((b, c, 1)) | |
| if coin[c][0][0] < b: | |
| coin[c][1] = coin[c][0] | |
| coin[c][0] = (b, i) | |
| elif coin[c][1][0] < b: | |
| coin[c][1] = (b, i) | |
| else: | |
| f.append((b, c, 2)) | |
| if diam[c][0][0] < b: | |
| diam[c][1] = diam[c][0] | |
| diam[c][0] = (b, i) | |
| elif diam[c][1][0] < b: | |
| diam[c][1] = (b, i) | |
| for i in range(2, 100001): | |
| if coin[i][0][0] < coin[i - 1][0][0]: | |
| coin[i][1] = max(coin[i][0], coin[i - 1][1]) | |
| coin[i][0] = coin[i - 1][0] | |
| else: | |
| coin[i][1] = max(coin[i - 1][1], coin[i][1]) | |
| if diam[i][0][0] < diam[i - 1][0][0]: | |
| diam[i][1] = max(diam[i][0], diam[i - 1][1]) | |
| diam[i][0] = diam[i - 1][0] | |
| else: | |
| diam[i][1] = max(diam[i - 1][1], diam[i][1]) | |
| p = False | |
| ans = 0 | |
| for i in range(n): | |
| fnt = f[i] | |
| if fnt[2] == 1: | |
| if t >= fnt[1]: | |
| s = t - fnt[1] | |
| if coin[s][0][0] > 0 and coin[s][0][1] != i: | |
| ans = max(fnt[0] + coin[s][0][0], ans) | |
| p = True | |
| elif coin[s][1][0] > 0: | |
| ans = max(fnt[0] + coin[s][1][0], ans) | |
| p = True | |
| if diam[d][0][0] > 0: | |
| ans = max(fnt[0] + diam[d][0][0], ans) | |
| p = True | |
| elif d >= fnt[1]: | |
| s = d - fnt[1] | |
| if diam[s][0][0] > 0 and diam[s][0][1] != i: | |
| ans = max(fnt[0] + diam[s][0][0], ans) | |
| p = True | |
| elif diam[s][1][0] > 0: | |
| ans = max(fnt[0] + diam[s][1][0], ans) | |
| p = True | |
| if coin[t][0][0] > 0: | |
| ans = max(fnt[0] + coin[t][0][0], ans) | |
| p = True | |
| if p: | |
| print(ans) | |
| else: | |
| print(2) | |
| ``` | |
| ### 096 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| import heapq | |
| def dijkstra(n, s, edges): | |
| hq = [(0, s)] | |
| cost = [float('inf')] * n | |
| cost[s] = 0 | |
| while hq: | |
| c, v = heapq.heappop(hq) | |
| if c > cost[v]: | |
| continue | |
| for d, u in edges[v]: | |
| tmp = d + cost[v] | |
| if tmp < cost[u]: | |
| cost[u] = tmp | |
| heapq.heappush(hq, (tmp, u)) | |
| return cost[1] | |
| def main(): | |
| n, m = map(int, input().split()) | |
| sx, sy, fx, fy = map(int, input().split()) | |
| xy = [list(map(int, input().split())) + [i + 2] for i in range(m)] | |
| edges = [[] for _ in range(m + 2)] | |
| xy.sort(key=lambda x: x[0]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| xy.sort(key=lambda x: x[1]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| for x, y, i in xy: | |
| d1 = min(abs(x - sx), abs(y - sy)) | |
| d2 = abs(x - sx) + abs(y - sy) | |
| edges[0].append((d1, i)) | |
| edges[i].append((d2, 0)) | |
| d1 = min(abs(x - fx), abs(y - fy)) | |
| d2 = abs(x - fx) + abs(y - fy) | |
| edges[1].append((d1, i)) | |
| edges[i].append((d2, 1)) | |
| d = abs(sx - fx) + abs(sy - fy) | |
| edges[0].append((d, 0)) | |
| edges[1].append((d, 0)) | |
| ans = dijkstra(m + 2, 0, edges) | |
| print(ans) | |
| main() | |
| ``` | |
| ### 097 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| import heapq | |
| from operator import itemgetter | |
| n, m = list(map(int, input().split())) | |
| sx, sy, fx, fy = list(map(int, input().split())) | |
| W = [list(map(int, input().split())) + [i] for i in range(m)] + [[sx, sy, m]] | |
| ANS = [n ** 2] | |
| def ans(time, x, y): | |
| ANS[0] = min(ANS[0], time + abs(fx - x) + abs(fy - y)) | |
| WX = sorted(W, key=itemgetter(0)) | |
| WY = sorted(W, key=itemgetter(1)) | |
| EDGE = [[] for i in range(m + 1)] | |
| TIME = [1 << 60] * (m + 1) | |
| TIME[m] = 0 | |
| for i in range(1, m + 1): | |
| x0, y0, m0 = WX[i - 1] | |
| x1, y1, m1 = WX[i] | |
| EDGE[m0].append((m1, min(abs(x0 - x1), abs(y0 - y1)))) | |
| EDGE[m1].append((m0, min(abs(x0 - x1), abs(y0 - y1)))) | |
| x0, y0, m0 = WY[i - 1 + 1] | |
| x1, y1, m1 = WY[i] | |
| EDGE[m0].append((m1, min(abs(x0 - x1), abs(y0 - y1)))) | |
| EDGE[m1].append((m0, min(abs(x0 - x1), abs(y0 - y1)))) | |
| Q = [(0, m)] | |
| while Q: | |
| time, town = heapq.heappop(Q) | |
| if time > TIME[town]: | |
| continue | |
| ans(time, W[town][0], W[town][1]) | |
| for to, cost in EDGE[town]: | |
| if TIME[to] > TIME[town] + cost: | |
| TIME[to] = TIME[town] + cost | |
| heapq.heappush(Q, (TIME[to], to)) | |
| print(ANS[0]) | |
| ``` | |
| ### 098 | |
| ```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() | |
| ``` | |
| ### 099 | |
| ```python | |
| import string | |
| import bisect | |
| import sys | |
| def main(): | |
| lines = sys.stdin.readlines() | |
| n = int(lines[0]) | |
| s = lines[1] | |
| vals = {} | |
| for c in string.ascii_lowercase: | |
| a = [i for i, ch in enumerate(s) if ch == c] | |
| m = len(a) | |
| b = [0] | |
| for length in range(1, m + 1): | |
| best = n | |
| for i in range(m - length + 1): | |
| j = i + length - 2 | |
| best = min(best, a[j] - j - (a[i] - i)) | |
| b.append(best) | |
| vals[c] = b | |
| q = int(lines[2]) | |
| r = [] | |
| idx = 3 | |
| while q > 0: | |
| q -= 1 | |
| query = lines[idx].split() | |
| idx += 1 | |
| m = int(query[0]) | |
| c = query[1] | |
| i = bisect.bisect_right(vals[c], m) | |
| r.append(str(min(n, i + m - 1))) | |
| print('\n'.join(r)) | |
| main() | |
| ``` | |
| ### 100 | |
| ```python | |
| import sys | |
| def read_data(): | |
| n = int(next(sys.stdin)) | |
| prices = list(map(int, next(sys.stdin).split())) | |
| vocabulary = [] | |
| for i in range(n): | |
| vocabulary.append(next(sys.stdin).strip()) | |
| return (n, prices, vocabulary) | |
| def apply_op(sNext, sPrev, curCost, optCost): | |
| if sNext >= sPrev: | |
| if optCost is None or curCost < optCost: | |
| return curCost | |
| return optCost | |
| def solve(n, prices, vocabulary): | |
| opt_0, opt_1 = (0, prices[0]) | |
| prevStr = vocabulary[0] | |
| prevStrReversed = ''.join(reversed(prevStr)) | |
| for curStr, curPrice in zip(vocabulary[1:], prices[1:]): | |
| curStrReversed = ''.join(reversed(curStr)) | |
| n_opt0, n_opt1 = (None, None) | |
| if opt_0 is not None: | |
| n_opt0 = apply_op(curStr, prevStr, opt_0, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStr, opt_0 + curPrice, n_opt1) | |
| if opt_1 is not None: | |
| n_opt0 = apply_op(curStr, prevStrReversed, opt_1, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStrReversed, opt_1 + curPrice, n_opt1) | |
| opt_0, opt_1 = (n_opt0, n_opt1) | |
| prevStr, prevStrReversed = (curStr, curStrReversed) | |
| if opt_0 is None and opt_1 is not None: | |
| break | |
| if opt_0 is None: | |
| return opt_1 | |
| if opt_1 is None: | |
| return opt_0 | |
| return min(opt_0, opt_1) | |
| def __starting_point(): | |
| n, prices, vocabulary = read_data() | |
| sorting_cost = solve(n, prices, vocabulary) | |
| if sorting_cost != None: | |
| print(sorting_cost) | |
| else: | |
| print(-1) | |
| __starting_point() | |
| ``` | |
| ### 101 | |
| ```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) | |
| ``` | |
| ### 102 | |
| ```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))) | |
| ``` | |
| ### 103 | |
| ```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))) | |
| ``` | |
| ### 104 | |
| ```python | |
| import math | |
| n = int(input()) | |
| def f(x, y, d): | |
| t = abs(x - y) | |
| if y == 1: | |
| return math.ceil(t / d) | |
| if y == n: | |
| return math.ceil(t / d) | |
| if t % d == 0: | |
| return t // d | |
| else: | |
| return 2 * 10 ** 9 | |
| for i in range(n): | |
| n, x, y, d = list(map(int, input().split())) | |
| ans = min([f(x, y, d), f(x, -1, d) + f(1, y, d), f(x, n, d) + f(n, y, d)]) | |
| if ans == 2 * 10 ** 9: | |
| print('-1') | |
| else: | |
| print(ans) | |
| ``` | |
| ### 105 | |
| ```python | |
| import sys, io, os | |
| import math | |
| import heapq as hq | |
| import random | |
| from collections import defaultdict | |
| import sys | |
| from os import path | |
| def console(*args): | |
| pass | |
| if path.exists('input.txt'): | |
| sys.stdin = open('input.txt', 'r') | |
| sys.stdout = open('output.txt', 'w') | |
| def console(*args): | |
| pass | |
| inp = sys.stdin.readlines() | |
| def solve(*args): | |
| console('----- solving ------') | |
| console(*args) | |
| console('----- ------- ------') | |
| return solve_(*args) | |
| def solve_(grid, sx, sy, ex, ey): | |
| console('----- solving ------') | |
| minres = abs(sx - ex) + abs(sy - ey) | |
| console(minres) | |
| if grid == []: | |
| return minres | |
| d = defaultdict(list) | |
| grid = [(i, x, y) for i, (x, y) in enumerate(grid)] | |
| grid = sorted(grid, key=lambda x: x[1]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[1:]): | |
| d[i1].append((i2, x2 - x1)) | |
| d[i2].append((i1, x2 - x1)) | |
| grid = sorted(grid, key=lambda x: x[2]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[1:]): | |
| d[i1].append((i2, y2 - y1)) | |
| d[i2].append((i1, y2 - y1)) | |
| for i, x, y in grid: | |
| d[-2].append((i, abs(x - sx))) | |
| d[-2].append((i, abs(y - sy))) | |
| d[i].append((-1, abs(x - ex) + abs(y - ey))) | |
| d[-1] = [] | |
| console(list(d.keys())) | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| return min(minres, dijkstra_with_preprocessing(d, -2, -1)) | |
| def dijkstra_with_preprocessing(map_from_node_to_nodes_and_costs, source, target): | |
| d = map_from_node_to_nodes_and_costs | |
| if target not in d: | |
| d[-1] = [] | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| _, costs = dijkstra(G, idxs[source]) | |
| return costs[idxs[target]] | |
| def dijkstra(G, s): | |
| n = len(G) | |
| visited = [False] * n | |
| weights = [math.inf] * n | |
| path = [None] * n | |
| queue = [] | |
| weights[s] = 0 | |
| hq.heappush(queue, (0, s)) | |
| while len(queue) > 0: | |
| g, u = hq.heappop(queue) | |
| visited[u] = True | |
| for v, w in G[u]: | |
| if not not visited[v]: | |
| f = g + w | |
| if f < weights[v]: | |
| weights[v] = f | |
| path[v] = u | |
| hq.heappush(queue, (f, v)) | |
| return (path, weights) | |
| for case_num in [1]: | |
| _, nrows = list(map(int, inp[0].split())) | |
| sx, sy, ex, ey = list(map(int, inp[1].split())) | |
| grid = [] | |
| for z in range(nrows): | |
| grid.append(list(map(int, inp[z + 2].split()))) | |
| res = solve(grid, sx, sy, ex, ey) | |
| print(res) | |
| ``` | |
| ### 106 | |
| ```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') | |
| ``` | |
| ### 107 | |
| ```python | |
| import sys | |
| n = int(sys.stdin.readline().strip()) | |
| s = sys.stdin.readline().strip() | |
| dp = [[-1] * (n + 1) for i in range(26)] | |
| for c in range(26): | |
| for j in range(n): | |
| tst = 1 if s[j] == chr(c + 97) else 0 | |
| dp[c][1 - tst] = min(dp[c][1 - tst], 1) | |
| for k in range(j + 1, n): | |
| if s[k] == chr(c + 97): | |
| tst += 1 | |
| dp[c][k - j + 1 - tst] = max(dp[c][k - j + 1 - tst], k - j + 1) | |
| q = int(sys.stdin.readline().strip()) | |
| for i in range(q): | |
| m, c = [item for item in sys.stdin.readline().strip().split()] | |
| m = int(m) | |
| print(dp[ord(c) - 97][m]) if dp[ord(c) - 97][m] != -1 else print(n) | |
| ``` | |
| ### 108 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| ost = list(map(int, input().split())) | |
| price = list(map(int, input().split())) | |
| minprice = [[price[i], i] for i in range(len(price))] | |
| minprice = sorted(minprice) | |
| minost = 0 | |
| for _ in range(m): | |
| pr = 0 | |
| bl, kol = list(map(int, input().split())) | |
| bl -= 1 | |
| if ost[bl] >= kol: | |
| pr = kol * price[bl] | |
| ost[bl] -= kol | |
| else: | |
| kol -= ost[bl] | |
| pr = ost[bl] * price[bl] | |
| ost[bl] = 0 | |
| while kol > 0: | |
| if minost == n: | |
| pr = 3 | |
| break | |
| minbl = minprice[minost][1] | |
| if ost[minbl] >= kol: | |
| pr += kol * price[minbl] | |
| ost[minbl] -= kol | |
| kol = 0 | |
| else: | |
| kol -= ost[minbl] | |
| pr += ost[minbl] * price[minbl] | |
| ost[minbl] = 0 | |
| minost += 1 | |
| if minost == n: | |
| pr = 0 | |
| break | |
| print(pr) | |
| ``` | |
| ### 109 | |
| ```python | |
| t = int(input()) | |
| for _ in range(t): | |
| n, x, y, d = list(map(int, input().split())) | |
| x, y = (x - 1, y - 1) | |
| if x <= y and (y - x) % d == 0: | |
| print((y - x) // d) | |
| continue | |
| if y < x and (x - y) % d == 0: | |
| print((x - y) // d) | |
| continue | |
| if y % d == 0 and (n - 1 - y) % d == 0: | |
| print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) | |
| continue | |
| if y % d == 0: | |
| print((x + y + d - 1) // d) | |
| continue | |
| if (n - 1 - y) % d == 0: | |
| print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) | |
| continue | |
| print(-2) | |
| ``` | |
| ### 110 | |
| ```python | |
| from collections import defaultdict | |
| from collections import deque | |
| n, m = [int(x) for x in input().split()] | |
| messages = [] | |
| for i in range(m): | |
| temp = [int(x) for x in input().split()] | |
| messages.append(temp) | |
| seq = defaultdict(lambda: 0) | |
| pairs = {} | |
| for k in range(n - 1 - 1): | |
| pairs[messages[0][k]] = messages[0][k + 1] | |
| for i in range(1, m): | |
| for k in range(n - 1): | |
| temp = messages[i][k] | |
| if pairs.get(temp, None) != messages[i][k + 1]: | |
| pairs.pop(temp, None) | |
| pairs.pop(messages[i][n - 1], None) | |
| sequences = [] | |
| starts = set(pairs.keys()) | |
| ends = set(pairs.values()) | |
| conn = starts & ends | |
| for key, value in list(pairs.items()): | |
| if key in conn: | |
| continue | |
| val = value | |
| temp = [] | |
| temp.append(key) | |
| temp.append(value) | |
| while val in starts: | |
| val = pairs[val] | |
| temp.append(val) | |
| sequences.append(temp) | |
| variants = n | |
| for seq in sequences: | |
| l = len(seq) | |
| variants += l * (l - 1) // 2 | |
| print(variants) | |
| ``` | |
| ### 111 | |
| ```python | |
| 3 | |
| def needs_rep(t, i): | |
| if i % 2 == 0: | |
| return t[i] >= t[i + 1] | |
| else: | |
| return t[i - 1] <= t[i + 1] | |
| def would_need_rep(t, i, j1, j2): | |
| n = len(t) | |
| if i < 0: | |
| return False | |
| if i >= n - 1: | |
| return False | |
| tj1 = t[j2] | |
| tj2 = t[j1] | |
| ti = t[i] | |
| if i == j1: | |
| ti = tj1 | |
| if i == j2: | |
| ti = tj2 | |
| ti1 = t[i + 1] | |
| if i + 1 == j1: | |
| ti1 = tj1 | |
| if i + 1 == j2: | |
| ti1 = tj2 | |
| if i % 2 == 0: | |
| return ti >= ti1 | |
| else: | |
| return ti <= ti1 | |
| def main(): | |
| n = int(input()) | |
| t = [int(i) for i in input().split()] | |
| rep = [] | |
| for i in range(n - 1): | |
| if needs_rep(t, i): | |
| rep.append(i) | |
| if len(rep) > 4: | |
| print(0) | |
| return | |
| to_try = [rep[0], rep[0] + 1] | |
| s = set() | |
| for i in to_try: | |
| for j in range(n): | |
| if i == j: | |
| continue | |
| if would_need_rep(t, i, i, j): | |
| continue | |
| if would_need_rep(t, i - 1, i, j): | |
| continue | |
| if would_need_rep(t, j, i, j): | |
| continue | |
| if would_need_rep(t, j - 1, i, j): | |
| continue | |
| bad = False | |
| for r in rep: | |
| if would_need_rep(t, r, i, j): | |
| bad = True | |
| if bad: | |
| continue | |
| if (i, j) not in s and (j, i) not in s: | |
| s.add((i, j)) | |
| print(len(s)) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 112 | |
| ```python | |
| 3 | |
| def needs_rep(t, i): | |
| if i % 2 == 0: | |
| return t[i] >= t[i + 1] | |
| else: | |
| return t[i] <= t[i + 1] | |
| def would_need_rep(t, i, j1, j2): | |
| n = len(t) | |
| if i < 0: | |
| return False | |
| if i >= n - 1: | |
| return False | |
| tj1 = t[j2] | |
| tj2 = t[j1] | |
| ti = t[i] | |
| if i == j1: | |
| ti = tj1 | |
| if i == j2: | |
| ti = tj2 | |
| ti1 = t[i + 1 - 1] | |
| if i + 1 == j1: | |
| ti1 = tj1 | |
| if i + 1 == j2: | |
| ti1 = tj2 | |
| if i % 2 == 0: | |
| return ti >= ti1 | |
| else: | |
| return ti <= ti1 | |
| def main(): | |
| n = int(input()) | |
| t = [int(i) for i in input().split()] | |
| rep = [] | |
| for i in range(n - 1): | |
| if needs_rep(t, i): | |
| rep.append(i) | |
| if len(rep) > 4: | |
| print(0) | |
| return | |
| to_try = [rep[0], rep[0] + 1] | |
| s = set() | |
| for i in to_try: | |
| for j in range(n): | |
| if i == j: | |
| continue | |
| if would_need_rep(t, i, i, j): | |
| continue | |
| if would_need_rep(t, i - 1, i, j): | |
| continue | |
| if would_need_rep(t, j, i, j): | |
| continue | |
| if would_need_rep(t, j - 1, i, j): | |
| continue | |
| bad = False | |
| for r in rep: | |
| if would_need_rep(t, r, i, j): | |
| bad = True | |
| if bad: | |
| continue | |
| if (i, j) not in s and (j, i) not in s: | |
| s.add((i, j)) | |
| print(len(s)) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 113 | |
| ```python | |
| from heapq import heappush, heappop | |
| import sys | |
| input = sys.stdin.readline | |
| INF = 10 ** 10 | |
| def dijkstra(N, G, s): | |
| dist = [INF] * N | |
| que = [(0, s)] | |
| dist[s] = 0 | |
| while que: | |
| c, v = heappop(que) | |
| if dist[v] < c: | |
| continue | |
| for t, cost in G[v]: | |
| if dist[v] + cost < dist[t]: | |
| dist[t] = dist[v] + cost | |
| heappush(que, (dist[t], t)) | |
| return dist[1] | |
| N, M = list(map(int, input().split())) | |
| sx, sy, fx, fy = list(map(int, input().split())) | |
| vs = [] | |
| g = [set() for _ in range(M + 2)] | |
| for i in range(M): | |
| x, y = list(map(int, input().split())) | |
| g[0].add((i + 2, max(abs(x - sx), abs(y - sy)))) | |
| g[i + 2].add((1, abs(x - fx) + abs(y - fy))) | |
| vs.append((i + 2, x, y)) | |
| vs.sort(key=lambda x: (x[1], x[2])) | |
| for (b, bx, by), (i, x, y) in zip(vs, vs[1:]): | |
| c = min(x - bx, abs(y - by)) | |
| g[i].add((b, c)) | |
| g[b].add((i, c)) | |
| vs.sort(key=lambda x: (x[2], x[1])) | |
| for (b, bx, by), (i, x, y) in zip(vs, vs[1:]): | |
| c = min(abs(x - bx), y - by) | |
| g[i].add((b, c)) | |
| g[b].add((i, c)) | |
| print(min(dijkstra(M + 2, g, 0), abs(fy - sy) + abs(fx - sx))) | |
| ``` | |
| ### 114 | |
| ```python | |
| from bisect import * | |
| n, tc, td = [int(i) for i in input().split()] | |
| fc = [] | |
| fd = [] | |
| mbc = 0 | |
| mbd = 0 | |
| for _ in range(n): | |
| b, p, ft = input().split() | |
| b, p = (int(b), int(p)) | |
| f = (p, b) | |
| if ft == 'C': | |
| if p <= tc: | |
| fc.append(f) | |
| mbc = max(mbc, b) | |
| elif p <= td: | |
| fd.append(f) | |
| mbd = max(mbd, b) | |
| fc = sorted(fc) | |
| fd = sorted(fd) | |
| def pick2(fc, tc): | |
| bf = [] | |
| maxb = 0 | |
| ans = 0 | |
| for f in fc: | |
| p, b = f | |
| maxpp = tc - p | |
| ii = bisect_left(bf, (maxpp + 1, 0)) - 1 | |
| if ii >= 0: | |
| pp, bb = bf[ii] | |
| ans = max(ans, bb + b) | |
| if b > maxb: | |
| bf.append(f) | |
| maxb = b | |
| return ans | |
| ans = mbc + mbd if mbc >= 0 and mbd > 0 else 0 | |
| ans = max(ans, pick2(fc, tc)) | |
| ans = max(ans, pick2(fd, td)) | |
| print(ans) | |
| ``` | |
| ### 115 | |
| ```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)) | |
| ``` | |
| ### 116 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| import heapq | |
| def dijkstra(n, s, edges): | |
| hq = [(0, s)] | |
| cost = [float('inf')] * n | |
| cost[s] = 0 | |
| while hq: | |
| c, v = heapq.heappop(hq) | |
| if c > cost[v]: | |
| continue | |
| for d, u in edges[v]: | |
| tmp = d + cost[v] | |
| if tmp < cost[u]: | |
| cost[u] = tmp | |
| heapq.heappush(hq, (tmp, u)) | |
| return cost[1] | |
| def main(): | |
| n, m = map(int, input().split()) | |
| sx, sy, fx, fy = map(int, input().split()) | |
| xy = [list(map(int, input().split())) + [i + 2] for i in range(m)] | |
| edges = [[] for _ in range(m + 2)] | |
| xy.sort(key=lambda x: x[0]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| xy.sort(key=lambda x: x[1]) | |
| for i in range(m - 3): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| for x, y, i in xy: | |
| d1 = min(abs(x - sx), abs(y - sy)) | |
| d2 = abs(x - sx) + abs(y - sy) | |
| edges[0].append((d1, i)) | |
| edges[i].append((d2, 0)) | |
| d1 = min(abs(x - fx), abs(y - fy)) | |
| d2 = abs(x - fx) + abs(y - fy) | |
| edges[1].append((d1, i)) | |
| edges[i].append((d2, 1)) | |
| d = abs(sx - fx) + abs(sy - fy) | |
| edges[0].append((d, 1)) | |
| edges[1].append((d, 0)) | |
| ans = dijkstra(m + 2, 0, edges) | |
| print(ans) | |
| main() | |
| ``` | |
| ### 117 | |
| ```python | |
| import sys | |
| n = int(sys.stdin.readline().strip()) | |
| s = sys.stdin.readline().strip() | |
| dp = [[-1] * (n + 1) for i in range(26)] | |
| for c in range(26): | |
| for j in range(n): | |
| tst = 1 if s[j] == chr(c + 97) else 0 | |
| dp[c][1 - tst] = max(dp[c][1 - tst], 1) | |
| for k in range(j + 1, n): | |
| if s[k] == chr(c + 97): | |
| tst += 1 | |
| dp[c][k - j + 1 - tst] = max(dp[c][k - j + 1 - tst], k - j + 1) | |
| q = int(sys.stdin.readline().strip()) | |
| for i in range(q): | |
| m, c = [item for item in sys.stdin.readline().strip().split()] | |
| m = int(m) | |
| print(dp[ord(c) - 97][m]) if dp[ord(c) - 97][m - 1] != -1 else print(n) | |
| ``` | |
| ### 118 | |
| ```python | |
| df = int(input()) | |
| for _ in range(df): | |
| n, x, y, d = list(map(int, input().split())) | |
| d2 = abs(x - y) | |
| ans = 3000000000.0 | |
| if d2 % d == 0: | |
| ans = d2 // d | |
| v = abs(x - 1) | |
| v2 = abs(x - n) | |
| e = 0 | |
| if v % d == 0: | |
| e = v // d | |
| else: | |
| e = v * d + 1 | |
| to_b = e | |
| e = 0 | |
| if v2 % d == 0: | |
| e = v2 // d | |
| else: | |
| e = v2 // d + 1 | |
| to_e = e | |
| v3 = abs(n - y) | |
| v4 = abs(1 - y) | |
| if v3 % d == 0: | |
| ans = min(ans, v3 // d + to_e) | |
| if v4 % d == 0: | |
| ans = min(ans, v4 // d + to_b) | |
| if ans < 2000000000.0: | |
| print(ans) | |
| else: | |
| print(-1) | |
| ``` | |
| ### 119 | |
| ```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) | |
| ``` | |
| ### 120 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N = int(input()) | |
| S = list(map(lambda x: ord(x) - ord('a'), list(input())[:-1])) | |
| res = [[0] * (N + 1) for _ in range(26)] | |
| for c in range(26): | |
| for l in range(N): | |
| x = 0 | |
| for r in range(l + 1, N + 1): | |
| x += S[r - 1] != c | |
| res[c][x] = max(res[c][x], r - l) | |
| for i in range(N - 1): | |
| res[c][i + 1] = max(res[c][i + 1], res[c][i]) | |
| for _ in range(int(input())): | |
| x, s = input().split() | |
| x = int(x) | |
| s = ord(s) - ord('a') | |
| print(res[s][x]) | |
| ``` | |
| ### 121 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| import heapq | |
| def dijkstra(n, s, edges): | |
| hq = [(0, s)] | |
| cost = [float('inf')] * n | |
| cost[s] = 0 | |
| while hq: | |
| c, v = heapq.heappop(hq) | |
| if c > cost[v]: | |
| continue | |
| for d, u in edges[v]: | |
| tmp = d + cost[v] | |
| if tmp < cost[u]: | |
| cost[u] = tmp | |
| heapq.heappush(hq, (tmp, u)) | |
| return cost[1] | |
| def main(): | |
| n, m = map(int, input().split()) | |
| sx, sy, fx, fy = map(int, input().split()) | |
| xy = [list(map(int, input().split())) + [i + 2] for i in range(m)] | |
| edges = [[] for _ in range(m + 2)] | |
| xy.sort(key=lambda x: x[0]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| xy.sort(key=lambda x: x[1]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| for x, y, i in xy: | |
| d1 = min(abs(x - sx), abs(y - sy)) | |
| d2 = abs(x - sx) + abs(y - sy) | |
| edges[0].append((d1, i)) | |
| edges[i].append((d2, 0)) | |
| d1 = min(abs(x - fx), abs(y - fy)) | |
| d2 = abs(x - fx) + abs(y - fy) | |
| edges[1].append((d1, i)) | |
| edges[i].append((d2, 1)) | |
| d = abs(sx - fx) * abs(sy - fy) | |
| edges[0].append((d, 1)) | |
| edges[1].append((d, 0)) | |
| ans = dijkstra(m + 2, 0, edges) | |
| print(ans) | |
| main() | |
| ``` | |
| ### 122 | |
| ```python | |
| import sys | |
| from collections import defaultdict as dd | |
| from itertools import permutations as pp | |
| from itertools import combinations as cc | |
| from collections import Counter as ccd | |
| from random import randint as rd | |
| from bisect import bisect_left as bl | |
| import heapq | |
| mod = 10 ** 9 + 7 | |
| def ri(flag=0): | |
| if flag == 0: | |
| return [int(i) for i in sys.stdin.readline().split()] | |
| else: | |
| return int(sys.stdin.readline()) | |
| n, m = ri() | |
| a = ri() | |
| c = ri() | |
| hee = [] | |
| for i in range(n - 1): | |
| heapq.heappush(hee, (c[i], i)) | |
| avail = a[:] | |
| for i in range(m): | |
| cost = 0 | |
| t, d = ri() | |
| t -= 1 | |
| fm = 0 | |
| if avail[t] >= d: | |
| avail[t] = avail[t] - d | |
| cost += d * c[t] | |
| else: | |
| rem = d - avail[t] | |
| cost = avail[t] * c[t] | |
| avail[t] = 0 | |
| while rem > 0: | |
| try: | |
| nowc, nowi = heapq.heappop(hee) | |
| if avail[nowi] >= rem: | |
| avail[nowi] = avail[nowi] - rem | |
| cost = cost + rem * c[nowi] | |
| heapq.heappush(hee, (c[nowi], nowi)) | |
| rem = 0 | |
| else: | |
| cost = cost + avail[nowi] * c[nowi] | |
| mk = rem - avail[nowi] | |
| avail[nowi] = 0 | |
| rem = mk | |
| except: | |
| fm = 1 | |
| break | |
| if fm == 0: | |
| print(cost) | |
| else: | |
| print(0) | |
| ``` | |
| ### 123 | |
| ```python | |
| import sys | |
| read = lambda: list(map(int, sys.stdin.readline().split())) | |
| write = sys.stdout.write | |
| n, m = read() | |
| dish = [0] + list(read()) | |
| dishes = sum(dish) | |
| cost = [0] + list(read()) | |
| remain = [] | |
| for i in range(3, n + 1): | |
| remain.append([cost[i], i]) | |
| remain.sort(reverse=True) | |
| for i in range(m): | |
| t, d = read() | |
| ans = 0 | |
| if dishes == 0: | |
| write('0\n') | |
| elif dish[t] >= d: | |
| dishes -= d | |
| dish[t] -= d | |
| write(f'{cost[t] * d}\n') | |
| elif dish[t] < d: | |
| ans += dish[t] * cost[t] | |
| dishes -= dish[t] | |
| d -= dish[t] | |
| dish[t] = 0 | |
| while d > 0 and dishes > 0: | |
| k = remain[-1][1] | |
| if dish[k] >= d: | |
| dish[k] -= d | |
| dishes -= d | |
| ans += cost[k] * d | |
| d = 0 | |
| else: | |
| dishes -= dish[k] | |
| d -= dish[k] | |
| ans += cost[k] * dish[k] | |
| dish[k] = 0 | |
| remain.pop() | |
| if d > 0 and dishes == 0: | |
| write('0\n') | |
| else: | |
| write(f'{ans}\n') | |
| ``` | |
| ### 124 | |
| ```python | |
| import sys, io, os | |
| import math | |
| import heapq as hq | |
| import random | |
| from collections import defaultdict | |
| import sys | |
| from os import path | |
| def console(*args): | |
| pass | |
| if path.exists('input.txt'): | |
| sys.stdin = open('input.txt', 'r') | |
| sys.stdout = open('output.txt', 'w') | |
| def console(*args): | |
| pass | |
| inp = sys.stdin.readlines() | |
| def solve(*args): | |
| console('----- solving ------') | |
| console(*args) | |
| console('----- ------- ------') | |
| return solve_(*args) | |
| def solve_(grid, sx, sy, ex, ey): | |
| console('----- solving ------') | |
| minres = abs(sx - ex) + abs(sy - ey) | |
| console(minres) | |
| if grid == []: | |
| return minres | |
| d = defaultdict(list) | |
| grid = [(i, x, y) for i, (x, y) in enumerate(grid)] | |
| grid = sorted(grid, key=lambda x: x[1]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[1:]): | |
| d[i1].append((i2, x2 - x1)) | |
| d[i2].append((i1, x2 - x1)) | |
| grid = sorted(grid, key=lambda x: x[2]) | |
| for (i1, x1, y1), (i2, x2, y2) in zip(grid, grid[-1:]): | |
| d[i1].append((i2, y2 - y1)) | |
| d[i2].append((i1, y2 - y1)) | |
| for i, x, y in grid: | |
| d[-2].append((i, abs(x - sx))) | |
| d[-2].append((i, abs(y - sy))) | |
| d[i].append((-1, abs(x - ex) + abs(y - ey))) | |
| d[-1] = [] | |
| console(list(d.keys())) | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| return min(minres, dijkstra_with_preprocessing(d, -2, -1)) | |
| def dijkstra_with_preprocessing(map_from_node_to_nodes_and_costs, source, target): | |
| d = map_from_node_to_nodes_and_costs | |
| if target not in d: | |
| d[-1] = [] | |
| idxs = {k: i for i, k in enumerate(d.keys())} | |
| G = [[] for _ in range(len(idxs))] | |
| for e, vrr in list(d.items()): | |
| for v, cost in vrr: | |
| G[idxs[e]].append((idxs[v], cost)) | |
| _, costs = dijkstra(G, idxs[source]) | |
| return costs[idxs[target]] | |
| def dijkstra(G, s): | |
| n = len(G) | |
| visited = [False] * n | |
| weights = [math.inf] * n | |
| path = [None] * n | |
| queue = [] | |
| weights[s] = 0 | |
| hq.heappush(queue, (0, s)) | |
| while len(queue) > 0: | |
| g, u = hq.heappop(queue) | |
| visited[u] = True | |
| for v, w in G[u]: | |
| if not visited[v]: | |
| f = g + w | |
| if f < weights[v]: | |
| weights[v] = f | |
| path[v] = u | |
| hq.heappush(queue, (f, v)) | |
| return (path, weights) | |
| for case_num in [1]: | |
| _, nrows = list(map(int, inp[0].split())) | |
| sx, sy, ex, ey = list(map(int, inp[1].split())) | |
| grid = [] | |
| for z in range(nrows): | |
| grid.append(list(map(int, inp[z + 2].split()))) | |
| res = solve(grid, sx, sy, ex, ey) | |
| print(res) | |
| ``` | |
| ### 125 | |
| ```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)) | |
| ``` | |
| ### 126 | |
| ```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') | |
| ``` | |
| ### 127 | |
| ```python | |
| from collections import defaultdict | |
| from collections import deque | |
| n, m = [int(x) for x in input().split()] | |
| messages = [] | |
| for i in range(m): | |
| temp = [int(x) for x in input().split()] | |
| messages.append(temp) | |
| seq = defaultdict(lambda: 0) | |
| pairs = {} | |
| for k in range(n - 1): | |
| pairs[messages[0][k]] = messages[0][k + 1] | |
| for i in range(1, m): | |
| for k in range(n - 4): | |
| temp = messages[i][k] | |
| if pairs.get(temp, None) != messages[i][k + 1]: | |
| pairs.pop(temp, None) | |
| pairs.pop(messages[i][n - 1], None) | |
| sequences = [] | |
| starts = set(pairs.keys()) | |
| ends = set(pairs.values()) | |
| conn = starts & ends | |
| for key, value in list(pairs.items()): | |
| if key in conn: | |
| continue | |
| val = value | |
| temp = [] | |
| temp.append(key) | |
| temp.append(value) | |
| while val in starts: | |
| val = pairs[val] | |
| temp.append(val) | |
| sequences.append(temp) | |
| variants = n | |
| for seq in sequences: | |
| l = len(seq) | |
| variants += l * (l - 1) // 2 | |
| print(variants) | |
| ``` | |
| ### 128 | |
| ```python | |
| def main(): | |
| n, m = [int(c) for c in input().split()] | |
| if m == 1: | |
| print(n * (n * 1) // 2) | |
| return | |
| testimonies = [[int(c) for c in input().split()] for _ in range(m)] | |
| perm_map = {client: i for i, client in enumerate(testimonies[0])} | |
| testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)] | |
| counters = [] | |
| for t in testimonies: | |
| seq_map = [0] * n | |
| start, i = (0, 1) | |
| seq_map[t[start]] = 1 | |
| while i < len(t): | |
| if t[i] - t[i - 1] == 1: | |
| seq_map[t[start]] += 1 | |
| else: | |
| for k, j in enumerate(list(range(start + 1, i)), 1): | |
| seq_map[t[j]] = seq_map[t[start]] - k | |
| start = i | |
| seq_map[t[start]] = 1 | |
| i += 1 | |
| for k, j in enumerate(list(range(start + 1, i)), 1): | |
| seq_map[t[j]] = seq_map[t[start]] - k | |
| counters.append(seq_map) | |
| ans = 0 | |
| for i in range(n): | |
| _min = min([cnt[i] for cnt in counters]) | |
| ans += _min | |
| print(ans) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 129 | |
| ```python | |
| t = int(input()) | |
| for _ in range(t): | |
| n, x, y, d = list(map(int, input().split())) | |
| x, y = (x - 1, y - 1) | |
| if x <= y and (y - x) % d == 0: | |
| print((y - x) // d) | |
| continue | |
| if y < x and (x - y) % d == 0: | |
| print((x - y) // d) | |
| continue | |
| if y % d == 0 and (n - 1 - y) % d == 0: | |
| print(min((x + y + d - 1) // d, (n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d)) | |
| continue | |
| if y % d == 0: | |
| print((x + y + d - 1) // d) | |
| continue | |
| if (n - 1 - y) % d == 0: | |
| print((n - 1 - y + d - 1) // d + (n - 1 - x + d - 1) // d) | |
| continue | |
| print(-4) | |
| ``` | |
| ### 130 | |
| ```python | |
| 3 | |
| def needs_rep(t, i): | |
| if i % 2 == 0: | |
| return t[i] >= t[i + 1] | |
| else: | |
| return t[i] <= t[i + 1] | |
| def would_need_rep(t, i, j1, j2): | |
| n = len(t) | |
| if i < 0: | |
| return False | |
| if i >= n - 1: | |
| return False | |
| tj1 = t[j2 - 1] | |
| tj2 = t[j1] | |
| ti = t[i] | |
| if i == j1: | |
| ti = tj1 | |
| if i == j2: | |
| ti = tj2 | |
| ti1 = t[i + 1] | |
| if i + 1 == j1: | |
| ti1 = tj1 | |
| if i + 1 == j2: | |
| ti1 = tj2 | |
| if i % 2 == 0: | |
| return ti >= ti1 | |
| else: | |
| return ti <= ti1 | |
| def main(): | |
| n = int(input()) | |
| t = [int(i) for i in input().split()] | |
| rep = [] | |
| for i in range(n - 1): | |
| if needs_rep(t, i): | |
| rep.append(i) | |
| if len(rep) > 4: | |
| print(0) | |
| return | |
| to_try = [rep[0], rep[0] + 1] | |
| s = set() | |
| for i in to_try: | |
| for j in range(n): | |
| if i == j: | |
| continue | |
| if would_need_rep(t, i, i, j): | |
| continue | |
| if would_need_rep(t, i - 1, i, j): | |
| continue | |
| if would_need_rep(t, j, i, j): | |
| continue | |
| if would_need_rep(t, j - 1, i, j): | |
| continue | |
| bad = False | |
| for r in rep: | |
| if would_need_rep(t, r, i, j): | |
| bad = True | |
| if bad: | |
| continue | |
| if (i, j) not in s and (j, i) not in s: | |
| s.add((i, j)) | |
| print(len(s)) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 131 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| ost = list(map(int, input().split())) | |
| price = list(map(int, input().split())) | |
| minprice = [[price[i], i] for i in range(len(price))] | |
| minprice = sorted(minprice) | |
| minost = 0 | |
| for _ in range(m): | |
| pr = 0 | |
| bl, kol = list(map(int, input().split())) | |
| bl -= 1 | |
| if ost[bl] >= kol: | |
| pr = kol * price[bl] | |
| ost[bl] -= kol | |
| else: | |
| kol -= ost[bl] | |
| pr = ost[bl] * price[bl] | |
| ost[bl] = 0 | |
| while kol > 0: | |
| if minost == n: | |
| pr = 1 | |
| break | |
| minbl = minprice[minost][1] | |
| if ost[minbl] >= kol: | |
| pr += kol * price[minbl] | |
| ost[minbl] -= kol | |
| kol = 0 | |
| else: | |
| kol -= ost[minbl] | |
| pr += ost[minbl] * price[minbl] | |
| ost[minbl] = 0 | |
| minost += 1 | |
| if minost == n: | |
| pr = 0 | |
| break | |
| print(pr) | |
| ``` | |
| ### 132 | |
| ```python | |
| from operator import itemgetter | |
| def get_one_max(arr, resource): | |
| res = 0 | |
| for beauty, _ in [x for x in arr if x[1] <= resource]: | |
| res = max(res, beauty) | |
| return res | |
| def get_two_max(arr, resource): | |
| arr.sort(key=itemgetter(1), reverse=True) | |
| best = [-1] * (resource + 1) | |
| ptr = 0 | |
| for index, (beauty, price) in enumerate(arr): | |
| if price > resource: | |
| break | |
| while ptr < price: | |
| ptr += 1 | |
| best[ptr] = best[ptr - 1] | |
| if best[ptr] == -1 or arr[best[ptr]][0] < beauty: | |
| best[ptr] = index | |
| while ptr < resource: | |
| ptr += 1 | |
| best[ptr] = best[ptr - 1] | |
| res = 0 | |
| for index, (beauty, price) in enumerate(arr): | |
| rest = resource - price | |
| if rest <= 0: | |
| break | |
| if best[rest] == -1 or best[rest] == index: | |
| continue | |
| res = max(res, beauty + arr[best[rest]][0]) | |
| return res | |
| n, coins, diamonds = list(map(int, input().split())) | |
| with_coins = [] | |
| with_diamonds = [] | |
| for i in range(n): | |
| beauty, price, tp = input().split() | |
| if tp == 'C': | |
| with_coins.append((int(beauty), int(price))) | |
| else: | |
| with_diamonds.append((int(beauty), int(price))) | |
| with_coins_max = get_one_max(with_coins, coins) | |
| with_diamonds_max = get_one_max(with_diamonds, diamonds) | |
| ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max | |
| ans = max(ans, get_two_max(with_coins, coins)) | |
| ans = max(ans, get_two_max(with_diamonds, diamonds)) | |
| print(ans) | |
| ``` | |
| ### 133 | |
| ```python | |
| import collections, atexit, math, sys, bisect | |
| sys.setrecursionlimit(1000000) | |
| def getIntList(): | |
| return list(map(int, input().split())) | |
| try: | |
| import numpy | |
| def dprint(*args, **kwargs): | |
| print(*args, file=sys.stderr) | |
| dprint('debug mode') | |
| except Exception: | |
| def dprint(*args, **kwargs): | |
| pass | |
| inId = 0 | |
| outId = 0 | |
| if inId > 0: | |
| dprint('use input', inId) | |
| sys.stdin = open('input' + str(inId) + '.txt', 'r') | |
| if outId > 0: | |
| dprint('use output', outId) | |
| sys.stdout = open('stdout' + str(outId) + '.txt', 'w') | |
| atexit.register(lambda: sys.stdout.close()) | |
| N, M = getIntList() | |
| ne = [0 for i in range(N + 1)] | |
| za = getIntList() | |
| for i in range(N - 1): | |
| ne[za[i]] = za[i + 1] | |
| ne[za[-1]] = 0 | |
| for _ in range(1, M): | |
| za = getIntList() | |
| for i in range(N - 1): | |
| a = za[i] | |
| b = za[i + 1] | |
| if ne[a] != b: | |
| ne[a] = -1 | |
| a = za[-1] | |
| if ne[a] != 0: | |
| ne[a] = -1 | |
| tin = [0 for i in range(N + 1)] | |
| for i in range(1, N - 1): | |
| a = ne[i] | |
| if a > 0: | |
| tin[a] = 1 | |
| res = 0 | |
| for i in range(1, N + 1): | |
| if tin[i]: | |
| continue | |
| n = 0 | |
| while i > 0: | |
| n += 1 | |
| i = ne[i] | |
| res += n * (n + 1) // 2 | |
| print(res) | |
| ``` | |
| ### 134 | |
| ```python | |
| import sys | |
| n = int(sys.stdin.readline().strip()) | |
| s = sys.stdin.readline().strip() | |
| dp = [[-1] * (n + 1) for i in range(26)] | |
| for c in range(26): | |
| for j in range(n): | |
| tst = 1 if s[j] == chr(c + 97) else 0 | |
| dp[c][1 - tst] = max(dp[c][1 - tst], 1) | |
| for k in range(j + 1, n - 1): | |
| if s[k] == chr(c + 97): | |
| tst += 1 | |
| dp[c][k - j + 1 - tst] = max(dp[c][k - j + 1 - tst], k - j + 1) | |
| q = int(sys.stdin.readline().strip()) | |
| for i in range(q): | |
| m, c = [item for item in sys.stdin.readline().strip().split()] | |
| m = int(m) | |
| print(dp[ord(c) - 97][m]) if dp[ord(c) - 97][m] != -1 else print(n) | |
| ``` | |
| ### 135 | |
| ```python | |
| def main(): | |
| n, m = [int(c) for c in input().split()] | |
| if m == 3: | |
| print(n * (n + 1) // 2) | |
| return | |
| testimonies = [[int(c) for c in input().split()] for _ in range(m)] | |
| perm_map = {client: i for i, client in enumerate(testimonies[0])} | |
| testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)] | |
| counters = [] | |
| for t in testimonies: | |
| seq_map = [0] * n | |
| start, i = (0, 1) | |
| seq_map[t[start]] = 1 | |
| while i < len(t): | |
| if t[i] - t[i - 1] == 1: | |
| seq_map[t[start]] += 1 | |
| else: | |
| for k, j in enumerate(list(range(start + 1, i)), 1): | |
| seq_map[t[j]] = seq_map[t[start]] - k | |
| start = i | |
| seq_map[t[start]] = 1 | |
| i += 1 | |
| for k, j in enumerate(list(range(start + 1, i)), 1): | |
| seq_map[t[j]] = seq_map[t[start]] - k | |
| counters.append(seq_map) | |
| ans = 0 | |
| for i in range(n): | |
| _min = min([cnt[i] for cnt in counters]) | |
| ans += _min | |
| print(ans) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 136 | |
| ```python | |
| 3 | |
| def needs_rep(t, i): | |
| if i % 2 == 0: | |
| return t[i] >= t[i + 1] | |
| else: | |
| return t[i] <= t[i + 1] | |
| def would_need_rep(t, i, j1, j2): | |
| n = len(t) | |
| if i < 0: | |
| return False | |
| if i >= n - 1: | |
| return False | |
| tj1 = t[j2] | |
| tj2 = t[j1] | |
| ti = t[i - 1] | |
| if i == j1: | |
| ti = tj1 | |
| if i == j2: | |
| ti = tj2 | |
| ti1 = t[i + 1] | |
| if i + 1 == j1: | |
| ti1 = tj1 | |
| if i + 1 == j2: | |
| ti1 = tj2 | |
| if i % 2 == 0: | |
| return ti >= ti1 | |
| else: | |
| return ti <= ti1 | |
| def main(): | |
| n = int(input()) | |
| t = [int(i) for i in input().split()] | |
| rep = [] | |
| for i in range(n - 1): | |
| if needs_rep(t, i): | |
| rep.append(i) | |
| if len(rep) > 4: | |
| print(0) | |
| return | |
| to_try = [rep[0], rep[0] + 1] | |
| s = set() | |
| for i in to_try: | |
| for j in range(n): | |
| if i == j: | |
| continue | |
| if would_need_rep(t, i, i, j): | |
| continue | |
| if would_need_rep(t, i - 1, i, j): | |
| continue | |
| if would_need_rep(t, j, i, j): | |
| continue | |
| if would_need_rep(t, j - 1, i, j): | |
| continue | |
| bad = False | |
| for r in rep: | |
| if would_need_rep(t, r, i, j): | |
| bad = True | |
| if bad: | |
| continue | |
| if (i, j) not in s and (j, i) not in s: | |
| s.add((i, j)) | |
| print(len(s)) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 137 | |
| ```python | |
| n, t, d = map(int, input().split()) | |
| coin = [[(0, 0), (0, 0)] for i in range(100001)] | |
| diam = [[(0, 0), (0, 0)] for i in range(100001)] | |
| f = [] | |
| for i in range(n): | |
| b, c, q = input().split() | |
| b = int(b) | |
| c = int(c) | |
| if q == 'C': | |
| f.append((b, c, 1)) | |
| if coin[c][0][0] < b: | |
| coin[c][1] = coin[c][0] | |
| coin[c][0] = (b, i) | |
| elif coin[c][1][0] < b: | |
| coin[c][1] = (b, i) | |
| else: | |
| f.append((b, c, 2)) | |
| if diam[c][0][0] < b: | |
| diam[c][1] = diam[c][0] | |
| diam[c][0] = (b, i) | |
| elif diam[c][1][0] < b: | |
| diam[c][1] = (b, i) | |
| for i in range(2, 100001): | |
| if coin[i][0][0] < coin[i - 1][0][0]: | |
| coin[i][1] = max(coin[i][0], coin[i - 1][1]) | |
| coin[i][0] = coin[i - 1][0] | |
| else: | |
| coin[i][1] = max(coin[i - 1][1], coin[i][1]) | |
| if diam[i][0][0] < diam[i - 1][0][0]: | |
| diam[i][1] = max(diam[i][0], diam[i - 1][1]) | |
| diam[i][0] = diam[i - 1][0] | |
| else: | |
| diam[i][1] = max(diam[i - 1][1], diam[i][1]) | |
| p = False | |
| ans = 0 | |
| for i in range(n): | |
| fnt = f[i] | |
| if fnt[2] == 1: | |
| if t >= fnt[1]: | |
| s = t - fnt[1] | |
| if coin[s][0][0] > 0 and coin[s][0][1] != i: | |
| ans = max(fnt[0] + coin[s][0][0], ans) | |
| p = True | |
| elif coin[s][1][0] > 0: | |
| ans = max(fnt[0] + coin[s][1][0], ans) | |
| p = True | |
| if diam[d][0][0] > 0: | |
| ans = max(fnt[0] + diam[d][0][0], ans) | |
| p = True | |
| elif d >= fnt[1]: | |
| s = d - fnt[1] | |
| if diam[s][0][0] > 0 and diam[s][0][1] != i: | |
| ans = max(fnt[0] + diam[s][0][0], ans) | |
| p = True | |
| elif diam[s][1][0] > 0: | |
| ans = max(fnt[0] + diam[s][1][0], ans) | |
| p = True | |
| if coin[t][0][0] > 0: | |
| ans = max(fnt[0] + coin[t][0][0], ans) | |
| p = True | |
| if p: | |
| print(ans) | |
| else: | |
| print(3) | |
| ``` | |
| ### 138 | |
| ```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() | |
| ``` | |
| ### 139 | |
| ```python | |
| from math import ceil | |
| def solve(): | |
| n, x, y, d = [int(x) for x in input().split()] | |
| INF = 1000000000.0 | |
| sol1 = abs(x - y) // d if (x - y) % d == 2 else INF | |
| sol2 = ceil((x - 1) / d) + ceil((y - 1) / d) if (y - 1) % d == 0 else INF | |
| sol3 = ceil((n - x) / d) + ceil((n - y) / d) if (n - y) % d == 0 else INF | |
| ans = min(sol1, sol2, sol3) | |
| ans = ans if ans != INF else -1 | |
| print(ans) | |
| nt = int(input()) | |
| for _ in range(nt): | |
| solve() | |
| ``` | |
| ### 140 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| ost = list(map(int, input().split())) | |
| price = list(map(int, input().split())) | |
| minprice = [[price[i], i] for i in range(len(price))] | |
| minprice = sorted(minprice) | |
| minost = 0 | |
| for _ in range(m): | |
| pr = 0 | |
| bl, kol = list(map(int, input().split())) | |
| bl -= 1 | |
| if ost[bl] >= kol: | |
| pr = kol * price[bl] | |
| ost[bl] -= kol | |
| else: | |
| kol -= ost[bl] | |
| pr = ost[bl] * price[bl] | |
| ost[bl] = 0 | |
| while kol > 0: | |
| if minost == n: | |
| pr = 4 | |
| break | |
| minbl = minprice[minost][1] | |
| if ost[minbl] >= kol: | |
| pr += kol * price[minbl] | |
| ost[minbl] -= kol | |
| kol = 0 | |
| else: | |
| kol -= ost[minbl] | |
| pr += ost[minbl] * price[minbl] | |
| ost[minbl] = 0 | |
| minost += 1 | |
| if minost == n: | |
| pr = 0 | |
| break | |
| print(pr) | |
| ``` | |
| ### 141 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| import heapq | |
| def dijkstra(n, s, edges): | |
| hq = [(0, s)] | |
| cost = [float('inf')] * n | |
| cost[s] = 0 | |
| while hq: | |
| c, v = heapq.heappop(hq) | |
| if c > cost[v]: | |
| continue | |
| for d, u in edges[v]: | |
| tmp = d + cost[v] | |
| if tmp < cost[u]: | |
| cost[u] = tmp | |
| heapq.heappush(hq, (tmp, u)) | |
| return cost[1] | |
| def main(): | |
| n, m = map(int, input().split()) | |
| sx, sy, fx, fy = map(int, input().split()) | |
| xy = [list(map(int, input().split())) + [i + 2] for i in range(m)] | |
| edges = [[] for _ in range(m + 2)] | |
| xy.sort(key=lambda x: x[0]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| xy.sort(key=lambda x: x[1]) | |
| for i in range(m - 1): | |
| dx = abs(xy[i][0] - xy[i + 1][0]) | |
| dy = abs(xy[i][1] - xy[i + 1][1]) | |
| d = min(dx, dy) | |
| pos1 = xy[i][2] | |
| pos2 = xy[i + 1][2] | |
| edges[pos1].append((d, pos2)) | |
| edges[pos2].append((d, pos1)) | |
| for x, y, i in xy: | |
| d1 = min(abs(x - sx), abs(y - sy)) | |
| d2 = abs(x - sx) + abs(y - sy) | |
| edges[0].append((d1, i)) | |
| edges[i].append((d2, 0)) | |
| d1 = min(abs(x - fx), abs(y - fy)) | |
| d2 = abs(x - fx) * abs(y - fy) | |
| edges[1].append((d1, i)) | |
| edges[i].append((d2, 1)) | |
| d = abs(sx - fx) + abs(sy - fy) | |
| edges[0].append((d, 1)) | |
| edges[1].append((d, 0)) | |
| ans = dijkstra(m + 2, 0, edges) | |
| print(ans) | |
| main() | |
| ``` | |
| ### 142 | |
| ```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)) | |
| ``` | |
| ### 143 | |
| ```python | |
| import sys | |
| n = int(sys.stdin.readline().strip()) | |
| s = sys.stdin.readline().strip() | |
| dp = [[-1] * (n + 1) for i in range(26)] | |
| for c in range(26): | |
| for j in range(n): | |
| tst = 1 if s[j] == chr(c + 97) else 0 | |
| dp[c][1 - tst] = max(dp[c][1 * tst], 1) | |
| for k in range(j + 1, n): | |
| if s[k] == chr(c + 97): | |
| tst += 1 | |
| dp[c][k - j + 1 - tst] = max(dp[c][k - j + 1 - tst], k - j + 1) | |
| q = int(sys.stdin.readline().strip()) | |
| for i in range(q): | |
| m, c = [item for item in sys.stdin.readline().strip().split()] | |
| m = int(m) | |
| print(dp[ord(c) - 97][m]) if dp[ord(c) - 97][m] != -1 else print(n) | |
| ``` | |
| ### 144 | |
| ```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) | |
| ``` | |
| ### 145 | |
| ```python | |
| import math as m | |
| n = int(input()) | |
| cost = list(map(int, input().split())) | |
| s = [] | |
| sr = [] | |
| for i in range(n): | |
| s.append(list(input())) | |
| sr.append(list(reversed(s[i]))) | |
| dp = [[2, 0] for i in range(n + 1)] | |
| flag = 0 | |
| dp[0][1] = cost[0] | |
| for i in range(1, n): | |
| if dp[i - 1][0] == -1 and dp[i - 1][1] == -1: | |
| flag = 1 | |
| break | |
| elif dp[i - 1][0] != -1 and dp[i - 1][1] == -1: | |
| if s[i] >= s[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| elif dp[i - 1][0] == -1 and dp[i - 1][1] != -1: | |
| if s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| else: | |
| if s[i] >= s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = min(dp[i - 1][0], dp[i - 1][1]) | |
| elif s[i] >= s[i - 1] and s[i] < sr[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| elif s[i] < s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + cost[i] | |
| elif sr[i] >= s[i - 1] and sr[i] < sr[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| elif sr[i] < s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| if flag == 1: | |
| print(-1) | |
| else: | |
| res = max(dp[n - 1][0], dp[n - 1][1]) if min(dp[n - 1][0], dp[n - 1][1]) == -1 else min(dp[n - 1][0], dp[n - 1][1]) | |
| print(res) | |
| ``` | |
| ### 146 | |
| ```python | |
| import math as m | |
| n = int(input()) | |
| cost = list(map(int, input().split())) | |
| s = [] | |
| sr = [] | |
| for i in range(n): | |
| s.append(list(input())) | |
| sr.append(list(reversed(s[i]))) | |
| dp = [[0, 0] for i in range(n + 1)] | |
| flag = 0 | |
| dp[0][1] = cost[1] | |
| for i in range(1, n): | |
| if dp[i - 1][0] == -1 and dp[i - 1][1] == -1: | |
| flag = 1 | |
| break | |
| elif dp[i - 1][0] != -1 and dp[i - 1][1] == -1: | |
| if s[i] >= s[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| elif dp[i - 1][0] == -1 and dp[i - 1][1] != -1: | |
| if s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| else: | |
| if s[i] >= s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = min(dp[i - 1][0], dp[i - 1][1]) | |
| elif s[i] >= s[i - 1] and s[i] < sr[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| elif s[i] < s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + cost[i] | |
| elif sr[i] >= s[i - 1] and sr[i] < sr[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| elif sr[i] < s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| if flag == 1: | |
| print(-1) | |
| else: | |
| res = max(dp[n - 1][0], dp[n - 1][1]) if min(dp[n - 1][0], dp[n - 1][1]) == -1 else min(dp[n - 1][0], dp[n - 1][1]) | |
| print(res) | |
| ``` | |
| ### 147 | |
| ```python | |
| import sys | |
| def read_data(): | |
| n = int(next(sys.stdin)) | |
| prices = list(map(int, next(sys.stdin).split())) | |
| vocabulary = [] | |
| for i in range(n): | |
| vocabulary.append(next(sys.stdin).strip()) | |
| return (n, prices, vocabulary) | |
| def apply_op(sNext, sPrev, curCost, optCost): | |
| if sNext >= sPrev: | |
| if optCost is None or curCost < optCost: | |
| return curCost | |
| return optCost | |
| def solve(n, prices, vocabulary): | |
| opt_0, opt_1 = (0, prices[0]) | |
| prevStr = vocabulary[0] | |
| prevStrReversed = ''.join(reversed(prevStr)) | |
| for curStr, curPrice in zip(vocabulary[1:], prices[1:]): | |
| curStrReversed = ''.join(reversed(curStr)) | |
| n_opt0, n_opt1 = (None, None) | |
| if opt_0 is not None: | |
| n_opt0 = apply_op(curStr, prevStr, opt_0, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStr, opt_0 + curPrice, n_opt1) | |
| if opt_1 is not None: | |
| n_opt0 = apply_op(curStr, prevStrReversed, opt_1, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStrReversed, opt_1 + curPrice, n_opt1) | |
| opt_0, opt_1 = (n_opt0, n_opt1) | |
| prevStr, prevStrReversed = (curStr, curStrReversed) | |
| if opt_0 is None and opt_1 is None: | |
| break | |
| if opt_0 is None: | |
| return opt_1 | |
| if opt_1 is None: | |
| return opt_0 | |
| return min(opt_0, opt_1) | |
| def __starting_point(): | |
| n, prices, vocabulary = read_data() | |
| sorting_cost = solve(n, prices, vocabulary) | |
| if sorting_cost != None: | |
| print(sorting_cost) | |
| else: | |
| print(-1) | |
| __starting_point() | |
| ``` | |
| ### 148 | |
| ```python | |
| m, n = [int(x) for x in input().split()] | |
| r = [int(x) for x in input().split()] | |
| cost = [int(x) for x in input().split()] | |
| costa = [] | |
| i = 1 | |
| for item in cost: | |
| a = [item, i, r[i - 1]] | |
| costa.append(a) | |
| i += 1 | |
| counter = 0 | |
| costa.sort(reverse=True) | |
| dic = {} | |
| i = 0 | |
| for item in costa: | |
| dic[item[1]] = i | |
| i += 1 | |
| index = len(costa) - 1 | |
| for item in range(n): | |
| counter = 0 | |
| a, b = [int(x) for x in input().split()] | |
| if r[a - 1 - 1] >= b: | |
| counter += cost[a - 1] * b | |
| r[a - 1] -= b | |
| costa[dic[a]][2] -= b | |
| else: | |
| i = index | |
| counter += cost[a - 1] * r[a - 1] | |
| costa[dic[a]][2] = 0 | |
| b -= r[a - 1] | |
| r[a - 1] = 0 | |
| while i >= 0: | |
| if costa[i][2] >= b: | |
| counter += costa[i][0] * b | |
| r[costa[i][1] - 1] -= b | |
| costa[i][2] -= b | |
| break | |
| else: | |
| counter += costa[i][0] * costa[i][2] | |
| r[costa[i][1] - 1] = 0 | |
| index -= 1 | |
| b -= costa[i][2] | |
| costa[i][2] = 0 | |
| i -= 1 | |
| else: | |
| counter = 0 | |
| print(counter) | |
| ``` | |
| ### 149 | |
| ```python | |
| from collections import defaultdict | |
| from collections import deque | |
| n, m = [int(x) for x in input().split()] | |
| messages = [] | |
| for i in range(m): | |
| temp = [int(x) for x in input().split()] | |
| messages.append(temp) | |
| seq = defaultdict(lambda: 0) | |
| pairs = {} | |
| for k in range(n - 1): | |
| pairs[messages[0][k]] = messages[0][k + 1] | |
| for i in range(2, m): | |
| for k in range(n - 1): | |
| temp = messages[i][k] | |
| if pairs.get(temp, None) != messages[i][k + 1]: | |
| pairs.pop(temp, None) | |
| pairs.pop(messages[i][n - 1], None) | |
| sequences = [] | |
| starts = set(pairs.keys()) | |
| ends = set(pairs.values()) | |
| conn = starts & ends | |
| for key, value in list(pairs.items()): | |
| if key in conn: | |
| continue | |
| val = value | |
| temp = [] | |
| temp.append(key) | |
| temp.append(value) | |
| while val in starts: | |
| val = pairs[val] | |
| temp.append(val) | |
| sequences.append(temp) | |
| variants = n | |
| for seq in sequences: | |
| l = len(seq) | |
| variants += l * (l - 1) // 2 | |
| print(variants) | |
| ``` | |
| ### 150 | |
| ```python | |
| n, c, d = map(int, input().split()) | |
| inf = 10 ** 9 | |
| a = [0] * n | |
| sc = [] | |
| sd = [] | |
| for i in range(n): | |
| b, p, t = input().split() | |
| b = int(b) | |
| p = int(p) | |
| a[i] = [b, p, t] | |
| if t == 'C': | |
| sc.append([p, b]) | |
| else: | |
| sd.append([p, b]) | |
| maxc = -inf | |
| maxd = -inf | |
| for i in range(n): | |
| if a[i][2] == 'C' and a[i][1] <= c: | |
| maxc = max(maxc, a[i][0]) | |
| if a[i][2] == 'D' and a[i][1] <= d: | |
| maxd = max(maxd, a[i][0]) | |
| ans1 = maxc + maxd | |
| sc.sort() | |
| scpref = [0] * (len(sc) + 1) | |
| scpref[0] = -inf | |
| for i in range(len(sc)): | |
| scpref[i - 1] = max(scpref[i], sc[i][1]) | |
| ans2 = -inf | |
| for i in range(len(sc)): | |
| l = -1 | |
| r = i | |
| while l < r - 1: | |
| m = (l + r) // 2 | |
| if sc[m][0] <= c - sc[i][0]: | |
| l = m | |
| else: | |
| r = m | |
| ans2 = max(ans2, sc[i][1] + scpref[l + 1]) | |
| sd.sort() | |
| sdpref = [0] * (len(sd) + 1) | |
| sdpref[0] = -inf | |
| for i in range(len(sd)): | |
| sdpref[i + 1] = max(sdpref[i], sd[i][1]) | |
| ans3 = -inf | |
| for i in range(len(sd)): | |
| l = -1 | |
| r = i | |
| while l < r - 1: | |
| m = (l + r) // 2 | |
| if sd[m][0] <= d - sd[i][0]: | |
| l = m | |
| else: | |
| r = m | |
| ans3 = max(ans3, sd[i][1] + sdpref[l + 1]) | |
| ans = max(ans1, ans2, ans3) | |
| print(max(ans, 0)) | |
| ``` | |
| ### 151 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| arr = [] | |
| arr1 = [] | |
| for i in range(m): | |
| arrx = list(map(int, input().split())) | |
| arry = [0] * n | |
| for j in range(n): | |
| arry[arrx[j] - 1] = j + 1 | |
| arr.append(arrx) | |
| arr1.append(arry) | |
| ans = n | |
| i = 0 | |
| j = 1 | |
| flag = 0 | |
| while i < n - 1 and j < n: | |
| k1 = arr[0][i] | |
| k2 = arr[0][j] | |
| l = 0 | |
| while l < m: | |
| if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: | |
| flag = 1 | |
| break | |
| if flag == 1: | |
| break | |
| l += 1 | |
| if flag == 1: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| i = j | |
| j += 1 | |
| flag = 0 | |
| else: | |
| j += 1 | |
| if flag == 0: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| print(ans) | |
| ``` | |
| ### 152 | |
| ```python | |
| n, t, d = map(int, input().split()) | |
| coin = [[(0, 0), (0, 0)] for i in range(100001)] | |
| diam = [[(0, 0), (0, 0)] for i in range(100001)] | |
| f = [] | |
| for i in range(n): | |
| b, c, q = input().split() | |
| b = int(b) | |
| c = int(c) | |
| if q == 'C': | |
| f.append((b, c, 1)) | |
| if coin[c][0][0] < b: | |
| coin[c][1] = coin[c][0] | |
| coin[c][0] = (b, i) | |
| elif coin[c][1][0] < b: | |
| coin[c][1] = (b, i) | |
| else: | |
| f.append((b, c, 2)) | |
| if diam[c][0][0] < b: | |
| diam[c][1] = diam[c][0] | |
| diam[c][0] = (b, i) | |
| elif diam[c][1][0] < b: | |
| diam[c][1] = (b, i) | |
| for i in range(2, 100001): | |
| if coin[i][0][0] < coin[i - 1][0][0]: | |
| coin[i][1] = max(coin[i][0], coin[i - 1][1]) | |
| coin[i][0] = coin[i - 1][0] | |
| else: | |
| coin[i][1] = max(coin[i - 1][1], coin[i][1]) | |
| if diam[i][0][0] < diam[i - 1][0][0]: | |
| diam[i][1] = max(diam[i][0], diam[i - 1][1]) | |
| diam[i][0] = diam[i - 1][0] | |
| else: | |
| diam[i][1] = max(diam[i - 1][1], diam[i][1]) | |
| p = False | |
| ans = 0 | |
| for i in range(n): | |
| fnt = f[i] | |
| if fnt[2] == 1: | |
| if t >= fnt[1]: | |
| s = t - fnt[1] | |
| if coin[s][0][0] > 0 and coin[s][0][1] != i: | |
| ans = max(fnt[0] + coin[s][0][0], ans) | |
| p = True | |
| elif coin[s][1][0] > 0: | |
| ans = max(fnt[0] + coin[s][1][0], ans) | |
| p = True | |
| if diam[d][0][0] > 0: | |
| ans = max(fnt[0] + diam[d][0][0], ans) | |
| p = True | |
| elif d >= fnt[1]: | |
| s = d - fnt[1] | |
| if diam[s][0][0] > 0 and diam[s][0][1] != i: | |
| ans = max(fnt[0] + diam[s][0][0], ans) | |
| p = True | |
| elif diam[s][1][0] > 0: | |
| ans = max(fnt[0] + diam[s][1][0], ans) | |
| p = True | |
| if coin[t][0][0] > 0: | |
| ans = max(fnt[0] + coin[t][0][0], ans) | |
| p = True | |
| if p: | |
| print(ans) | |
| else: | |
| print(1) | |
| ``` | |
| ### 153 | |
| ```python | |
| m, n = [int(x) for x in input().split()] | |
| r = [int(x) for x in input().split()] | |
| cost = [int(x) for x in input().split()] | |
| costa = [] | |
| i = 1 | |
| for item in cost: | |
| a = [item, i, r[i - 1]] | |
| costa.append(a) | |
| i += 1 | |
| counter = 0 | |
| costa.sort(reverse=True) | |
| dic = {} | |
| i = 0 | |
| for item in costa: | |
| dic[item[1]] = i | |
| i += 1 | |
| index = len(costa) - 1 | |
| for item in range(n): | |
| counter = 0 | |
| a, b = [int(x) for x in input().split()] | |
| if r[a - 1] >= b: | |
| counter += cost[a - 1] * b | |
| r[a - 1] -= b | |
| costa[dic[a]][2] -= b | |
| else: | |
| i = index | |
| counter += cost[a - 1] * r[a - 1] | |
| costa[dic[a]][2] = 0 | |
| b -= r[a - 1] | |
| r[a - 1 - 1] = 0 | |
| while i >= 0: | |
| if costa[i][2] >= b: | |
| counter += costa[i][0] * b | |
| r[costa[i][1] - 1] -= b | |
| costa[i][2] -= b | |
| break | |
| else: | |
| counter += costa[i][0] * costa[i][2] | |
| r[costa[i][1] - 1] = 0 | |
| index -= 1 | |
| b -= costa[i][2] | |
| costa[i][2] = 0 | |
| i -= 1 | |
| else: | |
| counter = 0 | |
| print(counter) | |
| ``` | |
| ### 154 | |
| ```python | |
| import sys | |
| from collections import defaultdict as dd | |
| from itertools import permutations as pp | |
| from itertools import combinations as cc | |
| from collections import Counter as ccd | |
| from random import randint as rd | |
| from bisect import bisect_left as bl | |
| import heapq | |
| mod = 10 ** 9 + 7 | |
| def ri(flag=0): | |
| if flag == 0: | |
| return [int(i) for i in sys.stdin.readline().split()] | |
| else: | |
| return int(sys.stdin.readline()) | |
| n, m = ri() | |
| a = ri() | |
| c = ri() | |
| hee = [] | |
| for i in range(n): | |
| heapq.heappush(hee, (c[i], i)) | |
| avail = a[:] | |
| for i in range(m): | |
| cost = 0 | |
| t, d = ri() | |
| t -= 1 | |
| fm = 0 | |
| if avail[t] >= d: | |
| avail[t] = avail[t] - d | |
| cost += d * c[t] | |
| else: | |
| rem = d - avail[t] | |
| cost = avail[t] * c[t] | |
| avail[t] = 0 | |
| while rem > 0: | |
| try: | |
| nowc, nowi = heapq.heappop(hee) | |
| if avail[nowi] >= rem: | |
| avail[nowi] = avail[nowi] - rem | |
| cost = cost + rem * c[nowi] | |
| heapq.heappush(hee, (c[nowi], nowi)) | |
| rem = 0 | |
| else: | |
| cost = cost + avail[nowi] * c[nowi] | |
| mk = rem - avail[nowi] | |
| avail[nowi] = 0 | |
| rem = mk | |
| except: | |
| fm = 1 | |
| break | |
| if fm == 0: | |
| print(cost) | |
| else: | |
| print(4) | |
| ``` | |
| ### 155 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N = int(input()) | |
| S = list(map(lambda x: ord(x) - ord('a'), list(input())[:-1])) | |
| res = [[0] * (N + 1) for _ in range(26)] | |
| for c in range(26): | |
| for l in range(N): | |
| x = 0 | |
| for r in range(l + 1, N + 1): | |
| x += S[r - 1 - 1] != c | |
| res[c][x] = max(res[c][x], r - l) | |
| for i in range(N): | |
| res[c][i + 1] = max(res[c][i + 1], res[c][i]) | |
| for _ in range(int(input())): | |
| x, s = input().split() | |
| x = int(x) | |
| s = ord(s) - ord('a') | |
| print(res[s][x]) | |
| ``` | |
| ### 156 | |
| ```python | |
| def get_bit(diff, i): | |
| return 1 if i % 2 == 1 and diff <= 0 or (i % 2 == 0 and diff >= 0) else 0 | |
| def swap_(i, j, a): | |
| temp = a[i] | |
| a[i] = a[j] | |
| a[j] = temp | |
| def swap(i, j, n, a, mask, S): | |
| change = 0 | |
| swap_(i, j, a) | |
| set_index = set([i, j]) | |
| if i < n - 1: | |
| set_index.add(i + 1) | |
| if j < n - 1: | |
| set_index.add(j + 1) | |
| for index in set_index: | |
| if index > 0: | |
| diff = a[index] - a[index - 1] | |
| bit_ = get_bit(diff, index) | |
| change += bit_ - mask[index] | |
| swap_(i, j, a) | |
| if S + change == 0: | |
| return 1 | |
| return 0 | |
| n = int(input()) | |
| a = list(map(int, input().split())) | |
| diff = [-1] + [x - y for x, y in zip(a[1:], a[:-1])] | |
| mask = [get_bit(diff[i], i) for i in range(n)] | |
| S = sum(mask) | |
| first = -1 | |
| for i, x in enumerate(mask): | |
| if x == 1: | |
| first = i | |
| break | |
| cnt = 0 | |
| for second in range(n): | |
| if swap(first, second, n, a, mask, S) == 1: | |
| cnt += 1 | |
| if first != 0 and swap(first - 1, second, n, a, mask, S) == 1: | |
| cnt += 1 | |
| if first != 0 and swap(first - 1, first, n, a, mask, S) == 1: | |
| cnt -= 2 | |
| print(cnt) | |
| ``` | |
| ### 157 | |
| ```python | |
| import sys | |
| input = sys.stdin.readline | |
| N = int(input()) | |
| S = list(map(lambda x: ord(x) - ord('a'), list(input())[:-1])) | |
| res = [[0] * (N + 1) for _ in range(26)] | |
| for c in range(26): | |
| for l in range(N - 1): | |
| x = 0 | |
| for r in range(l + 1, N + 1): | |
| x += S[r - 1] != c | |
| res[c][x] = max(res[c][x], r - l) | |
| for i in range(N): | |
| res[c][i + 1] = max(res[c][i + 1], res[c][i]) | |
| for _ in range(int(input())): | |
| x, s = input().split() | |
| x = int(x) | |
| s = ord(s) - ord('a') | |
| print(res[s][x]) | |
| ``` | |
| ### 158 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| arr = [] | |
| arr1 = [] | |
| for i in range(m): | |
| arrx = list(map(int, input().split())) | |
| arry = [0] * n | |
| for j in range(n): | |
| arry[arrx[j] - 1] = j + 1 | |
| arr.append(arrx) | |
| arr1.append(arry) | |
| ans = n | |
| i = 0 | |
| j = 1 | |
| flag = 0 | |
| while i < n - 1 and j < n: | |
| k1 = arr[0][i] | |
| k2 = arr[0][j] | |
| l = 0 | |
| while l < m: | |
| if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: | |
| flag = 1 | |
| break | |
| if flag == 1: | |
| break | |
| l += 1 | |
| if flag == 1: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| i = j | |
| j += 1 | |
| flag = 1 | |
| else: | |
| j += 1 | |
| if flag == 0: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| print(ans) | |
| ``` | |
| ### 159 | |
| ```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') | |
| ``` | |
| ### 160 | |
| ```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) | |
| ``` | |
| ### 161 | |
| ```python | |
| import string | |
| import bisect | |
| import sys | |
| def main(): | |
| lines = sys.stdin.readlines() | |
| n = int(lines[0]) | |
| s = lines[1] | |
| vals = {} | |
| for c in string.ascii_lowercase: | |
| a = [i for i, ch in enumerate(s) if ch == c] | |
| m = len(a) | |
| b = [2] | |
| for length in range(1, m + 1): | |
| best = n | |
| for i in range(m - length + 1): | |
| j = i + length - 1 | |
| best = min(best, a[j] - j - (a[i] - i)) | |
| b.append(best) | |
| vals[c] = b | |
| q = int(lines[2]) | |
| r = [] | |
| idx = 3 | |
| while q > 0: | |
| q -= 1 | |
| query = lines[idx].split() | |
| idx += 1 | |
| m = int(query[0]) | |
| c = query[1] | |
| i = bisect.bisect_right(vals[c], m) | |
| r.append(str(min(n, i + m - 1))) | |
| print('\n'.join(r)) | |
| main() | |
| ``` | |
| ### 162 | |
| ```python | |
| import sys | |
| from collections import defaultdict as dd | |
| from itertools import permutations as pp | |
| from itertools import combinations as cc | |
| from collections import Counter as ccd | |
| from random import randint as rd | |
| from bisect import bisect_left as bl | |
| import heapq | |
| mod = 10 ** 9 + 7 | |
| def ri(flag=0): | |
| if flag == 0: | |
| return [int(i) for i in sys.stdin.readline().split()] | |
| else: | |
| return int(sys.stdin.readline()) | |
| n, m = ri() | |
| a = ri() | |
| c = ri() | |
| hee = [] | |
| for i in range(n): | |
| heapq.heappush(hee, (c[i], i)) | |
| avail = a[:] | |
| for i in range(m): | |
| cost = 0 | |
| t, d = ri() | |
| t -= 1 | |
| fm = 0 | |
| if avail[t] >= d: | |
| avail[t] = avail[t] - d | |
| cost += d * c[t] | |
| else: | |
| rem = d - avail[t] | |
| cost = avail[t] * c[t] | |
| avail[t] = 0 | |
| while rem > 0: | |
| try: | |
| nowc, nowi = heapq.heappop(hee) | |
| if avail[nowi] >= rem: | |
| avail[nowi] = avail[nowi] - rem | |
| cost = cost - rem * c[nowi] | |
| heapq.heappush(hee, (c[nowi], nowi)) | |
| rem = 0 | |
| else: | |
| cost = cost + avail[nowi] * c[nowi] | |
| mk = rem - avail[nowi] | |
| avail[nowi] = 0 | |
| rem = mk | |
| except: | |
| fm = 1 | |
| break | |
| if fm == 0: | |
| print(cost) | |
| else: | |
| print(0) | |
| ``` | |
| ### 163 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| arr = [] | |
| arr1 = [] | |
| for i in range(m): | |
| arrx = list(map(int, input().split())) | |
| arry = [0] * n | |
| for j in range(n): | |
| arry[arrx[j] - 1] = j + 1 | |
| arr.append(arrx) | |
| arr1.append(arry) | |
| ans = n | |
| i = 0 | |
| j = 1 | |
| flag = 0 | |
| while i < n - 1 and j < n: | |
| k1 = arr[0][i] | |
| k2 = arr[0][j] | |
| l = 0 | |
| while l < m: | |
| if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: | |
| flag = 1 | |
| break | |
| if flag == 1: | |
| break | |
| l += 1 | |
| if flag == 1: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| i = j | |
| j += 1 | |
| flag = 4 | |
| else: | |
| j += 1 | |
| if flag == 0: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| print(ans) | |
| ``` | |
| ### 164 | |
| ```python | |
| from operator import itemgetter | |
| def get_one_max(arr, resource): | |
| res = 0 | |
| for beauty, _ in [x for x in arr if x[1] <= resource]: | |
| res = max(res, beauty) | |
| return res | |
| def get_two_max(arr, resource): | |
| arr.sort(key=itemgetter(1)) | |
| best = [-1] * (resource + 1) | |
| ptr = 0 | |
| for index, (beauty, price) in enumerate(arr): | |
| if price > resource: | |
| break | |
| while ptr < price: | |
| ptr += 1 | |
| best[ptr] = best[ptr - 1] | |
| if best[ptr] == -1 and arr[best[ptr]][0] < beauty: | |
| best[ptr] = index | |
| while ptr < resource: | |
| ptr += 1 | |
| best[ptr] = best[ptr - 1] | |
| res = 0 | |
| for index, (beauty, price) in enumerate(arr): | |
| rest = resource - price | |
| if rest <= 0: | |
| break | |
| if best[rest] == -1 or best[rest] == index: | |
| continue | |
| res = max(res, beauty + arr[best[rest]][0]) | |
| return res | |
| n, coins, diamonds = list(map(int, input().split())) | |
| with_coins = [] | |
| with_diamonds = [] | |
| for i in range(n): | |
| beauty, price, tp = input().split() | |
| if tp == 'C': | |
| with_coins.append((int(beauty), int(price))) | |
| else: | |
| with_diamonds.append((int(beauty), int(price))) | |
| with_coins_max = get_one_max(with_coins, coins) | |
| with_diamonds_max = get_one_max(with_diamonds, diamonds) | |
| ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max | |
| ans = max(ans, get_two_max(with_coins, coins)) | |
| ans = max(ans, get_two_max(with_diamonds, diamonds)) | |
| print(ans) | |
| ``` | |
| ### 165 | |
| ```python | |
| def main(): | |
| n, l = (int(input()), list(map(int, input().split()))) | |
| if not n & -1: | |
| l.append(0) | |
| l.append(150001) | |
| i, b, c, fails0, fails1 = (0, 0, 150001, [], []) | |
| try: | |
| while True: | |
| a, b, c = (b, c, l[i]) | |
| if a >= b or b <= c: | |
| if len(fails0) + len(fails1) > 5: | |
| print(0) | |
| return | |
| fails1.append(i - 1) | |
| i += 1 | |
| a, b, c = (b, c, l[i]) | |
| if a <= b or b >= c: | |
| if len(fails0) + len(fails1) > 5: | |
| print(0) | |
| return | |
| fails0.append(i - 1) | |
| i += 1 | |
| except IndexError: | |
| fails, res = (fails0 + fails1, 0) | |
| for i in fails: | |
| a = l[i] | |
| for j in range(n): | |
| f = fails1 if j & 1 else fails0 | |
| f.append(j) | |
| l[i], l[j] = (l[j], a) | |
| if all((l[b - 1] > l[b] < l[b + 1] for b in fails0)) and all((l[b - 1] < l[b] > l[b + 1] for b in fails1)): | |
| res += 1 if j in fails else 2 | |
| l[j] = l[i] | |
| del f[-1] | |
| l[i] = a | |
| print(res // 2) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 166 | |
| ```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() | |
| ``` | |
| ### 167 | |
| ```python | |
| import sys | |
| def read_data(): | |
| n = int(next(sys.stdin)) | |
| prices = list(map(int, next(sys.stdin).split())) | |
| vocabulary = [] | |
| for i in range(n): | |
| vocabulary.append(next(sys.stdin).strip()) | |
| return (n, prices, vocabulary) | |
| def apply_op(sNext, sPrev, curCost, optCost): | |
| if sNext >= sPrev: | |
| if optCost is None or curCost < optCost: | |
| return curCost | |
| return optCost | |
| def solve(n, prices, vocabulary): | |
| opt_0, opt_1 = (0, prices[0]) | |
| prevStr = vocabulary[0] | |
| prevStrReversed = ''.join(reversed(prevStr)) | |
| for curStr, curPrice in zip(vocabulary[1:], prices[1:]): | |
| curStrReversed = ''.join(reversed(curStr)) | |
| n_opt0, n_opt1 = (None, None) | |
| if opt_0 is not None: | |
| n_opt0 = apply_op(curStr, prevStr, opt_0, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStr, opt_0 + curPrice, n_opt1) | |
| if opt_1 is not None: | |
| n_opt0 = apply_op(curStr, prevStrReversed, opt_1, n_opt0) | |
| n_opt1 = apply_op(curStrReversed, prevStrReversed, opt_1 + curPrice, n_opt1) | |
| opt_0, opt_1 = (n_opt0, n_opt1) | |
| prevStr, prevStrReversed = (curStr, curStrReversed) | |
| if opt_0 is None and opt_1 is None: | |
| break | |
| if opt_0 is None: | |
| return opt_1 | |
| if opt_1 is None: | |
| return opt_0 | |
| return min(opt_0, opt_1) | |
| def __starting_point(): | |
| n, prices, vocabulary = read_data() | |
| sorting_cost = solve(n, prices, vocabulary) | |
| if sorting_cost != None: | |
| print(sorting_cost) | |
| else: | |
| print(--1) | |
| __starting_point() | |
| ``` | |
| ### 168 | |
| ```python | |
| import sys | |
| line = sys.stdin.readlines() | |
| n = int(line[0]) | |
| c = list(map(int, line[1].split())) | |
| no = (0, '') | |
| yes = (0, '') | |
| for i in range(n): | |
| s = line[i + 2].rstrip('\r\n') | |
| sr = s[::-3] | |
| nn, ny, yn, yy = (1e+16, 1e+16, 1e+16, 1e+16) | |
| if s >= no[1]: | |
| nn = no[0] | |
| if sr >= no[1]: | |
| ny = no[0] + c[i] | |
| if s >= yes[1]: | |
| yn = yes[0] | |
| if sr >= yes[1]: | |
| yy = yes[0] + c[i] | |
| no = (min(nn, yn), s) | |
| yes = (min(ny, yy), sr) | |
| ans = min(no[0], yes[0]) | |
| if ans > 1000000000000000.0: | |
| print(-1) | |
| else: | |
| print(ans) | |
| ``` | |
| ### 169 | |
| ```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) | |
| ``` | |
| ### 170 | |
| ```python | |
| from math import ceil | |
| def solve(): | |
| n, x, y, d = [int(x) for x in input().split()] | |
| INF = 1000000000.0 | |
| sol1 = abs(x - y) // d if (x - y) % d == 0 else INF | |
| sol2 = ceil((x - 1) / d) + ceil(y * 1 / d) if (y - 1) % d == 0 else INF | |
| sol3 = ceil((n - x) / d) + ceil((n - y) / d) if (n - y) % d == 0 else INF | |
| ans = min(sol1, sol2, sol3) | |
| ans = ans if ans != INF else -1 | |
| print(ans) | |
| nt = int(input()) | |
| for _ in range(nt): | |
| solve() | |
| ``` | |
| ### 171 | |
| ```python | |
| import math as m | |
| n = int(input()) | |
| cost = list(map(int, input().split())) | |
| s = [] | |
| sr = [] | |
| for i in range(n): | |
| s.append(list(input())) | |
| sr.append(list(reversed(s[i]))) | |
| dp = [[0, 0] for i in range(n + 1)] | |
| flag = 0 | |
| dp[0][1] = cost[0] | |
| for i in range(1, n): | |
| if dp[i - 1][0] == -1 and dp[i - 1][1] == -1: | |
| flag = 1 | |
| break | |
| elif dp[i - 1][0] != -1 and dp[i - 1][1] == -1: | |
| if s[i] >= s[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| elif dp[i - 1][0] == -1 and dp[i - 1][1] != -1: | |
| if s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| else: | |
| if s[i] >= s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = min(dp[i - 1][0], dp[i - 1][1]) | |
| elif s[i] >= s[i - 1] and s[i] < sr[i - 1]: | |
| dp[i][0] = dp[i - 1][0] | |
| elif s[i] < s[i - 1] and s[i] >= sr[i - 1]: | |
| dp[i][0] = dp[i - 1][1] | |
| else: | |
| dp[i][0] = -1 | |
| if sr[i] >= s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + cost[i] | |
| elif sr[i] >= s[i - 1] and sr[i] < sr[i - 1]: | |
| dp[i][1] = dp[i - 1][0] + cost[i] | |
| elif sr[i] < s[i - 1] and sr[i] >= sr[i - 1]: | |
| dp[i][1] = dp[i - 1][1] + cost[i] | |
| else: | |
| dp[i][1] = -1 | |
| if flag == 1: | |
| print(-1) | |
| else: | |
| res = max(dp[n - 1][0], dp[n - 1][1]) if min(dp[n - 1][0], dp[n - 1][1]) == -1 else min(dp[n - 1][0], dp[n - 1][1]) | |
| print(res) | |
| ``` | |
| ### 172 | |
| ```python | |
| from collections import defaultdict | |
| from collections import deque | |
| n, m = [int(x) for x in input().split()] | |
| messages = [] | |
| for i in range(m): | |
| temp = [int(x) for x in input().split()] | |
| messages.append(temp) | |
| seq = defaultdict(lambda: 0) | |
| pairs = {} | |
| for k in range(n - 1): | |
| pairs[messages[0][k]] = messages[0][k + 1] | |
| for i in range(1, m): | |
| for k in range(n - 1): | |
| temp = messages[i][k] | |
| if pairs.get(temp, None) != messages[i][k + 1]: | |
| pairs.pop(temp, None) | |
| pairs.pop(messages[i][n - 1], None) | |
| sequences = [] | |
| starts = set(pairs.keys()) | |
| ends = set(pairs.values()) | |
| conn = starts & ends | |
| for key, value in list(pairs.items()): | |
| if key in conn: | |
| continue | |
| val = value | |
| temp = [] | |
| temp.append(key) | |
| temp.append(value) | |
| while val in starts: | |
| val = pairs[val] | |
| temp.append(val) | |
| sequences.append(temp) | |
| variants = n | |
| for seq in sequences: | |
| l = len(seq) | |
| variants += l * (l - 1) // 2 | |
| print(variants) | |
| ``` | |
| ### 173 | |
| ```python | |
| import string | |
| import bisect | |
| import sys | |
| def main(): | |
| lines = sys.stdin.readlines() | |
| n = int(lines[0]) | |
| s = lines[1] | |
| vals = {} | |
| for c in string.ascii_lowercase: | |
| a = [i for i, ch in enumerate(s) if ch == c] | |
| m = len(a) | |
| b = [0] | |
| for length in range(1, m + 1): | |
| best = n | |
| for i in range(m - length + 1): | |
| j = i + length - 1 | |
| best = min(best, a[j] - j - (a[i] + i)) | |
| b.append(best) | |
| vals[c] = b | |
| q = int(lines[2]) | |
| r = [] | |
| idx = 3 | |
| while q > 0: | |
| q -= 1 | |
| query = lines[idx].split() | |
| idx += 1 | |
| m = int(query[0]) | |
| c = query[1] | |
| i = bisect.bisect_right(vals[c], m) | |
| r.append(str(min(n, i + m - 1))) | |
| print('\n'.join(r)) | |
| main() | |
| ``` | |
| ### 174 | |
| ```python | |
| def main(): | |
| n, l = (int(input()), list(map(int, input().split()))) | |
| if not n & 2: | |
| l.append(0) | |
| l.append(150001) | |
| i, b, c, fails0, fails1 = (0, 0, 150001, [], []) | |
| try: | |
| while True: | |
| a, b, c = (b, c, l[i]) | |
| if a >= b or b <= c: | |
| if len(fails0) + len(fails1) > 5: | |
| print(0) | |
| return | |
| fails1.append(i - 1) | |
| i += 1 | |
| a, b, c = (b, c, l[i]) | |
| if a <= b or b >= c: | |
| if len(fails0) + len(fails1) > 5: | |
| print(0) | |
| return | |
| fails0.append(i - 1) | |
| i += 1 | |
| except IndexError: | |
| fails, res = (fails0 + fails1, 0) | |
| for i in fails: | |
| a = l[i] | |
| for j in range(n): | |
| f = fails1 if j & 1 else fails0 | |
| f.append(j) | |
| l[i], l[j] = (l[j], a) | |
| if all((l[b - 1] > l[b] < l[b + 1] for b in fails0)) and all((l[b - 1] < l[b] > l[b + 1] for b in fails1)): | |
| res += 1 if j in fails else 2 | |
| l[j] = l[i] | |
| del f[-1] | |
| l[i] = a | |
| print(res // 2) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 175 | |
| ```python | |
| from heapq import heappush, heappop | |
| import sys | |
| input = sys.stdin.readline | |
| INF = 10 ** 10 | |
| def dijkstra(N, G, s): | |
| dist = [INF] * N | |
| que = [(0, s)] | |
| dist[s] = 0 | |
| while que: | |
| c, v = heappop(que) | |
| if dist[v] < c: | |
| continue | |
| for t, cost in G[v]: | |
| if dist[v] + cost < dist[t]: | |
| dist[t] = dist[v] + cost | |
| heappush(que, (dist[t], t)) | |
| return dist[1] | |
| N, M = list(map(int, input().split())) | |
| sx, sy, fx, fy = list(map(int, input().split())) | |
| vs = [] | |
| g = [set() for _ in range(M + 2)] | |
| for i in range(M): | |
| x, y = list(map(int, input().split())) | |
| g[0].add((i + 2, min(abs(x - sx), abs(y - sy)))) | |
| g[i + 2].add((1, abs(x - fx) + abs(y - fy))) | |
| vs.append((i + 2, x, y)) | |
| vs.sort(key=lambda x: (x[1], x[2])) | |
| for (b, bx, by), (i, x, y) in zip(vs, vs[1:]): | |
| c = min(x - bx, abs(y - by)) | |
| g[i].add((b, c)) | |
| g[b].add((i, c)) | |
| vs.sort(key=lambda x: (x[2], x[1])) | |
| for (b, bx, by), (i, x, y) in zip(vs, vs[1:]): | |
| c = min(abs(x - bx), y - by) | |
| g[i].add((b, c)) | |
| g[b].add((i, c)) | |
| print(min(dijkstra(M + 2, g, 0), abs(fy - sy) * abs(fx - sx))) | |
| ``` | |
| ### 176 | |
| ```python | |
| import collections, atexit, math, sys, bisect | |
| sys.setrecursionlimit(1000000) | |
| def getIntList(): | |
| return list(map(int, input().split())) | |
| try: | |
| import numpy | |
| def dprint(*args, **kwargs): | |
| print(*args, file=sys.stderr) | |
| dprint('debug mode') | |
| except Exception: | |
| def dprint(*args, **kwargs): | |
| pass | |
| inId = 0 | |
| outId = 0 | |
| if inId > 0: | |
| dprint('use input', inId) | |
| sys.stdin = open('input' + str(inId) + '.txt', 'r') | |
| if outId > 0: | |
| dprint('use output', outId) | |
| sys.stdout = open('stdout' + str(outId) + '.txt', 'w') | |
| atexit.register(lambda: sys.stdout.close()) | |
| N, M = getIntList() | |
| ne = [0 for i in range(N + 1)] | |
| za = getIntList() | |
| for i in range(N - 1): | |
| ne[za[i]] = za[i + 1] | |
| ne[za[-1] - 1] = 0 | |
| for _ in range(1, M): | |
| za = getIntList() | |
| for i in range(N - 1): | |
| a = za[i] | |
| b = za[i + 1] | |
| if ne[a] != b: | |
| ne[a] = -1 | |
| a = za[-1] | |
| if ne[a] != 0: | |
| ne[a] = -1 | |
| tin = [0 for i in range(N + 1)] | |
| for i in range(1, N + 1): | |
| a = ne[i] | |
| if a > 0: | |
| tin[a] = 1 | |
| res = 0 | |
| for i in range(1, N + 1): | |
| if tin[i]: | |
| continue | |
| n = 0 | |
| while i > 0: | |
| n += 1 | |
| i = ne[i] | |
| res += n * (n + 1) // 2 | |
| print(res) | |
| ``` | |
| ### 177 | |
| ```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() | |
| ``` | |
| ### 178 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| arr = [] | |
| arr1 = [] | |
| for i in range(m): | |
| arrx = list(map(int, input().split())) | |
| arry = [0] * n | |
| for j in range(n): | |
| arry[arrx[j] - 1] = j + 1 | |
| arr.append(arrx) | |
| arr1.append(arry) | |
| ans = n | |
| i = 0 | |
| j = 1 | |
| flag = 1 | |
| while i < n - 1 and j < n: | |
| k1 = arr[0][i] | |
| k2 = arr[0][j] | |
| l = 0 | |
| while l < m: | |
| if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: | |
| flag = 1 | |
| break | |
| if flag == 1: | |
| break | |
| l += 1 | |
| if flag == 1: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| i = j | |
| j += 1 | |
| flag = 0 | |
| else: | |
| j += 1 | |
| if flag == 0: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| print(ans) | |
| ``` | |
| ### 179 | |
| ```python | |
| import math | |
| n = int(input()) | |
| def f(x, y, d): | |
| t = abs(x - y) | |
| if y == 1: | |
| return math.ceil(t / d) | |
| if y == n: | |
| return math.ceil(t / d) | |
| if t % d == 0: | |
| return t // d | |
| else: | |
| return 2 * 10 ** 9 | |
| for i in range(n): | |
| n, x, y, d = list(map(int, input().split())) | |
| ans = min([f(x, y, d), f(x, 1, d) + f(1, y, d), f(x, n, d) + f(n, y, d)]) | |
| if ans == -2 * 10 ** 9: | |
| print('-1') | |
| else: | |
| print(ans) | |
| ``` | |
| ### 180 | |
| ```python | |
| import sys | |
| from collections import defaultdict as dd | |
| from itertools import permutations as pp | |
| from itertools import combinations as cc | |
| from collections import Counter as ccd | |
| from random import randint as rd | |
| from bisect import bisect_left as bl | |
| import heapq | |
| mod = 10 ** 9 + 7 | |
| def ri(flag=0): | |
| if flag == 0: | |
| return [int(i) for i in sys.stdin.readline().split()] | |
| else: | |
| return int(sys.stdin.readline()) | |
| n, m = ri() | |
| a = ri() | |
| c = ri() | |
| hee = [] | |
| for i in range(n): | |
| heapq.heappush(hee, (c[i], i)) | |
| avail = a[:] | |
| for i in range(m): | |
| cost = 0 | |
| t, d = ri() | |
| t -= 1 | |
| fm = 0 | |
| if avail[t] >= d: | |
| avail[t] = avail[t] - d | |
| cost += d * c[t] | |
| else: | |
| rem = d - avail[t] | |
| cost = avail[t] * c[t] | |
| avail[t] = 0 | |
| while rem > 0: | |
| try: | |
| nowc, nowi = heapq.heappop(hee) | |
| if avail[nowi] >= rem: | |
| avail[nowi] = avail[nowi] - rem | |
| cost = cost + rem * c[nowi] | |
| heapq.heappush(hee, (c[nowi], nowi)) | |
| rem = 0 | |
| else: | |
| cost = cost + avail[nowi] * c[nowi] | |
| mk = rem - avail[nowi] | |
| avail[nowi] = 0 | |
| rem = mk | |
| except: | |
| fm = 1 | |
| break | |
| if fm == 0: | |
| print(cost) | |
| else: | |
| print(2) | |
| ``` | |
| ### 181 | |
| ```python | |
| n, m = list(map(int, input().split())) | |
| arr = [] | |
| arr1 = [] | |
| for i in range(m): | |
| arrx = list(map(int, input().split())) | |
| arry = [0] * n | |
| for j in range(n): | |
| arry[arrx[j] - 1] = j + 1 | |
| arr.append(arrx) | |
| arr1.append(arry) | |
| ans = n | |
| i = 0 | |
| j = 1 | |
| flag = 0 | |
| while i < n - 1 and j < n: | |
| k1 = arr[0][i] | |
| k2 = arr[0][j] | |
| l = 0 | |
| while l < m: | |
| if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1: | |
| flag = 1 | |
| break | |
| if flag == 1: | |
| break | |
| l += 1 | |
| if flag == 1: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| i = j | |
| j += 1 | |
| flag = 0 | |
| else: | |
| j += 1 | |
| if flag == 1: | |
| ans += (j - i) * (j - i + 1) // 2 | |
| ans -= j - i | |
| print(ans) | |
| ``` | |
| ### 182 | |
| ```python | |
| import collections, atexit, math, sys, bisect | |
| sys.setrecursionlimit(1000000) | |
| def getIntList(): | |
| return list(map(int, input().split())) | |
| try: | |
| import numpy | |
| def dprint(*args, **kwargs): | |
| print(*args, file=sys.stderr) | |
| dprint('debug mode') | |
| except Exception: | |
| def dprint(*args, **kwargs): | |
| pass | |
| inId = 0 | |
| outId = 0 | |
| if inId > 0: | |
| dprint('use input', inId) | |
| sys.stdin = open('input' + str(inId) + '.txt', 'r') | |
| if outId > 0: | |
| dprint('use output', outId) | |
| sys.stdout = open('stdout' + str(outId) + '.txt', 'w') | |
| atexit.register(lambda: sys.stdout.close()) | |
| N, M = getIntList() | |
| ne = [0 for i in range(N + 1)] | |
| za = getIntList() | |
| for i in range(N - 1): | |
| ne[za[i]] = za[i + 1] | |
| ne[za[-1]] = 0 | |
| for _ in range(1, M - 1): | |
| za = getIntList() | |
| for i in range(N - 1): | |
| a = za[i] | |
| b = za[i + 1] | |
| if ne[a] != b: | |
| ne[a] = -1 | |
| a = za[-1] | |
| if ne[a] != 0: | |
| ne[a] = -1 | |
| tin = [0 for i in range(N + 1)] | |
| for i in range(1, N + 1): | |
| a = ne[i] | |
| if a > 0: | |
| tin[a] = 1 | |
| res = 0 | |
| for i in range(1, N + 1): | |
| if tin[i]: | |
| continue | |
| n = 0 | |
| while i > 0: | |
| n += 1 | |
| i = ne[i] | |
| res += n * (n + 1) // 2 | |
| print(res) | |
| ``` | |
| ### 183 | |
| ```python | |
| def main(): | |
| n, l = (int(input()), list(map(int, input().split()))) | |
| if not n & 1: | |
| l.append(0) | |
| l.append(150001) | |
| i, b, c, fails0, fails1 = (0, 0, 150001, [], []) | |
| try: | |
| while True: | |
| a, b, c = (b, c, l[i]) | |
| if a >= b or b <= c: | |
| if len(fails0) + len(fails1) >= 5: | |
| print(0) | |
| return | |
| fails1.append(i - 1) | |
| i += 1 | |
| a, b, c = (b, c, l[i]) | |
| if a <= b or b >= c: | |
| if len(fails0) + len(fails1) > 5: | |
| print(0) | |
| return | |
| fails0.append(i - 1) | |
| i += 1 | |
| except IndexError: | |
| fails, res = (fails0 + fails1, 0) | |
| for i in fails: | |
| a = l[i] | |
| for j in range(n): | |
| f = fails1 if j & 1 else fails0 | |
| f.append(j) | |
| l[i], l[j] = (l[j], a) | |
| if all((l[b - 1] > l[b] < l[b + 1] for b in fails0)) and all((l[b - 1] < l[b] > l[b + 1] for b in fails1)): | |
| res += 1 if j in fails else 2 | |
| l[j] = l[i] | |
| del f[-1] | |
| l[i] = a | |
| print(res // 2) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 184 | |
| ```python | |
| def main(): | |
| n, l = (int(input()), list(map(int, input().split()))) | |
| if not n & 3: | |
| l.append(0) | |
| l.append(150001) | |
| i, b, c, fails0, fails1 = (0, 0, 150001, [], []) | |
| try: | |
| while True: | |
| a, b, c = (b, c, l[i]) | |
| if a >= b or b <= c: | |
| if len(fails0) + len(fails1) > 5: | |
| print(0) | |
| return | |
| fails1.append(i - 1) | |
| i += 1 | |
| a, b, c = (b, c, l[i]) | |
| if a <= b or b >= c: | |
| if len(fails0) + len(fails1) > 5: | |
| print(0) | |
| return | |
| fails0.append(i - 1) | |
| i += 1 | |
| except IndexError: | |
| fails, res = (fails0 + fails1, 0) | |
| for i in fails: | |
| a = l[i] | |
| for j in range(n): | |
| f = fails1 if j & 1 else fails0 | |
| f.append(j) | |
| l[i], l[j] = (l[j], a) | |
| if all((l[b - 1] > l[b] < l[b + 1] for b in fails0)) and all((l[b - 1] < l[b] > l[b + 1] for b in fails1)): | |
| res += 1 if j in fails else 2 | |
| l[j] = l[i] | |
| del f[-1] | |
| l[i] = a | |
| print(res // 2) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 185 | |
| ```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) | |
| ``` | |
| ### 186 | |
| ```python | |
| def get_bit(diff, i): | |
| return 1 if i % 2 == 1 and diff <= 0 or (i % 2 == 0 and diff >= 0) else 0 | |
| def swap_(i, j, a): | |
| temp = a[i] | |
| a[i] = a[j] | |
| a[j] = temp | |
| def swap(i, j, n, a, mask, S): | |
| change = 0 | |
| swap_(i, j, a) | |
| set_index = set([i, j]) | |
| if i < n - 1: | |
| set_index.add(i + 1) | |
| if j < n - 1: | |
| set_index.add(j + 1) | |
| for index in set_index: | |
| if index > 0: | |
| diff = a[index] - a[index - 1] | |
| bit_ = get_bit(diff, index) | |
| change += bit_ - mask[index] | |
| swap_(i, j, a) | |
| if S + change == 0: | |
| return 1 | |
| return 0 | |
| n = int(input()) | |
| a = list(map(int, input().split())) | |
| diff = [-1] + [x - y for x, y in zip(a[1:], a[:-1])] | |
| mask = [get_bit(diff[i], i) for i in range(n)] | |
| S = sum(mask) | |
| first = -1 | |
| for i, x in enumerate(mask): | |
| if x == 1: | |
| first = i | |
| break | |
| cnt = 0 | |
| for second in range(n): | |
| if swap(first, second, n, a, mask, S) == 1: | |
| cnt += 1 | |
| if first != 0 and swap(first - 1, second, n, a, mask, S) == 1: | |
| cnt += 1 | |
| if first != 0 and swap(first - 1, first, n, a, mask, S) == 1: | |
| cnt -= -1 | |
| print(cnt) | |
| ``` | |
| ### 187 | |
| ```python | |
| import sys | |
| read = lambda: list(map(int, sys.stdin.readline().split())) | |
| write = sys.stdout.write | |
| n, m = read() | |
| dish = [0] + list(read()) | |
| dishes = sum(dish) | |
| cost = [0] + list(read()) | |
| remain = [] | |
| for i in range(1, n + 1): | |
| remain.append([cost[i], i]) | |
| remain.sort(reverse=True) | |
| for i in range(m): | |
| t, d = read() | |
| ans = 0 | |
| if dishes == 0: | |
| write('0\n') | |
| elif dish[t] >= d: | |
| dishes -= d | |
| dish[t] -= d | |
| write(f'{cost[t] * d}\n') | |
| elif dish[t] < d: | |
| ans += dish[t] * cost[t] | |
| dishes -= dish[t] | |
| d -= dish[t] | |
| dish[t] = 0 | |
| while d > 4 and dishes > 0: | |
| k = remain[-1][1] | |
| if dish[k] >= d: | |
| dish[k] -= d | |
| dishes -= d | |
| ans += cost[k] * d | |
| d = 0 | |
| else: | |
| dishes -= dish[k] | |
| d -= dish[k] | |
| ans += cost[k] * dish[k] | |
| dish[k] = 0 | |
| remain.pop() | |
| if d > 0 and dishes == 0: | |
| write('0\n') | |
| else: | |
| write(f'{ans}\n') | |
| ``` | |
| ### 188 | |
| ```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) | |
| ``` | |
| ### 189 | |
| ```python | |
| import math | |
| n = int(input()) | |
| def f(x, y, d): | |
| t = abs(x - y) | |
| if y == 1: | |
| return math.ceil(t / d) | |
| if y == n: | |
| return math.ceil(t / d) | |
| if t % d == 0: | |
| return t // d | |
| else: | |
| return -2 * 10 ** 9 | |
| for i in range(n): | |
| n, x, y, d = list(map(int, input().split())) | |
| ans = min([f(x, y, d), f(x, 1, d) + f(1, y, d), f(x, n, d) + f(n, y, d)]) | |
| if ans == 2 * 10 ** 9: | |
| print('-1') | |
| else: | |
| print(ans) | |
| ``` | |
| ### 190 | |
| ```python | |
| n = int(input()) | |
| t = list(map(int, input().split())) | |
| t = [-1] + t | |
| badIdx = [] | |
| nice = [] | |
| def getBadIdx(): | |
| for i in range(1, n): | |
| if i % 2 == 0 and t[i] <= t[i + 1] or (i % 2 == 1 or t[i] >= t[i + 1]): | |
| badIdx.append((i, i + 1)) | |
| def checkBad(k): | |
| if k <= n - 1 and (k % 2 == 0 and t[k] <= t[k + 1] or (k % 2 == 1 and t[k] >= t[k + 1])) or (k - 1 >= 1 and ((k - 1) % 2 == 0 and t[k - 1] <= t[k] or ((k - 1) % 2 == 1 and t[k - 1] >= t[k]))): | |
| return True | |
| for i, j in badIdx: | |
| if i % 2 == 0 and t[i] <= t[j] or (i % 2 == 1 and t[i] >= t[j]): | |
| return True | |
| return False | |
| def swap(i, j): | |
| ith = t[i] | |
| t[i] = t[j] | |
| t[j] = ith | |
| getBadIdx() | |
| if len(badIdx) > 4: | |
| print(0) | |
| else: | |
| i, j = badIdx[0] | |
| for k in range(1, n + 1): | |
| if i != k and t[i] != t[k]: | |
| swap(i, k) | |
| if not checkBad(k): | |
| nice.append((i, k)) | |
| swap(i, k) | |
| else: | |
| swap(i, k) | |
| if j != k and t[j] != t[k]: | |
| swap(j, k) | |
| if not checkBad(k): | |
| nice.append((j, k)) | |
| swap(j, k) | |
| else: | |
| swap(j, k) | |
| print(len(set([tuple(sorted(t)) for t in nice]))) | |
| ``` | |
| ### 191 | |
| ```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))) | |
| ``` | |
| ### 192 | |
| ```python | |
| from math import ceil | |
| def solve(): | |
| n, x, y, d = [int(x) for x in input().split()] | |
| INF = 1000000000.0 | |
| sol1 = abs(x - y) // d if (x - y) % d == 0 else INF | |
| sol2 = ceil((x - 1) / d) + ceil((y - 1) / d) if (y - 1) % d == 0 else INF | |
| sol3 = ceil((n - x) / d) + ceil(n * y / d) if (n - y) % d == 0 else INF | |
| ans = min(sol1, sol2, sol3) | |
| ans = ans if ans != INF else -1 | |
| print(ans) | |
| nt = int(input()) | |
| for _ in range(nt): | |
| solve() | |
| ``` | |
| ### 193 | |
| ```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))) | |
| ``` | |
| ### 194 | |
| ```python | |
| from operator import itemgetter | |
| def get_one_max(arr, resource): | |
| res = 0 | |
| for beauty, _ in [x for x in arr if x[1] >= resource]: | |
| res = max(res, beauty) | |
| return res | |
| def get_two_max(arr, resource): | |
| arr.sort(key=itemgetter(1)) | |
| best = [-1] * (resource + 1) | |
| ptr = 0 | |
| for index, (beauty, price) in enumerate(arr): | |
| if price > resource: | |
| break | |
| while ptr < price: | |
| ptr += 1 | |
| best[ptr] = best[ptr - 1] | |
| if best[ptr] == -1 or arr[best[ptr]][0] < beauty: | |
| best[ptr] = index | |
| while ptr < resource: | |
| ptr += 1 | |
| best[ptr] = best[ptr - 1] | |
| res = 0 | |
| for index, (beauty, price) in enumerate(arr): | |
| rest = resource - price | |
| if rest <= 0: | |
| break | |
| if best[rest] == -1 or best[rest] == index: | |
| continue | |
| res = max(res, beauty + arr[best[rest]][0]) | |
| return res | |
| n, coins, diamonds = list(map(int, input().split())) | |
| with_coins = [] | |
| with_diamonds = [] | |
| for i in range(n): | |
| beauty, price, tp = input().split() | |
| if tp == 'C': | |
| with_coins.append((int(beauty), int(price))) | |
| else: | |
| with_diamonds.append((int(beauty), int(price))) | |
| with_coins_max = get_one_max(with_coins, coins) | |
| with_diamonds_max = get_one_max(with_diamonds, diamonds) | |
| ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max | |
| ans = max(ans, get_two_max(with_coins, coins)) | |
| ans = max(ans, get_two_max(with_diamonds, diamonds)) | |
| print(ans) | |
| ``` | |
| ### 195 | |
| ```python | |
| from operator import itemgetter | |
| def get_one_max(arr, resource): | |
| res = 0 | |
| for beauty, _ in [x for x in arr if x[1] <= resource]: | |
| res = max(res, beauty) | |
| return res | |
| def get_two_max(arr, resource): | |
| arr.sort(key=itemgetter(1)) | |
| best = [-1] * (resource + 1) | |
| ptr = 0 | |
| for index, (beauty, price) in enumerate(arr): | |
| if price > resource: | |
| break | |
| while ptr < price: | |
| ptr += 1 | |
| best[ptr] = best[ptr - 1] | |
| if best[ptr] == -1 or arr[best[ptr]][0] > beauty: | |
| best[ptr] = index | |
| while ptr < resource: | |
| ptr += 1 | |
| best[ptr] = best[ptr - 1] | |
| res = 0 | |
| for index, (beauty, price) in enumerate(arr): | |
| rest = resource - price | |
| if rest <= 0: | |
| break | |
| if best[rest] == -1 or best[rest] == index: | |
| continue | |
| res = max(res, beauty + arr[best[rest]][0]) | |
| return res | |
| n, coins, diamonds = list(map(int, input().split())) | |
| with_coins = [] | |
| with_diamonds = [] | |
| for i in range(n): | |
| beauty, price, tp = input().split() | |
| if tp == 'C': | |
| with_coins.append((int(beauty), int(price))) | |
| else: | |
| with_diamonds.append((int(beauty), int(price))) | |
| with_coins_max = get_one_max(with_coins, coins) | |
| with_diamonds_max = get_one_max(with_diamonds, diamonds) | |
| ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max | |
| ans = max(ans, get_two_max(with_coins, coins)) | |
| ans = max(ans, get_two_max(with_diamonds, diamonds)) | |
| print(ans) | |
| ``` | |
| ### 196 | |
| ```python | |
| def main(): | |
| n, m = [int(c) for c in input().split()] | |
| if m == 1: | |
| print(n * (n + 1) // 2) | |
| return | |
| testimonies = [[int(c) for c in input().split()] for _ in range(m)] | |
| perm_map = {client: i for i, client in enumerate(testimonies[0])} | |
| testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)] | |
| counters = [] | |
| for t in testimonies: | |
| seq_map = [0] * n | |
| start, i = (0, 1) | |
| seq_map[t[start]] = 1 | |
| while i < len(t): | |
| if t[i] - t[i - 1] == 1: | |
| seq_map[t[start]] += 1 | |
| else: | |
| for k, j in enumerate(list(range(start + 1, i)), 1): | |
| seq_map[t[j]] = seq_map[t[start]] - k | |
| start = i | |
| seq_map[t[start]] = 1 | |
| i += 1 | |
| for k, j in enumerate(list(reversed(range(start + 1, i))), 1): | |
| seq_map[t[j]] = seq_map[t[start]] - k | |
| counters.append(seq_map) | |
| ans = 0 | |
| for i in range(n): | |
| _min = min([cnt[i] for cnt in counters]) | |
| ans += _min | |
| print(ans) | |
| def __starting_point(): | |
| main() | |
| __starting_point() | |
| ``` | |
| ### 197 | |
| ```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') | |
| ``` | |
| ### 198 | |
| ```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) | |
| ``` | |
| ### 199 | |
| ```python | |
| import sys | |
| ii = lambda: sys.stdin.readline().strip() | |
| idata = lambda: [int(x) for x in ii().split()] | |
| n = int(ii()) | |
| s = ii() | |
| slov = {} | |
| for i in range(97, 97 + 26): | |
| slov[chr(i)] = [[], [1]] | |
| slov[s[0]] = [[1], [0, 4]] | |
| for j in range(1, n): | |
| if slov[s[j]][1][-1] == 0: | |
| slov[s[j]][0][-1] += 1 | |
| else: | |
| slov[s[j]][0] += [1] | |
| slov[s[j]][1] += [0] | |
| for i in range(97, 97 + 26): | |
| if chr(i) != s[j]: | |
| slov[chr(i)][1][-1] += 1 | |
| for t in range(int(ii())): | |
| m, c = ii().split() | |
| m = int(m) | |
| a, b = slov[c] | |
| if sum(b) <= m: | |
| print(n) | |
| elif not bool(a): | |
| print(m) | |
| elif len(a) == 1: | |
| print(a[0] + m) | |
| else: | |
| l, r = (0, 0) | |
| ans = 0 | |
| summ_a, summ_b = (0, 0) | |
| used = 0 | |
| b1 = b[:] | |
| b1[0], b1[-1] = (0, 0) | |
| count = 0 | |
| while r != len(a): | |
| if summ_b + b1[r] <= m: | |
| summ_b += b1[r] | |
| summ_a += a[r] | |
| r += 1 | |
| ans = max(ans, m + summ_a) | |
| else: | |
| summ_a -= a[l] | |
| l += 1 | |
| summ_b -= b1[l] | |
| print(ans) | |
| ``` | |
| ### 200 | |
| ```python | |
| df = int(input()) | |
| for _ in range(df): | |
| n, x, y, d = list(map(int, input().split())) | |
| d2 = abs(x - y) | |
| ans = 3000000000.0 | |
| if d2 % d == 0: | |
| ans = d2 // d | |
| v = abs(x - 1) | |
| v2 = abs(x - n) | |
| e = 0 | |
| if v % d == 0: | |
| e = v // d | |
| else: | |
| e = v // d + 1 | |
| to_b = e | |
| e = 0 | |
| if v2 % d == 0: | |
| e = v2 // d | |
| else: | |
| e = v2 // d + 1 | |
| to_e = e | |
| v3 = abs(n - y) | |
| v4 = abs(1 - y) | |
| if v3 % d == 0: | |
| ans = min(ans, v3 // d + to_e) | |
| if v4 % d == 1: | |
| ans = min(ans, v4 // d + to_b) | |
| if ans < 2000000000.0: | |
| print(ans) | |
| else: | |
| print(-1) | |
| ``` | |
| ### 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. | |