I found an interesting problem on https://codeforces.com/problemset/problem/1159/B:
Let's call an array of non-negative integers $a_1, a_2, \ldots, a_n$ a $k$-extension for some non-negative integer $k$ if for all possible pairs of indices $1 \leq i, j \leq n$ the inequality $k \cdot |i - j| \leq min(a_i, a_j)$ is satisfied. The expansion coefficient of the array $a$ is the maximal integer $k$ such that the array $a$ is a $k$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.

You are given an array of non-negative integers $a_1, a_2, \ldots, a_n$. Find its expansion coefficient.

-----Input-----

The first line contains one positive integer $n$ — the number of elements in the array $a$ ($2 \leq n \leq 300\,000$). The next line contains $n$ non-negative integers $a_1, a_2, \ldots, a_n$, separated by spaces ($0 \leq a_i \leq 10^9$).

-----Output-----

Print one non-negative integer — expansion coefficient of the array $a_1, a_2, \ldots, a_n$.

-----Examples-----
Input
4
6 4 5 5

Output
1
Input
3
0 1 2

Output
0
Input
4
821 500 479 717

Output
239

-----Note-----

In the first test, the expansion coefficient of the array $[6, 4, 5, 5]$ is equal to $1$ because $|i-j| \leq min(a_i, a_j)$, because all elements of the array satisfy $a_i \geq 3$. On the other hand, this array isn't a $2$-extension, because $6 = 2 \cdot |1 - 4| \leq min(a_1, a_4) = 5$ is false.

In the second test, the expansion coefficient of the array $[0, 1, 2]$ is equal to $0$ because this array is not a $1$-extension, but it is $0$-extension.

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

def main():
    from sys import stdin, stdout

    def read():
        return stdin.readline().rstrip('\n')

    def read_array(sep=None, maxsplit=-1):
        return read().split(sep, maxsplit)

    def read_int():
        return int(read())

    def read_int_array(sep=None, maxsplit=-1):
        return [int(a) for a in read_array(sep, maxsplit)]

    def write(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in args) + end)

    def write_array(array, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in array) + end)

    n = read_int()
    nums = read_int_array()
    out = nums[0]
    first = nums[0]
    for i in range(1, n):
        out = min(out, min(nums[i], first) // i)
    last = nums[-1]
    for i in range(n-2, 0, -1):
        out = min(out, min(nums[i], last) // (n-1 - i))
    write(out)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1162/A:
You are planning to build housing on a street. There are $n$ spots available on the street on which you can build a house. The spots are labeled from $1$ to $n$ from left to right. In each spot, you can build a house with an integer height between $0$ and $h$.

In each spot, if a house has height $a$, you will gain $a^2$ dollars from it.

The city has $m$ zoning restrictions. The $i$-th restriction says that the tallest house from spots $l_i$ to $r_i$ (inclusive) must be at most $x_i$.

You would like to build houses to maximize your profit. Determine the maximum profit possible.

-----Input-----

The first line contains three integers $n$, $h$, and $m$ ($1 \leq n,h,m \leq 50$) — the number of spots, the maximum height, and the number of restrictions.

Each of the next $m$ lines contains three integers $l_i$, $r_i$, and $x_i$ ($1 \leq l_i \leq r_i \leq n$, $0 \leq x_i \leq h$) — left and right limits (inclusive) of the $i$-th restriction and the maximum possible height in that range.

-----Output-----

Print a single integer, the maximum profit you can make.

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

Output
14

Input
4 10 2
2 3 8
3 4 7

Output
262

-----Note-----

In the first example, there are $3$ houses, the maximum height of a house is $3$, and there are $3$ restrictions. The first restriction says the tallest house between $1$ and $1$ must be at most $1$. The second restriction says the tallest house between $2$ and $2$ must be at most $3$. The third restriction says the tallest house between $3$ and $3$ must be at most $2$.

In this case, it is optimal to build houses with heights $[1, 3, 2]$. This fits within all the restrictions. The total profit in this case is $1^2 + 3^2 + 2^2 = 14$.

In the second example, there are $4$ houses, the maximum height of a house is $10$, and there are $2$ restrictions. The first restriction says the tallest house from $2$ to $3$ must be at most $8$. The second restriction says the tallest house from $3$ to $4$ must be at most $7$.

In this case, it's...

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

n, h, m = [int(i) for i in input().split()]
a = [h] * (n + 1)
for i in range(m):
    l, r, x = [int(i) for i in input().split()]
    for j in range(l, r + 1):
        a[j] = min(a[j], x)
ans = 0
for i in range(1, n + 1):
    ans += a[i] * a[i]
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1162/B:
You are given two $n \times m$ matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly increasing. A matrix is increasing if all rows are strictly increasing and all columns are strictly increasing.

For example, the matrix $\begin{bmatrix} 9&10&11\\ 11&12&14\\ \end{bmatrix}$ is increasing because each individual row and column is strictly increasing. On the other hand, the matrix $\begin{bmatrix} 1&1\\ 2&3\\ \end{bmatrix}$ is not increasing because the first row is not strictly increasing.

Let a position in the $i$-th row (from top) and $j$-th column (from left) in a matrix be denoted as $(i, j)$.

In one operation, you can choose any two numbers $i$ and $j$ and swap the number located in $(i, j)$ in the first matrix with the number in $(i, j)$ in the second matrix. In other words, you can swap two numbers in different matrices if they are located in the corresponding positions.

You would like to make both matrices increasing by performing some number of operations (possibly none). Determine if it is possible to do this. If it is, print "Possible", otherwise, print "Impossible".

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \leq n,m \leq 50$) — the dimensions of each matrix.

Each of the next $n$ lines contains $m$ integers $a_{i1}, a_{i2}, \ldots, a_{im}$ ($1 \leq a_{ij} \leq 10^9$) — the number located in position $(i, j)$ in the first matrix.

Each of the next $n$ lines contains $m$ integers $b_{i1}, b_{i2}, \ldots, b_{im}$ ($1 \leq b_{ij} \leq 10^9$) — the number located in position $(i, j)$ in the second matrix.

-----Output-----

Print a string "Impossible" or "Possible".

-----Examples-----
Input
2 2
2 10
11 5
9 4
3 12

Output
Possible

Input
2 3
2 4 5
4 5 6
3 6 7
8 10 11

Output
Possible

Input
3 2
1 3
2 4
5 10
3 1
3 6
4...

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

import sys
input = sys.stdin.readline

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

arr1=[]
for i in range(n):
	arr1.append(list(map(int,input().split())))

arr2=[]
for i in range(n):
	arr2.append(list(map(int,input().split())))

arr3=[]
arr4=[]
for i in range(n):
	arr3.append([])
	arr4.append([])
	for j in range(m):
		arr3[i].append(min(arr1[i][j],arr2[i][j]))
		arr4[i].append(max(arr1[i][j],arr2[i][j]))

flag=False
for i in range(n):
	for j in range(m):
		try:
			if arr3[i][j]>=arr3[i][j+1] or arr4[i][j]>=arr4[i][j+1]:
				print("Impossible")
				flag=True
				break
		except:
			pass

		try:
			if arr3[i][j]>=arr3[i+1][j] or arr4[i][j]>=arr4[i+1][j]:
				print("Impossible")
				flag=True
				break
		except:
			pass

	if flag:
		break

if not flag:
	print("Possible")


I found an interesting problem on https://codeforces.com/problemset/problem/1163/A:
The three friends, Kuro, Shiro, and Katie, met up again! It's time for a party...

What the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now $n$ cats are at the party, sitting in a circle and eating soup. The rules are simple: anyone having finished their soup leaves the circle.

Katie suddenly notices that whenever a cat leaves, the place where she was sitting becomes an empty space, which means the circle is divided into smaller continuous groups of cats sitting next to each other. At the moment Katie observes, there are $m$ cats who left the circle. This raises a question for Katie: what is the maximum possible number of groups the circle is divided into at the moment?

Could you help her with this curiosity?

You can see the examples and their descriptions with pictures in the "Note" section.

-----Input-----

The only line contains two integers $n$ and $m$ ($2 \leq n \leq 1000$, $0 \leq m \leq n$) — the initial number of cats at the party and the number of cats who left the circle at the moment Katie observes, respectively.

-----Output-----

Print a single integer — the maximum number of groups of cats at the moment Katie observes.

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

Output
3

Input
6 2

Output
2

Input
3 0

Output
1

Input
2 2

Output
0

-----Note-----

In the first example, originally there are $7$ cats sitting as shown below, creating a single group: [Image]

At the observed moment, $4$ cats have left the table. Suppose the cats $2$, $3$, $5$ and $7$ have left, then there are $3$ groups remaining. It is possible to show that it is the maximum possible number of groups remaining. [Image]

In the second example, there are $6$ cats sitting as shown below: [Image]

At the observed moment, $2$ cats have left the table. Suppose the cats numbered $3$ and $6$ left, then there will be $2$ groups remaining ($\{1, 2\}$ and $\{4, 5\}$). It is impossible to have more than $2$ groups of cats remaining. [Image]

In the...

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

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

if m == n:
    print(0)

elif m == 0 or m == 1:
    print(1)

else:
    m -= 1
    n -= 1
    print(min(m+1, n - m))


I found an interesting problem on https://codeforces.com/problemset/problem/1163/B1:
This problem is same as the next one, but has smaller constraints.

Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.

For each of the $n$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $i$-th day has a ribbon with color $u_i$. Shiro wants to know the largest number $x$, such that if we consider the streak of the first $x$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $x - 1$ will have the same number of occurrences.

For example, consider the following sequence of $u_i$: $[2, 2, 1, 1, 5, 4, 4, 5]$. Then $x = 7$ makes a streak, since if we remove the leftmost $u_i = 5$, each ribbon color will appear exactly twice in the prefix of $x - 1$ days. Note that $x = 8$ doesn't form a streak, since you must remove exactly one day.

Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the total number of days.

The second line contains $n$ integers $u_1, u_2, \ldots, u_n$ ($1 \leq u_i \leq 10$) — the colors of the ribbons the cats wear.

-----Output-----

Print a single integer $x$ — the largest possible streak of days.

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

Output
13
Input
5
10 2 5 4 1

Output
5
Input
1
10

Output
1
Input
7
3 2 1 1 4 5 1

Output
6
Input
6
1 1 1 2 2 2

Output
5

-----Note-----

In the first example, we can choose the longest streak of $13$ days, since upon removing the last day out of the streak, all of the remaining colors $1$, $2$, $3$, and $4$ will have the same number of occurrences of $3$. Note that the streak can also be $10$ days (by removing the $10$-th day from this streak) but we are interested in the longest streak.

In the...

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

n = int(input())
u = [int(u) for u in input().split()]

NMAX = 100005

suma = [0 for _ in range(NMAX)]
total = [0 for _ in range(NMAX)]

diferentes = 0
sol = 0
maximo = 1

for i, v in enumerate(u):
	if total[v] == 0:
		diferentes += 1
	else:
		suma[total[v]] -= 1
	total[v] += 1
	suma[total[v]] += 1

	maximo = max(maximo, total[v])

	#print(i, v, ":", diferentes)
	#print(suma)
	#print(total)
	#print(maximo, ":", suma[maximo], suma[maximo+1], diferentes-1)
	#print(maximo, ":", suma[maximo-1], suma[maximo], diferentes-1)

	if diferentes <= 1:
		sol = i

	if suma[maximo-1] == diferentes-1 and suma[maximo] == 1:
		sol = i

	if suma[maximo] == diferentes-1 and suma[1] == 1:
		sol = i

	if suma[1] == diferentes:
		sol = i

	#print("SOL", sol)

print(sol+1)


I found an interesting problem on https://codeforces.com/problemset/problem/1163/B2:
This problem is same as the previous one, but has larger constraints.

Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.

For each of the $n$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $i$-th day has a ribbon with color $u_i$. Shiro wants to know the largest number $x$, such that if we consider the streak of the first $x$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $x - 1$ will have the same number of occurrences.

For example, consider the following sequence of $u_i$: $[2, 2, 1, 1, 5, 4, 4, 5]$. Then $x = 7$ makes a streak, since if we remove the leftmost $u_i = 5$, each ribbon color will appear exactly twice in the prefix of $x - 1$ days. Note that $x = 8$ doesn't form a streak, since you must remove exactly one day.

Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the total number of days.

The second line contains $n$ integers $u_1, u_2, \ldots, u_n$ ($1 \leq u_i \leq 10^5$) — the colors of the ribbons the cats wear.

-----Output-----

Print a single integer $x$ — the largest possible streak of days.

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

Output
13
Input
5
10 100 20 200 1

Output
5
Input
1
100000

Output
1
Input
7
3 2 1 1 4 5 1

Output
6
Input
6
1 1 1 2 2 2

Output
5

-----Note-----

In the first example, we can choose the longest streak of $13$ days, since upon removing the last day out of the streak, all of the remaining colors $1$, $2$, $3$, and $4$ will have the same number of occurrences of $3$. Note that the streak can also be $10$ days (by removing the $10$-th day from this streak) but we are interested in the longest...

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

n = int(input())
colors = list(map(int, input().split()))
cnt = [0 for _ in range(100001)]
vals = dict()
ind = 1
for i in range(n):
    el = colors[i]
    if cnt[el] != 0:
        vals[cnt[el]] -= 1
        if vals[cnt[el]] == 0:
            del vals[cnt[el]]
    cnt[el] += 1
    if cnt[el] in vals:
        vals[cnt[el]] += 1
    else:
        vals[cnt[el]] = 1
    if len(vals) == 2:
        tmp = list(vals.keys())
        tmp.sort()
        if tmp[0] == 1 and vals[tmp[0]] == 1 or tmp[1] - tmp[0] == 1 and vals[tmp[1]] == 1:
            ind = i
    elif len(vals) == 1 and list(vals.keys())[0] == 1:
        ind = i
if (cnt[colors[0]] == n):
    print(n)
else:
    print(ind + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1163/C1:
This problem is same as the next one, but has smaller constraints.

It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.

At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $(x_i, y_i)$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.

Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 50$) — the number of electric poles.

Each of the following $n$ lines contains two integers $x_i$, $y_i$ ($-10^4 \le x_i, y_i \le 10^4$) — the coordinates of the poles.

It is guaranteed that all of these $n$ points are distinct.

-----Output-----

Print a single integer — the number of pairs of wires that are intersecting.

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

Output
14

Input
4
0 0
0 2
0 4
2 0

Output
6

Input
3
-1 -1
1 0
3 1

Output
0

-----Note-----

In the first example: [Image]

In the second example: [Image]

Note that the three poles $(0, 0)$, $(0, 2)$ and $(0, 4)$ are connected by a single wire.

In the third example: [Image]

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

from fractions import Fraction
from math import inf

n = int(input())
coords = []
for i in range(n):
    x, y = [int(c) for c in input().split(" ")]
    coords.append((x, y))

tangents = {}
for i1 in range(n):
    for i2 in range(i1+1, n):
        x1, y1 = coords[i1]
        x2, y2 = coords[i2]
        if x2 == x1:
            tangent = inf
            offset = x1
        else:
            tangent = Fraction(y2-y1, x2-x1)
            offset = - tangent * x1 + y1

        if tangent not in tangents: tangents[tangent] = set()
        tangents[tangent].add(offset)

tangentlen = {}
for tangent in tangents: tangentlen[tangent] = len(tangents[tangent])

summ = 0
for tangent in tangents: summ += tangentlen[tangent]

answer = 0
for t1 in tangents:
    answer += tangentlen[t1] * (summ - tangentlen[t1])
print(answer // 2)


I found an interesting problem on https://codeforces.com/problemset/problem/1163/C2:
This problem is same as the previous one, but has larger constraints.

It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.

At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $(x_i, y_i)$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.

Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 1000$) — the number of electric poles.

Each of the following $n$ lines contains two integers $x_i$, $y_i$ ($-10^4 \le x_i, y_i \le 10^4$) — the coordinates of the poles.

It is guaranteed that all of these $n$ points are distinct.

-----Output-----

Print a single integer — the number of pairs of wires that are intersecting.

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

Output
14

Input
4
0 0
0 2
0 4
2 0

Output
6

Input
3
-1 -1
1 0
3 1

Output
0

-----Note-----

In the first example:

 [Image]

In the second example:

 [Image]

Note that the three poles $(0, 0)$, $(0, 2)$ and $(0, 4)$ are connected by a single wire.

In the third example:

 [Image]

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

from math import *

class slopeC:
    def __init__(self):
        self.chil = set()
n = int(input())

slopes = {}
L = []
for i in range(n):
    x, y = list(map(int, input().split()))

    for l in L:
        if x != l[0]:
            slope = (y - l[1]) / (x - l[0])
        else:
            slope = inf

        s1 = str(l[0]) + '-' + str(l[1])
        s2 = str(x) + '-' + str(y)
        if slope not in slopes:
            slopes[slope] = [slopeC()]
            slopes[slope][0].chil.add(s1)
            slopes[slope][0].chil.add(s2)
        else:
            f = 0
            for child in slopes[slope]:
                if s1 in child.chil:
                    f = 1
                    child.chil.add(s2)
                    break
            if f == 0:
                slopes[slope] += [slopeC()]
                slopes[slope][0].chil.add(s1)
                slopes[slope][0].chil.add(s2)

    L += [[x, y]]
A = []
P = [0]
for s in slopes:
    A += [(len(slopes[s]))]
    P += [P[-1] + A[-1]]

ans = 0

for i, v in enumerate(A):
    ans += A[i] * (P[-1] - P[i+1])
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1163/E:
Kuro has just learned about permutations and he is really excited to create a new permutation type. He has chosen $n$ distinct positive integers and put all of them in a set $S$. Now he defines a magical permutation to be: A permutation of integers from $0$ to $2^x - 1$, where $x$ is a non-negative integer.  The bitwise xor of any two consecutive elements in the permutation is an element in $S$.

Since Kuro is really excited about magical permutations, he wants to create the longest magical permutation possible. In other words, he wants to find the largest non-negative integer $x$ such that there is a magical permutation of integers from $0$ to $2^x - 1$. Since he is a newbie in the subject, he wants you to help him find this value of $x$ and also the magical permutation for that $x$.

-----Input-----

The first line contains the integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the number of elements in the set $S$.

The next line contains $n$ distinct integers $S_1, S_2, \ldots, S_n$ ($1 \leq S_i \leq 2 \cdot 10^5$) — the elements in the set $S$.

-----Output-----

In the first line print the largest non-negative integer $x$, such that there is a magical permutation of integers from $0$ to $2^x - 1$.

Then print $2^x$ integers describing a magical permutation of integers from $0$ to $2^x - 1$. If there are multiple such magical permutations, print any of them.

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

Output
2
0 1 3 2
Input
2
2 3

Output
2
0 2 1 3
Input
4
1 2 3 4

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

Output
0
0
Input
1
20

Output
0
0
Input
1
1

Output
1
0 1

-----Note-----

In the first example, $0, 1, 3, 2$ is a magical permutation since: $0 \oplus 1 = 1 \in S$  $1 \oplus 3 = 2 \in S$  $3 \oplus 2 = 1 \in S$

Where $\oplus$ denotes bitwise xor operation.

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

def size(k):
    return int(math.log2(k))
def v2(k):
    if k%2==1:
        return 0
    else:
        return 1+v2(k//2)
n=int(input())
s=list(map(int,input().split()))
import math
s.sort()
used=[]
use=0
found={0:1}
good=0
for guy in s:
    big=size(guy)
    if guy not in found:
        used.append(guy)
        use+=1
        new=[]
        for boi in found:
            new.append(boi^guy)
        for guy in new:
            found[guy]=1
        if use==big+1:
            good=use
if good==0:
    print(0)
    print(0)
else:
    useful=used[:good]
    perm=["0"]
    curr=0
    for i in range(2**good-1):
        curr^=useful[v2(i+1)]
        perm.append(str(curr))
    print(good)
    print(" ".join(perm))


I found an interesting problem on https://codeforces.com/problemset/problem/1165/A:
You are given a huge decimal number consisting of $n$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.

You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.

You are also given two integers $0 \le y < x < n$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $10^y$ modulo $10^x$. In other words, the obtained number should have remainder $10^y$ when divided by $10^x$.

-----Input-----

The first line of the input contains three integers $n, x, y$ ($0 \le y < x < n \le 2 \cdot 10^5$) — the length of the number and the integers $x$ and $y$, respectively.

The second line of the input contains one decimal number consisting of $n$ digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1.

-----Output-----

Print one integer — the minimum number of operations you should perform to obtain the number having remainder $10^y$ modulo $10^x$. In other words, the obtained number should have remainder $10^y$ when divided by $10^x$.

-----Examples-----
Input
11 5 2
11010100101

Output
1

Input
11 5 1
11010100101

Output
3

-----Note-----

In the first example the number will be $11010100100$ after performing one operation. It has remainder $100$ modulo $100000$.

In the second example the number will be $11010100010$ after performing three operations. It has remainder $10$ modulo $100000$.

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

n, x, y = list(map(int, input().split()))
s = input()
ans = 0
for i in range(n - x, n):
	if i < n - y - 1:
		if s[i] == '1':
			ans += 1
	else:
		if i == n - y - 1:
			if s[i] == '0':
				ans += 1
		else:
			if (s[i] == '1'):
				ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1165/B:
Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $1$ problem, during the second day — exactly $2$ problems, during the third day — exactly $3$ problems, and so on. During the $k$-th day he should solve $k$ problems.

Polycarp has a list of $n$ contests, the $i$-th contest consists of $a_i$ problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly $k$ problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least $k$ problems that Polycarp didn't solve yet during the $k$-th day, then Polycarp stops his training.

How many days Polycarp can train if he chooses the contests optimally?

-----Input-----

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

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2 \cdot 10^5$) — the number of problems in the $i$-th contest.

-----Output-----

Print one integer — the maximum number of days Polycarp can train if he chooses the contests optimally.

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

Output
3

Input
3
1 1 1

Output
1

Input
5
1 1 1 2 2

Output
2

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

n = int(input())
l = sorted(map(int, input().split()))
i = 0
res = 0
while i < n:
    if res < l[i]:
        res += 1
    i += 1
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1165/C:
Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.

You are given a string $s$, you have to delete minimum number of characters from this string so that it becomes good.

-----Input-----

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

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

-----Output-----

In the first line, print one integer $k$ ($0 \le k \le n$) — the minimum number of characters you have to delete from $s$ to make it good.

In the second line, print the resulting string $s$. If it is empty, you may leave the second line blank, or not print it at all.

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

Output
0
good

Input
4
aabc

Output
2
ab

Input
3
aaa

Output
3

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

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

res = []

l = 0
r = 1
while r < n:
    if s[l] != s[r]:
        res += [s[l], s[r]]
        l = r + 1
        r = l + 1
    else:
        r += 1

k = n - len(res)

print(k)
print(*res, sep='')


I found an interesting problem on https://codeforces.com/problemset/problem/1165/D:
We guessed some integer number $x$. You are given a list of almost all its divisors. Almost all means that there are all divisors except $1$ and $x$ in the list.

Your task is to find the minimum possible integer $x$ that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number.

You have to answer $t$ independent queries.

-----Input-----

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

The first line of the query contains one integer $n$ ($1 \le n \le 300$) — the number of divisors in the list.

The second line of the query contains $n$ integers $d_1, d_2, \dots, d_n$ ($2 \le d_i \le 10^6$), where $d_i$ is the $i$-th divisor of the guessed number. It is guaranteed that all values $d_i$ are distinct.

-----Output-----

For each query print the answer to it.

If the input data in the query is contradictory and it is impossible to find such number $x$ that the given list of divisors is the list of almost all its divisors, print -1. Otherwise print the minimum possible $x$.

-----Example-----
Input
2
8
8 2 12 6 4 24 16 3
1
2

Output
48
4

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

t = int(input())
for q in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    ans = min(a)*max(a)
    deliver = [q for q in range(2, round(ans**(1/2))+1) if ans % q == 0]
    if deliver+[ans//deliver[q] for q in range(len(deliver)-1-(deliver[-1]**2 == ans), -1, -1)] == sorted(a):
        print(ans)
    else:
        print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1165/E:
You are given two arrays $a$ and $b$, both of length $n$.

Let's define a function $f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$.

Your task is to reorder the elements (choose an arbitrary order of elements) of the array $b$ to minimize the value of $\sum\limits_{1 \le l \le r \le n} f(l, r)$. Since the answer can be very large, you have to print it modulo $998244353$. Note that you should minimize the answer but not its remainder.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of elements in $a$ and $b$.

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

The third line of the input contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_j \le 10^6$), where $b_j$ is the $j$-th element of $b$.

-----Output-----

Print one integer — the minimum possible value of $\sum\limits_{1 \le l \le r \le n} f(l, r)$ after rearranging elements of $b$, taken modulo $998244353$. Note that you should minimize the answer but not its remainder.

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

Output
646

Input
1
1000000
1000000

Output
757402647

Input
2
1 3
4 2

Output
20

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

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

for i in range(N):
	A[i] = A[i]*(i+1)*(N-i)

A.sort()
B.sort()

ans = 0
for i in range(N):
	ans = ans + (A[i]*B[N-i-1])%998244353

print(ans%998244353)


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

Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.

Each day (during the morning) Ivan earns exactly one burle.

There are $n$ types of microtransactions in the game. Each microtransaction costs $2$ burles usually and $1$ burle if it is on sale. Ivan has to order exactly $k_i$ microtransactions of the $i$-th type (he orders microtransactions during the evening).

Ivan can order any (possibly zero) number of microtransactions of any types during any day (of course, if he has enough money to do it). If the microtransaction he wants to order is on sale then he can buy it for $1$ burle and otherwise he can buy it for $2$ burles.

There are also $m$ special offers in the game shop. The $j$-th offer $(d_j, t_j)$ means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day.

Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 1000$) — the number of types of microtransactions and the number of special offers in the game shop.

The second line of the input contains $n$ integers $k_1, k_2, \dots, k_n$ ($0 \le k_i \le 1000$), where $k_i$ is the number of copies of microtransaction of the $i$-th type Ivan has to order. It is guaranteed that sum of all $k_i$ is not less than $1$ and not greater than $1000$.

The next $m$ lines contain special offers. The $j$-th of these lines contains the $j$-th special offer. It is given as a pair of integers $(d_j, t_j)$ ($1 \le d_j \le 1000, 1 \le t_j \le n$) and means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day.

-----Output-----

Print one...

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

from collections import deque

def main():
    n, m = list(map(int, input().split()))
    wanted_cnt = list(map(int, input().split()))
    Order = [tuple(map(int, input().split())) for i in range(m)]
    #count the maximum number which you can buy on sales day.
    S = sum(wanted_cnt)

    def ispossible_within(Day):
        sale_get_cnt = 0
        last_sale = [0]*n
        for day, good in Order:
            if day > Day:
                continue
            last_sale[good-1] = max(last_sale[good-1], day)
        Que = []
        for i in range(n):
            if wanted_cnt[i] > 0 and last_sale[i] > 0:
                Que.append((last_sale[i], wanted_cnt[i]))
        Que.sort()
        que = deque(Que)
        while que:
            sale_day, wanted = que.popleft()
            money_left = sale_day - sale_get_cnt
            if money_left >= wanted:
                sale_get_cnt += wanted
            elif money_left < wanted:
                sale_get_cnt += money_left
        left_money = Day - sale_get_cnt
        left = S - sale_get_cnt

        return left_money >= 2*left

    impossible = 0
    possible = 2020
    while possible - impossible > 1:
        m = (impossible + possible)//2
        if ispossible_within(m):
            possible = m
        else:
            impossible = m
    print(possible)
    return

def __starting_point():
    main()

__starting_point()


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

Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.

Each day (during the morning) Ivan earns exactly one burle.

There are $n$ types of microtransactions in the game. Each microtransaction costs $2$ burles usually and $1$ burle if it is on sale. Ivan has to order exactly $k_i$ microtransactions of the $i$-th type (he orders microtransactions during the evening).

Ivan can order any (possibly zero) number of microtransactions of any types during any day (of course, if he has enough money to do it). If the microtransaction he wants to order is on sale then he can buy it for $1$ burle and otherwise he can buy it for $2$ burles.

There are also $m$ special offers in the game shop. The $j$-th offer $(d_j, t_j)$ means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day.

Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the number of types of microtransactions and the number of special offers in the game shop.

The second line of the input contains $n$ integers $k_1, k_2, \dots, k_n$ ($0 \le k_i \le 2 \cdot 10^5$), where $k_i$ is the number of copies of microtransaction of the $i$-th type Ivan has to order. It is guaranteed that sum of all $k_i$ is not less than $1$ and not greater than $2 \cdot 10^5$.

The next $m$ lines contain special offers. The $j$-th of these lines contains the $j$-th special offer. It is given as a pair of integers $(d_j, t_j)$ ($1 \le d_j \le 2 \cdot 10^5, 1 \le t_j \le n$) and means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th...

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

import sys
import copy

DEBUG = False

if DEBUG:
    inf = open("input.txt")
else:
    inf = sys.stdin

N, M = list(map(int, inf.readline().split(' ')))
n_items = list(map(int, inf.readline().split(' ')))
sales = []
for _ in range(M):
    sale = list(map(int, inf.readline().split(' ')))
    sales.append(sale) # sale_day, sale_type

sales = sorted(sales, key=lambda x: x[0], reverse=True) # sort by day

def can_buy_in(dday):
    used = 0
    money_left = dday
    items = n_items[:]
    for sale_day, sale_type in sales:
        if sale_day > dday:
            continue

        if money_left > sale_day:
            money_left = sale_day
        can_buy = min(items[sale_type-1], money_left)
        # buy it
        used += can_buy
        items[sale_type-1] -= can_buy
        money_left -= can_buy

        if money_left == 0:
            break

    need_money_for_rest = sum(items) * 2
    return need_money_for_rest + used <= dday

total_items = sum(n_items)
low = total_items
high = total_items * 2

# find minimum can_buy day
while low <= high:
    mid = (low + high) // 2
    if can_buy_in(mid):
        high = mid-1
    else:
        low = mid+1

print(low)


I found an interesting problem on https://codeforces.com/problemset/problem/1166/A:
There are $n$ students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let $x$ be the number of such pairs of students in a split. Pairs $(a, b)$ and $(b, a)$ are the same and counted only once.

For example, if there are $6$ students: "olivia", "jacob", "tanya", "jack", "oliver" and "jessica", then:  splitting into two classrooms ("jack", "jacob", "jessica", "tanya") and ("olivia", "oliver") will give $x=4$ ($3$ chatting pairs in the first classroom, $1$ chatting pair in the second classroom),  splitting into two classrooms ("jack", "tanya", "olivia") and ("jessica", "oliver", "jacob") will give $x=1$ ($0$ chatting pairs in the first classroom, $1$ chatting pair in the second classroom).

You are given the list of the $n$ names. What is the minimum $x$ we can obtain by splitting the students into classrooms?

Note that it is valid to place all of the students in one of the classrooms, leaving the other one empty.

-----Input-----

The first line contains a single integer $n$ ($1\leq n \leq 100$) — the number of students.

After this $n$ lines follow.

The $i$-th line contains the name of the $i$-th student.

It is guaranteed each name is a string of lowercase English letters of length at most $20$. Note that multiple students may share the same name.

-----Output-----

The output must consist of a single integer $x$ — the minimum possible number of chatty pairs.

-----Examples-----
Input
4
jorge
jose
oscar
jerry

Output
1

Input
7
kambei
gorobei
shichiroji
kyuzo
heihachi
katsushiro
kikuchiyo

Output
2

Input
5
mike
mike
mike
mike
mike

Output
4

-----Note-----

In the first sample the minimum number of pairs is $1$. This can be achieved, for example, by putting everyone except jose in one classroom, and jose in the other, so jorge and...

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

n=int(input())
counter=0
dic={}
for i in range(n):
    a=list(input())
    if a[0] not in dic:
        dic[a[0]]=1
    else:
        dic[a[0]]+=1
for item in dic:
    y=dic[item]
    x=dic[item]//2
    counter+=x*(x-1)//2+(y-x)*(y-x-1)//2
print(counter)


I found an interesting problem on https://codeforces.com/problemset/problem/1166/B:
Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length $k$ is vowelly if there are positive integers $n$ and $m$ such that $n\cdot m = k$ and when the word is written by using $n$ rows and $m$ columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column.

You are given an integer $k$ and you must either print a vowelly word of length $k$ or print $-1$ if no such word exists.

In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'.

-----Input-----

Input consists of a single line containing the integer $k$ ($1\leq k \leq 10^4$) — the required length.

-----Output-----

The output must consist of a single line, consisting of a vowelly word of length $k$ consisting of lowercase English letters if it exists or $-1$ if it does not.

If there are multiple possible words, you may output any of them.

-----Examples-----
Input
7

Output
-1

Input
36

Output
agoeuioaeiruuimaeoieauoweouoiaouimae

-----Note-----

In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following $6 \times 6$ grid: $\left. \begin{array}{|c|c|c|c|c|c|} \hline a & {g} & {o} & {e} & {u} & {i} \\ \hline o & {a} & {e} & {i} & {r} & {u} \\ \hline u & {i} & {m} & {a} & {e} & {o} \\ \hline i & {e} & {a} & {u} & {o} & {w} \\ \hline e & {o} & {u} & {o} & {i} & {a} \\ \hline o & {u} & {i} & {m} & {a} & {e} \\ \hline \end{array} \right.$

It is easy to verify that every row and every column contain all the vowels.

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

def main():
    n = int(input())
    for i in range(1, n):
        if n % i == 0:
            if i < 5 or n // i < 5:
                continue
            vowels = "aeiou"
            ind = 0
            ans = ""
            for j in range(n // i):
                for k in range(i):
                    ans += vowels[(j + k) % 5]
            print(ans)
            return 0
    print(-1)
    return 0

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1166/C:
The legend of the foundation of Vectorland talks of two integers $x$ and $y$. Centuries ago, the array king placed two markers at points $|x|$ and $|y|$ on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at points $|x - y|$ and $|x + y|$ and conquered all the land in between (including the endpoints), which he declared to be Vectorland. He did so in such a way that the land of Arrayland was completely inside (including the endpoints) the land of Vectorland.

Here $|z|$ denotes the absolute value of $z$.

Now, Jose is stuck on a question of his history exam: "What are the values of $x$ and $y$?" Jose doesn't know the answer, but he believes he has narrowed the possible answers down to $n$ integers $a_1, a_2, \dots, a_n$. Now, he wants to know the number of unordered pairs formed by two different elements from these $n$ integers such that the legend could be true if $x$ and $y$ were equal to these two values. Note that it is possible that Jose is wrong, and that no pairs could possibly make the legend true.

-----Input-----

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

The second line contains $n$ pairwise distinct integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$) — the choices Jose is considering.

-----Output-----

Print a single integer number — the number of unordered pairs $\{x, y\}$ formed by different numbers from Jose's choices that could make the legend true.

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

Output
2

Input
2
3 6

Output
1

-----Note-----

Consider the first sample. For the pair $\{2, 5\}$, the situation looks as follows, with the Arrayland markers at $|2| = 2$ and $|5| = 5$, while the Vectorland markers are located at $|2 - 5| = 3$ and $|2 + 5| = 7$:

 [Image]

The legend is not true in this case, because the interval $[2, 3]$ is not conquered by Vectorland. For the pair $\{5, -3\}$ the situation looks as follows,...

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

from collections import deque

n = int(input().strip())
nums = list(map(int, input().strip().split()))
nums = sorted([abs(num) for num in nums], reverse=True)

res = 0
max_index = 0
curr_index = 1
for curr_index in range(1, n):
    while nums[curr_index] * 2 < nums[max_index]:
        max_index += 1
    res += curr_index - max_index
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1166/D:
Given a positive integer $m$, we say that a sequence $x_1, x_2, \dots, x_n$ of positive integers is $m$-cute if for every index $i$ such that $2 \le i \le n$ it holds that $x_i = x_{i - 1} + x_{i - 2} + \dots + x_1 + r_i$ for some positive integer $r_i$ satisfying $1 \le r_i \le m$.

You will be given $q$ queries consisting of three positive integers $a$, $b$ and $m$. For each query you must determine whether or not there exists an $m$-cute sequence whose first term is $a$ and whose last term is $b$. If such a sequence exists, you must additionally find an example of it.

-----Input-----

The first line contains an integer number $q$ ($1 \le q \le 10^3$) — the number of queries.

Each of the following $q$ lines contains three integers $a$, $b$, and $m$ ($1 \le a, b, m \le 10^{14}$, $a \leq b$), describing a single query.

-----Output-----

For each query, if no $m$-cute sequence whose first term is $a$ and whose last term is $b$ exists, print $-1$.

Otherwise print an integer $k$ ($1 \le k \leq 50$), followed by $k$ integers $x_1, x_2, \dots, x_k$ ($1 \le x_i \le 10^{14}$). These integers must satisfy $x_1 = a$, $x_k = b$, and that the sequence $x_1, x_2, \dots, x_k$ is $m$-cute.

It can be shown that under the problem constraints, for each query either no $m$-cute sequence exists, or there exists one with at most $50$ terms.

If there are multiple possible sequences, you may print any of them.

-----Example-----
Input
2
5 26 2
3 9 1

Output
4 5 6 13 26
-1

-----Note-----

Consider the sample. In the first query, the sequence $5, 6, 13, 26$ is valid since $6 = 5 + \bf{\color{blue} 1}$, $13 = 6 + 5 + {\bf\color{blue} 2}$ and $26 = 13 + 6 + 5 + {\bf\color{blue} 2}$ have the bold values all between $1$ and $2$, so the sequence is $2$-cute. Other valid sequences, such as $5, 7, 13, 26$ are also accepted.

In the second query, the only possible $1$-cute sequence starting at $3$ is $3, 4, 8, 16, \dots$, which does not contain $9$.

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

# https://codeforces.com/contest/1166/problem/D
def creat_r(X, k, m, p):
    q = X // p[k]
    r = X %  p[k]

    R = []
    for _ in range(k+1):
        R.append(q)

    s = bin(r)[2:]
    for i in range(1, len(s)+1):
        if s[-i] == '1':
            R[-(i+1)] += 1

    return R

i = 1
p = [1]
for _ in range(50):
    i*=2
    p.append(i)

T   = int(input())
ans = []
for _ in range(T):
    a, b, m = map(int, input().split())
    if a == b:
        print(1, a)
        continue

    flg = False
    for i in range(50):
        if p[i] * a  >= b: break

        k = i
        X = b - (p[i] * a)

        if X >= p[k] and X <= p[k]*m:
            flg = True
            R   = creat_r(X, k, m, p)
            sR  = 0
            A   = [a]

            for _ in range(k+1):
                A.append(p[_]*a+sR+R[_])
                sR += sR + R[_]

            print(len(A), end=' ')
            for x in A:
                print(x, end=' ')
            print()
            break

    if flg == False:
        print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1166/E:
Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?

There are $n$ stores numbered from $1$ to $n$ in Nlogonia. The $i$-th of these stores offers a positive integer $a_i$.

Each day among the last $m$ days Dora bought a single integer from some of the stores. The same day, Swiper the fox bought a single integer from all the stores that Dora did not buy an integer from on that day.

Dora considers Swiper to be her rival, and she considers that she beat Swiper on day $i$ if and only if the least common multiple of the numbers she bought on day $i$ is strictly greater than the least common multiple of the numbers that Swiper bought on day $i$.

The least common multiple (LCM) of a collection of integers is the smallest positive integer that is divisible by all the integers in the collection.

However, Dora forgot the values of $a_i$. Help Dora find out if there are positive integer values of $a_i$ such that she beat Swiper on every day. You don't need to find what are the possible values of $a_i$ though.

Note that it is possible for some values of $a_i$ to coincide in a solution.

-----Input-----

The first line contains integers $m$ and $n$ ($1\leq m \leq 50$, $1\leq n \leq 10^4$) — the number of days and the number of stores.

After this $m$ lines follow, the $i$-th line starts with an integer $s_i$ ($1\leq s_i \leq n-1$), the number of integers Dora bought on day $i$, followed by $s_i$ distinct integers, the indices of the stores where Dora bought an integer on the $i$-th day. The indices are between $1$ and $n$.

-----Output-----

Output must consist of a single line containing "possible" if there exist positive integers $a_i$ such that for each day the least common multiple of the integers bought by Dora is strictly greater than the least common multiple of the integers bought by Swiper on that day. Otherwise, print "impossible".

Note that you don't have to restore the integers...

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

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

s = [0] * m

for w in range(m):
    for i in list(map(int, input().split()))[1:]:
        s[w] |= 1 << i

for i in s:
    for j in s:
        if not (i & j):
            print('impossible')
            return

print('possible')


I found an interesting problem on https://codeforces.com/problemset/problem/1167/A:
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.

You are given a string $s$ of length $n$, consisting of digits.

In one operation you can delete any character from string $s$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.

You need to determine whether there is such a sequence of operations (possibly empty), after which the string $s$ becomes a telephone number.

-----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 string $s$.

The second line of each test case contains the string $s$ ($|s| = n$) consisting of digits.

-----Output-----

For each test print one line.

If there is a sequence of operations, after which $s$ becomes a telephone number, print YES.

Otherwise, print NO.

-----Example-----
Input
2
13
7818005553535
11
31415926535

Output
YES
NO

-----Note-----

In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.

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

def solve():
    n = int(input())
    s = input()
    for i in range(n):
        if s[i] == '8':
            break
    if i <= n - 11:
        print("YES")
    else:
        print("NO")

def main():
    for _ in range(int(input())):
        solve()
    return 0

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1167/C:
In some social network, there are $n$ users communicating with each other in $m$ groups of friends. Let's analyze the process of distributing some news between users.

Initially, some user $x$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.

For each user $x$ you have to determine what is the number of users that will know the news if initially only user $x$ starts distributing it.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 5 \cdot 10^5$) — the number of users and the number of groups of friends, respectively.

Then $m$ lines follow, each describing a group of friends. The $i$-th line begins with integer $k_i$ ($0 \le k_i \le n$) — the number of users in the $i$-th group. Then $k_i$ distinct integers follow, denoting the users belonging to the $i$-th group.

It is guaranteed that $\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$.

-----Output-----

Print $n$ integers. The $i$-th integer should be equal to the number of users that will know the news if user $i$ starts distributing it.

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

Output
4 4 1 4 4 2 2

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

# coding: UTF-8
import sys

def find(x):
    if node[x] < 0:
        return x
    else:
        node[x] = find(node[x])
        return node[x]

def unite(x, y):
    x = find(x)
    y = find(y)
    ret = False
    if x != y:
        ret = True
        if rank[x] > rank[y]:
            node[x] += node[y]
            node[y] = x
        else:
            node[y] += node[x]
            node[x] = y
            if rank[x] == rank[y]:
                rank[y] += 1
    return ret

def is_same(x, y):
    return find(x) == find(y)

def size(x):
    return -node[find(x)]

n, m = map(int, input().split())
node = [-1 for i in range(n + 1)]
rank = [0 for _ in range(n + 1)]
query = [tuple(map(int, sys.stdin.readline().split())) for _ in range(m)]
for a in query:
    if a[0] >= 2:
        for j in a[2:]:
            unite(a[1], j)
for i in range(1, n + 1):
    print(size(i), end=" ")


I found an interesting problem on https://codeforces.com/problemset/problem/1167/D:
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and "(()" are not.

We can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define nesting depth of the RBS as maximum number of bracket pairs, such that the $2$-nd pair lies inside the $1$-st one, the $3$-rd one — inside the $2$-nd one and so on. For example, nesting depth of "" is $0$, "()()()" is $1$ and "()((())())" is $3$.

Now, you are given RBS $s$ of even length $n$. You should color each bracket of $s$ into one of two colors: red or blue. Bracket sequence $r$, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets $b$, should be RBS. Any of them can be empty. You are not allowed to reorder characters in $s$, $r$ or $b$. No brackets can be left uncolored.

Among all possible variants you should choose one that minimizes maximum of $r$'s and $b$'s nesting depth. If there are multiple solutions you can print any of them.

-----Input-----

The first line contains an even integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the length of RBS $s$.

The second line contains regular bracket sequence $s$ ($|s| = n$, $s_i \in \{$"(", ")"$\}$).

-----Output-----

Print single string $t$ of length $n$ consisting of "0"-s and "1"-s. If $t_i$ is equal to 0 then character $s_i$ belongs to RBS $r$, otherwise $s_i$ belongs to $b$.

-----Examples-----
Input
2
()

Output
11

Input
4
(())

Output
0101

Input
10
((()())())

Output
0110001111

-----Note-----

In the first example one of optimal solutions is $s = $ "$\color{blue}{()}$". $r$ is empty and $b = $ "$()$". The answer is $\max(0, 1) = 1$.

In the second example it's optimal to make $s = $ "$\color{red}{(}\color{blue}{(}\color{red}{)}\color{blue}{)}$". $r = b...

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

n = int(input())
A = input()

stack = []

for i in A:
    if i == '(':
        if len(stack) == 0 or stack[-1] == 1:
            stack.append(0)
            print(0, end='')
        else:
            stack.append(1)
            print(1, end='')
    else:
        print(stack[-1], end='')
        stack.pop()


I found an interesting problem on https://codeforces.com/problemset/problem/1167/E:
You are given an array consisting of $n$ integers $a_1, a_2, \dots , a_n$ and an integer $x$. It is guaranteed that for every $i$, $1 \le a_i \le x$.

Let's denote a function $f(l, r)$ which erases all values such that $l \le a_i \le r$ from the array $a$ and returns the resulting array. For example, if $a = [4, 1, 1, 4, 5, 2, 4, 3]$, then $f(2, 4) = [1, 1, 5]$.

Your task is to calculate the number of pairs $(l, r)$ such that $1 \le l \le r \le x$ and $f(l, r)$ is sorted in non-descending order. Note that the empty array is also considered sorted.

-----Input-----

The first line contains two integers $n$ and $x$ ($1 \le n, x \le 10^6$) — the length of array $a$ and the upper limit for its elements, respectively.

The second line contains $n$ integers $a_1, a_2, \dots a_n$ ($1 \le a_i \le x$).

-----Output-----

Print the number of pairs $1 \le l \le r \le x$ such that $f(l, r)$ is sorted in non-descending order.

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

Output
4

Input
7 4
1 3 1 2 2 4 3

Output
6

-----Note-----

In the first test case correct pairs are $(1, 1)$, $(1, 2)$, $(1, 3)$ and $(2, 3)$.

In the second test case correct pairs are $(1, 3)$, $(1, 4)$, $(2, 3)$, $(2, 4)$, $(3, 3)$ and $(3, 4)$.

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

import os
from io import BytesIO, StringIO
#input = BytesIO(os.read(0, os.fstat(0).st_size)).readline

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

def array_of(f, *dim):
    return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()

def main():
    n, x = input_as_list()
    a = input_as_list()

    fo = array_of(lambda:-1, x+1)
    lo = array_of(lambda:-1, x+1)

    ans = 0

    for i, e in enumerate(a):
        if fo[e] == -1:
            fo[e] = i
        lo[e] = i

    lastidx = -1
    for i in range(1, x+1):
        if fo[i] != -1:
            if lastidx < fo[i]:
                lastidx = lo[i]
            else:
                i -= 1
                break
    L = i

    firstidx = n+1
    for i in range(x, 0, -1):
        if fo[i] != -1:
            if lo[i] < firstidx:
                firstidx = fo[i]
            else:
                i += 1
                break
    R = i

    ans += min(x - R + 2, x)

    c = n
    for i in range(x, R-1, -1):
        if fo[i] == -1:
            fo[i] = c
        else:
            c = fo[i]

    r = R
    l = 1

    while l <= L:
        if l + 1 < r and (lo[l] == -1 or x < r or lo[l] < fo[r]):
            ans += x - r + 2
            #print(l+1, r-1)
            l += 1
        else:
            r += 1
    #print(L, R, ans)
    print(ans)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1167/F:
You are given an array $a_1, a_2, \dots, a_n$. All $a_i$ are pairwise distinct.

Let's define function $f(l, r)$ as follows:   let's define array $b_1, b_2, \dots, b_{r - l + 1}$, where $b_i = a_{l - 1 + i}$;  sort array $b$ in increasing order;  result of the function $f(l, r)$ is $\sum\limits_{i = 1}^{r - l + 1}{b_i \cdot i}$.

Calculate $\left(\sum\limits_{1 \le l \le r \le n}{f(l, r)}\right) \mod (10^9+7)$, i.e. total sum of $f$ for all subsegments of $a$ modulo $10^9+7$.

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$, $a_i \neq a_j$ for $i \neq j$) — array $a$.

-----Output-----

Print one integer — the total sum of $f$ for all subsegments of $a$ modulo $10^9+7$

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

Output
167

Input
3
123456789 214365879 987654321

Output
582491518

-----Note-----

Description of the first example:   $f(1, 1) = 5 \cdot 1 = 5$;  $f(1, 2) = 2 \cdot 1 + 5 \cdot 2 = 12$;  $f(1, 3) = 2 \cdot 1 + 4 \cdot 2 + 5 \cdot 3 = 25$;  $f(1, 4) = 2 \cdot 1 + 4 \cdot 2 + 5 \cdot 3 + 7 \cdot 4 = 53$;  $f(2, 2) = 2 \cdot 1 = 2$;  $f(2, 3) = 2 \cdot 1 + 4 \cdot 2 = 10$;  $f(2, 4) = 2 \cdot 1 + 4 \cdot 2 + 7 \cdot 3 = 31$;  $f(3, 3) = 4 \cdot 1 = 4$;  $f(3, 4) = 4 \cdot 1 + 7 \cdot 2 = 18$;  $f(4, 4) = 7 \cdot 1 = 7$;

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

import sys

MOD = (int)(1e9+7)

def add(a, b):
	a += b
	if a >= MOD: a -= MOD
	return a

def mul(a, b):
	return (a * b) % MOD

class fenwickTree:
	def __init__(self, max_val):
		self.max_val = max_val + 5
		self.tree = [0] * self.max_val

	def update(self, idx, value):
		idx += 1
		while idx < self.max_val:
			self.tree[idx] = add(self.tree[idx], value)
			idx += (idx & (-idx))

	def read(self, idx):
		idx += 1
		res = 0
		while idx > 0:
			res = add(res, self.tree[idx])
			idx -= (idx & (-idx))
		return res

inp = [int(x) for x in sys.stdin.read().split()]

n = inp[0]
a = []
for i in range(1, n + 1):
	a.append(inp[i])

sorted_array = sorted(a)
dict = {}
for i in range(n):
	dict[sorted_array[i]] = i

factor = [0] * n
for i in range(0, n):
	factor[i] = mul(i + 1, n - i)

left_tree = fenwickTree(n)
for i in range(0, n):
	element_idx = dict[a[i]]
	factor[i] = add(factor[i], mul(n - i, left_tree.read(element_idx)))
	left_tree.update(element_idx, i + 1)

right_tree = fenwickTree(n)
for i in range(n - 1, -1, -1):
	element_idx = dict[a[i]]
	factor[i] = add(factor[i], mul(i + 1, right_tree.read(element_idx)))
	right_tree.update(element_idx, n - i)

ans = 0
for i in range(n):
	ans = add(ans, mul(a[i], factor[i]))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1169/A:
The circle line of the Roflanpolis subway has $n$ stations.

There are two parallel routes in the subway. The first one visits stations in order $1 \to 2 \to \ldots \to n \to 1 \to 2 \to \ldots$ (so the next stop after station $x$ is equal to $(x+1)$ if $x < n$ and $1$ otherwise). The second route visits stations in order $n \to (n-1) \to \ldots \to 1 \to n \to (n-1) \to \ldots$ (so the next stop after station $x$ is equal to $(x-1)$ if $x>1$ and $n$ otherwise). All trains depart their stations simultaneously, and it takes exactly $1$ minute to arrive at the next station.

Two toads live in this city, their names are Daniel and Vlad.

Daniel is currently in a train of the first route at station $a$ and will exit the subway when his train reaches station $x$.

Coincidentally, Vlad is currently in a train of the second route at station $b$ and he will exit the subway when his train reaches station $y$.

Surprisingly, all numbers $a,x,b,y$ are distinct.

Toad Ilya asks you to check if Daniel and Vlad will ever be at the same station at the same time during their journey. In other words, check if there is a moment when their trains stop at the same station. Note that this includes the moments when Daniel or Vlad enter or leave the subway.

-----Input-----

The first line contains five space-separated integers $n$, $a$, $x$, $b$, $y$ ($4 \leq n \leq 100$, $1 \leq a, x, b, y \leq n$, all numbers among $a$, $x$, $b$, $y$ are distinct) — the number of stations in Roflanpolis, Daniel's start station, Daniel's finish station, Vlad's start station and Vlad's finish station, respectively.

-----Output-----

Output "YES" if there is a time moment when Vlad and Daniel are at the same station, and "NO" otherwise. You can print each letter in any case (upper or lower).

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

Output
YES

Input
10 2 1 9 10

Output
NO

-----Note-----

In the first example, Daniel and Vlad start at the stations $(1, 3)$. One minute later they are at stations $(2, 2)$. They are at the same station at this...

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

#	!/usr/bin/env python3
#	encoding: UTF-8
#	Modified: <26/May/2019 09:11:38 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT), Gwalior

import sys

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return list(map(int, sys.stdin.readline().split()))

def input(): return sys.stdin.readline().strip()

def main():
    n, a, x, b, y = get_ints()
    daniel = [-1] * (n + 1)
    if x >= a:
        t = 0
        for i in range(a, x + 1):
            daniel[i] = t
            t += 1
    else:
        t = 0
        for i in range(a, n + 1):
            daniel[i] = t
            t += 1
        for i in range(1, x + 1):
            daniel[i] = t
            t += 1

    vlad = [-1] * (n + 1)
    if y <= b:
        t = 0
        for i in range(b, y - 1, -1):
            vlad[i] = t
            t += 1
    else:
        t = 0
        for i in range(b, 0, -1):
            vlad[i] = t
            t += 1
        for i in range(n, y - 1, -1):
            vlad[i] = t
            t += 1
    ans = 'NO'
    for i in range(1, n + 1):
        if daniel[i] == vlad[i] and daniel[i] != -1:
            ans = 'YES'
            break
    # print(vlad)
    # print(daniel)
    print(ans)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1169/B:
Toad Ivan has $m$ pairs of integers, each integer is between $1$ and $n$, inclusive. The pairs are $(a_1, b_1), (a_2, b_2), \ldots, (a_m, b_m)$.

He asks you to check if there exist two integers $x$ and $y$ ($1 \leq x < y \leq n$) such that in each given pair at least one integer is equal to $x$ or $y$.

-----Input-----

The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 300\,000$, $1 \leq m \leq 300\,000$) — the upper bound on the values of integers in the pairs, and the number of given pairs.

The next $m$ lines contain two integers each, the $i$-th of them contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n, a_i \neq b_i$) — the integers in the $i$-th pair.

-----Output-----

Output "YES" if there exist two integers $x$ and $y$ ($1 \leq x < y \leq n$) such that in each given pair at least one integer is equal to $x$ or $y$. Otherwise, print "NO". You can print each letter in any case (upper or lower).

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

Output
NO

Input
5 4
1 2
2 3
3 4
4 5

Output
YES

Input
300000 5
1 2
1 2
1 2
1 2
1 2

Output
YES

-----Note-----

In the first example, you can't choose any $x$, $y$ because for each such pair you can find a given pair where both numbers are different from chosen integers.

In the second example, you can choose $x=2$ and $y=4$.

In the third example, you can choose $x=1$ and $y=2$.

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

from collections import Counter
n, m = list(map(int, input().split()))
cp = []
for i in range(m):
    cp.append(list(map(int, input().split())))
v1, v2 = cp[0][0], cp[0][1]
m1, m2 = [], []
for i in range(1, m):
    if v1 not in cp[i]:
        m1.append(cp[i])
    if v2 not in cp[i]:
        m2.append(cp[i])
used = [[], [], [], []]
if (len(m1) < 2) | (len(m2) < 2):
    print('YES')
else:
    v1, v2 = m1[0][0], m1[0][1]
    for i in range(1, len(m1)):
        if v1 not in m1[i]:
            used[0].append(0)
        else:
            used[0].append(1)
        if v2 not in m1[i]:
            used[1].append(0)
        else:
            used[1].append(1)

    v1, v2 = m2[0][0], m2[0][1]
    for i in range(1, len(m2)):
        if v1 not in m2[i]:
            used[2].append(0)
        else:
            used[2].append(1)
        if v2 not in m2[i]:
            used[3].append(0)
        else:
            used[3].append(1)
    b = False
    for i in range(4):
        if Counter(used[i])[0] == 0:
            b = True
            break
    if b:
        print('YES')
    else:
        print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1172/A:
Nauuo is a girl who loves playing cards.

One day she was playing cards but found that the cards were mixed with some empty ones.

There are $n$ cards numbered from $1$ to $n$, and they were mixed with another $n$ empty cards. She piled up the $2n$ cards and drew $n$ of them. The $n$ cards in Nauuo's hands are given. The remaining $n$ cards in the pile are also given in the order from top to bottom.

In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile.

Nauuo wants to make the $n$ numbered cards piled up in increasing order (the $i$-th card in the pile from top to bottom is the card $i$) as quickly as possible. Can you tell her the minimum number of operations?

-----Input-----

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

The second line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($0\le a_i\le n$) — the initial cards in Nauuo's hands. $0$ represents an empty card.

The third line contains $n$ integers $b_1,b_2,\ldots,b_n$ ($0\le b_i\le n$) — the initial cards in the pile, given in order from top to bottom. $0$ represents an empty card.

It is guaranteed that each number from $1$ to $n$ appears exactly once, either in $a_{1..n}$ or $b_{1..n}$.

-----Output-----

The output contains a single integer — the minimum number of operations to make the $n$ numbered cards piled up in increasing order.

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

Output
2
Input
3
0 2 0
1 0 3

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

Output
18

-----Note-----

Example 1

We can play the card $2$ and draw the card $3$ in the first operation. After that, we have $[0,3,0]$ in hands and the cards in the pile are $[0,1,2]$ from top to bottom.

Then, we play the card $3$ in the second operation. The cards in the pile are $[1,2,3]$, in which the cards are piled up in increasing order.

Example 2

Play an empty card and draw the card $1$, then play $1$, $2$, $3$ in order.

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

from sys import stdin
from collections import deque

n = int(stdin.readline())

hand = [int(x) for x in stdin.readline().split()]

deck = [int(x) for x in stdin.readline().split()]

ind = {}

for i,x in enumerate(deck):
    if x != 0:
        ind[x] = i

offset = sorted([(ind[i]-i+2,i) for i in ind])

if not offset:
    print(n)

elif not 1 in deck:
    print(max(offset[-1][0]+n, n))
else:
    i1 = deck.index(1)
    newD = deck[i1:]
    valid = True
    for x in range(len(newD)-1):
        if newD[x] > newD[x+1]:
            valid = False
            break
    if valid:
        v2 = True
        newOff = i1-n
        for o,x in offset:
            if x > -newOff and o > newOff:
                v2 = False
                break

        if v2:
            print(newOff+n)
        else:
            print(max(offset[-1][0]+n, n))
    else:
        print(max(offset[-1][0]+n, n))


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

Nauuo is a girl who loves random picture websites.

One day she made a random picture website by herself which includes $n$ pictures.

When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The $i$-th picture has a non-negative weight $w_i$, and the probability of the $i$-th picture being displayed is $\frac{w_i}{\sum_{j=1}^nw_j}$. That is to say, the probability of a picture to be displayed is proportional to its weight.

However, Nauuo discovered that some pictures she does not like were displayed too often.

To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add $1$ to its weight; otherwise, she would subtract $1$ from its weight.

Nauuo will visit the website $m$ times. She wants to know the expected weight of each picture after all the $m$ visits modulo $998244353$. Can you help her?

The expected weight of the $i$-th picture can be denoted by $\frac {q_i} {p_i}$ where $\gcd(p_i,q_i)=1$, you need to print an integer $r_i$ satisfying $0\le r_i<998244353$ and $r_i\cdot p_i\equiv q_i\pmod{998244353}$. It can be proved that such $r_i$ exists and is unique.

-----Input-----

The first line contains two integers $n$ and $m$ ($1\le n\le 50$, $1\le m\le 50$) — the number of pictures and the number of visits to the website.

The second line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($a_i$ is either $0$ or $1$) — if $a_i=0$ , Nauuo does not like the $i$-th picture; otherwise Nauuo likes the $i$-th picture. It is guaranteed that there is at least one picture which Nauuo likes.

The third line contains $n$ integers $w_1,w_2,\ldots,w_n$ ($1\le w_i\le50$) — the initial weights of the pictures.

-----Output-----

The output contains $n$ integers $r_1,r_2,\ldots,r_n$ — the expected weights modulo $998244353$.

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

Output
332748119
332748119

Input
1 2
1
1

Output
3

Input
3 3
0 1 1
4 3...

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

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))

def inv(x):
    return pow(x, mod - 2, mod)

def main():
    n,m = LI()
    a = LI()
    w = LI()

    def plus(a,b):
        c = a[0] * b[1] % mod
        d = b[0] * a[1] % mod
        e = a[1] * b[1] % mod
        return [(c+d)%mod, e]

    def sub(a,b):
        c = a[0] * b[1] % mod
        d = -b[0] * a[1] % mod
        e = a[1] * b[1] % mod
        return [(c+d)%mod, e]

    def mul(a,b):
        c = a[0] * b[0] % mod
        d = a[1] * b[1] % mod
        return [c,d]

    fm = {}
    def f(c,a,m,p,q):
        if m == 0 or c == 0:
            return [c, 1]

        key = (c,a,m,p,q)
        if key in fm:
            return fm[key]

        s = c + p + q
        x = f(c+a,a,m-1,p,q)
        r = mul(x, [c, s])
        if p > 0:
            y = f(c,a,m-1,p+1,q)
            r = plus(r, mul(y, [p, s]))
        if q > 0:
            z = f(c,a,m-1,p,q-1)
            r = plus(r, mul(z, [q, s]))

        fm[key] = r
        return r

    ps = 0
    qs = 0
    for i in range(n):
        if a[i] == 1:
            ps += w[i]
        else:
            qs += w[i]

    r = []
    for i in range(n):
        if a[i] == 1:
            v = f(w[i],1,m,ps-w[i],qs)
        else:
            v =...


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

Nauuo is a girl who loves random picture websites.

One day she made a random picture website by herself which includes $n$ pictures.

When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The $i$-th picture has a non-negative weight $w_i$, and the probability of the $i$-th picture being displayed is $\frac{w_i}{\sum_{j=1}^nw_j}$. That is to say, the probability of a picture to be displayed is proportional to its weight.

However, Nauuo discovered that some pictures she does not like were displayed too often.

To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add $1$ to its weight; otherwise, she would subtract $1$ from its weight.

Nauuo will visit the website $m$ times. She wants to know the expected weight of each picture after all the $m$ visits modulo $998244353$. Can you help her?

The expected weight of the $i$-th picture can be denoted by $\frac {q_i} {p_i}$ where $\gcd(p_i,q_i)=1$, you need to print an integer $r_i$ satisfying $0\le r_i<998244353$ and $r_i\cdot p_i\equiv q_i\pmod{998244353}$. It can be proved that such $r_i$ exists and is unique.

-----Input-----

The first line contains two integers $n$ and $m$ ($1\le n\le 2\cdot 10^5$, $1\le m\le 3000$) — the number of pictures and the number of visits to the website.

The second line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($a_i$ is either $0$ or $1$) — if $a_i=0$ , Nauuo does not like the $i$-th picture; otherwise Nauuo likes the $i$-th picture. It is guaranteed that there is at least one picture which Nauuo likes.

The third line contains $n$ positive integers $w_1,w_2,\ldots,w_n$ ($w_i \geq 1$) — the initial weights of the pictures. It is guaranteed that the sum of all the initial weights does not exceed $998244352-m$.

-----Output-----

The output contains $n$ integers $r_1,r_2,\ldots,r_n$ — the expected weights modulo...

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

P = 998244353
N, M = list(map(int, input().split()))
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
li = sum([A[i]*B[i] for i in range(N)])
di = sum([(A[i]^1)*B[i] for i in range(N)])
X = [1]
SU = li+di
PO = [0] * (5*M+10)
for i in range(-M-5, 2*M+5):
    PO[i] = pow((SU+i)%P, P-2, P)

def calc(L):
    su = sum(L)
    pl = 0
    pd = 0
    RE = []
    for i in range(len(L)):
        a = li + i
        b = di - (len(L) - 1 - i)
        pd = b * L[i] * PO[a+b-SU]
        RE.append((pl+pd)%P)
        pl = a * L[i] * PO[a+b-SU]
    RE.append(pl%P)
    return RE

for i in range(M):
    X = calc(X)
ne = 0
po = 0
for i in range(M+1):
    po = (po + X[i] * (li + i)) % P
    ne = (ne + X[i] * (di - M + i)) % P
invli = pow(li, P-2, P)
invdi = pow(di, P-2, P)
for i in range(N):
    print(po * B[i] * invli % P if A[i] else ne * B[i] * invdi % P)


I found an interesting problem on https://codeforces.com/problemset/problem/1173/A:
Nauuo is a girl who loves writing comments.

One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes.

It's known that there were $x$ persons who would upvote, $y$ persons who would downvote, and there were also another $z$ persons who would vote, but you don't know whether they would upvote or downvote. Note that each of the $x+y+z$ people would vote exactly one time.

There are three different results: if there are more people upvote than downvote, the result will be "+"; if there are more people downvote than upvote, the result will be "-"; otherwise the result will be "0".

Because of the $z$ unknown persons, the result may be uncertain (i.e. there are more than one possible results). More formally, the result is uncertain if and only if there exist two different situations of how the $z$ persons vote, that the results are different in the two situations.

Tell Nauuo the result or report that the result is uncertain.

-----Input-----

The only line contains three integers $x$, $y$, $z$ ($0\le x,y,z\le100$), corresponding to the number of persons who would upvote, downvote or unknown.

-----Output-----

If there is only one possible result, print the result : "+", "-" or "0".

Otherwise, print "?" to report that the result is uncertain.

-----Examples-----
Input
3 7 0

Output
-
Input
2 0 1

Output
+
Input
1 1 0

Output
0
Input
0 0 1

Output
?

-----Note-----

In the first example, Nauuo would definitely get three upvotes and seven downvotes, so the only possible result is "-".

In the second example, no matter the person unknown downvotes or upvotes, Nauuo would get more upvotes than downvotes. So the only possible result is "+".

In the third example, Nauuo would definitely get one upvote and one downvote, so the only possible result is "0".

In the fourth example, if the only one person upvoted, the result would be "+", otherwise, the result would be "-". There are two possible results, so the result is uncertain.

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

def f(a):
    if a > 0:
        return '+'
    if a == 0:
        return '0'
    return '-'

x, y, z = list(map(int, input().split()))
if z == 0:
    print(f(x - y))
elif f(x - y - z) != f(x - y + z):
    print('?')
else:
    print(f(x-y-z))


I found an interesting problem on https://codeforces.com/problemset/problem/1173/B:
Nauuo is a girl who loves playing chess.

One day she invented a game by herself which needs $n$ chess pieces to play on a $m\times m$ chessboard. The rows and columns are numbered from $1$ to $m$. We denote a cell on the intersection of the $r$-th row and $c$-th column as $(r,c)$.

The game's goal is to place $n$ chess pieces numbered from $1$ to $n$ on the chessboard, the $i$-th piece lies on $(r_i,\,c_i)$, while the following rule is satisfied: for all pairs of pieces $i$ and $j$, $|r_i-r_j|+|c_i-c_j|\ge|i-j|$. Here $|x|$ means the absolute value of $x$.

However, Nauuo discovered that sometimes she couldn't find a solution because the chessboard was too small.

She wants to find the smallest chessboard on which she can put $n$ pieces according to the rules.

She also wonders how to place the pieces on such a chessboard. Can you help her?

-----Input-----

The only line contains a single integer $n$ ($1\le n\le 1000$) — the number of chess pieces for the game.

-----Output-----

The first line contains a single integer — the minimum value of $m$, where $m$ is the length of sides of the suitable chessboard.

The $i$-th of the next $n$ lines contains two integers $r_i$ and $c_i$ ($1\le r_i,c_i\le m$) — the coordinates of the $i$-th chess piece.

If there are multiple answers, print any.

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

Output
2
1 1
1 2
Input
4

Output
3
1 1
1 3
3 1
3 3

-----Note-----

In the first example, you can't place the two pieces on a $1\times1$ chessboard without breaking the rule. But you can place two pieces on a $2\times2$ chessboard like this:

[Image]

In the second example, you can't place four pieces on a $2\times2$ chessboard without breaking the rule. For example, if you place the pieces like this:

[Image]

then $|r_1-r_3|+|c_1-c_3|=|1-2|+|1-1|=1$, $|1-3|=2$, $1<2$; and $|r_1-r_4|+|c_1-c_4|=|1-2|+|1-2|=2$, $|1-4|=3$, $2<3$. It doesn't satisfy the rule.

However, on a $3\times3$ chessboard, you can place four pieces like this:

[Image]

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

from collections import defaultdict as dd
import math
import sys
input=sys.stdin.readline
def nn():
	return int(input())

def li():
	return list(input())

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

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

n=nn()

size=(n+2)//2

print(size)

for i in range(size):
	print(1, i+1)

for j in range(n-size):
	print(j+2,size)


I found an interesting problem on https://codeforces.com/problemset/problem/1174/A:
You're given an array $a$ of length $2n$. Is it possible to reorder it in such way so that the sum of the first $n$ elements isn't equal to the sum of the last $n$ elements?

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 1000$), where $2n$ is the number of elements in the array $a$.

The second line contains $2n$ space-separated integers $a_1$, $a_2$, $\ldots$, $a_{2n}$ ($1 \le a_i \le 10^6$) — the elements of the array $a$.

-----Output-----

If there's no solution, print "-1" (without quotes). Otherwise, print a single line containing $2n$ space-separated integers. They must form a reordering of $a$. You are allowed to not change the order.

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

Output
2 1 3 1 1 2
Input
1
1 1

Output
-1

-----Note-----

In the first example, the first $n$ elements have sum $2+1+3=6$ while the last $n$ elements have sum $1+1+2=4$. The sums aren't equal.

In the second example, there's no solution.

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

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

if sum(A)==2*sum(A[:n]):
    print(-1)
else:
    print(*A)


I found an interesting problem on https://codeforces.com/problemset/problem/1174/B:
You're given an array $a$ of length $n$. You can perform the following operation on it as many times as you want:  Pick two integers $i$ and $j$ $(1 \le i,j \le n)$ such that $a_i+a_j$ is odd, then swap $a_i$ and $a_j$.

What is lexicographically the smallest array you can obtain?

An array $x$ is lexicographically smaller than an array $y$ if there exists an index $i$ such that $x_i<y_i$, and $x_j=y_j$ for all $1 \le j < i$. Less formally, at the first index $i$ in which they differ, $x_i<y_i$

-----Input-----

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

The second line contains $n$ space-separated integers $a_1$, $a_2$, $\ldots$, $a_{n}$ ($1 \le a_i \le 10^9$) — the elements of the array $a$.

-----Output-----

The only line contains $n$ space-separated integers, the lexicographically smallest array you can obtain.

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

Output
1 4 7
Input
2
1 1

Output
1 1

-----Note-----

In the first example, we can swap $1$ and $4$ since $1+4=5$, which is odd.

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

import sys
input = sys.stdin.readline

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

ki=0
gu=0

for a in A:
    if a%2==0:
        gu=1
    else:
        ki=1

if ki==1 and gu==1:
    print(*sorted(A))
else:
    print(*A)


I found an interesting problem on https://codeforces.com/problemset/problem/1174/C:
You're given an integer $n$. For every integer $i$ from $2$ to $n$, assign a positive integer $a_i$ such that the following conditions hold:  For any pair of integers $(i,j)$, if $i$ and $j$ are coprime, $a_i \neq a_j$.  The maximal value of all $a_i$ should be minimized (that is, as small as possible).

A pair of integers is called coprime if their greatest common divisor is $1$.

-----Input-----

The only line contains the integer $n$ ($2 \le n \le 10^5$).

-----Output-----

Print $n-1$ integers, $a_2$, $a_3$, $\ldots$, $a_n$ ($1 \leq a_i \leq n$).

If there are multiple solutions, print any of them.

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

Output
1 2 1
Input
3

Output
2 1

-----Note-----

In the first example, notice that $3$ and $4$ are coprime, so $a_3 \neq a_4$. Also, notice that $a=[1,2,3]$ satisfies the first condition, but it's not a correct answer because its maximal value is $3$.

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

n = int(input())
prime = [0, 0] + [1] * 99999
ans = [0] * 100001
newcnt = 1
for i in range(2, n + 1):
	if prime[i] == 0:
		continue
	ans[i] = newcnt
	t = 2
	while i * t <= n:
		prime[i * t] = 0
		ans[i * t] = newcnt
		t += 1
	newcnt += 1
print(*(ans[2:n+1]))


I found an interesting problem on https://codeforces.com/problemset/problem/1174/D:
Given two integers $n$ and $x$, construct an array that satisfies the following conditions:   for any element $a_i$ in the array, $1 \le a_i<2^n$;  there is no non-empty subsegment with bitwise XOR equal to $0$ or $x$,  its length $l$ should be maximized.

A sequence $b$ is a subsegment of a sequence $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

-----Input-----

The only line contains two integers $n$ and $x$ ($1 \le n \le 18$, $1 \le x<2^{18}$).

-----Output-----

The first line should contain the length of the array $l$.

If $l$ is positive, the second line should contain $l$ space-separated integers $a_1$, $a_2$, $\dots$, $a_l$ ($1 \le a_i < 2^n$) — the elements of the array $a$.

If there are multiple solutions, print any of them.

-----Examples-----
Input
3 5

Output
3
6 1 3
Input
2 4

Output
3
1 3 1
Input
1 1

Output
0

-----Note-----

In the first example, the bitwise XOR of the subsegments are $\{6,7,4,1,2,3\}$.

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

N, X = list(map(int, input().split()))
if X == 0 or X >= 2**N:
    A = [a for a in range(N)]
else:
    for i in range(N):
        if (1<<i) & X:
            A = [a for a in range(N) if a != i]
            break

def calc(B):
    if B:
        b = B[-1]
        t = calc(B[:-1])
        return t + [1<<b] + t
    return []

ca = calc(A)
print(len(ca))
if len(ca):
    print(*ca)


I found an interesting problem on https://codeforces.com/problemset/problem/1174/E:
Let's define a function $f(p)$ on a permutation $p$ as follows. Let $g_i$ be the greatest common divisor (GCD) of elements $p_1$, $p_2$, ..., $p_i$ (in other words, it is the GCD of the prefix of length $i$). Then $f(p)$ is the number of distinct elements among $g_1$, $g_2$, ..., $g_n$.

Let $f_{max}(n)$ be the maximum value of $f(p)$ among all permutations $p$ of integers $1$, $2$, ..., $n$.

Given an integers $n$, count the number of permutations $p$ of integers $1$, $2$, ..., $n$, such that $f(p)$ is equal to $f_{max}(n)$. Since the answer may be large, print the remainder of its division by $1000\,000\,007 = 10^9 + 7$.

-----Input-----

The only line contains the integer $n$ ($2 \le n \le 10^6$) — the length of the permutations.

-----Output-----

The only line should contain your answer modulo $10^9+7$.

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

Output
1
Input
3

Output
4
Input
6

Output
120

-----Note-----

Consider the second example: these are the permutations of length $3$:  $[1,2,3]$, $f(p)=1$.  $[1,3,2]$, $f(p)=1$.  $[2,1,3]$, $f(p)=2$.  $[2,3,1]$, $f(p)=2$.  $[3,1,2]$, $f(p)=2$.  $[3,2,1]$, $f(p)=2$.

The maximum value $f_{max}(3) = 2$, and there are $4$ permutations $p$ such that $f(p)=2$.

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

p=10**9+7
import math
def r(l):
    x=1
    for m in l:
        x=x*m%p
    return x
n=int(input())
a,k,x,t=[],int(math.log2(n)),n,0
while x>0:
    a.append(x-x//2)
    x//=2
b=[n//(3*2**i)-n//(6*2**i) for i in range(k+1)]
d=[n//2**i-n//(3*2**i) for i in range(k+1)]
y=r(i for i in range(2,n+1))
s=k if n<3*2**(k-1) else 0
for j in range(s,k+1):
    e=[a[i] for i in range(j)]+[d[j]]+[b[i] for i in range(j,k)]
    x=y*r(e)%p
    f=r(sum(e[:i+1]) for i in range(k+1))
    while f>1:
        x*=p//f+1
        f=f*(p//f+1)%p
    t+=x%p
print(t%p)


I found an interesting problem on https://codeforces.com/problemset/problem/1175/A:
You are given an integer $n$ and an integer $k$.

In one step you can do one of the following moves:   decrease $n$ by $1$;  divide $n$ by $k$ if $n$ is divisible by $k$.

For example, if $n = 27$ and $k = 3$ you can do the following steps: $27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$.

You are asked to calculate the minimum number of steps to reach $0$ from $n$.

-----Input-----

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

The only line of each query contains two integers $n$ and $k$ ($1 \le n \le 10^{18}$, $2 \le k \le 10^{18}$).

-----Output-----

For each query print the minimum number of steps to reach $0$ from $n$ in single line.

-----Example-----
Input
2
59 3
1000000000000000000 10

Output
8
19

-----Note-----

Steps for the first test case are: $59 \rightarrow 58 \rightarrow 57 \rightarrow 19 \rightarrow 18 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$.

In the second test case you have to divide $n$ by $k$ $18$ times and then decrease $n$ by $1$.

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

q=int(input())
for i in range(q):
    n,k=[int(x) for x in input().split()]
    counter=0
    while n!=0:
        x=n%k
        n-=x
        counter+=x+1
        n//=k
    print(counter-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1175/B:
You are given a function $f$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $x$. $x$ is an integer variable and can be assigned values from $0$ to $2^{32}-1$. The function contains three types of commands:

  for $n$ — for loop;  end — every command between "for $n$" and corresponding "end" is executed $n$ times;  add — adds 1 to $x$.

After the execution of these commands, value of $x$ is returned.

Every "for $n$" is matched with "end", thus the function is guaranteed to be valid. "for $n$" can be immediately followed by "end"."add" command can be outside of any for loops.

Notice that "add" commands might overflow the value of $x$! It means that the value of $x$ becomes greater than $2^{32}-1$ after some "add" command.

Now you run $f(0)$ and wonder if the resulting value of $x$ is correct or some overflow made it incorrect.

If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of $x$.

-----Input-----

The first line contains a single integer $l$ ($1 \le l \le 10^5$) — the number of lines in the function.

Each of the next $l$ lines contains a single command of one of three types:

  for $n$ ($1 \le n \le 100$) — for loop;  end — every command between "for $n$" and corresponding "end" is executed $n$ times;  add — adds 1 to $x$.

-----Output-----

If overflow happened during execution of $f(0)$, then output "OVERFLOW!!!", otherwise print the resulting value of $x$.

-----Examples-----
Input
9
add
for 43
end
for 10
for 15
add
end
add
end

Output
161

Input
2
for 62
end

Output
0

Input
11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end

Output
OVERFLOW!!!

-----Note-----

In the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for $n$" can be immediately followed by "end" and that "add" can be outside of any for loops.

In the second example there are no commands "add", thus the returning...

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

T = int(input())
ans = 0
top = -1
stack = []
times = 1
j = 0
bj = 0
while T>0:
    T = T - 1
    s = input().strip().split()
    if len(s)==1:
        if s[0]=="add":
            ans+=times
        else:
            if j==0:
                times//=stack[top]
                top-=1
            else:
                j-=1
    else:
        x=int(s[1])

        if times<=4294967295:
            times*=x
            top+=1
            if top>=len(stack):
                stack.append(x)
            else:
                stack[top]=x
        else:
            j+=1

    if ans>4294967295:
        bj=1
        break
if bj==0:
    print(ans)
else:
    print("OVERFLOW!!!")