I found an interesting problem on https://codeforces.com/problemset/problem/1425/E:
Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.

There are $N$ atoms numbered from $1$ to $N$. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom $i$ requires $D_i$ energy. When atom $i$ is excited, it will give $A_i$ energy. You can excite any number of atoms (including zero).

These atoms also form a peculiar one-way bond. For each $i$, $(1 \le i < N)$, if atom $i$ is excited, atom $E_i$ will also be excited at no cost. Initially, $E_i$ = $i+1$. Note that atom $N$ cannot form a bond to any atom.

Mr. Chanek must change exactly $K$ bonds. Exactly $K$ times, Mr. Chanek chooses an atom $i$, $(1 \le i < N)$ and changes $E_i$ to a different value other than $i$ and the current $E_i$. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve!

note: You must first change exactly $K$ bonds before you can start exciting atoms.

-----Input-----

The first line contains two integers $N$ $K$ $(4 \le N \le 10^5, 0 \le K < N)$, the number of atoms, and the number of bonds that must be changed.

The second line contains $N$ integers $A_i$ $(1 \le A_i \le 10^6)$, which denotes the energy given by atom $i$ when on excited state.

The third line contains $N$ integers $D_i$ $(1 \le D_i \le 10^6)$, which denotes the energy needed to excite atom $i$.

-----Output-----

A line with an integer that denotes the maximum number of energy that Mr. Chanek can get.

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

Output
35

-----Note-----

An optimal solution to change $E_5$ to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35.

Another possible way is to change $E_3$ to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4,...

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

n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
d = list(map(int, input().split()))

if k >= 2:
    m = min(d[: -1])
    print(max(sum(a) - m, a[-1] - d[-1], 0))
elif k == 0:
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    print(max(rightans))
else:
    leftd = int(1e9)
    leftsum = 0
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    for i in range(n - 1, 0, -1):
        rightans[i - 1] = max(rightans[i - 1], rightans[i])
    for i in range(n - 1):
        leftd = min(leftd, d[i])
        leftsum += a[i]
        curans = max(leftsum - leftd, 0) + rightans[i + 1]
        ans = max(ans, curans)

    cursum = 0
    rightmin = int(1e9)
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        ans = max(ans, cursum - rightmin - d[i])
        rightmin = min(rightmin, a[i])
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1426/A:
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is $n$.

There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains $2$ apartments, every other floor contains $x$ apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers $1$ and $2$, apartments on the second floor have numbers from $3$ to $(x + 2)$, apartments on the third floor have numbers from $(x + 3)$ to $(2 \cdot x + 2)$, and so on.

Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least $n$ apartments.

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 only line of the test case contains two integers $n$ and $x$ ($1 \le n, x \le 1000$) — the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).

-----Output-----

For each test case, print the answer: the number of floor on which Petya lives.

-----Example-----
Input
4
7 3
1 5
22 5
987 13

Output
3
1
5
77

-----Note-----

Consider the first test case of the example: the first floor contains apartments with numbers $1$ and $2$, the second one contains apartments with numbers $3$, $4$ and $5$, the third one contains apartments with numbers $6$, $7$ and $8$. Therefore, Petya lives on the third floor.

In the second test case of the example, Petya lives in the apartment $1$ which is on the first floor.

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

from sys import stdin, stdout
input = stdin.readline
from collections import defaultdict as dd
import math
def geti(): return list(map(int, input().strip().split()))
def getl(): return list(map(int, input().strip().split()))
def gets(): return input()
def geta(): return int(input())
def print_s(s): stdout.write(s+'\n')

def solve():
    for _ in range(geta()):
        n,k=geti()
        n-=2
        ans=1
        while n>0:
            ans+=1
            n-=k
        print(ans)

def __starting_point():
    solve()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1426/B:
Masha has $n$ types of tiles of size $2 \times 2$. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.

Masha decides to construct the square of size $m \times m$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.

Symmetric with respect to the main diagonal matrix is such a square $s$ that for each pair $(i, j)$ the condition $s[i][j] = s[j][i]$ holds. I.e. it is true that the element written in the $i$-row and $j$-th column equals to the element written in the $j$-th row and $i$-th column.

Your task is to determine if Masha can construct a square of size $m \times m$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains two integers $n$ and $m$ ($1 \le n \le 100$, $1 \le m \le 100$) — the number of types of tiles and the size of the square Masha wants to construct.

The next $2n$ lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines.

The first line of the description contains two positive (greater than zero) integers not exceeding $100$ — the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the...

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

for _ in range(int(input())):
    n, m = tuple(map(int, input().split()))
    res = False
    for i in range(n):
        a, b = tuple(map(int, input().split()))
        c, d = tuple(map(int, input().split()))
        if b == c:
            res = True

    if m % 2 == 0 and res:
        print('YES')
    else:
        print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1426/D:
Kolya got an integer array $a_1, a_2, \dots, a_n$. The array can contain both positive and negative integers, but Kolya doesn't like $0$, so the array doesn't contain any zeros.

Kolya doesn't like that the sum of some subsegments of his array can be $0$. The subsegment is some consecutive segment of elements of the array.

You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum $0$. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, $0$, any by absolute value, even such a huge that they can't be represented in most standard programming languages).

Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $0$.

-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 200\,000$) — the number of elements in Kolya's array.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^{9} \le a_i \le 10^{9}, a_i \neq 0$) — the description of Kolya's array.

-----Output-----

Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $0$.

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

Output
1

Input
5
4 -2 3 -9 2

Output
0

Input
9
-1 1 -1 1 -1 1 1 -1 -1

Output
6

Input
8
16 -5 -11 -15 10 5 4 -4

Output
3

-----Note-----

Consider the first example. There is only one subsegment with the sum $0$. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer $1$ between second and third elements of the array.

There are no subsegments having sum $0$ in the second example so you don't need to do anything.

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

from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *
import sys
'''
@lru_cache(None)
def fact(x):
    if x<2:
        return 1
    return fact(x-1)*x

@lru_cache(None)
def per(i,j):
    return fact(i)//fact(i-j)

@lru_cache(None)
def com(i,j):
    return per(i,j)//fact(j)

def linc(f,t,l,r):
    while l<r:
        mid=(l+r)//2
        if t>f(mid):
            l=mid+1
        else:
            r=mid
    return l

def rinc(f,t,l,r):
    while l<r:
        mid=(l+r+1)//2
        if t<f(mid):
            r=mid-1
        else:
            l=mid
    return l

def ldec(f,t,l,r):
    while l<r:
        mid=(l+r)//2
        if t<f(mid):
            l=mid+1
        else:
            r=mid
    return l

def rdec(f,t,l,r):
    while l<r:
        mid=(l+r+1)//2
        if t>f(mid):
            r=mid-1
        else:
            l=mid
    return l

def isprime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False
    return True

def power2(n):
    while not n&1:
        n>>=1
    return n==1
'''
'''
for i in range(t):
    #n,m=map(int,input().split())
    n,m=1,0
    graph=defaultdict(set)
    for i in range(m):
        u,v=map(int,input().split())
        graph[u-1].add(v-1)
    visited=[0]*n
    ans=[]
    def delchild(u):
        for child in graph[u]:
            visited[child]=1
            ans.append(child+1)
    for i in range(n):
        if not visited[i]:
            children=graph[i]
            if len(children)==1:
                u=children.pop()
                visited[u]=1
                delchild(u)
            elif len(children)==2:
                u=children.pop()
                v=children.pop()
                if u in graph[v]:
                    delchild(v)
                    visited[v]=1
                elif v in graph[u]:
                    delchild(u)
                    visited[u]=1
                else:
                    delchild(u)
    ...


I found an interesting problem on https://codeforces.com/problemset/problem/1426/E:
Alice and Bob have decided to play the game "Rock, Paper, Scissors".

The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a draw. Otherwise, the following rules applied:

  if one player showed rock and the other one showed scissors, then the player who showed rock is considered the winner and the other one is considered the loser;  if one player showed scissors and the other one showed paper, then the player who showed scissors is considered the winner and the other one is considered the loser;  if one player showed paper and the other one showed rock, then the player who showed paper is considered the winner and the other one is considered the loser.

Alice and Bob decided to play exactly $n$ rounds of the game described above. Alice decided to show rock $a_1$ times, show scissors $a_2$ times and show paper $a_3$ times. Bob decided to show rock $b_1$ times, show scissors $b_2$ times and show paper $b_3$ times. Though, both Alice and Bob did not choose the sequence in which they show things. It is guaranteed that $a_1 + a_2 + a_3 = n$ and $b_1 + b_2 + b_3 = n$.

Your task is to find two numbers:

  the minimum number of round Alice can win;  the maximum number of rounds Alice can win.

-----Input-----

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

The second line of the input contains three integers $a_1, a_2, a_3$ ($0 \le a_i \le n$) — the number of times Alice will show rock, scissors and paper, respectively. It is guaranteed that $a_1 + a_2 + a_3 = n$.

The third line of the input contains three integers $b_1, b_2, b_3$ ($0 \le b_j \le n$) — the number of times Bob will show rock, scissors and paper, respectively. It is guaranteed that $b_1 + b_2 + b_3 = n$.

-----Output-----

Print two integers: the minimum and the maximum number of rounds Alice can...

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

from itertools import permutations

def read_int():
    return int(input())

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

n = read_int()
a = list(read_ints())
b = list(read_ints())
hi = min(a[0], b[1]) + min(a[1], b[2]) + min(a[2], b[0])
lo = n
prs = [(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 0)]
for seq in permutations(prs):
    a1 = a.copy()
    b1 = b.copy()
    no_win = 0
    for pr in seq:
        ai = pr[1]
        bi = pr[0]
        delta = min(a1[ai], b1[bi])
        no_win += delta
        a1[ai] -= delta
        b1[bi] -= delta
    lo = min(lo, n - no_win)
print(lo, hi)


I found an interesting problem on https://codeforces.com/problemset/problem/1426/F:
You are given a string $s$ consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".

Let the number of question marks in the string $s$ be $k$. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all $3^{k}$ possible strings consisting only of letters "a", "b" and "c". For example, if $s = $"ac?b?c" then we can obtain the following strings: $[$"acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"$]$.

Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo $10^{9} + 7$.

A subsequence of the string $t$ is such a sequence that can be derived from the string $t$ after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions $(2, 5, 6)$ and a subsequence consisting of letters at positions $(3, 5, 6)$.

-----Input-----

The first line of the input contains one integer $n$ $(3 \le n \le 200\,000)$ — the length of $s$.

The second line of the input contains the string $s$ of length $n$ consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".

-----Output-----

Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo $10^{9} + 7$.

-----Examples-----
Input
6
ac?b?c

Output
24

Input
7
???????

Output
2835

Input
9
cccbbbaaa

Output
0

Input
5
a???c

Output
46

-----Note-----

In the first example, we can obtain $9$ strings:  "acabac" — there are $2$ subsequences "abc",  "acabbc" — there are $4$ subsequences "abc",  "acabcc" — there are $4$ subsequences "abc",  "acbbac" — there are $2$ subsequences "abc",  "acbbbc" — there are $3$ subsequences "abc",  "acbbcc" — there are $4$ subsequences "abc",  "accbac" — there is $1$ subsequence "abc",  "accbbc" — there are $2$...

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

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

dp = [[0, 0, 0] for _ in range(n)]
dp2 = [[0, 0, 0] for _ in range(n)]
prev = [0, 0, 0]
free = 0

mod = 1000000007
for i in range(n):
	if i > 0:
		dp[i] = dp[i-1].copy()
	if s[i] == 'a':
		dp[i][0] += 1
	if s[i] == 'b':
		dp[i][1] += dp[i][0]
		if dp[i][1] >= mod:
			dp[i][1] -= mod
	if s[i] == 'c':
		dp[i][2] += dp[i][1]
		if dp[i][2] >= mod:
			dp[i][2] -= mod
	if s[i] == '?':
		free += 1

for i in reversed(range(0, n)):
	if i+1 < n:
		dp2[i] = dp2[i+1].copy()
	if s[i] == 'c':
		dp2[i][0] += 1
	if s[i] == 'b':
		dp2[i][1] += dp2[i][0]
		if dp2[i][1] >= mod:
			dp2[i][1] -= mod
	if s[i] == 'a':
		dp2[i][2] += dp2[i][1]
		if dp2[i][2] >= mod:
			dp2[i][2] -= mod

ans = dp[n-1][2] * pow(3, free, mod) % mod
ans += (free*(free-1)*(free-2)//6) * pow(3, mod-1+free-3, mod) % mod
before, after = 0, free
for i in range(n):
	if s[i] == '?':
		mul = pow(3, free-1, mod)
		ans += mul*(dp[i][0] * dp2[i][0] + dp2[i][1] + dp[i][1]) % mod
		before += 1
		after -= 1
	if s[i] == 'a':
		ans += pow(3, mod-1+free-2, mod) * (after*(after-1)//2) % mod
	if s[i] == 'b':
		ans += pow(3, mod-1+free-2, mod) * (after * before)%mod
	if s[i] == 'c':
		ans += pow(3, mod-1+free-2, mod) * (before*(before-1)//2) % mod
	if ans >= mod:
		ans %= mod
print(ans%mod)


I found an interesting problem on https://codeforces.com/problemset/problem/1427/A:
You are given an array of $n$ integers $a_1,a_2,\dots,a_n$.

You have to create an array of $n$ integers $b_1,b_2,\dots,b_n$ such that:   The array $b$ is a rearrangement of the array $a$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets $\{a_1,a_2,\dots,a_n\}$ and $\{b_1,b_2,\dots,b_n\}$ are equal.

For example, if $a=[1,-1,0,1]$, then $b=[-1,1,1,0]$ and $b=[0,1,-1,1]$ are rearrangements of $a$, but $b=[1,-1,-1,0]$ and $b=[1,0,2,-3]$ are not rearrangements of $a$.  For all $k=1,2,\dots,n$ the sum of the first $k$ elements of $b$ is nonzero. Formally, for all $k=1,2,\dots,n$, it must hold $$b_1+b_2+\cdots+b_k\not=0\,.$$

If an array $b_1,b_2,\dots, b_n$ with the required properties does not exist, you have to print NO.

-----Input-----

Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each testcase contains one integer $n$ ($1\le n\le 50$)  — the length of the array $a$.

The second line of each testcase contains $n$ integers $a_1,a_2,\dots, a_n$ ($-50\le a_i\le 50$)  — the elements of $a$.

-----Output-----

For each testcase, if there is not an array $b_1,b_2,\dots,b_n$ with the required properties, print a single line with the word NO.

Otherwise print a line with the word YES, followed by a line with the $n$ integers $b_1,b_2,\dots,b_n$.

If there is more than one array $b_1,b_2,\dots,b_n$ satisfying the required properties, you can print any of them.

-----Example-----
Input
4
4
1 -2 3 -4
3
0 0 0
5
1 -1 1 -1 1
6
40 -31 -9 0 13 -40

Output
YES
1 -2 3 -4
NO
YES
1 1 -1 1 -1
YES
-40 13 40 0 -9 -31

-----Note-----

Explanation of the first testcase: An array with the desired properties is $b=[1,-2,3,-4]$. For this array, it holds:   The first element of $b$ is $1$.  The sum of the first two elements of $b$ is $-1$.  The sum of the first three elements of $b$ is $2$.  The sum of the...

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

t = int(input())
for _ in range(t):
    n = int(input())
    l = sorted(map(int, input().split()))

    if sum(l) == 0:
        print('NO')
    elif sum(l) > 0:
        print('YES')
        print(' '.join(map(str,l[::-1])))
    else:
        print('YES')
        print(' '.join(map(str,l)))


I found an interesting problem on https://codeforces.com/problemset/problem/1428/B:
In the snake exhibition, there are $n$ rooms (numbered $0$ to $n - 1$) arranged in a circle, with a snake in each room. The rooms are connected by $n$ conveyor belts, and the $i$-th conveyor belt connects the rooms $i$ and $(i+1) \bmod n$. In the other words, rooms $0$ and $1$, $1$ and $2$, $\ldots$, $n-2$ and $n-1$, $n-1$ and $0$ are connected with conveyor belts.

The $i$-th conveyor belt is in one of three states:  If it is clockwise, snakes can only go from room $i$ to $(i+1) \bmod n$.  If it is anticlockwise, snakes can only go from room $(i+1) \bmod n$ to $i$.  If it is off, snakes can travel in either direction.  [Image]

Above is an example with $4$ rooms, where belts $0$ and $3$ are off, $1$ is clockwise, and $2$ is anticlockwise.

Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?

-----Input-----

Each test contains multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 1000$): the number of test cases. The description of the test cases follows.

 The first line of each test case description contains a single integer $n$ ($2 \le n \le 300\,000$): the number of rooms.

 The next line of each test case description contains a string $s$ of length $n$, consisting of only '<', '>' and '-'.  If $s_{i} = $ '>', the $i$-th conveyor belt goes clockwise.  If $s_{i} = $ '<', the $i$-th conveyor belt goes anticlockwise.  If $s_{i} = $ '-', the $i$-th conveyor belt is off.

It is guaranteed that the sum of $n$ among all test cases does not exceed $300\,000$.

-----Output-----

For each test case, output the number of returnable rooms.

-----Example-----
Input
4
4
-><-
5
>>>>>
3
<--
2
<>

Output
3
5
3
0

-----Note-----

In the first test case, all rooms are returnable except room $2$. The snake in the room $2$ is trapped and cannot exit. This test case corresponds to the picture from the problem statement.

 In the...

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

T = int(input())
for __ in range(T):
    n = int(input())
    s = input()
    ok = all((c in '-<') for c in s) or all((c in '->') for c in s)
    cnt = 0
    for i in range(n):
        j = (i + 1) % n
        c1, c2 = s[i], s[j]
        if c1 == '-' or c2 == '-':
            cnt += 1
        else:
            cnt += (1 if ok else 0)
    print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/1428/D:
To improve the boomerang throwing skills of the animals, Zookeeper has set up an $n \times n$ grid with some targets, where each row and each column has at most $2$ targets each. The rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $n$ from left to right.

 For each column, Zookeeper will throw a boomerang from the bottom of the column (below the grid) upwards. When the boomerang hits any target, it will bounce off, make a $90$ degree turn to the right and fly off in a straight line in its new direction. The boomerang can hit multiple targets and does not stop until it leaves the grid.

  [Image]

In the above example, $n=6$ and the black crosses are the targets. The boomerang in column $1$ (blue arrows) bounces $2$ times while the boomerang in column $3$ (red arrows) bounces $3$ times.

 The boomerang in column $i$ hits exactly $a_i$ targets before flying out of the grid. It is known that $a_i \leq 3$.

However, Zookeeper has lost the original positions of the targets. Thus, he asks you to construct a valid configuration of targets that matches the number of hits for each column, or tell him that no such configuration exists. If multiple valid configurations exist, you may print any of them.

-----Input-----

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

 The next line contains $n$ integers $a_1,a_2,\ldots,a_n$ $(0 \leq a_i \leq 3)$.

-----Output-----

If no configuration of targets exist, print $-1$.

 Otherwise, on the first line print a single integer $t$ $(0 \leq t \leq 2n)$: the number of targets in your configuration.

 Then print $t$ lines with two spaced integers each per line. Each line should contain two integers $r$ and $c$ $(1 \leq r,c \leq n)$, where $r$ is the target's row and $c$ is the target's column. All targets should be different.

 Every row and every column in your configuration should have at most two targets each.

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

Output
5
2 1
2 5
3 3
3 6
5...

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

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

    n = int(input())
    ans = []
    arr = list(map(int, input().split()))
    amt = [2 if x else 0 for x in arr]

    bottoms = []
    bottoms1 = []
    others = []
    idx = 0
    idx1 = 0

    for i in range(n-1, -1, -1):
        if arr[i] == 0:
            continue
        if arr[i] == 1:
            bottoms.append((i + 1, i + 1))
        if arr[i] == 2:
            if idx == len(bottoms):
                print(-1)
                return

            r, c = bottoms[idx]
            bottoms1.append((r, i + 1))
            idx += 1
        if arr[i] == 3:
            if idx == len(bottoms) and idx1 == len(bottoms1):
                print(-1)
                return
            elif idx1 == len(bottoms1):
                r, c = bottoms[idx]
                bottoms1.append((i + 1, i + 1))
                others.append((i + 1, c))
                idx += 1
            else:
                r, c = bottoms1[idx1]
                bottoms1.append((i + 1, i + 1))
                others.append((i + 1, c))
                idx1 += 1

    # if arr[-1] > 1:
    #     print(-1)
    #     return
    # elif arr[-1] == 1:
    #     amt[-1] -= 1
    #     ans.append((n, n))
    # x = -1
    # y = -1
    # rindex = n - 1
    # for i in range(n - 1, -1, -1):
    #     if arr[i] == 0:
    #         continue
    #     elif arr[i] == 1:
    #         amt[i] -= 1
    #         ans.append((i + 1, i + 1))

    #         if y == -1:
    #             x = i
    #             y = i + 1
    #     elif arr[i] == 2:
    #         if y == -1:
    #             print(-1)
    #             return

    #         amt[i] -= 1
    #         ans.append((y, i + 1))
    #     elif arr[i] == 3:
    #         if x == -1:
    #             print(-1)
    #             return
    #         while rindex > i and (rindex == x or not arr[rindex]):
    #             rindex -= 1
    #         if rindex == i:
    #             print(-1)
    #          ...


I found an interesting problem on https://codeforces.com/problemset/problem/1430/A:
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.

Monocarp went around the building and counted $n$ windows. Now he is wondering, how many apartments of each type the building may have.

Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has $n$ windows. If there are multiple answers, you can print any of them.

Here are some examples:

  if Monocarp has counted $30$ windows, there could have been $2$ three-room apartments, $2$ five-room apartments and $2$ seven-room apartments, since $2 \cdot 3 + 2 \cdot 5 + 2 \cdot 7 = 30$;  if Monocarp has counted $67$ windows, there could have been $7$ three-room apartments, $5$ five-room apartments and $3$ seven-room apartments, since $7 \cdot 3 + 5 \cdot 5 + 3 \cdot 7 = 67$;  if Monocarp has counted $4$ windows, he should have mistaken since no building with the aforementioned layout can have $4$ windows.

-----Input-----

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

The only line of each test case contains one integer $n$ ($1 \le n \le 1000$) — the number of windows in the building.

-----Output-----

For each test case, if a building with the new layout and the given number of windows just can't exist, print $-1$.

Otherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.

-----Example-----
Input
4
30
67
4
14

Output
2 2 2
7 5 3
-1
0 0 2

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('\n'.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=10**9+7

for t in range(int(data())):
    n=int(data())
    k=n//3
    if n%3==2:
        if k<1:
            print(-1)
            continue
        print(k-1,1,0)
    elif n%3==1:
        if k<2:
            print(-1)
            continue
        print(k-2,0,1)
    else:
        print(k,0,0)


I found an interesting problem on https://codeforces.com/problemset/problem/1430/E:
You are given a string $s$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the string "aeddba". To accomplish your goal, you can swap the neighboring elements of the string.

Your task is to calculate the minimum number of swaps you have to perform to reverse the given string.

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 200\,000$) — the length of $s$.

The second line contains $s$ — a string consisting of $n$ lowercase Latin letters.

-----Output-----

Print one integer — the minimum number of swaps of neighboring elements you have to perform to reverse the string.

-----Examples-----
Input
5
aaaza

Output
2

Input
6
cbaabc

Output
0

Input
9
icpcsguru

Output
30

-----Note-----

In the first example, you have to swap the third and the fourth elements, so the string becomes "aazaa". Then you have to swap the second and the third elements, so the string becomes "azaaa". So, it is possible to reverse the string in two swaps.

Since the string in the second example is a palindrome, you don't have to do anything to reverse it.

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

N = int(input())
S = input()

dic = {}
for i, s in enumerate(S):
    if s in dic:
        dic[s].append(i)
    else:
        dic[s] = [i]

X = list(range(N-1, -1, -1))
for c, idcs in list(dic.items()):
    for p, q in zip(idcs, reversed(idcs)):
        X[p] = N-1-q

class BIT():
    def __init__(self, N):
        self.N = N
        self.T = [0]*(N+1)
    def add(self, i, x):
        i += 1
        while i <= self.N:
            self.T[i] += x
            i += i & -i
    def _sum(self, i): #[0,i)
        ret = 0
        while i > 0:
            ret += self.T[i]
            i ^= i & -i
        return ret
    def sum(self, l, r): #[l,r)
        return self._sum(r)-self._sum(l)
    def lower_bound(self, w):
        if w <= 0:
            return 0
        x = 0
        k = 1<<self.N.bit_length()
        while k:
            if x+k <= self.N and self.T[x+k] < w:
                w -= self.t[x+k]
                x += k
                k >>= 1
        return x+1

b = BIT(N)
ans = 0
for i, x in enumerate(X):
    ans += i - b._sum(x+1)
    b.add(x, 1)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1430/F:
Recently you've discovered a new shooter. They say it has realistic game mechanics.

Your character has a gun with magazine size equal to $k$ and should exterminate $n$ waves of monsters. The $i$-th wave consists of $a_i$ monsters and happens from the $l_i$-th moment of time up to the $r_i$-th moments of time. All $a_i$ monsters spawn at moment $l_i$ and you have to exterminate all of them before the moment $r_i$ ends (you can kill monsters right at moment $r_i$). For every two consecutive waves, the second wave starts not earlier than the first wave ends (though the second wave can start at the same moment when the first wave ends) — formally, the condition $r_i \le l_{i + 1}$ holds. Take a look at the notes for the examples to understand the process better.

You are confident in yours and your character's skills so you can assume that aiming and shooting are instant and you need exactly one bullet to kill one monster. But reloading takes exactly $1$ unit of time.

One of the realistic mechanics is a mechanic of reloading: when you reload you throw away the old magazine with all remaining bullets in it. That's why constant reloads may cost you excessive amounts of spent bullets.

You've taken a liking to this mechanic so now you are wondering: what is the minimum possible number of bullets you need to spend (both used and thrown) to exterminate all waves.

Note that you don't throw the remaining bullets away after eradicating all monsters, and you start with a full magazine.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le n \le 2000$; $1 \le k \le 10^9$) — the number of waves and magazine size.

The next $n$ lines contain descriptions of waves. The $i$-th line contains three integers $l_i$, $r_i$ and $a_i$ ($1 \le l_i \le r_i \le 10^9$; $1 \le a_i \le 10^9$) — the period of time when the $i$-th wave happens and the number of monsters in it.

It's guaranteed that waves don't overlap (but may touch) and are given in the order they occur, i. e. $r_i \le l_{i +...

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

import sys

n, k = list(map(int, sys.stdin.readline().strip().split()))
L = []
R = []
A = []
for i in range (0, n):
    x = list(map(int, sys.stdin.readline().strip().split()))
    L.append(x[0])
    R.append(x[1])
    A.append(x[2])
L.append(R[-1])
i = n-1
x = 0
y = 0
ans = 0
v = True
N = [0 for i in range (0, n)]
while i >= 0:
    if R[i] == L[i+1]:
        x = max(x + A[i] - k * (R[i] - L[i]), 0)
        N[i] = x
    else:
        x = max(A[i] - k * (R[i] - L[i]), 0)
        N[i] = x
    if N[i] > k:
        v = False
    i = i - 1
m = k
N.append(0)
i = 0
while i < n and v == True:
    if m < N[i]:
        ans = ans + m
        m = k
    m = m - A[i]
    ans = ans + A[i]
    while m < 0:
        m = m + k
    i = i + 1
if v == True:
    print(ans)
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1433/A:
There is a building consisting of $10~000$ apartments numbered from $1$ to $10~000$, inclusive.

Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are $11, 2, 777, 9999$ and so on.

Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone answers the call, in the following order:

  First he calls all apartments consisting of digit $1$, in increasing order ($1, 11, 111, 1111$).  Next he calls all apartments consisting of digit $2$, in increasing order ($2, 22, 222, 2222$)  And so on.

The resident of the boring apartment $x$ answers the call, and our character stops calling anyone further.

Our character wants to know how many digits he pressed in total and your task is to help him to count the total number of keypresses.

For example, if the resident of boring apartment $22$ answered, then our character called apartments with numbers $1, 11, 111, 1111, 2, 22$ and the total number of digits he pressed is $1 + 2 + 3 + 4 + 1 + 2 = 13$.

You have to answer $t$ independent test cases.

-----Input-----

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

The only line of the test case contains one integer $x$ ($1 \le x \le 9999$) — the apartment number of the resident who answered the call. It is guaranteed that $x$ consists of the same digit.

-----Output-----

For each test case, print the answer: how many digits our character pressed in total.

-----Example-----
Input
4
22
9999
1
777

Output
13
90
1
66

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

import sys
input=sys.stdin.readline
from collections import defaultdict as dc
from bisect import bisect_right
import math
for _ in range(int(input())):
    n=int(input())
    x=n%10
    c=10*(x-1)
    s=str(n)
    for i in range(len(s)):
        c+=i+1
    print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/1433/B:
There is a bookshelf which can fit $n$ books. The $i$-th position of bookshelf is $a_i = 1$ if there is a book on this position and $a_i = 0$ otherwise. It is guaranteed that there is at least one book on the bookshelf.

In one move, you can choose some contiguous segment $[l; r]$ consisting of books (i.e. for each $i$ from $l$ to $r$ the condition $a_i = 1$ holds) and:  Shift it to the right by $1$: move the book at index $i$ to $i + 1$ for all $l \le i \le r$. This move can be done only if $r+1 \le n$ and there is no book at the position $r+1$.  Shift it to the left by $1$: move the book at index $i$ to $i-1$ for all $l \le i \le r$. This move can be done only if $l-1 \ge 1$ and there is no book at the position $l-1$.

Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).

For example, for $a = [0, 0, 1, 0, 1]$ there is a gap between books ($a_4 = 0$ when $a_3 = 1$ and $a_5 = 1$), for $a = [1, 1, 0]$ there are no gaps between books and for $a = [0, 0,0]$ there are also no gaps between books.

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 200$) — 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 places on a bookshelf. The second line of the test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 1$), where $a_i$ is $1$ if there is a book at this position and $0$ otherwise. It is guaranteed that there is at least one book on the bookshelf.

-----Output-----

For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).

-----Example-----
Input
5
7
0 0 1 0 1 0 1
3
1 0 0
5
1 1 0 0 1
6
1 0 0 0 0 1
5
1 1 0 1 1

Output
2
0
2
4
1

-----Note-----

In the first test case of the...

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

import sys

def read(func=int):
    return func(sys.stdin.readline().strip())

def readList(func=int):
    return list(map(func, sys.stdin.readline().strip().split()))

t = read()

for _ in range(t):
    n = read()
    A = readList()
    ri = -1
    for i in range(n - 1, -1, -1):
        if A[i]:
            ri = i
            break
    count = 0
    start = False
    for i in range(n):
        num = A[i]
        if num == 1:
            start = True
        if num == 0 and start and i < ri:
            count += 1

    print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/1433/D:
There are $n$ districts in the town, the $i$-th district belongs to the $a_i$-th bandit gang. Initially, no districts are connected to each other.

You are the mayor of the city and want to build $n-1$ two-way roads to connect all districts (two districts can be connected directly or through other connected districts).

If two districts belonging to the same gang are connected directly with a road, this gang will revolt.

You don't want this so your task is to build $n-1$ two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build $n-1$ roads to satisfy all the conditions.

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains one integer $n$ ($2 \le n \le 5000$) — the number of districts. The second line of the test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the gang the $i$-th district belongs to.

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

-----Output-----

For each test case, print:

  NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement.  YES on the first line and $n-1$ roads on the next $n-1$ lines. Each road should be presented as a pair of integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n; x_i \ne y_i$), where $x_i$ and $y_i$ are two districts the $i$-th road connects.

For each road $i$, the condition $a[x_i] \ne a[y_i]$ should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).

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

Output
YES
1 3
3 5
5 4
1 2
NO
YES
1 2
2 3
3 4
YES
1 2
1 3
1 4

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

'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return list(map(int,input().split()))
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
# mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

file = 1

def solve():

    for _ in range(ii()):

        n = ii()
        a = li()
        if len(set(a)) == 1:
            print('NO')
            continue
        print('YES')
        ans,p = [],[]
        x = a[0]
        y = -1
        for i in range(1,n):
            if a[i] != x:
                y = i+1
                ans.append([1,i+1])
            else:
                p.append(i+1)

        for i in p:
            ans.append([y,i])

        for i in ans:
            print(*i)

def __starting_point():

    if(file):

        if path.exists('input.txt'):
            sys.stdin=open('input.txt', 'r')
            sys.stdout=open('output.txt','w')
        else:
            input=sys.stdin.readline
    solve()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1433/E:
One day, $n$ people ($n$ is an even number) met on a plaza and made two round dances, each round dance consists of exactly $\frac{n}{2}$ people. Your task is to find the number of ways $n$ people can make two round dances if each round dance consists of exactly $\frac{n}{2}$ people. Each person should belong to exactly one of these two round dances.

Round dance is a dance circle consisting of $1$ or more people. Two round dances are indistinguishable (equal) if one can be transformed to another by choosing the first participant. For example, round dances $[1, 3, 4, 2]$, $[4, 2, 1, 3]$ and $[2, 1, 3, 4]$ are indistinguishable.

For example, if $n=2$ then the number of ways is $1$: one round dance consists of the first person and the second one of the second person.

For example, if $n=4$ then the number of ways is $3$. Possible options:  one round dance — $[1,2]$, another — $[3,4]$;  one round dance — $[2,4]$, another — $[3,1]$;  one round dance — $[4,1]$, another — $[3,2]$.

Your task is to find the number of ways $n$ people can make two round dances if each round dance consists of exactly $\frac{n}{2}$ people.

-----Input-----

The input contains one integer $n$ ($2 \le n \le 20$), $n$ is an even number.

-----Output-----

Print one integer — the number of ways to make two round dances. It is guaranteed that the answer fits in the $64$-bit integer data type.

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

Output
1

Input
4

Output
3

Input
8

Output
1260

Input
20

Output
12164510040883200

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

def fact(a):
    if a == 1:
        return 1
    else:
        return fact(a - 1) * a
n = int(input())
print(fact(n) // fact(n // 2) // (n // 2) * (fact(n // 2) // (n // 2)) // 2)


I found an interesting problem on https://codeforces.com/problemset/problem/1433/F:
You are given a matrix $a$ of size $n \times m$ consisting of integers.

You can choose no more than $\left\lfloor\frac{m}{2}\right\rfloor$ elements in each row. Your task is to choose these elements in such a way that their sum is divisible by $k$ and this sum is the maximum.

In other words, you can choose no more than a half (rounded down) of elements in each row, you have to find the maximum sum of these elements divisible by $k$.

Note that you can choose zero elements (and the sum of such set is $0$).

-----Input-----

The first line of the input contains three integers $n$, $m$ and $k$ ($1 \le n, m, k \le 70$) — the number of rows in the matrix, the number of columns in the matrix and the value of $k$. The next $n$ lines contain $m$ elements each, where the $j$-th element of the $i$-th row is $a_{i, j}$ ($1 \le a_{i, j} \le 70$).

-----Output-----

Print one integer — the maximum sum divisible by $k$ you can obtain.

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

Output
24

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

Output
56

-----Note-----

In the first example, the optimal answer is $2$ and $4$ in the first row, $5$ and $2$ in the second row and $7$ and $4$ in the third row. The total sum is $2 + 4 + 5 + 2 + 7 + 4 = 24$.

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

n, m, k = list(map(int, input().split()))
mat = [list(map(int, input().split())) for i in range(n)]
inf = 1 << 30
modulars = [[-inf]*(k) for i in range(n)]

for index in range(n):
    a = mat[index]
    dp = [[[-inf]*k for i in range(m//2+1)]for _ in range(m+1)]
    #dp[index][picked][mod] = index番目まで見てそのうちpicked個取ってmodular(mod k) になる時の最大値
    dp[0][0][0] = 0
    for i in range(1, m+1):
        v = a[i-1]
        for picked in range(m//2+1):
            for mod in range(k):
                if picked >= 1:
                    dp[i][picked][mod] = max(dp[i][picked][mod],dp[i-1][picked][mod], dp[i-1][picked-1][(mod-v) % k]+v)
                else:
                    dp[i][picked][mod] = max(dp[i][picked][mod],dp[i-1][picked][mod])

    for mod in range(k):
        modulars[index][mod] = max(dp[m][picked][mod]
                                   for picked in range(m//2+1))

dp = [[-inf]*(k) for i in range(n+1)]
dp[0][0] = 0
#dp[n][mod] = n番目まで見て総和がmodの時の最大値
for i in range(1, n+1):
    for mod in range(k):
        dp[i][mod] = max(dp[i-1][(mod-prevmod) % k] +
                         modulars[i-1][prevmod]for prevmod in range(k))

ans = dp[n][0]
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1433/G:
You are a mayor of Berlyatov. There are $n$ districts and $m$ two-way roads between them. The $i$-th road connects districts $x_i$ and $y_i$. The cost of travelling along this road is $w_i$. There is some path between each pair of districts, so the city is connected.

There are $k$ delivery routes in Berlyatov. The $i$-th route is going from the district $a_i$ to the district $b_i$. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district $a_i$ to the district $b_i$ to deliver products.

The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).

You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $0$).

Let $d(x, y)$ be the cheapest cost of travel between districts $x$ and $y$.

Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $0$. In other words, you have to find the minimum possible value of $\sum\limits_{i = 1}^{k} d(a_i, b_i)$ after applying the operation described above optimally.

-----Input-----

The first line of the input contains three integers $n$, $m$ and $k$ ($2 \le n \le 1000$; $n - 1 \le m \le min(1000, \frac{n(n-1)}{2})$; $1 \le k \le 1000$) — the number of districts, the number of roads and the number of courier routes.

The next $m$ lines describe roads. The $i$-th road is given as three integers $x_i$, $y_i$ and $w_i$ ($1 \le x_i, y_i \le n$; $x_i \ne y_i$; $1 \le w_i \le 1000$), where $x_i$ and $y_i$ are districts the $i$-th road connects and $w_i$ is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts.

The next $k$ lines describe courier routes. The $i$-th route is given as two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le n$) — the districts of the $i$-th route. The...

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

import sys
input = sys.stdin.readline

import heapq

def dijkstra(n, s, edges):
    hq = [(0, s)]
    cost = [float('inf')] * n
    cost[s] = 0
    while hq:
        c, v = heapq.heappop(hq)
        if c > cost[v]:
            continue
        for d, u in edges[v]:
            tmp = d + cost[v]
            if tmp < cost[u]:
                cost[u] = tmp
                heapq.heappush(hq, (tmp, u))
    return cost

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

    edges = [[] for _ in range(n)]
    xy = []
    for _ in range(m):
        x, y, t = map(int,input().split())
        x -= 1
        y -= 1
        edges[x].append((t, y))
        edges[y].append((t, x))
        xy.append((x, y))

    dist = [[] for _ in range(n)]
    for i in range(n):
        dist[i] = dijkstra(n, i, edges)

    ab = [list(map(int, input().split())) for _ in range(k)]
    ans = 10 ** 20
    for x, y in xy:
        tmp = 0
        for a, b in ab:
            a -= 1
            b -= 1
            tmp += min(dist[a][b], dist[a][x] + dist[b][y], dist[a][y] + dist[b][x])
        ans = min(ans, tmp)
    print(ans)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1436/A:
For a given array $a$ consisting of $n$ integers and a given integer $m$ find if it is possible to reorder elements of the array $a$ in such a way that $\sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}}$ equals $m$? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, $\frac{5}{2}=2.5$.

-----Input-----

The first line contains a single integer $t$ — the number of test cases ($1 \le t \le 100$). The test cases follow, each in two lines.

The first line of a test case contains two integers $n$ and $m$ ($1 \le n \le 100$, $0 \le m \le 10^6$). The second line contains integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^6$) — the elements of the array.

-----Output-----

For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.

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

Output
YES
NO

-----Note-----

In the first test case one of the reorders could be $[1, 2, 5]$. The sum is equal to $(\frac{1}{1} + \frac{2}{2} + \frac{5}{3}) + (\frac{2}{2} + \frac{5}{3}) + (\frac{5}{3}) = 8$. The brackets denote the inner sum $\sum_{j=i}^{n}{\frac{a_j}{j}}$, while the summation of brackets corresponds to the sum over $i$.

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

from sys import stdin, stdout
input = stdin.readline
from collections import defaultdict as dd
import math
def geti(): return list(map(int, input().strip().split()))
def getl(): return list(map(int, input().strip().split()))
def gets(): return input()
def geta(): return int(input())
def print_s(s): stdout.write(s+'\n')

def solve():
    for _ in range(geta()):
        n,m=geti()
        a=getl()
        if sum(a)==m:
            print("YES")
        else:
            print("NO")

def __starting_point():
    solve()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1436/C:
Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number $x$ in an array. For an array $a$ indexed from zero, and an integer $x$ the pseudocode of the algorithm is as follows:

BinarySearch(a, x)
  left = 0
  right = a.size()
  while left < right
    middle = (left + right) / 2
    if a[middle] <= x then
      left = middle + 1
    else
      right = middle

  if left > 0 and a[left - 1] == x then
    return true
  else
    return false

Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down).

Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find $x$!

Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size $n$ such that the algorithm finds $x$ in them. A permutation of size $n$ is an array consisting of $n$ distinct integers between $1$ and $n$ in arbitrary order.

Help Andrey and find the number of permutations of size $n$ which contain $x$ at position $pos$ and for which the given implementation of the binary search algorithm finds $x$ (returns true). As the result may be extremely large, print the remainder of its division by $10^9+7$.

-----Input-----

The only line of input contains integers $n$, $x$ and $pos$ ($1 \le x \le n \le 1000$, $0 \le pos \le n - 1$) — the required length of the permutation, the number to search, and the required position of that number, respectively.

-----Output-----

Print a single number — the remainder of the division of the number of valid permutations by $10^9+7$.

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

Output
6

Input
123 42 24

Output
824071958

-----Note-----

All possible permutations in the first test case: $(2, 3, 1, 4)$, $(2, 4, 1, 3)$, $(3, 2,...

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

import sys
input = sys.stdin.readline

n,x,pos=list(map(int,input().split()))
mod=10**9+7

ANS=[0]*n

left=0
right=n

while left<right:
    #print(left,right)
    middle=(left+right)//2
    if pos>=middle:
        ANS[middle]=-1
        left=middle+1
    else:
        ANS[middle]=1
        right=middle

ANS[pos]=9
#print(ANS)

P=ANS.count(1)
M=ANS.count(-1)
MINUS=x-1
PLUS=n-x

A=1
for i in range(P):
    A=A*PLUS%mod
    PLUS-=1

#print(A)
for i in range(M):
    A=A*MINUS%mod
    MINUS-=1

#print(A)

for i in range(1,n-P-M):
    A=A*i%mod

print(A)


I found an interesting problem on https://codeforces.com/problemset/problem/1436/D:
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.

The city consists of $n$ squares connected by $n-1$ roads in such a way that it is possible to reach any square from any other square. The square number $1$ is the main square.

After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.

At the moment when the bandit appeared on the main square there were $a_i$ citizens on the $i$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.

The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?

-----Input-----

The first line contains a single integer $n$ — the number of squares in the city ($2 \le n \le 2\cdot10^5$).

The second line contains $n-1$ integers $p_2, p_3 \dots p_n$ meaning that there is a one-way road from the square $p_i$ to the square $i$ ($1 \le p_i < i$).

The third line contains $n$ integers $a_1, a_2, \dots, a_n$ — the number of citizens on each square initially ($0 \le a_i \le 10^9$).

-----Output-----

Print a single integer — the number of citizens the bandit will catch if both sides act optimally.

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

Output
3

Input
3
1 1
3 1 3

Output
4

-----Note-----

In the first example the citizens on the square $1$ can split into two groups $2 + 1$, so that the second and on the third squares will have $3$ citizens each.

In the second...

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

import sys
input = sys.stdin.readline

n=int(input())
P=[1]+list(map(int,input().split()))
A=list(map(int,input().split()))

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

Y=[1]*n
for i in range(n):
    Y[P[i]]=0

#print(Y)

for i in range(n-1,0,-1):
    Y[P[i]]+=Y[i]

S=[a for a in A]
for i in range(n-1,0,-1):
    S[P[i]]+=S[i]

OK=sum(A)
NG=-1

while OK-NG>1:
    mid=(OK+NG)//2

    for i in range(n):
        if Y[i]*mid<S[i]:
            NG=mid
            break
    else:
        OK=mid

print(OK)


I found an interesting problem on https://codeforces.com/problemset/problem/1436/E:
In this problem MEX of a certain array is the smallest positive integer not contained in this array.

Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today.

You are given an array $a$ of length $n$. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers.

An array $b$ is a subarray of an array $a$, if $b$ can be obtained from $a$ by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself.

Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays!

-----Input-----

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

The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$) — the elements of the array.

-----Output-----

Print a single integer — the MEX of MEXes of all subarrays.

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

Output
3

Input
5
1 4 3 1 2

Output
6

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

class SegmentTree:
    def __init__(self, init_val, segfunc, ide_ele):
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.tree = [ide_ele] * 2 * self.num
        self.range = [(-1,n)] * 2 * self.num
        # 配列の値を葉にセット
        for i in range(n):
            self.tree[self.num + i] = init_val[i]
            self.range[self.num + i] = (i,i)
        # 構築していく
        for i in range(self.num - 1, 0, -1):
            self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
            self.range[i] = (self.range[2 * i][0],self.range[2 * i + 1][1])

    def update(self, k, x):
        k += self.num
        self.tree[k] = x
        while k > 1:
            self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
            k >>= 1

    def query(self, l, r):
        res = self.ide_ele

        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.tree[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res

    def bisect_l(self,l,r,x):
        l += self.num
        r += self.num
        Lmin = -1
        Rmin = -1
        while l<r:
            if l & 1:
                if self.tree[l] <= x and Lmin==-1:
                    Lmin = l
                l += 1
            if r & 1:
                if self.tree[r-1] <=x:
                    Rmin = r-1
            l >>= 1
            r >>= 1

        if Lmin != -1:
            pos = Lmin
            while pos<self.num:
                if self.tree[2 * pos] <=x:
                    pos = 2 * pos
                else:
                    pos = 2 * pos +1
            return pos-self.num
        elif Rmin != -1:
            pos = Rmin
            while pos<self.num:
                if self.tree[2 * pos] <=x:
                    pos = 2 * pos
                else:
                    pos...


I found an interesting problem on https://codeforces.com/problemset/problem/1437/A:
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.

Suppose you decided to sell packs with $a$ cans in a pack with a discount and some customer wants to buy $x$ cans of cat food. Then he follows a greedy strategy:   he buys $\left\lfloor \frac{x}{a} \right\rfloor$ packs with a discount;  then he wants to buy the remaining $(x \bmod a)$ cans one by one.

$\left\lfloor \frac{x}{a} \right\rfloor$ is $x$ divided by $a$ rounded down, $x \bmod a$ is the remainer of $x$ divided by $a$.

But customers are greedy in general, so if the customer wants to buy $(x \bmod a)$ cans one by one and it happens that $(x \bmod a) \ge \frac{a}{2}$ he decides to buy the whole pack of $a$ cans (instead of buying $(x \bmod a)$ cans). It makes you, as a marketer, happy since the customer bought more than he wanted initially.

You know that each of the customers that come to your shop can buy any number of cans from $l$ to $r$ inclusive. Can you choose such size of pack $a$ that each customer buys more cans than they wanted initially?

-----Input-----

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

The first and only line of each test case contains two integers $l$ and $r$ ($1 \le l \le r \le 10^9$) — the range of the number of cans customers can buy.

-----Output-----

For each test case, print YES if you can choose such size of pack $a$ that each customer buys more cans than they wanted initially. Otherwise, print NO.

You can print each character in any case.

-----Example-----
Input
3
3 4
1 2
120 150

Output
YES
NO
YES

-----Note-----

In the first test case, you can take, for example, $a = 5$ as the size of the pack. Then if a customer wants to buy $3$ cans, he'll buy $5$ instead ($3 \bmod 5 = 3$, $\frac{5}{2} = 2.5$). The one who wants $4$ cans will also buy $5$ cans.

In the second test case, there is no way to choose $a$.

In the third test case, you can take,...

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

for _ in range (int(input())):
    l,r=map(int,input().split())
    if l<=r//2:
        print("NO")
    else:
        print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1437/C:
Chef Monocarp has just put $n$ dishes into an oven. He knows that the $i$-th dish has its optimal cooking time equal to $t_i$ minutes.

At any positive integer minute $T$ Monocarp can put no more than one dish out of the oven. If the $i$-th dish is put out at some minute $T$, then its unpleasant value is $|T - t_i|$ — the absolute difference between $T$ and $t_i$. Once the dish is out of the oven, it can't go back in.

Monocarp should put all the dishes out of the oven. What is the minimum total unpleasant value Monocarp can obtain?

-----Input-----

The first line contains a single integer $q$ ($1 \le q \le 200$) — the number of testcases.

Then $q$ testcases follow.

The first line of the testcase contains a single integer $n$ ($1 \le n \le 200$) — the number of dishes in the oven.

The second line of the testcase contains $n$ integers $t_1, t_2, \dots, t_n$ ($1 \le t_i \le n$) — the optimal cooking time for each dish.

The sum of $n$ over all $q$ testcases doesn't exceed $200$.

-----Output-----

Print a single integer for each testcase — the minimum total unpleasant value Monocarp can obtain when he puts out all the dishes out of the oven. Remember that Monocarp can only put the dishes out at positive integer minutes and no more than one dish at any minute.

-----Example-----
Input
6
6
4 2 4 4 5 2
7
7 7 7 7 7 7 7
1
1
5
5 1 2 4 3
4
1 4 4 4
21
21 8 1 4 1 5 21 1 8 21 11 21 11 3 12 8 19 15 9 11 13

Output
4
12
0
0
2
21

-----Note-----

In the first example Monocarp can put out the dishes at minutes $3, 1, 5, 4, 6, 2$. That way the total unpleasant value will be $|4 - 3| + |2 - 1| + |4 - 5| + |4 - 4| + |6 - 5| + |2 - 2| = 4$.

In the second example Monocarp can put out the dishes at minutes $4, 5, 6, 7, 8, 9, 10$.

In the third example Monocarp can put out the dish at minute $1$.

In the fourth example Monocarp can put out the dishes at minutes $5, 1, 2, 4, 3$.

In the fifth example Monocarp can put out the dishes at minutes $1, 3, 4, 5$.

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

import sys
input=sys.stdin.readline
for _ in range(int(input())):
    n = int(input())
    t = sorted(map(int,input().split()))
    cur = [0]*(2*n)
    for i in range(n):
        low = high = t[i]
        while low and cur[low]:
            low -= 1
        while cur[high]:
            high += 1
        if low > 0 and i:
            lowsum = ind = j = 0
            cur[low] = 1
            while ind <= i:
                if cur[j]:
                    lowsum += abs(t[ind] - j)
                    ind += 1
                j += 1
            cur[low] = 0
            highsum = ind = j = 0
            cur[high] = 1
            while ind <= i:
                if cur[j]:
                    highsum += abs(t[ind] - j)
                    ind += 1
                j += 1
            cur[high] = 0
            if lowsum < highsum:
                cur[low] = 1
            else:
                cur[high] = 1
        else:
            cur[high] = 1
    ans = ind = j = 0
    while ind < n:
        if cur[j]:
            ans += abs(t[ind] - j)
            ind += 1
        j += 1
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1437/E:
You are given an array of $n$ integers $a_1$, $a_2$, ..., $a_n$, and a set $b$ of $k$ distinct integers from $1$ to $n$.

In one operation, you may choose two integers $i$ and $x$ ($1 \le i \le n$, $x$ can be any integer) and assign $a_i := x$. This operation can be done only if $i$ does not belong to the set $b$.

Calculate the minimum number of operations you should perform so the array $a$ is increasing (that is, $a_1 < a_2 < a_3 < \dots < a_n$), or report that it is impossible.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le n \le 5 \cdot 10^5$, $0 \le k \le n$) — the size of the array $a$ and the set $b$, respectively.

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

Then, if $k \ne 0$, the third line follows, containing $k$ integers $b_1$, $b_2$, ..., $b_k$ ($1 \le b_1 < b_2 < \dots < b_k \le n$). If $k = 0$, this line is skipped.

-----Output-----

If it is impossible to make the array $a$ increasing using the given operations, print $-1$.

Otherwise, print one integer — the minimum number of operations you have to perform.

-----Examples-----
Input
7 2
1 2 1 1 3 5 1
3 5

Output
4

Input
3 3
1 3 2
1 2 3

Output
-1

Input
5 0
4 3 1 2 3

Output
2

Input
10 3
1 3 5 6 12 9 8 10 13 15
2 4 9

Output
3

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

import sys
input=sys.stdin.readline
n,k = map(int,input().split())
a = list(map(int,input().split()))
b = []
if k:
    b = list(map(int,input().split()))
for i in range(n):
    a[i] -= i
prev = -1
ans = 0
for j in range(k + 1):
    if j < k:
        val = b[j] - 1
        if j and a[prev] > a[val]:
            print(-1)
            quit()
    else:
        val = n
    if val - prev > 1:
        path = [0] * (val - prev - 1)
        arr = [0] * (val - prev)
        found = 0
        for i in range(val - prev - 1):
            if val < n and a[i + prev + 1] > a[val]:
                continue
            elif prev + 1 and a[prev] > a[i + prev + 1]:
                continue
            l = 1
            h = found
            while h >= l:
                m = (l + h + 1) // 2
                if a[arr[m] + prev + 1] <= a[i + prev + 1]:
                    l = m + 1
                else:
                    h = m - 1
            path[i] = arr[l - 1]
            arr[l] = i
            if l > found:
                found = l
        ans += found
    prev = val
print(n - k - ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1437/F:
$n$ fishermen have just returned from a fishing vacation. The $i$-th fisherman has caught a fish of weight $a_i$.

Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of showing fish is a permutation of integers from $1$ to $n$). Then they show the fish they caught according to the chosen order. When a fisherman shows his fish, he might either become happy, become sad, or stay content.

Suppose a fisherman shows a fish of weight $x$, and the maximum weight of a previously shown fish is $y$ ($y = 0$ if that fisherman is the first to show his fish). Then:

  if $x \ge 2y$, the fisherman becomes happy;  if $2x \le y$, the fisherman becomes sad;  if none of these two conditions is met, the fisherman stays content.

Let's call an order in which the fishermen show their fish emotional if, after all fishermen show their fish according to this order, each fisherman becomes either happy or sad. Calculate the number of emotional orders modulo $998244353$.

-----Input-----

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

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

-----Output-----

Print one integer — the number of emotional orders, taken modulo $998244353$.

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

Output
20

Input
4
4 3 2 1

Output
0

Input
3
4 2 1

Output
6

Input
8
42 1337 13 37 420 666 616 97

Output
19200

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

M = 998244353
n = int(input())
l = sorted(map(int, input().split()))[::-1]
out = [0] * n
big = 0
if l[0] >= 2 * l[1]:
    out[1] = 1
    big = 1
for i in range(2, n):
    new = [0] * n
    bigN = 0
    for j in range(i):
        if l[j] >= 2 * l[i]:
            big += out[j]
        else:
            new[j] += out[j] * (i - 1)
            new[j] %= M

    new[i] = big
    bigN = (i * big) % M

    out = new
    big = bigN
print((big + sum(out))%M)


I found an interesting problem on https://codeforces.com/problemset/problem/1438/B:
You're given an array $b$ of length $n$. Let's define another array $a$, also of length $n$, for which $a_i = 2^{b_i}$ ($1 \leq i \leq n$).

Valerii says that every two non-intersecting subarrays of $a$ have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers $l_1,r_1,l_2,r_2$ that satisfy the following conditions:   $1 \leq l_1 \leq r_1 \lt l_2 \leq r_2 \leq n$;  $a_{l_1}+a_{l_1+1}+\ldots+a_{r_1-1}+a_{r_1} = a_{l_2}+a_{l_2+1}+\ldots+a_{r_2-1}+a_{r_2}$.

If such four integers exist, you will prove Valerii wrong. Do they exist?

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

-----Input-----

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

The first line of every test case contains a single integer $n$ ($2 \le n \le 1000$).

The second line of every test case contains $n$ integers $b_1,b_2,\ldots,b_n$ ($0 \le b_i \le 10^9$).

-----Output-----

For every test case, if there exist two non-intersecting subarrays in $a$ that have the same sum, output YES on a separate line. Otherwise, output NO on a separate line.

Also, note that each letter can be in any case.

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

Output
YES
NO

-----Note-----

In the first case, $a = [16,8,1,2,4,1]$. Choosing $l_1 = 1$, $r_1 = 1$, $l_2 = 2$ and $r_2 = 6$ works because $16 = (8+1+2+4+1)$.

In the second case, you can verify that there is no way to select to such subarrays.

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

t=int(input())
for i in range(t):
    n=int(input())
    b=list(map(int,input().split()))
    if len(set(b))==n:
        print("NO")
    else:
        print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1438/C:
Artem is building a new robot. He has a matrix $a$ consisting of $n$ rows and $m$ columns. The cell located on the $i$-th row from the top and the $j$-th column from the left has a value $a_{i,j}$ written in it.

If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells contain the same value, where two cells are called adjacent if they share a side.

Artem wants to increment the values in some cells by one to make $a$ good.

More formally, find a good matrix $b$ that satisfies the following condition —   For all valid ($i,j$), either $b_{i,j} = a_{i,j}$ or $b_{i,j} = a_{i,j}+1$.

For the constraints of this problem, it can be shown that such a matrix $b$ always exists. If there are several such tables, you can output any of them. Please note that you do not have to minimize the number of increments.

-----Input-----

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

The first line of each test case contains two integers $n, m$ ($1 \le n \le 100$, $1 \le m \le 100$)  — the number of rows and columns, respectively.

The following $n$ lines each contain $m$ integers. The $j$-th integer in the $i$-th line is $a_{i,j}$ ($1 \leq a_{i,j} \leq 10^9$).

-----Output-----

For each case, output $n$ lines each containing $m$ integers. The $j$-th integer in the $i$-th line is $b_{i,j}$.

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

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

-----Note-----

In all the cases, you can verify that no two adjacent cells have the same value and that $b$ is the same as $a$ with some values incremented by one.

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

t = int(input())
for case in range(t):
    n, m = [int(x) for x in input().split(' ')]
    a = [[int(x) for x in input().split(' ')] for i in range(n)]
    for i in range(n):
        for j in range(m):
            if (a[i][j] - (i + j)) % 2 != 0:
                a[i][j] += 1
    for row in a:
        print(*row)


I found an interesting problem on https://codeforces.com/problemset/problem/1438/D:
Ksenia has an array $a$ consisting of $n$ positive integers $a_1, a_2, \ldots, a_n$.

In one operation she can do the following:   choose three distinct indices $i$, $j$, $k$, and then  change all of $a_i, a_j, a_k$ to $a_i \oplus a_j \oplus a_k$ simultaneously, where $\oplus$ denotes the bitwise XOR operation.

She wants to make all $a_i$ equal in at most $n$ operations, or to determine that it is impossible to do so. She wouldn't ask for your help, but please, help her!

-----Input-----

The first line contains one integer $n$ ($3 \leq n \leq 10^5$) — the length of $a$.

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

-----Output-----

Print YES or NO in the first line depending on whether it is possible to make all elements equal in at most $n$ operations.

If it is possible, print an integer $m$ ($0 \leq m \leq n$), which denotes the number of operations you do.

In each of the next $m$ lines, print three distinct integers $i, j, k$, representing one operation.

If there are many such operation sequences possible, print any. Note that you do not have to minimize the number of operations.

-----Examples-----
Input
5
4 2 1 7 2

Output
YES
1
1 3 4
Input
4
10 4 49 22

Output
NO

-----Note-----

In the first example, the array becomes $[4 \oplus 1 \oplus 7, 2, 4 \oplus 1 \oplus 7, 4 \oplus 1 \oplus 7, 2] = [2, 2, 2, 2, 2]$.

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

def solve(n, arr):
    xor_sum = arr[0]
    for i in range(1, n):
        xor_sum ^= arr[i]
    if n % 2 == 0:
        if xor_sum:
            print("NO")
            return
        else:
            n -= 1
    if n == 3:
        print(1)
        print(1, 2, 3)
        return

    print("YES")
    print(n-2)
    for i in range(1, n-1, 2):
        print(i, i+1, i+2)
    for i in range(n-4, 0, -2):
        print(i, i+1, i+2)

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


I found an interesting problem on https://codeforces.com/problemset/problem/1438/E:
Yurii is sure he can do everything. Can he solve this task, though?

He has an array $a$ consisting of $n$ positive integers. Let's call a subarray $a[l...r]$ good if the following conditions are simultaneously satisfied:   $l+1 \leq r-1$, i. e. the subarray has length at least $3$;  $(a_l \oplus a_r) = (a_{l+1}+a_{l+2}+\ldots+a_{r-2}+a_{r-1})$, where $\oplus$ denotes the bitwise XOR operation.

In other words, a subarray is good if the bitwise XOR of the two border elements is equal to the sum of the rest of the elements.

Yurii wants to calculate the total number of good subarrays. What is it equal to?

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

-----Input-----

The first line contains a single integer $n$ ($3 \leq n \leq 2\cdot 10^5$) — the length of $a$.

The second line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($1 \leq a_i \lt 2^{30}$) — elements of $a$.

-----Output-----

Output a single integer — the number of good subarrays.

-----Examples-----
Input
8
3 1 2 3 1 2 3 15

Output
6
Input
10
997230370 58052053 240970544 715275815 250707702 156801523 44100666 64791577 43523002 480196854

Output
2

-----Note-----

There are $6$ good subarrays in the example:   $[3,1,2]$ (twice) because $(3 \oplus 2) = 1$;  $[1,2,3]$ (twice) because $(1 \oplus 3) = 2$;  $[2,3,1]$ because $(2 \oplus 1) = 3$;  $[3,1,2,3,1,2,3,15]$ because $(3 \oplus 15) = (1+2+3+1+2+3)$.

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

import itertools, math
n = int(input())
A = list(map(int, input().split()))
acc = [0] + list(itertools.accumulate(A))
ans = 0
seen = set()
for i in range(n - 2):
    a = int(math.log2(A[i]))
    for j in range(i + 2, n):
        cur = acc[j] - acc[i + 1]
        b = int(math.log2(cur))
        if b > a:
            break
        if A[i] ^ A[j] == cur and (i, j) not in seen:
            ans += 1
            seen.add((i, j))
for j in range(n - 1, 1, -1):
    a = int(math.log2(A[j]))
    for i in range(j - 2, -1, -1):
        cur = acc[j] - acc[i + 1]
        b = int(math.log2(cur))
        if b > a:
            break
        if A[i] ^ A[j] == cur and (i, j) not in seen:
            ans += 1
            seen.add((i, j))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1443/E:
A permutation is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$, $[3, 2, 1]$ — are permutations, and $[1, 1]$, $[4, 3, 1]$, $[2, 3, 4]$ — no.

Permutation $a$ is lexicographically smaller than permutation $b$ (they have the same length $n$), if in the first index $i$ in which they differ, $a[i] < b[i]$. For example, the permutation $[1, 3, 2, 4]$ is lexicographically smaller than the permutation $[1, 3, 4, 2]$, because the first two elements are equal, and the third element in the first permutation is smaller than in the second.

The next permutation for a permutation $a$ of length $n$ — is the lexicographically smallest permutation $b$ of length $n$ that lexicographically larger than $a$. For example:   for permutation $[2, 1, 4, 3]$ the next permutation is $[2, 3, 1, 4]$;  for permutation $[1, 2, 3]$ the next permutation is $[1, 3, 2]$;  for permutation $[2, 1]$ next permutation does not exist.

You are given the number $n$ — the length of the initial permutation. The initial permutation has the form $a = [1, 2, \ldots, n]$. In other words, $a[i] = i$ ($1 \le i \le n$).

You need to process $q$ queries of two types:   $1$ $l$ $r$: query for the sum of all elements on the segment $[l, r]$. More formally, you need to find $a[l] + a[l + 1] + \ldots + a[r]$.  $2$ $x$: $x$ times replace the current permutation with the next permutation. For example, if $x=2$ and the current permutation has the form $[1, 3, 4, 2]$, then we should perform such a chain of replacements $[1, 3, 4, 2] \rightarrow [1, 4, 2, 3] \rightarrow [1, 4, 3, 2]$.

For each query of the $1$-st type output the required sum.

-----Input-----

The first line contains two integers $n$ ($2 \le n \le 2 \cdot 10^5$) and $q$ ($1 \le q \le 2 \cdot 10^5$), where $n$ — the length of the initial permutation, and $q$ — the number of queries.

The next $q$ lines contain a single query of the $1$-st or $2$-nd type. The $1$-st type query consists of three integers $1$, $l$ and...

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

import sys
input = sys.stdin.readline

n,q=list(map(int,input().split()))
X=list(range(1,n+1))

S=[0]
for x in X:
    S.append(S[-1]+x)

FACT=[1,1]
for i in range(2,16):
    FACT.append(FACT[-1]*i)

A=X[-15:]
LEN=len(A)
def calc(x):
    AA=[a for a in A]
    ANS=[]

    for i in range(LEN,0,-1):
        q=x//FACT[i-1]
        x-=q*FACT[i-1]

        ANS.append(AA.pop(q))

        #print(q,x,AA,ANS)

    return ANS

NOW=0
for queries in range(q):
    Q=list(map(int,input().split()))

    if Q[0]==2:
        NOW+=Q[1]
        continue

    l,r=Q[1],Q[2]

    if r<=n-LEN:
        print(S[r]-S[l-1])
        continue

    elif l<=n-LEN:
        ANS=S[-LEN-1]-S[l-1]
        l=0
        r-=n-LEN+1
    else:
        ANS=0
        l-=n-LEN+1
        r-=n-LEN+1

    NOWA=calc(NOW)

    print(ANS+sum(NOWA[l:r+1]))


I found an interesting problem on https://codeforces.com/problemset/problem/1445/A:
You are given two arrays $a$ and $b$, each consisting of $n$ positive integers, and an integer $x$. Please determine if one can rearrange the elements of $b$ so that $a_i + b_i \leq x$ holds for each $i$ ($1 \le i \le n$).

-----Input-----

The first line of input contains one integer $t$ ($1 \leq t \leq 100$) — the number of test cases. $t$ blocks follow, each describing an individual test case.

The first line of each test case contains two integers $n$ and $x$ ($1 \leq n \leq 50$; $1 \leq x \leq 1000$) — the length of arrays $a$ and $b$, and the parameter $x$, described in the problem statement.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$) — the elements of array $a$ in non-descending order.

The third line of each test case contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$) — the elements of array $b$ in non-descending order.

Test cases are separated by a blank line.

-----Output-----

For each test case print Yes if one can rearrange the corresponding array $b$ so that $a_i + b_i \leq x$ holds for each $i$ ($1 \le i \le n$) or No otherwise.

Each character can be printed in any case.

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

2 6
1 4
2 5

4 4
1 2 3 4
1 2 3 4

1 5
5
5

Output
Yes
Yes
No
No

-----Note-----

In the first test case, one can rearrange $b$ so it'll look like $[1, 2, 1]$. In this case, $1 + 1 \leq 4$; $2 + 2 \leq 4$; $3 + 1 \leq 4$.

In the second test case, one can set $b$ to $[5, 2]$, then $1 + 5 \leq 6$; $4 + 2 \leq 6$.

In the third test case, no matter how one shuffles array $b$, $a_4 + b_4 = 4 + b_4 > 4$.

In the fourth test case, there is only one rearrangement of array $b$ and it doesn't satisfy the condition since $5 + 5 > 5$.

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

def testcase():

    n, x = list(map(int, input().split()))
    arr = list(map(int, input().split()))
    brr = list(map(int, input().split()))
    arr.sort()
    brr.sort(reverse=True)
    for i in range(n):
        if arr[i] + brr[i] > x:
            print('No')
            return
    print('Yes')
    return

import sys, os
if os.path.exists('input.txt'):
    sys.stdin = open('input.txt', 'r')
sys.setrecursionlimit(10 ** 5)
t = int(input())
for _ in range(t - 1):
    testcase()
    input()
testcase()


I found an interesting problem on https://codeforces.com/problemset/problem/1445/B:
There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.

A result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately.

In each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct).

In the first contest, the participant on the 100-th place scored $a$ points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least $b$ points in the second contest.

Similarly, for the second contest, the participant on the 100-th place has $c$ points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least $d$ points in the first contest.

After two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The cutoff score to qualify to the final stage is the total score of the participant on the 100-th place.

Given integers $a$, $b$, $c$, $d$, please help the jury determine the smallest possible value of the cutoff score.

-----Input-----

You need to process $t$ test cases.

The first line contains an integer $t$ ($1 \leq t \leq 3025$) — the number of test cases. Then descriptions of $t$ test cases follow.

The first line of each test case contains four integers $a$, $b$, $c$, $d$ ($0 \le a,\,b,\,c,\,d \le 9$; $d \leq a$; $b \leq c$).

One can show that for any test case satisfying the constraints...

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

for i in range(int(input())):
    a,b,c,d = map(int,input().split())
    print(max(a+b,c+d))


I found an interesting problem on https://codeforces.com/problemset/problem/233/A:
A permutation is a sequence of integers p_1, p_2, ..., p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as p_{i}. We'll call number n the size of permutation p_1, p_2, ..., p_{n}.

Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 ≤ i ≤ n) (n is the permutation size) the following equations hold p_{p}_{i} = i and p_{i} ≠ i. Nickolas asks you to print any perfect permutation of size n for the given n.

-----Input-----

A single line contains a single integer n (1 ≤ n ≤ 100) — the permutation size.

-----Output-----

If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p_1, p_2, ..., p_{n} — permutation p, that is perfect. Separate printed numbers by whitespaces.

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

Output
-1

Input
2

Output
2 1

Input
4

Output
2 1 4 3

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

#import sys
#my_file = sys.stdin
#my_file = open("input.txt", "r")
num = int(input())
a = list(range(1,num+1))
if num%2!=0:
    print('-1')
else:
    for i in range(num)[::2]:
        a[i],a[i+1] = a[i+1], a[i]
    print(' '.join(map(str, a)))


I found an interesting problem on https://codeforces.com/problemset/problem/233/B:
Let's consider equation:x^2 + s(x)·x - n = 0,

where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.

You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots.

-----Input-----

A single line contains integer n (1 ≤ n ≤ 10^18) — the equation parameter.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

-----Output-----

Print -1, if the equation doesn't have integer positive roots. Otherwise print such smallest integer x (x > 0), that the equation given in the statement holds.

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

Output
1

Input
110

Output
10

Input
4

Output
-1

-----Note-----

In the first test case x = 1 is the minimum root. As s(1) = 1 and 1^2 + 1·1 - 2 = 0.

In the second test case x = 10 is the minimum root. As s(10) = 1 + 0 = 1 and 10^2 + 1·10 - 110 = 0.

In the third test case the equation has no roots.

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

from math import *

def s(x):
    S = 0
    while x!=0:
        S += x%10
        x//=10
    return(S)

def Solve(n):
    sqrt = n**0.5//1
    x = int((10**(log(sqrt,10)//1)))-1

    if((sqrt - x)*log(sqrt,10) >= 10**4):
        x = int(sqrt-10**4)

    while(x <= sqrt):
        if x**2+int(s(x))*x == n:
            return(x)
        x+=1
    return(-1)

def solve(n):
    if(n >= 1024974):
        return(Solve(n))
    if(n == 0):
        return(0)
    sqrt = n**0.5//1
    x = int((10**(log(sqrt,10)//1-1)))
    while(x <= sqrt):
        if x**2+int(s(x))*x == n:
            return(x)
        x+=1
    return(-1)

n = int(input())
print(int(solve(n)))


I found an interesting problem on https://codeforces.com/problemset/problem/234/A:
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the $\frac{n}{2}$ desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.

But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.

On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.

Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.

-----Input-----

The first input line contains a single even integer n (4 ≤ n ≤ 100) — the number of students in the class. The second line contains exactly n capital English letters "L" and "R". If the i-th letter at the second line equals "L", then the student number i is a lefthander, otherwise he is a righthander.

-----Output-----

Print $\frac{n}{2}$ integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.

-----Examples-----
Input
6
LLRLLL

Output
1 4
2 5
6 3

Input
4
RRLL

Output
3 1
4 2

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

# python 3
"""
"""

def lefthanders_and_righthanders(n_int, student_list) -> list:
    sitting_order = []
    for i in range(n_int//2):
        if student_list[i] == 'R' and student_list[i + n_int//2] == 'L':
            sitting_order.append((i + n_int//2 + 1, i + 1))
            print(i + n_int//2 + 1, i + 1)
        else:
            sitting_order.append((i + 1, i + n_int//2 + 1))
            print(i + 1, i + n_int//2 + 1)
    return sitting_order

def __starting_point():
    """
    Inside of this is the test.
    Outside is the API
    """
    with open("input.txt", 'r') as f_input:
        n = int(f_input.readline())
        students = f_input.readline()
        # print(n, students)

    sitting = lefthanders_and_righthanders(n, students)
    with open("output.txt", 'w') as f_output:
        for each in sitting:
            f_output.write(str(each[0]) + ' ' + str(each[1]) + '\n')

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/234/B:
Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed k hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light.

Vasya has a train lighting schedule for all n hours of the trip — n numbers from 0 to 100 each (the light level in the first hour, the second hour and so on). During each of those hours he will either read the whole time, or not read at all. He wants to choose k hours to read a book, not necessarily consecutive, so that the minimum level of light among the selected hours were maximum. Vasya is very excited before the upcoming contest, help him choose reading hours.

-----Input-----

The first input line contains two integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ n) — the number of hours on the train and the number of hours to read, correspondingly. The second line contains n space-separated integers a_{i} (0 ≤ a_{i} ≤ 100), a_{i} is the light level at the i-th hour.

-----Output-----

In the first output line print the minimum light level Vasya will read at. In the second line print k distinct space-separated integers b_1, b_2, ..., b_{k}, — the indexes of hours Vasya will read at (1 ≤ b_{i} ≤ n). The hours are indexed starting from 1. If there are multiple optimal solutions, print any of them. Print the numbers b_{i} in an arbitrary order.

-----Examples-----
Input
5 3
20 10 30 40 10

Output
20
1 3 4

Input
6 5
90 20 35 40 60 100

Output
35
1 3 4 5 6

-----Note-----

In the first sample Vasya should read at the first hour (light 20), third hour (light 30) and at the fourth hour (light 40). The minimum light Vasya will have to read at is 20.

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

'''
Created on May 4, 2016
@author: Md. Rezwanul Haque
'''
import sys
from audioop import reverse
sys.stdin = open("input.txt","r");
sys.stdout = open("output.txt","w");

n,k = map(int,input().split())
p = [(x,i)for i,x in enumerate (list(map(int,input().split())),1)]
#print(p)
p.sort(reverse = True)
#print(p)
print(p[k-1][0])
print(" ".join(str(x[1])for x in p[:k]))