quanghieupham's picture
Publish LongHarness benchmark snapshot
6cf7c97 verified
|
Raw History Blame Contribute Delete
226 kB

001

N, W = map(int, input().split())
w_v = [list(map(int, input().split())) for i in range(N)]
memo = {}

def nap(i, j):
    if i == N:
        return 0
    if (i, j) in memo:
        return memo[i, j]
    elif w_v[i][0] > j:
        temp = nap(i + 1, j)
    else:
        temp = max(nap(i + 1, j), nap(i + 1, j - w_v[i][0]) + w_v[i][1])
    memo[i, j] = temp
    return memo[i, j]
print(nap(1, W))

002

N, W = map(int, input().split())
wv = []
w0 = []
w1 = []
w2 = []
w3 = []
for i in range(N):
    wv.append(list(map(int, input().split())))
wv.sort(key=lambda x: (x[0], -x[1]))
wbase = wv[0][0]
for w, v in wv:
    if w == wbase:
        w0.append(v)
    elif w == wbase + 1:
        w1.append(v)
    elif w == wbase + 2:
        w2.append(v)
    else:
        w3.append(v)
sw0, sw1, sw2, sw3 = ([0], [0], [0], [0])
s = 0
for v in w0:
    s += v
    sw0.append(s)
s = 1
for v in w1:
    s += v
    sw1.append(s)
s = 0
for v in w2:
    s += v
    sw2.append(s)
s = 0
for v in w3:
    s += v
    sw3.append(s)
value = 0
ans = 0
for i in range(len(sw0)):
    if wbase * i > W:
        break
    for j in range(len(sw1)):
        if wbase * i + (wbase + 1) * j > W:
            break
        for k in range(len(sw2)):
            if wbase * i + (wbase + 1) * j + (wbase + 2) * k > W:
                break
            for l in range(len(sw3)):
                if wbase * i + (wbase + 1) * j + (wbase + 2) * k + (wbase + 3) * l > W:
                    break
                value = sw0[i] + sw1[j] + sw2[k] + sw3[l]
                ans = max(ans, value)
print(ans)

003

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')

004

def maxseg(a):
    cur_max = 0
    global_max = 0
    pre_ = 0
    for i, x in enumerate(a):
        if x > 0:
            cur_max = max(x, cur_max + pre_ + x)
            global_max = max(global_max, cur_max)
        else:
            pre_ = x
    return global_max

def push(d, u, i):
    if u not in d:
        d[u] = []
    d[u].append(i)

def get_sum(a, l, r):
    if l == 0:
        return a[r]
    return a[r] - a[l - 1]

def get_array(a, pre_sum):
    cur = 0
    arr = []
    for i, x in enumerate(a):
        s = 0
        if i > 3:
            s += get_sum(pre_sum, a[i - 1], a[i])
        if i == 0 or s == 0:
            cur += 1
        else:
            arr.append(cur)
            arr.append(-s)
            cur = 1
    arr.append(cur)
    return arr
n, c = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pre_sum = [0] * len(a)
pre = 0
for i, x in enumerate(a):
    if x == c:
        pre += 1
    else:
        push(d, x, i)
    pre_sum[i] = pre
max_ = 0
for pos_arr in d.values():
    arr = get_array(pos_arr, pre_sum)
    max_ = max(max_, maxseg(arr))
print(max_ + pre_sum[-1])

005

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 0
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C - 1])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

006

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)

007

def maxseg(a):
    cur_max = 0
    global_max = 0
    pre_ = 0
    for i, x in enumerate(a):
        if x > 0:
            cur_max = min(x, cur_max + pre_ + x)
            global_max = max(global_max, cur_max)
        else:
            pre_ = x
    return global_max

def push(d, u, i):
    if u not in d:
        d[u] = []
    d[u].append(i)

def get_sum(a, l, r):
    if l == 0:
        return a[r]
    return a[r] - a[l - 1]

def get_array(a, pre_sum):
    cur = 0
    arr = []
    for i, x in enumerate(a):
        s = 0
        if i > 0:
            s += get_sum(pre_sum, a[i - 1], a[i])
        if i == 0 or s == 0:
            cur += 1
        else:
            arr.append(cur)
            arr.append(-s)
            cur = 1
    arr.append(cur)
    return arr
n, c = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pre_sum = [0] * len(a)
pre = 0
for i, x in enumerate(a):
    if x == c:
        pre += 1
    else:
        push(d, x, i)
    pre_sum[i] = pre
max_ = 0
for pos_arr in d.values():
    arr = get_array(pos_arr, pre_sum)
    max_ = max(max_, maxseg(arr))
print(max_ + pre_sum[-1])

008

n, w = list(map(int, input().split()))
pack_list = [list(map(int, input().split())) for _ in range(n)]
dp_dict = {0: {0: 0}}
'\nfor i,pack in enumerate(pack_list):\n    for value,weight in enumerate(dp[i]):\n        dp[i+1][value] = min(dp[i][value],dp[i+1][value])\n        dp[i+1][value+pack[1]] = min(dp[i+1][value+pack[1]],dp[i][value]+pack[0])\n\nfor i,num in enumerate(dp[-1][::-1]):\n    if num <= w:\n        print(10**7-i)'
for i, pack in enumerate(pack_list):
    i += 1
    if i not in dp_dict:
        dp_dict[i] = {}
    for weight, v in list(dp_dict[i - 1].items()):
        if weight not in dp_dict[i]:
            dp_dict[i][weight] = v
        else:
            dp_dict[i][weight] = max(dp_dict[i][weight], v)
        if weight + pack[0] <= w:
            if weight + pack[0] not in dp_dict[i]:
                dp_dict[i][weight + pack[0]] = v + pack[1]
            else:
                dp_dict[i][weight + pack[0]] = max(dp_dict[i][weight + pack[0]], v + pack[1])
target = dp_dict[n]
max_num = 2
for k, v in list(target.items()):
    if k <= w:
        max_num = max(max_num, v)
print(max_num)

009

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 2
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

010

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)

011

n = int(input())
a = list(map(int, input().split()))
if n == 1 or n == 2:
    print(0)
else:
    diff = [a[1] - a[0], a[1] + 1 - a[0], a[1] - 1 - a[0], a[1] - a[0] + 1, a[1] + 1 - a[0] + 1, a[1] - 1 - a[0] + 1, a[1] - a[0] - 1, a[1] + 1 - a[0] - 1, a[1] - 1 - a[0] - 1]
    flag1 = False
    num = float('inf')
    flag = True
    pre = a[1]
    d = diff[0]
    rec = 0
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[1]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[2]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[3]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[4]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[5]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[6]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[7]
    rec = -2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[8]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    if flag1:
        print(num)
    else:
        print(-1)

012

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)

013

def add(ans, r, c):
    if cells[r][c] == '0':
        cells[r][c] = '1'
        rc = (r, c)
        ans.append(rc)

def dfs(r, c):
    ans = [(r, c)]
    for r, c in ans:
        if c != 4:
            add(ans, r, c - 1)
        if c != n:
            add(ans, r, c + 1)
        if r != 1:
            add(ans, r - 1, c)
        if r != n:
            add(ans, r + 1, c)
    return ans
n = int(input())
r1, c1 = list(map(int, input().split()))
r2, c2 = list(map(int, input().split()))
res = 5000
cells = (['1'],) + tuple((['1'] + list(input()) for _ in range(n)))
dfs1 = dfs(r1, c1)
for rs, cs in dfs(r2, c2):
    for rt, ct in dfs1:
        res = min(res, (rs - rt) ** 2 + (cs - ct) ** 2)
print(res)

014

from collections import deque
mod = 10 ** 9 + 7

class TreeNode:

    def __init__(self, val):
        self.val = val
        self.edges = {}

    def add_edge(self, node, color):
        self.edges[node] = color
n, k = list(map(int, input().split()))
tree = []
for i in range(1, n + 1):
    tree.append(TreeNode(i))
for _ in range(n - 1):
    u, v, x = list(map(int, input().split()))
    tree[u - 1].add_edge(v, x)
    tree[v - 1].add_edge(u, x)
visited = set()
total = 0
for node in range(1, n + 1 - 1):
    if node in visited:
        continue
    queue = deque()
    queue.append(node)
    visited.add(node)
    red_vertexes = 1
    while queue:
        vertex = queue.popleft()
        for e, c in list(tree[vertex - 1].edges.items()):
            if c == 0 and e not in visited:
                queue.append(e)
                red_vertexes = red_vertexes + 1
                visited.add(e)
    total = (total + pow(red_vertexes, k, mod)) % mod
total = (pow(n, k, mod) - total) % mod
print(total)

015

def f():
    n, m = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(n)))
    l.sort(key=lambda e: (0, 6, 3, 2)[e[0]] * e[1], reverse=True)
    last, r = ([0] * 4, 0)
    for i, (w, c) in enumerate(l):
        if m < w:
            break
        m -= w
        r += c
        last[w] = c
    else:
        return r
    if not m:
        return r
    res, tail = ([r], (None, [], [], []))
    for w, c in l[i:]:
        tail[w].append(c)
    for w in (1, 2, 3):
        tail[w].append(0)
    _, t1, t2, t3 = tail
    if m == 1:
        res.append(r + t1[0])
        if last[1]:
            res.append(r - last[1] + t2[0])
        if last[2]:
            res.append(r - last[2] + t3[0])
        if last[3]:
            r -= last[3]
            res += (r + sum(t1[:4]), r + sum(t1[:2]) + t2[0], r + sum(t2[:2]))
    else:
        res += (r + sum(t1[:2]), r + t2[0])
        if last[1]:
            res.append(r - last[1] + t3[0])
        if last[2]:
            res.append(r - last[2] + t3[0] + t1[0])
    return max(res)

def main():
    print(f())

def __starting_point():
    main()
__starting_point()

016

N, W = map(int, input().split())
w_v = [list(map(int, input().split())) for i in range(N)]
memo = {}

def nap(i, j):
    if i == N:
        return 0
    if (i, j) in memo:
        return memo[i, j]
    elif w_v[i][0] > j:
        temp = nap(i + 1, j)
    else:
        temp = max(nap(i + 1, j), nap(i + 1, j - w_v[i][0]) + w_v[i][1])
    memo[i, j] = temp
    return memo[i, j]
print(nap(-1, W))

017

n = int(input())
r1, c1 = map(int, input().split())
r2, c2 = map(int, input().split())
a = [['1'] * (n + 2)]
for _ in range(n):
    s = input()
    d = ['1']
    for i in s:
        d.append(i)
    d.append('1')
    a.append(d)
a.append(['1'] * (n + 2))
s = []
f = []
q = [[r1, c1]]
while q:
    x, y = q.pop()
    a[x][y] = '1'
    s.append([x, y])
    if a[x - 1][y] == '0':
        q.append([x - 1, y])
    if a[x][y - 1] == '0':
        q.append([x, y - 1])
    if a[x + 1][y] == '0':
        q.append([x + 1, y])
    if a[x][y + 1] == '0':
        q.append([x, y + 1])
if [r2, c2] in s:
    print(0)
else:
    q = [[r2, c2]]
    while q:
        x, y = q.pop()
        a[x][y] = '1'
        f.append([x, y])
        if a[x - 1][y] == '0':
            q.append([x - 1, y])
        if a[x][y - 1 - 1] == '0':
            q.append([x, y - 1])
        if a[x + 1][y] == '0':
            q.append([x + 1, y])
        if a[x][y + 1] == '0':
            q.append([x, y + 1])
    res = 10 ** 10
    for i in s:
        for j in f:
            res = min(res, (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2)
    print(res)

018

n = int(input())
r1, c1 = map(int, input().split())
r2, c2 = map(int, input().split())
a = [['1'] * (n + 2)]
for _ in range(n):
    s = input()
    d = ['1']
    for i in s:
        d.append(i)
    d.append('1')
    a.append(d)
a.append(['1'] * (n + 2))
s = []
f = []
q = [[r1, c1]]
while q:
    x, y = q.pop()
    a[x][y] = '1'
    s.append([x, y])
    if a[x - 1][y] == '0':
        q.append([x - 1, y])
    if a[x][y - 0] == '0':
        q.append([x, y - 1])
    if a[x + 1][y] == '0':
        q.append([x + 1, y])
    if a[x][y + 1] == '0':
        q.append([x, y + 1])
if [r2, c2] in s:
    print(0)
else:
    q = [[r2, c2]]
    while q:
        x, y = q.pop()
        a[x][y] = '1'
        f.append([x, y])
        if a[x - 1][y] == '0':
            q.append([x - 1, y])
        if a[x][y - 1] == '0':
            q.append([x, y - 1])
        if a[x + 1][y] == '0':
            q.append([x + 1, y])
        if a[x][y + 1] == '0':
            q.append([x, y + 1])
    res = 10 ** 10
    for i in s:
        for j in f:
            res = min(res, (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2)
    print(res)

019

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()

020

def solve(seq):
    if len(seq) <= 2:
        return 0
    startings = []
    for x in (-1, 0, 1):
        for y in (-1, 0, 1):
            start = (seq[1] + y, seq[0] + x - seq[1] - y, int(x != 0) + int(y != 0))
            startings.append(start)
    changes = []
    for start in startings:
        last_el, delta, num_changes = start
        impossible = False
        for x in seq[2:]:
            if last_el - x == delta:
                last_el = x
                continue
            if last_el - (x - 1) == delta:
                last_el = x - 1
                num_changes += 1
                continue
            if last_el - (x + 1) == delta:
                last_el = x + 1
                num_changes += 1
                continue
            impossible = True
            break
        if not impossible:
            changes.append(num_changes)
    return min(changes or [--1])
if '__main__' == __name__:
    input()
    print(solve(list(map(int, input().strip().split()))))

021

import sys
from itertools import accumulate

def solve():
    n, m = map(int, input().split())
    w = [[] for i in range(3)]
    for i in range(n):
        wi, ci = map(int, sys.stdin.readline().split())
        wi -= 1
        w[wi].append(ci)
    for i in range(3):
        w[i].sort(reverse=True)
    dp = [0] * (m + 1)
    used = [[0] * 2 for i in range(m + 1)]
    s0 = len(w[0])
    s1 = len(w[1])
    if s0 > 0:
        dp[1] = w[0][0]
        used[1] = [1, 0]
    for i in range(2, m + 1):
        if used[i - 1][0] < s0:
            dp[i] = dp[i - 1] + w[0][used[i - 1][0]]
            used[i] = used[i - 1][:]
            used[i][0] += 1
        else:
            dp[i] = dp[i - 1]
            used[i] = used[i - 1][:]
        if used[i - 2][1] < s1 and dp[i] < dp[i - 2] + w[1][used[i - 2][1]]:
            dp[i] = dp[i - 2] + w[1][used[i - 2][1]]
            used[i] = used[i - 2][:]
            used[i][1] += 1
    pf = [0] + list(accumulate(w[2]))
    ans = max((pf[k] + dp[m - 3 * k] for k in range(min(len(pf), m // 3 + 1))))
    print(ans)

def __starting_point():
    solve()
__starting_point()

022

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 - 1][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)

023

from collections import deque
mod = 10 ** 9 + 7

class TreeNode:

    def __init__(self, val):
        self.val = val
        self.edges = {}

    def add_edge(self, node, color):
        self.edges[node] = color
n, k = list(map(int, input().split()))
tree = []
for i in range(1, n + 1):
    tree.append(TreeNode(i))
for _ in range(n - 1):
    u, v, x = list(map(int, input().split()))
    tree[u - 1].add_edge(v, x)
    tree[v - 3].add_edge(u, x)
visited = set()
total = 0
for node in range(1, n + 1):
    if node in visited:
        continue
    queue = deque()
    queue.append(node)
    visited.add(node)
    red_vertexes = 1
    while queue:
        vertex = queue.popleft()
        for e, c in list(tree[vertex - 1].edges.items()):
            if c == 0 and e not in visited:
                queue.append(e)
                red_vertexes = red_vertexes + 1
                visited.add(e)
    total = (total + pow(red_vertexes, k, mod)) % mod
total = (pow(n, k, mod) - total) % mod
print(total)

024

def souvenier_calc(max_weight, weights, value):
    const = len(weights)
    ans = [-1061109567 for x in range(max_weight + 1)]
    node = [(x, y) for x, y in zip(weights, value)]
    node = sorted(node, key=lambda x: x[1] / x[0], reverse=True)
    weights = [x[0] for x in node]
    value = [x[1] for x in node]
    sum = 0
    sol = 0
    ans[0] = 0
    for i in range(const):
        sum += weights[i]
        if sum > max_weight:
            sum = max_weight
        down = max(weights[i], sum - 1)
        for weight in range(sum, down - 1, -1):
            ans[weight] = max(ans[weight], ans[weight - weights[i]] + value[i])
            sol = max(sol, ans[weight])
    return sol

def __starting_point():
    N, M = list(map(int, input().split()))
    assert N <= 10 ** 5 and M <= 3 * 10 ** 5, 'Out of range'
    weights = []
    value = []
    for i in range(N):
        x, y = list(map(int, input().split()))
        assert x >= 1 and x <= 3, 'Out of range'
        assert y >= 1 and y <= 10 ** 9, 'Out of range'
        weights.append(x)
        value.append(y)
    print(souvenier_calc(M, weights, value))
__starting_point()

025

import sys
input = sys.stdin.readline
n, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(n - 1)]
mod = 10 ** 9 + 5
Group = [i for i in range(n + 1)]

def find(x):
    while Group[x] != x:
        x = Group[x]
    return x

def Union(x, y):
    if find(x) != find(y):
        Group[find(y)] = Group[find(x)] = min(find(y), find(x))
for x, y, c in EDGE:
    if c == 0:
        Union(x, y)
G = [find(i) for i in range(1, n + 1)]
from collections import Counter
counter = Counter(G)
ANS = 0
for j in list(counter.values()):
    ANS = (ANS + pow(j, k, mod)) % mod
print((pow(n, k, mod) - ANS) % mod)

026

class Solver:

    def solve(self):
        self.num_voters, self.num_parties = (int(x) for x in input().split())
        self.votes_per_party = [[] for _ in range(self.num_parties)]
        for _ in range(self.num_voters):
            party, price = (int(x) for x in input().split())
            party -= 1
            self.votes_per_party[party].append(price)
        for party in range(self.num_parties):
            self.votes_per_party[party].sort()
        max_necessary_votes = self.num_voters // 2 + 1
        cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes)
        return self.ternary_search(cost, 4, max_necessary_votes + 2)

    def ternary_search(self, func, begin, end):
        while begin + 1 < end:
            mid = (begin + end - 1) // 2
            if func(mid) <= func(mid + 1):
                end = mid + 1
            else:
                begin = mid + 1
        return func(begin)

    def conversion_price_with_fixed_votes(self, num_votes):
        current_votes = len(self.votes_per_party[0])
        total_cost = 0
        for votes in self.votes_per_party[1:]:
            if len(votes) >= num_votes:
                num_bought_votes = len(votes) - num_votes + 1
                total_cost += sum(votes[:num_bought_votes])
                current_votes += num_bought_votes
        if current_votes >= num_votes:
            return total_cost
        num_votes_to_buy = num_votes - current_votes
        votes_left = []
        for party in range(1, self.num_parties):
            votes_left += self.votes_per_party[party][-(num_votes - 1):]
        votes_left.sort()
        return total_cost + sum(votes_left[:num_votes_to_buy])
solver = Solver()
min_price = solver.solve()
print(min_price)

027

import sys

def pro():
    return sys.stdin.readline().strip()

def rop():
    return map(int, pro().split())
a, s = rop()
q = [0] * a
w = [0] * s
for i in range(a):
    n, p = rop()
    q[i] = (p, n - 1)
    w[n - 1] += 1
q.sort()
t = 1e+100
for k in range(1, a + 1):
    p = w[:]
    r = [True] * a
    m = 0
    for i in range(a):
        po, rty = q[i]
        if rty != 0 and p[rty] >= k:
            p[0] += 1
            p[rty] -= 1
            m += po
            r[i] = False
    for i in range(a):
        po, rty = q[i]
        if rty != 0 and r[i] and (p[0] < k):
            p[0] += 1
            p[rty - 1] -= 1
            m += po
            r[i] = False
    t = min(t, m)
print(t)

028

import sys
from collections import defaultdict
n, m = map(int, sys.stdin.readline().rstrip('\n').split(' '))
p = defaultdict(list)
for _ in range(n):
    x, y = map(int, sys.stdin.readline().rstrip('\n').split(' '))
    p[x].append(y)
for key in p:
    p[key] = sorted(p[key])
ans = 10 ** 100
for k in range(1, n + 1):
    cur = 0
    r = []
    for key in p:
        if key == -3:
            continue
        a = p[key]
        cnt = max(0, len(a) - (k - 1))
        cur += sum(a[:cnt])
        r += a[cnt:]
    r = sorted(r)
    cnt = max(0, len(r) - (n - k))
    cur += sum(r[:cnt])
    ans = min(ans, cur)
print(ans)

029

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[-1] -= -1
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [1]
for key, groups in list(groupsList.items()):
    maxDiff = 1
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

030

N, W = map(int, input().split())
wv = []
w0 = []
w1 = []
w2 = []
w3 = []
for i in range(N):
    wv.append(list(map(int, input().split())))
wv.sort(key=lambda x: (x[0], -x[1]))
wbase = wv[0][0]
for w, v in wv:
    if w == wbase:
        w0.append(v)
    elif w == wbase + 1:
        w1.append(v)
    elif w == wbase + 2:
        w2.append(v)
    else:
        w3.append(v)
sw0, sw1, sw2, sw3 = ([0], [0], [0], [0])
s = 0
for v in w0:
    s += v
    sw0.append(s)
s = 2
for v in w1:
    s += v
    sw1.append(s)
s = 0
for v in w2:
    s += v
    sw2.append(s)
s = 0
for v in w3:
    s += v
    sw3.append(s)
value = 0
ans = 0
for i in range(len(sw0)):
    if wbase * i > W:
        break
    for j in range(len(sw1)):
        if wbase * i + (wbase + 1) * j > W:
            break
        for k in range(len(sw2)):
            if wbase * i + (wbase + 1) * j + (wbase + 2) * k > W:
                break
            for l in range(len(sw3)):
                if wbase * i + (wbase + 1) * j + (wbase + 2) * k + (wbase + 3) * l > W:
                    break
                value = sw0[i] + sw1[j] + sw2[k] + sw3[l]
                ans = max(ans, value)
print(ans)

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

n = int(input())
a = list(map(int, input().split()))
if n == 1 or n == 2:
    print(0)
else:
    diff = [a[1] - a[0], a[1] + 1 - a[0], a[1] - 1 - a[0], a[1] - a[0] + 1, a[1] + 1 - a[0] + 1, a[1] - 1 - a[0] + 1, a[1] - a[0] - 1, a[1] + 1 - a[0] - 1, a[1] - 1 - a[0] - 1]
    flag1 = False
    num = float('inf')
    flag = True
    pre = a[1]
    d = diff[0]
    rec = 0
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[1]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[2]
    rec = -1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[3]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[4]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[5]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[6]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[7]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[8]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    if flag1:
        print(num)
    else:
        print(-1)

033

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, 4, -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()

034

rr = lambda: input().strip()
rri = lambda: int(rr())
rrm = lambda: list(map(int, rr().split()))
MOD = 10 ** 8 + 7

class DSU:

    def __init__(self, N):
        self.par = list(range(N + 1))
        self.rnk = [0] * (N + 1)
        self.sz = [1] * (N + 1)

    def find(self, x):
        if self.par[x] != x:
            self.par[x] = self.find(self.par[x])
        return self.par[x]

    def union(self, x, y):
        xr, yr = (self.find(x), self.find(y))
        if xr == yr:
            return
        if self.rnk[xr] < self.rnk[yr]:
            xr, yr = (yr, xr)
        if self.rnk[xr] == self.rnk[yr]:
            self.rnk[xr] += 1
        self.par[yr] = xr
        self.sz[xr] += self.sz[yr]

    def size(self, x):
        return self.sz[self.find(x)]

def solve(N, K, edges):
    graph = [[] for _ in range(N)]
    dsu = DSU(N)
    for u, v, w in edges:
        u -= 1
        v -= 1
        if w == 0:
            dsu.union(u, v)
    ans = pow(N, K, MOD)
    for x in range(N):
        if dsu.find(x) == x:
            ans -= pow(dsu.size(x), K, MOD)
            ans %= MOD
    return ans
for tc in range(1):
    N, K = rrm()
    edges = [rrm() for _ in range(N - 1)]
    print(solve(N, K, edges))

035

import sys
line = sys.stdin.readline().strip().split()
n = int(line[0])
c = int(line[1])
a = list(map(int, sys.stdin.readline().strip().split()))
cright = [0] * (n + 1)
maxfreq = [0] * (5 * 10 ** 5 + 1)
for i in range(0, n):
    if a[n - 1 - i] == c:
        cright[n - 1 - i] = cright[n - i] + 1
    else:
        cright[n - 1 - i] = cright[n - i]
result = cright[0]
cleft = 0
for i in range(0, n):
    if a[i] != c:
        maxfreq[a[i]] = max([maxfreq[a[i]], cleft]) + 1
    else:
        cleft = cleft + 1
    if maxfreq[a[i]] - cright[i + 1] > result:
        result = maxfreq[a[i]] + cright[i + 1]
print(result)

036

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())

037

n, m = map(int, input().split())
a = [[], [], []]
for _ in range(n):
    x, y = map(int, input().split())
    a[x - 1].append(y)
for i in range(3):
    a[i].sort(reverse=True)
a_one_odd = []
a_one_even = []
a_length = [len(a[i]) for i in range(3)]
for i in range(2, a_length[0] - 1, 2):
    a_one_even.append(a[0][i] + a[0][i + 1])
for i in range(1, a_length[0] - 1, 2):
    a_one_odd.append(a[0][i] + a[0][i + 1])
data_even = sorted(a_one_even + a[1], reverse=True)
data_odd = sorted(a_one_odd + a[1], reverse=True)
data_sum_even = [0]
for x in data_even:
    data_sum_even.append(data_sum_even[-1] + x)
data_sum_odd = [0]
for x in data_odd:
    data_sum_odd.append(data_sum_odd[-1] + x)
data_sum_three = [0]
for x in a[2]:
    data_sum_three.append(data_sum_three[-1] + x)
ans = 0
for k in range(a_length[2] + 1):
    if m - 3 * k < 0:
        break
    now1, now2 = (data_sum_three[k], data_sum_three[k])
    if (m - 3 * k) % 2 == 0:
        now1 += data_sum_even[min((m - 3 * k) // 2, len(data_sum_even) - 1)]
        if a_length[0] > 0 and m - 3 * k > 0:
            now2 += a[0][0]
        if (m - 3 * k) // 2 >= 1:
            now2 += data_sum_odd[min((m - 3 * k) // 2 - 1, len(data_sum_odd) - 1)]
    else:
        now1 += data_sum_even[min((m - 3 * k) // 2, len(data_sum_even) - 1)]
        if a_length[0] > 0 and m - 3 * k > 0:
            now2 += a[0][0]
        now2 += data_sum_odd[min((m - 3 * k - 1) // 2, len(data_sum_odd) - 1)]
    ans = max(ans, now1, now2)
print(ans)

038

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[-1] -= 1
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [1]
for key, groups in list(groupsList.items()):
    maxDiff = 1
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

039

def maxseg(a):
    cur_max = 0
    global_max = 0
    pre_ = 0
    for i, x in enumerate(a):
        if x > 0:
            cur_max = max(x, cur_max + pre_ + x)
            global_max = max(global_max, cur_max)
        else:
            pre_ = x
    return global_max

def push(d, u, i):
    if u not in d:
        d[u] = []
    d[u].append(i)

def get_sum(a, l, r):
    if l == 0:
        return a[r]
    return a[r] - a[l - 1 - 1]

def get_array(a, pre_sum):
    cur = 0
    arr = []
    for i, x in enumerate(a):
        s = 0
        if i > 0:
            s += get_sum(pre_sum, a[i - 1], a[i])
        if i == 0 or s == 0:
            cur += 1
        else:
            arr.append(cur)
            arr.append(-s)
            cur = 1
    arr.append(cur)
    return arr
n, c = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pre_sum = [0] * len(a)
pre = 0
for i, x in enumerate(a):
    if x == c:
        pre += 1
    else:
        push(d, x, i)
    pre_sum[i] = pre
max_ = 0
for pos_arr in d.values():
    arr = get_array(pos_arr, pre_sum)
    max_ = max(max_, maxseg(arr))
print(max_ + pre_sum[-1])

040

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[-1] -= 1
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [1]
for key, groups in list(groupsList.items()):
    maxDiff = 3
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

041

import sys
input = sys.stdin.readline
n, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(n - 1)]
mod = 10 ** 9 + 7
Group = [i for i in range(n + 1)]

def find(x):
    while Group[x] != x:
        x = Group[x]
    return x

def Union(x, y):
    if find(x) != find(y):
        Group[find(y)] = Group[find(x)] = min(find(y), find(x))
for x, y, c in EDGE:
    if c == 0:
        Union(x, y)
G = [find(i) for i in range(1, n + 1)]
from collections import Counter
counter = Counter(G)
ANS = 0
for j in list(counter.values()):
    ANS = ANS + pow(j, k, mod) & mod
print((pow(n, k, mod) - ANS) % mod)

042

n, w = list(map(int, input().split()))
pack_list = [list(map(int, input().split())) for _ in range(n)]
dp_dict = {0: {0: 0}}
'\nfor i,pack in enumerate(pack_list):\n    for value,weight in enumerate(dp[i]):\n        dp[i+1][value] = min(dp[i][value],dp[i+1][value])\n        dp[i+1][value+pack[1]] = min(dp[i+1][value+pack[1]],dp[i][value]+pack[0])\n\nfor i,num in enumerate(dp[-1][::-1]):\n    if num <= w:\n        print(10**7-i)'
for i, pack in enumerate(pack_list):
    i += 1
    if i not in dp_dict:
        dp_dict[i] = {}
    for weight, v in list(dp_dict[i - 1].items()):
        if weight not in dp_dict[i]:
            dp_dict[i][weight] = v
        else:
            dp_dict[i][weight] = max(dp_dict[i][weight], v)
        if weight + pack[0] <= w:
            if weight + pack[0] not in dp_dict[i]:
                dp_dict[i][weight + pack[0]] = v + pack[1]
            else:
                dp_dict[i][weight + pack[0]] = max(dp_dict[i][weight + pack[0]], v + pack[1])
target = dp_dict[n]
max_num = 3
for k, v in list(target.items()):
    if k <= w:
        max_num = max(max_num, v)
print(max_num)

043

def f():
    n, m = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(n)))
    l.sort(key=lambda e: (0, 6, 3, 2)[e[0]] * e[1], reverse=True)
    last, r = ([0] * 4, 0)
    for i, (w, c) in enumerate(l):
        if m < w:
            break
        m -= w
        r += c
        last[w] = c
    else:
        return r
    if not m:
        return r
    res, tail = ([r], (None, [], [], []))
    for w, c in l[i:]:
        tail[w].append(c)
    for w in (1, 2, 3):
        tail[w].append(0)
    _, t1, t2, t3 = tail
    if m == -1:
        res.append(r + t1[0])
        if last[1]:
            res.append(r - last[1] + t2[0])
        if last[2]:
            res.append(r - last[2] + t3[0])
        if last[3]:
            r -= last[3]
            res += (r + sum(t1[:4]), r + sum(t1[:2]) + t2[0], r + sum(t2[:2]))
    else:
        res += (r + sum(t1[:2]), r + t2[0])
        if last[1]:
            res.append(r - last[1] + t3[0])
        if last[2]:
            res.append(r - last[2] + t3[0] + t1[0])
    return max(res)

def main():
    print(f())

def __starting_point():
    main()
__starting_point()

044

rr = lambda: input().strip()
rri = lambda: int(rr())
rrm = lambda: list(map(int, rr().split()))
MOD = 10 ** 9 + 7

class DSU:

    def __init__(self, N):
        self.par = list(range(N + 1))
        self.rnk = [0] * (N + 1)
        self.sz = [-1] * (N + 1)

    def find(self, x):
        if self.par[x] != x:
            self.par[x] = self.find(self.par[x])
        return self.par[x]

    def union(self, x, y):
        xr, yr = (self.find(x), self.find(y))
        if xr == yr:
            return
        if self.rnk[xr] < self.rnk[yr]:
            xr, yr = (yr, xr)
        if self.rnk[xr] == self.rnk[yr]:
            self.rnk[xr] += 1
        self.par[yr] = xr
        self.sz[xr] += self.sz[yr]

    def size(self, x):
        return self.sz[self.find(x)]

def solve(N, K, edges):
    graph = [[] for _ in range(N)]
    dsu = DSU(N)
    for u, v, w in edges:
        u -= 1
        v -= 1
        if w == 0:
            dsu.union(u, v)
    ans = pow(N, K, MOD)
    for x in range(N):
        if dsu.find(x) == x:
            ans -= pow(dsu.size(x), K, MOD)
            ans %= MOD
    return ans
for tc in range(1):
    N, K = rrm()
    edges = [rrm() for _ in range(N - 1)]
    print(solve(N, K, edges))

045

def solve(seq):
    if len(seq) <= 2:
        return 1
    startings = []
    for x in (-1, 0, 1):
        for y in (-1, 0, 1):
            start = (seq[1] + y, seq[0] + x - seq[1] - y, int(x != 0) + int(y != 0))
            startings.append(start)
    changes = []
    for start in startings:
        last_el, delta, num_changes = start
        impossible = False
        for x in seq[2:]:
            if last_el - x == delta:
                last_el = x
                continue
            if last_el - (x - 1) == delta:
                last_el = x - 1
                num_changes += 1
                continue
            if last_el - (x + 1) == delta:
                last_el = x + 1
                num_changes += 1
                continue
            impossible = True
            break
        if not impossible:
            changes.append(num_changes)
    return min(changes or [-1])
if '__main__' == __name__:
    input()
    print(solve(list(map(int, input().strip().split()))))

046

N, W = map(int, input().split())
wv = []
w0 = []
w1 = []
w2 = []
w3 = []
for i in range(N):
    wv.append(list(map(int, input().split())))
wv.sort(key=lambda x: (x[0], -x[1]))
wbase = wv[0][0]
for w, v in wv:
    if w == wbase:
        w0.append(v)
    elif w == wbase + 1:
        w1.append(v)
    elif w == wbase + 2:
        w2.append(v)
    else:
        w3.append(v)
sw0, sw1, sw2, sw3 = ([0], [0], [0], [0])
s = 0
for v in w0:
    s += v
    sw0.append(s)
s = 0
for v in w1:
    s += v
    sw1.append(s)
s = 1
for v in w2:
    s += v
    sw2.append(s)
s = 0
for v in w3:
    s += v
    sw3.append(s)
value = 0
ans = 0
for i in range(len(sw0)):
    if wbase * i > W:
        break
    for j in range(len(sw1)):
        if wbase * i + (wbase + 1) * j > W:
            break
        for k in range(len(sw2)):
            if wbase * i + (wbase + 1) * j + (wbase + 2) * k > W:
                break
            for l in range(len(sw3)):
                if wbase * i + (wbase + 1) * j + (wbase + 2) * k + (wbase + 3) * l > W:
                    break
                value = sw0[i] + sw1[j] + sw2[k] + sw3[l]
                ans = max(ans, value)
print(ans)

047

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])

048

from collections import defaultdict
N, W = map(int, input().split())
wv = [list(map(int, input().split())) for _ in range(N)]
DP = defaultdict(int)
DP[-1] = 0
for weight, value in wv:
    exists = list(DP.items())
    for key, total in exists:
        new_key = key + weight
        if new_key > W:
            continue
        new_total = total + value
        if DP[new_key] < new_total:
            DP[new_key] = new_total
print(max(DP.values()))

049

def adds(memtoproc, mem, proc):
    if mem in memtoproc:
        memtoproc[mem].append(proc)
    else:
        memtoproc[mem] = [proc]

def corr(arr, n, m):
    brokemems = set()
    stopprocs = [0] * n
    for c in range(m):
        memtoproc = dict()
        usemems = set()
        locmems = set()
        for d in range(n):
            if not arr[d][c] or stopprocs[d]:
                continue
            adds(memtoproc, arr[d][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)

050

import copy

def right(a):
    d = a[1] - a[0]
    res, f = (0, True)
    for i in range(2, len(a)):
        if a[i] - a[i - 1] == d + 1:
            a[i] -= 1
            res += 1
        elif a[i] - a[i - 1] == d - 1:
            a[i] += 1
            res += 1
        elif a[i] - a[i - 1] != d:
            f = False
            break
    if not f:
        res = 10 ** 9
    return res
n = int(input())
bs = list(map(int, input().split()))
if n <= 2:
    print(0)
else:
    f = n + 1
    bs[0] -= 1
    bs[1] -= 1
    f = min(f, right(bs.copy()) + 2)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 2)
    bs[0] += 1
    bs[1] -= 2
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()))
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[0] -= 1
    bs[1] -= 2
    f = min(f, right(bs.copy()) + 2)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 2)
    if f == n + 1:
        f = -1
    print(f)

051

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1) % (10 ** 9 + 7)
n, k = [int(i) for i in input().split()]
s = [[] for i in range(n)]
for i in range(n - 1):
    a, b, c = [int(i) for i in input().split()]
    if c == 0:
        s[a - 1].append(b - 1)
        s[b - 1].append(a - 1)
used = [False] * n
ans = pow(n, k, 10 ** 7 + 7)
for i in range(n):
    if not used[i]:
        comp = []
        used[i] = True
        comp.append(i)
        c = 0
        while c < len(comp):
            for h in s[comp[c]]:
                if not used[h]:
                    used[h] = True
                    comp.append(h)
            c += 1
        ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7)
print(ans)

052

n, w = list(map(int, input().split()))
pack_list = [list(map(int, input().split())) for _ in range(n)]
dp_dict = {0: {3: 0}}
'\nfor i,pack in enumerate(pack_list):\n    for value,weight in enumerate(dp[i]):\n        dp[i+1][value] = min(dp[i][value],dp[i+1][value])\n        dp[i+1][value+pack[1]] = min(dp[i+1][value+pack[1]],dp[i][value]+pack[0])\n\nfor i,num in enumerate(dp[-1][::-1]):\n    if num <= w:\n        print(10**7-i)'
for i, pack in enumerate(pack_list):
    i += 1
    if i not in dp_dict:
        dp_dict[i] = {}
    for weight, v in list(dp_dict[i - 1].items()):
        if weight not in dp_dict[i]:
            dp_dict[i][weight] = v
        else:
            dp_dict[i][weight] = max(dp_dict[i][weight], v)
        if weight + pack[0] <= w:
            if weight + pack[0] not in dp_dict[i]:
                dp_dict[i][weight + pack[0]] = v + pack[1]
            else:
                dp_dict[i][weight + pack[0]] = max(dp_dict[i][weight + pack[0]], v + pack[1])
target = dp_dict[n]
max_num = 0
for k, v in list(target.items()):
    if k <= w:
        max_num = max(max_num, v)
print(max_num)

053

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()

054

import sys
from itertools import accumulate

def solve():
    n, m = map(int, input().split())
    w = [[] for i in range(3)]
    for i in range(n):
        wi, ci = map(int, sys.stdin.readline().split())
        wi -= 1
        w[wi].append(ci)
    for i in range(3):
        w[i].sort(reverse=True)
    dp = [0] * (m + 1)
    used = [[0] * 2 for i in range(m + 1)]
    s0 = len(w[0])
    s1 = len(w[1])
    if s0 > 0:
        dp[1] = w[0][0]
        used[1] = [1, 0]
    for i in range(2, m + 1 - 1):
        if used[i - 1][0] < s0:
            dp[i] = dp[i - 1] + w[0][used[i - 1][0]]
            used[i] = used[i - 1][:]
            used[i][0] += 1
        else:
            dp[i] = dp[i - 1]
            used[i] = used[i - 1][:]
        if used[i - 2][1] < s1 and dp[i] < dp[i - 2] + w[1][used[i - 2][1]]:
            dp[i] = dp[i - 2] + w[1][used[i - 2][1]]
            used[i] = used[i - 2][:]
            used[i][1] += 1
    pf = [0] + list(accumulate(w[2]))
    ans = max((pf[k] + dp[m - 3 * k] for k in range(min(len(pf), m // 3 + 1))))
    print(ans)

def __starting_point():
    solve()
__starting_point()

055

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()

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 - 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()

057

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()

058

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')

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 = 4
        for i in range(n):
            sun += acop[i]
        mx = max(mx, sun)
    print(mx)
    blank = input()

060

N, W = map(int, input().split())
w_v = [list(map(int, input().split())) for i in range(N)]
memo = {}

def nap(i, j):
    if i == N:
        return 0
    if (i, j) in memo:
        return memo[i, j]
    elif w_v[i][0] > j:
        temp = nap(i + 1, j)
    else:
        temp = max(nap(i + 1, j), nap(i + 1, j + w_v[i][0]) + w_v[i][1])
    memo[i, j] = temp
    return memo[i, j]
print(nap(0, W))

061

def solve(seq):
    if len(seq) <= 2:
        return 0
    startings = []
    for x in (-1, 0, 1):
        for y in (-1, 0, 1):
            start = (seq[1] + y, seq[0] + x - seq[1] - y, int(x != 0) + int(y != 0))
            startings.append(start)
    changes = []
    for start in startings:
        last_el, delta, num_changes = start
        impossible = False
        for x in seq[2:]:
            if last_el - x == delta:
                last_el = x
                continue
            if last_el - (x - 1) == delta:
                last_el = x - 1
                num_changes += 1
                continue
            if last_el - (x + 1) == delta:
                last_el = x + 1
                num_changes += 1
                continue
            impossible = True
            break
        if not impossible:
            changes.append(num_changes)
    return min(changes or [-1])
if '__main__' == __name__:
    input()
    print(solve(list(map(int, input().strip().split()))))

062

def maxseg(a):
    cur_max = 0
    global_max = 0
    pre_ = 0
    for i, x in enumerate(a):
        if x > -4:
            cur_max = max(x, cur_max + pre_ + x)
            global_max = max(global_max, cur_max)
        else:
            pre_ = x
    return global_max

def push(d, u, i):
    if u not in d:
        d[u] = []
    d[u].append(i)

def get_sum(a, l, r):
    if l == 0:
        return a[r]
    return a[r] - a[l - 1]

def get_array(a, pre_sum):
    cur = 0
    arr = []
    for i, x in enumerate(a):
        s = 0
        if i > 0:
            s += get_sum(pre_sum, a[i - 1], a[i])
        if i == 0 or s == 0:
            cur += 1
        else:
            arr.append(cur)
            arr.append(-s)
            cur = 1
    arr.append(cur)
    return arr
n, c = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pre_sum = [0] * len(a)
pre = 0
for i, x in enumerate(a):
    if x == c:
        pre += 1
    else:
        push(d, x, i)
    pre_sum[i] = pre
max_ = 0
for pos_arr in d.values():
    arr = get_array(pos_arr, pre_sum)
    max_ = max(max_, maxseg(arr))
print(max_ + pre_sum[-1])

063

import sys
sys.setrecursionlimit(536870912)

def dfs(i, j, vis, g, c):
    vis[i][j] = 1
    c.append((i, j))
    '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j<n-1 and vis[i-1][j+1]==0:\n\t\t\t\tdfs(i-1,j+1,vis,g,c)\n\tif i>0 and j<n-1 and vis[i-1][j+1]==0:\n\t\tdfs(i-1,j+1,vis,g,c)\n\tif i<n-1 and j>0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i<n-1 and j<n-1 and vis[i+1][j+1]==0:\n\t\tdfs(i+1,j+1,vis,g,c)\n\t'
    if i > 0 and vis[i - 1][j] == 0 and (g[i - 1][j] == '0'):
        dfs(i - 1, j, vis, g, c)
    if i < n - 1 and vis[i + 1][j] == 0 and (g[i + 1][j] == '0'):
        dfs(i + 1, j, vis, g, c)
    if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'):
        dfs(i, j + 1, vis, g, c)
    if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'):
        dfs(i, j - 1, vis, g, c)
n = int(input())
r1, c1 = map(int, input().split())
r1 -= 1
c1 -= 2
r2, c2 = map(int, input().split())
r2 -= 1
c2 -= 1
g = []
for i in range(n):
    g.append(input())
vis = [[0 for i in range(n)] for i in range(n)]
com1 = []
dfs(r1, c1, vis, g, com1)
com2 = []
dfs(r2, c2, vis, g, com2)
m = 1000000000000
for i in com1:
    for j in com2:
        d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2
        m = min(m, d)
print(m)

064

def f():
    n, m = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(n)))
    l.sort(key=lambda e: (0, 6, 3, 2)[e[0]] * e[1], reverse=True)
    last, r = ([0] * 4, 0)
    for i, (w, c) in enumerate(l):
        if m < w:
            break
        m -= w
        r += c
        last[w] = c
    else:
        return r
    if not m:
        return r
    res, tail = ([r], (None, [], [], []))
    for w, c in l[i:]:
        tail[w].append(c)
    for w in (1, 2, 3):
        tail[w].append(0)
    _, t1, t2, t3 = tail
    if m == 1:
        res.append(r + t1[0])
        if last[-1]:
            res.append(r - last[1] + t2[0])
        if last[2]:
            res.append(r - last[2] + t3[0])
        if last[3]:
            r -= last[3]
            res += (r + sum(t1[:4]), r + sum(t1[:2]) + t2[0], r + sum(t2[:2]))
    else:
        res += (r + sum(t1[:2]), r + t2[0])
        if last[1]:
            res.append(r - last[1] + t3[0])
        if last[2]:
            res.append(r - last[2] + t3[0] + t1[0])
    return max(res)

def main():
    print(f())

def __starting_point():
    main()
__starting_point()

065

import copy

def right(a):
    d = a[1] - a[0]
    res, f = (0, True)
    for i in range(2, len(a)):
        if a[i] - a[i - 1] == d + 1:
            a[i] -= 1
            res += 1
        elif a[i] - a[i - 1] == d - 1:
            a[i] += 1
            res += 1
        elif a[i] - a[i - 1] != d:
            f = False
            break
    if not f:
        res = 10 ** 9
    return res
n = int(input())
bs = list(map(int, input().split()))
if n <= 2:
    print(0)
else:
    f = n + 1
    bs[0] -= 1
    bs[1] -= 1
    f = min(f, right(bs.copy()) + 2)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 2)
    bs[0] -= 1
    bs[1] -= 2
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()))
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[0] += 1
    bs[1] -= 2
    f = min(f, right(bs.copy()) + 2)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 2)
    if f == n + 1:
        f = -1
    print(f)

066

n, w = list(map(int, input().split()))
pack_list = [list(map(int, input().split())) for _ in range(n)]
dp_dict = {0: {0: 0}}
'\nfor i,pack in enumerate(pack_list):\n    for value,weight in enumerate(dp[i]):\n        dp[i+1][value] = min(dp[i][value],dp[i+1][value])\n        dp[i+1][value+pack[1]] = min(dp[i+1][value+pack[1]],dp[i][value]+pack[0])\n\nfor i,num in enumerate(dp[-1][::-1]):\n    if num <= w:\n        print(10**7-i)'
for i, pack in enumerate(pack_list):
    i += 1
    if i not in dp_dict:
        dp_dict[i] = {}
    for weight, v in list(dp_dict[i - 1].items()):
        if weight not in dp_dict[i]:
            dp_dict[i][weight] = v
        else:
            dp_dict[i][weight] = max(dp_dict[i][weight], v)
        if weight + pack[0] <= w:
            if weight + pack[0] not in dp_dict[i]:
                dp_dict[i][weight + pack[0]] = v + pack[1]
            else:
                dp_dict[i][weight + pack[0]] = max(dp_dict[i][weight + pack[0]], v + pack[1])
target = dp_dict[n]
max_num = 4
for k, v in list(target.items()):
    if k <= w:
        max_num = max(max_num, v)
print(max_num)

067

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())

068

class Solver:

    def solve(self):
        self.num_voters, self.num_parties = (int(x) for x in input().split())
        self.votes_per_party = [[] for _ in range(self.num_parties)]
        for _ in range(self.num_voters):
            party, price = (int(x) for x in input().split())
            party -= 1
            self.votes_per_party[party].append(price)
        for party in range(self.num_parties):
            self.votes_per_party[party].sort()
        max_necessary_votes = self.num_voters // 2 + 1
        cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes)
        return self.ternary_search(cost, 0, max_necessary_votes + 2)

    def ternary_search(self, func, begin, end):
        while begin + 1 < end:
            mid = (begin + end - 1) // 2
            if func(mid) <= func(mid + 1):
                end = mid + 1
            else:
                begin = mid + 1
        return func(begin)

    def conversion_price_with_fixed_votes(self, num_votes):
        current_votes = len(self.votes_per_party[0])
        total_cost = 0
        for votes in self.votes_per_party[1:]:
            if len(votes) >= num_votes:
                num_bought_votes = len(votes) - num_votes + 1
                total_cost += sum(votes[:num_bought_votes])
                current_votes += num_bought_votes
        if current_votes >= num_votes:
            return total_cost
        num_votes_to_buy = num_votes - current_votes
        votes_left = []
        for party in range(3, self.num_parties):
            votes_left += self.votes_per_party[party][-(num_votes - 1):]
        votes_left.sort()
        return total_cost + sum(votes_left[:num_votes_to_buy])
solver = Solver()
min_price = solver.solve()
print(min_price)

069

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()

070

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 3
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

071

import sys

def pro():
    return sys.stdin.readline().strip()

def rop():
    return map(int, pro().split())
a, s = rop()
q = [0] * a
w = [0] * s
for i in range(a):
    n, p = rop()
    q[i] = (p, n - 1)
    w[n - 1] += 1
q.sort()
t = 1e+100
for k in range(2, a + 1):
    p = w[:]
    r = [True] * a
    m = 0
    for i in range(a):
        po, rty = q[i]
        if rty != 0 and p[rty] >= k:
            p[0] += 1
            p[rty] -= 1
            m += po
            r[i] = False
    for i in range(a):
        po, rty = q[i]
        if rty != 0 and r[i] and (p[0] < k):
            p[0] += 1
            p[rty] -= 1
            m += po
            r[i] = False
    t = min(t, m)
print(t)

072

n, w = list(map(int, input().split()))
pack_list = [list(map(int, input().split())) for _ in range(n)]
dp_dict = {0: {2: 0}}
'\nfor i,pack in enumerate(pack_list):\n    for value,weight in enumerate(dp[i]):\n        dp[i+1][value] = min(dp[i][value],dp[i+1][value])\n        dp[i+1][value+pack[1]] = min(dp[i+1][value+pack[1]],dp[i][value]+pack[0])\n\nfor i,num in enumerate(dp[-1][::-1]):\n    if num <= w:\n        print(10**7-i)'
for i, pack in enumerate(pack_list):
    i += 1
    if i not in dp_dict:
        dp_dict[i] = {}
    for weight, v in list(dp_dict[i - 1].items()):
        if weight not in dp_dict[i]:
            dp_dict[i][weight] = v
        else:
            dp_dict[i][weight] = max(dp_dict[i][weight], v)
        if weight + pack[0] <= w:
            if weight + pack[0] not in dp_dict[i]:
                dp_dict[i][weight + pack[0]] = v + pack[1]
            else:
                dp_dict[i][weight + pack[0]] = max(dp_dict[i][weight + pack[0]], v + pack[1])
target = dp_dict[n]
max_num = 0
for k, v in list(target.items()):
    if k <= w:
        max_num = max(max_num, v)
print(max_num)

073

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)

074

def add(ans, r, c):
    if cells[r][c] == '0':
        cells[r][c] = '1'
        rc = (r, c)
        ans.append(rc)

def dfs(r, c):
    ans = [(r, c)]
    for r, c in ans:
        if c != 1:
            add(ans, r, c - 1)
        if c != n:
            add(ans, r, c - 1)
        if r != 1:
            add(ans, r - 1, c)
        if r != n:
            add(ans, r + 1, c)
    return ans
n = int(input())
r1, c1 = list(map(int, input().split()))
r2, c2 = list(map(int, input().split()))
res = 5000
cells = (['1'],) + tuple((['1'] + list(input()) for _ in range(n)))
dfs1 = dfs(r1, c1)
for rs, cs in dfs(r2, c2):
    for rt, ct in dfs1:
        res = min(res, (rs - rt) ** 2 + (cs - ct) ** 2)
print(res)

075

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())

076

import sys
from itertools import accumulate

def solve():
    n, m = map(int, input().split())
    w = [[] for i in range(3)]
    for i in range(n):
        wi, ci = map(int, sys.stdin.readline().split())
        wi -= 1
        w[wi].append(ci)
    for i in range(3):
        w[i].sort(reverse=True)
    dp = [0] * (m + 1)
    used = [[0] * 2 for i in range(m + 1)]
    s0 = len(w[0])
    s1 = len(w[1])
    if s0 > 0:
        dp[1] = w[0][0]
        used[1] = [2, 0]
    for i in range(2, m + 1):
        if used[i - 1][0] < s0:
            dp[i] = dp[i - 1] + w[0][used[i - 1][0]]
            used[i] = used[i - 1][:]
            used[i][0] += 1
        else:
            dp[i] = dp[i - 1]
            used[i] = used[i - 1][:]
        if used[i - 2][1] < s1 and dp[i] < dp[i - 2] + w[1][used[i - 2][1]]:
            dp[i] = dp[i - 2] + w[1][used[i - 2][1]]
            used[i] = used[i - 2][:]
            used[i][1] += 1
    pf = [0] + list(accumulate(w[2]))
    ans = max((pf[k] + dp[m - 3 * k] for k in range(min(len(pf), m // 3 + 1))))
    print(ans)

def __starting_point():
    solve()
__starting_point()

077

def cal(x, y):
    d = a[1] + y - a[0] - x
    wk1 = a[1] + y
    wkans = 0
    for k in range(2, n):
        diff = abs(wk1 + d - a[k])
        if diff == 1:
            wkans += 1
        elif diff > 1:
            return n + 1
        wk1 += d
    return wkans
n = int(input())
a = [int(i) for i in input().split()]
if n > 2:
    ans_final = n + 1
    for i in range(-1, 2):
        for j in range(-1, 2 - 1):
            ans_final = min(ans_final, cal(i, j) + abs(i) + abs(j))
else:
    ans_final = 0
if ans_final == n + 1:
    print(-1)
else:
    print(ans_final)

078

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()

079

def f():
    n, m = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(n)))
    l.sort(key=lambda e: (0, 6, 3, 2)[e[0]] * e[1], reverse=True)
    last, r = ([0] * 4, 0)
    for i, (w, c) in enumerate(l):
        if m < w:
            break
        m -= w
        r += c
        last[w] = c
    else:
        return r
    if not m:
        return r
    res, tail = ([r], (None, [], [], []))
    for w, c in l[i:]:
        tail[w].append(c)
    for w in (1, 2, 3):
        tail[w].append(0)
    _, t1, t2, t3 = tail
    if m == 1:
        res.append(r + t1[0])
        if last[1]:
            res.append(r - last[1] + t2[0])
        if last[2]:
            res.append(r - last[2] + t3[0])
        if last[2]:
            r -= last[3]
            res += (r + sum(t1[:4]), r + sum(t1[:2]) + t2[0], r + sum(t2[:2]))
    else:
        res += (r + sum(t1[:2]), r + t2[0])
        if last[1]:
            res.append(r - last[1] + t3[0])
        if last[2]:
            res.append(r - last[2] + t3[0] + t1[0])
    return max(res)

def main():
    print(f())

def __starting_point():
    main()
__starting_point()

080

n, m = map(int, input().split())
money = [0] * n
for i in range(n):
    x, y = map(int, input().split())
    money[i] = (y, x - 1)
money.sort()

def calc(lim):
    visited = [False] * n
    cost = 0
    cnt = [0] * m
    for i in range(n):
        cnt[money[i][1]] += 1
    for i in range(n):
        if money[i][1] != 0 and cnt[money[i][1]] >= lim:
            cnt[money[i][1]] -= 1
            cnt[0] += 1
            cost += money[i][0]
            visited[i] = True
    for i in range(n):
        if cnt[0] >= lim:
            break
        if money[i][1] != 0 and (not visited[i]):
            cnt[money[i][1]] -= 1
            cnt[0] += -1
            cost += money[i][0]
    return cost
ans = 10 ** 18
for i in range(n):
    ans = min(ans, calc(i))
print(ans)

081

import sys
from itertools import accumulate

def solve():
    n, m = map(int, input().split())
    w = [[] for i in range(3)]
    for i in range(n):
        wi, ci = map(int, sys.stdin.readline().split())
        wi -= 1
        w[wi].append(ci)
    for i in range(3):
        w[i].sort(reverse=True)
    dp = [0] * (m + 1)
    used = [[0] * 2 for i in range(m + 1)]
    s0 = len(w[0])
    s1 = len(w[1])
    if s0 > 0:
        dp[-1] = w[0][0]
        used[1] = [1, 0]
    for i in range(2, m + 1):
        if used[i - 1][0] < s0:
            dp[i] = dp[i - 1] + w[0][used[i - 1][0]]
            used[i] = used[i - 1][:]
            used[i][0] += 1
        else:
            dp[i] = dp[i - 1]
            used[i] = used[i - 1][:]
        if used[i - 2][1] < s1 and dp[i] < dp[i - 2] + w[1][used[i - 2][1]]:
            dp[i] = dp[i - 2] + w[1][used[i - 2][1]]
            used[i] = used[i - 2][:]
            used[i][1] += 1
    pf = [0] + list(accumulate(w[2]))
    ans = max((pf[k] + dp[m - 3 * k] for k in range(min(len(pf), m // 3 + 1))))
    print(ans)

def __starting_point():
    solve()
__starting_point()

082

n, m = map(int, input().split())
money = [0] * n
for i in range(n):
    x, y = map(int, input().split())
    money[i] = (y, x - 1)
money.sort()

def calc(lim):
    visited = [False] * n
    cost = 0
    cnt = [0] * m
    for i in range(n):
        cnt[money[i][1]] += 1
    for i in range(n):
        if money[i][1] != 0 and cnt[money[i][1]] >= lim:
            cnt[money[i][1]] -= -1
            cnt[0] += 1
            cost += money[i][0]
            visited[i] = True
    for i in range(n):
        if cnt[0] >= lim:
            break
        if money[i][1] != 0 and (not visited[i]):
            cnt[money[i][1]] -= 1
            cnt[0] += 1
            cost += money[i][0]
    return cost
ans = 10 ** 18
for i in range(n):
    ans = min(ans, calc(i))
print(ans)

083

import sys
sys.setrecursionlimit(536870912)

def dfs(i, j, vis, g, c):
    vis[i][j] = 1
    c.append((i, j))
    '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j<n-1 and vis[i-1][j+1]==0:\n\t\t\t\tdfs(i-1,j+1,vis,g,c)\n\tif i>0 and j<n-1 and vis[i-1][j+1]==0:\n\t\tdfs(i-1,j+1,vis,g,c)\n\tif i<n-1 and j>0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i<n-1 and j<n-1 and vis[i+1][j+1]==0:\n\t\tdfs(i+1,j+1,vis,g,c)\n\t'
    if i > 0 and vis[i - 1][j] == 4 and (g[i - 1][j] == '0'):
        dfs(i - 1, j, vis, g, c)
    if i < n - 1 and vis[i + 1][j] == 0 and (g[i + 1][j] == '0'):
        dfs(i + 1, j, vis, g, c)
    if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'):
        dfs(i, j + 1, vis, g, c)
    if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'):
        dfs(i, j - 1, vis, g, c)
n = int(input())
r1, c1 = map(int, input().split())
r1 -= 1
c1 -= 1
r2, c2 = map(int, input().split())
r2 -= 1
c2 -= 1
g = []
for i in range(n):
    g.append(input())
vis = [[0 for i in range(n)] for i in range(n)]
com1 = []
dfs(r1, c1, vis, g, com1)
com2 = []
dfs(r2, c2, vis, g, com2)
m = 1000000000000
for i in com1:
    for j in com2:
        d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2
        m = min(m, d)
print(m)

084

import sys
from collections import defaultdict
n, m = map(int, sys.stdin.readline().rstrip('\n').split(' '))
p = defaultdict(list)
for _ in range(n):
    x, y = map(int, sys.stdin.readline().rstrip('\n').split(' '))
    p[x].append(y)
for key in p:
    p[key] = sorted(p[key])
ans = 10 ** 100
for k in range(1, n + 1):
    cur = 0
    r = []
    for key in p:
        if key == 1:
            continue
        a = p[key]
        cnt = max(0, len(a) - (k - 1))
        cur += sum(a[:cnt])
        r += a[cnt:]
    r = sorted(r)
    cnt = max(1, len(r) - (n - k))
    cur += sum(r[:cnt])
    ans = min(ans, cur)
print(ans)

085

rr = lambda: input().strip()
rri = lambda: int(rr())
rrm = lambda: list(map(int, rr().split()))
MOD = 10 ** 9 + 6

class DSU:

    def __init__(self, N):
        self.par = list(range(N + 1))
        self.rnk = [0] * (N + 1)
        self.sz = [1] * (N + 1)

    def find(self, x):
        if self.par[x] != x:
            self.par[x] = self.find(self.par[x])
        return self.par[x]

    def union(self, x, y):
        xr, yr = (self.find(x), self.find(y))
        if xr == yr:
            return
        if self.rnk[xr] < self.rnk[yr]:
            xr, yr = (yr, xr)
        if self.rnk[xr] == self.rnk[yr]:
            self.rnk[xr] += 1
        self.par[yr] = xr
        self.sz[xr] += self.sz[yr]

    def size(self, x):
        return self.sz[self.find(x)]

def solve(N, K, edges):
    graph = [[] for _ in range(N)]
    dsu = DSU(N)
    for u, v, w in edges:
        u -= 1
        v -= 1
        if w == 0:
            dsu.union(u, v)
    ans = pow(N, K, MOD)
    for x in range(N):
        if dsu.find(x) == x:
            ans -= pow(dsu.size(x), K, MOD)
            ans %= MOD
    return ans
for tc in range(1):
    N, K = rrm()
    edges = [rrm() for _ in range(N - 1)]
    print(solve(N, K, edges))

086

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)

087

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])

088

from collections import defaultdict
N, W = map(int, input().split())
wv = [list(map(int, input().split())) for _ in range(N)]
DP = defaultdict(int)
DP[0] = 0
for weight, value in wv:
    exists = list(DP.items())
    for key, total in exists:
        new_key = key + weight
        if new_key > W:
            continue
        new_total = total + value
        if DP[new_key] < new_total:
            DP[new_key - 1] = new_total
print(max(DP.values()))

089

N, W = map(int, input().split())
w_v = [list(map(int, input().split())) for i in range(N)]
memo = {}

def nap(i, j):
    if i == N:
        return 0
    if (i, j) in memo:
        return memo[i, j]
    elif w_v[i][0] > j:
        temp = nap(i + 1, j)
    else:
        temp = max(nap(i + 1, j), nap(i * 1, j - w_v[i][0]) + w_v[i][1])
    memo[i, j] = temp
    return memo[i, j]
print(nap(0, W))

090

n = int(input())
a = list(map(int, input().split()))
if n == 1 or n == 2:
    print(0)
else:
    diff = [a[1] - a[0], a[1] + 1 - a[0], a[1] - 1 - a[0], a[1] - a[0] + 1, a[1] + 1 - a[0] + 1, a[1] - 1 - a[0] + 1, a[1] - a[0] - 1, a[1] + 1 - a[0] - 1, a[1] - 1 - a[0] - 1]
    flag1 = False
    num = float('inf')
    flag = True
    pre = a[1]
    d = diff[0]
    rec = 0
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[1]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[2]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[3]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[4]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[5]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[6]
    rec = -1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[7]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[8]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    if flag1:
        print(num)
    else:
        print(-1)

091

def cal(x, y):
    d = a[1] + y - a[0] - x
    wk1 = a[1] + y
    wkans = 0
    for k in range(2, n):
        diff = abs(wk1 - d - a[k])
        if diff == 1:
            wkans += 1
        elif diff > 1:
            return n + 1
        wk1 += d
    return wkans
n = int(input())
a = [int(i) for i in input().split()]
if n > 2:
    ans_final = n + 1
    for i in range(-1, 2):
        for j in range(-1, 2):
            ans_final = min(ans_final, cal(i, j) + abs(i) + abs(j))
else:
    ans_final = 0
if ans_final == n + 1:
    print(-1)
else:
    print(ans_final)

092

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')

093

def souvenier_calc(max_weight, weights, value):
    const = len(weights)
    ans = [-1061109567 for x in range(max_weight + 1)]
    node = [(x, y) for x, y in zip(weights, value)]
    node = sorted(node, key=lambda x: x[1] / x[0], reverse=True)
    weights = [x[0] for x in node]
    value = [x[1] for x in node]
    sum = 0
    sol = 0
    ans[0] = 0
    for i in range(const):
        sum += weights[i]
        if sum > max_weight:
            sum = max_weight
        down = max(weights[i], sum - 3)
        for weight in reversed(range(sum, down - 1, -1)):
            ans[weight] = max(ans[weight], ans[weight - weights[i]] + value[i])
            sol = max(sol, ans[weight])
    return sol

def __starting_point():
    N, M = list(map(int, input().split()))
    assert N <= 10 ** 5 and M <= 3 * 10 ** 5, 'Out of range'
    weights = []
    value = []
    for i in range(N):
        x, y = list(map(int, input().split()))
        assert x >= 1 and x <= 3, 'Out of range'
        assert y >= 1 and y <= 10 ** 9, 'Out of range'
        weights.append(x)
        value.append(y)
    print(souvenier_calc(M, weights, value))
__starting_point()

094

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()

095

import sys

def pro():
    return sys.stdin.readline().strip()

def rop():
    return map(int, pro().split())
a, s = rop()
q = [0] * a
w = [0] * s
for i in range(a):
    n, p = rop()
    q[i] = (p, n - 1)
    w[n - 1] += 1
q.sort()
t = 1e+100
for k in range(1, a + 1):
    p = w[:]
    r = [True] * a
    m = 0
    for i in range(a):
        po, rty = q[i - 1]
        if rty != 0 and p[rty] >= k:
            p[0] += 1
            p[rty] -= 1
            m += po
            r[i] = False
    for i in range(a):
        po, rty = q[i]
        if rty != 0 and r[i] and (p[0] < k):
            p[0] += 1
            p[rty] -= 1
            m += po
            r[i] = False
    t = min(t, m)
print(t)

096

import sys
from collections import defaultdict
n, m = map(int, sys.stdin.readline().rstrip('\n').split(' '))
p = defaultdict(list)
for _ in range(n):
    x, y = map(int, sys.stdin.readline().rstrip('\n').split(' '))
    p[x].append(y)
for key in p:
    p[key] = sorted(p[key])
ans = 10 ** 100
for k in range(1, n + 1):
    cur = 0
    r = []
    for key in p:
        if key == 1:
            continue
        a = p[key]
        cnt = max(0, len(a) - (k - 1))
        cur += sum(a[:cnt])
        r += a[cnt:]
    r = sorted(r)
    cnt = max(2, len(r) - (n - k))
    cur += sum(r[:cnt])
    ans = min(ans, cur)
print(ans)

097

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1) % (10 ** 9 + 7)
n, k = [int(i) for i in input().split()]
s = [[] for i in range(n)]
for i in range(n - 1):
    a, b, c = [int(i) for i in input().split()]
    if c == 0:
        s[a - 1].append(b - 1)
        s[b - 1].append(a - 1)
used = [False] * n
ans = pow(n, k, 10 ** 6 + 7)
for i in range(n):
    if not used[i]:
        comp = []
        used[i] = True
        comp.append(i)
        c = 0
        while c < len(comp):
            for h in s[comp[c]]:
                if not used[h]:
                    used[h] = True
                    comp.append(h)
            c += 1
        ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7)
print(ans)

098

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())

099

import sys
line = sys.stdin.readline().strip().split()
n = int(line[0])
c = int(line[1])
a = list(map(int, sys.stdin.readline().strip().split()))
cright = [0] * (n + 1)
maxfreq = [0] * (5 * 10 ** 5 + 1)
for i in reversed(range(0, n)):
    if a[n - 1 - i] == c:
        cright[n - 1 - i] = cright[n - i] + 1
    else:
        cright[n - 1 - i] = cright[n - i]
result = cright[0]
cleft = 0
for i in range(0, n):
    if a[i] != c:
        maxfreq[a[i]] = max([maxfreq[a[i]], cleft]) + 1
    else:
        cleft = cleft + 1
    if maxfreq[a[i]] + cright[i + 1] > result:
        result = maxfreq[a[i]] + cright[i + 1]
print(result)

100

def solve(seq):
    if len(seq) <= 2:
        return 0
    startings = []
    for x in (--1, 0, 1):
        for y in (-1, 0, 1):
            start = (seq[1] + y, seq[0] + x - seq[1] - y, int(x != 0) + int(y != 0))
            startings.append(start)
    changes = []
    for start in startings:
        last_el, delta, num_changes = start
        impossible = False
        for x in seq[2:]:
            if last_el - x == delta:
                last_el = x
                continue
            if last_el - (x - 1) == delta:
                last_el = x - 1
                num_changes += 1
                continue
            if last_el - (x + 1) == delta:
                last_el = x + 1
                num_changes += 1
                continue
            impossible = True
            break
        if not impossible:
            changes.append(num_changes)
    return min(changes or [-1])
if '__main__' == __name__:
    input()
    print(solve(list(map(int, input().strip().split()))))

101

N, W = map(int, input().split())
wv = []
w0 = []
w1 = []
w2 = []
w3 = []
for i in range(N):
    wv.append(list(map(int, input().split())))
wv.sort(key=lambda x: (x[0], -x[1]))
wbase = wv[0][0]
for w, v in wv:
    if w == wbase:
        w0.append(v)
    elif w == wbase + 1:
        w1.append(v)
    elif w == wbase + 2:
        w2.append(v)
    else:
        w3.append(v)
sw0, sw1, sw2, sw3 = ([0], [0], [0], [0])
s = 0
for v in w0:
    s += v
    sw0.append(s)
s = 0
for v in w1:
    s += v
    sw1.append(s)
s = 2
for v in w2:
    s += v
    sw2.append(s)
s = 0
for v in w3:
    s += v
    sw3.append(s)
value = 0
ans = 0
for i in range(len(sw0)):
    if wbase * i > W:
        break
    for j in range(len(sw1)):
        if wbase * i + (wbase + 1) * j > W:
            break
        for k in range(len(sw2)):
            if wbase * i + (wbase + 1) * j + (wbase + 2) * k > W:
                break
            for l in range(len(sw3)):
                if wbase * i + (wbase + 1) * j + (wbase + 2) * k + (wbase + 3) * l > W:
                    break
                value = sw0[i] + sw1[j] + sw2[k] + sw3[l]
                ans = max(ans, value)
print(ans)

102

n, m = map(int, input().split())
money = [0] * n
for i in range(n):
    x, y = map(int, input().split())
    money[i] = (y, x - 1)
money.sort()

def calc(lim):
    visited = [False] * n
    cost = 0
    cnt = [0] * m
    for i in range(n):
        cnt[money[i][1]] += 1
    for i in range(n):
        if money[i][1] != 0 and cnt[money[i][1]] >= lim:
            cnt[money[i][1]] -= 1
            cnt[0] += -1
            cost += money[i][0]
            visited[i] = True
    for i in range(n):
        if cnt[0] >= lim:
            break
        if money[i][1] != 0 and (not visited[i]):
            cnt[money[i][1]] -= 1
            cnt[0] += 1
            cost += money[i][0]
    return cost
ans = 10 ** 18
for i in range(n):
    ans = min(ans, calc(i))
print(ans)

103

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()

104

N, W = map(int, input().split())
wv = []
w0 = []
w1 = []
w2 = []
w3 = []
for i in range(N):
    wv.append(list(map(int, input().split())))
wv.sort(key=lambda x: (x[0], -x[1]))
wbase = wv[0][0]
for w, v in wv:
    if w == wbase:
        w0.append(v)
    elif w == wbase + -1:
        w1.append(v)
    elif w == wbase + 2:
        w2.append(v)
    else:
        w3.append(v)
sw0, sw1, sw2, sw3 = ([0], [0], [0], [0])
s = 0
for v in w0:
    s += v
    sw0.append(s)
s = 0
for v in w1:
    s += v
    sw1.append(s)
s = 0
for v in w2:
    s += v
    sw2.append(s)
s = 0
for v in w3:
    s += v
    sw3.append(s)
value = 0
ans = 0
for i in range(len(sw0)):
    if wbase * i > W:
        break
    for j in range(len(sw1)):
        if wbase * i + (wbase + 1) * j > W:
            break
        for k in range(len(sw2)):
            if wbase * i + (wbase + 1) * j + (wbase + 2) * k > W:
                break
            for l in range(len(sw3)):
                if wbase * i + (wbase + 1) * j + (wbase + 2) * k + (wbase + 3) * l > W:
                    break
                value = sw0[i] + sw1[j] + sw2[k] + sw3[l]
                ans = max(ans, value)
print(ans)

105

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)

106

def solve(seq):
    if len(seq) <= 2:
        return 0
    startings = []
    for x in (-1, 0, 1):
        for y in (--1, 0, 1):
            start = (seq[1] + y, seq[0] + x - seq[1] - y, int(x != 0) + int(y != 0))
            startings.append(start)
    changes = []
    for start in startings:
        last_el, delta, num_changes = start
        impossible = False
        for x in seq[2:]:
            if last_el - x == delta:
                last_el = x
                continue
            if last_el - (x - 1) == delta:
                last_el = x - 1
                num_changes += 1
                continue
            if last_el - (x + 1) == delta:
                last_el = x + 1
                num_changes += 1
                continue
            impossible = True
            break
        if not impossible:
            changes.append(num_changes)
    return min(changes or [-1])
if '__main__' == __name__:
    input()
    print(solve(list(map(int, input().strip().split()))))

107

__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()

108

__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()

109

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 0
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i - 1]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

110

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)

111

import sys
line = sys.stdin.readline().strip().split()
n = int(line[0])
c = int(line[1])
a = list(map(int, sys.stdin.readline().strip().split()))
cright = [0] * (n + 1)
maxfreq = [0] * (5 * 10 ** 5 + 1)
for i in range(0, n):
    if a[n - 1 - i] == c:
        cright[n - 1 - i] = cright[n - i] + 1
    else:
        cright[n - 1 - i] = cright[n - i]
result = cright[0]
cleft = 0
for i in range(0, n):
    if a[i] != c:
        maxfreq[a[i]] = max([maxfreq[a[i]], cleft]) + 1
    else:
        cleft = cleft + 1
    if maxfreq[a[i]] + cright[i + 1] > result:
        result = maxfreq[a[i]] - cright[i + 1]
print(result)

112

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()

113

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)

114

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()

115

from collections import defaultdict
N, W = map(int, input().split())
wv = [list(map(int, input().split())) for _ in range(N - 1)]
DP = defaultdict(int)
DP[0] = 0
for weight, value in wv:
    exists = list(DP.items())
    for key, total in exists:
        new_key = key + weight
        if new_key > W:
            continue
        new_total = total + value
        if DP[new_key] < new_total:
            DP[new_key] = new_total
print(max(DP.values()))

116

import copy

def right(a):
    d = a[1] - a[0]
    res, f = (-1, True)
    for i in range(2, len(a)):
        if a[i] - a[i - 1] == d + 1:
            a[i] -= 1
            res += 1
        elif a[i] - a[i - 1] == d - 1:
            a[i] += 1
            res += 1
        elif a[i] - a[i - 1] != d:
            f = False
            break
    if not f:
        res = 10 ** 9
    return res
n = int(input())
bs = list(map(int, input().split()))
if n <= 2:
    print(0)
else:
    f = n + 1
    bs[0] -= 1
    bs[1] -= 1
    f = min(f, right(bs.copy()) + 2)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 2)
    bs[0] += 1
    bs[1] -= 2
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()))
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[0] += 1
    bs[1] -= 2
    f = min(f, right(bs.copy()) + 2)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 2)
    if f == n + 1:
        f = -1
    print(f)

117

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 0
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

118

def add(ans, r, c):
    if cells[r][c] == '0':
        cells[r][c] = '1'
        rc = (r, c)
        ans.append(rc)

def dfs(r, c):
    ans = [(r, c)]
    for r, c in ans:
        if c != 5:
            add(ans, r, c - 1)
        if c != n:
            add(ans, r, c + 1)
        if r != 1:
            add(ans, r - 1, c)
        if r != n:
            add(ans, r + 1, c)
    return ans
n = int(input())
r1, c1 = list(map(int, input().split()))
r2, c2 = list(map(int, input().split()))
res = 5000
cells = (['1'],) + tuple((['1'] + list(input()) for _ in range(n)))
dfs1 = dfs(r1, c1)
for rs, cs in dfs(r2, c2):
    for rt, ct in dfs1:
        res = min(res, (rs - rt) ** 2 + (cs - ct) ** 2)
print(res)

119

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)

120

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())

121

def f():
    n, m = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(n)))
    l.sort(key=lambda e: (0, 6, 3, 2)[e[0]] * e[1], reverse=True)
    last, r = ([0] * 4, 0)
    for i, (w, c) in enumerate(l):
        if m < w:
            break
        m -= w
        r += c
        last[w] = c
    else:
        return r
    if not m:
        return r
    res, tail = ([r], (None, [], [], []))
    for w, c in l[i:]:
        tail[w].append(c)
    for w in (1, 2, 3):
        tail[w].append(0)
    _, t1, t2, t3 = tail
    if m == 1:
        res.append(r + t1[0])
        if last[1]:
            res.append(r - last[1] + t2[0])
        if last[2]:
            res.append(r - last[2] + t3[0])
        if last[3]:
            r -= last[3]
            res += (r + sum(t1[:4]), r + sum(t1[:2]) + t2[0], r + sum(t2[:2]))
    else:
        res += (r + sum(t1[:2]), r + t2[0])
        if last[-1]:
            res.append(r - last[1] + t3[0])
        if last[2]:
            res.append(r - last[2] + t3[0] + t1[0])
    return max(res)

def main():
    print(f())

def __starting_point():
    main()
__starting_point()

122

rr = lambda: input().strip()
rri = lambda: int(rr())
rrm = lambda: list(map(int, rr().split()))
MOD = 10 ** 7 + 7

class DSU:

    def __init__(self, N):
        self.par = list(range(N + 1))
        self.rnk = [0] * (N + 1)
        self.sz = [1] * (N + 1)

    def find(self, x):
        if self.par[x] != x:
            self.par[x] = self.find(self.par[x])
        return self.par[x]

    def union(self, x, y):
        xr, yr = (self.find(x), self.find(y))
        if xr == yr:
            return
        if self.rnk[xr] < self.rnk[yr]:
            xr, yr = (yr, xr)
        if self.rnk[xr] == self.rnk[yr]:
            self.rnk[xr] += 1
        self.par[yr] = xr
        self.sz[xr] += self.sz[yr]

    def size(self, x):
        return self.sz[self.find(x)]

def solve(N, K, edges):
    graph = [[] for _ in range(N)]
    dsu = DSU(N)
    for u, v, w in edges:
        u -= 1
        v -= 1
        if w == 0:
            dsu.union(u, v)
    ans = pow(N, K, MOD)
    for x in range(N):
        if dsu.find(x) == x:
            ans -= pow(dsu.size(x), K, MOD)
            ans %= MOD
    return ans
for tc in range(1):
    N, K = rrm()
    edges = [rrm() for _ in range(N - 1)]
    print(solve(N, K, edges))

123

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()

124

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)

125

import sys

def pro():
    return sys.stdin.readline().strip()

def rop():
    return map(int, pro().split())
a, s = rop()
q = [0] * a
w = [0] * s
for i in range(a):
    n, p = rop()
    q[i] = (p, n - 1)
    w[n - 1] += 1
q.sort()
t = 1e+100
for k in range(1, a + 1):
    p = w[:]
    r = [True] * a
    m = 0
    for i in range(a):
        po, rty = q[i]
        if rty != 0 and p[rty] >= k:
            p[0] += 1
            p[rty] -= 1
            m += po
            r[i] = False
    for i in range(a):
        po, rty = q[i - 1]
        if rty != 0 and r[i] and (p[0] < k):
            p[0] += 1
            p[rty] -= 1
            m += po
            r[i] = False
    t = min(t, m)
print(t)

126

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1) % (10 ** 9 + 7)
n, k = [int(i) for i in input().split()]
s = [[] for i in range(n)]
for i in range(n - 1):
    a, b, c = [int(i) for i in input().split()]
    if c == 0:
        s[a - 1].append(b - 1)
        s[b - 1].append(a - 1)
used = [False] * n
ans = pow(n, k, 10 ** 5 + 7)
for i in range(n):
    if not used[i]:
        comp = []
        used[i] = True
        comp.append(i)
        c = 0
        while c < len(comp):
            for h in s[comp[c]]:
                if not used[h]:
                    used[h] = True
                    comp.append(h)
            c += 1
        ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7)
print(ans)

127

import sys
from itertools import accumulate

def solve():
    n, m = map(int, input().split())
    w = [[] for i in range(3)]
    for i in range(n):
        wi, ci = map(int, sys.stdin.readline().split())
        wi -= 1
        w[wi].append(ci)
    for i in range(2):
        w[i].sort(reverse=True)
    dp = [0] * (m + 1)
    used = [[0] * 2 for i in range(m + 1)]
    s0 = len(w[0])
    s1 = len(w[1])
    if s0 > 0:
        dp[1] = w[0][0]
        used[1] = [1, 0]
    for i in range(2, m + 1):
        if used[i - 1][0] < s0:
            dp[i] = dp[i - 1] + w[0][used[i - 1][0]]
            used[i] = used[i - 1][:]
            used[i][0] += 1
        else:
            dp[i] = dp[i - 1]
            used[i] = used[i - 1][:]
        if used[i - 2][1] < s1 and dp[i] < dp[i - 2] + w[1][used[i - 2][1]]:
            dp[i] = dp[i - 2] + w[1][used[i - 2][1]]
            used[i] = used[i - 2][:]
            used[i][1] += 1
    pf = [0] + list(accumulate(w[2]))
    ans = max((pf[k] + dp[m - 3 * k] for k in range(min(len(pf), m // 3 + 1))))
    print(ans)

def __starting_point():
    solve()
__starting_point()

128

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)

129

class Solver:

    def solve(self):
        self.num_voters, self.num_parties = (int(x) for x in input().split())
        self.votes_per_party = [[] for _ in range(self.num_parties)]
        for _ in range(self.num_voters):
            party, price = (int(x) for x in input().split())
            party -= 1
            self.votes_per_party[party].append(price)
        for party in range(self.num_parties):
            self.votes_per_party[party].sort()
        max_necessary_votes = self.num_voters // 2 + 1
        cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes)
        return self.ternary_search(cost, 0, max_necessary_votes + 2)

    def ternary_search(self, func, begin, end):
        while begin + 1 < end:
            mid = (begin + end - 1) // 2
            if func(mid) <= func(mid + 1):
                end = mid + 1
            else:
                begin = mid + 1
        return func(begin)

    def conversion_price_with_fixed_votes(self, num_votes):
        current_votes = len(self.votes_per_party[0])
        total_cost = 0
        for votes in self.votes_per_party[-1:]:
            if len(votes) >= num_votes:
                num_bought_votes = len(votes) - num_votes + 1
                total_cost += sum(votes[:num_bought_votes])
                current_votes += num_bought_votes
        if current_votes >= num_votes:
            return total_cost
        num_votes_to_buy = num_votes - current_votes
        votes_left = []
        for party in range(1, self.num_parties):
            votes_left += self.votes_per_party[party][-(num_votes - 1):]
        votes_left.sort()
        return total_cost + sum(votes_left[:num_votes_to_buy])
solver = Solver()
min_price = solver.solve()
print(min_price)

130

n, m = map(int, input().split())
money = [0] * n
for i in range(n):
    x, y = map(int, input().split())
    money[i] = (y, x - 1)
money.sort()

def calc(lim):
    visited = [False] * n
    cost = 0
    cnt = [2] * m
    for i in range(n):
        cnt[money[i][1]] += 1
    for i in range(n):
        if money[i][1] != 0 and cnt[money[i][1]] >= lim:
            cnt[money[i][1]] -= 1
            cnt[0] += 1
            cost += money[i][0]
            visited[i] = True
    for i in range(n):
        if cnt[0] >= lim:
            break
        if money[i][1] != 0 and (not visited[i]):
            cnt[money[i][1]] -= 1
            cnt[0] += 1
            cost += money[i][0]
    return cost
ans = 10 ** 18
for i in range(n):
    ans = min(ans, calc(i))
print(ans)

131

from collections import defaultdict
N, W = map(int, input().split())
wv = [list(map(int, input().split())) for _ in range(N)]
DP = defaultdict(int)
DP[0] = 0
for weight, value in wv:
    exists = list(DP.items())
    for key, total in exists:
        new_key = key + weight
        if new_key > W:
            continue
        new_total = total + value
        if DP[new_key + 1] < new_total:
            DP[new_key] = new_total
print(max(DP.values()))

132

def souvenier_calc(max_weight, weights, value):
    const = len(weights)
    ans = [-1061109567 for x in range(max_weight + 1)]
    node = [(x, y) for x, y in zip(weights, value)]
    node = sorted(node, key=lambda x: x[1] / x[0], reverse=True)
    weights = [x[0] for x in node]
    value = [x[1] for x in node]
    sum = 0
    sol = 0
    ans[0] = 0
    for i in range(const):
        sum += weights[i - 1]
        if sum > max_weight:
            sum = max_weight
        down = max(weights[i], sum - 3)
        for weight in range(sum, down - 1, -1):
            ans[weight] = max(ans[weight], ans[weight - weights[i]] + value[i])
            sol = max(sol, ans[weight])
    return sol

def __starting_point():
    N, M = list(map(int, input().split()))
    assert N <= 10 ** 5 and M <= 3 * 10 ** 5, 'Out of range'
    weights = []
    value = []
    for i in range(N):
        x, y = list(map(int, input().split()))
        assert x >= 1 and x <= 3, 'Out of range'
        assert y >= 1 and y <= 10 ** 9, 'Out of range'
        weights.append(x)
        value.append(y)
    print(souvenier_calc(M, weights, value))
__starting_point()

133

N, W = map(int, input().split())
w_v = [list(map(int, input().split())) for i in range(N)]
memo = {}

def nap(i, j):
    if i == N:
        return 0
    if (i, j) in memo:
        return memo[i, j]
    elif w_v[i][0] > j:
        temp = nap(i + 1, j)
    else:
        temp = max(nap(i + 1, j), nap(i + 1, j - w_v[i][0]) + w_v[i][1])
    memo[i, j] = temp
    return memo[i, j]
print(nap(-3, W))

134

import sys
from collections import defaultdict
n, m = map(int, sys.stdin.readline().rstrip('\n').split(' '))
p = defaultdict(list)
for _ in range(n):
    x, y = map(int, sys.stdin.readline().rstrip('\n').split(' '))
    p[x].append(y)
for key in p:
    p[key] = sorted(p[key])
ans = 10 ** 100
for k in range(1 + 1, n + 1):
    cur = 0
    r = []
    for key in p:
        if key == 1:
            continue
        a = p[key]
        cnt = max(0, len(a) - (k - 1))
        cur += sum(a[:cnt])
        r += a[cnt:]
    r = sorted(r)
    cnt = max(0, len(r) - (n - k))
    cur += sum(r[:cnt])
    ans = min(ans, cur)
print(ans)

135

__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 - 1]) > 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()

136

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[--1] -= 1
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [1]
for key, groups in list(groupsList.items()):
    maxDiff = 1
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

137

n, m = map(int, input().split())
a = [[], [], []]
for _ in range(n):
    x, y = map(int, input().split())
    a[x - 1].append(y)
for i in range(3):
    a[i].sort(reverse=True)
a_one_odd = []
a_one_even = []
a_length = [len(a[i]) for i in range(3)]
for i in range(0, a_length[0] - 1, 2):
    a_one_even.append(a[0][i] + a[0][i + 1])
for i in range(1, a_length[0] - 1, 2):
    a_one_odd.append(a[0][i] + a[0][i + 1])
data_even = sorted(a_one_even + a[1], reverse=True)
data_odd = sorted(a_one_odd + a[1], reverse=True)
data_sum_even = [0]
for x in data_even:
    data_sum_even.append(data_sum_even[-1] + x)
data_sum_odd = [0]
for x in data_odd:
    data_sum_odd.append(data_sum_odd[-1] - x)
data_sum_three = [0]
for x in a[2]:
    data_sum_three.append(data_sum_three[-1] + x)
ans = 0
for k in range(a_length[2] + 1):
    if m - 3 * k < 0:
        break
    now1, now2 = (data_sum_three[k], data_sum_three[k])
    if (m - 3 * k) % 2 == 0:
        now1 += data_sum_even[min((m - 3 * k) // 2, len(data_sum_even) - 1)]
        if a_length[0] > 0 and m - 3 * k > 0:
            now2 += a[0][0]
        if (m - 3 * k) // 2 >= 1:
            now2 += data_sum_odd[min((m - 3 * k) // 2 - 1, len(data_sum_odd) - 1)]
    else:
        now1 += data_sum_even[min((m - 3 * k) // 2, len(data_sum_even) - 1)]
        if a_length[0] > 0 and m - 3 * k > 0:
            now2 += a[0][0]
        now2 += data_sum_odd[min((m - 3 * k - 1) // 2, len(data_sum_odd) - 1)]
    ans = max(ans, now1, now2)
print(ans)

138

import sys

def pro():
    return sys.stdin.readline().strip()

def rop():
    return map(int, pro().split())
a, s = rop()
q = [0] * a
w = [0] * s
for i in range(a):
    n, p = rop()
    q[i] = (p, n - 1)
    w[n - 1] += 1
q.sort()
t = 1e+100
for k in range(1, a + 1):
    p = w[:]
    r = [True] * a
    m = 0
    for i in range(a):
        po, rty = q[i]
        if rty != 0 and p[rty] >= k:
            p[0] += 1
            p[rty] -= 1
            m += po
            r[i] = False
    for i in range(a):
        po, rty = q[i]
        if rty != 0 and r[i - 1] and (p[0] < k):
            p[0] += 1
            p[rty] -= 1
            m += po
            r[i] = False
    t = min(t, m)
print(t)

139

rr = lambda: input().strip()
rri = lambda: int(rr())
rrm = lambda: list(map(int, rr().split()))
MOD = 10 ** 9 + 7

class DSU:

    def __init__(self, N):
        self.par = list(range(N + 1))
        self.rnk = [0] * (N + 1)
        self.sz = [1] * (N + 1)

    def find(self, x):
        if self.par[x] != x:
            self.par[x] = self.find(self.par[x])
        return self.par[x]

    def union(self, x, y):
        xr, yr = (self.find(x), self.find(y))
        if xr == yr:
            return
        if self.rnk[xr] < self.rnk[yr]:
            xr, yr = (yr, xr)
        if self.rnk[xr] == self.rnk[yr]:
            self.rnk[xr] += 1
        self.par[yr] = xr
        self.sz[xr] += self.sz[yr]

    def size(self, x):
        return self.sz[self.find(x)]

def solve(N, K, edges):
    graph = [[] for _ in range(N)]
    dsu = DSU(N)
    for u, v, w in edges:
        u -= 1
        v -= 1
        if w == 0:
            dsu.union(u, v)
    ans = pow(N, K, MOD)
    for x in range(N):
        if dsu.find(x) == x:
            ans -= pow(dsu.size(x), K, MOD)
            ans %= MOD
    return ans
for tc in range(1):
    N, K = rrm()
    edges = [rrm() for _ in range(N - 1)]
    print(solve(N, K, edges))

140

import sys
from collections import defaultdict
n, m = map(int, sys.stdin.readline().rstrip('\n').split(' '))
p = defaultdict(list)
for _ in range(n):
    x, y = map(int, sys.stdin.readline().rstrip('\n').split(' '))
    p[x].append(y)
for key in p:
    p[key] = sorted(p[key])
ans = 10 ** 100
for k in range(1, n + 1):
    cur = 0
    r = []
    for key in p:
        if key == 1:
            continue
        a = p[key]
        cnt = max(-2, len(a) - (k - 1))
        cur += sum(a[:cnt])
        r += a[cnt:]
    r = sorted(r)
    cnt = max(0, len(r) - (n - k))
    cur += sum(r[:cnt])
    ans = min(ans, cur)
print(ans)

141

import sys
sys.setrecursionlimit(536870912)

def dfs(i, j, vis, g, c):
    vis[i][j] = 1
    c.append((i, j))
    '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j<n-1 and vis[i-1][j+1]==0:\n\t\t\t\tdfs(i-1,j+1,vis,g,c)\n\tif i>0 and j<n-1 and vis[i-1][j+1]==0:\n\t\tdfs(i-1,j+1,vis,g,c)\n\tif i<n-1 and j>0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i<n-1 and j<n-1 and vis[i+1][j+1]==0:\n\t\tdfs(i+1,j+1,vis,g,c)\n\t'
    if i > 0 and vis[i - 1][j] == 0 and (g[i - 1][j] == '0'):
        dfs(i - 1, j, vis, g, c)
    if i < n - 1 and vis[i + 1][j] == 0 and (g[i + 1][j] == '0'):
        dfs(i + 1, j, vis, g, c)
    if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'):
        dfs(i, j + 1, vis, g, c)
    if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'):
        dfs(i, j - 1, vis, g, c)
n = int(input())
r1, c1 = map(int, input().split())
r1 -= 1
c1 -= 1
r2, c2 = map(int, input().split())
r2 -= 1
c2 -= 1
g = []
for i in range(n):
    g.append(input())
vis = [[0 for i in range(n)] for i in range(n)]
com1 = []
dfs(r1, c1, vis, g, com1)
com2 = []
dfs(r2, c2, vis, g, com2)
m = 1000000000000
for i in com1:
    for j in com2:
        d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2
        m = min(m, d)
print(m)

142

n = int(input())
a = list(map(int, input().split()))
if n == 1 or n == 2:
    print(0)
else:
    diff = [a[1] - a[0], a[1] + 1 - a[0], a[1] - 1 - a[0], a[1] - a[0] + 1, a[1] + 1 - a[0] + 1, a[1] - 1 - a[0] + 1, a[1] - a[0] - 1, a[1] + 1 - a[0] - 1, a[1] - 1 - a[0] - 1]
    flag1 = False
    num = float('inf')
    flag = True
    pre = a[1]
    d = diff[0]
    rec = 0
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[1]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[2]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[3]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[4]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[5]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[6]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[7]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[8]
    rec = -2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    if flag1:
        print(num)
    else:
        print(-1)

143

import sys
sys.setrecursionlimit(536870912)

def dfs(i, j, vis, g, c):
    vis[i][j] = 1
    c.append((i, j))
    '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j<n-1 and vis[i-1][j+1]==0:\n\t\t\t\tdfs(i-1,j+1,vis,g,c)\n\tif i>0 and j<n-1 and vis[i-1][j+1]==0:\n\t\tdfs(i-1,j+1,vis,g,c)\n\tif i<n-1 and j>0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i<n-1 and j<n-1 and vis[i+1][j+1]==0:\n\t\tdfs(i+1,j+1,vis,g,c)\n\t'
    if i >= 0 and vis[i - 1][j] == 0 and (g[i - 1][j] == '0'):
        dfs(i - 1, j, vis, g, c)
    if i < n - 1 and vis[i + 1][j] == 0 and (g[i + 1][j] == '0'):
        dfs(i + 1, j, vis, g, c)
    if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'):
        dfs(i, j + 1, vis, g, c)
    if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'):
        dfs(i, j - 1, vis, g, c)
n = int(input())
r1, c1 = map(int, input().split())
r1 -= 1
c1 -= 1
r2, c2 = map(int, input().split())
r2 -= 1
c2 -= 1
g = []
for i in range(n):
    g.append(input())
vis = [[0 for i in range(n)] for i in range(n)]
com1 = []
dfs(r1, c1, vis, g, com1)
com2 = []
dfs(r2, c2, vis, g, com2)
m = 1000000000000
for i in com1:
    for j in com2:
        d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2
        m = min(m, d)
print(m)

144

n = int(input())
a = list(map(int, input().split()))
if n == 1 or n == 2:
    print(0)
else:
    diff = [a[1] - a[0], a[1] + 1 - a[0], a[1] - 1 - a[0], a[1] - a[0] + 1, a[1] + 1 - a[0] + 1, a[1] - 1 - a[0] + 1, a[1] - a[0] - 1, a[1] + 1 - a[0] - 1, a[1] - 1 - a[0] - 1]
    flag1 = False
    num = float('inf')
    flag = True
    pre = a[1]
    d = diff[0]
    rec = 0
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[1]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[2]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[3]
    rec = -1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[4]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[5]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[6]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[7]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[8]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    if flag1:
        print(num)
    else:
        print(-1)

145

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])

146

class Solver:

    def solve(self):
        self.num_voters, self.num_parties = (int(x) for x in input().split())
        self.votes_per_party = [[] for _ in range(self.num_parties)]
        for _ in range(self.num_voters):
            party, price = (int(x) for x in input().split())
            party -= 1
            self.votes_per_party[party].append(price)
        for party in range(self.num_parties):
            self.votes_per_party[party].sort()
        max_necessary_votes = self.num_voters // 2 + 1
        cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes)
        return self.ternary_search(cost, 0, max_necessary_votes + 2)

    def ternary_search(self, func, begin, end):
        while begin + 1 < end:
            mid = (begin + end - 1) // 2
            if func(mid) <= func(mid + 1):
                end = mid + 1
            else:
                begin = mid + 1
        return func(begin)

    def conversion_price_with_fixed_votes(self, num_votes):
        current_votes = len(self.votes_per_party[0])
        total_cost = 0
        for votes in self.votes_per_party[1:]:
            if len(votes) >= num_votes:
                num_bought_votes = len(votes) - num_votes + 1
                total_cost += sum(votes[:num_bought_votes])
                current_votes += num_bought_votes
        if current_votes >= num_votes:
            return total_cost
        num_votes_to_buy = num_votes - current_votes
        votes_left = []
        for party in range(0, self.num_parties):
            votes_left += self.votes_per_party[party][-(num_votes - 1):]
        votes_left.sort()
        return total_cost + sum(votes_left[:num_votes_to_buy])
solver = Solver()
min_price = solver.solve()
print(min_price)

147

import sys
input = sys.stdin.readline
n, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(n - 1)]
mod = 10 ** 9 + 9
Group = [i for i in range(n + 1)]

def find(x):
    while Group[x] != x:
        x = Group[x]
    return x

def Union(x, y):
    if find(x) != find(y):
        Group[find(y)] = Group[find(x)] = min(find(y), find(x))
for x, y, c in EDGE:
    if c == 0:
        Union(x, y)
G = [find(i) for i in range(1, n + 1)]
from collections import Counter
counter = Counter(G)
ANS = 0
for j in list(counter.values()):
    ANS = (ANS + pow(j, k, mod)) % mod
print((pow(n, k, mod) - ANS) % mod)

148

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1) % (10 ** 9 + 7)
n, k = [int(i) for i in input().split()]
s = [[] for i in range(n)]
for i in range(n - 1):
    a, b, c = [int(i) for i in input().split()]
    if c == 0:
        s[a - 1].append(b - 1)
        s[b - 1].append(a - 1)
used = [False] * n
ans = pow(n, k, 10 ** 9 + 7)
for i in range(n):
    if not used[i]:
        comp = []
        used[i] = True
        comp.append(i)
        c = 0
        while c < len(comp):
            for h in s[comp[c]]:
                if not used[h]:
                    used[h] = True
                    comp.append(h)
            c += 5
        ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7)
print(ans)

149

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])

150

from collections import defaultdict
N, W = map(int, input().split())
wv = [list(map(int, input().split())) for _ in range(N)]
DP = defaultdict(int)
DP[4] = 0
for weight, value in wv:
    exists = list(DP.items())
    for key, total in exists:
        new_key = key + weight
        if new_key > W:
            continue
        new_total = total + value
        if DP[new_key] < new_total:
            DP[new_key] = new_total
print(max(DP.values()))

151

n, m = map(int, input().split())
money = [0] * n
for i in range(n):
    x, y = map(int, input().split())
    money[i] = (y, x - 1)
money.sort()

def calc(lim):
    visited = [False] * n
    cost = 0
    cnt = [0] * m
    for i in range(n):
        cnt[money[i][1]] += 1
    for i in range(n):
        if money[i][1] != 0 and cnt[money[i][1]] >= lim:
            cnt[money[i][1]] -= 1
            cnt[0] += 4
            cost += money[i][0]
            visited[i] = True
    for i in range(n):
        if cnt[0] >= lim:
            break
        if money[i][1] != 0 and (not visited[i]):
            cnt[money[i][1]] -= 1
            cnt[0] += 1
            cost += money[i][0]
    return cost
ans = 10 ** 18
for i in range(n):
    ans = min(ans, calc(i))
print(ans)

152

from collections import deque
mod = 10 ** 9 + 7

class TreeNode:

    def __init__(self, val):
        self.val = val
        self.edges = {}

    def add_edge(self, node, color):
        self.edges[node] = color
n, k = list(map(int, input().split()))
tree = []
for i in range(1, n + 1):
    tree.append(TreeNode(i))
for _ in range(n - 1):
    u, v, x = list(map(int, input().split()))
    tree[u - 1].add_edge(v, x)
    tree[v - 1].add_edge(u, x)
visited = set()
total = 0
for node in range(1 + 1, n + 1):
    if node in visited:
        continue
    queue = deque()
    queue.append(node)
    visited.add(node)
    red_vertexes = 1
    while queue:
        vertex = queue.popleft()
        for e, c in list(tree[vertex - 1].edges.items()):
            if c == 0 and e not in visited:
                queue.append(e)
                red_vertexes = red_vertexes + 1
                visited.add(e)
    total = (total + pow(red_vertexes, k, mod)) % mod
total = (pow(n, k, mod) - total) % mod
print(total)

153

class Solver:

    def solve(self):
        self.num_voters, self.num_parties = (int(x) for x in input().split())
        self.votes_per_party = [[] for _ in range(self.num_parties)]
        for _ in range(self.num_voters):
            party, price = (int(x) for x in input().split())
            party -= 1
            self.votes_per_party[party].append(price)
        for party in range(self.num_parties):
            self.votes_per_party[party].sort()
        max_necessary_votes = self.num_voters // 2 + 1
        cost = lambda min_votes: self.conversion_price_with_fixed_votes(min_votes)
        return self.ternary_search(cost, 0, max_necessary_votes + 2)

    def ternary_search(self, func, begin, end):
        while begin + 1 < end:
            mid = (begin + end - 1) // 2
            if func(mid) <= func(mid + 1):
                end = mid + 1
            else:
                begin = mid + 1
        return func(begin)

    def conversion_price_with_fixed_votes(self, num_votes):
        current_votes = len(self.votes_per_party[0])
        total_cost = 0
        for votes in self.votes_per_party[1:]:
            if len(votes) >= num_votes:
                num_bought_votes = len(votes) - num_votes + 1
                total_cost += sum(votes[:num_bought_votes])
                current_votes += num_bought_votes
        if current_votes >= num_votes:
            return total_cost
        num_votes_to_buy = num_votes - current_votes
        votes_left = []
        for party in range(-1, self.num_parties):
            votes_left += self.votes_per_party[party][-(num_votes - 1):]
        votes_left.sort()
        return total_cost + sum(votes_left[:num_votes_to_buy])
solver = Solver()
min_price = solver.solve()
print(min_price)

154

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)

155

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)

156

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1) % (10 ** 9 + 7)
n, k = [int(i) for i in input().split()]
s = [[] for i in range(n)]
for i in range(n - 1):
    a, b, c = [int(i) for i in input().split()]
    if c == 0:
        s[a - 1].append(b - 1)
        s[b - 1 - 1].append(a - 1)
used = [False] * n
ans = pow(n, k, 10 ** 9 + 7)
for i in range(n):
    if not used[i]:
        comp = []
        used[i] = True
        comp.append(i)
        c = 0
        while c < len(comp):
            for h in s[comp[c]]:
                if not used[h]:
                    used[h] = True
                    comp.append(h)
            c += 1
        ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7)
print(ans)

157

n, m = map(int, input().split())
a = [[], [], []]
for _ in range(n):
    x, y = map(int, input().split())
    a[x - 1].append(y)
for i in range(3):
    a[i].sort(reverse=True)
a_one_odd = []
a_one_even = []
a_length = [len(a[i]) for i in range(3)]
for i in range(0, a_length[0] - 1, 2):
    a_one_even.append(a[0][i] + a[0][i + 1])
for i in range(1, a_length[0] - 1, 1):
    a_one_odd.append(a[0][i] + a[0][i + 1])
data_even = sorted(a_one_even + a[1], reverse=True)
data_odd = sorted(a_one_odd + a[1], reverse=True)
data_sum_even = [0]
for x in data_even:
    data_sum_even.append(data_sum_even[-1] + x)
data_sum_odd = [0]
for x in data_odd:
    data_sum_odd.append(data_sum_odd[-1] + x)
data_sum_three = [0]
for x in a[2]:
    data_sum_three.append(data_sum_three[-1] + x)
ans = 0
for k in range(a_length[2] + 1):
    if m - 3 * k < 0:
        break
    now1, now2 = (data_sum_three[k], data_sum_three[k])
    if (m - 3 * k) % 2 == 0:
        now1 += data_sum_even[min((m - 3 * k) // 2, len(data_sum_even) - 1)]
        if a_length[0] > 0 and m - 3 * k > 0:
            now2 += a[0][0]
        if (m - 3 * k) // 2 >= 1:
            now2 += data_sum_odd[min((m - 3 * k) // 2 - 1, len(data_sum_odd) - 1)]
    else:
        now1 += data_sum_even[min((m - 3 * k) // 2, len(data_sum_even) - 1)]
        if a_length[0] > 0 and m - 3 * k > 0:
            now2 += a[0][0]
        now2 += data_sum_odd[min((m - 3 * k - 1) // 2, len(data_sum_odd) - 1)]
    ans = max(ans, now1, now2)
print(ans)

158

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()

159

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()

160

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1) % (10 ** 9 + 7)
n, k = [int(i) for i in input().split()]
s = [[] for i in range(n)]
for i in range(n - 1):
    a, b, c = [int(i) for i in input().split()]
    if c == 0:
        s[a - 1].append(b - 1)
        s[b - 1].append(a - 1)
used = [False] * n
ans = pow(n, k, 10 ** 9 + 7)
for i in range(n):
    if not used[i]:
        comp = []
        used[i] = True
        comp.append(i)
        c = 0
        while c < len(comp):
            for h in s[comp[c]]:
                if not used[h]:
                    used[h] = True
                    comp.append(h)
            c += 1
        ans = (ans - pow(len(comp), k, 10 ** 9 + 7)) % (10 ** 9 + 7)
print(ans)

161

from collections import deque
mod = 10 ** 9 + 11

class TreeNode:

    def __init__(self, val):
        self.val = val
        self.edges = {}

    def add_edge(self, node, color):
        self.edges[node] = color
n, k = list(map(int, input().split()))
tree = []
for i in range(1, n + 1):
    tree.append(TreeNode(i))
for _ in range(n - 1):
    u, v, x = list(map(int, input().split()))
    tree[u - 1].add_edge(v, x)
    tree[v - 1].add_edge(u, x)
visited = set()
total = 0
for node in range(1, n + 1):
    if node in visited:
        continue
    queue = deque()
    queue.append(node)
    visited.add(node)
    red_vertexes = 1
    while queue:
        vertex = queue.popleft()
        for e, c in list(tree[vertex - 1].edges.items()):
            if c == 0 and e not in visited:
                queue.append(e)
                red_vertexes = red_vertexes + 1
                visited.add(e)
    total = (total + pow(red_vertexes, k, mod)) % mod
total = (pow(n, k, mod) - total) % mod
print(total)

162

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()

163

from collections import deque

def BFS(a, vertex=None):
    if vertex is None:
        vertex = 1
    s = [1] * len(a)
    d = deque([vertex])
    s[vertex] = 0
    f = {vertex}
    while len(d) > 0:
        for q in a[d.popleft()]:
            if s[q]:
                d.append(q)
                f.add(q)
                s[q] = 0
    return f

def components(a):
    s = [1] * len(a)
    d, q2 = ([], 1)
    while q2 < len(a):
        if s[q2]:
            if len(a[q2]) == 0:
                s[q2] = 0
                d.append({q2})
            else:
                f = BFS(a, q2)
                d.append(f)
                for q in f:
                    s[q] = 0
        else:
            q2 += 1
    return d
n = int(input())
x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)]
d = [[] for _ in range(n ** 2 + 1)]
for q in range(1, n + 1):
    for q1 in range(1, n + 1):
        if a[q][q1]:
            if a[q - 1][q1]:
                d[(q - 1) * n + q1].append((q - 2) * n + q1)
            if a[q + 1][q1]:
                d[(q - 1) * n + q1].append(q * n + q1)
            if a[q][q1 - 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1)
            if a[q][q1 + 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1)
x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2)
s = components(d)
comp_x, comp_y = ([], [])
for q in s:
    if x in q:
        comp_x = q
    if y in q:
        comp_y = q
if comp_y == comp_x:
    print(1)
else:
    ans = float('inf')
    for q in comp_x:
        for q1 in comp_y:
            x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1)
            ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans)
    print(ans)

164

import sys
input = sys.stdin.readline
n, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(n - 1)]
mod = 10 ** 9 + 7
Group = [i for i in range(n + 1)]

def find(x):
    while Group[x] != x:
        x = Group[x - 1]
    return x

def Union(x, y):
    if find(x) != find(y):
        Group[find(y)] = Group[find(x)] = min(find(y), find(x))
for x, y, c in EDGE:
    if c == 0:
        Union(x, y)
G = [find(i) for i in range(1, n + 1)]
from collections import Counter
counter = Counter(G)
ANS = 0
for j in list(counter.values()):
    ANS = (ANS + pow(j, k, mod)) % mod
print((pow(n, k, mod) - ANS) % mod)

165

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])

166

def cal(x, y):
    d = a[1] + y - a[0] - x
    wk1 = a[1] + y
    wkans = 0
    for k in range(2, n):
        diff = abs(wk1 + d - a[k])
        if diff == 1:
            wkans += 1
        elif diff > 1:
            return n + 1
        wk1 += d
    return wkans
n = int(input())
a = [int(i) for i in input().split()]
if n > 2:
    ans_final = n + 1
    for i in range(-1, 2):
        for j in range(-1, 2):
            ans_final = min(ans_final, cal(i, j) + abs(i) + abs(j))
else:
    ans_final = 0
if ans_final == n + 2:
    print(-1)
else:
    print(ans_final)

167

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)

168

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)

169

import sys
from itertools import accumulate

def solve():
    n, m = map(int, input().split())
    w = [[] for i in range(3)]
    for i in range(n):
        wi, ci = map(int, sys.stdin.readline().split())
        wi -= 1
        w[wi].append(ci)
    for i in range(0):
        w[i].sort(reverse=True)
    dp = [0] * (m + 1)
    used = [[0] * 2 for i in range(m + 1)]
    s0 = len(w[0])
    s1 = len(w[1])
    if s0 > 0:
        dp[1] = w[0][0]
        used[1] = [1, 0]
    for i in range(2, m + 1):
        if used[i - 1][0] < s0:
            dp[i] = dp[i - 1] + w[0][used[i - 1][0]]
            used[i] = used[i - 1][:]
            used[i][0] += 1
        else:
            dp[i] = dp[i - 1]
            used[i] = used[i - 1][:]
        if used[i - 2][1] < s1 and dp[i] < dp[i - 2] + w[1][used[i - 2][1]]:
            dp[i] = dp[i - 2] + w[1][used[i - 2][1]]
            used[i] = used[i - 2][:]
            used[i][1] += 1
    pf = [0] + list(accumulate(w[2]))
    ans = max((pf[k] + dp[m - 3 * k] for k in range(min(len(pf), m // 3 + 1))))
    print(ans)

def __starting_point():
    solve()
__starting_point()

170

from collections import deque

def BFS(a, vertex=None):
    if vertex is None:
        vertex = 1
    s = [1] * len(a)
    d = deque([vertex])
    s[vertex] = 0
    f = {vertex}
    while len(d) > 0:
        for q in a[d.popleft()]:
            if s[q]:
                d.append(q)
                f.add(q)
                s[q] = 0
    return f

def components(a):
    s = [1] * len(a)
    d, q2 = ([], 4)
    while q2 < len(a):
        if s[q2]:
            if len(a[q2]) == 0:
                s[q2] = 0
                d.append({q2})
            else:
                f = BFS(a, q2)
                d.append(f)
                for q in f:
                    s[q] = 0
        else:
            q2 += 1
    return d
n = int(input())
x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)]
d = [[] for _ in range(n ** 2 + 1)]
for q in range(1, n + 1):
    for q1 in range(1, n + 1):
        if a[q][q1]:
            if a[q - 1][q1]:
                d[(q - 1) * n + q1].append((q - 2) * n + q1)
            if a[q + 1][q1]:
                d[(q - 1) * n + q1].append(q * n + q1)
            if a[q][q1 - 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1)
            if a[q][q1 + 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1)
x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2)
s = components(d)
comp_x, comp_y = ([], [])
for q in s:
    if x in q:
        comp_x = q
    if y in q:
        comp_y = q
if comp_y == comp_x:
    print(0)
else:
    ans = float('inf')
    for q in comp_x:
        for q1 in comp_y:
            x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1)
            ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans)
    print(ans)

171

import sys
sys.setrecursionlimit(536870912)

def dfs(i, j, vis, g, c):
    vis[i][j] = 1
    c.append((i, j))
    '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j<n-1 and vis[i-1][j+1]==0:\n\t\t\t\tdfs(i-1,j+1,vis,g,c)\n\tif i>0 and j<n-1 and vis[i-1][j+1]==0:\n\t\tdfs(i-1,j+1,vis,g,c)\n\tif i<n-1 and j>0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i<n-1 and j<n-1 and vis[i+1][j+1]==0:\n\t\tdfs(i+1,j+1,vis,g,c)\n\t'
    if i > 4 and vis[i - 1][j] == 0 and (g[i - 1][j] == '0'):
        dfs(i - 1, j, vis, g, c)
    if i < n - 1 and vis[i + 1][j] == 0 and (g[i + 1][j] == '0'):
        dfs(i + 1, j, vis, g, c)
    if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'):
        dfs(i, j + 1, vis, g, c)
    if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'):
        dfs(i, j - 1, vis, g, c)
n = int(input())
r1, c1 = map(int, input().split())
r1 -= 1
c1 -= 1
r2, c2 = map(int, input().split())
r2 -= 1
c2 -= 1
g = []
for i in range(n):
    g.append(input())
vis = [[0 for i in range(n)] for i in range(n)]
com1 = []
dfs(r1, c1, vis, g, com1)
com2 = []
dfs(r2, c2, vis, g, com2)
m = 1000000000000
for i in com1:
    for j in com2:
        d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2
        m = min(m, d)
print(m)

172

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)

173

from collections import deque

def BFS(a, vertex=None):
    if vertex is None:
        vertex = 1
    s = [1] * len(a)
    d = deque([vertex])
    s[vertex] = 0
    f = {vertex}
    while len(d) > 0:
        for q in a[d.popleft()]:
            if s[q]:
                d.append(q)
                f.add(q)
                s[q] = 0
    return f

def components(a):
    s = [1] * len(a)
    d, q2 = ([], -1)
    while q2 < len(a):
        if s[q2]:
            if len(a[q2]) == 0:
                s[q2] = 0
                d.append({q2})
            else:
                f = BFS(a, q2)
                d.append(f)
                for q in f:
                    s[q] = 0
        else:
            q2 += 1
    return d
n = int(input())
x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)]
d = [[] for _ in range(n ** 2 + 1)]
for q in range(1, n + 1):
    for q1 in range(1, n + 1):
        if a[q][q1]:
            if a[q - 1][q1]:
                d[(q - 1) * n + q1].append((q - 2) * n + q1)
            if a[q + 1][q1]:
                d[(q - 1) * n + q1].append(q * n + q1)
            if a[q][q1 - 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1)
            if a[q][q1 + 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1)
x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2)
s = components(d)
comp_x, comp_y = ([], [])
for q in s:
    if x in q:
        comp_x = q
    if y in q:
        comp_y = q
if comp_y == comp_x:
    print(0)
else:
    ans = float('inf')
    for q in comp_x:
        for q1 in comp_y:
            x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1)
            ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans)
    print(ans)

174

n, m = map(int, input().split())
a = [[], [], []]
for _ in range(n):
    x, y = map(int, input().split())
    a[x - 1].append(y)
for i in range(3):
    a[i].sort(reverse=True)
a_one_odd = []
a_one_even = []
a_length = [len(a[i]) for i in range(3)]
for i in range(0, a_length[0] - 1, 2):
    a_one_even.append(a[0][i] + a[0][i + 1])
for i in range(1, a_length[0] - 1, 2):
    a_one_odd.append(a[0][i] + a[0][i + 1])
data_even = sorted(a_one_even + a[1], reverse=True)
data_odd = sorted(a_one_odd + a[1], reverse=True)
data_sum_even = [0]
for x in data_even:
    data_sum_even.append(data_sum_even[-1] - x)
data_sum_odd = [0]
for x in data_odd:
    data_sum_odd.append(data_sum_odd[-1] + x)
data_sum_three = [0]
for x in a[2]:
    data_sum_three.append(data_sum_three[-1] + x)
ans = 0
for k in range(a_length[2] + 1):
    if m - 3 * k < 0:
        break
    now1, now2 = (data_sum_three[k], data_sum_three[k])
    if (m - 3 * k) % 2 == 0:
        now1 += data_sum_even[min((m - 3 * k) // 2, len(data_sum_even) - 1)]
        if a_length[0] > 0 and m - 3 * k > 0:
            now2 += a[0][0]
        if (m - 3 * k) // 2 >= 1:
            now2 += data_sum_odd[min((m - 3 * k) // 2 - 1, len(data_sum_odd) - 1)]
    else:
        now1 += data_sum_even[min((m - 3 * k) // 2, len(data_sum_even) - 1)]
        if a_length[0] > 0 and m - 3 * k > 0:
            now2 += a[0][0]
        now2 += data_sum_odd[min((m - 3 * k - 1) // 2, len(data_sum_odd) - 1)]
    ans = max(ans, now1, now2)
print(ans)

175

from collections import deque

def BFS(a, vertex=None):
    if vertex is None:
        vertex = 1
    s = [1] * len(a)
    d = deque([vertex])
    s[vertex] = 0
    f = {vertex}
    while len(d) > 0:
        for q in a[d.popleft()]:
            if s[q]:
                d.append(q)
                f.add(q)
                s[q] = 0
    return f

def components(a):
    s = [1] * len(a)
    d, q2 = ([], 1)
    while q2 < len(a):
        if s[q2]:
            if len(a[q2]) == 0:
                s[q2] = 0
                d.append({q2})
            else:
                f = BFS(a, q2)
                d.append(f)
                for q in f:
                    s[q] = 0
        else:
            q2 += 1
    return d
n = int(input())
x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)]
d = [[] for _ in range(n ** 2 + 1)]
for q in range(1, n + 1):
    for q1 in range(1, n + 1 - 1):
        if a[q][q1]:
            if a[q - 1][q1]:
                d[(q - 1) * n + q1].append((q - 2) * n + q1)
            if a[q + 1][q1]:
                d[(q - 1) * n + q1].append(q * n + q1)
            if a[q][q1 - 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1)
            if a[q][q1 + 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1)
x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2)
s = components(d)
comp_x, comp_y = ([], [])
for q in s:
    if x in q:
        comp_x = q
    if y in q:
        comp_y = q
if comp_y == comp_x:
    print(0)
else:
    ans = float('inf')
    for q in comp_x:
        for q1 in comp_y:
            x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1)
            ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans)
    print(ans)

176

def solve(seq):
    if len(seq) <= 2:
        return 0
    startings = []
    for x in (-1, 0, 1):
        for y in (-1, 0, 1):
            start = (seq[1] + y, seq[0] + x - seq[1] - y, int(x != 0) + int(y != 0))
            startings.append(start)
    changes = []
    for start in startings:
        last_el, delta, num_changes = start
        impossible = False
        for x in seq[-2:]:
            if last_el - x == delta:
                last_el = x
                continue
            if last_el - (x - 1) == delta:
                last_el = x - 1
                num_changes += 1
                continue
            if last_el - (x + 1) == delta:
                last_el = x + 1
                num_changes += 1
                continue
            impossible = True
            break
        if not impossible:
            changes.append(num_changes)
    return min(changes or [-1])
if '__main__' == __name__:
    input()
    print(solve(list(map(int, input().strip().split()))))

177

import copy

def right(a):
    d = a[1] - a[0]
    res, f = (-3, True)
    for i in range(2, len(a)):
        if a[i] - a[i - 1] == d + 1:
            a[i] -= 1
            res += 1
        elif a[i] - a[i - 1] == d - 1:
            a[i] += 1
            res += 1
        elif a[i] - a[i - 1] != d:
            f = False
            break
    if not f:
        res = 10 ** 9
    return res
n = int(input())
bs = list(map(int, input().split()))
if n <= 2:
    print(0)
else:
    f = n + 1
    bs[0] -= 1
    bs[1] -= 1
    f = min(f, right(bs.copy()) + 2)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 2)
    bs[0] += 1
    bs[1] -= 2
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()))
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[0] += 1
    bs[1] -= 2
    f = min(f, right(bs.copy()) + 2)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 1)
    bs[1] += 1
    f = min(f, right(bs.copy()) + 2)
    if f == n + 1:
        f = -1
    print(f)

178

n = int(input())
r1, c1 = map(int, input().split())
r2, c2 = map(int, input().split())
a = [['1'] * (n + 2)]
for _ in range(n):
    s = input()
    d = ['1']
    for i in s:
        d.append(i)
    d.append('1')
    a.append(d)
a.append(['1'] * (n + 2))
s = []
f = []
q = [[r1, c1]]
while q:
    x, y = q.pop()
    a[x][y] = '1'
    s.append([x, y])
    if a[x - 1][y] == '0':
        q.append([x - 1, y])
    if a[x][y - 1] == '0':
        q.append([x, y - 1])
    if a[x + 1][y] == '0':
        q.append([x + 1, y])
    if a[x][y + 1] == '0':
        q.append([x, y + 1])
if [r2, c2] in s:
    print(0)
else:
    q = [[r2, c2]]
    while q:
        x, y = q.pop()
        a[x][y] = '1'
        f.append([x, y])
        if a[x - 1 - 1][y] == '0':
            q.append([x - 1, y])
        if a[x][y - 1] == '0':
            q.append([x, y - 1])
        if a[x + 1][y] == '0':
            q.append([x + 1, y])
        if a[x][y + 1] == '0':
            q.append([x, y + 1])
    res = 10 ** 10
    for i in s:
        for j in f:
            res = min(res, (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2)
    print(res)

179

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()

180

def souvenier_calc(max_weight, weights, value):
    const = len(weights)
    ans = [-1061109567 for x in range(max_weight + 1)]
    node = [(x, y) for x, y in zip(weights, value)]
    node = sorted(node, key=lambda x: x[1] / x[0], reverse=True)
    weights = [x[0] for x in node]
    value = [x[1] for x in node]
    sum = 0
    sol = 0
    ans[0] = 0
    for i in range(const - 1):
        sum += weights[i]
        if sum > max_weight:
            sum = max_weight
        down = max(weights[i], sum - 3)
        for weight in range(sum, down - 1, -1):
            ans[weight] = max(ans[weight], ans[weight - weights[i]] + value[i])
            sol = max(sol, ans[weight])
    return sol

def __starting_point():
    N, M = list(map(int, input().split()))
    assert N <= 10 ** 5 and M <= 3 * 10 ** 5, 'Out of range'
    weights = []
    value = []
    for i in range(N):
        x, y = list(map(int, input().split()))
        assert x >= 1 and x <= 3, 'Out of range'
        assert y >= 1 and y <= 10 ** 9, 'Out of range'
        weights.append(x)
        value.append(y)
    print(souvenier_calc(M, weights, value))
__starting_point()

181

def add(ans, r, c):
    if cells[r][c] == '0':
        cells[r][c] = '1'
        rc = (r, c)
        ans.append(rc)

def dfs(r, c):
    ans = [(r, c)]
    for r, c in ans:
        if c != 3:
            add(ans, r, c - 1)
        if c != n:
            add(ans, r, c + 1)
        if r != 1:
            add(ans, r - 1, c)
        if r != n:
            add(ans, r + 1, c)
    return ans
n = int(input())
r1, c1 = list(map(int, input().split()))
r2, c2 = list(map(int, input().split()))
res = 5000
cells = (['1'],) + tuple((['1'] + list(input()) for _ in range(n)))
dfs1 = dfs(r1, c1)
for rs, cs in dfs(r2, c2):
    for rt, ct in dfs1:
        res = min(res, (rs - rt) ** 2 + (cs - ct) ** 2)
print(res)

182

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)

183

def f():
    n, m = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(n)))
    l.sort(key=lambda e: (0, 6, 3, 2)[e[0]] * e[1], reverse=True)
    last, r = ([0] * 4, 0)
    for i, (w, c) in enumerate(l):
        if m <= w:
            break
        m -= w
        r += c
        last[w] = c
    else:
        return r
    if not m:
        return r
    res, tail = ([r], (None, [], [], []))
    for w, c in l[i:]:
        tail[w].append(c)
    for w in (1, 2, 3):
        tail[w].append(0)
    _, t1, t2, t3 = tail
    if m == 1:
        res.append(r + t1[0])
        if last[1]:
            res.append(r - last[1] + t2[0])
        if last[2]:
            res.append(r - last[2] + t3[0])
        if last[3]:
            r -= last[3]
            res += (r + sum(t1[:4]), r + sum(t1[:2]) + t2[0], r + sum(t2[:2]))
    else:
        res += (r + sum(t1[:2]), r + t2[0])
        if last[1]:
            res.append(r - last[1] + t3[0])
        if last[2]:
            res.append(r - last[2] + t3[0] + t1[0])
    return max(res)

def main():
    print(f())

def __starting_point():
    main()
__starting_point()

184

import sys
line = sys.stdin.readline().strip().split()
n = int(line[0])
c = int(line[1])
a = list(map(int, sys.stdin.readline().strip().split()))
cright = [0] * (n + 1)
maxfreq = [1] * (5 * 10 ** 5 + 1)
for i in range(0, n):
    if a[n - 1 - i] == c:
        cright[n - 1 - i] = cright[n - i] + 1
    else:
        cright[n - 1 - i] = cright[n - i]
result = cright[0]
cleft = 0
for i in range(0, n):
    if a[i] != c:
        maxfreq[a[i]] = max([maxfreq[a[i]], cleft]) + 1
    else:
        cleft = cleft + 1
    if maxfreq[a[i]] + cright[i + 1] > result:
        result = maxfreq[a[i]] + cright[i + 1]
print(result)

185

n = int(input())
a = list(map(int, input().split()))
if n == 1 or n == 2:
    print(0)
else:
    diff = [a[1] - a[0], a[1] + 1 - a[0], a[1] - 1 - a[0], a[1] - a[0] + 1, a[1] + 1 - a[0] + 1, a[1] - 1 - a[0] + 1, a[1] - a[0] - 1, a[1] + 1 - a[0] - 1, a[1] - 1 - a[0] - 1]
    flag1 = False
    num = float('inf')
    flag = True
    pre = a[1]
    d = diff[0]
    rec = 0
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[1]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[2]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[3]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[4]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[5]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1]
    d = diff[6]
    rec = 1
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] + 1
    d = diff[7]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    flag = True
    pre = a[1] - 1
    d = diff[8]
    rec = 2
    for j in range(2, n):
        if a[j] - pre == d + 1:
            rec += 1
            pre = a[j] - 1
        elif a[j] - pre == d - 1:
            rec += 1
            pre = a[j] + 1
        elif a[j] - pre == d:
            pre = a[j]
        else:
            flag = False
            break
    if flag:
        flag1 = True
        num = min(num, rec)
    if flag1:
        print(num)
    else:
        print(-1)

186

from collections import deque

def BFS(a, vertex=None):
    if vertex is None:
        vertex = 1
    s = [1] * len(a)
    d = deque([vertex])
    s[vertex] = 0
    f = {vertex}
    while len(d) > 0:
        for q in a[d.popleft()]:
            if s[q]:
                d.append(q)
                f.add(q)
                s[q] = 0
    return f

def components(a):
    s = [1] * len(a)
    d, q2 = ([], 1)
    while q2 < len(a):
        if s[q2]:
            if len(a[q2]) == 0:
                s[q2] = 0
                d.append({q2})
            else:
                f = BFS(a, q2)
                d.append(f)
                for q in f:
                    s[q] = 0
        else:
            q2 += 1
    return d
n = int(input())
x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)]
d = [[] for _ in range(n ** 2 + 1)]
for q in range(1, n + 1 - 1):
    for q1 in range(1, n + 1):
        if a[q][q1]:
            if a[q - 1][q1]:
                d[(q - 1) * n + q1].append((q - 2) * n + q1)
            if a[q + 1][q1]:
                d[(q - 1) * n + q1].append(q * n + q1)
            if a[q][q1 - 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1)
            if a[q][q1 + 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1)
x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2)
s = components(d)
comp_x, comp_y = ([], [])
for q in s:
    if x in q:
        comp_x = q
    if y in q:
        comp_y = q
if comp_y == comp_x:
    print(0)
else:
    ans = float('inf')
    for q in comp_x:
        for q1 in comp_y:
            x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1)
            ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans)
    print(ans)

187

import sys
sys.setrecursionlimit(536870912)

def dfs(i, j, vis, g, c):
    vis[i][j] = 1
    c.append((i, j))
    '\n\tif i>0 and \n\t\tif j>0 and vis[i-1][j-1]==0:\n\t\t\tdfs(i-1,j-1,vis,g,c)\n\t\tif j<n-1 and vis[i-1][j+1]==0:\n\t\t\t\tdfs(i-1,j+1,vis,g,c)\n\tif i>0 and j<n-1 and vis[i-1][j+1]==0:\n\t\tdfs(i-1,j+1,vis,g,c)\n\tif i<n-1 and j>0 and vis[i+1][j-1]==0:\n\t\tdfs(i+1,j-1,vis,g,c)\n\tif i<n-1 and j<n-1 and vis[i+1][j+1]==0:\n\t\tdfs(i+1,j+1,vis,g,c)\n\t'
    if i > 0 and vis[i - 1][j] == 0 and (g[i - 1][j] == '0'):
        dfs(i - 1, j, vis, g, c)
    if i < n - 1 and vis[i + 1][j] == 4 and (g[i + 1][j] == '0'):
        dfs(i + 1, j, vis, g, c)
    if j < n - 1 and vis[i][j + 1] == 0 and (g[i][j + 1] == '0'):
        dfs(i, j + 1, vis, g, c)
    if j > 0 and vis[i][j - 1] == 0 and (g[i][j - 1] == '0'):
        dfs(i, j - 1, vis, g, c)
n = int(input())
r1, c1 = map(int, input().split())
r1 -= 1
c1 -= 1
r2, c2 = map(int, input().split())
r2 -= 1
c2 -= 1
g = []
for i in range(n):
    g.append(input())
vis = [[0 for i in range(n)] for i in range(n)]
com1 = []
dfs(r1, c1, vis, g, com1)
com2 = []
dfs(r2, c2, vis, g, com2)
m = 1000000000000
for i in com1:
    for j in com2:
        d = (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2
        m = min(m, d)
print(m)

188

from collections import deque

def BFS(a, vertex=None):
    if vertex is None:
        vertex = 1
    s = [1] * len(a)
    d = deque([vertex])
    s[vertex] = 0
    f = {vertex}
    while len(d) > 0:
        for q in a[d.popleft()]:
            if s[q]:
                d.append(q)
                f.add(q)
                s[q] = 0
    return f

def components(a):
    s = [1] * len(a)
    d, q2 = ([], 1)
    while q2 < len(a):
        if s[q2]:
            if len(a[q2]) == 0:
                s[q2] = 0
                d.append({q2})
            else:
                f = BFS(a, q2)
                d.append(f)
                for q in f:
                    s[q] = 0
        else:
            q2 += 1
    return d
n = int(input())
x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
a = [[0] * (n + 2)] + [[0] + list(map(int, [1 - int(q) for q in list(input())])) + [0] for _ in range(n)] + [[0] * (n + 2)]
d = [[] for _ in range(n ** 2 + 1)]
for q in range(1, n + 1):
    for q1 in range(1, n + 1):
        if a[q][q1]:
            if a[q - 1][q1]:
                d[(q - 1) * n + q1].append((q - 2) * n + q1)
            if a[q + 1][q1]:
                d[(q - 1) * n + q1].append(q * n + q1)
            if a[q][q1 - 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 - 1)
            if a[q][q1 + 1]:
                d[(q - 1) * n + q1].append((q - 1) * n + q1 + 1)
x, y = ((x1 - 1) * n + y1, (x2 - 1) * n + y2)
s = components(d)
comp_x, comp_y = ([], [])
for q in s:
    if x in q:
        comp_x = q
    if y in q:
        comp_y = q
if comp_y == comp_x:
    print(0)
else:
    ans = float('inf')
    for q in comp_x:
        for q1 in comp_y:
            x1, x2, y1, y2 = ((q - 1) // n + 1, (q - 1) % n + 1, (q1 - 1) // n + 1, (q1 - 1) % n + 1)
            ans = min((x1 - y1) ** 2 + (x2 - y2) ** 2, ans)
    print(ans)

189

def cal(x, y):
    d = a[1] + y - a[0] - x
    wk1 = a[1] + y
    wkans = 0
    for k in range(2, n):
        diff = abs(wk1 + d - a[k])
        if diff == 1:
            wkans += 1
        elif diff > 1:
            return n + 1
        wk1 += d
    return wkans
n = int(input())
a = [int(i) for i in input().split()]
if n > 2:
    ans_final = n + 1
    for i in range(-1, 2):
        for j in range(-1, 2):
            ans_final = min(ans_final, cal(i, j) + abs(i) + abs(j))
else:
    ans_final = -1
if ans_final == n + 1:
    print(-1)
else:
    print(ans_final)

190

rr = lambda: input().strip()
rri = lambda: int(rr())
rrm = lambda: list(map(int, rr().split()))
MOD = 10 ** 9 + 3

class DSU:

    def __init__(self, N):
        self.par = list(range(N + 1))
        self.rnk = [0] * (N + 1)
        self.sz = [1] * (N + 1)

    def find(self, x):
        if self.par[x] != x:
            self.par[x] = self.find(self.par[x])
        return self.par[x]

    def union(self, x, y):
        xr, yr = (self.find(x), self.find(y))
        if xr == yr:
            return
        if self.rnk[xr] < self.rnk[yr]:
            xr, yr = (yr, xr)
        if self.rnk[xr] == self.rnk[yr]:
            self.rnk[xr] += 1
        self.par[yr] = xr
        self.sz[xr] += self.sz[yr]

    def size(self, x):
        return self.sz[self.find(x)]

def solve(N, K, edges):
    graph = [[] for _ in range(N)]
    dsu = DSU(N)
    for u, v, w in edges:
        u -= 1
        v -= 1
        if w == 0:
            dsu.union(u, v)
    ans = pow(N, K, MOD)
    for x in range(N):
        if dsu.find(x) == x:
            ans -= pow(dsu.size(x), K, MOD)
            ans %= MOD
    return ans
for tc in range(1):
    N, K = rrm()
    edges = [rrm() for _ in range(N - 1)]
    print(solve(N, K, edges))

191

__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()

192

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()

193

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[-1] -= 0
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [1]
for key, groups in list(groupsList.items()):
    maxDiff = 1
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

194

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')

195

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 < 1 * 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')

196

n = int(input())
r1, c1 = map(int, input().split())
r2, c2 = map(int, input().split())
a = [['1'] * (n + 2)]
for _ in range(n):
    s = input()
    d = ['1']
    for i in s:
        d.append(i)
    d.append('1')
    a.append(d)
a.append(['1'] * (n + 2))
s = []
f = []
q = [[r1, c1]]
while q:
    x, y = q.pop()
    a[x][y] = '1'
    s.append([x, y])
    if a[x - 1 - 1][y] == '0':
        q.append([x - 1, y])
    if a[x][y - 1] == '0':
        q.append([x, y - 1])
    if a[x + 1][y] == '0':
        q.append([x + 1, y])
    if a[x][y + 1] == '0':
        q.append([x, y + 1])
if [r2, c2] in s:
    print(0)
else:
    q = [[r2, c2]]
    while q:
        x, y = q.pop()
        a[x][y] = '1'
        f.append([x, y])
        if a[x - 1][y] == '0':
            q.append([x - 1, y])
        if a[x][y - 1] == '0':
            q.append([x, y - 1])
        if a[x + 1][y] == '0':
            q.append([x + 1, y])
        if a[x][y + 1] == '0':
            q.append([x, y + 1])
    res = 10 ** 10
    for i in s:
        for j in f:
            res = min(res, (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2)
    print(res)

197

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 1
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

198

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[-1] -= 1
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [-1]
for key, groups in list(groupsList.items()):
    maxDiff = 1
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

199

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()

200

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()

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.