A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey:  c=[1,2,4]c=[1,2,4];  c=[3,5,6,8]c=[3,5,6,8];  c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].

n = int(input())
a = list(map(int, input().split()))

sol = [i-a[i] for i in range(n)]

val = {}
ans = 0
for i in range(n):
    if sol[i] not in val:
        val[sol[i]] = a[i]
    else:
        val[sol[i]] += a[i]

    ans = max(ans, val[sol[i]])

print(ans)


B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.

t = int(input())

for i in range(t):

    n = int(input())

    l = list(map(int,input().split()))

    flag = True

    for i in range(n-2):

        try:

            x = l.index(l[i],i+2)

            flag = False

            print("YES")

            break

        except:

            continue

    if flag:

        print("NO")


B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:

t=int(input())

for i in range(t):

    n=int(input())

    xp=[]

    yp=[]

    for j in range(n):

        x,y=[int(k) for k in input().split()]

        xp.append(x)

        yp.append(y)

    s=set(xp)

    ans=""

    posx=0

    posy=0

    flag=True

    for z in s:

        l=[]

        for y in range(n):

            if xp[y]==z:

                l.append(yp[y])

        l.sort()

        if min(l)<posy:

            flag=False

            break

        else :

            ans+=("R"*(z-posx))

            ans+=("U"*(max(l)-posy))

            posx=z

            posy=max(l)

    if flag==True:

        print("YES")

        print(ans)

    else :

        print("NO")


A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11


E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times:  Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair).  Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.

import random, sys, os, math, gc

from collections import Counter, defaultdict, deque

from functools import lru_cache, reduce, cmp_to_key

from itertools import accumulate, combinations, permutations, product

from heapq import nsmallest, nlargest, heapify, heappop, heappush

from io import BytesIO, IOBase

from copy import deepcopy

from bisect import bisect_left, bisect_right

from math import factorial, gcd

from operator import mul, xor

from types import GeneratorType

# if "PyPy" in sys.version:

#     import pypyjit; pypyjit.set_param('max_unroll_recursion=-1')

# sys.setrecursionlimit(2*10**5)

BUFSIZE = 8192

MOD = 10**9 + 7

MODD = 998244353

INF = float('inf')

D4 = [(1, 0), (0, 1), (-1, 0), (0, -1)]

D8 = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]

def solve():

    n = II()

    arr = LII()

    dp = [[INF] * n for _ in range(n)]

    w = [[0] * n for _ in range(n)]

    for i in range(n):

        dp[i][i] = 1

        w[i][i] = arr[i]

    for i in range(n-1, -1, -1):

        for j in range(i+1, n):

            for k in range(i, j):

                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j])

                if dp[i][k] == dp[k+1][j] == 1 and w[i][k] == w[k+1][j]:

                    dp[i][j] = 1

                    w[i][j] = w[i][k] + 1

    print(dp[0][n-1])

def main():

    t = 1

    # t = II()

    for _ in range(t):

        solve()

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):

        if stack:

            return f(*args, **kwargs)

        else:

            to = f(*args, **kwargs)

            while True:

                if type(to) is GeneratorType:

                    stack.append(to)

                    to = next(to)

                else:

                    stack.pop()

                    if not stack:

                        break

                    to = stack[-1].send(to)

            return to

    return wrappedfunc

def bitcnt(n):

    c = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555)

    c = (c & 0x3333333333333333) + ((c >> 2) & 0x3333333333333333)

    c = (c & 0x0F0F0F0F0F0F0F0F) + ((c >> 4) & 0x0F0F0F0F0F0F0F0F)

    c = (c & 0x00FF00FF00FF00FF) + ((c >> 8) & 0x00FF00FF00FF00FF)

    c = (c & 0x0000FFFF0000FFFF) + ((c >> 16) & 0x0000FFFF0000FFFF)

    c = (c & 0x00000000FFFFFFFF) + ((c >> 32) & 0x00000000FFFFFFFF)

    return c

def lcm(x, y):

    return x * y // gcd(x, y)

def lowbit(x):

    return x & -x

def perm(n, r):

    return factorial(n) // factorial(n - r) if n >= r else 0

def comb(n, r):

    return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0

def probabilityMod(x, y, mod):

    return x * pow(y, mod-2, mod) % mod

class SortedList:

    def __init__(self, iterable=[], _load=200):

        """Initialize sorted list instance."""

        values = sorted(iterable)

        self._len = _len = len(values)

        self._load = _load

        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]

        self._list_lens = [len(_list) for _list in _lists]

        self._mins = [_list[0] for _list in _lists]

        self._fen_tree = []

        self._rebuild = True

    def _fen_build(self):

        """Build a fenwick tree instance."""

        self._fen_tree[:] = self._list_lens

        _fen_tree = self._fen_tree

        for i in range(len(_fen_tree)):

            if i | i + 1 < len(_fen_tree):

                _fen_tree[i | i + 1] += _fen_tree[i]

        self._rebuild = False

    def _fen_update(self, index, value):

        """Update `fen_tree[index] += value`."""

        if not self._rebuild:

            _fen_tree = self._fen_tree

            while index < len(_fen_tree):

                _fen_tree[index] += value

                index |= index + 1

    def _fen_query(self, end):

        """Return `sum(_fen_tree[:end])`."""

        if self._rebuild:

            self._fen_build()

        _fen_tree = self._fen_tree

        x = 0

        while end:

            x += _fen_tree[end - 1]

            end &= end - 1

        return x

    def _fen_findkth(self, k):

        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""

        _list_lens = self._list_lens

        if k < _list_lens[0]:

            return 0, k

        if k >= self._len - _list_lens[-1]:

            return len(_list_lens) - 1, k + _list_lens[-1] - self._len

        if self._rebuild:

            self._fen_build()

        _fen_tree = self._fen_tree

        idx = -1

        for d in reversed(range(len(_fen_tree).bit_length())):

            right_idx = idx + (1 << d)

            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:

                idx = right_idx

                k -= _fen_tree[idx]

        return idx + 1, k

    def _delete(self, pos, idx):

        """Delete value at the given `(pos, idx)`."""

        _lists = self._lists

        _mins = self._mins

        _list_lens = self._list_lens

        self._len -= 1

        self._fen_update(pos, -1)

        del _lists[pos][idx]

        _list_lens[pos] -= 1

        if _list_lens[pos]:

            _mins[pos] = _lists[pos][0]

        else:

            del _lists[pos]

            del _list_lens[pos]

            del _mins[pos]

            self._rebuild = True

    def _loc_left(self, value):

        """Return an index pair that corresponds to the first position of `value` in the sorted list."""

        if not self._len:

            return 0, 0

        _lists = self._lists

        _mins = self._mins

        lo, pos = -1, len(_lists) - 1

        while lo + 1 < pos:

            mi = (lo + pos) >> 1

            if value <= _mins[mi]:

                pos = mi

            else:

                lo = mi

        if pos and value <= _lists[pos - 1][-1]:

            pos -= 1

        _list = _lists[pos]

        lo, idx = -1, len(_list)

        while lo + 1 < idx:

            mi = (lo + idx) >> 1

            if value <= _list[mi]:

                idx = mi

            else:

                lo = mi

        return pos, idx

    def _loc_right(self, value):

        """Return an index pair that corresponds to the last position of `value` in the sorted list."""

        if not self._len:

            return 0, 0

        _lists = self._lists

        _mins = self._mins

        pos, hi = 0, len(_lists)

        while pos + 1 < hi:

            mi = (pos + hi) >> 1

            if value < _mins[mi]:

                hi = mi

            else:

                pos = mi

        _list = _lists[pos]

        lo, idx = -1, len(_list)

        while lo + 1 < idx:

            mi = (lo + idx) >> 1

            if value < _list[mi]:

                idx = mi

            else:

                lo = mi

        return pos, idx

    def add(self, value):

        """Add `value` to sorted list."""

        _load = self._load

        _lists = self._lists

        _mins = self._mins

        _list_lens = self._list_lens

        self._len += 1

        if _lists:

            pos, idx = self._loc_right(value)

            self._fen_update(pos, 1)

            _list = _lists[pos]

            _list.insert(idx, value)

            _list_lens[pos] += 1

            _mins[pos] = _list[0]

            if _load + _load < len(_list):

                _lists.insert(pos + 1, _list[_load:])

                _list_lens.insert(pos + 1, len(_list) - _load)

                _mins.insert(pos + 1, _list[_load])

                _list_lens[pos] = _load

                del _list[_load:]

                self._rebuild = True

        else:

            _lists.append([value])

            _mins.append(value)

            _list_lens.append(1)

            self._rebuild = True

    def discard(self, value):

        """Remove `value` from sorted list if it is a member."""

        _lists = self._lists

        if _lists:

            pos, idx = self._loc_right(value)

            if idx and _lists[pos][idx - 1] == value:

                self._delete(pos, idx - 1)

    def remove(self, value):

        """Remove `value` from sorted list; `value` must be a member."""

        _len = self._len

        self.discard(value)

        if _len == self._len:

            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):

        """Remove and return value at `index` in sorted list."""

        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)

        value = self._lists[pos][idx]

        self._delete(pos, idx)

        return value

    def bisect_left(self, value):

        """Return the first index to insert `value` in the sorted list."""

        pos, idx = self._loc_left(value)

        return self._fen_query(pos) + idx

    def bisect_right(self, value):

        """Return the last index to insert `value` in the sorted list."""

        pos, idx = self._loc_right(value)

        return self._fen_query(pos) + idx

    def count(self, value):

        """Return number of occurrences of `value` in the sorted list."""

        return self.bisect_right(value) - self.bisect_left(value)

    def __len__(self):

        """Return the size of the sorted list."""

        return self._len

    def __getitem__(self, index):

        """Lookup value at `index` in sorted list."""

        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)

        return self._lists[pos][idx]

    def __delitem__(self, index):

        """Remove value at `index` from sorted list."""

        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)

        self._delete(pos, idx)

    def __contains__(self, value):

        """Return true if `value` is an element of the sorted list."""

        _lists = self._lists

        if _lists:

            pos, idx = self._loc_left(value)

            return idx < len(_lists[pos]) and _lists[pos][idx] == value

        return False

    def __iter__(self):

        """Return an iterator over the sorted list."""

        return (value for _list in self._lists for value in _list)

    def __reversed__(self):

        """Return a reverse iterator over the sorted list."""

        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):

        """Return string representation of sorted list."""

        return 'SortedList({0})'.format(list(self))

class FastIO(IOBase):

    newlines = 0

    def __init__(self, file):

        self._fd = file.fileno()

        self.buffer = BytesIO()

        self.writable = "x" in file.mode or "r" not in file.mode

        self.write = self.buffer.write if self.writable else None

    def read(self):

        while True:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            if not b:

                break

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines = 0

        return self.buffer.read()

    def readline(self):

        while self.newlines == 0:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            self.newlines = b.count(b"\n") + (not b)

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines -= 1

        return self.buffer.readline()

    def flush(self):

        if self.writable:

            os.write(self._fd, self.buffer.getvalue())

            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):

    def __init__(self, file):

        self.buffer = FastIO(file)

        self.flush = self.buffer.flush

        self.writable = self.buffer.writable

        self.write = lambda s: self.buffer.write(s.encode("ascii"))

        self.read = lambda: self.buffer.read().decode("ascii")

        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin = IOWrapper(sys.stdin)

# sys.stdout = IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

def I():

    return input()

def II():

    return int(input())

def MI():

    return map(int, input().split())

def LI():

    return list(input().split())

def LII():

    return list(map(int, input().split()))

def GMI():

    return map(lambda x: int(x) - 1, input().split())

def LGMI():

    return list(map(lambda x: int(x) - 1, input().split()))

def getGraph(n, m, directed=False):

    d = [[] for _ in range(n)]

    for _ in range(m):

        u, v = LGMI()

        d[u].append(v)

        if not directed:

            d[v].append(u)

    return d

def getWeightedGraph(n, m, directed=False):

    d = [[] for _ in range(n)]

    for _ in range(m):

        u, v, w = LII()

        u -= 1; v -= 1

        d[u].append((v, w))

        if not directed:

            d[v].append((u, w))

    return d

if __name__ == "__main__":

    main()


B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.

from itertools import groupby

n = int(input())
a = list(map(int, input().split()))
groups = [(k, sum(1 for _ in v)) for k, v in groupby(a)]
midnight = groups[0][1] + groups[-1][1] if groups[0][0] == groups[-1][0] == 1 else 0
print(max(midnight, max([n for k, n in groups if k == 1], default=0)))


B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:  The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened;  The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.

def solve():

    n = int(input())

    aseq = read_ints()

    last = aseq[0]

    last_idx = 0

    for i in range(n):

        if aseq[i] >= i:

            last = aseq[i]

            last_idx = i

        else:

            break

    # print(last, last_idx)

    # print(aseq)

    for i in range(last_idx+1, n):

        # print(aseq[i], last-1)

        if aseq[i] >= aseq[i-1]:

            if aseq[i-1] - 1 < 0:

                return False

            aseq[i] = aseq[i-1] - 1

    return True

def main():

    t = int(input())

    output = []

    for _ in range(t):

        ans = solve()

        output.append('Yes' if ans else 'No')

    print_lines(output)

def read_ints(): return [int(c) for c in input().split()]

def print_lines(lst): print('\n'.join(map(str, lst)))

if __name__ == "__main__":

    from os import environ as env

    if 'COMPUTERNAME' in env and 'L2A6HRI' in env['COMPUTERNAME']:

        import sys

        sys.stdout = open('out.txt', 'w')

        sys.stdin = open('in.txt', 'r')

    main()


C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.

t=list(map(int,input().split(" ")))

p=int(t[2])

a=list(map(int,input().split(" ")))

b=list(map(int,input().split(" ")))

ans=0

t=0

for i in a:

    if i%p!=0:

        ans+=t

        break

    t+=1

t=0

for i in b:

    if i%p!=0:

        ans+=t

        break

    t+=1

print("%d"%(ans))


F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.

import os, sys

from io import BytesIO, IOBase

from collections import *

class FastIO(IOBase):

    newlines = 0

    def __init__(self, file):

        self._fd = file.fileno()

        self.buffer = BytesIO()

        self.writable = "x" in file.mode or "r" not in file.mode

        self.write = self.buffer.write if self.writable else None

    def read(self):

        while True:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192))

            if not b:

                break

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines = 0

        return self.buffer.read()

    def readline(self):

        while self.newlines == 0:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192))

            self.newlines = b.count(b"\n") + (not b)

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines -= 1

        return self.buffer.readline()

    def flush(self):

        if self.writable:

            os.write(self._fd, self.buffer.getvalue())

            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):

    def __init__(self, file):

        self.buffer = FastIO(file)

        self.flush = self.buffer.flush

        self.writable = self.buffer.writable

        self.write = lambda s: self.buffer.write(s.encode("ascii"))

        self.read = lambda: self.buffer.read().decode("ascii")

        self.readline = lambda: self.buffer.readline().decode("ascii")

class graph:

    def __init__(self, n):

        self.n, self.gdict = n, [[] for _ in range(n + 1)]

    def addEdge(self, node1, node2):

        self.gdict[node1].append(node2)

        self.gdict[node2].append(node1)

    def subtree(self, v):

        queue, visit, child = deque([v]), [False] * (n + 1), []

        visit[v], ma, parent, maxes = True, [0] * (n + 1), [-1] * (n + 1), [[-10 ** 9, 0] for _ in range(n + 1)]

        while queue:

            s = queue.popleft()

            for i1 in self.gdict[s]:

                if not visit[i1]:

                    queue.append(i1)

                    visit[i1] = True

                    child.append(i1)

                    parent[i1] = s

        for i in child[::-1]:

            ma[parent[i]] = max(ma[i] + 1, ma[parent[i]])

            maxes[parent[i]].append(ma[i] + 1)

        for i in range(1, n + 1):

            maxes[i] = sorted(maxes[i])[-3:]

        for i in child:

            new = -1

            if maxes[parent[i]][-1] == ma[i] + 1:

                new = -2

            maxes[i].append(maxes[parent[i]][new] + 1)

            maxes[i] = sorted(maxes[i])[-3:]

            ma[i] = max(ma[i], maxes[parent[i]][new] + 1)

        ix, ans, su = max(range(n + 1), key=[sum(x) for x in maxes].__getitem__), [], 0

        visit[ix], mem = False, [() for _ in range(n + 1)]

        for i in self.gdict[ix]:

            queue.append((i, 1))

            visit[i], parent[i] = False, i

        while queue:

            s, lev = queue.popleft()

            flag = 1

            for i1 in self.gdict[s]:

                if visit[i1]:

                    queue.append((i1, lev + 1))

                    visit[i1], flag, parent[i1] = False, 0, parent[s]

            if flag:

                mem[parent[s]] = (lev, s)

        mem.sort()

        for i in range(n, n - 3, -1):

            if not mem[i]:

                break

            ans.append(mem[i][1])

            su += mem[i][0]

        if len(ans) < 3:

            ans.append(ix)

        print(su, '\n', *ans)

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

inp = lambda dtype: [dtype(x) for x in input().split()]

inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]

inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]

inp_enu = lambda dtype: [(i, x) for i, x in enumerate(inp(dtype))]

inp_enus = lambda dtype, n: [[i] + inp(dtype) for i in range(n)]

ceil1 = lambda a, b: (a + b - 1) // b

n = int(input())

g = graph(n)

for _ in range(n - 1):

    u, v = inp(int)

    g.addEdge(u, v)

g.subtree(1)


import sys

from array import array

input = lambda: sys.stdin.buffer.readline().decode().strip()

inp = lambda dtype: [dtype(x) for x in input().split()]

debug = lambda *x: print(*x, file=sys.stderr)

ceil1 = lambda a, b: (a + b - 1) // b

Mint, Mlong, out = 2 ** 31 - 1, 2 ** 63 - 1, []

def shrink(l, r):

    stk = array('i')

    for i in range(l, r + 1):

        cur = a[i]

        while stk and stk[-1] == cur:

            stk.pop()

            cur += 1

        stk.append(cur)

    return len(stk) == 1

for _ in range(1):

    n, a = int(input()), array('i', inp(int))

    dp = array('i', [Mint] * (n + 1))

    dp[-1] = 0

    for i in range(n):

        for j in range(i, -1, -1):

            if shrink(j, i): dp[i] = min(dp[i], dp[j - 1] + 1)

    out.append(dp[n - 1])

print('\n'.join(map(str, out)))


A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.

import sys

from collections import *

from itertools import *

from math import *

from array import *

from functools import lru_cache

import heapq

import bisect

import random

import io, os

from bisect import *

if sys.hexversion == 50924784:

    sys.stdin = open('cfinput.txt')

RI = lambda: map(int, sys.stdin.buffer.readline().split())

RS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())

RILST = lambda: list(RI())

MOD = 10 ** 9 + 7

"""https://codeforces.com/problemset/problem/1286/A

输入 n(≤100) 和一个长为 n 的数组 p，p 原本是一个 1~n 的排列，但是有些数字丢失了，丢失的数字用 0 表示。

你需要还原 p，使得 p 中相邻元素奇偶性不同的对数最少。输出这个最小值。

输入

5

0 5 0 2 3

输出 2

输入

7

1 0 0 5 0 0 2

输出 1

"""

# 264  	 ms

def solve1(n, a):

    if n == 1:

        return print(0)

    even = n // 2  # 偶数

    ood = n - even  # 奇数

    for v in a:

        if not v:

            continue

        if v & 1:

            ood -= 1

        else:

            even -= 1

    # f[i][j][k][0] 前i个数，填了j个奇数，l个偶数时，且末位是偶数的情况

    # f[i][j][k][1] 前i个数，填了j个奇数，l个偶数时，且末位是奇数的情况

    f = [[[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)] for _ in range(n)]

    # f[0][0][0] = 0

    if a[0] == 0:

        f[0][1][0][1] = 0  # a[0]放奇数

        f[0][0][1][0] = 0  # a[0]放偶数

    else:

        if a[0] & 1:  # 奇数

            f[0][0][0][1] = 0

        else:

            f[0][0][0][0] = 0

    # print(ood,even)

    for i in range(1, n):

        if a[i] == 0:

            for j in range(ood + 1):

                for k in range(even + 1):

                    if k:

                        # a[i]放偶数，前一个是奇数就+1否则不+

                        f[i][j][k][0] = min(f[i][j][k][0], f[i - 1][j][k - 1][0])

                        f[i][j][k][0] = min(f[i][j][k][0], f[i - 1][j][k - 1][1] + 1)

                    if j:

                        # a[i]放奇数

                        f[i][j][k][1] = min(f[i][j][k][1], f[i - 1][j - 1][k][0] + 1)

                        f[i][j][k][1] = min(f[i][j][k][1], f[i - 1][j - 1][k][1])

        else:

            if a[i] & 1:

                for j in range(ood + 1):

                    for k in range(even + 1):

                        f[i][j][k][1] = min(f[i - 1][j][k][1], f[i - 1][j][k][0] + 1)

            else:

                for j in range(ood + 1):

                    for k in range(even + 1):

                        f[i][j][k][0] = min(f[i - 1][j][k][1] + 1, f[i - 1][j][k][0])

    # print(f)

    print(min(f[-1][-1][-1]))

# 155 ms

def solve2(n, a):

    if n == 1:

        return print(0)

    even = n // 2  # 偶数

    ood = n - even  # 奇数

    for v in a:

        if not v:

            continue

        if v & 1:

            ood -= 1

        else:

            even -= 1

    f = [[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)]

    # f[0][0][0] = 0

    if a[0] == 0:

        f[1][0][1] = 0  # a[0]放奇数

        f[0][1][0] = 0  # a[0]放偶数

    else:

        if a[0] & 1:  # 奇数

            f[0][0][1] = 0

        else:

            f[0][0][0] = 0

    # print(ood,even)

    for i in range(1, n):

        g = f

        f = [[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)]

        if a[i] == 0:

            for j in range(ood + 1):

                for k in range(even + 1):

                    if k:

                        # a[i]放偶数，前一个是奇数就+1否则不+

                        f[j][k][0] = min(f[j][k][0], g[j][k - 1][0])

                        f[j][k][0] = min(f[j][k][0], g[j][k - 1][1] + 1)

                    if j:

                        # a[i]放奇数

                        f[j][k][1] = min(f[j][k][1], g[j - 1][k][0] + 1)

                        f[j][k][1] = min(f[j][k][1], g[j - 1][k][1])

        else:

            if a[i] & 1:

                for j in range(ood + 1):

                    for k in range(even + 1):

                        f[j][k][1] = min(g[j][k][1], g[j][k][0] + 1)

            else:

                for j in range(ood + 1):

                    for k in range(even + 1):

                        f[j][k][0] = min(g[j][k][1] + 1, g[j][k][0])

    # print(f)

    print(min(f[-1][-1]))

# 93 ms

def solve3(n, a):

    if n == 1:

        return print(0)

    even = n // 2  # 偶数

    ood = n - even  # 奇数

    for v in a:

        if not v:

            continue

        if v & 1:

            ood -= 1

        else:

            even -= 1

    # f[i][j][0] 前i个数，填了j个偶数且末尾是偶数的情况

    f = [[inf] * 2 for _ in range(even + 1)]

    if a[0] == 0:

        f[0][1] = 0  # a[0]放奇数

        f[1][0] = 0  # a[0]放偶数

    else:

        if a[0] & 1:  # 奇数

            f[0][1] = 0

        else:

            f[0][0] = 0

    # print(ood,even)

    pos = 0 + (a[0] == 0)

    for i in range(1, n):

        g = f

        f = [[inf] * 2 for _ in range(even + 1)]

        if a[i] == 0:

            pos += 1

            for j in range(min(pos + 1, even + 1)):

                if j:

                    f[j][0] = min(g[j - 1][0], g[j - 1][1] + 1)

                f[j][1] = min(g[j][1], g[j][0] + 1)

        else:

            p = a[i] & 1

            for j in range(min(pos + 1, even + 1)):

                f[j][p] = min(g[j][p], g[j][p ^ 1] + 1)

            # if a[i] & 1:

            #     for j in range(min(pos + 1, ood + 1)):

            #         f[j][1] = min(g[j][1], g[j][0] + 1)

            # else:

            #     for j in range(min(pos + 1, ood + 1)):

            #         f[j][0] = min(g[j][1] + 1, g[j][0])

    # print(f)

    print(min(f[-1]))

# 93 ms

def solve(n, a):

    if n == 1:

        return print(0)

    even = n // 2  # 偶数

    for v in a:

        if not v:

            continue

        if v & 1 == 0:

            even -= 1

    f = [[inf] * 2 for _ in range(even + 1)]

    if a[0] == 0:

        f[0][1] = 0  # a[0]放奇数

        f[1][0] = 0  # a[0]放偶数

    else:

        f[0][a[0] & 1] = 0

    # print(ood,even)

    for i in range(1, n):

        g = f

        f = [[inf] * 2 for _ in range(even + 1)]

        if a[i] == 0:

            for j in range(even + 1):

                if j:

                    f[j][0] = min(g[j - 1][0], g[j - 1][1] + 1)

                f[j][1] = min(g[j][1], g[j][0] + 1)

        else:

            p = a[i] & 1

            for j in range(even + 1):

                f[j][p] = min(g[j][p], g[j][p ^ 1] + 1)

    print(min(f[-1]))

if __name__ == '__main__':

    n, = RI()

    a = RILST()

    solve(n, a)


import sys

from collections import *

from itertools import *

from math import *

from array import *

from functools import lru_cache

import heapq

import bisect

import random

import io, os

from bisect import *

if sys.hexversion == 50924784:

    sys.stdin = open('cfinput.txt')

RI = lambda: map(int, sys.stdin.buffer.readline().split())

RS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())

RILST = lambda: list(RI())

MOD = 10 ** 9 + 7

"""https://codeforces.com/problemset/problem/1286/A

输入 n(≤100) 和一个长为 n 的数组 p，p 原本是一个 1~n 的排列，但是有些数字丢失了，丢失的数字用 0 表示。

你需要还原 p，使得 p 中相邻元素奇偶性不同的对数最少。输出这个最小值。

输入

5

0 5 0 2 3

输出 2

输入

7

1 0 0 5 0 0 2

输出 1

"""

# 264  	 ms

def solve1(n, a):

    if n == 1:

        return print(0)

    even = n // 2  # 偶数

    ood = n - even  # 奇数

    for v in a:

        if not v:

            continue

        if v & 1:

            ood -= 1

        else:

            even -= 1

    f = [[[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)] for _ in range(n)]

    # f[0][0][0] = 0

    if a[0] == 0:

        f[0][1][0][1] = 0  # a[0]放奇数

        f[0][0][1][0] = 0  # a[0]放偶数

    else:

        if a[0] & 1:  # 奇数

            f[0][0][0][1] = 0

        else:

            f[0][0][0][0] = 0

    # print(ood,even)

    for i in range(1, n):

        if a[i] == 0:

            for j in range(ood + 1):

                for k in range(even + 1):

                    if k:

                        # a[i]放偶数，前一个是奇数就+1否则不+

                        f[i][j][k][0] = min(f[i][j][k][0], f[i - 1][j][k - 1][0])

                        f[i][j][k][0] = min(f[i][j][k][0], f[i - 1][j][k - 1][1] + 1)

                    if j:

                        # a[i]放奇数

                        f[i][j][k][1] = min(f[i][j][k][1], f[i - 1][j - 1][k][0] + 1)

                        f[i][j][k][1] = min(f[i][j][k][1], f[i - 1][j - 1][k][1])

        else:

            if a[i] & 1:

                for j in range(ood + 1):

                    for k in range(even + 1):

                        f[i][j][k][1] = min(f[i - 1][j][k][1], f[i - 1][j][k][0] + 1)

            else:

                for j in range(ood + 1):

                    for k in range(even + 1):

                        f[i][j][k][0] = min(f[i - 1][j][k][1] + 1, f[i - 1][j][k][0])

    # print(f)

    print(min(f[-1][-1][-1]))

# ms

def solve(n, a):

    if n == 1:

        return print(0)

    even = n // 2  # 偶数

    ood = n - even  # 奇数

    for v in a:

        if not v:

            continue

        if v & 1:

            ood -= 1

        else:

            even -= 1

    f = [[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)]

    # f[0][0][0] = 0

    if a[0] == 0:

        f[1][0][1] = 0  # a[0]放奇数

        f[0][1][0] = 0  # a[0]放偶数

    else:

        if a[0] & 1:  # 奇数

            f[0][0][1] = 0

        else:

            f[0][0][0] = 0

    # print(ood,even)

    for i in range(1, n):

        g = f

        f = [[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)]

        if a[i] == 0:

            for j in range(ood + 1):

                for k in range(even + 1):

                    if k:

                        # a[i]放偶数，前一个是奇数就+1否则不+

                        f[j][k][0] = min(f[j][k][0], g[j][k - 1][0])

                        f[j][k][0] = min(f[j][k][0], g[j][k - 1][1] + 1)

                    if j:

                        # a[i]放奇数

                        f[j][k][1] = min(f[j][k][1], g[j - 1][k][0] + 1)

                        f[j][k][1] = min(f[j][k][1], g[j - 1][k][1])

        else:

            if a[i] & 1:

                for j in range(ood + 1):

                    for k in range(even + 1):

                        f[j][k][1] = min(g[j][k][1], g[j][k][0] + 1)

            else:

                for j in range(ood + 1):

                    for k in range(even + 1):

                        f[j][k][0] = min(g[j][k][1] + 1, g[j][k][0])

    # print(f)

    print(min(f[-1][-1]))

if __name__ == '__main__':

    n, = RI()

    a = RILST()

    solve(n, a)


A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00:  You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2);  then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.

t = int(input())
while t:
    n = int(input())
    a = [int(x) for x in input().split()]
    a = sorted(a)
    a = [a[i] - a[i-1] for i in range(1,len(a))]
    res = any((aa %2) != 0 for aa in a)
    print("NO" if res else "YES")
    t -= 1


B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string:   Pick an integer kk, (1≤k≤n1≤k≤n).  For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through:   qwer (original string)  wqer (after reversing the first substring of length 22)  weqr (after reversing the second substring of length 22)  werq (after reversing the last substring of length 22)  Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds:   aa is a prefix of bb, but a≠ba≠b;  in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows :   for k=1k=1 : abab  for k=2k=2 : baba  for k=3k=3 : abab  for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.

def solve():

    n = int(input())

    seq = input()

    min_indices = []

    cmin = min(seq)

    for i, e in enumerate(seq):

        if e == cmin:

            min_indices.append(i)

    res = (seq, 1)

    for idx in min_indices:

        head = seq[idx:]

        tail = seq[:idx]

        if (n - idx) % 2 == 1:

            tail = tail[::-1]

        proc_seq = ''.join(head + tail)

        res = min(res, (proc_seq, idx+1))

    return res

def main():

    t = int(input())

    output = []

    for _ in range(t):

        seq, k = solve()

        output.append(seq)

        output.append(k)

    print_lines(output)

def input(): return next(test).strip()

def read_ints(): return [int(c) for c in input().split()]

def print_lines(lst): print('\n'.join(map(str, lst)))

if __name__ == "__main__":

    import sys

    from os import environ as env

    if 'COMPUTERNAME' in env and 'L2A6HRI' in env['COMPUTERNAME']:

        sys.stdout = open('out.txt', 'w')

        sys.stdin = open('in.txt', 'r')

    test = iter(sys.stdin.readlines())

    main()


F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0

def main():

    import sys

    input = sys.stdin.readline

    class Bit:

        def __init__(self, n):

            self.size = n

            self.tree = [0] * (n + 1)

        def sum(self, i):

            s = 0

            while i > 0:

                s += self.tree[i]

                i -= i & -i

            return s

        def add(self, i, x):

            while i <= self.size:

                self.tree[i] += x

                i += i & -i

    N = int(input())

    X = list(map(int, input().split()))

    V = list(map(int, input().split()))

    info = [(x, v) for x, v in zip(X, V)]

    info.sort(key=lambda p: p[0])

    info.sort(key=lambda p: p[1])

    X.sort()

    x2i = {x: i+1 for i, x in enumerate(X)}

    bit_x = Bit(N+1)

    bit_cnt = Bit(N+1)

    ans = 0

    for x, _ in info:

        i = x2i[x]

        ans += bit_cnt.sum(i) * x - bit_x.sum(i)

        bit_x.add(i, x)

        bit_cnt.add(i, 1)

    print(ans)

if __name__ == '__main__':

    main()


B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows:  The coordinates of the 00-th node is (x0,y0)(x0,y0)  For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions:  From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second.  If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows:   Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds.  Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds.  Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows:   Collect the 33-rd node. This requires no seconds.  Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.

import sys

input=lambda:sys.stdin.readline().rstrip()

def dist(a,b):

    return sum([abs(a[i]-b[i]) for i in range(2)])

temp=list(map(int,input().split()))

points=[temp[0:2]]

a=temp[2:4]

b=temp[4:6]

start=[0,0]

*start,t=map(int,input().split())

while points[-1][0]-start[0]<=t:

	points.append([points[-1][i]*a[i]+b[i] for i in range(2)])

for i in range(len(points)-1,-1,-1):

	for j in range(len(points)-i):

		if dist(points[j],points[j+i])+min(dist(start,points[j]),dist(start,points[j+i]))<=t:

			print(i+1)

			sys.exit()

print(0)


C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can:   either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki;  or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.

T = int (input())

for test in range (T):

    n , k =  map (int, input ().split(' '))

    arr = list (map (int, input ().split(' ')))

    mx = max(arr)

    values = list ()

    ind =1

    arr.sort()

    arr.reverse()

    while len (arr) > 0 and arr[-1] == 0:

        arr.pop()

    values.append(1)

    while ind <= mx:

        ind *= k

        values.append(ind)

    values.sort()

    ok = True

    while len (arr)>0:

        x = arr.pop()

        if (x == 0 ) :

            break

        while x > 0:

            mx = 0

            for it in values:

                if it <= x:

                    mx = it

            if mx == 0:

                break

            x -= mx

            values.remove(mx)

        ok&= x ==0

    print ("YES")  if ok else print ("NO")


A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).

for _ in range(int(input())):

    n= int(input())

    s= input()

    odd= 0

    for i in range(n):

        if int(s[i])%2 != 0:

            odd += 1

    if odd >= 2:

        even= str()

        for k in range(n):

            if int(s[k])%2 != 0:

                even += s[k]

            if len(even) == 2:

                print(even)

                break

        else:

            print(-1)

    else:

        print(-1)


A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets:  the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different),  the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows:  Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution:   Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.

import sys, os, io

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

t = int(input())

ans = []

for _ in range(t):

    n = int(input())

    a = list(map(int, input().split()))

    b = list(map(int, input().split()))

    a.sort()

    b.sort()

    ans.append(" ".join(map(str, a)))

    ans.append(" ".join(map(str, b)))

sys.stdout.write("\n".join(ans))


def get_ints():

    return map(int, input().strip().split())

def get_list():

    return list(map(int, input().strip().split()))

def get_string():

    return input().strip()

# For fast IO use sys.stdout.write(str(x) + "\n") instead of print

import sys

import math

input = sys.stdin.readline

for t in range(int(input().strip())):

    n = int(input().strip())

    arr = get_list()

    prefix_len, suffix_len = 0, 0

    for i in range(n):

        if arr[i] >= i:

            prefix_len += 1

        else:

            break

    for i in range(n-1, -1, -1):

        if arr[i] >= n-i-1:

            suffix_len += 1

        else:

            break

    if prefix_len + suffix_len > n:

        print("Yes")

    else:

        print("No")


D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.

import io,os
import math
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

MAX = 100001
prime = [0]*(MAX+1)

for i in range(2,MAX+1):
    if prime[i]>1: continue
    for j in range(i,MAX+1,i):
        prime[j] += 1

primelist = []
for i in range(2,MAX+1):
    if prime[i]==1:  primelist.append(i)

def factorize(num):

    pf = []
    for p in primelist:
        if num%p>0: continue
        count = 0
        while num%p==0:
            num = num//p
            count += 1
        pf.append(p)

    if num>1:  pf.append(num)
    return pf

def main(t):

    a,m = map(int,input().split())

    g = math.gcd(a,m)
    a = a//g
    m = m//g

    pf = factorize(m)
#    print(pf)

    tot = 1

    ans = m

    for b in range(1,1<<len(pf)):
#        print(b,"*")
        num = 1
        sym = 1

        for i in range(len(pf)-1,-1,-1):
            num *= pow(pf[i], b%2 )
            if b % 2==1:  sym *= (-1)
            b = b//2

        count = (a+m-1)//num - (a-1)//num
#        print(sym,count,num)
        ans += sym * count

    print(ans)

T = int(input())
t = 1
while t<=T:
    main(t)
    t += 1


D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10

from collections import defaultdict

n = int(input())

left = input()

right = input()

left_inds = defaultdict(list)

right_inds = defaultdict(list)

for idx, char in enumerate(left):

    left_inds[char].append(idx+1)

for idx, char in enumerate(right):

    right_inds[char].append(idx+1)

# print(right_inds)

# print(left_inds)

ans = []

if "?" in left_inds:

    for char in right_inds:

        if char == "?": continue

        while len(right_inds[char]) > len(left_inds[char]) and left_inds["?"]:

            idx1 = left_inds["?"].pop()

            idx2 = right_inds[char].pop()

            ans.append((idx1, idx2))

if "?" in right_inds:

    for char in left_inds:

        while len(left_inds[char]) > len(right_inds[char]) and right_inds["?"]:

            idx1 = right_inds["?"].pop()

            idx2 = left_inds[char].pop()

            ans.append((idx2, idx1))

for char in right_inds:

    res = min(len(right_inds[char]), len(left_inds[char]))

    for _ in range(res):

        idx1 = left_inds[char].pop()

        idx2 = right_inds[char].pop()

        ans.append((idx1, idx2))

print(len(ans))

for a, b in ans:

    print(a, b)


D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.

def find_min(num_list, pos):

    if pos < 0:

        return 0

    zeros = []

    ones = []

    for num in num_list:

        if num >> pos & 1 == 0:

            zeros.append(num)

        else:

            ones.append(num)

    if len(zeros) == 0:

        return find_min(ones, pos-1)

    if len(ones) == 0:

        return find_min(zeros, pos-1)

    return min(find_min(zeros, pos - 1), find_min(ones, pos - 1)) + (1 << pos)

n = int(input())

numbers = list(map(int, input().split()))

pos = 30

print(find_min(numbers, pos))


B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.

import sys

n = int(input())

m = 1<<20

zc = 0

fc = [0] * m

lc = [0] * m

for inp in sys.stdin:

  a = [*map(int,inp.split()[1:])]

  z = all(a[i] >= a[i+1] for i in range(len(a)-1))

  zc += z

  if z:

    fc[a[0]] += 1

    lc[a[-1]] += 1

ans = n*n - zc*zc

less = 0

for i in range(m):

  ans += fc[i] * less

  less += lc[i]

print(ans)


n = int(input())

ans = 0

mx = [0] * (10 ** 6 + 5)

mn = []

koltrue = 0

for _ in range(n):

    l = list(map(int, input().split()))

    mnn = l[1]

    mxx = l[1]

    t = False

    for i in range(2, l[0] + 1):

        if l[i-1] < l[i]:

            t = True

        mnn = min(mnn, l[i])

        mxx = max(mxx, l[i])

    if t:

        koltrue += 1

        mn.append('t')

    else:

        mn.append(mnn)

        mx[mxx] += 1

#print(koltrue)

sufs = [0] * (10 ** 6 + 5)

for i in range(len(sufs) - 2, -1, -1):

    sufs[i] = mx[i] + sufs[i+1]

#print(sufs[:10])

#print(mn)

for i in range(len(mn)):

    if mn[i] == 't':

        ans += n

    else:

        ans += koltrue

        #print('#', mn[i], i)

        ans += sufs[mn[i] + 1]

        #print(ans)

print(ans)


F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.

# NOT MY CODE

# https://codeforces.com/contest/1324/submission/73179914

## PYRIVAL BOOTSTRAP

# https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py

# This decorator allows for recursion without actually doing recursion

from types import GeneratorType

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):

        if stack:

            return f(*args, **kwargs)

        else:

            to = f(*args, **kwargs)

            while True:

                if type(to) is GeneratorType:

                    stack.append(to)

                    to = next(to)

                else:

                    stack.pop()

                    if not stack:

                        break

                    to = stack[-1].send(to)

            return to

    return wrappedfunc

######################

import math

from bisect import bisect_left, bisect_right

from sys import stdin, stdout, setrecursionlimit

from collections import Counter

input = lambda: stdin.readline().strip()

print = stdout.write

#setrecursionlimit(10**6)

n = int(input())

ls = list(map(int, input().split()))

children = {}

for i in range(1, n+1):

    children[i] = []

for i in range(n-1):

    a, b = map(int, input().split())

    children[a].append(b)

    children[b].append(a)

parent = [-1]

ans = [-1]

for i in range(1, n+1):

    parent.append(-1)

    ans.append(-1)

visited = [False]

for i in range(1, n+1):

    visited.append(False)

@bootstrap

def dfs(node):

    visited[node] = True

    ans[node] = 1 if ls[node-1] else -1

    for i in children[node]:

        if not visited[i]:

            parent[i] = node

            tmp = (yield dfs(i))

            if tmp>0:

                ans[node]+=tmp

    ans[node] = max(ans[node], 1 if ls[node-1] else -1)

    yield ans[node]

dfs(1)

visited = [False]

for i in range(1, n+1):

    visited.append(False)

@bootstrap

def dfs(node):

    visited[node] = True

    if node!=1:

        ans[node] = max(ans[node], ans[parent[node]] if ans[node]>=0 else ans[parent[node]]-1)

    for i in children[node]:

        if not visited[i]:

            yield dfs(i)

    yield

dfs(1)

for i in range(1, n+1):

    print(str(ans[i])+' ')

print('\n')


B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].

t = int(input())

for _ in range(t):

    n = int(input())

    l = list(map(int,input().split()))

    s = set(l)

    print(len(s))


A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb.  For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.


C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.

from collections import defaultdict

import sys, os, io

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def segment_tree(n):

    i = 2

    while True:

        if i >= n * 2:

            tree = [-inf] * i

            break

        else:

            i *= 2

    return tree

def update(i, x):

    i += len(tree) // 2

    tree[i] = x

    i //= 2

    while True:

        if i == 0:

            break

        tree[i] = max(tree[2 * i], tree[2 * i + 1])

        i //= 2

    return

def get_max(s, t):

    s += len(tree) // 2

    t += len(tree) // 2

    ans = -inf

    while s <= t:

        if s % 2 == 0:

            s //= 2

        else:

            ans = max(ans, tree[s])

            s = (s + 1) // 2

        if t % 2 == 1:

            t //= 2

        else:

            ans = max(ans, tree[t])

            t = (t - 1) // 2

    return ans

n = int(input())

m = list(map(int, input().split()))

d = defaultdict(lambda : [])

for i in range(n):

    d[m[i]].append(i)

x = list(d.keys())

x.sort()

inf = 1

tree = segment_tree(n)

dp1 = [0] * (n + 1)

for i in x:

    for j in d[i]:

        k = get_max(0, j)

        dp1[j] = dp1[k] + i * (j - k)

        update(j, j)

inf = n

tree = segment_tree(n)

dp2 = [0] * (n + 1)

for i in x:

    for j in reversed(d[i]):

        k = -get_max(j, n - 1)

        dp2[j] = dp2[k] + i * (k - j)

        update(j, -j)

s = 0

k = -1

c = 0

dp1.pop()

dp2.pop()

for i, j, l in zip(dp1, dp2, m):

    if s < i + j - l:

        s = i + j - l

        k = c

    c += 1

a = [0] * n

a[k] = m[k]

for j in range(k - 1, -1, -1):

    a[j] = min(a[j + 1], m[j])

    s += a[j]

for j in range(k + 1, n):

    a[j] = min(a[j - 1], m[j])

    s += a[j]

sys.stdout.write(" ".join(map(str, a)))