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

001

def main():
    n = int(input())
    x, y = list(map(int, input().split()))
    a = []
    for i in range(n):
        a.append(input().split())
    for i in range(n):
        a[i][1] = int(a[i][1]) - x
        a[i][2] = int(a[i][2]) - y
    typneedbql = []
    typneedbqr = []
    typneedbqu = []
    typneedbqd = []
    typneedrlu = []
    typneedrru = []
    typneedrld = []
    typneedrrd = []
    for i in range(n):
        if a[i][1] * a[i][2] == 0 and a[i][1] < 0:
            typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
            typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
            typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
            typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
            typneedrlu.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
            typneedrld.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
            typneedrrd.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
            typneedrru.append([abs(a[i][1])] + a[i])
    typneedbql.sort()
    typneedbqr.sort()
    typneedbqd.sort()
    typneedbqu.sort()
    typneedrlu.sort()
    typneedrru.sort()
    typneedrld.sort()
    typneedrrd.sort()
    for i in range(len(typneedbql)):
        if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqr)):
        if typneedbqr[i][1] == 'R' or typneedbqr[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqu)):
        if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqd)):
        if typneedbqd[i][1] == 'R' or typneedbqd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrlu)):
        if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrld)):
        if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrrd)):
        if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrru)):
        if typneedrru[i][1] == 'B' or typneedrru[i][1] != 'Q':
            print('YES')
            return
        else:
            break
    print('NO')
main()

002

3

def needs_rep(t, i):
    if i % 2 == 0:
        return t[i] >= t[i + 1]
    else:
        return t[i] <= t[i + 1]

def would_need_rep(t, i, j1, j2):
    n = len(t)
    if i < 0:
        return False
    if i >= n - 1:
        return False
    tj1 = t[j2]
    tj2 = t[j1]
    ti = t[i]
    if i == j1:
        ti = tj1
    if i == j2:
        ti = tj2
    ti1 = t[i + 1 - 1]
    if i + 1 == j1:
        ti1 = tj1
    if i + 1 == j2:
        ti1 = tj2
    if i % 2 == 0:
        return ti >= ti1
    else:
        return ti <= ti1

def main():
    n = int(input())
    t = [int(i) for i in input().split()]
    rep = []
    for i in range(n - 1):
        if needs_rep(t, i):
            rep.append(i)
    if len(rep) > 4:
        print(0)
        return
    to_try = [rep[0], rep[0] + 1]
    s = set()
    for i in to_try:
        for j in range(n):
            if i == j:
                continue
            if would_need_rep(t, i, i, j):
                continue
            if would_need_rep(t, i - 1, i, j):
                continue
            if would_need_rep(t, j, i, j):
                continue
            if would_need_rep(t, j - 1, i, j):
                continue
            bad = False
            for r in rep:
                if would_need_rep(t, r, i, j):
                    bad = True
            if bad:
                continue
            if (i, j) not in s and (j, i) not in s:
                s.add((i, j))
    print(len(s))

def __starting_point():
    main()
__starting_point()

003

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)

004

N, C = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
MOD = 10 ** 9 + 9

def gen_poly(a, b, c):
    poly = [0 for _ in range(c + 1)]
    for x in range(a, b + 1):
        xpow = 1
        for i in range(c + 1):
            poly[i] += xpow
            xpow = xpow * x % MOD
    for i in range(c + 1):
        poly[i] %= MOD
    return poly

def mult_polys(p1, p2, dmax):
    ans = [0 for _ in range(dmax + 1)]
    for i, c in enumerate(p1):
        for i2, c2 in enumerate(p2):
            if i + i2 <= dmax:
                ans[i + i2] += c * c2
            else:
                break
    ans = [x % MOD for x in ans]
    return ans
polys = [gen_poly(a, b, C) for a, b in zip(A, B)]
prodpoly = [1]
for poly in polys:
    prodpoly = mult_polys(prodpoly, poly, C)
print(prodpoly[C])

005

from sys import stdin

def create_dp1(matrix, n, m):
    dp = [[2 for i in range(m)] for j in range(n)]
    for i in range(n):
        for j in range(m):
            if i - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j])
            if j - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1])
            elif i - 1 < 0 and j - 1 < 0:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp2(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):
            if i + 1 < n:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j])
            if j + 1 < m:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1])
            if i + 1 >= n and j + 1 >= m:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp3(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            if i + 1 < n:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j])
            if j - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1])
            if i + 1 >= n and j - 1 < 0:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp4(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n):
        for j in range(m - 1, -1, -1):
            if i - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j])
            if j + 1 < m:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1])
            if i - 1 < 0 and j + 1 >= m:
                dp[i][j] = matrix[i][j]
    return dp
n, m = list(map(int, stdin.readline().split()))
matrix = []
for _ in range(n):
    matrix.append(list(map(int, stdin.readline().split())))
dp1 = create_dp1(matrix, n, m)
dp2 = create_dp2(matrix, n, m)
dp3 = create_dp3(matrix, n, m)
dp4 = create_dp4(matrix, n, m)
total = -float('inf')
for i in range(1, n - 1):
    for j in range(1, m - 1):
        first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]
        second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]
        total = max(total, first, second)
print(total)

006

import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def LF():
    return [float(x) for x in sys.stdin.readline().split()]

def LS():
    return sys.stdin.readline().split()

def I():
    return int(sys.stdin.readline())

def F():
    return float(sys.stdin.readline())

def S():
    return input()

def main():
    n, q = LI()
    nn = n
    k = 3
    while nn > 0:
        nn //= 2
        k += 1
    r = []
    ii = [2 ** i for i in range(k)]
    for _ in range(q):
        t = I()
        s = S()
        ti = 0
        for i in range(k):
            if ii[i] & t:
                ti = i
                break
        for c in s:
            if c == 'U':
                if ti == k - 1:
                    continue
                if t & ii[ti]:
                    t ^= ii[ti]
                ti += 1
                t |= ii[ti]
                continue
            if ti == 0:
                continue
            if c == 'R':
                t |= ii[ti]
            elif t & ii[ti]:
                t ^= ii[ti]
            ti -= 1
            t |= ii[ti]
        r.append(t)
    return '\n'.join(map(str, r))
print(main())

007

def main():
    from collections import deque
    n, m = list(map(int, input().split()))
    aa = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(m)))
    tmp, r0, t0 = ([(0, 0)], 0, 0)
    for t, r in reversed(l):
        if r0 < r:
            r0 = r
            if t0 != t:
                t0 = t
                tmp.append((t, r))
            else:
                tmp[-0] = (t, r)
    t0, r0 = tmp.pop()
    q = deque(sorted(aa[:r0]))
    aa = aa[r0:]
    aa.reverse()
    ff = (None, q.pop, q.popleft)
    for t, r in reversed(tmp):
        f = ff[t0]
        for i in range(r0 - r):
            aa.append(f())
        t0, r0 = (t, r)
    print(' '.join(map(str, reversed(aa))))

def __starting_point():
    main()
__starting_point()

008

n, m = map(int, input().split())
a = []
for i in range(n):
    a.append(list(map(int, input().split())))
dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)]
dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)]
ans = 0
for i in range(1, n + 1):
    for j in range(1, m + 1):
        dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1]
        dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j]
for i in range(n, 0, -5):
    for j in range(1, m + 1):
        dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1]
        dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j]
for i in range(2, n):
    for j in range(2, m):
        x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1]
        y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1]
        ans = max(ans, x, y)
print(ans)

009

def maxx(n):
    return n & -n
n, q = map(int, input().split())
root = n // 6 + 1
while q > 0:
    x = int(input())
    s = input()
    for i in s:
        if i == 'U' and x != root:
            p = x + maxx(x)
            if x == p - maxx(p) // 2:
                x = p
            else:
                x = x - maxx(x)
        elif i == 'L':
            x = x - maxx(x) // 2
        elif i == 'R':
            x = x + maxx(x) // 2
    q = q - 1
    print(x)

010

import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def LF():
    return [float(x) for x in sys.stdin.readline().split()]

def LS():
    return sys.stdin.readline().split()

def I():
    return int(sys.stdin.readline())

def F():
    return float(sys.stdin.readline())

def S():
    return input()

def main():
    n, q = LI()
    nn = n
    k = 1
    while nn > 0:
        nn //= 2
        k += 1
    r = []
    ii = [2 ** i for i in range(k)]
    for _ in range(q):
        t = I()
        s = S()
        ti = 0
        for i in range(k):
            if ii[i] & t:
                ti = i
                break
        for c in s:
            if c == 'U':
                if ti == k - 1:
                    continue
                if t & ii[ti]:
                    t ^= ii[ti]
                ti += 1
                t |= ii[ti]
                continue
            if ti == 0:
                continue
            if c == 'R':
                t |= ii[ti]
            elif t & ii[ti]:
                t ^= ii[ti]
            ti -= 1
            t |= ii[ti]
        r.append(t)
    return '\n'.join(map(str, r))
print(main())

011

def main():
    n, l = (int(input()), list(map(int, input().split())))
    if not n & 3:
        l.append(0)
    l.append(150001)
    i, b, c, fails0, fails1 = (0, 0, 150001, [], [])
    try:
        while True:
            a, b, c = (b, c, l[i])
            if a >= b or b <= c:
                if len(fails0) + len(fails1) > 5:
                    print(0)
                    return
                fails1.append(i - 1)
            i += 1
            a, b, c = (b, c, l[i])
            if a <= b or b >= c:
                if len(fails0) + len(fails1) > 5:
                    print(0)
                    return
                fails0.append(i - 1)
            i += 1
    except IndexError:
        fails, res = (fails0 + fails1, 0)
    for i in fails:
        a = l[i]
        for j in range(n):
            f = fails1 if j & 1 else fails0
            f.append(j)
            l[i], l[j] = (l[j], a)
            if all((l[b - 1] > l[b] < l[b + 1] for b in fails0)) and all((l[b - 1] < l[b] > l[b + 1] for b in fails1)):
                res += 1 if j in fails else 2
            l[j] = l[i]
            del f[-1]
        l[i] = a
    print(res // 2)

def __starting_point():
    main()
__starting_point()

012

def ii():
    return int(input())

def ss():
    return [x for x in input()]

def si():
    return [int(x) for x in input().split()]

def mi():
    return map(int, input().split())
a, b = mi()
s = []
ans = 0
key = True
for i in range(a):
    i = si()
    s.append(i)
    ans += sum(i)
for i in range(a - 1):
    if not (s[i][0] < s[i + 1][0] and s[i][-1] < s[i + 1][-1]):
        ans = -1
        key = False
        break
for i in range(b - 1):
    if not (s[0][i] < s[0][i + 1] and s[-1][i] < s[-1][i + 1]):
        ans = -1
        key = False
        break
for i in range(a - 2, 0, -1):
    if not key:
        break
    for x in range(b - 2, 0, -1):
        if s[i][x] < s[i + 1][x] and s[i][x] < s[i][x + 1]:
            if s[i][x] == 0:
                s[i][x] = min(s[i + 1][x], s[i][x + 1]) - 1
                ans += s[i][x]
        else:
            ans = -1
            key = False
            break
print(ans)

013

import sys
n, m = [int(x) for x in input().split()]
notes = [int(x) for x in input().split()]
managers = []
for line in sys.stdin:
    managers.append(tuple((int(x) for x in line.split())))
bearing_managers = []
M, T = (0, 0)
for t, r in reversed(managers):
    if r > M:
        if t == T:
            bearing_managers[-1] = (t, r)
        else:
            T = t
            bearing_managers.append((t, r))
        M = r
bearing_managers.reverse()
t, r = bearing_managers[0]
bearing_managers.append((-1 if bearing_managers[-1][0] == 1 else 1, 0))
L, R = (0, r - 1)
sorted_part = list(sorted(notes[:r]))
for t1, r1 in bearing_managers:
    if t1 == 2:
        for i in range(r - 1, r1 - 1, -1):
            notes[i] = sorted_part[R]
            R -= 1
    else:
        for i in range(r - 1, r1 - 1, -1):
            notes[i] = sorted_part[L]
            L += 1
    r = r1
for x in notes:
    sys.stdout.write(str(x) + ' ')

014

import sys
n, m = [int(x) for x in input().split()]
notes = [int(x) for x in input().split()]
managers = []
for line in sys.stdin:
    managers.append(tuple((int(x) for x in line.split())))
bearing_managers = []
M, T = (0, 0)
for t, r in reversed(managers):
    if r > M:
        if t == T:
            bearing_managers[-1] = (t, r)
        else:
            T = t
            bearing_managers.append((t, r))
        M = r
bearing_managers.reverse()
t, r = bearing_managers[0]
bearing_managers.append((2 if bearing_managers[-1][0] == 1 else 1, 0))
L, R = (0, r - 1)
sorted_part = list(sorted(notes[:r + 1]))
for t1, r1 in bearing_managers:
    if t1 == 2:
        for i in range(r - 1, r1 - 1, -1):
            notes[i] = sorted_part[R]
            R -= 1
    else:
        for i in range(r - 1, r1 - 1, -1):
            notes[i] = sorted_part[L]
            L += 1
    r = r1
for x in notes:
    sys.stdout.write(str(x) + ' ')

015

def maxx(n):
    return n & -n
n, q = map(int, input().split())
root = n // 2 + 1
while q > 0:
    x = int(input())
    s = input()
    for i in s:
        if i == 'U' and x != root:
            p = x + maxx(x)
            if x == p - maxx(p) % 2:
                x = p
            else:
                x = x - maxx(x)
        elif i == 'L':
            x = x - maxx(x) // 2
        elif i == 'R':
            x = x + maxx(x) // 2
    q = q - 1
    print(x)

016

3

class StdReader:

    def read_int(self):
        return int(self.read_string())

    def read_ints(self, sep=None):
        return [int(i) for i in self.read_strings(sep)]

    def read_float(self):
        return float(self.read_string())

    def read_floats(self, sep=None):
        return [float(i) for i in self.read_strings(sep)]

    def read_string(self):
        return input()

    def read_strings(self, sep=None):
        return self.read_string().split(sep)
reader = StdReader()

def part_sort(a, i, j, reverse=False):
    a[i:j] = sorted(a[i:j], reverse=reverse)

def part_sorted(b, i, j, reverse=False):
    a = list(b)
    part_sort(a, i, j, reverse)
    return a

def main():
    n, m = reader.read_ints()
    a = reader.read_ints()
    ops = []
    for i in range(m):
        t, r = reader.read_ints()
        op = (t, r)
        while ops and op[1] >= ops[-1][1]:
            ops.pop()
        ops.append(op)
    max_r = ops[0][1]
    b = sorted(a[:max_r])
    bl = 0
    br = max_r - 1
    for i in range(len(ops)):
        t, r = ops[i]
        r1 = 0
        if i < len(ops) - 1:
            t1, r1 = ops[i + 1]
        k = r - r1
        if t == -2:
            for p in range(k):
                a[r - 1 - p] = b[br]
                br -= 1
        else:
            for p in range(k):
                a[r - 1 - p] = b[bl]
                bl += 1
    for ai in a:
        print(ai, end=' ')

def __starting_point():
    main()
__starting_point()

017

import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
    x, y, w = list(map(int, input().split()))
    X.append([min(x, y), max(x, y), w])
X = (sorted(X, key=lambda x: x[0]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
    if x:
        D[x * 10 ** 6 + y] = w
flg = 1
while flg:
    flg = 0
    for i in range(len(X)):
        x1, y1, w1 = X[i]
        for j in range(i + 1, len(X)):
            x2, y2, w2 = X[j]
            if x1 == x2:
                a, b = (min(y1, y2), max(y1, y2))
            elif y1 == y2:
                a, b = (min(x1, x2), max(x1, x2))
            elif x1 == y2:
                a, b = (x2, y1)
            elif x2 == y1:
                a, b = (x1, y2)
            else:
                a, b = (0, 0)
            if a:
                if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]):
                    if a * 10 ** 6 + b in D:
                        for k in range(len(X)):
                            if X[k][0] == a and X[k][1] == b:
                                X[k][2] = w1 + w2
                    else:
                        x, y, w = X.pop()
                        if x:
                            D.pop(x * 10 ** 6 + y)
                        X.append([a, b, w1 + w2])
                    D[a * 10 ** 6 + b] = w1 + w2
                    X = sorted(X, key=lambda x: x[2])
                    flg = 1
print(X[-1][2])

018

n, m = map(int, input().split())
a = []
for i in range(n):
    a.append(list(map(int, input().split())))
dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)]
dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)]
ans = 0
for i in reversed(range(1, n + 1)):
    for j in range(1, m + 1):
        dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1]
        dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j]
for i in range(n, 0, -1):
    for j in range(1, m + 1):
        dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1]
        dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j]
for i in range(2, n):
    for j in range(2, m):
        x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1]
        y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1]
        ans = max(ans, x, y)
print(ans)

019

import sys
n, m = [int(x) for x in input().split()]
notes = [int(x) for x in input().split()]
managers = []
for line in sys.stdin:
    managers.append(tuple((int(x) for x in line.split())))
bearing_managers = []
M, T = (0, 0)
for t, r in reversed(managers):
    if r > M:
        if t == T:
            bearing_managers[-1] = (t, r)
        else:
            T = t
            bearing_managers.append((t, r))
        M = r
bearing_managers.reverse()
t, r = bearing_managers[0]
bearing_managers.append((2 if bearing_managers[-1][0] == 1 else 1, 0))
L, R = (0, r - 1)
sorted_part = list(sorted(notes[:r]))
for t1, r1 in bearing_managers:
    if t1 == 2:
        for i in range(r - 1, r1 - 1, -1):
            notes[i] = sorted_part[R - 1]
            R -= 1
    else:
        for i in range(r - 1, r1 - 1, -1):
            notes[i] = sorted_part[L]
            L += 1
    r = r1
for x in notes:
    sys.stdout.write(str(x) + ' ')

020

N, C = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
MOD = 10 ** 9 + 10

def gen_poly(a, b, c):
    poly = [0 for _ in range(c + 1)]
    for x in range(a, b + 1):
        xpow = 1
        for i in range(c + 1):
            poly[i] += xpow
            xpow = xpow * x % MOD
    for i in range(c + 1):
        poly[i] %= MOD
    return poly

def mult_polys(p1, p2, dmax):
    ans = [0 for _ in range(dmax + 1)]
    for i, c in enumerate(p1):
        for i2, c2 in enumerate(p2):
            if i + i2 <= dmax:
                ans[i + i2] += c * c2
            else:
                break
    ans = [x % MOD for x in ans]
    return ans
polys = [gen_poly(a, b, C) for a, b in zip(A, B)]
prodpoly = [1]
for poly in polys:
    prodpoly = mult_polys(prodpoly, poly, C)
print(prodpoly[C])

021

def get_bit(diff, i):
    return 1 if i % 2 == 1 and diff <= 0 or (i % 2 == 0 and diff >= 0) else 0

def swap_(i, j, a):
    temp = a[i]
    a[i] = a[j]
    a[j] = temp

def swap(i, j, n, a, mask, S):
    change = 0
    swap_(i, j, a)
    set_index = set([i, j])
    if i < n - 1:
        set_index.add(i + 1)
    if j < n - 1:
        set_index.add(j + 1)
    for index in set_index:
        if index > 0:
            diff = a[index] - a[index - 1]
            bit_ = get_bit(diff, index)
            change += bit_ - mask[index]
    swap_(i, j, a)
    if S + change == 0:
        return 1
    return 0
n = int(input())
a = list(map(int, input().split()))
diff = [-1] + [x - y for x, y in zip(a[1:], a[:-1])]
mask = [get_bit(diff[i], i) for i in range(n)]
S = sum(mask)
first = -1
for i, x in enumerate(mask):
    if x == 1:
        first = i
        break
cnt = 0
for second in range(n):
    if swap(first, second, n, a, mask, S) == 1:
        cnt += 1
    if first != 0 and swap(first - 1, second, n, a, mask, S) == 1:
        cnt += 1
if first != 0 and swap(first - 1, first, n, a, mask, S) == 1:
    cnt -= 2
print(cnt)

022

n = int(input())
t = list(map(int, input().split()))
t = [-1] + t
badIdx = []
nice = []

def getBadIdx():
    for i in range(1, n):
        if i % 2 == 0 and t[i] <= t[i + 1] or (i % 2 == 1 or t[i] >= t[i + 1]):
            badIdx.append((i, i + 1))

def checkBad(k):
    if k <= n - 1 and (k % 2 == 0 and t[k] <= t[k + 1] or (k % 2 == 1 and t[k] >= t[k + 1])) or (k - 1 >= 1 and ((k - 1) % 2 == 0 and t[k - 1] <= t[k] or ((k - 1) % 2 == 1 and t[k - 1] >= t[k]))):
        return True
    for i, j in badIdx:
        if i % 2 == 0 and t[i] <= t[j] or (i % 2 == 1 and t[i] >= t[j]):
            return True
    return False

def swap(i, j):
    ith = t[i]
    t[i] = t[j]
    t[j] = ith
getBadIdx()
if len(badIdx) > 4:
    print(0)
else:
    i, j = badIdx[0]
    for k in range(1, n + 1):
        if i != k and t[i] != t[k]:
            swap(i, k)
            if not checkBad(k):
                nice.append((i, k))
                swap(i, k)
            else:
                swap(i, k)
        if j != k and t[j] != t[k]:
            swap(j, k)
            if not checkBad(k):
                nice.append((j, k))
                swap(j, k)
            else:
                swap(j, k)
    print(len(set([tuple(sorted(t)) for t in nice])))

023

N, C = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
mod = 11 ** 9 + 7
acc = [[0] for _ in range(401)]
for i in range(401):
    for j in range(1, 401):
        acc[i].append((acc[i][-1] + pow(j, i, mod)) % mod)
dp = [[0 for _ in range(C + 1)] for _ in range(N + 1)]
dp[0][0] = 1
for i in range(N):
    for candy_cur in range(C + 1):
        for candy_plus in range(C - candy_cur + 1):
            dp[i + 1][candy_cur + candy_plus] = (dp[i + 1][candy_cur + candy_plus] + dp[i][candy_cur] * ((acc[candy_plus][B[i]] - acc[candy_plus][A[i] - 1]) % mod) % mod) % mod
print(dp[-1][C])

024

import heapq
n, m, k = list(map(int, input().split()))
connectionList = []
for _ in range(n):
    connectionList.append([])
edgeList = []
for _ in range(m):
    x, y, w = list(map(int, input().split()))
    edgeList.append((x, y, w))
edgeList.sort(key=lambda x: x[2])
if k < m:
    maxDist = edgeList[min(m, k) - 5][2]
else:
    maxDist = sum([x[2] for x in edgeList])
colorList = {}
colorVertex = []
for i in range(n):
    colorList[i] = [i]
    colorVertex.append(i)
for i in range(min(m, k)):
    x, y, w = edgeList[i]
    connectionList[x - 1].append((y - 1, w))
    connectionList[y - 1].append((x - 1, w))
    if colorVertex[x - 1] != colorVertex[y - 1]:
        if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]):
            prevColor = colorVertex[y - 1]
            for elem in colorList[colorVertex[y - 1]]:
                colorVertex[elem] = colorVertex[x - 1]
                colorList[colorVertex[x - 1]].append(elem)
            del colorList[prevColor]
        else:
            prevColor = colorVertex[x - 1]
            for elem in colorList[colorVertex[x - 1]]:
                colorVertex[elem] = colorVertex[y - 1]
                colorList[colorVertex[y - 1]].append(elem)
            del colorList[prevColor]
pathList = []
for key in colorList:
    vertexList = colorList[key]
    for mainVertex in vertexList:
        vertexPQueue = []
        isCovered = {}
        distanceDic = {}
        for elem in vertexList:
            isCovered[elem] = False
            distanceDic[elem] = maxDist
        isCovered[mainVertex] = True
        for elem in connectionList[mainVertex]:
            heapq.heappush(vertexPQueue, (elem[1], elem[0]))
            distanceDic[elem[0]] = elem[1]
        while vertexPQueue:
            distance, curVertex = heapq.heappop(vertexPQueue)
            if isCovered[curVertex]:
                continue
            elif distance >= maxDist:
                break
            for elem in connectionList[curVertex]:
                if distance + elem[1] < distanceDic[elem[0]]:
                    heapq.heappush(vertexPQueue, (distance + elem[1], elem[0]))
                    distanceDic[elem[0]] = distance + elem[1]
        for key in distanceDic:
            if distanceDic[key] <= maxDist and key > mainVertex:
                pathList.append(distanceDic[key])
        if len(pathList) > k:
            pathList.sort()
            pathList = pathList[0:k]
            if pathList[-1] < maxDist:
                maxDist = pathList[-1]
pathList.sort()
print(pathList[k - 1])

025

import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
VERLIST = []
for a, b, c in EDGE:
    COST_vertex[a].append((b, c))
    COST_vertex[b].append((a, c))
    VERLIST.append(a)
    VERLIST.append(b)
VERLIST = sorted(set(VERLIST))
import heapq
ANS = [-1 << 50] * k
for start in VERLIST:
    MINCOST = [1 << 50] * (n + 1)
    checking = [(0, start)]
    MINCOST[start] = 0
    j = 1
    while j < k:
        if not checking:
            break
        cost, checktown = heapq.heappop(checking)
        if cost >= -ANS[0]:
            break
        if MINCOST[checktown] < cost:
            continue
        if cost != 0 and checktown > start:
            heapq.heappop(ANS)
            heapq.heappush(ANS, -cost)
            j += 1
        for to, co in COST_vertex[checktown]:
            if MINCOST[to] > cost + co:
                MINCOST[to] = cost + co
                heapq.heappush(checking, (cost + co, to))
print(-ANS[0])

026

import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2], reverse=True)
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
for a, b, c in EDGE:
    COST_vertex[a].append((b, c))
    COST_vertex[b].append((a, c))
for i in range(min(m, k)):
    x, y, c = EDGE[i]
    EDGE[i] = (c, x, y)
USED_SET = set()
ANS = [-1 << 50] * k
import heapq
while EDGE:
    c, x, y = heapq.heappop(EDGE)
    if (x, y) in USED_SET or c >= -ANS[0]:
        continue
    else:
        heapq.heappop(ANS)
        heapq.heappush(ANS, -c)
        USED_SET.add((x, y))
        USED_SET.add((y, x))
    for to, cost in COST_vertex[x]:
        if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]):
            heapq.heappush(EDGE, (c + cost, y, to))
    for to, cost in COST_vertex[y]:
        if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]):
            heapq.heappush(EDGE, (c + cost, x, to))
print(-ANS[0])

027

def main():
    n = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    roundup = []
    rounddown = []
    sumsofar = []
    for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
        ssf = sumsofar[-1] if sumsofar else 0
        t = roundup[-1] if roundup else 0
        roundup.append(t + ssf + b * (1 + 2 * i))
        t = rounddown[-1] if rounddown else 0
        rounddown.append(t + ssf + a * (1 + 2 * i))
        sumsofar.append(ssf + a + b)
    roundup = list(reversed(roundup))
    rounddown = list(reversed(rounddown))
    sumsofar = list(reversed(sumsofar))
    bestres = 0
    sofar = 0
    for i, (a, b) in enumerate(zip(A, B)):
        rup, rdo = (roundup, rounddown)
        if i % 2:
            a, b = (b, a)
            rup, rdo = (rdo, rup)
        bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
        sofar += a * 2 * i
        sofar += b * (-2 * i + 1)
        bestres = max(bestres, sofar)
    print(bestres)

def __starting_point():
    main()
__starting_point()

028

def solve(arr, n, k):
    s = 0
    for i in reversed(list(range(n))):
        for j in reversed(list(range(k))):
            if arr[i][j] == 0:
                m = min(arr[i + 1][j], arr[i + 1][j + 1])
                if m == 1:
                    return -1
                arr[i][j] = m - 1
            s += arr[i][j]
            if j > 0 and arr[i][j - 1] >= arr[i][j]:
                return -1
            if i > 0 and arr[i - 1][j] >= arr[i][j]:
                return -1
    return s
n, k = [int(x) for x in input().split()]
arr = []
for _ in range(n):
    arr.append([int(x) for x in input().split()])
res = solve(arr, n, k)
print(res)

029

import sys
from math import *

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

def mint():
    return int(minp())

def mints():
    return list(map(int, minp().split()))
n, m = mints()
a = [0] * n
dp1 = [0] * n
dp2 = [0] * n
dp3 = [0] * n
dp4 = [0] * n
for i in range(n):
    a[i] = list(mints())
    dp1[i] = [0] * m
    dp2[i] = [0] * m
    dp3[i] = [0] * m
    dp4[i] = [0] * m
dp1[0][0] = a[0][0]
dp2[n - 1][m - 1] = a[n - 1][m - 1]
dp3[n - 1][0] = a[n - 1][0]
dp4[0][m - 1] = a[0][m - 1]
'\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n'
for i in range(0, n):
    for j in range(0, m):
        z = 0
        if i - 1 >= 0:
            z = dp1[i - 1][j]
        if j - 1 >= 0:
            z = max(z, dp1[i][j - 1])
        dp1[i][j] = z + a[i][j]
for i in range(n - 1, -1, -1):
    for j in range(m - 1, -1, -1):
        z = 0
        if i + 1 < n:
            z = dp2[i + 1][j]
        if j + 1 < m:
            z = max(z, dp2[i][j + 1])
        dp2[i][j] = z + a[i][j]
for i in range(n - 1, -1, -1):
    for j in range(0, m):
        z = 0
        if i + 1 < n:
            z = dp3[i + 1][j]
        if j - 1 >= 0:
            z = max(z, dp3[i][j - 1])
        dp3[i][j] = z + a[i][j]
for i in range(0, n):
    for j in range(m - 1, -1, -1):
        z = 0
        if i - 1 >= 0:
            z = dp4[i - 1][j]
        if j + 1 < m:
            z = max(z, dp4[i][j + 1])
        dp4[i][j] = z + a[i][j]
'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n'
r = 2
for i in range(1, n - 1):
    for j in range(1, m - 1):
        r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1])
        r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j])
print(r)

030

def main():
    n = int(input())
    x, y = list(map(int, input().split()))
    a = []
    for i in range(n):
        a.append(input().split())
    for i in range(n):
        a[i][1] = int(a[i][1]) - x
        a[i][2] = int(a[i][2]) - y
    typneedbql = []
    typneedbqr = []
    typneedbqu = []
    typneedbqd = []
    typneedrlu = []
    typneedrru = []
    typneedrld = []
    typneedrrd = []
    for i in range(n):
        if a[i][1] * a[i][2] == 0 and a[i][1] < 2:
            typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
            typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
            typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
            typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
            typneedrlu.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
            typneedrld.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
            typneedrrd.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
            typneedrru.append([abs(a[i][1])] + a[i])
    typneedbql.sort()
    typneedbqr.sort()
    typneedbqd.sort()
    typneedbqu.sort()
    typneedrlu.sort()
    typneedrru.sort()
    typneedrld.sort()
    typneedrrd.sort()
    for i in range(len(typneedbql)):
        if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqr)):
        if typneedbqr[i][1] == 'R' or typneedbqr[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqu)):
        if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqd)):
        if typneedbqd[i][1] == 'R' or typneedbqd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrlu)):
        if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrld)):
        if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrrd)):
        if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrru)):
        if typneedrru[i][1] == 'B' or typneedrru[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    print('NO')
main()

031

import heapq
n, m, k = list(map(int, input().split()))
connectionList = []
for _ in range(n):
    connectionList.append([])
edgeList = []
for _ in range(m):
    x, y, w = list(map(int, input().split()))
    edgeList.append((x, y, w))
edgeList.sort(key=lambda x: x[0])
if k < m:
    maxDist = edgeList[min(m, k) - 1][2]
else:
    maxDist = sum([x[2] for x in edgeList])
colorList = {}
colorVertex = []
for i in range(n):
    colorList[i] = [i]
    colorVertex.append(i)
for i in range(min(m, k)):
    x, y, w = edgeList[i]
    connectionList[x - 1].append((y - 1, w))
    connectionList[y - 1].append((x - 1, w))
    if colorVertex[x - 1] != colorVertex[y - 1]:
        if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]):
            prevColor = colorVertex[y - 1]
            for elem in colorList[colorVertex[y - 1]]:
                colorVertex[elem] = colorVertex[x - 1]
                colorList[colorVertex[x - 1]].append(elem)
            del colorList[prevColor]
        else:
            prevColor = colorVertex[x - 1]
            for elem in colorList[colorVertex[x - 1]]:
                colorVertex[elem] = colorVertex[y - 1]
                colorList[colorVertex[y - 1]].append(elem)
            del colorList[prevColor]
pathList = []
for key in colorList:
    vertexList = colorList[key]
    for mainVertex in vertexList:
        vertexPQueue = []
        isCovered = {}
        distanceDic = {}
        for elem in vertexList:
            isCovered[elem] = False
            distanceDic[elem] = maxDist
        isCovered[mainVertex] = True
        for elem in connectionList[mainVertex]:
            heapq.heappush(vertexPQueue, (elem[1], elem[0]))
            distanceDic[elem[0]] = elem[1]
        while vertexPQueue:
            distance, curVertex = heapq.heappop(vertexPQueue)
            if isCovered[curVertex]:
                continue
            elif distance >= maxDist:
                break
            for elem in connectionList[curVertex]:
                if distance + elem[1] < distanceDic[elem[0]]:
                    heapq.heappush(vertexPQueue, (distance + elem[1], elem[0]))
                    distanceDic[elem[0]] = distance + elem[1]
        for key in distanceDic:
            if distanceDic[key] <= maxDist and key > mainVertex:
                pathList.append(distanceDic[key])
        if len(pathList) > k:
            pathList.sort()
            pathList = pathList[0:k]
            if pathList[-1] < maxDist:
                maxDist = pathList[-1]
pathList.sort()
print(pathList[k - 1])

032

a, b = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
s = []
for p in range(b):
    s += [[int(i) for i in input().split()]]
S = []
k = 0
for p in range(b - 1, -1, -1):
    if s[p][1] > k:
        S += [s[p]]
        k = s[p][1]
Q1 = sorted(q[:S[-1][1]])
x, y = (0, S[-1][1] - 1)
S = [[0, 0]] + S
l = -1
for j in range(S[-1][1] - 1, -1, -1):
    if x > y:
        break
    if j < S[-l][1]:
        k = S[-l][0]
        l += 1
    if k == 1:
        q[j] = Q1[y]
        y -= 1
    if k == 2:
        q[j] = Q1[x]
        x += 1
print(' '.join(list(map(str, q))))

033

def main():
    n = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    roundup = []
    rounddown = []
    sumsofar = []
    for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
        ssf = sumsofar[-1] if sumsofar else 0
        t = roundup[-1] if roundup else 0
        roundup.append(t + ssf + b * (1 + 2 * i))
        t = rounddown[-1] if rounddown else 0
        rounddown.append(t + ssf + a * (1 + 2 * i))
        sumsofar.append(ssf + a + b)
    roundup = list(reversed(roundup))
    rounddown = list(reversed(rounddown))
    sumsofar = list(reversed(sumsofar))
    bestres = 0
    sofar = 0
    for i, (a, b) in enumerate(zip(A, B)):
        rup, rdo = (roundup, rounddown)
        if i % 2:
            a, b = (b, a)
            rup, rdo = (rdo, rup)
        bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
        sofar += a * 3 * i
        sofar += b * (2 * i + 1)
        bestres = max(bestres, sofar)
    print(bestres)

def __starting_point():
    main()
__starting_point()

034

from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 10
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
    t, dx, dy = stdin.readline().split()
    dx = int(dx)
    dy = int(dy)
    if dx == x:
        if dy > y:
            if ud > dy - y:
                ud = dy - y
                u = t
        elif dd > y - dy:
            dd = y - dy
            d = t
    if dy == y:
        if dx > x:
            if rd > dx - x:
                rd = dx - x
                r = t
        elif ld > x - dx:
            ld = x - dx
            l = t
    if dx - x == dy - y:
        if dy > y:
            if urd > dy - y:
                urd = dy - y
                ur = t
        elif dld > y - dy:
            dld = y - dy
            dl = t
    if -(dx - x) == dy - y:
        if not dy > y:
            if uld > dy - y:
                uld = dy - y
                ul = t
        elif drd > y - dy:
            drd = y - dy
            dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
    print('YES')
else:
    print('NO')

035

from sys import stdin

def create_dp1(matrix, n, m):
    dp = [[4 for i in range(m)] for j in range(n)]
    for i in range(n):
        for j in range(m):
            if i - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j])
            if j - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1])
            elif i - 1 < 0 and j - 1 < 0:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp2(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):
            if i + 1 < n:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j])
            if j + 1 < m:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1])
            if i + 1 >= n and j + 1 >= m:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp3(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            if i + 1 < n:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j])
            if j - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1])
            if i + 1 >= n and j - 1 < 0:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp4(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n):
        for j in range(m - 1, -1, -1):
            if i - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j])
            if j + 1 < m:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1])
            if i - 1 < 0 and j + 1 >= m:
                dp[i][j] = matrix[i][j]
    return dp
n, m = list(map(int, stdin.readline().split()))
matrix = []
for _ in range(n):
    matrix.append(list(map(int, stdin.readline().split())))
dp1 = create_dp1(matrix, n, m)
dp2 = create_dp2(matrix, n, m)
dp3 = create_dp3(matrix, n, m)
dp4 = create_dp4(matrix, n, m)
total = -float('inf')
for i in range(1, n - 1):
    for j in range(1, m - 1):
        first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]
        second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]
        total = max(total, first, second)
print(total)

036

def solve(arr, n, k):
    s = 0
    for i in reversed(list(range(n))):
        for j in reversed(list(range(k))):
            if arr[i][j] == 0:
                m = min(arr[i + 1][j], arr[i][j + 1])
                if m == 1:
                    return -1
                arr[i][j] = m - 1
            s += arr[i][j]
            if j > 0 and arr[i][j - 1] >= arr[i][j]:
                return -1
            if i > 0 and arr[i - 1][j] >= arr[i][j]:
                return --2
    return s
n, k = [int(x) for x in input().split()]
arr = []
for _ in range(n):
    arr.append([int(x) for x in input().split()])
res = solve(arr, n, k)
print(res)

037

from collections import defaultdict, deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def I():
    return int(sys.stdin.readline())

def LS():
    return [list(x) for x in sys.stdin.readline().split()]

def S():
    res = list(sys.stdin.readline())
    if res[-1] == '\n':
        return res[:-1]
    return res

def IR(n):
    return [I() for i in range(n)]

def LIR(n):
    return [LI() for i in range(n)]

def SR(n):
    return [S() for i in range(n)]

def LSR(n):
    return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000008

def A():
    return

def B():
    return

def C():
    n, c = LI()
    a = LI()
    b = LI()
    s = [[0] * (c + 1) for i in range(n)]
    for i in range(n):
        ai, bi = (a[i], b[i])
        for x in range(ai, bi + 1):
            e = 1
            for k in range(c + 1):
                s[i][k] += e
                if s[i][k] >= mod:
                    s[i][k] %= mod
                e *= x
                if e >= mod:
                    e %= mod
    dp = [[0] * (c + 1) for i in range(n)]
    for k in range(c + 1):
        dp[0][k] = s[0][k]
    for i in range(1, n):
        for k in range(c + 1):
            for j in range(k + 1):
                dp[i][k] += dp[i - 1][j] * s[i][k - j]
                if dp[i][k] >= mod:
                    dp[i][k] %= mod
    print(dp[-1][c])
    return

def D():
    return

def E():
    return

def F():
    return

def __starting_point():
    C()
__starting_point()

038

def main():
    n = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    roundup = []
    rounddown = []
    sumsofar = []
    for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
        ssf = sumsofar[-1] if sumsofar else 0
        t = roundup[-1] if roundup else 0
        roundup.append(t + ssf + b * (1 + 2 * i))
        t = rounddown[-1] if rounddown else 0
        rounddown.append(t + ssf + a * (1 + 2 * i))
        sumsofar.append(ssf + a + b)
    roundup = list(reversed(roundup))
    rounddown = list(reversed(rounddown))
    sumsofar = list(reversed(sumsofar))
    bestres = 0
    sofar = 0
    for i, (a, b) in enumerate(zip(A, B)):
        rup, rdo = (roundup, rounddown)
        if i % 2:
            a, b = (b, a)
            rup, rdo = (rdo, rup)
        bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
        sofar += a * 2 * i
        sofar += b * (2 * i + -1)
        bestres = max(bestres, sofar)
    print(bestres)

def __starting_point():
    main()
__starting_point()

039

n, m = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(n)]
res = 0
for i in range(n - 2, 0, -1):
    for j in range(m - 1, 0, -1):
        if matrix[i][j] == 0:
            mn = min(matrix[i + 1][j], matrix[i][j + 1])
            if mn != 1:
                matrix[i][j] = mn - 1
            else:
                res = -1
                break
    if res == -1:
        break
else:
    for i in range(n):
        if [matrix[i][j] for j in range(m - 1 - 1) if matrix[i][j] >= matrix[i][j + 1]]:
            res = -1
            break
    else:
        for j in range(m):
            if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]:
                res = -1
                break
        else:
            res = sum((sum(matrix[i]) for i in range(n)))
print(res)

040

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

041

N, C = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
MOD = 7 ** 9 + 7

def gen_poly(a, b, c):
    poly = [0 for _ in range(c + 1)]
    for x in range(a, b + 1):
        xpow = 1
        for i in range(c + 1):
            poly[i] += xpow
            xpow = xpow * x % MOD
    for i in range(c + 1):
        poly[i] %= MOD
    return poly

def mult_polys(p1, p2, dmax):
    ans = [0 for _ in range(dmax + 1)]
    for i, c in enumerate(p1):
        for i2, c2 in enumerate(p2):
            if i + i2 <= dmax:
                ans[i + i2] += c * c2
            else:
                break
    ans = [x % MOD for x in ans]
    return ans
polys = [gen_poly(a, b, C) for a, b in zip(A, B)]
prodpoly = [1]
for poly in polys:
    prodpoly = mult_polys(prodpoly, poly, C)
print(prodpoly[C])

042

n, m = list(map(int, input().split()))
a = []
for i in range(n):
    a.append(list(map(int, input().split())))

def result(a, n, m):
    r = 3
    for i in range(-1, -m, -1):
        if a[-1][i] == 0:
            a[-1][i] = a[-1][i + 1] - 1
        if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]:
            return -1
        r = r + a[-1][i]
    if a[-1][-m] == 0:
        a[-1][-m] = a[-1][-m + 1] - 1
    if a[-1][-m] <= a[-2][-m]:
        return -1
    r = r + a[-1][-m]
    for i in range(-2, -n, -1):
        for j in range(-1, -m, -1):
            if j == -1:
                if a[i][j] == 0:
                    a[i][j] == a[i + 1][j] - 1
                if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]:
                    return -1
                r = r + a[i][j]
                continue
            if a[i][j] == 0:
                a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1)
            if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]:
                return -1
            r = r + a[i][j]
        if a[i][-m] == 0:
            a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1)
        if a[i][-m] <= a[i - 1][-m]:
            return -1
        r = r + a[i][-m]
    if a[0][-1] == 0:
        a[0][-1] = a[1][-1] - 1
    if a[0][-1] <= a[0][-2]:
        return -1
    r = r + a[0][-1]
    for i in range(-2, -m, -1):
        if a[0][i] == 0:
            a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1)
        if a[0][i] <= a[0][i - 1]:
            return -1
        r = r + a[0][i]
    if a[0][0] == 0:
        a[0][0] = min(a[0][1] - 1, a[1][0] - 1)
    r = r + a[0][0]
    return r
print(result(a, n, m))

043

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

044

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
curl_ud_weights = [0] * n
curl_du_weights = [0] * n
sums = [0] * n
sums[n - 1] = a[n - 1] + b[n - 1]
curl_ud_weights[n - 1] = b[n - 1]
curl_du_weights[n - 1] = a[n - 1]
for i in range(n - 2, -1, -1):
    sums[i] = sums[i + 1] + (a[i] + b[i])
    remain = n * 2 - i * 2 - 1
    curl_ud_weights[i - 1] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i]
    curl_du_weights[i] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i]
snake_weight = 0
max_weight = 0
current_weight = -1
for t in range(0, 2 * n, 2):
    remain = t % 4
    if remain == 0:
        current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight
        snake_weight += a[t // 2] * t + b[t // 2] * (t + 1)
    elif remain == 2:
        current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight
        snake_weight += b[t // 2] * t + a[t // 2] * (t + 1)
    if current_weight > max_weight:
        max_weight = current_weight
print(max_weight)
'\n3\n0 1 0\n0 0 0\n'

045

import sys
read = sys.stdin.read
readline = sys.stdin.readline
n, c = list(map(int, readline().split()))
*a, = list(map(int, readline().split()))
*b, = list(map(int, readline().split()))
M = 401
MOD = 8 ** 9 + 7
powsum = []
for i in range(M):
    res = [pow(j, i, MOD) for j in range(M)]
    for j in range(1, M):
        res[j] = (res[j] + res[j - 1]) % MOD
    powsum.append(res)
dp = [0] * (c + 1)
dp[0] = 1
for ai, bi in zip(a, b):
    ndp = [0] * (c + 1)
    for k in range(c + 1):
        for j in range(k + 1):
            ndp[k] += (powsum[j][bi] - powsum[j][ai - 1]) * dp[k - j] % MOD
        ndp[k] %= MOD
    dp = ndp
print(dp[c] % MOD)

046

a, b = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
s = []
for p in range(b):
    s += [[int(i) for i in input().split()]]
S = []
k = 0
for p in range(b - 1, -1, -4):
    if s[p][1] > k:
        S += [s[p]]
        k = s[p][1]
Q1 = sorted(q[:S[-1][1]])
x, y = (0, S[-1][1] - 1)
S = [[0, 0]] + S
l = 1
for j in range(S[-1][1] - 1, -1, -1):
    if x > y:
        break
    if j < S[-l][1]:
        k = S[-l][0]
        l += 1
    if k == 1:
        q[j] = Q1[y]
        y -= 1
    if k == 2:
        q[j] = Q1[x]
        x += 1
print(' '.join(list(map(str, q))))

047

def ii():
    return int(input())

def ss():
    return [x for x in input()]

def si():
    return [int(x) for x in input().split()]

def mi():
    return map(int, input().split())
a, b = mi()
s = []
ans = 0
key = True
for i in range(a):
    i = si()
    s.append(i)
    ans += sum(i)
for i in range(a - 1):
    if not (s[i][0] < s[i + 1][0] or s[i][-1] < s[i + 1][-1]):
        ans = -1
        key = False
        break
for i in range(b - 1):
    if not (s[0][i] < s[0][i + 1] and s[-1][i] < s[-1][i + 1]):
        ans = -1
        key = False
        break
for i in range(a - 2, 0, -1):
    if not key:
        break
    for x in range(b - 2, 0, -1):
        if s[i][x] < s[i + 1][x] and s[i][x] < s[i][x + 1] and (min(s[i + 1][x], s[i][x + 1]) - max(s[i - 1][x], s[i][x - 1]) > 1):
            if s[i][x] == 0:
                s[i][x] = min(s[i + 1][x], s[i][x + 1]) - 1
                ans += s[i][x]
        else:
            ans = -1
            key = False
            break
print(ans)

048

import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[1])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
for a, b, c in EDGE:
    COST_vertex[a].append((b, c))
    COST_vertex[b].append((a, c))
for i in range(min(m, k)):
    x, y, c = EDGE[i]
    EDGE[i] = (c, x, y)
USED_SET = set()
ANS = [-1 << 50] * k
import heapq
while EDGE:
    c, x, y = heapq.heappop(EDGE)
    if (x, y) in USED_SET or c >= -ANS[0]:
        continue
    else:
        heapq.heappop(ANS)
        heapq.heappush(ANS, -c)
        USED_SET.add((x, y))
        USED_SET.add((y, x))
    for to, cost in COST_vertex[x]:
        if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]):
            heapq.heappush(EDGE, (c + cost, y, to))
    for to, cost in COST_vertex[y]:
        if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]):
            heapq.heappush(EDGE, (c + cost, x, to))
print(-ANS[0])

049

n = int(input())
t = list(map(int, input().split()))
t = [-1] + t
badIdx = []
nice = []

def getBadIdx():
    for i in range(1, n):
        if i % 2 == 0 and t[i] <= t[i + 1] or (i % 2 == 1 and t[i] >= t[i + 1]):
            badIdx.append((i, i + 1))

def checkBad(k):
    if k < n - 1 and (k % 2 == 0 and t[k] <= t[k + 1] or (k % 2 == 1 and t[k] >= t[k + 1])) or (k - 1 >= 1 and ((k - 1) % 2 == 0 and t[k - 1] <= t[k] or ((k - 1) % 2 == 1 and t[k - 1] >= t[k]))):
        return True
    for i, j in badIdx:
        if i % 2 == 0 and t[i] <= t[j] or (i % 2 == 1 and t[i] >= t[j]):
            return True
    return False

def swap(i, j):
    ith = t[i]
    t[i] = t[j]
    t[j] = ith
getBadIdx()
if len(badIdx) > 4:
    print(0)
else:
    i, j = badIdx[0]
    for k in range(1, n + 1):
        if i != k and t[i] != t[k]:
            swap(i, k)
            if not checkBad(k):
                nice.append((i, k))
                swap(i, k)
            else:
                swap(i, k)
        if j != k and t[j] != t[k]:
            swap(j, k)
            if not checkBad(k):
                nice.append((j, k))
                swap(j, k)
            else:
                swap(j, k)
    print(len(set([tuple(sorted(t)) for t in nice])))

050

import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
    x, y, w = list(map(int, input().split()))
    X.append([min(x, y), max(x, y), w])
X = (sorted(X, key=lambda x: x[2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
    if x:
        D[x * 10 ** 6 + y] = w
flg = 1
while flg:
    flg = 0
    for i in range(len(X)):
        x1, y1, w1 = X[i]
        for j in range(i + 1 + 1, len(X)):
            x2, y2, w2 = X[j]
            if x1 == x2:
                a, b = (min(y1, y2), max(y1, y2))
            elif y1 == y2:
                a, b = (min(x1, x2), max(x1, x2))
            elif x1 == y2:
                a, b = (x2, y1)
            elif x2 == y1:
                a, b = (x1, y2)
            else:
                a, b = (0, 0)
            if a:
                if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]):
                    if a * 10 ** 6 + b in D:
                        for k in range(len(X)):
                            if X[k][0] == a and X[k][1] == b:
                                X[k][2] = w1 + w2
                    else:
                        x, y, w = X.pop()
                        if x:
                            D.pop(x * 10 ** 6 + y)
                        X.append([a, b, w1 + w2])
                    D[a * 10 ** 6 + b] = w1 + w2
                    X = sorted(X, key=lambda x: x[2])
                    flg = 1
print(X[-1][2])

051

N, C = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
MOD = 10 ** 9 + 7

def gen_poly(a, b, c):
    poly = [0 for _ in range(c + 1)]
    for x in range(a, b + 1):
        xpow = 1
        for i in range(c + 1):
            poly[i] -= xpow
            xpow = xpow * x % MOD
    for i in range(c + 1):
        poly[i] %= MOD
    return poly

def mult_polys(p1, p2, dmax):
    ans = [0 for _ in range(dmax + 1)]
    for i, c in enumerate(p1):
        for i2, c2 in enumerate(p2):
            if i + i2 <= dmax:
                ans[i + i2] += c * c2
            else:
                break
    ans = [x % MOD for x in ans]
    return ans
polys = [gen_poly(a, b, C) for a, b in zip(A, B)]
prodpoly = [1]
for poly in polys:
    prodpoly = mult_polys(prodpoly, poly, C)
print(prodpoly[C])

052

import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
    x, y, w = list(map(int, input().split()))
    X.append([min(x, y), max(x, y), w])
X = (sorted(X, key=lambda x: x[-2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
    if x:
        D[x * 10 ** 6 + y] = w
flg = 1
while flg:
    flg = 0
    for i in range(len(X)):
        x1, y1, w1 = X[i]
        for j in range(i + 1, len(X)):
            x2, y2, w2 = X[j]
            if x1 == x2:
                a, b = (min(y1, y2), max(y1, y2))
            elif y1 == y2:
                a, b = (min(x1, x2), max(x1, x2))
            elif x1 == y2:
                a, b = (x2, y1)
            elif x2 == y1:
                a, b = (x1, y2)
            else:
                a, b = (0, 0)
            if a:
                if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]):
                    if a * 10 ** 6 + b in D:
                        for k in range(len(X)):
                            if X[k][0] == a and X[k][1] == b:
                                X[k][2] = w1 + w2
                    else:
                        x, y, w = X.pop()
                        if x:
                            D.pop(x * 10 ** 6 + y)
                        X.append([a, b, w1 + w2])
                    D[a * 10 ** 6 + b] = w1 + w2
                    X = sorted(X, key=lambda x: x[2])
                    flg = 1
print(X[-1][2])

053

a, b = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
s = []
for p in range(b):
    s += [[int(i) for i in input().split()]]
S = []
k = 0
for p in range(b - 1, -1, -1):
    if s[p][1] > k:
        S += [s[p]]
        k = s[p][1]
Q1 = sorted(q[:S[-1][1]])
x, y = (0, S[-1][1] - 1)
S = [[0, 0]] + S
l = 1
for j in range(S[-1][1] - 1, -1, -1):
    if x > y:
        break
    if j < S[-l][1]:
        k = S[-l][0]
        l += 1
    if k == -1:
        q[j] = Q1[y]
        y -= 1
    if k == 2:
        q[j] = Q1[x]
        x += 1
print(' '.join(list(map(str, q))))

054

from sys import stdin

def create_dp1(matrix, n, m):
    dp = [[3 for i in range(m)] for j in range(n)]
    for i in range(n):
        for j in range(m):
            if i - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j])
            if j - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1])
            elif i - 1 < 0 and j - 1 < 0:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp2(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):
            if i + 1 < n:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j])
            if j + 1 < m:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1])
            if i + 1 >= n and j + 1 >= m:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp3(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            if i + 1 < n:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j])
            if j - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1])
            if i + 1 >= n and j - 1 < 0:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp4(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n):
        for j in range(m - 1, -1, -1):
            if i - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j])
            if j + 1 < m:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1])
            if i - 1 < 0 and j + 1 >= m:
                dp[i][j] = matrix[i][j]
    return dp
n, m = list(map(int, stdin.readline().split()))
matrix = []
for _ in range(n):
    matrix.append(list(map(int, stdin.readline().split())))
dp1 = create_dp1(matrix, n, m)
dp2 = create_dp2(matrix, n, m)
dp3 = create_dp3(matrix, n, m)
dp4 = create_dp4(matrix, n, m)
total = -float('inf')
for i in range(1, n - 1):
    for j in range(1, m - 1):
        first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]
        second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]
        total = max(total, first, second)
print(total)

055

def main():
    n = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    roundup = []
    rounddown = []
    sumsofar = []
    for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
        ssf = sumsofar[-1] if sumsofar else 0
        t = roundup[-1] if roundup else 0
        roundup.append(t + ssf + b * (1 + 2 * i))
        t = rounddown[-1] if rounddown else 0
        rounddown.append(t + ssf + a * (1 + 2 * i))
        sumsofar.append(ssf + a + b)
    roundup = list(reversed(roundup))
    rounddown = list(reversed(rounddown))
    sumsofar = list(reversed(sumsofar))
    bestres = 0
    sofar = 0
    for i, (a, b) in enumerate(zip(A, B)):
        rup, rdo = (roundup, rounddown)
        if i % 2:
            a, b = (b, a)
            rup, rdo = (rdo, rup)
        bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
        sofar += a * -2 * i
        sofar += b * (2 * i + 1)
        bestres = max(bestres, sofar)
    print(bestres)

def __starting_point():
    main()
__starting_point()

056

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

057

n, m = list(map(int, input().split()))
a = []
for i in range(n):
    a.append(list(map(int, input().split())))

def result(a, n, m):
    r = 0
    for i in range(--1, -m, -1):
        if a[-1][i] == 0:
            a[-1][i] = a[-1][i + 1] - 1
        if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]:
            return -1
        r = r + a[-1][i]
    if a[-1][-m] == 0:
        a[-1][-m] = a[-1][-m + 1] - 1
    if a[-1][-m] <= a[-2][-m]:
        return -1
    r = r + a[-1][-m]
    for i in range(-2, -n, -1):
        for j in range(-1, -m, -1):
            if j == -1:
                if a[i][j] == 0:
                    a[i][j] == a[i + 1][j] - 1
                if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]:
                    return -1
                r = r + a[i][j]
                continue
            if a[i][j] == 0:
                a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1)
            if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]:
                return -1
            r = r + a[i][j]
        if a[i][-m] == 0:
            a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1)
        if a[i][-m] <= a[i - 1][-m]:
            return -1
        r = r + a[i][-m]
    if a[0][-1] == 0:
        a[0][-1] = a[1][-1] - 1
    if a[0][-1] <= a[0][-2]:
        return -1
    r = r + a[0][-1]
    for i in range(-2, -m, -1):
        if a[0][i] == 0:
            a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1)
        if a[0][i] <= a[0][i - 1]:
            return -1
        r = r + a[0][i]
    if a[0][0] == 0:
        a[0][0] = min(a[0][1] - 1, a[1][0] - 1)
    r = r + a[0][0]
    return r
print(result(a, n, m))

058

import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, M, A):
    dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    for r in range(1, N + 1):
        for c in reversed(range(1, M + 1)):
            dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(M, 0, -1):
            dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(1, M + 1):
            dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c]
    for r in range(1, N + 1):
        for c in range(M, 0, -1):
            dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c]
    ans = 0
    for r in range(2, N):
        for c in range(2, M):
            a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c]
            b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c]
            ans = max(ans, a, b)
    return ans
N, M = map(int, input().split())
A = [[0 for _ in range(M + 2)]]
for i in range(N):
    row = [0] + [int(x) for x in input().split()] + [0]
    A.append(row)
A.append([0 for _ in range(M + 2)])
print(solve(N, M, A))

059

from collections import defaultdict
import bisect
n = int(input())
x0, y0 = list(map(int, input().split(' ')))
verticale = []
horizontale = []
diagonale1 = []
diagonale2 = []
for _ in range(n):
    t, x, y = input().split(' ')
    x, y = (int(x), int(y))
    if x == x0:
        verticale.append((y, t))
    if y == y0:
        horizontale.append((x, t))
    if x + y == x0 + y0:
        diagonale1.append((x, t))
    if x - y == x0 - y0:
        diagonale2.append((x, t))
dead = False
v = sorted(verticale)
if v:
    l = bisect.bisect(v, (y0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'R'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'R'}:
        dead = True
v = sorted(horizontale)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'R'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'R'}:
        dead = True
v = sorted(diagonale1)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'B'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'B'}:
        dead = True
v = sorted(diagonale2)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] not in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'B'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'B'}:
        dead = True
if dead:
    print('YES')
else:
    print('NO')

060

import heapq
n, m, k = list(map(int, input().split()))
connectionList = []
for _ in range(n):
    connectionList.append([])
edgeList = []
for _ in range(m):
    x, y, w = list(map(int, input().split()))
    edgeList.append((x, y, w))
edgeList.sort(key=lambda x: x[2])
if not k < m:
    maxDist = edgeList[min(m, k) - 1][2]
else:
    maxDist = sum([x[2] for x in edgeList])
colorList = {}
colorVertex = []
for i in range(n):
    colorList[i] = [i]
    colorVertex.append(i)
for i in range(min(m, k)):
    x, y, w = edgeList[i]
    connectionList[x - 1].append((y - 1, w))
    connectionList[y - 1].append((x - 1, w))
    if colorVertex[x - 1] != colorVertex[y - 1]:
        if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]):
            prevColor = colorVertex[y - 1]
            for elem in colorList[colorVertex[y - 1]]:
                colorVertex[elem] = colorVertex[x - 1]
                colorList[colorVertex[x - 1]].append(elem)
            del colorList[prevColor]
        else:
            prevColor = colorVertex[x - 1]
            for elem in colorList[colorVertex[x - 1]]:
                colorVertex[elem] = colorVertex[y - 1]
                colorList[colorVertex[y - 1]].append(elem)
            del colorList[prevColor]
pathList = []
for key in colorList:
    vertexList = colorList[key]
    for mainVertex in vertexList:
        vertexPQueue = []
        isCovered = {}
        distanceDic = {}
        for elem in vertexList:
            isCovered[elem] = False
            distanceDic[elem] = maxDist
        isCovered[mainVertex] = True
        for elem in connectionList[mainVertex]:
            heapq.heappush(vertexPQueue, (elem[1], elem[0]))
            distanceDic[elem[0]] = elem[1]
        while vertexPQueue:
            distance, curVertex = heapq.heappop(vertexPQueue)
            if isCovered[curVertex]:
                continue
            elif distance >= maxDist:
                break
            for elem in connectionList[curVertex]:
                if distance + elem[1] < distanceDic[elem[0]]:
                    heapq.heappush(vertexPQueue, (distance + elem[1], elem[0]))
                    distanceDic[elem[0]] = distance + elem[1]
        for key in distanceDic:
            if distanceDic[key] <= maxDist and key > mainVertex:
                pathList.append(distanceDic[key])
        if len(pathList) > k:
            pathList.sort()
            pathList = pathList[0:k]
            if pathList[-1] < maxDist:
                maxDist = pathList[-1]
pathList.sort()
print(pathList[k - 1])

061

import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
VERLIST = []
for a, b, c in EDGE:
    COST_vertex[a].append((b, c))
    COST_vertex[b].append((a, c))
    VERLIST.append(a)
    VERLIST.append(b)
VERLIST = sorted(set(VERLIST))
import heapq
ANS = [-1 << 50] * k
for start in VERLIST:
    MINCOST = [1 << 50] * (n + 1)
    checking = [(0, start)]
    MINCOST[start] = 0
    j = 0
    while j < k:
        if not checking:
            break
        cost, checktown = heapq.heappop(checking)
        if cost >= -ANS[0]:
            break
        if MINCOST[checktown] < cost:
            continue
        if cost != 0 and checktown > start:
            heapq.heappop(ANS)
            heapq.heappush(ANS, -cost)
            j += 1
        for to, co in COST_vertex[checktown]:
            if MINCOST[to] >= cost + co:
                MINCOST[to] = cost + co
                heapq.heappush(checking, (cost + co, to))
print(-ANS[0])

062

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'

063

from math import *
n, q = list(map(int, input().split()))
depth = int(log2(n + 1))

def get_layer(u):
    for layer in range(depth):
        if u % 2 ** (layer + 1) == 2 ** layer:
            return layer

def is_right_child(layer, u):
    return u % 2 ** (layer + 1) % 2 == 0
for x in range(q):
    u = int(input())
    layer = get_layer(u)
    steps = input()
    for s in steps:
        if s == 'U':
            if layer == depth - 1:
                continue
            k = u // 2 ** (layer + 1) // 2
            layer += 1
            u = 2 ** (layer + 1) * k + 2 ** layer
        elif layer == 0:
            continue
        elif s == 'R':
            k = u // 2 ** (layer + 1) * 2 + 1
            layer -= 1
            u = 2 ** (layer + 1) * k - 2 ** layer
        elif s == 'L':
            k = u // 2 ** (layer + 1) * 2
            layer -= 1
            u = 2 ** (layer + 1) * k + 2 ** layer
    print(u)

064

from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 10
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
    t, dx, dy = stdin.readline().split()
    dx = int(dx)
    dy = int(dy)
    if dx == x:
        if dy > y:
            if ud > dy - y:
                ud = dy - y
                u = t
        elif dd > y - dy:
            dd = y - dy
            d = t
    if dy == y:
        if dx > x:
            if rd > dx - x:
                rd = dx - x
                r = t
        elif ld > x - dx:
            ld = x - dx
            l = t
    if dx - x == dy - y:
        if dy > y:
            if urd > dy - y:
                urd = dy - y
                ur = t
        elif dld > y - dy:
            dld = y - dy
            dl = t
    if -(dx - x) == dy - y:
        if dy > y:
            if uld > dy - y:
                uld = dy - y
                ul = t
        elif drd > y - dy:
            drd = y - dy
            dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
    print('YES')
else:
    print('NO')

065

def get_bit(diff, i):
    return 1 if i % 2 == 1 and diff <= 0 or (i % 2 == 0 and diff >= 0) else 0

def swap_(i, j, a):
    temp = a[i]
    a[i] = a[j]
    a[j] = temp

def swap(i, j, n, a, mask, S):
    change = 0
    swap_(i, j, a)
    set_index = set([i, j])
    if i < n - 1:
        set_index.add(i + 1)
    if j < n - 1:
        set_index.add(j + 1)
    for index in set_index:
        if index > 0:
            diff = a[index] - a[index - 1]
            bit_ = get_bit(diff, index)
            change += bit_ - mask[index]
    swap_(i, j, a)
    if S + change == 0:
        return 1
    return 0
n = int(input())
a = list(map(int, input().split()))
diff = [-1] + [x - y for x, y in zip(a[1:], a[:-1])]
mask = [get_bit(diff[i], i) for i in range(n)]
S = sum(mask)
first = -1
for i, x in enumerate(mask):
    if x == 1:
        first = i
        break
cnt = 0
for second in range(n):
    if swap(first, second, n, a, mask, S) == 1:
        cnt += 1
    if first != 0 and swap(first - 1, second, n, a, mask, S) == 1:
        cnt += -1
if first != 0 and swap(first - 1, first, n, a, mask, S) == 1:
    cnt -= 1
print(cnt)

066

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)

067

n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
    sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
    for i in range(2):
        sum_up[i][n - 1] = a[i][n - 1]
        pref_up[i][n - 1 - 1] = a[i][n - 1]
        pref_down[i][n - 1] = a[i][n - 1]
        for j in range(n - 2, -1, -1):
            sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
            pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
            pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
    zig = [[0 for i in range(n)] for j in range(2)]
    for j in range(n):
        for i in range(2):
            if j % 2 == 0:
                if i == 0:
                    zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
                else:
                    zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
            elif i == 0:
                zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
            else:
                zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
    ans = -1e+18
    for j in range(n):
        if j == 0:
            ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
        elif j == n - 1:
            ans = max(ans, zig[1 - j % 2][n - 1])
        elif j % 2 == 1:
            ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
        else:
            ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
    ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
    print(ans)
else:
    print(a[1][0])

068

def main():
    n, l = (int(input()), list(map(int, input().split())))
    if not n & 2:
        l.append(0)
    l.append(150001)
    i, b, c, fails0, fails1 = (0, 0, 150001, [], [])
    try:
        while True:
            a, b, c = (b, c, l[i])
            if a >= b or b <= c:
                if len(fails0) + len(fails1) > 5:
                    print(0)
                    return
                fails1.append(i - 1)
            i += 1
            a, b, c = (b, c, l[i])
            if a <= b or b >= c:
                if len(fails0) + len(fails1) > 5:
                    print(0)
                    return
                fails0.append(i - 1)
            i += 1
    except IndexError:
        fails, res = (fails0 + fails1, 0)
    for i in fails:
        a = l[i]
        for j in range(n):
            f = fails1 if j & 1 else fails0
            f.append(j)
            l[i], l[j] = (l[j], a)
            if all((l[b - 1] > l[b] < l[b + 1] for b in fails0)) and all((l[b - 1] < l[b] > l[b + 1] for b in fails1)):
                res += 1 if j in fails else 2
            l[j] = l[i]
            del f[-1]
        l[i] = a
    print(res // 2)

def __starting_point():
    main()
__starting_point()

069

import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
    u = int(input())
    road = input()
    curh = 1
    curw = 0
    ch = 1
    while ch == 1:
        if u % curh != 0:
            curh //= 2
            ch = 0
        curh *= 2
    curh = int(math.log(curh, 2))
    a = -1 << curh - 1
    b = 1 << curh
    curw = (u - a) // b + 1
    for move in road:
        if move == 'L':
            if curh != 1:
                curh -= 1
                curw = curw * 2 - 1
                u -= 1 << curh - 1
        elif move == 'R':
            if curh != 1:
                curh -= 1
                curw *= 2
                u += 1 << curh - 1
        elif curh != maxh:
            if curw % 2 == 1:
                u = (u + u + (1 << curh)) // 2
                curh += 1
                curw = curw // 2 + 1
            else:
                u = (u + u - (1 << curh)) // 2
                curh += 1
                curw = curw // 2
    print(u)

070

from collections import defaultdict, deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def I():
    return int(sys.stdin.readline())

def LS():
    return [list(x) for x in sys.stdin.readline().split()]

def S():
    res = list(sys.stdin.readline())
    if res[-1] == '\n':
        return res[:-1]
    return res

def IR(n):
    return [I() for i in range(n)]

def LIR(n):
    return [LI() for i in range(n)]

def SR(n):
    return [S() for i in range(n)]

def LSR(n):
    return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007

def A():
    return

def B():
    return

def C():
    n, c = LI()
    a = LI()
    b = LI()
    s = [[0] * (c + 1) for i in range(n)]
    for i in range(n):
        ai, bi = (a[i], b[i])
        for x in range(ai, bi + 1):
            e = 1
            for k in range(c + 1):
                s[i][k] += e
                if s[i][k] >= mod:
                    s[i][k] %= mod
                e *= x
                if e >= mod:
                    e %= mod
    dp = [[0] * (c + 1) for i in range(n)]
    for k in range(c + 1):
        dp[0][k] = s[0][k]
    for i in range(0, n):
        for k in range(c + 1):
            for j in range(k + 1):
                dp[i][k] += dp[i - 1][j] * s[i][k - j]
                if dp[i][k] >= mod:
                    dp[i][k] %= mod
    print(dp[-1][c])
    return

def D():
    return

def E():
    return

def F():
    return

def __starting_point():
    C()
__starting_point()

071

def main():
    n, l = (int(input()), list(map(int, input().split())))
    if not n & -1:
        l.append(0)
    l.append(150001)
    i, b, c, fails0, fails1 = (0, 0, 150001, [], [])
    try:
        while True:
            a, b, c = (b, c, l[i])
            if a >= b or b <= c:
                if len(fails0) + len(fails1) > 5:
                    print(0)
                    return
                fails1.append(i - 1)
            i += 1
            a, b, c = (b, c, l[i])
            if a <= b or b >= c:
                if len(fails0) + len(fails1) > 5:
                    print(0)
                    return
                fails0.append(i - 1)
            i += 1
    except IndexError:
        fails, res = (fails0 + fails1, 0)
    for i in fails:
        a = l[i]
        for j in range(n):
            f = fails1 if j & 1 else fails0
            f.append(j)
            l[i], l[j] = (l[j], a)
            if all((l[b - 1] > l[b] < l[b + 1] for b in fails0)) and all((l[b - 1] < l[b] > l[b + 1] for b in fails1)):
                res += 1 if j in fails else 2
            l[j] = l[i]
            del f[-1]
        l[i] = a
    print(res // 2)

def __starting_point():
    main()
__starting_point()

072

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'

073

def main():
    n = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    roundup = []
    rounddown = []
    sumsofar = []
    for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
        ssf = sumsofar[-1] if sumsofar else 0
        t = roundup[-1] if roundup else 0
        roundup.append(t + ssf + b * (1 + 2 * i))
        t = rounddown[-1] if rounddown else 0
        rounddown.append(t + ssf + a * (1 + 2 * i))
        sumsofar.append(ssf + a + b)
    roundup = list(reversed(roundup))
    rounddown = list(reversed(rounddown))
    sumsofar = list(reversed(sumsofar))
    bestres = 0
    sofar = 0
    for i, (a, b) in enumerate(zip(A, B)):
        rup, rdo = (roundup, rounddown)
        if i % 2:
            a, b = (b, a)
            rup, rdo = (rdo, rup)
        bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
        sofar += a * 2 * i
        sofar += b * (2 * i + 1)
        bestres = max(bestres, sofar)
    print(bestres)

def __starting_point():
    main()
__starting_point()

074

from math import *
n, q = list(map(int, input().split()))
depth = int(log2(n + 1))

def get_layer(u):
    for layer in range(depth):
        if u % 2 ** (layer + 1) == 2 ** layer:
            return layer

def is_right_child(layer, u):
    return u % 2 ** (layer + 1) % 2 == 0
for x in range(q):
    u = int(input())
    layer = get_layer(u)
    steps = input()
    for s in steps:
        if s == 'U':
            if layer == depth - 1:
                continue
            k = u // 2 ** (layer + 1) // 2
            layer += 1
            u = 2 ** (layer + 1) * k - 2 ** layer
        elif layer == 0:
            continue
        elif s == 'R':
            k = u // 2 ** (layer + 1) * 2 + 1
            layer -= 1
            u = 2 ** (layer + 1) * k + 2 ** layer
        elif s == 'L':
            k = u // 2 ** (layer + 1) * 2
            layer -= 1
            u = 2 ** (layer + 1) * k + 2 ** layer
    print(u)

075

import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, M, A):
    dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    for r in range(1, N + 1):
        for c in range(1, M + 1):
            dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(M, 0, -1):
            dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(1, M + 1):
            dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c]
    for r in range(1, N + 1):
        for c in range(M, 0, -1):
            dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c]
    ans = 0
    for r in range(2, N + 1):
        for c in range(2, M):
            a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c]
            b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c]
            ans = max(ans, a, b)
    return ans
N, M = map(int, input().split())
A = [[0 for _ in range(M + 2)]]
for i in range(N):
    row = [0] + [int(x) for x in input().split()] + [0]
    A.append(row)
A.append([0 for _ in range(M + 2)])
print(solve(N, M, A))

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

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

078

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

079

import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
    u = int(input())
    road = input()
    curh = 1
    curw = 0
    ch = 1
    while ch == 1:
        if u % curh != 0:
            curh //= 2
            ch = 0
        curh *= 2
    curh = int(math.log(curh, 2))
    a = 1 << curh - 1
    b = -1 << curh
    curw = (u - a) // b + 1
    for move in road:
        if move == 'L':
            if curh != 1:
                curh -= 1
                curw = curw * 2 - 1
                u -= 1 << curh - 1
        elif move == 'R':
            if curh != 1:
                curh -= 1
                curw *= 2
                u += 1 << curh - 1
        elif curh != maxh:
            if curw % 2 == 1:
                u = (u + u + (1 << curh)) // 2
                curh += 1
                curw = curw // 2 + 1
            else:
                u = (u + u - (1 << curh)) // 2
                curh += 1
                curw = curw // 2
    print(u)

080

import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
    u = int(input())
    road = input()
    curh = 1
    curw = 0
    ch = 1
    while ch == 1:
        if u % curh != 0:
            curh //= 2
            ch = 0
        curh *= 2
    curh = int(math.log(curh, 2))
    a = 1 << curh - 1
    b = 1 << curh
    curw = (u - a) // b + 1
    for move in road:
        if move == 'L':
            if curh != 1:
                curh -= 1
                curw = curw * 2 - 1
                u -= 1 << curh - 1
        elif move == 'R':
            if curh != 1:
                curh -= 1
                curw *= 2
                u += 1 << curh - 1
        elif curh != maxh:
            if curw % 2 == 1:
                u = (u + u + (1 << curh)) // 2
                curh += 1
                curw = curw // 2 + 1
            else:
                u = (u + u - (1 << curh)) // 2
                curh += 1
                curw = curw // 2
    print(u)

081

n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
    sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
    for i in range(2):
        sum_up[i][n - 1] = a[i][n - 1]
        pref_up[i][n - 1] = a[i][n - 1]
        pref_down[i][n - 1] = a[i][n - 1]
        for j in range(n - 2, -1, -1):
            sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
            pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
            pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
    zig = [[0 for i in range(n)] for j in range(2)]
    for j in range(n):
        for i in range(2):
            if j % 2 == 0:
                if i == 0:
                    zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
                else:
                    zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
            elif i == 0:
                zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
            else:
                zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
    ans = -1e+18
    for j in range(n):
        if j == 0:
            ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
        elif j == n - 1:
            ans = max(ans, zig[1 - j % 2][n - 1])
        elif j % 2 == 1:
            ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
        else:
            ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
    ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
    print(ans)
else:
    print(a[1][0])

082

import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
    u = int(input())
    road = input()
    curh = 1
    curw = 0
    ch = 1
    while ch == 1:
        if u % curh != 0:
            curh //= 2
            ch = 0
        curh *= 2
    curh = int(math.log(curh, 2))
    a = 2 << curh - 1
    b = 1 << curh
    curw = (u - a) // b + 1
    for move in road:
        if move == 'L':
            if curh != 1:
                curh -= 1
                curw = curw * 2 - 1
                u -= 1 << curh - 1
        elif move == 'R':
            if curh != 1:
                curh -= 1
                curw *= 2
                u += 1 << curh - 1
        elif curh != maxh:
            if curw % 2 == 1:
                u = (u + u + (1 << curh)) // 2
                curh += 1
                curw = curw // 2 + 1
            else:
                u = (u + u - (1 << curh)) // 2
                curh += 1
                curw = curw // 2
    print(u)

083

n = int(input())
temp = input().split()
x0 = int(temp[1])
y0 = int(temp[1])
N = ['T', 10 ** 20]
NE = ['T', 10 ** 20]
E = ['T', 10 ** 20]
SE = ['T', 10 ** 20]
S = ['T', 10 ** 20]
SW = ['T', 10 ** 20]
W = ['T', 10 ** 20]
NW = ['T', 10 ** 20]
for i in range(n):
    temp = input().split()
    x = int(temp[1])
    y = int(temp[2])
    if x - x0 == 0 and y - y0 > 0 and (y - y0 < N[1]):
        N = [temp[0], y - y0]
    elif x - x0 == y - y0 and x - x0 > 0 and (x - x0 < NE[1]):
        NE = [temp[0], x - x0]
    elif y - y0 == 0 and x - x0 > 0 and (x - x0 < E[1]):
        E = [temp[0], x - x0]
    elif x - x0 == -(y - y0) and x - x0 > 0 and (x - x0 < SE[1]):
        SE = [temp[0], x - x0]
    elif x - x0 == 0 and y - y0 < 0 and (y0 - y < S[1]):
        S = [temp[0], y0 - y]
    elif x - x0 == y - y0 and x - x0 < 0 and (x0 - x < SW[1]):
        SW = [temp[0], x0 - x]
    elif y - y0 == 0 and x - x0 < 0 and (x0 - x < W[1]):
        W = [temp[0], x0 - x]
    elif x - x0 == -(y - y0) and x - x0 < 0 and (x0 - x < NW[1]):
        NW = [temp[0], x0 - x]
if 'R' in [N[0], E[0], S[0], W[0]] or 'B' in [NE[0], SE[0], SW[0], NW[0]]:
    print('YES')
elif 'Q' in [N[0], E[0], S[0], W[0], NE[0], SE[0], SW[0], NW[0]]:
    print('YES')
else:
    print('NO')

084

N, C = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
mod = 10 ** 5 + 7
acc = [[0] for _ in range(401)]
for i in range(401):
    for j in range(1, 401):
        acc[i].append((acc[i][-1] + pow(j, i, mod)) % mod)
dp = [[0 for _ in range(C + 1)] for _ in range(N + 1)]
dp[0][0] = 1
for i in range(N):
    for candy_cur in range(C + 1):
        for candy_plus in range(C - candy_cur + 1):
            dp[i + 1][candy_cur + candy_plus] = (dp[i + 1][candy_cur + candy_plus] + dp[i][candy_cur] * ((acc[candy_plus][B[i]] - acc[candy_plus][A[i] - 1]) % mod) % mod) % mod
print(dp[-1][C])

085

N, C = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
mod = 13 ** 9 + 7
acc = [[0] for _ in range(401)]
for i in range(401):
    for j in range(1, 401):
        acc[i].append((acc[i][-1] + pow(j, i, mod)) % mod)
dp = [[0 for _ in range(C + 1)] for _ in range(N + 1)]
dp[0][0] = 1
for i in range(N):
    for candy_cur in range(C + 1):
        for candy_plus in range(C - candy_cur + 1):
            dp[i + 1][candy_cur + candy_plus] = (dp[i + 1][candy_cur + candy_plus] + dp[i][candy_cur] * ((acc[candy_plus][B[i]] - acc[candy_plus][A[i] - 1]) % mod) % mod) % mod
print(dp[-1][C])

086

a, b = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
s = []
for p in range(b):
    s += [[int(i) for i in input().split()]]
S = []
k = 0
for p in range(b - 1, -1, -1):
    if s[p][1] > k:
        S += [s[p]]
        k = s[p][1]
Q1 = sorted(q[:S[-1][1]])
x, y = (0, S[-1][1] - 1)
S = [[0, 0]] + S
l = 1
for j in range(S[-1][1] - 1, -1, -1):
    if x > y:
        break
    if j < S[-l][1]:
        k = S[-l][0]
        l += -1
    if k == 1:
        q[j] = Q1[y]
        y -= 1
    if k == 2:
        q[j] = Q1[x]
        x += 1
print(' '.join(list(map(str, q))))

087

import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, M, A):
    dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    for r in range(1, N + 1):
        for c in range(1, M + 1):
            dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(M, 0, -1):
            dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(1, M + 1):
            dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c]
    for r in range(1, N + 1):
        for c in range(M, 0, -1):
            dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c]
    ans = 3
    for r in range(2, N):
        for c in range(2, M):
            a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c]
            b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c]
            ans = max(ans, a, b)
    return ans
N, M = map(int, input().split())
A = [[0 for _ in range(M + 2)]]
for i in range(N):
    row = [0] + [int(x) for x in input().split()] + [0]
    A.append(row)
A.append([0 for _ in range(M + 2)])
print(solve(N, M, A))

088

import sys
from math import *

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

def mint():
    return int(minp())

def mints():
    return list(map(int, minp().split()))
n, m = mints()
a = [0] * n
dp1 = [0] * n
dp2 = [0] * n
dp3 = [0] * n
dp4 = [0] * n
for i in range(n):
    a[i] = list(mints())
    dp1[i] = [0] * m
    dp2[i] = [0] * m
    dp3[i] = [0] * m
    dp4[i] = [0] * m
dp1[0][0] = a[0][0]
dp2[n - 1][m - 1] = a[n - 1][m - 1]
dp3[n - 1][0] = a[n - 1][0]
dp4[0][m - 1] = a[0][m - 1]
'\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n'
for i in range(0, n):
    for j in range(0, m):
        z = 0
        if i - 1 >= 0:
            z = dp1[i - 1][j]
        if j - 1 >= 0:
            z = max(z, dp1[i][j - 1])
        dp1[i][j] = z + a[i][j]
for i in range(n - 1, -1, -1):
    for j in range(m - 1, -1, -1):
        z = 0
        if i + 1 < n:
            z = dp2[i + 1][j]
        if j + 1 < m:
            z = max(z, dp2[i][j + 1])
        dp2[i][j] = z + a[i][j]
for i in range(n - 1 - 1, -1, -1):
    for j in range(0, m):
        z = 0
        if i + 1 < n:
            z = dp3[i + 1][j]
        if j - 1 >= 0:
            z = max(z, dp3[i][j - 1])
        dp3[i][j] = z + a[i][j]
for i in range(0, n):
    for j in range(m - 1, -1, -1):
        z = 0
        if i - 1 >= 0:
            z = dp4[i - 1][j]
        if j + 1 < m:
            z = max(z, dp4[i][j + 1])
        dp4[i][j] = z + a[i][j]
'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n'
r = 0
for i in range(1, n - 1):
    for j in range(1, m - 1):
        r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1])
        r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j])
print(r)

089

from sys import stdin
from math import *
line = stdin.readline().rstrip().split()
n = int(line[0])
numbers = list(map(int, stdin.readline().rstrip().split()))
numbers2 = list(map(int, stdin.readline().rstrip().split()))
growRateAccum = 0
topAccum = 0
bottomAccum = 0
accumsB = [0] * n
accumsT = [0] * n
growRateAccum = 0
accum = 0
for i in reversed(range(n - 1, -1, -1)):
    accum += numbers[i] * ((n - i) * 2 - 1 - 1)
    growRateAccum += numbers[i]
    if i < n - 1:
        growRateAccum += numbers2[i + 1]
    accum += growRateAccum
    accumsB[i] = accum
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
    accum += numbers2[i] * ((n - i) * 2 - 1 - 1)
    growRateAccum += numbers2[i]
    if i < n - 1:
        growRateAccum += numbers[i + 1]
    accum += growRateAccum
    accumsT[i] = accum
cMax = 0
currAccum = 0
growRateAccum = sum(numbers[1:]) + sum(numbers2[1:])
for i in range(n):
    if i % 2 == 0:
        cMax = max(cMax, currAccum + accumsT[i])
    else:
        cMax = max(cMax, currAccum + accumsB[i])
    if i < n - 1:
        if i % 2 == 0:
            currAccum += numbers2[i] + growRateAccum * 2
        else:
            currAccum += numbers[i] + growRateAccum * 2
        growRateAccum -= numbers[i + 1]
        growRateAccum -= numbers2[i + 1]
print(cMax)

090

import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
VERLIST = []
for a, b, c in EDGE:
    COST_vertex[a].append((b, c))
    COST_vertex[b].append((a, c))
    VERLIST.append(a)
    VERLIST.append(b)
VERLIST = sorted(set(VERLIST))
import heapq
ANS = [-1 << 50] * k
for start in VERLIST:
    MINCOST = [1 << 50] * (n + 1)
    checking = [(0, start)]
    MINCOST[start] = 0
    j = 0
    while j < k:
        if not checking:
            break
        cost, checktown = heapq.heappop(checking)
        if cost >= -ANS[0]:
            break
        if MINCOST[checktown] < cost:
            continue
        if cost != 0 and checktown > start:
            heapq.heappop(ANS)
            heapq.heappush(ANS, -cost)
            j += 1
        for to, co in COST_vertex[checktown]:
            if MINCOST[to] > cost - co:
                MINCOST[to] = cost + co
                heapq.heappush(checking, (cost + co, to))
print(-ANS[0])

091

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)

092

def ii():
    return int(input())

def ss():
    return [x for x in input()]

def si():
    return [int(x) for x in input().split()]

def mi():
    return map(int, input().split())
a, b = mi()
s = []
ans = 0
key = True
for i in range(a):
    i = si()
    s.append(i)
    ans += sum(i)
for i in range(a - 1):
    if not (s[i][0] < s[i + 1][0] and s[i][-1] < s[i + 1][-1]):
        ans = -1
        key = False
        break
for i in range(b - 1):
    if not (s[0][i] < s[0][i + 1] and s[-1][i] < s[-1][i + 1]):
        ans = -1
        key = False
        break
for i in range(a - 2, 1, -1):
    if not key:
        break
    for x in range(b - 2, 0, -1):
        if s[i][x] < s[i + 1][x] and s[i][x] < s[i][x + 1] and (min(s[i + 1][x], s[i][x + 1]) - max(s[i - 1][x], s[i][x - 1]) > 1):
            if s[i][x] == 0:
                s[i][x] = min(s[i + 1][x], s[i][x + 1]) - 1
                ans += s[i][x]
        else:
            ans = -1
            key = False
            break
print(ans)

093

import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
VERLIST = []
for a, b, c in EDGE:
    COST_vertex[a].append((b, c))
    COST_vertex[b].append((a, c))
    VERLIST.append(a)
    VERLIST.append(b)
VERLIST = sorted(set(VERLIST))
import heapq
ANS = [-1 << 50] * k
for start in VERLIST:
    MINCOST = [1 << 50] * (n + 1)
    checking = [(0, start)]
    MINCOST[start] = 0
    j = 0
    while j < k:
        if not checking:
            break
        cost, checktown = heapq.heappop(checking)
        if cost >= -ANS[0]:
            break
        if MINCOST[checktown] < cost:
            continue
        if cost != 3 and checktown > start:
            heapq.heappop(ANS)
            heapq.heappush(ANS, -cost)
            j += 1
        for to, co in COST_vertex[checktown]:
            if MINCOST[to] > cost + co:
                MINCOST[to] = cost + co
                heapq.heappush(checking, (cost + co, to))
print(-ANS[0])

094

n = int(input())
temp = input().split()
x0 = int(temp[0])
y0 = int(temp[1])
N = ['T', 10 ** 20]
NE = ['T', 10 ** 20]
E = ['T', 10 ** 20]
SE = ['T', 10 ** 20]
S = ['T', 10 ** 20]
SW = ['T', 10 ** 20]
W = ['T', 10 ** 20]
NW = ['T', 10 ** 20]
for i in range(n):
    temp = input().split()
    x = int(temp[1])
    y = int(temp[2])
    if x - x0 == 0 and y - y0 > 0 and (y - y0 < N[1]):
        N = [temp[0], y - y0]
    elif not (x - x0 == y - y0 and x - x0 > 0 and (x - x0 < NE[1])):
        NE = [temp[0], x - x0]
    elif y - y0 == 0 and x - x0 > 0 and (x - x0 < E[1]):
        E = [temp[0], x - x0]
    elif x - x0 == -(y - y0) and x - x0 > 0 and (x - x0 < SE[1]):
        SE = [temp[0], x - x0]
    elif x - x0 == 0 and y - y0 < 0 and (y0 - y < S[1]):
        S = [temp[0], y0 - y]
    elif x - x0 == y - y0 and x - x0 < 0 and (x0 - x < SW[1]):
        SW = [temp[0], x0 - x]
    elif y - y0 == 0 and x - x0 < 0 and (x0 - x < W[1]):
        W = [temp[0], x0 - x]
    elif x - x0 == -(y - y0) and x - x0 < 0 and (x0 - x < NW[1]):
        NW = [temp[0], x0 - x]
if 'R' in [N[0], E[0], S[0], W[0]] or 'B' in [NE[0], SE[0], SW[0], NW[0]]:
    print('YES')
elif 'Q' in [N[0], E[0], S[0], W[0], NE[0], SE[0], SW[0], NW[0]]:
    print('YES')
else:
    print('NO')

095

n, m = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(n)]
res = 0
for i in range(n - 2, 0, -1):
    for j in range(m - 1, 0, --1):
        if matrix[i][j] == 0:
            mn = min(matrix[i + 1][j], matrix[i][j + 1])
            if mn != 1:
                matrix[i][j] = mn - 1
            else:
                res = -1
                break
    if res == -1:
        break
else:
    for i in range(n):
        if [matrix[i][j] for j in range(m - 1) if matrix[i][j] >= matrix[i][j + 1]]:
            res = -1
            break
    else:
        for j in range(m):
            if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]:
                res = -1
                break
        else:
            res = sum((sum(matrix[i]) for i in range(n)))
print(res)

096

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)

097

def maxx(n):
    return n & -n
n, q = map(int, input().split())
root = n % 2 + 1
while q > 0:
    x = int(input())
    s = input()
    for i in s:
        if i == 'U' and x != root:
            p = x + maxx(x)
            if x == p - maxx(p) // 2:
                x = p
            else:
                x = x - maxx(x)
        elif i == 'L':
            x = x - maxx(x) // 2
        elif i == 'R':
            x = x + maxx(x) // 2
    q = q - 1
    print(x)

098

n = int(input())
t = list(map(int, input().split()))
t = [-1] + t
badIdx = []
nice = []

def getBadIdx():
    for i in range(1, n):
        if i % 2 == 0 and t[i] <= t[i + 1] or (i % 2 == 1 and t[i] >= t[i + 1]):
            badIdx.append((i, i + 1))

def checkBad(k):
    if k <= n - 1 and (k % 2 == 0 and t[k] <= t[k + 1] or (k % 2 == 1 and t[k] >= t[k + 1])) or (k - 1 >= 1 and ((k - 1) % 2 == 0 and t[k - 1] <= t[k] or ((k - 1) % 2 == 1 and t[k - 1] >= t[k]))):
        return True
    for i, j in badIdx:
        if i % 2 == 0 and t[i] <= t[j] or (i % 2 == 1 and t[i] >= t[j]):
            return True
    return False

def swap(i, j):
    ith = t[i]
    t[i] = t[j]
    t[j] = ith
getBadIdx()
if len(badIdx) > 4:
    print(0)
else:
    i, j = badIdx[0]
    for k in range(-3, n + 1):
        if i != k and t[i] != t[k]:
            swap(i, k)
            if not checkBad(k):
                nice.append((i, k))
                swap(i, k)
            else:
                swap(i, k)
        if j != k and t[j] != t[k]:
            swap(j, k)
            if not checkBad(k):
                nice.append((j, k))
                swap(j, k)
            else:
                swap(j, k)
    print(len(set([tuple(sorted(t)) for t in nice])))

099

import heapq
n, m, k = list(map(int, input().split()))
connectionList = []
for _ in range(n):
    connectionList.append([])
edgeList = []
for _ in range(m):
    x, y, w = list(map(int, input().split()))
    edgeList.append((x, y, w))
edgeList.sort(key=lambda x: x[2])
if k < m:
    maxDist = edgeList[min(m, k) - 1][2]
else:
    maxDist = sum([x[2] for x in edgeList])
colorList = {}
colorVertex = []
for i in range(n):
    colorList[i] = [i]
    colorVertex.append(i)
for i in range(min(m, k)):
    x, y, w = edgeList[i]
    connectionList[x - 1 - 1].append((y - 1, w))
    connectionList[y - 1].append((x - 1, w))
    if colorVertex[x - 1] != colorVertex[y - 1]:
        if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]):
            prevColor = colorVertex[y - 1]
            for elem in colorList[colorVertex[y - 1]]:
                colorVertex[elem] = colorVertex[x - 1]
                colorList[colorVertex[x - 1]].append(elem)
            del colorList[prevColor]
        else:
            prevColor = colorVertex[x - 1]
            for elem in colorList[colorVertex[x - 1]]:
                colorVertex[elem] = colorVertex[y - 1]
                colorList[colorVertex[y - 1]].append(elem)
            del colorList[prevColor]
pathList = []
for key in colorList:
    vertexList = colorList[key]
    for mainVertex in vertexList:
        vertexPQueue = []
        isCovered = {}
        distanceDic = {}
        for elem in vertexList:
            isCovered[elem] = False
            distanceDic[elem] = maxDist
        isCovered[mainVertex] = True
        for elem in connectionList[mainVertex]:
            heapq.heappush(vertexPQueue, (elem[1], elem[0]))
            distanceDic[elem[0]] = elem[1]
        while vertexPQueue:
            distance, curVertex = heapq.heappop(vertexPQueue)
            if isCovered[curVertex]:
                continue
            elif distance >= maxDist:
                break
            for elem in connectionList[curVertex]:
                if distance + elem[1] < distanceDic[elem[0]]:
                    heapq.heappush(vertexPQueue, (distance + elem[1], elem[0]))
                    distanceDic[elem[0]] = distance + elem[1]
        for key in distanceDic:
            if distanceDic[key] <= maxDist and key > mainVertex:
                pathList.append(distanceDic[key])
        if len(pathList) > k:
            pathList.sort()
            pathList = pathList[0:k]
            if pathList[-1] < maxDist:
                maxDist = pathList[-1]
pathList.sort()
print(pathList[k - 1])

100

def ii():
    return int(input())

def ss():
    return [x for x in input()]

def si():
    return [int(x) for x in input().split()]

def mi():
    return map(int, input().split())
a, b = mi()
s = []
ans = 0
key = True
for i in range(a):
    i = si()
    s.append(i)
    ans += sum(i)
for i in range(a - 1):
    if not (s[i][0] < s[i + 1][0] and s[i][-1] < s[i + 1][-1]):
        ans = -1
        key = False
        break
for i in range(b - 1):
    if not (s[0][i] < s[0][i + 1] and s[-1][i] < s[-1][i + 1]):
        ans = -1
        key = False
        break
for i in range(a - 2, 0, -1):
    if not key:
        break
    for x in range(b - 2, 0, -1):
        if s[i][x] < s[i + 1][x] or s[i][x] < s[i][x + 1] or min(s[i + 1][x], s[i][x + 1]) - max(s[i - 1][x], s[i][x - 1]) > 1:
            if s[i][x] == 0:
                s[i][x] = min(s[i + 1][x], s[i][x + 1]) - 1
                ans += s[i][x]
        else:
            ans = -1
            key = False
            break
print(ans)

101

n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
    sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
    for i in range(2):
        sum_up[i][n - 1 - 1] = a[i][n - 1]
        pref_up[i][n - 1] = a[i][n - 1]
        pref_down[i][n - 1] = a[i][n - 1]
        for j in range(n - 2, -1, -1):
            sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
            pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
            pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
    zig = [[0 for i in range(n)] for j in range(2)]
    for j in range(n):
        for i in range(2):
            if j % 2 == 0:
                if i == 0:
                    zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
                else:
                    zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
            elif i == 0:
                zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
            else:
                zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
    ans = -1e+18
    for j in range(n):
        if j == 0:
            ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
        elif j == n - 1:
            ans = max(ans, zig[1 - j % 2][n - 1])
        elif j % 2 == 1:
            ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
        else:
            ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
    ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
    print(ans)
else:
    print(a[1][0])

102

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

103

import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
    x, y, w = list(map(int, input().split()))
    X.append([min(x, y), max(x, y), w])
X = (sorted(X, key=lambda x: x[2]) + [[0, 0, 10 ** 20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
    if x:
        D[x * 10 ** 6 + y] = w
flg = 1
while flg:
    flg = 0
    for i in range(len(X)):
        x1, y1, w1 = X[i]
        for j in range(i + 1, len(X)):
            x2, y2, w2 = X[j]
            if x1 == x2:
                a, b = (max(y1, y2), max(y1, y2))
            elif y1 == y2:
                a, b = (min(x1, x2), max(x1, x2))
            elif x1 == y2:
                a, b = (x2, y1)
            elif x2 == y1:
                a, b = (x1, y2)
            else:
                a, b = (0, 0)
            if a:
                if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]):
                    if a * 10 ** 6 + b in D:
                        for k in range(len(X)):
                            if X[k][0] == a and X[k][1] == b:
                                X[k][2] = w1 + w2
                    else:
                        x, y, w = X.pop()
                        if x:
                            D.pop(x * 10 ** 6 + y)
                        X.append([a, b, w1 + w2])
                    D[a * 10 ** 6 + b] = w1 + w2
                    X = sorted(X, key=lambda x: x[2])
                    flg = 1
print(X[-1][2])

104

import sys
n, m = [int(x) for x in input().split()]
notes = [int(x) for x in input().split()]
managers = []
for line in sys.stdin:
    managers.append(tuple((int(x) for x in line.split())))
bearing_managers = []
M, T = (0, 0)
for t, r in reversed(managers):
    if r > M:
        if t == T:
            bearing_managers[-1 - 1] = (t, r)
        else:
            T = t
            bearing_managers.append((t, r))
        M = r
bearing_managers.reverse()
t, r = bearing_managers[0]
bearing_managers.append((2 if bearing_managers[-1][0] == 1 else 1, 0))
L, R = (0, r - 1)
sorted_part = list(sorted(notes[:r]))
for t1, r1 in bearing_managers:
    if t1 == 2:
        for i in range(r - 1, r1 - 1, -1):
            notes[i] = sorted_part[R]
            R -= 1
    else:
        for i in range(r - 1, r1 - 1, -1):
            notes[i] = sorted_part[L]
            L += 1
    r = r1
for x in notes:
    sys.stdout.write(str(x) + ' ')

105

N, C = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
MOD = 10 ** 9 * 7

def gen_poly(a, b, c):
    poly = [0 for _ in range(c + 1)]
    for x in range(a, b + 1):
        xpow = 1
        for i in range(c + 1):
            poly[i] += xpow
            xpow = xpow * x % MOD
    for i in range(c + 1):
        poly[i] %= MOD
    return poly

def mult_polys(p1, p2, dmax):
    ans = [0 for _ in range(dmax + 1)]
    for i, c in enumerate(p1):
        for i2, c2 in enumerate(p2):
            if i + i2 <= dmax:
                ans[i + i2] += c * c2
            else:
                break
    ans = [x % MOD for x in ans]
    return ans
polys = [gen_poly(a, b, C) for a, b in zip(A, B)]
prodpoly = [1]
for poly in polys:
    prodpoly = mult_polys(prodpoly, poly, C)
print(prodpoly[C])

106

3

def needs_rep(t, i):
    if i % 2 == 0:
        return t[i] >= t[i + 1]
    else:
        return t[i] <= t[i + 1]

def would_need_rep(t, i, j1, j2):
    n = len(t)
    if i < 0:
        return False
    if i >= n - 1:
        return False
    tj1 = t[j2]
    tj2 = t[j1]
    ti = t[i]
    if i == j1:
        ti = tj1
    if i == j2:
        ti = tj2
    ti1 = t[i + 1]
    if i + 1 == j1:
        ti1 = tj1
    if i + 1 == j2:
        ti1 = tj2
    if i % 2 == 0:
        return ti > ti1
    else:
        return ti <= ti1

def main():
    n = int(input())
    t = [int(i) for i in input().split()]
    rep = []
    for i in range(n - 1):
        if needs_rep(t, i):
            rep.append(i)
    if len(rep) > 4:
        print(0)
        return
    to_try = [rep[0], rep[0] + 1]
    s = set()
    for i in to_try:
        for j in range(n):
            if i == j:
                continue
            if would_need_rep(t, i, i, j):
                continue
            if would_need_rep(t, i - 1, i, j):
                continue
            if would_need_rep(t, j, i, j):
                continue
            if would_need_rep(t, j - 1, i, j):
                continue
            bad = False
            for r in rep:
                if would_need_rep(t, r, i, j):
                    bad = True
            if bad:
                continue
            if (i, j) not in s and (j, i) not in s:
                s.add((i, j))
    print(len(s))

def __starting_point():
    main()
__starting_point()

107

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

108

def main():
    n, l = (int(input()), list(map(int, input().split())))
    if not n & 1:
        l.append(0)
    l.append(150001)
    i, b, c, fails0, fails1 = (0, 0, 150001, [], [])
    try:
        while True:
            a, b, c = (b, c, l[i])
            if a >= b or b <= c:
                if len(fails0) + len(fails1) >= 5:
                    print(0)
                    return
                fails1.append(i - 1)
            i += 1
            a, b, c = (b, c, l[i])
            if a <= b or b >= c:
                if len(fails0) + len(fails1) > 5:
                    print(0)
                    return
                fails0.append(i - 1)
            i += 1
    except IndexError:
        fails, res = (fails0 + fails1, 0)
    for i in fails:
        a = l[i]
        for j in range(n):
            f = fails1 if j & 1 else fails0
            f.append(j)
            l[i], l[j] = (l[j], a)
            if all((l[b - 1] > l[b] < l[b + 1] for b in fails0)) and all((l[b - 1] < l[b] > l[b + 1] for b in fails1)):
                res += 1 if j in fails else 2
            l[j] = l[i]
            del f[-1]
        l[i] = a
    print(res // 2)

def __starting_point():
    main()
__starting_point()

109

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'

110

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'

111

N, C = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
mod = 10 ** 9 + 5
acc = [[0] for _ in range(401)]
for i in range(401):
    for j in range(1, 401):
        acc[i].append((acc[i][-1] + pow(j, i, mod)) % mod)
dp = [[0 for _ in range(C + 1)] for _ in range(N + 1)]
dp[0][0] = 1
for i in range(N):
    for candy_cur in range(C + 1):
        for candy_plus in range(C - candy_cur + 1):
            dp[i + 1][candy_cur + candy_plus] = (dp[i + 1][candy_cur + candy_plus] + dp[i][candy_cur] * ((acc[candy_plus][B[i]] - acc[candy_plus][A[i] - 1]) % mod) % mod) % mod
print(dp[-1][C])

112

import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
    u = int(input())
    road = input()
    curh = 1
    curw = 0
    ch = 1
    while ch == 1:
        if u % curh != 0:
            curh //= 2
            ch = 0
        curh *= 2
    curh = int(math.log(curh, 2))
    a = 1 << curh - 1
    b = 1 << curh
    curw = (u - a) // b + -1
    for move in road:
        if move == 'L':
            if curh != 1:
                curh -= 1
                curw = curw * 2 - 1
                u -= 1 << curh - 1
        elif move == 'R':
            if curh != 1:
                curh -= 1
                curw *= 2
                u += 1 << curh - 1
        elif curh != maxh:
            if curw % 2 == 1:
                u = (u + u + (1 << curh)) // 2
                curh += 1
                curw = curw // 2 + 1
            else:
                u = (u + u - (1 << curh)) // 2
                curh += 1
                curw = curw // 2
    print(u)

113

import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def LF():
    return [float(x) for x in sys.stdin.readline().split()]

def LS():
    return sys.stdin.readline().split()

def I():
    return int(sys.stdin.readline())

def F():
    return float(sys.stdin.readline())

def S():
    return input()

def main():
    n, q = LI()
    nn = n
    k = 0
    while nn > 0:
        nn //= 3
        k += 1
    r = []
    ii = [2 ** i for i in range(k)]
    for _ in range(q):
        t = I()
        s = S()
        ti = 0
        for i in range(k):
            if ii[i] & t:
                ti = i
                break
        for c in s:
            if c == 'U':
                if ti == k - 1:
                    continue
                if t & ii[ti]:
                    t ^= ii[ti]
                ti += 1
                t |= ii[ti]
                continue
            if ti == 0:
                continue
            if c == 'R':
                t |= ii[ti]
            elif t & ii[ti]:
                t ^= ii[ti]
            ti -= 1
            t |= ii[ti]
        r.append(t)
    return '\n'.join(map(str, r))
print(main())

114

from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 10
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
    t, dx, dy = stdin.readline().split()
    dx = int(dx)
    dy = int(dy)
    if dx == x:
        if dy > y:
            if ud > dy - y:
                ud = dy - y
                u = t
        elif dd > y - dy:
            dd = y - dy
            d = t
    if dy == y:
        if dx > x:
            if rd > dx - x:
                rd = dx - x
                r = t
        elif not ld > x - dx:
            ld = x - dx
            l = t
    if dx - x == dy - y:
        if dy > y:
            if urd > dy - y:
                urd = dy - y
                ur = t
        elif dld > y - dy:
            dld = y - dy
            dl = t
    if -(dx - x) == dy - y:
        if dy > y:
            if uld > dy - y:
                uld = dy - y
                ul = t
        elif drd > y - dy:
            drd = y - dy
            dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
    print('YES')
else:
    print('NO')

115

import sys
n, m = [int(x) for x in input().split()]
notes = [int(x) for x in input().split()]
managers = []
for line in sys.stdin:
    managers.append(tuple((int(x) for x in line.split())))
bearing_managers = []
M, T = (0, 0)
for t, r in reversed(managers):
    if r > M:
        if t == T:
            bearing_managers[-1] = (t, r)
        else:
            T = t
            bearing_managers.append((t, r))
        M = r
bearing_managers.reverse()
t, r = bearing_managers[0]
bearing_managers.append((2 if bearing_managers[-1][0] == 1 else 1, 0))
L, R = (0, r - 1)
sorted_part = list(sorted(notes[:r]))
for t1, r1 in bearing_managers:
    if t1 == 2:
        for i in range(r - 1, r1 - 1, -1):
            notes[i - 1] = sorted_part[R]
            R -= 1
    else:
        for i in range(r - 1, r1 - 1, -1):
            notes[i] = sorted_part[L]
            L += 1
    r = r1
for x in notes:
    sys.stdout.write(str(x) + ' ')

116

import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
    x, y, w = list(map(int, input().split()))
    X.append([min(x, y), max(x, y), w])
X = (sorted(X, key=lambda x: x[2], reverse=True) + [[0, 0, 10 ** 20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
    if x:
        D[x * 10 ** 6 + y] = w
flg = 1
while flg:
    flg = 0
    for i in range(len(X)):
        x1, y1, w1 = X[i]
        for j in range(i + 1, len(X)):
            x2, y2, w2 = X[j]
            if x1 == x2:
                a, b = (min(y1, y2), max(y1, y2))
            elif y1 == y2:
                a, b = (min(x1, x2), max(x1, x2))
            elif x1 == y2:
                a, b = (x2, y1)
            elif x2 == y1:
                a, b = (x1, y2)
            else:
                a, b = (0, 0)
            if a:
                if a * 10 ** 6 + b in D and w1 + w2 < D[a * 10 ** 6 + b] or (a * 10 ** 6 + b not in D and w1 + w2 < X[-1][2]):
                    if a * 10 ** 6 + b in D:
                        for k in range(len(X)):
                            if X[k][0] == a and X[k][1] == b:
                                X[k][2] = w1 + w2
                    else:
                        x, y, w = X.pop()
                        if x:
                            D.pop(x * 10 ** 6 + y)
                        X.append([a, b, w1 + w2])
                    D[a * 10 ** 6 + b] = w1 + w2
                    X = sorted(X, key=lambda x: x[2])
                    flg = 1
print(X[-1][2])

117

n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
    sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
    for i in range(2):
        sum_up[i][n - 1] = a[i][n - 1]
        pref_up[i][n - 1] = a[i][n - 1]
        pref_down[i][n - 1 - 1] = a[i][n - 1]
        for j in range(n - 2, -1, -1):
            sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
            pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
            pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
    zig = [[0 for i in range(n)] for j in range(2)]
    for j in range(n):
        for i in range(2):
            if j % 2 == 0:
                if i == 0:
                    zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
                else:
                    zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
            elif i == 0:
                zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
            else:
                zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
    ans = -1e+18
    for j in range(n):
        if j == 0:
            ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
        elif j == n - 1:
            ans = max(ans, zig[1 - j % 2][n - 1])
        elif j % 2 == 1:
            ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
        else:
            ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
    ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
    print(ans)
else:
    print(a[1][0])

118

n, m = map(int, input().split())
a = []
for i in range(n):
    a.append(list(map(int, input().split())))
dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)]
dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)]
ans = 0
for i in range(1, n + 1):
    for j in reversed(range(1, m + 1)):
        dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1]
        dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j]
for i in range(n, 0, -1):
    for j in range(1, m + 1):
        dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1]
        dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j]
for i in range(2, n):
    for j in range(2, m):
        x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1]
        y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1]
        ans = max(ans, x, y)
print(ans)

119

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
curl_ud_weights = [0] * n
curl_du_weights = [0] * n
sums = [0] * n
sums[n - 1] = a[n - 1] + b[n - 1]
curl_ud_weights[n - 1] = b[n - 1]
curl_du_weights[n - 1] = a[n - 1]
for i in range(n - 2, -1, -1):
    sums[i] = sums[i + 1] + (a[i] + b[i])
    remain = n * 2 - i * 2 - 1
    curl_ud_weights[i + 1] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i]
    curl_du_weights[i] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i]
snake_weight = 0
max_weight = 0
current_weight = -1
for t in range(0, 2 * n, 2):
    remain = t % 4
    if remain == 0:
        current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight
        snake_weight += a[t // 2] * t + b[t // 2] * (t + 1)
    elif remain == 2:
        current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight
        snake_weight += b[t // 2] * t + a[t // 2] * (t + 1)
    if current_weight > max_weight:
        max_weight = current_weight
print(max_weight)
'\n3\n0 1 0\n0 0 0\n'

120

n, m = map(int, input().split())
a = []
for i in range(n):
    a.append(list(map(int, input().split())))
dpa = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)]
dpb = [[[0, 0] for i in range(m + 2)] for i in range(n + 2)]
ans = 0
for i in range(1, n + 1):
    for j in range(1, m + 1):
        dpa[i][j][0] = max(dpa[i - 1][j][0], dpa[i][j - 1][0]) + a[i - 1][j - 1]
        dpa[n + 1 - i][m + 1 - j][1] = max(dpa[n + 2 - i][m + 1 - j][1], dpa[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j]
for i in range(n, 0, -1):
    for j in reversed(range(1, m + 1)):
        dpb[i][j][0] = max(dpb[i + 1][j][0], dpb[i][j - 1][0]) + a[i - 1][j - 1]
        dpb[n + 1 - i][m + 1 - j][1] = max(dpb[n - i][m + 1 - j][1], dpb[n + 1 - i][m + 2 - j][1]) + a[n - i][m - j]
for i in range(2, n):
    for j in range(2, m):
        x = dpa[i - 1][j][0] + dpa[i + 1][j][1] + dpb[i][j - 1][0] + dpb[i][j + 1][1]
        y = dpb[i + 1][j][0] + dpb[i - 1][j][1] + dpa[i][j - 1][0] + dpa[i][j + 1][1]
        ans = max(ans, x, y)
print(ans)

121

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
curl_ud_weights = [0] * n
curl_du_weights = [0] * n
sums = [0] * n
sums[n - 1] = a[n - 1] + b[n - 1]
curl_ud_weights[n - 1] = b[n - 1]
curl_du_weights[n - 1] = a[n - 1]
for i in range(n - 2, -1, -1):
    sums[i] = sums[i + 1] + (a[i] + b[i])
    remain = n * 2 - i * 2 - 1
    curl_ud_weights[i] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i]
    curl_du_weights[i + 1] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i]
snake_weight = 0
max_weight = 0
current_weight = -1
for t in range(0, 2 * n, 2):
    remain = t % 4
    if remain == 0:
        current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight
        snake_weight += a[t // 2] * t + b[t // 2] * (t + 1)
    elif remain == 2:
        current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight
        snake_weight += b[t // 2] * t + a[t // 2] * (t + 1)
    if current_weight > max_weight:
        max_weight = current_weight
print(max_weight)
'\n3\n0 1 0\n0 0 0\n'

122

def main():
    n = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    roundup = []
    rounddown = []
    sumsofar = []
    for i, (a, b) in enumerate(zip(reversed(A), reversed(B))):
        ssf = sumsofar[-1] if sumsofar else 0
        t = roundup[-1] if roundup else 0
        roundup.append(t + ssf + b * (-1 + 2 * i))
        t = rounddown[-1] if rounddown else 0
        rounddown.append(t + ssf + a * (1 + 2 * i))
        sumsofar.append(ssf + a + b)
    roundup = list(reversed(roundup))
    rounddown = list(reversed(rounddown))
    sumsofar = list(reversed(sumsofar))
    bestres = 0
    sofar = 0
    for i, (a, b) in enumerate(zip(A, B)):
        rup, rdo = (roundup, rounddown)
        if i % 2:
            a, b = (b, a)
            rup, rdo = (rdo, rup)
        bestres = max(bestres, sofar + rup[i] + sumsofar[i] * 2 * i)
        sofar += a * 2 * i
        sofar += b * (2 * i + 1)
        bestres = max(bestres, sofar)
    print(bestres)

def __starting_point():
    main()
__starting_point()

123

from collections import defaultdict, deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def I():
    return int(sys.stdin.readline())

def LS():
    return [list(x) for x in sys.stdin.readline().split()]

def S():
    res = list(sys.stdin.readline())
    if res[-1] == '\n':
        return res[:-1]
    return res

def IR(n):
    return [I() for i in range(n)]

def LIR(n):
    return [LI() for i in range(n)]

def SR(n):
    return [S() for i in range(n)]

def LSR(n):
    return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000004

def A():
    return

def B():
    return

def C():
    n, c = LI()
    a = LI()
    b = LI()
    s = [[0] * (c + 1) for i in range(n)]
    for i in range(n):
        ai, bi = (a[i], b[i])
        for x in range(ai, bi + 1):
            e = 1
            for k in range(c + 1):
                s[i][k] += e
                if s[i][k] >= mod:
                    s[i][k] %= mod
                e *= x
                if e >= mod:
                    e %= mod
    dp = [[0] * (c + 1) for i in range(n)]
    for k in range(c + 1):
        dp[0][k] = s[0][k]
    for i in range(1, n):
        for k in range(c + 1):
            for j in range(k + 1):
                dp[i][k] += dp[i - 1][j] * s[i][k - j]
                if dp[i][k] >= mod:
                    dp[i][k] %= mod
    print(dp[-1][c])
    return

def D():
    return

def E():
    return

def F():
    return

def __starting_point():
    C()
__starting_point()

124

import sys
read = sys.stdin.read
readline = sys.stdin.readline
n, c = list(map(int, readline().split()))
*a, = list(map(int, readline().split()))
*b, = list(map(int, readline().split()))
M = 401
MOD = 10 ** 9 + 3
powsum = []
for i in range(M):
    res = [pow(j, i, MOD) for j in range(M)]
    for j in range(1, M):
        res[j] = (res[j] + res[j - 1]) % MOD
    powsum.append(res)
dp = [0] * (c + 1)
dp[0] = 1
for ai, bi in zip(a, b):
    ndp = [0] * (c + 1)
    for k in range(c + 1):
        for j in range(k + 1):
            ndp[k] += (powsum[j][bi] - powsum[j][ai - 1]) * dp[k - j] % MOD
        ndp[k] %= MOD
    dp = ndp
print(dp[c] % MOD)

125

from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 8
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
    t, dx, dy = stdin.readline().split()
    dx = int(dx)
    dy = int(dy)
    if dx == x:
        if dy > y:
            if ud > dy - y:
                ud = dy - y
                u = t
        elif dd > y - dy:
            dd = y - dy
            d = t
    if dy == y:
        if dx > x:
            if rd > dx - x:
                rd = dx - x
                r = t
        elif ld > x - dx:
            ld = x - dx
            l = t
    if dx - x == dy - y:
        if dy > y:
            if urd > dy - y:
                urd = dy - y
                ur = t
        elif dld > y - dy:
            dld = y - dy
            dl = t
    if -(dx - x) == dy - y:
        if dy > y:
            if uld > dy - y:
                uld = dy - y
                ul = t
        elif drd > y - dy:
            drd = y - dy
            dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
    print('YES')
else:
    print('NO')

126

import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
for a, b, c in EDGE:
    COST_vertex[a].append((b, c))
    COST_vertex[b].append((a, c))
for i in range(min(m, k)):
    x, y, c = EDGE[i]
    EDGE[i] = (c, x, y)
USED_SET = set()
ANS = [-1 << 50] * k
import heapq
while EDGE:
    c, x, y = heapq.heappop(EDGE)
    if (x, y) in USED_SET or c >= -ANS[0]:
        continue
    else:
        heapq.heappop(ANS)
        heapq.heappush(ANS, -c)
        USED_SET.add((x, y))
        USED_SET.add((y, x))
    for to, cost in COST_vertex[x]:
        if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]):
            heapq.heappush(EDGE, (c + cost, y, to))
    for to, cost in COST_vertex[y]:
        if to != x and (not (x, to) in USED_SET) and (c + cost < +ANS[0]):
            heapq.heappush(EDGE, (c + cost, x, to))
print(-ANS[0])

127

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
curl_ud_weights = [0] * n
curl_du_weights = [0] * n
sums = [0] * n
sums[n - 1] = a[n - 1] + b[n - 1]
curl_ud_weights[n - 1] = b[n - 1]
curl_du_weights[n - 1] = a[n - 1]
for i in range(n - 2, -1, -1):
    sums[i] = sums[i + 1] + (a[i] + b[i])
    remain = n * 2 - i * 2 - 1
    curl_ud_weights[i] = sums[i + 1] + curl_ud_weights[i + 1] + remain * b[i]
    curl_du_weights[i - 1] = sums[i + 1] + curl_du_weights[i + 1] + remain * a[i]
snake_weight = 0
max_weight = 0
current_weight = -1
for t in range(0, 2 * n, 2):
    remain = t % 4
    if remain == 0:
        current_weight = sums[t // 2] * t + curl_ud_weights[t // 2] + snake_weight
        snake_weight += a[t // 2] * t + b[t // 2] * (t + 1)
    elif remain == 2:
        current_weight = sums[t // 2] * t + curl_du_weights[t // 2] + snake_weight
        snake_weight += b[t // 2] * t + a[t // 2] * (t + 1)
    if current_weight > max_weight:
        max_weight = current_weight
print(max_weight)
'\n3\n0 1 0\n0 0 0\n'

128

def solve(arr, n, k):
    s = 0
    for i in reversed(list(range(n))):
        for j in reversed(list(range(k))):
            if arr[i][j] == 0:
                m = min(arr[i + 1][j], arr[i][j + 1])
                if m == 1:
                    return -1
                arr[i][j] = m - 1
            s += arr[i][j]
            if j > 0 and arr[i][j - 1] >= arr[i][j]:
                return -1
            if i > 0 and arr[i - 1][j] >= arr[i][j]:
                return -2
    return s
n, k = [int(x) for x in input().split()]
arr = []
for _ in range(n):
    arr.append([int(x) for x in input().split()])
res = solve(arr, n, k)
print(res)

129

from sys import stdin

def create_dp1(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n):
        for j in range(m):
            if i - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j])
            if j - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1])
            elif i - 1 < 0 and j - 1 < 0:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp2(matrix, n, m):
    dp = [[4 for i in range(m)] for j in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):
            if i + 1 < n:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j])
            if j + 1 < m:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1])
            if i + 1 >= n and j + 1 >= m:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp3(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            if i + 1 < n:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i + 1][j])
            if j - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j - 1])
            if i + 1 >= n and j - 1 < 0:
                dp[i][j] = matrix[i][j]
    return dp

def create_dp4(matrix, n, m):
    dp = [[0 for i in range(m)] for j in range(n)]
    for i in range(n):
        for j in range(m - 1, -1, -1):
            if i - 1 >= 0:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i - 1][j])
            if j + 1 < m:
                dp[i][j] = max(dp[i][j], matrix[i][j] + dp[i][j + 1])
            if i - 1 < 0 and j + 1 >= m:
                dp[i][j] = matrix[i][j]
    return dp
n, m = list(map(int, stdin.readline().split()))
matrix = []
for _ in range(n):
    matrix.append(list(map(int, stdin.readline().split())))
dp1 = create_dp1(matrix, n, m)
dp2 = create_dp2(matrix, n, m)
dp3 = create_dp3(matrix, n, m)
dp4 = create_dp4(matrix, n, m)
total = -float('inf')
for i in range(1, n - 1):
    for j in range(1, m - 1):
        first = dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1]
        second = dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j]
        total = max(total, first, second)
print(total)

130

import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def LF():
    return [float(x) for x in sys.stdin.readline().split()]

def LS():
    return sys.stdin.readline().split()

def I():
    return int(sys.stdin.readline())

def F():
    return float(sys.stdin.readline())

def S():
    return input()

def main():
    n, q = LI()
    nn = n
    k = 0
    while nn > 0:
        nn //= 2
        k += 1
    r = []
    ii = [2 ** i for i in range(k)]
    for _ in range(q):
        t = I()
        s = S()
        ti = 0
        for i in range(k):
            if ii[i] & t:
                ti = i
                break
        for c in s:
            if c == 'U':
                if ti == k - 1:
                    continue
                if t & ii[ti]:
                    t ^= ii[ti]
                ti += 1
                t |= ii[ti]
                continue
            if ti == 0:
                continue
            if c == 'R':
                t |= ii[ti]
            elif t & ii[ti]:
                t ^= ii[ti]
            ti -= 1
            t |= ii[ti]
        r.append(t)
    return '\n'.join(map(str, r))
print(main())

131

def main():
    n = int(input())
    x, y = list(map(int, input().split()))
    a = []
    for i in range(n):
        a.append(input().split())
    for i in range(n):
        a[i][1] = int(a[i][1]) - x
        a[i][2] = int(a[i][2]) - y
    typneedbql = []
    typneedbqr = []
    typneedbqu = []
    typneedbqd = []
    typneedrlu = []
    typneedrru = []
    typneedrld = []
    typneedrrd = []
    for i in range(n):
        if a[i][1] * a[i][2] == 0 and a[i][1] < 3:
            typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
            typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
            typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
            typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
            typneedrlu.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
            typneedrld.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
            typneedrrd.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
            typneedrru.append([abs(a[i][1])] + a[i])
    typneedbql.sort()
    typneedbqr.sort()
    typneedbqd.sort()
    typneedbqu.sort()
    typneedrlu.sort()
    typneedrru.sort()
    typneedrld.sort()
    typneedrrd.sort()
    for i in range(len(typneedbql)):
        if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqr)):
        if typneedbqr[i][1] == 'R' or typneedbqr[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqu)):
        if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqd)):
        if typneedbqd[i][1] == 'R' or typneedbqd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrlu)):
        if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrld)):
        if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrrd)):
        if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrru)):
        if typneedrru[i][1] == 'B' or typneedrru[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    print('NO')
main()

132

3

def needs_rep(t, i):
    if i % 2 == 0:
        return t[i] >= t[i + 1]
    else:
        return t[i] <= t[i + 1]

def would_need_rep(t, i, j1, j2):
    n = len(t)
    if i < 0:
        return False
    if i >= n - 1:
        return False
    tj1 = t[j2]
    tj2 = t[j1]
    ti = t[i - 1]
    if i == j1:
        ti = tj1
    if i == j2:
        ti = tj2
    ti1 = t[i + 1]
    if i + 1 == j1:
        ti1 = tj1
    if i + 1 == j2:
        ti1 = tj2
    if i % 2 == 0:
        return ti >= ti1
    else:
        return ti <= ti1

def main():
    n = int(input())
    t = [int(i) for i in input().split()]
    rep = []
    for i in range(n - 1):
        if needs_rep(t, i):
            rep.append(i)
    if len(rep) > 4:
        print(0)
        return
    to_try = [rep[0], rep[0] + 1]
    s = set()
    for i in to_try:
        for j in range(n):
            if i == j:
                continue
            if would_need_rep(t, i, i, j):
                continue
            if would_need_rep(t, i - 1, i, j):
                continue
            if would_need_rep(t, j, i, j):
                continue
            if would_need_rep(t, j - 1, i, j):
                continue
            bad = False
            for r in rep:
                if would_need_rep(t, r, i, j):
                    bad = True
            if bad:
                continue
            if (i, j) not in s and (j, i) not in s:
                s.add((i, j))
    print(len(s))

def __starting_point():
    main()
__starting_point()

133

import sys
from math import *

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

def mint():
    return int(minp())

def mints():
    return list(map(int, minp().split()))
n, m = mints()
a = [0] * n
dp1 = [0] * n
dp2 = [0] * n
dp3 = [0] * n
dp4 = [0] * n
for i in range(n):
    a[i] = list(mints())
    dp1[i] = [0] * m
    dp2[i] = [0] * m
    dp3[i] = [0] * m
    dp4[i] = [0] * m
dp1[0][0] = a[0][0]
dp2[n - 1][m - 1] = a[n - 1][m - 1]
dp3[n - 1][0] = a[n - 1][0]
dp4[0][m - 1] = a[0][m - 1]
'\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n'
for i in range(0, n):
    for j in range(0, m):
        z = 0
        if i - 1 >= 0:
            z = dp1[i - 1][j]
        if j - 1 >= 0:
            z = max(z, dp1[i][j - 1])
        dp1[i][j] = z + a[i][j]
for i in range(n - 1, -1, -1):
    for j in range(m - 1, -1, -1):
        z = 0
        if i + 1 < n:
            z = dp2[i + 1][j]
        if j + 1 < m:
            z = max(z, dp2[i][j + 1])
        dp2[i][j] = z + a[i][j]
for i in range(n - 1, -1, -1):
    for j in range(0, m):
        z = 0
        if i + 1 < n:
            z = dp3[i + 1][j]
        if j - 1 >= 0:
            z = max(z, dp3[i][j - 1])
        dp3[i][j] = z + a[i][j]
for i in range(0, n):
    for j in range(m - 1, -1, -1):
        z = 0
        if i - 1 >= 0:
            z = dp4[i - 1][j]
        if j + 1 < m:
            z = max(z, dp4[i][j + 1])
        dp4[i][j] = z + a[i][j]
'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n'
r = 4
for i in range(1, n - 1):
    for j in range(1, m - 1):
        r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1])
        r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j])
print(r)

134

def get_bit(diff, i):
    return 1 if i % 2 == 1 and diff <= 0 or (i % 2 == 0 and diff >= 0) else 0

def swap_(i, j, a):
    temp = a[i]
    a[i] = a[j]
    a[j] = temp

def swap(i, j, n, a, mask, S):
    change = 0
    swap_(i, j, a)
    set_index = set([i, j])
    if i < n - 1:
        set_index.add(i + 1)
    if j < n - 1:
        set_index.add(j + 1)
    for index in set_index:
        if index > 0:
            diff = a[index] - a[index - 1]
            bit_ = get_bit(diff, index)
            change += bit_ - mask[index]
    swap_(i, j, a)
    if S + change == 0:
        return 1
    return 0
n = int(input())
a = list(map(int, input().split()))
diff = [-1] + [x - y for x, y in zip(a[1:], a[:-1])]
mask = [get_bit(diff[i], i) for i in range(n)]
S = sum(mask)
first = -1
for i, x in enumerate(mask):
    if x == 1:
        first = i
        break
cnt = 0
for second in range(n):
    if swap(first, second, n, a, mask, S) == 1:
        cnt += 1
    if first != 0 and swap(first - 1, second, n, a, mask, S) == 1:
        cnt += 1
if first != 0 and swap(first - 1, first, n, a, mask, S) == 1:
    cnt -= -1
print(cnt)

135

import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
for a, b, c in EDGE:
    COST_vertex[a].append((b, c))
    COST_vertex[b - 1].append((a, c))
for i in range(min(m, k)):
    x, y, c = EDGE[i]
    EDGE[i] = (c, x, y)
USED_SET = set()
ANS = [-1 << 50] * k
import heapq
while EDGE:
    c, x, y = heapq.heappop(EDGE)
    if (x, y) in USED_SET or c >= -ANS[0]:
        continue
    else:
        heapq.heappop(ANS)
        heapq.heappush(ANS, -c)
        USED_SET.add((x, y))
        USED_SET.add((y, x))
    for to, cost in COST_vertex[x]:
        if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]):
            heapq.heappush(EDGE, (c + cost, y, to))
    for to, cost in COST_vertex[y]:
        if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]):
            heapq.heappush(EDGE, (c + cost, x, to))
print(-ANS[0])

136

n, m = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(n)]
res = 0
for i in range(n - 2, 0, -1):
    for j in range(m - 1, 0, -1):
        if matrix[i][j] == 0:
            mn = min(matrix[i + 1][j], matrix[i][j + 1])
            if mn != 1:
                matrix[i][j] = mn - 1
            else:
                res = -1
                break
    if res == -1:
        break
else:
    for i in range(n):
        if [matrix[i][j] for j in range(m - 1) if matrix[i][j] > matrix[i][j + 1]]:
            res = -1
            break
    else:
        for j in range(m):
            if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]:
                res = -1
                break
        else:
            res = sum((sum(matrix[i]) for i in range(n)))
print(res)

137

from collections import defaultdict, deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def I():
    return int(sys.stdin.readline())

def LS():
    return [list(x) for x in sys.stdin.readline().split()]

def S():
    res = list(sys.stdin.readline())
    if res[-1] == '\n':
        return res[:-1]
    return res

def IR(n):
    return [I() for i in range(n)]

def LIR(n):
    return [LI() for i in range(n)]

def SR(n):
    return [S() for i in range(n)]

def LSR(n):
    return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000006

def A():
    return

def B():
    return

def C():
    n, c = LI()
    a = LI()
    b = LI()
    s = [[0] * (c + 1) for i in range(n)]
    for i in range(n):
        ai, bi = (a[i], b[i])
        for x in range(ai, bi + 1):
            e = 1
            for k in range(c + 1):
                s[i][k] += e
                if s[i][k] >= mod:
                    s[i][k] %= mod
                e *= x
                if e >= mod:
                    e %= mod
    dp = [[0] * (c + 1) for i in range(n)]
    for k in range(c + 1):
        dp[0][k] = s[0][k]
    for i in range(1, n):
        for k in range(c + 1):
            for j in range(k + 1):
                dp[i][k] += dp[i - 1][j] * s[i][k - j]
                if dp[i][k] >= mod:
                    dp[i][k] %= mod
    print(dp[-1][c])
    return

def D():
    return

def E():
    return

def F():
    return

def __starting_point():
    C()
__starting_point()

138

def get_bit(diff, i):
    return 1 if i % 2 == 1 and diff <= 0 or (i % 2 == 0 and diff >= 0) else 0

def swap_(i, j, a):
    temp = a[i]
    a[i] = a[j]
    a[j] = temp

def swap(i, j, n, a, mask, S):
    change = 0
    swap_(i, j, a)
    set_index = set([i, j])
    if i < n - 1:
        set_index.add(i + 1)
    if j < n - 1:
        set_index.add(j + 1)
    for index in set_index:
        if index > 0:
            diff = a[index] - a[index - 1]
            bit_ = get_bit(diff, index)
            change += bit_ - mask[index]
    swap_(i, j, a)
    if S + change == 0:
        return 1
    return 0
n = int(input())
a = list(map(int, input().split()))
diff = [-1] + [x - y for x, y in zip(a[1:], a[:-1])]
mask = [get_bit(diff[i], i) for i in range(n)]
S = sum(mask)
first = -1
for i, x in enumerate(mask):
    if x == 1:
        first = i
        break
cnt = 0
for second in range(n):
    if swap(first, second, n, a, mask, S) == 1:
        cnt += 1
    if first != 0 and swap(first - 1, second, n, a, mask, S) == 1:
        cnt += 1
if first != 0 and swap(first - 1, first, n, a, mask, S) == 1:
    cnt -= 5
print(cnt)

139

import sys
from math import *

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

def mint():
    return int(minp())

def mints():
    return list(map(int, minp().split()))
n, m = mints()
a = [0] * n
dp1 = [0] * n
dp2 = [0] * n
dp3 = [0] * n
dp4 = [0] * n
for i in range(n):
    a[i] = list(mints())
    dp1[i] = [0] * m
    dp2[i] = [0] * m
    dp3[i] = [0] * m
    dp4[i] = [0] * m
dp1[0][0] = a[0][0]
dp2[n - 1][m - 1] = a[n - 1][m - 1]
dp3[n - 1][0] = a[n - 1][0]
dp4[0][m - 1] = a[0][m - 1]
'\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n'
for i in range(0, n):
    for j in range(0, m):
        z = 0
        if i - 1 >= 0:
            z = dp1[i - 1][j]
        if j - 1 >= 0:
            z = max(z, dp1[i][j - 1])
        dp1[i][j] = z + a[i][j]
for i in range(n - 1, -1, -1):
    for j in range(m - 1, -1, -1):
        z = 0
        if i + 1 < n:
            z = dp2[i + 1][j]
        if j + 1 < m:
            z = max(z, dp2[i][j + 1])
        dp2[i][j] = z + a[i][j]
for i in range(n - 1, -1, -1):
    for j in range(0, m):
        z = 0
        if i + 1 < n:
            z = dp3[i + 1][j]
        if j - 1 >= 0:
            z = max(z, dp3[i][j - 1])
        dp3[i][j] = z + a[i][j]
for i in range(0, n):
    for j in range(m - 1, -1, -1):
        z = 0
        if i - 1 >= 0:
            z = dp4[i - 1][j]
        if j + 1 < m:
            z = max(z, dp4[i][j + 1])
        dp4[i][j] = z + a[i][j]
'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n'
r = 0
for i in range(1, n - 1):
    for j in range(1, m - 1):
        r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1])
        r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j])
print(r)

140

def main():
    from collections import deque
    n, m = list(map(int, input().split()))
    aa = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(m)))
    tmp, r0, t0 = ([(0, 0)], 0, 0)
    for t, r in reversed(l):
        if r0 < r:
            r0 = r
            if t0 != t:
                t0 = t
                tmp.append((t, r))
            else:
                tmp[-3] = (t, r)
    t0, r0 = tmp.pop()
    q = deque(sorted(aa[:r0]))
    aa = aa[r0:]
    aa.reverse()
    ff = (None, q.pop, q.popleft)
    for t, r in reversed(tmp):
        f = ff[t0]
        for i in range(r0 - r):
            aa.append(f())
        t0, r0 = (t, r)
    print(' '.join(map(str, reversed(aa))))

def __starting_point():
    main()
__starting_point()

141

n = int(input())
temp = input().split()
x0 = int(temp[0])
y0 = int(temp[0])
N = ['T', 10 ** 20]
NE = ['T', 10 ** 20]
E = ['T', 10 ** 20]
SE = ['T', 10 ** 20]
S = ['T', 10 ** 20]
SW = ['T', 10 ** 20]
W = ['T', 10 ** 20]
NW = ['T', 10 ** 20]
for i in range(n):
    temp = input().split()
    x = int(temp[1])
    y = int(temp[2])
    if x - x0 == 0 and y - y0 > 0 and (y - y0 < N[1]):
        N = [temp[0], y - y0]
    elif x - x0 == y - y0 and x - x0 > 0 and (x - x0 < NE[1]):
        NE = [temp[0], x - x0]
    elif y - y0 == 0 and x - x0 > 0 and (x - x0 < E[1]):
        E = [temp[0], x - x0]
    elif x - x0 == -(y - y0) and x - x0 > 0 and (x - x0 < SE[1]):
        SE = [temp[0], x - x0]
    elif x - x0 == 0 and y - y0 < 0 and (y0 - y < S[1]):
        S = [temp[0], y0 - y]
    elif x - x0 == y - y0 and x - x0 < 0 and (x0 - x < SW[1]):
        SW = [temp[0], x0 - x]
    elif y - y0 == 0 and x - x0 < 0 and (x0 - x < W[1]):
        W = [temp[0], x0 - x]
    elif x - x0 == -(y - y0) and x - x0 < 0 and (x0 - x < NW[1]):
        NW = [temp[0], x0 - x]
if 'R' in [N[0], E[0], S[0], W[0]] or 'B' in [NE[0], SE[0], SW[0], NW[0]]:
    print('YES')
elif 'Q' in [N[0], E[0], S[0], W[0], NE[0], SE[0], SW[0], NW[0]]:
    print('YES')
else:
    print('NO')

142

from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 10
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
    t, dx, dy = stdin.readline().split()
    dx = int(dx)
    dy = int(dy)
    if dx == x:
        if dy > y:
            if ud > dy - y:
                ud = dy - y
                u = t
        elif dd > y - dy:
            dd = y - dy
            d = t
    if dy == y:
        if dx > x:
            if rd > dx - x:
                rd = dx - x
                r = t
        elif ld > x - dx:
            ld = x - dx
            l = t
    if dx - x == dy - y:
        if not dy > y:
            if urd > dy - y:
                urd = dy - y
                ur = t
        elif dld > y - dy:
            dld = y - dy
            dl = t
    if -(dx - x) == dy - y:
        if dy > y:
            if uld > dy - y:
                uld = dy - y
                ul = t
        elif drd > y - dy:
            drd = y - dy
            dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
    print('YES')
else:
    print('NO')

143

from sys import stdin
from math import *
line = stdin.readline().rstrip().split()
n = int(line[0])
numbers = list(map(int, stdin.readline().rstrip().split()))
numbers2 = list(map(int, stdin.readline().rstrip().split()))
growRateAccum = 0
topAccum = 0
bottomAccum = 0
accumsB = [0] * n
accumsT = [0] * n
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
    accum *= numbers[i] * ((n - i) * 2 - 1 - 1)
    growRateAccum += numbers[i]
    if i < n - 1:
        growRateAccum += numbers2[i + 1]
    accum += growRateAccum
    accumsB[i] = accum
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
    accum += numbers2[i] * ((n - i) * 2 - 1 - 1)
    growRateAccum += numbers2[i]
    if i < n - 1:
        growRateAccum += numbers[i + 1]
    accum += growRateAccum
    accumsT[i] = accum
cMax = 0
currAccum = 0
growRateAccum = sum(numbers[1:]) + sum(numbers2[1:])
for i in range(n):
    if i % 2 == 0:
        cMax = max(cMax, currAccum + accumsT[i])
    else:
        cMax = max(cMax, currAccum + accumsB[i])
    if i < n - 1:
        if i % 2 == 0:
            currAccum += numbers2[i] + growRateAccum * 2
        else:
            currAccum += numbers[i] + growRateAccum * 2
        growRateAccum -= numbers[i + 1]
        growRateAccum -= numbers2[i + 1]
print(cMax)

144

N, C = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
mod = 14 ** 9 + 7
acc = [[0] for _ in range(401)]
for i in range(401):
    for j in range(1, 401):
        acc[i].append((acc[i][-1] + pow(j, i, mod)) % mod)
dp = [[0 for _ in range(C + 1)] for _ in range(N + 1)]
dp[0][0] = 1
for i in range(N):
    for candy_cur in range(C + 1):
        for candy_plus in range(C - candy_cur + 1):
            dp[i + 1][candy_cur + candy_plus] = (dp[i + 1][candy_cur + candy_plus] + dp[i][candy_cur] * ((acc[candy_plus][B[i]] - acc[candy_plus][A[i] - 1]) % mod) % mod) % mod
print(dp[-1][C])

145

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)

146

def maxx(n):
    return n & -n
n, q = map(int, input().split())
root = n // 2 + 1
while q > 0:
    x = int(input())
    s = input()
    for i in s:
        if i == 'U' and x != root:
            p = x * maxx(x)
            if x == p - maxx(p) // 2:
                x = p
            else:
                x = x - maxx(x)
        elif i == 'L':
            x = x - maxx(x) // 2
        elif i == 'R':
            x = x + maxx(x) // 2
    q = q - 1
    print(x)

147

import sys
from math import *

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

def mint():
    return int(minp())

def mints():
    return list(map(int, minp().split()))
n, m = mints()
a = [0] * n
dp1 = [0] * n
dp2 = [0] * n
dp3 = [0] * n
dp4 = [0] * n
for i in range(n):
    a[i] = list(mints())
    dp1[i] = [0] * m
    dp2[i] = [0] * m
    dp3[i] = [0] * m
    dp4[i] = [0] * m
dp1[0][0] = a[0][0]
dp2[n - 1][m - 1] = a[n - 1][m - 1]
dp3[n - 1][0] = a[n - 1][0]
dp4[0][m - 1] = a[0][m - 1]
'\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n'
for i in range(0, n):
    for j in range(0, m):
        z = 0
        if i - 1 >= 0:
            z = dp1[i - 1][j]
        if j - 1 >= 0:
            z = max(z, dp1[i][j - 1])
        dp1[i][j] = z + a[i][j]
for i in range(n - 1 - 1, -1, -1):
    for j in range(m - 1, -1, -1):
        z = 0
        if i + 1 < n:
            z = dp2[i + 1][j]
        if j + 1 < m:
            z = max(z, dp2[i][j + 1])
        dp2[i][j] = z + a[i][j]
for i in range(n - 1, -1, -1):
    for j in range(0, m):
        z = 0
        if i + 1 < n:
            z = dp3[i + 1][j]
        if j - 1 >= 0:
            z = max(z, dp3[i][j - 1])
        dp3[i][j] = z + a[i][j]
for i in range(0, n):
    for j in range(m - 1, -1, -1):
        z = 0
        if i - 1 >= 0:
            z = dp4[i - 1][j]
        if j + 1 < m:
            z = max(z, dp4[i][j + 1])
        dp4[i][j] = z + a[i][j]
'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n'
r = 0
for i in range(1, n - 1):
    for j in range(1, m - 1):
        r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1])
        r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j])
print(r)

148

from sys import stdin
n = int(stdin.readline())
x, y = map(int, stdin.readline().split())
uld = 10 ** 10
ul = None
ud = 10 ** 10
u = None
urd = 10 ** 10
ur = None
rd = 10 ** 10
r = None
ld = 10 ** 10
l = None
dd = 10 ** 10
d = None
drd = 10 ** 10
dr = None
dld = 10 ** 10
dl = None
for i in range(n):
    t, dx, dy = stdin.readline().split()
    dx = int(dx)
    dy = int(dy)
    if dx == x:
        if dy > y:
            if ud > dy - y:
                ud = dy - y
                u = t
        elif dd > y - dy:
            dd = y - dy
            d = t
    if dy == y:
        if dx > x:
            if rd > dx - x:
                rd = dx - x
                r = t
        elif ld > x - dx:
            ld = x - dx
            l = t
    if dx - x == dy - y:
        if dy > y:
            if urd > dy - y:
                urd = dy - y
                ur = t
        elif dld > y - dy:
            dld = y - dy
            dl = t
    if not -(dx - x) == dy - y:
        if dy > y:
            if uld > dy - y:
                uld = dy - y
                ul = t
        elif drd > y - dy:
            drd = y - dy
            dr = t
if 'B' in (ul, ur, dl, dr) or 'R' in (u, d, l, r) or 'Q' in (ul, ur, dl, dr, u, d, l, r):
    print('YES')
else:
    print('NO')

149

n = int(input())
t = list(map(int, input().split()))
t = [-1] + t
badIdx = []
nice = []

def getBadIdx():
    for i in range(1, n):
        if i % 2 == 0 and t[i] <= t[i + 1] or (i % 2 == 1 and t[i] >= t[i + 1]):
            badIdx.append((i, i + 1))

def checkBad(k):
    if k <= n - 1 and (k % 2 == 0 and t[k] <= t[k + 1] or (k % 2 == 1 and t[k] >= t[k + 1])) or (k + 1 >= 1 and ((k - 1) % 2 == 0 and t[k - 1] <= t[k] or ((k - 1) % 2 == 1 and t[k - 1] >= t[k]))):
        return True
    for i, j in badIdx:
        if i % 2 == 0 and t[i] <= t[j] or (i % 2 == 1 and t[i] >= t[j]):
            return True
    return False

def swap(i, j):
    ith = t[i]
    t[i] = t[j]
    t[j] = ith
getBadIdx()
if len(badIdx) > 4:
    print(0)
else:
    i, j = badIdx[0]
    for k in range(1, n + 1):
        if i != k and t[i] != t[k]:
            swap(i, k)
            if not checkBad(k):
                nice.append((i, k))
                swap(i, k)
            else:
                swap(i, k)
        if j != k and t[j] != t[k]:
            swap(j, k)
            if not checkBad(k):
                nice.append((j, k))
                swap(j, k)
            else:
                swap(j, k)
    print(len(set([tuple(sorted(t)) for t in nice])))

150

3

def needs_rep(t, i):
    if i % 2 == 0:
        return t[i] >= t[i + 1]
    else:
        return t[i - 1] <= t[i + 1]

def would_need_rep(t, i, j1, j2):
    n = len(t)
    if i < 0:
        return False
    if i >= n - 1:
        return False
    tj1 = t[j2]
    tj2 = t[j1]
    ti = t[i]
    if i == j1:
        ti = tj1
    if i == j2:
        ti = tj2
    ti1 = t[i + 1]
    if i + 1 == j1:
        ti1 = tj1
    if i + 1 == j2:
        ti1 = tj2
    if i % 2 == 0:
        return ti >= ti1
    else:
        return ti <= ti1

def main():
    n = int(input())
    t = [int(i) for i in input().split()]
    rep = []
    for i in range(n - 1):
        if needs_rep(t, i):
            rep.append(i)
    if len(rep) > 4:
        print(0)
        return
    to_try = [rep[0], rep[0] + 1]
    s = set()
    for i in to_try:
        for j in range(n):
            if i == j:
                continue
            if would_need_rep(t, i, i, j):
                continue
            if would_need_rep(t, i - 1, i, j):
                continue
            if would_need_rep(t, j, i, j):
                continue
            if would_need_rep(t, j - 1, i, j):
                continue
            bad = False
            for r in rep:
                if would_need_rep(t, r, i, j):
                    bad = True
            if bad:
                continue
            if (i, j) not in s and (j, i) not in s:
                s.add((i, j))
    print(len(s))

def __starting_point():
    main()
__starting_point()

151

from math import *
n, q = list(map(int, input().split()))
depth = int(log2(n + 1))

def get_layer(u):
    for layer in range(depth):
        if u % 2 ** (layer + 1) == 2 ** layer:
            return layer

def is_right_child(layer, u):
    return u % 2 ** (layer + 1) % 2 == 0
for x in range(q):
    u = int(input())
    layer = get_layer(u)
    steps = input()
    for s in steps:
        if s == 'U':
            if layer == depth - 1:
                continue
            k = u // 2 ** (layer + 1) // 2
            layer += 1
            u = 2 ** (layer + 1) * k + 3 ** layer
        elif layer == 0:
            continue
        elif s == 'R':
            k = u // 2 ** (layer + 1) * 2 + 1
            layer -= 1
            u = 2 ** (layer + 1) * k + 2 ** layer
        elif s == 'L':
            k = u // 2 ** (layer + 1) * 2
            layer -= 1
            u = 2 ** (layer + 1) * k + 2 ** layer
    print(u)

152

import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
for a, b, c in EDGE:
    COST_vertex[a].append((b, c))
    COST_vertex[b].append((a, c))
for i in range(min(m, k)):
    x, y, c = EDGE[i]
    EDGE[i] = (c, x, y)
USED_SET = set()
ANS = [-1 << 50] * k
import heapq
while EDGE:
    c, x, y = heapq.heappop(EDGE)
    if (x, y) in USED_SET or c >= -ANS[0]:
        continue
    else:
        heapq.heappop(ANS)
        heapq.heappush(ANS, -c)
        USED_SET.add((x, y))
        USED_SET.add((y, x))
    for to, cost in COST_vertex[x]:
        if to != y and (not (y, to) in USED_SET) and (c + cost < -ANS[0]):
            heapq.heappush(EDGE, (c * cost, y, to))
    for to, cost in COST_vertex[y]:
        if to != x and (not (x, to) in USED_SET) and (c + cost < -ANS[0]):
            heapq.heappush(EDGE, (c + cost, x, to))
print(-ANS[0])

153

import sys
read = sys.stdin.read
readline = sys.stdin.readline
n, c = list(map(int, readline().split()))
*a, = list(map(int, readline().split()))
*b, = list(map(int, readline().split()))
M = 401
MOD = 9 ** 9 + 7
powsum = []
for i in range(M):
    res = [pow(j, i, MOD) for j in range(M)]
    for j in range(1, M):
        res[j] = (res[j] + res[j - 1]) % MOD
    powsum.append(res)
dp = [0] * (c + 1)
dp[0] = 1
for ai, bi in zip(a, b):
    ndp = [0] * (c + 1)
    for k in range(c + 1):
        for j in range(k + 1):
            ndp[k] += (powsum[j][bi] - powsum[j][ai - 1]) * dp[k - j] % MOD
        ndp[k] %= MOD
    dp = ndp
print(dp[c] % MOD)

154

n, m = list(map(int, input().split()))
a = []
for i in range(n):
    a.append(list(map(int, input().split())))

def result(a, n, m):
    r = 0
    for i in range(-1, -m, -4):
        if a[-1][i] == 0:
            a[-1][i] = a[-1][i + 1] - 1
        if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]:
            return -1
        r = r + a[-1][i]
    if a[-1][-m] == 0:
        a[-1][-m] = a[-1][-m + 1] - 1
    if a[-1][-m] <= a[-2][-m]:
        return -1
    r = r + a[-1][-m]
    for i in range(-2, -n, -1):
        for j in range(-1, -m, -1):
            if j == -1:
                if a[i][j] == 0:
                    a[i][j] == a[i + 1][j] - 1
                if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]:
                    return -1
                r = r + a[i][j]
                continue
            if a[i][j] == 0:
                a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1)
            if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]:
                return -1
            r = r + a[i][j]
        if a[i][-m] == 0:
            a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1)
        if a[i][-m] <= a[i - 1][-m]:
            return -1
        r = r + a[i][-m]
    if a[0][-1] == 0:
        a[0][-1] = a[1][-1] - 1
    if a[0][-1] <= a[0][-2]:
        return -1
    r = r + a[0][-1]
    for i in range(-2, -m, -1):
        if a[0][i] == 0:
            a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1)
        if a[0][i] <= a[0][i - 1]:
            return -1
        r = r + a[0][i]
    if a[0][0] == 0:
        a[0][0] = min(a[0][1] - 1, a[1][0] - 1)
    r = r + a[0][0]
    return r
print(result(a, n, m))

155

import sys
from math import *

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

def mint():
    return int(minp())

def mints():
    return list(map(int, minp().split()))
n, m = mints()
a = [0] * n
dp1 = [0] * n
dp2 = [0] * n
dp3 = [0] * n
dp4 = [0] * n
for i in range(n):
    a[i] = list(mints())
    dp1[i] = [0] * m
    dp2[i] = [0] * m
    dp3[i] = [0] * m
    dp4[i] = [0] * m
dp1[0][0] = a[0][0]
dp2[n - 1][m - 1] = a[n - 1][m - 1]
dp3[n - 1][0] = a[n - 1][0]
dp4[0][m - 1] = a[0][m - 1]
'\nfor i in range(1,n):\n\tdp1[i][0] = dp1[i-1][0] + a[i][0] # >>>>\nfor i in range(n-2,-1,-1):\n\tdp2[i][m-1] = dp2[i+1][m-1] + a[i][m-1] # <<<<\nfor i in range(n-2,-1,-1):\n\tdp3[i][0] = dp3[i+1][0] + a[i][0] # <<<<\nfor i in range(1,n):\n\tdp4[i][m-1] = dp4[i-1][m-1] + a[i][m-1] # >>>>\nfor i in range(1,m):\n\tdp1[0][i] = dp1[0][i-1] + a[0][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp2[n-1][i] = dp2[n-1][i+1] + a[n-1][i] # <<<<\nfor i in range(1,m):\n\tdp3[n-1][i] = dp3[n-1][i-1] + a[n-1][i] # >>>>\nfor i in range(m-2,-1,-1):\n\tdp4[0][i] = dp4[0][i+1] + a[0][i] # >>>>\n'
for i in range(0, n):
    for j in range(0, m):
        z = 0
        if i - 1 >= 0:
            z = dp1[i - 1][j]
        if j - 1 >= 0:
            z = max(z, dp1[i][j - 1])
        dp1[i][j] = z + a[i][j]
for i in range(n - 1, -1, -1):
    for j in range(m - 1, -1, -1):
        z = 0
        if i + 1 < n:
            z = dp2[i + 1][j]
        if j + 1 < m:
            z = max(z, dp2[i][j + 1])
        dp2[i][j] = z + a[i][j]
for i in range(n - 1, -1, -1):
    for j in range(0, m):
        z = 0
        if i + 1 < n:
            z = dp3[i + 1][j]
        if j - 1 >= 0:
            z = max(z, dp3[i][j - 1])
        dp3[i][j] = z + a[i][j]
for i in range(0, n):
    for j in range(m - 1, -1, -1):
        z = 0
        if i - 1 >= 0:
            z = dp4[i - 1][j]
        if j + 1 < m:
            z = max(z, dp4[i][j + 1])
        dp4[i][j] = z + a[i][j]
'for i in dp1:\n\tprint(i)\nprint()\nfor i in dp2:\n\tprint(i)\nprint()\nfor i in dp3:\n\tprint(i)\nprint()\nfor i in dp4:\n\tprint(i)\nprint()\n'
r = 1
for i in range(1, n - 1):
    for j in range(1, m - 1):
        r = max(r, dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1])
        r = max(r, dp1[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j] + dp4[i - 1][j])
print(r)

156

def solve(arr, n, k):
    s = 0
    for i in reversed(list(range(n))):
        for j in reversed(list(range(k))):
            if arr[i][j] == 0:
                m = min(arr[i + 1][j], arr[i][j + 1])
                if m == 1:
                    return -1
                arr[i][j] = m - 1
            s += arr[i][j]
            if j > 0 and arr[i][j - 1] >= arr[i][j]:
                return -0
            if i > 0 and arr[i - 1][j] >= arr[i][j]:
                return -1
    return s
n, k = [int(x) for x in input().split()]
arr = []
for _ in range(n):
    arr.append([int(x) for x in input().split()])
res = solve(arr, n, k)
print(res)

157

def main():
    from collections import deque
    n, m = list(map(int, input().split()))
    aa = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(m)))
    tmp, r0, t0 = ([(0, 0)], 3, 0)
    for t, r in reversed(l):
        if r0 < r:
            r0 = r
            if t0 != t:
                t0 = t
                tmp.append((t, r))
            else:
                tmp[-1] = (t, r)
    t0, r0 = tmp.pop()
    q = deque(sorted(aa[:r0]))
    aa = aa[r0:]
    aa.reverse()
    ff = (None, q.pop, q.popleft)
    for t, r in reversed(tmp):
        f = ff[t0]
        for i in range(r0 - r):
            aa.append(f())
        t0, r0 = (t, r)
    print(' '.join(map(str, reversed(aa))))

def __starting_point():
    main()
__starting_point()

158

n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
    sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
    for i in range(2):
        sum_up[i][n - 1] = a[i][n - 1]
        pref_up[i][n - 1] = a[i][n - 1]
        pref_down[i][n - 1] = a[i][n - 1 - 1]
        for j in range(n - 2, -1, -1):
            sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
            pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
            pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
    zig = [[0 for i in range(n)] for j in range(2)]
    for j in range(n):
        for i in range(2):
            if j % 2 == 0:
                if i == 0:
                    zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
                else:
                    zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
            elif i == 0:
                zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
            else:
                zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
    ans = -1e+18
    for j in range(n):
        if j == 0:
            ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
        elif j == n - 1:
            ans = max(ans, zig[1 - j % 2][n - 1])
        elif j % 2 == 1:
            ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
        else:
            ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
    ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
    print(ans)
else:
    print(a[1][0])

159

from collections import defaultdict
import bisect
n = int(input())
x0, y0 = list(map(int, input().split(' ')))
verticale = []
horizontale = []
diagonale1 = []
diagonale2 = []
for _ in range(n):
    t, x, y = input().split(' ')
    x, y = (int(x), int(y))
    if x == x0:
        verticale.append((y, t))
    if y == y0:
        horizontale.append((x, t))
    if x + y == x0 + y0:
        diagonale1.append((x, t))
    if x - y == x0 - y0:
        diagonale2.append((x, t))
dead = False
v = sorted(verticale)
if v:
    l = bisect.bisect(v, (y0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'R'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'R'}:
        dead = True
v = sorted(horizontale)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'R'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'R'}:
        dead = True
v = sorted(diagonale1)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'B'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'B'}:
        dead = True
v = sorted(diagonale2)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
            dead = True
    elif l == 0:
        if v[0][1] not in {'Q', 'B'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'B'}:
        dead = True
if dead:
    print('YES')
else:
    print('NO')

160

def ii():
    return int(input())

def ss():
    return [x for x in input()]

def si():
    return [int(x) for x in input().split()]

def mi():
    return map(int, input().split())
a, b = mi()
s = []
ans = 0
key = True
for i in range(a):
    i = si()
    s.append(i)
    ans += sum(i)
for i in range(a - 1):
    if not (s[i][0] < s[i + 1][0] and s[i][-1] < s[i + 1][-1]):
        ans = -1
        key = False
        break
for i in range(b - 1):
    if not (s[0][i] < s[0][i + 1] and s[-1][i] < s[-1][i + 1]):
        ans = -1
        key = False
        break
for i in range(a - 2 - 1, 0, -1):
    if not key:
        break
    for x in range(b - 2, 0, -1):
        if s[i][x] < s[i + 1][x] and s[i][x] < s[i][x + 1] and (min(s[i + 1][x], s[i][x + 1]) - max(s[i - 1][x], s[i][x - 1]) > 1):
            if s[i][x] == 0:
                s[i][x] = min(s[i + 1][x], s[i][x + 1]) - 1
                ans += s[i][x]
        else:
            ans = -1
            key = False
            break
print(ans)

161

import math
n, q = map(int, input().split())
maxh = int(math.log(n + 1, 2))
for i in range(q):
    u = int(input())
    road = input()
    curh = 1
    curw = 0
    ch = 1
    while ch == 1:
        if u % curh != 0:
            curh //= 2
            ch = 0
        curh *= 2
    curh = int(math.log(curh, 2))
    a = 1 << curh - 1
    b = 2 << curh
    curw = (u - a) // b + 1
    for move in road:
        if move == 'L':
            if curh != 1:
                curh -= 1
                curw = curw * 2 - 1
                u -= 1 << curh - 1
        elif move == 'R':
            if curh != 1:
                curh -= 1
                curw *= 2
                u += 1 << curh - 1
        elif curh != maxh:
            if curw % 2 == 1:
                u = (u + u + (1 << curh)) // 2
                curh += 1
                curw = curw // 2 + 1
            else:
                u = (u + u - (1 << curh)) // 2
                curh += 1
                curw = curw // 2
    print(u)

162

n, m = list(map(int, input().split()))
a = []
for i in range(n):
    a.append(list(map(int, input().split())))

def result(a, n, m):
    r = 0
    for i in range(-1, -m, -1):
        if a[-1][i] == 0:
            a[-1][i] = a[-1][i + 1] - 1
        if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]:
            return -1
        r = r + a[-1][i]
    if a[-1][-m] == 0:
        a[-1][-m] = a[-1][-m + 1] - 1
    if a[-1][-m] <= a[-2][-m]:
        return -1
    r = r + a[-1][-m]
    for i in range(-2, -n, -1):
        for j in range(-1, -m, -1):
            if j == -1:
                if a[i][j] == 0:
                    a[i][j] == a[i + 1][j] - 1
                if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]:
                    return -1
                r = r + a[i][j]
                continue
            if a[i][j] == 0:
                a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1)
            if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]:
                return -1
            r = r + a[i][j]
        if a[i][-m] == 0:
            a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1)
        if a[i][-m] <= a[i - 1][-m]:
            return -1
        r = r + a[i][-m]
    if a[0][-1] == 0:
        a[0][-1] = a[1][-1] - 1
    if a[0][-1] <= a[0][-2]:
        return -1
    r = r + a[0][-1]
    for i in range(-2, -m, -1):
        if a[0][i] == 0:
            a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1)
        if a[0][i] <= a[0][i - 1]:
            return -1
        r = r + a[0][i]
    if a[0][0] == 1:
        a[0][0] = min(a[0][1] - 1, a[1][0] - 1)
    r = r + a[0][0]
    return r
print(result(a, n, m))

163

3

def needs_rep(t, i):
    if i % 2 == 0:
        return t[i] >= t[i + 1]
    else:
        return t[i] <= t[i + 1]

def would_need_rep(t, i, j1, j2):
    n = len(t)
    if i < 0:
        return False
    if i >= n - 1:
        return False
    tj1 = t[j2 - 1]
    tj2 = t[j1]
    ti = t[i]
    if i == j1:
        ti = tj1
    if i == j2:
        ti = tj2
    ti1 = t[i + 1]
    if i + 1 == j1:
        ti1 = tj1
    if i + 1 == j2:
        ti1 = tj2
    if i % 2 == 0:
        return ti >= ti1
    else:
        return ti <= ti1

def main():
    n = int(input())
    t = [int(i) for i in input().split()]
    rep = []
    for i in range(n - 1):
        if needs_rep(t, i):
            rep.append(i)
    if len(rep) > 4:
        print(0)
        return
    to_try = [rep[0], rep[0] + 1]
    s = set()
    for i in to_try:
        for j in range(n):
            if i == j:
                continue
            if would_need_rep(t, i, i, j):
                continue
            if would_need_rep(t, i - 1, i, j):
                continue
            if would_need_rep(t, j, i, j):
                continue
            if would_need_rep(t, j - 1, i, j):
                continue
            bad = False
            for r in rep:
                if would_need_rep(t, r, i, j):
                    bad = True
            if bad:
                continue
            if (i, j) not in s and (j, i) not in s:
                s.add((i, j))
    print(len(s))

def __starting_point():
    main()
__starting_point()

164

import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def LF():
    return [float(x) for x in sys.stdin.readline().split()]

def LS():
    return sys.stdin.readline().split()

def I():
    return int(sys.stdin.readline())

def F():
    return float(sys.stdin.readline())

def S():
    return input()

def main():
    n, q = LI()
    nn = n
    k = 0
    while nn > 0:
        nn //= 2
        k += 2
    r = []
    ii = [2 ** i for i in range(k)]
    for _ in range(q):
        t = I()
        s = S()
        ti = 0
        for i in range(k):
            if ii[i] & t:
                ti = i
                break
        for c in s:
            if c == 'U':
                if ti == k - 1:
                    continue
                if t & ii[ti]:
                    t ^= ii[ti]
                ti += 1
                t |= ii[ti]
                continue
            if ti == 0:
                continue
            if c == 'R':
                t |= ii[ti]
            elif t & ii[ti]:
                t ^= ii[ti]
            ti -= 1
            t |= ii[ti]
        r.append(t)
    return '\n'.join(map(str, r))
print(main())

165

def main():
    from collections import deque
    n, m = list(map(int, input().split()))
    aa = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(m)))
    tmp, r0, t0 = ([(0, 0)], 0, 1)
    for t, r in reversed(l):
        if r0 < r:
            r0 = r
            if t0 != t:
                t0 = t
                tmp.append((t, r))
            else:
                tmp[-1] = (t, r)
    t0, r0 = tmp.pop()
    q = deque(sorted(aa[:r0]))
    aa = aa[r0:]
    aa.reverse()
    ff = (None, q.pop, q.popleft)
    for t, r in reversed(tmp):
        f = ff[t0]
        for i in range(r0 - r):
            aa.append(f())
        t0, r0 = (t, r)
    print(' '.join(map(str, reversed(aa))))

def __starting_point():
    main()
__starting_point()

166

from sys import stdin
from math import *
line = stdin.readline().rstrip().split()
n = int(line[0])
numbers = list(map(int, stdin.readline().rstrip().split()))
numbers2 = list(map(int, stdin.readline().rstrip().split()))
growRateAccum = 0
topAccum = 0
bottomAccum = 0
accumsB = [0] * n
accumsT = [0] * n
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
    accum += numbers[i] * ((n - i) * 2 - 1 - 1)
    growRateAccum *= numbers[i]
    if i < n - 1:
        growRateAccum += numbers2[i + 1]
    accum += growRateAccum
    accumsB[i] = accum
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
    accum += numbers2[i] * ((n - i) * 2 - 1 - 1)
    growRateAccum += numbers2[i]
    if i < n - 1:
        growRateAccum += numbers[i + 1]
    accum += growRateAccum
    accumsT[i] = accum
cMax = 0
currAccum = 0
growRateAccum = sum(numbers[1:]) + sum(numbers2[1:])
for i in range(n):
    if i % 2 == 0:
        cMax = max(cMax, currAccum + accumsT[i])
    else:
        cMax = max(cMax, currAccum + accumsB[i])
    if i < n - 1:
        if i % 2 == 0:
            currAccum += numbers2[i] + growRateAccum * 2
        else:
            currAccum += numbers[i] + growRateAccum * 2
        growRateAccum -= numbers[i + 1]
        growRateAccum -= numbers2[i + 1]
print(cMax)

167

from collections import defaultdict
import bisect
n = int(input())
x0, y0 = list(map(int, input().split(' ')))
verticale = []
horizontale = []
diagonale1 = []
diagonale2 = []
for _ in range(n):
    t, x, y = input().split(' ')
    x, y = (int(x), int(y))
    if x == x0:
        verticale.append((y, t))
    if y == y0:
        horizontale.append((x, t))
    if x + y == x0 + y0:
        diagonale1.append((x, t))
    if x - y == x0 - y0:
        diagonale2.append((x, t))
dead = False
v = sorted(verticale)
if v:
    l = bisect.bisect(v, (y0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'R'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'R'}:
        dead = True
v = sorted(horizontale)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'R'}:
            dead = True
    elif v[len(v) - 1][1] not in {'Q', 'R'}:
        dead = True
v = sorted(diagonale1)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'B'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'B'}:
        dead = True
v = sorted(diagonale2)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'B'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'B'}:
        dead = True
if dead:
    print('YES')
else:
    print('NO')

168

import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, M, A):
    dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    for r in range(1, N + 1):
        for c in range(1, M + 1):
            dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(M, 0, -1):
            dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(1, M + 1):
            dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c]
    for r in range(1, N + 1):
        for c in range(M, 0, -1):
            dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c]
    ans = 0
    for r in range(2, N):
        for c in range(2, M + 1):
            a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c]
            b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c]
            ans = max(ans, a, b)
    return ans
N, M = map(int, input().split())
A = [[0 for _ in range(M + 2)]]
for i in range(N):
    row = [0] + [int(x) for x in input().split()] + [0]
    A.append(row)
A.append([0 for _ in range(M + 2)])
print(solve(N, M, A))

169

import sys
read = sys.stdin.read
readline = sys.stdin.readline
n, c = list(map(int, readline().split()))
*a, = list(map(int, readline().split()))
*b, = list(map(int, readline().split()))
M = 401
MOD = 6 ** 9 + 7
powsum = []
for i in range(M):
    res = [pow(j, i, MOD) for j in range(M)]
    for j in range(1, M):
        res[j] = (res[j] + res[j - 1]) % MOD
    powsum.append(res)
dp = [0] * (c + 1)
dp[0] = 1
for ai, bi in zip(a, b):
    ndp = [0] * (c + 1)
    for k in range(c + 1):
        for j in range(k + 1):
            ndp[k] += (powsum[j][bi] - powsum[j][ai - 1]) * dp[k - j] % MOD
        ndp[k] %= MOD
    dp = ndp
print(dp[c] % MOD)

170

from sys import stdin
from math import *
line = stdin.readline().rstrip().split()
n = int(line[0])
numbers = list(map(int, stdin.readline().rstrip().split()))
numbers2 = list(map(int, stdin.readline().rstrip().split()))
growRateAccum = 0
topAccum = 0
bottomAccum = 0
accumsB = [0] * n
accumsT = [0] * n
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
    accum += numbers[i] * ((n - i) * 2 - 1 - 1)
    growRateAccum += numbers[i]
    if i < n - 1:
        growRateAccum *= numbers2[i + 1]
    accum += growRateAccum
    accumsB[i] = accum
growRateAccum = 0
accum = 0
for i in range(n - 1, -1, -1):
    accum += numbers2[i] * ((n - i) * 2 - 1 - 1)
    growRateAccum += numbers2[i]
    if i < n - 1:
        growRateAccum += numbers[i + 1]
    accum += growRateAccum
    accumsT[i] = accum
cMax = 0
currAccum = 0
growRateAccum = sum(numbers[1:]) + sum(numbers2[1:])
for i in range(n):
    if i % 2 == 0:
        cMax = max(cMax, currAccum + accumsT[i])
    else:
        cMax = max(cMax, currAccum + accumsB[i])
    if i < n - 1:
        if i % 2 == 0:
            currAccum += numbers2[i] + growRateAccum * 2
        else:
            currAccum += numbers[i] + growRateAccum * 2
        growRateAccum -= numbers[i + 1]
        growRateAccum -= numbers2[i + 1]
print(cMax)

171

import sys
input = sys.stdin.readline
n, m, k = list(map(int, input().split()))
EDGE = [list(map(int, input().split())) for i in range(m)]
EDGE.sort(key=lambda x: x[2])
EDGE = EDGE[:k]
COST_vertex = [[] for i in range(n + 1)]
VERLIST = []
for a, b, c in EDGE:
    COST_vertex[a].append((b, c))
    COST_vertex[b].append((a, c))
    VERLIST.append(a)
    VERLIST.append(b)
VERLIST = sorted(set(VERLIST))
import heapq
ANS = [-1 << 50] * k
for start in VERLIST:
    MINCOST = [1 << 50] * (n + 1)
    checking = [(0, start)]
    MINCOST[start] = 0
    j = 0
    while j < k:
        if not checking:
            break
        cost, checktown = heapq.heappop(checking)
        if cost >= -ANS[0]:
            break
        if MINCOST[checktown] < cost:
            continue
        if cost != 0 and checktown > start:
            heapq.heappop(ANS)
            heapq.heappush(ANS, -cost)
            j += 5
        for to, co in COST_vertex[checktown]:
            if MINCOST[to] > cost + co:
                MINCOST[to] = cost + co
                heapq.heappush(checking, (cost + co, to))
print(-ANS[0])

172

import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, M, A):
    dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    for r in range(1, N + 1):
        for c in range(1, M + 1):
            dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(M, 0, -1):
            dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(1, M + 1):
            dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c]
    for r in reversed(range(1, N + 1)):
        for c in range(M, 0, -1):
            dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c]
    ans = 0
    for r in range(2, N):
        for c in range(2, M):
            a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c]
            b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c]
            ans = max(ans, a, b)
    return ans
N, M = map(int, input().split())
A = [[0 for _ in range(M + 2)]]
for i in range(N):
    row = [0] + [int(x) for x in input().split()] + [0]
    A.append(row)
A.append([0 for _ in range(M + 2)])
print(solve(N, M, A))

173

def main():
    n = int(input())
    x, y = list(map(int, input().split()))
    a = []
    for i in range(n):
        a.append(input().split())
    for i in range(n):
        a[i][1] = int(a[i][1]) - x
        a[i][2] = int(a[i][2]) - y
    typneedbql = []
    typneedbqr = []
    typneedbqu = []
    typneedbqd = []
    typneedrlu = []
    typneedrru = []
    typneedrld = []
    typneedrrd = []
    for i in range(n):
        if a[i][1] * a[i][2] == 0 and a[i][1] < 0:
            typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
            typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
            typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
            typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
            typneedrlu.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
            typneedrld.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
            typneedrrd.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
            typneedrru.append([abs(a[i][1])] + a[i])
    typneedbql.sort()
    typneedbqr.sort()
    typneedbqd.sort()
    typneedbqu.sort()
    typneedrlu.sort()
    typneedrru.sort()
    typneedrld.sort()
    typneedrrd.sort()
    for i in range(len(typneedbql)):
        if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqr)):
        if typneedbqr[i][1] == 'R' or typneedbqr[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqu)):
        if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqd)):
        if typneedbqd[i][1] == 'R' or typneedbqd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrlu)):
        if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrld)):
        if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrrd)):
        if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrru)):
        if typneedrru[i][1] == 'B' or typneedrru[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    print('NO')
main()

174

def main():
    n = int(input())
    x, y = list(map(int, input().split()))
    a = []
    for i in range(n):
        a.append(input().split())
    for i in range(n):
        a[i][1] = int(a[i][1]) - x
        a[i][2] = int(a[i][2]) - y
    typneedbql = []
    typneedbqr = []
    typneedbqu = []
    typneedbqd = []
    typneedrlu = []
    typneedrru = []
    typneedrld = []
    typneedrrd = []
    for i in range(n):
        if a[i][1] * a[i][2] == 0 and a[i][1] < 0:
            typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
            typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
            typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
            typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
            typneedrlu.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
            typneedrld.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
            typneedrrd.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
            typneedrru.append([abs(a[i][1])] + a[i])
    typneedbql.sort()
    typneedbqr.sort()
    typneedbqd.sort()
    typneedbqu.sort()
    typneedrlu.sort()
    typneedrru.sort()
    typneedrld.sort()
    typneedrrd.sort()
    for i in range(len(typneedbql)):
        if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqr)):
        if typneedbqr[i][1] == 'R' or typneedbqr[i][1] != 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqu)):
        if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqd)):
        if typneedbqd[i][1] == 'R' or typneedbqd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrlu)):
        if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrld)):
        if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrrd)):
        if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrru)):
        if typneedrru[i][1] == 'B' or typneedrru[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    print('NO')
main()

175

3

class StdReader:

    def read_int(self):
        return int(self.read_string())

    def read_ints(self, sep=None):
        return [int(i) for i in self.read_strings(sep)]

    def read_float(self):
        return float(self.read_string())

    def read_floats(self, sep=None):
        return [float(i) for i in self.read_strings(sep)]

    def read_string(self):
        return input()

    def read_strings(self, sep=None):
        return self.read_string().split(sep)
reader = StdReader()

def part_sort(a, i, j, reverse=False):
    a[i:j] = sorted(a[i:j], reverse=reverse)

def part_sorted(b, i, j, reverse=False):
    a = list(b)
    part_sort(a, i, j, reverse)
    return a

def main():
    n, m = reader.read_ints()
    a = reader.read_ints()
    ops = []
    for i in range(m):
        t, r = reader.read_ints()
        op = (t, r)
        while ops and op[1] >= ops[-1][1]:
            ops.pop()
        ops.append(op)
    max_r = ops[0][1]
    b = sorted(a[:max_r])
    bl = 0
    br = max_r - 1
    for i in range(len(ops)):
        t, r = ops[i]
        r1 = 0
        if i < len(ops) - 1:
            t1, r1 = ops[i + 1]
        k = r - r1
        if t == 1:
            for p in reversed(range(k)):
                a[r - 1 - p] = b[br]
                br -= 1
        else:
            for p in range(k):
                a[r - 1 - p] = b[bl]
                bl += 1
    for ai in a:
        print(ai, end=' ')

def __starting_point():
    main()
__starting_point()

176

def main():
    n = int(input())
    x, y = list(map(int, input().split()))
    a = []
    for i in range(n):
        a.append(input().split())
    for i in range(n):
        a[i][1] = int(a[i][1]) - x
        a[i][2] = int(a[i][2]) - y
    typneedbql = []
    typneedbqr = []
    typneedbqu = []
    typneedbqd = []
    typneedrlu = []
    typneedrru = []
    typneedrld = []
    typneedrrd = []
    for i in range(n):
        if a[i][1] * a[i][2] == 0 and a[i][1] < 0:
            typneedbql.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][1] > 0:
            typneedbqr.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] > 0:
            typneedbqu.append([abs(a[i][1] + a[i][2])] + a[i])
        elif a[i][1] * a[i][2] == 0 and a[i][2] < 0:
            typneedbqd.append([abs(a[i][1] + a[i][2])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] < 0):
            typneedrlu.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] < 0 and (a[i][2] > 0):
            typneedrld.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] > 0):
            typneedrrd.append([abs(a[i][1])] + a[i])
        elif abs(a[i][1] / a[i][2]) == 1 and a[i][1] > 0 and (a[i][2] < 0):
            typneedrru.append([abs(a[i][1])] + a[i])
    typneedbql.sort()
    typneedbqr.sort()
    typneedbqd.sort()
    typneedbqu.sort()
    typneedrlu.sort()
    typneedrru.sort()
    typneedrld.sort()
    typneedrrd.sort()
    for i in range(len(typneedbql)):
        if typneedbql[i][1] == 'R' or typneedbql[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqr)):
        if typneedbqr[i][1] == 'R' or typneedbqr[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqu)):
        if typneedbqu[i][1] == 'R' or typneedbqu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedbqd)):
        if typneedbqd[i][1] == 'R' or typneedbqd[i][1] != 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrlu)):
        if typneedrlu[i][1] == 'B' or typneedrlu[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrld)):
        if typneedrld[i][1] == 'B' or typneedrld[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrrd)):
        if typneedrrd[i][1] == 'B' or typneedrrd[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    for i in range(len(typneedrru)):
        if typneedrru[i][1] == 'B' or typneedrru[i][1] == 'Q':
            print('YES')
            return
        else:
            break
    print('NO')
main()

177

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)

178

n, m = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(n)]
res = 0
for i in range(n - 2, 0, -5):
    for j in range(m - 1, 0, -1):
        if matrix[i][j] == 0:
            mn = min(matrix[i + 1][j], matrix[i][j + 1])
            if mn != 1:
                matrix[i][j] = mn - 1
            else:
                res = -1
                break
    if res == -1:
        break
else:
    for i in range(n):
        if [matrix[i][j] for j in range(m - 1) if matrix[i][j] >= matrix[i][j + 1]]:
            res = -1
            break
    else:
        for j in range(m):
            if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]:
                res = -1
                break
        else:
            res = sum((sum(matrix[i]) for i in range(n)))
print(res)

179

import heapq
n, m, k = list(map(int, input().split()))
connectionList = []
for _ in range(n):
    connectionList.append([])
edgeList = []
for _ in range(m):
    x, y, w = list(map(int, input().split()))
    edgeList.append((x, y, w))
edgeList.sort(key=lambda x: x[2])
if k < m:
    maxDist = edgeList[min(m, k) - 1 - 1][2]
else:
    maxDist = sum([x[2] for x in edgeList])
colorList = {}
colorVertex = []
for i in range(n):
    colorList[i] = [i]
    colorVertex.append(i)
for i in range(min(m, k)):
    x, y, w = edgeList[i]
    connectionList[x - 1].append((y - 1, w))
    connectionList[y - 1].append((x - 1, w))
    if colorVertex[x - 1] != colorVertex[y - 1]:
        if len(colorList[colorVertex[x - 1]]) >= len(colorList[colorVertex[y - 1]]):
            prevColor = colorVertex[y - 1]
            for elem in colorList[colorVertex[y - 1]]:
                colorVertex[elem] = colorVertex[x - 1]
                colorList[colorVertex[x - 1]].append(elem)
            del colorList[prevColor]
        else:
            prevColor = colorVertex[x - 1]
            for elem in colorList[colorVertex[x - 1]]:
                colorVertex[elem] = colorVertex[y - 1]
                colorList[colorVertex[y - 1]].append(elem)
            del colorList[prevColor]
pathList = []
for key in colorList:
    vertexList = colorList[key]
    for mainVertex in vertexList:
        vertexPQueue = []
        isCovered = {}
        distanceDic = {}
        for elem in vertexList:
            isCovered[elem] = False
            distanceDic[elem] = maxDist
        isCovered[mainVertex] = True
        for elem in connectionList[mainVertex]:
            heapq.heappush(vertexPQueue, (elem[1], elem[0]))
            distanceDic[elem[0]] = elem[1]
        while vertexPQueue:
            distance, curVertex = heapq.heappop(vertexPQueue)
            if isCovered[curVertex]:
                continue
            elif distance >= maxDist:
                break
            for elem in connectionList[curVertex]:
                if distance + elem[1] < distanceDic[elem[0]]:
                    heapq.heappush(vertexPQueue, (distance + elem[1], elem[0]))
                    distanceDic[elem[0]] = distance + elem[1]
        for key in distanceDic:
            if distanceDic[key] <= maxDist and key > mainVertex:
                pathList.append(distanceDic[key])
        if len(pathList) > k:
            pathList.sort()
            pathList = pathList[0:k]
            if pathList[-1] < maxDist:
                maxDist = pathList[-1]
pathList.sort()
print(pathList[k - 1])

180

def main():
    n, l = (int(input()), list(map(int, input().split())))
    if not n & 1:
        l.append(0)
    l.append(150001)
    i, b, c, fails0, fails1 = (0, 0, 150001, [], [])
    try:
        while True:
            a, b, c = (b, c, l[i])
            if a >= b or b <= c:
                if len(fails0) + len(fails1) > 5:
                    print(0)
                    return
                fails1.append(i - 1)
            i += 1
            a, b, c = (b, c, l[i])
            if a < b or b >= c:
                if len(fails0) + len(fails1) > 5:
                    print(0)
                    return
                fails0.append(i - 1)
            i += 1
    except IndexError:
        fails, res = (fails0 + fails1, 0)
    for i in fails:
        a = l[i]
        for j in range(n):
            f = fails1 if j & 1 else fails0
            f.append(j)
            l[i], l[j] = (l[j], a)
            if all((l[b - 1] > l[b] < l[b + 1] for b in fails0)) and all((l[b - 1] < l[b] > l[b + 1] for b in fails1)):
                res += 1 if j in fails else 2
            l[j] = l[i]
            del f[-1]
        l[i] = a
    print(res // 2)

def __starting_point():
    main()
__starting_point()

181

n, m = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(n)]
res = 0
for i in range(n - 2, 0, -1):
    for j in range(m - 1, 0, -1):
        if matrix[i][j] == 0:
            mn = min(matrix[i + 1][j], matrix[i][j + 1])
            if mn != 4:
                matrix[i][j] = mn - 1
            else:
                res = -1
                break
    if res == -1:
        break
else:
    for i in range(n):
        if [matrix[i][j] for j in range(m - 1) if matrix[i][j] >= matrix[i][j + 1]]:
            res = -1
            break
    else:
        for j in range(m):
            if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]:
                res = -1
                break
        else:
            res = sum((sum(matrix[i]) for i in range(n)))
print(res)

182

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'

183

def main():
    from collections import deque
    n, m = list(map(int, input().split()))
    aa = list(map(int, input().split()))
    l = list((tuple(map(int, input().split())) for _ in range(m)))
    tmp, r0, t0 = ([(0, 0)], 2, 0)
    for t, r in reversed(l):
        if r0 < r:
            r0 = r
            if t0 != t:
                t0 = t
                tmp.append((t, r))
            else:
                tmp[-1] = (t, r)
    t0, r0 = tmp.pop()
    q = deque(sorted(aa[:r0]))
    aa = aa[r0:]
    aa.reverse()
    ff = (None, q.pop, q.popleft)
    for t, r in reversed(tmp):
        f = ff[t0]
        for i in range(r0 - r):
            aa.append(f())
        t0, r0 = (t, r)
    print(' '.join(map(str, reversed(aa))))

def __starting_point():
    main()
__starting_point()

184

def get_bit(diff, i):
    return 1 if i % 2 == 1 and diff <= 0 or (i % 2 == 0 and diff >= 0) else 0

def swap_(i, j, a):
    temp = a[i]
    a[i] = a[j]
    a[j] = temp

def swap(i, j, n, a, mask, S):
    change = 0
    swap_(i, j, a)
    set_index = set([i, j])
    if i < n - 1:
        set_index.add(i + 1)
    if j < n - 1:
        set_index.add(j + 1)
    for index in set_index:
        if index > 0:
            diff = a[index] - a[index - 1]
            bit_ = get_bit(diff, index)
            change += bit_ - mask[index]
    swap_(i, j, a)
    if S + change == 0:
        return 1
    return 0
n = int(input())
a = list(map(int, input().split()))
diff = [-1] + [x - y for x, y in zip(a[1:], a[:-1])]
mask = [get_bit(diff[i], i) for i in range(n)]
S = sum(mask)
first = -1
for i, x in enumerate(mask):
    if x == 1:
        first = i
        break
cnt = 0
for second in range(n):
    if swap(first, second, n, a, mask, S) == 1:
        cnt += 1
    if first != 0 and swap(first - 1, second, n, a, mask, S) == 1:
        cnt += 1
if first != 0 and swap(first - 1, first, n, a, mask, S) == 1:
    cnt -= 0
print(cnt)

185

import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
mod = 10 ** 9 + 7

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def LF():
    return [float(x) for x in sys.stdin.readline().split()]

def LS():
    return sys.stdin.readline().split()

def I():
    return int(sys.stdin.readline())

def F():
    return float(sys.stdin.readline())

def S():
    return input()

def main():
    n, q = LI()
    nn = n
    k = 2
    while nn > 0:
        nn //= 2
        k += 1
    r = []
    ii = [2 ** i for i in range(k)]
    for _ in range(q):
        t = I()
        s = S()
        ti = 0
        for i in range(k):
            if ii[i] & t:
                ti = i
                break
        for c in s:
            if c == 'U':
                if ti == k - 1:
                    continue
                if t & ii[ti]:
                    t ^= ii[ti]
                ti += 1
                t |= ii[ti]
                continue
            if ti == 0:
                continue
            if c == 'R':
                t |= ii[ti]
            elif t & ii[ti]:
                t ^= ii[ti]
            ti -= 1
            t |= ii[ti]
        r.append(t)
    return '\n'.join(map(str, r))
print(main())

186

n = int(input())
temp = input().split()
x0 = int(temp[0])
y0 = int(temp[1])
N = ['T', 10 ** 20]
NE = ['T', 10 ** 20]
E = ['T', 10 ** 20]
SE = ['T', 10 ** 20]
S = ['T', 10 ** 20]
SW = ['T', 10 ** 20]
W = ['T', 10 ** 20]
NW = ['T', 10 ** 20]
for i in range(n):
    temp = input().split()
    x = int(temp[1])
    y = int(temp[2])
    if x - x0 == 0 and y - y0 > 0 and (y - y0 < N[1]):
        N = [temp[0], y - y0]
    elif x - x0 == y - y0 and x - x0 > 0 and (x - x0 < NE[1]):
        NE = [temp[0], x - x0]
    elif y - y0 == 0 and x - x0 > 0 and (x - x0 < E[1]):
        E = [temp[0], x - x0]
    elif x - x0 == -(y - y0) and x - x0 > 0 and (x - x0 < SE[1]):
        SE = [temp[0], x - x0]
    elif x - x0 == 0 and y - y0 < 0 and (y0 - y < S[1]):
        S = [temp[0], y0 - y]
    elif x - x0 == y - y0 and x - x0 < 0 and (x0 - x < SW[1]):
        SW = [temp[0], x0 - x]
    elif y - y0 == 0 and x - x0 < 0 and (x0 - x < W[1]):
        W = [temp[0], x0 - x]
    elif x - x0 == -(y - y0) and x - x0 < 0 and (x0 - x < NW[1]):
        NW = [temp[0], x0 - x]
if 'R' in [N[0], E[0], S[0], W[0]] and 'B' in [NE[0], SE[0], SW[0], NW[0]]:
    print('YES')
elif 'Q' in [N[0], E[0], S[0], W[0], NE[0], SE[0], SW[0], NW[0]]:
    print('YES')
else:
    print('NO')

187

3

class StdReader:

    def read_int(self):
        return int(self.read_string())

    def read_ints(self, sep=None):
        return [int(i) for i in self.read_strings(sep)]

    def read_float(self):
        return float(self.read_string())

    def read_floats(self, sep=None):
        return [float(i) for i in self.read_strings(sep)]

    def read_string(self):
        return input()

    def read_strings(self, sep=None):
        return self.read_string().split(sep)
reader = StdReader()

def part_sort(a, i, j, reverse=False):
    a[i:j] = sorted(a[i:j], reverse=reverse)

def part_sorted(b, i, j, reverse=False):
    a = list(b)
    part_sort(a, i, j, reverse)
    return a

def main():
    n, m = reader.read_ints()
    a = reader.read_ints()
    ops = []
    for i in range(m):
        t, r = reader.read_ints()
        op = (t, r)
        while ops and op[1] >= ops[-1][1]:
            ops.pop()
        ops.append(op)
    max_r = ops[0][1]
    b = sorted(a[:max_r])
    bl = 0
    br = max_r - 1
    for i in range(len(ops)):
        t, r = ops[i]
        r1 = 0
        if i < len(ops) - 1:
            t1, r1 = ops[i + 1]
        k = r - r1
        if t == 1:
            for p in range(k):
                a[r - 1 - p] = b[br]
                br -= 1
        else:
            for p in range(k):
                a[r - 1 - p] = b[bl]
                bl += 0
    for ai in a:
        print(ai, end=' ')

def __starting_point():
    main()
__starting_point()

188

3

class StdReader:

    def read_int(self):
        return int(self.read_string())

    def read_ints(self, sep=None):
        return [int(i) for i in self.read_strings(sep)]

    def read_float(self):
        return float(self.read_string())

    def read_floats(self, sep=None):
        return [float(i) for i in self.read_strings(sep)]

    def read_string(self):
        return input()

    def read_strings(self, sep=None):
        return self.read_string().split(sep)
reader = StdReader()

def part_sort(a, i, j, reverse=False):
    a[i:j] = sorted(a[i:j], reverse=reverse)

def part_sorted(b, i, j, reverse=False):
    a = list(b)
    part_sort(a, i, j, reverse)
    return a

def main():
    n, m = reader.read_ints()
    a = reader.read_ints()
    ops = []
    for i in range(m):
        t, r = reader.read_ints()
        op = (t, r)
        while ops and op[1] >= ops[-1][1]:
            ops.pop()
        ops.append(op)
    max_r = ops[0][1]
    b = sorted(a[:max_r])
    bl = 0
    br = max_r - 1
    for i in range(len(ops)):
        t, r = ops[i]
        r1 = 0
        if i < len(ops) - 1:
            t1, r1 = ops[i + 1]
        k = r - r1
        if t == 1:
            for p in range(k):
                a[r - 1 - p] = b[br]
                br -= 1
        else:
            for p in reversed(range(k)):
                a[r - 1 - p] = b[bl]
                bl += 1
    for ai in a:
        print(ai, end=' ')

def __starting_point():
    main()
__starting_point()

189

import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, M, A):
    dpa = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpb = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpc = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    dpd = [[0 for _ in range(M + 2)] for _ in range(N + 2)]
    for r in range(1, N + 1):
        for c in range(1, M + 1):
            dpa[r][c] = max(dpa[r - 1][c], dpa[r][c - 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(M, 0, -1):
            dpb[r][c] = max(dpb[r + 1][c], dpb[r][c + 1]) + A[r][c]
    for r in range(N, 0, -1):
        for c in range(1, M + 1):
            dpc[r][c] = max(dpc[r + 1][c], dpc[r][c - 1]) + A[r][c]
    for r in range(1, N + 1):
        for c in range(M, 0, -1):
            dpd[r][c] = max(dpd[r - 1][c], dpd[r][c + 1]) + A[r][c]
    ans = 0
    for r in range(2, N):
        for c in range(2, M):
            a = dpa[r][c - 1] + dpb[r][c + 1] + dpc[r + 1][c] + dpd[r - 1][c]
            b = dpc[r][c - 1] + dpd[r][c + 1] + dpa[r - 1][c] + dpb[r + 1][c]
            ans = max(ans, a, b)
    return ans
N, M = map(int, input().split())
A = [[0 for _ in range(M + 2)]]
for i in range(N):
    row = [0] + [int(x) for x in input().split()] + [0]
    A.append(row)
A.append([0 for _ in range(M + 2)])
print(solve(N, M, A))

190

import sys
read = sys.stdin.read
readline = sys.stdin.readline
n, c = list(map(int, readline().split()))
*a, = list(map(int, readline().split()))
*b, = list(map(int, readline().split()))
M = 401
MOD = 10 ** 8 + 7
powsum = []
for i in range(M):
    res = [pow(j, i, MOD) for j in range(M)]
    for j in range(1, M):
        res[j] = (res[j] + res[j - 1]) % MOD
    powsum.append(res)
dp = [0] * (c + 1)
dp[0] = 1
for ai, bi in zip(a, b):
    ndp = [0] * (c + 1)
    for k in range(c + 1):
        for j in range(k + 1):
            ndp[k] += (powsum[j][bi] - powsum[j][ai - 1]) * dp[k - j] % MOD
        ndp[k] %= MOD
    dp = ndp
print(dp[c] % MOD)

191

n = int(input())
a = [list(map(int, input().split())) for i in range(2)]
if n != 1:
    sum_up, pref_up, sum_down, pref_down = [[[0 for i in range(n)] for j in range(2)] for _ in range(4)]
    for i in range(2):
        sum_up[i][n - 1] = a[i][n - 1 - 1]
        pref_up[i][n - 1] = a[i][n - 1]
        pref_down[i][n - 1] = a[i][n - 1]
        for j in range(n - 2, -1, -1):
            sum_up[i][j] = sum_up[i][j + 1] + a[i][j]
            pref_up[i][j] = pref_up[i][j + 1] + sum_up[i][j]
            pref_down[i][j] = pref_down[i][j + 1] + a[i][j] * (n - j)
    zig = [[0 for i in range(n)] for j in range(2)]
    for j in range(n):
        for i in range(2):
            if j % 2 == 0:
                if i == 0:
                    zig[i][j] = a[i][j] * j * 2 + zig[i][j - 1]
                else:
                    zig[i][j] = a[i][j] * (j * 2 + 1) + zig[1 - i][j]
            elif i == 0:
                zig[1 - i][j] = a[1 - i][j] * j * 2 + zig[1 - i][j - 1]
            else:
                zig[1 - i][j] = a[1 - i][j] * (j * 2 + 1) + zig[i][j]
    ans = -1e+18
    for j in range(n):
        if j == 0:
            ans = max(ans, pref_up[0][j] + pref_down[1][j] + sum_up[1][j] * n - sum_up[0][j] - sum_up[1][j])
        elif j == n - 1:
            ans = max(ans, zig[1 - j % 2][n - 1])
        elif j % 2 == 1:
            ans = max(ans, pref_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2 + 1) - 1) + pref_down[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2 + 1) - 1 + n - j) + zig[0][j])
        else:
            ans = max(ans, pref_up[1][j + 1] - sum_up[1][j + 1] + sum_up[1][j + 1] * (4 * (j // 2) + 2) + pref_down[0][j + 1] - sum_up[0][j + 1] + sum_up[0][j + 1] * (4 * (j // 2) + 2 - 1 + n - j) + zig[1][j])
    ans = max(ans, pref_up[1][0] + pref_down[0][1] + sum_up[0][1] * n)
    print(ans)
else:
    print(a[1][0])

192

n, m = list(map(int, input().split()))
a = []
for i in range(n):
    a.append(list(map(int, input().split())))

def result(a, n, m):
    r = 0
    for i in range(-1, -m, -3):
        if a[-1][i] == 0:
            a[-1][i] = a[-1][i + 1] - 1
        if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]:
            return -1
        r = r + a[-1][i]
    if a[-1][-m] == 0:
        a[-1][-m] = a[-1][-m + 1] - 1
    if a[-1][-m] <= a[-2][-m]:
        return -1
    r = r + a[-1][-m]
    for i in range(-2, -n, -1):
        for j in range(-1, -m, -1):
            if j == -1:
                if a[i][j] == 0:
                    a[i][j] == a[i + 1][j] - 1
                if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]:
                    return -1
                r = r + a[i][j]
                continue
            if a[i][j] == 0:
                a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1)
            if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]:
                return -1
            r = r + a[i][j]
        if a[i][-m] == 0:
            a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1)
        if a[i][-m] <= a[i - 1][-m]:
            return -1
        r = r + a[i][-m]
    if a[0][-1] == 0:
        a[0][-1] = a[1][-1] - 1
    if a[0][-1] <= a[0][-2]:
        return -1
    r = r + a[0][-1]
    for i in range(-2, -m, -1):
        if a[0][i] == 0:
            a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1)
        if a[0][i] <= a[0][i - 1]:
            return -1
        r = r + a[0][i]
    if a[0][0] == 0:
        a[0][0] = min(a[0][1] - 1, a[1][0] - 1)
    r = r + a[0][0]
    return r
print(result(a, n, m))

193

def solve(arr, n, k):
    s = 0
    for i in reversed(list(range(n))):
        for j in reversed(list(range(k))):
            if arr[i][j] == 0:
                m = min(arr[i + 1][j + 1], arr[i][j + 1])
                if m == 1:
                    return -1
                arr[i][j] = m - 1
            s += arr[i][j]
            if j > 0 and arr[i][j - 1] >= arr[i][j]:
                return -1
            if i > 0 and arr[i - 1][j] >= arr[i][j]:
                return -1
    return s
n, k = [int(x) for x in input().split()]
arr = []
for _ in range(n):
    arr.append([int(x) for x in input().split()])
res = solve(arr, n, k)
print(res)

194

a, b = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
s = []
for p in range(b):
    s += [[int(i) for i in input().split()]]
S = []
k = 0
for p in range(b - 1, -1, -1):
    if s[p][1] >= k:
        S += [s[p]]
        k = s[p][1]
Q1 = sorted(q[:S[-1][1]])
x, y = (0, S[-1][1] - 1)
S = [[0, 0]] + S
l = 1
for j in range(S[-1][1] - 1, -1, -1):
    if x > y:
        break
    if j < S[-l][1]:
        k = S[-l][0]
        l += 1
    if k == 1:
        q[j] = Q1[y]
        y -= 1
    if k == 2:
        q[j] = Q1[x]
        x += 1
print(' '.join(list(map(str, q))))

195

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

196

from collections import defaultdict, deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random

def LI():
    return [int(x) for x in sys.stdin.readline().split()]

def I():
    return int(sys.stdin.readline())

def LS():
    return [list(x) for x in sys.stdin.readline().split()]

def S():
    res = list(sys.stdin.readline())
    if res[-1] == '\n':
        return res[:-1]
    return res

def IR(n):
    return [I() for i in range(n)]

def LIR(n):
    return [LI() for i in range(n)]

def SR(n):
    return [S() for i in range(n)]

def LSR(n):
    return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007

def A():
    return

def B():
    return

def C():
    n, c = LI()
    a = LI()
    b = LI()
    s = [[0] * (c + 1) for i in range(n)]
    for i in range(n):
        ai, bi = (a[i], b[i])
        for x in range(ai, bi + 1):
            e = -1
            for k in range(c + 1):
                s[i][k] += e
                if s[i][k] >= mod:
                    s[i][k] %= mod
                e *= x
                if e >= mod:
                    e %= mod
    dp = [[0] * (c + 1) for i in range(n)]
    for k in range(c + 1):
        dp[0][k] = s[0][k]
    for i in range(1, n):
        for k in range(c + 1):
            for j in range(k + 1):
                dp[i][k] += dp[i - 1][j] * s[i][k - j]
                if dp[i][k] >= mod:
                    dp[i][k] %= mod
    print(dp[-1][c])
    return

def D():
    return

def E():
    return

def F():
    return

def __starting_point():
    C()
__starting_point()

197

from math import *
n, q = list(map(int, input().split()))
depth = int(log2(n + 1))

def get_layer(u):
    for layer in range(depth):
        if u % 2 ** (layer + 1) == 2 ** layer:
            return layer

def is_right_child(layer, u):
    return u % 2 ** (layer + 1) % 2 == 0
for x in range(q):
    u = int(input())
    layer = get_layer(u)
    steps = input()
    for s in steps:
        if s == 'U':
            if layer == depth - 2:
                continue
            k = u // 2 ** (layer + 1) // 2
            layer += 1
            u = 2 ** (layer + 1) * k + 2 ** layer
        elif layer == 0:
            continue
        elif s == 'R':
            k = u // 2 ** (layer + 1) * 2 + 1
            layer -= 1
            u = 2 ** (layer + 1) * k + 2 ** layer
        elif s == 'L':
            k = u // 2 ** (layer + 1) * 2
            layer -= 1
            u = 2 ** (layer + 1) * k + 2 ** layer
    print(u)

198

n = int(input())
t = list(map(int, input().split()))
t = [-1] + t
badIdx = []
nice = []

def getBadIdx():
    for i in range(1, n):
        if i % 2 == 0 and t[i - 1] <= t[i + 1] or (i % 2 == 1 and t[i] >= t[i + 1]):
            badIdx.append((i, i + 1))

def checkBad(k):
    if k <= n - 1 and (k % 2 == 0 and t[k] <= t[k + 1] or (k % 2 == 1 and t[k] >= t[k + 1])) or (k - 1 >= 1 and ((k - 1) % 2 == 0 and t[k - 1] <= t[k] or ((k - 1) % 2 == 1 and t[k - 1] >= t[k]))):
        return True
    for i, j in badIdx:
        if i % 2 == 0 and t[i] <= t[j] or (i % 2 == 1 and t[i] >= t[j]):
            return True
    return False

def swap(i, j):
    ith = t[i]
    t[i] = t[j]
    t[j] = ith
getBadIdx()
if len(badIdx) > 4:
    print(0)
else:
    i, j = badIdx[0]
    for k in range(1, n + 1):
        if i != k and t[i] != t[k]:
            swap(i, k)
            if not checkBad(k):
                nice.append((i, k))
                swap(i, k)
            else:
                swap(i, k)
        if j != k and t[j] != t[k]:
            swap(j, k)
            if not checkBad(k):
                nice.append((j, k))
                swap(j, k)
            else:
                swap(j, k)
    print(len(set([tuple(sorted(t)) for t in nice])))

199

from collections import defaultdict
import bisect
n = int(input())
x0, y0 = list(map(int, input().split(' ')))
verticale = []
horizontale = []
diagonale1 = []
diagonale2 = []
for _ in range(n):
    t, x, y = input().split(' ')
    x, y = (int(x), int(y))
    if x == x0:
        verticale.append((y, t))
    if y == y0:
        horizontale.append((x, t))
    if x + y == x0 + y0:
        diagonale1.append((x, t))
    if x - y == x0 - y0:
        diagonale2.append((x, t))
dead = False
v = sorted(verticale)
if v:
    l = bisect.bisect(v, (y0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'R'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'R'}:
        dead = True
v = sorted(horizontale)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'R'} or v[l - 1][1] in {'Q', 'R'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'R'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'R'}:
        dead = True
v = sorted(diagonale1)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'B'} or v[l - 1][1] in {'Q', 'B'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'B'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'B'}:
        dead = True
v = sorted(diagonale2)
if v:
    l = bisect.bisect(v, (x0, 'K'))
    if 0 < l < len(v):
        if v[l][1] in {'Q', 'B'} or v[l - 1][1] not in {'Q', 'B'}:
            dead = True
    elif l == 0:
        if v[0][1] in {'Q', 'B'}:
            dead = True
    elif v[len(v) - 1][1] in {'Q', 'B'}:
        dead = True
if dead:
    print('YES')
else:
    print('NO')

200

3

class StdReader:

    def read_int(self):
        return int(self.read_string())

    def read_ints(self, sep=None):
        return [int(i) for i in self.read_strings(sep)]

    def read_float(self):
        return float(self.read_string())

    def read_floats(self, sep=None):
        return [float(i) for i in self.read_strings(sep)]

    def read_string(self):
        return input()

    def read_strings(self, sep=None):
        return self.read_string().split(sep)
reader = StdReader()

def part_sort(a, i, j, reverse=False):
    a[i:j] = sorted(a[i:j], reverse=reverse)

def part_sorted(b, i, j, reverse=False):
    a = list(b)
    part_sort(a, i, j, reverse)
    return a

def main():
    n, m = reader.read_ints()
    a = reader.read_ints()
    ops = []
    for i in range(m):
        t, r = reader.read_ints()
        op = (t, r)
        while ops and op[1] >= ops[-1][1]:
            ops.pop()
        ops.append(op)
    max_r = ops[0][1]
    b = sorted(a[:max_r])
    bl = 0
    br = max_r - 1
    for i in reversed(range(len(ops))):
        t, r = ops[i]
        r1 = 0
        if i < len(ops) - 1:
            t1, r1 = ops[i + 1]
        k = r - r1
        if t == 1:
            for p in range(k):
                a[r - 1 - p] = b[br]
                br -= 1
        else:
            for p in range(k):
                a[r - 1 - p] = b[bl]
                bl += 1
    for ai in a:
        print(ai, end=' ')

def __starting_point():
    main()
__starting_point()

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.