I found an interesting problem on https://codeforces.com/problemset/problem/1254/B2:
This is the harder version of the problem. In this version, $1 \le n \le 10^6$ and $0 \leq a_i \leq 10^6$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems

Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $n$ boxes of chocolate, numbered from $1$ to $n$. Initially, the $i$-th box contains $a_i$ chocolate pieces.

Since Bob is a typical nice guy, he will not send Alice $n$ empty boxes. In other words, at least one of $a_1, a_2, \ldots, a_n$ is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $k > 1$ such that the number of pieces in each box is divisible by $k$. Note that Alice won't mind if there exists some empty boxes.

Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $i$ and put it into either box $i-1$ or box $i+1$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^6$) — the number of chocolate boxes.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^6$) — the number of chocolate pieces in the $i$-th box.

It is guaranteed that at least one of $a_1, a_2, \ldots, a_n$ is positive.

-----Output-----

If there is no way for Charlie to make Alice happy, print $-1$.

Otherwise, print a single integer $x$ — the minimum number of seconds for Charlie to help Bob make Alice happy.

-----Examples-----
Input
3
4 8 5

Output
9

Input
5
3 10 2 1 5

Output
2

Input
4
0 5 15 10

Output
0

Input
1
1

Output
-1

-----Note-----

In the first example, Charlie can move all chocolate pieces to the second box. Each box will be divisible by...

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

def simple_div(x):
    if not x & 1:
        yield 2
        while not x & 1:
            x >>= 1
    i = 3
    while i * i <= x:
        if x % i == 0:
            yield i
            while x % i == 0:
                x //= i
        i += 2
    if x != 1:
        yield x

def __main__():
    n = int(input())
    a = list(map(int, input().split()))
    sa = sum(a)
    a.pop()
    if sa == 1:
        print(-1)
        return
    res = 1 << 64
    for d in simple_div(sa):
        tmp = 0
        m = 0
        half = d >> 1
        for x in a:
            m = (x + m) % d
            tmp += m if m <= half else d - m
            if res <= tmp:
                break
        else:
            res = tmp
    print(res)

__main__()


I found an interesting problem on https://codeforces.com/problemset/problem/1255/B:
Hanh lives in a shared apartment. There are $n$ people (including Hanh) living there, each has a private fridge.

$n$ fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of $n$ people can open it.

 [Image] For exampe, in the picture there are $n=4$ people and $5$ chains. The first person knows passcodes of two chains: $1-4$ and $1-2$. The fridge $1$ can be open by its owner (the person $1$), also two people $2$ and $4$ (acting together) can open it.

The weights of these fridges are $a_1, a_2, \ldots, a_n$. To make a steel chain connecting fridges $u$ and $v$, you have to pay $a_u + a_v$ dollars. Note that the landlord allows you to create multiple chains connecting the same pair of fridges.

Hanh's apartment landlord asks you to create exactly $m$ steel chains so that all fridges are private. A fridge is private if and only if, among $n$ people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge $i$ is not private if there exists the person $j$ ($i \ne j$) that the person $j$ can open the fridge $i$.

For example, in the picture all the fridges are private. On the other hand, if there are $n=2$ fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person).

Of course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly $m$ chains, and if yes, output any solution that minimizes the total cost.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $T$ ($1 \le T \le 10$). Then the descriptions of the test cases...

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

for _ in range(int(input())):
    fr,ch=list(map(int,input().split()))
    arr=list(map(int,input().split()))
    if(ch<fr):
        print(-1)
    elif(fr==2):
        print(-1)
    else:
        x=[[arr[i],i+1] for i in range(fr)]
        x.sort()
        print(sum(arr)*2+(ch-fr)*(x[0][0]+x[1][0]))

        for i in range(fr):
            if(i==fr-1):
                print(1,fr)
            else:
                print(i+1,i+2)
        for i in range(fr,ch):
            print(x[0][1],x[1][1])


I found an interesting problem on https://codeforces.com/problemset/problem/1255/C:
Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end!

The tournament consisted of $n$ ($n \ge 5$) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from $1$-st to $n$-th. After the final, he compared the prediction with the actual result and found out that the $i$-th team according to his prediction ended up at the $p_i$-th position ($1 \le p_i \le n$, all $p_i$ are unique). In other words, $p$ is a permutation of $1, 2, \dots, n$.

As Bob's favorite League player is the famous "3ga", he decided to write down every $3$ consecutive elements of the permutation $p$. Formally, Bob created an array $q$ of $n-2$ triples, where $q_i = (p_i, p_{i+1}, p_{i+2})$ for each $1 \le i \le n-2$. Bob was very proud of his array, so he showed it to his friend Alice.

After learning of Bob's array, Alice declared that she could retrieve the permutation $p$ even if Bob rearranges the elements of $q$ and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond.

For example, if $n = 5$ and $p = [1, 4, 2, 3, 5]$, then the original array $q$ will be $[(1, 4, 2), (4, 2, 3), (2, 3, 5)]$. Bob can then rearrange the numbers within each triple and the positions of the triples to get $[(4, 3, 2), (2, 3, 5), (4, 1, 2)]$. Note that $[(1, 4, 2), (4, 2, 2), (3, 3, 5)]$ is not a valid rearrangement of $q$, as Bob is not allowed to swap numbers belong to different triples.

As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation $p$ that is consistent with the array $q$ she was given.

-----Input-----

The first line contains a single integer $n$ ($5 \le n \le 10^5$) — the size of permutation $p$.

The $i$-th of the next $n-2$ lines contains $3$ integers $q_{i, 1}$, $q_{i, 2}$, $q_{i, 3}$ ($1 \le q_{i, j} \le n$) — the elements of...

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

from collections import defaultdict as dd
n=int(input())
l=[]
d=dd(list)
d2=dd(list)
for _ in range(n-2):
    a,b,c=list(map(int,input().split()))
    l+=[[a,b,c]]

for i in range(n-2):
    d[l[i][0]]+=[i]
    d[l[i][1]]+=[i]
    d[l[i][2]]+=[i]
for i in range(n-2):
    d2[(l[i][0],l[i][1])]+=[l[i][2]]
    d2[(l[i][1],l[i][2])]+=[l[i][0]]
    d2[(l[i][2],l[i][1])]+=[l[i][0]]
    d2[(l[i][1],l[i][0])]+=[l[i][2]]
    d2[(l[i][0],l[i][2])]+=[l[i][1]]
    d2[(l[i][2],l[i][0])]+=[l[i][1]]
for i in d:
    if(len(d[i])==1):
        k=i
        break
ans=[k]
bef=k
#print(d,k)
for i in d:
    if (len(d[i])==2):
        for j in d[i]:
            if j==d[k][0]:

                p=i
                break

ans+=[p]
ind=d[k][0]
#print(ans)
'''
for i in d[tuple(ans)]:
    if i not in ans:
        ans+=[i]
        nex+=[i]
        break
'''
nex=[ans[0],ans[1]]
#print(ans)
bef=99999999999999
for i in range(n-2):
    for j in d2[tuple(nex)]:
        if j !=bef:
            ans+=[j]
    bef=nex.pop(0)
    nex+=[ans[-1]]
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1256/A:
You have $a$ coins of value $n$ and $b$ coins of value $1$. You always pay in exact change, so you want to know if there exist such $x$ and $y$ that if you take $x$ ($0 \le x \le a$) coins of value $n$ and $y$ ($0 \le y \le b$) coins of value $1$, then the total value of taken coins will be $S$.

You have to answer $q$ independent test cases.

-----Input-----

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

The only line of the test case contains four integers $a$, $b$, $n$ and $S$ ($1 \le a, b, n, S \le 10^9$) — the number of coins of value $n$, the number of coins of value $1$, the value $n$ and the required total value.

-----Output-----

For the $i$-th test case print the answer on it — YES (without quotes) if there exist such $x$ and $y$ that if you take $x$ coins of value $n$ and $y$ coins of value $1$, then the total value of taken coins will be $S$, and NO otherwise.

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

-----Example-----
Input
4
1 2 3 4
1 2 3 6
5 2 6 27
3 3 5 18

Output
YES
NO
NO
YES

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

t=int(input())
for tt  in range(t):
	a,b,n,s=map(int,input().split())
	temp=s//n
	aa=min(temp,a)
	s-=(n*aa)
	if b>=s:
		print("YES")
	else:
		print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1256/B:
You are given a permutation of length $n$. Recall that the permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2, 3, 1, 5, 4]$ is a permutation, but $[1, 2, 2]$ is not a permutation ($2$ appears twice in the array) and $[1, 3, 4]$ is also not a permutation ($n=3$ but there is $4$ in the array).

You can perform at most $n-1$ operations with the given permutation (it is possible that you don't perform any operations at all). The $i$-th operation allows you to swap elements of the given permutation on positions $i$ and $i+1$. Each operation can be performed at most once. The operations can be performed in arbitrary order.

Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.

You can see the definition of the lexicographical order in the notes section.

You have to answer $q$ independent test cases.

For example, let's consider the permutation $[5, 4, 1, 3, 2]$. The minimum possible permutation we can obtain is $[1, 5, 2, 4, 3]$ and we can do it in the following way:

  perform the second operation (swap the second and the third elements) and obtain the permutation $[5, 1, 4, 3, 2]$;  perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation $[5, 1, 4, 2, 3]$;  perform the third operation (swap the third and the fourth elements) and obtain the permutation $[5, 1, 2, 4, 3]$.  perform the first operation (swap the first and the second elements) and obtain the permutation $[1, 5, 2, 4, 3]$;

Another example is $[1, 2, 4, 3]$. The minimum possible permutation we can obtain is $[1, 2, 3, 4]$ by performing the third operation (swap the third and the fourth elements).

-----Input-----

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

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

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

t = int(input())
answer = []

def mini(arr):
    minimum = arr[0]
    index = 0
    for i in range (1, len(arr)):
        if minimum > arr[i]:
            minimum = arr[i]
            index = i
    return index

for i in range (t):
    n = int(input())
    p = list(map(int,input().split()))
    ans = []

    while len(p) > 1:
        index = mini(p)
        ans.append(p[index])
        for k in range (index - 1):
            ans.append(p[k])
        p = p[index-1 : index] + p[index + 1:]
    if len(p) == 1:
        ans.append(p[0])
    answer.append(ans)
for i in range (t):
    print (*answer[i], sep = " ")


I found an interesting problem on https://codeforces.com/problemset/problem/1256/C:
There is a river of width $n$. The left bank of the river is cell $0$ and the right bank is cell $n + 1$ (more formally, the river can be represented as a sequence of $n + 2$ cells numbered from $0$ to $n + 1$). There are also $m$ wooden platforms on a river, the $i$-th platform has length $c_i$ (so the $i$-th platform takes $c_i$ consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed $n$.

You are standing at $0$ and want to reach $n+1$ somehow. If you are standing at the position $x$, you can jump to any position in the range $[x + 1; x + d]$. However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if $d=1$, you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells $0$ and $n+1$ belong to wooden platforms.

You want to know if it is possible to reach $n+1$ from $0$ if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.

Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping).

For example, if $n=7$, $m=3$, $d=2$ and $c = [1, 2, 1]$, then one of the ways to reach $8$ from $0$ is follow:

 [Image] The first example: $n=7$.

-----Input-----

The first line of the input contains three integers $n$, $m$ and $d$ ($1 \le n, m, d \le 1000, m \le n$) — the width of the river, the number of platforms and the maximum distance of your jump, correspondingly.

The second line of the input contains $m$ integers $c_1, c_2, \dots, c_m$ ($1 \le c_i \le n, \sum\limits_{i=1}^{m} c_i \le n$), where $c_i$ is the length of the $i$-th platform.

-----Output-----

If it is impossible to reach $n+1$ from $0$, print NO in the first line. Otherwise, print YES in the first line and the array $a$ of...

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

n, m, d = list(map(int, input().split()))
c = list(map(int, input().split()))
r = sum(c)
cur = 0
ci = 0
mmap = [0] * n
while cur < n+1 and ci < len(c):
    #print("pi =min ", cur + d," ",  n - r + 1)

    pi = min(cur + d, n - r + 1)
    #print("pi = ", pi)
    for j in range(pi, pi+c[ci]):
        mmap[j-1] = ci+1
    cur = pi + c[ci]-1
    r -= c[ci]
    ci += 1

if cur + d >= n+1:
    print("YES")
    print(" ".join(map(str, mmap)))
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1256/D:
You are given a binary string of length $n$ (i. e. a string consisting of $n$ characters '0' and '1').

In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than $k$ moves? It is possible that you do not perform any moves at all.

Note that you can swap the same pair of adjacent characters with indices $i$ and $i+1$ arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.

You have to answer $q$ independent test cases.

-----Input-----

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

The first line of the test case contains two integers $n$ and $k$ ($1 \le n \le 10^6, 1 \le k \le n^2$) — the length of the string and the number of moves you can perform.

The second line of the test case contains one string consisting of $n$ characters '0' and '1'.

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

-----Output-----

For each test case, print the answer on it: the lexicographically minimum possible string of length $n$ you can obtain from the given one if you can perform no more than $k$ moves.

-----Example-----
Input
3
8 5
11011010
7 9
1111100
7 11
1111100

Output
01011110
0101111
0011111

-----Note-----

In the first example, you can change the string as follows: $1\underline{10}11010 \rightarrow \underline{10}111010 \rightarrow 0111\underline{10}10 \rightarrow 011\underline{10}110 \rightarrow 01\underline{10}1110 \rightarrow 01011110$.

In the third example, there are enough operations to make the string sorted.

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

def __starting_point():

    q = int(input())

    for t in range(q):
        n, k = [int(i) for i in input().split(" ")]
        s = list(input())

        zero = []
        for i in range(len(s)):
            if s[i] == '0':
                zero.append(i)

        var = 0
        index = 0

        while k > 0 and var < len(zero) and index < len(s):
            temp = zero[var]
            if k < zero[var]-index:
                s[zero[var]-k], s[zero[var]] = s[zero[var]], s[zero[var]-k]
                k = 0
            else:
                s[index], s[zero[var]] = s[zero[var]], s[index]
                k -= zero[var]-index
            var += 1
            index += 1

        print("".join(s))

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1256/E:
There are $n$ students at your university. The programming skill of the $i$-th student is $a_i$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $2 \cdot 10^5$ students ready for the finals!

Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $k$ students with programming skills $a[i_1], a[i_2], \dots, a[i_k]$, then the diversity of this team is $\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$).

The total diversity is the sum of diversities of all teams formed.

Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students.

-----Input-----

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

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

-----Output-----

In the first line print two integers $res$ and $k$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly.

In the second line print $n$ integers $t_1, t_2, \dots, t_n$ ($1 \le t_i \le k$), where $t_i$ is the number of team to which the $i$-th student belong.

If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students.

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

Output
3 1
1 1 1 1 1

Input
6
1 5 12 13 2 15

Output
7 2
2 2 1 1 2 1

Input
10
1 2 5 129 185 581 1041 1909 1580 8150

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

-----Note-----

In the first example, there is only one team with...

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

import sys
input = sys.stdin.readline

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

B=[(a,ind) for ind,a in enumerate(A)]
B.sort()

DP=[0]*(n+1)

for i in range(3,n-2):
    DP[i]=max(DP[i-1],DP[i-3]+B[i][0]-B[i-1][0])

#print(DP)

MAX=max(DP)

x=DP.index(MAX)

REMLIST=[]

while x>0:
    if DP[x]==DP[x-1]:
        x-=1
    else:
        REMLIST.append(x)
        x-=3

REMLIST.sort()
REMLIST.append(1<<60)

print(max(A)-min(A)-MAX,len(REMLIST))

ANS=[-1]*n
remind=0
NOW=1

for i in range(n):
    if i==REMLIST[remind]:
        NOW+=1
        remind+=1
    ANS[B[i][1]]=NOW
print(*ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1257/A:
You are the gym teacher in the school.

There are $n$ students in the row. And there are two rivalling students among them. The first one is in position $a$, the second in position $b$. Positions are numbered from $1$ to $n$ from left to right.

Since they are rivals, you want to maximize the distance between them. If students are in positions $p$ and $s$ respectively, then distance between them is $|p - s|$.

You can do the following operation at most $x$ times: choose two adjacent (neighbouring) students and swap them.

Calculate the maximum distance between two rivalling students after at most $x$ swaps.

-----Input-----

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

The only line of each test case contains four integers $n$, $x$, $a$ and $b$ ($2 \le n \le 100$, $0 \le x \le 100$, $1 \le a, b \le n$, $a \neq b$) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

-----Output-----

For each test case print one integer — the maximum distance between two rivaling students which you can obtain.

-----Example-----
Input
3
5 1 3 2
100 33 100 1
6 0 2 3

Output
2
99
1

-----Note-----

In the first test case you can swap students in positions $3$ and $4$. And then the distance between the rivals is equal to $|4 - 2| = 2$.

In the second test case you don't have to swap students.

In the third test case you can't swap students.

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

for _ in range(int(input())):
    n,x,a,b = [int(i) for i in input().split(' ')]
    a,b = min(a,b),max(a,b)
    while x:
        if a>1:
            a-=1
        elif b<n:
            b+=1
        x-=1
    print(b-a)


I found an interesting problem on https://codeforces.com/problemset/problem/1257/B:
Recently Petya walked in the forest and found a magic stick.

Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:   If the chosen number $a$ is even, then the spell will turn it into $\frac{3a}{2}$;  If the chosen number $a$ is greater than one, then the spell will turn it into $a-1$.

Note that if the number is even and greater than one, then Petya can choose which spell to apply.

Petya now has only one number $x$. He wants to know if his favorite number $y$ can be obtained from $x$ using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave $x$ as it is.

-----Input-----

The first line contains single integer $T$ ($1 \le T \le 10^4$) — the number of test cases. Each test case consists of two lines.

The first line of each test case contains two integers $x$ and $y$ ($1 \le x, y \le 10^9$) — the current number and the number that Petya wants to get.

-----Output-----

For the $i$-th test case print the answer on it — YES if Petya can get the number $y$ from the number $x$ using known spells, and NO otherwise.

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

-----Example-----
Input
7
2 3
1 1
3 6
6 8
1 2
4 1
31235 6578234

Output
YES
YES
NO
YES
NO
YES
YES

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

n = int(input())
for i in range(n):
	a, b = list(map(int, input().split()))
	if a == 2:
		a = 3
	if a >= 4:
		print ("YES")
	else:
		if a >= b:
			print ("YES")
		else:
			print ("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1257/C:
Let's call an array $t$ dominated by value $v$ in the next situation.

At first, array $t$ should have at least $2$ elements. Now, let's calculate number of occurrences of each number $num$ in $t$ and define it as $occ(num)$. Then $t$ is dominated (by $v$) if (and only if) $occ(v) > occ(v')$ for any other number $v'$. For example, arrays $[1, 2, 3, 4, 5, 2]$, $[11, 11]$ and $[3, 2, 3, 2, 3]$ are dominated (by $2$, $11$ and $3$ respectevitely) but arrays $[3]$, $[1, 2]$ and $[3, 3, 2, 2, 1]$ are not.

Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.

You are given array $a_1, a_2, \dots, a_n$. Calculate its shortest dominated subarray or say that there are no such subarrays.

The subarray of $a$ is a contiguous part of the array $a$, i. e. the array $a_i, a_{i + 1}, \dots, a_j$ for some $1 \le i \le j \le n$.

-----Input-----

The first line contains single integer $T$ ($1 \le T \le 1000$) — the number of test cases. Each test case consists of two lines.

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

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

It's guaranteed that the total length of all arrays in one test doesn't exceed $2 \cdot 10^5$.

-----Output-----

Print $T$ integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or $-1$ if there are no such subarrays.

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

Output
-1
6
3
2

-----Note-----

In the first test case, there are no subarrays of length at least $2$, so the answer is $-1$.

In the second test case, the whole array is dominated (by $1$) and it's the only dominated subarray.

In the third test case, the subarray $a_4, a_5, a_6$ is the shortest dominated subarray.

In the fourth test case, all subarrays of length more...

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

for _ in range(int(input())):
    lasts = {}
    ans = n = int(input())
    for i, a in enumerate(input().split()):
        if a in lasts:
            ans = min(ans, i - lasts[a])
        lasts[a] = i
    ans += 1
    if ans > n:
        ans = -1
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1257/E:
A team of three programmers is going to play a contest. The contest consists of $n$ problems, numbered from $1$ to $n$. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order.

The first contestant has received problems $a_{1, 1}, a_{1, 2}, \dots, a_{1, k_1}$. The second one has received problems $a_{2, 1}, a_{2, 2}, \dots, a_{2, k_2}$. The third one has received all remaining problems ($a_{3, 1}, a_{3, 2}, \dots, a_{3, k_3}$).

The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems.

During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems?

It is possible that after redistribution some participant (or even two of them) will not have any problems.

-----Input-----

The first line contains three integers $k_1, k_2$ and $k_3$ ($1 \le k_1, k_2, k_3 \le 2 \cdot 10^5, k_1 + k_2 + k_3 \le 2 \cdot 10^5$) — the number of problems initially taken by the first, the second and the third participant, respectively.

The second line contains $k_1$ integers $a_{1, 1}, a_{1, 2}, \dots, a_{1, k_1}$ — the problems initially taken by the first participant.

The third line contains $k_2$ integers $a_{2, 1}, a_{2, 2}, \dots, a_{2, k_2}$ — the problems initially taken by the second participant.

The fourth line contains...

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

def LIS(X):
    N = len(X)
    P = [0] * N
    M = [0] * (N+1)
    L = 0
    for i in range(N):
        lo = 1
        hi = L
        while lo <= hi:
            mid = (lo+hi)//2
            if (X[M[mid]] < X[i]):
                lo = mid+1
            else:
                hi = mid-1

        newL = lo
        P[i] = M[newL-1]
        M[newL] = i

        if (newL > L):
            L = newL

    S = []
    k = M[L]
    for i in range(L-1, -1, -1):
        S.append(X[k])
        k = P[k]

    return len(S)#[::-1]

k1, k2, k3 = list(map(int, input().split()))
a = []
for _ in range(3):
    a.extend(sorted(list(map(int, input().split()))))

print(k1+k2+k3-LIS(a))

#1 5 1
#6
#5 1 2 4 7
#3

#2 1 3
#5 6
#4
#1 2 3


I found an interesting problem on https://codeforces.com/problemset/problem/1259/C:
You are given a non-empty string $s=s_1s_2\dots s_n$, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string $s$ if there is an integer $j$ ($1 \le j \le n-2$), that $s_{j}s_{j+1}s_{j+2}=$"one" or $s_{j}s_{j+1}s_{j+2}=$"two".

For example:

  Polycarp does not like strings "oneee", "ontwow", "twone" and "oneonetwo" (they all have at least one substring "one" or "two"),  Polycarp likes strings "oonnee", "twwwo" and "twnoe" (they have no substrings "one" and "two").

Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time.

For example, if the string looks like $s=$"onetwone", then if Polycarp selects two indices $3$ and $6$, then "onetwone" will be selected and the result is "ontwne".

What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be?

-----Input-----

The first line of the input contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Next, the test cases are given.

Each test case consists of one non-empty string $s$. Its length does not exceed $1.5\cdot10^5$. The string $s$ consists only of lowercase Latin letters.

It is guaranteed that the sum of lengths of all lines for all input data in the test does not exceed $1.5\cdot10^6$.

-----Output-----

Print an answer for each test case in the input in order of their appearance.

The first line of each answer should contain $r$ ($0 \le r \le |s|$) — the required minimum number of positions to be removed, where $|s|$ is the length of the given line. The second line of each answer should contain $r$ different integers — the indices themselves for removal in any order. Indices are numbered from left to right from $1$ to the length of the string. If $r=0$, then the second...

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

n = int(input())
Ans = []
for j in range(n):
    Ans_0 = []
    s = input()
    len_s = len(s)
    s = list(s)
    for i in range(2, len_s):
        S = s[i - 2] + s[i - 1] + s[i]
        if i < len_s - 2:
            if S + s[i + 1] + s[i + 2] == 'twone':
                Ans_0.append(i + 1)
            elif S == 'one' or S == 'two':
                if Ans_0:
                    if Ans_0[-1] != i - 1:
                        Ans_0.append(i)
                else:
                    Ans_0.append(i)

        elif S == 'one' or S == 'two':
            if Ans_0:
                if Ans_0[-1] != i - 1:
                    Ans_0.append(i)
            else:
                Ans_0.append(i)
    Ans.append(Ans_0)
for i in range(len(Ans)):
    print(len(Ans[i]))
    print(*Ans[i])


I found an interesting problem on https://codeforces.com/problemset/problem/1260/A:
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.

Your house has $n$ rooms. In the $i$-th room you can install at most $c_i$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $k$ sections is equal to $k^2$ burles.

Since rooms can have different sizes, you calculated that you need at least $sum_i$ sections in total in the $i$-th room.

For each room calculate the minimum cost to install at most $c_i$ radiators with total number of sections not less than $sum_i$.

-----Input-----

The first line contains single integer $n$ ($1 \le n \le 1000$) — the number of rooms.

Each of the next $n$ lines contains the description of some room. The $i$-th line contains two integers $c_i$ and $sum_i$ ($1 \le c_i, sum_i \le 10^4$) — the maximum number of radiators and the minimum total number of sections in the $i$-th room, respectively.

-----Output-----

For each room print one integer — the minimum possible cost to install at most $c_i$ radiators with total number of sections not less than $sum_i$.

-----Example-----
Input
4
1 10000
10000 1
2 6
4 6

Output
100000000
1
18
10

-----Note-----

In the first room, you can install only one radiator, so it's optimal to use the radiator with $sum_1$ sections. The cost of the radiator is equal to $(10^4)^2 = 10^8$.

In the second room, you can install up to $10^4$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.

In the third room, there $7$ variants to install radiators: $[6, 0]$, $[5, 1]$, $[4, 2]$, $[3, 3]$, $[2, 4]$, $[1, 5]$, $[0, 6]$. The optimal variant is $[3, 3]$ and it costs $3^2+ 3^2 = 18$.

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

t=int(input())
for nt in range(t):
    c,s=[int(k) for k in input().strip().split(" ")]
    res=0
    nba= s//c
    nbap=nba+1
    np= s%c
    na= c-np
    print(np*nbap*nbap + na *nba*nba)


I found an interesting problem on https://codeforces.com/problemset/problem/1260/B:
You are given two integers $a$ and $b$. You may perform any number of operations on them (possibly zero).

During each operation you should choose any positive integer $x$ and set $a := a - x$, $b := b - 2x$ or $a := a - 2x$, $b := b - x$. Note that you may choose different values of $x$ in different operations.

Is it possible to make $a$ and $b$ equal to $0$ simultaneously?

Your program should answer $t$ independent test cases.

-----Input-----

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

Then the test cases follow, each test case is represented by one line containing two integers $a$ and $b$ for this test case ($0 \le a, b \le 10^9$).

-----Output-----

For each test case print the answer to it — YES if it is possible to make $a$ and $b$ equal to $0$ simultaneously, and NO otherwise.

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

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

Output
YES
NO
YES

-----Note-----

In the first test case of the example two operations can be used to make both $a$ and $b$ equal to zero:  choose $x = 4$ and set $a := a - x$, $b := b - 2x$. Then $a = 6 - 4 = 2$, $b = 9 - 8 = 1$;  choose $x = 1$ and set $a := a - 2x$, $b := b - x$. Then $a = 2 - 2 = 0$, $b = 1 - 1 = 0$.

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

n = int(input())

for i in range(n):
    a,b = map(int,input().split())
    if a > b:
        a,b = b,a
    xx = 2 * b - a
    if xx < 0 or xx % 3 != 0:
        print('NO')
        continue
    x = xx // 3
    y = b - 2 * x
    if y < 0:
        print('NO')
        continue
    print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/1260/C:
You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.

You must paint a fence which consists of $10^{100}$ planks in two colors in the following way (suppose planks are numbered from left to right from $0$):   if the index of the plank is divisible by $r$ (such planks have indices $0$, $r$, $2r$ and so on) then you must paint it red;  if the index of the plank is divisible by $b$ (such planks have indices $0$, $b$, $2b$ and so on) then you must paint it blue;  if the index is divisible both by $r$ and $b$ you can choose the color to paint the plank;  otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it).

Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all painted planks of the fence in ascending order: if there are $k$ consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.

The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.

-----Input-----

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

The next $T$ lines contain descriptions of test cases — one per line. Each test case contains three integers $r$, $b$, $k$ ($1 \le r, b \le 10^9$, $2 \le k \le 10^9$) — the corresponding coefficients.

-----Output-----

Print $T$ words — one per line. For each test case print REBEL (case insensitive) if the execution is unavoidable or OBEY (case insensitive) otherwise.

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

Output
OBEY
REBEL
OBEY
OBEY

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

from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

def gcd(a,b):
	while b:
		a,b = b, a%b
	return a

T = inp()
for _ in range(T):
    a,b,k = inpl()
    a,b = min(a,b), max(a,b)

    n = gcd(a,b)
    # while n < b:
    #     n += a
    #     cnt += 1
    cnt = -((n-b)//a)

    if cnt >= k:
        print("REBEL")
    else:
        print("OBEY")


I found an interesting problem on https://codeforces.com/problemset/problem/1260/D:
You are playing a computer game, where you lead a party of $m$ soldiers. Each soldier is characterised by his agility $a_i$.

The level you are trying to get through can be represented as a straight line segment from point $0$ (where you and your squad is initially located) to point $n + 1$ (where the boss is located).

The level is filled with $k$ traps. Each trap is represented by three numbers $l_i$, $r_i$ and $d_i$. $l_i$ is the location of the trap, and $d_i$ is the danger level of the trap: whenever a soldier with agility lower than $d_i$ steps on a trap (that is, moves to the point $l_i$), he gets instantly killed. Fortunately, you can disarm traps: if you move to the point $r_i$, you disarm this trap, and it no longer poses any danger to your soldiers. Traps don't affect you, only your soldiers.

You have $t$ seconds to complete the level — that is, to bring some soldiers from your squad to the boss. Before the level starts, you choose which soldiers will be coming with you, and which soldiers won't be. After that, you have to bring all of the chosen soldiers to the boss. To do so, you may perform the following actions:

  if your location is $x$, you may move to $x + 1$ or $x - 1$. This action consumes one second;  if your location is $x$ and the location of your squad is $x$, you may move to $x + 1$ or to $x - 1$ with your squad in one second. You may not perform this action if it puts some soldier in danger (i. e. the point your squad is moving into contains a non-disarmed trap with $d_i$ greater than agility of some soldier from the squad). This action consumes one second;  if your location is $x$ and there is a trap $i$ with $r_i = x$, you may disarm this trap. This action is done instantly (it consumes no time).

Note that after each action both your coordinate and the coordinate of your squad should be integers.

You have to choose the maximum number of soldiers such that they all can be brought from the point $0$ to the point $n + 1$ (where the boss waits) in no more than $t$...

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

3

import os
import sys

def main():
    M, N, K, T = read_ints()
    A = read_ints()
    B = [tuple(read_ints()) for _ in range(K)]
    print(solve(M, N, K, T, A, B))

def solve(M, N, K, T, A, B):
    B.sort()

    def seconds(agi):
        traps = [(l, r) for l, r, d in B if d > agi]
        x = 0
        sec = 0
        sw = -1
        for l, r in traps:
            if sw != -1 and sw < l:
                sec += 2 * (sw - x)
                sw = -1

            if sw != -1:
                sw = max(sw, r)
                continue

            sec += l - 1 - x
            x = l - 1
            sw = r

        if sw != -1:
            sec += 2 * (sw - x)

        sec += N + 1 - x
        return sec

    min_agi = min(A)
    max_agi = max(A)

    if seconds(max_agi) > T:
        return 0
    if seconds(min_agi) <= T:
        return len(A)

    lb = min_agi
    ub = max_agi
    while ub - lb > 1:
        agi = (lb + ub) // 2
        if seconds(agi) > T:
            lb = agi
        else:
            ub = agi

    return len([a for a in A if a >= ub])

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

DEBUG = 'DEBUG' in os.environ

def inp():
    return sys.stdin.readline().rstrip()

def read_int():
    return int(inp())

def read_ints():
    return [int(e) for e in inp().split()]

def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1260/E:
You are organizing a boxing tournament, where $n$ boxers will participate ($n$ is a power of $2$), and your friend is one of them. All boxers have different strength from $1$ to $n$, and boxer $i$ wins in the match against boxer $j$ if and only if $i$ is stronger than $j$.

The tournament will be organized as follows: $n$ boxers will be divided into pairs; the loser in each pair leaves the tournament, and $\frac{n}{2}$ winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner).

Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower.

Furthermore, during each stage you distribute the boxers into pairs as you wish.

The boxer with strength $i$ can be bribed if you pay him $a_i$ dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish?

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 2^{18}$) — the number of boxers. $n$ is a power of $2$.

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$, where $a_i$ is the number of dollars you have to pay if you want to bribe the boxer with strength $i$. Exactly one of $a_i$ is equal to $-1$ — it means that the boxer with strength $i$ is your friend. All other values are in the range $[1, 10^9]$.

-----Output-----

Print one integer — the minimum number of dollars you have to pay so your friend wins.

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

Output
0
Input
8
11 -1 13 19 24 7 17 5

Output
12

-----Note-----

In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament.

In the second test case you...

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

import math
import sys
from sys import stdin, stdout

#sys.setrecursionlimit(300000)
# print(sys.getrecursionlimit())

# dp O(NlogN)
def getMinimunCost(a, sum, i, j, dp):

    if dp[i][j] != -1:
        return dp[i][j]

    if a[j] == -1:
        return 0

    remaining = sum[i] - j

    res = -2
    if i < len(dp)-1:
        min1 = getMinimunCost(a, sum, i+1, j+1, dp)
        if min1 != -2:
            res = min1 + a[j]

    if remaining > 0:
        min2 = getMinimunCost(a, sum, i, j+1, dp)
        if res == -2:
            res = min2
        elif min2 != -2:
            res = min(res, min2)

    dp[i][j] = res
    return dp[i][j]

def getMinimunCost2(a, sum, dp):

    if a[0] == -1:
        for j in range(0, len(dp[0])):
            dp[0][j] = 0
    else:
        for j in range(0, len(dp[0])):
            dp[0][j] = a[0]

    for i in range(1, len(dp)):
        for j in range(1, len(dp[i])):
            if j <= sum[i]:
                if j > 0:
                    dp[i][j] = min(dp[i][j], dp[i][j-1])
                    if i > 0:
                        dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + a[j])
            else:
                dp[i][j] = min(dp[i][j], dp[i][j-1])
                #break;

    #for i in range(len(dp)):
    #    print(dp[i])

    #print(a)

    return dp[-1][-1]

def __starting_point():
    try:
        n = int(stdin.readline())
        a = [int(i) for i in stdin.readline().split()]

        bcnt = int(math.log(n, 2))

        sum = []
        sum.append(0)

        x = int(n/2)
        for i in range(1, bcnt+1):
            sum.append(sum[i-1] + x)
            x = int(x/2)

        #dp = [[-1 for i in range(n)] for i in range(bcnt + 1)]
        dp = [[float("inf") for i in range(n)] for i in range(bcnt + 1)]

        #print(sum)
        #print(str(dp[0][0] + 1))

        #set 0
        flag = True
        for i in range(len(a)):
            if a[i] == -1:
                flag = False
                a[i] = 0
            if flag:
                a[i] = 0

        a.reverse()
       ...


I found an interesting problem on https://codeforces.com/problemset/problem/1262/E:
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.

A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a $n \times m$ rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.

The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as $0$) some trees were set on fire. At the beginning of minute $0$, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of $8$ neighboring trees. At the beginning of minute $T$, the fire was extinguished.

The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of $T$ (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of $T$ (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.

Note that you'd like to maximize value $T$ but the set of trees can be arbitrary.

-----Input-----

The first line contains two integer $n$ and $m$ ($1 \le n, m \le 10^6$, $1 \le n \cdot m \le 10^6$) — the sizes of the map.

Next $n$ lines contain the map. The $i$-th line corresponds to the $i$-th row of the map and contains $m$-character string. The $j$-th character of the $i$-th string is "X" if the corresponding tree is burnt and "." otherwise.

It's guaranteed that the map contains at least one "X".

-----Output-----

In the first line print the single integer $T$ — the maximum time the Forest was on fire. In the next $n$ lines print the certificate: the map ($n \times m$...

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

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

h,w=map(int,input().split())
d=w+2
b=[0]*(w+2)
for i in range(h):
  b+=([0]+[int(j=="X") for j in input()]+[0])
b+=([0]*(w+2))
co=sum(b)
t=10**10
for i in range(1,h+1):
  f=0
  for j in range(w+2):
    f+=b[i*d+j]
    if b[i*d+j]==0 and f:
      t=min(t,(f-1)//2)
      f=0
for j in range(1,w+1):
  f=0
  for i in range(h+2):
    f+=b[i*d+j]
    if b[i*d+j]==0 and f:
      t=min(t,(f-1)//2)
      f=0

coo=0
ans=[-1]*(w+2)*(h+2)
stack=[]
for i in range(h+2):
  for j in range(w+2):
    if b[i*d+j]==0:
      stack.append(i*d+j)
      ans[i*d+j]=0
dij=[(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
for ij in stack:
  i,j=divmod(ij,d)
  for x,y in dij:
    if 0<=i+x<h+2 and 0<=j+y<w+2:
      if ans[(i+x)*d+j+y]==-1:
        ans[(i+x)*d+j+y]=ans[i*d+j]+1
        if ans[(i+x)*d+j+y]>t:
          coo+=1
        stack.append((i+x)*d+(j+y))
if coo*6<co and t==1:
  t-=1
print(t)
for i in range(1,h+1):
  print("".join([".X"[int(t<j)]for j in ans[i*d+1:i*d+w+1]]))


I found an interesting problem on https://codeforces.com/problemset/problem/1263/B:
A PIN code is a string that consists of exactly $4$ digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.

Polycarp has $n$ ($2 \le n \le 10$) bank cards, the PIN code of the $i$-th card is $p_i$.

Polycarp has recently read a recommendation that it is better to set different PIN codes on different cards. Thus he wants to change the minimal number of digits in the PIN codes of his cards so that all $n$ codes would become different.

Formally, in one step, Polycarp picks $i$-th card ($1 \le i \le n$), then in its PIN code $p_i$ selects one position (from $1$ to $4$), and changes the digit in this position to any other. He needs to change the minimum number of digits so that all PIN codes become different.

Polycarp quickly solved this problem. Can you solve it?

-----Input-----

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

The first line of each of $t$ test sets contains a single integer $n$ ($2 \le n \le 10$) — the number of Polycarp's bank cards. The next $n$ lines contain the PIN codes $p_1, p_2, \dots, p_n$ — one per line. The length of each of them is $4$. All PIN codes consist of digits only.

-----Output-----

Print the answers to $t$ test sets. The answer to each set should consist of a $n + 1$ lines

In the first line print $k$ — the least number of changes to make all PIN codes different. In the next $n$ lines output the changed PIN codes in the order corresponding to their appearance in the input. If there are several optimal answers, print any of them.

-----Example-----
Input
3
2
1234
0600
2
1337
1337
4
3139
3139
3139
3139

Output
0
1234
0600
1
1337
1237
3
3139
3138
3939
6139

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

def solve():
    n = int(input())
    d = {}
    ss = [input() for i in range(n)]
    for s in ss:
        d[s] = d.get(s,0)+1
    ans = sum(i-1 for i in d.values())
    print(ans)
    used = set(d.keys())
    l = []
    for s in ss:
        if d[s] > 1:
            t = list(s)
            f = False
            for i in range(4):
                for j in range(10):
                    t[i] = str(j)
                    u = "".join(t)
                    if u not in used:
                        l.append(u)
                        used.add(u)
                        d[s] -= 1
                        f = True
                        break
                if f:
                    break
        else:
            l.append(s)
            used.add(s)
    print(*l, sep="\n")

t = int(input())
for i in range(t):
    solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1263/C:
On the well-known testing system MathForces, a draw of $n$ rating units is arranged. The rating will be distributed according to the following algorithm: if $k$ participants take part in this event, then the $n$ rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an unused rating may remain — it is not given to any of the participants.

For example, if $n = 5$ and $k = 3$, then each participant will recieve an $1$ rating unit, and also $2$ rating units will remain unused. If $n = 5$, and $k = 6$, then none of the participants will increase their rating.

Vasya participates in this rating draw but does not have information on the total number of participants in this event. Therefore, he wants to know what different values of the rating increment are possible to get as a result of this draw and asks you for help.

For example, if $n=5$, then the answer is equal to the sequence $0, 1, 2, 5$. Each of the sequence values (and only them) can be obtained as $\lfloor n/k \rfloor$ for some positive integer $k$ (where $\lfloor x \rfloor$ is the value of $x$ rounded down): $0 = \lfloor 5/7 \rfloor$, $1 = \lfloor 5/5 \rfloor$, $2 = \lfloor 5/2 \rfloor$, $5 = \lfloor 5/1 \rfloor$.

Write a program that, for a given $n$, finds a sequence of all possible rating increments.

-----Input-----

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

Each line contains an integer $n$ ($1 \le n \le 10^9$) — the total number of the rating units being drawn.

-----Output-----

Output the answers for each of $t$ test cases. Each answer should be contained in two lines.

In the first line print a single integer $m$ — the number of different rating increment values that Vasya can get.

In the following line print $m$ integers in ascending order — the values of possible rating increments.

-----Example-----
Input
4
5
11
1
3

Output
4
0 1 2 5
6
0 1 2 3 5 11
2
0 1
3
0 1 3

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

for _ in range(int(input())):
	n=int(input())
	if n<=1000005:
		l=[0,1]
		for k in range(n-1,0,-1):
			a=n//k
			if a>l[-1]:
				l.append(a)
		print(len(l))
		print(*l)
	else:
		l=[x for x in range(1001)]
		for k in range(1000000,0,-1):
			a=n//k
			if a>l[-1]:
				l.append(a)
		print(len(l))
		print(*l)


I found an interesting problem on https://codeforces.com/problemset/problem/1263/D:
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $n$ passwords — strings, consists of small Latin letters.

Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $a$ and $b$ as follows:  two passwords $a$ and $b$ are equivalent if there is a letter, that exists in both $a$ and $b$;  two passwords $a$ and $b$ are equivalent if there is a password $c$ from the list, which is equivalent to both $a$ and $b$.

If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.

For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:  admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";  admin's password is "d", then you can access to system by using only "d".

Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.

-----Input-----

The first line contain integer $n$ ($1 \le n \le 2 \cdot 10^5$) — number of passwords in the list. Next $n$ lines contains passwords from the list – non-empty strings $s_i$, with length at most $50$ letters. Some of the passwords may be equal.

It is guaranteed that the total length of all passwords does not exceed $10^6$ letters. All of them consist only of lowercase Latin letters.

-----Output-----

In a single line print the minimal number of passwords, the use of which will allow guaranteed to access...

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

import sys
input=sys.stdin.readline
n=int(input())
def find(x):
    if x!=f[x]:
        f[x]=find(f[x])
    return f[x]
f=list(range(n+26))
for i in range(0,n):
	for j in set(input().rstrip()):
		f[find(ord(j)-97)]=find(i+26)
ans=0
for i in range(26,n+26):
	if f[i]==i:
		ans+=1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1263/E:
The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text.

Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters). Thus, it points to an index character. The user can move the cursor left or right one position. If the cursor is already at the first (leftmost) position, then it does not move left.

Initially, the cursor is in the first (leftmost) character.

Also, the user can write a letter or brackets (either (, or )) to the position that the cursor is currently pointing at. A new character always overwrites the old value at that position.

Your editor must check, whether the current line is the correct text. Text is correct if the brackets in them form the correct bracket sequence.

Formally, correct text (CT) must satisfy the following rules:   any line without brackets is CT (the line can contain whitespaces);  If the first character of the string — is (, the last — is ), and all the rest form a CT, then the whole line is a CT;  two consecutively written CT is also CT.

Examples of correct texts: hello(codeforces), round, ((i)(write))edi(tor)s, ( me). Examples of incorrect texts: hello)oops(, round), ((me).

The user uses special commands to work with your editor. Each command has its symbol, which must be written to execute this command.

The correspondence of commands and characters is as follows:   L — move the cursor one character to the left (remains in place if it already points to the first character);  R — move the cursor one character to the right;  any lowercase Latin letter or bracket (( or )) — write the entered character to the position where the cursor is now.

For a complete understanding, take a look at the first example and its illustrations in the note below.

You are given a string containing the characters that the user entered. For the brackets coloring module's work, after each...

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

'''input
11
(R)R(R)Ra)c
'''

# MODIFIED SEGMENT TREE (MIN = MINIMUM PREFIX SUM instead of MINIMUM ELEMENT IN PREFIX)

class SegmentTree:
    def __init__(self, n, arr=[]):
        self.n = n
        self.tsum = [0] * (2 * n)
        self.tmin = [0] * (2 * n)
        self.tmax = [0] * (2 * n)
        if arr:
            for i in range(len(arr)):
                self.tsum[n + i] = arr[i];
            for i in range(len(arr) - 1, 0, -1) :
                self.tsum[i] = self.tsum[i << 1] + self.tsum[i << 1 | 1];

    def update(self, p, val):
        p += self.n;
        self.tsum[p] = val;
        self.tmin[p] = val;
        self.tmax[p] = val;

        i = p;
        while i > 1:
            self.tsum[i >> 1] = self.tsum[i] + self.tsum[i ^ 1];
            self.tmin[i >> 1] = min(self.tmin[i], self.tmin[i ^ 1] + self.tsum[i]) if i%2==0 else min(self.tmin[i^1], self.tmin[i] + self.tsum[i^1])
            self.tmax[i >> 1] = max(self.tmax[i], self.tmax[i ^ 1] + self.tsum[i]) if i%2==0 else max(self.tmax[i^1], self.tmax[i] + self.tsum[i^1])
            i >>= 1;

'''
import math
array = [1,3,5,7,9,11]
n = 2 ** math.ceil(math.log(len(array), 2))
st = SegmentTree(n, array)
st.update(0, 2)
'''

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

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

#n = 2 ** math.ceil(math.log(n, 2))
n = 1048576
st = SegmentTree(n)

maxit = -1
currentit = 0
output = []
for c in s:
    if c == 'L':
        currentit = max(0, currentit - 1)
    elif c == 'R':
        currentit += 1
    else:
        maxit = max(maxit, currentit)
        if c == '(':
            st.update(currentit, 1)
        elif c == ')':
            st.update(currentit, -1)
        else:
            st.update(currentit, 0)

    vmax = st.tmax[1]
    vmin = st.tmin[1]
    vsum = st.tsum[1]
    if vmin >= 0 and vsum == 0:
        output.append(vmax)
    else:
        output.append(-1)

print(' '.join(map(str, output)))


I found an interesting problem on https://codeforces.com/problemset/problem/1264/B:
An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to $1$. More formally, a sequence $s_1, s_2, \ldots, s_{n}$ is beautiful if $|s_i - s_{i+1}| = 1$ for all $1 \leq i \leq n - 1$.

Trans has $a$ numbers $0$, $b$ numbers $1$, $c$ numbers $2$ and $d$ numbers $3$. He wants to construct a beautiful sequence using all of these $a + b + c + d$ numbers.

However, it turns out to be a non-trivial task, and Trans was not able to do it. Could you please help Trans?

-----Input-----

The only input line contains four non-negative integers $a$, $b$, $c$ and $d$ ($0 < a+b+c+d \leq 10^5$).

-----Output-----

If it is impossible to construct a beautiful sequence satisfying the above constraints, print "NO" (without quotes) in one line.

Otherwise, print "YES" (without quotes) in the first line. Then in the second line print $a + b + c + d$ integers, separated by spaces — a beautiful sequence. There should be $a$ numbers equal to $0$, $b$ numbers equal to $1$, $c$ numbers equal to $2$ and $d$ numbers equal to $3$.

If there are multiple answers, you can print any of them.

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

Output
YES
0 1 0 1 2 3 2

Input
1 2 3 4

Output
NO

Input
2 2 2 3

Output
NO

-----Note-----

In the first test, it is easy to see, that the sequence is beautiful because the difference between any two consecutive numbers is equal to $1$. Also, there are exactly two numbers, equal to $0$, $1$, $2$ and exactly one number, equal to $3$.

It can be proved, that it is impossible to construct beautiful sequences in the second and third tests.

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

import sys
input = sys.stdin.readline

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

for start in range(4):
    ANS=[]
    now=start
    A=[a,b,c,d]

    if A[now]==0:
        continue

    while True:
        A[now]-=1
        ANS.append(now)

        if now==0:
            if A[1]!=0:
                now=1
            else:
                break

        elif now==1:
            if A[0]!=0:
                now=0
            elif A[2]!=0:
                now=2
            else:
                break

        elif now==2:
            if A[3]!=0:
                now=3
            elif A[1]!=0:
                now=1
            else:
                break
        else:
            if A[2]!=0:
                now=2
            else:
                break

    if max(A)==0:
        print("YES")
        print(*ANS)
        return
print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1264/F:
The well-known Fibonacci sequence $F_0, F_1, F_2,\ldots $ is defined as follows:   $F_0 = 0, F_1 = 1$.  For each $i \geq 2$: $F_i = F_{i - 1} + F_{i - 2}$.

Given an increasing arithmetic sequence of positive integers with $n$ elements: $(a, a + d, a + 2\cdot d,\ldots, a + (n - 1)\cdot d)$.

You need to find another increasing arithmetic sequence of positive integers with $n$ elements $(b, b + e, b + 2\cdot e,\ldots, b + (n - 1)\cdot e)$ such that:  $0 < b, e < 2^{64}$,  for all $0\leq i < n$, the decimal representation of $a + i \cdot d$ appears as substring in the last $18$ digits of the decimal representation of $F_{b + i \cdot e}$ (if this number has less than $18$ digits, then we consider all its digits).

-----Input-----

The first line contains three positive integers $n$, $a$, $d$ ($1 \leq n, a, d, a + (n - 1) \cdot d < 10^6$).

-----Output-----

If no such arithmetic sequence exists, print $-1$.

Otherwise, print two integers $b$ and $e$, separated by space in a single line ($0 < b, e < 2^{64}$).

If there are many answers, you can output any of them.

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

Output
2 1
Input
5 1 2

Output
19 5

-----Note-----

In the first test case, we can choose $(b, e) = (2, 1)$, because $F_2 = 1, F_3 = 2, F_4 = 3$.

In the second test case, we can choose $(b, e) = (19, 5)$ because:  $F_{19} = 4181$ contains $1$;  $F_{24} = 46368$ contains $3$;  $F_{29} = 514229$ contains $5$;  $F_{34} = 5702887$ contains $7$;  $F_{39} = 63245986$ contains $9$.

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


I found an interesting problem on https://codeforces.com/problemset/problem/1265/A:
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.

Ahcl wants to construct a beautiful string. He has a string $s$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!

More formally, after replacing all characters '?', the condition $s_i \neq s_{i+1}$ should be satisfied for all $1 \leq i \leq |s| - 1$, where $|s|$ is the length of the string $s$.

-----Input-----

The first line contains positive integer $t$ ($1 \leq t \leq 1000$) — the number of test cases. Next $t$ lines contain the descriptions of test cases.

Each line contains a non-empty string $s$ consisting of only characters 'a', 'b', 'c' and '?'.

It is guaranteed that in each test case a string $s$ has at least one character '?'. The sum of lengths of strings $s$ in all test cases does not exceed $10^5$.

-----Output-----

For each test case given in the input print the answer in the following format:

  If it is impossible to create a beautiful string, print "-1" (without quotes);  Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.

-----Example-----
Input
3
a???cb
a??bbc
a?b?c

Output
ababcb
-1
acbac

-----Note-----

In the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.

In the second test case, it is impossible to create a beautiful string, because the $4$-th and $5$-th characters will be always equal.

In the third test case, the only answer is "acbac".

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

import sys
def I():
        return sys.stdin.readline().rstrip()

for _ in range( int(I()) ):
    s = I()
    l = []
    last = 0
    for i in range(len(s)):
        nxt = s[ i + 1 ] if i < len(s) - 1 else 0
        if s[ i ] == '?':
            for c in 'abc':
                if c != last and c != nxt:
                    l.append(c)
                    last = c
                    break
        else:
            if s[ i ] == nxt:
                print(-1)
                break
            l.append( s[ i ] )
            last = s[ i ]
    else:
        print("".join(l))


I found an interesting problem on https://codeforces.com/problemset/problem/1265/E:
Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\frac{p_i}{100}$ for all $1 \le i \le n$.

Creatnx asks the mirrors one by one, starting from the $1$-st mirror. Every day, if he asks $i$-th mirror, there are two possibilities:  The $i$-th mirror tells Creatnx that he is beautiful. In this case, if $i = n$ Creatnx will stop and become happy, otherwise he will continue asking the $i+1$-th mirror next day;  In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the $1$-st mirror again.

You need to calculate the expected number of days until Creatnx becomes happy.

This number should be found by modulo $998244353$. Formally, let $M = 998244353$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output such an integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$.

-----Input-----

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

The second line contains $n$ integers $p_1, p_2, \ldots, p_n$ ($1 \leq p_i \leq 100$).

-----Output-----

Print the answer modulo $998244353$ in a single line.

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

Output
2

Input
3
10 20 50

Output
112

-----Note-----

In the first test, there is only one mirror and it tells, that Creatnx is beautiful with probability $\frac{1}{2}$. So, the expected number of days until Creatnx becomes happy is $2$.

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

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

ans = 0
size = 998244353

for p in p:
    ans = (ans+1) % size
    ans = (((ans*100) % size)*pow(p, size-2, size)) % size

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1266/A:
Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked $n$ of them how much effort they needed to reach red.

"Oh, I just spent $x_i$ hours solving problems", said the $i$-th of them.

Bob wants to train his math skills, so for each answer he wrote down the number of minutes ($60 \cdot x_i$), thanked the grandmasters and went home. Bob could write numbers with leading zeroes — for example, if some grandmaster answered that he had spent $2$ hours, Bob could write $000120$ instead of $120$.

Alice wanted to tease Bob and so she took the numbers Bob wrote down, and for each of them she did one of the following independently:   rearranged its digits, or  wrote a random number.

This way, Alice generated $n$ numbers, denoted $y_1$, ..., $y_n$.

For each of the numbers, help Bob determine whether $y_i$ can be a permutation of a number divisible by $60$ (possibly with leading zeroes).

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 418$) — the number of grandmasters Bob asked.

Then $n$ lines follow, the $i$-th of which contains a single integer $y_i$ — the number that Alice wrote down.

Each of these numbers has between $2$ and $100$ digits '0' through '9'. They can contain leading zeroes.

-----Output-----

Output $n$ lines.

For each $i$, output the following. If it is possible to rearrange the digits of $y_i$ such that the resulting number is divisible by $60$, output "red" (quotes for clarity). Otherwise, output "cyan".

-----Example-----
Input
6
603
006
205
228
1053
0000000000000000000000000000000000000000000000

Output
red
red
cyan
cyan
cyan
red

-----Note-----

In the first example, there is one rearrangement that yields a number divisible by $60$, and that is $360$.

In the second example, there are two solutions. One is $060$ and the second is $600$.

In the third example, there are $6$ possible rearrangments: $025$, $052$, $205$, $250$, $502$, $520$. None of these...

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

n = int(input())

for qwe in range(n):
	a = list(sorted(list(map(int, input()))))
	if sum(a) % 3 == 0 and a[0] == 0 and (0 in a[1:] or 2 in a[1:] or 4 in a[1:] or 6 in a[1:] or 8 in a[1:]):
		print('red')
	else:
		print('cyan')


I found an interesting problem on https://codeforces.com/problemset/problem/1266/D:
There are $n$ people in this world, conveniently numbered $1$ through $n$. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let $d(a,b)$ denote the debt of $a$ towards $b$, or $0$ if there is no such debt.

Sometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money.

When this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done:  Let $d(a,b) > 0$ and $d(c,d) > 0$ such that $a \neq c$ or $b \neq d$. We can decrease the $d(a,b)$ and $d(c,d)$ by $z$ and increase $d(c,b)$ and $d(a,d)$ by $z$, where $0 < z \leq \min(d(a,b),d(c,d))$.  Let $d(a,a) > 0$. We can set $d(a,a)$ to $0$.

The total debt is defined as the sum of all debts:

$$\Sigma_d = \sum_{a,b} d(a,b)$$

Your goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the number of non-zero debts, only the total debt.

-----Input-----

The first line contains two space separated integers $n$ ($1 \leq n \leq 10^5$) and $m$ ($0 \leq m \leq 3\cdot 10^5$), representing the number of people and the number of debts, respectively.

$m$ lines follow, each of which contains three space separated integers $u_i$, $v_i$ ($1 \leq u_i, v_i \leq n, u_i \neq v_i$), $d_i$ ($1 \leq d_i \leq 10^9$), meaning that the person $u_i$ borrowed $d_i$ burles from person $v_i$.

-----Output-----

On the first line print an integer $m'$ ($0 \leq m' \leq 3\cdot 10^5$), representing the number of debts after the consolidation. It can be shown that an answer always exists with this additional constraint.

After that print $m'$ lines, $i$-th of which contains three space separated...

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

import sys
input = sys.stdin.readline

n, m = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]

val = [0] * n
for i in range(m):
    a, b, cost = info[i]
    a -= 1
    b -= 1
    val[a] -= cost
    val[b] += cost

minus = []
plus = []
for i in range(n):
    if val[i] < 0:
        minus.append([i, -val[i]])
    if val[i] > 0:
        plus.append([i, val[i]])

ans = []
num1 = 0
for num2, cost in minus:
    a = num2 + 1
    value = cost
    while True:
        if value == 0:
            break
        if num1 >= len(plus):
            break
        if plus[num1][1] <= value:
            ans.append((a, plus[num1][0] + 1, plus[num1][1]))
            value -= plus[num1][1]
            num1 += 1
        else:
            ans.append((a, plus[num1][0] + 1, value))
            plus[num1][1] -= value
            break

print(len(ans))
for i in ans:
    print(*i)


I found an interesting problem on https://codeforces.com/problemset/problem/1266/E:
Bob is playing a game of Spaceship Solitaire. The goal of this game is to build a spaceship. In order to do this, he first needs to accumulate enough resources for the construction. There are $n$ types of resources, numbered $1$ through $n$. Bob needs at least $a_i$ pieces of the $i$-th resource to build the spaceship. The number $a_i$ is called the goal for resource $i$.

Each resource takes $1$ turn to produce and in each turn only one resource can be produced. However, there are certain milestones that speed up production. Every milestone is a triple $(s_j, t_j, u_j)$, meaning that as soon as Bob has $t_j$ units of the resource $s_j$, he receives one unit of the resource $u_j$ for free, without him needing to spend a turn. It is possible that getting this free resource allows Bob to claim reward for another milestone. This way, he can obtain a large number of resources in a single turn.

The game is constructed in such a way that there are never two milestones that have the same $s_j$ and $t_j$, that is, the award for reaching $t_j$ units of resource $s_j$ is at most one additional resource.

A bonus is never awarded for $0$ of any resource, neither for reaching the goal $a_i$ nor for going past the goal — formally, for every milestone $0 < t_j < a_{s_j}$.

A bonus for reaching certain amount of a resource can be the resource itself, that is, $s_j = u_j$.

Initially there are no milestones. You are to process $q$ updates, each of which adds, removes or modifies a milestone. After every update, output the minimum number of turns needed to finish the game, that is, to accumulate at least $a_i$ of $i$-th resource for each $i \in [1, n]$.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the number of types of resources.

The second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq 10^9$), the $i$-th of which is the goal for the $i$-th resource.

The third line contains a single integer $q$ ($1 \leq q \leq 10^5$) — the number of...

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

import sys
from collections import Counter
readline = sys.stdin.readline

N = int(readline())
A = list(map(int, readline().split()))
geta = 10**9+7

Q = int(readline())
C = Counter()

Ans = [sum(A)] + [0]*Q
A = [0] + A
table = [geta] + [0]*N
for qu in range(1, Q+1):
    s, t, u = list(map(int, readline().split()))
    vn = s*geta + t
    res = 0
    cv = C[vn]
    if u != cv:
        if table[cv] <= A[cv]:
            res = 1
        table[cv] -= 1
        if table[u] < A[u]:
            res -= 1
        table[u] += 1
    C[vn] = u
    Ans[qu] = Ans[qu-1] + res
print('\n'.join(map(str, [max(1, a) for a in Ans[1:]])))


I found an interesting problem on https://codeforces.com/problemset/problem/1266/G:
Let $n$ be an integer. Consider all permutations on integers $1$ to $n$ in lexicographic order, and concatenate them into one big sequence $P$. For example, if $n = 3$, then $P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$. The length of this sequence is $n \cdot n!$.

Let $1 \leq i \leq j \leq n \cdot n!$ be a pair of indices. We call the sequence $(P_i, P_{i+1}, \dots, P_{j-1}, P_j)$ a subarray of $P$.

You are given $n$. Find the number of distinct subarrays of $P$. Since this number may be large, output it modulo $998244353$ (a prime number).

-----Input-----

The only line contains one integer $n$ ($1 \leq n \leq 10^6$), as described in the problem statement.

-----Output-----

Output a single integer — the number of distinct subarrays, modulo $998244353$.

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

Output
8

Input
10

Output
19210869

-----Note-----

In the first example, the sequence $P = [1, 2, 2, 1]$. It has eight distinct subarrays: $[1]$, $[2]$, $[1, 2]$, $[2, 1]$, $[2, 2]$, $[1, 2, 2]$, $[2, 2, 1]$ and $[1, 2, 2, 1]$.

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


I found an interesting problem on https://codeforces.com/problemset/problem/1268/A:
You are given an integer $x$ of $n$ digits $a_1, a_2, \ldots, a_n$, which make up its decimal notation in order from left to right.

Also, you are given a positive integer $k < n$.

Let's call integer $b_1, b_2, \ldots, b_m$ beautiful if $b_i = b_{i+k}$ for each $i$, such that $1 \leq i \leq m - k$.

You need to find the smallest beautiful integer $y$, such that $y \geq x$.

-----Input-----

The first line of input contains two integers $n, k$ ($2 \leq n \leq 200\,000, 1 \leq k < n$): the number of digits in $x$ and $k$.

The next line of input contains $n$ digits $a_1, a_2, \ldots, a_n$ ($a_1 \neq 0$, $0 \leq a_i \leq 9$): digits of $x$.

-----Output-----

In the first line print one integer $m$: the number of digits in $y$.

In the next line print $m$ digits $b_1, b_2, \ldots, b_m$ ($b_1 \neq 0$, $0 \leq b_i \leq 9$): digits of $y$.

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

Output
3
353

Input
4 2
1234

Output
4
1313

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

import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

n,k = list(map(int, input().split()))
a = list(map(int, input()))
b = a[:k]
c = [b[i%k] for i in range(n)]
if tuple(a)>tuple(c):
    d = int("".join(map(str, b)))
    d += 1
    b = list(map(int, str(d)))
    c = [b[i%k] for i in range(n)]
print(len(c))
print("".join(map(str, c)))


I found an interesting problem on https://codeforces.com/problemset/problem/1269/A:
Let's call a positive integer composite if it has at least one divisor other than $1$ and itself. For example:

  the following numbers are composite: $1024$, $4$, $6$, $9$;  the following numbers are not composite: $13$, $1$, $2$, $3$, $37$.

You are given a positive integer $n$. Find two composite integers $a,b$ such that $a-b=n$.

It can be proven that solution always exists.

-----Input-----

The input contains one integer $n$ ($1 \leq n \leq 10^7$): the given integer.

-----Output-----

Print two composite integers $a,b$ ($2 \leq a, b \leq 10^9, a-b=n$).

It can be proven, that solution always exists.

If there are several possible solutions, you can print any.

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

Output
9 8

Input
512

Output
4608 4096

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


I found an interesting problem on https://codeforces.com/problemset/problem/1269/B:
You are given a positive integer $m$ and two integer sequence: $a=[a_1, a_2, \ldots, a_n]$ and $b=[b_1, b_2, \ldots, b_n]$. Both of these sequence have a length $n$.

Permutation is a sequence of $n$ different positive integers from $1$ to $n$. For example, these sequences are permutations: $[1]$, $[1,2]$, $[2,1]$, $[6,7,3,4,1,2,5]$. These are not: $[0]$, $[1,1]$, $[2,3]$.

You need to find the non-negative integer $x$, and increase all elements of $a_i$ by $x$, modulo $m$ (i.e. you want to change $a_i$ to $(a_i + x) \bmod m$), so it would be possible to rearrange elements of $a$ to make it equal $b$, among them you need to find the smallest possible $x$.

In other words, you need to find the smallest non-negative integer $x$, for which it is possible to find some permutation $p=[p_1, p_2, \ldots, p_n]$, such that for all $1 \leq i \leq n$, $(a_i + x) \bmod m = b_{p_i}$, where $y \bmod m$ — remainder of division of $y$ by $m$.

For example, if $m=3$, $a = [0, 0, 2, 1], b = [2, 0, 1, 1]$, you can choose $x=1$, and $a$ will be equal to $[1, 1, 0, 2]$ and you can rearrange it to make it equal $[2, 0, 1, 1]$, which is equal to $b$.

-----Input-----

The first line contains two integers $n,m$ ($1 \leq n \leq 2000, 1 \leq m \leq 10^9$): number of elemens in arrays and $m$.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i < m$).

The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($0 \leq b_i < m$).

It is guaranteed that there exists some non-negative integer $x$, such that it would be possible to find some permutation $p_1, p_2, \ldots, p_n$ such that $(a_i + x) \bmod m = b_{p_i}$.

-----Output-----

Print one integer, the smallest non-negative integer $x$, such that it would be possible to find some permutation $p_1, p_2, \ldots, p_n$ such that $(a_i + x) \bmod m = b_{p_i}$ for all $1 \leq i \leq n$.

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

Output
1

Input
3 2
0 0 0
1 1 1

Output
1

Input
5 10
0 0 0 1 2
2 1 0 0 0

Output
0

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

n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a.sort()
b.sort()
ans=[]
for i in range(n):
	if b[-1]<a[i]:
		ans.append(b[-1]-a[i]+m)
		#ans.append(b[-1]-a[i]+m+m)
	else:
		ans.append(b[-1]-a[i])
		#ans.append(b[-1]-a[i]+m)
ans=list(set(ans))
ans.sort()
for i in ans:
	temp=[]
	for j in range(n):
		temp.append((a[j]+i)%m)
	if sorted(temp)==b:
		print (i)
		return
print(1/0)


I found an interesting problem on https://codeforces.com/problemset/problem/1270/G:
You are given $n$ integers $a_1, a_2, \dots, a_n$, such that for each $1\le i \le n$ holds $i-n\le a_i\le i-1$.

Find some nonempty subset of these integers, whose sum is equal to $0$. It can be shown that such a subset exists under given constraints. If there are several possible subsets with zero-sum, you can find any of them.

-----Input-----

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

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

The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($i-n \le a_i \le i-1$).

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

-----Output-----

For each test case, output two lines.

In the first line, output $s$ ($1\le s \le n$) — the number of elements in your subset.

In the second line, output $s$ integers $i_1, i_2, \dots, i_s$ ($1\le i_k \le n$). All integers have to be pairwise different, and $a_{i_1} + a_{i_2} + \dots + a_{i_s}$ has to be equal to $0$. If there are several possible subsets with zero-sum, you can find any of them.

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

Output
1
1
4
1 4 3 2

-----Note-----

In the first example, we get sum is $a_1 = 0$.

In the second example, we get sum is $a_1 + a_4 + a_3 + a_2 = 0$.

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

import sys
input = sys.stdin.readline

t=int(input())
for test in range(t):
    n=int(input())
    A=list(map(int,input().split()))

    ANS=[]
    SET=set()

    NOW=1
    while not (NOW in SET):
        ANS.append(NOW)
        SET.add(NOW)
        NOW=NOW-A[NOW-1]

    x=ANS.index(NOW)

    print(len(ANS[x:]))
    print(*ANS[x:])


I found an interesting problem on https://codeforces.com/problemset/problem/1271/A:
A new delivery of clothing has arrived today to the clothing store. This delivery consists of $a$ ties, $b$ scarves, $c$ vests and $d$ jackets.

The store does not sell single clothing items — instead, it sells suits of two types:  a suit of the first type consists of one tie and one jacket;  a suit of the second type consists of one scarf, one vest and one jacket.

Each suit of the first type costs $e$ coins, and each suit of the second type costs $f$ coins.

Calculate the maximum possible cost of a set of suits that can be composed from the delivered clothing items. Note that one item cannot be used in more than one suit (though some items may be left unused).

-----Input-----

The first line contains one integer $a$ $(1 \le a \le 100\,000)$ — the number of ties.

The second line contains one integer $b$ $(1 \le b \le 100\,000)$ — the number of scarves.

The third line contains one integer $c$ $(1 \le c \le 100\,000)$ — the number of vests.

The fourth line contains one integer $d$ $(1 \le d \le 100\,000)$ — the number of jackets.

The fifth line contains one integer $e$ $(1 \le e \le 1\,000)$ — the cost of one suit of the first type.

The sixth line contains one integer $f$ $(1 \le f \le 1\,000)$ — the cost of one suit of the second type.

-----Output-----

Print one integer — the maximum total cost of some set of suits that can be composed from the delivered items.

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

Output
6

Input
12
11
13
20
4
6

Output
102

Input
17
14
5
21
15
17

Output
325

-----Note-----

It is possible to compose three suits of the second type in the first example, and their total cost will be $6$. Since all jackets will be used, it's impossible to add anything to this set.

The best course of action in the second example is to compose nine suits of the first type and eleven suits of the second type. The total cost is $9 \cdot 4 + 11 \cdot 6 = 102$.

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

a=int(input())
b=int(input())
c=int(input())
d=int(input())
e=int(input())
f=int(input())
if e>=f:
    ans=e*min(a,d)
    k=min(a,d)
    a -= k
    d -= k
    ans += f*min(b,c,d)
    print(ans)
else:
    ans=f*min(b,c,d)
    k=min(b,c,d)
    b -= k
    c -= k
    d -= k
    ans += e*min(a,d)
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1271/C:
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.

The main school of the capital is located in $(s_x, s_y)$. There are $n$ students attending this school, the $i$-th of them lives in the house located in $(x_i, y_i)$. It is possible that some students live in the same house, but no student lives in $(s_x, s_y)$.

After classes end, each student walks from the school to his house along one of the shortest paths. So the distance the $i$-th student goes from the school to his house is $|s_x - x_i| + |s_y - y_i|$.

The Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the $i$-th student will buy a shawarma if at least one of the shortest paths from the school to the $i$-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students).

You want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself.

-----Input-----

The first line contains three integers $n$, $s_x$, $s_y$ ($1 \le n \le 200\,000$, $0 \le s_x, s_y \le 10^{9}$) — the number of students and the coordinates of the school, respectively.

Then $n$ lines follow. The $i$-th of them contains two integers $x_i$, $y_i$ ($0 \le x_i, y_i \le 10^{9}$) — the location of the house where the $i$-th student lives. Some locations of houses may coincide, but no student lives in the same location where the school is situated.

-----Output-----

The output should consist of two lines. The first of them should contain one integer $c$ — the maximum number of students...

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

import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys

input = sys.stdin.readline
M = mod = 10**9 + 7
def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip('\n').split(' ')]
def st():return input().rstrip('\n')
def val():return int(input())
def li2():return [i for i in input().rstrip('\n').split(' ')]

n,s1,s2 = li()
l = []
for i in range(n):l.append(li())
a1,a2,a3,a4 = [0]*4

for i in range(n):
    if s1 == l[i][0]:
        if s2<l[i][1]:
            a2+=1
        else:
            a4+=1
    elif s2 == l[i][1]:
        if s1<l[i][0]:
            a3+=1
        else:
            a1+=1
    else:
        if s1<l[i][0]:
            a3 += 1
        else:
            a1+=1
        if s2<l[i][1]:
            a2 += 1
        else:
            a4 += 1
ans = max(a1,a2,a3,a4)
print(ans)
if a1 == ans:
    print(s1-1,s2)
elif a3 == ans:
    print(s1+1,s2)
elif a2 == ans:
    print(s1,s2+1)
else:
    print(s1,s2-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1271/D:
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer $n$ castles of your opponent.

Let's describe the game process in detail. Initially you control an army of $k$ warriors. Your enemy controls $n$ castles; to conquer the $i$-th castle, you need at least $a_i$ warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army — formally, after you capture the $i$-th castle, $b_i$ warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter $c_i$, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:

  if you are currently in the castle $i$, you may leave one warrior to defend castle $i$;  there are $m$ one-way portals connecting the castles. Each portal is characterised by two numbers of castles $u$ and $v$ (for each portal holds $u > v$). A portal can be used as follows: if you are currently in the castle $u$, you may send one warrior to defend castle $v$.

Obviously, when you order your warrior to defend some castle, he leaves your army.

You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle $i$ (but only before capturing castle $i + 1$) you may recruit new warriors from castle $i$, leave a warrior to defend castle $i$, and use any number of portals leading from castle $i$ to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle $i$ won't be available to you.

If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values...

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

import sys
input = sys.stdin.readline

n, m, k = map(int, input().split())
cas = [list(map(int, input().split())) for i in range(n)]
pot = [list(map(int, input().split())) for i in range(m)]

timing = [i for i in range(n)]
for i in range(m):
    a, b = pot[i]
    a -= 1
    b -= 1
    if a > b:
        a, b = b, a
    timing[a] = max(b, timing[a])

time = [[] for i in range(n)]
for i in range(n):
    time[timing[i]].append(cas[i][2])
for i in range(n):
    time[timing[i]].sort(reverse = True)

memo = {}
memo[k] = 0
for i in range(n):
    a, add_, c = cas[i]
    memo2 = {}
    for j in memo:
        if j >= a:
            memo2[j + add_] = memo[j]

    for num in time[i]:
        tmp = memo2.copy()
        for j in tmp:
            if j-1 not in memo2:
                memo2[j-1] = tmp[j] + num
            else:
                memo2[j-1] = max(tmp[j-1], tmp[j] + num)
    memo = memo2.copy()

ans = -1
for i in memo:
    ans = max(ans, memo[i])
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1271/E:
At first, let's define function $f(x)$ as follows: $$ \begin{matrix} f(x) & = & \left\{ \begin{matrix} \frac{x}{2} & \mbox{if } x \text{ is even} \\ x - 1 & \mbox{otherwise } \end{matrix} \right. \end{matrix} $$

We can see that if we choose some value $v$ and will apply function $f$ to it, then apply $f$ to $f(v)$, and so on, we'll eventually get $1$. Let's write down all values we get in this process in a list and denote this list as $path(v)$. For example, $path(1) = [1]$, $path(15) = [15, 14, 7, 6, 3, 2, 1]$, $path(32) = [32, 16, 8, 4, 2, 1]$.

Let's write all lists $path(x)$ for every $x$ from $1$ to $n$. The question is next: what is the maximum value $y$ such that $y$ is contained in at least $k$ different lists $path(x)$?

Formally speaking, you need to find maximum $y$ such that $\left| \{ x ~|~ 1 \le x \le n, y \in path(x) \} \right| \ge k$.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 10^{18}$).

-----Output-----

Print the only integer — the maximum value that is contained in at least $k$ paths.

-----Examples-----
Input
11 3

Output
5

Input
11 6

Output
4

Input
20 20

Output
1

Input
14 5

Output
6

Input
1000000 100

Output
31248

-----Note-----

In the first example, the answer is $5$, since $5$ occurs in $path(5)$, $path(10)$ and $path(11)$.

In the second example, the answer is $4$, since $4$ occurs in $path(4)$, $path(5)$, $path(8)$, $path(9)$, $path(10)$ and $path(11)$.

In the third example $n = k$, so the answer is $1$, since $1$ is the only number occuring in all paths for integers from $1$ to $20$.

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

import sys

def cnt(y, n):
    # print("in count")
    #print(y)
    if y <= 1:
        return n
    if y > n:
        return 0
    if y % 2 == 1:
        return 1 + cnt(2 * y, n)
    c = 0
    p = 1
    while p*y <= n:
        mx = min(n, p*y + 2*p - 1)
        c += mx - p*y + 1
        p *= 2
    return c

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

if k == 1:
    print(n)
    return

l, h = 1, n // 2
while l < h:
    m = (l + h) // 2
    #print("l = " + str(l))
    #print("h = " + str(h))
    #print("m = " + str(m))
    #print("cnt = " + str(cnt(m, n)))

    if cnt(2 * m, n) < k:
        h = m
    else:
        l = m + 1
mx_even = 2 * l - 2

l, h = 1, n // 2
while l < h:
    m = (l + h) // 2
    #print("l = " + str(l))
    #print("h = " + str(h))
    #print("m = " + str(m))
    #print("cnt = " + str(cnt(m, n)))

    if cnt(2 * m + 1, n) < k:
        h = m
    else:
        l = m + 1
mx_odd = 2 * l - 1
#assert(cnt(mx_odd, n) >= k)
#assert(cnt(mx_even, n) >= k)

mx_heur = -1
i = 0
while i < 20 and n - i > 0:
    if cnt(n - i, n) >= k:
        mx_heur = n - i
        break
    i += 1

print(max(mx_even, max(mx_odd, mx_heur)))