I found an interesting problem on https://codeforces.com/problemset/problem/1392/C:
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.

Omkar currently has $n$ supports arranged in a line, the $i$-th of which has height $a_i$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $1$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $1$ to each of their heights.

Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!

An array $b$ is a subsegment of an array $c$ if $b$ can be obtained from $c$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.

An array $b_1, b_2, \dots, b_n$ is called nondecreasing if $b_i\le b_{i+1}$ for every $i$ from $1$ to $n-1$.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \leq t \leq 100$). Description of the test cases follows.

The first line of each test case contains an integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the number of supports Omkar has.

The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ $(0 \leq a_{i} \leq 10^9)$ — the heights of the supports.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.

-----Output-----

For each test case, output a single integer — the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.

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

Output
3
2
0

-----Note-----

The subarray with which Omkar performs the operation is bolded.

In the first test case:

First operation:

$[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$

Second operation:

$[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$

Third operation:

$[5,...

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

for _ in range(int(input())):
    n = int(input())
    a = [0]+[*list(map(int,input().split()))]
    d = [0]*(n+1)
    for i in range(1,n+1):
        d[i]=a[i]-a[i-1]
    s = 0
    i = 1
    while(i<=n):
        if(d[i]>=0):
            i+=1
            continue
        mn = d[i]
        while(i+1<=n and d[i+1]<0):
            i+=1
            mn += d[i]
        s += (-1)*mn
        i+=1
    print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1392/D:
Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are $n$ players arranged in a circle, so that for all $j$ such that $2 \leq j \leq n$, player $j - 1$ is to the left of the player $j$, and player $j$ is to the right of player $j - 1$. Additionally, player $n$ is to the left of player $1$, and player $1$ is to the right of player $n$.

Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either $0$, $1$, or $2$ other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly $1$ other player, then they should logically attack that player in response. If instead a player is being attacked by $0$ or $2$ other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.

Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the $n$ players in the game to make them instead attack another player  — i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left.

Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The descriptions of the test cases follows.

The first line of each test case contains one integer $n$ ($3 \leq n \leq 2 \cdot 10^5$)  — the amount of players (and therefore beds) in this game of Bed...

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/1392/F:
Omkar is standing at the foot of Celeste mountain. The summit is $n$ meters away from him, and he can see all of the mountains up to the summit, so for all $1 \leq j \leq n$ he knows that the height of the mountain at the point $j$ meters away from himself is $h_j$ meters. It turns out that for all $j$ satisfying $1 \leq j \leq n - 1$, $h_j < h_{j + 1}$ (meaning that heights are strictly increasing).

Suddenly, a landslide occurs! While the landslide is occurring, the following occurs: every minute, if $h_j + 2 \leq h_{j + 1}$, then one square meter of dirt will slide from position $j + 1$ to position $j$, so that $h_{j + 1}$ is decreased by $1$ and $h_j$ is increased by $1$. These changes occur simultaneously, so for example, if $h_j + 2 \leq h_{j + 1}$ and $h_{j + 1} + 2 \leq h_{j + 2}$ for some $j$, then $h_j$ will be increased by $1$, $h_{j + 2}$ will be decreased by $1$, and $h_{j + 1}$ will be both increased and decreased by $1$, meaning that in effect $h_{j + 1}$ is unchanged during that minute.

The landslide ends when there is no $j$ such that $h_j + 2 \leq h_{j + 1}$. Help Omkar figure out what the values of $h_1, \dots, h_n$ will be after the landslide ends. It can be proven that under the given constraints, the landslide will always end in finitely many minutes.

Note that because of the large amount of input, it is recommended that your code uses fast IO.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 10^6$).

The second line contains $n$ integers $h_1, h_2, \dots, h_n$ satisfying $0 \leq h_1 < h_2 < \dots < h_n \leq 10^{12}$ — the heights.

-----Output-----

Output $n$ integers, where the $j$-th integer is the value of $h_j$ after the landslide has stopped.

-----Example-----
Input
4
2 6 7 8

Output
5 5 6 7

-----Note-----

Initially, the mountain has heights $2, 6, 7, 8$.

In the first minute, we have $2 + 2 \leq 6$, so $2$ increases to $3$ and $6$ decreases to $5$, leaving $3, 5, 7, 8$.

In the second minute, we have $3 + 2 \leq 5$ and $5 + 2 \leq 7$, so...

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

n = int(input());tot = sum(map(int, input().split()));extra = (n * (n - 1))//2;smol = (tot - extra) // n;out = [smol + i for i in range(n)]
for i in range(tot - sum(out)):out[i] += 1
print(' '.join(map(str,out)))


I found an interesting problem on https://codeforces.com/problemset/problem/1392/H:
zscoder has a deck of $n+m$ custom-made cards, which consists of $n$ cards labelled from $1$ to $n$ and $m$ jokers. Since zscoder is lonely, he wants to play a game with himself using those cards.

Initially, the deck is shuffled uniformly randomly and placed on the table. zscoder has a set $S$ which is initially empty.

Every second, zscoder draws the top card from the deck.   If the card has a number $x$ written on it, zscoder removes the card and adds $x$ to the set $S$.  If the card drawn is a joker, zscoder places all the cards back into the deck and reshuffles (uniformly randomly) the $n+m$ cards to form a new deck (hence the new deck now contains all cards from $1$ to $n$ and the $m$ jokers). Then, if $S$ currently contains all the elements from $1$ to $n$, the game ends. Shuffling the deck doesn't take time at all.

What is the expected number of seconds before the game ends? We can show that the answer can be written in the form $\frac{P}{Q}$ where $P, Q$ are relatively prime integers and $Q \neq 0 \bmod 998244353$. Output the value of $(P \cdot Q^{-1})$ modulo $998244353$.

-----Input-----

The only line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^{6}$).

-----Output-----

Output a single integer, the value of $(P \cdot Q^{-1})$ modulo $998244353$.

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

Output
5

Input
3 2

Output
332748127

Input
14 9

Output
969862773

-----Note-----

For the first sample, it can be proven that the expected time before the game ends is $5$ seconds.

For the second sample, it can be proven that the expected time before the game ends is $\frac{28}{3}$ seconds.

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

nn = 2002002
P = 998244353
fa = [1] * (nn+1)
fainv = [1] * (nn+1)
for i in range(nn):
    fa[i+1] = fa[i] * (i+1) % P
fainv[-1] = pow(fa[-1], P-2, P)
for i in range(nn)[::-1]:
    fainv[i] = fainv[i+1] * (i+1) % P

N, M = list(map(int, input().split()))
invM1 = pow(M + 1, P - 2, P)
pre = 1
for i in range(2, N + 2):
    nu = ((M + i - 1) + (i - 1) * pre) * (M + 1) + M * (N - i + 1)
    de = invM1 * fainv[i-1] % P * fa[i-2] % P
    pre = nu * de % P
print(pre)


I found an interesting problem on https://codeforces.com/problemset/problem/1393/A:
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal.

The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size $1\times1$, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks.

The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.

Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!

Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.

The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 100$): the number of grids of the games.

Each of the next $T$ lines contains a single integer $n$ ($1 \le n \le 10^9$): the size of the side of the grid of the game.

-----Output-----

For each grid of the game print the minimum number of turns required to build a chess coloring pattern out of blocks on it.

-----Example-----
Input
2
3
4

Output
2
3

-----Note-----

For $3\times3$ grid ponies can make two following moves: [Image]

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

read = lambda: map(int, input().split())
t = int(input())
for _ in range(t):
    n = int(input())
    print((n + 2) // 2)


I found an interesting problem on https://codeforces.com/problemset/problem/1393/B:
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).

Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $n$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format:

  $+$ $x$: the storehouse received a plank with length $x$  $-$ $x$: one plank with length $x$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $x$).

Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!

We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^5$): the initial amount of planks at the company's storehouse, the second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^5$): the lengths of the planks.

The third line contains a single integer $q$ ($1 \le q \le 10^5$): the number of events in the company. Each of the next $q$ lines contains a description of the events in a given format: the type of the event (a symbol $+$ or $-$) is given first, then goes the integer $x$ ($1 \le x \le 10^5$).

-----Output-----

After every event in the company, print...

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

import sys
input=sys.stdin.readline
n=int(input())
L=list(map(int,input().split()))
q=int(input())
ct2=0
ct4=0
ct6=0
ct8=0
ct=[0]*(10**5+10)
for i in L:ct[i]+=1
for i in ct:
    if i>1:ct2+=1
    if i>3:ct4+=1
    if i>5:ct6+=1
    if i>7:ct8+=1
for i in ' '*q:
    a,b=input().split()
    b=int(b)
    if a=='+':
        ct[b]+=1
        if ct[b]==2:ct2+=1
        if ct[b]==4:ct4+=1
        if ct[b]==6:ct6+=1
        if ct[b]==8:ct8+=1
    else:
        ct[b]-=1
        if ct[b]==1:ct2-=1
        if ct[b]==3:ct4-=1
        if ct[b]==5:ct6-=1
        if ct[b]==7:ct8-=1
    if ct2>=2 and ct6>=1:print('YES')
    elif ct2>=3 and ct4>=1:print('YES')
    elif ct4>=2:print('YES')
    elif ct8:print('YES')
    else:print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1393/C:
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.

Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.

Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!

Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 100$): the number of bags for which you need to solve the problem.

The first line of each bag description contains a single integer $n$ ($2 \le n \le 10^5$): the number of patty-cakes in it. The second line of the bag description contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling.

It is guaranteed that the sum of $n$ over all bags does not exceed $10^5$.

-----Output-----

For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.

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

Output
3
2
0
4

-----Note-----

For the first bag...

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

mod=998244353
for _ in range (int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    d=dict()
    for i in a:
        if i in d:
            d[i]+=1
        else:
            d[i]=1
    l=list()
    for i in d:
        l.append((d[i],i))
    l.sort(reverse=True)
    c=0
    lim=l[0][0]
    #print(lim)
    extra=0
    r=0
    for i in l:
        if i[0]==lim:
            r+=1
        else:
            extra+=i[0]
    if lim==1:
        print(n)
    else:
        r+=extra//(lim-1)
        print(r-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1393/D:
Carousel Boutique is busy again! Rarity has decided to visit the pony ball and she surely needs a new dress, because going out in the same dress several times is a sign of bad manners. First of all, she needs a dress pattern, which she is going to cut out from the rectangular piece of the multicolored fabric.

The piece of the multicolored fabric consists of $n \times m$ separate square scraps. Since Rarity likes dresses in style, a dress pattern must only include scraps sharing the same color. A dress pattern must be the square, and since Rarity is fond of rhombuses, the sides of a pattern must form a $45^{\circ}$ angle with sides of a piece of fabric (that way it will be resembling the traditional picture of a rhombus).

Examples of proper dress patterns: [Image] Examples of improper dress patterns: [Image] The first one consists of multi-colored scraps, the second one goes beyond the bounds of the piece of fabric, the third one is not a square with sides forming a $45^{\circ}$ angle with sides of the piece of fabric.

Rarity wonders how many ways to cut out a dress pattern that satisfies all the conditions that do exist. Please help her and satisfy her curiosity so she can continue working on her new masterpiece!

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2000$). Each of the next $n$ lines contains $m$ characters: lowercase English letters, the $j$-th of which corresponds to scrap in the current line and in the $j$-th column. Scraps having the same letter share the same color, scraps having different letters have different colors.

-----Output-----

Print a single integer: the number of ways to cut out a dress pattern to satisfy all of Rarity's conditions.

-----Examples-----
Input
3 3
aaa
aaa
aaa

Output
10

Input
3 4
abab
baba
abab

Output
12

Input
5 5
zbacg
baaac
aaaaa
eaaad
weadd

Output
31

-----Note-----

In the first example, all the dress patterns of size $1$ and one of size $2$ are satisfactory.

In the second example, only the dress patterns of size...

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

def tc():
    n, m = list(map(int, input().split()))
    mat = [input() for _ in range(n)]
    alpha = 'abcdefghijklmnopqrstuvwxyz'

    dp = [[0] * m for _ in range(n)]
    ans = 0
    for i in range(n):
        for j in range(m):

            if j == 0 or j == m - 1 or i < 2:
                dp[i][j] = 1
            elif mat[i][j] == mat[i - 1][j] and mat[i][j] == mat[i - 1][j - 1] and mat[i][j] == mat[i - 1][j + 1] and mat[i][j] == mat[i - 2][j]:
                dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1], dp[i - 1][j + 1], dp[i - 2][j]) + 1
            else:
                dp[i][j] = 1
            ans += dp[i][j]

    print(ans)

#################
tc()


I found an interesting problem on https://codeforces.com/problemset/problem/1395/A:
Boboniu gives you

  $r$ red balls,  $g$ green balls,  $b$ blue balls,  $w$ white balls.

He allows you to do the following operation as many times as you want:

  Pick a red ball, a green ball, and a blue ball and then change their color to white.

You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations.

-----Input-----

The first line contains one integer $T$ ($1\le T\le 100$) denoting the number of test cases.

For each of the next $T$ cases, the first line contains four integers $r$, $g$, $b$ and $w$ ($0\le r,g,b,w\le 10^9$).

-----Output-----

For each test case, print "Yes" if it's possible to arrange all the balls into a palindrome after doing several (possibly zero) number of described operations. Otherwise, print "No".

-----Example-----
Input
4
0 1 1 1
8 1 9 3
0 0 0 0
1000000000 1000000000 1000000000 1000000000

Output
No
Yes
Yes
Yes

-----Note-----

In the first test case, you're not able to do any operation and you can never arrange three balls of distinct colors into a palindrome.

In the second test case, after doing one operation, changing $(8,1,9,3)$ to $(7,0,8,6)$, one of those possible palindromes may be "rrrwwwbbbbrbbbbwwwrrr".

A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. For example, "rggbwbggr", "b", "gg" are palindromes while "rgbb", "gbbgr" are not. Notice that an empty word, phrase, or sequence is palindrome.

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

import sys
# sys.setrecursionlimit(10**6)
input=sys.stdin.readline
t=int(input())
def check(r,g,b,w):
    if(r>=0 and g>=0 and b>=0 and w>=0):
        c=0
        if(r%2!=0):
            c+=1
        if(g%2!=0):
            c+=1
        if(b%2!=0):
            c+=1
        if(w%2!=0):
            c+=1
        if(c==0 or c==1):
            return True

    return False
for t1 in range(t):
    r,g,b,w=list(map(int,input().split(" ")))
    if(check(r,g,b,w) or check(r-1,g-1,b-1,w+1)):
        print("Yes")
    else:
        print("No")


I found an interesting problem on https://codeforces.com/problemset/problem/1395/B:
Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.

You are a new applicant for his company. Boboniu will test you with the following chess question:

Consider a $n\times m$ grid (rows are numbered from $1$ to $n$, and columns are numbered from $1$ to $m$). You have a chess piece, and it stands at some cell $(S_x,S_y)$ which is not on the border (i.e. $2 \le S_x \le n-1$ and $2 \le S_y \le m-1$).

From the cell $(x,y)$, you can move your chess piece to $(x,y')$ ($1\le y'\le m, y' \neq y$) or $(x',y)$ ($1\le x'\le n, x'\neq x$). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.

Your goal is to visit each cell exactly once. Can you find a solution?

Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.

-----Input-----

The only line of the input contains four integers $n$, $m$, $S_x$ and $S_y$ ($3\le n,m\le 100$, $2 \le S_x \le n-1$, $2 \le S_y \le m-1$) — the number of rows, the number of columns, and the initial position of your chess piece, respectively.

-----Output-----

You should print $n\cdot m$ lines.

The $i$-th line should contain two integers $x_i$ and $y_i$ ($1 \leq x_i \leq n$, $1 \leq y_i \leq m$), denoting the $i$-th cell that you visited. You should print exactly $nm$ pairs $(x_i, y_i)$, they should cover all possible pairs $(x_i, y_i)$, such that $1 \leq x_i \leq n$, $1 \leq y_i \leq m$.

We can show that under these constraints there always exists a solution. If there are multiple answers, print any.

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

Output
2 2
1 2
1 3
2 3
3 3
3 2
3 1
2 1
1 1

Input
3 4 2 2

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

-----Note-----

Possible routes for two examples: [Image]

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

n, m, sx, sy = map(int, input().split())
used = [[False] * m for i in range(n)]
print(sx, sy)
for j in range(1, sy):
    print(sx, j)
for j in range(sy + 1, m + 1):
    print(sx, j)
for i in range(n, 0, -1):
    if i != sx:
        print(i, m)
j = m - 1
k = 0
while j:
    k += 1
    if k % 2 == 1:
        for i in range(1, n + 1):
            if i != sx:
                print(i, j)
    else:
        for i in range(n, 0, -1):
            if i != sx:
                print(i, j)
    j -= 1


I found an interesting problem on https://codeforces.com/problemset/problem/1395/C:
Boboniu likes bit operations. He wants to play a game with you.

Boboniu gives you two sequences of non-negative integers $a_1,a_2,\ldots,a_n$ and $b_1,b_2,\ldots,b_m$.

For each $i$ ($1\le i\le n$), you're asked to choose a $j$ ($1\le j\le m$) and let $c_i=a_i\& b_j$, where $\&$ denotes the bitwise AND operation. Note that you can pick the same $j$ for different $i$'s.

Find the minimum possible $c_1 | c_2 | \ldots | c_n$, where $|$ denotes the bitwise OR operation.

-----Input-----

The first line contains two integers $n$ and $m$ ($1\le n,m\le 200$).

The next line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($0\le a_i < 2^9$).

The next line contains $m$ integers $b_1,b_2,\ldots,b_m$ ($0\le b_i < 2^9$).

-----Output-----

Print one integer: the minimum possible $c_1 | c_2 | \ldots | c_n$.

-----Examples-----
Input
4 2
2 6 4 0
2 4

Output
2
Input
7 6
1 9 1 9 8 1 0
1 1 4 5 1 4

Output
0
Input
8 5
179 261 432 162 82 43 10 38
379 357 202 184 197

Output
147

-----Note-----

For the first example, we have $c_1=a_1\& b_2=0$, $c_2=a_2\& b_1=2$, $c_3=a_3\& b_1=0$, $c_4 = a_4\& b_1=0$.Thus $c_1 | c_2 | c_3 |c_4 =2$, and this is the minimal answer we can get.

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

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

M = [[a[i]&b[j] for j in range(m)] for i in range(n)]
res = 0
M = sorted(M, key=lambda x: min(x), reverse = True)
for x in M:
	res = min([e|res for e in x])
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1397/A:
You are given $n$ strings $s_1, s_2, \ldots, s_n$ consisting of lowercase Latin letters.

In one operation you can remove a character from a string $s_i$ and insert it to an arbitrary position in a string $s_j$ ($j$ may be equal to $i$). You may perform this operation any number of times. Is it possible to make all $n$ strings equal?

-----Input-----

The first line contains $t$ ($1 \le t \le 10$): the number of test cases.

The first line of each test case contains a single integer $n$ ($1 \le n \le 1000$): the number of strings.

$n$ lines follow, the $i$-th line contains $s_i$ ($1 \le \lvert s_i \rvert \le 1000$).

The sum of lengths of all strings in all test cases does not exceed $1000$.

-----Output-----

If it is possible to make the strings equal, print "YES" (without quotes).

Otherwise, print "NO" (without quotes).

You can output each character in either lowercase or uppercase.

-----Example-----
Input
4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc

Output
YES
NO
YES
NO

-----Note-----

In the first test case, you can do the following:   Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab".

In the second test case, it is impossible to make all $n$ strings equal.

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

import sys
input = lambda :sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
    n=int(input())
    d = [0]*(26)
    fl=True
    for _ in range(n):
        s = input()
        for i in s:
            d[ord(i)-ord('a')]+=1
    for x in d:
        if x>0 and x%n:
            fl=False
            break
    print("YES" if fl else "NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1397/B:
Let's call a list of positive integers $a_0, a_1, ..., a_{n-1}$ a power sequence if there is a positive integer $c$, so that for every $0 \le i \le n-1$ then $a_i = c^i$.

Given a list of $n$ positive integers $a_0, a_1, ..., a_{n-1}$, you are allowed to:  Reorder the list (i.e. pick a permutation $p$ of $\{0,1,...,n - 1\}$ and change $a_i$ to $a_{p_i}$), then  Do the following operation any number of times: pick an index $i$ and change $a_i$ to $a_i - 1$ or $a_i + 1$ (i.e. increment or decrement $a_i$ by $1$) with a cost of $1$.

Find the minimum cost to transform $a_0, a_1, ..., a_{n-1}$ into a power sequence.

-----Input-----

The first line contains an integer $n$ ($3 \le n \le 10^5$).

The second line contains $n$ integers $a_0, a_1, ..., a_{n-1}$ ($1 \le a_i \le 10^9$).

-----Output-----

Print the minimum cost to transform $a_0, a_1, ..., a_{n-1}$ into a power sequence.

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

Output
1

Input
3
1000000000 1000000000 1000000000

Output
1999982505

-----Note-----

In the first example, we first reorder $\{1, 3, 2\}$ into $\{1, 2, 3\}$, then increment $a_2$ to $4$ with cost $1$ to get a power sequence $\{1, 2, 4\}$.

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

import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict

# available on Google, not available on Codeforces
# import numpy as np
# import scipy

def solve(lst):  # fix inputs here
    lst = sorted(lst)
    console("----- solving ------")
    console(lst)

    if len(lst) > 40:
        return sum(lst) - len(lst)

    base = 0
    minres = 10**11
    while base**len(lst) < (10**15):
        req = [base**i for i in range(len(lst))]
        diff = [abs(r-x) for r,x in zip(req, lst)]
        # console(req, base, diff, sum(diff))
        minres = min(minres, sum(diff))
        base += 1

    return minres

def console(*args):  # the judge will not read these print statement
    print('\033[36m', *args, '\033[0m', file=sys.stderr)
    return

# fast read all
# sys.stdin.readlines()

# for case_num in range(int(input())):
for _ in range(1):
    # read line as a string
    # strr = input()

    # read line as an integer
    _ = int(input())

    # read one line and parse each word as a string
    # lst = input().split()

    # read one line and parse each word as an integer
    lst = list(map(int,input().split()))

    # read matrix and parse as integers (after reading read nrows)
    # lst = list(map(int,input().split()))
    # nrows = lst[0]  # index containing information, please change
    # grid = []
    # for _ in range(nrows):
    #     grid.append(list(map(int,input().split())))

    res = solve(lst)  # please change

    # Google - case number required
    # print("Case #{}: {}".format(case_num+1, res))

    # Codeforces - no case number required
    print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1398/A:
You are given an array $a_1, a_2, \dots , a_n$, which is sorted in non-decreasing order ($a_i \le a_{i + 1})$.

Find three indices $i$, $j$, $k$ such that $1 \le i < j < k \le n$ and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $a_i$, $a_j$ and $a_k$ (for example it is possible to construct a non-degenerate triangle with sides $3$, $4$ and $5$ but impossible with sides $3$, $4$ and $7$). If it is impossible to find such triple, report it.

-----Input-----

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

The first line of each test case contains one integer $n$ ($3 \le n \le 5 \cdot 10^4$) — the length of the array $a$.

The second line of each test case contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le 10^9$; $a_{i - 1} \le a_i$) — the array $a$.

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

-----Output-----

For each test case print the answer to it in one line.

If there is a triple of indices $i$, $j$, $k$ ($i < j < k$) such that it is impossible to construct a non-degenerate triangle having sides equal to $a_i$, $a_j$ and $a_k$, print that three indices in ascending order. If there are multiple answers, print any of them.

Otherwise, print -1.

-----Example-----
Input
3
7
4 6 11 11 15 18 20
4
10 10 10 11
3
1 1 1000000000

Output
2 3 6
-1
1 2 3

-----Note-----

In the first test case it is impossible with sides $6$, $11$ and $18$. Note, that this is not the only correct answer.

In the second test case you always can construct a non-degenerate triangle.

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

for _ in range(int(input())):
    am = int(input())
    arr = list(map(int,input().split()))
    if arr[0] + arr[1] > arr[-1]:
        print(-1)
    else:
        print(1,2,am)


I found an interesting problem on https://codeforces.com/problemset/problem/1398/C:
You are given an array $a_1, a_2, \dots , a_n$ consisting of integers from $0$ to $9$. A subarray $a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$ is good if the sum of elements of this subarray is equal to the length of this subarray ($\sum\limits_{i=l}^{r} a_i = r - l + 1$).

For example, if $a = [1, 2, 0]$, then there are $3$ good subarrays: $a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0]$ and $a_{1 \dots 3} = [1, 2, 0]$.

Calculate the number of good subarrays of the array $a$.

-----Input-----

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

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

The second line of each test case contains a string consisting of $n$ decimal digits, where the $i$-th digit is equal to the value of $a_i$.

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

-----Output-----

For each test case print one integer — the number of good subarrays of the array $a$.

-----Example-----
Input
3
3
120
5
11011
6
600005

Output
3
6
1

-----Note-----

The first test case is considered in the statement.

In the second test case, there are $6$ good subarrays: $a_{1 \dots 1}$, $a_{2 \dots 2}$, $a_{1 \dots 2}$, $a_{4 \dots 4}$, $a_{5 \dots 5}$ and $a_{4 \dots 5}$.

In the third test case there is only one good subarray: $a_{2 \dots 6}$.

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

for _ in range(int(input())):
    n = int(input())
    s = input()

    d = {0: 1}
    summa, cnt = 0, 0
    ans = 0
    for i in s:
        summa += int(i)
        cnt += 1

        k = cnt - summa
        if k not in d:
            d[k] = 0
        ans += d[k]
        d[k] += 1

    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1398/D:
You are given three multisets of pairs of colored sticks:   $R$ pairs of red sticks, the first pair has length $r_1$, the second pair has length $r_2$, $\dots$, the $R$-th pair has length $r_R$;  $G$ pairs of green sticks, the first pair has length $g_1$, the second pair has length $g_2$, $\dots$, the $G$-th pair has length $g_G$;  $B$ pairs of blue sticks, the first pair has length $b_1$, the second pair has length $b_2$, $\dots$, the $B$-th pair has length $b_B$;

You are constructing rectangles from these pairs of sticks with the following process:   take a pair of sticks of one color;  take a pair of sticks of another color different from the first one;  add the area of the resulting rectangle to the total area.

Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.

Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.

What is the maximum area you can achieve?

-----Input-----

The first line contains three integers $R$, $G$, $B$ ($1 \le R, G, B \le 200$) — the number of pairs of red sticks, the number of pairs of green sticks and the number of pairs of blue sticks.

The second line contains $R$ integers $r_1, r_2, \dots, r_R$ ($1 \le r_i \le 2000$) — the lengths of sticks in each pair of red sticks.

The third line contains $G$ integers $g_1, g_2, \dots, g_G$ ($1 \le g_i \le 2000$) — the lengths of sticks in each pair of green sticks.

The fourth line contains $B$ integers $b_1, b_2, \dots, b_B$ ($1 \le b_i \le 2000$) — the lengths of sticks in each pair of blue sticks.

-----Output-----

Print the maximum possible total area of the constructed rectangles.

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

Output
20

Input
2 1 3
9 5
1
2 8 5

Output
99

Input
10 1 1
11 7 20 15 19 14 2 4 13 14
8
11

Output
372

-----Note-----

In the first example you can construct one of these rectangles: red and green with sides $3$ and $5$, red and blue with sides $3$ and...

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

r, g, b = map(int, input().split())
red = list(map(int, input().split()))
green = list(map(int, input().split()))
blue = list(map(int, input().split()))
red.sort()
green.sort()
blue.sort()
red = red[::-1]
green = green[::-1]
blue = blue[::-1]

dp = []
for i in range(r + 1):
    temp = [[0] * (b + 1) for j in range(g + 1)]
    dp.append(temp)

answer = 0

for i in range(0, r + 1):
    for j in range(0, g + 1):
        for k in range(0, b + 1):
            if i > 0 and j > 0:
                dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - 1][k] + red[i - 1] * green[j - 1])
            if i > 0 and k > 0:
                dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j][k - 1] + red[i - 1] * blue[k - 1])
            if j > 0 and k > 0:
                dp[i][j][k] = max(dp[i][j][k], dp[i][j - 1][k - 1] + green[j - 1] * blue[k - 1])

            answer = max(answer, dp[i][j][k])
print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/1398/F:
Alice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won $x$ rounds in a row. For example, if Bob won five rounds in a row and $x = 2$, then two sets ends.

You know that Alice and Bob have already played $n$ rounds, and you know the results of some rounds. For each $x$ from $1$ to $n$, calculate the maximum possible number of sets that could have already finished if each set lasts until one of the players wins $x$ rounds in a row. It is possible that the last set is still not finished — in that case, you should not count it in the answer.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 10^6$) — the number of rounds.

The second line contains one string $s$ of length $n$ — the descriptions of rounds. If the $i$-th element of the string is 0, then Alice won the $i$-th round; if it is 1, then Bob won the $i$-th round, and if it is ?, then you don't know who won the $i$-th round.

-----Output-----

In the only line print $n$ integers. The $i$-th integer should be equal to the maximum possible number of sets that could have already finished if each set lasts until one of the players wins $i$ rounds in a row.

-----Examples-----
Input
6
11?000

Output
6 3 2 1 0 0

Input
5
01?01

Output
5 1 0 0 0

Input
12
???1??????1?

Output
12 6 4 3 2 2 1 1 1 1 1 1

-----Note-----

Let's consider the first test case:

  if $x = 1$ and $s = 110000$ or $s = 111000$ then there are six finished sets;  if $x = 2$ and $s = 110000$ then there are three finished sets;  if $x = 3$ and $s = 111000$ then there are two finished sets;  if $x = 4$ and $s = 110000$ then there is one finished set;  if $x = 5$ then there are no finished sets;  if $x = 6$ then there are no finished sets.

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

class bitset():
    def __init__(self,n):
        self.size=1<<((n+2).bit_length())
        self.bit=[0]*(self.size+1)

    def append(self,val):
        val+=1
        id=val
        while id<=self.size:
            self.bit[id]+=1
            id+=(id)&(-id)

    def erase(self,val):
        val+=1
        id=val
        while id<=self.size:
            self.bit[id]-=1
            id+=(id)&(-id)

    def cnt(self,val):
        res_sum = 0
        val+=1
        while val > 0:
            res_sum += self.bit[val]
            val -= val&(-val)
        return res_sum

    def next(self,val):
        val+=1
        base=self.cnt(val-1)
        start=0
        end=self.size
        while end-start>1:
            test=(end+start)//2
            if self.bit[test]>base:
                end=test
            else:
                start=test
                base-=self.bit[test]
        return end-1

n=int(input())
s=input()

alice=[int(s[i]=="0") for i in range(n)]
bob=[int(s[i]=="1") for i in range(n)]
for i in range(1,n):
    alice[i]+=alice[i-1]
    bob[i]+=bob[i-1]
alice.append(0)
bob.append(0)

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

alice_win=[]
id=0
while id<n:
    if s[id]!="0":
        pos=id
        while pos<n and s[pos]!="0":
            pos+=1
        update_que[pos-id-1].append(id)
        id=pos
    else:
        id+=1
bob_win=[]
id=0
while id<n:
    if s[id]!="1":
        pos=id
        while pos<n and s[pos]!="1":
            pos+=1
        update_que[pos-id-1].append(id)
        id=pos
    else:
        id+=1

bst=bitset(n)
bst.append(n)

ans=[0]*n
for i in range(n-1,-1,-1):
    for id in update_que[i]:
        bst.append(id)
    pos=0
    res=0
    while pos<n-i:
        check1=alice[pos+i]-alice[pos-1]
        check2=bob[pos+i]-bob[pos-1]
        if not check1 or not check2:
            res+=1
            pos+=i+1
        else:
            npos=bst.next(pos)
            if npos==n:
                break
            else:
                pos=npos+i+1
                res+=1
    ans[i]=res

print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1399/A:
You are given the array $a$ consisting of $n$ positive (greater than zero) integers.

In one move, you can choose two indices $i$ and $j$ ($i \ne j$) such that the absolute difference between $a_i$ and $a_j$ is no more than one ($|a_i - a_j| \le 1$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).

Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves 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 1000$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains one integer $n$ ($1 \le n \le 50$) — 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 100$), where $a_i$ is the $i$-th element of $a$.

-----Output-----

For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.

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

Output
YES
YES
NO
NO
YES

-----Note-----

In the first test case of the example, we can perform the following sequence of moves:  choose $i=1$ and $j=3$ and remove $a_i$ (so $a$ becomes $[2; 2]$);  choose $i=1$ and $j=2$ and remove $a_j$ (so $a$ becomes $[2]$).

In the second test case of the example, we can choose any possible $i$ and $j$ any move and it doesn't matter which element we remove.

In the third test case of the example, there is no way to get rid of $2$ and $4$.

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

"""
                            pppppppppppppppppppp
                         ppppp  ppppppppppppppppppp
                      ppppppp    ppppppppppppppppppppp
                      pppppppp  pppppppppppppppppppppp
                      pppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppppp
       ppppppppppppppppppppppppppppppppppppppppppppppp  pppppppppppppppppppp
      pppppppppppppppppppppppppppppppppppppppppppppppp  ppppppppppppppppppppp
     ppppppppppppppppppppppppppppppppppppppppppppppppp  pppppppppppppppppppppp
    ppppppppppppppppppppppppppppppppppppppppppppppp    pppppppppppppppppppppppp
   pppppppppppppppppppppppppppppppppppppppppppppp     pppppppppppppppppppppppppp
  ppppppppppppppppppppppppppppppppppppppppppppp      pppppppppppppppppppppppppppp
  pppppppppppppppppppppppppppppppp               pppppppppppppppppppppppppppppppp
  pppppppppppppppppppppppppppp     pppppppppppppppppppppppppppppppppppppppppppppp
  ppppppppppppppppppppppppppp    pppppppppppppppppppppppppppppppppppppppppppppppp
    pppppppppppppppppppppppp  pppppppppppppppppppppppppppppppppppppppppppppppppp
     ppppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppppppp
      pppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppppp
       ppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppppp
                              pppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppp  pppppppp
                              ppppppppppppppppppppp    ppppppp
                                 ppppppppppppppppppp  ppppp
                                    pppppppppppppppppppp
"""

import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as...


I found an interesting problem on https://codeforces.com/problemset/problem/1399/C:
There are $n$ people who want to participate in a boat competition. The weight of the $i$-th participant is $w_i$. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.

So, if there are $k$ teams $(a_1, b_1)$, $(a_2, b_2)$, $\dots$, $(a_k, b_k)$, where $a_i$ is the weight of the first participant of the $i$-th team and $b_i$ is the weight of the second participant of the $i$-th team, then the condition $a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s$, where $s$ is the total weight of each team, should be satisfied.

Your task is to choose such $s$ that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains one integer $n$ ($1 \le n \le 50$) — the number of participants. The second line of the test case contains $n$ integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le n$), where $w_i$ is the weight of the $i$-th participant.

-----Output-----

For each test case, print one integer $k$: the maximum number of teams people can compose with the total weight $s$, if you choose $s$ optimally.

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

Output
2
3
4
1
2

-----Note-----

In the first test case of the example, we can reach the optimal answer for $s=6$. Then the first boat is used by participants $1$ and $5$ and the second boat is used by participants $2$ and $4$ (indices are the same as weights).

In the second test case of the example, we can reach the optimal answer for $s=12$. Then first $6$ participants can form $3$ pairs.

In the third test case of the example, we can reach the optimal answer for $s=3$. The answer is $4$ because we have $4$ participants...

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

#!/usr/bin/env pypy3

from collections import Counter

def score(cN, target):
	ret1 = 0
	ret2 = 0
	for k in cN:
		if 2*k == target:
			ret1 += cN[k] // 2
		else:
			l = target - k
			ret2 += min(cN[k], cN[l])
	return ret1 + ret2//2

def ans(N):
	N = sorted(N)
	cN = Counter(N)

	return max(score(cN, target) for target in range(2, 101))

T = int(input())
for t in range(T):
	input()
	N = list(map(int, input().split()))

	print(ans(N))


I found an interesting problem on https://codeforces.com/problemset/problem/1399/F:
You are given $n$ segments on a coordinate axis $OX$. The $i$-th segment has borders $[l_i; r_i]$. All points $x$, for which $l_i \le x \le r_i$ holds, belong to the $i$-th segment.

Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.

Two segments $[l_i; r_i]$ and $[l_j; r_j]$ are non-intersecting if they have no common points. For example, segments $[1; 2]$ and $[3; 4]$, $[1; 3]$ and $[5; 5]$ are non-intersecting, while segments $[1; 2]$ and $[2; 3]$, $[1; 2]$ and $[2; 2]$ are intersecting.

The segment $[l_i; r_i]$ lies inside the segment $[l_j; r_j]$ if $l_j \le l_i$ and $r_i \le r_j$. For example, segments $[2; 2]$, $[2, 3]$, $[3; 4]$ and $[2; 4]$ lie inside the segment $[2; 4]$, while $[2; 5]$ and $[1; 4]$ 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 1000$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains one integer $n$ ($1 \le n \le 3000$) — the number of segments. The next $n$ lines describe segments. The $i$-th segment is given as two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le 2 \cdot 10^5$), where $l_i$ is the left border of the $i$-th segment and $r_i$ is the right border of the $i$-th segment.

Additional constraint on the input: there are no duplicates in the list of segments.

It is guaranteed that the sum of $n$ does not exceed $3000$ ($\sum n \le 3000$).

-----Output-----

For each test case, print the answer: the maximum possible size of the subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.

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

Output
3
4
2
7

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

import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s); sys.stdout.write('\n')
def wi(n): sys.stdout.write(str(n)); sys.stdout.write('\n')
def wia(a, sep=' '): sys.stdout.write(sep.join([str(x) for x in a])); sys.stdout.write('\n')

def solve(n, segs):
    vals = set()
    for l, r in segs:
        vals.add(l)
        vals.add(r)
    vals = sorted(list(vals))
    d = {x: i for i, x in enumerate(vals)}
    m = len(vals)

    c_segs = []
    r_segs = [[] for _ in range(m)]
    for l, r in segs:
        ll = d[l]
        rr = d[r]
        c_segs.append((ll, rr))
        r_segs[ll].append(rr)

    dp = [[0] * m for _ in range(m)]
    for ln in range(1, m + 1):
        for l in range(m):
            r = l + ln - 1
            if r >= m: continue
            if l + 1 <= r:
                dp[l][r] = dp[l + 1][r]
            for rr in r_segs[l]:
                if rr >= r:
                    continue
                dp[l][r] = max(dp[l][r], dp[l][rr] + dp[rr + 1][r])
            if r in r_segs[l]:
                dp[l][r] += 1

    return dp[0][-1]

def main():
    for _ in range(ri()):
        n = ri()
        segs = []
        for i in range(n):
            l, r = ria()
            segs.append((l, r))
        wi(solve(n, segs))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1400/A:
A binary string is a string where each character is either 0 or 1. Two binary strings $a$ and $b$ of equal length are similar, if they have the same character in some position (there exists an integer $i$ such that $a_i = b_i$). For example:  10010 and 01111 are similar (they have the same character in position $4$);  10010 and 11111 are similar;  111 and 111 are similar;  0110 and 1001 are not similar.

You are given an integer $n$ and a binary string $s$ consisting of $2n-1$ characters. Let's denote $s[l..r]$ as the contiguous substring of $s$ starting with $l$-th character and ending with $r$-th character (in other words, $s[l..r] = s_l s_{l + 1} s_{l + 2} \dots s_r$).

You have to construct a binary string $w$ of length $n$ which is similar to all of the following strings: $s[1..n]$, $s[2..n+1]$, $s[3..n+2]$, ..., $s[n..2n-1]$.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases.

The first line of each test case contains a single integer $n$ ($1 \le n \le 50$).

The second line of each test case contains the binary string $s$ of length $2n - 1$. Each character $s_i$ is either 0 or 1.

-----Output-----

For each test case, print the corresponding binary string $w$ of length $n$. If there are multiple such strings — print any of them. It can be shown that at least one string $w$ meeting the constraints always exists.

-----Example-----
Input
4
1
1
3
00000
4
1110000
2
101

Output
1
000
1010
00

-----Note-----

The explanation of the sample case (equal characters in equal positions are bold):

The first test case:   $\mathbf{1}$ is similar to $s[1..1] = \mathbf{1}$.

The second test case:   $\mathbf{000}$ is similar to $s[1..3] = \mathbf{000}$;  $\mathbf{000}$ is similar to $s[2..4] = \mathbf{000}$;  $\mathbf{000}$ is similar to $s[3..5] = \mathbf{000}$.

The third test case:   $\mathbf{1}0\mathbf{10}$ is similar to $s[1..4] = \mathbf{1}1\mathbf{10}$;  $\mathbf{1}01\mathbf{0}$ is similar to $s[2..5] = \mathbf{1}10\mathbf{0}$; ...

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

for _ in range(int(input())):
  n = int(input())
  print(input()[n - 1] * n)


I found an interesting problem on https://codeforces.com/problemset/problem/1400/B:
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.

You decided to rob a town's blacksmith and you take a follower with you. You can carry at most $p$ units and your follower — at most $f$ units.

In the blacksmith shop, you found $cnt_s$ swords and $cnt_w$ war axes. Each sword weights $s$ units and each war axe — $w$ units. You don't care what to take, since each of them will melt into one steel ingot.

What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

The first line of each test case contains two integers $p$ and $f$ ($1 \le p, f \le 10^9$) — yours and your follower's capacities.

The second line of each test case contains two integers $cnt_s$ and $cnt_w$ ($1 \le cnt_s, cnt_w \le 2 \cdot 10^5$) — the number of swords and war axes in the shop.

The third line of each test case contains two integers $s$ and $w$ ($1 \le s, w \le 10^9$) — the weights of each sword and each war axe.

It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed $2 \cdot 10^5$.

-----Output-----

For each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.

-----Example-----
Input
3
33 27
6 10
5 6
100 200
10 10
5 5
1 19
1 3
19 5

Output
11
20
3

-----Note-----

In the first test case:   you should take $3$ swords and $3$ war axes: $3 \cdot 5 + 3 \cdot 6 = 33 \le 33$  and your follower — $3$ swords and $2$ war axes: $3 \cdot 5 + 2 \cdot 6 = 27 \le 27$.  $3 + 3 + 3 + 2 = 11$ weapons in total.

In the second test case, you can take all available weapons even without your follower's help, since $5 \cdot 10 + 5 \cdot 10 \le 100$.

In the third test case, you can't take anything, but your follower can take $3$ war axes: $3...

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

t = int(input())
for i in range(t):
    c0, c1 = map(int,input().split())
    ma, mb = map(int,input().split())
    wa, wb = map(int,input().split())

    ans = 0
    if wa > wb:
        wa,wb = wb,wa
        ma,mb = mb,ma
    for i in range(ma+1):
        c0a = min(i, c0//wa)
        c1a = min(ma-i, c1//wa)
        n0 = c0-c0a*wa
        n1 = c1-c1a*wa
        ans0 = c0a + c1a
        c01b = min(mb, n0//wb + n1//wb)
        ans0 += c01b
        ans = max(ans,ans0)
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1400/E:
You have a multiset containing several integers. Initially, it contains $a_1$ elements equal to $1$, $a_2$ elements equal to $2$, ..., $a_n$ elements equal to $n$.

You may apply two types of operations:  choose two integers $l$ and $r$ ($l \le r$), then remove one occurrence of $l$, one occurrence of $l + 1$, ..., one occurrence of $r$ from the multiset. This operation can be applied only if each number from $l$ to $r$ occurs at least once in the multiset;  choose two integers $i$ and $x$ ($x \ge 1$), then remove $x$ occurrences of $i$ from the multiset. This operation can be applied only if the multiset contains at least $x$ occurrences of $i$.

What is the minimum number of operations required to delete all elements from the multiset?

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 5000$).

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$).

-----Output-----

Print one integer — the minimum number of operations required to delete all elements from the multiset.

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

Output
2

Input
5
1 0 1 0 1

Output
3

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

n = int(input()) + 1
l = list(map(int, input().split())) + [0]
out = 0

q = []
for v in l:
    if v == 0:
        dp = []
        n = len(q)
        for i in range(n):
            curr = q[i] + i
            smol = q[i]
            for j in range(i - 1, -1, -1):
                smol = min(q[j], smol)
                diff = q[i] - smol
                curr = min(curr, diff + dp[j] + i - j - 1)
            dp.append(curr)

        real = [n - i + dp[i] - 1 for i in range(n)] + [n]
        out += min(real)
        q = []
    else:
        q.append(v)
print(out)


I found an interesting problem on https://codeforces.com/problemset/problem/1401/A:
We have a point $A$ with coordinate $x = n$ on $OX$-axis. We'd like to find an integer point $B$ (also on $OX$-axis), such that the absolute difference between the distance from $O$ to $B$ and the distance from $A$ to $B$ is equal to $k$. [Image] The description of the first test case.

Since sometimes it's impossible to find such point $B$, we can, in one step, increase or decrease the coordinate of $A$ by $1$. What is the minimum number of steps we should do to make such point $B$ exist?

-----Input-----

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

The only line of each test case contains two integers $n$ and $k$ ($0 \le n, k \le 10^6$) — the initial position of point $A$ and desirable absolute difference.

-----Output-----

For each test case, print the minimum number of steps to make point $B$ exist.

-----Example-----
Input
6
4 0
5 8
0 1000000
0 0
1 0
1000000 1000000

Output
0
3
1000000
0
1
0

-----Note-----

In the first test case (picture above), if we set the coordinate of $B$ as $2$ then the absolute difference will be equal to $|(2 - 0) - (4 - 2)| = 0$ and we don't have to move $A$. So the answer is $0$.

In the second test case, we can increase the coordinate of $A$ by $3$ and set the coordinate of $B$ as $0$ or $8$. The absolute difference will be equal to $|8 - 0| = 8$, so the answer is $3$. [Image]

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

import math as mt
def tran(arr):
    if arr[1]>arr[0]:
        return arr[1]-arr[0]
    else:
        if arr[1]%2==0:
            if arr[0]%2==0:
                return 0
            else:
                return 1
        else:
            if arr[0]%2==1:
                return 0
            else:
                return 1

def __starting_point():
    t = int(input())
    ans = []
    for i in range(t):
        arr = list(map(int, input().rstrip().split()))
        r = tran(arr)
        ans.append(r)
    for i in ans:
        print(i)

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1401/B:
You are given two sequences $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$. Each element of both sequences is either $0$, $1$ or $2$. The number of elements $0$, $1$, $2$ in the sequence $a$ is $x_1$, $y_1$, $z_1$ respectively, and the number of elements $0$, $1$, $2$ in the sequence $b$ is $x_2$, $y_2$, $z_2$ respectively.

You can rearrange the elements in both sequences $a$ and $b$ however you like. After that, let's define a sequence $c$ as follows:

$c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\ 0 & \mbox{if }a_i = b_i \\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}$

You'd like to make $\sum_{i=1}^n c_i$ (the sum of all elements of the sequence $c$) as large as possible. What is the maximum possible sum?

-----Input-----

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

Each test case consists of two lines. The first line of each test case contains three integers $x_1$, $y_1$, $z_1$ ($0 \le x_1, y_1, z_1 \le 10^8$) — the number of $0$-s, $1$-s and $2$-s in the sequence $a$.

The second line of each test case also contains three integers $x_2$, $y_2$, $z_2$ ($0 \le x_2, y_2, z_2 \le 10^8$; $x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0$) — the number of $0$-s, $1$-s and $2$-s in the sequence $b$.

-----Output-----

For each test case, print the maximum possible sum of the sequence $c$.

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

Output
4
2
0

-----Note-----

In the first sample, one of the optimal solutions is:

$a = \{2, 0, 1, 1, 0, 2, 1\}$

$b = \{1, 0, 1, 0, 2, 1, 0\}$

$c = \{2, 0, 0, 0, 0, 2, 0\}$

In the second sample, one of the optimal solutions is:

$a = \{0, 2, 0, 0, 0\}$

$b = \{1, 1, 0, 1, 0\}$

$c = \{0, 2, 0, 0, 0\}$

In the third sample, the only possible solution is:

$a = \{2\}$

$b = \{2\}$

$c = \{0\}$

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

for _ in range(int(input())):
    a,b,c = list(map(int, input().split()))
    x,y,z = list(map(int, input().split()))

    temp = min(c,y)
    ans = 2*temp
    c -= temp
    y -= temp
    temp = min(c,z)
    c -= temp
    z -= temp
    temp = min(c,x)
    c -= temp
    x -= temp

    temp = min(a,z)
    a -= temp
    z -= temp
    temp = min(b,z)
    ans -= 2*temp
    b -= temp
    z -= temp
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1401/C:
You are given an array $a_1, a_2, \dots, a_n$ where all $a_i$ are integers and greater than $0$.

 In one operation, you can choose two different indices $i$ and $j$ ($1 \le i, j \le n$). If $gcd(a_i, a_j)$ is equal to the minimum element of the whole array $a$, you can swap $a_i$ and $a_j$. $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.

 Now you'd like to make $a$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this.

 An array $a$ is non-decreasing if and only if $a_1 \le a_2 \le \ldots \le a_n$.

-----Input-----

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

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

 The second line of each test case contains $n$ positive integers $a_1, a_2, \ldots a_n$ ($1 \le a_i \le 10^9$) — the array itself.

 It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.

-----Output-----

 For each test case, output "YES" if it is possible to make the array $a$ non-decreasing using the described operation, or "NO" if it is impossible to do so.

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

Output
YES
YES
YES
NO

-----Note-----

 In the first and third sample, the array is already non-decreasing.

 In the second sample, we can swap $a_1$ and $a_3$ first, and swap $a_1$ and $a_5$ second to make the array non-decreasing.

 In the forth sample, we cannot the array non-decreasing using the operation.

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

import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
#from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7

for t in range(int(data())):
    n=int(data())
    a=mdata()
    a1=sorted(a)
    k=1
    for i in range(n):
        if a[i]!=a1[i] and a[i]%a1[0]!=0:
            k=0
            break
    if k:
        out("YES")
    else:
        out("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1401/D:
You are given a tree that consists of $n$ nodes. You should label each of its $n-1$ edges with an integer in such way that satisfies the following conditions:   each integer must be greater than $0$;  the product of all $n-1$ numbers should be equal to $k$;  the number of $1$-s among all $n-1$ integers must be minimum possible.

Let's define $f(u,v)$ as the sum of the numbers on the simple path from node $u$ to node $v$. Also, let $\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$ be a distribution index of the tree.

Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $10^9 + 7$.

In this problem, since the number $k$ can be large, the result of the prime factorization of $k$ is given instead.

-----Input-----

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

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

Each of the next $n-1$ lines describes an edge: the $i$-th line contains two integers $u_i$ and $v_i$ ($1 \le u_i, v_i \le n$; $u_i \ne v_i$) — indices of vertices connected by the $i$-th edge.

Next line contains a single integer $m$ ($1 \le m \le 6 \cdot 10^4$) — the number of prime factors of $k$.

Next line contains $m$ prime numbers $p_1, p_2, \ldots, p_m$ ($2 \le p_i < 6 \cdot 10^4$) such that $k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$.

It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$, the sum of $m$ over all test cases doesn't exceed $6 \cdot 10^4$, and the given edges for each test cases form a tree.

-----Output-----

Print the maximum distribution index you can get. Since answer can be too large, print it modulo $10^9+7$.

-----Example-----
Input
3
4
1 2
2 3
3 4
2
2 2
4
3 4
1 3
3 2
2
3 2
7
6 1
2 3
4 6
7 3
5 1
3 6
4
7 5 13 3

Output
17
18
286

-----Note-----

 In the first test case, one of the optimal ways is on the following image:

 [Image]

 In this case, $f(1,2)=1$, $f(1,3)=3$, $f(1,4)=5$,...

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

import sys
from collections import deque

input=sys.stdin.readline

for _ in range(int(input())):
    n=int(input())
    edge=[[] for i in range(n)]
    for i in range(n-1):
        u,v=list(map(int,input().split()))
        edge[u-1].append(v-1)
        edge[v-1].append(u-1)
    m=int(input())
    p=list(map(int,input().split()))

    size=[1 for i in range(n)]
    parent=[-1 for i in range(n)]
    res=[]
    deq=deque([(0,-1)])
    while deq:
        v,pv=deq.popleft()
        res.append(v)
        for nv in edge[v]:
            if nv!=pv:
                parent[nv]=v
                deq.append((nv,v))

    res=res[::-1]
    for v in res:
        for nv in edge[v]:
            if nv!=parent[v]:
                size[v]+=size[nv]

    coef=[]
    for v in res:
        for nv in edge[v]:
            if nv!=parent[v]:
                c=size[nv]*(n-size[nv])
                coef.append(c)
    mod=10**9+7
    #print(coef)
    #print(p)
    #print(size)
    if m<n-1:
        res=0
        coef.sort(reverse=True)
        p.sort(reverse=True)
        for i in range(m):
            res+=coef[i]*p[i]
            res%=mod
        for i in range(m,n-1):
            res+=coef[i]
            res%=mod
        print(res)
    else:
        res=0
        coef.sort()
        p.sort()
        for i in range(n-2):
            res+=coef[i]*p[i]
            res%=mod
        tmp=coef[-1]
        for i in range(n-2,m):
            tmp*=p[i]
            tmp%=mod
        res=(res+tmp)%mod
        print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1401/E:
There is a square of size $10^6 \times 10^6$ on the coordinate plane with four points $(0, 0)$, $(0, 10^6)$, $(10^6, 0)$, and $(10^6, 10^6)$ as its vertices.

You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.

Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.

-----Input-----

The first line contains two integers $n$ and $m$ ($0 \le n, m \le 10^5$) — the number of horizontal segments and the number of vertical segments.

The next $n$ lines contain descriptions of the horizontal segments. The $i$-th line contains three integers $y_i$, $lx_i$ and $rx_i$ ($0 < y_i < 10^6$; $0 \le lx_i < rx_i \le 10^6$), which means the segment connects $(lx_i, y_i)$ and $(rx_i, y_i)$.

The next $m$ lines contain descriptions of the vertical segments. The $i$-th line contains three integers $x_i$, $ly_i$ and $ry_i$ ($0 < x_i < 10^6$; $0 \le ly_i < ry_i \le 10^6$), which means the segment connects $(x_i, ly_i)$ and $(x_i, ry_i)$.

It's guaranteed that there are no two segments on the same line, and each segment intersects with at least one of square's sides.

-----Output-----

Print the number of pieces the square is divided into after drawing all the segments.

-----Example-----
Input
3 3
2 3 1000000
4 0 4
3 0 1000000
4 0 1
2 0 5
3 1 1000000

Output
7

-----Note-----

 The sample is like this: [Image]

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

import sys
input=sys.stdin.readline

class BIT:
  def __init__(self,n):self.n=n+1;self.BIT=[0]*self.n
  def add(self,i,x):
    idx=i
    while idx<self.n:self.BIT[idx]+=x;idx+=(idx&-idx)
  def _sum(self,i):
    if i==-1:return -1
    ret=0;idx=i
    while idx>0:ret+=self.BIT[idx];idx-=(idx&-idx)
    return ret
  def sum(self,l,r):return self._sum(r)-self._sum(l-1)
  def value(self,i):return self._sum(i)-self._sum(i-1)

bound=10**6
n,m=map(int,input().split())
yoko_edges=[list(map(int,input().split())) for _ in range(n)]
yoko_edges=sorted(yoko_edges,reverse=True,key=lambda x:x[0])
ue_tate_edges=[[] for _ in range(bound+1)]
sita_tate_edges=[[] for _ in range(bound+1)]
tate_edges=BIT(bound)
tate_edges.add(bound,1)
ans=1
for _ in range(m):
    x,l,r=map(int,input().split())
    if l==0 and r==bound:tate_edges.add(x,1);ans+=1
    elif l==0:sita_tate_edges[r].append(x)
    elif r==bound:ue_tate_edges[l].append(x);tate_edges.add(x,1)
prev=bound-1
for y,l,r in yoko_edges:
    while prev>=y:
        for x in sita_tate_edges[prev]:tate_edges.add(x,1)
        for x in ue_tate_edges[prev+1]:tate_edges.add(x,-1)
        prev-=1
    ans+=tate_edges.sum(l,r)-1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1401/F:
You are given an array $a$ of length $2^n$. You should process $q$ queries on it. Each query has one of the following $4$ types:   $Replace(x, k)$ — change $a_x$ to $k$;  $Reverse(k)$ — reverse each subarray $[(i-1) \cdot 2^k+1, i \cdot 2^k]$ for all $i$ ($i \ge 1$);  $Swap(k)$ — swap subarrays $[(2i-2) \cdot 2^k+1, (2i-1) \cdot 2^k]$ and $[(2i-1) \cdot 2^k+1, 2i \cdot 2^k]$ for all $i$ ($i \ge 1$);  $Sum(l, r)$ — print the sum of the elements of subarray $[l, r]$.

Write a program that can quickly process given queries.

-----Input-----

The first line contains two integers $n$, $q$ ($0 \le n \le 18$; $1 \le q \le 10^5$) — the length of array $a$ and the number of queries.

The second line contains $2^n$ integers $a_1, a_2, \ldots, a_{2^n}$ ($0 \le a_i \le 10^9$).

Next $q$ lines contains queries — one per line. Each query has one of $4$ types:   "$1$ $x$ $k$" ($1 \le x \le 2^n$; $0 \le k \le 10^9$) — $Replace(x, k)$;  "$2$ $k$" ($0 \le k \le n$) — $Reverse(k)$;  "$3$ $k$" ($0 \le k < n$) — $Swap(k)$;  "$4$ $l$ $r$" ($1 \le l \le r \le 2^n$) — $Sum(l, r)$.

It is guaranteed that there is at least one $Sum$ query.

-----Output-----

Print the answer for each $Sum$ query.

-----Examples-----
Input
2 3
7 4 9 9
1 2 8
3 1
4 2 4

Output
24

Input
3 8
7 0 8 8 7 1 5 2
4 3 7
2 1
3 2
4 1 6
2 3
1 5 16
4 8 8
3 0

Output
29
22
1

-----Note-----

In the first sample, initially, the array $a$ is equal to $\{7,4,9,9\}$.

After processing the first query. the array $a$ becomes $\{7,8,9,9\}$.

After processing the second query, the array $a_i$ becomes $\{9,9,7,8\}$

Therefore, the answer to the third query is $9+7+8=24$.

In the second sample, initially, the array $a$ is equal to $\{7,0,8,8,7,1,5,2\}$. What happens next is:   $Sum(3, 7)$ $\to$ $8 + 8 + 7 + 1 + 5 = 29$;  $Reverse(1)$ $\to$ $\{0,7,8,8,1,7,2,5\}$;  $Swap(2)$ $\to$ $\{1,7,2,5,0,7,8,8\}$;  $Sum(1, 6)$ $\to$ $1 + 7 + 2 + 5 + 0 + 7 = 22$;  $Reverse(3)$ $\to$ $\{8,8,7,0,5,2,7,1\}$;  $Replace(5, 16)$ $\to$ $\{8,8,7,0,16,2,7,1\}$;  $Sum(8, 8)$ $\to$ $1$; ...

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

class BIT():
    def __init__(self,n):
        self.BIT=[0]*(n+1)
        self.num=n

    def query(self,idx):
        res_sum = 0
        while idx > 0:
            res_sum += self.BIT[idx]
            idx -= idx&(-idx)
        return res_sum

    #Ai += x O(logN)
    def update(self,idx,x):
        while idx <= self.num:
            self.BIT[idx] += x
            idx += idx&(-idx)
        return

n,q=map(int,input().split())
a=list(map(int,input().split()))
bit=BIT(2**n)
for i in range(2**n):
    bit.update(i+1,a[i])
b=0

def Sum(r,xor):
    id=xor
    res=0
    if r==-1:
        return res
    for i in range(n,-1,-1):
        if r>>i &1:
            L=(id>>i)<<i
            R=L+(1<<i)-1
            res+=bit.query(R+1)-bit.query(L)
            id^=(1<<i)
    return res

for _ in range(q):
    query=tuple(map(int,input().split()))
    if query[0]==1:
        g,x,k=query
        x-=1
        x^=b
        bit.update(x+1,k-a[x])
        a[x]=k
    elif query[0]==2:
        k=query[1]
        b^=2**k-1
    elif query[0]==3:
        k=query[1]
        if k!=n:
            b^=2**k
    else:
        gl,l,r=query
        l-=1
        test=Sum(r,b)-Sum(l,b)
        print(test)


I found an interesting problem on https://codeforces.com/problemset/problem/1406/A:
Given a set of integers (it can contain equal elements).

You have to split it into two subsets $A$ and $B$ (both of them can contain equal elements or be empty). You have to maximize the value of $mex(A)+mex(B)$.

Here $mex$ of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:   $mex(\{1,4,0,2,2,1\})=3$  $mex(\{3,3,2,1,3,0,0\})=4$  $mex(\varnothing)=0$ ($mex$ for empty set)

The set is splitted into two subsets $A$ and $B$ if for any integer number $x$ the number of occurrences of $x$ into this set is equal to the sum of the number of occurrences of $x$ into $A$ and the number of occurrences of $x$ into $B$.

-----Input-----

The input consists of multiple test cases. The first line contains an integer $t$ ($1\leq t\leq 100$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains an integer $n$ ($1\leq n\leq 100$) — the size of the set.

The second line of each testcase contains $n$ integers $a_1,a_2,\dots a_n$ ($0\leq a_i\leq 100$) — the numbers in the set.

-----Output-----

For each test case, print the maximum value of $mex(A)+mex(B)$.

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

Output
5
3
4
0

-----Note-----

In the first test case, $A=\left\{0,1,2\right\},B=\left\{0,1,5\right\}$ is a possible choice.

In the second test case, $A=\left\{0,1,2\right\},B=\varnothing$ is a possible choice.

In the third test case, $A=\left\{0,1,2\right\},B=\left\{0\right\}$ is a possible choice.

In the fourth test case, $A=\left\{1,3,5\right\},B=\left\{2,4,6\right\}$ is a possible choice.

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

for _ in range(int(input())):
    n = int(input())
    arr = list(map(int,input().split()))
    a,b = 0,0
    arr.sort()
    for i in arr:
        if a==i:
            a+=1
        elif b==i:
            b+=1
    print(a+b)


I found an interesting problem on https://codeforces.com/problemset/problem/1406/B:
You are given an array of integers $a_1,a_2,\ldots,a_n$. Find the maximum possible value of $a_ia_ja_ka_la_t$ among all five indices $(i, j, k, l, t)$ ($i<j<k<l<t$).

-----Input-----

The input consists of multiple test cases. The first line contains an integer $t$ ($1\le t\le 2 \cdot 10^4$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($5\le n\le 10^5$) — the size of the array.

The second line of each test case contains $n$ integers $a_1,a_2,\ldots,a_n$ ($-3\times 10^3\le a_i\le 3\times 10^3$) — given array.

It's guaranteed that the sum of $n$ over all test cases does not exceed $2\cdot 10^5$.

-----Output-----

For each test case, print one integer — the answer to the problem.

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

Output
-120
12
0
945

-----Note-----

In the first test case, choosing $a_1,a_2,a_3,a_4,a_5$ is a best choice: $(-1)\cdot (-2) \cdot (-3)\cdot (-4)\cdot (-5)=-120$.

In the second test case, choosing $a_1,a_2,a_3,a_5,a_6$ is a best choice: $(-1)\cdot (-2) \cdot (-3)\cdot 2\cdot (-1)=12$.

In the third test case, choosing $a_1,a_2,a_3,a_4,a_5$ is a best choice: $(-1)\cdot 0\cdot 0\cdot 0\cdot (-1)=0$.

In the fourth test case, choosing $a_1,a_2,a_3,a_4,a_6$ is a best choice: $(-9)\cdot (-7) \cdot (-5)\cdot (-3)\cdot 1=945$.

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/1406/C:
Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles.

A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible.

For example, the centroid of the following tree is $2$, because when you cut it, the size of the largest connected component of the remaining graph is $2$ and it can't be smaller. [Image]

However, in some trees, there might be more than one centroid, for example: [Image]

Both vertex $1$ and vertex $2$ are centroids because the size of the largest connected component is $3$ after cutting each of them.

Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut.

He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists.

-----Input-----

The input consists of multiple test cases. The first line contains an integer $t$ ($1\leq t\leq 10^4$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains an integer $n$ ($3\leq n\leq 10^5$) — the number of vertices.

Each of the next $n-1$ lines contains two integers $x, y$ ($1\leq x,y\leq n$). It means, that there exists an edge connecting vertices $x$ and $y$.

It's guaranteed that the given graph is a tree.

It's guaranteed that the sum of $n$ for all test cases does not exceed $10^5$.

-----Output-----

For each test case, print two lines.

In the first line print two integers $x_1, y_1$ ($1 \leq x_1, y_1 \leq n$), which means you cut the edge between vertices $x_1$ and $y_1$. There should exist edge connecting vertices $x_1$ and $y_1$.

In the second line print two integers $x_2, y_2$ ($1...

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

from collections import deque
import sys

def input():
    return sys.stdin.readline()[:-1]

def main():
    T = int(input())

    for i in range(T):
        N = int(input())
        e_list = [[] for i in range(N)]
        for i in range(N-1):
            a,b = list(map(int,input().split()))
            a,b = a-1,b-1
            e_list[a].append(b)
            e_list[b].append(a)

        vi = 0
        INF = 10**27
        Q = deque([vi])

        checked_list = [False]*N
        checked_list[vi]=True

        min_path_list = [INF]*N #change
        min_path_list[vi] = 0

        while len(Q)>0:
            v = Q.pop()
            for v1 in e_list[v]:
                if not checked_list[v1]:
                    checked_list[v1]=True
                    Q.appendleft(v1)
                    min_path_list[v1]=min(min_path_list[v1],min_path_list[v]+1)

        min_p = [(i,d) for i,d in enumerate(min_path_list)]
        min_p.sort(key = lambda x:x[1],reverse=True)
        member = [0]*N
        #print(min_p)
        center = []

        for z in min_p:
            #print(z)
            flag = True
            i,d = z
            mem = 0
            for v in e_list[i]:
                mem += member[v]
                if member[v] > N/2:
                    flag=False
            member[i] = mem + 1
            if flag and N - member[i] <= N/2:
                center.append(i)

        if len(center)==1:
            print(1,e_list[0][0]+1)
            print(1,e_list[0][0]+1)
        else:
            if e_list[center[0]][0]!=center[1]:
                print(center[0]+1, e_list[center[0]][0]+1)
                print(center[1]+1, e_list[center[0]][0]+1)
            else:
                print(center[0]+1, e_list[center[0]][1]+1)
                print(center[1]+1, e_list[center[0]][1]+1)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1406/D:
You are given a sequence of $n$ integers $a_1, a_2, \ldots, a_n$.

You have to construct two sequences of integers $b$ and $c$ with length $n$ that satisfy:  for every $i$ ($1\leq i\leq n$) $b_i+c_i=a_i$  $b$ is non-decreasing, which means that for every $1<i\leq n$, $b_i\geq b_{i-1}$ must hold  $c$ is non-increasing, which means that for every $1<i\leq n$, $c_i\leq c_{i-1}$ must hold

You have to minimize $\max(b_i,c_i)$. In other words, you have to minimize the maximum number in sequences $b$ and $c$.

Also there will be $q$ changes, the $i$-th change is described by three integers $l,r,x$. You should add $x$ to $a_l,a_{l+1}, \ldots, a_r$.

You have to find the minimum possible value of $\max(b_i,c_i)$ for the initial sequence and for sequence after each change.

-----Input-----

The first line contains an integer $n$ ($1\leq n\leq 10^5$).

The secound line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($1\leq i\leq n$, $-10^9\leq a_i\leq 10^9$).

The third line contains an integer $q$ ($1\leq q\leq 10^5$).

Each of the next $q$ lines contains three integers $l,r,x$ ($1\leq l\leq r\leq n,-10^9\leq x\leq 10^9$), desribing the next change.

-----Output-----

Print $q+1$ lines.

On the $i$-th ($1 \leq i \leq q+1$) line, print the answer to the problem for the sequence after $i-1$ changes.

-----Examples-----
Input
4
2 -1 7 3
2
2 4 -3
3 4 2

Output
5
5
6

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

Output
3
3
3
1

Input
1
0
2
1 1 -1
1 1 -1

Output
0
0
-1

-----Note-----

In the first test:  The initial sequence $a = (2, -1, 7, 3)$. Two sequences $b=(-3,-3,5,5),c=(5,2,2,-2)$ is a possible choice.  After the first change $a = (2, -4, 4, 0)$. Two sequences $b=(-3,-3,5,5),c=(5,-1,-1,-5)$ is a possible choice.  After the second change $a = (2, -4, 6, 2)$. Two sequences $b=(-4,-4,6,6),c=(6,0,0,-4)$ is a possible choice.

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

#Python Template

from sys import stdin, stdout
from math import ceil

def main():
	t = 1
	for _ in range(t):
		n = int(stdin.readline())
		a = [int(i) for i in stdin.readline().split()]
		q = int(stdin.readline())
		diffs = [0]*(n-1)
		start = a[0]
		for i in range(n-1):
			diffs[i] = a[i+1] - a[i]

		upstep = 0
		for d in diffs:
			if d > 0:
				upstep += d
		val = ceil((start + upstep)/2.0)
		#print(diffs)
		print(val)
		#print()

		for _ in range(q):
			l, r, x = [int(i) for i in stdin.readline().split()]
			l-=1
			r-=1
			if l == 0:
				start += x
			else:
				old = diffs[l-1]
				diffs[l-1] += x
				new = diffs[l-1]
				if old > 0:
					upstep -= old
				if new > 0:
					upstep += new
			if r != n-1:
				old = diffs[r]
				diffs[r] -= x
				new = diffs[r]
				if old > 0:
					upstep -= old
				if new > 0:
					upstep += new
			#print("Steps: {0}".format(upstep))
			#print(diffs)
			#print("Start: {0}".format(start))

			val = ceil((start + upstep)/2.0)
			#print("Answer: {0}".format(val))
			print(val)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1407/B:
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.

You're given $n$ positive integers $a_1, a_2, \dots, a_n$. Using each of them exactly at once, you're to make such sequence $b_1, b_2, \dots, b_n$ that sequence $c_1, c_2, \dots, c_n$ is lexicographically maximal, where $c_i=GCD(b_1,\dots,b_i)$ - the greatest common divisor of the first $i$ elements of $b$.

Alexander is really afraid of the conditions of this simple task, so he asks you to solve it.

A sequence $a$ is lexicographically smaller than a sequence $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 sequence $a$ has a smaller element than the corresponding element in $b$.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^3$). Description of the test cases follows.

The first line of each test case contains a single integer $n$ ($1 \le n \le 10^3$)  — the length of the sequence $a$.

The second line of each test case contains $n$ integers $a_1,\dots,a_n$ ($1 \le a_i \le 10^3$)  — the sequence $a$.

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

-----Output-----

For each test case output the answer in a single line  — the desired sequence $b$. If there are multiple answers, print any.

-----Example-----
Input
7
2
2 5
4
1 8 2 3
3
3 8 9
5
64 25 75 100 50
1
42
6
96 128 88 80 52 7
5
2 4 8 16 17

Output
5 2
8 2 1 3
9 3 8
100 50 25 75 64
42
128 96 80 88 52 7
17 2 4 8 16

-----Note-----

In the first test case of the...

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

def gcd(a,b):
    if b==0:return a
    return gcd(b,a%b)
for i in ' '*(int(input())):
    n=int(input())
    L=list(map(int,input().split()))
    M=[0]
    MM=[]
    check=[False]*n
    for i in range(n):
        ct=0
        pt=-1
        for j in range(n):
            if not check[j]:
                k=gcd(M[-1],L[j])
                if k>ct:
                    ct=k
                    pt=j
        M.append(ct)
        MM.append(pt)
        check[pt]=True
    for j in MM:print(L[j],end=' ')
    print()


I found an interesting problem on https://codeforces.com/problemset/problem/1407/D:
There are $n$ beautiful skyscrapers in New York, the height of the $i$-th one is $h_i$. Today some villains have set on fire first $n - 1$ of them, and now the only safety building is $n$-th skyscraper.

Let's call a jump from $i$-th skyscraper to $j$-th ($i < j$) discrete, if all skyscrapers between are strictly lower or higher than both of them. Formally, jump is discrete, if $i < j$ and one of the following conditions satisfied:   $i + 1 = j$  $\max(h_{i + 1}, \ldots, h_{j - 1}) < \min(h_i, h_j)$  $\max(h_i, h_j) < \min(h_{i + 1}, \ldots, h_{j - 1})$.

At the moment, Vasya is staying on the first skyscraper and wants to live a little longer, so his goal is to reach $n$-th skyscraper with minimal count of discrete jumps. Help him with calcualting this number.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 3 \cdot 10^5$) — total amount of skyscrapers.

The second line contains $n$ integers $h_1, h_2, \ldots, h_n$ ($1 \le h_i \le 10^9$) — heights of skyscrapers.

-----Output-----

Print single number $k$ — minimal amount of discrete jumps. We can show that an answer always exists.

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

Output
3
Input
4
4 2 2 4

Output
1
Input
2
1 1

Output
1
Input
5
100 1 100 1 100

Output
2

-----Note-----

In the first testcase, Vasya can jump in the following way: $1 \rightarrow 2 \rightarrow 4 \rightarrow 5$.

In the second and third testcases, we can reach last skyscraper in one jump.

Sequence of jumps in the fourth testcase: $1 \rightarrow 3 \rightarrow 5$.

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

class SegmentTree:
    def __init__(self, data, default=0, func=max):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(list(range(_size))):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        """func of data[start, stop)"""
        start += self._size
        stop += self._size

        res_left = res_right = self._default
        while start < stop:
            if start & 1:
                res_left = self._func(res_left, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res_right = self._func(self.data[stop], res_right)
            start >>= 1
            stop >>= 1

        return self._func(res_left, res_right)

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

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

stMax = SegmentTree(l)
stMin = SegmentTree(l, default = 10**10,func=min)

nexSmol = [-1] * n
nexTol = [-1] * n

smolS = [n-1]
tolS = [n-1]

for i in range(n - 2, -1 ,-1):
    while smolS and l[smolS[-1]] >= l[i]:
        smolS.pop()
    if smolS:
        nexSmol[i] = smolS[-1]
    smolS.append(i)

    while tolS and l[tolS[-1]] <= l[i]:
        tolS.pop()
    if tolS:
        nexTol[i] = tolS[-1]
    tolS.append(i)

best = [n] * n
best[0] = 0

for i in...


I found an interesting problem on https://codeforces.com/problemset/problem/1407/E:
Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.

There are $n$ cities in the republic, some of them are connected by $m$ directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city $1$, travel to the city $n$ by roads along some path, give a concert and fly away.

As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads — in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from $1$ to $n$, and for security reasons it has to be the shortest possible.

Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from $1$ to $n$ or the shortest path's length would be greatest possible.

A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only.

The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length.

-----Input-----

The first line contains two integers $n$, $m$ ($1 \leq n \leq 500000$, $0 \leq m \leq 500000$) — the number of cities and the number of roads.

The $i$-th of next $m$ lines contains three integers — $u_i$, $v_i$ and $t_i$ ($1 \leq u_i, v_i \leq n$, $t_i \in \{0, 1\}$) — numbers of cities connected by road and its type, respectively ($0$ —...

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

import sys
input = sys.stdin.readline
from collections import deque
n, m = map(int, input().split());back = [[] for i in range(n)]
for _ in range(m):u, v, w = map(int, input().split());u -= 1;v -= 1;back[v].append((u,w))
out = [2] * n;outl = [-1] * n;outl[-1] = 0;q = deque([n - 1])
while q:
    v = q.popleft()
    for u, w in back[v]:
        if out[u] != w:out[u] = 1 - w
        else:
            if outl[u] == -1:outl[u] = outl[v] + 1;q.append(u)
out = [v if v != 2 else 1 for v in out];print(outl[0]);print(''.join(map(str,out)))