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 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) and dp[j - 1] + 1 < dp[i]: dp[i] = dp[j - 1] + 1

    out.append(dp[n - 1])

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


B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5

def get(f): return f(input().strip())
def gets(f): return [*map(f, input().split())]

for _ in range(get(int)):
    n = get(int)
    print(*reversed(sorted(gets(int))))


F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either:  find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:

import math
import sys
input = sys.stdin.readline
from collections import *
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]

def dfs():
    global req
    dep = [0]* (n + 1)
    par = [0] * (n + 1)
    st = [5]
    while st:
        u = st.pop()
        if dep[u]:
            continue

        dep[u] = dep[par[u]] + 1
        for v in g2[u]:
            if not dep[v]:
                par[v] = u
                st.append(v)
            elif dep[u] - dep[v] + 1>= req:
                cyc = []
                while u != par[v]:
                    cyc.append(u)
                    u = par[u]
                return (None, cyc)

g = defaultdict(set)
g2 = defaultdict(set)
n,m = li()

for i in range(m):
    a,b = li()
    g[a].add(b)
    g[b].add(a)
    g2[a].add(b)
    g2[b].add(a)
for i in g2:
    g2[i] = set(sorted(list(g2[i])))
currset = set()
ma = math.ceil(n**0.5)
req = ma
for i in sorted(g,key = lambda x:len(g[x])):
    if i in g:

        currset.add(i)
        for k in list(g[i]):
            if k in g:g.pop(k)
        g.pop(i)
    if len(currset) == ma:break
if len(currset) >= ma:
    print(1)
    print(*list(currset)[:ma])
    exit()
print(2)
_,cycles = dfs()
print(len(cycles))
print(*cycles)


C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that:  the length of both arrays is equal to mm;  each element of each array is an integer between 11 and nn (inclusive);  ai≤biai≤bi for any index ii from 11 to mm;  array aa is sorted in non-descending order;  array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays:   a=[1,1],b=[2,2]a=[1,1],b=[2,2];  a=[1,2],b=[2,2]a=[1,2],b=[2,2];  a=[2,2],b=[2,2]a=[2,2],b=[2,2];  a=[1,1],b=[2,1]a=[1,1],b=[2,1];  a=[1,1],b=[1,1]a=[1,1],b=[1,1].

import sys

import math

import copy

import itertools

import bisect

from heapq import heappop, heappush, heapify

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

def ilst():

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

def islst():

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

def inum():

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

def freq(l):

    d = {}

    for i in l:

        d[i] = d.get(i,0)+1

    return d

n,m = inum()

print((math.factorial(n+2*m-1)//(math.factorial(2*m)*math.factorial(n-1)))%(10**9+7))


D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns.   You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster.  Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6

from math import ceil

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

m = a + b

h = list(map(lambda x: int(x) % m + (m if int(x) % m == 0 else 0), input().split()))

h.sort()

cnt = 0

while cnt < n and h[cnt] <= a:cnt += 1

del h[:cnt]

s = 0

for hp in h:

    cnt += 1

    s += ceil(hp / a) - 1

    if k < s:

        cnt -= 1

        break

print(cnt)


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

    input()

    print(*sorted([int(i)for i in input().split()])[::-1])


A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length).  Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note  The first test case of the example It can be shown that the answer for the second test case of the example is "NO".

# Problem: A. Two Regular Polygons

# Contest: Codeforces - Educational Codeforces Round 83 (Rated for Div. 2)

# URL: https://codeforces.com/problemset/problem/1312/A

# Memory Limit: 256 MB

# Time Limit: 1000 ms

#

# Powered by CP Editor (https://cpeditor.org)

# created by NARZULLAYEV SAIDMUROD

import bisect

import random

mod = 10 ** 9 + 7

eps = 10 ** -9

def _miillerTest(d, n):

    a = 2 + random.randint(1, n - 4)

    x = pow(a, d, n)

    if (x == 1 or x == n - 1):

        return True

    while (d != n - 1):

        x = (x * x) % n

        d *= 2;

        if (x == 1):

            return False

        if (x == n - 1):

            return True

    return False;

def _isprime(n):

    if (n < 2 or n == 4):

        return False

    if (n <= 3):

        return True

    d = n - 1;

    while (d % 2 == 0):

        d //= 2

    for i in range(5):

        if (_miillerTest(d, n) == False):

            return False

    return True

def _gcd(a, b):

    return a if b == 0 else _gcd(b, a % b)

def _lcm(a, b):

  return a * b // _gcd(a, b)

def _mex(a):

    mex = 0

    a.sort()

    for x in a:

        if x <= mex:

            mex += 1

        else:

            break

    return mex

def _dist(x1, y1, x2, y2):

  return (x1 - x2) ** 2 + (y1 - y2) ** 2

def _getprimes(n, m):

    primes = []

    if n <= 2:

        primes.append(2)

    if n % 2 == 0:

        n += 1

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

        if _isprime(i):

            primes.append(i)

    return primes

def _primefactors(n):

    ret = []

    x = n

    i = 2

    if _isprime(n):

        ret.append(n)

        return ret

    while i * i <= x:

        while n % i == 0:

            ret.append(i)

            n //= i

            if _isprime(n):

                break

        i += 1

    if n > 1:

        ret.append(n)

    return ret

def _pollardrho(n):

    if n % 2 == 0: return 2

    if _isprime(n): return n

    while True:

        c = random.randint(2, n -1)

        f = lambda x: x**2 + c

        x = y = 2

        d = 1

        while d == 1:

            x = f(x) % n

            y = f(f(y)) % n

            d = _gcd((x - y) % n, n)

        if d != n and _isprime(d): return d

def _sumdigit(n):

  ret = 0

  while n > 0:

    ret += n % 10

    n //= 10

  return ret

def _modinverse(n, m):

    return (n % mod) * (pow(m, mod - 2, mod) % mod) % mod

def p(n):

	return print(n, end = ' ')

def lip(type = int):

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

def mip(type = int):

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

def tip(type = int):

	return type(input())

def inp():

	return input()

def solve(t):

	n, m = mip()

	print('YES' if n % m == 0 else 'NO')

t = 1

t = int(input())

for i in range(t):

    solve(i + 1)


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

t = int(input())
for _ in range(t):
    n, d = (int(i) for i in input().split())
    a = (int(i) for i in input().split())
    res = next(a)
    for i, e in enumerate(a):
        res += min(d, (i + 1) * e) // (i + 1)
        d -= (i + 1) * e
        if d <= 0:
            break
    print(res)


E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific:  The artifact only contains 7575 units of energy.  For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy.  If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1
4

2 1 2

1 2

0

1OutputCopy

? C

? CH

? CCHO

! CCHH

InputCopy2
5

0

2 2 3

1
8

1 5

1 5

1 3

2 1 2

1OutputCopy

? O

? HHH

! CHHHH

? COO

? COOH

? HCCOO

? HH

! HHHCCOOH

NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.

import sys

n, L, minID = None, None, None

s = []

def fill(id, c):

    global n, L, s, minID

    L -= (s[id] == 'L')

    s = s[0:id] + c + s[ id +1:]

    minID = min(minID, id)

def query(cmd, str):

    global n, L, s, minID

    print(cmd, ''.join(str))

    print(cmd, ''.join(str), file=sys.stderr)

    sys.stdout.flush()

    if (cmd == '?'):

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

        assert(result[0] != -1)

        for z in result[1:]:

            z -= 1

            for i in range(len(str)):

                assert(s[z+i] == 'L' or s[z+i] == str[ i ])

                fill(z+i, str[i])

    elif (cmd == '!'):

        correct = int(input())

        assert(correct == 1)

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

    n = int(input())

    if n >= 13:

        ans = [''] * (n + 1)

        print('? CO')

        co = list(map(int, input().split()))[1:]

        print('? CH')

        ch = list(map(int, input().split()))[1:]

        print('? CC')

        cc = list(map(int, input().split()))[1:]

        for d in co:

            ans[d] = 'C'

            ans[d + 1] = 'O'

        for d in ch:

            ans[d] = 'C'

            ans[d + 1] = 'H'

        for d in cc:

            ans[d] = 'C'

            ans[d + 1] = 'C'

        print('? OO')

        oo = list(map(int, input().split()))[1:]

        print('? OH')

        oh = list(map(int, input().split()))[1:]

        for d in oo:

            ans[d] = 'O'

            ans[d + 1] = 'O'

        for d in oh:

            ans[d] = 'O'

            ans[d + 1] = 'H'

        for i in range(1, n):

            if ans[i] == 'O' and ans[i + 1] == '':

                ans[i + 1] = 'C'

        for i in range(1, n):

            if ans[i] == '' and ans[i + 1] == 'O':

                ans[i] = 'H'

        for i in range(1, n):

            if ans[i] == '' and ans[i + 1] == 'H':

                ans[i] = 'H'

        for i in range(1, n):

            if ans[i] == '' and ans[i + 1] == '':

                ans[i] = 'H'

        print('? HOC')

        hoc = list(map(int, input().split()))[1:]

        for d in hoc:

            ans[d] = 'H'

            ans[d + 1] = 'O'

            ans[d + 2] = 'C'

        for d in range(2, n):

            if ans[d] == '':

                ans[d] = 'H'

        if ans[1] == '':

            print('?', 'H' + ''.join(ans[2:-1]))

            if input()[0] != '0':

                ans[1] = 'H'

            else:

                ans[1] = 'O'

        if ans[-1] == '':

            print('?', ''.join(ans[1:-1]) + 'H')

            if input()[0] != '0':

                ans[-1] = 'H'

            else:

                print('?', ''.join(ans[1:-1]) + 'O')

                if input()[0] != '0':

                    ans[-1] = 'O'

                else:

                    ans[-1] = 'C'

        print('!', ''.join(ans[1:]))

        kek = input()

    else:

        L, minID = n, n

        s = 'L' * n

        query('?', "CH")

        query('?', "CO")

        query('?', "HC")

        query('?', "HO")

        if (L == n):

            # the string exists in form O...OX...X, with X=C or X=H

            # or it's completely mono-character

            query('?', "CCC")

            if (minID < n):

                for x in range(minID - 1, -1, -1): fill(x, 'O')

            else:

                query('?', "HHH")

                if (minID < n):

                    for x in range(minID - 1, -1, -1): fill(x, 'O')

                else:

                    query('?', "OOO")

                    if (minID == n):

                        # obviously n=4

                        query('?', "OOCC")

                        if (minID == n):

                            fill(0, 'O')

                            fill(1, 'O')

                            fill(2, 'H')

                            fill(3, 'H')

                    if (s[n - 1] == 'L'):

                        t = s[0:n - 1] + 'C'

                        if (t[n - 2] == 'L'): t = t[0:n - 2] + 'C' + t[n - 1:]

                        query('?', t)

                        if (s[n - 1] == 'L'):

                            fill(n - 1, 'H')

                            if (s[n - 2] == 'L'): fill(n - 2, 'H')

        else:

            maxID = minID

            while (maxID < n - 1 and s[maxID + 1] != 'L'): maxID += 1

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

                query('?', s[i + 1:i + 2] + s[minID:maxID + 1])

                if (minID != i):

                    for x in range(i + 1): fill(x, 'O')

                    break

            nextFilled = None

            i = maxID + 1

            while i < n:

                if (s[i] != 'L'):

                    i += 1

                    continue

                nextFilled = i

                while (nextFilled < n and s[nextFilled] == 'L'): nextFilled += 1

                query('?', s[0:i] + s[i - 1])

                if (s[i] == 'L'):

                    if (s[i - 1] != 'O'):

                        fill(i, 'O')

                    else:

                        if (nextFilled == n):

                            query('?', s[0:i] + 'C')

                            if (s[i] == 'L'): fill(i, 'H')

                            for x in range(i + 1, nextFilled): fill(x, s[i])

                        else:

                            for x in range(i, nextFilled): fill(x, s[nextFilled])

                        i = nextFilled - 1

                i += 1

        query('!', s)


B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2

from collections import  defaultdict

def dfs(g,node,parent,trees):

	l=0

	for i in g[node]:

		if i!=parent:

			l+=dfs(g,i,node,trees)

	trees[node]=l

	return l+1

def dfs2(g,node,Small,answer,C,trees):

	answer[node]=Small[C[node]]

	supersmall=[]

	for i in range(len(Small)):

		if i!=C[node]:

			supersmall.append(Small[i])

	cnts=0

	for i in g[node]:

		u=[]

		for j in range(trees[i]):

			u.append(supersmall[cnts])

			cnts+=1

		dfs2(g,i,u,answer,C,trees)

n=int(input())

root=None

C=[0]*n

g=defaultdict(list)

for i in range(n):

	parent,c=map(int,input().strip().split())

	if parent==0:

		root=i

	else:

		g[parent-1].append(i)

	C[i]=c

trees=[0]*(n)

dfs(g,root,-1,trees)

check=list(map(lambda x,y:x-y,trees,C))

for i in check:

	if i<0:

		print("NO")

		exit(0)

ans=[0]*n

small=[* range(1,n+1)]

trees=list(map(lambda s:s+1,trees))

dfs2(g,root,small,ans,C,trees)

print("YES")

print(*ans)


B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.

import sys

input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)

def isParallel(p1a,p1b,p2a,p2b):

    dx1=p1a[0]-p1b[0]

    dy1=p1a[1]-p1b[1]

    dx2=p2a[0]-p2b[0]

    dy2=p2a[1]-p2b[1]

    return dx1==dx2 and dy1==dy2

n=int(input())

xy=[] #[[x,y]]

for _ in range(n):

    a,b=[int(z) for z in input().split()]

    xy.append([a,b])

#YES if each line is parallel to another line

#xy.sort(key=lambda z:(z[0],z[1])) #no need to sort since polygon given in ccw direction

#xy[0] will match with xy[n-1],xy[1] will match with xy[n-2] etc.

if n%2==1:

    print('NO')

else:

    ans='YES'

    for i in range(n//2):

        p1a=xy[i]

        p1b=xy[i+1]

        j=i+n//2

        p2a=xy[(j+1)%n]

        p2b=xy[(j)]

        if not isParallel(p1a,p1b,p2a,p2b):

            ans='NO'

            break

    print(ans)


D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33.   The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.

from collections import deque

import sys

n,m,k = map(int,sys.stdin.readline().split())

a = list(map(int,sys.stdin.readline().split()))

g = [[] for _ in range(n+1)]

for _ in range(m):

    x,y = map(int,sys.stdin.readline().split())

    g[x].append(y)

    g[y].append(x)

def bfs(start):

    hold = [0]*(n+1)

    visited = [False]*(n+1)

    q = deque()

    q.append(start)

    h = 0

    while len(q)>0:

        for _ in range(len(q)):

            node = q.popleft()

            visited[node] = True

            hold[node] = h

            for child in g[node]:

                if not(visited[child]):

                    visited[child] = True

                    q.append(child)

        h+=1

    return hold

x = bfs(1) #dis 1 to i

y = bfs(n) #dis i to n

arr = sorted([(x[i]-y[i],i) for i in a])

pref,ans = -1e9,-1e9

for v,node in arr:

    ans = max(ans,pref+y[node])

    pref = max(pref,x[node])

print(min(x[n],ans+1))


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.

import array

import bisect

import heapq

import math

import collections

import sys

import copy

from functools import reduce

import decimal

from io import BytesIO, IOBase

import os

import itertools

import functools

from types import GeneratorType

import fractions

# sys.setrecursionlimit(10 ** 9)

decimal.getcontext().rounding = decimal.ROUND_HALF_UP

graphDict = collections.defaultdict

queue = collections.deque

################## pypy deep recursion handling ##############

# Author = @pajenegod

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):

        to = f(*args, **kwargs)

        if stack:

            return to

        else:

            while True:

                if type(to) is GeneratorType:

                    stack.append(to)

                    to = next(to)

                else:

                    stack.pop()

                    if not stack:

                        return to

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

    return wrappedfunc

################## Graphs ###################

class Graphs:

    def __init__(self):

        self.graph = graphDict(set)

    def add_edge(self, u, v):

        self.graph[u].add(v)

        self.graph[v].add(u)

    def dfs_utility(self, nodes, visited_nodes, colors, parity, level):

        global count

        if nodes == 1:

            colors[nodes] = -1

        else:

            if len(self.graph[nodes]) == 1 and parity % 2 == 0:

                if q == 1:

                    colors[nodes] = 1

                else:

                    colors[nodes] = -1

                    count += 1

            else:

                if parity % 2 == 0:

                    colors[nodes] = -1

                else:

                    colors[nodes] = 1

        visited_nodes.add(nodes)

        for neighbour in self.graph[nodes]:

            new_level = level + 1

            if neighbour not in visited_nodes:

                self.dfs_utility(neighbour, visited_nodes, colors, level - 1, new_level)

    def dfs(self, node):

        Visited = set()

        color = collections.defaultdict()

        self.dfs_utility(node, Visited, color, 0, 0)

        return color

    def bfs(self, node, f_node):

        count = float("inf")

        visited = set()

        level = 0

        if node not in visited:

            queue.append([node, level])

            visited.add(node)

        flag = 0

        while queue:

            parent = queue.popleft()

            if parent[0] == f_node:

                flag = 1

                count = min(count, parent[1])

            level = parent[1] + 1

            for item in self.graph[parent[0]]:

                if item not in visited:

                    queue.append([item, level])

                    visited.add(item)

        return count if flag else -1

        return False

################### Tree Implementaion ##############

class Tree:

    def __init__(self, data):

        self.data = data

        self.left = None

        self.right = None

def inorder(node, lis):

    if node:

        inorder(node.left, lis)

        lis.append(node.data)

        inorder(node.right, lis)

    return lis

def leaf_node_sum(root):

    if root is None:

        return 0

    if root.left is None and root.right is None:

        return root.data

    return leaf_node_sum(root.left) + leaf_node_sum(root.right)

def hight(root):

    if root is None:

        return -1

    if root.left is None and root.right is None:

        return 0

    return max(hight(root.left), hight(root.right)) + 1

################## Union Find #######################

class UnionFind():

    parents = []

    sizes = []

    count = 0

    def __init__(self, n):

        self.count = n

        self.parents = [i for i in range(n)]

        self.sizes = [1 for i in range(n)]

    def find(self, i):

        if self.parents[i] == i:

            return i

        else:

            self.parents[i] = self.find(self.parents[i])

            return self.parents[i]

    def unite(self, i, j):

        root_i = self.find(i)

        root_j = self.find(j)

        if root_i == root_j:

            return

        elif root_i < root_j:

            self.parents[root_j] = root_i

            self.sizes[root_i] += self.sizes[root_j]

        else:

            self.parents[root_i] = root_j

            self.sizes[root_j] += self.sizes[root_i]

    def same(self, i, j):

        return self.find(i) == self.find(j)

    def size(self, i):

        return self.sizes[self.find(i)]

    def group_count(self):

        return len(set(self.find(i) for i in range(self.count)))

    def answer(self, extra, p, q):

        dic = collections.Counter()

        for q in range(n):

            dic[self.find(q)] = self.size(q)

        hq = list(dic.values())

        heapq._heapify_max(hq)

        ans = -1

        for z in range(extra + 1):

            if hq:

                ans += heapq._heappop_max(hq)

            else:

                break

        return ans

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

def rounding(n):

    return int(decimal.Decimal(f'{n}').to_integral_value())

def factors(n):

    return set(reduce(list.__add__,

                      ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0), [1]))

def p_sum(array):

    return list(itertools.accumulate(array))

def base_change(nn, bb):

    if nn == 0:

        return [0]

    digits = []

    while nn:

        digits.append(int(nn % bb))

        nn //= bb

    return digits[::-1]

def diophantine(a: int, b: int, c: int):

    d, x, y = extended_gcd(a, b)

    r = c // d

    return r * x, r * y

@bootstrap

def extended_gcd(a: int, b: int):

    if b == 0:

        d, x, y = a, 1, 0

    else:

        (d, p, q) = yield extended_gcd(b, a % b)

        x = q

        y = p - q * (a // b)

    yield d, x, y

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

'''

Knowledge and awareness are vague, and perhaps better called illusions.

Everyone lives within their own subjective interpretation.

                                                            ~Uchiha Itachi

'''

################################ <fast I/O> ###########################################

BUFSIZE = 8192

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, **kwargs):

        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, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

#############################################<I/O Region >##############################################

def inp():

    return sys.stdin.readline().strip()

def map_inp(v_type):

    return map(v_type, inp().split())

def list_inp(v_type):

    return list(map_inp(v_type))

def interactive():

    return sys.stdout.flush()

######################################## Solution ####################################

@bootstrap

def create_dp(node, parent):

    for item in g.graph[node]:

        if item == parent:

            continue

        yield create_dp(item, node)

        dp[node] += max(dp[item], 0)

    yield

@bootstrap

def solve_dp(node, parent):

    global ans

    ans[node - 1] = dp[node]

    for item in g.graph[node]:

        if item == parent:

            continue

        dp[node] -= max(0, dp[item])

        dp[item] += max(0, dp[node])

        yield solve_dp(item, node)

        dp[item] -= max(dp[node], 0)

        dp[node] += max(dp[item], 0)

    yield

n = int(inp())

arr = list_inp(int)

dp = collections.Counter()

for i in range(n):

    if arr[i] == 0:

        dp[i + 1] = -1

    else:

        dp[i + 1] = 1

g = Graphs()

for i in range(n - 1):

    u, v = map_inp(int)

    g.add_edge(u, v)

ans = [0] * n

create_dp(1, -1)

solve_dp(1, -1)

print(*ans)


F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations:  Add 11 to the second element, making it equal to 99.  Subtract 11 from the third element, making it equal to 66.  Add 11 to the fifth element, making it equal to 22.  Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.

import random

n = int(input())

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

limit = min(8, n)

iterations = [x for x in range(n)]

random.shuffle(iterations)

iterations = iterations[:limit]

def factorization(x):

	primes = []

	i = 2

	while i * i <= x:

		if x % i == 0:

			primes.append(i)

			while x % i == 0: x //= i

		i = i + 1

	if x > 1: primes.append(x)

	return primes

def solve_with_fixed_gcd(arr, gcd):

	result = 0

	for x in arr:

		if x < gcd: result += (gcd - x)

		else:

			remainder = x % gcd

			result += min(remainder, gcd - remainder)

	return result

answer = float("inf")

prime_list = set()

for index in iterations:

	for x in range(-1, 2):

		tmp = factorization(a[index]-x)

		for z in tmp: prime_list.add(z)

for prime in prime_list:

	answer = min(answer, solve_with_fixed_gcd(a, prime))

	if answer == 0: break

print(answer)


B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111

t = int(input())

for _ in range(t):

    n = int(input())

    ans = 0

    while n != 0:

        if n > 9:

            ans += (n//10) * 10

            n = (n - ((n//10) * 10)) + (n//10)

        else:

            ans += n

            break

    print(ans)


D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote:   a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy).  or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one.   If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there.  If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1).  If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2).  If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below :   For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :

from collections import deque

N = int(input())

m = [[None]*N for i in range(N)]
v = [[False]*N for i in range(N)]

for i in range(N):
	r = list(map(int, input().split()))
	for j in range(N):
		x, y = r[2*j] - 1, r[2*j + 1] - 1
		m[i][j] = (x, y)

def bfs(x, y):
	# x, y is the coordinate of our input
	q = deque()
	q.append((x, y))
	while len(q):
		x, y = q.popleft()
		for i, j, d in [(x - 1, y, 'D'), (x + 1, y, 'U'), (x, y - 1, 'R'), (x, y + 1, 'L')]:
			if i != -1 and i != N and j != -1 and j != N:
				if m[i][j] != m[x][y]:
					continue
				if not v[i][j]:
					v[i][j] = d
					q.append((i, j))

for i in range(N):
	for j in range(N):
		if m[i][j] == (i, j):
			v[i][j] = 'X'
			bfs(i, j)
		elif m[i][j] == (-2, -2):
			for a, b, nxt, prev in [(i - 1, j, 'U', 'D'), (i + 1, j, 'D', 'U'), (i, j - 1,'L', 'R'), (i, j + 1, 'R', 'L')]:
				if a != -1 and a != N and b != -1 and b != N:
					if m[i][j] != m[a][b]:
						continue
					else:
						v[i][j] = nxt
						v[a][b] = prev
						break

for i in range(N):
	for j in range(N):
		if not v[i][j]:
			print('INVALID')
			exit()

print('VALID')
print('\n'.join([''.join(r) for r in v]))


B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.

from math import *

import sys

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

print = lambda *a, **kw: sys.stdout.write(kw.get('sep', ' ').join(map(str, a)) + kw.get('end', '\n'))

debug = lambda *a: sys.stderr.write(' '.join(map(str, a)) + '\n')

MOD = (10**9)+7

def prefixSum(arr):

    n=len(arr)

    if(n==0):

        return []

    ps = [0] * n

    ps[0] =arr[0]

    for i in range(1,n):

        ps[i]=arr[i]+ps[i-1]

    return ps

def sumDigits(no):

    return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10))

def inde(arr):

    ind = {}

    for i in range(len(n)):

        ind[arr[i]]=i

    return ind

def freq(arr):

    d = {}

    for i in arr:

        if(i in d):

            d[i]+=1

        else:

            d[i]=1

    return d

def isPrime(num):

    if(num > 1):

        for i in range(2,int(sqrt(num))+1):

            if (num % i == 0):

                return False

        return True

    else:

        return False

def cbrt(num):

    return pow(num,1/3)

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

n = int(input())

x = 0

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

    x+=(1/i)

print(x)


F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times:  Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0.  After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty.  After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3
2 6 8
OutputCopy2
InputCopy5
2 3 4 9 12
OutputCopy4
InputCopy4
5 7 2 9
OutputCopy1
NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible:   b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8])  b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible:   b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4])  b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9])  b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12])  b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty.

MOD = 1000000007

def isSubset(a, b):

    return (a & b) == a

def isIntersect(a, b):

    return (a & b) != 0

def cntOrder(s, t):

    p = len(s)

    m = len(t)

    inMask = [0 for i in range(m)]

    for x in range(p):

        for i in range(m):

            if t[i] % s[x] == 0:

                inMask[i] |= 1 << x

    cnt = [0 for mask in range(1 << p)]

    for mask in range(1 << p):

        for i in range(m):

            if isSubset(inMask[i], mask):

                cnt[mask] += 1

    dp = [[0 for mask in range(1 << p)] for k in range(m + 1)]

    for i in range(m):

        dp[1][inMask[i]] += 1

    for k in range(m):

        for mask in range(1 << p):

            for i in range(m):

                if not isSubset(inMask[i], mask) and isIntersect(inMask[i], mask):

                    dp[k + 1][mask | inMask[i]] = (dp[k + 1][mask | inMask[i]] + dp[k][mask]) % MOD

            dp[k + 1][mask] = (dp[k + 1][mask] + dp[k][mask] * (cnt[mask] - k)) % MOD

    return dp[m][(1 << p) - 1]

def dfs(u):

    global a, graph, degIn, visited, s, t

    visited[u] = True

    if degIn[u] == 0:

        s.append(a[u])

    else:

        t.append(a[u])

    for v in graph[u]:

        if not visited[v]:

            dfs(v)

def main():

    global a, graph, degIn, visited, s, t

    n = int(input())

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

    c = [[0 for j in range(n)] for i in range(n)]

    for i in range(n):

        c[i][0] = 1

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

            c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % MOD

    degIn = [0 for u in range(n)]

    graph = [[] for u in range(n)]

    for u in range(n):

        for v in range(n):

            if u != v and a[v] % a[u] == 0:

                graph[u].append(v)

                graph[v].append(u)

                degIn[v] += 1

    ans = 1

    curLen = 0

    visited = [False for u in range(n)]

    for u in range(n):

        if not visited[u]:

            s = []

            t = []

            dfs(u)

            if len(t) > 0:

                sz = len(t) - 1

                cnt = cntOrder(s, t)

                ans = (ans * cnt) % MOD

                ans = (ans * c[curLen + sz][sz]) % MOD

                curLen += sz

    print(ans)

if __name__ == "__main__":

    main()


E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions:   Set the power of the hole a to value b.  Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types:   0 a b  1 a  Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3

import sys

input = sys.stdin.readline

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

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

BLOCK_LENGTH = 450

block = [i//BLOCK_LENGTH for i in range(n)]

jumps = [0] * n

end = [0] * n

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

    nex = i + p[i]

    if nex >= n:

        jumps[i] = 1

        end[i] = i + n

    elif block[nex] > block[i]:

        jumps[i] = 1

        end[i] = nex

    else:

        jumps[i] = jumps[nex] + 1

        end[i] = end[nex]

out = []

for _ in range(m):

    #print(jumps)

    #print(end)

    #print(block)

    s = input().strip()

    if s[0] == '0':

        _,a,b = s.split()

        a = int(a) - 1

        b = int(b)

        p[a] = b

        i = a

        while i >= 0 and block[i] == block[a]:

            nex = i + p[i]

            if nex >= n:

                jumps[i] = 1

                end[i] = i + n

            elif block[nex] > block[i]:

                jumps[i] = 1

                end[i] = nex

            else:

                jumps[i] = jumps[nex] + 1

                end[i] = end[nex]

            i -= 1

    else:

        _,a = s.split()

        curr = int(a) - 1

        jmp = 0

        while curr < n:

            jmp += jumps[curr]

            curr = end[curr]

        out.append(str(curr - n + 1)+' '+str(jmp))

print('\n'.join(out))


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.

t=int(input())

M,L=[],[]

for i in range(t):

    n=int(input())

    L=[int(x) for x in  input().split()]

    M=[int(x) for x in input().split()]

    if len(L)==1 and len(M)==1:

        for k in L:

            print(k)

        for k in M:

            print(k)

    else:

        res1=sorted(L)

        res2=sorted(M)

        for i in range  (len(res1)-1):

            print(res1[i],end=' ')

        print(res1[len(res1)-1])

        for k in range (len(res2)-1):

             print(res2[k],end=' ')

        print(res2[len(res2)-1])


A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.

import sys
from collections import defaultdict
from heapq import heapify, heappush, heappop

n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
t = list(map(int, sys.stdin.readline().split()))

# create a map that stores list of time for each value of a
umap = defaultdict(list)
for i in range(n):
    umap[a[i]].append(t[i])

# maintain a priority queue that will store time of repeating values
# this will help us in retriving/deleting greatest time
pq = []  # max heap
heapify(pq)
heapsum = 0  # to store sum of heap

ans = 0
for num in sorted(set(a)):
    if len(umap[num]) > 1 or len(pq) > 0:  # either num repeats or pq is not empty
        for val in umap[num]:
            heappush(pq, -1*val)  # store negative value since it's min heap
            heapsum += val

        # remove the largest time value
        heapsum += pq[0]
        heappop(pq)

        # increment all the other values
        temp = num
        while len(pq) > 0:
            temp += 1
            ans += heapsum
            if len(umap[temp]) > 0:
                # the next num also contains many time value
                # hence should be added in next iteration
                break
            else:
                # remove the largest time value
                heapsum += pq[0]
                heappop(pq)

print(ans)


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

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

    input()

    print(len(set(input().split())))


E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times:   choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|;  erase the chosen subsequence from ss (ss can become empty);  concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES

import sys, os, io

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

def f(x, y):

    return x * (c2 + 1) + y

q = int(input())

inf = 114514

ans = []

for _ in range(q):

    s = list(input().rstrip())

    t = list(input().rstrip())

    n = len(s)

    m = len(t)

    x = [[-1] for _ in range(26)]

    for i in range(n):

        s[i] -= 97

        x[s[i]].append(i)

    dp0 = [[inf] * n for _ in range(26)]

    for i in range(26):

        xi = x[i]

        for j in range(len(xi) - 1):

            l, r = xi[j], xi[j + 1]

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

                dp0[i][k] = r

    for i in range(m):

        t[i] -= 97

    ans0 = "NO"

    i = 0

    for j in range(n):

        if i == m:

            break

        if s[j] == t[i]:

            i += 1

    if i == m:

        ans0 = "YES"

        ans.append(ans0)

        continue

    for c1 in range(1, m):

        c2 = m - c1

        dp = [inf] * ((c1 + 1) * (c2 + 1))

        dp[0] = 0

        for i in range(c1 + 1):

            for j in range(c2 + 1):

                if dp[f(i, j)] == inf:

                    break

                dpij = dp[f(i, j)]

                if i + 1 < c1 + 1 and dpij < n:

                    u = t[i]

                    if dp0[u][dpij] < inf:

                        dp[f(i + 1, j)] = min(dp[f(i + 1, j)], dp0[u][dpij] + 1)

                if j + 1 < c2 + 1 and dpij < n:

                    u = t[c1 + j]

                    if dp0[u][dpij] < inf:

                        dp[f(i, j + 1)] = min(dp[f(i, j + 1)], dp0[u][dpij] + 1)

        if dp[f(c1, c2)] ^ inf:

            ans0 = "YES"

            break

    ans.append(ans0)

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


E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:

import sys

input = sys.stdin.buffer.readline

def process(n, d):

    if d > n*(n-1)//2:

        return ['NO', None]

    answer = [1]

    while True:

        if sum(answer)+2*answer[-1] <= n:

            answer.append(2*answer[-1])

        else:

            break

    answer.append(n-sum(answer))

    curr = sum([i*answer[i] for i in range(len(answer))])

    if d < curr:

        return ['NO', None]

    while curr < d:

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

            if answer[i] > 1:

                break

        answer[i]-=1

        if i==len(answer)-1:

            answer.append(1)

        else:

            answer[i+1]+=1

        curr+=1

    assert sum([i*answer[i] for i in range(len(answer))])==d

    depths = [[] for i in range(len(answer))]

    depth1 = [None for i in range(n+1)]

    children = [0 for i in range(n+1)]

    final_answer = [None for i in range(n-1)]

    I = 0

    p = 1

    depth1[p] = 0

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

        if len(depths[I])==answer[I]:

            I+=1

        while children[p]==2 or depth1[p] < I-1:

            p+=1

        if i > 1:

            final_answer[i-2] = p

            children[p]+=1

        depths[I].append(i)

        depth1[i] = I

  #  print(answer)

  # print(depths)

   # print(depth1)

    #print(final_answer)

    return ['YES', final_answer]

t = int(input())

for i in range(t):

    n, d = [int(x) for x in input().split()]

    a1, a2 = process(n, d)

    print(a1)

    if a1=='YES':

        sys.stdout.write(' '.join(map(str, a2))+'\n')


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


F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li.  For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk].  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k.   The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3

import sys, os, io

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

from collections import defaultdict

n = int(input())

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

has = defaultdict(list)

def f(a,b):return a*n+b

def ff(a):return (a//n,a%n)

for j in range(n):

    lin = 0

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

        lin += a[i]

        if lin in has and ff(has[lin][-1])[1] >= i:continue

        has[lin].append(f(i,j))

mx = max(has.values(),key=lambda x:len(x))

print(len(mx))

for i in mx:

    a,b = ff(i)

    print(a+1,b+1)


B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.

import sys

input = sys.stdin.readline

t = int(input())

for _ in range(t):

    n, x = map(int, input().split())

    s = list(input().rstrip())

    a = [0]

    for i in s:

        a.append(a[-1] + (1 if i == "0" else -1))

    an = a[n]

    if an:

        ans = 0

        for i in range(n):

            if x - a[i] >= 0 and an > 0 or x - a[i] <= 0 and an < 0:

                if abs(x - a[i]) % abs(an) == 0:

                    ans += 1

    else:

        ans = -1 if x in set(a) else 0

    print(ans)


B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions:  If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss;  If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt;  For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e":  On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.

import sys

import math

input = sys.stdin.readline

from functools import cmp_to_key;

def pi():

    return(int(input()))

def pl():

    return(int(input(), 16))

def ti():

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

def ts():

    s = input()

    return(list(s[:len(s) - 1]))

def invr():

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

mod = 998244353;

f = [];

def fact(n,m):

    global f;

    f = [1 for i in range(n+1)];

    f[0] = 1;

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

        f[i] = (f[i-1]*i)%m;

def fast_mod_exp(a,b,m):

    res = 1;

    while b > 0:

        if b & 1:

            res = (res*a)%m;

        a = (a*a)%m;

        b = b >> 1;

    return res;

def inverseMod(n,m):

    return fast_mod_exp(n,m-2,m);

def ncr(n,r,m):

    if r == 0: return 1;

    return ((f[n]*inverseMod(f[n-r],m))%m*inverseMod(f[r],m))%m;

def main():

    B();

def B():

    s = ts();

    t = pi();

    c = [[0 for j in range(len(s))] for i in range(26)];

    for i in range(26):

        for j in range(len(s)):

            if ord(s[j])-ord("a") == i:

                c[i][j] = c[i][j-1] + 1 if j > 0 else 1;

            else:

                c[i][j] = c[i][j-1] if j > 0 else 0;

    for i in range(t):

        [l,r] = ti();

        count = 0;

        for j in range(26):

            count += (1 if c[j][r-1]-c[j][l-1] > 0 else 0);

        if s[l-1] != s[r-1] or l == r:

            print("Yes");

        elif count >= 3:

            print("Yes");

        else:

            print("No");

main();


B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES

from sys import stdin

input=lambda :stdin.readline()[:-1]

def solve():

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

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

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

  ok=[0]*(n-1)

  for i in b:

    ok[i]=1

  while True:

    flag=True

    for i in range(n-1):

      if a[i]>a[i+1]:

        flag=False

        if ok[i]:

          a[i],a[i+1]=a[i+1],a[i]

        else:

          print('NO')

          return

    if flag:

      print('YES')

      return

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

  solve()