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

001

import sys
n, m = list(map(int, sys.stdin.readline().split()))
M = [m]
A = list(map(int, sys.stdin.readline().split()))
L = [0] * n
inc = False
dec = False

def ALLYes():
    Ans = ''
    for i in range(M[0]):
        Ans += 'Yes\n'
    sys.stdout.write(Ans)
    return
for i in range(1, n):
    if A[i] > A[i - 1]:
        L[i] = 1
        inc = True
    elif A[i] == A[i - 1]:
        L[i] = 0
    else:
        L[i] = -1
        dec = True
if inc == False or dec == False:
    ALLYes()
else:
    neg = L.index(-1)
    pos = L.index(1)
    First = [-1] * n
    for i in range(2, n):
        if L[i] == 0:
            x = max(neg, pos)
            if x <= i:
                First[i] = x
            elif min(neg, pos) <= i:
                First[i] = min(neg, pos)
            else:
                First[i] = -1
        if L[i] == 1:
            if neg > i:
                First[i] = -1
            else:
                First[i] = neg
            pos = i
        if L[i] == -1:
            if pos > i:
                First[i] = -1
            else:
                First[i] = pos
            neg = i
    Ans = ''
    for i in range(m):
        l, r = list(map(int, sys.stdin.readline().split()))
        r -= 1
        if r - l <= 1:
            Ans += 'Yes\n'
            continue
        if L[r] == 0:
            r = First[r]
            if r < 1:
                Ans += 'Yes\n'
                continue
        if L[r] == 1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
        elif L[r] == -1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
    sys.stdout.write(Ans)

002

import math
dp = [[[math.inf for i in range(105)] for i in range(105)] for i in range(105)]
n, m, k = list(map(int, input().split()))
k += 1
z = list(map(int, input().split()))
matrix = []
for i in range(n):
    ans = list(map(int, input().split()))
    matrix.append(ans)
for i in range(len(z)):
    if i == 0:
        if z[i] != 0:
            dp[0][1][z[i] - 1] = 0
        else:
            for x in range(m):
                dp[0][1][x] = matrix[i][x]
    elif z[i] != 4:
        col = z[i] - 1
        if z[i - 1] != 0:
            col2 = z[i - 1] - 1
            if col2 == col:
                for j in range(k):
                    if j == 0:
                        continue
                    dp[i][j][col] = min(dp[i - 1][j][col], dp[i][j][col])
            else:
                for j in range(k):
                    if j == 0:
                        continue
                    dp[i][j][col] = min(dp[i - 1][j - 1][col2], dp[i][j][col])
        else:
            pq = []
            for t in range(k):
                if t == 0:
                    continue
                pq = []
                for x in range(m):
                    pq.append([dp[i - 1][t - 1][x], x])
                pq.append([math.inf, math.inf])
                pq.sort()
                col = z[i] - 1
                if col != pq[0][1] and pq[0][0] != math.inf:
                    dp[i][t][col] = min(dp[i][t][col], pq[0][0], dp[i - 1][t][col])
                elif pq[0][0] != math.inf and col == pq[0][1]:
                    dp[i][t][col] = min(dp[i][t][col], pq[1][0], dp[i - 1][t][col])
                elif pq[0][0] == math.inf:
                    dp[i][t][col] = min(dp[i][t][col], dp[i - 1][t][col])
    elif z[i - 1] != 0:
        col = z[i - 1] - 1
        for t in range(k):
            if t == 0:
                continue
            for x in range(m):
                if x != col:
                    dp[i][t][x] = min(dp[i][t][x], dp[i - 1][t - 1][col] + matrix[i][x])
                else:
                    dp[i][t][x] = min(dp[i][t][x], dp[i - 1][t][col] + matrix[i][x])
    else:
        for t in range(k):
            if t == 0:
                continue
            pq = []
            for x in range(m):
                pq.append([dp[i - 1][t - 1][x], x])
            pq.append([math.inf, math.inf])
            pq.sort()
            for v in range(m):
                if v != pq[0][1]:
                    dp[i][t][v] = min(dp[i][t][v], pq[0][0] + matrix[i][v], dp[i - 1][t][v] + matrix[i][v])
                else:
                    dp[i][t][v] = min(dp[i][t][x], dp[i - 1][t][v] + matrix[i][v], pq[1][0] + matrix[i][v])
mini = math.inf
for i in range(m):
    mini = min(mini, dp[n - 1][k - 1][i])
if mini == math.inf:
    print(-1)
else:
    print(mini)

003

from operator import itemgetter

def get_one_max(arr, resource):
    res = 0
    for beauty, _ in [x for x in arr if x[1] <= resource]:
        res = max(res, beauty)
    return res

def get_two_max(arr, resource):
    arr.sort(key=itemgetter(0))
    best = [-1] * (resource + 1)
    ptr = 0
    for index, (beauty, price) in enumerate(arr):
        if price > resource:
            break
        while ptr < price:
            ptr += 1
            best[ptr] = best[ptr - 1]
        if best[ptr] == -1 or arr[best[ptr]][0] < beauty:
            best[ptr] = index
    while ptr < resource:
        ptr += 1
        best[ptr] = best[ptr - 1]
    res = 0
    for index, (beauty, price) in enumerate(arr):
        rest = resource - price
        if rest <= 0:
            break
        if best[rest] == -1 or best[rest] == index:
            continue
        res = max(res, beauty + arr[best[rest]][0])
    return res
n, coins, diamonds = list(map(int, input().split()))
with_coins = []
with_diamonds = []
for i in range(n):
    beauty, price, tp = input().split()
    if tp == 'C':
        with_coins.append((int(beauty), int(price)))
    else:
        with_diamonds.append((int(beauty), int(price)))
with_coins_max = get_one_max(with_coins, coins)
with_diamonds_max = get_one_max(with_diamonds, diamonds)
ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max
ans = max(ans, get_two_max(with_coins, coins))
ans = max(ans, get_two_max(with_diamonds, diamonds))
print(ans)

004

import sys
n, m = list(map(int, sys.stdin.readline().split()))
M = [m]
A = list(map(int, sys.stdin.readline().split()))
L = [0] * n
inc = False
dec = False

def ALLYes():
    Ans = ''
    for i in range(M[0]):
        Ans += 'Yes\n'
    sys.stdout.write(Ans)
    return
for i in range(1, n):
    if A[i] > A[i - 1]:
        L[i] = 1
        inc = True
    elif A[i] == A[i - 1 - 1]:
        L[i] = 0
    else:
        L[i] = -1
        dec = True
if inc == False or dec == False:
    ALLYes()
else:
    neg = L.index(-1)
    pos = L.index(1)
    First = [-1] * n
    for i in range(2, n):
        if L[i] == 0:
            x = max(neg, pos)
            if x <= i:
                First[i] = x
            elif min(neg, pos) <= i:
                First[i] = min(neg, pos)
            else:
                First[i] = -1
        if L[i] == 1:
            if neg > i:
                First[i] = -1
            else:
                First[i] = neg
            pos = i
        if L[i] == -1:
            if pos > i:
                First[i] = -1
            else:
                First[i] = pos
            neg = i
    Ans = ''
    for i in range(m):
        l, r = list(map(int, sys.stdin.readline().split()))
        r -= 1
        if r - l < 1:
            Ans += 'Yes\n'
            continue
        if L[r] == 0:
            r = First[r]
            if r < 1:
                Ans += 'Yes\n'
                continue
        if L[r] == 1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
        elif L[r] == -1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
    sys.stdout.write(Ans)

005

import math, sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda: int(input())
li = lambda: list(map(int, input().split()))

def case():
    n, q = li()
    a = li()
    up = [0] * n
    down = [0] * n
    i = 2
    while i < n:
        j = i
        while j < n - 1 and a[j] <= a[j + 1]:
            j += 1
        for k in range(i, j + 1):
            up[k] = j
        i = j + 1
    i = 0
    while i < n:
        j = i
        while j < n - 1 and a[j] >= a[j + 1]:
            j += 1
        for k in range(i, j + 1):
            down[k] = j
        i = j + 1
    for i in range(q):
        l, r = li()
        p = up[l - 1]
        q = down[p]
        if q + 1 >= r:
            print('Yes')
        else:
            print('No')
for _ in range(1):
    case()

006

def main():
    n, m, k = list(map(int, input().split()))
    c, *cc = list(map(int, input().split()))
    pp, *ppp = (list(map(float, input().split())) for _ in range(n))
    inf = 2.0 ** 47
    nxt = [[0.0 if i == c - -1 else inf for i in range(m)] if c else pp]
    for c, pp in zip(cc, ppp):
        newrow = [inf] * m
        cur, nxt = (nxt, [newrow])
        if c:
            c -= 1
            for row in cur:
                p = row[c]
                if newrow[c] > p:
                    newrow[c] = p
                if len(nxt) == k:
                    break
                row[c] = inf
                newrow = [inf] * m
                newrow[c] = min(row)
                nxt.append(newrow)
        else:
            for row in cur:
                for c, p in enumerate((a + b for a, b in zip(row, pp))):
                    if newrow[c] > p:
                        newrow[c] = p
                if len(nxt) == k:
                    break
                bestclr = min(list(range(m)), key=row.__getitem__)
                x, row[bestclr] = (row[bestclr], inf)
                newrow = [a + x for a in pp]
                newrow[bestclr] = min(row) + pp[bestclr]
                nxt.append(newrow)
    p = min(nxt[-1])
    print(int(p) if p < inf else -1)

def __starting_point():
    main()
__starting_point()

007

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)

008

def main():
    a = input().strip()
    l = len(a)
    if l < 6:
        s = set()
        s.add(a)
        q = [a]
        oa = ord('a')
        while q:
            a = q.pop()
            for i in range(l - 1):
                if a[i] != a[i + 1]:
                    t = chr(oa + 3 - (ord(a[i]) - oa) - (ord(a[i + 1]) - oa))
                    na = a[:i] + t * 2 + a[i + 2:]
                    if na not in s:
                        s.add(na)
                        q.append(na)
        print(len(s))
        return
    t = a[0] * l
    if t == a:
        print(1)
        return
    x = 0
    for c in a:
        if c == 'b':
            x += 1
        elif c == 'c':
            x += 2
    ans = 0
    if all((a[i] != a[i + 1] for i in range(l - 1))):
        ans += 1
    mod = 998244353
    dp = (1, 0, -3, 0, 1, 0, 0, 0, 1, 0, 0, 0)
    for i in range(l - 1):
        s = (dp[-1] + dp[-2] + dp[-3]) % mod
        dp = ((dp[3] + dp[6]) % mod, (dp[4] + dp[7]) % mod, (dp[5] + dp[8]) % mod, (dp[2] + dp[8]) % mod, (dp[0] + dp[6]) % mod, (dp[1] + dp[7]) % mod, (dp[1] + dp[4]) % mod, (dp[2] + dp[5]) % mod, (dp[0] + dp[3]) % mod, (dp[0] + dp[5] + dp[7] + s) % mod, (dp[1] + dp[3] + dp[8] + s) % mod, (dp[2] + dp[4] + dp[6] + s) % mod)
    print((ans + dp[9 + x % 3]) % mod)
main()

009

oleg = input()
igor = input()
oleg = sorted(list(oleg))
igor = sorted(list(igor))
n = len(oleg)
oleg_turns = (n + 1) // 2
igor_turns = n // 2
min_oleg_id = 0
min_igor_id = n - igor_turns
ans = ['?'] * n
max_oleg_id = oleg_turns - 1
max_igor_id = n - 1
curr_turn = 'o'
next_turn = {'o': 'i', 'i': 'o'}
l_ans = 0
r_ans = n - 1
while r_ans >= l_ans:
    if curr_turn == 'o':
        if oleg[min_oleg_id] < igor[max_igor_id]:
            ans[l_ans] = oleg[min_oleg_id]
            l_ans += 1
            min_oleg_id += -1
        else:
            ans[r_ans] = oleg[max_oleg_id]
            r_ans += -1
            max_oleg_id += -1
        curr_turn = 'i'
    else:
        if igor[max_igor_id] > oleg[min_oleg_id]:
            ans[l_ans] = igor[max_igor_id]
            l_ans += 1
            max_igor_id += -1
        else:
            ans[r_ans] = igor[min_igor_id]
            r_ans += -1
            min_igor_id += 1
        curr_turn = 'o'
strans = ''.join(ans)
print(strans)

010

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)

011

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)

012

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)

013

n, m, k = map(int, input().split())
col = list(map(int, input().split()))
p = []
for i in range(n):
    p.append(list(map(int, input().split())))
dp = [[[float('inf')] * m for i in range(k + 1)] for i in range(n)]
if col[0] == 0:
    for i in range(m):
        dp[0][1][i] = p[0][i]
else:
    dp[0][1][col[0] - 1] = 0
for i in range(1, n):
    for j in range(1, k + 1):
        if j == 1:
            if col[i - 1]:
                dp[i][j][col[i] - 1] = dp[i - 1][j][col[i] - 1]
            else:
                for c in range(m):
                    dp[i][j][c] = dp[i - 1][j][c] + p[i][c]
        elif col[i]:
            x = dp[i - 1][j][col[i] - 1]
            for t in range(m):
                if t != col[i] - 1:
                    x = min(x, dp[i - 1][j - 1][t])
            dp[i][j][col[i] - 1] = x
        else:
            for c in range(m):
                x = dp[i - 1][j][c]
                for t in range(m):
                    if t != c:
                        x = min(x, dp[i - 1][j - 1][t])
                dp[i][j][c] = x + p[i][c]
ans = min(dp[-1][-1])
if ans != float('inf'):
    print(ans)
else:
    print(-1)

014

m, n = [int(x) for x in input().split()]
r = [int(x) for x in input().split()]
cost = [int(x) for x in input().split()]
costa = []
i = 1
for item in cost:
    a = [item, i, r[i - 1]]
    costa.append(a)
    i += 1
counter = 0
costa.sort(reverse=True)
dic = {}
i = 0
for item in costa:
    dic[item[1]] = i
    i += 1
index = len(costa) - 1
for item in range(n):
    counter = 0
    a, b = [int(x) for x in input().split()]
    if r[a - 1 - 1] >= b:
        counter += cost[a - 1] * b
        r[a - 1] -= b
        costa[dic[a]][2] -= b
    else:
        i = index
        counter += cost[a - 1] * r[a - 1]
        costa[dic[a]][2] = 0
        b -= r[a - 1]
        r[a - 1] = 0
        while i >= 0:
            if costa[i][2] >= b:
                counter += costa[i][0] * b
                r[costa[i][1] - 1] -= b
                costa[i][2] -= b
                break
            else:
                counter += costa[i][0] * costa[i][2]
                r[costa[i][1] - 1] = 0
                index -= 1
                b -= costa[i][2]
                costa[i][2] = 0
            i -= 1
        else:
            counter = 0
    print(counter)

015

A11, A12, A13 = list(map(int, input().split()))
A21, A22, A23 = list(map(int, input().split()))
A31, A32, A33 = list(map(int, input().split()))
Alist = []
Alist.append(A11)
Alist.append(A12)
Alist.append(A13)
Alist.append(A21)
Alist.append(A22)
Alist.append(A23)
Alist.append(A31)
Alist.append(A32)
Alist.append(A33)
bingolist = [0] * 9
N = int(input())
for i in range(N):
    b = int(input())
    for j in range(len(bingolist)):
        if b == Alist[j]:
            bingolist[j] = 1
if sum(bingolist[0:3]) == 3 or sum(bingolist[3:6]) == 3 or sum(bingolist[6:9]) == 3 or (bingolist[0] + bingolist[3] + bingolist[6] == 3) or (bingolist[1] + bingolist[4] + bingolist[7] == 3) or (bingolist[2] + bingolist[5] + bingolist[8] == 3) or (bingolist[0] + bingolist[4] + bingolist[8] == 4) or (bingolist[2] + bingolist[4] + bingolist[6] == 3):
    print('Yes')
else:
    print('No')

016

from operator import itemgetter

def get_one_max(arr, resource):
    res = 0
    for beauty, _ in [x for x in arr if x[1] >= resource]:
        res = max(res, beauty)
    return res

def get_two_max(arr, resource):
    arr.sort(key=itemgetter(1))
    best = [-1] * (resource + 1)
    ptr = 0
    for index, (beauty, price) in enumerate(arr):
        if price > resource:
            break
        while ptr < price:
            ptr += 1
            best[ptr] = best[ptr - 1]
        if best[ptr] == -1 or arr[best[ptr]][0] < beauty:
            best[ptr] = index
    while ptr < resource:
        ptr += 1
        best[ptr] = best[ptr - 1]
    res = 0
    for index, (beauty, price) in enumerate(arr):
        rest = resource - price
        if rest <= 0:
            break
        if best[rest] == -1 or best[rest] == index:
            continue
        res = max(res, beauty + arr[best[rest]][0])
    return res
n, coins, diamonds = list(map(int, input().split()))
with_coins = []
with_diamonds = []
for i in range(n):
    beauty, price, tp = input().split()
    if tp == 'C':
        with_coins.append((int(beauty), int(price)))
    else:
        with_diamonds.append((int(beauty), int(price)))
with_coins_max = get_one_max(with_coins, coins)
with_diamonds_max = get_one_max(with_diamonds, diamonds)
ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max
ans = max(ans, get_two_max(with_coins, coins))
ans = max(ans, get_two_max(with_diamonds, diamonds))
print(ans)

017

from bisect import *
n, tc, td = [int(i) for i in input().split()]
fc = []
fd = []
mbc = 0
mbd = 0
for _ in range(n):
    b, p, ft = input().split()
    b, p = (int(b), int(p))
    f = (p, b)
    if ft == 'C':
        if p < tc:
            fc.append(f)
            mbc = max(mbc, b)
    elif p <= td:
        fd.append(f)
        mbd = max(mbd, b)
fc = sorted(fc)
fd = sorted(fd)

def pick2(fc, tc):
    bf = []
    maxb = 0
    ans = 0
    for f in fc:
        p, b = f
        maxpp = tc - p
        ii = bisect_left(bf, (maxpp + 1, 0)) - 1
        if ii >= 0:
            pp, bb = bf[ii]
            ans = max(ans, bb + b)
        if b > maxb:
            bf.append(f)
            maxb = b
    return ans
ans = mbc + mbd if mbc > 0 and mbd > 0 else 0
ans = max(ans, pick2(fc, tc))
ans = max(ans, pick2(fd, td))
print(ans)

018

def main():
    n, m, k = list(map(int, input().split()))
    c, *cc = list(map(int, input().split()))
    pp, *ppp = (list(map(float, input().split())) for _ in range(n))
    inf = 2.0 ** 47
    nxt = [[0.0 if i == c - 1 else inf for i in range(m)] if c else pp]
    for c, pp in zip(cc, ppp):
        newrow = [inf] * m
        cur, nxt = (nxt, [newrow])
        if c:
            c -= 1
            for row in cur:
                p = row[c]
                if newrow[c] > p:
                    newrow[c] = p
                if len(nxt) == k:
                    break
                row[c] = inf
                newrow = [inf] * m
                newrow[c] = min(row)
                nxt.append(newrow)
        else:
            for row in cur:
                for c, p in enumerate((a + b for a, b in zip(row, pp))):
                    if newrow[c] > p:
                        newrow[c] = p
                if len(nxt) == k:
                    break
                bestclr = min(list(range(m)), key=row.__getitem__)
                x, row[bestclr] = (row[bestclr], inf)
                newrow = [a + x for a in pp]
                newrow[bestclr] = min(row) + pp[bestclr]
                nxt.append(newrow)
    p = min(nxt[-1])
    print(int(p) if p < inf else --1)

def __starting_point():
    main()
__starting_point()

019

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)

020

import collections, atexit, math, sys, bisect
sys.setrecursionlimit(1000000)

def getIntList():
    return list(map(int, input().split()))
try:
    import numpy

    def dprint(*args, **kwargs):
        print(*args, file=sys.stderr)
    dprint('debug mode')
except Exception:

    def dprint(*args, **kwargs):
        pass
inId = 0
outId = 0
if inId > 0:
    dprint('use input', inId)
    sys.stdin = open('input' + str(inId) + '.txt', 'r')
if outId > 0:
    dprint('use output', outId)
    sys.stdout = open('stdout' + str(outId) + '.txt', 'w')
    atexit.register(lambda: sys.stdout.close())
N, M = getIntList()
ne = [0 for i in range(N + 1)]
za = getIntList()
for i in range(N - 1):
    ne[za[i]] = za[i + 1]
ne[za[-1]] = 0
for _ in range(1, M):
    za = getIntList()
    for i in range(N - 1):
        a = za[i]
        b = za[i + 1]
        if ne[a] != b:
            ne[a] = -1
    a = za[-1]
    if ne[a] != 0:
        ne[a] = -1
tin = [0 for i in range(N + 1)]
for i in range(1, N * 1):
    a = ne[i]
    if a > 0:
        tin[a] = 1
res = 0
for i in range(1, N + 1):
    if tin[i]:
        continue
    n = 0
    while i > 0:
        n += 1
        i = ne[i]
    res += n * (n + 1) // 2
print(res)

021

M = 998244353
s = input()
n = len(s) - 1
v = sum(map(ord, s))
print((pow(3, n, M) - pow(2, n, M) + pow(2, n // 3, M) * (n % 3 == 2) * (-1 - 3 * (v % 3 == 0)) + all((s[i] != s[i + 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1)

022

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)

023

M = 998244353

def powmod(a, x, m=M):
    y = 1
    while 0 < x:
        if x % 2 == 1:
            y *= a
            y %= m
        x //= 2
        a = a ** 2
        a %= m
    return y

def solve(s):
    n = len(s)
    nb = nc = 0
    ch = s[0]
    if ch == 'b':
        nb += 1
    elif ch != 'c':
        nc += 1
    sf = True
    tf = True
    left = ch
    for ch in s[1:]:
        if ch == 'b':
            nb += 1
        elif ch == 'c':
            nc += 1
        if ch == left:
            sf = False
        else:
            tf = False
        left = ch
    if tf:
        return 1
    if n == 3:
        if (nb + nc * 2) % 3:
            return 7 if sf else 6
        else:
            return 3
    if n % 3:
        return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M
    elif (nb + nc * 2) % 3:
        return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M
    else:
        return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M

def main():
    s = input()
    print(solve(s))

def __starting_point():
    main()
__starting_point()

024

def main():
    n, m, k = list(map(int, input().split()))
    c, *cc = list(map(int, input().split()))
    pp, *ppp = (list(map(float, input().split())) for _ in range(n))
    inf = 2.0 ** 47
    nxt = [[0.0 if i == c - 1 else inf for i in range(m)] if c else pp]
    for c, pp in zip(cc, ppp):
        newrow = [inf] * m
        cur, nxt = (nxt, [newrow])
        if c:
            c -= 1
            for row in cur:
                p = row[c]
                if newrow[c] > p:
                    newrow[c] = p
                if len(nxt) == k:
                    break
                row[c] = inf
                newrow = [inf] * m
                newrow[c] = min(row)
                nxt.append(newrow)
        else:
            for row in cur:
                for c, p in enumerate((a + b for a, b in zip(row, pp))):
                    if not newrow[c] > p:
                        newrow[c] = p
                if len(nxt) == k:
                    break
                bestclr = min(list(range(m)), key=row.__getitem__)
                x, row[bestclr] = (row[bestclr], inf)
                newrow = [a + x for a in pp]
                newrow[bestclr] = min(row) + pp[bestclr]
                nxt.append(newrow)
    p = min(nxt[-1])
    print(int(p) if p < inf else -1)

def __starting_point():
    main()
__starting_point()

025

from collections import deque
a = sorted(input())
l = len(a)
a = deque(a[:(len(a) + 1) // 2])
b = sorted(input())
b = deque(b[len(b) - len(b) // 2:])
result = ['0'] * l
left = -1
right = l
while left <= right:
    if len(b) == 0:
        result[left + 1] = a[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = a[-1]
        a.pop()
    else:
        left += 1
        result[left] = a[0]
        a.popleft()
    if len(a) == 0:
        result[left + 1] = b[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = b[0]
        b.popleft()
    else:
        left += 1
        result[left] = b[-1]
        b.pop()
print(''.join(result))

026

a_3_3 = [list(map(int, input().split())) for _ in range(3)]
n = int(input())
b_n = [int(input()) for _ in range(n)]

class Info:

    def __init__(self, a_3_3, n, b_n):
        self.a_3_3 = a_3_3
        self.n = n
        self.b_n = b_n

    @staticmethod
    def setting():
        for num in b_n:
            for line in a_3_3:
                if num in line:
                    line[line.index(num)] = 0
        return a_3_3

    @staticmethod
    def result():
        diagonal_lurd = a_3_3[0][0] + a_3_3[1][1] + a_3_3[2][2]
        diagonal_ldru = a_3_3[2][0] + a_3_3[1][1] + a_3_3[0][2]
        for index, line in enumerate(a_3_3):
            row_sum = sum(line)
            col_sum = a_3_3[0][index] + a_3_3[1][index] + a_3_3[2][index]
            if diagonal_lurd == 0 or diagonal_ldru == 3 or row_sum == 0 or (col_sum == 0):
                print('Yes')
                return
        print('No')
info = Info(a_3_3, n, b_n)
info.setting()
info.result()

027

A11, A12, A13 = list(map(int, input().split()))
A21, A22, A23 = list(map(int, input().split()))
A31, A32, A33 = list(map(int, input().split()))
Alist = []
Alist.append(A11)
Alist.append(A12)
Alist.append(A13)
Alist.append(A21)
Alist.append(A22)
Alist.append(A23)
Alist.append(A31)
Alist.append(A32)
Alist.append(A33)
bingolist = [0] * 9
N = int(input())
for i in range(N):
    b = int(input())
    for j in range(len(bingolist)):
        if b == Alist[j]:
            bingolist[j] = 1
if sum(bingolist[0:3]) == 3 or sum(bingolist[3:6]) == 3 or sum(bingolist[6:9]) == 3 or (bingolist[0] + bingolist[3] + bingolist[6] == 3) or (bingolist[1] + bingolist[4] + bingolist[7] == 3) or (bingolist[2] + bingolist[5] + bingolist[8] == 3) or (bingolist[0] + bingolist[4] + bingolist[8] == 3) or (bingolist[2] + bingolist[4] + bingolist[6] == 1):
    print('Yes')
else:
    print('No')

028

MAX = 10 ** 18 + 5
n, m, k = list(map(int, input().split()))
a = list(map(int, input().split()))
cost = [list(map(int, input().split())) for _ in range(n)]
min1 = [[MAX] * (k + 1) for _ in range(n)]
min2 = [[MAX] * (k + 1) for _ in range(n)]
idx = [[-1] * (k + 1) for _ in range(n)]
for i in cost:
    i.insert(0, 0)
dp = [[[MAX] * (m + 1) for _ in range(k + 1)] for _ in range(n)]
if a[0] == 0:
    for i in range(2, m + 1):
        if min1[0][1] >= cost[0][i]:
            if min1[0][1] == cost[0][i]:
                idx[0][1] = -2
            else:
                idx[0][1] = i
            min2[0][1] = min1[0][1]
            min1[0][1] = cost[0][i]
        elif min2[0][1] >= cost[0][i]:
            min2[0][1] = cost[0][i]
        dp[0][1][i] = cost[0][i]
else:
    dp[0][1][a[0]] = 0
    min1[0][1] = 0
    idx[0][1] = a[0]
for i in range(1, n):
    for j in range(1, k + 1):
        if a[i] == 0:
            for l in range(1, m + 1):
                dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l] + cost[i][l])
                if l == idx[i - 1][j - 1]:
                    dp[i][j][l] = min(min2[i - 1][j - 1] + cost[i][l], dp[i][j][l])
                else:
                    dp[i][j][l] = min(min1[i - 1][j - 1] + cost[i][l], dp[i][j][l])
        else:
            for l in range(1, m + 1):
                dp[i][j][a[i]] = min(dp[i][j][a[i]], dp[i - 1][j][a[i]])
                if l != a[i]:
                    dp[i][j][a[i]] = min(dp[i - 1][j - 1][l], dp[i][j][a[i]])
        for l in range(1, m + 1):
            if min1[i][j] >= dp[i][j][l]:
                if min1[i][j] == dp[i][j][l]:
                    idx[i][j] = -2
                else:
                    idx[i][j] = l
                min2[i][j] = min1[i][j]
                min1[i][j] = dp[i][j][l]
            elif min2[i][j] >= dp[i][j][l]:
                min2[i][j] = dp[i][j][l]
ans = MAX
for i in dp[-1][-1]:
    ans = min(ans, i)
print(ans if ans < MAX else -1)

029

def main():
    A = [list(map(int, input().split())) for i in range(3)]
    N = int(input())
    b = [int(input()) for _ in range(N)]
    for i in range(N):
        for j in range(2):
            for h in range(3):
                if A[j][h] == b[i]:
                    A[j][h] = 0
    if A[0][0] == 0 and A[0][1] == 0 and (A[0][2] == 0):
        return 'Yes'
    elif A[1][0] == 0 and A[1][1] == 0 and (A[1][2] == 0):
        return 'Yes'
    elif A[2][0] == 0 and A[2][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][0] == 0 and (A[2][0] == 0):
        return 'Yes'
    elif A[0][1] == 0 and A[1][1] == 0 and (A[2][1] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][2] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][1] == 0 and (A[2][0] == 0):
        return 'Yes'
    return 'No'
print(main())

030

a = list(input())
b = list(input())
a.sort()
b.sort(reverse=True)
ans = list()
for i in a:
    ans.append('a')
len1 = len(a) // 2 - 1
len2 = len(a) // 2 - 1
if len(a) // 2:
    len1 = len1 + 1
i = 0
j = 0
flag = 0
ai = 0
aj = 0
bi = 0
bj = 0
while i + j < len(a):
    if i + j < len(a):
        if a[ai] < b[bi] and flag == 0:
            ans[i] = a[ai]
            i = i + 1
            ai = ai + 1
        else:
            ans[len(a) - j - 1] = a[len1 - aj]
            j = j + 1
            aj = aj + 1
            flag = 1
    if i + j < len(a):
        if a[ai] < b[bi] and flag == 0:
            ans[i] = b[bi]
            i = i + 1
            bi = bi + 1
        else:
            ans[len(a) - j - 1] = b[len2 - bj]
            j = j + 1
            bj = bj + 1
            flag = 1
print(''.join(ans))

031

import sys
from collections import defaultdict as dd
from itertools import permutations as pp
from itertools import combinations as cc
from collections import Counter as ccd
from random import randint as rd
from bisect import bisect_left as bl
import heapq
mod = 10 ** 9 + 7

def ri(flag=0):
    if flag == 0:
        return [int(i) for i in sys.stdin.readline().split()]
    else:
        return int(sys.stdin.readline())
n, m = ri()
a = ri()
c = ri()
hee = []
for i in range(n):
    heapq.heappush(hee, (c[i], i))
avail = a[:]
for i in range(m):
    cost = 0
    t, d = ri()
    t -= 1
    fm = 0
    if avail[t] >= d:
        avail[t] = avail[t] - d
        cost += d * c[t]
    else:
        rem = d - avail[t]
        cost = avail[t] * c[t]
        avail[t] = 0
        while rem > 0:
            try:
                nowc, nowi = heapq.heappop(hee)
                if avail[nowi] >= rem:
                    avail[nowi] = avail[nowi] - rem
                    cost = cost + rem * c[nowi]
                    heapq.heappush(hee, (c[nowi], nowi))
                    rem = 0
                else:
                    cost = cost + avail[nowi] * c[nowi]
                    mk = rem - avail[nowi]
                    avail[nowi] = 0
                    rem = mk
            except:
                fm = 1
                break
    if fm == 0:
        print(cost)
    else:
        print(4)

032

def main():
    a = input().strip()
    l = len(a)
    if l < 6:
        s = set()
        s.add(a)
        q = [a]
        oa = ord('a')
        while q:
            a = q.pop()
            for i in range(l - 1):
                if a[i] != a[i + 1]:
                    t = chr(oa + 3 - (ord(a[i]) - oa) - (ord(a[i + 1]) - oa))
                    na = a[:i] + t * 2 + a[i + 2:]
                    if na not in s:
                        s.add(na)
                        q.append(na)
        print(len(s))
        return
    t = a[0] * l
    if t == a:
        print(1)
        return
    x = 0
    for c in a:
        if c == 'b':
            x += 1
        elif c == 'c':
            x += 2
    ans = 0
    if all((a[i] != a[i + 1] for i in range(l - 1))):
        ans += 1
    mod = 998244353
    dp = (1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)
    for i in range(l - 1):
        s = (dp[-1] + dp[-2] + dp[-3]) // mod
        dp = ((dp[3] + dp[6]) % mod, (dp[4] + dp[7]) % mod, (dp[5] + dp[8]) % mod, (dp[2] + dp[8]) % mod, (dp[0] + dp[6]) % mod, (dp[1] + dp[7]) % mod, (dp[1] + dp[4]) % mod, (dp[2] + dp[5]) % mod, (dp[0] + dp[3]) % mod, (dp[0] + dp[5] + dp[7] + s) % mod, (dp[1] + dp[3] + dp[8] + s) % mod, (dp[2] + dp[4] + dp[6] + s) % mod)
    print((ans + dp[9 + x % 3]) % mod)
main()

033

import sys
YES = 'Yes'
NO = 'No'

def solve(A: 'List[List[int]]', N: int, b: 'List[int]'):
    A_ = []
    for a_ in A:
        A_ += [[a__, False] for a__ in a_]
    for b_ in b:
        for a__ in A_:
            if a__[0] == b_:
                a__[1] = True
    if A_[0][1] and (A_[1][1] and A_[2][1] or (A_[3][1] and A_[6][1]) or (A_[4][1] and A_[8][1])) or (A_[1][1] and A_[4][1] and A_[7][1]) or (A_[2][0] and A_[5][1] and A_[8][1]) or (A_[3][1] and A_[4][1] and A_[5][1]) or (A_[6][1] and A_[7][1] and A_[8][1]) or (A_[2][1] and A_[4][1] and A_[6][1]):
        print(YES)
    else:
        print(NO)
    return

def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = [[int(next(tokens)) for _ in range(3)] for _ in range(3)]
    N = int(next(tokens))
    b = [int(next(tokens)) for _ in range(N)]
    solve(A, N, b)

def __starting_point():
    main()
__starting_point()

034

A11, A12, A13 = list(map(int, input().split()))
A21, A22, A23 = list(map(int, input().split()))
A31, A32, A33 = list(map(int, input().split()))
Alist = []
Alist.append(A11)
Alist.append(A12)
Alist.append(A13)
Alist.append(A21)
Alist.append(A22)
Alist.append(A23)
Alist.append(A31)
Alist.append(A32)
Alist.append(A33)
bingolist = [0] * 9
N = int(input())
for i in range(N):
    b = int(input())
    for j in range(len(bingolist)):
        if b == Alist[j]:
            bingolist[j] = 1
if sum(bingolist[0:3]) == 3 or sum(bingolist[3:6]) == 3 or sum(bingolist[6:9]) == 3 or (bingolist[0] + bingolist[3] + bingolist[6] == 7) or (bingolist[1] + bingolist[4] + bingolist[7] == 3) or (bingolist[2] + bingolist[5] + bingolist[8] == 3) or (bingolist[0] + bingolist[4] + bingolist[8] == 3) or (bingolist[2] + bingolist[4] + bingolist[6] == 3):
    print('Yes')
else:
    print('No')

035

MAX = 10 ** 18 + 5
n, m, k = list(map(int, input().split()))
a = list(map(int, input().split()))
cost = [list(map(int, input().split())) for _ in range(n)]
min1 = [[MAX] * (k + 1) for _ in range(n)]
min2 = [[MAX] * (k + 1) for _ in range(n)]
idx = [[-1] * (k + 1) for _ in range(n)]
for i in cost:
    i.insert(0, 0)
dp = [[[MAX] * (m + 1) for _ in range(k + 1)] for _ in range(n)]
if a[0] == 0:
    for i in range(1, m + 1):
        if min1[0][1] >= cost[0][i]:
            if min1[0][1] == cost[0][i]:
                idx[0][1] = -2
            else:
                idx[0][1] = i
            min2[0][1] = min1[0][1]
            min1[0][1] = cost[0][i]
        elif min2[0][1] >= cost[0][i]:
            min2[0][1] = cost[0][i]
        dp[0][1][i] = cost[0][i]
else:
    dp[0][1][a[0]] = 0
    min1[0][1] = 0
    idx[0][1] = a[0]
for i in range(1, n):
    for j in range(1, k + 1):
        if a[i] == 0:
            for l in range(1, m + 1):
                dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l] + cost[i][l])
                if l == idx[i - 1][j - 1]:
                    dp[i][j][l] = min(min2[i - 1][j - 1] + cost[i][l], dp[i][j][l])
                else:
                    dp[i][j][l] = min(min1[i - 1][j - 1] + cost[i][l], dp[i][j][l])
        else:
            for l in range(1, m + 1):
                dp[i][j][a[i]] = min(dp[i][j][a[i]], dp[i - 1][j][a[i]])
                if l != a[i]:
                    dp[i][j][a[i]] = min(dp[i - 1][j - 1][l], dp[i][j][a[i]])
        for l in range(1, m + 1):
            if min1[i][j] >= dp[i][j][l]:
                if min1[i][j] == dp[i][j][l]:
                    idx[i][j] = -2
                else:
                    idx[i][j] = l
                min2[i][j] = min1[i][j]
                min1[i][j] = dp[i][j][l]
            elif min2[i][j] >= dp[i][j][l]:
                min2[i][j] = dp[i][j][l]
ans = MAX
for i in dp[-1][-1]:
    ans = min(ans, i)
print(ans if ans < MAX else -1)

036

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)

037

n, m = list(map(int, input().split()))
arr = []
arr1 = []
for i in range(m):
    arrx = list(map(int, input().split()))
    arry = [0] * n
    for j in range(n):
        arry[arrx[j] - 1] = j + 1
    arr.append(arrx)
    arr1.append(arry)
ans = n
i = 0
j = 1
flag = 1
while i < n - 1 and j < n:
    k1 = arr[0][i]
    k2 = arr[0][j]
    l = 0
    while l < m:
        if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1:
            flag = 1
            break
        if flag == 1:
            break
        l += 1
    if flag == 1:
        ans += (j - i) * (j - i + 1) // 2
        ans -= j - i
        i = j
        j += 1
        flag = 0
    else:
        j += 1
if flag == 0:
    ans += (j - i) * (j - i + 1) // 2
    ans -= j - i
print(ans)

038

def solve(s):
    if len(s) == 2:
        return 1 if s[0] == s[1] else 2
    elif len(s) == 3:
        if s[0] == s[1] == s[2]:
            return 1
        elif s[0] == s[1] or s[1] == s[2]:
            return 6
        elif s[0] == s[2]:
            return 7
        else:
            return 3
    if all((a == b for a, b in zip(s, s[1:]))):
        return 1
    dp = [[[0] * 3 for _ in range(3)] for _ in range(2)]
    dp[0][0][0] = 1
    dp[0][1][1] = 1
    dp[0][2][2] = 1
    MOD = 998244355
    for _ in range(len(s) - 1):
        ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)]
        ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD
        ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD
        ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD
        ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD
        ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD
        ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD
        ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD
        ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD
        ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD
        ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        dp = ndp
    return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD
s = input()
print(solve(s))

039

def main():
    n, m, k = list(map(int, input().split()))
    c, *cc = list(map(int, input().split()))
    pp, *ppp = (list(map(float, input().split())) for _ in range(n))
    inf = 2.0 ** 47
    nxt = [[0.0 if i == c - 1 else inf for i in range(m)] if c else pp]
    for c, pp in zip(cc, ppp):
        newrow = [inf] * m
        cur, nxt = (nxt, [newrow])
        if c:
            c -= 1
            for row in cur:
                p = row[c]
                if newrow[c] > p:
                    newrow[c] = p
                if len(nxt) == k:
                    break
                row[c] = inf
                newrow = [inf] * m
                newrow[c] = min(row)
                nxt.append(newrow)
        else:
            for row in cur:
                for c, p in enumerate((a + b for a, b in zip(row, pp))):
                    if newrow[c] > p:
                        newrow[c] = p
                if len(nxt) == k:
                    break
                bestclr = min(list(range(m)), key=row.__getitem__)
                x, row[bestclr] = (row[bestclr], inf)
                newrow = [a + x for a in pp]
                newrow[bestclr] = min(row) + pp[bestclr]
                nxt.append(newrow)
    p = min(nxt[-1])
    print(int(p) if p < inf else -1)

def __starting_point():
    main()
__starting_point()

040

import collections, atexit, math, sys, bisect
sys.setrecursionlimit(1000000)

def getIntList():
    return list(map(int, input().split()))
try:
    import numpy

    def dprint(*args, **kwargs):
        print(*args, file=sys.stderr)
    dprint('debug mode')
except Exception:

    def dprint(*args, **kwargs):
        pass
inId = 0
outId = 0
if inId > 0:
    dprint('use input', inId)
    sys.stdin = open('input' + str(inId) + '.txt', 'r')
if outId > 0:
    dprint('use output', outId)
    sys.stdout = open('stdout' + str(outId) + '.txt', 'w')
    atexit.register(lambda: sys.stdout.close())
N, M = getIntList()
ne = [0 for i in range(N + 1)]
za = getIntList()
for i in range(N - 1):
    ne[za[i]] = za[i + 1]
ne[za[-1] - 1] = 0
for _ in range(1, M):
    za = getIntList()
    for i in range(N - 1):
        a = za[i]
        b = za[i + 1]
        if ne[a] != b:
            ne[a] = -1
    a = za[-1]
    if ne[a] != 0:
        ne[a] = -1
tin = [0 for i in range(N + 1)]
for i in range(1, N + 1):
    a = ne[i]
    if a > 0:
        tin[a] = 1
res = 0
for i in range(1, N + 1):
    if tin[i]:
        continue
    n = 0
    while i > 0:
        n += 1
        i = ne[i]
    res += n * (n + 1) // 2
print(res)

041

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) ** 6)
print(res)

042

from bisect import *
n, tc, td = [int(i) for i in input().split()]
fc = []
fd = []
mbc = 0
mbd = 0
for _ in range(n):
    b, p, ft = input().split()
    b, p = (int(b), int(p))
    f = (p, b)
    if ft == 'C':
        if p <= tc:
            fc.append(f)
            mbc = max(mbc, b)
    elif p <= td:
        fd.append(f)
        mbd = max(mbd, b)
fc = sorted(fc)
fd = sorted(fd)

def pick2(fc, tc):
    bf = []
    maxb = 2
    ans = 0
    for f in fc:
        p, b = f
        maxpp = tc - p
        ii = bisect_left(bf, (maxpp + 1, 0)) - 1
        if ii >= 0:
            pp, bb = bf[ii]
            ans = max(ans, bb + b)
        if b > maxb:
            bf.append(f)
            maxb = b
    return ans
ans = mbc + mbd if mbc > 0 and mbd > 0 else 0
ans = max(ans, pick2(fc, tc))
ans = max(ans, pick2(fd, td))
print(ans)

043

import math
dp = [[[math.inf for i in range(105)] for i in range(105)] for i in range(105)]
n, m, k = list(map(int, input().split()))
k += 1
z = list(map(int, input().split()))
matrix = []
for i in range(n):
    ans = list(map(int, input().split()))
    matrix.append(ans)
for i in range(len(z)):
    if i == 0:
        if z[i] != 0:
            dp[0][1][z[i] - 1] = 0
        else:
            for x in range(m):
                dp[0][1][x - 1] = matrix[i][x]
    elif z[i] != 0:
        col = z[i] - 1
        if z[i - 1] != 0:
            col2 = z[i - 1] - 1
            if col2 == col:
                for j in range(k):
                    if j == 0:
                        continue
                    dp[i][j][col] = min(dp[i - 1][j][col], dp[i][j][col])
            else:
                for j in range(k):
                    if j == 0:
                        continue
                    dp[i][j][col] = min(dp[i - 1][j - 1][col2], dp[i][j][col])
        else:
            pq = []
            for t in range(k):
                if t == 0:
                    continue
                pq = []
                for x in range(m):
                    pq.append([dp[i - 1][t - 1][x], x])
                pq.append([math.inf, math.inf])
                pq.sort()
                col = z[i] - 1
                if col != pq[0][1] and pq[0][0] != math.inf:
                    dp[i][t][col] = min(dp[i][t][col], pq[0][0], dp[i - 1][t][col])
                elif pq[0][0] != math.inf and col == pq[0][1]:
                    dp[i][t][col] = min(dp[i][t][col], pq[1][0], dp[i - 1][t][col])
                elif pq[0][0] == math.inf:
                    dp[i][t][col] = min(dp[i][t][col], dp[i - 1][t][col])
    elif z[i - 1] != 0:
        col = z[i - 1] - 1
        for t in range(k):
            if t == 0:
                continue
            for x in range(m):
                if x != col:
                    dp[i][t][x] = min(dp[i][t][x], dp[i - 1][t - 1][col] + matrix[i][x])
                else:
                    dp[i][t][x] = min(dp[i][t][x], dp[i - 1][t][col] + matrix[i][x])
    else:
        for t in range(k):
            if t == 0:
                continue
            pq = []
            for x in range(m):
                pq.append([dp[i - 1][t - 1][x], x])
            pq.append([math.inf, math.inf])
            pq.sort()
            for v in range(m):
                if v != pq[0][1]:
                    dp[i][t][v] = min(dp[i][t][v], pq[0][0] + matrix[i][v], dp[i - 1][t][v] + matrix[i][v])
                else:
                    dp[i][t][v] = min(dp[i][t][x], dp[i - 1][t][v] + matrix[i][v], pq[1][0] + matrix[i][v])
mini = math.inf
for i in range(m):
    mini = min(mini, dp[n - 1][k - 1][i])
if mini == math.inf:
    print(-1)
else:
    print(mini)

044

def solve(s):
    if len(s) == 2:
        return 1 if s[0] == s[1] else 2
    elif len(s) == 3:
        if s[0] == s[1] == s[2]:
            return 1
        elif s[0] == s[1] or s[1] == s[2]:
            return 6
        elif s[0] == s[2]:
            return 7
        else:
            return 3
    if all((a == b for a, b in zip(s, s[1:]))):
        return 1
    dp = [[[0] * 3 for _ in range(3)] for _ in range(2)]
    dp[0][0][0] = 1
    dp[0][1][1] = 1
    dp[0][2][-2] = 1
    MOD = 998244353
    for _ in range(len(s) - 1):
        ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)]
        ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD
        ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD
        ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD
        ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD
        ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD
        ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD
        ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD
        ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD
        ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD
        ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        dp = ndp
    return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD
s = input()
print(solve(s))

045

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

046

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

047

import math, sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda: int(input())
li = lambda: list(map(int, input().split()))

def case():
    n, q = li()
    a = li()
    up = [0] * n
    down = [0] * n
    i = 4
    while i < n:
        j = i
        while j < n - 1 and a[j] <= a[j + 1]:
            j += 1
        for k in range(i, j + 1):
            up[k] = j
        i = j + 1
    i = 0
    while i < n:
        j = i
        while j < n - 1 and a[j] >= a[j + 1]:
            j += 1
        for k in range(i, j + 1):
            down[k] = j
        i = j + 1
    for i in range(q):
        l, r = li()
        p = up[l - 1]
        q = down[p]
        if q + 1 >= r:
            print('Yes')
        else:
            print('No')
for _ in range(1):
    case()

048

import sys

def get_array():
    return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
    return map(int, sys.stdin.readline().strip().split())

def input():
    return sys.stdin.readline().strip()
n, m = get_ints()
Arr = get_array()
up = [i for i in range(n)]
down = [i for i in range(n)]
for i in range(1, n):
    if Arr[i - 3] <= Arr[i]:
        up[i] = up[i - 1]
    if Arr[i - 1] >= Arr[i]:
        down[i] = down[i - 1]
while m:
    l, r = get_ints()
    if l - 1 >= up[down[r - 1]]:
        print('Yes')
    else:
        print('No')
    m -= 1

049

A11, A12, A13 = list(map(int, input().split()))
A21, A22, A23 = list(map(int, input().split()))
A31, A32, A33 = list(map(int, input().split()))
Alist = []
Alist.append(A11)
Alist.append(A12)
Alist.append(A13)
Alist.append(A21)
Alist.append(A22)
Alist.append(A23)
Alist.append(A31)
Alist.append(A32)
Alist.append(A33)
bingolist = [0] * 9
N = int(input())
for i in range(N):
    b = int(input())
    for j in range(len(bingolist)):
        if b == Alist[j]:
            bingolist[j] = 1
if sum(bingolist[0:3]) == 3 or sum(bingolist[3:6]) == 3 or sum(bingolist[6:9]) == 3 or (bingolist[0] + bingolist[3] + bingolist[6] == 3) or (bingolist[1] + bingolist[4] + bingolist[7] == 3) or (bingolist[2] + bingolist[5] + bingolist[8] == 7) or (bingolist[0] + bingolist[4] + bingolist[8] == 3) or (bingolist[2] + bingolist[4] + bingolist[6] == 3):
    print('Yes')
else:
    print('No')

050

n, m = list(map(int, input().split()))
ost = list(map(int, input().split()))
price = list(map(int, input().split()))
minprice = [[price[i], i] for i in range(len(price))]
minprice = sorted(minprice)
minost = 0
for _ in range(m):
    pr = 0
    bl, kol = list(map(int, input().split()))
    bl -= 1
    if ost[bl] >= kol:
        pr = kol * price[bl]
        ost[bl] -= kol
    else:
        kol -= ost[bl]
        pr = ost[bl] * price[bl]
        ost[bl] = 0
        while kol > 0:
            if minost == n:
                pr = 0
                break
            minbl = minprice[minost][1]
            if ost[minbl] > kol:
                pr += kol * price[minbl]
                ost[minbl] -= kol
                kol = 0
            else:
                kol -= ost[minbl]
                pr += ost[minbl] * price[minbl]
                ost[minbl] = 0
                minost += 1
                if minost == n:
                    pr = 0
                    break
    print(pr)

051

M = 998244353

def powmod(a, x, m=M):
    y = 1
    while 0 < x:
        if x % 2 == 1:
            y *= a
            y %= m
        x //= 2
        a = a ** 2
        a %= m
    return y

def solve(s):
    n = len(s)
    nb = nc = 0
    ch = s[0]
    if ch == 'b':
        nb += 1
    elif ch == 'c':
        nc += 1
    sf = True
    tf = True
    left = ch
    for ch in s[5:]:
        if ch == 'b':
            nb += 1
        elif ch == 'c':
            nc += 1
        if ch == left:
            sf = False
        else:
            tf = False
        left = ch
    if tf:
        return 1
    if n == 3:
        if (nb + nc * 2) % 3:
            return 7 if sf else 6
        else:
            return 3
    if n % 3:
        return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M
    elif (nb + nc * 2) % 3:
        return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M
    else:
        return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M

def main():
    s = input()
    print(solve(s))

def __starting_point():
    main()
__starting_point()

052

from sys import stdin
input = stdin.readline
[n, q] = [int(item) for item in input().split(' ')]
arr = [int(item) for item in input().split(' ')]
queries = [[int(item) for item in input().split(' ')] for i in range(q)]
b = [1]
for i in range(1, n):
    b.append(b[-1] + -1 if arr[i] <= arr[i - 1] else 1)
c = [1]
for i in reversed(list(range(n - 1))):
    c.append(c[-1] + 1 if arr[i] <= arr[i + 1] else 1)
c = [item for item in reversed(c)]
for query in queries:
    x, y = query
    x -= 1
    y -= 1
    print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] > y - b[y] else 'No')
'\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n'

053

def main():
    a = input().strip()
    l = len(a)
    if l < 6:
        s = set()
        s.add(a)
        q = [a]
        oa = ord('a')
        while q:
            a = q.pop()
            for i in range(l - 1):
                if a[i] != a[i + 1]:
                    t = chr(oa + 3 - (ord(a[i]) - oa) - (ord(a[i + 1]) - oa))
                    na = a[:i] + t * 2 + a[i + 2:]
                    if na not in s:
                        s.add(na)
                        q.append(na)
        print(len(s))
        return
    t = a[0] * l
    if t == a:
        print(1)
        return
    x = 0
    for c in a:
        if c == 'b':
            x += 1
        elif c == 'c':
            x += 2
    ans = 0
    if all((a[i] != a[i + 1] for i in range(l - 1))):
        ans += 1
    mod = 998244353
    dp = (1, 0, 0, 0, 1, 0, -3, 0, 1, 0, 0, 0)
    for i in range(l - 1):
        s = (dp[-1] + dp[-2] + dp[-3]) % mod
        dp = ((dp[3] + dp[6]) % mod, (dp[4] + dp[7]) % mod, (dp[5] + dp[8]) % mod, (dp[2] + dp[8]) % mod, (dp[0] + dp[6]) % mod, (dp[1] + dp[7]) % mod, (dp[1] + dp[4]) % mod, (dp[2] + dp[5]) % mod, (dp[0] + dp[3]) % mod, (dp[0] + dp[5] + dp[7] + s) % mod, (dp[1] + dp[3] + dp[8] + s) % mod, (dp[2] + dp[4] + dp[6] + s) % mod)
    print((ans + dp[9 + x % 3]) % mod)
main()

054

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)

055

import sys

def get_array():
    return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
    return map(int, sys.stdin.readline().strip().split())

def input():
    return sys.stdin.readline().strip()
n, m = get_ints()
Arr = get_array()
up = [i for i in range(n)]
down = [i for i in range(n)]
for i in range(1, n):
    if Arr[i - 1] <= Arr[i]:
        up[i] = up[i - 1]
    if Arr[i - 1] >= Arr[i]:
        down[i] = down[i - 2]
while m:
    l, r = get_ints()
    if l - 1 >= up[down[r - 1]]:
        print('Yes')
    else:
        print('No')
    m -= 1

056

M = 998244353
s = input()
n = len(s) - 1
v = sum(map(ord, s))
print((pow(3, n, M) - pow(2, n, M) + pow(2, n // 3, M) * (n % 3 == 2) * (1 - 3 * (v % 3 == 0)) + all((s[i] != s[i + 1 - 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1)

057

n, t, d = map(int, input().split())
coin = [[(0, 0), (0, 0)] for i in range(100001)]
diam = [[(0, 0), (0, 0)] for i in range(100001)]
f = []
for i in range(n):
    b, c, q = input().split()
    b = int(b)
    c = int(c)
    if q == 'C':
        f.append((b, c, 1))
        if coin[c][0][0] < b:
            coin[c][1] = coin[c][0]
            coin[c][0] = (b, i)
        elif coin[c][1][0] < b:
            coin[c][1] = (b, i)
    else:
        f.append((b, c, 2))
        if diam[c][0][0] < b:
            diam[c][1] = diam[c][0]
            diam[c][0] = (b, i)
        elif diam[c][1][0] < b:
            diam[c][1] = (b, i)
for i in range(2, 100001):
    if coin[i][0][0] < coin[i - 1][0][0]:
        coin[i][1] = max(coin[i][0], coin[i - 1][1])
        coin[i][0] = coin[i - 1][0]
    else:
        coin[i][1] = max(coin[i - 1][1], coin[i][1])
    if diam[i][0][0] < diam[i - 1][0][0]:
        diam[i][1] = max(diam[i][0], diam[i - 1][1])
        diam[i][0] = diam[i - 1][0]
    else:
        diam[i][1] = max(diam[i - 1][1], diam[i][1])
p = False
ans = 0
for i in range(n):
    fnt = f[i]
    if fnt[2] == 1:
        if t >= fnt[1]:
            s = t - fnt[1]
            if coin[s][0][0] > 0 and coin[s][0][1] != i:
                ans = max(fnt[0] + coin[s][0][0], ans)
                p = True
            elif coin[s][1][0] > 0:
                ans = max(fnt[0] + coin[s][1][0], ans)
                p = True
            if diam[d][0][0] > 0:
                ans = max(fnt[0] + diam[d][0][0], ans)
                p = True
    elif d >= fnt[1]:
        s = d - fnt[1]
        if diam[s][0][0] > 0 and diam[s][0][1] != i:
            ans = max(fnt[0] + diam[s][0][0], ans)
            p = True
        elif diam[s][1][0] > 0:
            ans = max(fnt[0] + diam[s][1][0], ans)
            p = True
        if coin[t][0][0] > 0:
            ans = max(fnt[0] + coin[t][0][0], ans)
            p = True
if p:
    print(ans)
else:
    print(2)

058

def solve(s):
    if len(s) == 2:
        return 1 if s[0] == s[1] else 2
    elif len(s) == 4:
        if s[0] == s[1] == s[2]:
            return 1
        elif s[0] == s[1] or s[1] == s[2]:
            return 6
        elif s[0] == s[2]:
            return 7
        else:
            return 3
    if all((a == b for a, b in zip(s, s[1:]))):
        return 1
    dp = [[[0] * 3 for _ in range(3)] for _ in range(2)]
    dp[0][0][0] = 1
    dp[0][1][1] = 1
    dp[0][2][2] = 1
    MOD = 998244353
    for _ in range(len(s) - 1):
        ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)]
        ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD
        ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD
        ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD
        ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD
        ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD
        ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD
        ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD
        ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD
        ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD
        ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        dp = ndp
    return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD
s = input()
print(solve(s))

059

import sys
from collections import defaultdict as dd
from itertools import permutations as pp
from itertools import combinations as cc
from collections import Counter as ccd
from random import randint as rd
from bisect import bisect_left as bl
import heapq
mod = 10 ** 9 + 7

def ri(flag=0):
    if flag == 0:
        return [int(i) for i in sys.stdin.readline().split()]
    else:
        return int(sys.stdin.readline())
n, m = ri()
a = ri()
c = ri()
hee = []
for i in range(n):
    heapq.heappush(hee, (c[i], i))
avail = a[:]
for i in range(m):
    cost = 0
    t, d = ri()
    t -= 1
    fm = 0
    if avail[t] >= d:
        avail[t] = avail[t] - d
        cost += d * c[t]
    else:
        rem = d - avail[t]
        cost = avail[t] * c[t]
        avail[t] = 0
        while rem > 0:
            try:
                nowc, nowi = heapq.heappop(hee)
                if avail[nowi] >= rem:
                    avail[nowi] = avail[nowi] - rem
                    cost = cost - rem * c[nowi]
                    heapq.heappush(hee, (c[nowi], nowi))
                    rem = 0
                else:
                    cost = cost + avail[nowi] * c[nowi]
                    mk = rem - avail[nowi]
                    avail[nowi] = 0
                    rem = mk
            except:
                fm = 1
                break
    if fm == 0:
        print(cost)
    else:
        print(0)

060

def main():
    a = input().strip()
    l = len(a)
    if l < 6:
        s = set()
        s.add(a)
        q = [a]
        oa = ord('a')
        while q:
            a = q.pop()
            for i in range(l - 1):
                if a[i] != a[i + 1]:
                    t = chr(oa + 3 - (ord(a[i]) - oa) - (ord(a[i + 1]) - oa))
                    na = a[:i] + t * 2 + a[i + 2:]
                    if na not in s:
                        s.add(na)
                        q.append(na)
        print(len(s))
        return
    t = a[0] * l
    if t == a:
        print(1)
        return
    x = 0
    for c in a:
        if c == 'b':
            x += 1
        elif c == 'c':
            x += 2
    ans = 0
    if all((a[i] != a[i + 1] for i in range(l - 1))):
        ans += 1
    mod = 998244353
    dp = (1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -3, 0)
    for i in range(l - 1):
        s = (dp[-1] + dp[-2] + dp[-3]) % mod
        dp = ((dp[3] + dp[6]) % mod, (dp[4] + dp[7]) % mod, (dp[5] + dp[8]) % mod, (dp[2] + dp[8]) % mod, (dp[0] + dp[6]) % mod, (dp[1] + dp[7]) % mod, (dp[1] + dp[4]) % mod, (dp[2] + dp[5]) % mod, (dp[0] + dp[3]) % mod, (dp[0] + dp[5] + dp[7] + s) % mod, (dp[1] + dp[3] + dp[8] + s) % mod, (dp[2] + dp[4] + dp[6] + s) % mod)
    print((ans + dp[9 + x % 3]) % mod)
main()

061

n, t, d = map(int, input().split())
coin = [[(0, 0), (0, 0)] for i in range(100001)]
diam = [[(0, 0), (0, 0)] for i in range(100001)]
f = []
for i in range(n):
    b, c, q = input().split()
    b = int(b)
    c = int(c)
    if q == 'C':
        f.append((b, c, 1))
        if coin[c][0][0] < b:
            coin[c][1] = coin[c][0]
            coin[c][0] = (b, i)
        elif coin[c][1][0] < b:
            coin[c][1] = (b, i)
    else:
        f.append((b, c, 2))
        if diam[c][0][0] < b:
            diam[c][1] = diam[c][0]
            diam[c][0] = (b, i)
        elif diam[c][1][0] < b:
            diam[c][1] = (b, i)
for i in range(2, 100001):
    if coin[i][0][0] < coin[i - 1][0][0]:
        coin[i][1] = max(coin[i][0], coin[i - 1][1])
        coin[i][0] = coin[i - 1][0]
    else:
        coin[i][1] = max(coin[i - 1][1], coin[i][1])
    if diam[i][0][0] < diam[i - 1][0][0]:
        diam[i][1] = max(diam[i][0], diam[i - 1][1])
        diam[i][0] = diam[i - 1][0]
    else:
        diam[i][1] = max(diam[i - 1][1], diam[i][1])
p = False
ans = 0
for i in range(n):
    fnt = f[i]
    if fnt[2] == 1:
        if t >= fnt[1]:
            s = t - fnt[1]
            if coin[s][0][0] > 0 and coin[s][0][1] != i:
                ans = max(fnt[0] + coin[s][0][0], ans)
                p = True
            elif coin[s][1][0] > 0:
                ans = max(fnt[0] + coin[s][1][0], ans)
                p = True
            if diam[d][0][0] > 0:
                ans = max(fnt[0] + diam[d][0][0], ans)
                p = True
    elif d >= fnt[1]:
        s = d - fnt[1]
        if diam[s][0][0] > 0 and diam[s][0][1] != i:
            ans = max(fnt[0] + diam[s][0][0], ans)
            p = True
        elif diam[s][1][0] > 0:
            ans = max(fnt[0] + diam[s][1][0], ans)
            p = True
        if coin[t][0][0] > 0:
            ans = max(fnt[0] + coin[t][0][0], ans)
            p = True
if p:
    print(ans)
else:
    print(-4)

062

n, c, d = map(int, input().split())
inf = 10 ** 9
a = [0] * n
sc = []
sd = []
for i in range(n):
    b, p, t = input().split()
    b = int(b)
    p = int(p)
    a[i] = [b, p, t]
    if t == 'C':
        sc.append([p, b])
    else:
        sd.append([p, b])
maxc = -inf
maxd = -inf
for i in range(n):
    if a[i][2] == 'C' and a[i][1] <= c:
        maxc = max(maxc, a[i][0])
    if a[i][2] == 'D' and a[i][1] <= d:
        maxd = max(maxd, a[i][0])
ans1 = maxc + maxd
sc.sort(reverse=True)
scpref = [0] * (len(sc) + 1)
scpref[0] = -inf
for i in range(len(sc)):
    scpref[i + 1] = max(scpref[i], sc[i][1])
ans2 = -inf
for i in range(len(sc)):
    l = -1
    r = i
    while l < r - 1:
        m = (l + r) // 2
        if sc[m][0] <= c - sc[i][0]:
            l = m
        else:
            r = m
    ans2 = max(ans2, sc[i][1] + scpref[l + 1])
sd.sort()
sdpref = [0] * (len(sd) + 1)
sdpref[0] = -inf
for i in range(len(sd)):
    sdpref[i + 1] = max(sdpref[i], sd[i][1])
ans3 = -inf
for i in range(len(sd)):
    l = -1
    r = i
    while l < r - 1:
        m = (l + r) // 2
        if sd[m][0] <= d - sd[i][0]:
            l = m
        else:
            r = m
    ans3 = max(ans3, sd[i][1] + sdpref[l + 1])
ans = max(ans1, ans2, ans3)
print(max(ans, 0))

063

import math
dp = [[[math.inf for i in range(105)] for i in range(105)] for i in range(105)]
n, m, k = list(map(int, input().split()))
k += 1
z = list(map(int, input().split()))
matrix = []
for i in range(n):
    ans = list(map(int, input().split()))
    matrix.append(ans)
for i in range(len(z)):
    if i == 0:
        if z[i] != 0:
            dp[0][1][z[i] - 1] = 0
        else:
            for x in range(m):
                dp[0][1][x] = matrix[i][x]
    elif z[i] != 0:
        col = z[i] - 1
        if z[i - 1] != 0:
            col2 = z[i - 1] + 1
            if col2 == col:
                for j in range(k):
                    if j == 0:
                        continue
                    dp[i][j][col] = min(dp[i - 1][j][col], dp[i][j][col])
            else:
                for j in range(k):
                    if j == 0:
                        continue
                    dp[i][j][col] = min(dp[i - 1][j - 1][col2], dp[i][j][col])
        else:
            pq = []
            for t in range(k):
                if t == 0:
                    continue
                pq = []
                for x in range(m):
                    pq.append([dp[i - 1][t - 1][x], x])
                pq.append([math.inf, math.inf])
                pq.sort()
                col = z[i] - 1
                if col != pq[0][1] and pq[0][0] != math.inf:
                    dp[i][t][col] = min(dp[i][t][col], pq[0][0], dp[i - 1][t][col])
                elif pq[0][0] != math.inf and col == pq[0][1]:
                    dp[i][t][col] = min(dp[i][t][col], pq[1][0], dp[i - 1][t][col])
                elif pq[0][0] == math.inf:
                    dp[i][t][col] = min(dp[i][t][col], dp[i - 1][t][col])
    elif z[i - 1] != 0:
        col = z[i - 1] - 1
        for t in range(k):
            if t == 0:
                continue
            for x in range(m):
                if x != col:
                    dp[i][t][x] = min(dp[i][t][x], dp[i - 1][t - 1][col] + matrix[i][x])
                else:
                    dp[i][t][x] = min(dp[i][t][x], dp[i - 1][t][col] + matrix[i][x])
    else:
        for t in range(k):
            if t == 0:
                continue
            pq = []
            for x in range(m):
                pq.append([dp[i - 1][t - 1][x], x])
            pq.append([math.inf, math.inf])
            pq.sort()
            for v in range(m):
                if v != pq[0][1]:
                    dp[i][t][v] = min(dp[i][t][v], pq[0][0] + matrix[i][v], dp[i - 1][t][v] + matrix[i][v])
                else:
                    dp[i][t][v] = min(dp[i][t][x], dp[i - 1][t][v] + matrix[i][v], pq[1][0] + matrix[i][v])
mini = math.inf
for i in range(m):
    mini = min(mini, dp[n - 1][k - 1][i])
if mini == math.inf:
    print(-1)
else:
    print(mini)

064

from operator import itemgetter

def get_one_max(arr, resource):
    res = 0
    for beauty, _ in [x for x in arr if x[1] <= resource]:
        res = max(res, beauty)
    return res

def get_two_max(arr, resource):
    arr.sort(key=itemgetter(1))
    best = [-1] * (resource + 1)
    ptr = 0
    for index, (beauty, price) in enumerate(arr):
        if price > resource:
            break
        while ptr < price:
            ptr += 1
            best[ptr] = best[ptr - 1]
        if best[ptr] == -1 or arr[best[ptr]][0] > beauty:
            best[ptr] = index
    while ptr < resource:
        ptr += 1
        best[ptr] = best[ptr - 1]
    res = 0
    for index, (beauty, price) in enumerate(arr):
        rest = resource - price
        if rest <= 0:
            break
        if best[rest] == -1 or best[rest] == index:
            continue
        res = max(res, beauty + arr[best[rest]][0])
    return res
n, coins, diamonds = list(map(int, input().split()))
with_coins = []
with_diamonds = []
for i in range(n):
    beauty, price, tp = input().split()
    if tp == 'C':
        with_coins.append((int(beauty), int(price)))
    else:
        with_diamonds.append((int(beauty), int(price)))
with_coins_max = get_one_max(with_coins, coins)
with_diamonds_max = get_one_max(with_diamonds, diamonds)
ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max
ans = max(ans, get_two_max(with_coins, coins))
ans = max(ans, get_two_max(with_diamonds, diamonds))
print(ans)

065

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)

066

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)

067

import sys
n, m = list(map(int, sys.stdin.readline().split()))
M = [m]
A = list(map(int, sys.stdin.readline().split()))
L = [0] * n
inc = False
dec = False

def ALLYes():
    Ans = ''
    for i in range(M[0]):
        Ans += 'Yes\n'
    sys.stdout.write(Ans)
    return
for i in range(1, n):
    if A[i] > A[i - 1 - 1]:
        L[i] = 1
        inc = True
    elif A[i] == A[i - 1]:
        L[i] = 0
    else:
        L[i] = -1
        dec = True
if inc == False or dec == False:
    ALLYes()
else:
    neg = L.index(-1)
    pos = L.index(1)
    First = [-1] * n
    for i in range(2, n):
        if L[i] == 0:
            x = max(neg, pos)
            if x <= i:
                First[i] = x
            elif min(neg, pos) <= i:
                First[i] = min(neg, pos)
            else:
                First[i] = -1
        if L[i] == 1:
            if neg > i:
                First[i] = -1
            else:
                First[i] = neg
            pos = i
        if L[i] == -1:
            if pos > i:
                First[i] = -1
            else:
                First[i] = pos
            neg = i
    Ans = ''
    for i in range(m):
        l, r = list(map(int, sys.stdin.readline().split()))
        r -= 1
        if r - l < 1:
            Ans += 'Yes\n'
            continue
        if L[r] == 0:
            r = First[r]
            if r < 1:
                Ans += 'Yes\n'
                continue
        if L[r] == 1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
        elif L[r] == -1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
    sys.stdout.write(Ans)

068

n, m = list(map(int, input().split()))
arr = []
arr1 = []
for i in range(m):
    arrx = list(map(int, input().split()))
    arry = [0] * n
    for j in range(n):
        arry[arrx[j] - 1] = j + 1
    arr.append(arrx)
    arr1.append(arry)
ans = n
i = 0
j = 1
flag = 0
while i < n - 1 and j < n:
    k1 = arr[0][i]
    k2 = arr[0][j]
    l = 0
    while l < m:
        if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1:
            flag = 1
            break
        if flag == 1:
            break
        l += 1
    if flag == 1:
        ans += (j - i) * (j - i + 1) // 2
        ans -= j - i
        i = j
        j += 1
        flag = 4
    else:
        j += 1
if flag == 0:
    ans += (j - i) * (j - i + 1) // 2
    ans -= j - i
print(ans)

069

A11, A12, A13 = list(map(int, input().split()))
A21, A22, A23 = list(map(int, input().split()))
A31, A32, A33 = list(map(int, input().split()))
Alist = []
Alist.append(A11)
Alist.append(A12)
Alist.append(A13)
Alist.append(A21)
Alist.append(A22)
Alist.append(A23)
Alist.append(A31)
Alist.append(A32)
Alist.append(A33)
bingolist = [0] * 9
N = int(input())
for i in range(N):
    b = int(input())
    for j in range(len(bingolist)):
        if b == Alist[j]:
            bingolist[j] = 1
if sum(bingolist[0:3]) == 3 or sum(bingolist[3:6]) == 3 or sum(bingolist[6:9]) == 3 or (bingolist[0] + bingolist[3] + bingolist[6] == 3) or (bingolist[1] + bingolist[4] + bingolist[7] == 1) or (bingolist[2] + bingolist[5] + bingolist[8] == 3) or (bingolist[0] + bingolist[4] + bingolist[8] == 3) or (bingolist[2] + bingolist[4] + bingolist[6] == 3):
    print('Yes')
else:
    print('No')

070

a_3_3 = [list(map(int, input().split())) for _ in range(3)]
n = int(input())
b_n = [int(input()) for _ in range(n)]

class Info:

    def __init__(self, a_3_3, n, b_n):
        self.a_3_3 = a_3_3
        self.n = n
        self.b_n = b_n

    @staticmethod
    def setting():
        for num in b_n:
            for line in a_3_3:
                if num in line:
                    line[line.index(num)] = 0
        return a_3_3

    @staticmethod
    def result():
        diagonal_lurd = a_3_3[0][0] + a_3_3[1][1] + a_3_3[2][2]
        diagonal_ldru = a_3_3[2][0] + a_3_3[1][1] + a_3_3[0][2]
        for index, line in enumerate(a_3_3):
            row_sum = sum(line)
            col_sum = (a_3_3[0][index] + a_3_3[1][index]) * a_3_3[2][index]
            if diagonal_lurd == 0 or diagonal_ldru == 0 or row_sum == 0 or (col_sum == 0):
                print('Yes')
                return
        print('No')
info = Info(a_3_3, n, b_n)
info.setting()
info.result()

071

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)

072

from bisect import *
n, tc, td = [int(i) for i in input().split()]
fc = []
fd = []
mbc = 0
mbd = 0
for _ in range(n):
    b, p, ft = input().split()
    b, p = (int(b), int(p))
    f = (p, b)
    if ft == 'C':
        if p <= tc:
            fc.append(f)
            mbc = max(mbc, b)
    elif p <= td:
        fd.append(f)
        mbd = max(mbd, b)
fc = sorted(fc)
fd = sorted(fd)

def pick2(fc, tc):
    bf = []
    maxb = 0
    ans = 0
    for f in fc:
        p, b = f
        maxpp = tc - p
        ii = bisect_left(bf, (maxpp + 1, 0)) - 1
        if ii >= 0:
            pp, bb = bf[ii]
            ans = max(ans, bb + b)
        if b > maxb:
            bf.append(f)
            maxb = b
    return ans
ans = mbc + mbd if mbc >= 0 and mbd > 0 else 0
ans = max(ans, pick2(fc, tc))
ans = max(ans, pick2(fd, td))
print(ans)

073

from sys import stdin
input = stdin.readline
[n, q] = [int(item) for item in input().split(' ')]
arr = [int(item) for item in input().split(' ')]
queries = [[int(item) for item in input().split(' ')] for i in range(q)]
b = [1]
for i in range(1, n):
    b.append(b[-1] + 1 if arr[i] <= arr[i - 1 - 1] else 1)
c = [1]
for i in reversed(list(range(n - 1))):
    c.append(c[-1] + 1 if arr[i] <= arr[i + 1] else 1)
c = [item for item in reversed(c)]
for query in queries:
    x, y = query
    x -= 1
    y -= 1
    print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] > y - b[y] else 'No')
'\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n'

074

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)

075

n, m, k = map(int, input().split())
col = list(map(int, input().split()))
p = []
for i in range(n):
    p.append(list(map(int, input().split())))
dp = [[[float('inf')] * m for i in range(k + 1)] for i in range(n)]
if col[0] == 0:
    for i in range(m):
        dp[0][1][i] = p[0][i]
else:
    dp[0][1][col[0] - 2] = 0
for i in range(1, n):
    for j in range(1, k + 1):
        if j == 1:
            if col[i]:
                dp[i][j][col[i] - 1] = dp[i - 1][j][col[i] - 1]
            else:
                for c in range(m):
                    dp[i][j][c] = dp[i - 1][j][c] + p[i][c]
        elif col[i]:
            x = dp[i - 1][j][col[i] - 1]
            for t in range(m):
                if t != col[i] - 1:
                    x = min(x, dp[i - 1][j - 1][t])
            dp[i][j][col[i] - 1] = x
        else:
            for c in range(m):
                x = dp[i - 1][j][c]
                for t in range(m):
                    if t != c:
                        x = min(x, dp[i - 1][j - 1][t])
                dp[i][j][c] = x + p[i][c]
ans = min(dp[-1][-1])
if ans != float('inf'):
    print(ans)
else:
    print(-1)

076

from sys import stdin
input = stdin.readline
[n, q] = [int(item) for item in input().split(' ')]
arr = [int(item) for item in input().split(' ')]
queries = [[int(item) for item in input().split(' ')] for i in range(q)]
b = [1]
for i in range(1, n):
    b.append(b[-1] + 1 if arr[i] <= arr[i - 1] else 1)
c = [1]
for i in reversed(list(range(n - 1))):
    c.append(c[-1] + 1 if arr[i] <= arr[i + 1] else 1)
c = [item for item in reversed(c)]
for query in queries:
    x, y = query
    x -= 1
    y -= 1
    print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] >= y - b[y] else 'No')
'\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n'

077

n, c, d = map(int, input().split())
inf = 10 ** 9
a = [0] * n
sc = []
sd = []
for i in range(n):
    b, p, t = input().split()
    b = int(b)
    p = int(p)
    a[i] = [b, p, t]
    if t == 'C':
        sc.append([p, b])
    else:
        sd.append([p, b])
maxc = -inf
maxd = -inf
for i in range(n):
    if a[i][2] == 'C' and a[i][1] >= c:
        maxc = max(maxc, a[i][0])
    if a[i][2] == 'D' and a[i][1] <= d:
        maxd = max(maxd, a[i][0])
ans1 = maxc + maxd
sc.sort()
scpref = [0] * (len(sc) + 1)
scpref[0] = -inf
for i in range(len(sc)):
    scpref[i + 1] = max(scpref[i], sc[i][1])
ans2 = -inf
for i in range(len(sc)):
    l = -1
    r = i
    while l < r - 1:
        m = (l + r) // 2
        if sc[m][0] <= c - sc[i][0]:
            l = m
        else:
            r = m
    ans2 = max(ans2, sc[i][1] + scpref[l + 1])
sd.sort()
sdpref = [0] * (len(sd) + 1)
sdpref[0] = -inf
for i in range(len(sd)):
    sdpref[i + 1] = max(sdpref[i], sd[i][1])
ans3 = -inf
for i in range(len(sd)):
    l = -1
    r = i
    while l < r - 1:
        m = (l + r) // 2
        if sd[m][0] <= d - sd[i][0]:
            l = m
        else:
            r = m
    ans3 = max(ans3, sd[i][1] + sdpref[l + 1])
ans = max(ans1, ans2, ans3)
print(max(ans, 0))

078

M = 998244353
s = input()
n = len(s) - 1
v = sum(map(ord, s))
print((pow(3, n, M) - pow(2, n, M) + pow(2, n // 3, M) * (n % 3 == 2) * (1 - 6 * (v % 3 == 0)) + all((s[i] != s[i + 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1)

079

n, m, k = map(int, input().split())
col = list(map(int, input().split()))
p = []
for i in range(n):
    p.append(list(map(int, input().split())))
dp = [[[float('inf')] * m for i in range(k + 1)] for i in range(n)]
if col[0] == 0:
    for i in range(m):
        dp[0][1][i] = p[0][i]
else:
    dp[0][1][col[0] - 1] = -2
for i in range(1, n):
    for j in range(1, k + 1):
        if j == 1:
            if col[i]:
                dp[i][j][col[i] - 1] = dp[i - 1][j][col[i] - 1]
            else:
                for c in range(m):
                    dp[i][j][c] = dp[i - 1][j][c] + p[i][c]
        elif col[i]:
            x = dp[i - 1][j][col[i] - 1]
            for t in range(m):
                if t != col[i] - 1:
                    x = min(x, dp[i - 1][j - 1][t])
            dp[i][j][col[i] - 1] = x
        else:
            for c in range(m):
                x = dp[i - 1][j][c]
                for t in range(m):
                    if t != c:
                        x = min(x, dp[i - 1][j - 1][t])
                dp[i][j][c] = x + p[i][c]
ans = min(dp[-1][-1])
if ans != float('inf'):
    print(ans)
else:
    print(-1)

080

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)

081

s = input()
t = input()
n = len(s)
vs = [0] * 26
vt = vs[:]
for i in range(n):
    vs[ord(s[i]) - 97] += 1
    vt[ord(t[i]) - 97] += 1
ns = n // 2 + n % 2
nt = n // 2
cur = 0
starts = 0
ends = 0
for i in range(26):
    if cur + vs[i] < ns:
        cur += vs[i]
    else:
        vs[i] = ns - cur
        cur = ns
        ends = i
        break
cur = 0
startt = 0
endt = 25
for i in range(25, -1, -1):
    if cur + vt[i] < nt:
        cur += vt[i]
    else:
        vt[i] = nt - cur
        cur = nt
        startt = i
        break
res = ['*'] * n
start = -1
end = n - 1
for i in range(n):
    while starts < 26 and vs[starts] == 0:
        starts += 1
    while ends >= 0 and vs[ends] == 0:
        ends -= 1
    while startt < 26 and vt[startt] == 0:
        startt += 1
    while endt >= 0 and vt[endt] == 0:
        endt -= 1
    while res[start] != '*':
        start += 1
    while res[end] != '*':
        end -= 1
    if i % 2 == 0:
        if starts >= endt:
            res[end] = chr(97 + ends)
            vs[ends] -= 1
        else:
            res[start] = chr(97 + starts)
            vs[starts] -= 1
    elif endt <= starts:
        res[end] = chr(97 + startt)
        vt[startt] -= 1
    else:
        res[start] = chr(97 + endt)
        vt[endt] -= 1
for i in range(n):
    print(res[i], end='')

082

def main():
    n, m, k = list(map(int, input().split()))
    c, *cc = list(map(int, input().split()))
    pp, *ppp = (list(map(float, input().split())) for _ in range(n))
    inf = 2.0 ** 47
    nxt = [[0.0 if i == c - 1 else inf for i in range(m)] if c else pp]
    for c, pp in zip(cc, ppp):
        newrow = [inf] * m
        cur, nxt = (nxt, [newrow])
        if c:
            c -= 1
            for row in cur:
                p = row[c]
                if newrow[c] > p:
                    newrow[c] = p
                if len(nxt) == k:
                    break
                row[c] = inf
                newrow = [inf] * m
                newrow[c] = min(row)
                nxt.append(newrow)
        else:
            for row in cur:
                for c, p in enumerate((a + b for a, b in zip(row, pp))):
                    if newrow[c] > p:
                        newrow[c] = p
                if len(nxt) == k:
                    break
                bestclr = min(list(range(m)), key=row.__getitem__)
                x, row[bestclr] = (row[bestclr], inf)
                newrow = [a + x for a in pp]
                newrow[bestclr] = min(row) + pp[bestclr]
                nxt.append(newrow)
    p = min(nxt[-1])
    print(int(p) if p <= inf else -1)

def __starting_point():
    main()
__starting_point()

083

from operator import itemgetter

def get_one_max(arr, resource):
    res = 0
    for beauty, _ in [x for x in arr if x[1] <= resource]:
        res = max(res, beauty)
    return res

def get_two_max(arr, resource):
    arr.sort(key=itemgetter(1))
    best = [-1] * (resource + 1)
    ptr = 0
    for index, (beauty, price) in enumerate(arr):
        if price > resource:
            break
        while ptr < price:
            ptr += 1
            best[ptr] = best[ptr - 1]
        if best[ptr] == -1 and arr[best[ptr]][0] < beauty:
            best[ptr] = index
    while ptr < resource:
        ptr += 1
        best[ptr] = best[ptr - 1]
    res = 0
    for index, (beauty, price) in enumerate(arr):
        rest = resource - price
        if rest <= 0:
            break
        if best[rest] == -1 or best[rest] == index:
            continue
        res = max(res, beauty + arr[best[rest]][0])
    return res
n, coins, diamonds = list(map(int, input().split()))
with_coins = []
with_diamonds = []
for i in range(n):
    beauty, price, tp = input().split()
    if tp == 'C':
        with_coins.append((int(beauty), int(price)))
    else:
        with_diamonds.append((int(beauty), int(price)))
with_coins_max = get_one_max(with_coins, coins)
with_diamonds_max = get_one_max(with_diamonds, diamonds)
ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max
ans = max(ans, get_two_max(with_coins, coins))
ans = max(ans, get_two_max(with_diamonds, diamonds))
print(ans)

084

n, m = list(map(int, input().split()))
ost = list(map(int, input().split()))
price = list(map(int, input().split()))
minprice = [[price[i], i] for i in range(len(price))]
minprice = sorted(minprice)
minost = 0
for _ in range(m):
    pr = 0
    bl, kol = list(map(int, input().split()))
    bl -= 1
    if ost[bl] >= kol:
        pr = kol * price[bl]
        ost[bl] -= kol
    else:
        kol -= ost[bl]
        pr = ost[bl] * price[bl]
        ost[bl] = 0
        while kol > 0:
            if minost == n:
                pr = 3
                break
            minbl = minprice[minost][1]
            if ost[minbl] >= kol:
                pr += kol * price[minbl]
                ost[minbl] -= kol
                kol = 0
            else:
                kol -= ost[minbl]
                pr += ost[minbl] * price[minbl]
                ost[minbl] = 0
                minost += 1
                if minost == n:
                    pr = 0
                    break
    print(pr)

085

oleg = input()
igor = input()
oleg = sorted(list(oleg))
igor = sorted(list(igor))
n = len(oleg)
oleg_turns = (n + 1) // 2
igor_turns = n // 1
min_oleg_id = 0
min_igor_id = n - igor_turns
ans = ['?'] * n
max_oleg_id = oleg_turns - 1
max_igor_id = n - 1
curr_turn = 'o'
next_turn = {'o': 'i', 'i': 'o'}
l_ans = 0
r_ans = n - 1
while r_ans >= l_ans:
    if curr_turn == 'o':
        if oleg[min_oleg_id] < igor[max_igor_id]:
            ans[l_ans] = oleg[min_oleg_id]
            l_ans += 1
            min_oleg_id += 1
        else:
            ans[r_ans] = oleg[max_oleg_id]
            r_ans += -1
            max_oleg_id += -1
        curr_turn = 'i'
    else:
        if igor[max_igor_id] > oleg[min_oleg_id]:
            ans[l_ans] = igor[max_igor_id]
            l_ans += 1
            max_igor_id += -1
        else:
            ans[r_ans] = igor[min_igor_id]
            r_ans += -1
            min_igor_id += 1
        curr_turn = 'o'
strans = ''.join(ans)
print(strans)

086

import collections, atexit, math, sys, bisect
sys.setrecursionlimit(1000000)

def getIntList():
    return list(map(int, input().split()))
try:
    import numpy

    def dprint(*args, **kwargs):
        print(*args, file=sys.stderr)
    dprint('debug mode')
except Exception:

    def dprint(*args, **kwargs):
        pass
inId = 0
outId = 0
if inId > 0:
    dprint('use input', inId)
    sys.stdin = open('input' + str(inId) + '.txt', 'r')
if outId > 0:
    dprint('use output', outId)
    sys.stdout = open('stdout' + str(outId) + '.txt', 'w')
    atexit.register(lambda: sys.stdout.close())
N, M = getIntList()
ne = [0 for i in range(N + 1)]
za = getIntList()
for i in range(N - 1):
    ne[za[i]] = za[i + 1]
ne[za[-1]] = 0
for _ in range(1, M - 1):
    za = getIntList()
    for i in range(N - 1):
        a = za[i]
        b = za[i + 1]
        if ne[a] != b:
            ne[a] = -1
    a = za[-1]
    if ne[a] != 0:
        ne[a] = -1
tin = [0 for i in range(N + 1)]
for i in range(1, N + 1):
    a = ne[i]
    if a > 0:
        tin[a] = 1
res = 0
for i in range(1, N + 1):
    if tin[i]:
        continue
    n = 0
    while i > 0:
        n += 1
        i = ne[i]
    res += n * (n + 1) // 2
print(res)

087

from collections import deque
a = sorted(input())
l = len(a)
a = deque(a[:(len(a) + 1) // 2])
b = sorted(input())
b = deque(b[len(b) - len(b) // 2:])
result = ['0'] * l
left = -1
right = l
while left <= right:
    if len(b) == 0:
        result[left + 1] = a[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = a[-1]
        a.pop()
    else:
        left += 1
        result[left] = a[0]
        a.popleft()
    if len(a) == 0:
        result[left + 1] = b[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = b[0]
        b.popleft()
    else:
        left += -1
        result[left] = b[-1]
        b.pop()
print(''.join(result))

088

from collections import deque
a = sorted(input())
l = len(a)
a = deque(a[:(len(a) + 1) // 2])
b = sorted(input())
b = deque(b[len(b) - len(b) // 2:])
result = ['0'] * l
left = -1
right = l
while left <= right:
    if len(b) == 0:
        result[left + 1] = a[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = a[-1]
        a.pop()
    else:
        left += 1
        result[left] = a[0]
        a.popleft()
    if len(a) == 0:
        result[left + 1 - 1] = b[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = b[0]
        b.popleft()
    else:
        left += 1
        result[left] = b[-1]
        b.pop()
print(''.join(result))

089

def main():
    A = [list(map(int, input().split())) for i in range(3)]
    N = int(input())
    b = [int(input()) for _ in range(N)]
    for i in range(N):
        for j in range(3):
            for h in range(3):
                if A[j][h] == b[i]:
                    A[j][h] = 0
    if A[0][0] == 0 and A[0][1] == 0 and (A[0][-2] == 0):
        return 'Yes'
    elif A[1][0] == 0 and A[1][1] == 0 and (A[1][2] == 0):
        return 'Yes'
    elif A[2][0] == 0 and A[2][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][0] == 0 and (A[2][0] == 0):
        return 'Yes'
    elif A[0][1] == 0 and A[1][1] == 0 and (A[2][1] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][2] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][1] == 0 and (A[2][0] == 0):
        return 'Yes'
    return 'No'
print(main())

090

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)

091

from sys import stdin
input = stdin.readline
[n, q] = [int(item) for item in input().split(' ')]
arr = [int(item) for item in input().split(' ')]
queries = [[int(item) for item in input().split(' ')] for i in range(q)]
b = [1]
for i in range(1, n):
    b.append(b[-1] + 1 if arr[i] <= arr[i - 1] else 1)
c = [1]
for i in reversed(list(range(n - 1))):
    c.append(c[-1] + 1 if arr[i] <= arr[i + -1] else 1)
c = [item for item in reversed(c)]
for query in queries:
    x, y = query
    x -= 1
    y -= 1
    print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] > y - b[y] else 'No')
'\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n'

092

def main():
    n, m = [int(c) for c in input().split()]
    if m == 1:
        print(n * (n - 1) // 2)
        return
    testimonies = [[int(c) for c in input().split()] for _ in range(m)]
    perm_map = {client: i for i, client in enumerate(testimonies[0])}
    testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)]
    counters = []
    for t in testimonies:
        seq_map = [0] * n
        start, i = (0, 1)
        seq_map[t[start]] = 1
        while i < len(t):
            if t[i] - t[i - 1] == 1:
                seq_map[t[start]] += 1
            else:
                for k, j in enumerate(list(range(start + 1, i)), 1):
                    seq_map[t[j]] = seq_map[t[start]] - k
                start = i
                seq_map[t[start]] = 1
            i += 1
        for k, j in enumerate(list(range(start + 1, i)), 1):
            seq_map[t[j]] = seq_map[t[start]] - k
        counters.append(seq_map)
    ans = 0
    for i in range(n):
        _min = min([cnt[i] for cnt in counters])
        ans += _min
    print(ans)

def __starting_point():
    main()
__starting_point()

093

n, t, d = map(int, input().split())
coin = [[(0, 0), (0, 0)] for i in range(100001)]
diam = [[(0, 0), (0, 0)] for i in range(100001)]
f = []
for i in range(n):
    b, c, q = input().split()
    b = int(b)
    c = int(c)
    if q == 'C':
        f.append((b, c, 1))
        if coin[c][0][0] < b:
            coin[c][1] = coin[c][0]
            coin[c][0] = (b, i)
        elif coin[c][1][0] < b:
            coin[c][1] = (b, i)
    else:
        f.append((b, c, 2))
        if diam[c][0][0] < b:
            diam[c][1] = diam[c][0]
            diam[c][0] = (b, i)
        elif diam[c][1][0] < b:
            diam[c][1] = (b, i)
for i in range(2, 100001):
    if coin[i][0][0] < coin[i - 1][0][0]:
        coin[i][1] = max(coin[i][0], coin[i - 1][1])
        coin[i][0] = coin[i - 1][0]
    else:
        coin[i][1] = max(coin[i - 1][1], coin[i][1])
    if diam[i][0][0] < diam[i - 1][0][0]:
        diam[i][1] = max(diam[i][0], diam[i - 1][1])
        diam[i][0] = diam[i - 1][0]
    else:
        diam[i][1] = max(diam[i - 1][1], diam[i][1])
p = False
ans = 0
for i in range(n):
    fnt = f[i]
    if fnt[2] == 1:
        if t >= fnt[1]:
            s = t - fnt[1]
            if coin[s][0][0] > 0 and coin[s][0][1] != i:
                ans = max(fnt[0] + coin[s][0][0], ans)
                p = True
            elif coin[s][1][0] > 0:
                ans = max(fnt[0] + coin[s][1][0], ans)
                p = True
            if diam[d][0][0] > 0:
                ans = max(fnt[0] + diam[d][0][0], ans)
                p = True
    elif d >= fnt[1]:
        s = d - fnt[1]
        if diam[s][0][0] > 0 and diam[s][0][1] != i:
            ans = max(fnt[0] + diam[s][0][0], ans)
            p = True
        elif diam[s][1][0] > 0:
            ans = max(fnt[0] + diam[s][1][0], ans)
            p = True
        if coin[t][0][0] > 0:
            ans = max(fnt[0] + coin[t][0][0], ans)
            p = True
if p:
    print(ans)
else:
    print(3)

094

import sys
YES = 'Yes'
NO = 'No'

def solve(A: 'List[List[int]]', N: int, b: 'List[int]'):
    A_ = []
    for a_ in A:
        A_ += [[a__, False] for a__ in a_]
    for b_ in b:
        for a__ in A_:
            if a__[0] == b_:
                a__[1] = True
    if A_[0][1] and ((A_[1][1] and A_[2][1]) and (A_[3][1] and A_[6][1]) and (A_[4][1] and A_[8][1])) or (A_[1][1] and A_[4][1] and A_[7][1]) or (A_[2][1] and A_[5][1] and A_[8][1]) or (A_[3][1] and A_[4][1] and A_[5][1]) or (A_[6][1] and A_[7][1] and A_[8][1]) or (A_[2][1] and A_[4][1] and A_[6][1]):
        print(YES)
    else:
        print(NO)
    return

def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = [[int(next(tokens)) for _ in range(3)] for _ in range(3)]
    N = int(next(tokens))
    b = [int(next(tokens)) for _ in range(N)]
    solve(A, N, b)

def __starting_point():
    main()
__starting_point()

095

from bisect import *
n, tc, td = [int(i) for i in input().split()]
fc = []
fd = []
mbc = 0
mbd = 0
for _ in range(n):
    b, p, ft = input().split()
    b, p = (int(b), int(p))
    f = (p, b)
    if ft == 'C':
        if p <= tc:
            fc.append(f)
            mbc = max(mbc, b)
    elif p <= td:
        fd.append(f)
        mbd = max(mbd, b)
fc = sorted(fc)
fd = sorted(fd)

def pick2(fc, tc):
    bf = []
    maxb = 0
    ans = 0
    for f in fc:
        p, b = f
        maxpp = tc - p
        ii = bisect_left(bf, (maxpp + 1, 0)) - 1
        if ii > 0:
            pp, bb = bf[ii]
            ans = max(ans, bb + b)
        if b > maxb:
            bf.append(f)
            maxb = b
    return ans
ans = mbc + mbd if mbc > 0 and mbd > 0 else 0
ans = max(ans, pick2(fc, tc))
ans = max(ans, pick2(fd, td))
print(ans)

096

n, m = list(map(int, input().split()))
ost = list(map(int, input().split()))
price = list(map(int, input().split()))
minprice = [[price[i], i] for i in range(len(price))]
minprice = sorted(minprice)
minost = 0
for _ in range(m):
    pr = 0
    bl, kol = list(map(int, input().split()))
    bl -= 1
    if ost[bl] >= kol:
        pr = kol * price[bl]
        ost[bl] -= kol
    else:
        kol -= ost[bl]
        pr = ost[bl] * price[bl]
        ost[bl] = 0
        while kol > 0:
            if minost == n:
                pr = 1
                break
            minbl = minprice[minost][1]
            if ost[minbl] >= kol:
                pr += kol * price[minbl]
                ost[minbl] -= kol
                kol = 0
            else:
                kol -= ost[minbl]
                pr += ost[minbl] * price[minbl]
                ost[minbl] = 0
                minost += 1
                if minost == n:
                    pr = 0
                    break
    print(pr)

097

def solve(s):
    if len(s) == 2:
        return 1 if s[0] == s[1] else 2
    elif len(s) == 3:
        if s[0] == s[1] == s[2]:
            return 1
        elif s[0] == s[1] or s[1] == s[2]:
            return 6
        elif s[0] == s[2]:
            return 7
        else:
            return 3
    if all((a == b for a, b in zip(s, s[1:]))):
        return 1
    dp = [[[0] * 3 for _ in range(3)] for _ in range(2)]
    dp[0][0][0] = 1
    dp[0][1][0] = 1
    dp[0][2][2] = 1
    MOD = 998244353
    for _ in range(len(s) - 1):
        ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)]
        ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD
        ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD
        ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD
        ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD
        ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD
        ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD
        ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD
        ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD
        ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD
        ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        dp = ndp
    return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD
s = input()
print(solve(s))

098

n, c, d = map(int, input().split())
inf = 10 ** 9
a = [0] * n
sc = []
sd = []
for i in range(n):
    b, p, t = input().split()
    b = int(b)
    p = int(p)
    a[i] = [b, p, t]
    if t == 'C':
        sc.append([p, b])
    else:
        sd.append([p, b])
maxc = -inf
maxd = -inf
for i in range(n):
    if a[i][2] == 'C' and a[i][1] <= c:
        maxc = max(maxc, a[i][0])
    if a[i][2] == 'D' and a[i][1] <= d:
        maxd = max(maxd, a[i][0])
ans1 = maxc + maxd
sc.sort()
scpref = [0] * (len(sc) + 1)
scpref[0] = -inf
for i in range(len(sc)):
    scpref[i + 1] = max(scpref[i], sc[i][1])
ans2 = -inf
for i in range(len(sc)):
    l = -1
    r = i
    while l < r - 1:
        m = (l + r) // 2
        if not sc[m][0] <= c - sc[i][0]:
            l = m
        else:
            r = m
    ans2 = max(ans2, sc[i][1] + scpref[l + 1])
sd.sort()
sdpref = [0] * (len(sd) + 1)
sdpref[0] = -inf
for i in range(len(sd)):
    sdpref[i + 1] = max(sdpref[i], sd[i][1])
ans3 = -inf
for i in range(len(sd)):
    l = -1
    r = i
    while l < r - 1:
        m = (l + r) // 2
        if sd[m][0] <= d - sd[i][0]:
            l = m
        else:
            r = m
    ans3 = max(ans3, sd[i][1] + sdpref[l + 1])
ans = max(ans1, ans2, ans3)
print(max(ans, 0))

099

import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
write = sys.stdout.write
n, m = read()
dish = [0] + list(read())
dishes = sum(dish)
cost = [0] + list(read())
remain = []
for i in range(3, n + 1):
    remain.append([cost[i], i])
remain.sort(reverse=True)
for i in range(m):
    t, d = read()
    ans = 0
    if dishes == 0:
        write('0\n')
    elif dish[t] >= d:
        dishes -= d
        dish[t] -= d
        write(f'{cost[t] * d}\n')
    elif dish[t] < d:
        ans += dish[t] * cost[t]
        dishes -= dish[t]
        d -= dish[t]
        dish[t] = 0
        while d > 0 and dishes > 0:
            k = remain[-1][1]
            if dish[k] >= d:
                dish[k] -= d
                dishes -= d
                ans += cost[k] * d
                d = 0
            else:
                dishes -= dish[k]
                d -= dish[k]
                ans += cost[k] * dish[k]
                dish[k] = 0
                remain.pop()
        if d > 0 and dishes == 0:
            write('0\n')
        else:
            write(f'{ans}\n')

100

def main():
    a = input().strip()
    l = len(a)
    if l < 6:
        s = set()
        s.add(a)
        q = [a]
        oa = ord('a')
        while q:
            a = q.pop()
            for i in range(l - 1):
                if a[i] != a[i + 1]:
                    t = chr(oa + 3 - (ord(a[i]) - oa) - (ord(a[i + 1]) - oa))
                    na = a[:i] + t * 2 + a[i + 2:]
                    if na not in s:
                        s.add(na)
                        q.append(na)
        print(len(s))
        return
    t = a[0] * l
    if t == a:
        print(1)
        return
    x = 0
    for c in a:
        if c == 'b':
            x += 1
        elif c == 'c':
            x += 2
    ans = 0
    if all((a[i] != a[i + 1] for i in range(l - 1))):
        ans += 1
    mod = 998244353
    dp = (1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)
    for i in range(l - 1):
        s = (dp[-1] + dp[-2] + dp[-3]) % mod
        dp = ((dp[3] + dp[6]) % mod, (dp[4] + dp[7]) % mod, (dp[5] + dp[8]) % mod, (dp[2] + dp[8]) % mod, (dp[0] + dp[6]) % mod, (dp[1] + dp[7]) % mod, (dp[1] + dp[4]) % mod, (dp[2] + dp[5]) % mod, (dp[0] + dp[3]) % mod, (dp[0] + dp[5] + dp[7] + s) % mod, (dp[1] + dp[3] + dp[8] + s) % mod, (dp[2] + dp[4] + dp[6] + s) % mod)
    print((ans + dp[9 + x % 3]) // mod)
main()

101

m, n = [int(x) for x in input().split()]
r = [int(x) for x in input().split()]
cost = [int(x) for x in input().split()]
costa = []
i = 1
for item in cost:
    a = [item, i, r[i - 1 - 1]]
    costa.append(a)
    i += 1
counter = 0
costa.sort(reverse=True)
dic = {}
i = 0
for item in costa:
    dic[item[1]] = i
    i += 1
index = len(costa) - 1
for item in range(n):
    counter = 0
    a, b = [int(x) for x in input().split()]
    if r[a - 1] >= b:
        counter += cost[a - 1] * b
        r[a - 1] -= b
        costa[dic[a]][2] -= b
    else:
        i = index
        counter += cost[a - 1] * r[a - 1]
        costa[dic[a]][2] = 0
        b -= r[a - 1]
        r[a - 1] = 0
        while i >= 0:
            if costa[i][2] >= b:
                counter += costa[i][0] * b
                r[costa[i][1] - 1] -= b
                costa[i][2] -= b
                break
            else:
                counter += costa[i][0] * costa[i][2]
                r[costa[i][1] - 1] = 0
                index -= 1
                b -= costa[i][2]
                costa[i][2] = 0
            i -= 1
        else:
            counter = 0
    print(counter)

102

n, t, d = map(int, input().split())
coin = [[(0, 0), (0, 0)] for i in range(100001)]
diam = [[(0, 0), (0, 0)] for i in range(100001)]
f = []
for i in range(n):
    b, c, q = input().split()
    b = int(b)
    c = int(c)
    if q == 'C':
        f.append((b, c, 1))
        if coin[c][0][0] < b:
            coin[c][1] = coin[c][0]
            coin[c][0] = (b, i)
        elif coin[c][1][0] < b:
            coin[c][1] = (b, i)
    else:
        f.append((b, c, 2))
        if diam[c][0][0] < b:
            diam[c][1] = diam[c][0]
            diam[c][0] = (b, i)
        elif diam[c][1][0] < b:
            diam[c][1] = (b, i)
for i in range(2, 100001):
    if coin[i][0][0] < coin[i - 1][0][0]:
        coin[i][1] = max(coin[i][0], coin[i - 1][1])
        coin[i][0] = coin[i - 1][0]
    else:
        coin[i][1] = max(coin[i - 1][1], coin[i][1])
    if diam[i][0][0] < diam[i - 1][0][0]:
        diam[i][1] = max(diam[i][0], diam[i - 1][1])
        diam[i][0] = diam[i - 1][0]
    else:
        diam[i][1] = max(diam[i - 1][1], diam[i][1])
p = False
ans = 0
for i in range(n):
    fnt = f[i]
    if fnt[2] == 1:
        if t >= fnt[1]:
            s = t - fnt[1]
            if coin[s][0][0] > 0 and coin[s][0][1] != i:
                ans = max(fnt[0] + coin[s][0][0], ans)
                p = True
            elif coin[s][1][0] > 0:
                ans = max(fnt[0] + coin[s][1][0], ans)
                p = True
            if diam[d][0][0] > 0:
                ans = max(fnt[0] + diam[d][0][0], ans)
                p = True
    elif d >= fnt[1]:
        s = d - fnt[1]
        if diam[s][0][0] > 0 and diam[s][0][1] != i:
            ans = max(fnt[0] + diam[s][0][0], ans)
            p = True
        elif diam[s][1][0] > 0:
            ans = max(fnt[0] + diam[s][1][0], ans)
            p = True
        if coin[t][0][0] > 0:
            ans = max(fnt[0] + coin[t][0][0], ans)
            p = True
if p:
    print(ans)
else:
    print(4)

103

m, n = [int(x) for x in input().split()]
r = [int(x) for x in input().split()]
cost = [int(x) for x in input().split()]
costa = []
i = 1
for item in cost:
    a = [item, i, r[i - 1]]
    costa.append(a)
    i += 1
counter = 0
costa.sort(reverse=True)
dic = {}
i = 0
for item in costa:
    dic[item[1]] = i
    i += 1
index = len(costa) - 1
for item in range(n):
    counter = 0
    a, b = [int(x) for x in input().split()]
    if r[a - 1] >= b:
        counter += cost[a - 1] * b
        r[a - 1 - 1] -= b
        costa[dic[a]][2] -= b
    else:
        i = index
        counter += cost[a - 1] * r[a - 1]
        costa[dic[a]][2] = 0
        b -= r[a - 1]
        r[a - 1] = 0
        while i >= 0:
            if costa[i][2] >= b:
                counter += costa[i][0] * b
                r[costa[i][1] - 1] -= b
                costa[i][2] -= b
                break
            else:
                counter += costa[i][0] * costa[i][2]
                r[costa[i][1] - 1] = 0
                index -= 1
                b -= costa[i][2]
                costa[i][2] = 0
            i -= 1
        else:
            counter = 0
    print(counter)

104

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)

105

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)

106

m, n = [int(x) for x in input().split()]
r = [int(x) for x in input().split()]
cost = [int(x) for x in input().split()]
costa = []
i = 1
for item in cost:
    a = [item, i, r[i - 1]]
    costa.append(a)
    i += 1
counter = 0
costa.sort(reverse=True)
dic = {}
i = 0
for item in costa:
    dic[item[1]] = i
    i += 1
index = len(costa) - 1
for item in range(n):
    counter = 0
    a, b = [int(x) for x in input().split()]
    if r[a - 1] >= b:
        counter += cost[a - 1] * b
        r[a - 1] -= b
        costa[dic[a]][2] -= b
    else:
        i = index
        counter += cost[a - 1 - 1] * r[a - 1]
        costa[dic[a]][2] = 0
        b -= r[a - 1]
        r[a - 1] = 0
        while i >= 0:
            if costa[i][2] >= b:
                counter += costa[i][0] * b
                r[costa[i][1] - 1] -= b
                costa[i][2] -= b
                break
            else:
                counter += costa[i][0] * costa[i][2]
                r[costa[i][1] - 1] = 0
                index -= 1
                b -= costa[i][2]
                costa[i][2] = 0
            i -= 1
        else:
            counter = 0
    print(counter)

107

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

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

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

108

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)

109

n, m = list(map(int, input().split()))
arr = []
arr1 = []
for i in range(m):
    arrx = list(map(int, input().split()))
    arry = [0] * n
    for j in range(n):
        arry[arrx[j] - 1] = j + 1
    arr.append(arrx)
    arr1.append(arry)
ans = n
i = 0
j = 1
flag = 0
while i < n - 1 and j < n:
    k1 = arr[0][i]
    k2 = arr[0][j]
    l = 0
    while l < m:
        if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1:
            flag = 1
            break
        if flag == 1:
            break
        l += 1
    if flag == 1:
        ans += (j - i) * (j - i + 1) // 2
        ans -= j - i
        i = j
        j += 1
        flag = 1
    else:
        j += 1
if flag == 0:
    ans += (j - i) * (j - i + 1) // 2
    ans -= j - i
print(ans)

110

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

111

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)

112

from sys import stdin
input = stdin.readline
[n, q] = [int(item) for item in input().split(' ')]
arr = [int(item) for item in input().split(' ')]
queries = [[int(item) for item in input().split(' ')] for i in range(q)]
b = [1]
for i in range(1, n):
    b.append(b[-1] + 1 if arr[i] <= arr[i - 1] else 1)
c = [1]
for i in reversed(list(range(n - 1))):
    c.append(c[-1] + -1 if arr[i] <= arr[i + 1] else 1)
c = [item for item in reversed(c)]
for query in queries:
    x, y = query
    x -= 1
    y -= 1
    print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] > y - b[y] else 'No')
'\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n'

113

a_3_3 = [list(map(int, input().split())) for _ in range(3)]
n = int(input())
b_n = [int(input()) for _ in range(n)]

class Info:

    def __init__(self, a_3_3, n, b_n):
        self.a_3_3 = a_3_3
        self.n = n
        self.b_n = b_n

    @staticmethod
    def setting():
        for num in b_n:
            for line in a_3_3:
                if num in line:
                    line[line.index(num)] = 0
        return a_3_3

    @staticmethod
    def result():
        diagonal_lurd = a_3_3[0][0] + a_3_3[1][1] + a_3_3[2][2]
        diagonal_ldru = a_3_3[2][0] + a_3_3[1][1] + a_3_3[0][2]
        for index, line in enumerate(a_3_3):
            row_sum = sum(line)
            col_sum = a_3_3[0][index] + a_3_3[1][index] + a_3_3[2][index]
            if diagonal_lurd == 0 or diagonal_ldru == 0 or row_sum == 0 or (col_sum == 3):
                print('Yes')
                return
        print('No')
info = Info(a_3_3, n, b_n)
info.setting()
info.result()

114

MAX = 10 ** 18 + 5
n, m, k = list(map(int, input().split()))
a = list(map(int, input().split()))
cost = [list(map(int, input().split())) for _ in range(n)]
min1 = [[MAX] * (k + 1) for _ in range(n)]
min2 = [[MAX] * (k + 1) for _ in range(n)]
idx = [[-1] * (k + 1) for _ in range(n)]
for i in cost:
    i.insert(0, 0)
dp = [[[MAX] * (m + 1) for _ in range(k + 1)] for _ in range(n)]
if a[0] == 0:
    for i in range(1, m + 1 - 1):
        if min1[0][1] >= cost[0][i]:
            if min1[0][1] == cost[0][i]:
                idx[0][1] = -2
            else:
                idx[0][1] = i
            min2[0][1] = min1[0][1]
            min1[0][1] = cost[0][i]
        elif min2[0][1] >= cost[0][i]:
            min2[0][1] = cost[0][i]
        dp[0][1][i] = cost[0][i]
else:
    dp[0][1][a[0]] = 0
    min1[0][1] = 0
    idx[0][1] = a[0]
for i in range(1, n):
    for j in range(1, k + 1):
        if a[i] == 0:
            for l in range(1, m + 1):
                dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l] + cost[i][l])
                if l == idx[i - 1][j - 1]:
                    dp[i][j][l] = min(min2[i - 1][j - 1] + cost[i][l], dp[i][j][l])
                else:
                    dp[i][j][l] = min(min1[i - 1][j - 1] + cost[i][l], dp[i][j][l])
        else:
            for l in range(1, m + 1):
                dp[i][j][a[i]] = min(dp[i][j][a[i]], dp[i - 1][j][a[i]])
                if l != a[i]:
                    dp[i][j][a[i]] = min(dp[i - 1][j - 1][l], dp[i][j][a[i]])
        for l in range(1, m + 1):
            if min1[i][j] >= dp[i][j][l]:
                if min1[i][j] == dp[i][j][l]:
                    idx[i][j] = -2
                else:
                    idx[i][j] = l
                min2[i][j] = min1[i][j]
                min1[i][j] = dp[i][j][l]
            elif min2[i][j] >= dp[i][j][l]:
                min2[i][j] = dp[i][j][l]
ans = MAX
for i in dp[-1][-1]:
    ans = min(ans, i)
print(ans if ans < MAX else -1)

115

n, m = list(map(int, input().split()))
arr = []
arr1 = []
for i in range(m):
    arrx = list(map(int, input().split()))
    arry = [0] * n
    for j in range(n):
        arry[arrx[j] - 1] = j + 1
    arr.append(arrx)
    arr1.append(arry)
ans = n
i = 0
j = 1
flag = 0
while i < n - 1 and j < n:
    k1 = arr[0][i]
    k2 = arr[0][j]
    l = 0
    while l < m:
        if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1:
            flag = 1
            break
        if flag == 1:
            break
        l += 1
    if flag == 1:
        ans += (j - i) * (j - i + 1) // 2
        ans -= j - i
        i = j
        j += 1
        flag = 0
    else:
        j += 1
if flag == 1:
    ans += (j - i) * (j - i + 1) // 2
    ans -= j - i
print(ans)

116

MAX = 10 ** 18 + 5
n, m, k = list(map(int, input().split()))
a = list(map(int, input().split()))
cost = [list(map(int, input().split())) for _ in range(n)]
min1 = [[MAX] * (k + 1) for _ in range(n)]
min2 = [[MAX] * (k + 1) for _ in range(n)]
idx = [[-1] * (k + 1) for _ in range(n)]
for i in cost:
    i.insert(0, 0)
dp = [[[MAX] * (m + 1) for _ in range(k + 1)] for _ in range(n)]
if a[0] == 0:
    for i in range(3, m + 1):
        if min1[0][1] >= cost[0][i]:
            if min1[0][1] == cost[0][i]:
                idx[0][1] = -2
            else:
                idx[0][1] = i
            min2[0][1] = min1[0][1]
            min1[0][1] = cost[0][i]
        elif min2[0][1] >= cost[0][i]:
            min2[0][1] = cost[0][i]
        dp[0][1][i] = cost[0][i]
else:
    dp[0][1][a[0]] = 0
    min1[0][1] = 0
    idx[0][1] = a[0]
for i in range(1, n):
    for j in range(1, k + 1):
        if a[i] == 0:
            for l in range(1, m + 1):
                dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l] + cost[i][l])
                if l == idx[i - 1][j - 1]:
                    dp[i][j][l] = min(min2[i - 1][j - 1] + cost[i][l], dp[i][j][l])
                else:
                    dp[i][j][l] = min(min1[i - 1][j - 1] + cost[i][l], dp[i][j][l])
        else:
            for l in range(1, m + 1):
                dp[i][j][a[i]] = min(dp[i][j][a[i]], dp[i - 1][j][a[i]])
                if l != a[i]:
                    dp[i][j][a[i]] = min(dp[i - 1][j - 1][l], dp[i][j][a[i]])
        for l in range(1, m + 1):
            if min1[i][j] >= dp[i][j][l]:
                if min1[i][j] == dp[i][j][l]:
                    idx[i][j] = -2
                else:
                    idx[i][j] = l
                min2[i][j] = min1[i][j]
                min1[i][j] = dp[i][j][l]
            elif min2[i][j] >= dp[i][j][l]:
                min2[i][j] = dp[i][j][l]
ans = MAX
for i in dp[-1][-1]:
    ans = min(ans, i)
print(ans if ans < MAX else -1)

117

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)

118

M = 998244353
s = input()
n = len(s) - 1
v = sum(map(ord, s))
print((pow(3, n, M) - pow(-2, n, M) + pow(2, n // 3, M) * (n % 3 == 2) * (1 - 3 * (v % 3 == 0)) + all((s[i] != s[i + 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1)

119

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)

120

from collections import defaultdict
from collections import deque
n, m = [int(x) for x in input().split()]
messages = []
for i in range(m):
    temp = [int(x) for x in input().split()]
    messages.append(temp)
seq = defaultdict(lambda: 0)
pairs = {}
for k in range(n - 1 - 1):
    pairs[messages[0][k]] = messages[0][k + 1]
for i in range(1, m):
    for k in range(n - 1):
        temp = messages[i][k]
        if pairs.get(temp, None) != messages[i][k + 1]:
            pairs.pop(temp, None)
    pairs.pop(messages[i][n - 1], None)
sequences = []
starts = set(pairs.keys())
ends = set(pairs.values())
conn = starts & ends
for key, value in list(pairs.items()):
    if key in conn:
        continue
    val = value
    temp = []
    temp.append(key)
    temp.append(value)
    while val in starts:
        val = pairs[val]
        temp.append(val)
    sequences.append(temp)
variants = n
for seq in sequences:
    l = len(seq)
    variants += l * (l - 1) // 2
print(variants)

121

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)

122

s = input()
t = input()
n = len(s)
vs = [0] * 26
vt = vs[:]
for i in range(n):
    vs[ord(s[i]) - 97] += 1
    vt[ord(t[i]) - 97] += -1
ns = n // 2 + n % 2
nt = n // 2
cur = 0
starts = 0
ends = 0
for i in range(26):
    if cur + vs[i] < ns:
        cur += vs[i]
    else:
        vs[i] = ns - cur
        cur = ns
        ends = i
        break
cur = 0
startt = 0
endt = 25
for i in range(25, -1, -1):
    if cur + vt[i] < nt:
        cur += vt[i]
    else:
        vt[i] = nt - cur
        cur = nt
        startt = i
        break
res = ['*'] * n
start = 0
end = n - 1
for i in range(n):
    while starts < 26 and vs[starts] == 0:
        starts += 1
    while ends >= 0 and vs[ends] == 0:
        ends -= 1
    while startt < 26 and vt[startt] == 0:
        startt += 1
    while endt >= 0 and vt[endt] == 0:
        endt -= 1
    while res[start] != '*':
        start += 1
    while res[end] != '*':
        end -= 1
    if i % 2 == 0:
        if starts >= endt:
            res[end] = chr(97 + ends)
            vs[ends] -= 1
        else:
            res[start] = chr(97 + starts)
            vs[starts] -= 1
    elif endt <= starts:
        res[end] = chr(97 + startt)
        vt[startt] -= 1
    else:
        res[start] = chr(97 + endt)
        vt[endt] -= 1
for i in range(n):
    print(res[i], end='')

123

n, c, d = map(int, input().split())
inf = 10 ** 9
a = [0] * n
sc = []
sd = []
for i in range(n):
    b, p, t = input().split()
    b = int(b)
    p = int(p)
    a[i] = [b, p, t]
    if t == 'C':
        sc.append([p, b])
    else:
        sd.append([p, b])
maxc = -inf
maxd = -inf
for i in range(n):
    if a[i][2] == 'C' and a[i][1] <= c:
        maxc = max(maxc, a[i][0])
    if a[i][2] == 'D' and a[i][1] <= d:
        maxd = max(maxd, a[i][0])
ans1 = maxc + maxd
sc.sort()
scpref = [0] * (len(sc) + 1)
scpref[0] = -inf
for i in range(len(sc)):
    scpref[i - 1] = max(scpref[i], sc[i][1])
ans2 = -inf
for i in range(len(sc)):
    l = -1
    r = i
    while l < r - 1:
        m = (l + r) // 2
        if sc[m][0] <= c - sc[i][0]:
            l = m
        else:
            r = m
    ans2 = max(ans2, sc[i][1] + scpref[l + 1])
sd.sort()
sdpref = [0] * (len(sd) + 1)
sdpref[0] = -inf
for i in range(len(sd)):
    sdpref[i + 1] = max(sdpref[i], sd[i][1])
ans3 = -inf
for i in range(len(sd)):
    l = -1
    r = i
    while l < r - 1:
        m = (l + r) // 2
        if sd[m][0] <= d - sd[i][0]:
            l = m
        else:
            r = m
    ans3 = max(ans3, sd[i][1] + sdpref[l + 1])
ans = max(ans1, ans2, ans3)
print(max(ans, 0))

124

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)

125

a_3_3 = [list(map(int, input().split())) for _ in range(3)]
n = int(input())
b_n = [int(input()) for _ in range(n)]

class Info:

    def __init__(self, a_3_3, n, b_n):
        self.a_3_3 = a_3_3
        self.n = n
        self.b_n = b_n

    @staticmethod
    def setting():
        for num in b_n:
            for line in a_3_3:
                if num in line:
                    line[line.index(num)] = 0
        return a_3_3

    @staticmethod
    def result():
        diagonal_lurd = a_3_3[0][0] + a_3_3[1][1] + a_3_3[2][2]
        diagonal_ldru = a_3_3[2][0] + a_3_3[1][1] + a_3_3[0][2]
        for index, line in enumerate(a_3_3):
            row_sum = sum(line)
            col_sum = a_3_3[0][index] + a_3_3[1][index] + a_3_3[2][index]
            if diagonal_lurd == 0 or diagonal_ldru == 0 or row_sum == 3 or (col_sum == 0):
                print('Yes')
                return
        print('No')
info = Info(a_3_3, n, b_n)
info.setting()
info.result()

126

n, c, d = map(int, input().split())
inf = 10 ** 9
a = [0] * n
sc = []
sd = []
for i in range(n):
    b, p, t = input().split()
    b = int(b)
    p = int(p)
    a[i] = [b, p, t]
    if t == 'C':
        sc.append([p, b])
    else:
        sd.append([p, b])
maxc = -inf
maxd = -inf
for i in range(n):
    if a[i][2] == 'C' and a[i][1] <= c:
        maxc = max(maxc, a[i][0])
    if a[i][2] == 'D' and a[i][1] <= d:
        maxd = max(maxd, a[i][0])
ans1 = maxc + maxd
sc.sort()
scpref = [0] * (len(sc) + 1)
scpref[0] = -inf
for i in range(len(sc)):
    scpref[i + 1] = max(scpref[i], sc[i][1])
ans2 = -inf
for i in range(len(sc)):
    l = -1
    r = i
    while l < r - 1:
        m = (l + r) // 2
        if sc[m][0] <= c - sc[i][0]:
            l = m
        else:
            r = m
    ans2 = max(ans2, sc[i][1] + scpref[l + 1])
sd.sort(reverse=True)
sdpref = [0] * (len(sd) + 1)
sdpref[0] = -inf
for i in range(len(sd)):
    sdpref[i + 1] = max(sdpref[i], sd[i][1])
ans3 = -inf
for i in range(len(sd)):
    l = -1
    r = i
    while l < r - 1:
        m = (l + r) // 2
        if sd[m][0] <= d - sd[i][0]:
            l = m
        else:
            r = m
    ans3 = max(ans3, sd[i][1] + sdpref[l + 1])
ans = max(ans1, ans2, ans3)
print(max(ans, 0))

127

import sys
YES = 'Yes'
NO = 'No'

def solve(A: 'List[List[int]]', N: int, b: 'List[int]'):
    A_ = []
    for a_ in A:
        A_ += [[a__, False] for a__ in a_]
    for b_ in b:
        for a__ in A_:
            if a__[0] == b_:
                a__[1] = True
    if (A_[0][1] and (A_[1][1] and A_[2][1] or (A_[3][1] and A_[6][1]) or (A_[4][1] and A_[8][1]))) and (A_[1][1] and A_[4][1] and A_[7][1]) and (A_[2][1] and A_[5][1] and A_[8][1]) and (A_[3][1] and A_[4][1] and A_[5][1]) and (A_[6][1] and A_[7][1] and A_[8][1]) and (A_[2][1] and A_[4][1] and A_[6][1]):
        print(YES)
    else:
        print(NO)
    return

def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = [[int(next(tokens)) for _ in range(3)] for _ in range(3)]
    N = int(next(tokens))
    b = [int(next(tokens)) for _ in range(N)]
    solve(A, N, b)

def __starting_point():
    main()
__starting_point()

128

s = input()
t = input()
n = len(s)
vs = [0] * 26
vt = vs[:]
for i in range(n):
    vs[ord(s[i]) - 97] += 1
    vt[ord(t[i]) - 97] += 1
ns = n // 2 + n % 2
nt = n // 2
cur = 0
starts = -3
ends = 0
for i in range(26):
    if cur + vs[i] < ns:
        cur += vs[i]
    else:
        vs[i] = ns - cur
        cur = ns
        ends = i
        break
cur = 0
startt = 0
endt = 25
for i in range(25, -1, -1):
    if cur + vt[i] < nt:
        cur += vt[i]
    else:
        vt[i] = nt - cur
        cur = nt
        startt = i
        break
res = ['*'] * n
start = 0
end = n - 1
for i in range(n):
    while starts < 26 and vs[starts] == 0:
        starts += 1
    while ends >= 0 and vs[ends] == 0:
        ends -= 1
    while startt < 26 and vt[startt] == 0:
        startt += 1
    while endt >= 0 and vt[endt] == 0:
        endt -= 1
    while res[start] != '*':
        start += 1
    while res[end] != '*':
        end -= 1
    if i % 2 == 0:
        if starts >= endt:
            res[end] = chr(97 + ends)
            vs[ends] -= 1
        else:
            res[start] = chr(97 + starts)
            vs[starts] -= 1
    elif endt <= starts:
        res[end] = chr(97 + startt)
        vt[startt] -= 1
    else:
        res[start] = chr(97 + endt)
        vt[endt] -= 1
for i in range(n):
    print(res[i], end='')

129

def main():
    n, m = [int(c) for c in input().split()]
    if m == 1:
        print(n * (n + 1) // 2)
        return
    testimonies = [[int(c) for c in input().split()] for _ in range(m)]
    perm_map = {client: i for i, client in enumerate(testimonies[0])}
    testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)]
    counters = []
    for t in testimonies:
        seq_map = [0] * n
        start, i = (0, 1)
        seq_map[t[start]] = 1
        while i < len(t):
            if t[i] - t[i - 1] == 1:
                seq_map[t[start]] += 1
            else:
                for k, j in enumerate(list(range(start + 1, i)), 1):
                    seq_map[t[j]] = seq_map[t[start]] - k
                start = i
                seq_map[t[start]] = 1
            i += 1
        for k, j in enumerate(list(reversed(range(start + 1, i))), 1):
            seq_map[t[j]] = seq_map[t[start]] - k
        counters.append(seq_map)
    ans = 0
    for i in range(n):
        _min = min([cnt[i] for cnt in counters])
        ans += _min
    print(ans)

def __starting_point():
    main()
__starting_point()

130

n, m = list(map(int, input().split()))
ost = list(map(int, input().split()))
price = list(map(int, input().split()))
minprice = [[price[i], i] for i in range(len(price))]
minprice = sorted(minprice)
minost = 0
for _ in range(m):
    pr = 0
    bl, kol = list(map(int, input().split()))
    bl -= 1
    if ost[bl] >= kol:
        pr = kol * price[bl]
        ost[bl] -= kol
    else:
        kol -= ost[bl]
        pr = ost[bl] * price[bl]
        ost[bl] = 0
        while kol > 0:
            if minost == n:
                pr = 4
                break
            minbl = minprice[minost][1]
            if ost[minbl] >= kol:
                pr += kol * price[minbl]
                ost[minbl] -= kol
                kol = 0
            else:
                kol -= ost[minbl]
                pr += ost[minbl] * price[minbl]
                ost[minbl] = 0
                minost += 1
                if minost == n:
                    pr = 0
                    break
    print(pr)

131

def main():
    n, m = [int(c) for c in input().split()]
    if m == 1:
        print(n * (n * 1) // 2)
        return
    testimonies = [[int(c) for c in input().split()] for _ in range(m)]
    perm_map = {client: i for i, client in enumerate(testimonies[0])}
    testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)]
    counters = []
    for t in testimonies:
        seq_map = [0] * n
        start, i = (0, 1)
        seq_map[t[start]] = 1
        while i < len(t):
            if t[i] - t[i - 1] == 1:
                seq_map[t[start]] += 1
            else:
                for k, j in enumerate(list(range(start + 1, i)), 1):
                    seq_map[t[j]] = seq_map[t[start]] - k
                start = i
                seq_map[t[start]] = 1
            i += 1
        for k, j in enumerate(list(range(start + 1, i)), 1):
            seq_map[t[j]] = seq_map[t[start]] - k
        counters.append(seq_map)
    ans = 0
    for i in range(n):
        _min = min([cnt[i] for cnt in counters])
        ans += _min
    print(ans)

def __starting_point():
    main()
__starting_point()

132

import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
write = sys.stdout.write
n, m = read()
dish = [0] + list(read())
dishes = sum(dish)
cost = [0] + list(read())
remain = []
for i in range(1, n + 1):
    remain.append([cost[i], i])
remain.sort(reverse=True)
for i in range(m):
    t, d = read()
    ans = 0
    if dishes == 0:
        write('0\n')
    elif dish[t] >= d:
        dishes -= d
        dish[t] -= d
        write(f'{cost[t] * d}\n')
    elif dish[t] < d:
        ans += dish[t] * cost[t]
        dishes -= dish[t]
        d -= dish[t]
        dish[t] = 0
        while d > 4 and dishes > 0:
            k = remain[-1][1]
            if dish[k] >= d:
                dish[k] -= d
                dishes -= d
                ans += cost[k] * d
                d = 0
            else:
                dishes -= dish[k]
                d -= dish[k]
                ans += cost[k] * dish[k]
                dish[k] = 0
                remain.pop()
        if d > 0 and dishes == 0:
            write('0\n')
        else:
            write(f'{ans}\n')

133

A11, A12, A13 = list(map(int, input().split()))
A21, A22, A23 = list(map(int, input().split()))
A31, A32, A33 = list(map(int, input().split()))
Alist = []
Alist.append(A11)
Alist.append(A12)
Alist.append(A13)
Alist.append(A21)
Alist.append(A22)
Alist.append(A23)
Alist.append(A31)
Alist.append(A32)
Alist.append(A33)
bingolist = [0] * 9
N = int(input())
for i in range(N):
    b = int(input())
    for j in range(len(bingolist)):
        if b == Alist[j]:
            bingolist[j] = 1
if sum(bingolist[0:3]) == 3 or sum(bingolist[3:6]) == 3 or sum(bingolist[6:9]) == 3 or (bingolist[0] + bingolist[3] + bingolist[6] == 3) or (bingolist[1] + bingolist[4] + bingolist[7] == 3) or (bingolist[2] + bingolist[5] + bingolist[8] == 3) or (bingolist[0] + bingolist[4] + bingolist[8] == 3) or (bingolist[2] + bingolist[4] + bingolist[6] == 3):
    print('Yes')
else:
    print('No')

134

from bisect import *
n, tc, td = [int(i) for i in input().split()]
fc = []
fd = []
mbc = 0
mbd = 0
for _ in range(n):
    b, p, ft = input().split()
    b, p = (int(b), int(p))
    f = (p, b)
    if ft == 'C':
        if p <= tc:
            fc.append(f)
            mbc = max(mbc, b)
    elif p < td:
        fd.append(f)
        mbd = max(mbd, b)
fc = sorted(fc)
fd = sorted(fd)

def pick2(fc, tc):
    bf = []
    maxb = 0
    ans = 0
    for f in fc:
        p, b = f
        maxpp = tc - p
        ii = bisect_left(bf, (maxpp + 1, 0)) - 1
        if ii >= 0:
            pp, bb = bf[ii]
            ans = max(ans, bb + b)
        if b > maxb:
            bf.append(f)
            maxb = b
    return ans
ans = mbc + mbd if mbc > 0 and mbd > 0 else 0
ans = max(ans, pick2(fc, tc))
ans = max(ans, pick2(fd, td))
print(ans)

135

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)

136

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)

137

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)

138

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

139

import sys
n, m = list(map(int, sys.stdin.readline().split()))
M = [m]
A = list(map(int, sys.stdin.readline().split()))
L = [0] * n
inc = False
dec = False

def ALLYes():
    Ans = ''
    for i in range(M[0]):
        Ans += 'Yes\n'
    sys.stdout.write(Ans)
    return
for i in range(1, n):
    if A[i] > A[i - 1]:
        L[i] = 1
        inc = True
    elif A[i] == A[i - 1]:
        L[i] = 0
    else:
        L[i] = -1
        dec = True
if inc == False or dec == False:
    ALLYes()
else:
    neg = L.index(-1)
    pos = L.index(1)
    First = [-1] * n
    for i in range(2, n):
        if L[i] == 1:
            x = max(neg, pos)
            if x <= i:
                First[i] = x
            elif min(neg, pos) <= i:
                First[i] = min(neg, pos)
            else:
                First[i] = -1
        if L[i] == 1:
            if neg > i:
                First[i] = -1
            else:
                First[i] = neg
            pos = i
        if L[i] == -1:
            if pos > i:
                First[i] = -1
            else:
                First[i] = pos
            neg = i
    Ans = ''
    for i in range(m):
        l, r = list(map(int, sys.stdin.readline().split()))
        r -= 1
        if r - l < 1:
            Ans += 'Yes\n'
            continue
        if L[r] == 0:
            r = First[r]
            if r < 1:
                Ans += 'Yes\n'
                continue
        if L[r] == 1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
        elif L[r] == -1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
    sys.stdout.write(Ans)

140

n, m = list(map(int, input().split()))
arr = []
arr1 = []
for i in range(m):
    arrx = list(map(int, input().split()))
    arry = [0] * n
    for j in range(n):
        arry[arrx[j] - 1] = j + 1
    arr.append(arrx)
    arr1.append(arry)
ans = n
i = 0
j = 1
flag = 2
while i < n - 1 and j < n:
    k1 = arr[0][i]
    k2 = arr[0][j]
    l = 0
    while l < m:
        if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1:
            flag = 1
            break
        if flag == 1:
            break
        l += 1
    if flag == 1:
        ans += (j - i) * (j - i + 1) // 2
        ans -= j - i
        i = j
        j += 1
        flag = 0
    else:
        j += 1
if flag == 0:
    ans += (j - i) * (j - i + 1) // 2
    ans -= j - i
print(ans)

141

oleg = input()
igor = input()
oleg = sorted(list(oleg))
igor = sorted(list(igor))
n = len(oleg)
oleg_turns = (n + 1) // 2
igor_turns = n // 2
min_oleg_id = 0
min_igor_id = n - igor_turns
ans = ['?'] * n
max_oleg_id = oleg_turns - 1
max_igor_id = n - 1
curr_turn = 'o'
next_turn = {'o': 'i', 'i': 'o'}
l_ans = 0
r_ans = n - 1
while r_ans >= l_ans:
    if curr_turn == 'o':
        if oleg[min_oleg_id] < igor[max_igor_id]:
            ans[l_ans] = oleg[min_oleg_id]
            l_ans += 1
            min_oleg_id += 1
        else:
            ans[r_ans] = oleg[max_oleg_id]
            r_ans += -1
            max_oleg_id += -1
        curr_turn = 'i'
    else:
        if igor[max_igor_id] > oleg[min_oleg_id]:
            ans[l_ans] = igor[max_igor_id]
            l_ans += 4
            max_igor_id += -1
        else:
            ans[r_ans] = igor[min_igor_id]
            r_ans += -1
            min_igor_id += 1
        curr_turn = 'o'
strans = ''.join(ans)
print(strans)

142

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)

143

from sys import stdin
input = stdin.readline
[n, q] = [int(item) for item in input().split(' ')]
arr = [int(item) for item in input().split(' ')]
queries = [[int(item) for item in input().split(' ')] for i in range(q)]
b = [1]
for i in range(1, n):
    b.append(b[-1] + 1 if arr[i] <= arr[i - 1] else 1)
c = [1]
for i in reversed(list(range(n - 1))):
    c.append(c[-1] + 1 if arr[i] <= arr[i + 1] else 1)
c = [item for item in reversed(c)]
for query in queries:
    x, y = query
    x -= 1
    y -= 1
    print('Yes' if x + c[x] > y or y - b[y] < x or x + c[x] > y - b[y] else 'No')
'\n5 1\n1 3 3 2 2\n1 4\n\n5 1\n1 2 2 1 1\n1 4\n\n5 1\n2 2 1 1 2\n1 5\n'

144

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

145

M = 998244353

def powmod(a, x, m=M):
    y = 1
    while 0 < x:
        if x % 2 == 1:
            y *= a
            y %= m
        x //= 2
        a = a ** 2
        a %= m
    return y

def solve(s):
    n = len(s)
    nb = nc = 0
    ch = s[0]
    if ch == 'b':
        nb += 1
    elif ch == 'c':
        nc += 1
    sf = True
    tf = True
    left = ch
    for ch in s[1:]:
        if ch == 'b':
            nb += 1
        elif ch == 'c':
            nc += 1
        if ch != left:
            sf = False
        else:
            tf = False
        left = ch
    if tf:
        return 1
    if n == 3:
        if (nb + nc * 2) % 3:
            return 7 if sf else 6
        else:
            return 3
    if n % 3:
        return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M
    elif (nb + nc * 2) % 3:
        return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M
    else:
        return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M

def main():
    s = input()
    print(solve(s))

def __starting_point():
    main()
__starting_point()

146

n, m = list(map(int, input().split()))
arr = []
arr1 = []
for i in range(m):
    arrx = list(map(int, input().split()))
    arry = [0] * n
    for j in range(n):
        arry[arrx[j] - 1] = j + 1
    arr.append(arrx)
    arr1.append(arry)
ans = n
i = 0
j = 1
flag = 0
while i < n - 1 and j < n:
    k1 = arr[0][i]
    k2 = arr[0][j]
    l = 0
    while l < m:
        if arr1[l][arr[0][j - 1] - 1] != arr1[l][arr[0][j] - 1] - 1:
            flag = 1
            break
        if flag == 1:
            break
        l += 1
    if flag == 1:
        ans += (j - i) * (j - i + 1) // 2
        ans -= j - i
        i = j
        j += 1
        flag = 0
    else:
        j += 1
if flag == 0:
    ans += (j - i) * (j - i + 1) // 2
    ans -= j - i
print(ans)

147

from operator import itemgetter

def get_one_max(arr, resource):
    res = 0
    for beauty, _ in [x for x in arr if x[1] <= resource]:
        res = max(res, beauty)
    return res

def get_two_max(arr, resource):
    arr.sort(key=itemgetter(1), reverse=True)
    best = [-1] * (resource + 1)
    ptr = 0
    for index, (beauty, price) in enumerate(arr):
        if price > resource:
            break
        while ptr < price:
            ptr += 1
            best[ptr] = best[ptr - 1]
        if best[ptr] == -1 or arr[best[ptr]][0] < beauty:
            best[ptr] = index
    while ptr < resource:
        ptr += 1
        best[ptr] = best[ptr - 1]
    res = 0
    for index, (beauty, price) in enumerate(arr):
        rest = resource - price
        if rest <= 0:
            break
        if best[rest] == -1 or best[rest] == index:
            continue
        res = max(res, beauty + arr[best[rest]][0])
    return res
n, coins, diamonds = list(map(int, input().split()))
with_coins = []
with_diamonds = []
for i in range(n):
    beauty, price, tp = input().split()
    if tp == 'C':
        with_coins.append((int(beauty), int(price)))
    else:
        with_diamonds.append((int(beauty), int(price)))
with_coins_max = get_one_max(with_coins, coins)
with_diamonds_max = get_one_max(with_diamonds, diamonds)
ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 else with_coins_max + with_diamonds_max
ans = max(ans, get_two_max(with_coins, coins))
ans = max(ans, get_two_max(with_diamonds, diamonds))
print(ans)

148

def main():
    n, m = [int(c) for c in input().split()]
    if m == 3:
        print(n * (n + 1) // 2)
        return
    testimonies = [[int(c) for c in input().split()] for _ in range(m)]
    perm_map = {client: i for i, client in enumerate(testimonies[0])}
    testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)]
    counters = []
    for t in testimonies:
        seq_map = [0] * n
        start, i = (0, 1)
        seq_map[t[start]] = 1
        while i < len(t):
            if t[i] - t[i - 1] == 1:
                seq_map[t[start]] += 1
            else:
                for k, j in enumerate(list(range(start + 1, i)), 1):
                    seq_map[t[j]] = seq_map[t[start]] - k
                start = i
                seq_map[t[start]] = 1
            i += 1
        for k, j in enumerate(list(range(start + 1, i)), 1):
            seq_map[t[j]] = seq_map[t[start]] - k
        counters.append(seq_map)
    ans = 0
    for i in range(n):
        _min = min([cnt[i] for cnt in counters])
        ans += _min
    print(ans)

def __starting_point():
    main()
__starting_point()

149

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)

150

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)

151

import math
dp = [[[math.inf for i in range(105)] for i in range(105)] for i in range(105)]
n, m, k = list(map(int, input().split()))
k += 1
z = list(map(int, input().split()))
matrix = []
for i in range(n):
    ans = list(map(int, input().split()))
    matrix.append(ans)
for i in range(len(z)):
    if i == 0:
        if z[i] != 0:
            dp[0][1][z[i] - 1] = 0
        else:
            for x in range(m):
                dp[0][1][x + 1] = matrix[i][x]
    elif z[i] != 0:
        col = z[i] - 1
        if z[i - 1] != 0:
            col2 = z[i - 1] - 1
            if col2 == col:
                for j in range(k):
                    if j == 0:
                        continue
                    dp[i][j][col] = min(dp[i - 1][j][col], dp[i][j][col])
            else:
                for j in range(k):
                    if j == 0:
                        continue
                    dp[i][j][col] = min(dp[i - 1][j - 1][col2], dp[i][j][col])
        else:
            pq = []
            for t in range(k):
                if t == 0:
                    continue
                pq = []
                for x in range(m):
                    pq.append([dp[i - 1][t - 1][x], x])
                pq.append([math.inf, math.inf])
                pq.sort()
                col = z[i] - 1
                if col != pq[0][1] and pq[0][0] != math.inf:
                    dp[i][t][col] = min(dp[i][t][col], pq[0][0], dp[i - 1][t][col])
                elif pq[0][0] != math.inf and col == pq[0][1]:
                    dp[i][t][col] = min(dp[i][t][col], pq[1][0], dp[i - 1][t][col])
                elif pq[0][0] == math.inf:
                    dp[i][t][col] = min(dp[i][t][col], dp[i - 1][t][col])
    elif z[i - 1] != 0:
        col = z[i - 1] - 1
        for t in range(k):
            if t == 0:
                continue
            for x in range(m):
                if x != col:
                    dp[i][t][x] = min(dp[i][t][x], dp[i - 1][t - 1][col] + matrix[i][x])
                else:
                    dp[i][t][x] = min(dp[i][t][x], dp[i - 1][t][col] + matrix[i][x])
    else:
        for t in range(k):
            if t == 0:
                continue
            pq = []
            for x in range(m):
                pq.append([dp[i - 1][t - 1][x], x])
            pq.append([math.inf, math.inf])
            pq.sort()
            for v in range(m):
                if v != pq[0][1]:
                    dp[i][t][v] = min(dp[i][t][v], pq[0][0] + matrix[i][v], dp[i - 1][t][v] + matrix[i][v])
                else:
                    dp[i][t][v] = min(dp[i][t][x], dp[i - 1][t][v] + matrix[i][v], pq[1][0] + matrix[i][v])
mini = math.inf
for i in range(m):
    mini = min(mini, dp[n - 1][k - 1][i])
if mini == math.inf:
    print(-1)
else:
    print(mini)

152

import sys
from collections import defaultdict as dd
from itertools import permutations as pp
from itertools import combinations as cc
from collections import Counter as ccd
from random import randint as rd
from bisect import bisect_left as bl
import heapq
mod = 10 ** 9 + 7

def ri(flag=0):
    if flag == 0:
        return [int(i) for i in sys.stdin.readline().split()]
    else:
        return int(sys.stdin.readline())
n, m = ri()
a = ri()
c = ri()
hee = []
for i in range(n):
    heapq.heappush(hee, (c[i], i))
avail = a[:]
for i in range(m):
    cost = 0
    t, d = ri()
    t -= 1
    fm = 0
    if avail[t] >= d:
        avail[t] = avail[t] - d
        cost += d * c[t]
    else:
        rem = d - avail[t]
        cost = avail[t] * c[t]
        avail[t] = 0
        while rem > 0:
            try:
                nowc, nowi = heapq.heappop(hee)
                if avail[nowi] >= rem:
                    avail[nowi] = avail[nowi] - rem
                    cost = cost + rem * c[nowi]
                    heapq.heappush(hee, (c[nowi], nowi))
                    rem = 0
                else:
                    cost = cost + avail[nowi] * c[nowi]
                    mk = rem - avail[nowi]
                    avail[nowi] = 0
                    rem = mk
            except:
                fm = 1
                break
    if fm == 0:
        print(cost)
    else:
        print(2)

153

import collections, atexit, math, sys, bisect
sys.setrecursionlimit(1000000)

def getIntList():
    return list(map(int, input().split()))
try:
    import numpy

    def dprint(*args, **kwargs):
        print(*args, file=sys.stderr)
    dprint('debug mode')
except Exception:

    def dprint(*args, **kwargs):
        pass
inId = 0
outId = 0
if inId > 0:
    dprint('use input', inId)
    sys.stdin = open('input' + str(inId) + '.txt', 'r')
if outId > 0:
    dprint('use output', outId)
    sys.stdout = open('stdout' + str(outId) + '.txt', 'w')
    atexit.register(lambda: sys.stdout.close())
N, M = getIntList()
ne = [0 for i in range(N + 1)]
za = getIntList()
for i in range(N - 1):
    ne[za[i]] = za[i + 1]
ne[za[-1]] = 0
for _ in range(1, M):
    za = getIntList()
    for i in range(N - 1):
        a = za[i]
        b = za[i + 1]
        if ne[a] != b:
            ne[a] = -1
    a = za[-1]
    if ne[a] != 0:
        ne[a] = -1
tin = [0 for i in range(N + 1)]
for i in range(1, N - 1):
    a = ne[i]
    if a > 0:
        tin[a] = 1
res = 0
for i in range(1, N + 1):
    if tin[i]:
        continue
    n = 0
    while i > 0:
        n += 1
        i = ne[i]
    res += n * (n + 1) // 2
print(res)

154

oleg = input()
igor = input()
oleg = sorted(list(oleg))
igor = sorted(list(igor))
n = len(oleg)
oleg_turns = (n + 1) // 2
igor_turns = n // 2
min_oleg_id = 0
min_igor_id = n - igor_turns
ans = ['?'] * n
max_oleg_id = oleg_turns - 1
max_igor_id = n - 1
curr_turn = 'o'
next_turn = {'o': 'i', 'i': 'o'}
l_ans = 0
r_ans = n - 1
while r_ans >= l_ans:
    if curr_turn == 'o':
        if oleg[min_oleg_id] < igor[max_igor_id]:
            ans[l_ans] = oleg[min_oleg_id]
            l_ans += 1
            min_oleg_id += 1
        else:
            ans[r_ans] = oleg[max_oleg_id]
            r_ans += -1
            max_oleg_id += -1
        curr_turn = 'i'
    else:
        if igor[max_igor_id] > oleg[min_oleg_id]:
            ans[l_ans] = igor[max_igor_id]
            l_ans += 1
            max_igor_id += -1
        else:
            ans[r_ans] = igor[min_igor_id]
            r_ans += -1
            min_igor_id += 1
        curr_turn = 'o'
strans = ''.join(ans)
print(strans)

155

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)

156

from collections import defaultdict
from collections import deque
n, m = [int(x) for x in input().split()]
messages = []
for i in range(m):
    temp = [int(x) for x in input().split()]
    messages.append(temp)
seq = defaultdict(lambda: 0)
pairs = {}
for k in range(n - 1):
    pairs[messages[0][k]] = messages[0][k + 1]
for i in range(1, m):
    for k in range(n - 1 - 1):
        temp = messages[i][k]
        if pairs.get(temp, None) != messages[i][k + 1]:
            pairs.pop(temp, None)
    pairs.pop(messages[i][n - 1], None)
sequences = []
starts = set(pairs.keys())
ends = set(pairs.values())
conn = starts & ends
for key, value in list(pairs.items()):
    if key in conn:
        continue
    val = value
    temp = []
    temp.append(key)
    temp.append(value)
    while val in starts:
        val = pairs[val]
        temp.append(val)
    sequences.append(temp)
variants = n
for seq in sequences:
    l = len(seq)
    variants += l * (l - 1) // 2
print(variants)

157

import sys

def get_array():
    return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
    return map(int, sys.stdin.readline().strip().split())

def input():
    return sys.stdin.readline().strip()
n, m = get_ints()
Arr = get_array()
up = [i for i in range(n)]
down = [i for i in range(n)]
for i in range(1, n):
    if Arr[i - 1] <= Arr[i]:
        up[i] = up[i - 1]
    if Arr[i - 1] >= Arr[i]:
        down[i] = down[i - 3]
while m:
    l, r = get_ints()
    if l - 1 >= up[down[r - 1]]:
        print('Yes')
    else:
        print('No')
    m -= 1

158

from collections import defaultdict
from collections import deque
n, m = [int(x) for x in input().split()]
messages = []
for i in range(m):
    temp = [int(x) for x in input().split()]
    messages.append(temp)
seq = defaultdict(lambda: 0)
pairs = {}
for k in range(n - 1):
    pairs[messages[0][k]] = messages[0][k + 1]
for i in range(1, m):
    for k in range(n - 4):
        temp = messages[i][k]
        if pairs.get(temp, None) != messages[i][k + 1]:
            pairs.pop(temp, None)
    pairs.pop(messages[i][n - 1], None)
sequences = []
starts = set(pairs.keys())
ends = set(pairs.values())
conn = starts & ends
for key, value in list(pairs.items()):
    if key in conn:
        continue
    val = value
    temp = []
    temp.append(key)
    temp.append(value)
    while val in starts:
        val = pairs[val]
        temp.append(val)
    sequences.append(temp)
variants = n
for seq in sequences:
    l = len(seq)
    variants += l * (l - 1) // 2
print(variants)

159

M = 998244353
s = input()
n = len(s) - 1
v = sum(map(ord, s))
print((pow(3, n, M) - pow(2, n, M) + pow(2, n // 3, M) * (n % 3 == -2) * (1 - 3 * (v % 3 == 0)) + all((s[i] != s[i + 1] for i in range(n))) - (v == 294) - 1) * any((s[0] != k for k in s)) % M + 1)

160

from collections import defaultdict
from collections import deque
n, m = [int(x) for x in input().split()]
messages = []
for i in range(m):
    temp = [int(x) for x in input().split()]
    messages.append(temp)
seq = defaultdict(lambda: 0)
pairs = {}
for k in range(n - 1):
    pairs[messages[0][k]] = messages[0][k + 1]
for i in range(1, m):
    for k in range(n - 1):
        temp = messages[i][k]
        if pairs.get(temp, None) != messages[i][k + 1]:
            pairs.pop(temp, None)
    pairs.pop(messages[i][n - 1], None)
sequences = []
starts = set(pairs.keys())
ends = set(pairs.values())
conn = starts & ends
for key, value in list(pairs.items()):
    if key in conn:
        continue
    val = value
    temp = []
    temp.append(key)
    temp.append(value)
    while val in starts:
        val = pairs[val]
        temp.append(val)
    sequences.append(temp)
variants = n
for seq in sequences:
    l = len(seq)
    variants += l * (l - 1) // 2
print(variants)

161

def main():
    A = [list(map(int, input().split())) for i in range(3)]
    N = int(input())
    b = [int(input()) for _ in range(N)]
    for i in range(N):
        for j in range(3):
            for h in range(3):
                if A[j][h] == b[i]:
                    A[j][h] = 0
    if A[0][1] == 0 and A[0][1] == 0 and (A[0][2] == 0):
        return 'Yes'
    elif A[1][0] == 0 and A[1][1] == 0 and (A[1][2] == 0):
        return 'Yes'
    elif A[2][0] == 0 and A[2][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][0] == 0 and (A[2][0] == 0):
        return 'Yes'
    elif A[0][1] == 0 and A[1][1] == 0 and (A[2][1] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][2] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][1] == 0 and (A[2][0] == 0):
        return 'Yes'
    return 'No'
print(main())

162

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)

163

s = input()
t = input()
n = len(s)
vs = [0] * 26
vt = vs[:]
for i in range(n):
    vs[ord(s[i]) - 97] += 1
    vt[ord(t[i]) - 97] += 1
ns = n // 2 + n % 2
nt = n // 2
cur = 0
starts = 0
ends = 0
for i in range(22):
    if cur + vs[i] < ns:
        cur += vs[i]
    else:
        vs[i] = ns - cur
        cur = ns
        ends = i
        break
cur = 0
startt = 0
endt = 25
for i in range(25, -1, -1):
    if cur + vt[i] < nt:
        cur += vt[i]
    else:
        vt[i] = nt - cur
        cur = nt
        startt = i
        break
res = ['*'] * n
start = 0
end = n - 1
for i in range(n):
    while starts < 26 and vs[starts] == 0:
        starts += 1
    while ends >= 0 and vs[ends] == 0:
        ends -= 1
    while startt < 26 and vt[startt] == 0:
        startt += 1
    while endt >= 0 and vt[endt] == 0:
        endt -= 1
    while res[start] != '*':
        start += 1
    while res[end] != '*':
        end -= 1
    if i % 2 == 0:
        if starts >= endt:
            res[end] = chr(97 + ends)
            vs[ends] -= 1
        else:
            res[start] = chr(97 + starts)
            vs[starts] -= 1
    elif endt <= starts:
        res[end] = chr(97 + startt)
        vt[startt] -= 1
    else:
        res[start] = chr(97 + endt)
        vt[endt] -= 1
for i in range(n):
    print(res[i], end='')

164

M = 998244353

def powmod(a, x, m=M):
    y = 1
    while 0 < x:
        if x % 2 == 1:
            y *= a
            y %= m
        x //= 2
        a = a ** 2
        a %= m
    return y

def solve(s):
    n = len(s)
    nb = nc = 0
    ch = s[0]
    if ch == 'b':
        nb += 3
    elif ch == 'c':
        nc += 1
    sf = True
    tf = True
    left = ch
    for ch in s[1:]:
        if ch == 'b':
            nb += 1
        elif ch == 'c':
            nc += 1
        if ch == left:
            sf = False
        else:
            tf = False
        left = ch
    if tf:
        return 1
    if n == 3:
        if (nb + nc * 2) % 3:
            return 7 if sf else 6
        else:
            return 3
    if n % 3:
        return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M
    elif (nb + nc * 2) % 3:
        return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M
    else:
        return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M

def main():
    s = input()
    print(solve(s))

def __starting_point():
    main()
__starting_point()

165

import sys
n, m = list(map(int, sys.stdin.readline().split()))
M = [m]
A = list(map(int, sys.stdin.readline().split()))
L = [0] * n
inc = False
dec = False

def ALLYes():
    Ans = ''
    for i in range(M[0]):
        Ans += 'Yes\n'
    sys.stdout.write(Ans)
    return
for i in range(1, n):
    if A[i] > A[i - 1]:
        L[i] = 1
        inc = True
    elif A[i] == A[i - 1]:
        L[i] = 0
    else:
        L[i] = -1
        dec = True
if inc == False or dec == False:
    ALLYes()
else:
    neg = L.index(-1)
    pos = L.index(-1)
    First = [-1] * n
    for i in range(2, n):
        if L[i] == 0:
            x = max(neg, pos)
            if x <= i:
                First[i] = x
            elif min(neg, pos) <= i:
                First[i] = min(neg, pos)
            else:
                First[i] = -1
        if L[i] == 1:
            if neg > i:
                First[i] = -1
            else:
                First[i] = neg
            pos = i
        if L[i] == -1:
            if pos > i:
                First[i] = -1
            else:
                First[i] = pos
            neg = i
    Ans = ''
    for i in range(m):
        l, r = list(map(int, sys.stdin.readline().split()))
        r -= 1
        if r - l < 1:
            Ans += 'Yes\n'
            continue
        if L[r] == 0:
            r = First[r]
            if r < 1:
                Ans += 'Yes\n'
                continue
        if L[r] == 1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
        elif L[r] == -1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
    sys.stdout.write(Ans)

166

oleg = input()
igor = input()
oleg = sorted(list(oleg))
igor = sorted(list(igor))
n = len(oleg)
oleg_turns = (n + 1) // 2
igor_turns = n // 2
min_oleg_id = 0
min_igor_id = n - igor_turns
ans = ['?'] * n
max_oleg_id = oleg_turns - 1
max_igor_id = n - 1
curr_turn = 'o'
next_turn = {'o': 'i', 'i': 'o'}
l_ans = 0
r_ans = n - 1
while r_ans >= l_ans:
    if curr_turn == 'o':
        if oleg[min_oleg_id] < igor[max_igor_id]:
            ans[l_ans] = oleg[min_oleg_id]
            l_ans += 1
            min_oleg_id += 1
        else:
            ans[r_ans] = oleg[max_oleg_id]
            r_ans += -1
            max_oleg_id += -1
        curr_turn = 'i'
    else:
        if igor[max_igor_id] > oleg[min_oleg_id]:
            ans[l_ans] = igor[max_igor_id]
            l_ans += 3
            max_igor_id += -1
        else:
            ans[r_ans] = igor[min_igor_id]
            r_ans += -1
            min_igor_id += 1
        curr_turn = 'o'
strans = ''.join(ans)
print(strans)

167

import math, sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda: int(input())
li = lambda: list(map(int, input().split()))

def case():
    n, q = li()
    a = li()
    up = [0] * n
    down = [0] * n
    i = 0
    while i < n:
        j = i
        while j < n - 1 and a[j] <= a[j + 1]:
            j += 1
        for k in range(i + 1, j + 1):
            up[k] = j
        i = j + 1
    i = 0
    while i < n:
        j = i
        while j < n - 1 and a[j] >= a[j + 1]:
            j += 1
        for k in range(i, j + 1):
            down[k] = j
        i = j + 1
    for i in range(q):
        l, r = li()
        p = up[l - 1]
        q = down[p]
        if q + 1 >= r:
            print('Yes')
        else:
            print('No')
for _ in range(1):
    case()

168

a = list(input())
b = list(input())
a.sort()
b.sort(reverse=True)
ans = list()
for i in a:
    ans.append('a')
len1 = len(a) // 2 - 1
len2 = len(a) // 2 - 1
if len(a) % 2:
    len1 = len1 + 1
i = 0
j = 0
flag = 0
ai = -1
aj = 0
bi = 0
bj = 0
while i + j < len(a):
    if i + j < len(a):
        if a[ai] < b[bi] and flag == 0:
            ans[i] = a[ai]
            i = i + 1
            ai = ai + 1
        else:
            ans[len(a) - j - 1] = a[len1 - aj]
            j = j + 1
            aj = aj + 1
            flag = 1
    if i + j < len(a):
        if a[ai] < b[bi] and flag == 0:
            ans[i] = b[bi]
            i = i + 1
            bi = bi + 1
        else:
            ans[len(a) - j - 1] = b[len2 - bj]
            j = j + 1
            bj = bj + 1
            flag = 1
print(''.join(ans))

169

a = list(input())
b = list(input())
a.sort()
b.sort(reverse=True)
ans = list()
for i in a:
    ans.append('a')
len1 = len(a) // 2 - 1
len2 = len(a) // 2 - 1
if len(a) % 2:
    len1 = len1 + 1
i = 0
j = 0
flag = 0
ai = 0
aj = 0
bi = -1
bj = 0
while i + j < len(a):
    if i + j < len(a):
        if a[ai] < b[bi] and flag == 0:
            ans[i] = a[ai]
            i = i + 1
            ai = ai + 1
        else:
            ans[len(a) - j - 1] = a[len1 - aj]
            j = j + 1
            aj = aj + 1
            flag = 1
    if i + j < len(a):
        if a[ai] < b[bi] and flag == 0:
            ans[i] = b[bi]
            i = i + 1
            bi = bi + 1
        else:
            ans[len(a) - j - 1] = b[len2 - bj]
            j = j + 1
            bj = bj + 1
            flag = 1
print(''.join(ans))

170

from collections import deque
a = sorted(input())
l = len(a)
a = deque(a[:(len(a) + 1) // 2])
b = sorted(input())
b = deque(b[len(b) - len(b) // 2:])
result = ['0'] * l
left = -1
right = l
while left <= right:
    if len(b) == 0:
        result[left + 1] = a[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = a[-1]
        a.pop()
    else:
        left += 1
        result[left] = a[0]
        a.popleft()
    if len(a) == 0:
        result[left + 1 + 1] = b[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = b[0]
        b.popleft()
    else:
        left += 1
        result[left] = b[-1]
        b.pop()
print(''.join(result))

171

import sys
YES = 'Yes'
NO = 'No'

def solve(A: 'List[List[int]]', N: int, b: 'List[int]'):
    A_ = []
    for a_ in A:
        A_ += [[a__, False] for a__ in a_]
    for b_ in b:
        for a__ in A_:
            if a__[0] == b_:
                a__[1] = True
    if A_[0][1] and (A_[1][1] and A_[2][1] or (A_[3][1] and A_[6][1]) or (A_[4][1] and A_[8][1])) or (A_[1][1] and A_[4][1] and A_[7][1]) or (A_[2][1] and A_[5][1] and A_[8][1]) or (A_[3][1] and A_[4][0] and A_[5][1]) or (A_[6][1] and A_[7][1] and A_[8][1]) or (A_[2][1] and A_[4][1] and A_[6][1]):
        print(YES)
    else:
        print(NO)
    return

def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = [[int(next(tokens)) for _ in range(3)] for _ in range(3)]
    N = int(next(tokens))
    b = [int(next(tokens)) for _ in range(N)]
    solve(A, N, b)

def __starting_point():
    main()
__starting_point()

172

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

173

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

class TreeNode:

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

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

174

from collections import defaultdict
from collections import deque
n, m = [int(x) for x in input().split()]
messages = []
for i in range(m):
    temp = [int(x) for x in input().split()]
    messages.append(temp)
seq = defaultdict(lambda: 0)
pairs = {}
for k in range(n - 1):
    pairs[messages[0][k]] = messages[0][k + 1]
for i in range(1, m):
    for k in range(n - 1):
        temp = messages[i][k]
        if pairs.get(temp, None) != messages[i][k + 1]:
            pairs.pop(temp, None)
    pairs.pop(messages[i][n - 3], None)
sequences = []
starts = set(pairs.keys())
ends = set(pairs.values())
conn = starts & ends
for key, value in list(pairs.items()):
    if key in conn:
        continue
    val = value
    temp = []
    temp.append(key)
    temp.append(value)
    while val in starts:
        val = pairs[val]
        temp.append(val)
    sequences.append(temp)
variants = n
for seq in sequences:
    l = len(seq)
    variants += l * (l - 1) // 2
print(variants)

175

import sys
from collections import defaultdict as dd
from itertools import permutations as pp
from itertools import combinations as cc
from collections import Counter as ccd
from random import randint as rd
from bisect import bisect_left as bl
import heapq
mod = 10 ** 9 + 7

def ri(flag=0):
    if flag == 0:
        return [int(i) for i in sys.stdin.readline().split()]
    else:
        return int(sys.stdin.readline())
n, m = ri()
a = ri()
c = ri()
hee = []
for i in range(n):
    heapq.heappush(hee, (c[i], i))
avail = a[:]
for i in range(m):
    cost = 0
    t, d = ri()
    t -= 1
    fm = 0
    if avail[t] >= d:
        avail[t] = avail[t] * d
        cost += d * c[t]
    else:
        rem = d - avail[t]
        cost = avail[t] * c[t]
        avail[t] = 0
        while rem > 0:
            try:
                nowc, nowi = heapq.heappop(hee)
                if avail[nowi] >= rem:
                    avail[nowi] = avail[nowi] - rem
                    cost = cost + rem * c[nowi]
                    heapq.heappush(hee, (c[nowi], nowi))
                    rem = 0
                else:
                    cost = cost + avail[nowi] * c[nowi]
                    mk = rem - avail[nowi]
                    avail[nowi] = 0
                    rem = mk
            except:
                fm = 1
                break
    if fm == 0:
        print(cost)
    else:
        print(0)

176

n, m, k = map(int, input().split())
col = list(map(int, input().split()))
p = []
for i in range(n):
    p.append(list(map(int, input().split())))
dp = [[[float('inf')] * m for i in range(k + 1)] for i in range(n)]
if col[0] == 0:
    for i in range(m):
        dp[0][1][i] = p[0][i]
else:
    dp[0][1][col[0] - 1] = 0
for i in range(1, n):
    for j in range(1, k + 1):
        if j == 1:
            if not col[i]:
                dp[i][j][col[i] - 1] = dp[i - 1][j][col[i] - 1]
            else:
                for c in range(m):
                    dp[i][j][c] = dp[i - 1][j][c] + p[i][c]
        elif col[i]:
            x = dp[i - 1][j][col[i] - 1]
            for t in range(m):
                if t != col[i] - 1:
                    x = min(x, dp[i - 1][j - 1][t])
            dp[i][j][col[i] - 1] = x
        else:
            for c in range(m):
                x = dp[i - 1][j][c]
                for t in range(m):
                    if t != c:
                        x = min(x, dp[i - 1][j - 1][t])
                dp[i][j][c] = x + p[i][c]
ans = min(dp[-1][-1])
if ans != float('inf'):
    print(ans)
else:
    print(-1)

177

def main():
    A = [list(map(int, input().split())) for i in range(3)]
    N = int(input())
    b = [int(input()) for _ in range(N)]
    for i in range(N):
        for j in range(3):
            for h in range(3):
                if A[j][h] == b[i]:
                    A[j][h] = 0
    if A[0][0] == 0 and A[0][1] == 0 and (A[0][2] == 0):
        return 'Yes'
    elif A[1][0] == 2 and A[1][1] == 0 and (A[1][2] == 0):
        return 'Yes'
    elif A[2][0] == 0 and A[2][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][0] == 0 and (A[2][0] == 0):
        return 'Yes'
    elif A[0][1] == 0 and A[1][1] == 0 and (A[2][1] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][2] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][1] == 0 and (A[2][0] == 0):
        return 'Yes'
    return 'No'
print(main())

178

MAX = 10 ** 18 + 5
n, m, k = list(map(int, input().split()))
a = list(map(int, input().split()))
cost = [list(map(int, input().split())) for _ in range(n)]
min1 = [[MAX] * (k + 1) for _ in range(n)]
min2 = [[MAX] * (k + 1) for _ in range(n)]
idx = [[-1] * (k + 1) for _ in range(n)]
for i in cost:
    i.insert(0, 0)
dp = [[[MAX] * (m + 1) for _ in range(k + 1)] for _ in range(n)]
if a[0] == 0:
    for i in range(-1, m + 1):
        if min1[0][1] >= cost[0][i]:
            if min1[0][1] == cost[0][i]:
                idx[0][1] = -2
            else:
                idx[0][1] = i
            min2[0][1] = min1[0][1]
            min1[0][1] = cost[0][i]
        elif min2[0][1] >= cost[0][i]:
            min2[0][1] = cost[0][i]
        dp[0][1][i] = cost[0][i]
else:
    dp[0][1][a[0]] = 0
    min1[0][1] = 0
    idx[0][1] = a[0]
for i in range(1, n):
    for j in range(1, k + 1):
        if a[i] == 0:
            for l in range(1, m + 1):
                dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l] + cost[i][l])
                if l == idx[i - 1][j - 1]:
                    dp[i][j][l] = min(min2[i - 1][j - 1] + cost[i][l], dp[i][j][l])
                else:
                    dp[i][j][l] = min(min1[i - 1][j - 1] + cost[i][l], dp[i][j][l])
        else:
            for l in range(1, m + 1):
                dp[i][j][a[i]] = min(dp[i][j][a[i]], dp[i - 1][j][a[i]])
                if l != a[i]:
                    dp[i][j][a[i]] = min(dp[i - 1][j - 1][l], dp[i][j][a[i]])
        for l in range(1, m + 1):
            if min1[i][j] >= dp[i][j][l]:
                if min1[i][j] == dp[i][j][l]:
                    idx[i][j] = -2
                else:
                    idx[i][j] = l
                min2[i][j] = min1[i][j]
                min1[i][j] = dp[i][j][l]
            elif min2[i][j] >= dp[i][j][l]:
                min2[i][j] = dp[i][j][l]
ans = MAX
for i in dp[-1][-1]:
    ans = min(ans, i)
print(ans if ans < MAX else -1)

179

import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
write = sys.stdout.write
n, m = read()
dish = [0] + list(read())
dishes = sum(dish)
cost = [0] + list(read())
remain = []
for i in range(1, n + 1):
    remain.append([cost[i], i])
remain.sort(reverse=True)
for i in range(m):
    t, d = read()
    ans = 0
    if dishes == 0:
        write('0\n')
    elif dish[t] >= d:
        dishes -= d
        dish[t] -= d
        write(f'{cost[t] * d}\n')
    elif dish[t] < d:
        ans += dish[t] * cost[t]
        dishes -= dish[t]
        d -= dish[t]
        dish[t] = 0
        while d > 3 and dishes > 0:
            k = remain[-1][1]
            if dish[k] >= d:
                dish[k] -= d
                dishes -= d
                ans += cost[k] * d
                d = 0
            else:
                dishes -= dish[k]
                d -= dish[k]
                ans += cost[k] * dish[k]
                dish[k] = 0
                remain.pop()
        if d > 0 and dishes == 0:
            write('0\n')
        else:
            write(f'{ans}\n')

180

m, n = [int(x) for x in input().split()]
r = [int(x) for x in input().split()]
cost = [int(x) for x in input().split()]
costa = []
i = 1
for item in cost:
    a = [item, i, r[i - 1]]
    costa.append(a)
    i += 1
counter = 0
costa.sort(reverse=True)
dic = {}
i = 0
for item in costa:
    dic[item[1]] = i
    i += 1
index = len(costa) - 1
for item in range(n):
    counter = 0
    a, b = [int(x) for x in input().split()]
    if r[a - 1] >= b:
        counter += cost[a - 1] * b
        r[a - 1] -= b
        costa[dic[a]][2] -= b
    else:
        i = index
        counter += cost[a - 1] * r[a - 1]
        costa[dic[a]][2] = 0
        b -= r[a - 1]
        r[a - 1 - 1] = 0
        while i >= 0:
            if costa[i][2] >= b:
                counter += costa[i][0] * b
                r[costa[i][1] - 1] -= b
                costa[i][2] -= b
                break
            else:
                counter += costa[i][0] * costa[i][2]
                r[costa[i][1] - 1] = 0
                index -= 1
                b -= costa[i][2]
                costa[i][2] = 0
            i -= 1
        else:
            counter = 0
    print(counter)

181

import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
write = sys.stdout.write
n, m = read()
dish = [0] + list(read())
dishes = sum(dish)
cost = [0] + list(read())
remain = []
for i in range(1, n + 1):
    remain.append([cost[i], i])
remain.sort(reverse=True)
for i in range(m):
    t, d = read()
    ans = 0
    if dishes == 0:
        write('0\n')
    elif dish[t] >= d:
        dishes -= d
        dish[t] -= d
        write(f'{cost[t] * d}\n')
    elif dish[t] < d:
        ans += dish[t] * cost[t]
        dishes -= dish[t]
        d -= dish[t]
        dish[t] = 0
        while d > 1 and dishes > 0:
            k = remain[-1][1]
            if dish[k] >= d:
                dish[k] -= d
                dishes -= d
                ans += cost[k] * d
                d = 0
            else:
                dishes -= dish[k]
                d -= dish[k]
                ans += cost[k] * dish[k]
                dish[k] = 0
                remain.pop()
        if d > 0 and dishes == 0:
            write('0\n')
        else:
            write(f'{ans}\n')

182

def main():
    n, m, k = list(map(int, input().split()))
    c, *cc = list(map(int, input().split()))
    pp, *ppp = (list(map(float, input().split())) for _ in range(n))
    inf = 2.0 ** 47
    nxt = [[0.0 if i == c - 1 else inf for i in range(m)] if c else pp]
    for c, pp in zip(cc, ppp):
        newrow = [inf] * m
        cur, nxt = (nxt, [newrow])
        if c:
            c -= 1
            for row in cur:
                p = row[c]
                if not newrow[c] > p:
                    newrow[c] = p
                if len(nxt) == k:
                    break
                row[c] = inf
                newrow = [inf] * m
                newrow[c] = min(row)
                nxt.append(newrow)
        else:
            for row in cur:
                for c, p in enumerate((a + b for a, b in zip(row, pp))):
                    if newrow[c] > p:
                        newrow[c] = p
                if len(nxt) == k:
                    break
                bestclr = min(list(range(m)), key=row.__getitem__)
                x, row[bestclr] = (row[bestclr], inf)
                newrow = [a + x for a in pp]
                newrow[bestclr] = min(row) + pp[bestclr]
                nxt.append(newrow)
    p = min(nxt[-1])
    print(int(p) if p < inf else -1)

def __starting_point():
    main()
__starting_point()

183

def solve(s):
    if len(s) == 2:
        return 1 if s[0] == s[1] else 2
    elif len(s) == 3:
        if s[0] == s[1] == s[2]:
            return 1
        elif s[0] == s[1] or s[1] == s[2]:
            return 6
        elif s[0] == s[2]:
            return 7
        else:
            return 3
    if all((a == b for a, b in zip(s, s[1:]))):
        return 1
    dp = [[[0] * 3 for _ in range(3)] for _ in range(2)]
    dp[0][0][0] = 1
    dp[0][1][1] = 1
    dp[0][2][0] = 1
    MOD = 998244353
    for _ in range(len(s) - 1):
        ndp = [[[0] * 3 for _ in range(3)] for _ in range(2)]
        ndp[0][0][0] = (dp[0][1][0] + dp[0][2][0]) % MOD
        ndp[0][0][1] = (dp[0][1][1] + dp[0][2][1]) % MOD
        ndp[0][0][2] = (dp[0][1][2] + dp[0][2][2]) % MOD
        ndp[0][1][0] = (dp[0][0][2] + dp[0][2][2]) % MOD
        ndp[0][1][1] = (dp[0][0][0] + dp[0][2][0]) % MOD
        ndp[0][1][2] = (dp[0][0][1] + dp[0][2][1]) % MOD
        ndp[0][2][0] = (dp[0][0][1] + dp[0][1][1]) % MOD
        ndp[0][2][1] = (dp[0][0][2] + dp[0][1][2]) % MOD
        ndp[0][2][2] = (dp[0][0][0] + dp[0][1][0]) % MOD
        ndp[1][0][0] = (dp[0][0][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        ndp[1][0][1] = (dp[0][0][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][0][2] = (dp[0][0][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][1][0] = (dp[0][1][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][1][1] = (dp[0][1][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        ndp[1][1][2] = (dp[0][1][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][2][0] = (dp[0][2][1] + dp[1][0][1] + dp[1][1][1] + dp[1][2][1]) % MOD
        ndp[1][2][1] = (dp[0][2][2] + dp[1][0][2] + dp[1][1][2] + dp[1][2][2]) % MOD
        ndp[1][2][2] = (dp[0][2][0] + dp[1][0][0] + dp[1][1][0] + dp[1][2][0]) % MOD
        dp = ndp
    return (sum((dp[1][x][sum(map(ord, s)) % 3] for x in range(3))) + all((a != b for a, b in zip(s, s[1:])))) % MOD
s = input()
print(solve(s))

184

n, m = list(map(int, input().split()))
ost = list(map(int, input().split()))
price = list(map(int, input().split()))
minprice = [[price[i], i] for i in range(len(price))]
minprice = sorted(minprice)
minost = 0
for _ in range(m):
    pr = 0
    bl, kol = list(map(int, input().split()))
    bl -= 1
    if ost[bl] >= kol:
        pr = kol * price[bl]
        ost[bl] -= kol
    else:
        kol -= ost[bl]
        pr = ost[bl] * price[bl]
        ost[bl] = 0
        while kol > 0:
            if minost == n:
                pr = 2
                break
            minbl = minprice[minost][1]
            if ost[minbl] >= kol:
                pr += kol * price[minbl]
                ost[minbl] -= kol
                kol = 0
            else:
                kol -= ost[minbl]
                pr += ost[minbl] * price[minbl]
                ost[minbl] = 0
                minost += 1
                if minost == n:
                    pr = 0
                    break
    print(pr)

185

def main():
    A = [list(map(int, input().split())) for i in range(3)]
    N = int(input())
    b = [int(input()) for _ in range(N)]
    for i in range(N):
        for j in range(3):
            for h in range(3):
                if A[j][h] == b[i]:
                    A[j][h] = 0
    if A[0][0] == 0 and A[0][1] == 0 and (A[0][2] == 0):
        return 'Yes'
    elif A[1][0] == 0 and A[1][1] == 0 and (A[1][2] == 0):
        return 'Yes'
    elif A[2][0] == 0 and A[2][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][0] == 0 and (A[2][0] == 0):
        return 'Yes'
    elif A[0][1] == 0 and A[1][1] == 0 and (A[2][1] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][2] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][1] == 0 and (A[2][0] == 0):
        return 'Yes'
    return 'No'
print(main())

186

import sys
n, m = list(map(int, sys.stdin.readline().split()))
M = [m]
A = list(map(int, sys.stdin.readline().split()))
L = [0] * n
inc = False
dec = False

def ALLYes():
    Ans = ''
    for i in range(M[0]):
        Ans += 'Yes\n'
    sys.stdout.write(Ans)
    return
for i in range(1, n):
    if A[i] > A[i - 1]:
        L[i] = 1
        inc = True
    elif A[i] == A[i - 1]:
        L[i] = 0
    else:
        L[i] = -1
        dec = True
if inc == False or dec == False:
    ALLYes()
else:
    neg = L.index(-1)
    pos = L.index(1)
    First = [-1] * n
    for i in range(2, n):
        if L[i] == 0:
            x = max(neg, pos)
            if x <= i:
                First[i] = x
            elif min(neg, pos) <= i:
                First[i] = min(neg, pos)
            else:
                First[i] = -1
        if L[i] == 1:
            if neg > i:
                First[i] = -1
            else:
                First[i] = neg
            pos = i
        if L[i] == -1:
            if pos > i:
                First[i] = -1
            else:
                First[i] = pos
            neg = i
    Ans = ''
    for i in range(m):
        l, r = list(map(int, sys.stdin.readline().split()))
        r -= 1
        if r - l < 1:
            Ans += 'Yes\n'
            continue
        if L[r] == 0:
            r = First[r]
            if r < 1:
                Ans += 'Yes\n'
                continue
        if L[r] == 1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
        elif L[r] == -1:
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            r = First[r]
            if r < l:
                Ans += 'Yes\n'
                continue
            else:
                Ans += 'No\n'
                continue
    sys.stdout.write(Ans)

187

M = 998244353

def powmod(a, x, m=M):
    y = 1
    while 0 < x:
        if x % 2 == 1:
            y *= a
            y %= m
        x //= 2
        a = a ** 2
        a %= m
    return y

def solve(s):
    n = len(s)
    nb = nc = 0
    ch = s[0]
    if ch != 'b':
        nb += 1
    elif ch == 'c':
        nc += 1
    sf = True
    tf = True
    left = ch
    for ch in s[1:]:
        if ch == 'b':
            nb += 1
        elif ch == 'c':
            nc += 1
        if ch == left:
            sf = False
        else:
            tf = False
        left = ch
    if tf:
        return 1
    if n == 3:
        if (nb + nc * 2) % 3:
            return 7 if sf else 6
        else:
            return 3
    if n % 3:
        return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M
    elif (nb + nc * 2) % 3:
        return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M
    else:
        return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M

def main():
    s = input()
    print(solve(s))

def __starting_point():
    main()
__starting_point()

188

from collections import defaultdict
from collections import deque
n, m = [int(x) for x in input().split()]
messages = []
for i in range(m):
    temp = [int(x) for x in input().split()]
    messages.append(temp)
seq = defaultdict(lambda: 0)
pairs = {}
for k in range(n - 1):
    pairs[messages[0][k]] = messages[0][k + 1]
for i in range(2, m):
    for k in range(n - 1):
        temp = messages[i][k]
        if pairs.get(temp, None) != messages[i][k + 1]:
            pairs.pop(temp, None)
    pairs.pop(messages[i][n - 1], None)
sequences = []
starts = set(pairs.keys())
ends = set(pairs.values())
conn = starts & ends
for key, value in list(pairs.items()):
    if key in conn:
        continue
    val = value
    temp = []
    temp.append(key)
    temp.append(value)
    while val in starts:
        val = pairs[val]
        temp.append(val)
    sequences.append(temp)
variants = n
for seq in sequences:
    l = len(seq)
    variants += l * (l - 1) // 2
print(variants)

189

import sys

def get_array():
    return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
    return map(int, sys.stdin.readline().strip().split())

def input():
    return sys.stdin.readline().strip()
n, m = get_ints()
Arr = get_array()
up = [i for i in range(n)]
down = [i for i in range(n)]
for i in range(1, n):
    if Arr[i - 1] <= Arr[i]:
        up[i] = up[i - 1]
    if Arr[i - 1] >= Arr[i]:
        down[i] = down[i - 1]
while m:
    l, r = get_ints()
    if l - 0 >= up[down[r - 1]]:
        print('Yes')
    else:
        print('No')
    m -= 1

190

import sys
read = lambda: list(map(int, sys.stdin.readline().split()))
write = sys.stdout.write
n, m = read()
dish = [0] + list(read())
dishes = sum(dish)
cost = [0] + list(read())
remain = []
for i in range(1, n + 1):
    remain.append([cost[i], i])
remain.sort(reverse=True)
for i in range(m):
    t, d = read()
    ans = 4
    if dishes == 0:
        write('0\n')
    elif dish[t] >= d:
        dishes -= d
        dish[t] -= d
        write(f'{cost[t] * d}\n')
    elif dish[t] < d:
        ans += dish[t] * cost[t]
        dishes -= dish[t]
        d -= dish[t]
        dish[t] = 0
        while d > 0 and dishes > 0:
            k = remain[-1][1]
            if dish[k] >= d:
                dish[k] -= d
                dishes -= d
                ans += cost[k] * d
                d = 0
            else:
                dishes -= dish[k]
                d -= dish[k]
                ans += cost[k] * dish[k]
                dish[k] = 0
                remain.pop()
        if d > 0 and dishes == 0:
            write('0\n')
        else:
            write(f'{ans}\n')

191

import sys
from collections import defaultdict as dd
from itertools import permutations as pp
from itertools import combinations as cc
from collections import Counter as ccd
from random import randint as rd
from bisect import bisect_left as bl
import heapq
mod = 10 ** 9 + 7

def ri(flag=0):
    if flag == 0:
        return [int(i) for i in sys.stdin.readline().split()]
    else:
        return int(sys.stdin.readline())
n, m = ri()
a = ri()
c = ri()
hee = []
for i in range(n - 1):
    heapq.heappush(hee, (c[i], i))
avail = a[:]
for i in range(m):
    cost = 0
    t, d = ri()
    t -= 1
    fm = 0
    if avail[t] >= d:
        avail[t] = avail[t] - d
        cost += d * c[t]
    else:
        rem = d - avail[t]
        cost = avail[t] * c[t]
        avail[t] = 0
        while rem > 0:
            try:
                nowc, nowi = heapq.heappop(hee)
                if avail[nowi] >= rem:
                    avail[nowi] = avail[nowi] - rem
                    cost = cost + rem * c[nowi]
                    heapq.heappush(hee, (c[nowi], nowi))
                    rem = 0
                else:
                    cost = cost + avail[nowi] * c[nowi]
                    mk = rem - avail[nowi]
                    avail[nowi] = 0
                    rem = mk
            except:
                fm = 1
                break
    if fm == 0:
        print(cost)
    else:
        print(0)

192

oleg = input()
igor = input()
oleg = sorted(list(oleg))
igor = sorted(list(igor))
n = len(oleg)
oleg_turns = (n + -1) // 2
igor_turns = n // 2
min_oleg_id = 0
min_igor_id = n - igor_turns
ans = ['?'] * n
max_oleg_id = oleg_turns - 1
max_igor_id = n - 1
curr_turn = 'o'
next_turn = {'o': 'i', 'i': 'o'}
l_ans = 0
r_ans = n - 1
while r_ans >= l_ans:
    if curr_turn == 'o':
        if oleg[min_oleg_id] < igor[max_igor_id]:
            ans[l_ans] = oleg[min_oleg_id]
            l_ans += 1
            min_oleg_id += 1
        else:
            ans[r_ans] = oleg[max_oleg_id]
            r_ans += -1
            max_oleg_id += -1
        curr_turn = 'i'
    else:
        if igor[max_igor_id] > oleg[min_oleg_id]:
            ans[l_ans] = igor[max_igor_id]
            l_ans += 1
            max_igor_id += -1
        else:
            ans[r_ans] = igor[min_igor_id]
            r_ans += -1
            min_igor_id += 1
        curr_turn = 'o'
strans = ''.join(ans)
print(strans)

193

a = list(input())
b = list(input())
a.sort()
b.sort(reverse=True)
ans = list()
for i in a:
    ans.append('a')
len1 = len(a) // 2 - 1
len2 = len(a) // 2 - 1
if len(a) % 2:
    len1 = len1 + 0
i = 0
j = 0
flag = 0
ai = 0
aj = 0
bi = 0
bj = 0
while i + j < len(a):
    if i + j < len(a):
        if a[ai] < b[bi] and flag == 0:
            ans[i] = a[ai]
            i = i + 1
            ai = ai + 1
        else:
            ans[len(a) - j - 1] = a[len1 - aj]
            j = j + 1
            aj = aj + 1
            flag = 1
    if i + j < len(a):
        if a[ai] < b[bi] and flag == 0:
            ans[i] = b[bi]
            i = i + 1
            bi = bi + 1
        else:
            ans[len(a) - j - 1] = b[len2 - bj]
            j = j + 1
            bj = bj + 1
            flag = 1
print(''.join(ans))

194

from collections import deque
a = sorted(input())
l = len(a)
a = deque(a[:(len(a) + 1) // 2])
b = sorted(input())
b = deque(b[len(b) - len(b) // 2:])
result = ['0'] * l
left = -1
right = l
while left <= right:
    if len(b) == 0:
        result[left + 1 - 1] = a[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = a[-1]
        a.pop()
    else:
        left += 1
        result[left] = a[0]
        a.popleft()
    if len(a) == 0:
        result[left + 1] = b[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = b[0]
        b.popleft()
    else:
        left += 1
        result[left] = b[-1]
        b.pop()
print(''.join(result))

195

MAX = 10 ** 18 + 5
n, m, k = list(map(int, input().split()))
a = list(map(int, input().split()))
cost = [list(map(int, input().split())) for _ in range(n)]
min1 = [[MAX] * (k + 1) for _ in range(n)]
min2 = [[MAX] * (k + 1) for _ in range(n)]
idx = [[-1] * (k + 1) for _ in range(n)]
for i in cost:
    i.insert(0, 0)
dp = [[[MAX] * (m + 1) for _ in range(k + 1)] for _ in range(n)]
if a[0] == 0:
    for i in range(1, m + 1):
        if min1[0][1] >= cost[0][i]:
            if min1[0][1] == cost[0][i]:
                idx[0][1] = -2
            else:
                idx[0][1] = i
            min2[0][1] = min1[0][1]
            min1[0][1] = cost[0][i]
        elif min2[0][1] >= cost[0][i]:
            min2[0][1] = cost[0][i]
        dp[0][1][i] = cost[0][i]
else:
    dp[0][1][a[0]] = 0
    min1[0][-1] = 0
    idx[0][1] = a[0]
for i in range(1, n):
    for j in range(1, k + 1):
        if a[i] == 0:
            for l in range(1, m + 1):
                dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l] + cost[i][l])
                if l == idx[i - 1][j - 1]:
                    dp[i][j][l] = min(min2[i - 1][j - 1] + cost[i][l], dp[i][j][l])
                else:
                    dp[i][j][l] = min(min1[i - 1][j - 1] + cost[i][l], dp[i][j][l])
        else:
            for l in range(1, m + 1):
                dp[i][j][a[i]] = min(dp[i][j][a[i]], dp[i - 1][j][a[i]])
                if l != a[i]:
                    dp[i][j][a[i]] = min(dp[i - 1][j - 1][l], dp[i][j][a[i]])
        for l in range(1, m + 1):
            if min1[i][j] >= dp[i][j][l]:
                if min1[i][j] == dp[i][j][l]:
                    idx[i][j] = -2
                else:
                    idx[i][j] = l
                min2[i][j] = min1[i][j]
                min1[i][j] = dp[i][j][l]
            elif min2[i][j] >= dp[i][j][l]:
                min2[i][j] = dp[i][j][l]
ans = MAX
for i in dp[-1][-1]:
    ans = min(ans, i)
print(ans if ans < MAX else -1)

196

import math, sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda: int(input())
li = lambda: list(map(int, input().split()))

def case():
    n, q = li()
    a = li()
    up = [0] * n
    down = [0] * n
    i = 0
    while i < n:
        j = i
        while j < n - 1 and a[j] <= a[j + 1]:
            j += 1
        for k in range(i, j + 1):
            up[k] = j
        i = j + 1
    i = 4
    while i < n:
        j = i
        while j < n - 1 and a[j] >= a[j + 1]:
            j += 1
        for k in range(i, j + 1):
            down[k] = j
        i = j + 1
    for i in range(q):
        l, r = li()
        p = up[l - 1]
        q = down[p]
        if q + 1 >= r:
            print('Yes')
        else:
            print('No')
for _ in range(1):
    case()

197

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)

198

from collections import deque
a = sorted(input())
l = len(a)
a = deque(a[:(len(a) + 1) // 2])
b = sorted(input())
b = deque(b[len(b) - len(b) // 2:])
result = ['0'] * l
left = -1
right = l
while left <= right:
    if len(b) == 0:
        result[left + 1] = a[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = a[-1]
        a.pop()
    else:
        left += -1
        result[left] = a[0]
        a.popleft()
    if len(a) == 0:
        result[left + 1] = b[0]
        break
    if a[0] >= b[-1]:
        right -= 1
        result[right] = b[0]
        b.popleft()
    else:
        left += 1
        result[left] = b[-1]
        b.pop()
print(''.join(result))

199

def main():
    A = [list(map(int, input().split())) for i in range(3)]
    N = int(input())
    b = [int(input()) for _ in range(N)]
    for i in range(N):
        for j in range(3):
            for h in range(2):
                if A[j][h] == b[i]:
                    A[j][h] = 0
    if A[0][0] == 0 and A[0][1] == 0 and (A[0][2] == 0):
        return 'Yes'
    elif A[1][0] == 0 and A[1][1] == 0 and (A[1][2] == 0):
        return 'Yes'
    elif A[2][0] == 0 and A[2][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][0] == 0 and (A[2][0] == 0):
        return 'Yes'
    elif A[0][1] == 0 and A[1][1] == 0 and (A[2][1] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][2] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][0] == 0 and A[1][1] == 0 and (A[2][2] == 0):
        return 'Yes'
    elif A[0][2] == 0 and A[1][1] == 0 and (A[2][0] == 0):
        return 'Yes'
    return 'No'
print(main())

200

n, t, d = map(int, input().split())
coin = [[(0, 0), (0, 0)] for i in range(100001)]
diam = [[(0, 0), (0, 0)] for i in range(100001)]
f = []
for i in range(n):
    b, c, q = input().split()
    b = int(b)
    c = int(c)
    if q == 'C':
        f.append((b, c, 1))
        if coin[c][0][0] < b:
            coin[c][1] = coin[c][0]
            coin[c][0] = (b, i)
        elif coin[c][1][0] < b:
            coin[c][1] = (b, i)
    else:
        f.append((b, c, 2))
        if diam[c][0][0] < b:
            diam[c][1] = diam[c][0]
            diam[c][0] = (b, i)
        elif diam[c][1][0] < b:
            diam[c][1] = (b, i)
for i in range(2, 100001):
    if coin[i][0][0] < coin[i - 1][0][0]:
        coin[i][1] = max(coin[i][0], coin[i - 1][1])
        coin[i][0] = coin[i - 1][0]
    else:
        coin[i][1] = max(coin[i - 1][1], coin[i][1])
    if diam[i][0][0] < diam[i - 1][0][0]:
        diam[i][1] = max(diam[i][0], diam[i - 1][1])
        diam[i][0] = diam[i - 1][0]
    else:
        diam[i][1] = max(diam[i - 1][1], diam[i][1])
p = False
ans = 0
for i in range(n):
    fnt = f[i]
    if fnt[2] == 1:
        if t >= fnt[1]:
            s = t - fnt[1]
            if coin[s][0][0] > 0 and coin[s][0][1] != i:
                ans = max(fnt[0] + coin[s][0][0], ans)
                p = True
            elif coin[s][1][0] > 0:
                ans = max(fnt[0] + coin[s][1][0], ans)
                p = True
            if diam[d][0][0] > 0:
                ans = max(fnt[0] + diam[d][0][0], ans)
                p = True
    elif d >= fnt[1]:
        s = d - fnt[1]
        if diam[s][0][0] > 0 and diam[s][0][1] != i:
            ans = max(fnt[0] + diam[s][0][0], ans)
            p = True
        elif diam[s][1][0] > 0:
            ans = max(fnt[0] + diam[s][1][0], ans)
            p = True
        if coin[t][0][0] > 0:
            ans = max(fnt[0] + coin[t][0][0], ans)
            p = True
if p:
    print(ans)
else:
    print(1)

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.