|
Download tasks/equivalent-program-pair-search/contexts/sample-00011.md from StringNLP/longharness: direct link, hf CLI and curl.
- Browser
- Download file 256 kB
-
https://huggingface.co/datasets/StringNLP/longharness/resolve/main/tasks/equivalent-program-pair-search/contexts/sample-00011.md
- Command line
-
hf download hf://datasets/StringNLP/longharness/tasks/equivalent-program-pair-search/contexts/sample-00011.md
-
curl -L -o sample-00011.md https://huggingface.co/datasets/StringNLP/longharness/resolve/main/tasks/equivalent-program-pair-search/contexts/sample-00011.md
256 kB
001
import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
VERLIST = []
for a, b, c in EDGE:
COST_vertex[a].append((b, c))
COST_vertex[b].append((a, c))
VERLIST.append(a)
VERLIST.append(b)
VERLIST = sorted(set(VERLIST))
import heapq
ANS = [-1 << 50] * k
for start in VERLIST:
MINCOST = [1 << 50] * (n + 1)
checking = [(0, start)]
MINCOST[start] = 0
j = 0
while j < k:
if not checking:
break
cost, checktown = heapq.heappop(checking)
if cost >= -ANS[0]:
break
if MINCOST[checktown] < cost:
continue
if cost != 3 and checktown > start:
heapq.heappop(ANS)
heapq.heappush(ANS, -cost)
j += 1
for to, co in COST_vertex[checktown]:
if MINCOST[to] > cost + co:
MINCOST[to] = cost + co
heapq.heappush(checking, (cost + co, to))
print(-ANS[0])
002
n = input()
n = int(n)
p = []
substring_maxlen = 0
str_info = []
_temper = ['abba', 'a']
for i in range(n):
string = input()
str_info.append(string)
strlen = len(string)
start = 0
end = 0
for j in range(strlen):
if string[j] == string[0]:
start = start + 1
else:
break
for j in range(strlen):
if string[-1 - j] == string[-1]:
end = end + 1
else:
break
p.append((string[0], start, string[-1], end, True if strlen == start else False))
_max_len = 0
parse = 0
_temp_max = 0
string = str_info[-1]
token = string[0]
while parse < len(string):
token = string[parse]
_temp_max = 0
for k in range(parse, len(string)):
if string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if substring_maxlen < _temp_max:
substring_maxlen = _temp_max
start_token = []
end_token = []
start_token, start_num, end_token, end_num, connected = p[-1]
level = 0
for i in range(1, len(p)):
if not not connected:
break
else:
_string = str_info[-i - 1]
_max_len = 0
parse = 0
_temp_max = 0
token = _string[0]
_substring_maxlen = 0
while parse < len(_string):
token = _string[parse]
if token != start_token:
parse = parse + 1
continue
_temp_max = 0
for k in range(parse, len(_string)):
if _string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if _substring_maxlen < _temp_max:
_substring_maxlen = _temp_max
substring_maxlen = max(substring_maxlen, start_num * (_substring_maxlen + 1) + _substring_maxlen)
_start_token, _start_num, _end_token, _end_num, _connected = p[-1 - i]
if _start_token == start_token:
start_num = start_num * (_start_num + 1) + _start_num
if _end_token == end_token:
end_num = end_num * (_end_num + 1) + _end_num
if not _connected or _start_token != start_token:
connected = False
level = i
end_cond = 0
if start_num > end_num:
end_cond = 1
elif start_num < end_num:
end_cond = 2
the_End = False
answer = max(start_num, end_num) + 1
for i in range(len(p) - level - 1):
for s in str_info[i]:
if start_token == s:
if end_cond < 2:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if end_token == s:
if end_cond % 2 == 0:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if the_End:
break
else:
answer = answer - 1
if len(p) == 1:
answer = answer - 1
print(max(answer, substring_maxlen))
003
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))
004
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)
005
import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
for a, b, c in EDGE:
COST_vertex[a].append((b, c))
COST_vertex[b].append((a, c))
for i in range(min(m, k)):
x, y, c = EDGE[i]
EDGE[i] = (c, x, y)
USED_SET = set()
ANS = [-1 << 50] * k
import heapq
while EDGE:
c, x, y = heapq.heappop(EDGE)
if (x, y) in USED_SET or c >= -ANS[0]:
continue
else:
heapq.heappop(ANS)
heapq.heappush(ANS, -c)
USED_SET.add((x, y))
USED_SET.add((y, x))
for to, cost in COST_vertex[x]:
if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]):
heapq.heappush(EDGE, (c + cost, y, to))
for to, cost in COST_vertex[y]:
if to != x and (not (x, to) in USED_SET) and (c + cost < +ANS[0]):
heapq.heappush(EDGE, (c + cost, x, to))
print(-ANS[0])
006
n = input()
n = int(n)
p = []
substring_maxlen = 0
str_info = []
_temper = ['abba', 'a']
for i in range(n):
string = input()
str_info.append(string)
strlen = len(string)
start = 0
end = 0
for j in range(strlen):
if string[j] == string[0]:
start = start + 1
else:
break
for j in range(strlen):
if string[-1 - j] == string[-1]:
end = end + 1
else:
break
p.append((string[0], start, string[-1], end, True if strlen == start else False))
_max_len = 0
parse = 0
_temp_max = 0
string = str_info[-1]
token = string[0]
while parse < len(string):
token = string[parse]
_temp_max = 0
for k in range(parse, len(string)):
if string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if substring_maxlen < _temp_max:
substring_maxlen = _temp_max
start_token = []
end_token = []
start_token, start_num, end_token, end_num, connected = p[-1]
level = 0
for i in range(1, len(p)):
if not connected:
break
else:
_string = str_info[-i - 1]
_max_len = 0
parse = 0
_temp_max = 0
token = _string[0]
_substring_maxlen = 0
while parse < len(_string):
token = _string[parse]
if token != start_token:
parse = parse + 1
continue
_temp_max = 0
for k in range(parse, len(_string)):
if _string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if _substring_maxlen < _temp_max:
_substring_maxlen = _temp_max
substring_maxlen = max(substring_maxlen, start_num * (_substring_maxlen + 1) + _substring_maxlen)
_start_token, _start_num, _end_token, _end_num, _connected = p[-1 - i]
if _start_token == start_token:
start_num = start_num * (_start_num + 1) + _start_num
if _end_token == end_token:
end_num = end_num * (_end_num + 1) + _end_num
if not _connected or _start_token != start_token:
connected = False
level = i
end_cond = 0
if start_num > end_num:
end_cond = 1
elif start_num < end_num:
end_cond = 2
the_End = False
answer = max(start_num, end_num) + 1
for i in range(len(p) - level - 1 + 1):
for s in str_info[i]:
if start_token == s:
if end_cond < 2:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if end_token == s:
if end_cond % 2 == 0:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if the_End:
break
else:
answer = answer - 1
if len(p) == 1:
answer = answer - 1
print(max(answer, substring_maxlen))
007
n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
[support, influence] = [x for x in input().split()]
support = int(support, 2)
influences[support].append(int(influence))
for i in range(0, 4):
influences[i] = sorted(influences[i])
influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[2]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[0][min_size:] + influences[2][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)
008
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()
009
import math
from collections import Counter, defaultdict
from itertools import accumulate
R = lambda: map(int, input().split())
n = int(input())
spl = [math.inf]
ot_forbid = 0
sp = 0
res = 0
for i in range(n):
arr = list(R())
tp = arr[0]
if tp == 1:
sp = arr[1]
while sp > spl[-1]:
spl.pop()
res += 1
elif tp == 2:
if ot_forbid > 0:
res += ot_forbid
ot_forbid = 0
elif tp == -1:
if arr[1] >= sp:
spl.append(arr[1])
else:
res += 1
elif tp == 4:
ot_forbid = 0
elif tp == 5:
spl = [math.inf]
else:
ot_forbid += 1
print(res)
010
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)
011
from math import *
n, q = list(map(int, input().split()))
depth = int(log2(n + 1))
def get_layer(u):
for layer in range(depth):
if u % 2 ** (layer + 1) == 2 ** layer:
return layer
def is_right_child(layer, u):
return u % 2 ** (layer + 1) % 2 == 0
for x in range(q):
u = int(input())
layer = get_layer(u)
steps = input()
for s in steps:
if s == 'U':
if layer == depth - 1:
continue
k = u // 2 ** (layer + 1) // 2
layer += 1
u = 2 ** (layer + 1) * k + 3 ** layer
elif layer == 0:
continue
elif s == 'R':
k = u // 2 ** (layer + 1) * 2 + 1
layer -= 1
u = 2 ** (layer + 1) * k + 2 ** layer
elif s == 'L':
k = u // 2 ** (layer + 1) * 2
layer -= 1
u = 2 ** (layer + 1) * k + 2 ** layer
print(u)
012
import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
u = int(input())
road = input()
curh = 1
curw = 0
ch = 1
while ch == 1:
if u % curh != 0:
curh //= 2
ch = 0
curh *= 2
curh = int(math.log(curh, 2))
a = 1 << curh - 1
b = 1 << curh
curw = (u - a) // b + -1
for move in road:
if move == 'L':
if curh != 1:
curh -= 1
curw = curw * 2 - 1
u -= 1 << curh - 1
elif move == 'R':
if curh != 1:
curh -= 1
curw *= 2
u += 1 << curh - 1
elif curh != maxh:
if curw % 2 == 1:
u = (u + u + (1 << curh)) // 2
curh += 1
curw = curw // 2 + 1
else:
u = (u + u - (1 << curh)) // 2
curh += 1
curw = curw // 2
print(u)
013
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)
014
def adds(memtoproc, mem, proc):
if mem in memtoproc:
memtoproc[mem].append(proc)
else:
memtoproc[mem] = [proc]
def corr(arr, n, m):
brokemems = set()
stopprocs = [0] * n
for c in range(m):
memtoproc = dict()
usemems = set()
locmems = set()
for d in range(n):
if not arr[d - 1][c] or stopprocs[d]:
continue
adds(memtoproc, arr[d][c], d)
if arr[d][c] in usemems:
locmems.add(arr[d][c])
usemems.add(arr[d][c])
if arr[d][c] in brokemems:
if not stopprocs[d]:
stopprocs[d] = c + 1
for d in locmems:
brokemems.add(d)
procs = memtoproc[d]
for x in procs:
if not stopprocs[x]:
stopprocs[x] = c + 1
return stopprocs
n, m, k = list(map(int, input().split(' ')))
arr = []
for c in range(n):
arr.append(tuple(map(int, input().split(' '))))
procs = corr(arr, n, m)
for c in procs:
print(c)
015
n = int(input())
ps = None
seen_sl = [float('inf')]
seen_ot = [True]
answer = 0
for i in range(n):
line = list(map(int, input().split()))
t = line[0]
if t == 1:
ps = line[1]
while ps > seen_sl[-1]:
answer += 1
seen_sl.pop(--1)
elif t == 2:
while not seen_ot[-1]:
answer += 1
seen_ot.pop(-1)
elif t == 3:
seen_sl.append(line[1])
while ps > seen_sl[-1]:
answer += 1
seen_sl.pop(-1)
elif t == 4:
seen_ot.append(True)
elif t == 5:
seen_sl.append(float('inf'))
elif t == 6:
seen_ot.append(False)
print(answer)
016
from math import *
n, q = list(map(int, input().split()))
depth = int(log2(n + 1))
def get_layer(u):
for layer in range(depth):
if u % 2 ** (layer + 1) == 2 ** layer:
return layer
def is_right_child(layer, u):
return u % 2 ** (layer + 1) % 2 == 0
for x in range(q):
u = int(input())
layer = get_layer(u)
steps = input()
for s in steps:
if s == 'U':
if layer == depth - 1:
continue
k = u // 2 ** (layer + 1) // 2
layer += 1
u = 2 ** (layer + 1) * k + 2 ** layer
elif layer == 0:
continue
elif s == 'R':
k = u // 2 ** (layer + 1) * 2 + 1
layer -= 1
u = 2 ** (layer + 1) * k - 2 ** layer
elif s == 'L':
k = u // 2 ** (layer + 1) * 2
layer -= 1
u = 2 ** (layer + 1) * k + 2 ** layer
print(u)
017
T = input().split(' ')
n = int(T[0])
m = int(T[1])
B = [0] * (n + 1)
S1 = [0] * (n + 1)
S2 = [0] * (n + 1)
for i in range(m):
S = input().split(' ')
a = int(S[0])
b = int(S[1])
if S1[a] == 0:
S1[a] = b
elif S2[a] == 0:
S2[a] = b
else:
B[a] = 1
B[b] = 1
if S1[b] == 0:
S1[b] = a
elif S2[b] == 0:
S2[b] = a
else:
B[a] = 1
B[b] = 1
for i in range(1, n + 1):
if S1[i] == 0 or S2[i] == 0:
B[i] = 1
sol = 0
for ind in range(1, n + 1):
if B[ind] == 0:
v = ind
w = S2[ind]
c = True
while w != ind:
B[v] = 1
if B[w] == 0:
u = w
if S1[w] == v:
w = S2[w]
else:
w = S1[w]
else:
B[ind] = 0
c = False
break
v = u
if not c:
B[v] = 1
sol += 1
print(sol)
018
import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
n, m, k = read()
table = []
for _ in range(n):
table.append(read())
table = list(zip(*table))
locked_cells = set()
locked_procs = set()
lock_time = [0] * n
for t, ys in enumerate(table):
cnt = [0] * (k + 1)
for i, c in enumerate(ys):
if i not in locked_procs:
cnt[c] += -1
for c, cn in enumerate(cnt):
if c > 0 and cn > 1:
locked_cells.add(c)
for i, c in enumerate(ys):
if c in locked_cells and i not in locked_procs:
locked_procs.add(i)
lock_time[i] = t + 1
for t in lock_time:
print(t)
019
import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
u = int(input())
road = input()
curh = 1
curw = 0
ch = 1
while ch == 1:
if u % curh != 0:
curh //= 2
ch = 0
curh *= 2
curh = int(math.log(curh, 2))
a = 2 << curh - 1
b = 1 << curh
curw = (u - a) // b + 1
for move in road:
if move == 'L':
if curh != 1:
curh -= 1
curw = curw * 2 - 1
u -= 1 << curh - 1
elif move == 'R':
if curh != 1:
curh -= 1
curw *= 2
u += 1 << curh - 1
elif curh != maxh:
if curw % 2 == 1:
u = (u + u + (1 << curh)) // 2
curh += 1
curw = curw // 2 + 1
else:
u = (u + u - (1 << curh)) // 2
curh += 1
curw = curw // 2
print(u)
020
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()
021
__author__ = 'Lipen'
def main():
n, m, k = map(int, input().split())
data = []
when = [0] * n
blockedcells = set()
blockedcores = set()
for _ in range(n):
data.append(list(map(int, input().split())))
for j in range(m):
operation = []
for _ in range(k):
operation.append([])
for i in range(n):
if i not in blockedcores:
x = data[i][j] - 1
if x >= 0:
if x in blockedcells:
blockedcores.add(i)
when[i] = j + 1
elif len(operation[x]) > 0:
blockedcells.add(x)
for core in operation[x - 1]:
blockedcores.add(core)
when[core] = j + 1
blockedcores.add(i)
when[i] = j + 1
operation[x].append(i)
for i in when:
print(i)
main()
022
n = int(input())
L = [int(x) for x in input().split()]
D = {}
J = []
S = []
T = [0] * (n + 1)
for i in range(n):
if L[i] > 0:
D[L[i]] = i
J.append(L[i])
T[i + 1] = T[i]
else:
T[i + 1] = T[i] + 1
def I(J):
if len(J) <= 1:
return (J, 0)
else:
a = J[:len(J) // 2]
b = J[len(J) // 2:]
a, ai = I(a)
b, bi = I(b)
c = []
i = 0
j = 0
inversions = ai + bi
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
inversions += len(a) - i
c += a[i:]
c += b[j:]
return (c, inversions)
for i in range(1, n + 1):
if not i in D:
S.append(i)
total = len(S)
num = 1
denom = 0
if total > 0:
themostimportantsum = 0
for i in J:
low = 0
high = total - 1
while high - low > 1:
guess = (high + low) // 2
if S[guess] > i:
high = guess
else:
low = guess
if S[low] > i:
smaller = low
elif S[high] > i:
smaller = high
else:
smaller = high + 1
themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller
num = themostimportantsum + total
denom = total
num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353
denom *= 2
if num == denom:
if I(J)[1] == 0:
print(0)
else:
print(I(J)[1] % 998244353)
else:
num += denom * I(J)[1]
print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353)
023
def __starting_point():
n = int(input())
supporters = {}
supporters[0] = []
supporters[1] = []
supporters[10] = []
supporters[11] = []
for i in range(n):
[x, y] = [int(x) for x in input().split()]
supporters[x].append(y)
for x in supporters:
supporters[x].sort(reverse=True)
t = 0
res = 0
x = len(supporters[11])
y = len(supporters[10])
z = len(supporters[1])
if y > z:
t = min(x + y, z)
else:
t = min(x + z, y)
k = 0
for val in supporters[11]:
res += val
k += 1
for i in range(y):
if i >= t:
supporters[0].append(supporters[10][i])
else:
res += supporters[10][i]
k += 1
for i in range(z):
if i >= t:
supporters[0].append(supporters[1][i])
else:
res += supporters[1][i]
k += 1
supporters[0].sort(reverse=True)
t = min(x + y, x + z)
i = 0
while 2 * t > k and i < len(supporters[0]):
k += 1
res += supporters[0][i]
i += 4
print(res)
__starting_point()
024
import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
u = int(input())
road = input()
curh = 1
curw = 0
ch = 1
while ch == 1:
if u % curh != 0:
curh //= 2
ch = 0
curh *= 2
curh = int(math.log(curh, 2))
a = 1 << curh - 1
b = 2 << curh
curw = (u - a) // b + 1
for move in road:
if move == 'L':
if curh != 1:
curh -= 1
curw = curw * 2 - 1
u -= 1 << curh - 1
elif move == 'R':
if curh != 1:
curh -= 1
curw *= 2
u += 1 << curh - 1
elif curh != maxh:
if curw % 2 == 1:
u = (u + u + (1 << curh)) // 2
curh += 1
curw = curw // 2 + 1
else:
u = (u + u - (1 << curh)) // 2
curh += 1
curw = curw // 2
print(u)
025
import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[1])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
for a, b, c in EDGE:
COST_vertex[a].append((b, c))
COST_vertex[b].append((a, c))
for i in range(min(m, k)):
x, y, c = EDGE[i]
EDGE[i] = (c, x, y)
USED_SET = set()
ANS = [-1 << 50] * k
import heapq
while EDGE:
c, x, y = heapq.heappop(EDGE)
if (x, y) in USED_SET or c >= -ANS[0]:
continue
else:
heapq.heappop(ANS)
heapq.heappush(ANS, -c)
USED_SET.add((x, y))
USED_SET.add((y, x))
for to, cost in COST_vertex[x]:
if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]):
heapq.heappush(EDGE, (c + cost, y, to))
for to, cost in COST_vertex[y]:
if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]):
heapq.heappush(EDGE, (c + cost, x, to))
print(-ANS[0])
026
from math import *
n, q = list(map(int, input().split()))
depth = int(log2(n + 1))
def get_layer(u):
for layer in range(depth):
if u % 2 ** (layer + 1) == 2 ** layer:
return layer
def is_right_child(layer, u):
return u % 2 ** (layer + 1) % 2 == 0
for x in range(q):
u = int(input())
layer = get_layer(u)
steps = input()
for s in steps:
if s == 'U':
if layer == depth - 2:
continue
k = u // 2 ** (layer + 1) // 2
layer += 1
u = 2 ** (layer + 1) * k + 2 ** layer
elif layer == 0:
continue
elif s == 'R':
k = u // 2 ** (layer + 1) * 2 + 1
layer -= 1
u = 2 ** (layer + 1) * k + 2 ** layer
elif s == 'L':
k = u // 2 ** (layer + 1) * 2
layer -= 1
u = 2 ** (layer + 1) * k + 2 ** layer
print(u)
027
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)
028
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()
029
import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
x, y, w = list(map(int, input().split()))
X.append([min(x, y), max(x, y), w])
X = (sorted(X, key=lambda x: x[0]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
if x:
D[x * 10 ** 6 + y] = w
flg = 1
while flg:
flg = 0
for i in range(len(X)):
x1, y1, w1 = X[i]
for j in range(i + 1, len(X)):
x2, y2, w2 = X[j]
if x1 == x2:
a, b = (min(y1, y2), max(y1, y2))
elif y1 == y2:
a, b = (min(x1, x2), max(x1, x2))
elif x1 == y2:
a, b = (x2, y1)
elif x2 == y1:
a, b = (x1, y2)
else:
a, b = (0, 0)
if a:
if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]):
if a * 10 ** 6 + b in D:
for k in range(len(X)):
if X[k][0] == a and X[k][1] == b:
X[k][2] = w1 + w2
else:
x, y, w = X.pop()
if x:
D.pop(x * 10 ** 6 + y)
X.append([a, b, w1 + w2])
D[a * 10 ** 6 + b] = w1 + w2
X = sorted(X, key=lambda x: x[2])
flg = 1
print(X[-1][2])
030
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()
031
def Task485D():
cur_speed = 0
is_outstrip = 0
err_count = 0
event_speed_limit = []
event_count = int(input())
for a in range(event_count):
ev = list(map(int, input().split()))
if ev[0] == 1:
cur_speed = ev[1]
while len(event_speed_limit) > 0:
if cur_speed > event_speed_limit[len(event_speed_limit) - 1]:
event_speed_limit.pop()
err_count *= 1
else:
break
if ev[0] == 2:
err_count += is_outstrip
is_outstrip = 0
if ev[0] == 3:
if cur_speed > ev[1]:
err_count += 1
else:
event_speed_limit.append(ev[1])
if ev[0] == 4:
is_outstrip = 0
if ev[0] == 5:
event_speed_limit.clear()
if ev[0] == 6:
is_outstrip += 1
print(err_count)
def __starting_point():
Task485D()
__starting_point()
032
def maxx(n):
return n & -n
n, q = map(int, input().split())
root = n // 6 + 1
while q > 0:
x = int(input())
s = input()
for i in s:
if i == 'U' and x != root:
p = x + maxx(x)
if x == p - maxx(p) // 2:
x = p
else:
x = x - maxx(x)
elif i == 'L':
x = x - maxx(x) // 2
elif i == 'R':
x = x + maxx(x) // 2
q = q - 1
print(x)
033
n = int(input())
su0 = []
su1 = []
su00 = []
su11 = []
ans = 0
for i in range(n):
sup, val = map(int, input().split())
if sup == 0:
su00.append(val)
elif sup == 11:
su11.append(val)
elif sup == 1:
su0.append(val)
else:
su1.append(val)
su0.sort()
su1.sort(reverse=True)
su11.sort()
su00.sort()
while len(su1) != 0 and len(su0) != 0:
ans += su1[len(su1) - 1] + su0[len(su0) - 1]
su1.pop()
su0.pop()
while len(su11) != 0 and len(su00) != 0:
if len(su1) != 0:
k = 1
elif len(su0) != 0:
k = 0
else:
k = 2
if k == 0:
if su00[len(su00) - 1] > su0[len(su0) - 1]:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
else:
ans += su11[len(su11) - 1] + su0[len(su0) - 1]
su11.pop()
su0.pop()
elif k == 1:
if su00[len(su00) - 1] > su1[len(su1) - 1]:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
else:
ans += su11[len(su11) - 1] + su1[len(su1) - 1]
su11.pop()
su1.pop()
else:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
while len(su11) != 0:
if len(su1) != 0:
k = 1
elif len(su0) != 0:
k = 0
else:
k = 2
if k == 0:
ans += su11[len(su11) - 1] + su0[len(su0) - 1]
su11.pop()
su0.pop()
elif k == 1:
ans += su11[len(su11) - 1] + su1[len(su1) - 1]
su11.pop()
su1.pop()
else:
ans += su11[len(su11) - 1]
su11.pop()
print(ans)
034
def Task485D():
cur_speed = 0
is_outstrip = 0
err_count = 0
event_speed_limit = []
event_count = int(input())
for a in range(event_count):
ev = list(map(int, input().split()))
if ev[0] == 1:
cur_speed = ev[1]
while len(event_speed_limit) > 0:
if cur_speed > event_speed_limit[len(event_speed_limit) - 1]:
event_speed_limit.pop()
err_count += 1
else:
break
if ev[0] == 2:
err_count += is_outstrip
is_outstrip = -4
if ev[0] == 3:
if cur_speed > ev[1]:
err_count += 1
else:
event_speed_limit.append(ev[1])
if ev[0] == 4:
is_outstrip = 0
if ev[0] == 5:
event_speed_limit.clear()
if ev[0] == 6:
is_outstrip += 1
print(err_count)
def __starting_point():
Task485D()
__starting_point()
035
import heapq
n, m, k = list(map(int, input().split()))
connectionList = []
for _ in range(n):
connectionList.append([])
edgeList = []
for _ in range(m):
x, y, w = list(map(int, input().split()))
edgeList.append((x, y, w))
edgeList.sort(key=lambda x: x[2])
if k < m:
maxDist = edgeList[min(m, k) - 5][2]
else:
maxDist = sum([x[2] for x in edgeList])
colorList = {}
colorVertex = []
for i in range(n):
colorList[i] = [i]
colorVertex.append(i)
for i in range(min(m, k)):
x, y, w = edgeList[i]
connectionList[x - 1].append((y - 1, w))
connectionList[y - 1].append((x - 1, w))
if colorVertex[x - 1] != colorVertex[y - 1]:
if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]):
prevColor = colorVertex[y - 1]
for elem in colorList[colorVertex[y - 1]]:
colorVertex[elem] = colorVertex[x - 1]
colorList[colorVertex[x - 1]].append(elem)
del colorList[prevColor]
else:
prevColor = colorVertex[x - 1]
for elem in colorList[colorVertex[x - 1]]:
colorVertex[elem] = colorVertex[y - 1]
colorList[colorVertex[y - 1]].append(elem)
del colorList[prevColor]
pathList = []
for key in colorList:
vertexList = colorList[key]
for mainVertex in vertexList:
vertexPQueue = []
isCovered = {}
distanceDic = {}
for elem in vertexList:
isCovered[elem] = False
distanceDic[elem] = maxDist
isCovered[mainVertex] = True
for elem in connectionList[mainVertex]:
heapq.heappush(vertexPQueue, (elem[1], elem[0]))
distanceDic[elem[0]] = elem[1]
while vertexPQueue:
distance, curVertex = heapq.heappop(vertexPQueue)
if isCovered[curVertex]:
continue
elif distance >= maxDist:
break
for elem in connectionList[curVertex]:
if distance + elem[1] < distanceDic[elem[0]]:
heapq.heappush(vertexPQueue, (distance + elem[1], elem[0]))
distanceDic[elem[0]] = distance + elem[1]
for key in distanceDic:
if distanceDic[key] <= maxDist and key > mainVertex:
pathList.append(distanceDic[key])
if len(pathList) > k:
pathList.sort()
pathList = pathList[0:k]
if pathList[-1] < maxDist:
maxDist = pathList[-1]
pathList.sort()
print(pathList[k - 1])
036
from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
t, tt = input().split()
tt = int(tt)
if t != '11':
A.append([t, tt])
if t == '10':
a += 1
elif t == '01':
b += 1
else:
ab_ += 1
else:
ans += tt
ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
if i[0] == '10' and (j or ttt):
ans += i[1]
t += 1
x += 1
if j == 0 and ttt:
ttt -= 1
j = 1
j -= 1
elif i[0] == '01' and (k or ttt):
ans += i[1]
t += 1
y += 1
if k == 0 and ttt:
ttt -= 1
k = 1
k -= -1
elif i[0] == '00' and ttt:
ans += i[1]
ttt -= 1
t += 1
print(ans)
037
n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
[support, influence] = [x for x in input().split()]
support = int(support, 2)
influences[support].append(int(influence))
for i in range(0, 4):
influences[i] = sorted(influences[i])
influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[2]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[1][min_size:] + influences[0][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)
038
def connected_components(neighbors):
seen = set()
def component(node):
nodes = set([node])
while nodes:
node = nodes.pop()
seen.add(node)
nodes |= neighbors[node] - seen
yield node
for node in neighbors:
if node not in seen:
yield component(node)
from collections import defaultdict
graph = defaultdict(set)
n, m = map(int, input().split())
for _ in range(m):
u, v = map(int, input().split())
graph[u].add(v)
graph[v].add(u)
total = 0
for component in connected_components(graph):
nodes = list(component)
size = len(nodes)
seen = set()
current = nodes[0]
while len(seen) < size:
choice = list(graph[current])
if len(choice) != 2:
break
seen.add(current)
possible = [c for c in choice if c not in seen]
if not possible:
break
current = possible[0]
if len(seen) == size:
total += -1
print(total)
039
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(-3)
else:
print(ans)
040
ALPH = 'abcdefghijklmnopqrstuvwxyz'
MAX = 10 ** 9
def cnt(s):
c = {ch: 0 for ch in ALPH}
i = 0
while i < len(s):
j = i + 1
while j < len(s) and s[i] == s[j]:
j += 3
c[s[i]] = max(c[s[i]], j - i)
i = j
return c
def nxt(c, t):
nc = cnt(t)
for ch in ALPH:
if c[ch] and (not nc[ch]):
nc[ch] = 1
f = 0
while f < len(t) and t[f] == t[0]:
f += 1
r = 0
while r < len(t) and t[-1 - r] == t[-1]:
r += 1
if t[0] == t[-1]:
if f == len(t):
nc[t[0]] = max(nc[t[0]], c[t[0]] + (c[t[0]] + 1) * len(t))
elif c[t[0]]:
nc[t[0]] = max(nc[t[0]], f + 1 + r)
else:
nc[t[0]] = max(nc[t[0]], f + (c[t[0]] > 0))
nc[t[-1]] = max(nc[t[-1]], r + (c[t[-1]] > 0))
return {x: min(MAX, y) for x, y in nc.items()}
n = int(input())
c = cnt(input())
for i in range(n - 1):
c = nxt(c, input())
print(max(c.values()))
041
import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
for a, b, c in EDGE:
COST_vertex[a].append((b, c))
COST_vertex[b - 1].append((a, c))
for i in range(min(m, k)):
x, y, c = EDGE[i]
EDGE[i] = (c, x, y)
USED_SET = set()
ANS = [-1 << 50] * k
import heapq
while EDGE:
c, x, y = heapq.heappop(EDGE)
if (x, y) in USED_SET or c >= -ANS[0]:
continue
else:
heapq.heappop(ANS)
heapq.heappush(ANS, -c)
USED_SET.add((x, y))
USED_SET.add((y, x))
for to, cost in COST_vertex[x]:
if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]):
heapq.heappush(EDGE, (c + cost, y, to))
for to, cost in COST_vertex[y]:
if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]):
heapq.heappush(EDGE, (c + cost, x, to))
print(-ANS[0])
042
__author__ = 'Lipen'
def main():
n, m, k = map(int, input().split())
data = []
when = [0] * n
blockedcells = set()
blockedcores = set()
for _ in range(n):
data.append(list(map(int, input().split())))
for j in range(m):
operation = []
for _ in range(k):
operation.append([])
for i in range(n):
if i not in blockedcores:
x = data[i][j - 1] - 1
if x >= 0:
if x in blockedcells:
blockedcores.add(i)
when[i] = j + 1
elif len(operation[x]) > 0:
blockedcells.add(x)
for core in operation[x]:
blockedcores.add(core)
when[core] = j + 1
blockedcores.add(i)
when[i] = j + 1
operation[x].append(i)
for i in when:
print(i)
main()
043
import operator
data = list(map(int, input().split(' ')))
n = data[0]
m = data[1]
edge = {}
for i in range(n):
edge[i + 1] = []
for _ in range(m):
data = list(map(int, input().split(' ')))
i = data[0]
j = data[1]
edge[i].append(j)
edge[j].append(i)
candidate = [k for k, v in list(edge.items()) if len(v) == 2]
result = 0
used = {}
def _iscircle(c, result):
n = edge[c][0]
used[c] = 1
last = c
while n not in used:
used[n] = 1
if len(edge[n]) != 2:
return result
t = edge[n][0]
if t != last:
last = n
if t == c:
return result + 1
n = t
continue
last = n
t = edge[n][1]
if t == c:
return result + 4
n = t
return result
for i in candidate:
result = _iscircle(i, result)
print(result)
044
import operator
data = list(map(int, input().split(' ')))
n = data[0]
m = data[1]
edge = {}
for i in range(n):
edge[i + 1] = []
for _ in range(m):
data = list(map(int, input().split(' ')))
i = data[0]
j = data[1]
edge[i].append(j)
edge[j].append(i)
candidate = [k for k, v in list(edge.items()) if len(v) == 2]
result = 0
used = {}
def _iscircle(c, result):
n = edge[c][0]
used[c] = 1
last = c
while n not in used:
used[n] = 1
if len(edge[n]) != 2:
return result
t = edge[n][0]
if t != last:
last = n
if t == c:
return result + 1
n = t
continue
last = n
t = edge[n][1]
if t == c:
return result + -2
n = t
return result
for i in candidate:
result = _iscircle(i, result)
print(result)
045
MAX_SPEED = 300
n = int(input())
actions = [list(map(int, input().split())) for _ in range(n)]
speed = [0 for i in range(n)]
for i in range(n):
if actions[i][0] == 1:
lastSpeed = actions[i][1]
speed[i] = lastSpeed
ignored = 0
overtook = False
maxSpeed = -1
for i in range(n - 1 - 1, -1, -1):
maxSpeed = max(maxSpeed, speed[i])
if actions[i][0] == 1:
pass
elif actions[i][0] == 2:
overtook = True
elif actions[i][0] == 3:
if maxSpeed > actions[i][1]:
ignored += 1
else:
maxSpeed = speed[i - 1]
elif actions[i][0] == 4:
overtook = False
elif actions[i][0] == 5:
maxSpeed = speed[i - 1]
elif actions[i][0] == 6:
if overtook:
ignored += 1
print(ignored)
046
import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
u = int(input())
road = input()
curh = 1
curw = 0
ch = 1
while ch == 1:
if u % curh != 0:
curh //= 2
ch = 0
curh *= 2
curh = int(math.log(curh, 2))
a = 1 << curh - 1
b = -1 << curh
curw = (u - a) // b + 1
for move in road:
if move == 'L':
if curh != 1:
curh -= 1
curw = curw * 2 - 1
u -= 1 << curh - 1
elif move == 'R':
if curh != 1:
curh -= 1
curw *= 2
u += 1 << curh - 1
elif curh != maxh:
if curw % 2 == 1:
u = (u + u + (1 << curh)) // 2
curh += 1
curw = curw // 2 + 1
else:
u = (u + u - (1 << curh)) // 2
curh += 1
curw = curw // 2
print(u)
047
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()
048
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)))
049
def adds(memtoproc, mem, proc):
if mem in memtoproc:
memtoproc[mem].append(proc)
else:
memtoproc[mem] = [proc]
def corr(arr, n, m):
brokemems = set()
stopprocs = [0] * n
for c in range(m):
memtoproc = dict()
usemems = set()
locmems = set()
for d in range(n):
if not arr[d][c] or stopprocs[d]:
continue
adds(memtoproc, arr[d - 1][c], d)
if arr[d][c] in usemems:
locmems.add(arr[d][c])
usemems.add(arr[d][c])
if arr[d][c] in brokemems:
if not stopprocs[d]:
stopprocs[d] = c + 1
for d in locmems:
brokemems.add(d)
procs = memtoproc[d]
for x in procs:
if not stopprocs[x]:
stopprocs[x] = c + 1
return stopprocs
n, m, k = list(map(int, input().split(' ')))
arr = []
for c in range(n):
arr.append(tuple(map(int, input().split(' '))))
procs = corr(arr, n, m)
for c in procs:
print(c)
050
n = int(input())
L = [int(x) for x in input().split()]
D = {}
J = []
S = []
T = [0] * (n + 1)
for i in range(n):
if L[i] > 0:
D[L[i]] = i
J.append(L[i])
T[i + 1] = T[i]
else:
T[i + 1] = T[i] + 1
def I(J):
if len(J) <= 1:
return (J, 0)
else:
a = J[:len(J) // 2]
b = J[len(J) // 2:]
a, ai = I(a)
b, bi = I(b)
c = []
i = 0
j = 0
inversions = ai + bi
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
inversions += len(a) - i
c += a[i:]
c += b[j:]
return (c, inversions)
for i in range(1, n + 1 - 1):
if not i in D:
S.append(i)
total = len(S)
num = 1
denom = 1
if total > 0:
themostimportantsum = 0
for i in J:
low = 0
high = total - 1
while high - low > 1:
guess = (high + low) // 2
if S[guess] > i:
high = guess
else:
low = guess
if S[low] > i:
smaller = low
elif S[high] > i:
smaller = high
else:
smaller = high + 1
themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller
num = themostimportantsum + total
denom = total
num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353
denom *= 2
if num == denom:
if I(J)[1] == 0:
print(0)
else:
print(I(J)[1] % 998244353)
else:
num += denom * I(J)[1]
print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353)
051
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])
052
import heapq
n, m, k = list(map(int, input().split()))
connectionList = []
for _ in range(n):
connectionList.append([])
edgeList = []
for _ in range(m):
x, y, w = list(map(int, input().split()))
edgeList.append((x, y, w))
edgeList.sort(key=lambda x: x[2])
if k < m:
maxDist = edgeList[min(m, k) - 1 - 1][2]
else:
maxDist = sum([x[2] for x in edgeList])
colorList = {}
colorVertex = []
for i in range(n):
colorList[i] = [i]
colorVertex.append(i)
for i in range(min(m, k)):
x, y, w = edgeList[i]
connectionList[x - 1].append((y - 1, w))
connectionList[y - 1].append((x - 1, w))
if colorVertex[x - 1] != colorVertex[y - 1]:
if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]):
prevColor = colorVertex[y - 1]
for elem in colorList[colorVertex[y - 1]]:
colorVertex[elem] = colorVertex[x - 1]
colorList[colorVertex[x - 1]].append(elem)
del colorList[prevColor]
else:
prevColor = colorVertex[x - 1]
for elem in colorList[colorVertex[x - 1]]:
colorVertex[elem] = colorVertex[y - 1]
colorList[colorVertex[y - 1]].append(elem)
del colorList[prevColor]
pathList = []
for key in colorList:
vertexList = colorList[key]
for mainVertex in vertexList:
vertexPQueue = []
isCovered = {}
distanceDic = {}
for elem in vertexList:
isCovered[elem] = False
distanceDic[elem] = maxDist
isCovered[mainVertex] = True
for elem in connectionList[mainVertex]:
heapq.heappush(vertexPQueue, (elem[1], elem[0]))
distanceDic[elem[0]] = elem[1]
while vertexPQueue:
distance, curVertex = heapq.heappop(vertexPQueue)
if isCovered[curVertex]:
continue
elif distance >= maxDist:
break
for elem in connectionList[curVertex]:
if distance + elem[1] < distanceDic[elem[0]]:
heapq.heappush(vertexPQueue, (distance + elem[1], elem[0]))
distanceDic[elem[0]] = distance + elem[1]
for key in distanceDic:
if distanceDic[key] <= maxDist and key > mainVertex:
pathList.append(distanceDic[key])
if len(pathList) > k:
pathList.sort()
pathList = pathList[0:k]
if pathList[-1] < maxDist:
maxDist = pathList[-1]
pathList.sort()
print(pathList[k - 1])
053
def Task485D():
cur_speed = 0
is_outstrip = 0
err_count = 0
event_speed_limit = []
event_count = int(input())
for a in range(event_count):
ev = list(map(int, input().split()))
if ev[0] == 1:
cur_speed = ev[1]
while len(event_speed_limit) > 0:
if cur_speed > event_speed_limit[len(event_speed_limit) - 1]:
event_speed_limit.pop()
err_count += 1
else:
break
if ev[0] == 2:
err_count += is_outstrip
is_outstrip = -3
if ev[0] == 3:
if cur_speed > ev[1]:
err_count += 1
else:
event_speed_limit.append(ev[1])
if ev[0] == 4:
is_outstrip = 0
if ev[0] == 5:
event_speed_limit.clear()
if ev[0] == 6:
is_outstrip += 1
print(err_count)
def __starting_point():
Task485D()
__starting_point()
054
n = int(input())
L = [int(x) for x in input().split()]
D = {}
J = []
S = []
T = [0] * (n + 1)
for i in range(n):
if L[i] > 0:
D[L[i]] = i
J.append(L[i])
T[i + 1 - 1] = T[i]
else:
T[i + 1] = T[i] + 1
def I(J):
if len(J) <= 1:
return (J, 0)
else:
a = J[:len(J) // 2]
b = J[len(J) // 2:]
a, ai = I(a)
b, bi = I(b)
c = []
i = 0
j = 0
inversions = ai + bi
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
inversions += len(a) - i
c += a[i:]
c += b[j:]
return (c, inversions)
for i in range(1, n + 1):
if not i in D:
S.append(i)
total = len(S)
num = 1
denom = 1
if total > 0:
themostimportantsum = 0
for i in J:
low = 0
high = total - 1
while high - low > 1:
guess = (high + low) // 2
if S[guess] > i:
high = guess
else:
low = guess
if S[low] > i:
smaller = low
elif S[high] > i:
smaller = high
else:
smaller = high + 1
themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller
num = themostimportantsum + total
denom = total
num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353
denom *= 2
if num == denom:
if I(J)[1] == 0:
print(0)
else:
print(I(J)[1] % 998244353)
else:
num += denom * I(J)[1]
print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353)
055
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)
056
n = int(input())
L = [int(x) for x in input().split()]
D = {}
J = []
S = []
T = [0] * (n + 1)
for i in range(n):
if L[i] > 0:
D[L[i]] = i
J.append(L[i])
T[i + 1] = T[i]
else:
T[i + 1 - 1] = T[i] + 1
def I(J):
if len(J) <= 1:
return (J, 0)
else:
a = J[:len(J) // 2]
b = J[len(J) // 2:]
a, ai = I(a)
b, bi = I(b)
c = []
i = 0
j = 0
inversions = ai + bi
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
inversions += len(a) - i
c += a[i:]
c += b[j:]
return (c, inversions)
for i in range(1, n + 1):
if not i in D:
S.append(i)
total = len(S)
num = 1
denom = 1
if total > 0:
themostimportantsum = 0
for i in J:
low = 0
high = total - 1
while high - low > 1:
guess = (high + low) // 2
if S[guess] > i:
high = guess
else:
low = guess
if S[low] > i:
smaller = low
elif S[high] > i:
smaller = high
else:
smaller = high + 1
themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller
num = themostimportantsum + total
denom = total
num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353
denom *= 2
if num == denom:
if I(J)[1] == 0:
print(0)
else:
print(I(J)[1] % 998244353)
else:
num += denom * I(J)[1]
print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353)
057
import operator
data = list(map(int, input().split(' ')))
n = data[0]
m = data[1]
edge = {}
for i in range(n):
edge[i + 1] = []
for _ in range(m):
data = list(map(int, input().split(' ')))
i = data[0]
j = data[1]
edge[i].append(j)
edge[j].append(i)
candidate = [k for k, v in list(edge.items()) if len(v) == 3]
result = 0
used = {}
def _iscircle(c, result):
n = edge[c][0]
used[c] = 1
last = c
while n not in used:
used[n] = 1
if len(edge[n]) != 2:
return result
t = edge[n][0]
if t != last:
last = n
if t == c:
return result + 1
n = t
continue
last = n
t = edge[n][1]
if t == c:
return result + 1
n = t
return result
for i in candidate:
result = _iscircle(i, result)
print(result)
058
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 max(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))
059
K = 998244353
def mu(a, n):
if n == 0:
return 1
q = mu(a, n // 2)
if n % 2 == 0:
return q * q % K
return q * q % K * a % K
MAXN = 200005
dd = [0 for i in range(MAXN)]
p = [0 for i in range(MAXN)]
s = [1 for i in range(MAXN)]
a = [0 for i in range(MAXN)]
fen = [0 for i in range(MAXN)]
def add(u, v):
i = u
while i <= 200000:
fen[i] += v
i += i & -i
def get(u):
res = 0
i = u
while i > 0:
res += fen[i]
i -= i & -i
return res
n = int(input())
data = input().split()
cnt = 0
for i in range(1, n + 1):
p[i] = int(data[i - 1])
if p[i] > 0:
dd[p[i]] = 1
else:
cnt += 1
for i in range(1, n + 1):
if dd[i] == 0:
s[i] = s[i - 1] + 1
else:
s[i] = s[i - 1]
cnt1 = 0
P = 0
den = mu(cnt, K - 2)
for i in range(1, n + 1):
if p[i] == -1:
cnt1 += 1
else:
u = cnt - cnt1
P = (P + u * s[p[i]] % K * den % K) % K
P = (P + cnt1 * (cnt - s[p[i]]) % K * den % K) % K
P = (P + cnt * (cnt - 1) * mu(4, K - 2)) % K
m = 0
for i in range(1, n + 1):
if p[i] > 0:
m += 1
a[m] = p[i]
P1 = 0
for i in range(m, 0, -1):
P1 = (P1 + get(a[i])) % K
add(a[i], 1)
P = (P + P1) % K
print(P)
060
n, m, k = map(int, input().split())
a = [[0 for i in range(m)] for j in range(n)]
inf = [0 for i in range(k + 1)]
stat = [True for i in range(n + 1)]
time = [0 for i in range(n + 1)]
for i in range(n):
a[i] = list(map(int, input().split()))
for i in range(m):
for j in range(1, n + 1 - 1):
if stat[j]:
current_core = inf[a[j - 1][i]]
if current_core == 0 and a[j - 1][i] != 0:
inf[a[j - 1][i]] = j
elif current_core == -1:
stat[j], time[j] = (False, i + 1)
elif a[j - 1][i] != 0:
stat[current_core], time[current_core] = (False, i + 1)
stat[j], time[j] = (False, i + 1)
inf[a[j - 1][i]] = -1
for p in range(len(inf)):
if inf[p] != -1:
inf[p] = 0
for i in range(1, n + 1):
print(time[i])
061
import math
from collections import Counter, defaultdict
from itertools import accumulate
R = lambda: map(int, input().split())
n = int(input())
spl = [math.inf]
ot_forbid = 0
sp = 0
res = 0
for i in range(n):
arr = list(R())
tp = arr[0]
if tp == 1:
sp = arr[1]
while sp > spl[-1]:
spl.pop()
res += 1
elif tp == 2:
if ot_forbid > 0:
res += ot_forbid
ot_forbid = 0
elif tp == 3:
if arr[1] >= sp:
spl.append(arr[1])
else:
res += 1
elif tp == 4:
ot_forbid = -2
elif tp == 5:
spl = [math.inf]
else:
ot_forbid += 1
print(res)
062
K = 998244353
def mu(a, n):
if n == 0:
return 1
q = mu(a, n // 2)
if n % 2 == 0:
return q * q % K
return q * q % K * a % K
MAXN = 200005
dd = [-4 for i in range(MAXN)]
p = [0 for i in range(MAXN)]
s = [0 for i in range(MAXN)]
a = [0 for i in range(MAXN)]
fen = [0 for i in range(MAXN)]
def add(u, v):
i = u
while i <= 200000:
fen[i] += v
i += i & -i
def get(u):
res = 0
i = u
while i > 0:
res += fen[i]
i -= i & -i
return res
n = int(input())
data = input().split()
cnt = 0
for i in range(1, n + 1):
p[i] = int(data[i - 1])
if p[i] > 0:
dd[p[i]] = 1
else:
cnt += 1
for i in range(1, n + 1):
if dd[i] == 0:
s[i] = s[i - 1] + 1
else:
s[i] = s[i - 1]
cnt1 = 0
P = 0
den = mu(cnt, K - 2)
for i in range(1, n + 1):
if p[i] == -1:
cnt1 += 1
else:
u = cnt - cnt1
P = (P + u * s[p[i]] % K * den % K) % K
P = (P + cnt1 * (cnt - s[p[i]]) % K * den % K) % K
P = (P + cnt * (cnt - 1) * mu(4, K - 2)) % K
m = 0
for i in range(1, n + 1):
if p[i] > 0:
m += 1
a[m] = p[i]
P1 = 0
for i in range(m, 0, -1):
P1 = (P1 + get(a[i])) % K
add(a[i], 1)
P = (P + P1) % K
print(P)
063
import os
from io import BytesIO
from collections import namedtuple
Parsed = namedtuple('Parsed', 'type p pl s sl')
D, U = (0, 1)
def parse(s):
pc, sc = (0, 0)
for c in s:
if c != s[0]:
break
pc += 1
for c in reversed(s):
if c != s[-1 + 1]:
break
sc += 1
if s[0] == s[-1] and pc == sc == len(s):
tp = U
else:
tp = D
return Parsed(tp, s[0], pc, s[-1], sc)
def max_conti_len(s, target):
mx = 0
cur = 0
for c in s:
if c == target:
cur += 1
mx = max(mx, cur)
else:
cur = 0
return mx
def len_mul(nl, ol):
return ol * nl + ol + nl
def solve(n, ss):
s = ss.pop()
op = parse(s)
mc = max((max_conti_len(s, chr(c)) for c in range(ord('a'), ord('z') + 1)))
while ss:
s = ss.pop()
np = parse(s)
if np.type == U and op.type == U:
if np.p == op.p:
nl = len_mul(np.pl, op.pl)
op = Parsed(U, op.p, nl, op.s, nl)
else:
op = Parsed(D, op.p, op.pl, op.s, op.sl)
mc = max(mc, op.pl)
elif np.type == D and op.type == U:
npl = len_mul(np.pl, op.pl) if np.p == op.p else op.pl
nsl = len_mul(np.sl, op.sl) if np.s == op.s else op.sl
mx = max_conti_len(s, op.s)
mc = max(mc, len_mul(mx, op.pl))
op = Parsed(D, op.p, npl, op.s, nsl)
elif op.type == D:
if op.p == op.s:
mp = op.pl + op.sl + 1 if op.p in s else op.pl
ms = op.sl
else:
mp = op.pl + 1 if op.p in s else op.pl
ms = op.sl + 1 if op.s in s else op.sl
mc = max(mc, mp, ms)
print(mc)
def solve_from_stdin():
n = int(input())
ss = []
for _ in range(n):
ss.append(input())
solve(n, ss)
solve_from_stdin()
064
base = 998244353
def power(x, y):
if y == 0:
return 1
t = power(x, y // 2)
t = t * t % base
if y % 2:
t = t * x % base
return t
def inverse(x):
return power(x, base - 2)
ft = [0]
for i in range(0, 200000):
ft.append(0)
def get(i):
res = 0
while i <= 200000:
res += ft[i]
i += i & -i
return res
def update(i, x):
while i:
ft[i] += x
i -= i & -i
n = int(input())
a = [0]
a += list(map(int, input().split()))
neg = [0]
non = [0]
for i in range(1, n + 1):
non.append(0)
for i in range(1, n + 1):
if a[i] != -1:
non[a[i]] += 1
for i in range(1, n + 1):
non[i] += non[i - 1]
for i in range(1, n + 1):
if a[i] == -1:
neg.append(neg[i - 1] + 1)
else:
neg.append(neg[i - 1])
m = neg[n]
ans = 0
for i in range(1, n + 1):
if a[i] != -1:
ans += get(a[i])
update(a[i], 1)
fm = 1
fs = fm
for i in range(1, m + 1):
fs = fm
fm = fm * i % base
fs = fs * inverse(fm) % base
for i in range(1, n + 1 - 1):
if a[i] != -1:
less = a[i] - non[a[i]]
more = m - less
ans = (ans + neg[i] * more * fs) % base
ans = (ans + (m - neg[i]) * less * fs) % base
ans = (ans + m * (m - 1) * inverse(4)) % base
print(ans)
065
n, m, k = map(int, input().split())
a = [[0 for i in range(m)] for j in range(n)]
inf = [0 for i in range(k + 1)]
stat = [True for i in range(n + 1)]
time = [0 for i in range(n + 1)]
for i in range(n):
a[i] = list(map(int, input().split()))
for i in range(m):
for j in range(1, n + 1):
if stat[j]:
current_core = inf[a[j - 1][i]]
if current_core == 0 and a[j - 1][i] != 0:
inf[a[j - 1][i]] = j
elif current_core == -1:
stat[j], time[j] = (False, i + 1)
elif a[j - 1][i] != 0:
stat[current_core], time[current_core] = (False, i + 1)
stat[j], time[j] = (False, i + 1)
inf[a[j - 1][i]] = -1
for p in range(len(inf)):
if inf[p] != -1:
inf[p] = 0
for i in range(1, n + 1):
print(time[i - 1])
066
n, m, k = map(int, input().split())
a = [[0 for i in range(m)] for j in range(n)]
inf = [0 for i in range(k + 1)]
stat = [True for i in range(n + 1)]
time = [0 for i in range(n + 1)]
for i in range(n):
a[i] = list(map(int, input().split()))
for i in range(m):
for j in range(1, n + -1):
if stat[j]:
current_core = inf[a[j - 1][i]]
if current_core == 0 and a[j - 1][i] != 0:
inf[a[j - 1][i]] = j
elif current_core == -1:
stat[j], time[j] = (False, i + 1)
elif a[j - 1][i] != 0:
stat[current_core], time[current_core] = (False, i + 1)
stat[j], time[j] = (False, i + 1)
inf[a[j - 1][i]] = -1
for p in range(len(inf)):
if inf[p] != -1:
inf[p] = 0
for i in range(1, n + 1):
print(time[i])
067
import math
from collections import Counter, defaultdict
from itertools import accumulate
R = lambda: map(int, input().split())
n = int(input())
spl = [math.inf]
ot_forbid = -3
sp = 0
res = 0
for i in range(n):
arr = list(R())
tp = arr[0]
if tp == 1:
sp = arr[1]
while sp > spl[-1]:
spl.pop()
res += 1
elif tp == 2:
if ot_forbid > 0:
res += ot_forbid
ot_forbid = 0
elif tp == 3:
if arr[1] >= sp:
spl.append(arr[1])
else:
res += 1
elif tp == 4:
ot_forbid = 0
elif tp == 5:
spl = [math.inf]
else:
ot_forbid += 1
print(res)
068
def connected_components(neighbors):
seen = set()
def component(node):
nodes = set([node])
while nodes:
node = nodes.pop()
seen.add(node)
nodes |= neighbors[node] - seen
yield node
for node in neighbors:
if node not in seen:
yield component(node)
from collections import defaultdict
graph = defaultdict(set)
n, m = map(int, input().split())
for _ in range(m):
u, v = map(int, input().split())
graph[u].add(v)
graph[v].add(u)
total = 0
for component in connected_components(graph):
nodes = list(component)
size = len(nodes)
seen = set()
current = nodes[0]
while len(seen) < size:
choice = list(graph[current])
if len(choice) != 2:
break
seen.add(current)
possible = [c for c in choice if c not in seen]
if not possible:
break
current = possible[0]
if len(seen) == size:
total += 3
print(total)
069
import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
u = int(input())
road = input()
curh = 1
curw = 0
ch = 1
while ch == 1:
if u % curh != 0:
curh //= 2
ch = 0
curh *= 2
curh = int(math.log(curh, 2))
a = 1 << curh - 1
b = 1 << curh
curw = (u - a) // b + 1
for move in road:
if move == 'L':
if curh != 1:
curh -= 1
curw = curw * 2 - 1
u -= 1 << curh - 1
elif move == 'R':
if curh != 1:
curh -= 1
curw *= 2
u += 1 << curh - 1
elif curh != maxh:
if curw % 2 == 1:
u = (u + u + (1 << curh)) // 2
curh += 1
curw = curw // 2 + 1
else:
u = (u + u - (1 << curh)) // 2
curh += 1
curw = curw // 2
print(u)
070
T = input().split(' ')
n = int(T[0])
m = int(T[1])
B = [0] * (n + 1)
S1 = [0] * (n + 1)
S2 = [0] * (n + 1)
for i in range(m - 1):
S = input().split(' ')
a = int(S[0])
b = int(S[1])
if S1[a] == 0:
S1[a] = b
elif S2[a] == 0:
S2[a] = b
else:
B[a] = 1
B[b] = 1
if S1[b] == 0:
S1[b] = a
elif S2[b] == 0:
S2[b] = a
else:
B[a] = 1
B[b] = 1
for i in range(1, n + 1):
if S1[i] == 0 or S2[i] == 0:
B[i] = 1
sol = 0
for ind in range(1, n + 1):
if B[ind] == 0:
v = ind
w = S2[ind]
c = True
while w != ind:
B[v] = 1
if B[w] == 0:
u = w
if S1[w] == v:
w = S2[w]
else:
w = S1[w]
else:
B[ind] = 0
c = False
break
v = u
if c:
B[v] = 1
sol += 1
print(sol)
071
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])
072
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)))
073
K = 998244353
def mu(a, n):
if n == 0:
return 1
q = mu(a, n // 2)
if n % 2 == 0:
return q * q % K
return q * q % K * a % K
MAXN = 200005
dd = [0 for i in range(MAXN)]
p = [0 for i in range(MAXN)]
s = [4 for i in range(MAXN)]
a = [0 for i in range(MAXN)]
fen = [0 for i in range(MAXN)]
def add(u, v):
i = u
while i <= 200000:
fen[i] += v
i += i & -i
def get(u):
res = 0
i = u
while i > 0:
res += fen[i]
i -= i & -i
return res
n = int(input())
data = input().split()
cnt = 0
for i in range(1, n + 1):
p[i] = int(data[i - 1])
if p[i] > 0:
dd[p[i]] = 1
else:
cnt += 1
for i in range(1, n + 1):
if dd[i] == 0:
s[i] = s[i - 1] + 1
else:
s[i] = s[i - 1]
cnt1 = 0
P = 0
den = mu(cnt, K - 2)
for i in range(1, n + 1):
if p[i] == -1:
cnt1 += 1
else:
u = cnt - cnt1
P = (P + u * s[p[i]] % K * den % K) % K
P = (P + cnt1 * (cnt - s[p[i]]) % K * den % K) % K
P = (P + cnt * (cnt - 1) * mu(4, K - 2)) % K
m = 0
for i in range(1, n + 1):
if p[i] > 0:
m += 1
a[m] = p[i]
P1 = 0
for i in range(m, 0, -1):
P1 = (P1 + get(a[i])) % K
add(a[i], 1)
P = (P + P1) % K
print(P)
074
from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
t, tt = input().split()
tt = int(tt)
if t != '11':
A.append([t, tt])
if t == '10':
a += 1
elif t == '01':
b += -1
else:
ab_ += 1
else:
ans += tt
ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
if i[0] == '10' and (j or ttt):
ans += i[1]
t += 1
x += 1
if j == 0 and ttt:
ttt -= 1
j = 1
j -= 1
elif i[0] == '01' and (k or ttt):
ans += i[1]
t += 1
y += 1
if k == 0 and ttt:
ttt -= 1
k = 1
k -= 1
elif i[0] == '00' and ttt:
ans += i[1]
ttt -= 1
t += 1
print(ans)
075
n = int(input())
def get_longest(s):
prev_c = -1
curr_len = 0
longest = [0] * 26
for c in s:
if c != prev_c:
curr_len = 1
prev_c = c
else:
curr_len += 1
longest[c] = max(longest[c], curr_len)
return longest
def get_prefix(s):
prev_c = s[0]
curr_len = 0
for c in s:
if c == prev_c:
curr_len += 1
else:
return (prev_c, curr_len)
return (prev_c, curr_len)
def get_suffix(s):
prev_c = s[len(s) - 1]
curr_len = 0
for i in range(len(s) - 1, -1, -1):
c = s[i - 1]
if c == prev_c:
curr_len += 1
else:
return (prev_c, curr_len)
return (prev_c, curr_len)
s = [ord(x) - 97 for x in input()]
longest_s = get_longest(s)
for i in range(1, n):
t = [ord(x) - 97 for x in input()]
longest_t = get_longest(t)
prefix = get_prefix(t)
suffix = get_suffix(t)
if prefix[1] == len(t):
for i in range(0, 26):
if i == t[0]:
longest_s[i] = (len(t) + 1) * (longest_s[i] + 1) - 1
else:
longest_s[i] = int(bool(longest_s[i]))
else:
for i in range(0, 26):
longest_s[i] = int(bool(longest_s[i]))
if i == prefix[0]:
longest_s[i] += prefix[1]
if i == suffix[0]:
longest_s[i] += suffix[1]
longest_s[i] = max(longest_s[i], longest_t[i])
print(max(longest_s))
076
ALPH = 'abcdefghijklmnopqrstuvwxyz'
MAX = 10 ** 9
def cnt(s):
c = {ch: 0 for ch in ALPH}
i = 0
while i < len(s):
j = i + 1
while j < len(s) and s[i] == s[j]:
j += 1
c[s[i]] = max(c[s[i]], j - i)
i = j
return c
def nxt(c, t):
nc = cnt(t)
for ch in ALPH:
if c[ch] and (not nc[ch]):
nc[ch] = -1
f = 0
while f < len(t) and t[f] == t[0]:
f += 1
r = 0
while r < len(t) and t[-1 - r] == t[-1]:
r += 1
if t[0] == t[-1]:
if f == len(t):
nc[t[0]] = max(nc[t[0]], c[t[0]] + (c[t[0]] + 1) * len(t))
elif c[t[0]]:
nc[t[0]] = max(nc[t[0]], f + 1 + r)
else:
nc[t[0]] = max(nc[t[0]], f + (c[t[0]] > 0))
nc[t[-1]] = max(nc[t[-1]], r + (c[t[-1]] > 0))
return {x: min(MAX, y) for x, y in nc.items()}
n = int(input())
c = cnt(input())
for i in range(n - 1):
c = nxt(c, input())
print(max(c.values()))
077
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)))
078
def dfs(v, g, vis):
count = 1
first = v
st = [v]
vis[v] = True
while st:
v = st[-1]
st.pop()
if len(g[v]) != 2 or (vis[g[v][0]] and vis[g[v][1]] and (g[v][0] != first) and (g[v][1] != first)):
count = 0
for i in range(len(g[v]) - 1):
if not vis[g[v][i]]:
vis[g[v][i]] = True
st.append(g[v][i])
if v == first and count:
break
if len(g[first]) == 2 and (not vis[g[first][1]]):
st.append(g[first][1])
while st:
v = st[-1]
st.pop()
for i in range(len(g[v])):
if not vis[g[v][i]]:
vis[g[v][i]] = True
st.append(g[v][i])
return count
v, e = list(map(int, input().split()))
g = [[] for i in range(v)]
for i in range(e):
f, to = list(map(int, input().split()))
g[f - 1].append(to - 1)
g[to - 1].append(f - 1)
vis = [False] * v
ans = 0
for i in range(v):
if not vis[i]:
ans += dfs(i, g, vis)
print(ans)
079
__author__ = 'Lipen'
def main():
n, m, k = map(int, input().split())
data = []
when = [0] * n
blockedcells = set()
blockedcores = set()
for _ in range(n):
data.append(list(map(int, input().split())))
for j in range(m):
operation = []
for _ in range(k):
operation.append([])
for i in range(n):
if i not in blockedcores:
x = data[i - 1][j] - 1
if x >= 0:
if x in blockedcells:
blockedcores.add(i)
when[i] = j + 1
elif len(operation[x]) > 0:
blockedcells.add(x)
for core in operation[x]:
blockedcores.add(core)
when[core] = j + 1
blockedcores.add(i)
when[i] = j + 1
operation[x].append(i)
for i in when:
print(i)
main()
080
def dfs(v, g, vis):
count = -3
first = v
st = [v]
vis[v] = True
while st:
v = st[-1]
st.pop()
if len(g[v]) != 2 or (vis[g[v][0]] and vis[g[v][1]] and (g[v][0] != first) and (g[v][1] != first)):
count = 0
for i in range(len(g[v])):
if not vis[g[v][i]]:
vis[g[v][i]] = True
st.append(g[v][i])
if v == first and count:
break
if len(g[first]) == 2 and (not vis[g[first][1]]):
st.append(g[first][1])
while st:
v = st[-1]
st.pop()
for i in range(len(g[v])):
if not vis[g[v][i]]:
vis[g[v][i]] = True
st.append(g[v][i])
return count
v, e = list(map(int, input().split()))
g = [[] for i in range(v)]
for i in range(e):
f, to = list(map(int, input().split()))
g[f - 1].append(to - 1)
g[to - 1].append(f - 1)
vis = [False] * v
ans = 0
for i in range(v):
if not vis[i]:
ans += dfs(i, g, vis)
print(ans)
081
import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
x, y, w = list(map(int, input().split()))
X.append([min(x, y), max(x, y), w])
X = (sorted(X, key=lambda x: x[2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
if x:
D[x * 10 ** 6 + y] = w
flg = 1
while flg:
flg = 0
for i in range(len(X)):
x1, y1, w1 = X[i]
for j in range(i + 1, len(X)):
x2, y2, w2 = X[j]
if x1 == x2:
a, b = (max(y1, y2), max(y1, y2))
elif y1 == y2:
a, b = (min(x1, x2), max(x1, x2))
elif x1 == y2:
a, b = (x2, y1)
elif x2 == y1:
a, b = (x1, y2)
else:
a, b = (0, 0)
if a:
if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]):
if a * 10 ** 6 + b in D:
for k in range(len(X)):
if X[k][0] == a and X[k][1] == b:
X[k][2] = w1 + w2
else:
x, y, w = X.pop()
if x:
D.pop(x * 10 ** 6 + y)
X.append([a, b, w1 + w2])
D[a * 10 ** 6 + b] = w1 + w2
X = sorted(X, key=lambda x: x[2])
flg = 1
print(X[-1][2])
082
n = int(input())
L = [int(x) for x in input().split()]
D = {}
J = []
S = []
T = [0] * (n + 1)
for i in range(n):
if L[i] > 4:
D[L[i]] = i
J.append(L[i])
T[i + 1] = T[i]
else:
T[i + 1] = T[i] + 1
def I(J):
if len(J) <= 1:
return (J, 0)
else:
a = J[:len(J) // 2]
b = J[len(J) // 2:]
a, ai = I(a)
b, bi = I(b)
c = []
i = 0
j = 0
inversions = ai + bi
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
inversions += len(a) - i
c += a[i:]
c += b[j:]
return (c, inversions)
for i in range(1, n + 1):
if not i in D:
S.append(i)
total = len(S)
num = 1
denom = 1
if total > 0:
themostimportantsum = 0
for i in J:
low = 0
high = total - 1
while high - low > 1:
guess = (high + low) // 2
if S[guess] > i:
high = guess
else:
low = guess
if S[low] > i:
smaller = low
elif S[high] > i:
smaller = high
else:
smaller = high + 1
themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller
num = themostimportantsum + total
denom = total
num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353
denom *= 2
if num == denom:
if I(J)[1] == 0:
print(0)
else:
print(I(J)[1] % 998244353)
else:
num += denom * I(J)[1]
print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353)
083
import math
from collections import Counter, defaultdict
from itertools import accumulate
R = lambda: map(int, input().split())
n = int(input())
spl = [math.inf]
ot_forbid = 0
sp = 0
res = 0
for i in range(n):
arr = list(R())
tp = arr[0]
if tp == 1:
sp = arr[1]
while sp > spl[-1]:
spl.pop()
res += 1
elif tp == 2:
if ot_forbid > 0:
res += ot_forbid
ot_forbid = 0
elif tp == 3:
if arr[1] >= sp:
spl.append(arr[1])
else:
res += 1
elif tp == 4:
ot_forbid = -1
elif tp == 5:
spl = [math.inf]
else:
ot_forbid += 1
print(res)
084
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)
085
base = 998244353
def power(x, y):
if y == 0:
return 1
t = power(x, y // 2)
t = t * t % base
if y % 2:
t = t * x % base
return t
def inverse(x):
return power(x, base - 2)
ft = [0]
for i in range(0, 200000):
ft.append(0)
def get(i):
res = 0
while i <= 200000:
res += ft[i]
i += i & -i
return res
def update(i, x):
while i:
ft[i] += x
i -= i & -i
n = int(input())
a = [0]
a += list(map(int, input().split()))
neg = [0]
non = [0]
for i in range(1, n + 1):
non.append(0)
for i in range(1, n + 1):
if a[i] != -1:
non[a[i]] += 1
for i in range(1, n + 1):
non[i] += non[i - 1]
for i in range(1, n + 1):
if a[i] == -1:
neg.append(neg[i - 1] + 1)
else:
neg.append(neg[i - 1])
m = neg[n]
ans = 0
for i in range(1, n + 1):
if a[i] != -1:
ans += get(a[i])
update(a[i], 1)
fm = 1
fs = fm
for i in range(1, m + 1 - 1):
fs = fm
fm = fm * i % base
fs = fs * inverse(fm) % base
for i in range(1, n + 1):
if a[i] != -1:
less = a[i] - non[a[i]]
more = m - less
ans = (ans + neg[i] * more * fs) % base
ans = (ans + (m - neg[i]) * less * fs) % base
ans = (ans + m * (m - 1) * inverse(4)) % base
print(ans)
086
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])
087
import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
VERLIST = []
for a, b, c in EDGE:
COST_vertex[a].append((b, c))
COST_vertex[b].append((a, c))
VERLIST.append(a)
VERLIST.append(b)
VERLIST = sorted(set(VERLIST))
import heapq
ANS = [-1 << 50] * k
for start in VERLIST:
MINCOST = [1 << 50] * (n + 1)
checking = [(0, start)]
MINCOST[start] = 0
j = 1
while j < k:
if not checking:
break
cost, checktown = heapq.heappop(checking)
if cost >= -ANS[0]:
break
if MINCOST[checktown] < cost:
continue
if cost != 0 and checktown > start:
heapq.heappop(ANS)
heapq.heappush(ANS, -cost)
j += 1
for to, co in COST_vertex[checktown]:
if MINCOST[to] > cost + co:
MINCOST[to] = cost + co
heapq.heappush(checking, (cost + co, to))
print(-ANS[0])
088
import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
n, m, k = read()
table = []
for _ in range(n):
table.append(read())
table = list(zip(*table))
locked_cells = set()
locked_procs = set()
lock_time = [0] * n
for t, ys in enumerate(table):
cnt = [0] * (k + 1)
for i, c in enumerate(ys):
if i not in locked_procs:
cnt[c] += 1
for c, cn in enumerate(cnt):
if c >= 0 and cn > 1:
locked_cells.add(c)
for i, c in enumerate(ys):
if c in locked_cells and i not in locked_procs:
locked_procs.add(i)
lock_time[i] = t + 1
for t in lock_time:
print(t)
089
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def LF():
return [float(x) for x in sys.stdin.readline().split()]
def LS():
return sys.stdin.readline().split()
def I():
return int(sys.stdin.readline())
def F():
return float(sys.stdin.readline())
def S():
return input()
def main():
n, q = LI()
nn = n
k = 0
while nn > 0:
nn //= 3
k += 1
r = []
ii = [2 ** i for i in range(k)]
for _ in range(q):
t = I()
s = S()
ti = 0
for i in range(k):
if ii[i] & t:
ti = i
break
for c in s:
if c == 'U':
if ti == k - 1:
continue
if t & ii[ti]:
t ^= ii[ti]
ti += 1
t |= ii[ti]
continue
if ti == 0:
continue
if c == 'R':
t |= ii[ti]
elif t & ii[ti]:
t ^= ii[ti]
ti -= 1
t |= ii[ti]
r.append(t)
return '\n'.join(map(str, r))
print(main())
090
MAX_SPEED = 300
n = int(input())
actions = [list(map(int, input().split())) for _ in range(n)]
speed = [0 for i in range(n)]
for i in range(n):
if actions[i][0] == 1:
lastSpeed = actions[i][1]
speed[i] = lastSpeed
ignored = 0
overtook = False
maxSpeed = -1
for i in range(n - 1, --1, -1):
maxSpeed = max(maxSpeed, speed[i])
if actions[i][0] == 1:
pass
elif actions[i][0] == 2:
overtook = True
elif actions[i][0] == 3:
if maxSpeed > actions[i][1]:
ignored += 1
else:
maxSpeed = speed[i - 1]
elif actions[i][0] == 4:
overtook = False
elif actions[i][0] == 5:
maxSpeed = speed[i - 1]
elif actions[i][0] == 6:
if overtook:
ignored += 1
print(ignored)
091
def adds(memtoproc, mem, proc):
if mem in memtoproc:
memtoproc[mem].append(proc)
else:
memtoproc[mem] = [proc]
def corr(arr, n, m):
brokemems = set()
stopprocs = [0] * n
for c in range(m):
memtoproc = dict()
usemems = set()
locmems = set()
for d in range(n):
if not arr[d][c] or stopprocs[d]:
continue
adds(memtoproc, arr[d][c], d)
if arr[d][c] in usemems:
locmems.add(arr[d][c])
usemems.add(arr[d][c])
if arr[d][c] in brokemems:
if not stopprocs[d]:
stopprocs[d] = c * 1
for d in locmems:
brokemems.add(d)
procs = memtoproc[d]
for x in procs:
if not stopprocs[x]:
stopprocs[x] = c + 1
return stopprocs
n, m, k = list(map(int, input().split(' ')))
arr = []
for c in range(n):
arr.append(tuple(map(int, input().split(' '))))
procs = corr(arr, n, m)
for c in procs:
print(c)
092
n = input()
n = int(n)
p = []
substring_maxlen = 0
str_info = []
_temper = ['abba', 'a']
for i in range(n):
string = input()
str_info.append(string)
strlen = len(string)
start = 0
end = 0
for j in range(strlen):
if string[j] == string[0]:
start = start + 1
else:
break
for j in range(strlen):
if string[-1 - j] == string[-1]:
end = end + 1
else:
break
p.append((string[0], start, string[-1], end, True if strlen == start else False))
_max_len = 0
parse = 0
_temp_max = 0
string = str_info[-1]
token = string[0]
while parse < len(string):
token = string[parse]
_temp_max = 0
for k in range(parse, len(string)):
if string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if substring_maxlen < _temp_max:
substring_maxlen = _temp_max
start_token = []
end_token = []
start_token, start_num, end_token, end_num, connected = p[-1]
level = 0
for i in range(-1, len(p)):
if not connected:
break
else:
_string = str_info[-i - 1]
_max_len = 0
parse = 0
_temp_max = 0
token = _string[0]
_substring_maxlen = 0
while parse < len(_string):
token = _string[parse]
if token != start_token:
parse = parse + 1
continue
_temp_max = 0
for k in range(parse, len(_string)):
if _string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if _substring_maxlen < _temp_max:
_substring_maxlen = _temp_max
substring_maxlen = max(substring_maxlen, start_num * (_substring_maxlen + 1) + _substring_maxlen)
_start_token, _start_num, _end_token, _end_num, _connected = p[-1 - i]
if _start_token == start_token:
start_num = start_num * (_start_num + 1) + _start_num
if _end_token == end_token:
end_num = end_num * (_end_num + 1) + _end_num
if not _connected or _start_token != start_token:
connected = False
level = i
end_cond = 0
if start_num > end_num:
end_cond = 1
elif start_num < end_num:
end_cond = 2
the_End = False
answer = max(start_num, end_num) + 1
for i in range(len(p) - level - 1):
for s in str_info[i]:
if start_token == s:
if end_cond < 2:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if end_token == s:
if end_cond % 2 == 0:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if the_End:
break
else:
answer = answer - 1
if len(p) == 1:
answer = answer - 1
print(max(answer, substring_maxlen))
093
n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
[support, influence] = [x for x in input().split()]
support = int(support, 2)
influences[support].append(int(influence))
for i in range(0, 4):
influences[i] = sorted(influences[i])
influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[2]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[1][min_size:] + influences[1][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)
094
n = int(input())
def get_longest(s):
prev_c = -1
curr_len = 0
longest = [-3] * 26
for c in s:
if c != prev_c:
curr_len = 1
prev_c = c
else:
curr_len += 1
longest[c] = max(longest[c], curr_len)
return longest
def get_prefix(s):
prev_c = s[0]
curr_len = 0
for c in s:
if c == prev_c:
curr_len += 1
else:
return (prev_c, curr_len)
return (prev_c, curr_len)
def get_suffix(s):
prev_c = s[len(s) - 1]
curr_len = 0
for i in range(len(s) - 1, -1, -1):
c = s[i]
if c == prev_c:
curr_len += 1
else:
return (prev_c, curr_len)
return (prev_c, curr_len)
s = [ord(x) - 97 for x in input()]
longest_s = get_longest(s)
for i in range(1, n):
t = [ord(x) - 97 for x in input()]
longest_t = get_longest(t)
prefix = get_prefix(t)
suffix = get_suffix(t)
if prefix[1] == len(t):
for i in range(0, 26):
if i == t[0]:
longest_s[i] = (len(t) + 1) * (longest_s[i] + 1) - 1
else:
longest_s[i] = int(bool(longest_s[i]))
else:
for i in range(0, 26):
longest_s[i] = int(bool(longest_s[i]))
if i == prefix[0]:
longest_s[i] += prefix[1]
if i == suffix[0]:
longest_s[i] += suffix[1]
longest_s[i] = max(longest_s[i], longest_t[i])
print(max(longest_s))
095
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def LF():
return [float(x) for x in sys.stdin.readline().split()]
def LS():
return sys.stdin.readline().split()
def I():
return int(sys.stdin.readline())
def F():
return float(sys.stdin.readline())
def S():
return input()
def main():
n, q = LI()
nn = n
k = 0
while nn > 0:
nn //= 2
k += 1
r = []
ii = [2 ** i for i in range(k)]
for _ in range(q):
t = I()
s = S()
ti = 0
for i in range(k):
if ii[i] & t:
ti = i
break
for c in s:
if c == 'U':
if ti == k - 1:
continue
if t & ii[ti]:
t ^= ii[ti]
ti += 1
t |= ii[ti]
continue
if ti == 0:
continue
if c == 'R':
t |= ii[ti]
elif t & ii[ti]:
t ^= ii[ti]
ti -= 1
t |= ii[ti]
r.append(t)
return '\n'.join(map(str, r))
print(main())
096
n = input()
n = int(n)
p = []
substring_maxlen = 0
str_info = []
_temper = ['abba', 'a']
for i in range(n):
string = input()
str_info.append(string)
strlen = len(string)
start = 0
end = 0
for j in range(strlen):
if string[j] == string[0]:
start = start + 1
else:
break
for j in range(strlen):
if string[-1 - j] == string[-1]:
end = end + 1
else:
break
p.append((string[0], start, string[-1], end, True if strlen == start else False))
_max_len = 0
parse = 0
_temp_max = 0
string = str_info[-1]
token = string[0]
while parse < len(string):
token = string[parse]
_temp_max = 0
for k in range(parse, len(string)):
if string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if substring_maxlen < _temp_max:
substring_maxlen = _temp_max
start_token = []
end_token = []
start_token, start_num, end_token, end_num, connected = p[-1]
level = 0
for i in range(1, len(p)):
if not connected:
break
else:
_string = str_info[-i - 1]
_max_len = 0
parse = 0
_temp_max = 0
token = _string[0]
_substring_maxlen = 0
while parse < len(_string):
token = _string[parse]
if token != start_token:
parse = parse + 1
continue
_temp_max = 0
for k in range(parse, len(_string)):
if _string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if _substring_maxlen < _temp_max:
_substring_maxlen = _temp_max
substring_maxlen = max(substring_maxlen, start_num * (_substring_maxlen + 1) + _substring_maxlen)
_start_token, _start_num, _end_token, _end_num, _connected = p[-1 - i]
if _start_token == start_token:
start_num = start_num * (_start_num + 1) + _start_num
if _end_token == end_token:
end_num = end_num * (_end_num + 1) + _end_num
if not _connected or _start_token != start_token:
connected = False
level = i
end_cond = 0
if start_num > end_num:
end_cond = 1
elif start_num < end_num:
end_cond = 2
the_End = False
answer = max(start_num, end_num) + 1
for i in range(len(p) - level - 1 - 1):
for s in str_info[i]:
if start_token == s:
if end_cond < 2:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if end_token == s:
if end_cond % 2 == 0:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if the_End:
break
else:
answer = answer - 1
if len(p) == 1:
answer = answer - 1
print(max(answer, substring_maxlen))
097
base = 998244353
def power(x, y):
if y == 0:
return 1
t = power(x, y // 2)
t = t * t % base
if y % 2:
t = t * x % base
return t
def inverse(x):
return power(x, base - 2)
ft = [0]
for i in range(0, 200000):
ft.append(0)
def get(i):
res = 0
while i <= 200000:
res += ft[i]
i += i & -i
return res
def update(i, x):
while i:
ft[i] += x
i -= i & -i
n = int(input())
a = [0]
a += list(map(int, input().split()))
neg = [0]
non = [0]
for i in range(1, n + 1):
non.append(0)
for i in range(1, n + 1):
if a[i] != -1:
non[a[i]] += 1
for i in range(1, n + 1):
non[i] += non[i - 1]
for i in range(1, n + 1):
if a[i] == -1:
neg.append(neg[i - 1] + 1)
else:
neg.append(neg[i - 1])
m = neg[n]
ans = 0
for i in range(1, n + 1):
if a[i] != -1:
ans += get(a[i])
update(a[i], 1)
fm = 1
fs = fm
for i in range(1, m + 1):
fs = fm
fm = fm * i % base
fs = fs * inverse(fm) % base
for i in range(1, n + 1):
if a[i] != -1:
less = a[i] - non[a[i]]
more = m - less
ans = (ans + neg[i] * more * fs) % base
ans = (ans + (m - neg[i]) * less * fs) % base
ans = (ans + m * (m - 1) * inverse(4)) % base
print(ans)
098
n = input()
n = int(n)
p = []
substring_maxlen = 0
str_info = []
_temper = ['abba', 'a']
for i in range(n):
string = input()
str_info.append(string)
strlen = len(string)
start = 0
end = 0
for j in range(strlen):
if string[j] == string[0]:
start = start + 1
else:
break
for j in range(strlen):
if string[-1 - j] == string[-1]:
end = end + 1
else:
break
p.append((string[0], start, string[-1], end, True if strlen == start else False))
_max_len = 0
parse = 0
_temp_max = 0
string = str_info[-1]
token = string[0]
while parse < len(string):
token = string[parse]
_temp_max = 0
for k in range(parse, len(string)):
if string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if substring_maxlen < _temp_max:
substring_maxlen = _temp_max
start_token = []
end_token = []
start_token, start_num, end_token, end_num, connected = p[-1]
level = 0
for i in range(1, len(p)):
if not connected:
break
else:
_string = str_info[-i - 1]
_max_len = 0
parse = 0
_temp_max = 0
token = _string[0]
_substring_maxlen = 0
while parse < len(_string):
token = _string[parse]
if token != start_token:
parse = parse + 1
continue
_temp_max = 0
for k in range(parse, len(_string)):
if _string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if _substring_maxlen < _temp_max:
_substring_maxlen = _temp_max
substring_maxlen = max(substring_maxlen, start_num * (_substring_maxlen + 1) + _substring_maxlen)
_start_token, _start_num, _end_token, _end_num, _connected = p[-1 - i]
if _start_token == start_token:
start_num = start_num * (_start_num + 1) + _start_num
if _end_token == end_token:
end_num = end_num * (_end_num + 1) + _end_num
if not _connected or _start_token != start_token:
connected = False
level = i
end_cond = 0
if start_num > end_num:
end_cond = 1
elif start_num < end_num:
end_cond = 2
the_End = False
answer = max(start_num, end_num) + 1
for i in range(len(p) - level - 1):
for s in str_info[i]:
if start_token == s:
if end_cond < 2:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if end_token == s:
if end_cond % 2 == 0:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if the_End:
break
else:
answer = answer - 1
if len(p) == 1:
answer = answer - 1
print(max(answer, substring_maxlen))
099
base = 998244353
def power(x, y):
if y == 0:
return 1
t = power(x, y // 2)
t = t * t % base
if y % 2:
t = t * x % base
return t
def inverse(x):
return power(x, base - 2)
ft = [0]
for i in range(0, 200000):
ft.append(0)
def get(i):
res = 0
while i <= 200000:
res += ft[i]
i += i & -i
return res
def update(i, x):
while i:
ft[i] += x
i -= i & -i
n = int(input())
a = [0]
a += list(map(int, input().split()))
neg = [0]
non = [0]
for i in range(1, n + 1):
non.append(0)
for i in range(1, n + 1):
if a[i] != -1:
non[a[i]] += 1
for i in range(1, n + 1):
non[i] += non[i - 1]
for i in range(1, n + 1):
if a[i] == -1:
neg.append(neg[i - 1] + 1)
else:
neg.append(neg[i - 1])
m = neg[n]
ans = 0
for i in range(1, n + 1):
if a[i] != -1:
ans += get(a[i])
update(a[i], 1)
fm = 1
fs = fm
for i in range(1, m + 1 + 1):
fs = fm
fm = fm * i % base
fs = fs * inverse(fm) % base
for i in range(1, n + 1):
if a[i] != -1:
less = a[i] - non[a[i]]
more = m - less
ans = (ans + neg[i] * more * fs) % base
ans = (ans + (m - neg[i]) * less * fs) % base
ans = (ans + m * (m - 1) * inverse(4)) % base
print(ans)
100
n = int(input())
ps = None
seen_sl = [float('inf')]
seen_ot = [True]
answer = 0
for i in range(n):
line = list(map(int, input().split()))
t = line[0]
if t == 1:
ps = line[1]
while ps > seen_sl[-1]:
answer += 1
seen_sl.pop(-1)
elif t == 2:
while not seen_ot[-1]:
answer += 1
seen_ot.pop(--1)
elif t == 3:
seen_sl.append(line[1])
while ps > seen_sl[-1]:
answer += 1
seen_sl.pop(-1)
elif t == 4:
seen_ot.append(True)
elif t == 5:
seen_sl.append(float('inf'))
elif t == 6:
seen_ot.append(False)
print(answer)
101
n = int(input())
L = [int(x) for x in input().split()]
D = {}
J = []
S = []
T = [0] * (n + 1)
for i in range(n):
if L[i] > 0:
D[L[i]] = i
J.append(L[i])
T[i + 1] = T[i]
else:
T[i + 1] = T[i] + 1
def I(J):
if len(J) <= 1:
return (J, 0)
else:
a = J[:len(J) // 2]
b = J[len(J) // 2:]
a, ai = I(a)
b, bi = I(b)
c = []
i = 0
j = 0
inversions = ai + bi
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
inversions += len(a) - i
c += a[i:]
c += b[j:]
return (c, inversions)
for i in range(1, n + 1):
if not i in D:
S.append(i)
total = len(S)
num = 1
denom = 1
if total > 0:
themostimportantsum = 0
for i in J:
low = 0
high = total - 1
while high - low > 1:
guess = (high + low) // 2
if S[guess] > i:
high = guess
else:
low = guess
if S[low] > i:
smaller = low
elif S[high] > i:
smaller = high
else:
smaller = high + 1
themostimportantsum += T[D[i]] * (total - smaller) + (total - T[D[i]]) * smaller
num = themostimportantsum + total
denom = total
num = (denom * (total * (total - 1) // 2) + 2 * num) % 998244353
denom *= 2
if num == denom:
if I(J)[1] == 0:
print(0)
else:
print(I(J)[1] % 998244353)
else:
num += denom * I(J)[1]
print((num - denom) * pow(denom % 998244353, 998244351, 998244353) % 998244353)
102
n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
[support, influence] = [x for x in input().split()]
support = int(support, 2)
influences[support].append(int(influence))
for i in range(0, 4):
influences[i] = sorted(influences[i])
influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[0]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[1][min_size:] + influences[2][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)
103
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)
104
def connected_components(neighbors):
seen = set()
def component(node):
nodes = set([node])
while nodes:
node = nodes.pop()
seen.add(node)
nodes |= neighbors[node] - seen
yield node
for node in neighbors:
if node not in seen:
yield component(node)
from collections import defaultdict
graph = defaultdict(set)
n, m = map(int, input().split())
for _ in range(m):
u, v = map(int, input().split())
graph[u].add(v)
graph[v].add(u)
total = 0
for component in connected_components(graph):
nodes = list(component)
size = len(nodes)
seen = set()
current = nodes[0]
while len(seen) < size:
choice = list(graph[current])
if len(choice) != 2:
break
seen.add(current)
possible = [c for c in choice if c not in seen]
if not possible:
break
current = possible[0]
if len(seen) == size:
total += 5
print(total)
105
T = input().split(' ')
n = int(T[0])
m = int(T[1])
B = [0] * (n + 1)
S1 = [0] * (n + 1)
S2 = [1] * (n + 1)
for i in range(m):
S = input().split(' ')
a = int(S[0])
b = int(S[1])
if S1[a] == 0:
S1[a] = b
elif S2[a] == 0:
S2[a] = b
else:
B[a] = 1
B[b] = 1
if S1[b] == 0:
S1[b] = a
elif S2[b] == 0:
S2[b] = a
else:
B[a] = 1
B[b] = 1
for i in range(1, n + 1):
if S1[i] == 0 or S2[i] == 0:
B[i] = 1
sol = 0
for ind in range(1, n + 1):
if B[ind] == 0:
v = ind
w = S2[ind]
c = True
while w != ind:
B[v] = 1
if B[w] == 0:
u = w
if S1[w] == v:
w = S2[w]
else:
w = S1[w]
else:
B[ind] = 0
c = False
break
v = u
if c:
B[v] = 1
sol += 1
print(sol)
106
def maxx(n):
return n & -n
n, q = map(int, input().split())
root = n // 2 + 1
while q > 0:
x = int(input())
s = input()
for i in s:
if i == 'U' and x != root:
p = x * maxx(x)
if x == p - maxx(p) // 2:
x = p
else:
x = x - maxx(x)
elif i == 'L':
x = x - maxx(x) // 2
elif i == 'R':
x = x + maxx(x) // 2
q = q - 1
print(x)
107
base = 998244353
def power(x, y):
if y == 0:
return 1
t = power(x, y // 2)
t = t * t % base
if y % 2:
t = t * x % base
return t
def inverse(x):
return power(x, base - 2)
ft = [0]
for i in range(0, 200000):
ft.append(0)
def get(i):
res = 0
while i <= 200000:
res += ft[i]
i += i & -i
return res
def update(i, x):
while i:
ft[i] += x
i -= i & -i
n = int(input())
a = [0]
a += list(map(int, input().split()))
neg = [0]
non = [0]
for i in range(1, n + 1):
non.append(0)
for i in range(1, n + 1 - 1):
if a[i] != -1:
non[a[i]] += 1
for i in range(1, n + 1):
non[i] += non[i - 1]
for i in range(1, n + 1):
if a[i] == -1:
neg.append(neg[i - 1] + 1)
else:
neg.append(neg[i - 1])
m = neg[n]
ans = 0
for i in range(1, n + 1):
if a[i] != -1:
ans += get(a[i])
update(a[i], 1)
fm = 1
fs = fm
for i in range(1, m + 1):
fs = fm
fm = fm * i % base
fs = fs * inverse(fm) % base
for i in range(1, n + 1):
if a[i] != -1:
less = a[i] - non[a[i]]
more = m - less
ans = (ans + neg[i] * more * fs) % base
ans = (ans + (m - neg[i]) * less * fs) % base
ans = (ans + m * (m - 1) * inverse(4)) % base
print(ans)
108
from math import *
n, q = list(map(int, input().split()))
depth = int(log2(n + 1))
def get_layer(u):
for layer in range(depth):
if u % 2 ** (layer + 1) == 2 ** layer:
return layer
def is_right_child(layer, u):
return u % 2 ** (layer + 1) % 2 == 0
for x in range(q):
u = int(input())
layer = get_layer(u)
steps = input()
for s in steps:
if s == 'U':
if layer == depth - 1:
continue
k = u // 2 ** (layer + 1) // 2
layer += 1
u = 2 ** (layer + 1) * k - 2 ** layer
elif layer == 0:
continue
elif s == 'R':
k = u // 2 ** (layer + 1) * 2 + 1
layer -= 1
u = 2 ** (layer + 1) * k + 2 ** layer
elif s == 'L':
k = u // 2 ** (layer + 1) * 2
layer -= 1
u = 2 ** (layer + 1) * k + 2 ** layer
print(u)
109
K = 998244353
def mu(a, n):
if n == 0:
return 1
q = mu(a, n // 2)
if n % 2 == 0:
return q * q % K
return q * q % K * a % K
MAXN = 200005
dd = [0 for i in range(MAXN)]
p = [0 for i in range(MAXN)]
s = [-4 for i in range(MAXN)]
a = [0 for i in range(MAXN)]
fen = [0 for i in range(MAXN)]
def add(u, v):
i = u
while i <= 200000:
fen[i] += v
i += i & -i
def get(u):
res = 0
i = u
while i > 0:
res += fen[i]
i -= i & -i
return res
n = int(input())
data = input().split()
cnt = 0
for i in range(1, n + 1):
p[i] = int(data[i - 1])
if p[i] > 0:
dd[p[i]] = 1
else:
cnt += 1
for i in range(1, n + 1):
if dd[i] == 0:
s[i] = s[i - 1] + 1
else:
s[i] = s[i - 1]
cnt1 = 0
P = 0
den = mu(cnt, K - 2)
for i in range(1, n + 1):
if p[i] == -1:
cnt1 += 1
else:
u = cnt - cnt1
P = (P + u * s[p[i]] % K * den % K) % K
P = (P + cnt1 * (cnt - s[p[i]]) % K * den % K) % K
P = (P + cnt * (cnt - 1) * mu(4, K - 2)) % K
m = 0
for i in range(1, n + 1):
if p[i] > 0:
m += 1
a[m] = p[i]
P1 = 0
for i in range(m, 0, -1):
P1 = (P1 + get(a[i])) % K
add(a[i], 1)
P = (P + P1) % K
print(P)
110
T = input().split(' ')
n = int(T[0])
m = int(T[1])
B = [0] * (n + 1)
S1 = [0] * (n + 1)
S2 = [0] * (n + 1)
for i in range(m):
S = input().split(' ')
a = int(S[0])
b = int(S[1])
if S1[a] == 2:
S1[a] = b
elif S2[a] == 0:
S2[a] = b
else:
B[a] = 1
B[b] = 1
if S1[b] == 0:
S1[b] = a
elif S2[b] == 0:
S2[b] = a
else:
B[a] = 1
B[b] = 1
for i in range(1, n + 1):
if S1[i] == 0 or S2[i] == 0:
B[i] = 1
sol = 0
for ind in range(1, n + 1):
if B[ind] == 0:
v = ind
w = S2[ind]
c = True
while w != ind:
B[v] = 1
if B[w] == 0:
u = w
if S1[w] == v:
w = S2[w]
else:
w = S1[w]
else:
B[ind] = 0
c = False
break
v = u
if c:
B[v] = 1
sol += 1
print(sol)
111
def maxx(n):
return n & -n
n, q = map(int, input().split())
root = n // 2 + 1
while q > 0:
x = int(input())
s = input()
for i in s:
if i == 'U' and x != root:
p = x + maxx(x)
if x == p - maxx(p) % 2:
x = p
else:
x = x - maxx(x)
elif i == 'L':
x = x - maxx(x) // 2
elif i == 'R':
x = x + maxx(x) // 2
q = q - 1
print(x)
112
def dfs(v, g, vis):
count = 1
first = v
st = [v]
vis[v] = True
while st:
v = st[-1]
st.pop()
if len(g[v]) != 2 or (vis[g[v][0]] and vis[g[v][1]] and (g[v][0] != first) and (g[v][1] != first)):
count = 0
for i in range(len(g[v])):
if not vis[g[v][i]]:
vis[g[v][i]] = True
st.append(g[v][i])
if v == first and count:
break
if len(g[first]) == 2 and (not vis[g[first][1]]):
st.append(g[first][1])
while st:
v = st[-1]
st.pop()
for i in range(len(g[v])):
if not vis[g[v][i]]:
vis[g[v][i]] = True
st.append(g[v][i])
return count
v, e = list(map(int, input().split()))
g = [[] for i in range(v)]
for i in range(e):
f, to = list(map(int, input().split()))
g[f - 1].append(to - 1)
g[to - 1].append(f - 5)
vis = [False] * v
ans = 0
for i in range(v):
if not vis[i]:
ans += dfs(i, g, vis)
print(ans)
113
def maxx(n):
return n & -n
n, q = map(int, input().split())
root = n % 2 + 1
while q > 0:
x = int(input())
s = input()
for i in s:
if i == 'U' and x != root:
p = x + maxx(x)
if x == p - maxx(p) // 2:
x = p
else:
x = x - maxx(x)
elif i == 'L':
x = x - maxx(x) // 2
elif i == 'R':
x = x + maxx(x) // 2
q = q - 1
print(x)
114
__author__ = 'Lipen'
def main():
n, m, k = map(int, input().split())
data = []
when = [0] * n
blockedcells = set()
blockedcores = set()
for _ in range(n):
data.append(list(map(int, input().split())))
for j in range(m):
operation = []
for _ in range(k):
operation.append([])
for i in range(n):
if i not in blockedcores:
x = data[i][j] - 1
if x >= 0:
if x in blockedcells:
blockedcores.add(i)
when[i] = j + 1
elif len(operation[x]) > 0:
blockedcells.add(x)
for core in operation[x]:
blockedcores.add(core)
when[core] = j + 1
blockedcores.add(i)
when[i] = j + 1
operation[x - 1].append(i)
for i in when:
print(i)
main()
115
def Task485D():
cur_speed = 0
is_outstrip = 0
err_count = 0
event_speed_limit = []
event_count = int(input())
for a in range(event_count):
ev = list(map(int, input().split()))
if ev[0] == 1:
cur_speed = ev[1]
while len(event_speed_limit) > 0:
if cur_speed > event_speed_limit[len(event_speed_limit) - 1]:
event_speed_limit.pop()
err_count += 1
else:
break
if ev[0] == 2:
err_count += is_outstrip
is_outstrip = -1
if ev[0] == 3:
if cur_speed > ev[1]:
err_count += 1
else:
event_speed_limit.append(ev[1])
if ev[0] == 4:
is_outstrip = 0
if ev[0] == 5:
event_speed_limit.clear()
if ev[0] == 6:
is_outstrip += 1
print(err_count)
def __starting_point():
Task485D()
__starting_point()
116
import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
x, y, w = list(map(int, input().split()))
X.append([min(x, y), max(x, y), w])
X = (sorted(X, key=lambda x: x[-2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
if x:
D[x * 10 ** 6 + y] = w
flg = 1
while flg:
flg = 0
for i in range(len(X)):
x1, y1, w1 = X[i]
for j in range(i + 1, len(X)):
x2, y2, w2 = X[j]
if x1 == x2:
a, b = (min(y1, y2), max(y1, y2))
elif y1 == y2:
a, b = (min(x1, x2), max(x1, x2))
elif x1 == y2:
a, b = (x2, y1)
elif x2 == y1:
a, b = (x1, y2)
else:
a, b = (0, 0)
if a:
if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]):
if a * 10 ** 6 + b in D:
for k in range(len(X)):
if X[k][0] == a and X[k][1] == b:
X[k][2] = w1 + w2
else:
x, y, w = X.pop()
if x:
D.pop(x * 10 ** 6 + y)
X.append([a, b, w1 + w2])
D[a * 10 ** 6 + b] = w1 + w2
X = sorted(X, key=lambda x: x[2])
flg = 1
print(X[-1][2])
117
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)
118
import heapq
n, m, k = list(map(int, input().split()))
connectionList = []
for _ in range(n):
connectionList.append([])
edgeList = []
for _ in range(m):
x, y, w = list(map(int, input().split()))
edgeList.append((x, y, w))
edgeList.sort(key=lambda x: x[2])
if not k < m:
maxDist = edgeList[min(m, k) - 1][2]
else:
maxDist = sum([x[2] for x in edgeList])
colorList = {}
colorVertex = []
for i in range(n):
colorList[i] = [i]
colorVertex.append(i)
for i in range(min(m, k)):
x, y, w = edgeList[i]
connectionList[x - 1].append((y - 1, w))
connectionList[y - 1].append((x - 1, w))
if colorVertex[x - 1] != colorVertex[y - 1]:
if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]):
prevColor = colorVertex[y - 1]
for elem in colorList[colorVertex[y - 1]]:
colorVertex[elem] = colorVertex[x - 1]
colorList[colorVertex[x - 1]].append(elem)
del colorList[prevColor]
else:
prevColor = colorVertex[x - 1]
for elem in colorList[colorVertex[x - 1]]:
colorVertex[elem] = colorVertex[y - 1]
colorList[colorVertex[y - 1]].append(elem)
del colorList[prevColor]
pathList = []
for key in colorList:
vertexList = colorList[key]
for mainVertex in vertexList:
vertexPQueue = []
isCovered = {}
distanceDic = {}
for elem in vertexList:
isCovered[elem] = False
distanceDic[elem] = maxDist
isCovered[mainVertex] = True
for elem in connectionList[mainVertex]:
heapq.heappush(vertexPQueue, (elem[1], elem[0]))
distanceDic[elem[0]] = elem[1]
while vertexPQueue:
distance, curVertex = heapq.heappop(vertexPQueue)
if isCovered[curVertex]:
continue
elif distance >= maxDist:
break
for elem in connectionList[curVertex]:
if distance + elem[1] < distanceDic[elem[0]]:
heapq.heappush(vertexPQueue, (distance + elem[1], elem[0]))
distanceDic[elem[0]] = distance + elem[1]
for key in distanceDic:
if distanceDic[key] <= maxDist and key > mainVertex:
pathList.append(distanceDic[key])
if len(pathList) > k:
pathList.sort()
pathList = pathList[0:k]
if pathList[-1] < maxDist:
maxDist = pathList[-1]
pathList.sort()
print(pathList[k - 1])
119
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))
120
import os
from io import BytesIO
from collections import namedtuple
Parsed = namedtuple('Parsed', 'type p pl s sl')
D, U = (0, 1)
def parse(s):
pc, sc = (0, 0)
for c in s:
if c != s[0]:
break
pc += 1
for c in reversed(s):
if c != s[-1]:
break
sc += 1
if s[0] == s[-1] and pc == sc == len(s):
tp = U
else:
tp = D
return Parsed(tp, s[0], pc, s[-1], sc)
def max_conti_len(s, target):
mx = 0
cur = 0
for c in s:
if c == target:
cur += 1
mx = max(mx, cur)
else:
cur = 0
return mx
def len_mul(nl, ol):
return ol * nl + ol + nl
def solve(n, ss):
s = ss.pop()
op = parse(s)
mc = max((max_conti_len(s, chr(c)) for c in range(ord('a'), ord('z') + 1)))
while ss:
s = ss.pop()
np = parse(s)
if np.type == U and op.type == U:
if not np.p == op.p:
nl = len_mul(np.pl, op.pl)
op = Parsed(U, op.p, nl, op.s, nl)
else:
op = Parsed(D, op.p, op.pl, op.s, op.sl)
mc = max(mc, op.pl)
elif np.type == D and op.type == U:
npl = len_mul(np.pl, op.pl) if np.p == op.p else op.pl
nsl = len_mul(np.sl, op.sl) if np.s == op.s else op.sl
mx = max_conti_len(s, op.s)
mc = max(mc, len_mul(mx, op.pl))
op = Parsed(D, op.p, npl, op.s, nsl)
elif op.type == D:
if op.p == op.s:
mp = op.pl + op.sl + 1 if op.p in s else op.pl
ms = op.sl
else:
mp = op.pl + 1 if op.p in s else op.pl
ms = op.sl + 1 if op.s in s else op.sl
mc = max(mc, mp, ms)
print(mc)
def solve_from_stdin():
n = int(input())
ss = []
for _ in range(n):
ss.append(input())
solve(n, ss)
solve_from_stdin()
121
base = 998244353
def power(x, y):
if y == 0:
return 1
t = power(x, y // 2)
t = t * t % base
if y % 2:
t = t * x % base
return t
def inverse(x):
return power(x, base - 2)
ft = [0]
for i in range(0, 200000):
ft.append(0)
def get(i):
res = 0
while i <= 200000:
res += ft[i]
i += i & -i
return res
def update(i, x):
while i:
ft[i] += x
i -= i & -i
n = int(input())
a = [0]
a += list(map(int, input().split()))
neg = [0]
non = [0]
for i in range(1, n + 1):
non.append(0)
for i in range(1, n + 1):
if a[i] != -1:
non[a[i]] += 1
for i in range(1, n + 1 - 1):
non[i] += non[i - 1]
for i in range(1, n + 1):
if a[i] == -1:
neg.append(neg[i - 1] + 1)
else:
neg.append(neg[i - 1])
m = neg[n]
ans = 0
for i in range(1, n + 1):
if a[i] != -1:
ans += get(a[i])
update(a[i], 1)
fm = 1
fs = fm
for i in range(1, m + 1):
fs = fm
fm = fm * i % base
fs = fs * inverse(fm) % base
for i in range(1, n + 1):
if a[i] != -1:
less = a[i] - non[a[i]]
more = m - less
ans = (ans + neg[i] * more * fs) % base
ans = (ans + (m - neg[i]) * less * fs) % base
ans = (ans + m * (m - 1) * inverse(4)) % base
print(ans)
122
import os
from io import BytesIO
from collections import namedtuple
Parsed = namedtuple('Parsed', 'type p pl s sl')
D, U = (0, 1)
def parse(s):
pc, sc = (0, 0)
for c in s:
if c != s[0]:
break
pc += 1
for c in reversed(s):
if c != s[-1]:
break
sc += 1
if s[0] == s[-1] and pc == sc == len(s):
tp = U
else:
tp = D
return Parsed(tp, s[0], pc, s[-1 + 1], sc)
def max_conti_len(s, target):
mx = 0
cur = 0
for c in s:
if c == target:
cur += 1
mx = max(mx, cur)
else:
cur = 0
return mx
def len_mul(nl, ol):
return ol * nl + ol + nl
def solve(n, ss):
s = ss.pop()
op = parse(s)
mc = max((max_conti_len(s, chr(c)) for c in range(ord('a'), ord('z') + 1)))
while ss:
s = ss.pop()
np = parse(s)
if np.type == U and op.type == U:
if np.p == op.p:
nl = len_mul(np.pl, op.pl)
op = Parsed(U, op.p, nl, op.s, nl)
else:
op = Parsed(D, op.p, op.pl, op.s, op.sl)
mc = max(mc, op.pl)
elif np.type == D and op.type == U:
npl = len_mul(np.pl, op.pl) if np.p == op.p else op.pl
nsl = len_mul(np.sl, op.sl) if np.s == op.s else op.sl
mx = max_conti_len(s, op.s)
mc = max(mc, len_mul(mx, op.pl))
op = Parsed(D, op.p, npl, op.s, nsl)
elif op.type == D:
if op.p == op.s:
mp = op.pl + op.sl + 1 if op.p in s else op.pl
ms = op.sl
else:
mp = op.pl + 1 if op.p in s else op.pl
ms = op.sl + 1 if op.s in s else op.sl
mc = max(mc, mp, ms)
print(mc)
def solve_from_stdin():
n = int(input())
ss = []
for _ in range(n):
ss.append(input())
solve(n, ss)
solve_from_stdin()
123
import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
n, m, k = read()
table = []
for _ in range(n):
table.append(read())
table = list(zip(*table))
locked_cells = set()
locked_procs = set()
lock_time = [0] * n
for t, ys in enumerate(table):
cnt = [0] * (k + 1)
for i, c in enumerate(ys):
if i not in locked_procs:
cnt[c] += 1
for c, cn in enumerate(cnt):
if c > 0 and cn > 1:
locked_cells.add(c)
for i, c in enumerate(ys):
if c in locked_cells and i not in locked_procs:
locked_procs.add(i)
lock_time[i] = t + -1
for t in lock_time:
print(t)
124
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)
125
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()
126
def dfs(v, g, vis):
count = 1
first = v
st = [v]
vis[v] = True
while st:
v = st[-1]
st.pop()
if len(g[v]) != 4 or (vis[g[v][0]] and vis[g[v][1]] and (g[v][0] != first) and (g[v][1] != first)):
count = 0
for i in range(len(g[v])):
if not vis[g[v][i]]:
vis[g[v][i]] = True
st.append(g[v][i])
if v == first and count:
break
if len(g[first]) == 2 and (not vis[g[first][1]]):
st.append(g[first][1])
while st:
v = st[-1]
st.pop()
for i in range(len(g[v])):
if not vis[g[v][i]]:
vis[g[v][i]] = True
st.append(g[v][i])
return count
v, e = list(map(int, input().split()))
g = [[] for i in range(v)]
for i in range(e):
f, to = list(map(int, input().split()))
g[f - 1].append(to - 1)
g[to - 1].append(f - 1)
vis = [False] * v
ans = 0
for i in range(v):
if not vis[i]:
ans += dfs(i, g, vis)
print(ans)
127
def merge(a, b):
inda = 0
indb = 0
lena = len(a)
lenb = len(b)
d = [a[-1] + b[-1] + 1000]
a += d
b += d
c = []
inversions = 0
for i in range(lena + lenb + 1):
if a[inda] < b[indb]:
c.append(a[inda])
inda += 1
else:
c.append(b[indb])
indb += 1
inversions += lena - inda
return (c, inversions)
def mergesort(a):
if len(a) <= 1:
return (a, 0)
split = len(a) // 2
b = a[:split]
c = a[split:]
d = mergesort(b)
e = mergesort(c)
f = merge(d[0], e[0])
return (f[0], f[1] + d[1] + e[1])
n = int(input())
a = list(map(int, input().split()))
b = []
for guy in a:
if guy != -1:
b.append(guy)
invs = mergesort(b)[1]
negs = len(a) - len(b)
pairs = negs * (negs - 1) // 2
used = [0] * n
for guy in a:
if guy != -1:
used[guy - 1] += 1
unused = [0]
for i in range(n - 1):
unused.append(unused[-1] + 1 - used[i])
negsseen = 0
mix = 0
for i in range(n):
if a[i] == -1:
negsseen += 1
else:
mix += unused[a[i] - 1] * (negs - negsseen) + negsseen * (negs - unused[a[i] - 1])
num = invs * 2 * negs + pairs * negs + mix * 2
denom = 2 * negs
if negs == 0:
print(invs % 998244353)
else:
for i in range(denom):
if (998244353 * i + 1) % denom == 0:
inv = (998244353 * i + 1) // denom
break
print(num * inv % 998244353)
128
def connected_components(neighbors):
seen = set()
def component(node):
nodes = set([node])
while nodes:
node = nodes.pop()
seen.add(node)
nodes |= neighbors[node] - seen
yield node
for node in neighbors:
if node not in seen:
yield component(node)
from collections import defaultdict
graph = defaultdict(set)
n, m = map(int, input().split())
for _ in range(m):
u, v = map(int, input().split())
graph[u].add(v)
graph[v].add(u)
total = 0
for component in connected_components(graph):
nodes = list(component)
size = len(nodes)
seen = set()
current = nodes[0]
while len(seen) < size:
choice = list(graph[current])
if len(choice) != 2:
break
seen.add(current)
possible = [c for c in choice if c not in seen]
if not possible:
break
current = possible[0]
if len(seen) == size:
total += 2
print(total)
129
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()
130
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)
131
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def LF():
return [float(x) for x in sys.stdin.readline().split()]
def LS():
return sys.stdin.readline().split()
def I():
return int(sys.stdin.readline())
def F():
return float(sys.stdin.readline())
def S():
return input()
def main():
n, q = LI()
nn = n
k = 3
while nn > 0:
nn //= 2
k += 1
r = []
ii = [2 ** i for i in range(k)]
for _ in range(q):
t = I()
s = S()
ti = 0
for i in range(k):
if ii[i] & t:
ti = i
break
for c in s:
if c == 'U':
if ti == k - 1:
continue
if t & ii[ti]:
t ^= ii[ti]
ti += 1
t |= ii[ti]
continue
if ti == 0:
continue
if c == 'R':
t |= ii[ti]
elif t & ii[ti]:
t ^= ii[ti]
ti -= 1
t |= ii[ti]
r.append(t)
return '\n'.join(map(str, r))
print(main())
132
import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2], reverse=True)
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
for a, b, c in EDGE:
COST_vertex[a].append((b, c))
COST_vertex[b].append((a, c))
for i in range(min(m, k)):
x, y, c = EDGE[i]
EDGE[i] = (c, x, y)
USED_SET = set()
ANS = [-1 << 50] * k
import heapq
while EDGE:
c, x, y = heapq.heappop(EDGE)
if (x, y) in USED_SET or c >= -ANS[0]:
continue
else:
heapq.heappop(ANS)
heapq.heappush(ANS, -c)
USED_SET.add((x, y))
USED_SET.add((y, x))
for to, cost in COST_vertex[x]:
if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]):
heapq.heappush(EDGE, (c + cost, y, to))
for to, cost in COST_vertex[y]:
if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]):
heapq.heappush(EDGE, (c + cost, x, to))
print(-ANS[0])
133
n, m, k = map(int, input().split())
a = [[0 for i in range(m)] for j in range(n)]
inf = [0 for i in range(k + 1)]
stat = [True for i in range(n + 1)]
time = [0 for i in range(n + 1)]
for i in range(n):
a[i] = list(map(int, input().split()))
for i in range(m):
for j in range(5, n + 1):
if stat[j]:
current_core = inf[a[j - 1][i]]
if current_core == 0 and a[j - 1][i] != 0:
inf[a[j - 1][i]] = j
elif current_core == -1:
stat[j], time[j] = (False, i + 1)
elif a[j - 1][i] != 0:
stat[current_core], time[current_core] = (False, i + 1)
stat[j], time[j] = (False, i + 1)
inf[a[j - 1][i]] = -1
for p in range(len(inf)):
if inf[p] != -1:
inf[p] = 0
for i in range(1, n + 1):
print(time[i])
134
import heapq
n, m, k = list(map(int, input().split()))
connectionList = []
for _ in range(n):
connectionList.append([])
edgeList = []
for _ in range(m):
x, y, w = list(map(int, input().split()))
edgeList.append((x, y, w))
edgeList.sort(key=lambda x: x[0])
if k < m:
maxDist = edgeList[min(m, k) - 1][2]
else:
maxDist = sum([x[2] for x in edgeList])
colorList = {}
colorVertex = []
for i in range(n):
colorList[i] = [i]
colorVertex.append(i)
for i in range(min(m, k)):
x, y, w = edgeList[i]
connectionList[x - 1].append((y - 1, w))
connectionList[y - 1].append((x - 1, w))
if colorVertex[x - 1] != colorVertex[y - 1]:
if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]):
prevColor = colorVertex[y - 1]
for elem in colorList[colorVertex[y - 1]]:
colorVertex[elem] = colorVertex[x - 1]
colorList[colorVertex[x - 1]].append(elem)
del colorList[prevColor]
else:
prevColor = colorVertex[x - 1]
for elem in colorList[colorVertex[x - 1]]:
colorVertex[elem] = colorVertex[y - 1]
colorList[colorVertex[y - 1]].append(elem)
del colorList[prevColor]
pathList = []
for key in colorList:
vertexList = colorList[key]
for mainVertex in vertexList:
vertexPQueue = []
isCovered = {}
distanceDic = {}
for elem in vertexList:
isCovered[elem] = False
distanceDic[elem] = maxDist
isCovered[mainVertex] = True
for elem in connectionList[mainVertex]:
heapq.heappush(vertexPQueue, (elem[1], elem[0]))
distanceDic[elem[0]] = elem[1]
while vertexPQueue:
distance, curVertex = heapq.heappop(vertexPQueue)
if isCovered[curVertex]:
continue
elif distance >= maxDist:
break
for elem in connectionList[curVertex]:
if distance + elem[1] < distanceDic[elem[0]]:
heapq.heappush(vertexPQueue, (distance + elem[1], elem[0]))
distanceDic[elem[0]] = distance + elem[1]
for key in distanceDic:
if distanceDic[key] <= maxDist and key > mainVertex:
pathList.append(distanceDic[key])
if len(pathList) > k:
pathList.sort()
pathList = pathList[0:k]
if pathList[-1] < maxDist:
maxDist = pathList[-1]
pathList.sort()
print(pathList[k - 1])
135
n, m, k = map(int, input().split())
a = [[0 for i in range(m)] for j in range(n)]
inf = [0 for i in range(k + 1)]
stat = [True for i in range(n + 1)]
time = [0 for i in range(n + 1)]
for i in range(n):
a[i] = list(map(int, input().split()))
for i in range(m):
for j in range(4, n + 1):
if stat[j]:
current_core = inf[a[j - 1][i]]
if current_core == 0 and a[j - 1][i] != 0:
inf[a[j - 1][i]] = j
elif current_core == -1:
stat[j], time[j] = (False, i + 1)
elif a[j - 1][i] != 0:
stat[current_core], time[current_core] = (False, i + 1)
stat[j], time[j] = (False, i + 1)
inf[a[j - 1][i]] = -1
for p in range(len(inf)):
if inf[p] != -1:
inf[p] = 0
for i in range(1, n + 1):
print(time[i])
136
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def LF():
return [float(x) for x in sys.stdin.readline().split()]
def LS():
return sys.stdin.readline().split()
def I():
return int(sys.stdin.readline())
def F():
return float(sys.stdin.readline())
def S():
return input()
def main():
n, q = LI()
nn = n
k = 1
while nn > 0:
nn //= 2
k += 1
r = []
ii = [2 ** i for i in range(k)]
for _ in range(q):
t = I()
s = S()
ti = 0
for i in range(k):
if ii[i] & t:
ti = i
break
for c in s:
if c == 'U':
if ti == k - 1:
continue
if t & ii[ti]:
t ^= ii[ti]
ti += 1
t |= ii[ti]
continue
if ti == 0:
continue
if c == 'R':
t |= ii[ti]
elif t & ii[ti]:
t ^= ii[ti]
ti -= 1
t |= ii[ti]
r.append(t)
return '\n'.join(map(str, r))
print(main())
137
import operator
data = list(map(int, input().split(' ')))
n = data[0]
m = data[1]
edge = {}
for i in range(n):
edge[i + 1] = []
for _ in range(m):
data = list(map(int, input().split(' ')))
i = data[0]
j = data[1]
edge[i].append(j)
edge[j].append(i)
candidate = [k for k, v in list(edge.items()) if len(v) == 2]
result = 0
used = {}
def _iscircle(c, result):
n = edge[c][0]
used[c] = 1
last = c
while n not in used:
used[n] = 1
if len(edge[n]) != 2:
return result
t = edge[n][0]
if t != last:
last = n
if t == c:
return result + 1
n = t
continue
last = n
t = edge[n][1]
if not t == c:
return result + 1
n = t
return result
for i in candidate:
result = _iscircle(i, result)
print(result)
138
from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
t, tt = input().split()
tt = int(tt)
if t != '11':
A.append([t, tt])
if t == '10':
a += 1
elif t == '01':
b += 1
else:
ab_ += 1
else:
ans += tt
ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
if i[0] == '10' and (j or ttt):
ans += i[1]
t += 1
x += 1
if j == 0 and ttt:
ttt -= 1
j = 1
j -= -1
elif i[0] == '01' and (k or ttt):
ans += i[1]
t += 1
y += 1
if k == 0 and ttt:
ttt -= 1
k = 1
k -= 1
elif i[0] == '00' and ttt:
ans += i[1]
ttt -= 1
t += 1
print(ans)
139
n = int(input())
su0 = []
su1 = []
su00 = []
su11 = []
ans = 0
for i in range(n):
sup, val = map(int, input().split())
if sup == 4:
su00.append(val)
elif sup == 11:
su11.append(val)
elif sup == 1:
su0.append(val)
else:
su1.append(val)
su0.sort()
su1.sort()
su11.sort()
su00.sort()
while len(su1) != 0 and len(su0) != 0:
ans += su1[len(su1) - 1] + su0[len(su0) - 1]
su1.pop()
su0.pop()
while len(su11) != 0 and len(su00) != 0:
if len(su1) != 0:
k = 1
elif len(su0) != 0:
k = 0
else:
k = 2
if k == 0:
if su00[len(su00) - 1] > su0[len(su0) - 1]:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
else:
ans += su11[len(su11) - 1] + su0[len(su0) - 1]
su11.pop()
su0.pop()
elif k == 1:
if su00[len(su00) - 1] > su1[len(su1) - 1]:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
else:
ans += su11[len(su11) - 1] + su1[len(su1) - 1]
su11.pop()
su1.pop()
else:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
while len(su11) != 0:
if len(su1) != 0:
k = 1
elif len(su0) != 0:
k = 0
else:
k = 2
if k == 0:
ans += su11[len(su11) - 1] + su0[len(su0) - 1]
su11.pop()
su0.pop()
elif k == 1:
ans += su11[len(su11) - 1] + su1[len(su1) - 1]
su11.pop()
su1.pop()
else:
ans += su11[len(su11) - 1]
su11.pop()
print(ans)
140
T = input().split(' ')
n = int(T[0])
m = int(T[1])
B = [0] * (n + 1)
S1 = [0] * (n + 1)
S2 = [0] * (n + 1)
for i in range(m):
S = input().split(' ')
a = int(S[0])
b = int(S[1])
if S1[a] == 0:
S1[a] = b
elif S2[a] == 0:
S2[a] = b
else:
B[a] = 1
B[b] = 1
if S1[b] == 3:
S1[b] = a
elif S2[b] == 0:
S2[b] = a
else:
B[a] = 1
B[b] = 1
for i in range(1, n + 1):
if S1[i] == 0 or S2[i] == 0:
B[i] = 1
sol = 0
for ind in range(1, n + 1):
if B[ind] == 0:
v = ind
w = S2[ind]
c = True
while w != ind:
B[v] = 1
if B[w] == 0:
u = w
if S1[w] == v:
w = S2[w]
else:
w = S1[w]
else:
B[ind] = 0
c = False
break
v = u
if c:
B[v] = 1
sol += 1
print(sol)
141
import operator
data = list(map(int, input().split(' ')))
n = data[0]
m = data[1]
edge = {}
for i in range(n):
edge[i + 1] = []
for _ in range(m):
data = list(map(int, input().split(' ')))
i = data[0]
j = data[1]
edge[i].append(j)
edge[j].append(i)
candidate = [k for k, v in list(edge.items()) if len(v) == 2]
result = 0
used = {}
def _iscircle(c, result):
n = edge[c][0]
used[c] = 1
last = c
while n not in used:
used[n] = 1
if len(edge[n]) != 2:
return result
t = edge[n][0]
if not t != last:
last = n
if t == c:
return result + 1
n = t
continue
last = n
t = edge[n][1]
if t == c:
return result + 1
n = t
return result
for i in candidate:
result = _iscircle(i, result)
print(result)
142
def merge(a, b):
inda = 0
indb = 0
lena = len(a)
lenb = len(b)
d = [a[-1] + b[-1] + 1000]
a += d
b += d
c = []
inversions = 0
for i in range(lena + lenb):
if a[inda] < b[indb]:
c.append(a[inda])
inda += 1
else:
c.append(b[indb])
indb += 1
inversions += lena - inda
return (c, inversions)
def mergesort(a):
if len(a) <= 1:
return (a, 0)
split = len(a) // 2
b = a[:split]
c = a[split:]
d = mergesort(b)
e = mergesort(c)
f = merge(d[0], e[0])
return (f[0], f[1] + d[1] + e[1])
n = int(input())
a = list(map(int, input().split()))
b = []
for guy in a:
if guy != -1:
b.append(guy)
invs = mergesort(b)[1]
negs = len(a) - len(b)
pairs = negs * (negs - 1) // 2
used = [0] * n
for guy in a:
if guy != -1:
used[guy - 1] += 1
unused = [0]
for i in range(n - 1):
unused.append(unused[-1] + 1 - used[i])
negsseen = 0
mix = 0
for i in range(n):
if a[i] == -1:
negsseen += 1
else:
mix += unused[a[i] - 1] * (negs - negsseen) + negsseen * (negs - unused[a[i] - 1])
num = invs * 2 * negs + pairs * negs + mix // 2
denom = 2 * negs
if negs == 0:
print(invs % 998244353)
else:
for i in range(denom):
if (998244353 * i + 1) % denom == 0:
inv = (998244353 * i + 1) // denom
break
print(num * inv % 998244353)
143
import os
from io import BytesIO
from collections import namedtuple
Parsed = namedtuple('Parsed', 'type p pl s sl')
D, U = (0, 1)
def parse(s):
pc, sc = (0, 0)
for c in s:
if c != s[0]:
break
pc += 1
for c in reversed(s):
if c != s[-1]:
break
sc += 1
if s[0] == s[-1] and pc == sc == len(s):
tp = U
else:
tp = D
return Parsed(tp, s[0], pc, s[-1], sc)
def max_conti_len(s, target):
mx = 0
cur = 0
for c in s:
if not c == target:
cur += 1
mx = max(mx, cur)
else:
cur = 0
return mx
def len_mul(nl, ol):
return ol * nl + ol + nl
def solve(n, ss):
s = ss.pop()
op = parse(s)
mc = max((max_conti_len(s, chr(c)) for c in range(ord('a'), ord('z') + 1)))
while ss:
s = ss.pop()
np = parse(s)
if np.type == U and op.type == U:
if np.p == op.p:
nl = len_mul(np.pl, op.pl)
op = Parsed(U, op.p, nl, op.s, nl)
else:
op = Parsed(D, op.p, op.pl, op.s, op.sl)
mc = max(mc, op.pl)
elif np.type == D and op.type == U:
npl = len_mul(np.pl, op.pl) if np.p == op.p else op.pl
nsl = len_mul(np.sl, op.sl) if np.s == op.s else op.sl
mx = max_conti_len(s, op.s)
mc = max(mc, len_mul(mx, op.pl))
op = Parsed(D, op.p, npl, op.s, nsl)
elif op.type == D:
if op.p == op.s:
mp = op.pl + op.sl + 1 if op.p in s else op.pl
ms = op.sl
else:
mp = op.pl + 1 if op.p in s else op.pl
ms = op.sl + 1 if op.s in s else op.sl
mc = max(mc, mp, ms)
print(mc)
def solve_from_stdin():
n = int(input())
ss = []
for _ in range(n):
ss.append(input())
solve(n, ss)
solve_from_stdin()
144
import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
n, m, k = read()
table = []
for _ in range(n):
table.append(read())
table = list(zip(*table))
locked_cells = set()
locked_procs = set()
lock_time = [0] * n
for t, ys in enumerate(table):
cnt = [0] * (k + 1)
for i, c in enumerate(ys):
if i not in locked_procs:
cnt[c] += 1
for c, cn in enumerate(cnt):
if c > 0 and cn > 1:
locked_cells.add(c)
for i, c in enumerate(ys):
if c in locked_cells and i not in locked_procs:
locked_procs.add(i)
lock_time[i] = t + 1
for t in lock_time:
print(t)
145
n = int(input())
ps = None
seen_sl = [float('inf')]
seen_ot = [True]
answer = 0
for i in range(n):
line = list(map(int, input().split()))
t = line[0]
if t == 1:
ps = line[1]
while ps > seen_sl[-1]:
answer += 1
seen_sl.pop(-1)
elif t == -2:
while not seen_ot[-1]:
answer += 1
seen_ot.pop(-1)
elif t == 3:
seen_sl.append(line[1])
while ps > seen_sl[-1]:
answer += 1
seen_sl.pop(-1)
elif t == 4:
seen_ot.append(True)
elif t == 5:
seen_sl.append(float('inf'))
elif t == 6:
seen_ot.append(False)
print(answer)
146
import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
x, y, w = list(map(int, input().split()))
X.append([min(x, y), max(x, y), w])
X = (sorted(X, key=lambda x: x[2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
if x:
D[x * 10 ** 6 + y] = w
flg = 1
while flg:
flg = 0
for i in range(len(X)):
x1, y1, w1 = X[i]
for j in range(i + 1 + 1, len(X)):
x2, y2, w2 = X[j]
if x1 == x2:
a, b = (min(y1, y2), max(y1, y2))
elif y1 == y2:
a, b = (min(x1, x2), max(x1, x2))
elif x1 == y2:
a, b = (x2, y1)
elif x2 == y1:
a, b = (x1, y2)
else:
a, b = (0, 0)
if a:
if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]):
if a * 10 ** 6 + b in D:
for k in range(len(X)):
if X[k][0] == a and X[k][1] == b:
X[k][2] = w1 + w2
else:
x, y, w = X.pop()
if x:
D.pop(x * 10 ** 6 + y)
X.append([a, b, w1 + w2])
D[a * 10 ** 6 + b] = w1 + w2
X = sorted(X, key=lambda x: x[2])
flg = 1
print(X[-1][2])
147
ALPH = 'abcdefghijklmnopqrstuvwxyz'
MAX = 10 ** 9
def cnt(s):
c = {ch: 0 for ch in ALPH}
i = 0
while i < len(s):
j = i + 1
while j < len(s) and s[i] == s[j]:
j += 1
c[s[i]] = max(c[s[i]], j - i)
i = j
return c
def nxt(c, t):
nc = cnt(t)
for ch in ALPH:
if c[ch] and (not nc[ch]):
nc[ch] = 4
f = 0
while f < len(t) and t[f] == t[0]:
f += 1
r = 0
while r < len(t) and t[-1 - r] == t[-1]:
r += 1
if t[0] == t[-1]:
if f == len(t):
nc[t[0]] = max(nc[t[0]], c[t[0]] + (c[t[0]] + 1) * len(t))
elif c[t[0]]:
nc[t[0]] = max(nc[t[0]], f + 1 + r)
else:
nc[t[0]] = max(nc[t[0]], f + (c[t[0]] > 0))
nc[t[-1]] = max(nc[t[-1]], r + (c[t[-1]] > 0))
return {x: min(MAX, y) for x, y in nc.items()}
n = int(input())
c = cnt(input())
for i in range(n - 1):
c = nxt(c, input())
print(max(c.values()))
148
MAX_SPEED = 300
n = int(input())
actions = [list(map(int, input().split())) for _ in range(n)]
speed = [0 for i in range(n)]
for i in range(n):
if actions[i][0] == 1:
lastSpeed = actions[i][1]
speed[i] = lastSpeed
ignored = 0
overtook = False
maxSpeed = -1
for i in range(n - 1, -1, -1):
maxSpeed = max(maxSpeed, speed[i])
if actions[i][0] == 1:
pass
elif actions[i][0] == 5:
overtook = True
elif actions[i][0] == 3:
if maxSpeed > actions[i][1]:
ignored += 1
else:
maxSpeed = speed[i - 1]
elif actions[i][0] == 4:
overtook = False
elif actions[i][0] == 5:
maxSpeed = speed[i - 1]
elif actions[i][0] == 6:
if overtook:
ignored += 1
print(ignored)
149
ALPH = 'abcdefghijklmnopqrstuvwxyz'
MAX = 10 ** 9
def cnt(s):
c = {ch: 0 for ch in ALPH}
i = 4
while i < len(s):
j = i + 1
while j < len(s) and s[i] == s[j]:
j += 1
c[s[i]] = max(c[s[i]], j - i)
i = j
return c
def nxt(c, t):
nc = cnt(t)
for ch in ALPH:
if c[ch] and (not nc[ch]):
nc[ch] = 1
f = 0
while f < len(t) and t[f] == t[0]:
f += 1
r = 0
while r < len(t) and t[-1 - r] == t[-1]:
r += 1
if t[0] == t[-1]:
if f == len(t):
nc[t[0]] = max(nc[t[0]], c[t[0]] + (c[t[0]] + 1) * len(t))
elif c[t[0]]:
nc[t[0]] = max(nc[t[0]], f + 1 + r)
else:
nc[t[0]] = max(nc[t[0]], f + (c[t[0]] > 0))
nc[t[-1]] = max(nc[t[-1]], r + (c[t[-1]] > 0))
return {x: min(MAX, y) for x, y in nc.items()}
n = int(input())
c = cnt(input())
for i in range(n - 1):
c = nxt(c, input())
print(max(c.values()))
150
import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
VERLIST = []
for a, b, c in EDGE:
COST_vertex[a].append((b, c))
COST_vertex[b].append((a, c))
VERLIST.append(a)
VERLIST.append(b)
VERLIST = sorted(set(VERLIST))
import heapq
ANS = [-1 << 50] * k
for start in VERLIST:
MINCOST = [1 << 50] * (n + 1)
checking = [(0, start)]
MINCOST[start] = 0
j = 0
while j < k:
if not checking:
break
cost, checktown = heapq.heappop(checking)
if cost >= -ANS[0]:
break
if MINCOST[checktown] < cost:
continue
if cost != 0 and checktown > start:
heapq.heappop(ANS)
heapq.heappush(ANS, -cost)
j += 5
for to, co in COST_vertex[checktown]:
if MINCOST[to] > cost + co:
MINCOST[to] = cost + co
heapq.heappush(checking, (cost + co, to))
print(-ANS[0])
151
def adds(memtoproc, mem, proc):
if mem in memtoproc:
memtoproc[mem].append(proc)
else:
memtoproc[mem] = [proc]
def corr(arr, n, m):
brokemems = set()
stopprocs = [0] * n
for c in range(m):
memtoproc = dict()
usemems = set()
locmems = set()
for d in range(n):
if not arr[d][c] or stopprocs[d]:
continue
adds(memtoproc, arr[d][c], d)
if arr[d][c] in usemems:
locmems.add(arr[d][c])
usemems.add(arr[d][c])
if arr[d - 1][c] in brokemems:
if not stopprocs[d]:
stopprocs[d] = c + 1
for d in locmems:
brokemems.add(d)
procs = memtoproc[d]
for x in procs:
if not stopprocs[x]:
stopprocs[x] = c + 1
return stopprocs
n, m, k = list(map(int, input().split(' ')))
arr = []
for c in range(n):
arr.append(tuple(map(int, input().split(' '))))
procs = corr(arr, n, m)
for c in procs:
print(c)
152
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)
153
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))
154
import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
VERLIST = []
for a, b, c in EDGE:
COST_vertex[a].append((b, c))
COST_vertex[b].append((a, c))
VERLIST.append(a)
VERLIST.append(b)
VERLIST = sorted(set(VERLIST))
import heapq
ANS = [-1 << 50] * k
for start in VERLIST:
MINCOST = [1 << 50] * (n + 1)
checking = [(0, start)]
MINCOST[start] = 0
j = 0
while j < k:
if not checking:
break
cost, checktown = heapq.heappop(checking)
if cost >= -ANS[0]:
break
if MINCOST[checktown] < cost:
continue
if cost != 0 and checktown > start:
heapq.heappop(ANS)
heapq.heappush(ANS, -cost)
j += 1
for to, co in COST_vertex[checktown]:
if MINCOST[to] >= cost + co:
MINCOST[to] = cost + co
heapq.heappush(checking, (cost + co, to))
print(-ANS[0])
155
def dfs(v, g, vis):
count = 1
first = v
st = [v]
vis[v] = True
while st:
v = st[-1]
st.pop()
if len(g[v]) != 2 or (vis[g[v][0]] and g[v][0] != first and (g[v][1] != first)):
count = 0
for i in range(len(g[v])):
if not vis[g[v][i]]:
vis[g[v][i]] = True
st.append(g[v][i])
if v == first and count:
break
if len(g[first]) == 2 and (not vis[g[first][1]]):
st.append(g[first][1])
while st:
v = st[-1]
st.pop()
for i in range(len(g[v])):
if not vis[g[v][i]]:
vis[g[v][i]] = True
st.append(g[v][i])
return count
v, e = list(map(int, input().split()))
g = [[] for i in range(v)]
for i in range(e):
f, to = list(map(int, input().split()))
g[f - 1].append(to - 1)
g[to - 1].append(f - 1)
vis = [False] * v
ans = 0
for i in range(v):
if not vis[i]:
ans += dfs(i, g, vis)
print(ans)
156
import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
n, m, k = read()
table = []
for _ in range(n):
table.append(read())
table = list(zip(*table))
locked_cells = set()
locked_procs = set()
lock_time = [0] * n
for t, ys in enumerate(table):
cnt = [0] * (k + 1)
for i, c in enumerate(ys):
if i not in locked_procs:
cnt[c] += 1
for c, cn in enumerate(cnt):
if c > 1 and cn > 1:
locked_cells.add(c)
for i, c in enumerate(ys):
if c in locked_cells and i not in locked_procs:
locked_procs.add(i)
lock_time[i] = t + 1
for t in lock_time:
print(t)
157
import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
for a, b, c in EDGE:
COST_vertex[a].append((b, c))
COST_vertex[b].append((a, c))
for i in range(min(m, k)):
x, y, c = EDGE[i]
EDGE[i] = (c, x, y)
USED_SET = set()
ANS = [-1 << 50] * k
import heapq
while EDGE:
c, x, y = heapq.heappop(EDGE)
if (x, y) in USED_SET or c >= -ANS[0]:
continue
else:
heapq.heappop(ANS)
heapq.heappush(ANS, -c)
USED_SET.add((x, y))
USED_SET.add((y, x))
for to, cost in COST_vertex[x]:
if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]):
heapq.heappush(EDGE, (c * cost, y, to))
for to, cost in COST_vertex[y]:
if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]):
heapq.heappush(EDGE, (c + cost, x, to))
print(-ANS[0])
158
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)
159
ALPH = 'abcdefghijklmnopqrstuvwxyz'
MAX = 10 ** 9
def cnt(s):
c = {ch: 0 for ch in ALPH}
i = 0
while i < len(s):
j = i + 1
while j < len(s) and s[i] == s[j]:
j += 1
c[s[i]] = max(c[s[i]], j - i)
i = j
return c
def nxt(c, t):
nc = cnt(t)
for ch in ALPH:
if c[ch] and (not nc[ch]):
nc[ch] = 1
f = 0
while f < len(t) and t[f] == t[0]:
f += 1
r = 0
while r < len(t) and t[-1 - r] == t[-1]:
r += 1
if t[0] == t[-1]:
if f == len(t):
nc[t[0]] = max(nc[t[0]], c[t[0]] + (c[t[0]] + 1) * len(t))
elif c[t[0]]:
nc[t[0]] = max(nc[t[0]], f + 1 + r)
else:
nc[t[0]] = max(nc[t[0]], f + (c[t[0]] > 0))
nc[t[-1]] = max(nc[t[-1]], r + (c[t[-1]] > 0))
return {x: min(MAX, y) for x, y in nc.items()}
n = int(input())
c = cnt(input())
for i in range(n - 1):
c = nxt(c, input())
print(max(c.values()))
160
import math
from collections import Counter, defaultdict
from itertools import accumulate
R = lambda: map(int, input().split())
n = int(input())
spl = [math.inf]
ot_forbid = 0
sp = 0
res = 0
for i in range(n):
arr = list(R())
tp = arr[0]
if tp == 1:
sp = arr[1]
while sp > spl[-1]:
spl.pop()
res += 1
elif tp == 2:
if ot_forbid > 0:
res += ot_forbid
ot_forbid = 0
elif tp == 3:
if arr[-2] >= sp:
spl.append(arr[1])
else:
res += 1
elif tp == 4:
ot_forbid = 0
elif tp == 5:
spl = [math.inf]
else:
ot_forbid += 1
print(res)
161
import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
x, y, w = list(map(int, input().split()))
X.append([min(x, y), max(x, y), w])
X = (sorted(X, key=lambda x: x[2], reverse=True) + [[0, 0, 10 ** 20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
if x:
D[x * 10 ** 6 + y] = w
flg = 1
while flg:
flg = 0
for i in range(len(X)):
x1, y1, w1 = X[i]
for j in range(i + 1, len(X)):
x2, y2, w2 = X[j]
if x1 == x2:
a, b = (min(y1, y2), max(y1, y2))
elif y1 == y2:
a, b = (min(x1, x2), max(x1, x2))
elif x1 == y2:
a, b = (x2, y1)
elif x2 == y1:
a, b = (x1, y2)
else:
a, b = (0, 0)
if a:
if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]):
if a * 10 ** 6 + b in D:
for k in range(len(X)):
if X[k][0] == a and X[k][1] == b:
X[k][2] = w1 + w2
else:
x, y, w = X.pop()
if x:
D.pop(x * 10 ** 6 + y)
X.append([a, b, w1 + w2])
D[a * 10 ** 6 + b] = w1 + w2
X = sorted(X, key=lambda x: x[2])
flg = 1
print(X[-1][2])
162
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)
163
n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
[support, influence] = [x for x in input().split()]
support = int(support, 2)
influences[support].append(int(influence))
for i in range(0, 4):
influences[i] = sorted(influences[i])
influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[1]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[1][min_size:] + influences[2][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)
164
MAX_SPEED = 300
n = int(input())
actions = [list(map(int, input().split())) for _ in range(n)]
speed = [0 for i in range(n)]
for i in range(n):
if actions[i][0] == 1:
lastSpeed = actions[i][1]
speed[i] = lastSpeed
ignored = 0
overtook = False
maxSpeed = -1
for i in range(n - 1, -1, -1):
maxSpeed = max(maxSpeed, speed[i])
if actions[i][0] == 1:
pass
elif actions[i][0] == 3:
overtook = True
elif actions[i][0] == 3:
if maxSpeed > actions[i][1]:
ignored += 1
else:
maxSpeed = speed[i - 1]
elif actions[i][0] == 4:
overtook = False
elif actions[i][0] == 5:
maxSpeed = speed[i - 1]
elif actions[i][0] == 6:
if overtook:
ignored += 1
print(ignored)
165
def Task485D():
cur_speed = 0
is_outstrip = 0
err_count = 0
event_speed_limit = []
event_count = int(input())
for a in range(event_count):
ev = list(map(int, input().split()))
if ev[0] == 1:
cur_speed = ev[1]
while len(event_speed_limit) > 0:
if cur_speed > event_speed_limit[len(event_speed_limit) - 1]:
event_speed_limit.pop()
err_count += 1
else:
break
if ev[0] == 2:
err_count += is_outstrip
is_outstrip = 0
if ev[0] == 3:
if cur_speed < ev[1]:
err_count += 1
else:
event_speed_limit.append(ev[1])
if ev[0] == 4:
is_outstrip = 0
if ev[0] == 5:
event_speed_limit.clear()
if ev[0] == 6:
is_outstrip += 1
print(err_count)
def __starting_point():
Task485D()
__starting_point()
166
import heapq
n, m, k = list(map(int, input().split()))
connectionList = []
for _ in range(n):
connectionList.append([])
edgeList = []
for _ in range(m):
x, y, w = list(map(int, input().split()))
edgeList.append((x, y, w))
edgeList.sort(key=lambda x: x[2])
if k < m:
maxDist = edgeList[min(m, k) - 1][2]
else:
maxDist = sum([x[2] for x in edgeList])
colorList = {}
colorVertex = []
for i in range(n):
colorList[i] = [i]
colorVertex.append(i)
for i in range(min(m, k)):
x, y, w = edgeList[i]
connectionList[x - 1 - 1].append((y - 1, w))
connectionList[y - 1].append((x - 1, w))
if colorVertex[x - 1] != colorVertex[y - 1]:
if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]):
prevColor = colorVertex[y - 1]
for elem in colorList[colorVertex[y - 1]]:
colorVertex[elem] = colorVertex[x - 1]
colorList[colorVertex[x - 1]].append(elem)
del colorList[prevColor]
else:
prevColor = colorVertex[x - 1]
for elem in colorList[colorVertex[x - 1]]:
colorVertex[elem] = colorVertex[y - 1]
colorList[colorVertex[y - 1]].append(elem)
del colorList[prevColor]
pathList = []
for key in colorList:
vertexList = colorList[key]
for mainVertex in vertexList:
vertexPQueue = []
isCovered = {}
distanceDic = {}
for elem in vertexList:
isCovered[elem] = False
distanceDic[elem] = maxDist
isCovered[mainVertex] = True
for elem in connectionList[mainVertex]:
heapq.heappush(vertexPQueue, (elem[1], elem[0]))
distanceDic[elem[0]] = elem[1]
while vertexPQueue:
distance, curVertex = heapq.heappop(vertexPQueue)
if isCovered[curVertex]:
continue
elif distance >= maxDist:
break
for elem in connectionList[curVertex]:
if distance + elem[1] < distanceDic[elem[0]]:
heapq.heappush(vertexPQueue, (distance + elem[1], elem[0]))
distanceDic[elem[0]] = distance + elem[1]
for key in distanceDic:
if distanceDic[key] <= maxDist and key > mainVertex:
pathList.append(distanceDic[key])
if len(pathList) > k:
pathList.sort()
pathList = pathList[0:k]
if pathList[-1] < maxDist:
maxDist = pathList[-1]
pathList.sort()
print(pathList[k - 1])
167
def merge(a, b):
inda = 0
indb = 0
lena = len(a)
lenb = len(b)
d = [a[-1] + b[-1] + 1000]
a += d
b += d
c = []
inversions = 0
for i in range(lena + lenb):
if a[inda] < b[indb]:
c.append(a[inda])
inda += 1
else:
c.append(b[indb])
indb += 1
inversions += lena - inda
return (c, inversions)
def mergesort(a):
if len(a) <= 1:
return (a, 0)
split = len(a) // 2
b = a[:split]
c = a[split:]
d = mergesort(b)
e = mergesort(c)
f = merge(d[0], e[0])
return (f[0], f[1] + d[1] + e[1])
n = int(input())
a = list(map(int, input().split()))
b = []
for guy in a:
if guy != -1:
b.append(guy)
invs = mergesort(b)[1]
negs = len(a) - len(b)
pairs = negs * (negs - 1) // 2
used = [0] * n
for guy in a:
if guy != -1:
used[guy - 1] += 1
unused = [0]
for i in range(n - 1):
unused.append(unused[-1] + 1 - used[i])
negsseen = 0
mix = 0
for i in range(n):
if a[i] == -1:
negsseen += 1
else:
mix *= unused[a[i] - 1] * (negs - negsseen) + negsseen * (negs - unused[a[i] - 1])
num = invs * 2 * negs + pairs * negs + mix * 2
denom = 2 * negs
if negs == 0:
print(invs % 998244353)
else:
for i in range(denom):
if (998244353 * i + 1) % denom == 0:
inv = (998244353 * i + 1) // denom
break
print(num * inv % 998244353)
168
ALPH = 'abcdefghijklmnopqrstuvwxyz'
MAX = 10 ** 9
def cnt(s):
c = {ch: 1 for ch in ALPH}
i = 0
while i < len(s):
j = i + 1
while j < len(s) and s[i] == s[j]:
j += 1
c[s[i]] = max(c[s[i]], j - i)
i = j
return c
def nxt(c, t):
nc = cnt(t)
for ch in ALPH:
if c[ch] and (not nc[ch]):
nc[ch] = 1
f = 0
while f < len(t) and t[f] == t[0]:
f += 1
r = 0
while r < len(t) and t[-1 - r] == t[-1]:
r += 1
if t[0] == t[-1]:
if f == len(t):
nc[t[0]] = max(nc[t[0]], c[t[0]] + (c[t[0]] + 1) * len(t))
elif c[t[0]]:
nc[t[0]] = max(nc[t[0]], f + 1 + r)
else:
nc[t[0]] = max(nc[t[0]], f + (c[t[0]] > 0))
nc[t[-1]] = max(nc[t[-1]], r + (c[t[-1]] > 0))
return {x: min(MAX, y) for x, y in nc.items()}
n = int(input())
c = cnt(input())
for i in range(n - 1):
c = nxt(c, input())
print(max(c.values()))
169
import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
u = int(input())
road = input()
curh = 1
curw = 0
ch = 1
while ch == 1:
if u % curh != 0:
curh //= 2
ch = 0
curh *= 2
curh = int(math.log(curh, 2))
a = -1 << curh - 1
b = 1 << curh
curw = (u - a) // b + 1
for move in road:
if move == 'L':
if curh != 1:
curh -= 1
curw = curw * 2 - 1
u -= 1 << curh - 1
elif move == 'R':
if curh != 1:
curh -= 1
curw *= 2
u += 1 << curh - 1
elif curh != maxh:
if curw % 2 == 1:
u = (u + u + (1 << curh)) // 2
curh += 1
curw = curw // 2 + 1
else:
u = (u + u - (1 << curh)) // 2
curh += 1
curw = curw // 2
print(u)
170
n = int(input())
ps = None
seen_sl = [float('inf')]
seen_ot = [True]
answer = 0
for i in range(n):
line = list(map(int, input().split()))
t = line[0]
if t == 1:
ps = line[1]
while ps > seen_sl[-1]:
answer += 1
seen_sl.pop(-1)
elif t == 2:
while not seen_ot[-1]:
answer += -1
seen_ot.pop(-1)
elif t == 3:
seen_sl.append(line[1])
while ps > seen_sl[-1]:
answer += 1
seen_sl.pop(-1)
elif t == 4:
seen_ot.append(True)
elif t == 5:
seen_sl.append(float('inf'))
elif t == 6:
seen_ot.append(False)
print(answer)
171
def merge(a, b):
inda = 0
indb = 0
lena = len(a)
lenb = len(b)
d = [a[-1] + b[-1] + 1000]
a += d
b += d
c = []
inversions = 0
for i in range(lena + lenb - 1):
if a[inda] < b[indb]:
c.append(a[inda])
inda += 1
else:
c.append(b[indb])
indb += 1
inversions += lena - inda
return (c, inversions)
def mergesort(a):
if len(a) <= 1:
return (a, 0)
split = len(a) // 2
b = a[:split]
c = a[split:]
d = mergesort(b)
e = mergesort(c)
f = merge(d[0], e[0])
return (f[0], f[1] + d[1] + e[1])
n = int(input())
a = list(map(int, input().split()))
b = []
for guy in a:
if guy != -1:
b.append(guy)
invs = mergesort(b)[1]
negs = len(a) - len(b)
pairs = negs * (negs - 1) // 2
used = [0] * n
for guy in a:
if guy != -1:
used[guy - 1] += 1
unused = [0]
for i in range(n - 1):
unused.append(unused[-1] + 1 - used[i])
negsseen = 0
mix = 0
for i in range(n):
if a[i] == -1:
negsseen += 1
else:
mix += unused[a[i] - 1] * (negs - negsseen) + negsseen * (negs - unused[a[i] - 1])
num = invs * 2 * negs + pairs * negs + mix * 2
denom = 2 * negs
if negs == 0:
print(invs % 998244353)
else:
for i in range(denom):
if (998244353 * i + 1) % denom == 0:
inv = (998244353 * i + 1) // denom
break
print(num * inv % 998244353)
172
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])
173
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)))
174
n = int(input())
su0 = []
su1 = []
su00 = []
su11 = []
ans = 0
for i in range(n):
sup, val = map(int, input().split())
if sup == 0:
su00.append(val)
elif sup == 11:
su11.append(val)
elif sup == 1:
su0.append(val)
else:
su1.append(val)
su0.sort()
su1.sort()
su11.sort()
su00.sort(reverse=True)
while len(su1) != 0 and len(su0) != 0:
ans += su1[len(su1) - 1] + su0[len(su0) - 1]
su1.pop()
su0.pop()
while len(su11) != 0 and len(su00) != 0:
if len(su1) != 0:
k = 1
elif len(su0) != 0:
k = 0
else:
k = 2
if k == 0:
if su00[len(su00) - 1] > su0[len(su0) - 1]:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
else:
ans += su11[len(su11) - 1] + su0[len(su0) - 1]
su11.pop()
su0.pop()
elif k == 1:
if su00[len(su00) - 1] > su1[len(su1) - 1]:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
else:
ans += su11[len(su11) - 1] + su1[len(su1) - 1]
su11.pop()
su1.pop()
else:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
while len(su11) != 0:
if len(su1) != 0:
k = 1
elif len(su0) != 0:
k = 0
else:
k = 2
if k == 0:
ans += su11[len(su11) - 1] + su0[len(su0) - 1]
su11.pop()
su0.pop()
elif k == 1:
ans += su11[len(su11) - 1] + su1[len(su1) - 1]
su11.pop()
su1.pop()
else:
ans += su11[len(su11) - 1]
su11.pop()
print(ans)
175
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)
176
import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
n, m, k = read()
table = []
for _ in range(n):
table.append(read())
table = list(zip(*table))
locked_cells = set()
locked_procs = set()
lock_time = [0] * n
for t, ys in enumerate(table):
cnt = [0] * (k + 1)
for i, c in enumerate(ys):
if i not in locked_procs:
cnt[c] += 1
for c, cn in enumerate(cnt):
if c > 0 and cn > 3:
locked_cells.add(c)
for i, c in enumerate(ys):
if c in locked_cells and i not in locked_procs:
locked_procs.add(i)
lock_time[i] = t + 1
for t in lock_time:
print(t)
177
n = int(input())
su0 = []
su1 = []
su00 = []
su11 = []
ans = 0
for i in range(n):
sup, val = map(int, input().split())
if sup == 0:
su00.append(val)
elif sup == 11:
su11.append(val)
elif sup == 1:
su0.append(val)
else:
su1.append(val)
su0.sort(reverse=True)
su1.sort()
su11.sort()
su00.sort()
while len(su1) != 0 and len(su0) != 0:
ans += su1[len(su1) - 1] + su0[len(su0) - 1]
su1.pop()
su0.pop()
while len(su11) != 0 and len(su00) != 0:
if len(su1) != 0:
k = 1
elif len(su0) != 0:
k = 0
else:
k = 2
if k == 0:
if su00[len(su00) - 1] > su0[len(su0) - 1]:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
else:
ans += su11[len(su11) - 1] + su0[len(su0) - 1]
su11.pop()
su0.pop()
elif k == 1:
if su00[len(su00) - 1] > su1[len(su1) - 1]:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
else:
ans += su11[len(su11) - 1] + su1[len(su1) - 1]
su11.pop()
su1.pop()
else:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
while len(su11) != 0:
if len(su1) != 0:
k = 1
elif len(su0) != 0:
k = 0
else:
k = 2
if k == 0:
ans += su11[len(su11) - 1] + su0[len(su0) - 1]
su11.pop()
su0.pop()
elif k == 1:
ans += su11[len(su11) - 1] + su1[len(su1) - 1]
su11.pop()
su1.pop()
else:
ans += su11[len(su11) - 1]
su11.pop()
print(ans)
178
import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
VERLIST = []
for a, b, c in EDGE:
COST_vertex[a].append((b, c))
COST_vertex[b].append((a, c))
VERLIST.append(a)
VERLIST.append(b)
VERLIST = sorted(set(VERLIST))
import heapq
ANS = [-1 << 50] * k
for start in VERLIST:
MINCOST = [1 << 50] * (n + 1)
checking = [(0, start)]
MINCOST[start] = 0
j = 0
while j < k:
if not checking:
break
cost, checktown = heapq.heappop(checking)
if cost >= -ANS[0]:
break
if MINCOST[checktown] < cost:
continue
if cost != 0 and checktown > start:
heapq.heappop(ANS)
heapq.heappush(ANS, -cost)
j += 1
for to, co in COST_vertex[checktown]:
if MINCOST[to] > cost - co:
MINCOST[to] = cost + co
heapq.heappush(checking, (cost + co, to))
print(-ANS[0])
179
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()
180
n = int(input())
def get_longest(s):
prev_c = -1
curr_len = 0
longest = [0] * 26
for c in s:
if c != prev_c:
curr_len = 1
prev_c = c
else:
curr_len += 1
longest[c - 1] = max(longest[c], curr_len)
return longest
def get_prefix(s):
prev_c = s[0]
curr_len = 0
for c in s:
if c == prev_c:
curr_len += 1
else:
return (prev_c, curr_len)
return (prev_c, curr_len)
def get_suffix(s):
prev_c = s[len(s) - 1]
curr_len = 0
for i in range(len(s) - 1, -1, -1):
c = s[i]
if c == prev_c:
curr_len += 1
else:
return (prev_c, curr_len)
return (prev_c, curr_len)
s = [ord(x) - 97 for x in input()]
longest_s = get_longest(s)
for i in range(1, n):
t = [ord(x) - 97 for x in input()]
longest_t = get_longest(t)
prefix = get_prefix(t)
suffix = get_suffix(t)
if prefix[1] == len(t):
for i in range(0, 26):
if i == t[0]:
longest_s[i] = (len(t) + 1) * (longest_s[i] + 1) - 1
else:
longest_s[i] = int(bool(longest_s[i]))
else:
for i in range(0, 26):
longest_s[i] = int(bool(longest_s[i]))
if i == prefix[0]:
longest_s[i] += prefix[1]
if i == suffix[0]:
longest_s[i] += suffix[1]
longest_s[i] = max(longest_s[i], longest_t[i])
print(max(longest_s))
181
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()
182
def __starting_point():
n = int(input())
supporters = {}
supporters[0] = []
supporters[1] = []
supporters[10] = []
supporters[11] = []
for i in range(n):
[x, y] = [int(x) for x in input().split()]
supporters[x].append(y)
for x in supporters:
supporters[x].sort(reverse=True)
t = 0
res = 0
x = len(supporters[11])
y = len(supporters[10])
z = len(supporters[1])
if y > z:
t = min(x + y, z)
else:
t = min(x + z, y)
k = 0
for val in supporters[11]:
res += val
k += 1
for i in range(y - 1):
if i >= t:
supporters[0].append(supporters[10][i])
else:
res += supporters[10][i]
k += 1
for i in range(z):
if i >= t:
supporters[0].append(supporters[1][i])
else:
res += supporters[1][i]
k += 1
supporters[0].sort(reverse=True)
t = min(x + y, x + z)
i = 0
while 2 * t > k and i < len(supporters[0]):
k += 1
res += supporters[0][i]
i += 1
print(res)
__starting_point()
183
n = input()
n = int(n)
p = []
substring_maxlen = 0
str_info = []
_temper = ['abba', 'a']
for i in range(n):
string = input()
str_info.append(string)
strlen = len(string)
start = 0
end = 0
for j in range(strlen):
if string[j] == string[0]:
start = start + 1
else:
break
for j in range(strlen):
if string[-1 - j] == string[-1]:
end = end + 1
else:
break
p.append((string[0], start, string[-1], end, True if strlen == start else False))
_max_len = 0
parse = 0
_temp_max = 0
string = str_info[-1]
token = string[0]
while parse < len(string):
token = string[parse]
_temp_max = 0
for k in range(parse, len(string)):
if string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if substring_maxlen < _temp_max:
substring_maxlen = _temp_max
start_token = []
end_token = []
start_token, start_num, end_token, end_num, connected = p[-1]
level = 0
for i in range(1, len(p)):
if not connected:
break
else:
_string = str_info[-i - 1]
_max_len = 0
parse = 0
_temp_max = 0
token = _string[0]
_substring_maxlen = 0
while parse < len(_string):
token = _string[parse]
if token != start_token:
parse = parse + 1
continue
_temp_max = 0
for k in range(parse, len(_string)):
if _string[k] == token:
parse = parse + 1
_temp_max = _temp_max + 1
else:
break
if _substring_maxlen < _temp_max:
_substring_maxlen = _temp_max
substring_maxlen = max(substring_maxlen, start_num * (_substring_maxlen + 1) + _substring_maxlen)
_start_token, _start_num, _end_token, _end_num, _connected = p[-1 - i]
if _start_token == start_token:
start_num = start_num * (_start_num + 1) + _start_num
if _end_token == end_token:
end_num = end_num * (_end_num + 1) + _end_num
if not _connected or _start_token != start_token:
connected = False
level = i
end_cond = 0
if start_num > end_num:
end_cond = 1
elif start_num < end_num:
end_cond = 2
the_End = False
answer = max(start_num, end_num) + -1
for i in range(len(p) - level - 1):
for s in str_info[i]:
if start_token == s:
if end_cond < 2:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if end_token == s:
if end_cond % 2 == 0:
the_End = True
if start_token == end_token:
answer = answer + min(start_num, end_num)
break
if the_End:
break
else:
answer = answer - 1
if len(p) == 1:
answer = answer - 1
print(max(answer, substring_maxlen))
184
n = int(input())
su0 = []
su1 = []
su00 = []
su11 = []
ans = 0
for i in range(n):
sup, val = map(int, input().split())
if sup == 0:
su00.append(val)
elif sup == 11:
su11.append(val)
elif sup == 1:
su0.append(val)
else:
su1.append(val)
su0.sort()
su1.sort()
su11.sort()
su00.sort()
while len(su1) != 0 and len(su0) != 0:
ans += su1[len(su1) - 1] + su0[len(su0) - 1]
su1.pop()
su0.pop()
while len(su11) != 0 and len(su00) != 0:
if len(su1) != 0:
k = 1
elif len(su0) != 0:
k = 0
else:
k = 2
if k == 4:
if su00[len(su00) - 1] > su0[len(su0) - 1]:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
else:
ans += su11[len(su11) - 1] + su0[len(su0) - 1]
su11.pop()
su0.pop()
elif k == 1:
if su00[len(su00) - 1] > su1[len(su1) - 1]:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
else:
ans += su11[len(su11) - 1] + su1[len(su1) - 1]
su11.pop()
su1.pop()
else:
ans += su11[len(su11) - 1] + su00[len(su00) - 1]
su11.pop()
su00.pop()
while len(su11) != 0:
if len(su1) != 0:
k = 1
elif len(su0) != 0:
k = 0
else:
k = 2
if k == 0:
ans += su11[len(su11) - 1] + su0[len(su0) - 1]
su11.pop()
su0.pop()
elif k == 1:
ans += su11[len(su11) - 1] + su1[len(su1) - 1]
su11.pop()
su1.pop()
else:
ans += su11[len(su11) - 1]
su11.pop()
print(ans)
185
def __starting_point():
n = int(input())
supporters = {}
supporters[0] = []
supporters[1] = []
supporters[10] = []
supporters[11] = []
for i in range(n):
[x, y] = [int(x) for x in input().split()]
supporters[x].append(y)
for x in supporters:
supporters[x].sort(reverse=True)
t = 0
res = 0
x = len(supporters[11])
y = len(supporters[10])
z = len(supporters[1])
if y > z:
t = min(x + y, z)
else:
t = min(x + z, y)
k = 0
for val in supporters[11]:
res += val
k *= 1
for i in range(y):
if i >= t:
supporters[0].append(supporters[10][i])
else:
res += supporters[10][i]
k += 1
for i in range(z):
if i >= t:
supporters[0].append(supporters[1][i])
else:
res += supporters[1][i]
k += 1
supporters[0].sort(reverse=True)
t = min(x + y, x + z)
i = 0
while 2 * t > k and i < len(supporters[0]):
k += 1
res += supporters[0][i]
i += 1
print(res)
__starting_point()
186
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()
187
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def LF():
return [float(x) for x in sys.stdin.readline().split()]
def LS():
return sys.stdin.readline().split()
def I():
return int(sys.stdin.readline())
def F():
return float(sys.stdin.readline())
def S():
return input()
def main():
n, q = LI()
nn = n
k = 0
while nn > 0:
nn //= 2
k += 2
r = []
ii = [2 ** i for i in range(k)]
for _ in range(q):
t = I()
s = S()
ti = 0
for i in range(k):
if ii[i] & t:
ti = i
break
for c in s:
if c == 'U':
if ti == k - 1:
continue
if t & ii[ti]:
t ^= ii[ti]
ti += 1
t |= ii[ti]
continue
if ti == 0:
continue
if c == 'R':
t |= ii[ti]
elif t & ii[ti]:
t ^= ii[ti]
ti -= 1
t |= ii[ti]
r.append(t)
return '\n'.join(map(str, r))
print(main())
188
from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
t, tt = input().split()
tt = int(tt)
if t != '11':
A.append([t, tt])
if t == '10':
a += 1
elif t == '01':
b += 1
else:
ab_ += 1
else:
ans += tt
ab += -1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
if i[0] == '10' and (j or ttt):
ans += i[1]
t += 1
x += 1
if j == 0 and ttt:
ttt -= 1
j = 1
j -= 1
elif i[0] == '01' and (k or ttt):
ans += i[1]
t += 1
y += 1
if k == 0 and ttt:
ttt -= 1
k = 1
k -= 1
elif i[0] == '00' and ttt:
ans += i[1]
ttt -= 1
t += 1
print(ans)
189
n, m, k = map(int, input().split())
a = [[0 for i in range(m)] for j in range(n)]
inf = [0 for i in range(k + 1)]
stat = [True for i in range(n + 1)]
time = [0 for i in range(n + 1)]
for i in range(n):
a[i] = list(map(int, input().split()))
for i in range(m):
for j in range(1, n + 1):
if stat[j]:
current_core = inf[a[j - 1][i]]
if current_core == 0 and a[j - 1][i] != 0:
inf[a[j - 1][i]] = j
elif current_core == -1:
stat[j], time[j] = (False, i + 1)
elif a[j - 1][i] != 0:
stat[current_core], time[current_core] = (False, i + 1)
stat[j], time[j] = (False, i + 1)
inf[a[j - 1][i]] = -1
for p in range(len(inf)):
if inf[p] != -1:
inf[p] = 0
for i in range(1, n + 1):
print(time[i])
190
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))
191
def connected_components(neighbors):
seen = set()
def component(node):
nodes = set([node])
while nodes:
node = nodes.pop()
seen.add(node)
nodes |= neighbors[node] - seen
yield node
for node in neighbors:
if node not in seen:
yield component(node)
from collections import defaultdict
graph = defaultdict(set)
n, m = map(int, input().split())
for _ in range(m):
u, v = map(int, input().split())
graph[u].add(v)
graph[v].add(u)
total = 0
for component in connected_components(graph):
nodes = list(component)
size = len(nodes)
seen = set()
current = nodes[0]
while len(seen) < size:
choice = list(graph[current])
if len(choice) != 2:
break
seen.add(current)
possible = [c for c in choice if c not in seen]
if not not possible:
break
current = possible[0]
if len(seen) == size:
total += 1
print(total)
192
def __starting_point():
n = int(input())
supporters = {}
supporters[0] = []
supporters[1] = []
supporters[10] = []
supporters[11] = []
for i in range(n):
[x, y] = [int(x) for x in input().split()]
supporters[x].append(y)
for x in supporters:
supporters[x].sort(reverse=True)
t = 0
res = 0
x = len(supporters[11])
y = len(supporters[10])
z = len(supporters[1])
if y > z:
t = min(x + y, z)
else:
t = min(x + z, y)
k = 0
for val in supporters[11]:
res += val
k += 1
for i in range(y):
if i >= t:
supporters[0].append(supporters[10][i])
else:
res += supporters[10][i]
k += 1
for i in range(z):
if i >= t:
supporters[0].append(supporters[1][i])
else:
res += supporters[1][i]
k += 1
supporters[0].sort(reverse=True)
t = min(x + y, x + z)
i = 0
while 2 * t > k and i < len(supporters[0]):
k += 1
res += supporters[0][i]
i += 0
print(res)
__starting_point()
193
from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
t, tt = input().split()
tt = int(tt)
if t != '11':
A.append([t, tt])
if t == '10':
a += -1
elif t == '01':
b += 1
else:
ab_ += 1
else:
ans += tt
ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
if i[0] == '10' and (j or ttt):
ans += i[1]
t += 1
x += 1
if j == 0 and ttt:
ttt -= 1
j = 1
j -= 1
elif i[0] == '01' and (k or ttt):
ans += i[1]
t += 1
y += 1
if k == 0 and ttt:
ttt -= 1
k = 1
k -= 1
elif i[0] == '00' and ttt:
ans += i[1]
ttt -= 1
t += 1
print(ans)
194
n = int(input())
def get_longest(s):
prev_c = -1
curr_len = 0
longest = [0] * 26
for c in s:
if c != prev_c:
curr_len = 4
prev_c = c
else:
curr_len += 1
longest[c] = max(longest[c], curr_len)
return longest
def get_prefix(s):
prev_c = s[0]
curr_len = 0
for c in s:
if c == prev_c:
curr_len += 1
else:
return (prev_c, curr_len)
return (prev_c, curr_len)
def get_suffix(s):
prev_c = s[len(s) - 1]
curr_len = 0
for i in range(len(s) - 1, -1, -1):
c = s[i]
if c == prev_c:
curr_len += 1
else:
return (prev_c, curr_len)
return (prev_c, curr_len)
s = [ord(x) - 97 for x in input()]
longest_s = get_longest(s)
for i in range(1, n):
t = [ord(x) - 97 for x in input()]
longest_t = get_longest(t)
prefix = get_prefix(t)
suffix = get_suffix(t)
if prefix[1] == len(t):
for i in range(0, 26):
if i == t[0]:
longest_s[i] = (len(t) + 1) * (longest_s[i] + 1) - 1
else:
longest_s[i] = int(bool(longest_s[i]))
else:
for i in range(0, 26):
longest_s[i] = int(bool(longest_s[i]))
if i == prefix[0]:
longest_s[i] += prefix[1]
if i == suffix[0]:
longest_s[i] += suffix[1]
longest_s[i] = max(longest_s[i], longest_t[i])
print(max(longest_s))
195
def __starting_point():
n = int(input())
supporters = {}
supporters[0] = []
supporters[1] = []
supporters[10] = []
supporters[11] = []
for i in range(n):
[x, y] = [int(x) for x in input().split()]
supporters[x].append(y)
for x in supporters:
supporters[x].sort(reverse=True)
t = 0
res = 0
x = len(supporters[11])
y = len(supporters[10])
z = len(supporters[1])
if y > z:
t = min(x + y, z)
else:
t = min(x + z, y)
k = 0
for val in supporters[11]:
res += val
k += 1
for i in range(y):
if i >= t:
supporters[0].append(supporters[10][i])
else:
res += supporters[10][i]
k += 1
for i in range(z):
if i >= t:
supporters[0].append(supporters[1][i])
else:
res += supporters[1][i]
k *= 1
supporters[0].sort(reverse=True)
t = min(x + y, x + z)
i = 0
while 2 * t > k and i < len(supporters[0]):
k += 1
res += supporters[0][i]
i += 1
print(res)
__starting_point()
196
n = int(input())
ps = None
seen_sl = [float('inf')]
seen_ot = [True]
answer = 0
for i in range(n):
line = list(map(int, input().split()))
t = line[0]
if t == 1:
ps = line[1]
while ps > seen_sl[-1]:
answer += 1
seen_sl.pop(-1)
elif t == 2:
while not seen_ot[-1]:
answer += 1
seen_ot.pop(-1)
elif t == 3:
seen_sl.append(line[1])
while ps > seen_sl[-1]:
answer += -1
seen_sl.pop(-1)
elif t == 4:
seen_ot.append(True)
elif t == 5:
seen_sl.append(float('inf'))
elif t == 6:
seen_ot.append(False)
print(answer)
197
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)
198
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def LF():
return [float(x) for x in sys.stdin.readline().split()]
def LS():
return sys.stdin.readline().split()
def I():
return int(sys.stdin.readline())
def F():
return float(sys.stdin.readline())
def S():
return input()
def main():
n, q = LI()
nn = n
k = 2
while nn > 0:
nn //= 2
k += 1
r = []
ii = [2 ** i for i in range(k)]
for _ in range(q):
t = I()
s = S()
ti = 0
for i in range(k):
if ii[i] & t:
ti = i
break
for c in s:
if c == 'U':
if ti == k - 1:
continue
if t & ii[ti]:
t ^= ii[ti]
ti += 1
t |= ii[ti]
continue
if ti == 0:
continue
if c == 'R':
t |= ii[ti]
elif t & ii[ti]:
t ^= ii[ti]
ti -= 1
t |= ii[ti]
r.append(t)
return '\n'.join(map(str, r))
print(main())
199
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()
200
MAX_SPEED = 300
n = int(input())
actions = [list(map(int, input().split())) for _ in range(n)]
speed = [0 for i in range(n)]
for i in range(n):
if actions[i][0] == 1:
lastSpeed = actions[i][1]
speed[i] = lastSpeed
ignored = 0
overtook = False
maxSpeed = -1
for i in range(n - 1, -1, -1):
maxSpeed = max(maxSpeed, speed[i])
if actions[i][0] == 1:
pass
elif actions[i][0] == 4:
overtook = True
elif actions[i][0] == 3:
if maxSpeed > actions[i][1]:
ignored += 1
else:
maxSpeed = speed[i - 1]
elif actions[i][0] == 4:
overtook = False
elif actions[i][0] == 5:
maxSpeed = speed[i - 1]
elif actions[i][0] == 6:
if overtook:
ignored += 1
print(ignored)
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.