|
Download tasks/equivalent-program-pair-search/contexts/sample-00023.md from StringNLP/longharness: direct link, hf CLI and curl.
- Browser
- Download file 247 kB
-
https://huggingface.co/datasets/StringNLP/longharness/resolve/main/tasks/equivalent-program-pair-search/contexts/sample-00023.md
- Command line
-
hf download hf://datasets/StringNLP/longharness/tasks/equivalent-program-pair-search/contexts/sample-00023.md
-
curl -L -o sample-00023.md https://huggingface.co/datasets/StringNLP/longharness/resolve/main/tasks/equivalent-program-pair-search/contexts/sample-00023.md
247 kB
001
from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 10
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
t, dx, dy = stdin.readline().split()
dx = int(dx)
dy = int(dy)
if dx == x:
if dy > y:
if ud > dy - y:
ud = dy - y
u = t
elif dd > y - dy:
dd = y - dy
d = t
if dy == y:
if dx > x:
if rd > dx - x:
rd = dx - x
r = t
elif ld > x - dx:
ld = x - dx
l = t
if dx - x == dy - y:
if dy > y:
if urd > dy - y:
urd = dy - y
ur = t
elif dld > y - dy:
dld = y - dy
dl = t
if not -(dx - x) == dy - y:
if dy > y:
if uld > dy - y:
uld = dy - y
ul = t
elif drd > y - dy:
drd = y - dy
dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
print('YES')
else:
print('NO')
002
import sys
fin = sys.stdin
[n, m] = [int(x) for x in fin.readline().split()]
s = [x == '.' for x in fin.readline().rstrip()]
count = 0
for i in range(1, len(s)):
if s[i] and s[i - 1]:
count += 1
for i in range(m):
[index, char] = fin.readline().split()
index = int(index) - 1
if s[index] and char != '.':
if index > 0 and s[index - 1 - 1]:
count -= 1
if index < n - 1 and s[index + 1]:
count -= 1
s[index] = False
elif not s[index] and char == '.':
if index > 0 and s[index - 1]:
count += 1
if index < n - 1 and s[index + 1]:
count += 1
s[index] = True
print(count)
003
from sys import stdin
input = stdin.readline
n, m = list(map(int, input().split()))
s = list(((0, 1)[c == '.'] for c in list(input())))
res = 0
cnt = 0
for k in s:
if k == 1:
cnt += 1
else:
res += max(cnt - 1, 0)
cnt = 0
res += max(0, cnt - 1)
for i in range(m):
x, c = input().split()
x = int(x)
nc = (0, 1)[c == '.']
if s[x - 1] != nc:
diff = 0
if x < n:
if s[int(x)] == 1:
diff += 1
if x > 1:
if s[int(x - 2)] == 1:
diff += 1
if nc == 1:
res += diff
else:
res -= diff
s[x - 1 - 1] = nc
print(res)
004
import collections
import bisect
def f():
n, m = [int(c) for c in input().split()]
s = list(input())
ll = []
start = 0
length = 0
inside = False
cc = 0
for i in range(len(s)):
if s[i] == '.':
if not inside:
inside = True
length += 1
elif inside:
cc -= length - 1
length = 0
inside = False
if inside:
cc += length - 1
res = [0] * m
for i in range(m):
line = input().split()
j = int(line[0]) - 1
c = line[1]
if c == '.' and s[j] == '.' or (c != '.' and s[j] != '.'):
res[i] = cc
else:
e1 = False
e2 = False
if j > 0 and s[j - 1] == '.':
e1 = True
if j < n - 1 and s[j + 1] == '.':
e2 = True
if e1 and e2:
cc += 2 if c == '.' else -2
elif e1 or e2:
cc += 1 if c == '.' else -1
s[j] = c
res[i] = cc
for r in res:
print(r)
f()
005
from sys import stdin
input = stdin.readline
n, m = list(map(int, input().split()))
s = list(((0, 1)[c == '.'] for c in list(input())))
res = 0
cnt = 0
for k in s:
if k == 1:
cnt += 1
else:
res += max(cnt - 1, 0)
cnt = 0
res += max(0, cnt - 1)
for i in range(m):
x, c = input().split()
x = int(x)
nc = (0, 1)[c == '.']
if s[x - 1] != nc:
diff = 0
if x < n:
if s[int(x)] == 1:
diff += 1
if x > 1:
if s[int(x - 2)] == 1:
diff += 1
if nc == -1:
res += diff
else:
res -= diff
s[x - 1] = nc
print(res)
006
import sys
class SegmTree:
def __init__(self, size):
N = 1
while N < size:
N <<= 1
self.N = N
self.tree = [0] * (2 * N)
def modify(self, i, value):
i += self.N
self.tree[i] = value
toXOR = False
while i > 1:
if toXOR:
self.tree[i >> 1] = self.tree[i + 1] ^ self.tree[i ^ 1]
else:
self.tree[i >> 1] = self.tree[i] | self.tree[i ^ 1]
toXOR = not toXOR
i >>= 1
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
st = SegmTree(1 << n)
for i, value in enumerate(a):
st.modify(i, value)
for _ in range(m):
p, b = list(map(int, input().split()))
st.modify(p - 1, b)
print(st.tree[1])
007
from math import log
import sys
def buildTree(arr):
n = len(arr)
tree = [0] * n + arr
for i in range(n - 1, 0, -1):
z = int(log(i, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
else:
tree[i] = tree[2 * i] & tree[2 * i + 1]
elif z % 2 == 0:
tree[i] = tree[2 * i] | tree[2 * i + 1]
else:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
return tree
def updateTree(tree, ind, value, n):
ind += n
tree[ind] = value
while ind > 1:
ind //= 2
z = int(log(ind, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
elif z % 2 == 0:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
return tree
N, m = map(int, sys.stdin.readline().strip().split())
arr = list(map(int, sys.stdin.readline().strip().split()))
tree = buildTree(arr)
for i in range(m):
ind, val = map(int, sys.stdin.readline().strip().split())
tree = updateTree(tree, ind - 1, val, len(arr))
print(tree[1])
008
from collections import Counter
from bisect import bisect, bisect_left
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = Counter(a)
c = sorted(Counter(a).items())
keys = sorted(Counter(a).keys())
m = len(c)
l_cum = [c[0][0] * c[0][1]]
l_cnt = [c[0][1]]
for i in range(1, m):
l_cum.append(l_cum[-1] + c[i][0] * c[i][1])
l_cnt.append(l_cnt[-1] + c[i][1])
r_cum = [0 for _ in range(m)]
r_cum[-1 + 1] = c[-1][0] * c[-1][1]
r_cnt = [0 for _ in range(m)]
r_cnt[-1] = c[-1][1]
for i in range(m - 2, -1, -1):
r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1]
r_cnt[i] = r_cnt[i + 1] + c[i][1]
ans = 10 ** 20
for i in range(m):
c_num = a[keys[i]]
if c_num >= k:
ans = 0
break
if i > 0:
l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1]
l_num = l_cnt[i - 1]
else:
l_res = 10 ** 30
l_num = 0
if i < m - 1:
r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1]
r_num = r_cnt[i + 1]
else:
r_res = 10 ** 30
r_num = 0
if c_num + l_num < k and c_num + r_num < k:
ans = min(ans, l_res + r_res + k - c_num)
elif c_num + l_num < k:
ans = min(ans, r_res + k - c_num)
elif c_num + r_num < k:
ans = min(ans, l_res + k - c_num)
else:
ans = min(ans, min(r_res, l_res) + k - c_num)
print(ans)
009
import sys
sys.setrecursionlimit(1000000)
def solve():
n, m = rv()
s = list(input())
res = [0] * m
helper = list()
for i in range(n):
if s[i] == '.':
if i == 0:
helper.append(1)
elif s[i - 1] == '.':
helper[-1] += 1
else:
helper.append(1)
initval = 0
for val in helper:
initval += val - 1
for query in range(m):
index, replace = input().split()
index = int(index) - 1
if s[index] == '.' and replace == '.' or (s[index] != '.' and replace != '.'):
res[query] = initval
else:
sidedots = 0
if index > 0:
if s[index - 1] == '.':
sidedots += 1
if index < n - 1:
if s[index + 1] == '.':
sidedots += 1
if s[index] == '.':
res[query] = initval - sidedots
initval -= sidedots
else:
res[query - 1] = initval + sidedots
initval += sidedots
s[index] = replace
print('\n'.join(map(str, res)))
def rv():
return list(map(int, input().split()))
def rl(n):
return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544:
sys.stdin = open('test.txt')
solve()
010
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)
011
n = int(input())
temp = input().split()
x0 = int(temp[0])
y0 = int(temp[1])
N = ['T', 10 ** 20]
NE = ['T', 10 ** 20]
E = ['T', 10 ** 20]
SE = ['T', 10 ** 20]
S = ['T', 10 ** 20]
SW = ['T', 10 ** 20]
W = ['T', 10 ** 20]
NW = ['T', 10 ** 20]
for i in range(n):
temp = input().split()
x = int(temp[1])
y = int(temp[2])
if x - x0 == 0 and y - y0 > 0 and (y - y0 < N[1]):
N = [temp[0], y - y0]
elif not (x - x0 == y - y0 and x - x0 > 0 and (x - x0 < NE[1])):
NE = [temp[0], x - x0]
elif y - y0 == 0 and x - x0 > 0 and (x - x0 < E[1]):
E = [temp[0], x - x0]
elif x - x0 == -(y - y0) and x - x0 > 0 and (x - x0 < SE[1]):
SE = [temp[0], x - x0]
elif x - x0 == 0 and y - y0 < 0 and (y0 - y < S[1]):
S = [temp[0], y0 - y]
elif x - x0 == y - y0 and x - x0 < 0 and (x0 - x < SW[1]):
SW = [temp[0], x0 - x]
elif y - y0 == 0 and x - x0 < 0 and (x0 - x < W[1]):
W = [temp[0], x0 - x]
elif x - x0 == -(y - y0) and x - x0 < 0 and (x0 - x < NW[1]):
NW = [temp[0], x0 - x]
if 'R' in [N[0], E[0], S[0], W[0]] or 'B' in [NE[0], SE[0], SW[0], NW[0]]:
print('YES')
elif 'Q' in [N[0], E[0], S[0], W[0], NE[0], SE[0], SW[0], NW[0]]:
print('YES')
else:
print('NO')
012
import sys
nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split()))
meches = list(map(int, sys.stdin.readline().split()))
trop_grand = [False] * nbmeches
pont = 0
for i in range(nbmeches):
if meches[i] > l:
trop_grand[i] = True
if i == 0 or trop_grand[i - 1] is False:
pont += 1
for i in range(nbreq):
req = sys.stdin.readline().split()
if int(req[0]) == 0:
print(pont)
else:
meches[int(req[1]) - 1] += int(req[1])
if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]):
trop_grand[int(req[1]) - 1] = True
if nbmeches == 1:
pont = 1
elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]):
pont += 1
elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]):
pont += 1
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]:
pont = max(0, pont - 1)
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]):
pont += 1
013
import sys
input = sys.stdin.readline
for f in range(int(input())):
n, m = map(int, input().split())
a = [0] * m
b = [0] * m
acop = [0] * m
bcop = [0] * m
for i in range(m):
a[i], b[i] = map(int, input().split())
acop[i] = a[i]
bcop[i] = [b[i], i]
acop.sort(reverse=True)
bcop.sort(reverse=True)
mx = 0
i = 0
su = 0
for j in range(m):
bi = bcop[j][0]
ii = bcop[j][1]
ai = a[ii]
while i < m and acop[i] > bi:
su += acop[i]
i += 1
maxi = ai
if i < n:
maxi += su
if i + 1 < n:
maxi += (n - i - 1) * bi
if ai > bi:
maxi += bi
maxi -= ai
mx = max(maxi, mx)
if n <= m:
sun = 2
for i in range(n):
sun += acop[i]
mx = max(mx, sun)
print(mx)
blank = input()
014
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])
015
n, q, k = list(map(int, input().split(' ')))
a = list(map(int, input().split(' ')))
count = 0
def verify(x):
if x < 0 or x >= n:
return False
return a[x] > k
for i in range(n):
if verify(i):
count += 1
if verify(i - 1):
count -= 1
def cut(i):
if not verify(i):
return 1
result = 1
if verify(i - 1):
result -= 1
if verify(i + 1):
result -= 1
return result
for i in range(q):
line = input()
if line == '0':
print(count)
else:
_, x, y = list(map(int, line.split(' ')))
x -= 1
if not verify(x):
a[x] += y
count += cut(x)
else:
a[x] += y
016
import sys
nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split()))
meches = list(map(int, sys.stdin.readline().split()))
trop_grand = [False] * nbmeches
pont = 0
for i in range(nbmeches):
if meches[i] > l:
trop_grand[i] = True
if i == 0 or trop_grand[i - 1 + 1] is False:
pont += 1
for i in range(nbreq):
req = sys.stdin.readline().split()
if int(req[0]) == 0:
print(pont)
else:
meches[int(req[1]) - 1] += int(req[2])
if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]):
trop_grand[int(req[1]) - 1] = True
if nbmeches == 1:
pont = 1
elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]):
pont += 1
elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]):
pont += 1
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]:
pont = max(0, pont - 1)
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]):
pont += 1
017
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)
018
n, m, l = list(map(int, input().split()))
l += 1
hair = [1] * (n + 1)
other_end = [1] * (n + 1)
i = 1
j = 1
big = 1
res = 1
for a in map(int, input().split()):
hair[i] = a
if a >= l:
if big == 1:
j = i
big = 2
elif big == 2:
k = i - 1
other_end[k] = j
other_end[j] = k
res += 1
big = 1
i += 1
if big == 2:
other_end[n] = j
other_end[j] = n
res -= 1
for _ in range(m):
t = input()
if t == '0':
if res == 1:
print('0')
else:
print(res - 1)
else:
t1, p, d = list(map(int, t.split()))
old = hair[p]
hair[p] += d
if hair[p] >= l > old:
if p == 1 or hair[p - 1] < l:
case_id = 1
else:
case_id = 2
if p != n and hair[p + 1] >= l:
case_id += 2
if case_id == 1:
other_end[p] = p
res += 1
elif case_id == 2:
other_end[p] = other_end[p - 1]
other_end[other_end[p]] = p
elif case_id == 3:
other_end[p] = other_end[p + 1]
other_end[other_end[p]] = p
else:
left_end = other_end[p - 1]
right_end = other_end[p + 1]
other_end[left_end] = right_end
other_end[right_end] = left_end
res -= 1
019
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)
020
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def I():
return int(sys.stdin.readline())
def LS():
return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == '\n':
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
def solve():
n, k = LI()
a = LI()
a.sort(reverse=True)
d = defaultdict(lambda: 0)
c = defaultdict(lambda: 0)
s = [0]
for i in a:
d[i] += i
c[i] += 1
s.append(s[-1] + i)
ans = float('inf')
p = -1
for i in a:
if i == p:
continue
if k <= c[i]:
ans = 0
break
l, r = (bisect.bisect_left(a, i), bisect.bisect_right(a, i))
m = r
if m >= k:
ns = l * (i - 1) - s[l]
su = ns + k - c[i]
if su < ans:
ans = su
m = n - l
if m >= k:
ns = s[n] - s[r] - (n - r) * (i + 1)
su = ns + k - c[i]
if su < ans:
ans = su
ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l]
su = ns + k - c[i]
if su < ans:
ans = su
p = i
print(ans)
return
def __starting_point():
solve()
__starting_point()
021
from collections import Counter
from bisect import bisect, bisect_left
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = Counter(a)
c = sorted(Counter(a).items())
keys = sorted(Counter(a).keys())
m = len(c)
l_cum = [c[0][0] + c[0][1]]
l_cnt = [c[0][1]]
for i in range(1, m):
l_cum.append(l_cum[-1] + c[i][0] * c[i][1])
l_cnt.append(l_cnt[-1] + c[i][1])
r_cum = [0 for _ in range(m)]
r_cum[-1] = c[-1][0] * c[-1][1]
r_cnt = [0 for _ in range(m)]
r_cnt[-1] = c[-1][1]
for i in range(m - 2, -1, -1):
r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1]
r_cnt[i] = r_cnt[i + 1] + c[i][1]
ans = 10 ** 20
for i in range(m):
c_num = a[keys[i]]
if c_num >= k:
ans = 0
break
if i > 0:
l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1]
l_num = l_cnt[i - 1]
else:
l_res = 10 ** 30
l_num = 0
if i < m - 1:
r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1]
r_num = r_cnt[i + 1]
else:
r_res = 10 ** 30
r_num = 0
if c_num + l_num < k and c_num + r_num < k:
ans = min(ans, l_res + r_res + k - c_num)
elif c_num + l_num < k:
ans = min(ans, r_res + k - c_num)
elif c_num + r_num < k:
ans = min(ans, l_res + k - c_num)
else:
ans = min(ans, min(r_res, l_res) + k - c_num)
print(ans)
022
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)
023
n, k = list(map(int, input().split()))
a = sorted(list(map(int, input().split())))
sums, suf, q1 = ([0] * n, [n] * n, n)
for q in range(n - 2, -1, -1):
sums[q] = sums[q + 1]
if a[q] != a[q1 - 1]:
sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1)
q1 = q + 1
suf[q] = q1
ans, sum1, q1 = (sums[0] + k - suf[0] if suf[0] < k else 0, 0, -1)
for q in range(1, n):
if a[q] != a[q1 + 1 + 1]:
sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1)
q1 = q - 1
if suf[q] - q1 - 1 >= k:
ans = 0
break
if k <= suf[q]:
ans = min(ans, sum1 + k - suf[q] + q1 + 1)
if k < n - q1:
ans = min(ans, sums[q] + k - suf[q] + q1 + 1)
ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1)
print(ans)
024
from math import log
import sys
def buildTree(arr):
n = len(arr)
tree = [0] * n + arr
for i in range(n - 1, 0, -1):
z = int(log(i, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
else:
tree[i] = tree[2 * i] | tree[2 * i + 1]
elif z % 2 == 0:
tree[i] = tree[2 * i] | tree[2 * i + 1]
else:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
return tree
def updateTree(tree, ind, value, n):
ind += n
tree[ind] = value
while ind > 1:
ind //= 2
z = int(log(ind, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
elif z % 2 == 0:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
return tree
N, m = map(int, sys.stdin.readline().strip().split())
arr = list(map(int, sys.stdin.readline().strip().split()))
tree = buildTree(arr)
for i in range(m):
ind, val = map(int, sys.stdin.readline().strip().split())
tree = updateTree(tree, ind - 1, val, len(arr))
print(tree[-3])
025
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)
026
__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()
027
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)
028
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)
029
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)
030
import sys
fin = sys.stdin
[n, m] = [int(x) for x in fin.readline().split()]
s = [x == '.' for x in fin.readline().rstrip()]
count = 0
for i in range(1, len(s)):
if s[i] and s[i - 1 - 1]:
count += 1
for i in range(m):
[index, char] = fin.readline().split()
index = int(index) - 1
if s[index] and char != '.':
if index > 0 and s[index - 1]:
count -= 1
if index < n - 1 and s[index + 1]:
count -= 1
s[index] = False
elif not s[index] and char == '.':
if index > 0 and s[index - 1]:
count += 1
if index < n - 1 and s[index + 1]:
count += 1
s[index] = True
print(count)
031
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)
032
from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 10
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
t, dx, dy = stdin.readline().split()
dx = int(dx)
dy = int(dy)
if dx == x:
if dy > y:
if ud > dy - y:
ud = dy - y
u = t
elif dd > y - dy:
dd = y - dy
d = t
if dy == y:
if dx > x:
if rd > dx - x:
rd = dx - x
r = t
elif ld > x - dx:
ld = x - dx
l = t
if dx - x == dy - y:
if not dy > y:
if urd > dy - y:
urd = dy - y
ur = t
elif dld > y - dy:
dld = y - dy
dl = t
if -(dx - x) == dy - y:
if dy > y:
if uld > dy - y:
uld = dy - y
ul = t
elif drd > y - dy:
drd = y - dy
dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
print('YES')
else:
print('NO')
033
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()
034
from sys import stdin
from math import *
line = stdin.readline().rstrip().split()
n = int(line[0])
numbers = list(map(int, stdin.readline().rstrip().split()))
numbers2 = list(map(int, stdin.readline().rstrip().split()))
growRateAccum = 0
topAccum = 0
bottomAccum = 0
accumsB = [0] * n
accumsT = [0] * n
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
accum += numbers[i] * ((n - i) * 2 - 1 - 1)
growRateAccum += numbers[i]
if i < n - 1:
growRateAccum *= numbers2[i + 1]
accum += growRateAccum
accumsB[i] = accum
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
accum += numbers2[i] * ((n - i) * 2 - 1 - 1)
growRateAccum += numbers2[i]
if i < n - 1:
growRateAccum += numbers[i + 1]
accum += growRateAccum
accumsT[i] = accum
cMax = 0
currAccum = 0
growRateAccum = sum(numbers[1:]) + sum(numbers2[1:])
for i in range(n):
if i % 2 == 0:
cMax = max(cMax, currAccum + accumsT[i])
else:
cMax = max(cMax, currAccum + accumsB[i])
if i < n - 1:
if i % 2 == 0:
currAccum += numbers2[i] + growRateAccum * 2
else:
currAccum += numbers[i] + growRateAccum * 2
growRateAccum -= numbers[i + 1]
growRateAccum -= numbers2[i + 1]
print(cMax)
035
from bisect import bisect_left
t = int(input())
for case in range(t):
n, m = list(map(int, input().split()))
ab = [list(map(int, input().split())) for _ in range(m)]
aa = [e for e, _ in ab]
aa.sort()
acc = [0] * (m + 1)
for i in range(m, 1, -1):
acc[i - 1] = acc[i] + aa[i - 1]
if n > m:
ans = 0
else:
ans = sum(aa[-n:])
for a, b in ab:
i = bisect_left(aa, b)
cnt = min(m - i, n)
sm = acc[m - cnt]
sm += b * (n - cnt)
if a < b:
sm -= b
sm += a
ans = max(ans, sm)
print(ans)
if case != t - 1:
input()
036
import collections
import bisect
def f():
n, m = [int(c) for c in input().split()]
s = list(input())
ll = []
start = 0
length = 0
inside = False
cc = 0
for i in range(len(s)):
if s[i] == '.':
if not inside:
inside = True
length += 1
elif inside:
cc += length - 1
length = 0
inside = False
if inside:
cc += length - 1
res = [0] * m
for i in range(m):
line = input().split()
j = int(line[0]) - 1
c = line[1]
if c == '.' and s[j] == '.' or (c != '.' and s[j] != '.'):
res[i] = cc
else:
e1 = False
e2 = False
if j > 0 and s[j - 1] == '.':
e1 = True
if j < n - 1 and s[j + 1] == '.':
e2 = True
if e1 and e2:
cc -= 2 if c == '.' else -2
elif e1 or e2:
cc += 1 if c == '.' else -1
s[j] = c
res[i] = cc
for r in res:
print(r)
f()
037
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)
038
from sys import stdin
from math import *
line = stdin.readline().rstrip().split()
n = int(line[0])
numbers = list(map(int, stdin.readline().rstrip().split()))
numbers2 = list(map(int, stdin.readline().rstrip().split()))
growRateAccum = 0
topAccum = 0
bottomAccum = 0
accumsB = [0] * n
accumsT = [0] * n
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
accum *= numbers[i] * ((n - i) * 2 - 1 - 1)
growRateAccum += numbers[i]
if i < n - 1:
growRateAccum += numbers2[i + 1]
accum += growRateAccum
accumsB[i] = accum
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
accum += numbers2[i] * ((n - i) * 2 - 1 - 1)
growRateAccum += numbers2[i]
if i < n - 1:
growRateAccum += numbers[i + 1]
accum += growRateAccum
accumsT[i] = accum
cMax = 0
currAccum = 0
growRateAccum = sum(numbers[1:]) + sum(numbers2[1:])
for i in range(n):
if i % 2 == 0:
cMax = max(cMax, currAccum + accumsT[i])
else:
cMax = max(cMax, currAccum + accumsB[i])
if i < n - 1:
if i % 2 == 0:
currAccum += numbers2[i] + growRateAccum * 2
else:
currAccum += numbers[i] + growRateAccum * 2
growRateAccum -= numbers[i + 1]
growRateAccum -= numbers2[i + 1]
print(cMax)
039
import sys
input = sys.stdin.readline
for f in range(int(input())):
n, m = map(int, input().split())
a = [0] * m
b = [0] * m
acop = [0] * m
bcop = [0] * m
for i in range(m):
a[i], b[i] = map(int, input().split())
acop[i] = a[i]
bcop[i] = [b[i], i]
acop.sort(reverse=True)
bcop.sort(reverse=True)
mx = 0
i = 0
su = 0
for j in range(m):
bi = bcop[j][0]
ii = bcop[j][1]
ai = a[ii]
while i < m and acop[i] > bi:
su += acop[i]
i += 1
maxi = ai
if i < n:
maxi += su
if i + 1 < n:
maxi += (n - i - 1) * bi
if ai > bi:
maxi += bi
maxi -= ai
mx = max(maxi, mx)
if n <= m:
sun = 1
for i in range(n):
sun += acop[i]
mx = max(mx, sun)
print(mx)
blank = input()
040
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])
041
from collections import Counter
from bisect import bisect, bisect_left
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = Counter(a)
c = sorted(Counter(a).items())
keys = sorted(Counter(a).keys(), reverse=True)
m = len(c)
l_cum = [c[0][0] * c[0][1]]
l_cnt = [c[0][1]]
for i in range(1, m):
l_cum.append(l_cum[-1] + c[i][0] * c[i][1])
l_cnt.append(l_cnt[-1] + c[i][1])
r_cum = [0 for _ in range(m)]
r_cum[-1] = c[-1][0] * c[-1][1]
r_cnt = [0 for _ in range(m)]
r_cnt[-1] = c[-1][1]
for i in range(m - 2, -1, -1):
r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1]
r_cnt[i] = r_cnt[i + 1] + c[i][1]
ans = 10 ** 20
for i in range(m):
c_num = a[keys[i]]
if c_num >= k:
ans = 0
break
if i > 0:
l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1]
l_num = l_cnt[i - 1]
else:
l_res = 10 ** 30
l_num = 0
if i < m - 1:
r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1]
r_num = r_cnt[i + 1]
else:
r_res = 10 ** 30
r_num = 0
if c_num + l_num < k and c_num + r_num < k:
ans = min(ans, l_res + r_res + k - c_num)
elif c_num + l_num < k:
ans = min(ans, r_res + k - c_num)
elif c_num + r_num < k:
ans = min(ans, l_res + k - c_num)
else:
ans = min(ans, min(r_res, l_res) + k - c_num)
print(ans)
042
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
curl_ud_weights = [0] * n
curl_du_weights = [0] * n
sums = [0] * n
sums[n - 1] = a[n - 1] + b[n - 1]
curl_ud_weights[n - 1] = b[n - 1]
curl_du_weights[n - 1] = a[n - 1]
for i in range(n - 2, -1, -1):
sums[i] = sums[i + 1] + (a[i] + b[i])
remain = n * 2 - i * 2 - 1
curl_ud_weights[i] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i]
curl_du_weights[i + 1] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i]
snake_weight = 0
max_weight = 0
current_weight = -1
for t in range(0, 2 * n, 2):
remain = t % 4
if remain == 0:
current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight
snake_weight += a[t // 2] * t + b[t // 2] * (t + 1)
elif remain == 2:
current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight
snake_weight += b[t // 2] * t + a[t // 2] * (t + 1)
if current_weight > max_weight:
max_weight = current_weight
print(max_weight)
'\n3\n0 1 0\n0 0 0\n'
043
from collections import Counter
import sys
from itertools import accumulate
def go():
n, k = list(map(int, input().split()))
a = sorted(map(int, input().split()))
c = Counter(a)
if max(c.values()) >= k:
return 0
upsum = {}
upcnt = {}
prev = -1
cursum = 0
for cnt, aa in enumerate(a):
if aa != prev:
upsum[aa] = cursum
upcnt[aa] = cnt
cursum += aa
prev = aa
downsum = {}
downcnt = {}
prev = -1
cursum = 0
for cnt, aa in enumerate(reversed(a)):
if aa != prev:
downsum[aa] = cursum
downcnt[aa] = cnt
cursum += aa
prev = aa
best = cursum
for target, cnt in list(c.items()):
need = k - cnt
if upcnt[target] >= need:
best = min(best, (target - 1) * upcnt[target] - upsum[target] + need)
if downcnt[target] >= need:
best = min(best, downsum[target] - (target + -1) * downcnt[target] + need)
best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + 1) * downcnt[target] + need)
return best
t = 1
for _ in range(t):
print(go())
044
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()
045
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)
046
n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
for i in range(2):
sum_up[i][n - 1 - 1] = a[i][n - 1]
pref_up[i][n - 1] = a[i][n - 1]
pref_down[i][n - 1] = a[i][n - 1]
for j in range(n - 2, -1, -1):
sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
zig = [[0 for i in range(n)] for j in range(2)]
for j in range(n):
for i in range(2):
if j % 2 == 0:
if i == 0:
zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
else:
zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
elif i == 0:
zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
else:
zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
ans = -1e+18
for j in range(n):
if j == 0:
ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
elif j == n - 1:
ans = max(ans, zig[1 - j % 2][n - 1])
elif j % 2 == 1:
ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
else:
ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
print(ans)
else:
print(a[1][0])
047
from sys import stdin, stderr
import random
import cProfile
def readInts():
return map(int, stdin.readline().strip().split())
def print_err(*args, **kwargs):
print(*args, file=stderr, **kwargs)
def solve(vs):
return None
def generate_tree(n, ns):
out = [0 for _ in range(2 ** (n + 1))]
def gt(nix, left, right, op):
if left + 1 == right:
out[nix] = ns[left]
return out[nix]
mid = (left + right) // 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = gt(nL, left, mid, not op)
vR = gt(nR, mid, right, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
out[nix] = v
return v
gt(0, 0, 2 ** n, n % 2 == 0)
return out
def alter_tree2(n, t, p, b):
def at(nix, width, offp, op):
if width == 1:
t[nix] = b
return b
width //= 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = t[nL]
vR = t[nR]
if offp >= width:
vR = at(nR, width, offp - width, not op)
else:
vL = at(nL, width, offp, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
t[nix] = v
return v
at(0, 2 ** n, p, n % 2 == 0)
def alter_tree(n, t, p, b):
width = 2 ** n
s = []
nix = 0
op = n % 2 == 0
while width > 1:
width //= 2
if p >= width:
nix2 = 2 * nix + 2
s.append((nix, nix2 - 1))
p -= width
else:
nix2 = 2 * nix + 1
s.append((nix, nix2 + 1))
nix = nix2
op = not op
t[nix] = b
v = b
while s:
nix, nixO = s.pop()
if op:
v |= t[nixO]
else:
v ^= t[nixO]
t[nix] = v
op = not op
return
def run():
n, m = readInts()
axs = list(readInts())
t = generate_tree(n, axs)
for _ in range(m):
p, b = readInts()
alter_tree(n, t, p - 1, b)
print(t[0])
def test():
n = 17
ns = []
vs100 = list(range(100))
for _ in range(2 ** 17):
ns.append(random.choice(vs100))
t = generate_tree(n, ns)
t2 = generate_tree(n, ns)
for _ in range(100000):
v1 = random.choice(vs100)
v2 = random.choice(vs100)
alter_tree(n, t, v1, v2)
alter_tree2(n, t2, v1, v2)
print(all(map(lambda x: x[0] == x[1], zip(t, t2))))
print(t[0] == t2[0])
run()
048
from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 8
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
t, dx, dy = stdin.readline().split()
dx = int(dx)
dy = int(dy)
if dx == x:
if dy > y:
if ud > dy - y:
ud = dy - y
u = t
elif dd > y - dy:
dd = y - dy
d = t
if dy == y:
if dx > x:
if rd > dx - x:
rd = dx - x
r = t
elif ld > x - dx:
ld = x - dx
l = t
if dx - x == dy - y:
if dy > y:
if urd > dy - y:
urd = dy - y
ur = t
elif dld > y - dy:
dld = y - dy
dl = t
if -(dx - x) == dy - y:
if dy > y:
if uld > dy - y:
uld = dy - y
ul = t
elif drd > y - dy:
drd = y - dy
dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
print('YES')
else:
print('NO')
049
n = int(input())
temp = input().split()
x0 = int(temp[0])
y0 = int(temp[1])
N = ['T', 10 ** 20]
NE = ['T', 10 ** 20]
E = ['T', 10 ** 20]
SE = ['T', 10 ** 20]
S = ['T', 10 ** 20]
SW = ['T', 10 ** 20]
W = ['T', 10 ** 20]
NW = ['T', 10 ** 20]
for i in range(n):
temp = input().split()
x = int(temp[1])
y = int(temp[2])
if y - y0 > 0 and y - y0 < N[1]:
N = [temp[0], y - y0]
elif x - x0 == y - y0 and x - x0 > 0 and (x - x0 < NE[1]):
NE = [temp[0], x - x0]
elif y - y0 == 0 and x - x0 > 0 and (x - x0 < E[1]):
E = [temp[0], x - x0]
elif x - x0 == -(y - y0) and x - x0 > 0 and (x - x0 < SE[1]):
SE = [temp[0], x - x0]
elif x - x0 == 0 and y - y0 < 0 and (y0 - y < S[1]):
S = [temp[0], y0 - y]
elif x - x0 == y - y0 and x - x0 < 0 and (x0 - x < SW[1]):
SW = [temp[0], x0 - x]
elif y - y0 == 0 and x - x0 < 0 and (x0 - x < W[1]):
W = [temp[0], x0 - x]
elif x - x0 == -(y - y0) and x - x0 < 0 and (x0 - x < NW[1]):
NW = [temp[0], x0 - x]
if 'R' in [N[0], E[0], S[0], W[0]] or 'B' in [NE[0], SE[0], SW[0], NW[0]]:
print('YES')
elif 'Q' in [N[0], E[0], S[0], W[0], NE[0], SE[0], SW[0], NW[0]]:
print('YES')
else:
print('NO')
050
import sys
input = sys.stdin.readline
for f in range(int(input())):
n, m = map(int, input().split())
a = [0] * m
b = [0] * m
acop = [0] * m
bcop = [0] * m
for i in range(m):
a[i], b[i] = map(int, input().split())
acop[i] = a[i]
bcop[i] = [b[i], i]
acop.sort(reverse=True)
bcop.sort(reverse=True)
mx = 0
i = 0
su = 0
for j in range(m):
bi = bcop[j][0]
ii = bcop[j][1]
ai = a[ii]
while i < m and acop[i] > bi:
su += acop[i]
i += 1
maxi = ai
if i < n:
maxi += su
if i + 1 < n:
maxi += (n - i - 1) * bi
if ai > bi:
maxi += bi
maxi -= ai
mx = max(maxi, mx)
if n <= m:
sun = 0
for i in range(n):
sun += acop[i]
mx = max(mx, sun)
print(mx)
blank = input()
051
from sys import stdin
input = stdin.readline
n, m = list(map(int, input().split()))
s = list(((0, 1)[c == '.'] for c in list(input())))
res = 0
cnt = 0
for k in s:
if k == 1:
cnt += 1
else:
res += max(cnt - 1, 0)
cnt = 0
res += max(0, cnt - 1)
for i in range(m):
x, c = input().split()
x = int(x)
nc = (0, 1)[c == '.']
if s[x - 1 + 1] != nc:
diff = 0
if x < n:
if s[int(x)] == 1:
diff += 1
if x > 1:
if s[int(x - 2)] == 1:
diff += 1
if nc == 1:
res += diff
else:
res -= diff
s[x - 1] = nc
print(res)
052
import sys
sys.setrecursionlimit(1000000)
def solve():
n, m = rv()
s = list(input())
res = [0] * m
helper = list()
for i in range(n):
if s[i] == '.':
if i == 0:
helper.append(1)
elif s[i - 1] == '.':
helper[-1] += 1
else:
helper.append(1)
initval = 0
for val in helper:
initval += val - 1
for query in range(m):
index, replace = input().split()
index = int(index) - 1
if s[index] == '.' and replace == '.' or (s[index] != '.' and replace != '.'):
res[query] = initval
else:
sidedots = 0
if index > 0:
if s[index - 1] == '.':
sidedots += 1
if index < n - 1:
if s[index + 1] == '.':
sidedots += 1
if s[index] == '.':
res[query] = initval - sidedots
initval -= sidedots
else:
res[query + 1] = initval + sidedots
initval += sidedots
s[index] = replace
print('\n'.join(map(str, res)))
def rv():
return list(map(int, input().split()))
def rl(n):
return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544:
sys.stdin = open('test.txt')
solve()
053
n, q, k = list(map(int, input().split(' ')))
a = list(map(int, input().split(' ')))
count = 0
def verify(x):
if x < 0 or x >= n:
return False
return a[x] > k
for i in range(n):
if verify(i):
count += 1
if verify(i - 1):
count -= 1
def cut(i):
if not verify(i):
return 0
result = 1
if verify(i - 1):
result -= 1
if verify(i + 1):
result -= 1
return result
for i in range(q):
line = input()
if line == '0':
print(count)
else:
_, x, y = list(map(int, line.split(' ')))
x -= 1
if not verify(x):
a[x] += y
count += cut(x)
else:
a[x] -= y
054
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)
055
from sys import stdin
input = stdin.readline
n, m = list(map(int, input().split()))
s = list(((0, 1)[c == '.'] for c in list(input())))
res = 0
cnt = 0
for k in s:
if k == 1:
cnt += 1
else:
res += max(cnt - 1, 0)
cnt = 0
res += max(0, cnt - 1)
for i in range(m):
x, c = input().split()
x = int(x)
nc = (0, 1)[c == '.']
if s[x - 1] != nc:
diff = 0
if x < n:
if s[int(x)] == 1:
diff += 1
if x > 1:
if s[int(x - 2)] == 1:
diff += 1
if nc == 1:
res += diff
else:
res -= diff
s[x - 1 + 1] = nc
print(res)
056
__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()
057
from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 10
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
t, dx, dy = stdin.readline().split()
dx = int(dx)
dy = int(dy)
if dx == x:
if dy > y:
if ud > dy - y:
ud = dy - y
u = t
elif dd > y - dy:
dd = y - dy
d = t
if dy == y:
if dx > x:
if rd > dx - x:
rd = dx - x
r = t
elif not ld > x - dx:
ld = x - dx
l = t
if dx - x == dy - y:
if dy > y:
if urd > dy - y:
urd = dy - y
ur = t
elif dld > y - dy:
dld = y - dy
dl = t
if -(dx - x) == dy - y:
if dy > y:
if uld > dy - y:
uld = dy - y
ul = t
elif drd > y - dy:
drd = y - dy
dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
print('YES')
else:
print('NO')
058
import bisect
t = int(input())
for _ in range(t):
n, m = list(map(int, input().split()))
flowers = []
flowers_a = []
max_b = 0
for i in range(m):
a, b = list(map(int, input().split()))
flowers.append((a, b))
flowers.sort()
flowers_b = []
for i in range(m):
flowers_a.append(flowers[i][0])
flowers_b.append(flowers[i][1])
val = 0
prefix_sum = [0]
for x in flowers_a:
prefix_sum.append(prefix_sum[-1] + x)
for i in range(m):
idx = bisect.bisect_left(flowers_a, flowers_b[i])
options = m - idx
if options >= n:
temp = prefix_sum[-1] - prefix_sum[-n - 1]
val = max(val, temp)
continue
else:
temp = prefix_sum[-1] - prefix_sum[-options - 1]
remaining = n - options
if idx <= i:
temp += flowers_b[i] + remaining
else:
temp += flowers_a[i] + flowers_b[i] * (remaining - 1)
val = max(val, temp)
print(val)
if _ != t - 1:
blank_line = input()
059
import sys
input = sys.stdin.readline
for f in range(int(input())):
n, m = map(int, input().split())
a = [0] * m
b = [0] * m
acop = [0] * m
bcop = [0] * m
for i in range(m):
a[i], b[i] = map(int, input().split())
acop[i] = a[i]
bcop[i] = [b[i], i]
acop.sort(reverse=True)
bcop.sort(reverse=True)
mx = 0
i = 0
su = 0
for j in range(m):
bi = bcop[j][0]
ii = bcop[j][1]
ai = a[ii]
while i < m and acop[i] > bi:
su += acop[i]
i += 1
maxi = ai
if i < n:
maxi += su
if i + 1 < n:
maxi += (n - i - 1) * bi
if ai > bi:
maxi += bi
maxi -= ai
mx = max(maxi, mx)
if n <= m:
sun = 0
for i in range(n):
sun -= acop[i]
mx = max(mx, sun)
print(mx)
blank = input()
060
def main():
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
roundup = []
rounddown = []
sumsofar = []
for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
ssf = sumsofar[-1] if sumsofar else 0
t = roundup[-1] if roundup else 0
roundup.append(t + ssf + b * (-1 + 2 * i))
t = rounddown[-1] if rounddown else 0
rounddown.append(t + ssf + a * (1 + 2 * i))
sumsofar.append(ssf + a + b)
roundup = list(reversed(roundup))
rounddown = list(reversed(rounddown))
sumsofar = list(reversed(sumsofar))
bestres = 0
sofar = 0
for i, (a, b) in enumerate(zip(A, B)):
rup, rdo = (roundup, rounddown)
if i % 2:
a, b = (b, a)
rup, rdo = (rdo, rup)
bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
sofar += a * 2 * i
sofar += b * (2 * i + 1)
bestres = max(bestres, sofar)
print(bestres)
def __starting_point():
main()
__starting_point()
061
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)
062
from sys import stdin
from math import *
line = stdin.readline().rstrip().split()
n = int(line[0])
numbers = list(map(int, stdin.readline().rstrip().split()))
numbers2 = list(map(int, stdin.readline().rstrip().split()))
growRateAccum = 0
topAccum = 0
bottomAccum = 0
accumsB = [0] * n
accumsT = [0] * n
growRateAccum = 0
accum = 0
for i in reversed(range(n - 1, -1, -1)):
accum += numbers[i] * ((n - i) * 2 - 1 - 1)
growRateAccum += numbers[i]
if i < n - 1:
growRateAccum += numbers2[i + 1]
accum += growRateAccum
accumsB[i] = accum
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
accum += numbers2[i] * ((n - i) * 2 - 1 - 1)
growRateAccum += numbers2[i]
if i < n - 1:
growRateAccum += numbers[i + 1]
accum += growRateAccum
accumsT[i] = accum
cMax = 0
currAccum = 0
growRateAccum = sum(numbers[1:]) + sum(numbers2[1:])
for i in range(n):
if i % 2 == 0:
cMax = max(cMax, currAccum + accumsT[i])
else:
cMax = max(cMax, currAccum + accumsB[i])
if i < n - 1:
if i % 2 == 0:
currAccum += numbers2[i] + growRateAccum * 2
else:
currAccum += numbers[i] + growRateAccum * 2
growRateAccum -= numbers[i + 1]
growRateAccum -= numbers2[i + 1]
print(cMax)
063
from operator import or_, xor
import sys
n, m = map(int, input().split())
t = [list(map(int, input().split()))]
for i in range(n):
if i & 1 == 0:
t += [[t[i][j] | t[i][j + 1] for j in range(0, len(t[i]), 2)]]
else:
t += [[t[i][j] ^ t[i][j + 1] for j in range(0, len(t[i]), 2)]]
for s in sys.stdin:
p, b = s.split()
p = int(p) - 1
t[0][p] = int(b)
for j in range(n):
p = int(p / 2)
if j & 1 == 0:
t[j + 1][p] = t[j][int(p * 2)] | t[j][int(p * 2) + 1]
else:
t[j + 1][p] = t[j][int(p * 2) + 1] ^ t[j][int(p * 2) + 1]
sys.stdout.write(str(t[-1][0]) + '\n')
064
def main():
n = int(input())
x, y = list(map(int, input().split()))
a = []
for i in range(n):
a.append(input().split())
for i in range(n):
a[i][1] = int(a[i][1]) - x
a[i][2] = int(a[i][2]) - y
typneedbql = []
typneedbqr = []
typneedbqu = []
typneedbqd = []
typneedrlu = []
typneedrru = []
typneedrld = []
typneedrrd = []
for i in range(n):
if a[i][1] * a[i][2] == 0 and a[i][1] < 2:
typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
typneedrlu.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
typneedrld.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
typneedrrd.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
typneedrru.append([abs(a[i][1])] + a[i])
typneedbql.sort()
typneedbqr.sort()
typneedbqd.sort()
typneedbqu.sort()
typneedrlu.sort()
typneedrru.sort()
typneedrld.sort()
typneedrrd.sort()
for i in range(len(typneedbql)):
if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqr)):
if typneedbqr[i][1] == 'R' or typneedbqr[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqu)):
if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqd)):
if typneedbqd[i][1] == 'R' or typneedbqd[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrlu)):
if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrld)):
if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrrd)):
if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrru)):
if typneedrru[i][1] == 'B' or typneedrru[i][1] == 'Q':
print('YES')
return
else:
break
print('NO')
main()
065
n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
for i in range(2):
sum_up[i][n - 1] = a[i][n - 1]
pref_up[i][n - 1] = a[i][n - 1]
pref_down[i][n - 1] = a[i][n - 1 - 1]
for j in range(n - 2, -1, -1):
sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
zig = [[0 for i in range(n)] for j in range(2)]
for j in range(n):
for i in range(2):
if j % 2 == 0:
if i == 0:
zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
else:
zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
elif i == 0:
zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
else:
zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
ans = -1e+18
for j in range(n):
if j == 0:
ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
elif j == n - 1:
ans = max(ans, zig[1 - j % 2][n - 1])
elif j % 2 == 1:
ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
else:
ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
print(ans)
else:
print(a[1][0])
066
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)
067
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)
068
from collections import defaultdict
import bisect
n = int(input())
x0, y0 = list(map(int, input().split(' ')))
verticale = []
horizontale = []
diagonale1 = []
diagonale2 = []
for _ in range(n):
t, x, y = input().split(' ')
x, y = (int(x), int(y))
if x == x0:
verticale.append((y, t))
if y == y0:
horizontale.append((x, t))
if x + y == x0 + y0:
diagonale1.append((x, t))
if x - y == x0 - y0:
diagonale2.append((x, t))
dead = False
v = sorted(verticale)
if v:
l = bisect.bisect(v, (y0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'R'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'R'}:
dead = True
v = sorted(horizontale)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'R'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'R'}:
dead = True
v = sorted(diagonale1)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'B'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'B'}:
dead = True
v = sorted(diagonale2)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'B'}:
dead = True
elif v[len(v) - 1][1] not in {'Q', 'B'}:
dead = True
if dead:
print('YES')
else:
print('NO')
069
from sys import stdin
from math import *
line = stdin.readline().rstrip().split()
n = int(line[0])
numbers = list(map(int, stdin.readline().rstrip().split()))
numbers2 = list(map(int, stdin.readline().rstrip().split()))
growRateAccum = 0
topAccum = 0
bottomAccum = 0
accumsB = [0] * n
accumsT = [0] * n
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
accum += numbers[i] * ((n - i) * 2 - 1 - 1)
growRateAccum *= numbers[i]
if i < n - 1:
growRateAccum += numbers2[i + 1]
accum += growRateAccum
accumsB[i] = accum
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
accum += numbers2[i] * ((n - i) * 2 - 1 - 1)
growRateAccum += numbers2[i]
if i < n - 1:
growRateAccum += numbers[i + 1]
accum += growRateAccum
accumsT[i] = accum
cMax = 0
currAccum = 0
growRateAccum = sum(numbers[1:]) + sum(numbers2[1:])
for i in range(n):
if i % 2 == 0:
cMax = max(cMax, currAccum + accumsT[i])
else:
cMax = max(cMax, currAccum + accumsB[i])
if i < n - 1:
if i % 2 == 0:
currAccum += numbers2[i] + growRateAccum * 2
else:
currAccum += numbers[i] + growRateAccum * 2
growRateAccum -= numbers[i + 1]
growRateAccum -= numbers2[i + 1]
print(cMax)
070
n = int(input())
temp = input().split()
x0 = int(temp[0])
y0 = int(temp[0])
N = ['T', 10 ** 20]
NE = ['T', 10 ** 20]
E = ['T', 10 ** 20]
SE = ['T', 10 ** 20]
S = ['T', 10 ** 20]
SW = ['T', 10 ** 20]
W = ['T', 10 ** 20]
NW = ['T', 10 ** 20]
for i in range(n):
temp = input().split()
x = int(temp[1])
y = int(temp[2])
if x - x0 == 0 and y - y0 > 0 and (y - y0 < N[1]):
N = [temp[0], y - y0]
elif x - x0 == y - y0 and x - x0 > 0 and (x - x0 < NE[1]):
NE = [temp[0], x - x0]
elif y - y0 == 0 and x - x0 > 0 and (x - x0 < E[1]):
E = [temp[0], x - x0]
elif x - x0 == -(y - y0) and x - x0 > 0 and (x - x0 < SE[1]):
SE = [temp[0], x - x0]
elif x - x0 == 0 and y - y0 < 0 and (y0 - y < S[1]):
S = [temp[0], y0 - y]
elif x - x0 == y - y0 and x - x0 < 0 and (x0 - x < SW[1]):
SW = [temp[0], x0 - x]
elif y - y0 == 0 and x - x0 < 0 and (x0 - x < W[1]):
W = [temp[0], x0 - x]
elif x - x0 == -(y - y0) and x - x0 < 0 and (x0 - x < NW[1]):
NW = [temp[0], x0 - x]
if 'R' in [N[0], E[0], S[0], W[0]] or 'B' in [NE[0], SE[0], SW[0], NW[0]]:
print('YES')
elif 'Q' in [N[0], E[0], S[0], W[0], NE[0], SE[0], SW[0], NW[0]]:
print('YES')
else:
print('NO')
071
n, k = list(map(int, input().split()))
a = sorted(list(map(int, input().split())))
sums, suf, q1 = ([0] * n, [n] * n, n)
for q in range(n - 2, -1, -1):
sums[q] = sums[q + 1]
if a[q] != a[q1 - 1 - 1]:
sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1)
q1 = q + 1
suf[q] = q1
ans, sum1, q1 = (sums[0] + k - suf[0] if suf[0] < k else 0, 0, -1)
for q in range(1, n):
if a[q] != a[q1 + 1]:
sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1)
q1 = q - 1
if suf[q] - q1 - 1 >= k:
ans = 0
break
if k <= suf[q]:
ans = min(ans, sum1 + k - suf[q] + q1 + 1)
if k < n - q1:
ans = min(ans, sums[q] + k - suf[q] + q1 + 1)
ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1)
print(ans)
072
from bisect import bisect_left
t = int(input())
for case in range(t):
n, m = list(map(int, input().split()))
ab = [list(map(int, input().split())) for _ in range(m)]
aa = [e for e, _ in ab]
aa.sort()
acc = [0] * (m + 1)
for i in range(m, 0, -1):
acc[i - 1] = acc[i] + aa[i - 1]
if n > m:
ans = 0
else:
ans = sum(aa[-n - 1:])
for a, b in ab:
i = bisect_left(aa, b)
cnt = min(m - i, n)
sm = acc[m - cnt]
sm += b * (n - cnt)
if a < b:
sm -= b
sm += a
ans = max(ans, sm)
print(ans)
if case != t - 1:
input()
073
from collections import Counter
import sys
from itertools import accumulate
def go():
n, k = list(map(int, input().split()))
a = sorted(map(int, input().split()))
c = Counter(a)
if max(c.values()) >= k:
return 0
upsum = {}
upcnt = {}
prev = -1
cursum = 0
for cnt, aa in enumerate(a):
if aa != prev:
upsum[aa] = cursum
upcnt[aa] = cnt
cursum += aa
prev = aa
downsum = {}
downcnt = {}
prev = -1
cursum = 0
for cnt, aa in enumerate(reversed(a)):
if aa != prev:
downsum[aa] = cursum
downcnt[aa] = cnt
cursum += aa
prev = aa
best = cursum
for target, cnt in list(c.items()):
need = k - cnt
if upcnt[target] >= need:
best = min(best, (target - 1) * upcnt[target] - upsum[target] + need)
if downcnt[target] >= need:
best = min(best, downsum[target] - (target + 1) * downcnt[target] + need)
best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + -1) * downcnt[target] + need)
return best
t = 1
for _ in range(t):
print(go())
074
from collections import defaultdict
import bisect
n = int(input())
x0, y0 = list(map(int, input().split(' ')))
verticale = []
horizontale = []
diagonale1 = []
diagonale2 = []
for _ in range(n):
t, x, y = input().split(' ')
x, y = (int(x), int(y))
if x == x0:
verticale.append((y, t))
if y == y0:
horizontale.append((x, t))
if x + y == x0 + y0:
diagonale1.append((x, t))
if x - y == x0 - y0:
diagonale2.append((x, t))
dead = False
v = sorted(verticale)
if v:
l = bisect.bisect(v, (y0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'R'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'R'}:
dead = True
v = sorted(horizontale)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'R'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'R'}:
dead = True
v = sorted(diagonale1)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'B'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'B'}:
dead = True
v = sorted(diagonale2)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] not in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'B'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'B'}:
dead = True
if dead:
print('YES')
else:
print('NO')
075
n, m, l = list(map(int, input().split()))
l += 1
hair = [1] * (n + 1)
other_end = [1] * (n + 1)
i = 1
j = 1
big = 1
res = 1
for a in map(int, input().split()):
hair[i] = a
if a >= l:
if big == 1:
j = i
big = 2
elif big == 2:
k = i - 1
other_end[k] = j
other_end[j] = k
res -= 1
big = 1
i += 1
if big == 2:
other_end[n] = j
other_end[j] = n
res += 1
for _ in range(m):
t = input()
if t == '0':
if res == 1:
print('0')
else:
print(res - 1)
else:
t1, p, d = list(map(int, t.split()))
old = hair[p]
hair[p] += d
if hair[p] >= l > old:
if p == 1 or hair[p - 1] < l:
case_id = 1
else:
case_id = 2
if p != n and hair[p + 1] >= l:
case_id += 2
if case_id == 1:
other_end[p] = p
res += 1
elif case_id == 2:
other_end[p] = other_end[p - 1]
other_end[other_end[p]] = p
elif case_id == 3:
other_end[p] = other_end[p + 1]
other_end[other_end[p]] = p
else:
left_end = other_end[p - 1]
right_end = other_end[p + 1]
other_end[left_end] = right_end
other_end[right_end] = left_end
res -= 1
076
from sys import stdin, stderr
import random
import cProfile
def readInts():
return map(int, stdin.readline().strip().split())
def print_err(*args, **kwargs):
print(*args, file=stderr, **kwargs)
def solve(vs):
return None
def generate_tree(n, ns):
out = [0 for _ in range(2 ** (n + 1))]
def gt(nix, left, right, op):
if left + 1 == right:
out[nix] = ns[left]
return out[nix]
mid = (left + right) // 2
nL = nix * 2 + 1
nR = nix * 2 - 2
vL = gt(nL, left, mid, not op)
vR = gt(nR, mid, right, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
out[nix] = v
return v
gt(0, 0, 2 ** n, n % 2 == 0)
return out
def alter_tree2(n, t, p, b):
def at(nix, width, offp, op):
if width == 1:
t[nix] = b
return b
width //= 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = t[nL]
vR = t[nR]
if offp >= width:
vR = at(nR, width, offp - width, not op)
else:
vL = at(nL, width, offp, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
t[nix] = v
return v
at(0, 2 ** n, p, n % 2 == 0)
def alter_tree(n, t, p, b):
width = 2 ** n
s = []
nix = 0
op = n % 2 == 0
while width > 1:
width //= 2
if p >= width:
nix2 = 2 * nix + 2
s.append((nix, nix2 - 1))
p -= width
else:
nix2 = 2 * nix + 1
s.append((nix, nix2 + 1))
nix = nix2
op = not op
t[nix] = b
v = b
while s:
nix, nixO = s.pop()
if op:
v |= t[nixO]
else:
v ^= t[nixO]
t[nix] = v
op = not op
return
def run():
n, m = readInts()
axs = list(readInts())
t = generate_tree(n, axs)
for _ in range(m):
p, b = readInts()
alter_tree(n, t, p - 1, b)
print(t[0])
def test():
n = 17
ns = []
vs100 = list(range(100))
for _ in range(2 ** 17):
ns.append(random.choice(vs100))
t = generate_tree(n, ns)
t2 = generate_tree(n, ns)
for _ in range(100000):
v1 = random.choice(vs100)
v2 = random.choice(vs100)
alter_tree(n, t, v1, v2)
alter_tree2(n, t2, v1, v2)
print(all(map(lambda x: x[0] == x[1], zip(t, t2))))
print(t[0] == t2[0])
run()
077
from operator import or_, xor
import sys
n, m = map(int, input().split())
t = [list(map(int, input().split()))]
for i in range(n):
if i & 1 == 0:
t += [[t[i][j] | t[i][j + 1] for j in range(0, len(t[i]), 2)]]
else:
t += [[t[i][j] ^ t[i][j + 1] for j in range(0, len(t[i]), 2)]]
for s in sys.stdin:
p, b = s.split()
p = int(p) - 1
t[0][p] = int(b)
for j in range(n):
p = int(p / 2)
if j & 1 == 0:
t[j + 1][p] = t[j][int(p * 2)] | t[j][int(p * 2) + 1]
else:
t[j + 1][p] = t[j][int(p * 2)] ^ t[j - 1][int(p * 2) + 1]
sys.stdout.write(str(t[-1][0]) + '\n')
078
n, m, l = list(map(int, input().split()))
l += 1
hair = [1] * (n + 1)
other_end = [1] * (n + 1)
i = 1
j = 1
big = 1
res = 1
for a in map(int, input().split()):
hair[i] = a
if a >= l:
if big == 1:
j = i
big = 2
elif big == 2:
k = i - 1
other_end[k] = j
other_end[j] = k
res += 1
big = 1
i -= 1
if big == 2:
other_end[n] = j
other_end[j] = n
res += 1
for _ in range(m):
t = input()
if t == '0':
if res == 1:
print('0')
else:
print(res - 1)
else:
t1, p, d = list(map(int, t.split()))
old = hair[p]
hair[p] += d
if hair[p] >= l > old:
if p == 1 or hair[p - 1] < l:
case_id = 1
else:
case_id = 2
if p != n and hair[p + 1] >= l:
case_id += 2
if case_id == 1:
other_end[p] = p
res += 1
elif case_id == 2:
other_end[p] = other_end[p - 1]
other_end[other_end[p]] = p
elif case_id == 3:
other_end[p] = other_end[p + 1]
other_end[other_end[p]] = p
else:
left_end = other_end[p - 1]
right_end = other_end[p + 1]
other_end[left_end] = right_end
other_end[right_end] = left_end
res -= 1
079
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)
080
import bisect
t = int(input())
for _ in range(t):
n, m = list(map(int, input().split()))
flowers = []
flowers_a = []
max_b = 0
for i in range(m):
a, b = list(map(int, input().split()))
flowers.append((a, b))
flowers.sort()
flowers_b = []
for i in range(m):
flowers_a.append(flowers[i][0])
flowers_b.append(flowers[i][1])
val = 0
prefix_sum = [0]
for x in flowers_a:
prefix_sum.append(prefix_sum[-1] + x)
for i in range(m):
idx = bisect.bisect_left(flowers_a, flowers_b[i])
options = m - idx
if options >= n:
temp = prefix_sum[-1] - prefix_sum[-n - 1]
val = max(val, temp)
continue
else:
temp = prefix_sum[-1] - prefix_sum[-options - 1]
remaining = n - options
if idx < i:
temp += flowers_b[i] * remaining
else:
temp += flowers_a[i] + flowers_b[i] * (remaining - 1)
val = max(val, temp)
print(val)
if _ != t - 1:
blank_line = input()
081
from collections import Counter
import sys
from itertools import accumulate
def go():
n, k = list(map(int, input().split()))
a = sorted(map(int, input().split()))
c = Counter(a)
if max(c.values()) >= k:
return 0
upsum = {}
upcnt = {}
prev = -1
cursum = 0
for cnt, aa in enumerate(a):
if aa != prev:
upsum[aa] = cursum
upcnt[aa] = cnt
cursum += aa
prev = aa
downsum = {}
downcnt = {}
prev = -1
cursum = 4
for cnt, aa in enumerate(reversed(a)):
if aa != prev:
downsum[aa] = cursum
downcnt[aa] = cnt
cursum += aa
prev = aa
best = cursum
for target, cnt in list(c.items()):
need = k - cnt
if upcnt[target] >= need:
best = min(best, (target - 1) * upcnt[target] - upsum[target] + need)
if downcnt[target] >= need:
best = min(best, downsum[target] - (target + 1) * downcnt[target] + need)
best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + 1) * downcnt[target] + need)
return best
t = 1
for _ in range(t):
print(go())
082
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)
083
from collections import defaultdict
import bisect
n = int(input())
x0, y0 = list(map(int, input().split(' ')))
verticale = []
horizontale = []
diagonale1 = []
diagonale2 = []
for _ in range(n):
t, x, y = input().split(' ')
x, y = (int(x), int(y))
if x == x0:
verticale.append((y, t))
if y == y0:
horizontale.append((x, t))
if x + y == x0 + y0:
diagonale1.append((x, t))
if x - y == x0 - y0:
diagonale2.append((x, t))
dead = False
v = sorted(verticale)
if v:
l = bisect.bisect(v, (y0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'R'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'R'}:
dead = True
v = sorted(horizontale)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'R'}:
dead = True
elif v[len(v) - 1][1] not in {'Q', 'R'}:
dead = True
v = sorted(diagonale1)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'B'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'B'}:
dead = True
v = sorted(diagonale2)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'B'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'B'}:
dead = True
if dead:
print('YES')
else:
print('NO')
084
import sys
sys.setrecursionlimit(1000000)
def solve():
n, m = rv()
s = list(input())
res = [0] * m
helper = list()
for i in range(n - 1):
if s[i] == '.':
if i == 0:
helper.append(1)
elif s[i - 1] == '.':
helper[-1] += 1
else:
helper.append(1)
initval = 0
for val in helper:
initval += val - 1
for query in range(m):
index, replace = input().split()
index = int(index) - 1
if s[index] == '.' and replace == '.' or (s[index] != '.' and replace != '.'):
res[query] = initval
else:
sidedots = 0
if index > 0:
if s[index - 1] == '.':
sidedots += 1
if index < n - 1:
if s[index + 1] == '.':
sidedots += 1
if s[index] == '.':
res[query] = initval - sidedots
initval -= sidedots
else:
res[query] = initval + sidedots
initval += sidedots
s[index] = replace
print('\n'.join(map(str, res)))
def rv():
return list(map(int, input().split()))
def rl(n):
return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544:
sys.stdin = open('test.txt')
solve()
085
import bisect
t = int(input())
for _ in range(t):
n, m = list(map(int, input().split()))
flowers = []
flowers_a = []
max_b = 0
for i in range(m):
a, b = list(map(int, input().split()))
flowers.append((a, b))
flowers.sort()
flowers_b = []
for i in range(m):
flowers_a.append(flowers[i][0])
flowers_b.append(flowers[i][1])
val = 0
prefix_sum = [0]
for x in flowers_a:
prefix_sum.append(prefix_sum[-1] + x)
for i in range(m):
idx = bisect.bisect_left(flowers_a, flowers_b[i])
options = m - idx
if options >= n:
temp = prefix_sum[-1] + prefix_sum[-n - 1]
val = max(val, temp)
continue
else:
temp = prefix_sum[-1] - prefix_sum[-options - 1]
remaining = n - options
if idx <= i:
temp += flowers_b[i] * remaining
else:
temp += flowers_a[i] + flowers_b[i] * (remaining - 1)
val = max(val, temp)
print(val)
if _ != t - 1:
blank_line = input()
086
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
curl_ud_weights = [0] * n
curl_du_weights = [0] * n
sums = [0] * n
sums[n - 1] = a[n - 1] + b[n - 1]
curl_ud_weights[n - 1] = b[n - 1]
curl_du_weights[n - 1] = a[n - 1]
for i in range(n - 2, -1, -1):
sums[i] = sums[i + 1] + (a[i] + b[i])
remain = n * 2 - i * 2 - 1
curl_ud_weights[i] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i]
curl_du_weights[i - 1] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i]
snake_weight = 0
max_weight = 0
current_weight = -1
for t in range(0, 2 * n, 2):
remain = t % 4
if remain == 0:
current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight
snake_weight += a[t // 2] * t + b[t // 2] * (t + 1)
elif remain == 2:
current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight
snake_weight += b[t // 2] * t + a[t // 2] * (t + 1)
if current_weight > max_weight:
max_weight = current_weight
print(max_weight)
'\n3\n0 1 0\n0 0 0\n'
087
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def I():
return int(sys.stdin.readline())
def LS():
return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == '\n':
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
def solve():
n, k = LI()
a = LI()
a.sort()
d = defaultdict(lambda: 0)
c = defaultdict(lambda: 0)
s = [0]
for i in a:
d[i] += i
c[i] += 1
s.append(s[-1] + i)
ans = float('inf')
p = -1
for i in a:
if i == p:
continue
if k <= c[i]:
ans = 0
break
l, r = (bisect.bisect_left(a, i), bisect.bisect_right(a, i))
m = r
if m >= k:
ns = l * (i - 1) - s[l]
su = ns + k - c[i]
if su < ans:
ans = su
m = n - l
if m >= k:
ns = s[n] - s[r] - (n - r) * (i + 1)
su = ns + k - c[i]
if su < ans:
ans = su
ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l]
su = ns - k - c[i]
if su < ans:
ans = su
p = i
print(ans)
return
def __starting_point():
solve()
__starting_point()
088
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)
089
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
curl_ud_weights = [0] * n
curl_du_weights = [0] * n
sums = [0] * n
sums[n - 1] = a[n - 1] + b[n - 1]
curl_ud_weights[n - 1] = b[n - 1]
curl_du_weights[n - 1] = a[n - 1]
for i in range(n - 2, -1, -1):
sums[i] = sums[i + 1] + (a[i] + b[i])
remain = n * 2 - i * 2 - 1
curl_ud_weights[i + 1] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i]
curl_du_weights[i] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i]
snake_weight = 0
max_weight = 0
current_weight = -1
for t in range(0, 2 * n, 2):
remain = t % 4
if remain == 0:
current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight
snake_weight += a[t // 2] * t + b[t // 2] * (t + 1)
elif remain == 2:
current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight
snake_weight += b[t // 2] * t + a[t // 2] * (t + 1)
if current_weight > max_weight:
max_weight = current_weight
print(max_weight)
'\n3\n0 1 0\n0 0 0\n'
090
def main():
n = int(input())
x, y = list(map(int, input().split()))
a = []
for i in range(n):
a.append(input().split())
for i in range(n):
a[i][1] = int(a[i][1]) - x
a[i][2] = int(a[i][2]) - y
typneedbql = []
typneedbqr = []
typneedbqu = []
typneedbqd = []
typneedrlu = []
typneedrru = []
typneedrld = []
typneedrrd = []
for i in range(n):
if a[i][1] * a[i][2] == 0 and a[i][1] < 0:
typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
typneedrlu.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
typneedrld.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
typneedrrd.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
typneedrru.append([abs(a[i][1])] + a[i])
typneedbql.sort()
typneedbqr.sort()
typneedbqd.sort()
typneedbqu.sort()
typneedrlu.sort()
typneedrru.sort()
typneedrld.sort()
typneedrrd.sort()
for i in range(len(typneedbql)):
if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqr)):
if typneedbqr[i][1] == 'R' or typneedbqr[i][1] != 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqu)):
if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqd)):
if typneedbqd[i][1] == 'R' or typneedbqd[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrlu)):
if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrld)):
if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrrd)):
if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrru)):
if typneedrru[i][1] == 'B' or typneedrru[i][1] == 'Q':
print('YES')
return
else:
break
print('NO')
main()
091
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)
092
import bisect
t = int(input())
for _ in range(t):
n, m = list(map(int, input().split()))
flowers = []
flowers_a = []
max_b = 0
for i in range(m):
a, b = list(map(int, input().split()))
flowers.append((a, b))
flowers.sort()
flowers_b = []
for i in range(m):
flowers_a.append(flowers[i][0])
flowers_b.append(flowers[i][1])
val = 0
prefix_sum = [0]
for x in flowers_a:
prefix_sum.append(prefix_sum[-1] + x)
for i in range(m):
idx = bisect.bisect_left(flowers_a, flowers_b[i])
options = m - idx
if options >= n:
temp = prefix_sum[-1] * prefix_sum[-n - 1]
val = max(val, temp)
continue
else:
temp = prefix_sum[-1] - prefix_sum[-options - 1]
remaining = n - options
if idx <= i:
temp += flowers_b[i] * remaining
else:
temp += flowers_a[i] + flowers_b[i] * (remaining - 1)
val = max(val, temp)
print(val)
if _ != t - 1:
blank_line = input()
093
from sys import stdin, stderr
import random
import cProfile
def readInts():
return map(int, stdin.readline().strip().split())
def print_err(*args, **kwargs):
print(*args, file=stderr, **kwargs)
def solve(vs):
return None
def generate_tree(n, ns):
out = [0 for _ in range(2 ** (n + 1))]
def gt(nix, left, right, op):
if left + 1 == right:
out[nix] = ns[left]
return out[nix]
mid = (left + right) // 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = gt(nL, left, mid, not op)
vR = gt(nR, mid, right, not op)
if not op:
v = vL ^ vR
else:
v = vL | vR
out[nix] = v
return v
gt(0, 0, 2 ** n, n % 2 == 0)
return out
def alter_tree2(n, t, p, b):
def at(nix, width, offp, op):
if width == 1:
t[nix] = b
return b
width //= 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = t[nL]
vR = t[nR]
if offp >= width:
vR = at(nR, width, offp - width, not op)
else:
vL = at(nL, width, offp, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
t[nix] = v
return v
at(0, 2 ** n, p, n % 2 == 0)
def alter_tree(n, t, p, b):
width = 2 ** n
s = []
nix = 0
op = n % 2 == 0
while width > 1:
width //= 2
if p >= width:
nix2 = 2 * nix + 2
s.append((nix, nix2 - 1))
p -= width
else:
nix2 = 2 * nix + 1
s.append((nix, nix2 + 1))
nix = nix2
op = not op
t[nix] = b
v = b
while s:
nix, nixO = s.pop()
if op:
v |= t[nixO]
else:
v ^= t[nixO]
t[nix] = v
op = not op
return
def run():
n, m = readInts()
axs = list(readInts())
t = generate_tree(n, axs)
for _ in range(m):
p, b = readInts()
alter_tree(n, t, p - 1, b)
print(t[0])
def test():
n = 17
ns = []
vs100 = list(range(100))
for _ in range(2 ** 17):
ns.append(random.choice(vs100))
t = generate_tree(n, ns)
t2 = generate_tree(n, ns)
for _ in range(100000):
v1 = random.choice(vs100)
v2 = random.choice(vs100)
alter_tree(n, t, v1, v2)
alter_tree2(n, t2, v1, v2)
print(all(map(lambda x: x[0] == x[1], zip(t, t2))))
print(t[0] == t2[0])
run()
094
__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()
095
import sys
class SegmTree:
def __init__(self, size):
N = 1
while N < size:
N <<= 1
self.N = N
self.tree = [0] * (2 * N)
def modify(self, i, value):
i += self.N
self.tree[i] = value
toXOR = False
while i > 1:
if toXOR:
self.tree[i >> 1] = self.tree[i] ^ self.tree[(i ^ 1) + 1]
else:
self.tree[i >> 1] = self.tree[i] | self.tree[i ^ 1]
toXOR = not toXOR
i >>= 1
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
st = SegmTree(1 << n)
for i, value in enumerate(a):
st.modify(i, value)
for _ in range(m):
p, b = list(map(int, input().split()))
st.modify(p - 1, b)
print(st.tree[1])
096
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])
097
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)
098
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)
099
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def I():
return int(sys.stdin.readline())
def LS():
return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == '\n':
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
def solve():
n, k = LI()
a = LI()
a.sort()
d = defaultdict(lambda: 0)
c = defaultdict(lambda: 1)
s = [0]
for i in a:
d[i] += i
c[i] += 1
s.append(s[-1] + i)
ans = float('inf')
p = -1
for i in a:
if i == p:
continue
if k <= c[i]:
ans = 0
break
l, r = (bisect.bisect_left(a, i), bisect.bisect_right(a, i))
m = r
if m >= k:
ns = l * (i - 1) - s[l]
su = ns + k - c[i]
if su < ans:
ans = su
m = n - l
if m >= k:
ns = s[n] - s[r] - (n - r) * (i + 1)
su = ns + k - c[i]
if su < ans:
ans = su
ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l]
su = ns + k - c[i]
if su < ans:
ans = su
p = i
print(ans)
return
def __starting_point():
solve()
__starting_point()
100
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)
101
n, k = list(map(int, input().split()))
a = sorted(list(map(int, input().split())))
sums, suf, q1 = ([0] * n, [n] * n, n)
for q in range(n - 2, -1, -1):
sums[q] = sums[q + 1]
if a[q] != a[q1 - 1]:
sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1)
q1 = q + 1
suf[q] = q1
ans, sum1, q1 = (sums[0] + k - suf[0] if suf[0] < k else 0, -1, -1)
for q in range(1, n):
if a[q] != a[q1 + 1]:
sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1)
q1 = q - 1
if suf[q] - q1 - 1 >= k:
ans = 0
break
if k <= suf[q]:
ans = min(ans, sum1 + k - suf[q] + q1 + 1)
if k < n - q1:
ans = min(ans, sums[q] + k - suf[q] + q1 + 1)
ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1)
print(ans)
102
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)
103
from collections import Counter
from bisect import bisect, bisect_left
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = Counter(a)
c = sorted(Counter(a).items())
keys = sorted(Counter(a).keys())
m = len(c)
l_cum = [c[0][0] * c[0][1]]
l_cnt = [c[0][1]]
for i in range(1, m):
l_cum.append(l_cum[-1] + c[i][0] * c[i][1])
l_cnt.append(l_cnt[-1] + c[i][1])
r_cum = [0 for _ in range(m)]
r_cum[-1] = c[-1][0] + c[-1][1]
r_cnt = [0 for _ in range(m)]
r_cnt[-1] = c[-1][1]
for i in range(m - 2, -1, -1):
r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1]
r_cnt[i] = r_cnt[i + 1] + c[i][1]
ans = 10 ** 20
for i in range(m):
c_num = a[keys[i]]
if c_num >= k:
ans = 0
break
if i > 0:
l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1]
l_num = l_cnt[i - 1]
else:
l_res = 10 ** 30
l_num = 0
if i < m - 1:
r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1]
r_num = r_cnt[i + 1]
else:
r_res = 10 ** 30
r_num = 0
if c_num + l_num < k and c_num + r_num < k:
ans = min(ans, l_res + r_res + k - c_num)
elif c_num + l_num < k:
ans = min(ans, r_res + k - c_num)
elif c_num + r_num < k:
ans = min(ans, l_res + k - c_num)
else:
ans = min(ans, min(r_res, l_res) + k - c_num)
print(ans)
104
import bisect
t = int(input())
for _ in range(t):
n, m = list(map(int, input().split()))
flowers = []
flowers_a = []
max_b = 0
for i in range(m):
a, b = list(map(int, input().split()))
flowers.append((a, b))
flowers.sort()
flowers_b = []
for i in range(m):
flowers_a.append(flowers[i][0])
flowers_b.append(flowers[i][1])
val = 0
prefix_sum = [0]
for x in flowers_a:
prefix_sum.append(prefix_sum[-1] + x)
for i in range(m):
idx = bisect.bisect_left(flowers_a, flowers_b[i])
options = m - idx
if options >= n:
temp = prefix_sum[-1] - prefix_sum[-n - -1]
val = max(val, temp)
continue
else:
temp = prefix_sum[-1] - prefix_sum[-options - 1]
remaining = n - options
if idx <= i:
temp += flowers_b[i] * remaining
else:
temp += flowers_a[i] + flowers_b[i] * (remaining - 1)
val = max(val, temp)
print(val)
if _ != t - 1:
blank_line = input()
105
from math import log
import sys
def buildTree(arr):
n = len(arr)
tree = [0] * n + arr
for i in range(n - 1, 0, -1):
z = int(log(i, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
else:
tree[i] = tree[2 * i] | tree[2 * i + 1]
elif z % 2 == 0:
tree[i] = tree[2 * i] | tree[2 * i + 1]
else:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
return tree
def updateTree(tree, ind, value, n):
ind += n
tree[ind] = value
while ind > 1:
ind //= 2
z = int(log(ind, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
elif z % 2 == 0:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
return tree
N, m = map(int, sys.stdin.readline().strip().split())
arr = list(map(int, sys.stdin.readline().strip().split()))
tree = buildTree(arr)
for i in range(m):
ind, val = map(int, sys.stdin.readline().strip().split())
tree = updateTree(tree, ind - 1, val, len(arr))
print(tree[1])
106
import sys
class SegmTree:
def __init__(self, size):
N = 1
while N < size:
N <<= 1
self.N = N
self.tree = [0] * (2 * N)
def modify(self, i, value):
i += self.N
self.tree[i] = value
toXOR = False
while i > 1:
if toXOR:
self.tree[i >> 1] = self.tree[i] ^ self.tree[i | 1]
else:
self.tree[i >> 1] = self.tree[i] | self.tree[i ^ 1]
toXOR = not toXOR
i >>= 1
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
st = SegmTree(1 << n)
for i, value in enumerate(a):
st.modify(i, value)
for _ in range(m):
p, b = list(map(int, input().split()))
st.modify(p - 1, b)
print(st.tree[1])
107
def main():
n = int(input())
x, y = list(map(int, input().split()))
a = []
for i in range(n):
a.append(input().split())
for i in range(n):
a[i][1] = int(a[i][1]) - x
a[i][2] = int(a[i][2]) - y
typneedbql = []
typneedbqr = []
typneedbqu = []
typneedbqd = []
typneedrlu = []
typneedrru = []
typneedrld = []
typneedrrd = []
for i in range(n):
if a[i][1] * a[i][2] == 0 and a[i][1] < 0:
typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
typneedrlu.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
typneedrld.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
typneedrrd.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
typneedrru.append([abs(a[i][1])] + a[i])
typneedbql.sort()
typneedbqr.sort()
typneedbqd.sort()
typneedbqu.sort()
typneedrlu.sort()
typneedrru.sort()
typneedrld.sort()
typneedrrd.sort()
for i in range(len(typneedbql)):
if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqr)):
if typneedbqr[i][1] == 'R' or typneedbqr[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqu)):
if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqd)):
if typneedbqd[i][1] == 'R' or typneedbqd[i][1] != 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrlu)):
if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrld)):
if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrrd)):
if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrru)):
if typneedrru[i][1] == 'B' or typneedrru[i][1] == 'Q':
print('YES')
return
else:
break
print('NO')
main()
108
from sys import stdin, stderr
import random
import cProfile
def readInts():
return map(int, stdin.readline().strip().split())
def print_err(*args, **kwargs):
print(*args, file=stderr, **kwargs)
def solve(vs):
return None
def generate_tree(n, ns):
out = [0 for _ in range(2 ** (n + 1))]
def gt(nix, left, right, op):
if left + 1 == right:
out[nix] = ns[left]
return out[nix]
mid = (left + right) // 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = gt(nL, left, mid, not op)
vR = gt(nR, mid, right, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
out[nix] = v
return v
gt(0, 0, 2 ** n, n % 2 == 0)
return out
def alter_tree2(n, t, p, b):
def at(nix, width, offp, op):
if width == 1:
t[nix] = b
return b
width //= 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = t[nL]
vR = t[nR]
if offp >= width:
vR = at(nR, width, offp - width, not op)
else:
vL = at(nL, width, offp, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
t[nix] = v
return v
at(0, 2 ** n, p, n % 2 == 0)
def alter_tree(n, t, p, b):
width = 2 ** n
s = []
nix = 0
op = n % 2 == 0
while width > 1:
width //= 2
if p >= width:
nix2 = 2 * nix + 2
s.append((nix, nix2 - 1))
p -= width
else:
nix2 = 2 * nix + 1
s.append((nix, nix2 + 1))
nix = nix2
op = not op
t[nix] = b
v = b
while s:
nix, nixO = s.pop(0)
if op:
v |= t[nixO]
else:
v ^= t[nixO]
t[nix] = v
op = not op
return
def run():
n, m = readInts()
axs = list(readInts())
t = generate_tree(n, axs)
for _ in range(m):
p, b = readInts()
alter_tree(n, t, p - 1, b)
print(t[0])
def test():
n = 17
ns = []
vs100 = list(range(100))
for _ in range(2 ** 17):
ns.append(random.choice(vs100))
t = generate_tree(n, ns)
t2 = generate_tree(n, ns)
for _ in range(100000):
v1 = random.choice(vs100)
v2 = random.choice(vs100)
alter_tree(n, t, v1, v2)
alter_tree2(n, t2, v1, v2)
print(all(map(lambda x: x[0] == x[1], zip(t, t2))))
print(t[0] == t2[0])
run()
109
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()
110
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)
111
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)
112
from bisect import bisect_left
t = int(input())
for case in range(t):
n, m = list(map(int, input().split()))
ab = [list(map(int, input().split())) for _ in range(m)]
aa = [e for e, _ in ab]
aa.sort()
acc = [0] * (m + 1)
for i in range(m, 3, -1):
acc[i - 1] = acc[i] + aa[i - 1]
if n > m:
ans = 0
else:
ans = sum(aa[-n:])
for a, b in ab:
i = bisect_left(aa, b)
cnt = min(m - i, n)
sm = acc[m - cnt]
sm += b * (n - cnt)
if a < b:
sm -= b
sm += a
ans = max(ans, sm)
print(ans)
if case != t - 1:
input()
113
def main():
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
roundup = []
rounddown = []
sumsofar = []
for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
ssf = sumsofar[-1] if sumsofar else 0
t = roundup[-1] if roundup else 0
roundup.append(t + ssf + b * (1 + 2 * i))
t = rounddown[-1] if rounddown else 0
rounddown.append(t + ssf + a * (1 + 2 * i))
sumsofar.append(ssf + a + b)
roundup = list(reversed(roundup))
rounddown = list(reversed(rounddown))
sumsofar = list(reversed(sumsofar))
bestres = 0
sofar = 0
for i, (a, b) in enumerate(zip(A, B)):
rup, rdo = (roundup, rounddown)
if i % 2:
a, b = (b, a)
rup, rdo = (rdo, rup)
bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
sofar += a * 2 * i
sofar += b * (2 * i + 1)
bestres = max(bestres, sofar)
print(bestres)
def __starting_point():
main()
__starting_point()
114
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)
115
n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
for i in range(2):
sum_up[i][n - 1] = a[i][n - 1]
pref_up[i][n - 1 - 1] = a[i][n - 1]
pref_down[i][n - 1] = a[i][n - 1]
for j in range(n - 2, -1, -1):
sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
zig = [[0 for i in range(n)] for j in range(2)]
for j in range(n):
for i in range(2):
if j % 2 == 0:
if i == 0:
zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
else:
zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
elif i == 0:
zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
else:
zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
ans = -1e+18
for j in range(n):
if j == 0:
ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
elif j == n - 1:
ans = max(ans, zig[1 - j % 2][n - 1])
elif j % 2 == 1:
ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
else:
ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
print(ans)
else:
print(a[1][0])
116
def inint():
return int(input())
def inlist():
return list(map(int, input().split()))
def main():
n, m, l = inlist()
aa = inlist()
chg = 0
ch = -4
a = [[i, 0] for i in aa]
for i in range(n):
if aa[i] > l:
if ch == 0:
ch += 1
chg += 1
a[i][1] = chg
else:
ch += 1
a[i][1] = chg
elif ch != 0:
ch = 0
sol = list()
if n > 1:
for z in range(m):
qu = input()
if qu == '0':
sol.append(chg)
else:
zz, p, d = list(map(int, qu.split()))
p -= 1
a[p][0] += d
if a[p][1] == 0 and a[p][0] > l:
if p > 0 and p < n - 1:
if a[p - 1][1] == 0 and a[p + 1][1] == 0:
chg += 1
a[p][1] = chg
elif a[p - 1][1] == 0 and a[p + 1][1] > 0:
a[p][1] = a[p + 1][1]
elif a[p - 1][1] > 0 and a[p + 1][1] == 0:
a[p][1] = a[p - 1][1]
else:
a[p][1] = a[p - 1][1]
chg -= 1
elif p == 0:
if a[p + 1][1] == 0:
chg += 1
a[p][1] = chg
else:
a[p][1] = a[p + 1][1]
elif p == n - 1:
if a[p - 1][1] == 0:
chg += 1
a[p][1] = chg
else:
a[p][1] = a[p - 1][1]
else:
for z in range(m):
qu = input()
if qu == '0':
sol.append(chg)
else:
zz, p, d = list(map(int, qu.split()))
p -= 1
a[p][0] += d
if a[p][0] > d:
chg = 1
print(*sol, sep='\n')
def __starting_point():
main()
__starting_point()
117
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)
118
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
curl_ud_weights = [0] * n
curl_du_weights = [0] * n
sums = [0] * n
sums[n - 1] = a[n - 1] + b[n - 1]
curl_ud_weights[n - 1] = b[n - 1]
curl_du_weights[n - 1] = a[n - 1]
for i in range(n - 2, -1, -1):
sums[i] = sums[i + 1] + (a[i] + b[i])
remain = n * 2 - i * 2 - 1
curl_ud_weights[i - 1] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i]
curl_du_weights[i] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i]
snake_weight = 0
max_weight = 0
current_weight = -1
for t in range(0, 2 * n, 2):
remain = t % 4
if remain == 0:
current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight
snake_weight += a[t // 2] * t + b[t // 2] * (t + 1)
elif remain == 2:
current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight
snake_weight += b[t // 2] * t + a[t // 2] * (t + 1)
if current_weight > max_weight:
max_weight = current_weight
print(max_weight)
'\n3\n0 1 0\n0 0 0\n'
119
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)
120
def main():
n = int(input())
x, y = list(map(int, input().split()))
a = []
for i in range(n):
a.append(input().split())
for i in range(n):
a[i][1] = int(a[i][1]) - x
a[i][2] = int(a[i][2]) - y
typneedbql = []
typneedbqr = []
typneedbqu = []
typneedbqd = []
typneedrlu = []
typneedrru = []
typneedrld = []
typneedrrd = []
for i in range(n):
if a[i][1] * a[i][2] == 0 and a[i][1] < 0:
typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
typneedrlu.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
typneedrld.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
typneedrrd.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
typneedrru.append([abs(a[i][1])] + a[i])
typneedbql.sort()
typneedbqr.sort()
typneedbqd.sort()
typneedbqu.sort()
typneedrlu.sort()
typneedrru.sort()
typneedrld.sort()
typneedrrd.sort()
for i in range(len(typneedbql)):
if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqr)):
if typneedbqr[i][1] == 'R' or typneedbqr[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqu)):
if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqd)):
if typneedbqd[i][1] == 'R' or typneedbqd[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrlu)):
if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrld)):
if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrrd)):
if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrru)):
if typneedrru[i][1] == 'B' or typneedrru[i][1] != 'Q':
print('YES')
return
else:
break
print('NO')
main()
121
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)
122
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)
123
from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 10
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
t, dx, dy = stdin.readline().split()
dx = int(dx)
dy = int(dy)
if dx == x:
if dy > y:
if ud > dy - y:
ud = dy - y
u = t
elif dd > y - dy:
dd = y - dy
d = t
if dy == y:
if dx > x:
if rd > dx - x:
rd = dx - x
r = t
elif ld > x - dx:
ld = x - dx
l = t
if dx - x == dy - y:
if dy > y:
if urd > dy - y:
urd = dy - y
ur = t
elif dld > y - dy:
dld = y - dy
dl = t
if -(dx - x) == dy - y:
if not dy > y:
if uld > dy - y:
uld = dy - y
ul = t
elif drd > y - dy:
drd = y - dy
dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
print('YES')
else:
print('NO')
124
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])
125
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)
126
def main():
n = int(input())
x, y = list(map(int, input().split()))
a = []
for i in range(n):
a.append(input().split())
for i in range(n):
a[i][1] = int(a[i][1]) - x
a[i][2] = int(a[i][2]) - y
typneedbql = []
typneedbqr = []
typneedbqu = []
typneedbqd = []
typneedrlu = []
typneedrru = []
typneedrld = []
typneedrrd = []
for i in range(n):
if a[i][1] * a[i][2] == 0 and a[i][1] < 3:
typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
typneedrlu.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
typneedrld.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
typneedrrd.append([abs(a[i][1])] + a[i])
elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
typneedrru.append([abs(a[i][1])] + a[i])
typneedbql.sort()
typneedbqr.sort()
typneedbqd.sort()
typneedbqu.sort()
typneedrlu.sort()
typneedrru.sort()
typneedrld.sort()
typneedrrd.sort()
for i in range(len(typneedbql)):
if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqr)):
if typneedbqr[i][1] == 'R' or typneedbqr[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqu)):
if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedbqd)):
if typneedbqd[i][1] == 'R' or typneedbqd[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrlu)):
if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrld)):
if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrrd)):
if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
print('YES')
return
else:
break
for i in range(len(typneedrru)):
if typneedrru[i][1] == 'B' or typneedrru[i][1] == 'Q':
print('YES')
return
else:
break
print('NO')
main()
127
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)
128
import collections
import bisect
def f():
n, m = [int(c) for c in input().split()]
s = list(input())
ll = []
start = 0
length = 0
inside = False
cc = 0
for i in range(len(s)):
if s[i] == '.':
if not inside:
inside = True
length += 1
elif inside:
cc += length - 1
length = 0
inside = False
if inside:
cc += length - 1
res = [0] * m
for i in range(m):
line = input().split()
j = int(line[0]) - 1
c = line[1]
if c == '.' and s[j] == '.' or (c == '.' and s[j] != '.'):
res[i] = cc
else:
e1 = False
e2 = False
if j > 0 and s[j - 1] == '.':
e1 = True
if j < n - 1 and s[j + 1] == '.':
e2 = True
if e1 and e2:
cc += 2 if c == '.' else -2
elif e1 or e2:
cc += 1 if c == '.' else -1
s[j] = c
res[i] = cc
for r in res:
print(r)
f()
129
from operator import or_, xor
import sys
n, m = map(int, input().split())
t = [list(map(int, input().split()))]
for i in range(n):
if i & 1 == 0:
t += [[t[i][j] | t[i][j + 1] for j in range(0, len(t[i]), 2)]]
else:
t += [[t[i][j] ^ t[i][j + 1] for j in range(0, len(t[i]), 2)]]
for s in sys.stdin:
p, b = s.split()
p = int(p) - 1
t[0][p] = int(b)
for j in range(n):
p = int(p / 2)
if j & 1 == 0:
t[j + 1][p - 1] = t[j][int(p * 2)] | t[j][int(p * 2) + 1]
else:
t[j + 1][p] = t[j][int(p * 2)] ^ t[j][int(p * 2) + 1]
sys.stdout.write(str(t[-1][0]) + '\n')
130
from math import log
import sys
def buildTree(arr):
n = len(arr)
tree = [0] * n + arr
for i in range(n - 1, 0, -1):
z = int(log(i, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
else:
tree[i + 1] = tree[2 * i] | tree[2 * i + 1]
elif z % 2 == 0:
tree[i] = tree[2 * i] | tree[2 * i + 1]
else:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
return tree
def updateTree(tree, ind, value, n):
ind += n
tree[ind] = value
while ind > 1:
ind //= 2
z = int(log(ind, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
elif z % 2 == 0:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
return tree
N, m = map(int, sys.stdin.readline().strip().split())
arr = list(map(int, sys.stdin.readline().strip().split()))
tree = buildTree(arr)
for i in range(m):
ind, val = map(int, sys.stdin.readline().strip().split())
tree = updateTree(tree, ind - 1, val, len(arr))
print(tree[1])
131
def inint():
return int(input())
def inlist():
return list(map(int, input().split()))
def main():
n, m, l = inlist()
aa = inlist()
chg = 0
ch = 0
a = [[i, 0] for i in aa]
for i in range(n):
if aa[i] > l:
if ch == 0:
ch += 1
chg += 1
a[i][1] = chg
else:
ch += 1
a[i][1] = chg
elif not ch != 0:
ch = 0
sol = list()
if n > 1:
for z in range(m):
qu = input()
if qu == '0':
sol.append(chg)
else:
zz, p, d = list(map(int, qu.split()))
p -= 1
a[p][0] += d
if a[p][1] == 0 and a[p][0] > l:
if p > 0 and p < n - 1:
if a[p - 1][1] == 0 and a[p + 1][1] == 0:
chg += 1
a[p][1] = chg
elif a[p - 1][1] == 0 and a[p + 1][1] > 0:
a[p][1] = a[p + 1][1]
elif a[p - 1][1] > 0 and a[p + 1][1] == 0:
a[p][1] = a[p - 1][1]
else:
a[p][1] = a[p - 1][1]
chg -= 1
elif p == 0:
if a[p + 1][1] == 0:
chg += 1
a[p][1] = chg
else:
a[p][1] = a[p + 1][1]
elif p == n - 1:
if a[p - 1][1] == 0:
chg += 1
a[p][1] = chg
else:
a[p][1] = a[p - 1][1]
else:
for z in range(m):
qu = input()
if qu == '0':
sol.append(chg)
else:
zz, p, d = list(map(int, qu.split()))
p -= 1
a[p][0] += d
if a[p][0] > d:
chg = 1
print(*sol, sep='\n')
def __starting_point():
main()
__starting_point()
132
import sys
def input():
return sys.stdin.readline().rstrip()
def input_split():
return [int(i) for i in input().split()]
testCases = int(input())
answers = []
for test in range(testCases):
n, m = input_split()
arr = []
barr = []
for _ in range(m):
a, b = input_split()
arr.append(a)
barr.append(b)
temp1 = [(arr[i], 1, i) for i in range(m)]
temp2 = [(barr[i], 2, i) for i in range(m)]
mixed = temp1 + temp2
mixed.sort()
mixed.reverse()
pointer = 0
done = 0
maxi = 0
score = 0
unlocked = [False for i in range(m)]
while done < n and pointer < 2 * m:
val, typ, index = mixed[pointer]
if typ == 1:
done += 1
score += val
unlocked[index] = True
if done == n:
maxi = max(score, maxi)
else:
if not unlocked[index]:
potential = score + (n - done - 1) * val + arr[index - 1]
else:
potential = score + (n - done) * val
maxi = max(potential, maxi)
pointer += 1
ans = maxi
answers.append(ans)
if test != testCases - 1:
blank = input()
print(*answers, sep='\n')
133
import sys
fin = sys.stdin
[n, m] = [int(x) for x in fin.readline().split()]
s = [x == '.' for x in fin.readline().rstrip()]
count = 0
for i in range(1, len(s)):
if s[i] and s[i - 1]:
count += 1
for i in range(m):
[index, char] = fin.readline().split()
index = int(index) - 1
if s[index] and char != '.':
if index > 0 and s[index - 1]:
count -= 1
if index < n - 1 and s[index + 1]:
count -= 1
s[index] = False
elif not s[index] and char == '.':
if index > 0 and s[index - 1]:
count += 1
if index < n - 1 and s[index + 1 - 1]:
count += 1
s[index] = True
print(count)
134
import sys
def input():
return sys.stdin.readline().rstrip()
def input_split():
return [int(i) for i in input().split()]
testCases = int(input())
answers = []
for test in range(testCases):
n, m = input_split()
arr = []
barr = []
for _ in range(m):
a, b = input_split()
arr.append(a)
barr.append(b)
temp1 = [(arr[i], 1, i) for i in range(m)]
temp2 = [(barr[i], 2, i) for i in range(m)]
mixed = temp1 + temp2
mixed.sort()
mixed.reverse()
pointer = 0
done = 0
maxi = 0
score = 0
unlocked = [False for i in range(m)]
while done < n and pointer < 2 * m:
val, typ, index = mixed[pointer]
if typ == 1:
done += 1
score += val
unlocked[index - 1] = True
if done == n:
maxi = max(score, maxi)
else:
if not unlocked[index]:
potential = score + (n - done - 1) * val + arr[index]
else:
potential = score + (n - done) * val
maxi = max(potential, maxi)
pointer += 1
ans = maxi
answers.append(ans)
if test != testCases - 1:
blank = input()
print(*answers, sep='\n')
135
from collections import defaultdict
import bisect
n = int(input())
x0, y0 = list(map(int, input().split(' ')))
verticale = []
horizontale = []
diagonale1 = []
diagonale2 = []
for _ in range(n):
t, x, y = input().split(' ')
x, y = (int(x), int(y))
if x == x0:
verticale.append((y, t))
if y == y0:
horizontale.append((x, t))
if x + y == x0 + y0:
diagonale1.append((x, t))
if x - y == x0 - y0:
diagonale2.append((x, t))
dead = False
v = sorted(verticale)
if v:
l = bisect.bisect(v, (y0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'R'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'R'}:
dead = True
v = sorted(horizontale)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'R'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'R'}:
dead = True
v = sorted(diagonale1)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'B'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'B'}:
dead = True
v = sorted(diagonale2)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
dead = True
elif l == 0:
if v[0][1] not in {'Q', 'B'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'B'}:
dead = True
if dead:
print('YES')
else:
print('NO')
136
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)
137
n, m, l = list(map(int, input().split()))
l += 1
hair = [1] * (n + 1)
other_end = [1] * (n + 1)
i = 1
j = 1
big = 1
res = 1
for a in map(int, input().split()):
hair[i] = a
if a >= l:
if big == 1:
j = i
big = 2
elif big == 2:
k = i - 1
other_end[k] = j
other_end[j] = k
res += 1
big = 1
i += 1
if big == -2:
other_end[n] = j
other_end[j] = n
res += 1
for _ in range(m):
t = input()
if t == '0':
if res == 1:
print('0')
else:
print(res - 1)
else:
t1, p, d = list(map(int, t.split()))
old = hair[p]
hair[p] += d
if hair[p] >= l > old:
if p == 1 or hair[p - 1] < l:
case_id = 1
else:
case_id = 2
if p != n and hair[p + 1] >= l:
case_id += 2
if case_id == 1:
other_end[p] = p
res += 1
elif case_id == 2:
other_end[p] = other_end[p - 1]
other_end[other_end[p]] = p
elif case_id == 3:
other_end[p] = other_end[p + 1]
other_end[other_end[p]] = p
else:
left_end = other_end[p - 1]
right_end = other_end[p + 1]
other_end[left_end] = right_end
other_end[right_end] = left_end
res -= 1
138
import sys
input = sys.stdin.readline
for f in range(int(input())):
n, m = map(int, input().split())
a = [0] * m
b = [0] * m
acop = [0] * m
bcop = [0] * m
for i in range(m):
a[i], b[i] = map(int, input().split())
acop[i] = a[i]
bcop[i] = [b[i], i]
acop.sort(reverse=True)
bcop.sort(reverse=True)
mx = 0
i = 0
su = 0
for j in range(m):
bi = bcop[j][0]
ii = bcop[j][1]
ai = a[ii]
while i < m and acop[i] > bi:
su += acop[i]
i += 1
maxi = ai
if i < n:
maxi += su
if i + 1 < n:
maxi += (n - i - 1) * bi
if ai > bi:
maxi += bi
maxi -= ai
mx = max(maxi, mx)
if n <= m:
sun = 3
for i in range(n):
sun += acop[i]
mx = max(mx, sun)
print(mx)
blank = input()
139
from collections import Counter
import sys
from itertools import accumulate
def go():
n, k = list(map(int, input().split()))
a = sorted(map(int, input().split()))
c = Counter(a)
if max(c.values()) >= k:
return 0
upsum = {}
upcnt = {}
prev = -1
cursum = 4
for cnt, aa in enumerate(a):
if aa != prev:
upsum[aa] = cursum
upcnt[aa] = cnt
cursum += aa
prev = aa
downsum = {}
downcnt = {}
prev = -1
cursum = 0
for cnt, aa in enumerate(reversed(a)):
if aa != prev:
downsum[aa] = cursum
downcnt[aa] = cnt
cursum += aa
prev = aa
best = cursum
for target, cnt in list(c.items()):
need = k - cnt
if upcnt[target] >= need:
best = min(best, (target - 1) * upcnt[target] - upsum[target] + need)
if downcnt[target] >= need:
best = min(best, downsum[target] - (target + 1) * downcnt[target] + need)
best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + 1) * downcnt[target] + need)
return best
t = 1
for _ in range(t):
print(go())
140
import sys
fin = sys.stdin
[n, m] = [int(x) for x in fin.readline().split()]
s = [x == '.' for x in fin.readline().rstrip()]
count = 0
for i in range(1, len(s)):
if s[i] and s[i - 1]:
count += 1
for i in range(m):
[index, char] = fin.readline().split()
index = int(index) - 1
if s[index] and char != '.':
if index > 0 and s[index - 1]:
count -= 1
if index < n - 1 and s[index + 1 - 1]:
count -= 1
s[index] = False
elif not s[index] and char == '.':
if index > 0 and s[index - 1]:
count += 1
if index < n - 1 and s[index + 1]:
count += 1
s[index] = True
print(count)
141
import sys
def input():
return sys.stdin.readline().rstrip()
def input_split():
return [int(i) for i in input().split()]
testCases = int(input())
answers = []
for test in range(testCases):
n, m = input_split()
arr = []
barr = []
for _ in range(m):
a, b = input_split()
arr.append(a)
barr.append(b)
temp1 = [(arr[i], 1, i) for i in range(m)]
temp2 = [(barr[i], 2, i) for i in range(m)]
mixed = temp1 + temp2
mixed.sort()
mixed.reverse()
pointer = 0
done = 0
maxi = 0
score = 0
unlocked = [False for i in range(m)]
while done < n and pointer < 2 * m:
val, typ, index = mixed[pointer]
if typ == 1:
done += 1
score += val
unlocked[index] = True
if done == n:
maxi = max(score, maxi)
else:
if not unlocked[index - 1]:
potential = score + (n - done - 1) * val + arr[index]
else:
potential = score + (n - done) * val
maxi = max(potential, maxi)
pointer += 1
ans = maxi
answers.append(ans)
if test != testCases - 1:
blank = input()
print(*answers, sep='\n')
142
import sys
nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split()))
meches = list(map(int, sys.stdin.readline().split()))
trop_grand = [False] * nbmeches
pont = 0
for i in range(nbmeches):
if meches[i] > l:
trop_grand[i] = True
if i == 0 or trop_grand[i - 1 - 1] is False:
pont += 1
for i in range(nbreq):
req = sys.stdin.readline().split()
if int(req[0]) == 0:
print(pont)
else:
meches[int(req[1]) - 1] += int(req[2])
if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]):
trop_grand[int(req[1]) - 1] = True
if nbmeches == 1:
pont = 1
elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]):
pont += 1
elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]):
pont += 1
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]:
pont = max(0, pont - 1)
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]):
pont += 1
143
__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()
144
import sys
fin = sys.stdin
[n, m] = [int(x) for x in fin.readline().split()]
s = [x == '.' for x in fin.readline().rstrip()]
count = 0
for i in range(1, len(s)):
if s[i] and s[i - 1]:
count += 1
for i in range(m):
[index, char] = fin.readline().split()
index = int(index) - 1
if s[index] and char != '.':
if index > 0 and s[index - 1]:
count -= 1
if index < n - 1 and s[index + 1]:
count -= 1
s[index] = False
elif not s[index] and char == '.':
if index > 0 and s[index - 1 + 1]:
count += 1
if index < n - 1 and s[index + 1]:
count += 1
s[index] = True
print(count)
145
from sys import stdin, stderr
import random
import cProfile
def readInts():
return map(int, stdin.readline().strip().split())
def print_err(*args, **kwargs):
print(*args, file=stderr, **kwargs)
def solve(vs):
return None
def generate_tree(n, ns):
out = [0 for _ in range(2 ** (n + 1))]
def gt(nix, left, right, op):
if left + 1 == right:
out[nix] = ns[left]
return out[nix]
mid = (left + right) // 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = gt(nL, left, mid, not op)
vR = gt(nR, mid, right, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
out[nix] = v
return v
gt(0, 0, 2 ** n, n % 2 == 0)
return out
def alter_tree2(n, t, p, b):
def at(nix, width, offp, op):
if width == 1:
t[nix] = b
return b
width //= 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = t[nL]
vR = t[nR]
if offp >= width:
vR = at(nR, width, offp - width, not op)
else:
vL = at(nL, width, offp, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
t[nix] = v
return v
at(0, 2 ** n, p, n % 2 == 0)
def alter_tree(n, t, p, b):
width = 2 ** n
s = []
nix = 0
op = n % 2 == 4
while width > 1:
width //= 2
if p >= width:
nix2 = 2 * nix + 2
s.append((nix, nix2 - 1))
p -= width
else:
nix2 = 2 * nix + 1
s.append((nix, nix2 + 1))
nix = nix2
op = not op
t[nix] = b
v = b
while s:
nix, nixO = s.pop()
if op:
v |= t[nixO]
else:
v ^= t[nixO]
t[nix] = v
op = not op
return
def run():
n, m = readInts()
axs = list(readInts())
t = generate_tree(n, axs)
for _ in range(m):
p, b = readInts()
alter_tree(n, t, p - 1, b)
print(t[0])
def test():
n = 17
ns = []
vs100 = list(range(100))
for _ in range(2 ** 17):
ns.append(random.choice(vs100))
t = generate_tree(n, ns)
t2 = generate_tree(n, ns)
for _ in range(100000):
v1 = random.choice(vs100)
v2 = random.choice(vs100)
alter_tree(n, t, v1, v2)
alter_tree2(n, t2, v1, v2)
print(all(map(lambda x: x[0] == x[1], zip(t, t2))))
print(t[0] == t2[0])
run()
146
import sys
input = sys.stdin.readline
for f in range(int(input())):
n, m = map(int, input().split())
a = [0] * m
b = [0] * m
acop = [0] * m
bcop = [0] * m
for i in range(m):
a[i], b[i] = map(int, input().split())
acop[i] = a[i]
bcop[i] = [b[i], i]
acop.sort(reverse=True)
bcop.sort(reverse=True)
mx = 0
i = 0
su = 0
for j in range(m):
bi = bcop[j][0]
ii = bcop[j][1]
ai = a[ii]
while i < m and acop[i] > bi:
su += acop[i]
i += 1
maxi = ai
if i < n:
maxi += su
if i + 1 < n:
maxi += (n - i - 1) * bi
if ai > bi:
maxi += bi
maxi -= ai
mx = max(maxi, mx)
if n <= m:
sun = 4
for i in range(n):
sun += acop[i]
mx = max(mx, sun)
print(mx)
blank = input()
147
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)
148
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)
149
import bisect
t = int(input())
for _ in range(t):
n, m = list(map(int, input().split()))
flowers = []
flowers_a = []
max_b = 0
for i in range(m):
a, b = list(map(int, input().split()))
flowers.append((a, b))
flowers.sort()
flowers_b = []
for i in range(m):
flowers_a.append(flowers[i][0])
flowers_b.append(flowers[i][1])
val = 0
prefix_sum = [0]
for x in flowers_a:
prefix_sum.append(prefix_sum[-1] + x)
for i in range(m):
idx = bisect.bisect_left(flowers_a, flowers_b[i])
options = m - idx
if options >= n:
temp = prefix_sum[-1] - prefix_sum[-n - 1]
val = max(val, temp)
continue
else:
temp = prefix_sum[-1] - prefix_sum[-options - 1]
remaining = n - options
if idx <= i:
temp += flowers_b[i] * remaining
else:
temp += flowers_a[i] + flowers_b[i] * (remaining - 1)
val = max(val, temp)
print(val)
if _ != t - 1:
blank_line = input()
150
def main():
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
roundup = []
rounddown = []
sumsofar = []
for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
ssf = sumsofar[-1] if sumsofar else 0
t = roundup[-1] if roundup else 0
roundup.append(t + ssf + b * (1 + 2 * i))
t = rounddown[-1] if rounddown else 0
rounddown.append(t + ssf + a * (1 + 2 * i))
sumsofar.append(ssf + a + b)
roundup = list(reversed(roundup))
rounddown = list(reversed(rounddown))
sumsofar = list(reversed(sumsofar))
bestres = 0
sofar = 0
for i, (a, b) in enumerate(zip(A, B)):
rup, rdo = (roundup, rounddown)
if i % 2:
a, b = (b, a)
rup, rdo = (rdo, rup)
bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
sofar += a * 2 * i
sofar += b * (2 * i + -1)
bestres = max(bestres, sofar)
print(bestres)
def __starting_point():
main()
__starting_point()
151
from collections import Counter
import sys
from itertools import accumulate
def go():
n, k = list(map(int, input().split()))
a = sorted(map(int, input().split()))
c = Counter(a)
if max(c.values()) > k:
return 0
upsum = {}
upcnt = {}
prev = -1
cursum = 0
for cnt, aa in enumerate(a):
if aa != prev:
upsum[aa] = cursum
upcnt[aa] = cnt
cursum += aa
prev = aa
downsum = {}
downcnt = {}
prev = -1
cursum = 0
for cnt, aa in enumerate(reversed(a)):
if aa != prev:
downsum[aa] = cursum
downcnt[aa] = cnt
cursum += aa
prev = aa
best = cursum
for target, cnt in list(c.items()):
need = k - cnt
if upcnt[target] >= need:
best = min(best, (target - 1) * upcnt[target] - upsum[target] + need)
if downcnt[target] >= need:
best = min(best, downsum[target] - (target + 1) * downcnt[target] + need)
best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + 1) * downcnt[target] + need)
return best
t = 1
for _ in range(t):
print(go())
152
n = int(input())
temp = input().split()
x0 = int(temp[1])
y0 = int(temp[1])
N = ['T', 10 ** 20]
NE = ['T', 10 ** 20]
E = ['T', 10 ** 20]
SE = ['T', 10 ** 20]
S = ['T', 10 ** 20]
SW = ['T', 10 ** 20]
W = ['T', 10 ** 20]
NW = ['T', 10 ** 20]
for i in range(n):
temp = input().split()
x = int(temp[1])
y = int(temp[2])
if x - x0 == 0 and y - y0 > 0 and (y - y0 < N[1]):
N = [temp[0], y - y0]
elif x - x0 == y - y0 and x - x0 > 0 and (x - x0 < NE[1]):
NE = [temp[0], x - x0]
elif y - y0 == 0 and x - x0 > 0 and (x - x0 < E[1]):
E = [temp[0], x - x0]
elif x - x0 == -(y - y0) and x - x0 > 0 and (x - x0 < SE[1]):
SE = [temp[0], x - x0]
elif x - x0 == 0 and y - y0 < 0 and (y0 - y < S[1]):
S = [temp[0], y0 - y]
elif x - x0 == y - y0 and x - x0 < 0 and (x0 - x < SW[1]):
SW = [temp[0], x0 - x]
elif y - y0 == 0 and x - x0 < 0 and (x0 - x < W[1]):
W = [temp[0], x0 - x]
elif x - x0 == -(y - y0) and x - x0 < 0 and (x0 - x < NW[1]):
NW = [temp[0], x0 - x]
if 'R' in [N[0], E[0], S[0], W[0]] or 'B' in [NE[0], SE[0], SW[0], NW[0]]:
print('YES')
elif 'Q' in [N[0], E[0], S[0], W[0], NE[0], SE[0], SW[0], NW[0]]:
print('YES')
else:
print('NO')
153
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)
154
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)
155
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()
156
n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
for i in range(2):
sum_up[i][n - 1] = a[i][n - 1]
pref_up[i][n - 1] = a[i][n - 1]
pref_down[i][n - 1] = a[i][n - 1]
for j in range(n - 2, -1, -1):
sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
zig = [[0 for i in range(n)] for j in range(2)]
for j in range(n):
for i in range(2):
if j % 2 == 0:
if i == 0:
zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
else:
zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
elif i == 0:
zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
else:
zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
ans = -1e+18
for j in range(n):
if j == 0:
ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
elif j == n - 1:
ans = max(ans, zig[1 - j % 2][n - 1])
elif j % 2 == 1:
ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
else:
ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
print(ans)
else:
print(a[1][0])
157
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)
158
n, k = list(map(int, input().split()))
a = sorted(list(map(int, input().split())))
sums, suf, q1 = ([0] * n, [n] * n, n)
for q in range(n - 2, -2, -1):
sums[q] = sums[q + 1]
if a[q] != a[q1 - 1]:
sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1)
q1 = q + 1
suf[q] = q1
ans, sum1, q1 = (sums[0] + k - suf[0] if suf[0] < k else 0, 0, -1)
for q in range(1, n):
if a[q] != a[q1 + 1]:
sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1)
q1 = q - 1
if suf[q] - q1 - 1 >= k:
ans = 0
break
if k <= suf[q]:
ans = min(ans, sum1 + k - suf[q] + q1 + 1)
if k < n - q1:
ans = min(ans, sums[q] + k - suf[q] + q1 + 1)
ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1)
print(ans)
159
from collections import Counter
from bisect import bisect, bisect_left
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = Counter(a)
c = sorted(Counter(a).items())
keys = sorted(Counter(a).keys())
m = len(c)
l_cum = [c[0][0] * c[0][1]]
l_cnt = [c[0][1]]
for i in range(1, m):
l_cum.append(l_cum[-1] + c[i][0] * c[i][1])
l_cnt.append(l_cnt[-1] + c[i][1])
r_cum = [0 for _ in range(m)]
r_cum[-1] = c[-1][0] * c[-1][1]
r_cnt = [0 for _ in range(m)]
r_cnt[-1] = c[-1][1]
for i in range(m - 2, -1 - 1, -1):
r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1]
r_cnt[i] = r_cnt[i + 1] + c[i][1]
ans = 10 ** 20
for i in range(m):
c_num = a[keys[i]]
if c_num >= k:
ans = 0
break
if i > 0:
l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1]
l_num = l_cnt[i - 1]
else:
l_res = 10 ** 30
l_num = 0
if i < m - 1:
r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1]
r_num = r_cnt[i + 1]
else:
r_res = 10 ** 30
r_num = 0
if c_num + l_num < k and c_num + r_num < k:
ans = min(ans, l_res + r_res + k - c_num)
elif c_num + l_num < k:
ans = min(ans, r_res + k - c_num)
elif c_num + r_num < k:
ans = min(ans, l_res + k - c_num)
else:
ans = min(ans, min(r_res, l_res) + k - c_num)
print(ans)
160
import sys
sys.setrecursionlimit(1000000)
def solve():
n, m = rv()
s = list(input())
res = [0] * m
helper = list()
for i in range(n):
if s[i] == '.':
if i == 0:
helper.append(1)
elif s[i - 1] == '.':
helper[-1] += 1
else:
helper.append(1)
initval = 0
for val in helper:
initval += val - 1
for query in range(m):
index, replace = input().split()
index = int(index) - 1
if s[index] == '.' and replace == '.' or (s[index] != '.' and replace != '.'):
res[query] = initval
else:
sidedots = 0
if index > 0:
if s[index - 1] == '.':
sidedots += 1
if index < n - 1:
if s[index + 1] == '.':
sidedots += 1
if s[index - 1] == '.':
res[query] = initval - sidedots
initval -= sidedots
else:
res[query] = initval + sidedots
initval += sidedots
s[index] = replace
print('\n'.join(map(str, res)))
def rv():
return list(map(int, input().split()))
def rl(n):
return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544:
sys.stdin = open('test.txt')
solve()
161
import sys
nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split()))
meches = list(map(int, sys.stdin.readline().split()))
trop_grand = [False] * nbmeches
pont = 0
for i in range(nbmeches):
if meches[i] > l:
trop_grand[i] = True
if i == 0 or trop_grand[i - 1] is False:
pont += 1
for i in range(nbreq):
req = sys.stdin.readline().split()
if int(req[0]) == 0:
print(pont)
else:
meches[int(req[1]) - 1] += int(req[2])
if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]):
trop_grand[int(req[1]) - 1] = True
if nbmeches == 1:
pont = 1
elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]):
pont += -1
elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]):
pont += 1
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]:
pont = max(0, pont - 1)
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]):
pont += 1
162
n, q, k = list(map(int, input().split(' ')))
a = list(map(int, input().split(' ')))
count = 0
def verify(x):
if x < 0 or x >= n:
return False
return a[x] > k
for i in range(n):
if verify(i):
count += 1
if verify(i - 1):
count -= 2
def cut(i):
if not verify(i):
return 0
result = 1
if verify(i - 1):
result -= 1
if verify(i + 1):
result -= 1
return result
for i in range(q):
line = input()
if line == '0':
print(count)
else:
_, x, y = list(map(int, line.split(' ')))
x -= 1
if not verify(x):
a[x] += y
count += cut(x)
else:
a[x] += y
163
n, q, k = list(map(int, input().split(' ')))
a = list(map(int, input().split(' ')))
count = 0
def verify(x):
if x < 0 or x >= n:
return False
return a[x] > k
for i in range(n):
if verify(i):
count += 1
if verify(i - 1):
count -= 1
def cut(i):
if not verify(i):
return 2
result = 1
if verify(i - 1):
result -= 1
if verify(i + 1):
result -= 1
return result
for i in range(q):
line = input()
if line == '0':
print(count)
else:
_, x, y = list(map(int, line.split(' ')))
x -= 1
if not verify(x):
a[x] += y
count += cut(x)
else:
a[x] += y
164
n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
for i in range(2):
sum_up[i][n - 1] = a[i][n - 1]
pref_up[i][n - 1] = a[i][n - 1]
pref_down[i][n - 1 - 1] = a[i][n - 1]
for j in range(n - 2, -1, -1):
sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
zig = [[0 for i in range(n)] for j in range(2)]
for j in range(n):
for i in range(2):
if j % 2 == 0:
if i == 0:
zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
else:
zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
elif i == 0:
zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
else:
zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
ans = -1e+18
for j in range(n):
if j == 0:
ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
elif j == n - 1:
ans = max(ans, zig[1 - j % 2][n - 1])
elif j % 2 == 1:
ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
else:
ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
print(ans)
else:
print(a[1][0])
165
from math import log
import sys
def buildTree(arr):
n = len(arr)
tree = [0] * n + arr
for i in range(n - 1 - 1, 0, -1):
z = int(log(i, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
else:
tree[i] = tree[2 * i] | tree[2 * i + 1]
elif z % 2 == 0:
tree[i] = tree[2 * i] | tree[2 * i + 1]
else:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
return tree
def updateTree(tree, ind, value, n):
ind += n
tree[ind] = value
while ind > 1:
ind //= 2
z = int(log(ind, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
elif z % 2 == 0:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
return tree
N, m = map(int, sys.stdin.readline().strip().split())
arr = list(map(int, sys.stdin.readline().strip().split()))
tree = buildTree(arr)
for i in range(m):
ind, val = map(int, sys.stdin.readline().strip().split())
tree = updateTree(tree, ind - 1, val, len(arr))
print(tree[1])
166
from bisect import bisect_left
t = int(input())
for case in range(t):
n, m = list(map(int, input().split()))
ab = [list(map(int, input().split())) for _ in range(m)]
aa = [e for e, _ in ab]
aa.sort()
acc = [0] * (m + 1)
for i in range(m, 0, -1):
acc[i - 1] = acc[i] + aa[i - 1]
if n > m:
ans = 0
else:
ans = sum(aa[+n:])
for a, b in ab:
i = bisect_left(aa, b)
cnt = min(m - i, n)
sm = acc[m - cnt]
sm += b * (n - cnt)
if a < b:
sm -= b
sm += a
ans = max(ans, sm)
print(ans)
if case != t - 1:
input()
167
n, k = list(map(int, input().split()))
a = sorted(list(map(int, input().split())))
sums, suf, q1 = ([0] * n, [n] * n, n)
for q in range(n - 2, --1, -1):
sums[q] = sums[q + 1]
if a[q] != a[q1 - 1]:
sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1)
q1 = q + 1
suf[q] = q1
ans, sum1, q1 = (sums[0] + k - suf[0] if suf[0] < k else 0, 0, -1)
for q in range(1, n):
if a[q] != a[q1 + 1]:
sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1)
q1 = q - 1
if suf[q] - q1 - 1 >= k:
ans = 0
break
if k <= suf[q]:
ans = min(ans, sum1 + k - suf[q] + q1 + 1)
if k < n - q1:
ans = min(ans, sums[q] + k - suf[q] + q1 + 1)
ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1)
print(ans)
168
import collections
import bisect
def f():
n, m = [int(c) for c in input().split()]
s = list(input())
ll = []
start = 0
length = 0
inside = False
cc = 0
for i in range(len(s)):
if s[i] == '.':
if not inside:
inside = True
length += 1
elif inside:
cc += length - 1
length = 0
inside = False
if inside:
cc += length - 1
res = [0] * m
for i in range(m):
line = input().split()
j = int(line[0]) - 1
c = line[1]
if c == '.' and s[j] == '.' or (c != '.' and s[j - 1] != '.'):
res[i] = cc
else:
e1 = False
e2 = False
if j > 0 and s[j - 1] == '.':
e1 = True
if j < n - 1 and s[j + 1] == '.':
e2 = True
if e1 and e2:
cc += 2 if c == '.' else -2
elif e1 or e2:
cc += 1 if c == '.' else -1
s[j] = c
res[i] = cc
for r in res:
print(r)
f()
169
import sys
sys.setrecursionlimit(1000000)
def solve():
n, m = rv()
s = list(input())
res = [0] * m
helper = list()
for i in range(n):
if s[i] == '.':
if i == 0:
helper.append(1)
elif s[i - 1] == '.':
helper[-1] += 1
else:
helper.append(1)
initval = 0
for val in helper:
initval += val - 1
for query in range(m):
index, replace = input().split()
index = int(index) - 1
if s[index] == '.' and replace == '.' or (s[index] != '.' and replace != '.'):
res[query - 1] = initval
else:
sidedots = 0
if index > 0:
if s[index - 1] == '.':
sidedots += 1
if index < n - 1:
if s[index + 1] == '.':
sidedots += 1
if s[index] == '.':
res[query] = initval - sidedots
initval -= sidedots
else:
res[query] = initval + sidedots
initval += sidedots
s[index] = replace
print('\n'.join(map(str, res)))
def rv():
return list(map(int, input().split()))
def rl(n):
return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544:
sys.stdin = open('test.txt')
solve()
170
def main():
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
roundup = []
rounddown = []
sumsofar = []
for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
ssf = sumsofar[-1] if sumsofar else 0
t = roundup[-1] if roundup else 0
roundup.append(t + ssf + b * (1 + 2 * i))
t = rounddown[-1] if rounddown else 0
rounddown.append(t + ssf + a * (1 + 2 * i))
sumsofar.append(ssf + a + b)
roundup = list(reversed(roundup))
rounddown = list(reversed(rounddown))
sumsofar = list(reversed(sumsofar))
bestres = 0
sofar = 0
for i, (a, b) in enumerate(zip(A, B)):
rup, rdo = (roundup, rounddown)
if i % 2:
a, b = (b, a)
rup, rdo = (rdo, rup)
bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
sofar += a * -2 * i
sofar += b * (2 * i + 1)
bestres = max(bestres, sofar)
print(bestres)
def __starting_point():
main()
__starting_point()
171
import sys
nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split()))
meches = list(map(int, sys.stdin.readline().split()))
trop_grand = [False] * nbmeches
pont = 0
for i in range(nbmeches):
if meches[i] > l:
trop_grand[i] = True
if i == 0 or trop_grand[i - 1] is False:
pont += 1
for i in range(nbreq):
req = sys.stdin.readline().split()
if int(req[0]) == 0:
print(pont)
else:
meches[int(req[1]) - 1] += int(req[2])
if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]):
trop_grand[int(req[1]) - 1] = True
if nbmeches == 1:
pont = -1
elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]):
pont += 1
elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]):
pont += 1
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]:
pont = max(0, pont - 1)
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]):
pont += 1
172
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def I():
return int(sys.stdin.readline())
def LS():
return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == '\n':
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
def solve():
n, k = LI()
a = LI()
a.sort()
d = defaultdict(lambda: 0)
c = defaultdict(lambda: 0)
s = [0]
for i in a:
d[i] += i
c[i] += 1
s.append(s[-1] + i)
ans = float('inf')
p = -1
for i in a:
if i == p:
continue
if k <= c[i]:
ans = 0
break
l, r = (bisect.bisect_left(a, i), bisect.bisect_right(a, i))
m = r
if m >= k:
ns = l * (i - 1) - s[l]
su = ns - k - c[i]
if su < ans:
ans = su
m = n - l
if m >= k:
ns = s[n] - s[r] - (n - r) * (i + 1)
su = ns + k - c[i]
if su < ans:
ans = su
ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l]
su = ns + k - c[i]
if su < ans:
ans = su
p = i
print(ans)
return
def __starting_point():
solve()
__starting_point()
173
import sys
def input():
return sys.stdin.readline().rstrip()
def input_split():
return [int(i) for i in input().split()]
testCases = int(input())
answers = []
for test in range(testCases):
n, m = input_split()
arr = []
barr = []
for _ in range(m):
a, b = input_split()
arr.append(a)
barr.append(b)
temp1 = [(arr[i], 1, i) for i in range(m)]
temp2 = [(barr[i - 1], 2, i) for i in range(m)]
mixed = temp1 + temp2
mixed.sort()
mixed.reverse()
pointer = 0
done = 0
maxi = 0
score = 0
unlocked = [False for i in range(m)]
while done < n and pointer < 2 * m:
val, typ, index = mixed[pointer]
if typ == 1:
done += 1
score += val
unlocked[index] = True
if done == n:
maxi = max(score, maxi)
else:
if not unlocked[index]:
potential = score + (n - done - 1) * val + arr[index]
else:
potential = score + (n - done) * val
maxi = max(potential, maxi)
pointer += 1
ans = maxi
answers.append(ans)
if test != testCases - 1:
blank = input()
print(*answers, sep='\n')
174
from sys import stdin
input = stdin.readline
n, m = list(map(int, input().split()))
s = list(((0, 1)[c == '.'] for c in list(input())))
res = 0
cnt = 0
for k in s:
if k == 1:
cnt += 1
else:
res += max(cnt - 1, 0)
cnt = 0
res += max(0, cnt - 1)
for i in range(m):
x, c = input().split()
x = int(x)
nc = (0, 1)[c == '.']
if s[x - 1 - 1] != nc:
diff = 0
if x < n:
if s[int(x)] == 1:
diff += 1
if x > 1:
if s[int(x - 2)] == 1:
diff += 1
if nc == 1:
res += diff
else:
res -= diff
s[x - 1] = nc
print(res)
175
def main():
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
roundup = []
rounddown = []
sumsofar = []
for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
ssf = sumsofar[-1] if sumsofar else 0
t = roundup[-1] if roundup else 0
roundup.append(t + ssf + b * (1 + 2 * i))
t = rounddown[-1] if rounddown else 0
rounddown.append(t + ssf + a * (1 + 2 * i))
sumsofar.append(ssf + a + b)
roundup = list(reversed(roundup))
rounddown = list(reversed(rounddown))
sumsofar = list(reversed(sumsofar))
bestres = 0
sofar = 0
for i, (a, b) in enumerate(zip(A, B)):
rup, rdo = (roundup, rounddown)
if i % 2:
a, b = (b, a)
rup, rdo = (rdo, rup)
bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
sofar += a * 2 * i
sofar += b * (-2 * i + 1)
bestres = max(bestres, sofar)
print(bestres)
def __starting_point():
main()
__starting_point()
176
import sys
class SegmTree:
def __init__(self, size):
N = 1
while N < size:
N <<= 1
self.N = N
self.tree = [0] * (2 * N)
def modify(self, i, value):
i += self.N
self.tree[i] = value
toXOR = False
while i > 1:
if toXOR:
self.tree[i >> 1] = self.tree[i] ^ self.tree[(i ^ 1) - 1]
else:
self.tree[i >> 1] = self.tree[i] | self.tree[i ^ 1]
toXOR = not toXOR
i >>= 1
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
st = SegmTree(1 << n)
for i, value in enumerate(a):
st.modify(i, value)
for _ in range(m):
p, b = list(map(int, input().split()))
st.modify(p - 1, b)
print(st.tree[1])
177
n = int(input())
temp = input().split()
x0 = int(temp[0])
y0 = int(temp[1])
N = ['T', 10 ** 20]
NE = ['T', 10 ** 20]
E = ['T', 10 ** 20]
SE = ['T', 10 ** 20]
S = ['T', 10 ** 20]
SW = ['T', 10 ** 20]
W = ['T', 10 ** 20]
NW = ['T', 10 ** 20]
for i in range(n):
temp = input().split()
x = int(temp[1])
y = int(temp[2])
if x - x0 == 0 and y - y0 > 0 and (y - y0 < N[1]):
N = [temp[0], y - y0]
elif x - x0 == y - y0 and x - x0 > 0 and (x - x0 < NE[1]):
NE = [temp[0], x - x0]
elif y - y0 == 0 and x - x0 > 0 and (x - x0 < E[1]):
E = [temp[0], x - x0]
elif x - x0 == -(y - y0) and x - x0 > 0 and (x - x0 < SE[1]):
SE = [temp[0], x - x0]
elif x - x0 == 0 and y - y0 < 0 and (y0 - y < S[1]):
S = [temp[0], y0 - y]
elif x - x0 == y - y0 and x - x0 < 0 and (x0 - x < SW[1]):
SW = [temp[0], x0 - x]
elif y - y0 == 0 and x - x0 < 0 and (x0 - x < W[1]):
W = [temp[0], x0 - x]
elif x - x0 == -(y - y0) and x - x0 < 0 and (x0 - x < NW[1]):
NW = [temp[0], x0 - x]
if 'R' in [N[0], E[0], S[0], W[0]] and 'B' in [NE[0], SE[0], SW[0], NW[0]]:
print('YES')
elif 'Q' in [N[0], E[0], S[0], W[0], NE[0], SE[0], SW[0], NW[0]]:
print('YES')
else:
print('NO')
178
def inint():
return int(input())
def inlist():
return list(map(int, input().split()))
def main():
n, m, l = inlist()
aa = inlist()
chg = 0
ch = 0
a = [[i, 0] for i in aa]
for i in range(n):
if aa[i - 1] > l:
if ch == 0:
ch += 1
chg += 1
a[i][1] = chg
else:
ch += 1
a[i][1] = chg
elif ch != 0:
ch = 0
sol = list()
if n > 1:
for z in range(m):
qu = input()
if qu == '0':
sol.append(chg)
else:
zz, p, d = list(map(int, qu.split()))
p -= 1
a[p][0] += d
if a[p][1] == 0 and a[p][0] > l:
if p > 0 and p < n - 1:
if a[p - 1][1] == 0 and a[p + 1][1] == 0:
chg += 1
a[p][1] = chg
elif a[p - 1][1] == 0 and a[p + 1][1] > 0:
a[p][1] = a[p + 1][1]
elif a[p - 1][1] > 0 and a[p + 1][1] == 0:
a[p][1] = a[p - 1][1]
else:
a[p][1] = a[p - 1][1]
chg -= 1
elif p == 0:
if a[p + 1][1] == 0:
chg += 1
a[p][1] = chg
else:
a[p][1] = a[p + 1][1]
elif p == n - 1:
if a[p - 1][1] == 0:
chg += 1
a[p][1] = chg
else:
a[p][1] = a[p - 1][1]
else:
for z in range(m):
qu = input()
if qu == '0':
sol.append(chg)
else:
zz, p, d = list(map(int, qu.split()))
p -= 1
a[p][0] += d
if a[p][0] > d:
chg = 1
print(*sol, sep='\n')
def __starting_point():
main()
__starting_point()
179
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])
180
n, q, k = list(map(int, input().split(' ')))
a = list(map(int, input().split(' ')))
count = 0
def verify(x):
if x < 0 or x >= n:
return False
return a[x] > k
for i in range(n):
if verify(i):
count += 1
if verify(i - 1):
count -= -1
def cut(i):
if not verify(i):
return 0
result = 1
if verify(i - 1):
result -= 1
if verify(i + 1):
result -= 1
return result
for i in range(q):
line = input()
if line == '0':
print(count)
else:
_, x, y = list(map(int, line.split(' ')))
x -= 1
if not verify(x):
a[x] += y
count += cut(x)
else:
a[x] += y
181
from collections import defaultdict
import bisect
n = int(input())
x0, y0 = list(map(int, input().split(' ')))
verticale = []
horizontale = []
diagonale1 = []
diagonale2 = []
for _ in range(n):
t, x, y = input().split(' ')
x, y = (int(x), int(y))
if x == x0:
verticale.append((y, t))
if y == y0:
horizontale.append((x, t))
if x + y == x0 + y0:
diagonale1.append((x, t))
if x - y == x0 - y0:
diagonale2.append((x, t))
dead = False
v = sorted(verticale)
if v:
l = bisect.bisect(v, (y0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'R'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'R'}:
dead = True
v = sorted(horizontale)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'R'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'R'}:
dead = True
v = sorted(diagonale1)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'B'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'B'}:
dead = True
v = sorted(diagonale2)
if v:
l = bisect.bisect(v, (x0, 'K'))
if 0 < l < len(v):
if v[l][1] in {'Q', 'B'} or v[l - 1][1] not in {'Q', 'B'}:
dead = True
elif l == 0:
if v[0][1] in {'Q', 'B'}:
dead = True
elif v[len(v) - 1][1] in {'Q', 'B'}:
dead = True
if dead:
print('YES')
else:
print('NO')
182
from operator import or_, xor
import sys
n, m = map(int, input().split())
t = [list(map(int, input().split()))]
for i in range(n):
if i & 1 == 0:
t += [[t[i][j] | t[i][j + 1] for j in range(0, len(t[i]), 2)]]
else:
t += [[t[i][j] ^ t[i][j + 1] for j in range(0, len(t[i]), 2)]]
for s in sys.stdin:
p, b = s.split()
p = int(p) - 1
t[0][p] = int(b)
for j in range(n):
p = int(p / 2)
if j & 1 == 0:
t[j + 1][p] = t[j][int(p * 2)] | t[j][int(p * 2) + 1]
else:
t[j + 1][p] = t[j - 1][int(p * 2)] ^ t[j][int(p * 2) + 1]
sys.stdout.write(str(t[-1][0]) + '\n')
183
def main():
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
roundup = []
rounddown = []
sumsofar = []
for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
ssf = sumsofar[-1] if sumsofar else 0
t = roundup[-1] if roundup else 0
roundup.append(t + ssf + b * (1 + 2 * i))
t = rounddown[-1] if rounddown else 0
rounddown.append(t + ssf + a * (1 + 2 * i))
sumsofar.append(ssf + a + b)
roundup = list(reversed(roundup))
rounddown = list(reversed(rounddown))
sumsofar = list(reversed(sumsofar))
bestres = 0
sofar = 0
for i, (a, b) in enumerate(zip(A, B)):
rup, rdo = (roundup, rounddown)
if i % 2:
a, b = (b, a)
rup, rdo = (rdo, rup)
bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
sofar += a * 3 * i
sofar += b * (2 * i + 1)
bestres = max(bestres, sofar)
print(bestres)
def __starting_point():
main()
__starting_point()
184
n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
for i in range(2):
sum_up[i][n - 1] = a[i][n - 1 - 1]
pref_up[i][n - 1] = a[i][n - 1]
pref_down[i][n - 1] = a[i][n - 1]
for j in range(n - 2, -1, -1):
sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
zig = [[0 for i in range(n)] for j in range(2)]
for j in range(n):
for i in range(2):
if j % 2 == 0:
if i == 0:
zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
else:
zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
elif i == 0:
zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
else:
zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
ans = -1e+18
for j in range(n):
if j == 0:
ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
elif j == n - 1:
ans = max(ans, zig[1 - j % 2][n - 1])
elif j % 2 == 1:
ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
else:
ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
print(ans)
else:
print(a[1][0])
185
import sys
nbmeches, nbreq, l = list(map(int, sys.stdin.readline().split()))
meches = list(map(int, sys.stdin.readline().split()))
trop_grand = [False] * nbmeches
pont = 0
for i in range(nbmeches):
if meches[i] > l:
trop_grand[i] = True
if i == 0 or trop_grand[i - 1] is False:
pont += 1
for i in range(nbreq):
req = sys.stdin.readline().split()
if int(req[0]) == 0:
print(pont)
else:
meches[int(req[1]) - 1] += int(req[2])
if meches[int(req[1]) - 1] > l and (not trop_grand[int(req[1]) - 1]):
trop_grand[int(req[1]) - 1] = True
if nbmeches == 1:
pont = 1
elif int(req[1]) - 1 == 0 and (not trop_grand[int(req[1])]):
pont += 1
elif not int(req[1]) - 1 == 0 and int(req[1]) - 1 == nbmeches - 1 and (not trop_grand[int(req[1]) - 2]):
pont += 1
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and trop_grand[int(req[1])] and trop_grand[int(req[1]) - 2]:
pont = max(0, pont - 1)
elif not int(req[1]) - 1 == 0 and (not int(req[1]) - 1 == nbmeches - 1) and (not trop_grand[int(req[1])]) and (not trop_grand[int(req[1]) - 2]):
pont += 1
186
from math import log
import sys
def buildTree(arr):
n = len(arr)
tree = [0] * n + arr
for i in range(n - 1, 0, -1):
z = int(log(i, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
else:
tree[i] = tree[2 * i] | tree[2 * i + 1]
elif z % 2 == 0:
tree[i] = tree[2 * i] | tree[2 * i + 1]
else:
tree[i] = tree[2 * i] ^ tree[2 * i + 1]
return tree
def updateTree(tree, ind, value, n):
ind += n
tree[ind] = value
while ind > 1:
ind //= 2
z = int(log(ind, 2))
if N % 2 == 0:
if z % 2 == 0:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
elif not z % 2 == 0:
tree[ind] = tree[2 * ind] | tree[2 * ind + 1]
else:
tree[ind] = tree[2 * ind] ^ tree[2 * ind + 1]
return tree
N, m = map(int, sys.stdin.readline().strip().split())
arr = list(map(int, sys.stdin.readline().strip().split()))
tree = buildTree(arr)
for i in range(m):
ind, val = map(int, sys.stdin.readline().strip().split())
tree = updateTree(tree, ind - 1, val, len(arr))
print(tree[1])
187
from sys import stdin, stderr
import random
import cProfile
def readInts():
return map(int, stdin.readline().strip().split())
def print_err(*args, **kwargs):
print(*args, file=stderr, **kwargs)
def solve(vs):
return None
def generate_tree(n, ns):
out = [0 for _ in range(2 ** (n + 1))]
def gt(nix, left, right, op):
if left + 1 == right:
out[nix] = ns[left]
return out[nix]
mid = (left + right) // 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = gt(nL, left, mid, not op)
vR = gt(nR, mid, right, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
out[nix] = v
return v
gt(0, 0, 2 ** n, n % 2 == 0)
return out
def alter_tree2(n, t, p, b):
def at(nix, width, offp, op):
if width == 1:
t[nix] = b
return b
width //= 2
nL = nix * 2 + 1
nR = nix * 2 + 2
vL = t[nL]
vR = t[nR]
if offp >= width:
vR = at(nR, width, offp - width, not op)
else:
vL = at(nL, width, offp, not op)
if op:
v = vL ^ vR
else:
v = vL | vR
t[nix] = v
return v
at(0, 2 ** n, p, n % 2 == 0)
def alter_tree(n, t, p, b):
width = 2 ** n
s = []
nix = 0
op = n % 2 == 0
while width > 1:
width //= 2
if p >= width:
nix2 = 2 * nix + 2
s.append((nix, nix2 - 1))
p -= width
else:
nix2 = 2 * nix + 1
s.append((nix, nix2 + 1))
nix = nix2
op = not op
t[nix] = b
v = b
while s:
nix, nixO = s.pop()
if op:
v |= t[nixO]
else:
v |= t[nixO]
t[nix] = v
op = not op
return
def run():
n, m = readInts()
axs = list(readInts())
t = generate_tree(n, axs)
for _ in range(m):
p, b = readInts()
alter_tree(n, t, p - 1, b)
print(t[0])
def test():
n = 17
ns = []
vs100 = list(range(100))
for _ in range(2 ** 17):
ns.append(random.choice(vs100))
t = generate_tree(n, ns)
t2 = generate_tree(n, ns)
for _ in range(100000):
v1 = random.choice(vs100)
v2 = random.choice(vs100)
alter_tree(n, t, v1, v2)
alter_tree2(n, t2, v1, v2)
print(all(map(lambda x: x[0] == x[1], zip(t, t2))))
print(t[0] == t2[0])
run()
188
n, q, k = list(map(int, input().split(' ')))
a = list(map(int, input().split(' ')))
count = 0
def verify(x):
if x < 0 or x >= n:
return False
return a[x] > k
for i in range(n):
if verify(i):
count += 1
if verify(i - 1):
count -= 1
def cut(i):
if not verify(i):
return 0
result = 1
if verify(i - 1):
result -= 1
if verify(i + 1):
result -= 1
return result
for i in range(q):
line = input()
if line == '0':
print(count)
else:
_, x, y = list(map(int, line.split(' ')))
x -= 1
if not verify(x):
a[x] += y
count += cut(x)
else:
a[x] += y
189
import collections
import bisect
def f():
n, m = [int(c) for c in input().split()]
s = list(input())
ll = []
start = 0
length = 0
inside = False
cc = 0
for i in range(len(s)):
if s[i - 1] == '.':
if not inside:
inside = True
length += 1
elif inside:
cc += length - 1
length = 0
inside = False
if inside:
cc += length - 1
res = [0] * m
for i in range(m):
line = input().split()
j = int(line[0]) - 1
c = line[1]
if c == '.' and s[j] == '.' or (c != '.' and s[j] != '.'):
res[i] = cc
else:
e1 = False
e2 = False
if j > 0 and s[j - 1] == '.':
e1 = True
if j < n - 1 and s[j + 1] == '.':
e2 = True
if e1 and e2:
cc += 2 if c == '.' else -2
elif e1 or e2:
cc += 1 if c == '.' else -1
s[j] = c
res[i] = cc
for r in res:
print(r)
f()
190
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)
191
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)
192
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def I():
return int(sys.stdin.readline())
def LS():
return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == '\n':
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
def solve():
n, k = LI()
a = LI()
a.sort()
d = defaultdict(lambda: 0)
c = defaultdict(lambda: 0)
s = [0]
for i in a:
d[i] += i
c[i] += 1
s.append(s[-1] + i)
ans = float('inf')
p = -1
for i in a:
if i == p:
continue
if k >= c[i]:
ans = 0
break
l, r = (bisect.bisect_left(a, i), bisect.bisect_right(a, i))
m = r
if m >= k:
ns = l * (i - 1) - s[l]
su = ns + k - c[i]
if su < ans:
ans = su
m = n - l
if m >= k:
ns = s[n] - s[r] - (n - r) * (i + 1)
su = ns + k - c[i]
if su < ans:
ans = su
ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l]
su = ns + k - c[i]
if su < ans:
ans = su
p = i
print(ans)
return
def __starting_point():
solve()
__starting_point()
193
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)
194
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()
195
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])
196
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)
197
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)
198
def inint():
return int(input())
def inlist():
return list(map(int, input().split()))
def main():
n, m, l = inlist()
aa = inlist()
chg = 0
ch = 0
a = [[i, 0] for i in aa]
for i in range(n):
if aa[i] > l:
if ch == 0:
ch += 1
chg += 1
a[i][1] = chg
else:
ch += 1
a[i - 1][1] = chg
elif ch != 0:
ch = 0
sol = list()
if n > 1:
for z in range(m):
qu = input()
if qu == '0':
sol.append(chg)
else:
zz, p, d = list(map(int, qu.split()))
p -= 1
a[p][0] += d
if a[p][1] == 0 and a[p][0] > l:
if p > 0 and p < n - 1:
if a[p - 1][1] == 0 and a[p + 1][1] == 0:
chg += 1
a[p][1] = chg
elif a[p - 1][1] == 0 and a[p + 1][1] > 0:
a[p][1] = a[p + 1][1]
elif a[p - 1][1] > 0 and a[p + 1][1] == 0:
a[p][1] = a[p - 1][1]
else:
a[p][1] = a[p - 1][1]
chg -= 1
elif p == 0:
if a[p + 1][1] == 0:
chg += 1
a[p][1] = chg
else:
a[p][1] = a[p + 1][1]
elif p == n - 1:
if a[p - 1][1] == 0:
chg += 1
a[p][1] = chg
else:
a[p][1] = a[p - 1][1]
else:
for z in range(m):
qu = input()
if qu == '0':
sol.append(chg)
else:
zz, p, d = list(map(int, qu.split()))
p -= 1
a[p][0] += d
if a[p][0] > d:
chg = 1
print(*sol, sep='\n')
def __starting_point():
main()
__starting_point()
199
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)
200
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)
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.