C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between 00 and n−2n−2 inclusive.  All the written labels are distinct.  The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample:

import sys

input = sys.stdin.readline

n = int(input())

dic = {i:[] for i in range(1,n+1)}

for i in range(n-1):

    u,v = map(int, input().split())

    dic[u].append([i,v])

    dic[v].append([i,u])

ans = [i for i in range(n-2,-1,-1)]

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

for i in dic:

    if len(dic[i])==1 and res[dic[i][0][0]]==-1:

        res[dic[i][0][0]] = ans.pop()

for i in range(n-1):

    if res[i]==-1:

        res[i] = ans.pop()

print(*res,sep=" ")


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

#!/usr/bin/env python3

import io, os, sys
from sys import stdin, stdout

# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def input(): return stdin.readline().strip()
def read_int_list(): return list(map(int, input().split()))
def read_int_tuple(): return tuple(map(int, input().split()))
def read_int(): return int(input())

from itertools import permutations, chain, combinations, product
from math import factorial, gcd
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
from bisect import bisect_left
from functools import lru_cache

### CODE HERE

def ans_slow(A):
    ret = max(A)
    for x in range(4*max(A)):
        ret = min(ret, max([a^x for a in A]))
    return ret

def any_set(d, A):
    mask = (1 << d)
    for a in A:
        if mask & a:
            return True
    return False

def lowest_d(A):
    for d in range(33, -1, -1):
        if any_set(d, A):
            return d
    assert(False)

def ans_list(A):
    if len(A) <= 1: return 0

    d = lowest_d(A)
    mask = (1 << d)

    L = []
    R = []

    for a in A:
        if mask & a:
            L += [a]
        else:
            R += [a]

    L = [l^mask for l in L]

    if len(L) == 0:
        return ans_list(R)
    if len(R) == 0:
        return ans_list(L)

    L = list(set(L))
    R = list(set(R))

    # print(A, "split into", L, R)

    assert(len(L) < len(A))
    assert(len(R) < len(A))

    return (1 << d) + min(ans_list(R), ans_list(L))

if False:
    for _ in range(10000):
        import random
        A = [random.randint(1, 15) for _ in range(15)]
        A = list(sorted(set(A)))
        if ans_slow(A) != ans_list(A):
            print(A, ans_slow(A), ans_list(A))
            assert(False)
else:
    input()
    A = read_int_list()
    A = list(set(A))
    print(ans_list(A))
    # A = [1, 2, 3, 5]
    # print(ans(A))


C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2

3 4
1 1 1
1 1
1 2
2 2
2 3

4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.

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

T = int(input())

for _ in range(T):
	n, m = map(int, input().split())
	values = list(map(int, input().split()))
	neigh_values = [0]*n
	y_neigh = [[] for i in range(n)]
	di = [[] for i in range(n)]
	for i in range(m):
		x, y = map(int, input().split())
		neigh_values[x - 1] += values[y - 1]
		di[x - 1].append(y - 1)
		y_neigh[y - 1].append(x - 1)

	# group indices with the same neighboring set
	y_n = {}
	for i in range(n):
		nst = frozenset(y_neigh[i])
		if nst != set():
			if nst in y_n:
				y_n[nst].append(i)
			else:
				y_n[nst] = [i]

	curr = 0
	for nst in y_n.values():
		tosum = [values[i] for i in nst]
		curr = gcd(curr, sum(tosum))

	print (curr)

	if _ != T - 1:
		blank = input()


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.

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

    n = int(input())

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

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

    A.sort()

    B.sort()

    print(*A)

    print(*B)


C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following:  if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

from collections import defaultdict,deque

n = int(input())

for _ in range(n):

    graph = defaultdict(set)

    degrees = defaultdict(int)

    visited = set()

    edges = input()

    graph[edges[0]] = set()

    degrees[edges[0]] = 0

    for i in range(1,len(edges)):

        u,v = edges[i-1],edges[i]

        if (u,v) not in visited and (v,u) not in visited:

            graph[u].add(v)

            graph[v].add(u)

            degrees[u]+=1

            degrees[v]+=1

            visited.add((u,v))

            visited.add((v,u))

    flag = False

    for node,degree in degrees.items():

        if degree >= 3:

            flag = True

            break

    q = deque([char for char in degrees if degrees[char]<2])

    order = []

    visited = set()

    while q:

        char = q.popleft()

        if char in visited:

            continue

        order.append(char)

        visited.add(char)

        for adjChar in graph[char]:

            graph[adjChar].remove(char)

            degrees[adjChar]-=1

            if degrees[adjChar]<=1:

                q.appendleft(adjChar)

    if len(order)!=len(graph) or flag == True:

        print("NO")

    else:

        for charOrd in range(ord('a'),ord('z')+1):

            char = chr(charOrd)

            if char not in graph:

                order.append(char)

        print("YES")

        print("".join(order))


F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values:  his departure station ajaj;  his arrival station bjbj;  minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1

import sys

class RangeMinQuery:
    # O(nlog(n)) construction/space, O(1) range minimum query
    def __init__(self, data):
        self._data = [list(data)]
        n = len(self._data[0])

        # self._data[i][j] stores the min of the segment [j, j + 2 ** i] where i is in [1,2,4,8,...,log(N)]
        w = 1
        while 2 * w <= n:
            prev = self._data[-1]
            self._data.append([min(prev[j], prev[j + w]) for j in range(n - 2 * w + 1)])
            w *= 2

    def query(self, begin, end):
        # Find min of [begin, end)
        # Take the min of the overlapping intervals [begin, begin + 2**depth) and [end - 2**depth, end)
        assert begin < end
        depth = (end - begin).bit_length() - 1
        return min(self._data[depth][begin], self._data[depth][end - (1 << depth)])

class LCA:
    def __init__(self, graph, root=1):
        # Euler tour representation recording every visit to each node in the DFS
        self.eulerTour = []
        # For each node record the index of their first visit in the euler tour
        self.preorder = [None] * len(graph)
        # Record last visit
        self.postorder = [None] * len(graph)
        # Depth of each node to the root
        self.depth = [None] * len(graph)
        # Parent of each node
        self.parent = [None] * len(graph)

        # DFS
        stack = [root]
        self.depth[root] = 0
        self.parent[root] = None
        while stack:
            node = stack.pop()
            # Record a visit in the euler tour
            self.eulerTour.append(node)
            if self.preorder[node] is None:
                # Record first visit
                self.preorder[node] = len(self.eulerTour) - 1

                for nbr in graph[node]:
                    if self.preorder[nbr] is None:
                        self.depth[nbr] = self.depth[node] + 1
                        self.parent[nbr] = node
                        stack.append(node)
                        stack.append(nbr)
            # Record last visit (this can be overwritten)
            self.postorder[node] = len(self.eulerTour) - 1

        # self.rmq = RangeMinQuery(self.preorder[node] for node in self.eulerTour)

        if False:
            # Check invariants

            assert self.depth[1] == 0
            assert self.parent[1] == None
            for node in range(1, len(graph)):
                assert self.preorder[node] == self.eulerTour.index(node)
                assert self.postorder[node] == max(
                    i for i, x in enumerate(self.eulerTour) if x == node
                )

            for i in range(len(self.rmq._data)):
                for j in range(i + 1, len(self.rmq._data) + 1):
                    assert min(self.rmq._data[0][i:j]) == self.rmq.query(i, j)

            for u in range(1, N + 1):
                for v in range(1, N + 1):
                    assert self.lca(u, v) == self.lca(v, u)
                    lca = self.lca(u, v)
                    assert self.isAncestor(lca, u)
                    assert self.isAncestor(lca, v)
                    path = self.path(u, v)
                    assert len(path) == self.dist(u, v) + 1
                    for x, y in zip(path, path[1:]):
                        assert y in graph[x]
                    assert len(set(path)) == len(path)

    def lca(self, u, v):
        a = self.preorder[u]
        b = self.preorder[v]
        if a > b:
            a, b = b, a
        return self.eulerTour[self.rmq.query(a, b + 1)]

    def dist(self, u, v):
        return self.depth[u] + self.depth[v] - 2 * self.depth[self.lca(u, v)]

    def isAncestor(self, ancestor, v):
        # Checks if `ancestor` is an ancestor of `v`
        return (
            self.preorder[ancestor] <= self.preorder[v]
            and self.postorder[v] <= self.postorder[ancestor]
        )

    def path(self, u, v):
        # Returns the path from u to v in the tree. This doesn't rely on rmq
        # Walk up from u until u becomes ancestor of v (the LCA)
        uPath = []
        while not self.isAncestor(u, v):
            uPath.append(u)
            u = self.parent[u]
        lca = u
        # Walk up from v until v is at the LCA too
        assert self.isAncestor(u, v)
        vPath = []
        while v != lca:
            vPath.append(v)
            v = self.parent[v]
        ret = uPath + [lca] + vPath[::-1]
        return ret

def solve(N, edges, passengers):
    graph = [[] for i in range(N + 1)]
    for e in edges:
        graph[e[0]].append(e[1])
        graph[e[1]].append(e[0])

    tree = LCA(graph)

    scores = [[1 for j in range(N + 1)] for i in range(N + 1)]
    for a, b, score in passengers:
        path = tree.path(a, b)
        assert path[0] == a and path[-1] == b
        for u, v in zip(path, path[1:]):
            scores[u][v] = max(scores[u][v], score)
            scores[v][u] = max(scores[v][u], score)

    for a, b, score in passengers:
        ans = float("inf")
        path = tree.path(a, b)
        for u, v in zip(path, path[1:]):
            ans = min(ans, scores[u][v])
        if ans != score:
            return -1

    return " ".join(str(scores[e[0]][e[1]]) for e in edges)

if False:
    N = 5000
    edges = list(zip(range(N - 1), range(1, N)))
    assert len(edges) == N - 1
    passengers = [(0, p, N - p) for p in range(1, N)]
    solve(N, edges, passengers)
    exit(0)

if __name__ == "__main__":
    input = sys.stdin.readline

    N = int(input())
    edges = [[int(x) for x in input().split()] for i in range(N - 1)]
    P = int(input())
    passengers = [[int(x) for x in input().split()] for i in range(P)]

    ans = solve(N, edges, passengers)
    print(ans)


A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).

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

    line = input()

    s, f = -1, -1

    for i in range(len(line)):

        if line[i] == '1':

            if s < 0:

                s = i

            f = i

    print(line[s:f].count('0'))


C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation:   z=acacez=acace (if we choose subsequence aceace);  z=acbcdz=acbcd (if we choose subsequence bcdbcd);  z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3

#z=int(input())

import math

from itertools import combinations

import time

import random

def transformare_baza(numar,baza):

 transformare=""

 while numar>=baza:

  rest=numar%baza

  numar=numar//baza

  transformare+=str(rest)

 transformare+=str(numar)

 noua_baza=transformare[::-1]

 return noua_baza

def bitwise_or(a,b):

 stringul_1=transformare_baza(a,2)

 stringul_2=transformare_baza(b,2)

 lungime=max(len(stringul_1), len(stringul_2))

 raspunsul=0

 #print(stringul_1,stringul_2)

 str_answ=[0]*lungime

# print('lungime=', lungime)

 #print(str_answ)

 for i in range(0,lungime):

 # print(i,str_answ)

  j=lungime-1-i

  if len(stringul_1)>i and len(stringul_2)>i:

   if stringul_1[len(stringul_1)-1-i]!='0' or  stringul_2[len(stringul_2)-1-i]!='0':

    raspunsul+=2**(i)

    str_answ[i]='1'

  elif len(stringul_1)>i and stringul_1[len(stringul_1)-1-i]=='1':

   raspunsul+=2**(i)

   str_answ[i]='1'

  elif len(stringul_2)>i and stringul_2[len(stringul_2)-1-i]=='1':

   raspunsul+=2**(i)

   str_answ[i]='1'

 #print(str_answ)

 return raspunsul

def bitwise_and(a,b):

 stringul_1=transformare_baza(a,2)

 stringul_2=transformare_baza(b,2)

 lungime=max(len(stringul_1), len(stringul_2))

 raspunsul=0

 #print(stringul_1,stringul_2)

 str_answ=[0]*lungime

# print('lungime=', lungime)

 #print(str_answ)

 for i in range(0,lungime):

 # print(i,str_answ)

  j=lungime-1-i

  if len(stringul_1)>i and len(stringul_2)>i:

   if stringul_1[len(stringul_1)-1-i]=='1' and  stringul_2[len(stringul_2)-1-i]=='1':

    raspunsul+=2**(i)

    str_answ[i]='1'

   else:

    str_answ[i]='0'

 #print(str_answ)

 return raspunsul

alfabet = {'a': 1, 'b': 2,'c': 3,'d': 4,'e': 5,'f': 6,'g': 7,'h': 8,'i': 9,'j': 10,'k': 11,'l': 12,'m': 13,'n': 14,'o': 15,'p': 16,'q': 17,'r': 18,'s': 19,'t': 20,'u': 21,'v': 22,'w': 23,'x': 24,'y': 25,'z': 26}

alfabet_2={'1':"a", '2':"b", '3':"c", '4':"d", '5':"e", '6':"f", '7':"g", '8':"h", '9':"i", '10':"j", '11':"k", '12':"l", '13':"m", '14':"n", '15':"o", '16':"p", '17':"q", '18':"r", '19':"s", '20':"t", '21':"u", '22':"v", '23':"w", '24':"x", '25':"y", '26':"z"}

def comparatie(a,b):

  #print("1st",a,b)

  if len(a)<=1:

   return a==b

  elif a[0:len(a)//2]==b[0:len(b)//2]:

   return comparatie (a[len(a)//2:len(a)],b[len(b)//2:len(b)])

  else:

   return  False

def functie(vector,suma,pozitie,cate):

 answ=0

 #if pozitie==2:

  #print(suma,min(cate,pozitie+1))

 if pozitie>=0:

  if suma>=vector[pozitie]:

   if pozitie+1>=cate:

    suma-=vector[pozitie]

    answ+=cate

    answ+=functie(vector,suma,pozitie-cate,cate)

   else:

    suma-=vector[pozitie]

    answ+=1

    answ+=functie(vector,suma,pozitie-1,cate)

 return answ

def functie_string_baza(stringul,baza):

 answ=pr

 stringul=stringul.lower()

 lungime=len(stringul)

 for j in range(lungime):

  if stringul[j] in alfabet:

   answ+=(baza**(lungime-1-j))*(alfabet[stringul[j]]+9)

  else:

   #print("baza=",baza, lungime-1-j,j)

   answ+=(baza**(lungime-1-j))*(int(stringul[j]))

 return (answ)

#z=int(input())

tupla=[]

dictionar={}

z=int(input())

for contorr in range(z):

 #n=int(input())

 stringul=input()

 target=input()

 #maximul=10**9+1

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

 #bloc=list(map(int, input().split()))

# vector=list(map(int, input().split()))

 #bloc=[]

 #vector=[]

 #n=200

 #m=200

 vector=[[] for x in range(27)]

 setul=set()

 n= len(stringul)

 for i in range(n):

  vector[(alfabet[stringul[i]])].append(i)

  setul.add(stringul[i])

  cate=0

  posibil=1

  pornire=0

 first=-1

 for dd in range(len(target)):

  #print("dd=",dd,first)

  i=target[dd]

  if i not in setul:

   posibil=0

   break

  else:

   if first==-1:

    cate+=1

    first=vector[alfabet[i]][0]

   else:

    if vector[alfabet[i]][len(vector[alfabet[i]])-1]>first:

     #cb

     prima= 0

     ultima=len(vector[alfabet[i]])-1

     pp=1

     centru=prima

     while prima+1<ultima:

      centru=(prima+ultima)//2

      while vector[alfabet[i]][centru]<=first and prima+1<ultima:

       prima=centru

       centru=(prima+ultima)//2

      while vector[alfabet[i]][centru]>first and prima+1<ultima:

       ultima=centru

       centru=(prima+ultima)//2

     if vector[alfabet[i]][centru]<=first:

      centru+=1

     first=vector[alfabet[i]][centru]

     #print("i=",i,"ff=",first,"centru=",centru)

    else:

     cate+=1

     first=vector[alfabet[i]][0]

  #print("dd=",dd,first)

 if posibil==0:

  print(-1)

 else:

  print(cate)

  #print(first)


#! /bin/env python3

# please follow ATshayu

def main():

    N = 100000 + 5

    edge = [(0, 0) for i in range(N)]

    d = [0 for i in range(N)]

    n = int(input())

    for i in range(n-1):

        edge[i] = list(map(int, input().split(' ')))

        for ele in edge[i]: d[ele] += 1

    # solve

    core = -1

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

        if d[i] > 2:

            core = i

            break

    if core < 0:

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

        return

    p, q = 0, 3

    for i in range(n-1):

        if edge[i][0] == core or edge[i][1] == core:

            if p < 3:

                print(p)

                p += 1

            else:

                print(q)

                q += 1

        else:

            print(q)

            q += 1

main()


E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can:  choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously.  Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this:  In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.

# Legends Always Come Up with Solution

# Author: Manvir Singh

import os

import sys

from io import BytesIO, IOBase

from collections import Counter

def main():

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

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

    ans=0

    for i in range(m):

        b=Counter()

        for j in range(n):

            b[m*j+i+1]=j+1

        c=Counter()

        for j in range(n):

            z=b[a[j][i]]

            if z:

                c[(j-z+1)%n]+=1

        mi=n

        for j in c:

            mi=min(mi,j+n-c[j])

        ans+=mi

    print(ans)

# region fastio

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

        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)

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

if __name__ == "__main__":

    main()


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

caseNumber = int(input())

while caseNumber != 0:

    arraySize = int(input())

    array = input().split(" ")

    positionCount = 0

    middlePosition = int(arraySize/2) - 1

    Pass = True

    if arraySize%2 == 0:

            if int(array[middlePosition]) < middlePosition + 1 and int(array[middlePosition + 1]) < middlePosition + 1:

                #print("proc failure")

                Pass = False

    for digit in array:

        #print("assessing " + digit)

        digit = int(digit)

        reversePositionCount = arraySize - 1 - positionCount

        if reversePositionCount < positionCount:

            relativePosition = reversePositionCount

        else:

            relativePosition = positionCount

        #print("relative position: " + str(relativePosition))

        if digit < relativePosition:

            #print("proc failure")

            Pass = False

            break

        positionCount = positionCount + 1

    if Pass == True:

        print("Yes")

    else:

        print("No")

    caseNumber = caseNumber - 1


A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.

import math

n = int(input())

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

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

total1 = 0

total2 = 0

arr_count = 0

total1 = sum(arr)

total2 = sum(arr2)

if total2 == len(arr2):

    print(-1)

    exit()

for i in range(len(arr)):

    if arr[i] == 1 and arr[i] == arr2[i]:

        arr_count += 1

if arr_count == total1:

    print(-1)

    exit()

total1 -= arr_count

total2 -= arr_count

val = math.ceil((total2+1) / (total1))

print(val)


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.

# ------------------- fast io --------------------

import os

import sys

from io import BytesIO, IOBase

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

        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)

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

# ------------------- fast io --------------------

dict1={}

for s in range(26):

    dict1[s]=0

vals=[ord(k)-97 for k in input()]

n=len(vals);store=[]

for s in range(n):

    dict1[vals[s]]+=1

    store.append(dict1.copy())

#always doable when u have 3 distinct

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

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

    l-=1;r-=1

    distinct=[]

    if l==0:

        dict2=store[r]

    else:

        dict2=store[r].copy()

        for s in range(26):

            dict2[s]-=store[l-1][s]

    for s in range(26):

        if dict2[s]>=1:

            distinct.append(dict2[s])

    if len(distinct)>=3:

        print("Yes")

    else:

        if len(distinct)==2:

            if vals[l]==vals[r]:

                print("No")

            else:

                print("Yes")

        else:

            if l==r:

                print("Yes")

            else:

                print("No")


D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.

import re

import functools

import random

import sys

import os

import math

from collections import Counter, defaultdict, deque

from functools import lru_cache, reduce

from itertools import accumulate, combinations, permutations

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

from io import BytesIO, IOBase

from copy import deepcopy

import threading

from typing import *

from operator import add, xor, mul, ior, iand, itemgetter

import bisect

BUFSIZE = 4096

inf = float('inf')

class FastIO(IOBase):

    newlines = 0

    def __init__(self, file):

        self._fd = file.fileno()

        self.buffer = BytesIO()

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

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

    def read(self):

        while True:

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

            if not b:

                break

            ptr = self.buffer.tell()

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

        self.newlines = 0

        return self.buffer.read()

    def readline(self):

        while self.newlines == 0:

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

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

            ptr = self.buffer.tell()

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

        self.newlines -= 1

        return self.buffer.readline()

    def flush(self):

        if self.writable:

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

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

class IOWrapper(IOBase):

    def __init__(self, file):

        self.buffer = FastIO(file)

        self.flush = self.buffer.flush

        self.writable = self.buffer.writable

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

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

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

sys.stdin = IOWrapper(sys.stdin)

sys.stdout = IOWrapper(sys.stdout)

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

def I():

    return input()

def II():

    return int(input())

def MII():

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

def LI():

    return list(input().split())

def LII():

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

def GMI():

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

def LGMI():

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

from types import GeneratorType

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):

        if stack:

            return f(*args, **kwargs)

        else:

            to = f(*args, **kwargs)

            while True:

                if type(to) is GeneratorType:

                    stack.append(to)

                    to = next(to)

                else:

                    stack.pop()

                    if not stack:

                        break

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

            return to

    return wrappedfunc

n, m, k = MII()

events = []

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

    l, r = GMI()

    events.append([l, i])

    events.append([r+1, -i])

events.sort()

M = 1 << k

cnt = [0] * M

dp = [-inf] * M

dp[0] = 0

for i in range(k):

    cnt[1 << i] = 1

for i in range(M):

    cnt[i] = cnt[i - (i & -i)] + cnt[i & -i]

name = [0] * k

for i in range(2 * n):

    idx, event = events[i]

    length = events[i+1][0] - events[i][0] if i < 2 * n - 1 else 0

    if event > 0:

        for j in range(k):

            if name[j] == 0:

                name[j] = event

                pos = j

                break

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

            if (j >> pos) & 1: dp[j] = dp[j - (1 << pos)] + cnt[j] % 2 * length

            else: dp[j] += cnt[j] % 2 * length

    else:

        for j in range(M):

            if name[j] == -event:

                name[j] = 0

                pos = j

                break

        for j in range(M):

            if (j >> pos) & 1: dp[j] = -inf

            else: dp[j] = max(dp[j], dp[j + (1 << pos)]) + cnt[j] % 2 * length

print(dp[0])


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

import os, sys

from io import BytesIO, IOBase

from math import log2, ceil, sqrt, gcd

from _collections import deque

import heapq as hp

from bisect import bisect_left, bisect_right

from math import cos, sin

from itertools import permutations

from operator import itemgetter

sys.setrecursionlimit(5 * 10 ** 4)

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

        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)

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

pi = 3.1415926535

mod = 998244353

from types import GeneratorType

def iterative(f, stack=[]):

    def wrapped_func(*args, **kwargs):

        if stack: return f(*args, **kwargs)

        to = f(*args, **kwargs)

        while True:

            if type(to) is GeneratorType:

                stack.append(to)

                to = next(to)

                continue

            stack.pop()

            if not stack: break

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

        return to

    return wrapped_func

@iterative

def dfs(x, y):

    for i in a[x]:

        if i != y:

            yield dfs(i, x)

    if len(a[x]) == 1:

        dp[x].append([0, x])

        dp[y].append([1, x])

    else:

        dp[x].sort(key=itemgetter(0), reverse=True)

        while len(dp[x]) > 3:

            dp[x].pop()

        dp[y].append([dp[x][0][0] + 1, dp[x][0][1]])

    yield

@iterative

def dfs2(x, y):

    if len(dp[x]) == 3:

        ct = 0

        for i, j in dp[x]:

            ct += i

        ct += 1

        if ct > tot[0]:

            pt[0] = x

            tot[0] = ct

            ans.clear()

            for i, j in dp[x]:

                ans.append(j)

    elif len(dp[x]) == 2:

        ct = 0

        for i,j in dp[x]:

            ct+=i

            if j==x:

                ct=-1

                break

        if ct!=-1:

            ct+=1

            if ct > tot[0]:

                pt[0] = x

                tot[0] = ct

                ans.clear()

                for i, j in dp[x]:

                    ans.append(j)

                ans.append(x)

    for i in a[x]:

        if i != y:

            for j1, j2 in dp[x]:

                if [j1 - 1, j2] not in dp[i]:

                    dp[i].append([j1 + 1, j2])

                    break

            dp[i].sort(key=itemgetter(0), reverse=True)

            while len(dp[i]) > 3:

                dp[i].pop()

            yield dfs2(i, x)

    yield

n = int(input())

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

for _ in range(n - 1):

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

    a[x].append(y)

    a[y].append(x)

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

dfs(1, 0)

tot = [0]

ans = []

pt = [-1]

dfs2(1, 0)

print(tot[0] - 1)

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 :

d4i=[0,-1,0,1]

d4j=[-1,0,1,0]

direction=['L','U','R','D']

back=['R','D','L','U']

def main():

    # Observations:

    #     if ri,cj==xi,yj, i,j is x

    #     if ri,cj==-1,-1, i,j is cycle:

    # Steps:

    #     Mark cycles and Xs

    #     DFS from all X only to nodes pointing to x

    #     Fill cycles by pointing to an adjacent cycle square

    #     Check that all cells are marked

    n=int(input())

    finalState=[[] for _ in range(n)] #[xi,yj]

    ans=[[None for _ in range(n+1)] for __ in range(n+1)]

    for i in range(n):

        temp=readIntArr()

        temp.append(-11) #adding extra col to avoid checking for out of grid

        temp.append(-11)

        for j in range(n+1):

            finalState[i].append([temp[2*j]-1,temp[2*j+1]-1]) #0-indexing

    finalState.append([None]*(n+1)) #adding extra row to avoid checking for out of grid

    endPoints=[]

    cyclePoints=set()

    for i in range(n):

        for j in range(n):

            x,y=finalState[i][j]

            if x==i and y==j:

                ans[i][j]='X'

                endPoints.append([x,y])

            elif x==-2: #due to 0-indexing

                ans[i][j]='c' #cycle

                cyclePoints.add((i,j))

    # multiLineArrayOfArraysPrint(finalState)

    # multiLineArrayOfArraysPrint(ans)

    for endX,endY in endPoints:

        stack=[[endX,endY]]

        while stack:

            i,j=stack.pop()

            for z in range(4):

                ii=i+d4i[z]

                jj=j+d4j[z]

                if ans[ii][jj]==None and finalState[ii][jj]==[endX,endY]:

                    ans[ii][jj]=back[z]

                    stack.append([ii,jj])

    # Fill Cycles (point each cycle point to another cycle point)

    for ci,cj in cyclePoints:

        for z in range(4):

            ii=ci+d4i[z]

            jj=cj+d4j[z]

            if (ii,jj) in cyclePoints:

                ans[ci][cj]=direction[z]

                break

    ok=True

    outcomes={'U','D','R','L','X'}

    for i in range(n):

        for j in range(n):

            if ans[i][j] not in outcomes:

                ok=False

    if ok:

        print('VALID')

        ans.pop()#remove extra row

        for i in range(n):

            ans[i].pop() #remove extra col

        multiLineArrayOfArraysPrint(ans)

    else:

        print('INVALID')

    return

import sys

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

# import sys

# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.

def oneLineArrayPrint(arr):

    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):

    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):

    print('\n'.join([''.join([str(x) for x in y]) for y in arr]))

def readIntArr():

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

inf=float('inf')

MOD=10**9+7

for _ in range(1):

    main()


import sys, random
input = lambda : sys.stdin.readline().rstrip()

write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x))
debug = lambda x: sys.stderr.write(x+"\n")
YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO); INF=10**18
LI = lambda : list(map(int, input().split())); II=lambda : int(input())
def debug(_l_):
    for s in _l_.split():
        print(f"{s}={eval(s)}", end=" ")
    print()
def dlist(*l, fill=0):
    if len(l)==1:
        return [fill]*l[0]
    ll = l[1:]
    return [dlist(*ll, fill=fill) for _ in range(l[0])]

T = II()
for ind in range(T):
    n,m = list(map(int, input().split()))
    c = LI()
    ns = [[] for _ in range(n)]
    for _ in range(m):
        u,v = LI()
        u -= 1
        v -= 1
        ns[v].append(u)
    d = {}
    for i in range(n):
        t = tuple(sorted(ns[i]))
        d.setdefault(t, []).append(i)
    ans = 0
    from math import gcd
    for k,v in d.items():
        if not k:
            continue
        val = sum((c[i] for i in v))
        ans = gcd(ans, val)
    print(ans)
    if ind==T-1:
        break
    LI()


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

n = int(input())

for i in range (0,n):

    check = 0

    a = int(input())

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

    d = max(lst)

    for i in lst:

        if (d - i)%2 != 0:

            check +=1

            break

    if check != 0:

        print("NO")

    else:

        print("YES")


q = int(input())

while q:

    w = int(input())

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

    t = a[0]%2

    for o in a:

        if(o%2!=t):

            t=2

            break

    if(t==2):

        print("NO")

    else:

        print("YES")

    q-=1


def solve():

    # process t test-cases

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

        # Read input list a and b

        n = int(input())

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

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

        # sort the lists

        a = sorted(a)

        b = sorted(b)

        # print the result

        print(*a)

        print(*b)

solve()


G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk.  The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1

import sys

import io, os

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

def main():

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

    edge = [[] for i in range(n)]

    ind = [0]*n

    toid = {}

    for i in range(n-1):

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

        x,y = x-1, y-1

        edge[x].append(y)

        edge[y].append(x)

        ind[x] += 1

        ind[y] += 1

        toid[(x, y)] = i

        toid[(y, x)] = i

    ind.sort()

    import bisect

    ng = 0

    ok = n-1

    while ng+1 < ok:

        c = (ng+ok)//2

        if n-bisect.bisect_left(ind, c+1) <= k:

            ok = c

        else:

            ng = c

    s = []

    s.append(0)

    par = [-1]*n

    order = []

    while s:

        v = s.pop()

        order.append(v)

        for u in edge[v]:

            if par[v] == u:

                continue

            s.append(u)

            par[u] = v

    ans = [-1]*(n-1)

    color = list(range(ok))

    for v in order:

        p = par[v]

        if par[v] != -1:

            color[ans[toid[(p, v)]]], color[-1] = color[-1], color[ans[toid[(p, v)]]]

            cnt = 0

            for u in edge[v]:

                if u == p:

                    continue

                ans[toid[(v, u)]] = color[cnt%ok]

                cnt += 1

            color[ans[toid[(p, v)]]], color[-1] = color[-1], color[ans[toid[(p, v)]]]

        else:

            cnt = 0

            for u in edge[v]:

                ans[toid[(v, u)]] = color[cnt%ok]

                cnt += 1

    print(ok)

    ans = [i+1 for i in ans]

    print(*ans)

if __name__ == '__main__':

    main()


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

from math import comb
n,m=map(int,input().split())
print(comb(n+2*m-1,2*m)%(10**9+7))


C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10

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

    n = int(input())

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

    lt = sorted(l)

    count = 0

    imp = False

    for k in range(2*n,0,-1):

        #print(lt[-1],k, "max et k")

        if lt[-1]<k:

            count+=1

        else:

            count-=1

            #print("SALUT", count)

            lt.pop()

        #print("COUNT VAUT:", count)

        if count<0: imp = True; break

    if imp: print(-1)

    else:

        rep = []

        s = set([k+1 for k in range(2*n)])

        for e in l: s.remove(e)

        l2 = sorted(list(s))

        for k in range(2*n):

            cur = l[k//2]

            if not k%2: rep.append(cur)

            else:

                for e in l2:

                    if e>cur: m =e; break

                rep.append(m)

                l2.pop(l2.index(m))

        print(*rep)


B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6].  |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0;  |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3;  |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3;  |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3;  |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.

# chalo shuru karte hai!

import sys

from math import *

from itertools import *

from heapq import heapify, heappop, heappush

from bisect import bisect, bisect_left, bisect_right

from collections import deque, Counter, defaultdict as dd

mod = 10**9+7

# Sangeeta Singh

def input(): return sys.stdin.readline().rstrip("\r\n")

def ri(): return int(input())

def rl(): return list(map(int, input().split()))

def rls(): return list(map(str, input().split()))

def isPowerOfTwo(x): return (x and (not(x & (x - 1))))

def lcm(x, y): return (x*y)//gcd(x, y)

def alpha(x): return ord(x)-ord('A')

def gcd(x, y):

    while y:

        x, y = y, x % y

    return x

def d2b(n):

    s = bin(n).replace("0b", "")

    return (34-len(s))*'0'+s

def highestPowerof2(x):

    x |= x >> 1

    x |= x >> 2

    x |= x >> 4

    x |= x >> 8

    x |= x >> 16

    return x ^ (x >> 1)

def isPrime(x):

    if x == 1:

        return False

    if x == 2:

        return True

    for i in range(2, int(x ** 0.5) + 1):

        if x % i == 0:

            return False

    return True

def factors(n):

    i = 1

    ans = []

    while i <= sqrt(n):

        if (n % i == 0):

            if (n / i != i):

                ans.append(int(n/i))

            if i != 1:

                ans.append(i)

        i += 1

    return ans

Primes = [1] * 100001

primeNos = []

def SieveOfEratosthenes(n):

    p = 2

    while (p * p <= n):

        if (Primes[p]):

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

                Primes[i] = 0

        p += 1

    for p in range(2, n+1):

        if Primes[p]:

            primeNos.append(p)

# SieveOfEratosthenes(100000)

# P = len(primeNos)

# print("P", P)

############ Main! #############

# for _ in range(1):

for _ in range(ri()):

    n = ri()

    a = rl()

    if a.count(-1) == n:

        print(0, 0)

        continue

    mn = inf

    mx = 0

    max_dif = 0

    for i in range(1, n):

        # print(a[i-1], a[i])

        if a[i-1] == -1 and a[i] != -1:

            mn = min(mn, a[i])

            mx = max(mx, a[i])

        elif a[i-1] != -1 and a[i] == -1:

            mn = min(mn, a[i-1])

            mx = max(mx, a[i-1])

        # print("min:", mn, "max:", mx)

    ans = (mx+mn)//2

    for i in range(n):

        if a[i] == -1:

            a[i] = ans

    # print(a)

    for i in range(1, n):

        max_dif = max(max_dif, abs(a[i]-a[i-1]))

    print(max_dif, ans)


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

def problem(s, p):
    for i in range(len(p)):
        l = p[:i] + ' '
        r = p[i:] + ' '

        dp = [0] + [None] * i

        for x in s:
            for j in range(i, -1, -1):
                if dp[j] is None:
                    continue

                if l[j] == x:
                    dp[j + 1] = dp[j] if dp[j + 1] is None else max(dp[j], dp[j + 1])

                temp = r[dp[j]]
                if r[dp[j]] == x:
                    dp[j] += 1

        if dp[-1] == len(r) - 1:
            return 'YES'

    return 'NO'

for _ in range(int(input())):
    print(problem(input(), input()))


C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab.  During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab.  During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab.  During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba.  During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows.  During the first move, remove the third character s3=s3= d, ss becomes bca.  During the second move, remove the second character s2=s2= c, ss becomes ba.  And during the third move, remove the first character s1=s1= b, ss becomes a.

import bisect

import collections

import heapq

import io

import math

import os

import sys

LO = 'abcdefghijklmnopqrstuvwxyz'

Mod = 1000000007

def gcd(x, y):

    while y:

        x, y = y, x % y

    return x

# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()

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

for _ in range(1):

    n = int(_input())

    a = list(map(ord, _input()))

    b = [[] for _ in range(128)]

    for i, x in enumerate(a):

        b[x].append(i)

    l = list(range(-1, n - 1))

    r = list(range(1, n + 1))

    c = 0

    for x in range(ord('z') - 1, ord('a') - 1, -1):

        for i in b[x]:

            i1 = l[i]

            while i1 >= 0 and a[i1] == a[i] + 1:

                l[i] = i1 = l[i1]

                if l[i] >= 0:

                    r[l[i]] = i

                c += 1

            i2 = r[i]

            while i2 < n and a[i2] == a[i] + 1:

                r[i] = i2 = r[i2]

                if r[i] < n:

                    l[r[i]] = i

                c += 1

    print(c)


D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0

n=int(input())

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

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

for i in range(n):

    a[i]-=b[i]

a.sort()

count=0

lastindex=n

pos=0

for i in range(n):

    if a[i]>0:

        pos+=1

    count+=n-lastindex

    if lastindex==0:

        continue

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

        if a[i]+a[j]<=0:

            lastindex=j+1

            break

        if j==0 and a[i]+a[j]>0:

            lastindex=0

count+=n-lastindex

print((count-pos)//2)


A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied:   All scores are integers  0≤ai≤m0≤ai≤m  The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105)  — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m)  — scores of the students.OutputFor each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.

for _ in range(int(input())):
    n, m = map(int, input().split())
    a = list(map(int, input().split()))
    print(min(m, sum(a)))


A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.

t = int(input())

for _ in range(t):

    n = int(input())

    print(1,n-1)


E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements:  The score of each problem should be a positive integer not exceeding 109109.  A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109.  The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution.   (1,2,3)(1,2,3)  (1,3,4)(1,3,4)  (2,4,5)(2,4,5)

import sys

reader = (line.rstrip() for line in sys.stdin)

input = reader.__next__

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

def limit(n):

    if n < 3:

        return 0

    if n ^ 1:

        return ((n - 1) * (n - 1)) >> 2

    else:

        return ((n - 2) * n) >> 2

if m > limit(n):

    print(-1)

    sys.exit()

elif not m:

    ans = [10 ** 8 + 1]

    while len(ans) < n:

        ans.append(ans[-1] + 10 ** 4)

    print(*ans)

    sys.exit()

L = 3

R = n + 1

while L + 1 < R:

    k = (L + R) >> 1

    if limit(k) > m:

        R = k

    else:

        L = k

k = L

ans = list(range(1, k + 1))

req = m - limit(k)

if req > 0:

    ans.append(ans[-1] + ans[-2 * req])

    k += 1

big_num = 10 ** 8 + 1

for i in range(k, n):

    ans.append(big_num)

    big_num += 10 ** 4

print(*ans)