I found an interesting problem on https://codeforces.com/problemset/problem/1238/D:
The string $t_1t_2 \dots t_k$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.

A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.

Here are some examples of good strings:   $t$ = AABBB (letters $t_1$, $t_2$ belong to palindrome $t_1 \dots t_2$ and letters $t_3$, $t_4$, $t_5$ belong to palindrome $t_3 \dots t_5$);  $t$ = ABAA (letters $t_1$, $t_2$, $t_3$ belong to palindrome $t_1 \dots t_3$ and letter $t_4$ belongs to palindrome $t_3 \dots t_4$);  $t$ = AAAAA (all letters belong to palindrome $t_1 \dots t_5$);

You are given a string $s$ of length $n$, consisting of only letters A and B.

You have to calculate the number of good substrings of string $s$.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the length of the string $s$.

The second line contains the string $s$, consisting of letters A and B.

-----Output-----

Print one integer — the number of good substrings of string $s$.

-----Examples-----
Input
5
AABBB

Output
6

Input
3
AAA

Output
3

Input
7
AAABABB

Output
15

-----Note-----

In the first test case there are six good substrings: $s_1 \dots s_2$, $s_1 \dots s_4$, $s_1 \dots s_5$, $s_3 \dots s_4$, $s_3 \dots s_5$ and $s_4 \dots s_5$.

In the second test case there are three good substrings: $s_1 \dots s_2$, $s_1 \dots s_3$ and $s_2 \dots s_3$.

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

import sys
readline = sys.stdin.readline
N = int(readline())
S = [1 if s == 'A' else 0 for s in readline().strip()]
ans = 0
L1 = [None]*(N+1)
L2 = [None]*(N+1)
for i in range(N-1, -1, -1):
    s = S[i]
    L1[i] = L1[i+1]
    L2[i] = L2[i+1]
    if s == 1:
        L1[i] = i
    else:
        L2[i] = i

for i in range(N-1):
    s = S[i]
    sn = S[i+1]
    if s == sn:
        if s == 1:
            if L2[i] is not None:
                ans -= 1
        else:
            if L1[i] is not None:
                ans -= 1
    else:
        if s == 1:
            if L1[i+1] is None:
                ans -= N-i-1
            else:
                ans -= L1[i+1] - (i+1)
        else:
            if L2[i+1] is None:
                ans -= N-i-1
            else:
                ans -= L2[i+1] - (i+1)
print((N-1)*N//2+ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1239/A:
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.

To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of $n$ rows and $m$ columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.

Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo $10^9 + 7$.

-----Input-----

The only line contains two integers $n$ and $m$ ($1 \le n, m \le 100\,000$), the number of rows and the number of columns of the field.

-----Output-----

Print one integer, the number of random pictures modulo $10^9 + 7$.

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

Output
8

-----Note-----

The picture below shows all possible random pictures of size $2$ by $3$.  [Image]

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/1242/A:
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.

The path consists of $n$ consecutive tiles, numbered from $1$ to $n$. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles with numbers $i$ and $j$, such that $|j - i|$ is a divisor of $n$ greater than $1$, they have the same color. Formally, the colors of two tiles with numbers $i$ and $j$ should be the same if $|i-j| > 1$ and $n \bmod |i-j| = 0$ (where $x \bmod y$ is the remainder when dividing $x$ by $y$).

Ujan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic?

-----Input-----

The first line of input contains a single integer $n$ ($1 \leq n \leq 10^{12}$), the length of the path.

-----Output-----

Output a single integer, the maximum possible number of colors that the path can be painted in.

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

Output
2

Input
5

Output
5

-----Note-----

In the first sample, two colors is the maximum number. Tiles $1$ and $3$ should have the same color since $4 \bmod |3-1| = 0$. Also, tiles $2$ and $4$ should have the same color since $4 \bmod |4-2| = 0$.

In the second sample, all five colors can be used. [Image]

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

from math import sqrt, ceil

def mindiv(n):
    if n==1: return 1
    if n%2==0: return 2
    if n%3==0: return 3
    div,inc=5,2
    while div<ceil(sqrt(n))+1:
        if n%div == 0: return div
        div+=inc
        inc=6-inc
    return n
n=int(input())
m=mindiv(n)
while n%m==0 and n>m: n=n/m
print(1 if n>m else m)


I found an interesting problem on https://codeforces.com/problemset/problem/1243/A:
Ujan decided to make a new wooden roof for the house. He has $n$ rectangular planks numbered from $1$ to $n$. The $i$-th plank has size $a_i \times 1$ (that is, the width is $1$ and the height is $a_i$).

Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.

For example, if Ujan had planks with lengths $4$, $3$, $1$, $4$ and $5$, he could choose planks with lengths $4$, $3$ and $5$. Then he can cut out a $3 \times 3$ square, which is the maximum possible. Note that this is not the only way he can obtain a $3 \times 3$ square.

 [Image]

What is the maximum side length of the square Ujan can get?

-----Input-----

The first line of input contains a single integer $k$ ($1 \leq k \leq 10$), the number of test cases in the input.

For each test case, the first line contains a single integer $n$ ($1 \leq n \leq 1\,000$), the number of planks Ujan has in store. The next line contains $n$ integers $a_1, \ldots, a_n$ ($1 \leq a_i \leq n$), the lengths of the planks.

-----Output-----

For each of the test cases, output a single integer, the maximum possible side length of the square.

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

Output
3
4
1
3

-----Note-----

The first sample corresponds to the example in the statement.

In the second sample, gluing all $4$ planks will result in a $4 \times 4$ square.

In the third sample, the maximum possible square is $1 \times 1$ and can be taken simply as any of the planks.

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

def mi():
        return list(map(int, input().split()))
'''
4
5
4 3 1 4 5
4
4 4 4 4
3
1 1 1
5
5 5 1 1 5
'''
for _ in range(int(input())):
    n = int(input())
    a = sorted(list(mi()))[::-1]
    ans = -1
    mintillnow = 1e99
    for i in range(n):
        mintillnow = min(mintillnow, a[i])
        ans = max(ans, min(i+1, mintillnow))
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1243/B1:
This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems.

After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.

Ujan has two distinct strings $s$ and $t$ of length $n$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation exactly once: he takes two positions $i$ and $j$ ($1 \le i,j \le n$, the values $i$ and $j$ can be equal or different), and swaps the characters $s_i$ and $t_j$. Can he succeed?

Note that he has to perform this operation exactly once. He has to perform this operation.

-----Input-----

The first line contains a single integer $k$ ($1 \leq k \leq 10$), the number of test cases.

For each of the test cases, the first line contains a single integer $n$ ($2 \leq n \leq 10^4$), the length of the strings $s$ and $t$.

Each of the next two lines contains the strings $s$ and $t$, each having length exactly $n$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.

-----Output-----

For each test case, output "Yes" if Ujan can make the two strings equal and "No" otherwise.

You can print each letter in any case (upper or lower).

-----Example-----
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca

Output
Yes
No
No
No

-----Note-----

In the first test case, Ujan can swap characters $s_1$ and $t_4$, obtaining the word "house".

In the second test case, it is not possible to make the strings equal using exactly one swap of $s_i$ and $t_j$.

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

t = int(input())
while t>0:
    n = int(input())

    a = input()
    b = input()
    ind = []
    for i in range(0,len(a)):
        if a[i] == b[i]:
            pass
        else:
            ind.append(i)
    if len(ind)>2 or len(ind)==1:
        print('No')
    else:
        if a[ind[0]] == a[ind[1]] and b[ind[0]] == b[ind[1]]:
            print('Yes')
        else:
            print('No')
    t-=1


I found an interesting problem on https://codeforces.com/problemset/problem/1244/A:
Tomorrow is a difficult day for Polycarp: he has to attend $a$ lectures and $b$ practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.

While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and draw everything he has to during all of the practical classes. Polycarp writes lectures using a pen (he can't use a pencil to write lectures!); he can write down $c$ lectures using one pen, and after that it runs out of ink. During practical classes Polycarp draws blueprints with a pencil (he can't use a pen to draw blueprints!); one pencil is enough to draw all blueprints during $d$ practical classes, after which it is unusable.

Polycarp's pencilcase can hold no more than $k$ writing implements, so if Polycarp wants to take $x$ pens and $y$ pencils, they will fit in the pencilcase if and only if $x + y \le k$.

Now Polycarp wants to know how many pens and pencils should he take. Help him to determine it, or tell that his pencilcase doesn't have enough room for all the implements he needs tomorrow!

Note that you don't have to minimize the number of writing implements (though their total number must not exceed $k$).

-----Input-----

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

Each test case is described by one line containing five integers $a$, $b$, $c$, $d$ and $k$, separated by spaces ($1 \le a, b, c, d, k \le 100$) — the number of lectures Polycarp has to attend, the number of practical classes Polycarp has to attend, the number of lectures which can be written down using one pen, the number of practical classes for which one pencil is enough, and the number of writing implements that can fit into Polycarp's pencilcase, respectively.

In hacks it is allowed to use only one test case in the input, so $t = 1$ should be satisfied.

-----Output-----

For each test case, print the answer as...

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

import math
amount = int(input())
for i in range(amount):
    a, b, c, d, k = [int(s) for s in input().split()]
    if math.ceil(a/c) + math.ceil(b/d) > k:
        print(-1)
    else:
        print(math.ceil(a/c), math.ceil(b/d))


I found an interesting problem on https://codeforces.com/problemset/problem/1244/B:
Nikolay lives in a two-storied house. There are $n$ rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between $1$ and $n$).

If Nikolay is currently in some room, he can move to any of the neighbouring rooms (if they exist). Rooms with numbers $i$ and $i+1$ on each floor are neighbouring, for all $1 \leq i \leq n - 1$. There may also be staircases that connect two rooms from different floors having the same numbers. If there is a staircase connecting the room $x$ on the first floor and the room $x$ on the second floor, then Nikolay can use it to move from one room to another.

 $\text{floor}$  The picture illustrates a house with $n = 4$. There is a staircase between the room $2$ on the first floor and the room $2$ on the second floor, and another staircase between the room $4$ on the first floor and the room $4$ on the second floor. The arrows denote possible directions in which Nikolay can move. The picture corresponds to the string "0101" in the input.

Nikolay wants to move through some rooms in his house. To do this, he firstly chooses any room where he starts. Then Nikolay moves between rooms according to the aforementioned rules. Nikolay never visits the same room twice (he won't enter a room where he has already been).

Calculate the maximum number of rooms Nikolay can visit during his tour, if:

  he can start in any room on any floor of his choice,  and he won't visit the same room twice.

-----Input-----

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

The first line contains one integer $n$ $(1 \le n \le 1\,000)$ — the number of rooms on each floor.

The second line contains one string consisting of $n$ characters, each character is either a '0' or a '1'. If the $i$-th character is a '1', then there is a...

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

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

    def solve():
        n = int(input())
        s = input()
        l, r = -1, -1
        for i in range(n):
            if s[i] == '1':
                if l == -1:
                    l = i
                r = i

        if l == -1:
            print(n)
        else:
            print(2 * max(r + 1, n - l))

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

    return 0

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1244/D:
You are given a tree consisting of $n$ vertices. A tree is an undirected connected acyclic graph. [Image] Example of a tree.

You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.

You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples $(x, y, z)$ such that $x \neq y, y \neq z, x \neq z$, $x$ is connected by an edge with $y$, and $y$ is connected by an edge with $z$. The colours of $x$, $y$ and $z$ should be pairwise distinct. Let's call a painting which meets this condition good.

You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.

-----Input-----

The first line contains one integer $n$ $(3 \le n \le 100\,000)$ — the number of vertices.

The second line contains a sequence of integers $c_{1, 1}, c_{1, 2}, \dots, c_{1, n}$ $(1 \le c_{1, i} \le 10^{9})$, where $c_{1, i}$ is the cost of painting the $i$-th vertex into the first color.

The third line contains a sequence of integers $c_{2, 1}, c_{2, 2}, \dots, c_{2, n}$ $(1 \le c_{2, i} \le 10^{9})$, where $c_{2, i}$ is the cost of painting the $i$-th vertex into the second color.

The fourth line contains a sequence of integers $c_{3, 1}, c_{3, 2}, \dots, c_{3, n}$ $(1 \le c_{3, i} \le 10^{9})$, where $c_{3, i}$ is the cost of painting the $i$-th vertex into the third color.

Then $(n - 1)$ lines follow, each containing two integers $u_j$ and $v_j$ $(1 \le u_j, v_j \le n, u_j \neq v_j)$ — the numbers of vertices connected by the $j$-th undirected edge. It is guaranteed that these edges denote a tree.

-----Output-----

If there is no good painting, print $-1$.

Otherwise, print the minimum cost of a good painting in the first line. In the second line print $n$ integers $b_1, b_2, \dots, b_n$ $(1 \le b_i \le 3)$, where the $i$-th integer should denote the color of the...

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

class Vertex:
    def __init__(self, index):
        self.index = index
        self.neighbours = []
        self.color = None

def main():

    n = int(input())
    cols = []
    cols.append([int(z) for z in input().split()])
    cols.append([int(z) for z in input().split()])
    cols.append([int(z) for z in input().split()])

    tree = [Vertex(i) for i in range(n)]

    for _ in range(n-1):
        u1, u2 = [int(p) - 1 for p in input().split()]
        tree[u1].neighbours.append(u2)
        tree[u2].neighbours.append(u1)

    if any(len(vertex.neighbours) > 2 for vertex in tree):
        print("-1")
        return

    root = None
    for vertex in tree:
        if len(vertex.neighbours) == 1:
            root = vertex
            break

    current_group = 1
    prev_vertex = root.index
    vertex = tree[root.neighbours[0]]
    groups = [[root.index], [], []]

    while True:
        is_leaf = len(vertex.neighbours) == 1
        groups[current_group].append(vertex.index)
        if is_leaf:
            break
        current_group = (current_group + 1) % 3
        next_vertex_index = sum(vertex.neighbours) - prev_vertex
        prev_vertex = vertex.index
        vertex = tree[next_vertex_index]

    best_col_per_group = None
    best_price = None
    for col_per_group in [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]:
        price = 0
        for group_id in range(len(groups)):
            group_col = col_per_group[group_id] - 1
            for node_id in groups[group_id]:
                price += cols[group_col][node_id]
        if best_price is None or price < best_price:
            best_price = price
            best_col_per_group = col_per_group

    print(best_price)
    for color, group in zip(best_col_per_group, groups):
        for node_id in group:
            tree[node_id].color = color

    for node in tree:
        print(node.color, end=' ')

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1244/E:
You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ integers.

You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.

Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than $k$ times.

-----Input-----

The first line contains two integers $n$ and $k$ $(2 \le n \le 10^{5}, 1 \le k \le 10^{14})$ — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively.

The second line contains a sequence of integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^{9})$.

-----Output-----

Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than $k$ times.

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

Output
2

Input
3 10
100 100 100

Output
0

Input
10 9
4 5 5 7 5 4 5 2 4 3

Output
1

-----Note-----

In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes $[3, 3, 5, 5]$, and the difference between maximum and minimum is $2$. You still can perform one operation after that, but it's useless since you can't make the answer less than $2$.

In the second example all elements are already equal, so you may get $0$ as the answer even without applying any operations.

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

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

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

S=sorted(set(A))

if len(S)==1:
    print(0)
    return

MIN0=0
MIN1=1
MAX0=-1
MAX1=-2

C=Counter(A)

while k and S[MIN0]!=S[MAX0]:

    if C[S[MIN0]]<=C[S[MAX0]] and k>=C[S[MIN0]]:

        if k>=(S[MIN1]-S[MIN0])*C[S[MIN0]]:

            k-=(S[MIN1]-S[MIN0])*C[S[MIN0]]
            C[S[MIN1]]+=C[S[MIN0]]
            del(C[S[MIN0]])
            MIN0+=1
            MIN1+=1

        else:
            print(S[MAX0]-(S[MIN0]+k//C[S[MIN0]]))
            return

    elif C[S[MAX0]]<=C[S[MIN0]] and k>=C[S[MAX0]]:

        if k>=(S[MAX0]-S[MAX1])*C[S[MAX0]]:

            k-=(S[MAX0]-S[MAX1])*C[S[MAX0]]
            C[S[MAX1]]+=C[S[MAX0]]
            del(C[S[MAX0]])
            MAX0-=1
            MAX1-=1

        else:
            print((S[MAX0]-k//C[S[MAX0]])-S[MIN0])
            return

    else:
        break

print(S[MAX0]-S[MIN0])


I found an interesting problem on https://codeforces.com/problemset/problem/1244/F:
There are $n$ chips arranged in a circle, numbered from $1$ to $n$.

Initially each chip has black or white color. Then $k$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $i$, three chips are considered: chip $i$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $i$ becomes white. Otherwise, the chip $i$ becomes black.

Note that for each $i$ from $2$ to $(n - 1)$ two neighbouring chips have numbers $(i - 1)$ and $(i + 1)$. The neighbours for the chip $i = 1$ are $n$ and $2$. The neighbours of $i = n$ are $(n - 1)$ and $1$.

The following picture describes one iteration with $n = 6$. The chips $1$, $3$ and $4$ are initially black, and the chips $2$, $5$ and $6$ are white. After the iteration $2$, $3$ and $4$ become black, and $1$, $5$ and $6$ become white.

 [Image]

Your task is to determine the color of each chip after $k$ iterations.

-----Input-----

The first line contains two integers $n$ and $k$ $(3 \le n \le 200\,000, 1 \le k \le 10^{9})$ — the number of chips and the number of iterations, respectively.

The second line contains a string consisting of $n$ characters "W" and "B". If the $i$-th character is "W", then the $i$-th chip is white initially. If the $i$-th character is "B", then the $i$-th chip is black initially.

-----Output-----

Print a string consisting of $n$ characters "W" and "B". If after $k$ iterations the $i$-th chip is white, then the $i$-th character should be "W". Otherwise the $i$-th character should be "B".

-----Examples-----
Input
6 1
BWBBWW

Output
WBBBWW

Input
7 3
WBWBWBW

Output
WWWWWWW

Input
6 4
BWBWBW

Output
BWBWBW

-----Note-----

The first example is described in the statement.

The second example: "WBWBWBW" $\rightarrow$ "WWBWBWW" $\rightarrow$ "WWWBWWW" $\rightarrow$ "WWWWWWW". So all chips become white.

The third example: "BWBWBW" $\rightarrow$ "WBWBWB" $\rightarrow$ "BWBWBW"...

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

rev = {'B': 'W', 'W': 'B'}

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

if all([a[0] == x for x in a]):
	print(''.join(a))
	return

f = [i for i in range(n)]
c = [1 for i in range(n)]

def getF(u):
	if f[u] == u:
		return u
	if f[f[u]] == f[u]:
		return f[u]
	f[u] = getF(f[u])
	return f[u]

def uniF(u, v):
	u, v = list(map(getF, (u, v)))
	if u == v:
		return
	f[u] = v
	c[v] += c[u]

for i in range(n):
	if a[i] == a[(i - 1) % n]:
		uniF(i, (i - 1) % n)
	if a[i] == a[(i + 1) % n]:
		uniF(i, (i + 1) % n)

p = []

for i in range(n):
	if getF(i) == i and c[i] > 1:
		p.append(i)

if len(p) == 0:
	if k % 2:
		a = list(map(rev.__getitem__, a))
	print(''.join(a))
	return

for i in range(len(p)):
	u = p[i]
	while a[(u + 1) % n] == a[p[i]]:
		u = (u + 1) % n
	v = p[(i + 1) % len(p)]
	while a[(v - 1) % n] == a[p[(i + 1) % len(p)]]:
		v = (v - 1) % n
	if v < u:
		v += n
	l = v - u - 1
	if 2 * k >= l:
		for i in range(u, u + l // 2 + 1):
			a[i % n] = a[u]
		for i in range(u + l // 2 + 1, v):
			a[i % n] = a[v % n]
	else:
		for i in range(u + 1, u + k + 1):
			a[i % n] = a[u]
		for i in range(v - k, v):
			a[i % n] = a[v % n]
		for i in range(u + k + 1, v - k):
			a[i % n] = rev[a[(i - 1) % n]]

print(''.join(a))


I found an interesting problem on https://codeforces.com/problemset/problem/1245/A:
Consider the set of all nonnegative integers: ${0, 1, 2, \dots}$. Given two integers $a$ and $b$ ($1 \le a, b \le 10^4$). We paint all the numbers in increasing number first we paint $0$, then we paint $1$, then $2$ and so on.

Each number is painted white or black. We paint a number $i$ according to the following rules:   if $i = 0$, it is colored white;   if $i \ge a$ and $i - a$ is colored white, $i$ is also colored white;   if $i \ge b$ and $i - b$ is colored white, $i$ is also colored white;   if $i$ is still not colored white, it is colored black.

In this way, each nonnegative integer gets one of two colors.

For example, if $a=3$, $b=5$, then the colors of the numbers (in the order from $0$) are: white ($0$), black ($1$), black ($2$), white ($3$), black ($4$), white ($5$), white ($6$), black ($7$), white ($8$), white ($9$), ...

Note that:   It is possible that there are infinitely many nonnegative integers colored black. For example, if $a = 10$ and $b = 10$, then only $0, 10, 20, 30$ and any other nonnegative integers that end in $0$ when written in base 10 are white. The other integers are colored black.   It is also possible that there are only finitely many nonnegative integers colored black. For example, when $a = 1$ and $b = 10$, then there is no nonnegative integer colored black at all.

Your task is to determine whether or not the number of nonnegative integers colored black is infinite.

If there are infinitely many nonnegative integers colored black, simply print a line containing "Infinite" (without the quotes). Otherwise, print "Finite" (without the quotes).

-----Input-----

The first line of input contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases in the input. Then $t$ lines follow, each line contains two space-separated integers $a$ and $b$ ($1 \le a, b \le 10^4$).

-----Output-----

For each test case, print one line containing either "Infinite" or "Finite" (without the quotes). Output is case-insensitive (i.e. "infinite", "inFiNite" or "finiTE" are all...

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

def gcd(a, b):
    return a if b == 0 else gcd(b, a % b)

for _ in range(int(input())):
    a, b = list(map(int, input().split()))
    if gcd(a, b) == 1:
        print("Finite")
    else:
        print("Infinite")


I found an interesting problem on https://codeforces.com/problemset/problem/1245/B:
Let $n$ be a positive integer. Let $a, b, c$ be nonnegative integers such that $a + b + c = n$.

Alice and Bob are gonna play rock-paper-scissors $n$ times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock $a$ times, paper $b$ times, and scissors $c$ times.

Alice wins if she beats Bob in at least $\lceil \frac{n}{2} \rceil$ ($\frac{n}{2}$ rounded up to the nearest integer) hands, otherwise Alice loses.

Note that in rock-paper-scissors:

  rock beats scissors;  paper beats rock;  scissors beat paper.

The task is, given the sequence of hands that Bob will play, and the numbers $a, b, c$, determine whether or not Alice can win. And if so, find any possible sequence of hands that Alice can use to win.

If there are multiple answers, print any of them.

-----Input-----

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

Then, $t$ testcases follow, each consisting of three lines:   The first line contains a single integer $n$ ($1 \le n \le 100$).  The second line contains three integers, $a, b, c$ ($0 \le a, b, c \le n$). It is guaranteed that $a + b + c = n$.  The third line contains a string $s$ of length $n$. $s$ is made up of only 'R', 'P', and 'S'. The $i$-th character is 'R' if for his $i$-th Bob plays rock, 'P' if paper, and 'S' if scissors.

-----Output-----

For each testcase:   If Alice cannot win, print "NO" (without the quotes).  Otherwise, print "YES" (without the quotes). Also, print a string $t$ of length $n$ made up of only 'R', 'P', and 'S' — a sequence of hands that Alice can use to win. $t$ must contain exactly $a$ 'R's, $b$ 'P's, and $c$ 'S's.  If there are multiple answers, print any of them.

The "YES" / "NO" part of the output is case-insensitive (i.e. "yEs", "no" or "YEs" are all valid answers). Note that 'R', 'P' and 'S' are case-sensitive.

-----Example-----
Input
2
3
1 1 1
RPS
3
3 0 0
RPS

Output
YES
PSR
NO

-----Note-----

In the first testcase, in the first hand, Alice plays paper and Bob plays...

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

import sys
input = sys.stdin.readline

t=int(input())

for testcases in range(t):
    n=int(input())
    a,b,c=list(map(int,input().split()))
    B=input().strip()

    R=B.count("R")
    P=B.count("P")
    S=B.count("S")

    if min(b,R)+min(c,P)+min(a,S)>=n/2:
        print("YES")
    else:
        print("NO")
        continue

    ANS=[0]*n

    R0=min(a,S)
    P0=min(b,R)
    S0=min(c,P)

    R1=a-R0
    P1=b-P0
    S1=c-S0

    for i in range(n):
        if B[i]=="S" and R0>0:
            ANS[i]="R"
            R0-=1
        elif B[i]=="R" and P0>0:
            ANS[i]="P"
            P0-=1
        elif B[i]=="P" and S0>0:
            ANS[i]="S"
            S0-=1

    for i in range(n):
        if ANS[i]==0:
            if R1>0:
                R1-=1
                ANS[i]="R"

            elif P1>0:
                P1-=1
                ANS[i]="P"

            else:
                S1-=1
                ANS[i]="S"

    print("".join(ANS))


I found an interesting problem on https://codeforces.com/problemset/problem/1245/C:
Constanze is the smartest girl in her village but she has bad eyesight.

One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe "code" onto the paper. Thanks to this machine, she can finally write messages without using her glasses.

However, her dumb friend Akko decided to play a prank on her. Akko tinkered with the machine so that if you pronounce 'w', it will inscribe "uu" instead of "w", and if you pronounce 'm', it will inscribe "nn" instead of "m"! Since Constanze had bad eyesight, she was not able to realize what Akko did.

The rest of the letters behave the same as before: if you pronounce any letter besides 'w' and 'm', the machine will just inscribe it onto a piece of paper.

The next day, I received a letter in my mailbox. I can't understand it so I think it's either just some gibberish from Akko, or Constanze made it using her machine. But since I know what Akko did, I can just list down all possible strings that Constanze's machine would have turned into the message I got and see if anything makes sense.

But I need to know how much paper I will need, and that's why I'm asking you for help. Tell me the number of strings that Constanze's machine would've turned into the message I got.

But since this number can be quite large, tell me instead its remainder when divided by $10^9+7$.

If there are no strings that Constanze's machine would've turned into the message I got, then print $0$.

-----Input-----

Input consists of a single line containing a string $s$ ($1 \leq |s| \leq 10^5$) — the received message. $s$ contains only lowercase Latin letters.

-----Output-----

Print a single integer — the number of strings that Constanze's machine would've turned into the message $s$, modulo...

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

"""T=int(input())
for _ in range(0,T):
    N=int(input())
    a,b=map(int,input().split())
    s=input()
    s=[int(x) for x in input().split()]
    for i in range(0,len(s)):
        a,b=map(int,input().split())"""

MOD=1000000007
s=input()
flag=0
for i in range(0,len(s)):
    if(s[i]=='w' or s[i]=='m'):
        flag=1
        break

if(flag==0):
    c=1
    g=[]
    for i in range(1,len(s)):
        if(s[i]==s[i-1]):
            c=(c+1)%MOD
        else:
            if(s[i-1]=='n' or s[i-1]=='u'):
                g.append(c)
            c=1

    if(s[-1]=='n' or s[-1]=='u'):
        g.append(c)
    #print(g)
    dp=[0,1,2,3]
    ggg=10
    if(len(g)>0):
        ggg=max(g)+10
    else:
        ggg=10
    for i in range(ggg):
        dp.append((dp[-1]+dp[-2])%MOD)

    ans=1
    for i in range(0,len(g)):
        ans=(ans*(dp[g[i]%MOD])%MOD)%MOD

    print(ans%MOD)
else:
    print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/1245/D:
Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows:

There are $n$ new cities located in Prefecture X. Cities are numbered from $1$ to $n$. City $i$ is located $x_i$ km North of the shrine and $y_i$ km East of the shrine. It is possible that $(x_i, y_i) = (x_j, y_j)$ even when $i \ne j$.

Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections.

    Building a power station in City $i$ will cost $c_i$ yen;     Making a connection between City $i$ and City $j$ will cost $k_i + k_j$ yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City $i$ and City $j$ are connected by a wire, the wire will go through any shortest path from City $i$ to City $j$. Thus, the length of the wire if City $i$ and City $j$ are connected is $|x_i - x_j| + |y_i - y_j|$ km.

Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help.

And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made.

If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.

-----Input-----

First line of input contains a single integer $n$ ($1 \leq n \leq 2000$) — the number of cities.

Then,...

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

import math

n = int(input())
cityNo=[0]*n
for i in range(n):
	cityNo[i]=list(map(int,input().split()))
cost=list(map(int,input().split()))
ks  =list(map(int,input().split()))

powerStation=[0]*n

totalCost=0

req_Powerstation=[]
notReq_Powerstation=[]
totalCost=0
established={}
updated=[-1]*n

for j in range(n):

	city=-1
	mini=9999999999999999
	for i in range(n):
		if mini>cost[i] and i not in established:
			city=i
			mini=cost[i]
	if updated[city]==-1:
		req_Powerstation.append(city+1)
	else:
		notReq_Powerstation.append([city+1,updated[city]+1])
	totalCost+=cost[city]
	established[city]=1

	for i in range(n):

		cost_From_City = (ks[i]+ks[city])*(abs(cityNo[i][0]-cityNo[city][0])+abs(cityNo[i][1]-cityNo[city][1]))

		if cost_From_City<cost[i]:
			cost[i]=cost_From_City
			updated[i]=city

		# print(updated)
print(totalCost)
print(len(req_Powerstation))
print(*req_Powerstation)
print(len(notReq_Powerstation))
for i in range(len(notReq_Powerstation)):
	print(*notReq_Powerstation[i])


I found an interesting problem on https://codeforces.com/problemset/problem/1245/E:
Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing "Cat's Cradle" so now she wants to try a different game — "Snakes and Ladders". Unfortunately, she already killed all the snakes, so there are only ladders left now.

The game is played on a $10 \times 10$ board as follows:  At the beginning of the game, the player is at the bottom left square.  The objective of the game is for the player to reach the Goal (the top left square) by following the path and climbing vertical ladders. Once the player reaches the Goal, the game ends.  The path is as follows: if a square is not the end of its row, it leads to the square next to it along the direction of its row; if a square is the end of its row, it leads to the square above it. The direction of a row is determined as follows: the direction of the bottom row is to the right; the direction of any other row is opposite the direction of the row below it. See Notes section for visualization of path.  During each turn, the player rolls a standard six-sided dice. Suppose that the number shown on the dice is $r$. If the Goal is less than $r$ squares away on the path, the player doesn't move (but the turn is performed). Otherwise, the player advances exactly $r$ squares along the path and then stops. If the player stops on a square with the bottom of a ladder, the player chooses whether or not to climb up that ladder. If she chooses not to climb, then she stays in that square for the beginning of the next turn.  Some squares have a ladder in them. Ladders are only placed vertically — each one leads to the same square of some of the upper rows. In order for the player to climb up a ladder, after rolling the dice, she must stop at the square containing the bottom of the ladder. After using the ladder, the player will end up in the square containing the top of the ladder. She cannot leave the ladder in the middle of climbing. And if the...

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

board = []
for i in range(10):
    board.append([int(i) for i in input().split()])

def next_squares(x, y):
    current_dir = 1 if x%2 else -1
    # print(x, y, current_dir)
    res = []
    for _ in range(6):
        nx, ny = x, y + current_dir
        if ny < 0 or ny == 10:
            nx, ny = x - 1, y
            current_dir *= -1
            if nx == -1: break
        x, y = nx, ny
        res.append([x, y])
    # print(x, y, res)
    return res

from functools import lru_cache

@lru_cache(None)
def dp(i, j, can_climb):
    if i == j == 0: return 0
    expected = []
    for x, y in next_squares(i, j):
        expected.append(dp(x, y, True))
    score = sum(expected) / len(expected) + (6 / len(expected))
    # print(i, j)
    if can_climb and board[i][j]: return min(score, dp(i - board[i][j], j, False))
    return score

print(dp(9, 0, True))


I found an interesting problem on https://codeforces.com/problemset/problem/1248/A:
DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew $n$ distinct lines, given by equations $y = x + p_i$ for some distinct $p_1, p_2, \ldots, p_n$.

Then JLS drew on the same paper sheet $m$ distinct lines given by equations $y = -x + q_i$ for some distinct $q_1, q_2, \ldots, q_m$.

DLS and JLS are interested in counting how many line pairs have integer intersection points, i.e. points with both coordinates that are integers. Unfortunately, the lesson will end up soon, so DLS and JLS are asking for your help.

-----Input-----

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

The first line of a test case contains an integer $n$ ($1 \le n \le 10^5$), the number of lines drawn by DLS.

The second line of a test case contains $n$ distinct integers $p_i$ ($0 \le p_i \le 10^9$) describing the lines drawn by DLS. The integer $p_i$ describes a line given by the equation $y = x + p_i$.

The third line of a test case contains an integer $m$ ($1 \le m \le 10^5$), the number of lines drawn by JLS.

The fourth line of a test case contains $m$ distinct integers $q_i$ ($0 \le q_i \le 10^9$) describing the lines drawn by JLS. The integer $q_i$ describes a line given by the equation $y = -x + q_i$.

The sum of the values of $n$ over all test cases in the input does not exceed $10^5$. Similarly, the sum of the values of $m$ over all test cases in the input does not exceed $10^5$.

In hacks it is allowed to use only one test case in the input, so $t=1$ should be satisfied.

-----Output-----

For each test case in the input print a single integer — the number of line pairs with integer intersection points.

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

Output
3
1
0

-----Note-----

The picture shows the lines from the first test case of the example. Black circles denote intersection points with integer coordinates. [Image]

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

t=int(input())
for nt in range(t):
	n=int(input())
	ln=list(map(int,input().split()))
	m=int(input())
	lm=list(map(int,input().split()))
	lne,lno,lme,lmo=0,0,0,0
	for i in ln:
		if i%2==0:
			lne+=1
		else:
			lno+=1
	for i in lm:
		if i%2==0:
			lme+=1
		else:
			lmo+=1
	print (lne*lme+lno*lmo)


I found an interesting problem on https://codeforces.com/problemset/problem/1248/B:
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.

The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $(0, 0)$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $OX$ or $OY$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.

Alexey wants to make a polyline in such a way that its end is as far as possible from $(0, 0)$. Please help him to grow the tree this way.

Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 100\,000$) — the number of sticks Alexey got as a present.

The second line contains $n$ integers $a_1, \ldots, a_n$ ($1 \le a_i \le 10\,000$) — the lengths of the sticks.

-----Output-----

Print one integer — the square of the largest possible distance from $(0, 0)$ to the tree end.

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

Output
26
Input
4
1 1 2 2

Output
20

-----Note-----

The following pictures show optimal trees for example tests. The squared distance in the first example equals $5 \cdot 5 + 1 \cdot 1 = 26$, and in the second example $4 \cdot 4 + 2 \cdot 2 = 20$.

 [Image]

 [Image]

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

n=int(input())
a=list(map(int,input().split()))
a=sorted(a)
x,y=0,0
for i in range(n//2):
    x += a[i]
for i in range(n//2,n):
    y += a[i]
print(pow(x,2)+pow(y,2))


I found an interesting problem on https://codeforces.com/problemset/problem/1248/D1:
This is an easier version of the problem. In this version, $n \le 500$.

Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.

To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.

We remind that bracket sequence $s$ is called correct if:   $s$ is empty;  $s$ is equal to "($t$)", where $t$ is correct bracket sequence;  $s$ is equal to $t_1 t_2$, i.e. concatenation of $t_1$ and $t_2$, where $t_1$ and $t_2$ are correct bracket sequences.

For example, "(()())", "()" are correct, while ")(" and "())" are not.

The cyclical shift of the string $s$ of length $n$ by $k$ ($0 \leq k < n$) is a string formed by a concatenation of the last $k$ symbols of the string $s$ with the first $n - k$ symbols of string $s$. For example, the cyclical shift of string "(())()" by $2$ equals "()(())".

Cyclical shifts $i$ and $j$ are considered different, if $i \ne j$.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 500$), the length of the string.

The second line contains a string, consisting of exactly $n$ characters, where each of the characters is either "(" or ")".

-----Output-----

The first line should contain a single integer — the largest beauty of the string, which can be achieved by swapping some two characters.

The second line should contain integers $l$ and $r$ ($1 \leq l, r \leq n$) — the indices of two characters, which should be swapped in order to maximize the string's beauty.

In case there are several possible swaps, print...

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

n = int(input())
s = list(input())
r = -1
l = n
root = []

def find_right(node):
    nonlocal l,r,s,n
    while n:
        r += 1
        n -= 1
        if s[r] == '(':
            node[2].append([r,-1,[]])
            find_right(node[2][-1])
        else:
            node[1] = r
            return True
    return False

def find_left(node):
    nonlocal l,r,s,n
    while n:
        l -= 1
        n -= 1
        if s[l] == ')':
            node[2].append([-1,l,[]])
            find_left(node[2][-1])
        else:
            node[0] = l
            return True
    return False

is_correct = True
while n:
    r += 1
    n -= 1
    if s[r]=='(':
        root.append([r,-1,[]])
        is_correct &= find_right(root[-1])
    else:
        root = [[-1,r,root]]
        is_correct &= find_left(root[-1])

sol = [[0,1,1]]
if is_correct:
    sol.append([len(root), 1, 1])
    for child in root:
        sol.append([len(child[2])+1, child[0]+1, child[1]+1])
        for gr_child in child[2]:
            if len(gr_child[2]):
                sol.append([len(root)+len(gr_child[2])+1, gr_child[0]+1, gr_child[1]+1])

print('%d\n%d %d'%tuple(max(sol)))


I found an interesting problem on https://codeforces.com/problemset/problem/1248/E:
There are $n$ seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from $1$ to $n$ from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat $i$ ($1 \leq i \leq n$) will decide to go for boiled water at minute $t_i$.

Tank with a boiled water is located to the left of the $1$-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly $p$ minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small.

Nobody likes to stand in a queue. So when the passenger occupying the $i$-th seat wants to go for a boiled water, he will first take a look on all seats from $1$ to $i - 1$. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than $i$ are busy, he will go to the tank.

There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment.

Your goal is to find for each passenger, when he will receive the boiled water for his noodles.

-----Input-----

The first line contains integers $n$ and $p$ ($1 \leq n \leq 100\,000$, $1 \leq p \leq 10^9$) — the number of people and the amount of time one person uses the tank.

The second line contains $n$ integers $t_1, t_2, \dots, t_n$ ($0 \leq t_i \leq 10^9$) — the moments when the corresponding passenger will go for the boiled water.

-----Output-----

Print $n$ integers, where $i$-th of them is the time moment the passenger on $i$-th seat will...

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__

from heapq import heappop, heappush, heapify
from collections import deque
class SWAG_Stack():
    def __init__(self, F):
        self.stack1 = deque()
        self.stack2 = deque()
        self.F = F
        self.len = 0

    def push(self, x):
        if self.stack2:
            self.stack2.append((x, self.F(self.stack2[-1][1], x)))
        else:
            self.stack2.append((x, x))
        self.len += 1

    def pop(self):
        if not self.stack1:
            while self.stack2:
                x, _ = self.stack2.pop()
                if self.stack1:
                    self.stack1.appendleft((x, self.F(x, self.stack1[0][1])))
                else:
                    self.stack1.appendleft((x, x))
        x, _ = self.stack1.popleft()
        self.len -= 1
        return x

    def sum_all(self):
        if self.stack1 and self.stack2:
            return self.F(self.stack1[0][1], self.stack2[-1][1])
        elif self.stack1:
            return self.stack1[0][1]
        elif self.stack2:
            return self.stack2[-1][1]
        else:
            return float("inf")

n,p = map(int, input().split())
t = list((j, i) for i,j in enumerate(map(int, input().split())))
heapify(t)

stack = SWAG_Stack(min)

heap = []
cur = 0
ans = [-1]*n
hoge = 0
# 今追加できるやつで最も小さいものを追加
# ここでなにもなかったら？
#   時間を変更する
# 次の時間までに追加できるものを追加
# 清算
while hoge != n:
    if heap and stack.sum_all() > heap[0]:
        j = heappop(heap)
        stack.push(j)

    if stack.len==0 and t:
        cur = max(cur, t[0][0])

    while t and t[0][0] <= cur+p:
        ti, i = heappop(t)
        if ti == cur+p:
            # 後回し
            heappush(heap, i)
        else:
            # いま追加できるか確認
            if stack.sum_all() > i:
                stack.push(i)
            else:
                # 後回し
                heappush(heap, i)

    if stack.len:
        j = stack.pop()
        cur += p
        ans[j] = cur
        hoge += 1
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1249/A:
You are a coach of a group consisting of $n$ students. The $i$-th student has programming skill $a_i$. All students have distinct programming skills. You want to divide them into teams in such a way that:  No two students $i$ and $j$ such that $|a_i - a_j| = 1$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $1$);  the number of teams is the minimum possible.

You have to answer $q$ independent queries.

-----Input-----

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

The first line of the query contains one integer $n$ ($1 \le n \le 100$) — the number of students in the query. The second line of the query contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$, all $a_i$ are distinct), where $a_i$ is the programming skill of the $i$-th student.

-----Output-----

For each query, print the answer on it — the minimum number of teams you can form if no two students $i$ and $j$ such that $|a_i - a_j| = 1$ may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than $1$)

-----Example-----
Input
4
4
2 10 1 20
2
3 6
5
2 3 4 99 100
1
42

Output
2
1
2
1

-----Note-----

In the first query of the example, there are $n=4$ students with the skills $a=[2, 10, 1, 20]$. There is only one restriction here: the $1$-st and the $3$-th students can't be in the same team (because of $|a_1 - a_3|=|2-1|=1$). It is possible to divide them into $2$ teams: for example, students $1$, $2$ and $4$ are in the first team and the student $3$ in the second team.

In the second query of the example, there are $n=2$ students with the skills $a=[3, 6]$. It is possible to compose just a single team containing both students.

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

q = int(input())
for i in range(q):
    n = int(input())
    a = [int(i) for i in input().split()]
    a.sort()
    f = False
    for i in range(n - 1):
        if a[i] - a[i + 1] == -1:
            print(2)
            f = True
            break
    if not f:
        print(1)


I found an interesting problem on https://codeforces.com/problemset/problem/1249/B1:
The only difference between easy and hard versions is constraints.

There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are distinct integers from $1$ to $n$ (i.e. $p$ is a permutation). The sequence $p$ doesn't change from day to day, it is fixed.

For example, if $n=6$ and $p=[4, 6, 1, 3, 5, 2]$ then at the end of the first day the book of the $1$-st kid will belong to the $4$-th kid, the $2$-nd kid will belong to the $6$-th kid and so on. At the end of the second day the book of the $1$-st kid will belong to the $3$-th kid, the $2$-nd kid will belong to the $2$-th kid and so on.

Your task is to determine the number of the day the book of the $i$-th child is returned back to him for the first time for every $i$ from $1$ to $n$.

Consider the following example: $p = [5, 1, 2, 4, 3]$. The book of the $1$-st kid will be passed to the following kids:  after the $1$-st day it will belong to the $5$-th kid,  after the $2$-nd day it will belong to the $3$-rd kid,  after the $3$-rd day it will belong to the $2$-nd kid,  after the $4$-th day it will belong to the $1$-st kid.

So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.

You have to answer $q$ independent queries.

-----Input-----

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

The first line of the query contains one integer $n$ ($1 \le n \le 200$) — the number of kids in the query. The second line of the query contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ are distinct, i.e. $p$ is a permutation), where $p_i$ is the kid which will get the book of the $i$-th kid.

-----Output-----

For each query, print the answer on it: $n$ integers $a_1, a_2, \dots,...

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

q = int(input())
for i in range(q):
    a = int(input())
    cycle = [1 for i in range(a)]

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

    for indice, j in enumerate(tab):
        var = indice +1

        while tab[var-1] != indice+1:
            var = tab[var-1]
            cycle[indice] += 1

    print(*cycle)


I found an interesting problem on https://codeforces.com/problemset/problem/1249/B2:
The only difference between easy and hard versions is constraints.

There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are distinct integers from $1$ to $n$ (i.e. $p$ is a permutation). The sequence $p$ doesn't change from day to day, it is fixed.

For example, if $n=6$ and $p=[4, 6, 1, 3, 5, 2]$ then at the end of the first day the book of the $1$-st kid will belong to the $4$-th kid, the $2$-nd kid will belong to the $6$-th kid and so on. At the end of the second day the book of the $1$-st kid will belong to the $3$-th kid, the $2$-nd kid will belong to the $2$-th kid and so on.

Your task is to determine the number of the day the book of the $i$-th child is returned back to him for the first time for every $i$ from $1$ to $n$.

Consider the following example: $p = [5, 1, 2, 4, 3]$. The book of the $1$-st kid will be passed to the following kids:  after the $1$-st day it will belong to the $5$-th kid,  after the $2$-nd day it will belong to the $3$-rd kid,  after the $3$-rd day it will belong to the $2$-nd kid,  after the $4$-th day it will belong to the $1$-st kid.

So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.

You have to answer $q$ independent queries.

-----Input-----

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

The first line of the query contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of kids in the query. The second line of the query contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ are distinct, i.e. $p$ is a permutation), where $p_i$ is the kid which will get the book of the $i$-th kid.

It is guaranteed that $\sum n \le 2 \cdot 10^5$ (sum of $n$ over all queries does...

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

import sys
input = sys.stdin.readline

q=int(input())

def find(x):
    while Group[x] != x:
        x=Group[x]
    return x

def Union(x,y):
    if find(x) != find(y):
        Group[find(y)]=Group[find(x)]=min(find(y),find(x))

for testcases in range(q):
    n=int(input())
    P=list(map(int,input().split()))

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

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

    G=[find(i) for i in range(n)]

    count=[0]*n

    for g in G:
        count[g]+=1

    for i in range(n):
        print(count[G[i]],end=" ")
    print()


I found an interesting problem on https://codeforces.com/problemset/problem/1249/C1:
The only difference between easy and hard versions is the maximum value of $n$.

You are given a positive integer number $n$. You really love good numbers so you want to find the smallest good number greater than or equal to $n$.

The positive integer is called good if it can be represented as a sum of distinct powers of $3$ (i.e. no duplicates of powers of $3$ are allowed).

For example:  $30$ is a good number: $30 = 3^3 + 3^1$,  $1$ is a good number: $1 = 3^0$,  $12$ is a good number: $12 = 3^2 + 3^1$,  but $2$ is not a good number: you can't represent it as a sum of distinct powers of $3$ ($2 = 3^0 + 3^0$),  $19$ is not a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representations $19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$ are invalid),  $20$ is also not a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representation $20 = 3^2 + 3^2 + 3^0 + 3^0$ is invalid).

Note, that there exist other representations of $19$ and $20$ as sums of powers of $3$ but none of them consists of distinct powers of $3$.

For the given positive integer $n$ find such smallest $m$ ($n \le m$) that $m$ is a good number.

You have to answer $q$ independent queries.

-----Input-----

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

The only line of the query contains one integer $n$ ($1 \le n \le 10^4$).

-----Output-----

For each query, print such smallest integer $m$ (where $n \le m$) that $m$ is a good number.

-----Example-----
Input
7
1
2
6
13
14
3620
10000

Output
1
3
9
13
27
6561
19683

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

import bisect

t = int(input())

tmp_ans = [0]*100
for i in range(100):
    tmp_ans[i] = 3**i

ans = []
for i in range(18):
    tmp = ans[0:]
    for j in tmp:
        ans.append(j + tmp_ans[i])
    ans.append(tmp_ans[i])
ans = sorted(ans)

for _ in range(t):
    n = int(input())
    ind = bisect.bisect_left(ans, n)
    print(ans[ind])


I found an interesting problem on https://codeforces.com/problemset/problem/1249/C2:
The only difference between easy and hard versions is the maximum value of $n$.

You are given a positive integer number $n$. You really love good numbers so you want to find the smallest good number greater than or equal to $n$.

The positive integer is called good if it can be represented as a sum of distinct powers of $3$ (i.e. no duplicates of powers of $3$ are allowed).

For example:

  $30$ is a good number: $30 = 3^3 + 3^1$,  $1$ is a good number: $1 = 3^0$,  $12$ is a good number: $12 = 3^2 + 3^1$,  but $2$ is not a good number: you can't represent it as a sum of distinct powers of $3$ ($2 = 3^0 + 3^0$),  $19$ is not a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representations $19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$ are invalid),  $20$ is also not a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representation $20 = 3^2 + 3^2 + 3^0 + 3^0$ is invalid).

Note, that there exist other representations of $19$ and $20$ as sums of powers of $3$ but none of them consists of distinct powers of $3$.

For the given positive integer $n$ find such smallest $m$ ($n \le m$) that $m$ is a good number.

You have to answer $q$ independent queries.

-----Input-----

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

The only line of the query contains one integer $n$ ($1 \le n \le 10^{18}$).

-----Output-----

For each query, print such smallest integer $m$ (where $n \le m$) that $m$ is a good number.

-----Example-----
Input
8
1
2
6
13
14
3620
10000
1000000000000000000

Output
1
3
9
13
27
6561
19683
1350851717672992089

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

#started 20 minutes late !

# print(len(str(3**36)))
arr=[]
for i in range(40):
    arr.append(3**i)
# print(arr)

n=int(input())
for i in range(n):
    sb=[0]*40
    a=int(input())
    x=a
    xx=a
    for j in range(39,-1,-1):
        if(a-arr[j]>=0):
            a-=arr[j]
            sb[j]=1
    # print(x-a,1)
    x=x-a
    # print(sb)
    if(a==0):
        print(x)
        continue
    for j in range(40):
        if(sb[j]==0):
            x=x+3**j
        # if(x>xx):
            break
        else:
            x=x-3**j
    print(x)
# print(3**8)


I found an interesting problem on https://codeforces.com/problemset/problem/1249/D1:
The only difference between easy and hard versions is constraints.

You are given $n$ segments on the coordinate axis $OX$. Segments can intersect, lie inside each other and even coincide. The $i$-th segment is $[l_i; r_i]$ ($l_i \le r_i$) and it covers all integer points $j$ such that $l_i \le j \le r_i$.

The integer point is called bad if it is covered by strictly more than $k$ segments.

Your task is to remove the minimum number of segments so that there are no bad points at all.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 200$) — the number of segments and the maximum number of segments by which each integer point can be covered.

The next $n$ lines contain segments. The $i$-th line contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le 200$) — the endpoints of the $i$-th segment.

-----Output-----

In the first line print one integer $m$ ($0 \le m \le n$) — the minimum number of segments you need to remove so that there are no bad points.

In the second line print $m$ distinct integers $p_1, p_2, \dots, p_m$ ($1 \le p_i \le n$) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.

-----Examples-----
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9

Output
3
1 4 7

Input
5 1
29 30
30 30
29 29
28 30
30 30

Output
3
1 2 4

Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3

Output
4
1 3 5 6

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

n, k = map(int, input().split())
s = []
for i in range(n):
    l, r = map(int, input().split())
    s.append([r, l, i]) # Greedy on largest right endpoint
s.sort()

ans = []
for i in range(201):
    a = 0
    u = []
    for tmp in s:
        if i <= tmp[0] and i >= tmp[1]:
            a += 1
            if a > k:
                u.append(tmp)
                ans.append(tmp[2] + 1)
    for tmp in u:
        s.remove(tmp)
print(len(ans))
print(' '.join(map(str, ans)))


I found an interesting problem on https://codeforces.com/problemset/problem/1249/D2:
The only difference between easy and hard versions is constraints.

You are given $n$ segments on the coordinate axis $OX$. Segments can intersect, lie inside each other and even coincide. The $i$-th segment is $[l_i; r_i]$ ($l_i \le r_i$) and it covers all integer points $j$ such that $l_i \le j \le r_i$.

The integer point is called bad if it is covered by strictly more than $k$ segments.

Your task is to remove the minimum number of segments so that there are no bad points at all.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the number of segments and the maximum number of segments by which each integer point can be covered.

The next $n$ lines contain segments. The $i$-th line contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le 2 \cdot 10^5$) — the endpoints of the $i$-th segment.

-----Output-----

In the first line print one integer $m$ ($0 \le m \le n$) — the minimum number of segments you need to remove so that there are no bad points.

In the second line print $m$ distinct integers $p_1, p_2, \dots, p_m$ ($1 \le p_i \le n$) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.

-----Examples-----
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9

Output
3
4 6 7

Input
5 1
29 30
30 30
29 29
28 30
30 30

Output
3
1 4 5

Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3

Output
4
1 3 5 6

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

import sys
input = sys.stdin.readline

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

S=[tuple(map(int,input().split()))+(i+1,) for i in range(n)]
S.sort()

segtemp=2*10**5
seg_el=1<<((segtemp).bit_length())# Segment treeの台の要素数
SEG=[0]*(2*seg_el)# 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化

def getvalue(n,seg_el):# 一点の値を取得
    i=n+seg_el
    ANS=0

    ANS+=SEG[i]
    i>>=1# 子ノードへ

    while i!=0:
        ANS+=SEG[i]
        i>>=1

    return ANS

def updates(l,r,x):# 区間[l,r)のminを更新.
    L=l+seg_el
    R=r+seg_el

    while L<R:
        if L & 1:
            SEG[L]+=x
            L+=1

        if R & 1:
            R-=1
            SEG[R]+=x
        L>>=1
        R>>=1

ind=0
SH=[]
ANS=[]
import heapq

for point in range(segtemp):
    while ind<n and S[ind][0]<=point:
        l,r,x=S[ind]
        updates(l,r+1,1)
        ind+=1

        heapq.heappush(SH,(-r,l,x))

    #print(getvalue(point,seg_el),SH)

    while getvalue(point,seg_el)>k:
        r,l,x=heapq.heappop(SH)
        r=-r
        ANS.append(x)
        updates(l,r+1,-1)

    #print(point,ANS,getvalue(point,seg_el))

print(len(ANS))
print(*ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1249/E:
You are planning to buy an apartment in a $n$-floor building. The floors are numbered from $1$ to $n$ from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor.

Let:  $a_i$ for all $i$ from $1$ to $n-1$ be the time required to go from the $i$-th floor to the $(i+1)$-th one (and from the $(i+1)$-th to the $i$-th as well) using the stairs;  $b_i$ for all $i$ from $1$ to $n-1$ be the time required to go from the $i$-th floor to the $(i+1)$-th one (and from the $(i+1)$-th to the $i$-th as well) using the elevator, also there is a value $c$ — time overhead for elevator usage (you need to wait for it, the elevator doors are too slow!).

In one move, you can go from the floor you are staying at $x$ to any floor $y$ ($x \ne y$) in two different ways:  If you are using the stairs, just sum up the corresponding values of $a_i$. Formally, it will take $\sum\limits_{i=min(x, y)}^{max(x, y) - 1} a_i$ time units.  If you are using the elevator, just sum up $c$ and the corresponding values of $b_i$. Formally, it will take $c + \sum\limits_{i=min(x, y)}^{max(x, y) - 1} b_i$ time units.

You can perform as many moves as you want (possibly zero).

So your task is for each $i$ to determine the minimum total time it takes to reach the $i$-th floor from the $1$-st (bottom) floor.

-----Input-----

The first line of the input contains two integers $n$ and $c$ ($2 \le n \le 2 \cdot 10^5, 1 \le c \le 1000$) — the number of floors in the building and the time overhead for the elevator rides.

The second line of the input contains $n - 1$ integers $a_1, a_2, \dots, a_{n-1}$ ($1 \le a_i \le 1000$), where $a_i$ is the time required to go from the $i$-th floor to the $(i+1)$-th one (and from the $(i+1)$-th to the $i$-th as well) using the stairs.

The third line of the input contains $n - 1$ integers $b_1, b_2, \dots, b_{n-1}$ ($1 \le b_i \le 1000$), where $b_i$ is the time required to go from the $i$-th floor to the $(i+1)$-th one (and from the...

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

import sys
input = sys.stdin.readline

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

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

TIME0=[0]*n
TIME1=[0]*n

TIME1[0]=c

for i in range(1,n):
    TIME0[i]=min(TIME0[i-1],TIME1[i-1])+A[i-1]
    TIME1[i]=min(TIME0[i-1]+c+B[i-1],TIME1[i-1]+B[i-1])

ANS=[min(TIME0[i],TIME1[i]) for i in range(n)]
print(*ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1249/F:
You are given a tree, which consists of $n$ vertices. Recall that a tree is a connected undirected graph without cycles.  [Image] Example of a tree.

Vertices are numbered from $1$ to $n$. All vertices have weights, the weight of the vertex $v$ is $a_v$.

Recall that the distance between two vertices in the tree is the number of edges on a simple path between them.

Your task is to find the subset of vertices with the maximum total weight (the weight of the subset is the sum of weights of all vertices in it) such that there is no pair of vertices with the distance $k$ or less between them in this subset.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 200$) — the number of vertices in the tree and the distance restriction, respectively.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^5$), where $a_i$ is the weight of the vertex $i$.

The next $n - 1$ lines contain edges of the tree. Edge $i$ is denoted by two integers $u_i$ and $v_i$ — the labels of vertices it connects ($1 \le u_i, v_i \le n$, $u_i \ne v_i$).

It is guaranteed that the given edges form a tree.

-----Output-----

Print one integer — the maximum total weight of the subset in which all pairs of vertices have distance more than $k$.

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

Output
11

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

Output
4

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

n, k = map(int, input().split())
a = list(map(int, input().split()))
g = {}

def dfs(v, p=-1):
	c = [dfs(child, v) for child in g.get(v, set()) - {p}]
	c.sort(key=len, reverse=True)
	r = []
	i = 0
	while c:
		if i >= len(c[-1]):
			c.pop()
		else:
			o = max(i, k - i - 1)
			s = q = 0
			for x in c:
				if len(x) <= o:
					q = max(q, x[i])
				else:
					s += x[o]
					q = max(q, x[i] - x[o])
			r.append(q + s)
			i += 1
	r.append(0)
	for i in range(len(r) - 1, 0, -1):
		r[i - 1] = max(r[i - 1], r[i])
	while len(r) > 1 and r[-2] == 0:
		r.pop()
	o = (r[k] if k < len(r) else 0) + a[v]
	r.insert(0, max(o, r[0]))
	return r

for _ in range(1, n):
	u, v = map(lambda x: int(x) - 1, input().split())
	g.setdefault(u, set()).add(v)
	g.setdefault(v, set()).add(u)

print(dfs(0)[0])


I found an interesting problem on https://codeforces.com/problemset/problem/1251/A:
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $26$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning.

To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $s$ appeared on the screen. When Polycarp presses a button with character $c$, one of the following events happened:

  if the button was working correctly, a character $c$ appeared at the end of the string Polycarp was typing;  if the button was malfunctioning, two characters $c$ appeared at the end of the string.

For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $\rightarrow$ abb $\rightarrow$ abba $\rightarrow$ abbac $\rightarrow$ abbaca $\rightarrow$ abbacabb $\rightarrow$ abbacabba.

You are given a string $s$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).

You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.

-----Input-----

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

Then the test cases follow. Each test case is represented by one line containing a string $s$ consisting of no less than $1$ and no more than $500$ lowercase Latin letters.

-----Output-----

For each test case, print one line containing a string $res$. The string $res$ should contain all characters which correspond to buttons that work correctly in alphabetical order, without any...

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

n = int(input())
for i in range(n):
	st = input()
	st += '#'
	k = len(st)
	lastch = '.'
	lastl = 0
	able = [False for i in range(256)]
	for j in range(k):
		if st[j] != lastch:
			if lastl % 2 == 1:
				able[ord(lastch)] = True
			lastl = 1
			lastch = st[j]
		else:
			lastl += 1
	for j in range(ord('a'),ord('z')+1):
		if able[j]:
			print(chr(j),end='')
	print()


I found an interesting problem on https://codeforces.com/problemset/problem/1251/B:
A palindrome is a string $t$ which reads the same backward as forward (formally, $t[i] = t[|t| + 1 - i]$ for all $i \in [1, |t|]$). Here $|t|$ denotes the length of a string $t$. For example, the strings 010, 1001 and 0 are palindromes.

You have $n$ binary strings $s_1, s_2, \dots, s_n$ (each $s_i$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.

Formally, in one move you:  choose four integer numbers $x, a, y, b$ such that $1 \le x, y \le n$ and $1 \le a \le |s_x|$ and $1 \le b \le |s_y|$ (where $x$ and $y$ are string indices and $a$ and $b$ are positions in strings $s_x$ and $s_y$ respectively),  swap (exchange) the characters $s_x[a]$ and $s_y[b]$.

What is the maximum number of strings you can make palindromic simultaneously?

-----Input-----

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

The first line on each test case contains single integer $n$ ($1 \le n \le 50$) — the number of binary strings you have.

Next $n$ lines contains binary strings $s_1, s_2, \dots, s_n$ — one per line. It's guaranteed that $1 \le |s_i| \le 50$ and all strings constist of zeroes and/or ones.

-----Output-----

Print $Q$ integers — one per test case. The $i$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $i$-th test case.

-----Example-----
Input
4
1
0
3
1110
100110
010101
2
11111
000001
2
001
11100111

Output
1
2
2
2

-----Note-----

In the first test case, $s_1$ is palindrome, so the answer is $1$.

In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $s_1 = \text{0110}$, $s_2 = \text{111111}$ and $s_3 = \text{010000}$.

In the third test case we can make both strings palindromic. For example, $s_1 = \text{11011}$...

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

import sys
from collections import Counter
input = sys.stdin.readline
sys.setrecursionlimit(100000)
def getN():
    return int(input())
def getList():
    return list(map(int, input().split()))

def solve():
    n = getN()
    iso = False
    ise = False
    cnt1, cnt0 = 0, 0
    for _ in range(n):
        s = input().strip()
        if len(s) % 2 == 1:
            iso = 1
        else:
            ise = 1

        cnt = Counter(s)
        cnt1 += cnt["1"]
        cnt0 += cnt["0"]

    # print(iso, ise, cnt1, cnt0)
    if not iso and cnt1 % 2 and cnt0 % 2:
        print(n - 1)
    else:
        print(n)

def main():
    t = getN()
    for times in range(t):
        solve()

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1251/C:
You are given a huge integer $a$ consisting of $n$ digits ($n$ is between $1$ and $3 \cdot 10^5$, inclusive). It may contain leading zeros.

You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by $2$).

For example, if $a = 032867235$ you can get the following integers in a single operation:   $302867235$ if you swap the first and the second digits;  $023867235$ if you swap the second and the third digits;  $032876235$ if you swap the fifth and the sixth digits;  $032862735$ if you swap the sixth and the seventh digits;  $032867325$ if you swap the seventh and the eighth digits.

Note, that you can't swap digits on positions $2$ and $4$ because the positions are not adjacent. Also, you can't swap digits on positions $3$ and $4$ because the digits have the same parity.

You can perform any number (possibly, zero) of such operations.

Find the minimum integer you can obtain.

Note that the resulting integer also may contain leading zeros.

-----Input-----

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

The only line of each test case contains the integer $a$, its length $n$ is between $1$ and $3 \cdot 10^5$, inclusive.

It is guaranteed that the sum of all values $n$ does not exceed $3 \cdot 10^5$.

-----Output-----

For each test case print line — the minimum integer you can obtain.

-----Example-----
Input
3
0709
1337
246432

Output
0079
1337
234642

-----Note-----

In the first test case, you can perform the following sequence of operations (the pair of swapped digits is highlighted): $0 \underline{\textbf{70}} 9 \rightarrow 0079$.

In the second test case, the initial integer is optimal.

In the third test case you can perform the following sequence of operations: $246 \underline{\textbf{43}} 2 \rightarrow 24 \underline{\textbf{63}}42 \rightarrow 2 \underline{\textbf{43}} 642 \rightarrow 234642$.

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

# PARITY'S RELATIVE POSITION DOESN'T CHANGE! (PROBLEM C)
def solve(s):
    # return list
    evens = [u for u in s if u % 2 == 0]
    odds  = [u for u in s if u % 2 == 1]
    if len(odds) == 0:
        return evens
    ans = []
    inserted_odd = 0
    current_odd = odds[inserted_odd]
    for i in range(len(evens)):
        while current_odd < evens[i] and inserted_odd < len(odds):
            ans.append(current_odd)
            inserted_odd += 1
            if inserted_odd < len(odds):
                current_odd = odds[inserted_odd]
        ans.append(evens[i])
    while inserted_odd < len(odds):
        ans.append(current_odd)
        inserted_odd += 1
        if inserted_odd < len(odds):
            current_odd = odds[inserted_odd]
    return ans

for _ in range(int(input())):
    s = list(map(int, list(input())))
    ans = solve(s)
    print (''.join(map(str, ans)))


I found an interesting problem on https://codeforces.com/problemset/problem/1251/D:
You are the head of a large enterprise. $n$ people work at you, and $n$ is odd (i. e. $n$ is not divisible by $2$).

You have to distribute salaries to your employees. Initially, you have $s$ dollars for it, and the $i$-th employee should get a salary from $l_i$ to $r_i$ dollars. You have to distribute salaries in such a way that the median salary is maximum possible.

To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:  the median of the sequence $[5, 1, 10, 17, 6]$ is $6$,  the median of the sequence $[1, 2, 1]$ is $1$.

It is guaranteed that you have enough money to pay the minimum salary, i.e $l_1 + l_2 + \dots + l_n \le s$.

Note that you don't have to spend all your $s$ dollars on salaries.

You have to answer $t$ test cases.

-----Input-----

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

The first line of each query contains two integers $n$ and $s$ ($1 \le n < 2 \cdot 10^5$, $1 \le s \le 2 \cdot 10^{14}$) — the number of employees and the amount of money you have. The value $n$ is not divisible by $2$.

The following $n$ lines of each query contain the information about employees. The $i$-th line contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le 10^9$).

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

It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. $\sum\limits_{i=1}^{n} l_i \le s$.

-----Output-----

For each test case print one integer — the maximum median salary that you can obtain.

-----Example-----
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7

Output
11
1337
6

-----Note-----

In the first test case, you can distribute salaries as follows: $sal_1 = 12, sal_2 = 2, sal_3 = 11$ ($sal_i$ is the salary of the $i$-th employee). Then the median salary is $11$.

In the second test case, you have to pay $1337$ dollars to the...

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

import sys
input1 = sys.stdin.readline

def solve():
    n, s = [int(i) for i in input1().split()]
    empl = []
    for i in range(n):
        empl.append([int(j) for j in input1().split()])
    empl.sort(reverse = True)
    lg = 0
    rg = 10 ** 9 + 1
    while rg - lg > 1:
        mg = (rg + lg) // 2
        need = (n + 1) // 2
        money = s
        for i in range(n):
            li = empl[i][0]
            ri = empl[i][1]
            if ri >= mg and need > 0:
                money -= max(mg, li)
                need -= 1
            else:
                money -= li
        if need == 0 and money >= 0:
            check = True
        else:
            check = False
        if check:
            lg = mg
        else:
            rg = mg
    print(lg)

t = int(input1())
while t > 0:
    empl = []
    solve()
    t -= 1


I found an interesting problem on https://codeforces.com/problemset/problem/1253/A:
You're given two arrays $a[1 \dots n]$ and $b[1 \dots n]$, both of the same length $n$.

In order to perform a push operation, you have to choose three integers $l, r, k$ satisfying $1 \le l \le r \le n$ and $k > 0$. Then, you will add $k$ to elements $a_l, a_{l+1}, \ldots, a_r$.

For example, if $a = [3, 7, 1, 4, 1, 2]$ and you choose $(l = 3, r = 5, k = 2)$, the array $a$ will become $[3, 7, \underline{3, 6, 3}, 2]$.

You can do this operation at most once. Can you make array $a$ equal to array $b$?

(We consider that $a = b$ if and only if, for every $1 \le i \le n$, $a_i = b_i$)

-----Input-----

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

The first line of each test case contains a single integer $n$ ($1 \le n \le 100\ 000$) — the number of elements in each array.

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

The third line of each test case contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le 1000$).

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

-----Output-----

For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing at most once the described operation or "NO" if it's impossible.

You can print each letter in any case (upper or lower).

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

Output
YES
NO
YES
NO

-----Note-----

The first test case is described in the statement: we can perform a push operation with parameters $(l=3, r=5, k=2)$ to make $a$ equal to $b$.

In the second test case, we would need at least two operations to make $a$ equal to $b$.

In the third test case, arrays $a$ and $b$ are already equal.

In the fourth test case, it's impossible to make $a$ equal to $b$, because the integer $k$ has to be positive.

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

q=int(input())

for qq in range(q):
    n=int(input())
    a=list(map(int, input().split()))
    b=list(map(int, input().split()))
    started = False
    ended = False
    possible = True
    diff=0
    for i in range(n):
        if a[i] != b[i]:
            if a[i] > b[i]:
                possible = False
                break
            elif ended:
                possible = False
                break
            elif started and b[i] - a[i] != diff:
                possible = False
                break
            elif started:
                continue
            elif not started:
                started = True
                diff = b[i] - a[i]
        elif a[i] == b[i] and started:
            ended = True

    if possible:
        print("YES")
    else:
        print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1253/B:
The Central Company has an office with a sophisticated security system. There are $10^6$ employees, numbered from $1$ to $10^6$.

The security system logs entrances and departures. The entrance of the $i$-th employee is denoted by the integer $i$, while the departure of the $i$-th employee is denoted by the integer $-i$.

The company has some strict rules about access to its office:

  An employee can enter the office at most once per day.  He obviously can't leave the office if he didn't enter it earlier that day.  In the beginning and at the end of every day, the office is empty (employees can't stay at night). It may also be empty at any moment of the day.

Any array of events satisfying these conditions is called a valid day.

Some examples of valid or invalid days:

  $[1, 7, -7, 3, -1, -3]$ is a valid day ($1$ enters, $7$ enters, $7$ leaves, $3$ enters, $1$ leaves, $3$ leaves).  $[2, -2, 3, -3]$ is also a valid day.  $[2, 5, -5, 5, -5, -2]$ is not a valid day, because $5$ entered the office twice during the same day.  $[-4, 4]$ is not a valid day, because $4$ left the office without being in it.  $[4]$ is not a valid day, because $4$ entered the office and didn't leave it before the end of the day.

There are $n$ events $a_1, a_2, \ldots, a_n$, in the order they occurred. This array corresponds to one or more consecutive days. The system administrator erased the dates of events by mistake, but he didn't change the order of the events.

You must partition (to cut) the array $a$ of events into contiguous subarrays, which must represent non-empty valid days (or say that it's impossible). Each array element should belong to exactly one contiguous subarray of a partition. Each contiguous subarray of a partition should be a valid day.

For example, if $n=8$ and $a=[1, -1, 1, 2, -1, -2, 3, -3]$ then he can partition it into two contiguous subarrays which are valid days: $a = [1, -1~ \boldsymbol{|}~ 1, 2, -1, -2, 3, -3]$.

Help the administrator to partition the given array $a$ in the required way or report...

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

ints = lambda: [int(x) for x in input().split()]

def solve(arr):
    p, inside, entered = [], set(), set()
    for x in arr:
        if (x<0 and -x not in inside) or (x>0 and x in entered):
            return []
        elif x<0:
            inside.remove(-x)
            if len(inside)==0:
                p.append(2*len(entered))
                entered = set()
        else:
            inside.add(x)
            entered.add(x)
    if inside: return []
    return p

def main():
    while 1:
        try: n, = ints()
        except EOFError: break
        ans = solve(ints())
        if not ans: print('-1')
        else: print(len(ans)) ; print(*ans)
    return

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1253/C:
Tsumugi brought $n$ delicious sweets to the Light Music Club. They are numbered from $1$ to $n$, where the $i$-th sweet has a sugar concentration described by an integer $a_i$.

Yui loves sweets, but she can eat at most $m$ sweets each day for health reasons.

Days are $1$-indexed (numbered $1, 2, 3, \ldots$). Eating the sweet $i$ at the $d$-th day will cause a sugar penalty of $(d \cdot a_i)$, as sweets become more sugary with time. A sweet can be eaten at most once.

The total sugar penalty will be the sum of the individual penalties of each sweet eaten.

Suppose that Yui chooses exactly $k$ sweets, and eats them in any order she wants. What is the minimum total sugar penalty she can get?

Since Yui is an undecided girl, she wants you to answer this question for every value of $k$ between $1$ and $n$.

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 200\ 000$).

-----Output-----

You have to output $n$ integers $x_1, x_2, \ldots, x_n$ on a single line, separed by spaces, where $x_k$ is the minimum total sugar penalty Yui can get if she eats exactly $k$ sweets.

-----Examples-----
Input
9 2
6 19 3 4 4 2 6 7 8

Output
2 5 11 18 30 43 62 83 121

Input
1 1
7

Output
7

-----Note-----

Let's analyze the answer for $k = 5$ in the first example. Here is one of the possible ways to eat $5$ sweets that minimize total sugar penalty:  Day $1$: sweets $1$ and $4$  Day $2$: sweets $5$ and $3$  Day $3$ : sweet $6$

Total penalty is $1 \cdot a_1 + 1 \cdot a_4 + 2 \cdot a_5 + 2 \cdot a_3 + 3 \cdot a_6 = 6 + 4 + 8 + 6 + 6 = 30$. We can prove that it's the minimum total sugar penalty Yui can achieve if she eats $5$ sweets, hence $x_5 = 30$.

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

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

a = sorted(a)
ruiseki = [0] * (n + 1)
for i in range(n):
    ruiseki[i+1] = ruiseki[i] + a[i]

ans = [0] * n
for i in range(n):
    if i-m >=0:
        ans[i] = ruiseki[i+1] + ans[i-m]
    else:
        ans[i] = ruiseki[i+1]
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1253/D:
You're given an undirected graph with $n$ nodes and $m$ edges. Nodes are numbered from $1$ to $n$.

The graph is considered harmonious if and only if the following property holds:  For every triple of integers $(l, m, r)$ such that $1 \le l < m < r \le n$, if there exists a path going from node $l$ to node $r$, then there exists a path going from node $l$ to node $m$.

In other words, in a harmonious graph, if from a node $l$ we can reach a node $r$ through edges ($l < r$), then we should able to reach nodes $(l+1), (l+2), \ldots, (r-1)$ too.

What is the minimum number of edges we need to add to make the graph harmonious?

-----Input-----

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

The $i$-th of the next $m$ lines contains two integers $u_i$ and $v_i$ ($1 \le u_i, v_i \le n$, $u_i \neq v_i$), that mean that there's an edge between nodes $u$ and $v$.

It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes).

-----Output-----

Print the minimum number of edges we have to add to the graph to make it harmonious.

-----Examples-----
Input
14 8
1 2
2 7
3 4
6 3
5 7
3 8
6 8
11 12

Output
1

Input
200000 3
7 9
9 8
4 5

Output
0

-----Note-----

In the first example, the given graph is not harmonious (for instance, $1 < 6 < 7$, node $1$ can reach node $7$ through the path $1 \rightarrow 2 \rightarrow 7$, but node $1$ can't reach node $6$). However adding the edge $(2, 4)$ is sufficient to make it harmonious.

In the second example, the given graph is already harmonious.

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

# unionfind
class Uf:
    def __init__(self, N):
        self.p = list(range(N))
        self.rank = [0] * N
        self.size = [1] * N

    def root(self, x):
        if self.p[x] != x:
            self.p[x] = self.root(self.p[x])

        return self.p[x]

    def same(self, x, y):
        return self.root(x) == self.root(y)

    def unite(self, x, y):
        u = self.root(x)
        v = self.root(y)

        if u == v: return

        if self.rank[u] < self.rank[v]:
            self.p[u] = v
            self.size[v] += self.size[u]
            self.size[u] = 0
        else:
            self.p[v] = u
            self.size[u] += self.size[v]
            self.size[v] = 0

            if self.rank[u] == self.rank[v]:
                self.rank[u] += 1

    def count(self, x):
        return self.size[self.root(x)]

import sys
from operator import itemgetter
def main():
    input = sys.stdin.readline
    N, M = list(map(int, input().split()))
    # harmonious <=> l < m < r で、l から r に辿り着けるなら、l から m に辿り着ける

    uf = Uf(N+1)
    for u, v in zip(*[iter(map(int, sys.stdin.read().split()))]*2):
        uf.unite(u, v)

    L = [10**9] * (N+1)
    R = [-1] * (N+1)
    for i in range(1, N+1):
        r = uf.root(i)
        L[r] = min(L[r], i)
        R[r] = max(R[r], i)
    ans = 0
    LR = []
    for l, r in zip(L, R):
        if r != -1:
            LR.append((l, r))
    LR.sort(key=itemgetter(0))
    rr = -1
    for l, r in LR:
        if rr > l:
            ans += 1
        rr = max(rr, r)
    print(ans)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1253/E:
The mayor of the Central Town wants to modernize Central Street, represented in this problem by the $(Ox)$ axis.

On this street, there are $n$ antennas, numbered from $1$ to $n$. The $i$-th antenna lies on the position $x_i$ and has an initial scope of $s_i$: it covers all integer positions inside the interval $[x_i - s_i; x_i + s_i]$.

It is possible to increment the scope of any antenna by $1$, this operation costs $1$ coin. We can do this operation as much as we want (multiple times on the same antenna if we want).

To modernize the street, we need to make all integer positions from $1$ to $m$ inclusive covered by at least one antenna. Note that it is authorized to cover positions outside $[1; m]$, even if it's not required.

What is the minimum amount of coins needed to achieve this modernization?

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 80$ and $n \le m \le 100\ 000$).

The $i$-th of the next $n$ lines contains two integers $x_i$ and $s_i$ ($1 \le x_i \le m$ and $0 \le s_i \le m$).

On each position, there is at most one antenna (values $x_i$ are pairwise distinct).

-----Output-----

You have to output a single integer: the minimum amount of coins required to make all integer positions from $1$ to $m$ inclusive covered by at least one antenna.

-----Examples-----
Input
3 595
43 2
300 4
554 10

Output
281

Input
1 1
1 1

Output
0

Input
2 50
20 0
3 1

Output
30

Input
5 240
13 0
50 25
60 5
155 70
165 70

Output
26

-----Note-----

In the first example, here is a possible strategy:

  Increase the scope of the first antenna by $40$, so that it becomes $2 + 40 = 42$. This antenna will cover interval $[43 - 42; 43 + 42]$ which is $[1; 85]$  Increase the scope of the second antenna by $210$, so that it becomes $4 + 210 = 214$. This antenna will cover interval $[300 - 214; 300 + 214]$, which is $[86; 514]$  Increase the scope of the third antenna by $31$, so that it becomes $10 + 31 = 41$. This antenna will cover interval $[554 - 41; 554 + 41]$, which is $[513;...

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

# Antennas coverage

import sys
from bisect import bisect_right

def upgrade_minCost(n, m, antennas):
    covered = [False] * (m + 1)
    intervals = []
    for x, s in antennas:
        L = max(1, x - s)
        R = min(m, x + s)
        intervals.append((L, R))
        for i in range(L, R + 1):
            covered[i] = True
    intervals.sort()

    d = [(m - i) for i in range(m + 1)]
    for i in range(m - 1, -1, -1):
        if covered[i + 1]:
            d[i] = d[i + 1]
        else:
            ant_idx = bisect_right(intervals, (i, m))
            for L, R in intervals[ant_idx:]:
                u = L - i - 1
                prev = min(m, R + u)
                d[i] = min(d[i], u + d[prev])
    return d[0]

def main():
    # inf = open('input.txt', 'r')
    # reader = (map(int, line.split()) for line in inf)
    reader = (map(int, s.split()) for s in sys.stdin)

    n, m = next(reader)
    antennas = [list(next(reader)) for _ in range(n)]
    ans = upgrade_minCost(n, m, antennas)
    print(ans)

    # inf.close()

def __starting_point():
    main()
__starting_point()