C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use:   fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

import sys, os

input = sys.stdin.buffer.readline

n = int(input())

a, b = "?".encode(), "!".encode()

if n == 1:

    os.write(1, b"%s %d %d\n" % (a, 1, 1))

    s = input().rstrip().decode()

    ans = ("! " + s).encode()

    os.write(1, b"%s\n" % ans)

    exit()

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

os.write(1, b"%s %d %d\n" % (a, 1, n))

for _ in range(n * (n + 1) // 2):

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

    c = cnt1[len(s)]

    for i in s:

        c[i - 97] += 1

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

os.write(1, b"%s %d %d\n" % (a, 1, n - 1))

for _ in range(n * (n - 1) // 2):

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

    c = cnt2[len(s)]

    for i in s:

        c[i - 97] += 1

ans = [-1] * n

c1, c2 = cnt1[n], cnt2[n - 1]

for i in range(26):

    if c1[i] ^ c2[i]:

        ans[-1] = i

        break

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

    x = [min(j + 1, n - j, i) for j in range(n)]

    c = cnt1[i]

    for j in range(n):

        if ans[j] ^ -1:

            c[ans[j]] -= x[j]

    for j in range(26):

        if c[j] % i:

            ans[i - 2] = j

            break

    x = [min(j + 1, n - 1 - j, i) for j in range(n - 1)]

    c = cnt2[i]

    for j in range(n - 1):

        if ans[j] ^ -1:

            c[ans[j]] -= x[j]

    for j in range(26):

        if c[j] % i:

            ans[-i] = j

            break

if not n % 2:

    c = cnt1[n]

    for i in ans:

        if i ^ -1:

            c[i] -= 1

    for i in range(26):

        if c[i]:

            ans[n // 2 - 1] = i

            break

ans = ("! " + "".join(chr(i + 97) for i in ans)).encode()

os.write(1, b"%s\n" % ans)

exit()


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.

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

def solve():

    n, h, l, r = read_ints()

    nums = read_list()

    dp = [0] * (n + 1)

    pres = 0

    for i in range(n):

        pres += nums[i]

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

            if j and dp[j - 1] > dp[j]:

                dp[j] = dp[j - 1]

            if l <= (pres - j) % h <= r:

                dp[j] += 1

    print(max(dp))

solve()


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.

import os

os.system("cls")  # clear screen

t = int(input())

for T in range(t):

    n = int(input())

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

    parity = arr[0] % 2

    answer = "YES"

    for x in arr:

        if x % 2 != parity:

            answer = "NO"

            break

    print(answer)


F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way:   On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days.  On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days.  If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1:   Example 2:   Example 3:   Example 4:

import sys, os, io

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

def sparse_table(a):

    table = []

    s0, l = a, 1

    table.append(s0)

    while 2 * l <= len(a):

        s = [max(s0[i], s0[i + l]) for i in range(len(s0) - l)]

        table.append(list(s))

        s0 = s

        l *= 2

    return table

def get_max(l, r, table):

    d = len(bin(r - l + 1)) - 3

    ans = max(table[d][l], table[d][r - pow2[d] + 1])

    return ans

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

s = []

for _ in range(n):

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

    u = [0]

    for i in s0:

        u.append(u[-1] + i)

    s.append(u)

s.append([0] * (m + 1))

l = m - k + 1

dp0 = [0] * l

s0, s1 = s[0], s[1]

for i in range(l):

    dp0[i] = s0[i + k] + s1[i + k] - s0[i] - s1[i]

s0 = s[1]

pow2 = [1]

for _ in range(20):

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

for i in range(1, n):

    s1 = s[i + 1]

    dp = [0] * l

    table = sparse_table(dp0)

    for j in range(l):

        c = s0[j + k] + s1[j + k] - s0[j] - s1[j]

        dpj = 0

        for u in range(max(0, j - k + 1), min(l, j + k)):

            x, y = max(j, u), min(j, u) + k

            dpj = max(dpj, dp0[u] + c - s0[y] + s0[x])

        if j - k >= 0:

            dpj = max(dpj, get_max(0, j - k, table) + c)

        if j + k <= l - 1:

            dpj = max(dpj, get_max(j + k, l - 1, table) + c)

        dp[j] = dpj

    dp0 = dp

    s0 = s1

ans = max(dp0)

print(ans)


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

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

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

    ld, rd = 0, n * (n - 1) // 2

    tn = n

    cd = 0

    mvl = 1

    while tn:

        vl = min(tn, mvl)

        ld += cd * vl

        cd += 1

        tn -= vl

        mvl *= 2

    if not (ld <= d <= rd):

        print('NO')

        continue

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

    bad = [False] * n

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

    child = [1] * n

    child[-1] = 0

    cur = rd

    while cur > d:

        v = None

        for i in range(n):

            if not bad[i] and not child[i] and (v is None or deep[i] < deep[v]):

                v = i

        p = None

        for i in range(n):

            if child[i] < 2 and deep[i] < deep[v] - 1 and (p is None or deep[i] > deep[p]):

                p = i

        if p is None:

            bad[v] = True

        else:

            child[parent[v]] -= 1

            deep[v] -= 1

            child[p] += 1

            parent[v] = p

            cur -= 1

    print('YES')

    print(*map(lambda x: x + 1, parent[1:]))


C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way:  At 00-th minute, change the state to heating (the temperature is 0).  At 22-nd minute, change the state to off (the temperature is 2).  At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied).  At 66-th minute, change the state to off (the temperature is 3).  At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied).  At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.

T = int (input())

for test in range (T):

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

    repost = list()

    time = dict ()

    scad = list()

    for reservation in range (n):

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

        if t in time.keys():

            old = repost[time[t]]

            l = max (old[0],l)

            r= min (old[1],r)

            repost.append([l,r])

            ind = int (len(repost)-1)

            time.update({t:ind})

        else:

            repost.append([l,r])

            ind = int (len(repost)-1)

            time.update({t:ind})

            scad.append(t)

    scad.sort()

    past_time= 0

    past_range = [m,m]

    ok = True

    for t in scad :

        nowRang= [past_range[0]-  abs  (t-past_time),past_range[1] +abs (t-past_time) ]

        thistine = repost[time[t]]

        now =[max (nowRang[0],thistine[0]), min (nowRang[1],thistine[1])]

        ok &= now[1]>=now[0]

        past_range = now

        past_time =t

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


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

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

    n = int((input()))

    s = input()

    cur = (0, 0)

    dic = {(0, 0): 0}

    l, r = -1, n

    for i, a in enumerate(s):

      f, s = cur

      if a == 'L':

        cur = (f - 1, s)

      if a == 'R':

        cur = (f + 1, s)

      if a == 'U':

        cur = (f, s + 1)

      if a == 'D':

        cur = (f, s - 1)

      if cur in dic:

        if i - dic[cur] + 1 < r - l + 1:

          l, r = dic[cur], i

      dic[cur] = i + 1

    if l == -1:

      print(-1)

    else:

      print(l + 1, r + 1)


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

print(sum([1/i for i in range(1,int(input())+1)]))


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

import sys
from itertools import permutations

"""
1 1
2 6
3 32
4 180
5 1116
6 7728
7 59904
8 518400
"""

def solve(N, M):
    ans = 0
    for perm in permutations(range(N)):
        for l in range(N):
            for r in range(N):
                mn = 1e18
                mx = -1e18
                for i in range(l, r+1):
                    mn = min(perm[i], mn)
                    mx = max(perm[i], mx)
                if mx-mn == r-l:
                    ans += 1
                    ans %= M
    return ans

def solve2(N, M):
    # n!/(n P i) = n!/(n!/(n-i)!) = (n-i)!
    fact = [1]
    for i in range(1, N+1):
        fact.append((fact[-1]*i) % M)
    ans = (N*fact[N]) % M
    for len in range(2, N+1):
        tmp = N-len+1
        tmp *= fact[N-len]
        tmp %= M
        tmp *= N-len+1
        tmp %= M
        tmp *= fact[len]
        tmp %= M
        ans += tmp
        if ans >= M: ans -= M
    return ans

toks = sys.stdin.read().split()
N = int(toks[0])
M = int(toks[1])
print(solve2(N, M))


D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules:  He starts at the top-left cell in the grid;  In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to:   in the case 'U' to the cell (i−1,j)(i−1,j);  in the case 'D' to the cell (i+1,j)(i+1,j);  in the case 'L' to the cell (i,j−1)(i,j−1);  in the case 'R' to the cell (i,j+1)(i,j+1);   He wants to run exactly kk kilometers, so he wants to make exactly kk moves;  Bashar can finish in any cell of the grid;  He can't go out of the grid so at any moment of the time he should be on some cell;  Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):

import sys
input = sys.stdin.readline
import math
import copy
import collections
from collections import deque

def solve(ans):
    print(len(ans))
    for ele in ans:
        print(ele[0],ele[1])

n,m,k = map(int,input().split())
count = 0
ans = []
if 4*n*m-2*n-2*m<k:
    print("NO")
elif n==1:
    print("YES")
    if m-1>=k:
        ans.append([k,'R'])
        solve(ans)
        quit()
    else:
        ans.append([m-1,'R'])
        k-=m-1
    ans.append([k,'L'])
    solve(ans)
elif m==1:
    print("YES")
    if n-1>=k:
        ans.append([k,'D'])
        solve(ans)
        quit()
    else:
        ans.append([n-1,'D'])
        k-=n-1
    ans.append([k,'U'])
    solve(ans)
else:
    print("YES")
    if n-1>=k:
        ans.append([k,'D'])
        solve(ans)
        quit()
    else:
        k-=n-1
        count+=1
        ans.append([n-1,'D'])
    row = n-1
    while row>0:
        if m-1>=k:
            ans.append([k,'R'])
            solve(ans)
            quit()
        else:
            k-=m-1
            count+=1
            ans.append([m-1,'R'])
        if m-1>=k:
            ans.append([k,'L'])
            solve(ans)
            quit()
        else:
            k-=m-1
            count+=1
            ans.append([m-1,'L'])
        count+=1
        ans.append([1,'U'])
        k-=1
        if k==0:
            solve(ans)
            quit()
        row-=1
    col = 0
    while col<m-1:
        col+=1
        count+=1
        ans.append([1,'R'])
        k-=1
        if k==0:
            solve(ans)
            quit()
        if n-1>=k:
            ans.append([k,'D'])
            solve(ans)
            quit()
        else:
            count+=1
            k-=n-1
            ans.append([n-1,'D'])
        if n-1>=k:
            ans.append([k,'U'])
            solve(ans)
            quit()
        else:
            count+=1
            k-=n-1
            ans.append([n-1,'U'])
    count+=1
    ans.append([k,'L'])
    solve(ans)


A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — 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≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO

t = int(input())

for i in range(t):

    n = int(input())

    number = (input().split())

    ans = 0

    for x in number:

        if int(x) % 2 == 0:

            ans += 1

    if (ans == n) or (ans == 0 and n % 2 == 0):

        print("NO")

    else:

        print("YES")


A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.

import sys

import math

import bisect

import heapq

import string

from collections import defaultdict,Counter,deque

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

def WRITE(out):

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

def WS(out):

  return print(' '.join(map(str, out)))

def WNS(out):

  return print(''.join(map(str, out)))

'''

b > a

gcd(b,a) == 1

n = 1000

b => (2,n+1)

    a = n-b

        if gcd(a,b) == 1:

            cnt += 1

print(cnt)

6

1 5

2 4 x

x x x x x

x x x x x

x x x x x

x x x x x

x x x x x

x x x x x

x x x x x

x x x x x

x x ! x x

x x x x x

'''

# sys.stdin = open("backforth.in", "r")

# sys.stdout = open("backforth.out", "w")

input = sys.stdin.readline

directions = [[-1,-1],[-1,1],[1,-1],[1,1]]

def isCross(i,j,grid):

    for di, dj in directions:

        if grid[i+di][j+dj] != 'X':

            return False

    return True

def solve():

    t = II()

    for _ in range(t):

        a,b,x,y = MII()

        all_rows = max(b * x, b * (a - x - 1))

        all_cols = max(a * y, a * (b - y - 1))

        print(max(all_rows, all_cols))

solve()


import sys

input = sys.stdin.buffer.readline

def convert(s):

    answer = [0 for i in range(26)]

    for c in s:

        answer[ord(c)-ord('a')]+=1

    return answer

def string_apply(t1, t2, f):

    answer = [f(t1[i], t2[i]) for i in range(26)]

    return answer

def convert2(t):

    if max(t)==1 and min(t)==0 and sum(t)==1:

        for i in range(26):

            if t[i]==1:

                return chr(i+ord('a'))

    return -1

def process(n):

    L = []

    sys.stdout.write(f'? 1 {n}\n')

    sys.stdout.flush()

    for i in range(n*(n+1)//2):

        substring = input().decode().strip()

        L.append([convert(substring), 1])

    if n >= 2:

        sys.stdout.write(f'? 2 {n}\n')

        sys.stdout.flush()

        for i in range(n*(n-1)//2):

            substring = input().decode().strip()

            L.append([convert(substring), 2])

    L.sort()

    curr = [L[0][0], 0, 0]

    L2 = []

    for i in range(len(L)):

        if curr[0] < L[i][0]:

            L2.append(curr)

            curr = [L[i][0], 0, 0]

        t = L[i][1]

        curr[t]+=1

    L2.append(curr)

    final  = []

    for x in L2:

        if x[1] > x[2]:

            final.append(x[0])

    answer = [None for i in range(n)]

    answer[0] = convert2(final[0])

    for i in range(1, n):

        X = string_apply(final[i], final[i-1], lambda a, b: a-b)

        answer[i] = convert2(X)

    answer = ''.join(answer)

    sys.stdout.write(f'! {answer}\n')

    sys.stdout.flush()

n = int(input())

process(n)


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

def d(a, b):

    return 1000000 * ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) + (abs(a[0] - b[0]) + abs(a[1] - b[1]))

n = int(input())

a = []

b = []

for i in range(n):

    b.append([int(x) for x in input().split()])

for i in range(n - 1):

    a.append(d(b[i], b[i + 1]))

a.append(d(b[0], b[-1]))

if n % 2:

    print('NO')

    quit()

for i in range(n // 2):

    if a[i] != a[i + n // 2]:

        print('NO')

        quit()

print('YES')


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

# Thank God that I'm not you.

import bisect

from collections import Counter, deque

import heapq

import itertools

import math

import random

import sys

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

def primeFactors(n):

    counter = Counter();

    while n % 2 == 0:

        counter[2] += 1;

        n = n / 2

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

        while n % i== 0:

            counter[i] += 1;

            n = n / i

    if (n > 2):

        counter[n] += 1;

    return counter;

n = int(input())

arrays = []

genCnt = 0;

count = 0;

maxes, mins = [], []

for _ in range(n):

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

    array = array[1:]

    if array != sorted(array, reverse = True):

        continue

    else:

        maxes.append(max(array));

        mins.append(min(array))

mins.sort()

maxes.sort()

def bisectLeft(val):

    leftPointer, rightPointer = 0, len(maxes) - 1

    ans = -1

    while(rightPointer >= leftPointer):

        middlePointer = (rightPointer + leftPointer) // 2

        if maxes[middlePointer] <= val:

            ans = middlePointer;

            leftPointer = middlePointer + 1

        else:

            rightPointer = middlePointer - 1

    return ans;

for num in mins:

    count += bisectLeft(num) + 1

print((n * n) - count)


D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:  for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array;  for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array;  for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example:  After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11.  After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22.  After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33.  After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations).  After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44.  After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44.  After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations:   a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5,  a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3,  a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3,  a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6,  a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7,  a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4.  The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.


from sys import stdin

input = stdin.readline

#google = lambda : print("Case #%d: "%(T + 1) , end = '')

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

mod = 998244353

def add(a , b):return ((a%mod) + (b%mod))%mod

def sub(a , b):return (a - b + mod)%mod

def mul(a , b):return ((a%mod) * (b%mod))%mod

def ncr(n , r):return mul(fact[n] , mul(facti[n - r] , facti[r]))

def div(a , b):return mul(a , pow(b , mod - 2 , mod))

def answer():

    ans = 0

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

        w = (n - x + 1) * (n - x + 1)

        ways = mul(fact[x] , fact[n - x])

        ways = mul(ways , w)

        ans = add(ans , ways)

    return ans

for T in range(1):

    n , mod = inp()

    fact , facti = [1] , [1]

    size = 3 * (10**5) + 1

    for i in range(1 , size):

        fact.append(mul(fact[-1] , i))

        facti.append(pow(fact[-1] , mod - 2 , mod))

    print(answer())


E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence.

import sys

MAX = 1_000_005

lp = [0] * MAX

pr = []

pid = {1: 0}

for i in range(2, MAX):

	if not lp[i]:

		lp[i] = i

		pr.append(i)

		pid[i] = len(pr)

	for p in pr:

		if p > lp[i] or i * p >= MAX:

			break

		lp[i * p] = p

n = int(input())

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

g = [[] for _ in range(len(pid))]

e = set()

for x in a:

	f = []

	while x > 1:

		p, c = lp[x], 0

		while lp[x] == p:

			x //= p

			c ^= 1

		if c:

			f.append(p)

	if not f:

		print(1)

		sys.exit(0)

	f += [1] * (2 - len(f))

	u, v = pid[f[0]], pid[f[1]]

	if (u, v) in e or (v, u) in e:

		print(2)

		sys.exit(0)

	g[u].append(v)

	g[v].append(u)

def bfs(s):

	d = [-1] * len(pid)

	d[s] = 0

	q = [(s, -1)]

	while q:

		q2 = []

		for u, p in q:

			for v in g[u]:

				if d[v] != -1:

					if v != p:

						return d[u] + d[v] + 1

				else:

					d[v] = d[u] + 1

					q2.append((v, u))

		q = q2

ans = n + 1

for i in range(len(pid)):

	if i > 0 and pr[i - 1] ** 2 >= MAX:

		break

	ans = min(ans, bfs(i) or ans)

print(ans if ans <= n else -1)


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.

n = int(input())

for i in range(n):

    x = int(input())

    print(1,x-1, sep=" ")


#  If you win, you live. You cannot win unless you fight.

from sys import  stdin

input=stdin.readline

import heapq

import string

rd=lambda: map(lambda s: int(s), input().strip().split())

ri=lambda: int(input())

rs=lambda :input().strip()

from collections import defaultdict,deque,Counter

from bisect import bisect_left as bl, bisect_right as br

from random import randint

from math import gcd, ceil, floor,log2,factorial

random = randint(1, 10 ** 9)

mod=10**9+7

class wrapper(int):

    def __hash__(self):

        return super(wrapper, self).__hash__() ^ random

#similar to last contest C

n,m=rd()

mod=m

fac=[0]*(n+2)

fac[1]=1

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

    fac[i]=(i*fac[i-1])%(mod)

ans=0

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

    r=n

    l=i

    ans+=(r-l+1)*((fac[r-l+1]*(fac[l]))%mod)

    ans%=mod

print(ans)


A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.

t=int(input())

M=[]

def fonction(L,n):

    res=[i%2 for i in L]

    if 0 not in res:

        if n>=2:

            return (2,(1,2))

        else:

            return -1

    else:

        return (1,(res.index(0)+1,))

for i in range(t):

    n=int(input())

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

    M.append(fonction(L,n))

for k in M:

    if k==-1:

        print(k)

    else:

        print(k[0])

        print(" ".join([str(x) for x in k[1]]))


from bisect import bisect_left

import sys

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

n = int(input())

li = []

for _ in range(n):

    _, *temp = map(int, input().split())

    li.append(temp)

asc_c = 0

no_asc_c = 0

no_asc_maxes = []

no_asc_mins = []

for temp in li:

    cur_min = temp[0]

    min_v = temp[0]

    max_v = temp[0]

    is_asc = False

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

        min_v = min(min_v, temp[i])

        max_v = max(max_v, temp[i])

        if cur_min < temp[i]:

            is_asc = True

            break

        cur_min = min(cur_min, temp[i])

    if is_asc:

        asc_c += 1

    else:

        no_asc_c += 1

        no_asc_maxes.append(max_v)

        no_asc_mins.append(min_v)

total = n * asc_c + asc_c * no_asc_c

no_asc_maxes_len = len(no_asc_maxes)

no_asc_maxes.sort()

for min_v in no_asc_mins:

    total += no_asc_maxes_len - bisect_left(no_asc_maxes, min_v + 0.1)

print(total)


n=int(input())

l1=[]

l2=[]

for i in range(n):

    l1.append(int(input()))

    l2.append([int(x) for x in input().split()])

for i in range(n):

    a=0

    b=0

    for j in l2[i]:

        if j%2==0:

            a=a+1

        else:

            b=b+1

    if min(a,b)==0:

        print("YES")

    else:

        print("NO")

print()


E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1

from bisect import *

from collections import *

import sys

import io, os

import math

import random

from heapq import *

gcd = math.gcd

sqrt = math.sqrt

maxint=10**21

def ceil(a, b):

    a = -a

    k = a // b

    k = -k

    return k

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

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

def strinp(testcases):

    k = 5

    if (testcases == -1 or testcases == 1):

        k = 1

    f = str(input())

    f = f[2:len(f) - k]

    return f

def main():

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

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

    pref=[0]*(n)

    prev=0

    ans=-1

    for i in range(n):

        pref[i]=d[i]+prev

        prev=pref[i]

        if(prev+H<=0):

            ans=i+1

            break

    if(ans!=-1):

        print(ans)

        return()

    tot=prev

    if(tot>=0):

        print(-1)

        return()

    tot=-tot

    mi=10**21

    for i in range(n):

        ans=(i+1)+((((H+pref[i])//tot)+min((H+pref[i])%tot,1))*n)

        mi=min(mi,ans)

    print(mi)

main()


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.

import sys

from collections import *

input = sys.stdin.readline

from math import *

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

def rd(): return int(input())

MAXN = 2 * 10**5 + 5

INF = 10**16 * 2

mod = 10**9 + 7

#----------------------------------------------------------------------------------#

def solve():

    n, h, l, r = mrd()

    a = mrd()

    f = [-INF] * h

    f[0] = 0

    for x in a:

        g = f[:]

        for i in range(h):

            f[i] = max(g[(i - x + 1) % h], g[(i - x) % h]) + (l <= i <= r)

    print(max(f))

if __name__ == "__main__":

    solve()


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.

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

ans = []
for i in range(N):
    k = A[:]
    num = A[i]
    for l in range(i-1,-1,-1):
        num = min(num,k[l])
        k[l] = num
    num = A[i]
    for r in range(i+1,N):
        num = min(num,k[r])
        k[r] = num
    ans.append([sum(k),k,i])
ans.sort(reverse=True)
print(*ans[0][1])


A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element.  the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8];  the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8];  if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element);  if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.

import gc

import heapq

import itertools

import math

import sqlite3

from collections import Counter, deque, defaultdict

from sys import stdout

import time

from math import factorial, log, gcd

import sys

from decimal import Decimal

import threading

from heapq import *

def S():

    return sys.stdin.readline().split()

def I():

    return [int(i) for i in sys.stdin.readline().split()]

def II():

    return int(sys.stdin.readline())

def IS():

    return sys.stdin.readline().replace('\n', '')

def main():

    n, m, k = I()

    m -= 1

    k = min(m, k)

    m -= k

    fix = [float('inf')] * (k + 1)

    a = I()

    for i in range(m + 1):

        for j in range(k + 1):

            fix[j] = min(fix[j], max(a[i + j], a[-(m - i + (k - j)) - 1]))

    print(max(fix))

if __name__ == '__main__':

    for _ in range(II()):

        main()

    # main()


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.

n = int(input())

s = input()

while len(s) > 1:

    checker = 0

    for letter in 'zyxwvutsrqponmlkjihgfedcb':

        # print(letter, end='')

        if letter in s:

            for i in range(0, len(s)):

                a = i-1

                b = i+1

                neighbours = []

                if a >= 0:

                    neighbours.append(s[a])

                if b < len(s):

                    neighbours.append(s[b])

                if s[i] == letter and chr(ord(s[i])-1) in neighbours:

                    s = s[:i] + s[i+1:]

                    checker = 1

                    break

            if checker == 1:

                break

    # print()

    if checker == 0:

        # print(s)

        break

print(n-len(s))


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:

n = int(input())
g = [0]*(n+1)
l = []
for i in range(n-1):
	a,b = map(int,input().split())
	a -= 1
	b -= 1
	g[a] += 1
	g[b] += 1
	l.append([a,b])
cnt = 0
mex = n-2
for a,b in l:
	if g[a] == 1 or g[b] == 1:
		print(cnt)
		cnt += 1
	else:
		print(mex)
		mex -= 1


C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1

from sys import stdin, stdout

from bisect import bisect_left, bisect_right

dp = []

add = []

am = []

def build(pos, l,r):

    global dp

    global am

    if l == r - 1:

        dp[pos] = -am[l][1]

        return

    mid = int((l+r)/2)

    build (pos*2+1,l,mid)

    build (pos*2+2,mid,r)

    dp[pos] = max(dp[pos*2+1],dp[pos*2+2])

def push(pos, l,r):

    global dp

    global add

    if add[pos] != 0:

        if r- l > 1:

            add[pos*2+1] += add[pos]

            dp[pos*2+1] += add[pos]

            add[pos*2+2] += add[pos]

            dp[pos*2+2] += add[pos]

        add[pos] = 0

def update(pos, l,r,L,R, val):

    global dp

    global add

    if L>=R:

        return

    if l == L and r == R:

        add[pos] += val

        dp[pos] += val

        push(pos, l,r)

        return

    push(pos, l,r)

    mid = int((l+r)/2)

    update(pos*2+1, l, mid, L, min(R,mid), val)

    update(pos*2+2, mid, r, max(L,mid), R, val)

    dp[pos] = max(dp[pos*2+1],dp[pos*2+2])

def main():

    global dp

    global am

    global add

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

    AMT = 1000002

    dp = [0] * (m *4 + 2)

    add = [0] * (m *4 + 2)

    WP = [-1] * AMT

    AM = [-1] * AMT

    am2 = []

    PWN = [[] for _ in range(AMT)]

    max_atk = -1

    for _ in range(n):

        power, cost = list(map(int, stdin.readline().split()))

        if WP[power] == -1 or (WP[power] != -1 and WP[power] > cost):

            WP[power] = cost

            if power > max_atk:

                max_atk = power

    for _ in range(m):

        power, cost = list(map(int, stdin.readline().split()))

        if AM[power] == -1 or (AM[power] != -1 and AM[power] > cost):

            AM[power] = cost

    for _ in range(k):

        atk, df, gold =  list(map(int, stdin.readline().split()))

        PWN[atk+1].append((df, gold))

    for i in range(AMT):

        if AM[i] != -1:

            am.append((i, AM[i]))

            am2.append(i)

    m = len(am)

    build(0,0,m)

    mx = -999999999999

    for i in range(AMT):

        if i > max_atk:

            break

        for a,b in PWN[i]:

            right = bisect_right(am2, a)

            update(0, 0, m, right, m, b)

        if WP[i] == -1:

            continue

        temp = dp[0]

        if  temp - WP[i] > mx:

            mx = temp - WP[i]

    stdout.write(str(mx))

main()


import collections
import math

def prime_range(n):
    sieve = [0] * n
    pid = {1: 0}
    for i in range(2, n):
        if not sieve[i]:
            sieve[i] = i
            pid[i] = len(pid)
            for j in range(i * i, n, i):
                if not sieve[j]:
                    sieve[j] = i
    return sieve, pid

def odd_prime_factors(a, min_p_factor):
    f = collections.Counter()
    while a > 1:
        x = min_p_factor[a]
        f[x] ^= 1
        a //= x
    return [x for x in f if f[x]]

def shortest_cycle(root, g):
    if not g[root]:
        return math.inf
    # -1 is faster than None (PyPy 3.6.9)
    depth = [-1] * len(g)
    depth[root] = 0
    queue = collections.deque([(root, None)])
    while queue:
        u, parent = queue.popleft()
        for v in g[u]:
            if depth[v] is -1:
                depth[v] = depth[u] + 1
                queue.append((v, u))
            elif v != parent:
                return depth[u] + depth[v] + 1
    return math.inf

min_p_factor, pid = prime_range(10**6 + 1)
input()
g = [[] for _ in range(len(pid))]
for x in map(int, input().split()):
    f = odd_prime_factors(x, min_p_factor)
    if not f:
        print(1)
        exit()
    f.append(1)
    u, v = pid[f[0]], pid[f[1]]
    g[u].append(v)
    g[v].append(u)
shortest = min(shortest_cycle(i, g) for i in range(169))  # pid[1009] == 169
print(shortest if math.isfinite(shortest) else -1)


B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows:  However, the results of the Olympiad could also look like this:  In the first case Nikolay would have taken first place, and in the second — third place.

t=int(input())

for k in range(t):

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

    print(max(1,min(nit,x+y-nit+1)),min(x+y-1,nit))


D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5

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

arr=[]

for _ in range(n):

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

l=0

a1=0

a2=0

r=10**10

def check(x):

    d=[-1 for _ in range(1<<m)]

    for i,el in enumerate(arr):

        curr=0

        for j in range(m):

            if el[j]>x:

                curr|=(1<<j)

        d[curr]=i

    if d[-1]!=-1:

        a1=d[-1]

        a2=d[-1]

        return True,a1,a2

    for  i in range(1<<m):

        for j in range(1<<m):

            if d[i]!=-1 and d[j]!=-1 and (i|j)==len(d)-1:

                a1=d[i]

                a2=d[j]

                return True,a1,a2

    return False,-1,-1

while l<=r:

    mid=(l+r)//2

    p,i,j=check(mid)

    if p:

        a1=i

        a2=j

        ans=mid

        l=mid+1

    else:

        r=mid-1

print(a1+1,a2+1)


C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way:  At 00-th minute, change the state to heating (the temperature is 0).  At 22-nd minute, change the state to off (the temperature is 2).  At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied).  At 66-th minute, change the state to off (the temperature is 3).  At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied).  At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.

import math

import random

cazuri=int(input())

for jj in range(cazuri):

 #n=int(input())

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

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

 max_left=t_initial

 max_right=t_initial

 timpul_initial=0

 posibil_total="YES"

 vector=[]

 contor=-1

 s=''

 s=str(n)+"|"+str(t_initial)+"||"

 partial=1

 for pp in range(n):

  posibil=0

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

  #if jj==1 and cazuri==2 :

   #for h in bloc:

   # s+=str(h)+"|"

 #  s+="||"

  if pp>0:

   if vector[contor][0]==bloc[0]:

    left=max(vector[contor][1],bloc[1])

    right=min(vector[contor][2],bloc[2])

    if left>right:

     partial=0

    else:

     vector[contor][1]=left

     vector[contor][2]=right

   else:

    vector.append(bloc)

    contor+=1

  else:

   vector.append(bloc)

   contor+=1

 if partial==0:

  print("NO")

 else:

 # print(vector)

  for pp in vector:

   posibil=0

   ti,li,hi=pp

  # print(ti,li,hi)

   durata=ti-timpul_initial

   timpul_initial=ti

   max_left=max_left-durata

   max_right=max_right+durata

   if (li>=max_left and li<=max_right) or (hi>=max_left and hi<=max_right) or (li<=max_left and hi>=max_right):

    posibil=1

    max_left=min(max(li,max_left),max_right)

    max_right=max(min(hi,max_right),max_left)

   if posibil==0:

    posibil_total="NO"

    break

  print(posibil_total)