I found an interesting problem on https://codeforces.com/problemset/problem/1312/D:
Your task is to calculate the number of arrays such that:  each array contains $n$ elements;  each element is an integer from $1$ to $m$;  for each array, there is exactly one pair of equal elements;  for each array $a$, there exists an index $i$ such that the array is strictly ascending before the $i$-th element and strictly descending after it (formally, it means that $a_j < a_{j + 1}$, if $j < i$, and $a_j > a_{j + 1}$, if $j \ge i$).

-----Input-----

The first line contains two integers $n$ and $m$ ($2 \le n \le m \le 2 \cdot 10^5$).

-----Output-----

Print one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo $998244353$.

-----Examples-----
Input
3 4

Output
6

Input
3 5

Output
10

Input
42 1337

Output
806066790

Input
100000 200000

Output
707899035

-----Note-----

The arrays in the first example are:  $[1, 2, 1]$;  $[1, 3, 1]$;  $[1, 4, 1]$;  $[2, 3, 2]$;  $[2, 4, 2]$;  $[3, 4, 3]$.

I tried it in Python, but could not do it. Can you solve it?

import math, collections, sys
input = sys.stdin.readline
def ncr(n, r, p):
    num = den = 1
    for i in range(r):
        num = (num * (n - i)) % p
        den = (den * (i + 1)) % p
    return (num * pow(den, p - 2, p)) % p
n, m = map(int, input().split())
mod = 998244353
if n == 2:
    print(0)
else:
    ans = ncr(m, n-1, mod)
    ans*=(n-2)
    ans%=mod
    ans*=pow(2, n-3, mod)
    ans%=mod
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1312/E:
You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times:  Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair).  Replace them by one element with value $a_i + 1$.

After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?

-----Input-----

The first line contains the single integer $n$ ($1 \le n \le 500$) — the initial length of the array $a$.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) — the initial array $a$.

-----Output-----

Print the only integer — the minimum possible length you can get after performing the operation described above any number of times.

-----Examples-----
Input
5
4 3 2 2 3

Output
2

Input
7
3 3 4 4 4 3 3

Output
2

Input
3
1 3 5

Output
3

Input
1
1000

Output
1

-----Note-----

In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.

In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.

In the third and fourth tests, you can't perform the operation at all.

I tried it in Python, but could not do it. Can you solve it?

rr = lambda: input().rstrip()
rri = lambda: int(rr())
rrm = lambda: list(map(int, rr().split()))

from functools import lru_cache;memo=lru_cache(None)
from sys import setrecursionlimit as srl;srl(10**5)

def solve(N, A):
    @memo
    def dp(i, j, left=0):
        if i == j:
            if left == 0:
                return 1
            if A[i] == left:
                return 1
            return 2
        if i > j:
            return 0 if left == 0 else 1
        # Try to greedy run up until left
        ans = 1 + dp(i+1, j, A[i])
        if left >= 1:
            stack = []
            for k in range(i, j+1):
                stack.append(A[k])

                while len(stack) >= 2 and stack[-1] == stack[-2]:
                    stack.pop()
                    stack[-1] += 1
                if len(stack) == 1 and left == stack[-1]:
                    cand = dp(k+1, j, left+1)
                    if cand < ans:
                        ans = cand
        return ans

    return dp(1, N-1, A[0])

#print(solve(2,[2,2]))
#print(solve(3,[3,2,2]))
#print(solve(4,[3,2,2,3]))
#print(solve(5,[4,3,2,2,3]))
#print(solve(4,[4,3,2,2]))
#import random;random.seed(0);ri=random.randint
#print(solve(500, [ri(1,5) for _ in range(500)]))
print(solve(rri(), rrm()))


I found an interesting problem on https://codeforces.com/problemset/problem/1312/F:
The Red Kingdom is attacked by the White King and the Black King!

The Kingdom is guarded by $n$ castles, the $i$-th castle is defended by $a_i$ soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.

Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.

Each attack must target a castle with at least one alive defender in it. There are three types of attacks:

  a mixed attack decreases the number of defenders in the targeted castle by $x$ (or sets it to $0$ if there are already less than $x$ defenders);  an infantry attack decreases the number of defenders in the targeted castle by $y$ (or sets it to $0$ if there are already less than $y$ defenders);  a cavalry attack decreases the number of defenders in the targeted castle by $z$ (or sets it to $0$ if there are already less than $z$ defenders).

The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.

The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are...

I tried it in Python, but could not do it. Can you solve it?

import sys
input = sys.stdin.readline

G0=[[[[0]*5500 for i in range(6)] for j in range(6)] for k in range(6)]
G1=[[[[0]*5500 for i in range(6)] for j in range(6)] for k in range(6)]
G2=[[[[0]*5500 for i in range(6)] for j in range(6)] for k in range(6)]

for x in range(1,6):
    for y in range(1,6):
        for z in range(1,6):

            for i in range(1,5500):
                s=G0[x][y][z][max(0,i-x)]
                t=G1[x][y][z][max(0,i-y)]
                u=G2[x][y][z][max(0,i-z)]

                for j in range(5):
                    if j==s or j==t or j==u:
                        continue
                    else:
                        G0[x][y][z][i]=j
                        break

                for j in range(5):
                    if j==s or j==u:
                        continue
                    else:
                        G1[x][y][z][i]=j
                        break

                for j in range(5):
                    if j==s or j==t:
                        continue
                    else:
                        G2[x][y][z][i]=j
                        break

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

t=int(input())
for tests in range(t):
    n,x,y,z=list(map(int,input().split()))
    B=list(map(int,input().split()))
    A=[]
    for a in B:
        if a<=5400:
            A.append(a)
        else:
            A.append(a%2520+2520)

    XOR=0

    for a in A:
        XOR^=G0[x][y][z][a]

    ANS=0
    for a in A:
        k=XOR^G0[x][y][z][a]

        if G0[x][y][z][max(0,a-x)]==k:
            ANS+=1

        if G1[x][y][z][max(0,a-y)]==k:
            ANS+=1

        if G2[x][y][z][max(0,a-z)]==k:
            ANS+=1

    print(ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1313/A:
Tired of boring office work, Denis decided to open a fast food restaurant.

On the first day he made $a$ portions of dumplings, $b$ portions of cranberry juice and $c$ pancakes with condensed milk.

The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:  every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);  each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;  all visitors should receive different sets of dishes.

What is the maximum number of visitors Denis can feed?

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 500$) — the number of test cases to solve.

Each of the remaining $t$ lines contains integers $a$, $b$ and $c$ ($0 \leq a, b, c \leq 10$) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.

-----Output-----

For each test case print a single integer — the maximum number of visitors Denis can feed.

-----Example-----
Input
7
1 2 1
0 0 0
9 1 7
2 2 3
2 3 2
3 2 2
4 4 4

Output
3
0
4
5
5
5
7

-----Note-----

In the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.

In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.

In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth...

I tried it in Python, but could not do it. Can you solve it?

t = int(input())
for q in range(t):
    a = list(map(int, input().split()))
    ans = 0
    for i in range(3):
        if a[i] > 0:
            ans += 1
            a[i] -= 1
    a.sort()
    a.reverse()
    if a[0] and a[1]:
        a[0] -= 1
        a[1] -= 1
        ans += 1
    if a[0] and a[2]:
        a[0] -= 1
        a[2] -= 1
        ans += 1
    if a[1] and a[2]:
        a[1] -= 1
        a[2] -= 1
        ans += 1
    if a[0] and a[1] and a[2]:
        ans += 1
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1313/B:
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $n$ 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 $x$-th place and in the second round — $y$-th place. Then the total score of the participant A is sum $x + 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 $i$ from $1$ to $n$ exactly one participant took $i$-th place in first round and exactly one participant took $i$-th place in second round.

Right after the end of the Olympiad, Nikolay was informed that he got $x$-th place in first round and $y$-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.

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 100$) — the number of test cases to solve.

Each of the following $t$ lines contains integers $n$, $x$, $y$ ($1 \leq n \leq 10^9$, $1 \le x, y \le 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.

-----Output-----

Print two integers — the minimum and maximum possible overall place Nikolay could take.

-----Examples-----
Input
1
5 1 3

Output
1 3

Input
1
6 3 4

Output
2 6

-----Note-----

Explanation for the first...

I tried it in Python, but could not do it. Can you solve it?

t=int(input())
for tt in range(t):
    n,x,y=list(map(int,input().split()))
    mi = min(max(1, x + y - n + 1), n)
    k = n - ( 0 if x+y > n else n-x-y+1)
    print(mi, k)


I found an interesting problem on https://codeforces.com/problemset/problem/1313/C1:
This is an easier version of the problem. In this version $n \le 1000$

The 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 $n$ plots along the highway and is preparing to build $n$ 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 $1$ to $n$. Then if the skyscraper on the $i$-th plot has $a_i$ floors, it must hold that $a_i$ is at most $m_i$ ($1 \le a_i \le m_i$). Also there mustn't be integers $j$ and $k$ such that $j < i < k$ and $a_j > a_i < a_k$. Plots $j$ and $k$ are not required to be adjacent to $i$.

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.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 1000$) — the number of plots.

The second line contains the integers $m_1, m_2, \ldots, m_n$ ($1 \leq m_i \leq 10^9$) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.

-----Output-----

Print $n$ integers $a_i$ — 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...

I tried it in Python, but could not do it. Can you solve it?

def main():
    import sys
    input = sys.stdin.readline

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

    S = -1
    for mid in range(N):
        ans = [0] * N
        ans[mid] = A[mid]
        prev = A[mid]
        for j in range(mid-1, -1, -1):
            ans[j] = min(prev, A[j])
            prev = ans[j]
        prev = A[mid]
        for j in range(mid+1, N):
            ans[j] = min(prev, A[j])
            prev = ans[j]
        if sum(ans) > S:
            S = sum(ans)
            ans_best = ans
    print(*ans_best)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1313/C2:
This is a harder version of the problem. In this version $n \le 500\,000$

The 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 $n$ plots along the highway and is preparing to build $n$ 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 $1$ to $n$. Then if the skyscraper on the $i$-th plot has $a_i$ floors, it must hold that $a_i$ is at most $m_i$ ($1 \le a_i \le m_i$). Also there mustn't be integers $j$ and $k$ such that $j < i < k$ and $a_j > a_i < a_k$. Plots $j$ and $k$ are not required to be adjacent to $i$.

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.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 500\,000$) — the number of plots.

The second line contains the integers $m_1, m_2, \ldots, m_n$ ($1 \leq m_i \leq 10^9$) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.

-----Output-----

Print $n$ integers $a_i$ — 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,...

I tried it in Python, but could not do it. Can you solve it?

from sys import stdin

def solve():
    n = int(stdin.readline())
    m = list(map(int, stdin.readline().split()))
    msl = [-1] * n
    msp = [n] * n
    q = []
    for i in range(n):
        while q and m[q[-1]] > m[i]:
            q.pop()
        if q:
            msl[i] = q[-1]
        q.append(i)
    q = []
    for i in range(n - 1, -1, -1):
        while q and m[q[-1]] > m[i]:
            q.pop()
        if q:
            msp[i] = q[-1]
        q.append(i)

    dp1 = [0] * n
    for i in range(n):
        dp1[i] = m[i] * (i - msl[i])
        if msl[i] != -1:
            dp1[i] += dp1[msl[i]]
    dp2 = [0] * n
    for i in range(n - 1, -1, -1):
        dp2[i] += m[i] * (msp[i] - i)
        if msp[i] != n:
            dp2[i] += dp2[msp[i]]
    ansm = 0
    answc = 0
    for i in range(n):
        cur = dp1[i] + dp2[i] - m[i]
        if cur > answc:
            answc = cur
            ansm = i
    i = ansm
    cur = [0] * n
    cur[i] = m[i]
    for j in range(i + 1, n):
        cur[j] = min(cur[j - 1], m[j])
    for j in range(i - 1, -1, -1):
        cur[j] = min(cur[j + 1], m[j])
    print(*cur)

for i in range(1):
    solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1313/E:
Vasya had three strings $a$, $b$ and $s$, which consist of lowercase English letters. The lengths of strings $a$ and $b$ are equal to $n$, the length of the string $s$ is equal to $m$.

Vasya decided to choose a substring of the string $a$, then choose a substring of the string $b$ and concatenate them. Formally, he chooses a segment $[l_1, r_1]$ ($1 \leq l_1 \leq r_1 \leq n$) and a segment $[l_2, r_2]$ ($1 \leq l_2 \leq r_2 \leq n$), and after concatenation he obtains a string $a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} \ldots a_{r_1} b_{l_2} b_{l_2 + 1} \ldots b_{r_2}$.

Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions:

  segments $[l_1, r_1]$ and $[l_2, r_2]$ have non-empty intersection, i.e. there exists at least one integer $x$, such that $l_1 \leq x \leq r_1$ and $l_2 \leq x \leq r_2$;  the string $a[l_1, r_1] + b[l_2, r_2]$ is equal to the string $s$.

-----Input-----

The first line contains integers $n$ and $m$ ($1 \leq n \leq 500\,000, 2 \leq m \leq 2 \cdot n$) — the length of strings $a$ and $b$ and the length of the string $s$.

The next three lines contain strings $a$, $b$ and $s$, respectively. The length of the strings $a$ and $b$ is $n$, while the length of the string $s$ is $m$.

All strings consist of lowercase English letters.

-----Output-----

Print one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.

-----Examples-----
Input
6 5
aabbaa
baaaab
aaaaa

Output
4

Input
5 4
azaza
zazaz
azaz

Output
11

Input
9 12
abcabcabc
xyzxyzxyz
abcabcayzxyz

Output
2

-----Note-----

Let's list all the pairs of segments that Vasya could choose in the first example:

  $[2, 2]$ and $[2, 5]$;  $[1, 2]$ and $[2, 4]$;  $[5, 5]$ and $[2, 5]$;  $[5, 6]$ and $[3, 5]$;

I tried it in Python, but could not do it. Can you solve it?

import sys, logging
logging.basicConfig(level=logging.INFO)
logging.disable(logging.INFO)

def build(S, n):
    Z = [0 for i in range(3 * n + 3)]
    #logging.info(S)
    n = len(S)
    L = 0
    R = 0
    Z[0] = n
    for i in range(1, n):
        if(i > R):
            L = R = i
            while(R < n and S[R] == S[R - L]):
                R += 1
            Z[i] = R - L
            R -= 1
        else:
            k = i - L
            if(Z[k] < R - i + 1):
                Z[i] = Z[k]
            else:
                L = i
                while(R < n and S[R] == S[R - L]):
                    R += 1
                Z[i] = R - L
                R -= 1
    return Z

def update1(n, x, val):
    while(x <= n + 1):
        bit1[x] += val
        x += x & -x

def get1(n, x):
    ans = 0
    while(x > 0):
        ans += bit1[x]
        x -= x & -x
    return ans

def update2(n, x, val):
    while(x <= n + 1):
        bit2[x] += val
        x += x & -x

def get2(n, x):
    ans = 0
    while(x > 0):
        ans += bit2[x]
        x -= x & -x
    return ans

def process(n, m, fa, fb):
    r2 = int(1)
    ans = 0
    for l1 in range(1, n + 1):
        while(r2 <= min(n, l1 + m - 2)):
            update1(n, m - fb[r2] + 1, 1)
            update2(n, m - fb[r2] + 1, fb[r2] - m + 1)
            r2 += 1
        ans += get1(n, fa[l1] + 1) * fa[l1] + get2(n, fa[l1] + 1)
        update1(n, m - fb[l1] + 1, -1)
        update2(n, m - fb[l1] + 1, m - 1 - fb[l1])
    print(ans)

def main():
    n, m = map(int, sys.stdin.readline().split())
    a = sys.stdin.readline()
    b = sys.stdin.readline()
    s = sys.stdin.readline()
    a = a[:(len(a) - 1)]
    b = b[:(len(b) - 1)]
    s = s[:(len(s) - 1)]
    fa = build(s + a, n)
    kb = build(s[::-1] + b[::-1], n)
    fb = [0 for k in range(n + 2)]
    for i in range(m, m + n):
        fa[i - m + 1] = fa[i]
        if(fa[i - m + 1] >= m):
            fa[i - m + 1] = m - 1
        fb[m + n - i] = kb[i]
        if(fb[m + n - i] >= m):
            fb[m + n - i] = m - 1
   ...


I found an interesting problem on https://codeforces.com/problemset/problem/1315/C:
You are given a sequence $b_1, b_2, \ldots, b_n$. Find the lexicographically minimal permutation $a_1, a_2, \ldots, a_{2n}$ such that $b_i = \min(a_{2i-1}, a_{2i})$, or determine that it is impossible.

-----Input-----

Each test contains one or more test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$).

The first line of each test case consists of one integer $n$ — the number of elements in the sequence $b$ ($1 \le n \le 100$).

The second line of each test case consists of $n$ different integers $b_1, \ldots, b_n$ — elements of the sequence $b$ ($1 \le b_i \le 2n$).

It is guaranteed that the sum of $n$ by all test cases doesn't exceed $100$.

-----Output-----

For each test case, if there is no appropriate permutation, print one number $-1$.

Otherwise, print $2n$ integers $a_1, \ldots, a_{2n}$ — required lexicographically minimal permutation of numbers from $1$ to $2n$.

-----Example-----
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8

Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10

I tried it in Python, but could not do it. Can you solve it?

# from collections import defaultdict

for _ in range(int(input())):
	n = int(input())
	b = list(map(int, input().split()))
	a = []
	taken = [False] * (2*n+1)
	for bi in b: taken[bi] = True

	for bi in b:
		a.append(bi)
		next = bi+1
		while next <= 2*n and taken[next]:
			next += 1

		if next <= 2*n:
			a.append(next)
			taken[next] = 1
		else:
			break

	if len(a) == 2*n:
		print(' '.join(map(str, a)))
	else:
		print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1316/A:
$n$ students are taking an exam. The highest possible score at this exam is $m$. Let $a_{i}$ be the score of the $i$-th student. You have access to the school database which stores the results of all students.

You can change each student's score as long as the following conditions are satisfied:   All scores are integers  $0 \leq a_{i} \leq m$  The average score of the class doesn't change.

You are student $1$ and you would like to maximize your own score.

Find the highest possible score you can assign to yourself such that all conditions are satisfied.

-----Input-----

Each test contains multiple test cases.

The first line contains the number of test cases $t$ ($1 \le t \le 200$). The description of the test cases follows.

The first line of each test case contains two integers $n$ and $m$ ($1 \leq n \leq 10^{3}$, $1 \leq m \leq 10^{5}$)  — the number of students and the highest possible score respectively.

The second line of each testcase contains $n$ integers $a_1, a_2, \dots, a_n$ ($ 0 \leq a_{i} \leq m$)  — scores of the students.

-----Output-----

For each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._

-----Example-----
Input
2
4 10
1 2 3 4
4 5
1 2 3 4

Output
10
5

-----Note-----

In the first case, $a = [1,2,3,4] $, with average of $2.5$. You can change array $a$ to $[10,0,0,0]$. Average remains $2.5$, and all conditions are satisfied.

In the second case, $0 \leq a_{i} \leq 5$. You can change $a$ to $[5,1,1,3]$. You cannot increase $a_{1}$ further as it will violate condition $0\le a_i\le m$.

I tried it in Python, but could not do it. Can you solve it?

# -*- coding: utf-8 -*-

import sys
from collections import Counter

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return list(map(int, input().split()))
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
# sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

for _ in range(INT()):
    N, K = MAP()
    A = LIST()

    print(min(sum(A), K))


I found an interesting problem on https://codeforces.com/problemset/problem/1316/B:
Vasya has a string $s$ of length $n$. He decides to make the following modification to the string:   Pick an integer $k$, ($1 \leq k \leq n$).  For $i$ from $1$ to $n-k+1$, reverse the substring $s[i:i+k-1]$ of $s$. For example, if string $s$ is qwer and $k = 2$, below is the series of transformations the string goes through:   qwer (original string)  wqer (after reversing the first substring of length $2$)  weqr (after reversing the second substring of length $2$)  werq (after reversing the last substring of length $2$)  Hence, the resulting string after modifying $s$ with $k = 2$ is werq.

Vasya wants to choose a $k$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $k$. Among all such $k$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.

A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:   $a$ is a prefix of $b$, but $a \ne b$;  in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.

-----Input-----

Each test contains multiple test cases.

The first line contains the number of test cases $t$ ($1 \le t \le 5000$). The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($1 \le n \le 5000$) — the length of the string $s$.

The second line of each test case contains the string $s$ of $n$ lowercase latin letters.

It is guaranteed that the sum of $n$ over all test cases does not exceed $5000$.

-----Output-----

For each testcase output two lines:

In the first line output the lexicographically smallest string $s'$ achievable after the above-mentioned modification.

In the second line output the appropriate value of $k$ ($1 \leq k \leq n$) that you chose for performing the modification. If there are multiple values of $k$ that give the lexicographically smallest string, output...

I tried it in Python, but could not do it. Can you solve it?

t=int(input())
for nt in range(t):
    n=int(input())
    s=input()
    mr=s
    bk=1
    for k in range(2,n+1):
        p=s[k-1:]+(s[:k-1] if (n-k)%2 else s[:k-1][::-1])

        if (p<mr):
            mr=min(s,p)
            bk=k
    print(mr)
    print(bk)


I found an interesting problem on https://codeforces.com/problemset/problem/1316/C:
It is Professor R's last class of his teaching career. Every time Professor R taught a class, he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.

You are given two polynomials $f(x) = a_0 + a_1x + \dots + a_{n-1}x^{n-1}$ and $g(x) = b_0 + b_1x + \dots + b_{m-1}x^{m-1}$, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to $1$ for both the given polynomials. In other words, $gcd(a_0, a_1, \dots, a_{n-1}) = gcd(b_0, b_1, \dots, b_{m-1}) = 1$. Let $h(x) = f(x)\cdot g(x)$. Suppose that $h(x) = c_0 + c_1x + \dots + c_{n+m-2}x^{n+m-2}$.

You are also given a prime number $p$. Professor R challenges you to find any $t$ such that $c_t$ isn't divisible by $p$. He guarantees you that under these conditions such $t$ always exists. If there are several such $t$, output any of them.

As the input is quite large, please use fast input reading methods.

-----Input-----

The first line of the input contains three integers, $n$, $m$ and $p$ ($1 \leq n, m \leq 10^6, 2 \leq p \leq 10^9$),  — $n$ and $m$ are the number of terms in $f(x)$ and $g(x)$ respectively (one more than the degrees of the respective polynomials) and $p$ is the given prime number.

It is guaranteed that $p$ is prime.

The second line contains $n$ integers $a_0, a_1, \dots, a_{n-1}$ ($1 \leq a_{i} \leq 10^{9}$) — $a_i$ is the coefficient of $x^{i}$ in $f(x)$.

The third line contains $m$ integers $b_0, b_1, \dots, b_{m-1}$ ($1 \leq b_{i} \leq 10^{9}$)  — $b_i$ is the coefficient of $x^{i}$ in $g(x)$.

-----Output-----

Print a single integer $t$ ($0\le t \le n+m-2$)  — the appropriate power of $x$ in $h(x)$ whose coefficient isn't divisible by the given prime $p$. If there are multiple powers of $x$ that satisfy the condition, print any.

-----Examples-----
Input
3 2 2
1 1 2
2 1

Output
1

Input
2 2 999999937
2 1
3 1

Output
2

-----Note-----

In the first test case, $f(x)$ is $2x^2 + x + 1$ and $g(x)$ is $x + 2$,...

I tried it in Python, but could not do it. Can you solve it?

from random import randint
import sys

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

f = list(map(int, input().strip().split()))
g = list(map(int, input().strip().split()))

for i in range(len(f)):
    if f[i] % p != 0:
        break

j = 0
while g[j] % p == 0:
    j += 1

print(i+j)


I found an interesting problem on https://codeforces.com/problemset/problem/1319/B:
Tanya wants to go on a journey across the cities of Berland. There are $n$ cities situated along the main railroad line of Berland, and these cities are numbered from $1$ to $n$.

Tanya plans her journey as follows. First of all, she will choose some city $c_1$ to start her journey. She will visit it, and after that go to some other city $c_2 > c_1$, then to some other city $c_3 > c_2$, and so on, until she chooses to end her journey in some city $c_k > c_{k - 1}$. So, the sequence of visited cities $[c_1, c_2, \dots, c_k]$ should be strictly increasing.

There are some additional constraints on the sequence of cities Tanya visits. Each city $i$ has a beauty value $b_i$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $c_i$ and $c_{i + 1}$, the condition $c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$ must hold.

For example, if $n = 8$ and $b = [3, 4, 4, 6, 6, 7, 8, 9]$, there are several three possible ways to plan a journey:  $c = [1, 2, 4]$;  $c = [3, 5, 6, 8]$;  $c = [7]$ (a journey consisting of one city is also valid).

There are some additional ways to plan a journey that are not listed above.

Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of cities in Berland.

The second line contains $n$ integers $b_1$, $b_2$, ..., $b_n$ ($1 \le b_i \le 4 \cdot 10^5$), where $b_i$ is the beauty value of the $i$-th city.

-----Output-----

Print one integer — the maximum beauty of a journey Tanya can choose.

-----Examples-----
Input
6
10 7 1 9 10 15

Output
26

Input
1
400000

Output
400000

Input
7
8 9 26 11 12 29 14

Output
55

-----Note-----

The optimal...

I tried it in Python, but could not do it. Can you solve it?

from collections import Counter
ans = Counter()
input()
for i, b in enumerate(map(int, input().split())):
    ans[b - i] += b
print(max(ans.values()))


I found an interesting problem on https://codeforces.com/problemset/problem/1319/D:
The map of Bertown can be represented as a set of $n$ intersections, numbered from $1$ to $n$ and connected by $m$ one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection $v$ to another intersection $u$ is the path that starts in $v$, ends in $u$ and has the minimum length among all such paths.

Polycarp lives near the intersection $s$ and works in a building near the intersection $t$. Every day he gets from $s$ to $t$ by car. Today he has chosen the following path to his workplace: $p_1$, $p_2$, ..., $p_k$, where $p_1 = s$, $p_k = t$, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from $s$ to $t$.

Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection $s$, the system chooses some shortest path from $s$ to $t$ and shows it to Polycarp. Let's denote the next intersection in the chosen path as $v$. If Polycarp chooses to drive along the road from $s$ to $v$, then the navigator shows him the same shortest path (obviously, starting from $v$ as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection $w$ instead, the navigator rebuilds the path: as soon as Polycarp arrives at $w$, the navigation system chooses some shortest path from $w$ to $t$ and shows it to Polycarp. The same process continues until Polycarp arrives at $t$: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path,...

I tried it in Python, but could not do it. Can you solve it?

import sys
from collections import deque
input = lambda : sys.stdin.readline().strip()
# for i in range(int(input())):
n,m = list(map(int,input().split()))
g = {}
for i in range(m):
    a,b = list(map(int,input().split()))
    if b-1 in g:
        g[b-1].append(a-1)
    else:
        g[b-1]=[a-1]
k = int(input())
way = list([int(x)-1 for x in input().split()])
bfs = deque()
bfs.append(way[-1])
lvl = [-1]*n
ans = [0]*n
a = [set() for j in range(n)]
lvl[way[-1]]=0
while bfs:
    v = bfs.popleft()
    for u in g[v]:
        if lvl[u]==-1:
            lvl[u]=lvl[v]+1
            a[u].add(v)
            bfs.append(u)
        elif lvl[u]==lvl[v]+1:
            ans[u]=1
            a[u].add(v)
ansv = 0
ans1 = 0
for v in range(k-1):
    if k-v-1!=lvl[way[v]] and way[v+1] not in a[way[v]]:
        ans1+=1
    elif k-v-1 == lvl[way[v]]:
        break
for v in range(k-1):
    if ans[way[v]] or  a[way[v]].pop()!=way[v+1]:#
        ansv +=1

print(ans1,ansv)


I found an interesting problem on https://codeforces.com/problemset/problem/1321/A:
Polycarp is preparing the first programming contest for robots. There are $n$ problems in it, and a lot of robots are going to participate in it. Each robot solving the problem $i$ gets $p_i$ points, and the score of each robot in the competition is calculated as the sum of $p_i$ over all problems $i$ solved by it. For each problem, $p_i$ is an integer not less than $1$.

Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them.

For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of $p_i$ in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of $p_i$ will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of $p_i$ over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 100$) — the number of problems.

The second line contains $n$ integers $r_1$, $r_2$, ..., $r_n$ ($0 \le r_i \le 1$). $r_i = 1$ means that the "Robo-Coder Inc." robot will solve the $i$-th problem, $r_i = 0$ means that it won't solve the $i$-th problem.

The third line contains $n$ integers $b_1$, $b_2$, ..., $b_n$ ($0 \le b_i \le 1$). $b_i = 1$ means that the "BionicSolver Industries" robot will solve the $i$-th problem, $b_i = 0$ means that it won't solve the $i$-th problem.

-----Output-----

If "Robo-Coder Inc." robot...

I tried it in Python, but could not do it. Can you solve it?

import math, collections, sys
input = sys.stdin.readline
n = int(input())
r = list(map(int, input().split()))
b = list(map(int, input().split()))
countr, countb = 0, 0
for i in range(n):
    if r[i] and not b[i]:
        countr+=1
    elif not r[i] and b[i]:
        countb+=1
if countr == 0:
    print(-1)
    return
print(countb//countr + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1321/C:
You are given a string $s$ consisting of lowercase Latin letters. Let the length of $s$ be $|s|$. You may perform several operations on this string.

In one operation, you can choose some index $i$ and remove the $i$-th character of $s$ ($s_i$) if at least one of its adjacent characters is the previous letter in the Latin alphabet for $s_i$. 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 $i$ should satisfy the condition $1 \le i \le |s|$ during each operation.

For the character $s_i$ adjacent characters are $s_{i-1}$ and $s_{i+1}$. The first and the last characters of $s$ both have only one adjacent character (unless $|s| = 1$).

Consider the following example. Let $s=$ bacabcab.  During the first move, you can remove the first character $s_1=$ b because $s_2=$ a. Then the string becomes $s=$ acabcab.  During the second move, you can remove the fifth character $s_5=$ c because $s_4=$ b. Then the string becomes $s=$ acabab.  During the third move, you can remove the sixth character $s_6=$'b' because $s_5=$ a. Then the string becomes $s=$ acaba.  During the fourth move, the only character you can remove is $s_4=$ b, because $s_3=$ a (or $s_5=$ a). The string becomes $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.

-----Input-----

The first line of the input contains one integer $|s|$ ($1 \le |s| \le 100$) — the length of $s$.

The second line of the input contains one string $s$ consisting of $|s|$ lowercase Latin letters.

-----Output-----

Print one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.

-----Examples-----
Input
8
bacabcab

Output
4

Input
4
bcda

Output
3

Input
6
abbbbb

Output
5

-----Note-----

The first example is described in the problem...

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
s = list(input())
k = 0
answer = 0
while k == 0:
    k = 1
    mas = []
    for i in range(1, len(s)):
        if ord(s[i]) - 1 == ord(s[i - 1]):
            k = 0
            mas.append([ord(s[i]), i])
        elif ord(s[i]) + 1 == ord(s[i - 1]):
            k = 0
            mas.append([ord(s[i - 1]), i - 1])
    if mas:
        mas.sort()
        answer += 1
        ind = mas[-1][1]
        s.pop(ind)
print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/1322/A:
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.

The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.

Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.

The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $l$ nanoseconds, where $l$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take $2$ nanoseconds).

Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^6$) — the length of Dima's sequence.

The second line contains string of length $n$, consisting of characters "(" and ")" only.

-----Output-----

Print a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.

-----Examples-----
Input
8
))((())(

Output
6

Input
3
(()

Output
-1

-----Note-----

In the first example we can...

I tried it in Python, but could not do it. Can you solve it?

def main():
    import sys
    input = sys.stdin.readline

    N = int(input())
    S = input().rstrip('\n')

    T = [0] * N
    for i, s in enumerate(S):
        if s == '(':
            T[i] = 1
        else:
            T[i] = -1

    if sum(T) != 0:
        print(-1)
        return

    for i in range(1, N):
        T[i] += T[i-1]
    ans = 0
    cnt = 0
    for t in T:
        if t < 0:
            cnt += 1
        else:
            if cnt:
                ans += cnt+1
            cnt = 0
    print(ans)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1322/D:
A popular reality show is recruiting a new cast for the third season! $n$ candidates numbered from $1$ to $n$ have been interviewed. The candidate $i$ has aggressiveness level $l_i$, and recruiting this candidate will cost the show $s_i$ roubles.

The show host reviewes applications of all candidates from $i=1$ to $i=n$ by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate $i$ is strictly higher than that of any already accepted candidates, then the candidate $i$ will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.

The show makes revenue as follows. For each aggressiveness level $v$ a corresponding profitability value $c_v$ is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant $i$ enters the stage, events proceed as follows:

  The show makes $c_{l_i}$ roubles, where $l_i$ is initial aggressiveness level of the participant $i$.  If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is:

  the defeated participant is hospitalized and leaves the show.  aggressiveness level of the victorious participant is increased by one, and the show makes $c_t$ roubles, where $t$ is the new aggressiveness level.

 The fights continue until all participants on stage have distinct aggressiveness levels.

It is allowed to select an empty set of participants (to choose neither of the candidates).

The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total $s_i$). Help the host to make the show as profitable as possible.

-----Input-----

The first line contains...

I tried it in Python, but could not do it. Can you solve it?

import sys
input = sys.stdin.readline

n,m=list(map(int,input().split()))
A=list(map(int,input().split()))
C=list(map(int,input().split()))
P=list(map(int,input().split()))

DP=[[-1<<30]*(n+1) for i in range(5001)]
# DP[k][cnt] = Aのmaxがkで, そういう人間がcnt人いるときのprofitの最大値

for i in range(5001):
    DP[i][0]=0

for i in range(n-1,-1,-1):
    a,c = A[i]-1,C[i]

    for j in range(n,-1,-1):
        if DP[a][j]==-1<<30:
            continue

        if DP[a][j] - c + P[a] > DP[a][j+1]:
            DP[a][j+1] = DP[a][j] - c + P[a]

            x, w=a, j+1
            while x+1<n+m:
                if DP[x+1][w//2] < DP[x][w] + w//2 * P[x+1]:
                    DP[x+1][w//2] = DP[x][w] + w//2 * P[x+1]

                    x,w=x+1,w//2
                else:
                    break

ANS=0
for i in range(5001):
    ANS=max(ANS,DP[i][0],DP[i][1])

print(ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1323/A:
You are given an array $a$ consisting of $n$ positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by $2$) or determine that there is no such subset.

Both the given array and required subset may contain equal values.

-----Input-----

The first line contains a single integer $t$ ($1 \leq t \leq 100$), number of test cases to solve. Descriptions of $t$ test cases follow.

A description of each test case consists of two lines. The first line contains a single integer $n$ ($1 \leq n \leq 100$), length of array $a$.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 100$), elements of $a$. The given array $a$ can contain equal values (duplicates).

-----Output-----

For each test case output $-1$ if there is no such subset of elements. Otherwise output positive integer $k$, number of elements in the required subset. Then output $k$ distinct integers ($1 \leq p_i \leq n$), indexes of the chosen elements. If there are multiple solutions output any of them.

-----Example-----
Input
3
3
1 4 3
1
15
2
3 5

Output
1
2
-1
2
1 2

-----Note-----

There 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 $4$ 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.

I tried it in Python, but could not do it. Can you solve it?

T = int(input())
for cas in range(T):
  n = int(input())
  a = [int(e) for e in input().split()]
  ok = False
  b = []
  for i, j in enumerate(a):
    if j % 2 == 0:
      print(1)
      print(i + 1)
      ok = True
      break
    else:
      b.append(i + 1)
    if len(b) >= 2:
      print(2)
      print(b[0], b[1])
      ok = True
      break
  if not ok:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1323/B:
You are given an array $a$ of length $n$ and array $b$ of length $m$ both consisting of only integers $0$ and $1$. Consider a matrix $c$ of size $n \times m$ formed by following rule: $c_{i, j} = a_i \cdot b_j$ (i.e. $a_i$ multiplied by $b_j$). It's easy to see that $c$ consists of only zeroes and ones too.

How many subrectangles of size (area) $k$ consisting only of ones are there in $c$?

A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers $x_1, x_2, y_1, y_2$ ($1 \le x_1 \le x_2 \le n$, $1 \le y_1 \le y_2 \le m$) a subrectangle $c[x_1 \dots x_2][y_1 \dots y_2]$ is an intersection of the rows $x_1, x_1+1, x_1+2, \dots, x_2$ and the columns $y_1, y_1+1, y_1+2, \dots, y_2$.

The size (area) of a subrectangle is the total number of cells in it.

-----Input-----

The first line contains three integers $n$, $m$ and $k$ ($1 \leq n, m \leq 40\,000, 1 \leq k \leq n \cdot m$), length of array $a$, length of array $b$ and required size of subrectangles.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 1$), elements of $a$.

The third line contains $m$ integers $b_1, b_2, \ldots, b_m$ ($0 \leq b_i \leq 1$), elements of $b$.

-----Output-----

Output single integer — the number of subrectangles of $c$ with size (area) $k$ consisting only of ones.

-----Examples-----
Input
3 3 2
1 0 1
1 1 1

Output
4

Input
3 5 4
1 1 1
1 1 1 1 1

Output
14

-----Note-----

In first example matrix $c$ is:

 $\left(\begin{array}{l l l}{1} & {1} & {1} \\{0} & {0} & {0} \\{1} & {1} & {1} \end{array} \right)$

There are $4$ subrectangles of size $2$ consisting of only ones in it:

 [Image]

In second example matrix $c$ is:

 $\left(\begin{array}{l l l l l}{1} & {1} & {1} & {1} & {1} \\{1} & {1} & {1} & {1} & {1} \\{1} & {1} & {1} & {1} & {1} \end{array} \right)$

I tried it in Python, but could not do it. Can you solve it?

from math import sqrt
n, m, k = list(map(int, input().split()))

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

ac = [0] * (n + 1)
bc = [0] * (m + 1)

cs = 0

for ai in a:
    if ai == 1:
        cs += 1
    if ai == 0:
        ac[cs] += 1
        cs = 0
ac[cs] += 1

cs = 0
for bi in b:
    if bi == 1:
        cs += 1
    if bi == 0:
        bc[cs] += 1
        cs = 0
bc[cs] += 1

pairs = []

for i in range(1, int(sqrt(k) + 1)):
    if k % i == 0:
        pairs.append((i, k // i))

total = 0

for i, j in pairs:
    if i <= n and j <= m:
        act = 0
        for k in range(i, n + 1):
            act += ac[k] * (k - i + 1)
        bct = 0
        for k in range(j, m + 1):
            bct += bc[k] * (k - j + 1)

        total += act * bct
    if j <= n and i <= m and i != j:
        act = 0
        for k in range(j, n + 1):
            act += ac[k] * (k - j + 1)
        bct = 0
        for k in range(i, m + 1):
            bct += bc[k] * (k - i + 1)

        total += act * bct

print(total)


I found an interesting problem on https://codeforces.com/problemset/problem/1324/A:
You are given some Tetris field consisting of $n$ columns. The initial height of the $i$-th column of the field is $a_i$ blocks. On top of these columns you can place only figures of size $2 \times 1$ (i.e. the height of this figure is $2$ blocks and the width of this figure is $1$ 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 $a_i$ is greater than $0$:  You place one figure $2 \times 1$ (choose some $i$ from $1$ to $n$ and replace $a_i$ with $a_i + 2$);  then, while all $a_i$ are greater than zero, replace each $a_i$ with $a_i - 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 $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.

The next $2t$ lines describe test cases. The first line of the test case contains one integer $n$ ($1 \le n \le 100$) — the number of columns in the Tetris field. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the initial height of the $i$-th column of the Tetris field.

-----Output-----

For each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.

-----Example-----
Input
4
3
1 1 3
4
1 1 2 1
2
11 11
1
100

Output
YES
NO
YES
YES

-----Note-----

The first test case of the example field is shown below:

[Image]

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]$. Then place the figure in the second column and after the second step of the process, the field becomes...

I tried it in Python, but could not do it. Can you solve it?

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    c = [i%2 for i in a]
    if sum(c) == 0 or sum(c) == n:
        print('YES')
    else:
        print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1324/B:
You are given an array $a$ consisting of $n$ integers.

Your task is to determine if $a$ has some subsequence of length at least $3$ that is a palindrome.

Recall that an array $b$ is called a subsequence of the array $a$ if $b$ can be obtained by removing some (possibly, zero) elements from $a$ (not necessarily consecutive) without changing the order of remaining elements. For example, $[2]$, $[1, 2, 1, 3]$ and $[2, 3]$ are subsequences of $[1, 2, 1, 3]$, but $[1, 1, 2]$ and $[4]$ are not.

Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array $a$ of length $n$ is the palindrome if $a_i = a_{n - i - 1}$ for all $i$ from $1$ to $n$. For example, arrays $[1234]$, $[1, 2, 1]$, $[1, 3, 2, 2, 3, 1]$ and $[10, 100, 10]$ are palindromes, but arrays $[1, 2]$ and $[1, 2, 3, 1]$ are not.

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.

Next $2t$ lines describe test cases. The first line of the test case contains one integer $n$ ($3 \le n \le 5000$) — the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the $i$-th element of $a$.

It is guaranteed that the sum of $n$ over all test cases does not exceed $5000$ ($\sum n \le 5000$).

-----Output-----

For each test case, print the answer — "YES" (without quotes) if $a$ has some subsequence of length at least $3$ that is a palindrome and "NO" otherwise.

-----Example-----
Input
5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5

Output
YES
YES
NO
YES
NO

-----Note-----

In the first test case of the example, the array $a$ has a subsequence $[1, 2, 1]$ which is a palindrome.

In the second test case of the example, the array $a$ has two subsequences of length $3$ which are palindromes: $[2, 3, 2]$ and $[2, 2, 2]$.

In the third test case of the example, the array $a$ has no subsequences of length at least...

I tried it in Python, but could not do it. Can you solve it?

def f(N,L):
    V=[0]*(N+1)
    for i,a in enumerate(L):
        if V[a]>0:
            r=V[a]
            if L[i-1]==a:
                r-=1
            if r>0:
                return True
        V[a]+=1
    return False

for _ in range(int(input())):
    N=int(input())
    L=list(map(int,input().split()))
    if f(N,L): print('YES')
    else: print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1324/D:
The next lecture in a high school requires two topics to be discussed. The $i$-th topic is interesting by $a_i$ units for the teacher and by $b_i$ units for the students.

The pair of topics $i$ and $j$ ($i < j$) is called good if $a_i + a_j > b_i + b_j$ (i.e. it is more interesting for the teacher).

Your task is to find the number of good pairs of topics.

-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of topics.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the interestingness of the $i$-th topic for the teacher.

The third line of the input contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 10^9$), where $b_i$ is the interestingness of the $i$-th topic for the students.

-----Output-----

Print one integer — the number of good pairs of topic.

-----Examples-----
Input
5
4 8 2 6 2
4 5 4 1 3

Output
7

Input
4
1 3 2 4
1 3 2 4

Output
0

I tried it in Python, but could not do it. Can you solve it?

import sys
input = sys.stdin.readline

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

C=[A[i]-B[i] for i in range(n)]
C.sort()

import bisect
ANS=0

for i in range(n):
    x=bisect.bisect_right(C,-C[i])

    ANS+=n-max(x,i+1)

print(ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1324/E:
Vova had a pretty weird sleeping schedule. There are $h$ hours in a day. Vova will sleep exactly $n$ times. The $i$-th time he will sleep exactly after $a_i$ 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 $0$). Each time Vova sleeps exactly one day (in other words, $h$ hours).

Vova thinks that the $i$-th sleeping time is good if he starts to sleep between hours $l$ and $r$ inclusive.

Vova can control himself and before the $i$-th time can choose between two options: go to sleep after $a_i$ hours or after $a_i - 1$ hours.

Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.

-----Input-----

The first line of the input contains four integers $n, h, l$ and $r$ ($1 \le n \le 2000, 3 \le h \le 2000, 0 \le l \le 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 $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i < h$), where $a_i$ is the number of hours after which Vova goes to sleep the $i$-th time.

-----Output-----

Print one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.

-----Example-----
Input
7 24 21 23
16 17 14 20 20 11 22

Output
3

-----Note-----

The maximum number of good times in the example is $3$.

The story starts from $t=0$. Then Vova goes to sleep after $a_1 - 1$ hours, now the time is $15$. This time is not good. Then Vova goes to sleep after $a_2 - 1$ hours, now the time is $15 + 16 = 7$. This time is also not good. Then Vova goes to sleep after $a_3$ hours, now the time is $7 + 14 = 21$. This time is good. Then Vova goes to sleep after $a_4 - 1$ hours, now the time is $21 + 19 = 16$. This time is not good. Then Vova goes to sleep after $a_5$ hours, now the time is $16 + 20 = 12$. This time is not good. Then Vova goes to sleep after $a_6$ hours, now the time is $12 + 11 = 23$. This time is good. Then Vova goes to...

I tried it in Python, but could not do it. Can you solve it?

def main():
    import sys
    input = sys.stdin.readline

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

    dp = [[-1] * H for _ in range(N+1)]
    dp[0][0] = 0
    for i, a in enumerate(A):
        for t in range(H):
            if dp[i][t] >= 0:
                dp[i+1][(t+a)%H] = max(dp[i+1][(t+a)%H], dp[i][t] + int(L <= (t+a)%H <= R))
                dp[i + 1][(t + a-1) % H] = max(dp[i + 1][(t + a-1) % H], dp[i][t] + int(L <= (t + a-1) % H <= R))
    print(max(dp[-1]))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1324/F:
You are given a tree consisting of $n$ vertices. A tree is a connected undirected graph with $n-1$ edges. Each vertex $v$ of this tree has a color assigned to it ($a_v = 1$ if the vertex $v$ is white and $0$ if the vertex $v$ is black).

You have to solve the following problem for each vertex $v$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $v$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $cnt_w$ white vertices and $cnt_b$ black vertices, you have to maximize $cnt_w - cnt_b$.

-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of vertices in the tree.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 1$), where $a_i$ is the color of the $i$-th vertex.

Each of the next $n-1$ lines describes an edge of the tree. Edge $i$ is denoted by two integers $u_i$ and $v_i$, the labels of vertices it connects $(1 \le u_i, v_i \le n, u_i \ne v_i$).

It is guaranteed that the given edges form a tree.

-----Output-----

Print $n$ integers $res_1, res_2, \dots, res_n$, where $res_i$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $i$.

-----Examples-----
Input
9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9

Output
2 2 2 2 2 1 1 0 2

Input
4
0 0 1 0
1 2
1 3
1 4

Output
0 -1 1 -1

-----Note-----

The first example is shown below:

[Image]

The black vertices have bold borders.

In the second example, the best subtree for vertices $2, 3$ and $4$ are vertices $2, 3$ and $4$ correspondingly. And the best subtree for the vertex $1$ is the subtree consisting of vertices $1$ and $3$.

I tried it in Python, but could not do it. Can you solve it?

import sys

_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__

def go():
    n = int(input())
    # n, h, l, r = map(int, input().split())
    a = list(map(int, input().split()))
    e = {i: set() for i in range(n)}
    for _ in range(n - 1):
        u, v = list(map(int, input().split()))
        u, v = u - 1, v - 1
        e[u].add(v)
        e[v].add(u)
    ranks = [len(e[i]) for i in range(n)]
    leafs = [i for i in range(n) if ranks[i] == 1]
    index = 0
    vs = {i: {} for i in range(n)}
    done = set()
    while index < len(leafs):
        cur = leafs[index]
        mysum = sum(vs[cur].values())

        if a[cur] == 0:
            mysum -= 1
        else:
            mysum += 1

        for i in e[cur] - done:
            vs[i][cur] = max(mysum, 0)
            ranks[i] -= 1
            if ranks[i] == 1:
                leafs.append(i)
        done.add(cur)
        index += 1

    sums = [0] * n
    que = [ranks.index(0)]
    done = set()
    index = 0
    while index < len(que):
        cur = que[index]

        mysum = sum(vs[cur].values())

        if a[cur] == 0:
            mysum -= 1
        else:
            mysum += 1

        sums[cur] = mysum

        for i in e[cur] - done:
            vs[i][cur] = max(mysum - vs[cur][i], 0)
            que.append(i)

        done.add(cur)
        index += 1

    return ' '.join(map(str,sums))

# t = int(input())
for _ in range(1):
    print(go())


I found an interesting problem on https://codeforces.com/problemset/problem/1325/B:
Ehab has an array $a$ of length $n$. He has just enough free time to make a new array consisting of $n$ copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?

A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.

-----Input-----

The first line contains an integer $t$ — the number of test cases you need to solve. The description of the test cases follows.

The first line of each test case contains an integer $n$ ($1 \le n \le 10^5$) — the number of elements in the array $a$.

The second line contains $n$ space-separated integers $a_1$, $a_2$, $\ldots$, $a_{n}$ ($1 \le a_i \le 10^9$) — the elements of the array $a$.

The sum of $n$ across the test cases doesn't exceed $10^5$.

-----Output-----

For each testcase, output the length of the longest increasing subsequence of $a$ if you concatenate it to itself $n$ times.

-----Example-----
Input
2
3
3 2 1
6
3 1 4 1 5 9

Output
3
5

-----Note-----

In the first sample, the new array is $[3,2,\textbf{1},3,\textbf{2},1,\textbf{3},2,1]$. The longest increasing subsequence is marked in bold.

In the second sample, the longest increasing subsequence will be $[1,3,4,5,9]$.

I tried it in Python, but could not do it. Can you solve it?

from sys import stdin,stdout                           #
import math                                            #
import heapq                                           #
                                                       #
t = 1                                                  #
def aint():                                            #
	return int(input().strip())                        #
def lint():                                            #
	return list(map(int,input().split()))              #
def fint():                                            #
	return list(map(int,stdin.readline().split()))     #
                                                       #
########################################################

def main():
	n=aint()
	l=lint()
	print(len(set(l)))
	#solve

t=int(input())

########################################################
for i in range(t):                                     #
	main()                                             #


I found an interesting problem on https://codeforces.com/problemset/problem/1325/C:
You are given a tree consisting of $n$ nodes. You want to write some labels on the tree's edges such that the following conditions hold:

  Every label is an integer between $0$ and $n-2$ inclusive.  All the written labels are distinct.  The largest value among $MEX(u,v)$ over all pairs of nodes $(u,v)$ is as small as possible.

Here, $MEX(u,v)$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $u$ to node $v$.

-----Input-----

The first line contains the integer $n$ ($2 \le n \le 10^5$) — the number of nodes in the tree.

Each of the next $n-1$ lines contains two space-separated integers $u$ and $v$ ($1 \le u,v \le n$) that mean there's an edge between nodes $u$ and $v$. It's guaranteed that the given graph is a tree.

-----Output-----

Output $n-1$ integers. The $i^{th}$ of them will be the number written on the $i^{th}$ edge (in the input order).

-----Examples-----
Input
3
1 2
1 3

Output
0
1

Input
6
1 2
1 3
2 4
2 5
5 6

Output
0
3
2
4
1

-----Note-----

The tree from the second sample:

[Image]

I tried it in Python, but could not do it. Can you solve it?

import sys
input = sys.stdin.readline

n=int(input())
E=[[] for i in range(n+1)]
D=dict()
DEG=[0]*(n+1)
for i in range(n-1):
    x,y=list(map(int,input().split()))
    E[x].append(y)
    E[y].append(x)
    D[x,y]=i
    D[y,x]=i
    DEG[x]+=1
    DEG[y]+=1

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

LIST=[]
for i in range(n+1):
    if DEG[i]==1:
        LIST.append(i)

if len(LIST)==2:
    for i in range(n-1):
        print(i)

else:
    now=0
    for l in LIST:
        k=E[l][0]
        ANS[D[k,l]]=now
        now+=1

    #print(ANS)

    for i in range(n-1):
        if ANS[i]==-1:
            ANS[i]=now
            now+=1

    for a in ANS:
        print(a)


I found an interesting problem on https://codeforces.com/problemset/problem/1325/D:
Given 2 integers $u$ and $v$, find the shortest array such that bitwise-xor of its elements is $u$, and the sum of its elements is $v$.

-----Input-----

The only line contains 2 integers $u$ and $v$ $(0 \le u,v \le 10^{18})$.

-----Output-----

If there's no array that satisfies the condition, print "-1". Otherwise:

The first line should contain one integer, $n$, representing the length of the desired array. The next line should contain $n$ positive integers, the array itself. If there are multiple possible answers, print any.

-----Examples-----
Input
2 4

Output
2
3 1
Input
1 3

Output
3
1 1 1
Input
8 5

Output
-1
Input
0 0

Output
0

-----Note-----

In the first sample, $3\oplus 1 = 2$ and $3 + 1 = 4$. There is no valid array of smaller length.

Notice that in the fourth sample the array is empty.

I tried it in Python, but could not do it. Can you solve it?

#!/usr/bin/env python
#-*- coding:utf-8 -*-

# Code by H~$~C

from sys import stdin
input = stdin.readline
import math

u, v = map(int, input().split())
if (u == v):
  if (u == 0):
    print(0)
    return
  print(1)
  print(u)
  return
if (u > v):
  print('-1')
  return
if ((v - u) % 2):
  print('-1')
  return

p = (v - u) // 2
if ((u & p) == 0):
  print(2)
  print(p, u + p, sep = ' ')
  return

print(3)
print(u, p, p, sep = ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/1325/E:
You are given an array $a$ of length $n$ 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 $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 10^5$) — the length of $a$.

The second line contains $n$ integers $a_1$, $a_2$, $\ldots$, $a_{n}$ ($1 \le a_i \le 10^6$) — the elements of the array $a$.

-----Output-----

Output the length of the shortest non-empty subsequence of $a$ 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".

-----Examples-----
Input
3
1 4 6

Output
1
Input
4
2 3 6 6

Output
2
Input
3
6 15 10

Output
3
Input
4
2 3 5 7

Output
-1

-----Note-----

In the first sample, you can choose a subsequence $[1]$.

In the second sample, you can choose a subsequence $[6, 6]$.

In the third sample, you can choose a subsequence $[6, 15, 10]$.

In the fourth sample, there is no such subsequence.

I tried it in Python, but could not do it. Can you solve it?

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))]
ec = 0
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)
        import sys
        return
    f += [1] * (2 - len(f))
    u, v = pid[f[0]], pid[f[1]]
    g[u].append((v, ec))
    g[v].append((u, ec))
    ec += 1

def bfs(p):
    d = [-1] * len(pid)
    d[p] = 0
    q = [(p, -1)]
    while q:
        q2 = []
        for u, peid in q:
            for v, eid in g[u]:
                if d[v] != -1:
                    if eid != peid:
                        return d[u] + d[v] + 1
                else:
                    d[v] = d[u] + 1
                    q2.append((v, eid))
        q = q2

ans = -1
for i in range(len(pid)):
    if i > 0 and pr[i - 1] ** 2 >= MAX:
        break
    cyc = bfs(i) or ans
    if ans == -1 or cyc < ans:
        ans = cyc
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1325/F:
It's the year 5555. You have a graph, and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.

Given a connected graph with $n$ vertices, you can choose to either:

  find an independent set that has exactly $\lceil\sqrt{n}\rceil$ vertices.

 find a simple cycle of length at least $\lceil\sqrt{n}\rceil$.

An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.

-----Input-----

The first line contains two integers $n$ and $m$ ($5 \le n \le 10^5$, $n-1 \le m \le 2 \cdot 10^5$) — the number of vertices and edges in the graph.

Each of the next $m$ lines contains two space-separated integers $u$ and $v$ ($1 \le u,v \le n$) that mean there's an edge between vertices $u$ and $v$. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.

-----Output-----

If you choose to solve the first problem, then on the first line print "1", followed by a line containing $\lceil\sqrt{n}\rceil$ distinct integers not exceeding $n$, the vertices in the desired independent set.

If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, $c$, representing the length of the found cycle, followed by a line containing $c$ distinct integers integers not exceeding $n$, the vertices in the desired cycle, in the order they appear in the cycle.

-----Examples-----
Input
6 6
1 3
3 4
4 2
2 6
5 6
5 1

Output
1
1 6 4
Input
6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5

Output
2
4
1 5 2 4
Input
5 4
1 2
1 3
2 4
2 5

Output
1
3 4 5

-----Note-----

In the first sample:

[Image]

Notice that you can solve either problem, so printing the cycle $2-4-3-1-5-6$ is also acceptable.

In the second sample:

[Image]

Notice that if there are multiple answers you can print any, so...

I tried it in Python, but could not do it. Can you solve it?

import sys
input = sys.stdin.readline

n, m = list(map(int, input().split()))
e = [tuple(map(int, input().split())) for _ in range(m)]
g = [[] for _ in range(n + 1)]
for u, v in e:
    g[u].append(v)
    g[v].append(u)

req = 1
while req * req < n:
    req += 1

def dfs():
    dep = [0] * (n + 1)
    par = [0] * (n + 1)
    mk = [0] * (n + 1)
    st = [1]
    st2 = []
    while st:
        u = st.pop()
        if dep[u]:
            continue
        st2.append(u)
        dep[u] = dep[par[u]] + 1
        for v in g[u]:
            if not dep[v]:
                par[v] = u
                st.append(v)
            elif dep[u] - dep[v] + 1 >= req:
                ans = []
                while u != par[v]:
                    ans.append(u)
                    u = par[u]
                return (None, ans)
    while st2:
        u = st2.pop()
        if not mk[u]:
            for v in g[u]:
                if dep[v] < dep[u]:
                    mk[v] = 1
    return ([u for u in range(1, n + 1) if not mk[u]][:req], None)

iset, cyc = dfs()
if iset:
    print(1)
    print(*iset)
else:
    print(2)
    print(len(cyc))
    print(*cyc)


I found an interesting problem on https://codeforces.com/problemset/problem/1326/B:
Alicia has an array, $a_1, a_2, \ldots, a_n$, of non-negative integers. For each $1 \leq i \leq n$, she has found a non-negative integer $x_i = max(0, a_1, \ldots, a_{i-1})$. Note that for $i=1$, $x_i = 0$.

For example, if Alicia had the array $a = \{0, 1, 2, 0, 3\}$, then $x = \{0, 0, 1, 2, 2\}$.

Then, she calculated an array, $b_1, b_2, \ldots, b_n$: $b_i = a_i - x_i$.

For example, if Alicia had the array $a = \{0, 1, 2, 0, 3\}$, $b = \{0-0, 1-0, 2-1, 0-2, 3-2\} = \{0, 1, 1, -2, 1\}$.

Alicia gives you the values $b_1, b_2, \ldots, b_n$ and asks you to restore the values $a_1, a_2, \ldots, a_n$. Can you help her solve the problem?

-----Input-----

The first line contains one integer $n$ ($3 \leq n \leq 200\,000$) – the number of elements in Alicia's array.

The next line contains $n$ integers, $b_1, b_2, \ldots, b_n$ ($-10^9 \leq b_i \leq 10^9$).

It is guaranteed that for the given array $b$ there is a solution $a_1, a_2, \ldots, a_n$, for all elements of which the following is true: $0 \leq a_i \leq 10^9$.

-----Output-----

Print $n$ integers, $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 10^9$), such that if you calculate $x$ according to the statement, $b_1$ will be equal to $a_1 - x_1$, $b_2$ will be equal to $a_2 - x_2$, ..., and $b_n$ will be equal to $a_n - x_n$.

It is guaranteed that there exists at least one solution for the given tests. It can be shown that the solution is unique.

-----Examples-----
Input
5
0 1 1 -2 1

Output
0 1 2 0 3
Input
3
1000 999999000 -1000000000

Output
1000 1000000000 0
Input
5
2 1 2 2 3

Output
2 3 5 7 10

-----Note-----

The first test was described in the problem statement.

In the second test, if Alicia had an array $a = \{1000, 1000000000, 0\}$, then $x = \{0, 1000, 1000000000\}$ and $b = \{1000-0, 1000000000-1000, 0-1000000000\} = \{1000, 999999000, -1000000000\}$.

I tried it in Python, but could not do it. Can you solve it?

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

msf = 0
res = []
for e in ls:
    v = msf + e
    msf = max(msf, v)
    res.append(v)

for e in res:
    print(e, end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/1326/C:
You are given a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$ and an integer $k$, such that $1 \leq k \leq n$. A permutation means that every number from $1$ to $n$ is contained in $p$ exactly once.

Let's consider all partitions of this permutation into $k$ disjoint segments. Formally, a partition is a set of segments $\{[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\}$, such that:

  $1 \leq l_i \leq r_i \leq n$ for all $1 \leq i \leq k$;  For all $1 \leq j \leq n$ there exists exactly one segment $[l_i, r_i]$, such that $l_i \leq j \leq r_i$.

Two partitions are different if there exists a segment that lies in one partition but not the other.

Let's calculate the partition value, defined as $\sum\limits_{i=1}^{k} {\max\limits_{l_i \leq j \leq r_i} {p_j}}$, for all possible partitions of the permutation into $k$ disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by $998\,244\,353$.

-----Input-----

The first line contains two integers, $n$ and $k$ ($1 \leq k \leq n \leq 200\,000$) — the size of the given permutation and the number of segments in a partition.

The second line contains $n$ different integers $p_1, p_2, \ldots, p_n$ ($1 \leq p_i \leq n$) — the given permutation.

-----Output-----

Print two integers — the maximum possible partition value over all partitions of the permutation into $k$ disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo $998\,244\,353$.

Please note that you should only find the second value modulo $998\,244\,353$.

-----Examples-----
Input
3 2
2 1 3

Output
5 2

Input
5 5
2 1 5 3 4

Output
15 1

Input
7 3
2 7 3 1 5 4 6

Output
18 6

-----Note-----

In the first test, for $k = 2$, there exists only two valid partitions: $\{[1, 1], [2, 3]\}$ and $\{[1, 2], [3, 3]\}$. For each partition, the partition value is equal to $2...

I tried it in Python, but could not do it. Can you solve it?

n,k=map(int,input().split())
L=list(map(int,input().split()))
ind=[]
for i in range(n):
    if L[i]>n-k:ind.append(i)
m=1
for i in range(len(ind)-1):
    m*=(ind[i+1]-ind[i])
    m%=998244353
print(((n*(n+1)//2)-((n-k)*((n-k)+1))//2),m)


I found an interesting problem on https://codeforces.com/problemset/problem/1326/D1:
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.

You are given a string $s$, consisting of lowercase English letters. Find the longest string, $t$, which satisfies the following conditions:   The length of $t$ does not exceed the length of $s$.  $t$ is a palindrome.  There exists two strings $a$ and $b$ (possibly empty), such that $t = a + b$ ( "$+$" represents concatenation), and $a$ is prefix of $s$ while $b$ is suffix of $s$.

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \leq t \leq 1000$), the number of test cases. The next $t$ lines each describe a test case.

Each test case is a non-empty string $s$, consisting of lowercase English letters.

It is guaranteed that the sum of lengths of strings over all test cases does not exceed $5000$.

-----Output-----

For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.

-----Example-----
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba

Output
a
abcdfdcba
xyzyx
c
abba

-----Note-----

In the first test, the string $s = $"a" satisfies all conditions.

In the second test, the string "abcdfdcba" satisfies all conditions, because:  Its length is $9$, which does not exceed the length of the string $s$, which equals $11$.  It is a palindrome.  "abcdfdcba" $=$ "abcdfdc" $+$ "ba", and "abcdfdc" is a prefix of $s$ while "ba" is a suffix of $s$.

It can be proven that there does not exist a longer string which satisfies the conditions.

In the fourth test, the string "c" is correct, because "c" $=$ "c" $+$ "" and $a$ or $b$ can be empty. The other possible solution for this test is "s".

I tried it in Python, but could not do it. Can you solve it?

def ispalin(s):
    ans = True
    for i in range(len(s)):
        if s[i] != s[len(s)-1-i]:
            ans = False
            break
        if i > len(s)//2:
            break
    return ans

for _ in range(int(input())):
    s = input()
    k = ''
    l = ''
    for j in range(len(s)):
        if s[j] == s[len(s)-1-j]:
            k += s[j]
            l = s[j] + l
        else:
            break
    if j != len(s)-1:
        t = ''
        y = ''
        for r in range(j,len(s)-j):
            t += s[r]
            if ispalin(t):
                y = t
        q = ''
        v = ''
        for r in range(len(s)-j-1,j-1,-1):
            q = s[r] + q
            if ispalin(q):
                v = q
        if len(v) > len(y):
            print(k+v+l)
        else:
            print(k+y+l)
    else:
        print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1326/D2:
This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.

You are given a string $s$, consisting of lowercase English letters. Find the longest string, $t$, which satisfies the following conditions:   The length of $t$ does not exceed the length of $s$.  $t$ is a palindrome.  There exists two strings $a$ and $b$ (possibly empty), such that $t = a + b$ ( "$+$" represents concatenation), and $a$ is prefix of $s$ while $b$ is suffix of $s$.

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \leq t \leq 10^5$), the number of test cases. The next $t$ lines each describe a test case.

Each test case is a non-empty string $s$, consisting of lowercase English letters.

It is guaranteed that the sum of lengths of strings over all test cases does not exceed $10^6$.

-----Output-----

For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.

-----Example-----
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba

Output
a
abcdfdcba
xyzyx
c
abba

-----Note-----

In the first test, the string $s = $"a" satisfies all conditions.

In the second test, the string "abcdfdcba" satisfies all conditions, because:  Its length is $9$, which does not exceed the length of the string $s$, which equals $11$.  It is a palindrome.  "abcdfdcba" $=$ "abcdfdc" $+$ "ba", and "abcdfdc" is a prefix of $s$ while "ba" is a suffix of $s$.

It can be proven that there does not exist a longer string which satisfies the conditions.

In the fourth test, the string "c" is correct, because "c" $=$ "c" $+$ "" and $a$ or $b$ can be empty. The other possible solution for this test is "s".

I tried it in Python, but could not do it. Can you solve it?

def main():
    import sys
    input = sys.stdin.readline

    # 偶数長含めた回文の長さを求める
    # R[2*i] = L: S[i]を中心とする奇数長の最大回文
    # R[2*i+1] = L: S[i:i+2]を中心とする偶数長の最大回文
    # ダミー文字を挟むが、各 R[i] は実際の回文の文字列長と一致する
    def manacher(S):
        C = []
        for a in S:
            C.append(a)
            C.append(0)
        C.pop()

        L = len(C)

        R = [0] * L

        i = j = 0
        while i < L:
            while j <= i < L - j and C[i - j] == C[i + j]:
                j += 1
            R[i] = j
            k = 1
            while j - R[i - k] > k <= i < L - k:
                R[i + k] = R[i - k]
                k += 1
            i += k
            j -= k
        return R

    for _ in range(int(input())):
        S = input().rstrip('\n')
        N = len(S)
        if N == 1:
            print(S)
            continue
        ii = -1
        for i in range(N//2):
            if S[i] != S[N-1-i]:
                break
            ii = i
        if ii >= 0:
            ss = S[:ii+1]
            S = S[ii+1:N-ii-1]
        else:
            ss = ''
        N = len(S)
        if N == 0:
            print(''.join([ss, ss[::-1]]))
            continue
        R = manacher(S)
        M = 0
        iii = 0
        for i in range(N):
            if R[i*2] > M:
                if R[i*2]%2 == 0:
                    continue
                k = R[i*2] // 2
                if i-k == 0 or i+k == N-1:
                    M = R[i*2]
                    iii = i
        for i in range(N-1):
            if R[i*2+1] > M:
                if R[i*2+1]%2 == 1:
                    continue
                k = R[i*2+1] // 2
                if i-k+1 == 0 or i+k == N-1:
                    M = R[i*2+1]
                    iii = i
        if M & 1:
            ans = S[iii - M//2: iii + M // 2 + 1]
        else:
            ans = S[iii - M // 2 + 1: iii + M // 2 + 1]
        print(''.join([ss, ans, ss[::-1]]))
        #print(S, R, iii, M)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1326/F1:
This is the easy version of the problem. The difference is constraints on the number of wise men and the time limit. You can make hacks only if all versions of this task are solved.

$n$ wise men live in a beautiful city. Some of them know each other.

For each of the $n!$ possible permutations $p_1, p_2, \ldots, p_n$ of the wise men, let's generate a binary string of length $n-1$: for each $1 \leq i < n$ set $s_i=1$ if $p_i$ and $p_{i+1}$ know each other, and $s_i=0$ otherwise.

For all possible $2^{n-1}$ binary strings, find the number of permutations that produce this binary string.

-----Input-----

The first line of input contains one integer $n$ ($2 \leq n \leq 14)$  — the number of wise men in the city.

The next $n$ lines contain a binary string of length $n$ each, such that the $j$-th character of the $i$-th string is equal to '1' if wise man $i$ knows wise man $j$, and equals '0' otherwise.

It is guaranteed that if the $i$-th man knows the $j$-th man, then the $j$-th man knows $i$-th man and no man knows himself.

-----Output-----

Print $2^{n-1}$ space-separated integers. For each $0 \leq x < 2^{n-1}$:

  Let's consider a string $s$ of length $n-1$, such that $s_i = \lfloor \frac{x}{2^{i-1}} \rfloor \bmod 2$ for all $1 \leq i \leq n - 1$.  The $(x+1)$-th number should be equal to the required answer for $s$.

-----Examples-----
Input
3
011
101
110

Output
0 0 0 6

Input
4
0101
1000
0001
1010

Output
2 2 6 2 2 6 2 2

-----Note-----

In the first test, each wise man knows each other, so every permutation will produce the string $11$.

In the second test:

  If $p = \{1, 2, 3, 4\}$, the produced string is $101$, because wise men $1$ and $2$ know each other, $2$ and $3$ don't know each other, and $3$ and $4$ know each other;  If $p = \{4, 1, 2, 3\}$, the produced string is $110$, because wise men $1$ and $4$ know each other, $1$ and $2$ know each other and $2$, and $3$ don't know each other;  If $p = \{1, 3, 2, 4\}$, the produced string is $000$, because wise men $1$ and $3$ don't know each...

I tried it in Python, but could not do it. Can you solve it?

from sys import stdout

n = int(input())

class Person:

    num = n - 1

    def __init__(self, rel):
        self.relationship = int(rel, 2)

    def __getitem__(self, k):
        return (self.relationship >> Person.num - k) & 1

rel = [Person(input()) for _ in range(n)]

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

for people in range(1, 1 << n):
    ones = [i for i in range(n) if people & (1 << i)]
    # print(f'ones: {ones}')
    one_num = len(ones)

    if one_num == 1:
        dp[people][ones[0]] = [1]
        continue

    for i in ones:
        dp[people][i] = [0] * (1 << one_num - 1)
        pre_people = people ^ (1 << i)
        for j in ones:
            if j == i:
                continue
            for pre_s, times in enumerate(dp[pre_people][j]):
                s = pre_s | (rel[j][i] << one_num - 2)
                # print(f'dp[{people}][{i}][{s}]: {dp[people][i][s]}')
                dp[people][i][s] += times

people = (1 << n) - 1

for s in range(1 << (n-1)):
    ans = 0
    for i in range(n):
        ans += dp[people][i][s]
    print(ans, end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/1327/A:
You are given two integers $n$ and $k$. Your task is to find if $n$ can be represented as a sum of $k$ distinct positive odd (not divisible by $2$) integers or not.

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 10^5$) — the number of test cases.

The next $t$ lines describe test cases. The only line of the test case contains two integers $n$ and $k$ ($1 \le n, k \le 10^7$).

-----Output-----

For each test case, print the answer — "YES" (without quotes) if $n$ can be represented as a sum of $k$ distinct positive odd (not divisible by $2$) integers and "NO" otherwise.

-----Example-----
Input
6
3 1
4 2
10 3
10 2
16 4
16 5

Output
YES
YES
NO
YES
YES
NO

-----Note-----

In the first test case, you can represent $3$ as $3$.

In the second test case, the only way to represent $4$ is $1+3$.

In the third test case, you cannot represent $10$ as the sum of three distinct positive odd integers.

In the fourth test case, you can represent $10$ as $3+7$, for example.

In the fifth test case, you can represent $16$ as $1+3+5+7$.

In the sixth test case, you cannot represent $16$ as the sum of five distinct positive odd integers.

I tried it in Python, but could not do it. Can you solve it?

for _ in range(int(input())):
	n,k = map(int,input().split())
	if(n >= k*k and n%2 == (k*k)%2):
		print("YES")
	else:
		print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1327/C:
Petya has a rectangular Board of size $n \times m$. Initially, $k$ chips are placed on the board, $i$-th chip is located in the cell at the intersection of $sx_i$-th row and $sy_i$-th column.

In one action, Petya can move all the chips to the left, right, down or up by $1$ cell.

If the chip was in the $(x, y)$ cell, then after the operation:   left, its coordinates will be $(x, y - 1)$;  right, its coordinates will be $(x, y + 1)$;  down, its coordinates will be $(x + 1, y)$;  up, its coordinates will be $(x - 1, y)$.

If the chip is located by the wall of the board, and the action chosen by Petya moves it towards the wall, then the chip remains in its current position.

Note that several chips can be located in the same cell.

For each chip, Petya chose the position which it should visit. Note that it's not necessary for a chip to end up in this position.

Since Petya does not have a lot of free time, he is ready to do no more than $2nm$ actions.

You have to find out what actions Petya should do so that each chip visits the position that Petya selected for it at least once. Or determine that it is not possible to do this in $2nm$ actions.

-----Input-----

The first line contains three integers $n, m, k$ ($1 \le n, m, k \le 200$) — the number of rows and columns of the board and the number of chips, respectively.

The next $k$ lines contains two integers each $sx_i, sy_i$ ($ 1 \le sx_i \le n, 1 \le sy_i \le m$) — the starting position of the $i$-th chip.

The next $k$ lines contains two integers each $fx_i, fy_i$ ($ 1 \le fx_i \le n, 1 \le fy_i \le m$) — the position that the $i$-chip should visit at least once.

-----Output-----

In the first line print the number of operations so that each chip visits the position that Petya selected for it at least once.

In the second line output the sequence of operations. To indicate operations left, right, down, and up, use the characters $L, R, D, U$ respectively.

If the required sequence does not exist, print -1 in the single...

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/1327/E:
You wrote down all integers from $0$ to $10^n - 1$, padding them with leading zeroes so their lengths are exactly $n$. For example, if $n = 3$ then you wrote out 000, 001, ..., 998, 999.

A block in an integer $x$ is a consecutive segment of equal digits that cannot be extended to the left or to the right.

For example, in the integer $00027734000$ there are three blocks of length $1$, one block of length $2$ and two blocks of length $3$.

For all integers $i$ from $1$ to $n$ count the number of blocks of length $i$ among the written down integers.

Since these integers may be too large, print them modulo $998244353$.

-----Input-----

The only line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$).

-----Output-----

In the only line print $n$ integers. The $i$-th integer is equal to the number of blocks of length $i$.

Since these integers may be too large, print them modulo $998244353$.

-----Examples-----
Input
1

Output
10

Input
2

Output
180 10

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
arr = [0]
sm = 0
smarr = 0
ten = 1
MOD = 998244353
for i in range(1, n + 1):
    ten = (ten * 10) % MOD
    all = i * ten % MOD
    sm = (sm + smarr) % MOD
    x = (all - sm + MOD) % MOD
    arr.append(x)
    smarr = (smarr + x) % MOD
    sm = (sm + x) % MOD
arr.reverse()
arr.pop()
print(*arr)


I found an interesting problem on https://codeforces.com/problemset/problem/1328/A:
You are given two positive integers $a$ and $b$. In one move you can increase $a$ by $1$ (replace $a$ with $a+1$). Your task is to find the minimum number of moves you need to do in order to make $a$ divisible by $b$. It is possible, that you have to make $0$ moves, as $a$ is already divisible by $b$. You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow.

The only line of the test case contains two integers $a$ and $b$ ($1 \le a, b \le 10^9$).

-----Output-----

For each test case print the answer — the minimum number of moves you need to do in order to make $a$ divisible by $b$.

-----Example-----
Input
5
10 4
13 9
100 13
123 456
92 46

Output
2
5
4
333
0

I tried it in Python, but could not do it. Can you solve it?

import sys
def input():
	return sys.stdin.readline()[:-1]
t = int(input())
for _ in range(t):
	a, b = map(int, input().split())
	if a%b == 0:
		print(0)
	else:
		print(b - a%b)