B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.

strings = input()

left, right = 0, len(strings)-1

count = 0

ans=set()

while left < right:

    if strings[right] == "(":

        right-=1

    else:

        if strings[left] == "(":

            ans.add(right+1)

            ans.add(left+1)

            count+=1

            right-=1

            left+=1

    if strings[left] == ")":

        left+=1

if count:

    print(1)

    print(len(ans))

    ans = list(ans)

    ans.sort()

    print(*ans)

else:

    print(0)


B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

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

  n=int(input())

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

  s=sum(arr)

  a=0

  mini=0

  new=[]

  ans=1

  for i in range(n):

    a+=arr[i]

    if a<=0:

      ans=0

      break

    mini=min(a,mini)

    new.append(mini)

  summ=0

  if ans==0:

    print("no")

    continue

  # print(new)

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

    summ+=arr[i]

    # print(summ)

    if summ+new[i-1]<=0:

      ans=0

      break

  print("yes" if ans else "no")


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

import math

def inp(sa):

	b=[]

	j=0

	for i in range(len(sa)):

		if sa[i]==" ":

			b.append(int(sa[j:i]))

			j=i+1

	b.append(int(sa[j:]))

	return b

def iskpow(n,k):

	basek=[]

	i=0

	while n!=0:

		temp=n%k

		if temp>1:

			return 0

		if temp==1:

			basek.append(i)

		n=n//k

		i+=1

	return basek

t=int(input())

def lyans():

	temp=input()

	temp=inp(temp)

	k=temp[1]

	a=input()

	a=inp(a)

	listk=[]

	for i in a:

		if i==0:

			continue

		m=iskpow(i,k)

		if isinstance(m,list) :

			listk+=m

		else:

			print("NO")

			return 0

	if len(set(listk))==len(listk):

		print("YES")

	else:

		print("NO")

for ti in range(t):

	lyans()


C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move:   'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y);  'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y);  'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1);  'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1

t = int(input())

for _ in range(t):

    n = int(input())

    s = input()

    prefix = {(0, 0):-1}

    cur = [0, 0]

    max_len = float('inf')

    answer = [-1, -1]

    for idx, char in enumerate(s):

        if char == "U":

            cur[1] += 1

        elif char == "L":

            cur[0] -= 1

        elif char == "R":

            cur[0] += 1

        else:

            cur[1] -= 1

        key = tuple(cur)

        if key in prefix and idx - prefix[key]+1 < max_len:

            max_len = idx - prefix[key] + 1

            answer = [prefix[key]+1, idx]

        prefix[key] = idx

    if answer == [-1, -1]:

        print(-1)

    else:

        # print(max_len, answer)

        print(answer[0] + 1, answer[1] + 1)


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

#! /bin/env python3

# please follow ATshayu

def main():

    n = int(input())

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

    # solve

    ans = 0

    for i in range(n):

        l, r = i - 1, i + 1

        x = m[i]

        b = [int(1e9)]*1005

        b[i] = m[i]

        while l >= 0:

            b[l] = min(m[l], b[l+1])

            x += b[l]

            l -= 1

        while r < n:

            b[r] = min(m[r], b[r-1])

            x += b[r]

            r += 1

        if x > ans:

            ans = x

            a = b

    for i in range(n): print(a[i], end=' ')

main()


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

import sys

input = sys.stdin.buffer.readline

def process(X, V):

    n = len(X)

    A = []

    for i in range(n):

        A.append([X[i], V[i]])

    d = {}

    A1 = sorted(A)

    for i in range(n):

        xi, vi = A1[i]

        d[xi] = i

    A2 = sorted(A, key=lambda a:(a[1], a[0]))

    answer = 0

    S = 0

    for i in range(n):

        xi, vi = A1[i]

        answer+=(i*xi-S)

        S+=xi

    S2 = 0

    for i in range(n):

        x2, v2 = A2[i]

        i1 = d[x2]

        answer+=(i-i1)*x2

    return answer

n = int(input())

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

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

print(process(X, V))


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

t = int(input())

for _ in range(t):

    s = str(input())

    res = 0

    curr = 0

    flag = False

    for i in s:

        if i == "1" and not flag:

            flag = True

        elif i == "0" and flag:

            curr += 1

        elif i == "1":

            res += curr

            curr = 0

    print(res)


E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]:   if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2];  if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2];  if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this:   [1,2,3,4,5][1,2,3,4,5]  [3,1,2,4,5][3,1,2,4,5]  [5,3,1,2,4][5,3,1,2,4]  [1,5,3,2,4][1,5,3,2,4]  [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this:   [1,2,3,4][1,2,3,4]  [1,2,3,4][1,2,3,4]  [2,1,3,4][2,1,3,4]  [4,2,1,3][4,2,1,3]

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

a = [int(i) - 1 for i in input().split()]

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

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

for i in set(a):

    ans1[i] = 1

N = 1

while N < n + m: N <<= 1

st = [0 for i in range(N << 1)]

pos = [i + m for i in range(n)]

for i in range(n):

    st[i + N + m] = 1

for i in range(N - 1, 0, -1):

    st[i] = st[i << 1] + st[i << 1 | 1]

def up(i,v):

    i+=N

    st[i]=v

    i>>=1

    while(i>0):

        st[i]=st[i<<1]+st[i<<1|1]

        i>>=1

def qr(l,r=N):

    l+=N

    r+=N

    add=0

    while(l<r):

        if l&1:

            add+=st[l]

            l+=1

        if(r&1):

            add+=st[r]

            r-=1

        l>>=1

        r>>=1

    return add

for j in range(m):

    x = a[j]

    i = pos[x]

    ans2[x] = max(ans2[x], n - qr(i + 1))

    up(i, 0)

    pos[x] = m - 1 - j

    up(pos[x], 1)

for i in range(n):

    x = pos[i]

    ans2[i] = max(ans2[i], n - qr(x + 1))

for i in range(n):

    print(ans1[i], ans2[i])


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

# by the authority of GOD     author: manhar singh sachdev #

import os,sys

from io import BytesIO,IOBase

class SortedList:

    def __init__(self,iterable=None,_load=200):

        """Initialize sorted list instance."""

        if iterable is None:

            iterable = []

        values = sorted(iterable)

        self._len = _len = len(values)

        self._load = _load

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

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

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

        self._fen_tree = []

        self._rebuild = True

    def _fen_build(self):

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

        self._fen_tree[:] = self._list_lens

        _fen_tree = self._fen_tree

        for i in range(len(_fen_tree)):

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

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

        self._rebuild = False

    def _fen_update(self,index,value):

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

        if not self._rebuild:

            _fen_tree = self._fen_tree

            while index<len(_fen_tree):

                _fen_tree[index] += value

                index |= index+1

    def _fen_query(self,end):

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

        if self._rebuild:

            self._fen_build()

        _fen_tree = self._fen_tree

        x = 0

        while end:

            x += _fen_tree[end-1]

            end &= end-1

        return x

    def _fen_findkth(self,k):

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

        _list_lens = self._list_lens

        if k<_list_lens[0]:

            return 0,k

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

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

        if self._rebuild:

            self._fen_build()

        _fen_tree = self._fen_tree

        idx = -1

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

            right_idx = idx+(1<<d)

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

                idx = right_idx

                k -= _fen_tree[idx]

        return idx+1,k

    def _delete(self,pos,idx):

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

        _lists = self._lists

        _mins = self._mins

        _list_lens = self._list_lens

        self._len -= 1

        self._fen_update(pos,-1)

        del _lists[pos][idx]

        _list_lens[pos] -= 1

        if _list_lens[pos]:

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

        else:

            del _lists[pos]

            del _list_lens[pos]

            del _mins[pos]

            self._rebuild = True

    def _loc_left(self,value):

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

        if not self._len:

            return 0,0

        _lists = self._lists

        _mins = self._mins

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

        while lo+1<pos:

            mi = (lo+pos)>>1

            if value<=_mins[mi]:

                pos = mi

            else:

                lo = mi

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

            pos -= 1

        _list = _lists[pos]

        lo,idx = -1,len(_list)

        while lo+1<idx:

            mi = (lo+idx)>>1

            if value<=_list[mi]:

                idx = mi

            else:

                lo = mi

        return pos,idx

    def _loc_right(self,value):

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

        if not self._len:

            return 0,0

        _lists = self._lists

        _mins = self._mins

        pos,hi = 0,len(_lists)

        while pos+1<hi:

            mi = (pos+hi)>>1

            if value<_mins[mi]:

                hi = mi

            else:

                pos = mi

        _list = _lists[pos]

        lo,idx = -1,len(_list)

        while lo+1<idx:

            mi = (lo+idx)>>1

            if value<_list[mi]:

                idx = mi

            else:

                lo = mi

        return pos,idx

    def add(self,value):

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

        _load = self._load

        _lists = self._lists

        _mins = self._mins

        _list_lens = self._list_lens

        self._len += 1

        if _lists:

            pos,idx = self._loc_right(value)

            self._fen_update(pos,1)

            _list = _lists[pos]

            _list.insert(idx,value)

            _list_lens[pos] += 1

            _mins[pos] = _list[0]

            if _load+_load<len(_list):

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

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

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

                _list_lens[pos] = _load

                del _list[_load:]

                self._rebuild = True

        else:

            _lists.append([value])

            _mins.append(value)

            _list_lens.append(1)

            self._rebuild = True

    def discard(self,value):

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

        _lists = self._lists

        if _lists:

            pos,idx = self._loc_right(value)

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

                self._delete(pos,idx-1)

    def remove(self,value):

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

        _len = self._len

        self.discard(value)

        if _len==self._len:

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

    def pop(self,index=-1):

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

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

        value = self._lists[pos][idx]

        self._delete(pos,idx)

        return value

    def bisect_left(self,value):

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

        pos,idx = self._loc_left(value)

        return self._fen_query(pos)+idx

    def bisect_right(self,value):

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

        pos,idx = self._loc_right(value)

        return self._fen_query(pos)+idx

    def count(self,value):

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

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

    def __len__(self):

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

        return self._len

    def __getitem__(self,index):

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

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

        return self._lists[pos][idx]

    def __delitem__(self,index):

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

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

        self._delete(pos,idx)

    def __contains__(self,value):

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

        _lists = self._lists

        if _lists:

            pos,idx = self._loc_left(value)

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

        return False

    def __iter__(self):

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

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

    def __reversed__(self):

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

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

    def __repr__(self):

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

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

def dfs(root,path,ans,n):

    st = [root]

    nums = SortedList(range(1,n+1))

    lst = [-1]*n

    cou = 0

    val = [-1]*n

    if ans[st[-1]] >= len(nums):

        print('NO')

        return

    val[st[-1]-1] = nums[ans[st[-1]]]

    nums.discard(nums[ans[st[-1]]])

    lst[st[-1]-1] = cou

    cou += 1

    while len(st):

        if not len(path[st[-1]]):

            y,z = 0,st[-1]-1

            for j in range(n):

                if lst[j] > lst[z] and val[j] < val[z]:

                    y += 1

            if y != ans[z+1]:

                print('NO')

                return

            st.pop()

            continue

        st.append(path[st[-1]].pop())

        if ans[st[-1]] >= len(nums):

            print('NO')

            return

        val[st[-1]-1] = nums[ans[st[-1]]]

        nums.discard(nums[ans[st[-1]]])

        lst[st[-1]-1] = cou

        cou += 1

    if val.count(-1):

        print('NO')

    else:

        print('YES')

        print(*val)

def main():

    n = int(input())

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

    ans = [0]*(n+1)

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

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

        if p:

            path[p].append(i)

        else:

            root = i

        ans[i] = c

    dfs(root,path,ans,n)

#Fast IO Region

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


A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.

import sys

input = sys.stdin.readline

n = int(input())

s = input()[:-1]

c = 0

d, e = 0, -1

ans = 0

for i in range(n):

    if s[i] == '(':

        c += 1

    else:

        c -= 1

    if d == 0 and c < 0:

        d = 1

        e = i

    elif d == 1 and c >= 0:

        d = 0

        ans += i - e + 1

        e = -1

if e != -1:

    ans += n-e

if c == 0:

    print(ans)

else:

    print(-1)


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.

from sys import stdin

input = stdin.readline

inp = lambda : list(map(int,input().split()))

from collections import deque

"""

it is obv that two vertices are the end points of the tree diameter

we can try all third vertices

"""

def dfs(p , want_update):

    s = [[p , -1 , 0]]

    best = -1

    while(len(s)):

        p , prev , lvl = s.pop()

        if(want_update):

            parent[p] = prev

            level[p] = lvl

        if(best < lvl):

            best = lvl

            node = p

        for i in child[p]:

            if(i == prev):continue

            if(done[i]):continue

            s.append([i , p , lvl + 1])

    return [node , best]

def chain(u , v):

    if(level[u] > level[v]):

        v , u = u , v

    d = level[v] - level[u]

    for i in range(d):

        done[v] = True

        v = parent[v]

    while(u != v):

        done[u] = True

        done[v] = True

        u = parent[u]

        v = parent[v]

    done[u] = True

for T in range(1):

    n = int(input())

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

    for i in range(n - 1):

        u , v = inp()

        child[u].append(v)

        child[v].append(u)

    done = [False for i in range(n + 1)]

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

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

    a , dist = dfs(1 , True)

    b , dist = dfs(a , False)

    chain(a , b)

    best = -1

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

        if(not done[i]):continue

        node , d = dfs(i , False)

        if(node == i):continue

        total = dist + d

        if(best < total):

            best = total

            c = node

    if(best == -1):

        best = dist

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

            if(i != a and i != b):

                c = i

                break

    print(best)

    print(a , b , c)


C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1

n=int(input());x=[0]

for i in input().split():x+=x[-1]+int(i),

m=min(x)

print(*([-1],[i-m+1 for i in x])[set(x)==set(range(m,m+n))])


A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single 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 string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.

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

    a = input()

    b = input()

    c = input()

    for i in range(len(a)):

        if c[i] not in (a[i], b[i]):

            print("NO")

            break

    else:

        print("YES")


E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).  Possible paths for the queries with "YES" answers are:   11-st query: 11 – 33 – 22  22-nd query: 11 – 22 – 33  44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33

import sys

# Testing out some really weird behaviours in pypy

class RangeQuery:

    def __init__(self, data, func=min):

        self.func = func

        self._data = _data = [list(data)]

        i, n = 1, len(_data[0])

        while 2 * i <= n:

            prev = _data[-1]

            _data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])

            i <<= 1

    def query(self, begin, end):

        depth = (end - begin).bit_length() - 1

        return self.func(self._data[depth][begin], self._data[depth][end - (1 << depth)])

class LCA:

    def __init__(self, root, graph):

        self.time = [-1] * len(graph)

        self.path = [-1] * len(graph)

        P = [-1] * len(graph)

        t = -1

        dfs = [root]

        while dfs:

            node = dfs.pop()

            self.path[t] = P[node]

            self.time[node] = t = t + 1

            for nei in graph[node]:

                if self.time[nei] == -1:

                    P[nei] = node

                    dfs.append(nei)

        self.rmq = RangeQuery(self.time[node] for node in self.path)

    def __call__(self, a, b):

        if a == b:

            return a

        a = self.time[a]

        b = self.time[b]

        diff = ((b - a) >> 31) & (b - a)

        a += diff

        b -= diff

        return self.path[self.rmq.query(a, b)]

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0

n = inp[ii]; ii += 1

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

for _ in range(n - 1):

    u = inp[ii] - 1; ii += 1

    v = inp[ii] - 1; ii += 1

    coupl[u].append(v)

    coupl[v].append(u)

root = 0

lca = LCA(root, coupl)

depth = [-1]*n

depth[root] = 0

bfs = [root]

for node in bfs:

    for nei in coupl[node]:

        if depth[nei] == -1:

            depth[nei] = depth[node] + 1

            bfs.append(nei)

def dist(a,b):

    for _ in range(0): pass

    c = lca(a,b)

    return depth[a] + depth[b] - 2 * depth[c]

q = inp[ii]; ii += 1

out = []

for _ in range(q):

    x = inp[ii] - 1; ii += 1

    y = inp[ii] - 1; ii += 1

    a = inp[ii] - 1; ii += 1

    b = inp[ii] - 1; ii += 1

    k = inp[ii]; ii += 1

    dists = [dist(a,b), dist(a,x) + dist(y,b) + 1, dist(a,y) + dist(x,b) + 1]

    #dist(a,b) + dist(b,x) # this line makes everything 2 s faster for no reason

    for d in dists:

        if d - k & 1 == 0 and d <= k:

            out.append('YES')

            break

    else:

        out.append('NO')

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


C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.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 nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823

#bisect.bisect_left(a, x, lo=0, hi=len(a)) is the analog of std::lower_bound()

#bisect.bisect_right(a, x, lo=0, hi=len(a)) is the analog of std::upper_bound()

#from heapq import heappop,heappush,heapify #heappop(hq), heapify(list)

#from collections import deque as dq #deque  e.g. myqueue=dq(list)

#append/appendleft/appendright/pop/popleft

#from bisect import bisect as bis #a=[1,3,4,6,7,8] #bis(a,5)-->3

#import bisect #bisect.bisect_left(a,4)-->2 #bisect.bisect(a,4)-->3

#import statistics as stat  # stat.median(a), mode, mean

#from itertools import permutations(p,r)#combinations(p,r)

#combinations(p,r) gives r-length tuples #combinations_with_replacement

#every element can be repeated

import sys, threading, os, io

import math

import time

from os import path

from collections import defaultdict, Counter, deque

from bisect import *

from string import ascii_lowercase

from functools import cmp_to_key

import heapq

from bisect import bisect_left as lower_bound

from bisect import bisect_right as upper_bound

from io import BytesIO, IOBase

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

#       JAI SHREE RAM         #

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

def lcm(a, b):

    return (a*b)//(math.gcd(a,b))

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

)

def lmii():

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

def ii():

    return int(input())

def si():

    return str(input())

def lmsi():

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

def mii():

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

def msi():

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

i2c = lambda n: chr(ord('a') + n)

c2i = lambda c: ord(c) - ord('a')

# if(os.path.exists("/Users/nitishkumar/Documents/Template_Codes/Python/CP/Codeforces/input.txt")):

#     sys.stdin = open("/Users/nitishkumar/Documents/Template_Codes/Python/CP/Codeforces/input.txt", 'r')

#     sys.stdout = open("/Users/nitishkumar/Documents/Template_Codes/Python/CP/Codeforces/output.txt", 'w')

# else:

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

## ayush chabra's solution, better and shorter than mine

import math

def solve(t):

    n=ii()

    ans=[]

    for ele in range(2,int(math.sqrt(n))+1):

        if len(ans)==2:

            break

        if n%ele==0:

            n=n//ele

            ans.append(ele)

    ans.append(n)

    if len(ans)==3 and len(set(ans))==3:

        print("Yes")

        print(*ans)

    else:

        print("No")

def main():

    t = 1

    if path.exists("/Users/nitishkumar/Documents/Template_Codes/Python/CP/Codeforces/input.txt"):

        sys.stdin = open("/Users/nitishkumar/Documents/Template_Codes/Python/CP/Codeforces/input.txt", 'r')

        sys.stdout = open("/Users/nitishkumar/Documents/Template_Codes/Python/CP/Codeforces/output.txt", 'w')

        start_time = time.time()

        print("--- %s seconds ---" % (time.time() - start_time))

    sys.setrecursionlimit(10**5)

    t = int(input())

    for i in range(t):

        solve(i+1)

if __name__ == '__main__':

    main()


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

for i in range(int(input())):
    n=int(input())
    l=[]
    for j in range(n):
        l.append(tuple(map(int,input().split())))
    l.sort()
    for j in range(n-1):
        if l[j][1]>l[j+1][1]:
            print("NO")
            break
    else:
        s="R"*l[0][0]+"U"*l[0][1]
        for j in range(1,n):
            s+="R"*(l[j][0]-l[j-1][0])+"U"*(l[j][1]-l[j-1][1])
        print("YES")
        print(s)


C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1

from collections import Counter

import math

n = int(input())

num = Counter()

ans = 0

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

    if n % i == 0:

        num[i] = n // i

re = num.most_common()

re.reverse()

for i in re:

    if math.gcd(i[0], i[1]) == 1:

        print(*i)

        break


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

from collections import deque

def f():

  global a, n

  l = [0 for i in range(n)]

  q = deque()

  for i in range(n):

    while(len(q) and a[q[-1]] >= a[i]):

      q.pop()

    if(not len(q)):

      l[i] = (i+1)*a[i]

    else:

      l[i] = (i-q[-1])*a[i] + l[q[-1]]

    q.append(i)

  return l

n = int(input())

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

l = f()

a.reverse()

r = f()

a.reverse()

r.reverse()

mx = max([_ for _ in range(0,n)], key=lambda i: l[i]+r[i]-a[i])

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

  a[i] = min(a[i],a[i+1])

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

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

print(*a)


A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":   "A" corresponds to an angry student  "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is:   after 11 minute — AAPAAPPAAPPP  after 22 minutes — AAAAAAPAAAPP  after 33 minutes — AAAAAAAAAAAP  after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.

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

	input()

	s = input().lstrip('P')

	print(max(map(len, s.split('A'))))


E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.

n,h,l,r = list(map(int,input().split()))

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

total = 0

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

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

    total += a[i - 1]

    total %= h

    dp[i][0] = int(total >= l and total <= r) + dp[i - 1][0]

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

        dp[i][j] = max(dp[i - 1][j],dp[i - 1][j - 1]) + int((total - j)%h >= l and (total - j)%h <= r)

print(max(dp[-1]))


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

import sys, collections, math, bisect, heapq, random, functools

input = sys.stdin.readline

out = sys.stdout.flush

def solve():

    n = int(input())

    left = input().rstrip('\n')

    right = input().rstrip('\n')

    c1,c2 = collections.defaultdict(list),collections.defaultdict(list)

    c1i,c2i = [],[]

    for i in range(n):

        c11 = left[i]

        c22 = right[i]

        if c11 == '?':

            c1i.append(i + 1)

        else:

            c1[c11].append(i + 1)

        if c22 == '?':

            c2i.append(i + 1)

        else:

            c2[c22].append(i + 1)

    ans = []

    for c in c1:

        while c1[c] and c2[c]:

            l,r = c1[c].pop(-1),c2[c].pop(-1)

            ans.append([l,r])

        if c1[c]:

            while c1[c] and c2i:

                l,r = c1[c].pop(-1), c2i.pop(-1)

                ans.append([l, r])

    for c in c2:

        while c1[c] and c2[c]:

            l,r = c1[c].pop(-1),c2[c].pop(-1)

            ans.append([l,r])

        if c2[c]:

            while c2[c] and c1i:

                r,l = c2[c].pop(-1), c1i.pop(-1)

                ans.append([l, r])

    posa,posb = [],[]

    for c in c1:

        posa.extend(c1[c])

    for c in c2:

        posb.extend(c2[c])

    while c1i:

        if not posb and not c2i:

            break

        while c1i and posb:

            l,r = c1i.pop(-1),posb.pop(-1)

            ans.append([l,r])

        while c1i and c2i:

            l,r = c1i.pop(-1),c2i.pop(-1)

            ans.append([l,r])

    while c2i:

        if not posa and not c1i:

            break

        while c2i and posa:

            r,l = c2i.pop(-1),posa.pop(-1)

            ans.append([l,r])

        while c1i and c2i:

            l,r = c1i.pop(-1),c2i.pop(-1)

            ans.append([l,r])

    print(len(ans))

    for l,r in ans:

        print(l,r)

if __name__ == '__main__':

        solve()


import sys, collections, math, bisect, heapq

input = sys.stdin.readline

n = int(input())

edges = collections.defaultdict(list)

for i in range(n - 1):

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

    edges[u].append(v)

    edges[v].append(u)

# 找到树的直径

def bfs1():

    queue = collections.deque()

    node1,dis1,node2,dis2 = 0,-1,0,-1

    queue.append([1,0])

    vis = {1}

    while queue:

        cur,d = queue.popleft()

        if dis1 < d:

            dis1 = d

            node1 = cur

        for next_ in edges[cur]:

            if next_ not in vis:

                vis.add(next_)

                queue.append([next_,d + 1])

    vis.clear()

    queue.append([node1,0])

    vis.add(node1)

    while queue:

        cur,d = queue.popleft()

        if dis2 < d:

            dis2 = d

            node2 = cur

        for next_ in edges[cur]:

            if next_ not in vis:

                vis.add(next_)

                queue.append([next_,d + 1])

    return node1,node2,dis2

node1,node2,diameter = bfs1()

# bfs找到距离最远的点

def bfs2(u):

    queue = collections.deque()

    dis = [-1] * n

    dis[u - 1] = 0

    queue.append([u,0])

    while queue:

        cur,d = queue.popleft()

        for next_ in edges[cur]:

            if dis[next_ - 1] == -1:

                dis[next_ - 1] = d + 1

                queue.append([next_,d + 1])

    return dis

c1,c2 = bfs2(node1),bfs2(node2)

# 枚举中间点

node3 = -1

dis = 0

for i in range(n):

    if i + 1 == node1 or i + 1 == node2:

        continue

    temp = c1[i] + c2[i]

    if temp > dis:

        dis = temp

        node3 = i + 1

print((diameter + dis) // 2)

print(node1,node2,node3)


A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES

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

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

    mx=max(a,b)

    mx=max(mx,c)

    n-=(3*mx)-(a+b+c)

    if n<0:

        print('NO')

        continue

    elif n%3==0:

        print("YES")

    else:

        print("NO")


import os

import sys

from io import BytesIO, IOBase

MOD0 = 10 ** 9 + 7

MOD1 = 998244353

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

read_str = lambda: input().strip()

read_int = lambda: int(input())

read_ints = lambda: map(int, input().split())

read_list = lambda: list(map(int, input().split()))

import math

def solve():

    n, h, l, r = read_ints()

    nums = read_list()

    dp = [-math.inf]*h

    dp[nums[0]] = 1 if l<=nums[0]<=r else 0

    dp[nums[0]-1] = 1 if l<=nums[0]-1<=r else 0

    for i in range(1, n):

        tmp_dp = [-math.inf]*h

        for j, v in enumerate(dp):

            if v==-math.inf:

                continue

            idx = (j+nums[i])%h

            tmp = v+1 if l <= idx <= r else v

            if tmp > tmp_dp[idx]:

                tmp_dp[idx] = tmp

            idx = (j+nums[i]-1)%h

            tmp = v+1 if l <= idx <= r else v

            if tmp > tmp_dp[idx]:

                tmp_dp[idx] = tmp

        dp = tmp_dp

    print(max(dp))

solve()


C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets:   a occurs at (1)(1), (2)(2), (3)(3)  b occurs at (4)(4), (5)(5)  ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5)  aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3)  bb occurs at (4,5)(4,5)  aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4)  aaa occurs at (1,2,3)(1,2,3)  abb occurs at (3,4,5)(3,4,5)  aaab occurs at (1,2,3,4)(1,2,3,4)  aabb occurs at (2,3,4,5)(2,3,4,5)  aaabb occurs at (1,2,3,4,5)(1,2,3,4,5)  Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.

# watchu lookin at?

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

abc = "abcdefghijklmnopqrstuvwxyz"

# 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 nextPowerOf2(N):

    if not (N & (N - 1)):

        return N

    return int("1" + (len(bin(N)) - 2) * "0", 2)

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)

def ncr(n, r):

    ans = 1

    while(r):

        ans *= n

        ans %= mod

        n -= 1

        r -= 1

    return ans

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

# mod = 998244353

def sangee():

    s = input()

    d = dd(int)

    for i in s:

        for a in abc:

            d[a+i] += d[a]

        d[i] += 1

    # print(d)

    print(max(d.values()))

t = 1

for _ in range(t):

    sangee()


n,h,l,r = list(map(int,input().split()))

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

total = 0

dp = [[-10**9]*(n + 1) for _ in range(n + 1)]

dp[0][0] = 0

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

    total += a[i - 1]

    total %= h

    dp[i][0] = int(total >= l and total <= r) + dp[i - 1][0]

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

        dp[i][j] = max(dp[i - 1][j],dp[i - 1][j - 1]) + int((total - j)%h >= l and (total - j)%h <= r)

print(max(dp[-1]))


D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.

[u,v]=list(map(int,input().split(" ")))

if u==0 and v==0:

  print(0)

elif u>v or u%2!=v%2:

  print(-1)

elif u==v:

  print(1)

  print(v)

else:

  t=(v-u)//2

  if t&u:

    print(3)

    print(str(t)+" "+str(t)+" "+str(u))

  else:

    print(2)

    print(str(t)+" "+str(t+u))


B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.

from sys import stdin, stdout
def get_ints(): return map(int, stdin.readline().split())
def PRINT(s): stdout.write(s + '\n')
# n = int(stdin.readline())
# arr = [int(x) for x in stdin.readline().split()]

def logic(s):
    try:
        l = s.index('(')
        r = s.rindex(')')
    except:
        PRINT('0')
        return
    if l >= r:
        PRINT('0')
        return
    L = [l]
    R = [r]
    n = 2
    while True:
        # find the next positions of l and r
        l += 1
        while l < len(s) and s[l] != '(':
            l += 1
        r -= 1
        while r > 0 and s[r] != ')':
            r -= 1
        if l >= r:
            break
        L.append(l)
        R.append(r)
        n += 2
    PRINT('1')
    PRINT(str(n))
    PRINT(' '.join([str(x+1) for x in L]) + ' ' + ' '.join([str(x+1) for x in R[::-1]]))
    #return L + R[::-1]

s = stdin.readline()[:-1]

logic(s)

##import random as r
##for k in range(10000):
##    s = ''
##    for i in range(200):
##        s += r.choice(['(',')'])
##    res = logic(s)
##    S = ''
##    for i in range(len(s)):
##        if i not in res:
##            S += s[i]
##
##    if logic(S) != None:
##        print('issue')
##        print(s,S)


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

def solve():

    # First we'd like to get the number of test cases that we'd like to run

    t = int(input())

    # Now let's run a loop to get the input for each testcase

    for i in range(t):

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

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

        positions = list(

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

        )  # these positions would help us sorting the array

        positions.sort()

        # If an array can be sorted it can be sorted in n steps

        for _ in range(n):

            for p in positions:

                if a[p - 1] > a[p]:

                    a[p - 1], a[p] = a[p], a[p - 1]

        if a == sorted(a):

            print("YES")

        else:

            print("NO")

solve()