I found an interesting problem on https://codeforces.com/problemset/problem/1292/F:
SIHanatsuka - EMber SIHanatsuka - ATONEMENT

Back in time, the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.

One day, Nora's adoptive father, Phoenix Wyle, brought Nora $n$ boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.

She labelled all $n$ boxes with $n$ distinct integers $a_1, a_2, \ldots, a_n$ and asked ROBO to do the following action several (possibly zero) times:

  Pick three distinct indices $i$, $j$ and $k$, such that $a_i \mid a_j$ and $a_i \mid a_k$. In other words, $a_i$ divides both $a_j$ and $a_k$, that is $a_j \bmod a_i = 0$, $a_k \bmod a_i = 0$.  After choosing, Nora will give the $k$-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty.  After doing so, the box $k$ becomes unavailable for any further actions.

Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.

Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?

As the number of such piles can be very large, you should print the answer modulo $10^9 + 7$.

-----Input-----

The first line contains an integer $n$ ($3 \le n \le 60$), denoting the number of boxes.

The second line contains $n$ distinct integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 60$), where $a_i$ is the label of the $i$-th box.

-----Output-----

Print the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo $10^9 + 7$.

-----Examples-----
Input
3
2 6 8

Output
2

Input
5
2 3 4 9 12

Output
4

Input
4
5 7 2 9

Output
1

-----Note-----

Let's illustrate the box pile as a sequence $b$, with the pile's bottommost box being at the leftmost...

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

MOD = 1000000007

def isSubset(a, b):
	return (a & b) == a

def isIntersect(a, b):
	return (a & b) != 0

# Solve for each weakly connected component (WCC)
def cntOrder(s, t):
	p = len(s)
	m = len(t)

	inMask = [0 for i in range(m)]

	for x in range(p):
		for i in range(m):
			if t[i] % s[x] == 0:
				inMask[i] |= 1 << x

	cnt = [0 for mask in range(1<<p)]
	for mask in range(1<<p):
		for i in range(m):
			if isSubset(inMask[i], mask):
				cnt[mask] += 1

	dp = [[0 for mask in range(1<<p)] for k in range(m+1)]
	for i in range(m):
		dp[1][inMask[i]] += 1
	for k in range(m):
		for mask in range(1<<p):
			for i in range(m):
				if not isSubset(inMask[i], mask) and isIntersect(inMask[i], mask):
					dp[k+1][mask | inMask[i]] = (dp[k+1][mask | inMask[i]] + dp[k][mask]) % MOD
			dp[k+1][mask] = (dp[k+1][mask] + dp[k][mask] * (cnt[mask] - k)) % MOD

	return dp[m][(1<<p)-1]

def dfs(u):
	nonlocal a, graph, degIn, visited, s, t

	visited[u] = True
	if degIn[u] == 0:
		s.append(a[u])
	else:
		t.append(a[u])

	for v in graph[u]:
		if not visited[v]:
			dfs(v)

def main():
	nonlocal a, graph, degIn, visited, s, t

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

	# Pre-calculate C(n, k)
	c = [[0 for j in range(n)] for i in range(n)]
	for i in range(n):
		c[i][0] = 1
		for j in range(1, i+1):
			c[i][j] = (c[i-1][j-1] + c[i-1][j]) % MOD

	# Building divisibility graph
	degIn = [0 for u in range(n)]
	graph = [[] for u in range(n)]
	for u in range(n):
		for v in range(n):
			if u != v and a[v] % a[u] == 0:
				graph[u].append(v)
				graph[v].append(u)
				degIn[v] += 1

	# Solve for each WCC of divisibility graph and combine result
	ans = 1
	curLen = 0
	visited = [False for u in range(n)]
	for u in range(n):
		if not visited[u]:
			s = []
			t = []
			dfs(u)

			if len(t) > 0:
				sz = len(t) - 1
				cnt = cntOrder(s, t)

				# Number of orders for current WCC
				ans = (ans * cnt) % MOD
				# Number of ways to insert <sz> number to array of <curLen> elements
				ans = (ans * c[curLen + sz][sz])...


I found an interesting problem on https://codeforces.com/problemset/problem/1293/A:
Sakuzyo - Imprinting

A.R.C. Markland-N is a tall building with $n$ floors numbered from $1$ to $n$. Between each two adjacent floors in the building, there is a staircase connecting them.

It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.

ConneR's office is at floor $s$ of the building. On each floor (including floor $s$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $k$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.

CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.

Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!

-----Input-----

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

The first line of a test case contains three integers $n$, $s$ and $k$ ($2 \le n \le 10^9$, $1 \le s \le n$, $1 \le k \le \min(n-1, 1000)$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.

The second line of a test case contains $k$ distinct integers $a_1, a_2, \ldots, a_k$ ($1 \le a_i \le n$) — the floor numbers of the currently closed restaurants.

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

-----Output-----

For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $s$ to a floor with an open restaurant.

-----Example-----
Input
5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77

Output
2
0
4
0
2

-----Note-----

In the first example test case, the nearest floor with an open restaurant would be the floor $4$.

In the second example test case, the floor with ConneR's...

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

def main():
    for _ in range(int(input())):
        n, s, k = map(int,input().split())
        a = list(map(int,input().split()))

        if s not in a:
            print(0)
            continue

        ans = 1
        t1 = s + 1
        t2 = s - 1
        for i in range(n):
            if t2 > 0:
                if t2 not in a:
                    break
                t2 -= 1
            if t1 <= n:
                if t1 not in a:
                    break
                t1 += 1
            ans += 1

        print(ans)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1293/B:
3R2 - Standby for Action

Our dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. $n$"!

The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).

For each question JOE answers, if there are $s$ ($s > 0$) opponents remaining and $t$ ($0 \le t \le s$) of them make a mistake on it, JOE receives $\displaystyle\frac{t}{s}$ dollars, and consequently there will be $s - t$ opponents left for the next question.

JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?

-----Input-----

The first and single line contains a single integer $n$ ($1 \le n \le 10^5$), denoting the number of JOE's opponents in the show.

-----Output-----

Print a number denoting the maximum prize (in dollars) JOE could have.

Your answer will be considered correct if it's absolute or relative error won't exceed $10^{-4}$. In other words, if your answer is $a$ and the jury answer is $b$, then it must hold that $\frac{|a - b|}{max(1, b)} \le 10^{-4}$.

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

Output
1.000000000000

Input
2

Output
1.500000000000

-----Note-----

In the second example, the best scenario would be: one contestant fails at the first question, the other fails at the next one. The total reward will be $\displaystyle \frac{1}{2} + \frac{1}{1} = 1.5$ dollars.

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

a=int(input())
s=0
for i in range(a):
    s+=1/(i+1)
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1294/A:
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $a$ coins, Barbara has $b$ coins and Cerene has $c$ coins. Recently Polycarp has returned from the trip around the world and brought $n$ coins.

He wants to distribute all these $n$ coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives $A$ coins to Alice, $B$ coins to Barbara and $C$ coins to Cerene ($A+B+C=n$), then $a + A = b + B = c + C$.

Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.

Your task is to find out if it is possible to distribute all $n$ coins between sisters in a way described above.

You have to answer $t$ independent test cases.

-----Input-----

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

The next $t$ lines describe test cases. Each test case is given on a new line and consists of four space-separated integers $a, b, c$ and $n$ ($1 \le a, b, c, n \le 10^8$) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.

-----Output-----

For each test case, print "YES" if Polycarp can distribute all $n$ coins between his sisters and "NO" otherwise.

-----Example-----
Input
5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3

Output
YES
YES
NO
NO
YES

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

for _ in range(int(input())):
    a,b,c,n=map(int,input().split())
    s=a+b+c
    mx=max(a,b,c)
    if((s+n)%3==0 and (s+n)//3 >= mx):
        print("YES")
    else:
        print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1294/B:
There is a robot in a warehouse and $n$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $(0, 0)$. The $i$-th package is at the point $(x_i, y_i)$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $(0, 0)$ doesn't contain a package.

The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $(x, y)$ to the point ($x + 1, y$) or to the point $(x, y + 1)$.

As we say above, the robot wants to collect all $n$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.

The string $s$ of length $n$ is lexicographically less than the string $t$ of length $n$ if there is some index $1 \le j \le n$ that for all $i$ from $1$ to $j-1$ $s_i = t_i$ and $s_j < t_j$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.

-----Input-----

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

The first line of a test case contains one integer $n$ ($1 \le n \le 1000$) — the number of packages.

The next $n$ lines contain descriptions of packages. The $i$-th package is given as two integers $x_i$ and $y_i$ ($0 \le x_i, y_i \le 1000$) — the $x$-coordinate of the package and the $y$-coordinate of the package.

It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $(0, 0)$ doesn't contain a package.

The sum of all values $n$ over test cases in the test doesn't exceed $1000$.

-----Output-----

Print the answer for each test case.

If it is impossible to collect all $n$ packages in some order starting from ($0,0$), print "NO" on the first line.

Otherwise, print "YES" in the first line. Then print the shortest...

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

t = int(input())
for i in range(t):
    a = int(input())
    x, y = 0, 0
    l = []
    for i in range(a):
        x1, y1 = map(int, input().split())
        l.append([x1, y1])
    l.sort()
    ll = 0
    ch = 1
    for i in range(1, a):
        if l[i][1] < l[i - 1][1]:
            ch = 0
            break
    if ch == 0:
        print('NO')
    else:
        print('YES')
        st = ''
        for i in l:
            st += 'R' * (i[0] - x)
            x = i[0]
            st += 'U' * (i[1] - y)
            y = i[1]
        print(st)


I found an interesting problem on https://codeforces.com/problemset/problem/1294/C:
You are given one integer number $n$. Find three distinct integers $a, b, c$ such that $2 \le a, b, c$ and $a \cdot b \cdot c = n$ or say that it is impossible to do it.

If there are several answers, you can print any.

You have to answer $t$ independent test cases.

-----Input-----

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

The next $n$ lines describe test cases. The $i$-th test case is given on a new line as one integer $n$ ($2 \le n \le 10^9$).

-----Output-----

For each test case, print the answer on it. Print "NO" if it is impossible to represent $n$ as $a \cdot b \cdot c$ for some distinct integers $a, b, c$ such that $2 \le a, b, c$.

Otherwise, print "YES" and any possible such representation.

-----Example-----
Input
5
64
32
97
2
12345

Output
YES
2 4 8
NO
NO
NO
YES
3 5 823

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

from functools import reduce
def factors(n):
    k = sorted(list(set(reduce(list.__add__,
                     ([i,n//i] for i in range(1,int(n**0.5+1)) if n%i == 0)))))
    return k[1:]
t = int(input())
for _ in range(0,t):
    n = int(input())
    f = factors(n)
    if len(f) < 3:
        print('NO')
    else:
        ans = 'NO'
        a,b,c = -1,-1,-1
        for i in range(0,len(f)):
            for j in range(i+1,len(f)):
                 temp = n//f[i]
                 temp //= f[j]
                 if temp in f and temp != f[i] and temp != f[j]:
                     a,b,c = f[i],f[j],temp
                     ans = 'YES'
                     break
            if ans == 'YES':
                break
        if ans == 'YES':
            print(ans)
            print(a,b,c)
        else:
            print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1294/D:
Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:  for the array $[0, 0, 1, 0, 2]$ MEX equals to $3$ because numbers $0, 1$ and $2$ are presented in the array and $3$ is the minimum non-negative integer not presented in the array;  for the array $[1, 2, 3, 4]$ MEX equals to $0$ because $0$ is the minimum non-negative integer not presented in the array;  for the array $[0, 1, 4, 3]$ MEX equals to $2$ because $2$ is the minimum non-negative integer not presented in the array.

You are given an empty array $a=[]$ (in other words, a zero-length array). You are also given a positive integer $x$.

You are also given $q$ queries. The $j$-th query consists of one integer $y_j$ and means that you have to append one element $y_j$ to the array. The array length increases by $1$ after a query.

In one move, you can choose any index $i$ and set $a_i := a_i + x$ or $a_i := a_i - x$ (i.e. increase or decrease any element of the array by $x$). The only restriction is that $a_i$ cannot become negative. Since initially the array is empty, you can perform moves only after the first query.

You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).

You have to find the answer after each of $q$ queries (i.e. the $j$-th answer corresponds to the array of length $j$).

Operations are discarded before each query. I.e. the array $a$ after the $j$-th query equals to $[y_1, y_2, \dots, y_j]$.

-----Input-----

The first line of the input contains two integers $q, x$ ($1 \le q, x \le 4 \cdot 10^5$) — the number of queries and the value of $x$.

The next $q$ lines describe queries. The $j$-th query consists of one integer $y_j$ ($0 \le y_j \le 10^9$) and means that you have to append one element $y_j$ to the array.

-----Output-----

Print the answer to the initial problem after each query — for the query $j$ print the maximum value of MEX after first $j$...

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

import sys
input = sys.stdin.readline

q,x=list(map(int,input().split()))

seg_el=1<<((x+1).bit_length())
SEG=[0]*(2*seg_el)

def add1(n,seg_el):
    i=n+seg_el
    SEG[i]+=1
    i>>=1

    while i!=0:
        SEG[i]=min(SEG[i*2],SEG[i*2+1])
        i>>=1

def getvalues(l,r):
    L=l+seg_el
    R=r+seg_el
    ANS=1<<30

    while L<R:
        if L & 1:
            ANS=min(ANS , SEG[L])
            L+=1

        if R & 1:
            R-=1
            ANS=min(ANS , SEG[R])
        L>>=1
        R>>=1

    return ANS

for qu in range(q):
    t=int(input())
    add1(t%x,seg_el)

    #print(SEG)

    MIN=getvalues(0,x)

    OK=0
    NG=x

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

        if getvalues(0,mid)>MIN:
            OK=mid
        else:
            NG=mid

    #print(MIN,OK)
    print(MIN*x+OK)


I found an interesting problem on https://codeforces.com/problemset/problem/1294/E:
You are given a rectangular matrix of size $n \times m$ consisting of integers from $1$ to $2 \cdot 10^5$.

In one move, you can:  choose any element of the matrix and change its value to any integer between $1$ and $n \cdot m$, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below).

A cyclic shift is an operation such that you choose some $j$ ($1 \le j \le m$) and set $a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}$ simultaneously. [Image] Example of cyclic shift of the first column

You want to perform the minimum number of moves to make this matrix look like this: $\left. \begin{array}{|c c c c|} \hline 1 & {2} & {\ldots} & {m} \\{m + 1} & {m + 2} & {\ldots} & {2m} \\{\vdots} & {\vdots} & {\ddots} & {\vdots} \\{(n - 1) m + 1} & {(n - 1) m + 2} & {\ldots} & {nm} \\ \hline \end{array} \right.$

In other words, the goal is to obtain the matrix, where $a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$ (i.e. $a_{i, j} = (i - 1) \cdot m + j$) with the minimum number of moves performed.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5$) — the size of the matrix.

The next $n$ lines contain $m$ integers each. The number at the line $i$ and position $j$ is $a_{i, j}$ ($1 \le a_{i, j} \le 2 \cdot 10^5$).

-----Output-----

Print one integer — the minimum number of moves required to obtain the matrix, where $a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$ ($a_{i, j} = (i - 1)m + j$).

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

Output
6

Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12

Output
0

Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12

Output
2

-----Note-----

In the first example, you can set $a_{1, 1} := 7, a_{1, 2} := 8$ and $a_{1, 3} := 9$ then shift the first, the second and the third columns cyclically, so the answer...

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

n, m = (int(i) for i in input().split())
a = [[int(i) for i in input().split()] for _ in range(n)]
res = 0
for j in range(m):
	b = [0] * n
	for i in range(n):
		if a[i][j] <= n*m and (a[i][j]-j-1)%m == 0:
			pos = (a[i][j]-j-1)//m
			shift = i-pos if i>=pos else i-pos+n
			b[shift] += 1
	res += min(i+n-b[i] for i in range(n))
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1294/F:
You are given an unweighted tree with $n$ vertices. Recall that a tree is a connected undirected graph without cycles.

Your task is to choose three distinct vertices $a, b, c$ on this tree such that the number of edges which belong to at least one of the simple paths between $a$ and $b$, $b$ and $c$, or $a$ and $c$ is the maximum possible. See the notes section for a better understanding.

The simple path is the path that visits each vertex at most once.

-----Input-----

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

Next $n - 1$ lines describe the edges of the tree in form $a_i, b_i$ ($1 \le a_i$, $b_i \le n$, $a_i \ne b_i$). It is guaranteed that given graph is a tree.

-----Output-----

In the first line print one integer $res$ — the maximum number of edges which belong to at least one of the simple paths between $a$ and $b$, $b$ and $c$, or $a$ and $c$.

In the second line print three integers $a, b, c$ such that $1 \le a, b, c \le n$ and $a \ne, b \ne c, a \ne c$.

If there are several answers, you can print any.

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

Output
5
1 8 6

-----Note-----

The picture corresponding to the first example (and another one correct answer):

[Image]

If you choose vertices $1, 5, 6$ then the path between $1$ and $5$ consists of edges $(1, 2), (2, 3), (3, 4), (4, 5)$, the path between $1$ and $6$ consists of edges $(1, 2), (2, 3), (3, 4), (4, 6)$ and the path between $5$ and $6$ consists of edges $(4, 5), (4, 6)$. The union of these paths is $(1, 2), (2, 3), (3, 4), (4, 5), (4, 6)$ so the answer is $5$. It can be shown that there is no better answer.

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

import sys
from collections import deque

# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__

n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
    v, to = list(map(int, input().split()))
    v -= 1
    to -= 1
    g[v].append(to)
    g[to].append(v)

# (vertex, distance)
queue = deque([(0, 0)])
visited = [False] * n
while queue:
    v, d = queue.popleft()
    visited[v] = True
    for to in g[v]:
        if not visited[to]:
            queue.append((to, d + 1))
a = v

# (vertex, distance)
queue = deque([(a, 0)])
prev = [-1] * n
for i in range(n):
    visited[i] = False
while queue:
    v, d = queue.popleft()
    visited[v] = True
    for to in g[v]:
        if not visited[to]:
            queue.append((to, d + 1))
            prev[to] = v
b, ctr = v, d

for i in range(n):
    visited[i] = False
curr = prev[b]
nxt = b
prv = prev[curr]
add = 0
if a != 0 and b != 0:
    c = 0
elif a != 1 and b != 1:
    c = 1
else:
    c = 2
while curr != a:
    visited[curr] = True
    for to in g[curr]:
        if to == nxt or to == prv:
            continue
        queue = deque([(to, 1)])
        while queue:
            v, d = queue.popleft()
            visited[v] = True
            for to in g[v]:
                if not visited[to]:
                    queue.append((to, d + 1))
        if add < d:
            c, add = v, d
    nxt = curr
    curr = prev[curr]
    prv = prev[curr]

print(ctr + add)
print(a + 1, b + 1, c + 1)

# inf.close()


I found an interesting problem on https://codeforces.com/problemset/problem/1295/B:
You are given string $s$ of length $n$ consisting of 0-s and 1-s. You build an infinite string $t$ as a concatenation of an infinite number of strings $s$, or $t = ssss \dots$ For example, if $s =$ 10010, then $t =$ 100101001010010...

Calculate the number of prefixes of $t$ with balance equal to $x$. The balance of some string $q$ is equal to $cnt_{0, q} - cnt_{1, q}$, where $cnt_{0, q}$ is the number of occurrences of 0 in $q$, and $cnt_{1, q}$ is the number of occurrences of 1 in $q$. The number of such prefixes can be infinite; if it is so, you must say that.

A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".

-----Input-----

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

Next $2T$ lines contain descriptions of test cases — two lines per test case. The first line contains two integers $n$ and $x$ ($1 \le n \le 10^5$, $-10^9 \le x \le 10^9$) — the length of string $s$ and the desired balance, respectively.

The second line contains the binary string $s$ ($|s| = n$, $s_i \in \{\text{0}, \text{1}\}$).

It's guaranteed that the total sum of $n$ doesn't exceed $10^5$.

-----Output-----

Print $T$ integers — one per test case. For each test case print the number of prefixes or $-1$ if there is an infinite number of such prefixes.

-----Example-----
Input
4
6 10
010010
5 3
10101
1 0
0
2 0
01

Output
3
0
1
-1

-----Note-----

In the first test case, there are 3 good prefixes of $t$: with length $28$, $30$ and $32$.

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

for _ in range(int(input())):
    n,x=map(int,input().split())
    s=input()
    y=s.count('0')-s.count('1')
    z=0
    inf=False
    ans=0
    if x==0: ans=1
    for i in s:
        z+=(i=='0')-(i=='1')
        if y==0 and z==x:
            inf=True
            print(-1)
            break
        if x-z==0 or ((x-z)*y>0 and (x-z)%y==0):ans+=1
    if not inf:
        print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1295/C:
You are given two strings $s$ and $t$ consisting of lowercase Latin letters. Also you have a string $z$ which is initially empty. You want string $z$ to be equal to string $t$. You can perform the following operation to achieve this: append any subsequence of $s$ at the end of string $z$. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if $z = ac$, $s = abcde$, you may turn $z$ into following strings in one operation:   $z = acace$ (if we choose subsequence $ace$);  $z = acbcd$ (if we choose subsequence $bcd$);  $z = acbce$ (if we choose subsequence $bce$).

Note that after this operation string $s$ doesn't change.

Calculate the minimum number of such operations to turn string $z$ into string $t$.

-----Input-----

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

The first line of each testcase contains one string $s$ ($1 \le |s| \le 10^5$) consisting of lowercase Latin letters.

The second line of each testcase contains one string $t$ ($1 \le |t| \le 10^5$) consisting of lowercase Latin letters.

It is guaranteed that the total length of all strings $s$ and $t$ in the input does not exceed $2 \cdot 10^5$.

-----Output-----

For each testcase, print one integer — the minimum number of operations to turn string $z$ into string $t$. If it's impossible print $-1$.

-----Example-----
Input
3
aabce
ace
abacaba
aax
ty
yyt

Output
1
-1
3

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

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

def ctoi(c):
	return ord(c) - ord("a")
	print(ans)

T = int(input())
for _ in range(T):
	s = input()
	t = input()
	if not (set(s) >= set(t)):
		print(-1)
	else:
		alph = [[] for _ in range(26)]
		for i in range(len(s)):
			alph[ctoi(s[i])].append(i)
		for a in alph:
			if a:
				a.append(a[0] + len(s))
		#print(alph)
		cur = len(s)-1
		ans = 0
		for i in range(len(t)):
			ind = bisect(alph[ctoi(t[i])], cur)
			ans += alph[ctoi(t[i])][ind] - cur
			cur = alph[ctoi(t[i])][ind] % len(s)
		print(-(-ans//len(s)))


I found an interesting problem on https://codeforces.com/problemset/problem/1295/D:
You are given two integers $a$ and $m$. Calculate the number of integers $x$ such that $0 \le x < m$ and $\gcd(a, m) = \gcd(a + x, m)$.

Note: $\gcd(a, b)$ is the greatest common divisor of $a$ and $b$.

-----Input-----

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

Next $T$ lines contain test cases — one per line. Each line contains two integers $a$ and $m$ ($1 \le a < m \le 10^{10}$).

-----Output-----

Print $T$ integers — one per test case. For each test case print the number of appropriate $x$-s.

-----Example-----
Input
3
4 9
5 10
42 9999999967

Output
6
1
9999999966

-----Note-----

In the first test case appropriate $x$-s are $[0, 1, 3, 4, 6, 7]$.

In the second test case the only appropriate $x$ is $0$.

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

from functools import *
from math import gcd
from collections import *
def isValid(n):
    if n <= 0: return 0
    if n - int(n) != 0: return 0
    return 1
def mu(n):
    if n == 1:
        return 1
    elif isDivisibleBySquare(n):
        return 0
    else:
        return (-1) ** numberOfFactors(n)
def isDivisibleBySquare(n):
    if n % 2 == 0:
        n = n / 2
    if n % 2 == 0:
        return True
    for i in range(3, int(n ** 0.5) + 1):
        if n % i == 0:
            n //= i
        if n % i == 0:
            return True
    return False
def factorGenerator(n):
    r = []
    while n % 2 == 0:
        n //= 2
        r.append(2)
    i = 3
    while i * i <= n:
        while n % i == 0:
            n //= i
            r.append(i)
        i += 2
    if n != 1:
        r.append(n)
    return r
def numberOfFactors(n):
    return len(factorGenerator(n))
def divisors(n):
    return set(reduce(list.__add__,
                ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

def calc(m, n):
    # Calculate number of integers in [1, m] coprime to n
    s = 0
    for d in sorted(list(set(divisors(n)))):
        s += mu(d) * (m // d)
    return s

n = int(input())
for _ in range(n):
    a, m = list(map(int, input().split()))
    g = gcd(a, m)
    # print (calc(a, m))
    print(calc((m + a - 1) // g, m // g) - calc((a - 1) // g, m // g))
    # print (sum(gcd(a, m) == gcd(a + x, m) for x in range(m)))


I found an interesting problem on https://codeforces.com/problemset/problem/1295/F:
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $n$ problems; and since the platform is very popular, $998244351$ coder from all over the world is going to solve them.

For each problem, the authors estimated the number of people who would solve it: for the $i$-th problem, the number of accepted solutions will be between $l_i$ and $r_i$, inclusive.

The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $(x, y)$ such that $x$ is located earlier in the contest ($x < y$), but the number of accepted solutions for $y$ is strictly greater.

Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $i$, any integral number of accepted solutions for it (between $l_i$ and $r_i$) is equally probable, and all these numbers are independent.

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 50$) — the number of problems in the contest.

Then $n$ lines follow, the $i$-th line contains two integers $l_i$ and $r_i$ ($0 \le l_i \le r_i \le 998244351$) — the minimum and maximum number of accepted solutions for the $i$-th problem, respectively.

-----Output-----

The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $\frac{x}{y}$, where $y$ is coprime with $998244353$. Print one integer — the value of $xy^{-1}$, taken modulo $998244353$, where $y^{-1}$ is an integer such that $yy^{-1} \equiv 1$ $(mod$ $998244353)$.

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

Output
499122177

Input
2
42 1337
13 420

Output
578894053

Input
2
1 1
0 0

Output
1

Input
2
1 1
1 1

Output
1

-----Note-----

The real answer in the first test is $\frac{1}{2}$.

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

from bisect import bisect_left

M = 998244353

def pw(x, y):
    if y == 0:
        return 1
    res = pw(x, y//2)
    res = res * res % M
    if y % 2 == 1:
        res = res * x % M
    return res

def cal(x, y):
    y += x - 1
    res = 1
    for i in range(1, x + 1):
        res = res * (y - i + 1)
        res = res * pw(i, M - 2) % M
    return res % M

n = int(input())
a = []
b = []
res = 1
for i in range(n):
    a.append(list(map(int, input().split())))
    res = res * (a[-1][1] + 1 - a[-1][0]) % M
    b.append(a[-1][0])
    b.append(a[-1][1] + 1)
    b = set(b)
    b = sorted(list(b))

g = [b[i + 1] - b[i] for i in range(len(b) - 1)]

for i in range(n):
    a[i][0] = bisect_left(b, a[i][0])
    a[i][1] = bisect_left(b, a[i][1] + 1)

a = a[::-1]

f = [[0 for _ in range(len(b))] for __ in range(n)]

for i in range(a[0][0], len(b)):
    if i == 0:
        f[0][i] = g[i]
    else:
        if i < a[0][1]:
            f[0][i] = (f[0][i - 1] + g[i]) % M
        else:
            f[0][i] = f[0][i - 1]

for i in range(1, n):
    for j in range(a[i][0], len(b)):
        if j > 0:
            f[i][j] = f[i][j - 1]
        if j < a[i][1]:
            for k in range(i, -1, -1):
                if a[k][1] <= j or j < a[k][0]:
                    break
                if k == 0 or j != 0:
                    tmp = cal(i - k + 1, g[j])
                    if k > 0:
                        f[i][j] += f[k - 1][j - 1] * tmp % M
                    else:
                        f[i][j] += tmp
                    f[i][j] %= M

#print(f)
#print(f[n - 1][len(b) - 1], res)
print(f[n - 1][len(b) - 1] * pw(res, M - 2) % M)


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

In one move, you can choose two indices $1 \le i, j \le n$ such that $i \ne j$ and set $a_i := a_j$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $i$ and $j$ and replace $a_i$ with $a_j$).

Your task is to say if it is possible to obtain an array with an odd (not divisible by $2$) sum of elements.

You have to answer $t$ independent test cases.

-----Input-----

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

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

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

-----Output-----

For each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.

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

Output
YES
NO
YES
NO
NO

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

n = int(input())
for i in range(n):
    num = int(input())
    lst = list(map(int, input().split()))
    even = 0
    odd = 0
    for j in lst:
        if j % 2 == 0:
            even+=1
        else:
            odd+=1
    if odd == 0 or (odd == num and num % 2 == 0):
        print("NO")
    else:
        print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1296/C:
There is a robot on a coordinate plane. Initially, the robot is located at the point $(0, 0)$. Its path is described as a string $s$ of length $n$ consisting of characters 'L', 'R', 'U', 'D'.

Each of these characters corresponds to some move:   'L' (left): means that the robot moves from the point $(x, y)$ to the point $(x - 1, y)$;  'R' (right): means that the robot moves from the point $(x, y)$ to the point $(x + 1, y)$;  'U' (up): means that the robot moves from the point $(x, y)$ to the point $(x, y + 1)$;  'D' (down): means that the robot moves from the point $(x, y)$ to the point $(x, y - 1)$.

The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point $(x_e, y_e)$, then after optimization (i.e. removing some single substring from $s$) the robot also ends its path at the point $(x_e, y_e)$.

This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string $s$).

Recall that the substring of $s$ is such string that can be obtained from $s$ by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".

You have to answer $t$ independent test cases.

-----Input-----

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

The next $2t$ lines describe test cases. Each test case is given on two lines. The first line of the test case contains...

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

import sys
input = sys.stdin.readline
def getInt(): return int(input())
def getVars(): return list(map(int, input().split()))
def getList(): return list(map(int, input().split()))
def getStr(): return input().strip()
## -------------------------------

t = getInt()
for _ in range(t):
    n = getInt()
    s = getStr()
    d = {}
    d['0/0'] = 0
    x = 0
    y = 0
    res = [0, n+1]
    for i in range(n):
        if s[i] == 'L':
            x -= 1
        if s[i] == 'R':
            x += 1
        if s[i] == 'U':
            y += 1
        if s[i] == 'D':
            y -= 1
        k = str(x) + '/' + str(y)
        if k not in d:
            d[k] = i+1
        else:
            if i+1 - d[k] < res[1] - res[0]:
                res = [d[k]+1, i+1]
            d[k] = i+1
    if res[1] == n+1:
        print(-1)
    else:
        print(*res)


I found an interesting problem on https://codeforces.com/problemset/problem/1296/D:
There are $n$ monsters standing in a row numbered from $1$ to $n$. The $i$-th monster has $h_i$ health points (hp). You have your attack power equal to $a$ hp and your opponent has his attack power equal to $b$ hp.

You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to $0$.

The fight with a monster happens in turns.   You hit the monster by $a$ hp. If it is dead after your hit, you gain one point and you both proceed to the next monster.  Your opponent hits the monster by $b$ hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster.

You have some secret technique to force your opponent to skip his turn. You can use this technique at most $k$ times in total (for example, if there are two monsters and $k=4$, then you can use the technique $2$ times on the first monster and $1$ time on the second monster, but not $2$ times on the first monster and $3$ times on the second monster).

Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.

-----Input-----

The first line of the input contains four integers $n, a, b$ and $k$ ($1 \le n \le 2 \cdot 10^5, 1 \le a, b, k \le 10^9$) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.

The second line of the input contains $n$ integers $h_1, h_2, \dots, h_n$ ($1 \le h_i \le 10^9$), where $h_i$ is the health points of the $i$-th monster.

-----Output-----

Print one integer — the maximum number of points you can gain if you use the secret technique optimally.

-----Examples-----
Input
6 2 3 3
7 10 50 12 1 8

Output
5

Input
1 1 100 99
100

Output
1

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

Output
6

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

n,a,b,k=map(int,input().split())
h=input().split()
for i in range(n):
    h[i]=int(h[i])
ls=[]
for i in range(n):
    if(h[i]%(a+b)==0):
        h[i]=a+b
        if(h[i]%a==0):mauka=h[i]//a
        else:mauka=h[i]//a+1
        ls.append(mauka-1)
    else:
        h[i]=h[i]%(a+b)
        if(h[i]<=a):ls.append(0)
        else:
            if(h[i]%a==0):mauka=h[i]//a
            else:mauka=h[i]//a+1
            ls.append(mauka-1)
ls.sort()
count=0
for i in range(n):
    if(ls[i]<=k):
        k-=ls[i]
        count+=1
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/1296/E1:
This is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.

You are given a string $s$ consisting of $n$ lowercase Latin letters.

You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $s$).

After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.

The goal is to make the string sorted, i.e. all characters should be in alphabetical order.

Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.

-----Input-----

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

The second line of the input contains the string $s$ consisting of exactly $n$ lowercase Latin letters.

-----Output-----

If it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.

Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of $n$ characters, the $i$-th character should be '0' if the $i$-th character is colored the first color and '1' otherwise).

-----Examples-----
Input
9
abacbecfd

Output
YES
001010101

Input
8
aaabbcbb

Output
YES
01011011

Input
7
abcdedc

Output
NO

Input
5
abcde

Output
YES
00000

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

#!/usr/bin/env python3
import sys
input = sys.stdin.readline

class SegmentTree:
    def __init__(self, a):
        # Operator
        self.op = lambda a, b : max(a, b)
        # Identity element
        self.e = 0

        self.n = len(a)
        self.lv = (self.n - 1).bit_length()
        self.size = 2**self.lv
        self.data = [self.e] * (2*self.size - 1)
        # Bisect checking function
        self._check = lambda x, acc : acc >= x
        self._acc = self.e

        self.initialize(a)

    # Initialize data
    def initialize(self, a):
        for i in range(self.n):
            self.data[self.size + i - 1] = a[i]
        for i in range(self.size-2, -1, -1):
            self.data[i] = self.op(self.data[i*2 + 1], self.data[i*2 + 2])

    # Update ak as x (0-indexed)
    def update(self, k, x):
        k += self.size - 1
        self.data[k] = x
        while k > 0:
            k = (k - 1) // 2
            self.data[k] = self.op(self.data[2*k+1], self.data[2*k+2])

    # Min value in [l, r) (0-indexed)
    def fold(self, l, r):
        L = l + self.size; R = r + self.size
        s = self.e
        while L < R:
            if R & 1:
                R -= 1
                s = self.op(s, self.data[R-1])
            if L & 1:
                s = self.op(s, self.data[L-1])
                L += 1
            L >>= 1; R >>= 1
        return s

    def _bisect_forward(self, x, start, k):
        # When segment-k is at the bottom, accumulate and return.
        if k >= self.size - 1:
            self._acc = self.op(self._acc, self.data[k])
            if self._check(x, self._acc):
                return k - (self.size - 1)
            else:
                return -1
        width = 2**(self.lv - (k+1).bit_length() + 1)
        mid = (k+1) * width + width // 2 - self.size
        # When left-child isn't in range, just look at right-child.
        if mid <= start:
            return self._bisect_forward(x, start, 2*k + 2)
        # When segment-k is in range and has no answer in it, accumulate and return...


I found an interesting problem on https://codeforces.com/problemset/problem/1296/E2:
This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.

You are given a string $s$ consisting of $n$ lowercase Latin letters.

You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $s$).

After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.

The goal is to make the string sorted, i.e. all characters should be in alphabetical order.

Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.

-----Input-----

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

The second line of the input contains the string $s$ consisting of exactly $n$ lowercase Latin letters.

-----Output-----

In the first line print one integer $res$ ($1 \le res \le n$) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.

In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array $c$ of length $n$, where $1 \le c_i \le res$ and $c_i$ means the color of the $i$-th character.

-----Examples-----
Input
9
abacbecfd

Output
2
1 1 2 1 2 1 2 1 2

Input
8
aaabbcbb

Output
2
1 2 1 2 1 2 1 1

Input
7
abcdedc

Output
3
1 1 1 1 1 2 3

Input
5
abcde

Output
1
1 1 1 1 1

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

n = int(input())
s = input()
kol = [-1] * n
cur = 1
ind = 0
while ind < n:
    if kol[ind] != -1:
        ind += 1
    else:
        kol[ind] = cur
        best = s[ind]
        for i in range(ind+1, n):
            if kol[i] != -1:
                continue
            else:
                if s[i] >= best:
                    kol[i] = cur
                    best = s[i]
        ind += 1
        cur += 1
print(max(kol))
for i in range(n):
    print(kol[i], end = " ")


I found an interesting problem on https://codeforces.com/problemset/problem/1300/A:
Guy-Manuel and Thomas have an array $a$ of $n$ integers [$a_1, a_2, \dots, a_n$]. In one step they can add $1$ to any element of the array. Formally, in one step they can choose any integer index $i$ ($1 \le i \le n$) and do $a_i := a_i + 1$.

If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.

What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $a_1 + a_2 +$ $\dots$ $+ a_n \ne 0$ and $a_1 \cdot a_2 \cdot$ $\dots$ $\cdot a_n \ne 0$.

-----Input-----

Each test contains multiple test cases.

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

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

The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-100 \le a_i \le 100$) — elements of the array .

-----Output-----

For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.

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

Output
1
2
0
2

-----Note-----

In the first test case, the sum is $0$. If we add $1$ to the first element, the array will be $[3,-1,-1]$, the sum will be equal to $1$ and the product will be equal to $3$.

In the second test case, both product and sum are $0$. If we add $1$ to the second and the third element, the array will be $[-1,1,1,1]$, the sum will be equal to $2$ and the product will be equal to $-1$. It can be shown that fewer steps can't be enough.

In the third test case, both sum and product are non-zero, we don't need to do anything.

In the fourth test case, after adding $1$ twice to the first element the array will be $[2,-2,1]$, the sum will be $1$ and the product will be $-4$.

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

import sys
import math
from collections import defaultdict
from collections import deque
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : list(map(int, input().split()))
go = lambda : 1/0
def write(*args, sep="\n"):
  for i in args:
    sys.stdout.write("{}{}".format(i, sep))
INF = float('inf')
MOD = int(1e9 + 7)
YES = "YES"
NO = "NO"

for _ in range(int(input())):
  try:
    n = int(input())
    arr = read()
    ans = 0

    for i in range(n):
      if arr[i] == 0:
        arr[i] = 1
        ans += 1

    if sum(arr) == 0:
      print(ans + 1)
    else:
      print(ans)

  except ZeroDivisionError:
    continue

  except Exception as e:
    print(e)
    continue


I found an interesting problem on https://codeforces.com/problemset/problem/1300/C:
Anu has created her own function $f$: $f(x, y) = (x | y) - y$ where $|$ denotes the bitwise OR operation. For example, $f(11, 6) = (11|6) - 6 = 15 - 6 = 9$. It can be proved that for any nonnegative numbers $x$ and $y$ value of $f(x, y)$ is also nonnegative.

She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.

A value of an array $[a_1, a_2, \dots, a_n]$ is defined as $f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$). Elements of the array are not guaranteed to be different.

-----Output-----

Output $n$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.

-----Examples-----
Input
4
4 0 11 6

Output
11 6 4 0
Input
1
13

Output
13

-----Note-----

In the first testcase, value of the array $[11, 6, 4, 0]$ is $f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$.

$[11, 4, 0, 6]$ is also a valid answer.

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

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

B = [[0] * 33 for i in range(n)]
C = [0] * 33
for i in range(n):
    t = A[i]
    j = 0
    while t > 0:
        B[i][j] += t%2
        C[j] += B[i][j]
        t//=2
        j += 1

M2 = [1]
for i in range(40):
    M2.append(M2[-1]*2)

S = [0] * n
for i in range(n):
    for j in range(33):
        if B[i][j] == 1:
            if C[j] == 1:
                S[i] += M2[j]

ind = S.index(max(S))
ANS = [A[ind]]
for i in range(n):
    if i != ind:
        ANS.append(A[i])
print(" ".join([str(i) for i in ANS]))


I found an interesting problem on https://codeforces.com/problemset/problem/1301/E:
Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.

The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.

An Example of some correct logos:

[Image]

An Example of some incorrect logos:

[Image]

Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of $n$ rows and $m$ columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').

Adhami gave Warawreh $q$ options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is $0$.

Warawreh couldn't find the best option himself so he asked you for help, can you help him?

-----Input-----

The first line of input contains three integers $n$, $m$ and $q$ $(1 \leq n , m \leq 500, 1 \leq q \leq 3 \cdot 10^{5})$  — the number of row, the number columns and the number of options.

For the next $n$ lines, every line will contain $m$ characters. In the $i$-th line the $j$-th character will contain the color of the cell at the $i$-th row and $j$-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.

For the next $q$ lines, the input will contain four integers $r_1$, $c_1$, $r_2$ and $c_2$ $(1 \leq r_1 \leq r_2 \leq n, 1 \leq c_1 \leq c_2 \leq m)$. In that option, Adhami gave to Warawreh a sub-rectangle of the...

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

import sys
readline = sys.stdin.readline

def accumulate2d(X):
    N = len(X)
    M = len(X[0])

    for i in range(0, N):
        for j in range(1, M):
            X[i][j] += X[i][j-1]

    for j in range(0, M):
        for i in range(1, N):
            X[i][j] += X[i-1][j]

    return X

N, M, Q = map(int, readline().split())
table = [None]*100
table[ord('R')] = 0
table[ord('G')] = 1
table[ord('B')] = 2
table[ord('Y')] = 3

INF = 10**3
D = [[table[ord(s)] for s in readline().strip()] for _ in range(N)]
G = [[0]*M for _ in range(N)]

BS = 25
candi = []
geta = M
for i in range(N-1):
    for j in range(M-1):
        if D[i][j] == 0 and D[i][j+1] == 1 and D[i+1][j+1] == 2 and D[i+1][j] == 3:
            G[i][j] = 1
            nh, nw = i, j
            while True:
                k = G[nh][nw]
                fh, fw = nh-k, nw-k
                k2 = 2*(k+1)
                kh = k+1
                if fh < 0 or fw < 0 or N < fh+k2-1 or M < fw+k2-1:
                    break
                if any(D[fh][j] != 0 for j in range(fw, fw+kh)) or\
                any(D[j][fw] != 0 for j in range(fh, fh+kh)) or\
                any(D[fh][j] != 1 for j in range(fw+kh, fw+k2)) or\
                any(D[j][fw+k2-1] != 1 for j in range(fh, fh+kh)) or\
                any(D[j][fw+k2-1] != 2 for j in range(fh+kh, fh+k2)) or\
                any(D[fh+k2-1][j] != 2 for j in range(fw+kh, fw+k2)) or\
                any(D[fh+k2-1][j] != 3 for j in range(fw, fw+kh)) or\
                any(D[j][fw] != 3 for j in range(fh+kh, fh+k2)):
                    break
                G[nh][nw] += 1
            if G[nh][nw] > BS:
                candi.append((nh, nw))

Gnum = [None] + [[[0]*M for _ in range(N)] for _ in range(BS)]
for h in range(N):
    for w in range(M):
        if G[h][w] > 0:
            for k in range(1, min(BS, G[h][w])+1):
                Gnum[k][h][w] = 1

Gnum = [None] + [accumulate2d(g) for g in Gnum[1:]]

Ans = [None]*Q
for qu in range(Q):
    h1, w1, h2, w2 = map(lambda x: int(x)-1,...


I found an interesting problem on https://codeforces.com/problemset/problem/1303/A:
You are given a string $s$. Each character is either 0 or 1.

You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.

You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?

-----Input-----

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

Then $t$ lines follow, each representing a test case. Each line contains one string $s$ ($1 \le |s| \le 100$); each character of $s$ is either 0 or 1.

-----Output-----

Print $t$ integers, where the $i$-th integer is the answer to the $i$-th testcase (the minimum number of 0's that you have to erase from $s$).

-----Example-----
Input
3
010011
0
1111000

Output
2
0
0

-----Note-----

In the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).

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

for _ in range(int(input())):
    s = input()
    res = s.count('0')
    i = 0
    while i < len(s) and s[i] == '0':
        res -= 1
        i += 1
    j = len(s) - 1
    while j > i and s[j] == '0':
        res -= 1
        j -= 1
    print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1303/E:
You are given a string $s$. You can build new string $p$ from $s$ using the following operation no more than two times:   choose any subsequence $s_{i_1}, s_{i_2}, \dots, s_{i_k}$ where $1 \le i_1 < i_2 < \dots < i_k \le |s|$;  erase the chosen subsequence from $s$ ($s$ can become empty);  concatenate chosen subsequence to the right of the string $p$ (in other words, $p = p + s_{i_1}s_{i_2}\dots s_{i_k}$).

Of course, initially the string $p$ is empty.

For example, let $s = \text{ababcd}$. At first, let's choose subsequence $s_1 s_4 s_5 = \text{abc}$ — we will get $s = \text{bad}$ and $p = \text{abc}$. At second, let's choose $s_1 s_2 = \text{ba}$ — we will get $s = \text{d}$ and $p = \text{abcba}$. So we can build $\text{abcba}$ from $\text{ababcd}$.

Can you build a given string $t$ using the algorithm above?

-----Input-----

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

Next $2T$ lines contain test cases — two per test case. The first line contains string $s$ consisting of lowercase Latin letters ($1 \le |s| \le 400$) — the initial string.

The second line contains string $t$ consisting of lowercase Latin letters ($1 \le |t| \le |s|$) — the string you'd like to build.

It's guaranteed that the total length of strings $s$ doesn't exceed $400$.

-----Output-----

Print $T$ answers — one per test case. Print YES (case insensitive) if it's possible to build $t$ and NO (case insensitive) otherwise.

-----Example-----
Input
4
ababcd
abcba
a
b
defi
fed
xyz
x

Output
YES
NO
NO
YES

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

def main():
    T = int(input().strip())
    for _ in range(T):
        s = input().strip()
        t = input().strip()
        n = len(s)

        find = [[n] * 26 for _ in range(n + 2)]
        for i in range(n - 1, -1, -1):
            find[i][:] = find[i + 1]
            find[i][ord(s[i]) - ord("a")] = i

        def interleaving(a, b):
            dp = [n] * (len(b) + 1)
            for i in range(len(a) + 1):
                for j in range(len(b) + 1):
                    if i == j == 0:
                        dp[j] = -1
                        continue
                    res = n
                    if i > 0:
                        res = min(res, find[dp[j] + 1][ord(a[i - 1]) - ord("a")])
                    if j > 0:
                        res = min(res, find[dp[j - 1] + 1][ord(b[j - 1]) - ord("a")])
                    dp[j] = res
            return dp[-1] < n

        if any(interleaving(t[:i], t[i:]) for i in range(len(t))):
            print("YES")
        else:
            print("NO")

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1304/B:
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.

Gildong loves this concept so much, so he wants to play with it. He has $n$ distinct strings of equal length $m$. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 100$, $1 \le m \le 50$) — the number of strings and the length of each string.

Next $n$ lines contain a string of length $m$ each, consisting of lowercase Latin letters only. All strings are distinct.

-----Output-----

In the first line, print the length of the longest palindrome string you made.

In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.

-----Examples-----
Input
3 3
tab
one
bat

Output
6
tabbat

Input
4 2
oo
ox
xo
xx

Output
6
oxxxxo

Input
3 5
hello
codef
orces

Output
0

Input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji

Output
20
ababwxyzijjizyxwbaba

-----Note-----

In the first example, "battab" is also a valid answer.

In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.

In the third example, the empty string is the only valid palindrome string.

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

n, m = list(map(int, input().split()))
ar = []
for _ in range(n):
    ar.append(input())
ans1 = ''
ans2 = ''
kek = set()
for i in range(n):
    for j in range(i + 1, n):
        if ar[i] == ar[j][::-1]:
            ans1 += ar[i]
            ans2 = ar[j] + ans2
            kek.add(ar[i])
for i in range(n):
    if ar[i] == ar[i][::-1] and ar[i] not in kek:
        ans1 += ar[i]
        break
print(len(ans1) + len(ans2))
print(ans1 + ans2)


I found an interesting problem on https://codeforces.com/problemset/problem/1304/E:
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?

Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.

First, he'll provide you a tree (not 1-tree) with $n$ vertices, then he will ask you $q$ queries. Each query contains $5$ integers: $x$, $y$, $a$, $b$, and $k$. This means you're asked to determine if there exists a path from vertex $a$ to $b$ that contains exactly $k$ edges after adding a bidirectional edge between vertices $x$ and $y$. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.

-----Input-----

The first line contains an integer $n$ ($3 \le n \le 10^5$), the number of vertices of the tree.

Next $n-1$ lines contain two integers $u$ and $v$ ($1 \le u,v \le n$, $u \ne v$) each, which means there is an edge between vertex $u$ and $v$. All edges are bidirectional and distinct.

Next line contains an integer $q$ ($1 \le q \le 10^5$), the number of queries Gildong wants to ask.

Next $q$ lines contain five integers $x$, $y$, $a$, $b$, and $k$ each ($1 \le x,y,a,b \le n$, $x \ne y$, $1 \le k \le 10^9$) – the integers explained in the description. It is guaranteed that the edge between $x$ and $y$ does not exist in the original tree.

-----Output-----

For each query, print "YES" if there exists a path that contains exactly $k$ edges from vertex $a$ to $b$ after adding an edge between vertices $x$ and $y$. Otherwise, print "NO".

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

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

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 collections import deque

class LCA():
    def __init__(self, G, root):
        self.n = len(G)
        self.dep=[0]*self.n
        self.par=[[-1]*self.n for i in range(18)]

        def bfs(root):
            que = deque()
            que.append((-1,root,0))
            while que:
                p,v,d = que.pop()
                self.dep[v]=d
                self.par[0][v]=p
                for to in G[v]:
                    if to != p:
                        que.append((v,to,d+1))

        bfs(root)

        for i in range(17):
            for j in range(self.n):
                self.par[i+1][j]=self.par[i][self.par[i][j]]

    def lca(self,a,b):
        if self.dep[a]>self.dep[b]:
            a,b=b,a
        for i in range(18):
            if (self.dep[b]-self.dep[a]) & 1<<i:
                b=self.par[i][b]
        if a==b:
            return a
        for i in range(18)[::-1]:
            if self.par[i][a]!=self.par[i][b]:
                a=self.par[i][a]
                b=self.par[i][b]
        return self.par[0][a]

    def dist(self, a,b):
        lca = self.lca(a,b)
        return self.dep[a]+self.dep[b]-2*self.dep[lca]

n = int(input())
G = [[] for i in range(n)]

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

L = LCA(G, 0)

q = int(input())
for i in range(q):
    x,y,a,b,k = list(map(int, input().split()))
    x,y,a,b = x-1,y-1,a-1,b-1

    ab = L.dist(a,b)
    base = [ab]

    ax = L.dist(a,x)
    ay = L.dist(a,y)
    bx = L.dist(b,x)
    by = L.dist(b,y)

    base.append(ax+1+by)
    base.append(ay+1+bx)

    flag = any(ki<=k and (k-ki)%2==0 for ki in base)

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


I found an interesting problem on https://codeforces.com/problemset/problem/1305/B:
Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!

We say that a string formed by $n$ characters '(' or ')' is simple if its length $n$ is even and positive, its first $\frac{n}{2}$ characters are '(', and its last $\frac{n}{2}$ characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.

Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'.

Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.

Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?

A sequence of characters $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters.

-----Input-----

The only line of input contains a string $s$ ($1 \le |s| \le 1000$) formed by characters '(' and ')', where $|s|$ is the length of $s$.

-----Output-----

In the first line, print an integer $k$  — the minimum number of operations you have to apply. Then, print $2k$ lines describing the operations in the following format:

For each operation, print...

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

s = input()

p_lo = 0
p_hi = len(s) - 1
rem_lo = []
rem_hi = []

while p_lo < p_hi:
    if s[p_lo] == ")":
        p_lo += 1
    elif s[p_hi] == "(":
        p_hi -= 1
    else:
        rem_lo.append(p_lo)
        rem_hi.append(p_hi)
        p_lo += 1
        p_hi -= 1

if len(rem_lo) == 0:
    print(0)
else:
    print(1)
    print(2*len(rem_lo))
    print(*[x + 1 for x in rem_lo + list(reversed(rem_hi))])


I found an interesting problem on https://codeforces.com/problemset/problem/1305/C:
To become the king of Codeforces, Kuroni has to solve the following problem.

He is given $n$ numbers $a_1, a_2, \dots, a_n$. Help Kuroni to calculate $\prod_{1\le i<j\le n} |a_i - a_j|$. As result can be very big, output it modulo $m$.

If you are not familiar with short notation, $\prod_{1\le i<j\le n} |a_i - a_j|$ is equal to $|a_1 - a_2|\cdot|a_1 - a_3|\cdot$ $\dots$ $\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$ $\dots$ $\cdot|a_2 - a_n| \cdot$ $\dots$ $\cdot |a_{n-1} - a_n|$. In other words, this is the product of $|a_i - a_j|$ for all $1\le i < j \le n$.

-----Input-----

The first line contains two integers $n$, $m$ ($2\le n \le 2\cdot 10^5$, $1\le m \le 1000$) — number of numbers and modulo.

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

-----Output-----

Output the single number — $\prod_{1\le i<j\le n} |a_i - a_j| \bmod m$.

-----Examples-----
Input
2 10
8 5

Output
3
Input
3 12
1 4 5

Output
0
Input
3 7
1 4 9

Output
1

-----Note-----

In the first sample, $|8 - 5| = 3 \equiv 3 \bmod 10$.

In the second sample, $|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$.

In the third sample, $|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$.

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

from sys import stdin
input = stdin.readline
n,m = map(int,input().split())
l = list(map(int,input().split()))
if n > m:
	print(0)
else:
	res = 1
	for i in range(n-1):
		for j in range(i+1,n):
			res = ((res*abs(l[i]-l[j])) % m)
	print(res%m)


I found an interesting problem on https://codeforces.com/problemset/problem/1305/F:
Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:

You have an array $a$ consisting of $n$ positive integers. An operation consists of choosing an element and either adding $1$ to it or subtracting $1$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $1$. Find the minimum number of operations needed to make the array good.

Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!

-----Input-----

The first line contains an integer $n$ ($2 \le n \le 2 \cdot 10^5$)  — the number of elements in the array.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$. ($1 \le a_i \le 10^{12}$)  — the elements of the array.

-----Output-----

Print a single integer  — the minimum number of operations required to make the array good.

-----Examples-----
Input
3
6 2 4

Output
0

Input
5
9 8 7 3 1

Output
4

-----Note-----

In the first example, the first array is already good, since the greatest common divisor of all the elements is $2$.

In the second example, we may apply the following operations:

  Add $1$ to the second element, making it equal to $9$.  Subtract $1$ from the third element, making it equal to $6$.  Add $1$ to the fifth element, making it equal to $2$.  Add $1$ to the fifth element again, making it equal to $3$.

The greatest common divisor of all elements will then be equal to $3$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.

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

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

primes = set()
for x in random.choices(a, k=min(n, 30)):
    for y in (x-1, x, x+1):
        d = 2
        while d * d <= y:
            while y % d == 0:
                primes.add(d)
                y //= d
            d += 1 + (d & 1)
        if y > 1:
            primes.add(y)

ans = float('inf')
for p in primes:
    cand = 0
    for x in a:
        if x < p:
            cand += p - x
        else:
            r = x % p
            cand += min(r, p-r)
        if cand >= ans:
            break
    else:
        ans = cand

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1307/C:
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.

The text is a string $s$ of lowercase Latin letters. She considers a string $t$ as hidden in string $s$ if $t$ exists as a subsequence of $s$ whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices $1$, $3$, and $5$, which form an arithmetic progression with a common difference of $2$. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of $S$ are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!

For example, in the string aaabb, a is hidden $3$ times, b is hidden $2$ times, ab is hidden $6$ times, aa is hidden $3$ times, bb is hidden $1$ time, aab is hidden $2$ times, aaa is hidden $1$ time, abb is hidden $1$ time, aaab is hidden $1$ time, aabb is hidden $1$ time, and aaabb is hidden $1$ time. The number of occurrences of the secret message is $6$.

-----Input-----

The first line contains a string $s$ of lowercase Latin letters ($1 \le |s| \le 10^5$) — the text that Bessie intercepted.

-----Output-----

Output a single integer  — the number of occurrences of the secret message.

-----Examples-----
Input
aaabb

Output
6

Input
usaco

Output
1

Input
lol

Output
2

-----Note-----

In the first example, these are all the hidden strings and their indice sets:   a occurs at $(1)$, $(2)$, $(3)$  b occurs at $(4)$, $(5)$  ab occurs at $(1,4)$, $(1,5)$, $(2,4)$, $(2,5)$, $(3,4)$, $(3,5)$  aa occurs at $(1,2)$, $(1,3)$, $(2,3)$  bb occurs at $(4,5)$  aab occurs at $(1,3,5)$, $(2,3,4)$  aaa occurs at $(1,2,3)$  abb occurs at $(3,4,5)$  aaab occurs at $(1,2,3,4)$  aabb occurs at $(2,3,4,5)$  aaabb occurs at $(1,2,3,4,5)$  Note that all the sets of indices are arithmetic progressions.

In the second example, no hidden string occurs more than once.

In the third...

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

import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
mii=lambda:list(map(int,input().split()))

s=input().strip()
d=[0]*1000
e=[0]*1000

hist=[0]*26
for i in s:
    j=ord(i)-ord('a')
    for k in range(26):
        e[k*26+j]+=hist[k]
    hist[j]+=1
    d[j]+=1

print(max(d+e))


I found an interesting problem on https://codeforces.com/problemset/problem/1310/A:
VK news recommendation system daily selects interesting publications of one of $n$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $i$ batch algorithm selects $a_i$ publications.

The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $i$-th category within $t_i$ seconds.

What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.

-----Input-----

The first line of input consists of single integer $n$ — the number of news categories ($1 \le n \le 200\,000$).

The second line of input consists of $n$ integers $a_i$ — the number of publications of $i$-th category selected by the batch algorithm ($1 \le a_i \le 10^9$).

The third line of input consists of $n$ integers $t_i$ — time it takes for targeted algorithm to find one new publication of category $i$ ($1 \le t_i \le 10^5)$.

-----Output-----

Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.

-----Examples-----
Input
5
3 7 9 7 8
5 2 5 7 5

Output
6

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

Output
0

-----Note-----

In the first example, it is possible to find three publications of the second type, which will take 6 seconds.

In the second example, all news categories contain a different number of publications.

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

import heapq
h = []
n = int(input())
a = [int(x) for x in input().strip().split()]
t = [int(x) for x in input().strip().split()]
for i in range(len(t)):
    a[i] = [a[i], t[i]]
a.sort(key = lambda x: (x[0], -x[1]))
prev, i, ans= a[0][0], 1, 0
#print(a)
while(i<len(a)):
    #print(prev, ans, h)
    if h:
        if a[i][0] == prev:
            heapq.heappush(h, [-a[i][1], a[i][0]])
            i += 1
        elif a[i][0] == prev+1:
            heapq.heappush(h, [-a[i][1], a[i][0]])
            p = heapq.heappop(h)
            ans += (-p[0]*(prev + 1 - p[1]))
            prev = prev+1
            i += 1
        else:
            p = heapq.heappop(h)
            ans += (-p[0]*(prev + 1 - p[1]))
            prev = prev+1
    else:
        if a[i][0] != prev:
            prev = a[i][0]
            i+=1
        else:
            heapq.heappush(h, [-a[i][1], a[i][0]])
            i+=1
while h:
    p = heapq.heappop(h)
    ans += (-p[0]*(prev + 1 - p[1]))
    prev = prev+1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1311/A:
You are given two positive integers $a$ and $b$.

In one move, you can change $a$ in the following way:

  Choose any positive odd integer $x$ ($x > 0$) and replace $a$ with $a+x$;  choose any positive even integer $y$ ($y > 0$) and replace $a$ with $a-y$.

You can perform as many such operations as you want. You can choose the same numbers $x$ and $y$ in different moves.

Your task is to find the minimum number of moves required to obtain $b$ from $a$. It is guaranteed that you can always obtain $b$ from $a$.

You have to answer $t$ independent test cases.

-----Input-----

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

Then $t$ test cases follow. Each test case is given as two space-separated integers $a$ and $b$ ($1 \le a, b \le 10^9$).

-----Output-----

For each test case, print the answer — the minimum number of moves required to obtain $b$ from $a$ if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain $b$ from $a$.

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

Output
1
0
2
2
1

-----Note-----

In the first test case, you can just add $1$.

In the second test case, you don't need to do anything.

In the third test case, you can add $1$ two times.

In the fourth test case, you can subtract $4$ and add $1$.

In the fifth test case, you can just subtract $6$.

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

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

import sys
from collections import Counter

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

for _ in range(INT()):
    a, b = MAP()

    if a == b:
        print(0)
    elif a < b:
        if abs(a - b) % 2 == 0:
            print(2)
        else:
            print(1)
    else:
        if abs(a - b) % 2 == 0:
            print(1)
        else:
            print(2)


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

You are also given a set of distinct positions $p_1, p_2, \dots, p_m$, where $1 \le p_i < n$. The position $p_i$ means that you can swap elements $a[p_i]$ and $a[p_i + 1]$. You can apply this operation any number of times for each of the given positions.

Your task is to determine if it is possible to sort the initial array in non-decreasing order ($a_1 \le a_2 \le \dots \le a_n$) using only allowed swaps.

For example, if $a = [3, 2, 1]$ and $p = [1, 2]$, then we can first swap elements $a[2]$ and $a[3]$ (because position $2$ is contained in the given set $p$). We get the array $a = [3, 1, 2]$. Then we swap $a[1]$ and $a[2]$ (position $1$ is also contained in $p$). We get the array $a = [1, 3, 2]$. Finally, we swap $a[2]$ and $a[3]$ again and get the array $a = [1, 2, 3]$, sorted in non-decreasing order.

You can see that if $a = [4, 1, 2, 3]$ and $p = [3, 2]$ then you cannot sort the array.

You have to answer $t$ independent test cases.

-----Input-----

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

Then $t$ test cases follow. The first line of each test case contains two integers $n$ and $m$ ($1 \le m < n \le 100$) — the number of elements in $a$ and the number of elements in $p$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$). The third line of the test case contains $m$ integers $p_1, p_2, \dots, p_m$ ($1 \le p_i < n$, all $p_i$ are distinct) — the set of positions described in the problem statement.

-----Output-----

For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order ($a_1 \le a_2 \le \dots \le a_n$) using only allowed swaps. Otherwise, print "NO".

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

Output
YES
NO
YES
YES
NO
YES

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

from sys import stdin

def solve():
    n, m = map(int, input().split())
    a = list(map(int, input().split()))
    u = [0] * n
    p = list(map(int, input().split()))
    for x in p:
        u[x-1] = 1
    p = []
    for i in range(n):
        if u[i] == 0:
            p.append(i)
    pos = 0
    prevmx = -1
    curmx = -1
    curmn = 101
    for i in range(n):
        curmn = min(a[i], curmn)
        curmx = max(a[i], curmx)
        if i == p[pos]:
            if curmn < prevmx:
                return print("NO")
            prevmx = curmx
            curmx = -1
            curmn = 101
            pos += 1
    print("YES")

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


I found an interesting problem on https://codeforces.com/problemset/problem/1311/C:
You want to perform the combo on your opponent in one popular fighting game. The combo is the string $s$ consisting of $n$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $s$. I.e. if $s=$"abca" then you have to press 'a', then 'b', 'c' and 'a' again.

You know that you will spend $m$ wrong tries to perform the combo and during the $i$-th try you will make a mistake right after $p_i$-th button ($1 \le p_i < n$) (i.e. you will press first $p_i$ buttons right and start performing the combo from the beginning). It is guaranteed that during the $m+1$-th try you press all buttons right and finally perform the combo.

I.e. if $s=$"abca", $m=2$ and $p = [1, 3]$ then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.

Your task is to calculate for each button (letter) the number of times you'll press it.

You have to answer $t$ independent test cases.

-----Input-----

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

Then $t$ test cases follow.

The first line of each test case contains two integers $n$ and $m$ ($2 \le n \le 2 \cdot 10^5$, $1 \le m \le 2 \cdot 10^5$) — the length of $s$ and the number of tries correspondingly.

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

The third line of each test case contains $m$ integers $p_1, p_2, \dots, p_m$ ($1 \le p_i < n$) — the number of characters pressed right during the $i$-th try.

It is guaranteed that the sum of $n$ and the sum of $m$ both does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$, $\sum m \le 2 \cdot 10^5$).

It is guaranteed that the answer for each letter does not exceed $2 \cdot 10^9$.

-----Output-----

For each...

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

from string import ascii_lowercase

t = int(input())

for _ in range(t):
    n, m = [int(x) for x in input().split()]

    s = input()
    count = {x : 0 for x in ascii_lowercase}
    errors = [int(x) for x in input().split()]

    errors = sorted(errors)

    e_idx = 0
    for j, c in enumerate(s):
        while e_idx < m and errors[e_idx] <= j:
            e_idx += 1
        count[c] += (m - e_idx) + 1

    print(*[count[c] for c in ascii_lowercase])


I found an interesting problem on https://codeforces.com/problemset/problem/1311/D:
You are given three integers $a \le b \le c$.

In one move, you can add $+1$ or $-1$ to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.

You have to perform the minimum number of such operations in order to obtain three integers $A \le B \le C$ such that $B$ is divisible by $A$ and $C$ is divisible by $B$.

You have to answer $t$ independent test cases.

-----Input-----

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

The next $t$ lines describe test cases. Each test case is given on a separate line as three space-separated integers $a, b$ and $c$ ($1 \le a \le b \le c \le 10^4$).

-----Output-----

For each test case, print the answer. In the first line print $res$ — the minimum number of operations you have to perform to obtain three integers $A \le B \le C$ such that $B$ is divisible by $A$ and $C$ is divisible by $B$. On the second line print any suitable triple $A, B$ and $C$.

-----Example-----
Input
8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46

Output
1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48

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

mii = 3*10**4

factors = [set() for _ in range(mii + 1)]
factors[1] = set([1])

for k in range(2, mii + 1):
    for p in range(2, mii + 1):
        if k % p == 0:
            factors[k] = set(ole*p for ole in factors[k//p]) | factors[k//p]
            break
        elif p * p > k:
            factors[k] = set([1, k])
            break

# print(factors[:20])

t = int(input())
for _ in range(t):

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

    best_score = 10**15
    best_trip = a, b, c

    for k in range(1, mii + 1):
        this_b = k
        if c % this_b < this_b - (c % this_b):
            this_c = this_b * (c // this_b)
        else:
            this_c = this_b * (c // this_b + 1)

        this_c = max(this_c, this_b)

        this_a = -1
        loss_a = 10**15
        for cur_a in factors[this_b]:
            if abs(a - cur_a) < loss_a:
                this_a = cur_a
                loss_a = abs(a - cur_a)

        cur_score = abs(a - this_a) + abs(b - this_b) + abs(c - this_c)
        if cur_score < best_score:
            best_score = cur_score
            best_trip = this_a, this_b, this_c

    print(best_score)
    print(*best_trip)


I found an interesting problem on https://codeforces.com/problemset/problem/1311/F:
There are $n$ points on a coordinate axis $OX$. The $i$-th point is located at the integer point $x_i$ and has a speed $v_i$. It is guaranteed that no two points occupy the same coordinate. All $n$ points move with the constant speed, the coordinate of the $i$-th point at the moment $t$ ($t$ can be non-integer) is calculated as $x_i + t \cdot v_i$.

Consider two points $i$ and $j$. Let $d(i, j)$ be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points $i$ and $j$ coincide at some moment, the value $d(i, j)$ will be $0$.

Your task is to calculate the value $\sum\limits_{1 \le i < j \le n}$ $d(i, j)$ (the sum of minimum distances over all pairs of points).

-----Input-----

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

The second line of the input contains $n$ integers $x_1, x_2, \dots, x_n$ ($1 \le x_i \le 10^8$), where $x_i$ is the initial coordinate of the $i$-th point. It is guaranteed that all $x_i$ are distinct.

The third line of the input contains $n$ integers $v_1, v_2, \dots, v_n$ ($-10^8 \le v_i \le 10^8$), where $v_i$ is the speed of the $i$-th point.

-----Output-----

Print one integer — the value $\sum\limits_{1 \le i < j \le n}$ $d(i, j)$ (the sum of minimum distances over all pairs of points).

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

Output
3

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

Output
19

Input
2
2 1
-3 0

Output
0

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

import sys
input = sys.stdin.readline

n=int(input())
X=list(map(int,input().split()))
V=list(map(int,input().split()))

XV=[(X[i],V[i]) for i in range(n)]

#compression_dict_x={a: ind for ind, a in enumerate(sorted(set(X)))}
compression_dict_v={a: ind+2 for ind, a in enumerate(sorted(set(V)))}

XV=[(XV[i][0], compression_dict_v[XV[i][1]]) for i in range(n)]
XV.sort(reverse=True)

LEN=len(compression_dict_v)+3

BIT1=[0]*(LEN+1)

def update1(v,w):
    while v<=LEN:
        BIT1[v]+=w
        v+=(v&(-v))

def getvalue1(v):
    ANS=0
    while v!=0:
        ANS+=BIT1[v]
        v-=(v&(-v))
    return ANS

BIT2=[0]*(LEN+1)

def update2(v,w):
    while v<=LEN:
        BIT2[v]+=w
        v+=(v&(-v))

def getvalue2(v):
    ANS=0
    while v!=0:
        ANS+=BIT2[v]
        v-=(v&(-v))
    return ANS

ANS=0
for x,v in XV:
    ANS+=(getvalue2(LEN)-getvalue2(v-1))-(getvalue1(LEN)-getvalue1(v-1))*x
    #print(getvalue2(LEN),getvalue2(v-1),getvalue1(LEN),getvalue1(v-1))
    #print(x,v,ANS)

    update1(v,1)
    update2(v,x)

print(ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1312/A:
You are given two integers $n$ and $m$ ($m < n$). Consider a convex regular polygon of $n$ vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). [Image] Examples of convex regular polygons

Your task is to say if it is possible to build another convex regular polygon with $m$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.

You have to answer $t$ independent test cases.

-----Input-----

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

The next $t$ lines describe test cases. Each test case is given as two space-separated integers $n$ and $m$ ($3 \le m < n \le 100$) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.

-----Output-----

For each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with $m$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.

-----Example-----
Input
2
6 3
7 3

Output
YES
NO

-----Note----- $0$ The first test case of the example

It can be shown that the answer for the second test case of the example is "NO".

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

for i in range(int(input())):
    n, m = list(map(int, input().split()))
    if n % m == 0:
        print('YES')
    else:
        print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1312/B:
You are given an array $a_1, a_2, \dots , a_n$. Array is good if for each pair of indexes $i < j$ the condition $j - a_j \ne i - a_i$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).

For example, if $a = [1, 1, 3, 5]$, then shuffled arrays $[1, 3, 5, 1]$, $[3, 5, 1, 1]$ and $[5, 3, 1, 1]$ are good, but shuffled arrays $[3, 1, 5, 1]$, $[1, 1, 3, 5]$ and $[1, 1, 5, 3]$ aren't.

It's guaranteed that it's always possible to shuffle an array to meet this condition.

-----Input-----

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

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

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

-----Output-----

For each test case print the shuffled version of the array $a$ which is good.

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

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

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

import sys
input = sys.stdin.readline

t=int(input())
for tests in range(t):
    n=int(input())
    A=list(map(int,input().split()))
    print(*sorted(A,reverse=True))


I found an interesting problem on https://codeforces.com/problemset/problem/1312/C:
Suppose you are performing the following algorithm. There is an array $v_1, v_2, \dots, v_n$ filled with zeroes at start. The following operation is applied to the array several times — at $i$-th step ($0$-indexed) you can:   either choose position $pos$ ($1 \le pos \le n$) and increase $v_{pos}$ by $k^i$;  or not choose any position and skip this step.

You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array $v$ equal to the given array $a$ ($v_j = a_j$ for each $j$) after some step?

-----Input-----

The first line contains one integer $T$ ($1 \le T \le 1000$) — the number of test cases. Next $2T$ lines contain test cases — two lines per test case.

The first line of each test case contains two integers $n$ and $k$ ($1 \le n \le 30$, $2 \le k \le 100$) — the size of arrays $v$ and $a$ and value $k$ used in the algorithm.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^{16}$) — the array you'd like to achieve.

-----Output-----

For each test case print YES (case insensitive) if you can achieve the array $a$ after some step or NO (case insensitive) otherwise.

-----Example-----
Input
5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810

Output
YES
YES
NO
NO
YES

-----Note-----

In the first test case, you can stop the algorithm before the $0$-th step, or don't choose any position several times and stop the algorithm.

In the second test case, you can add $k^0$ to $v_1$ and stop the algorithm.

In the third test case, you can't make two $1$ in the array $v$.

In the fifth test case, you can skip $9^0$ and $9^1$, then add $9^2$ and $9^3$ to $v_3$, skip $9^4$ and finally, add $9^5$ to $v_2$.

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

import sys
input=lambda: sys.stdin.readline().rstrip()
t=int(input())
for _ in range(t):
  n,k=list(map(int,input().split()))
  A=[int(i) for i in input().split()]
  B=[0]*100
  for a in A:
    ct=0
    while a:
      B[ct]+=a%k
      a//=k
      ct+=1
  print("YES" if max(B)<=1 else "NO")