I found an interesting problem on https://codeforces.com/problemset/problem/1097/B:
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of $360$ degrees and a pointer which initially points at zero:

 [Image]

Petr called his car dealer, who instructed him to rotate the lock's wheel exactly $n$ times. The $i$-th rotation should be $a_i$ degrees, either clockwise or counterclockwise, and after all $n$ rotations the pointer should again point at zero.

This confused Petr a little bit as he isn't sure which rotations should be done clockwise and which should be done counterclockwise. As there are many possible ways of rotating the lock, help him and find out whether there exists at least one, such that after all $n$ rotations the pointer will point at zero again.

-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 15$) — the number of rotations.

Each of the following $n$ lines contains one integer $a_i$ ($1 \leq a_i \leq 180$) — the angle of the $i$-th rotation in degrees.

-----Output-----

If it is possible to do all the rotations so that the pointer will point at zero after all of them are performed, print a single word "YES". Otherwise, print "NO". Petr will probably buy a new car in this case.

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

-----Examples-----
Input
3
10
20
30

Output
YES

Input
3
10
10
10

Output
NO

Input
3
120
120
120

Output
YES

-----Note-----

In the first example, we can achieve our goal by applying the first and the second rotation clockwise, and performing the third rotation counterclockwise.

In the second example, it's impossible to perform the rotations in order to make the pointer point at zero in the end.

In the third example, Petr can do all three rotations clockwise. In this case, the whole wheel will be rotated by $360$ degrees clockwise and the pointer will point at zero again.

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

n = int(input())
a = [int(input()) for i in range(n)]
for i in range(2 ** n):
	su = 0
	for j in range(n):
		if ((1 << j) | i) != i:
			su += a[j]
		else:
			su -= a[j]
	if su % 360 == 0:
		print('YES')
		return
print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1097/C:
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.

A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.

Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.

This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?

-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 10^5$) — the number of bracket sequences.

Each of the following $n$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")".

The sum of lengths of all bracket sequences in the input is at most $5 \cdot 10^5$.

Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.

-----Output-----

Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.

-----Examples-----
Input
7
)())
)
((
((
(
)
)

Output
2

Input
4
(
((
(((
(())

Output
0

Input
2
(())
()

Output
1

-----Note-----

In the first example, it's optimal to construct two pairs: "((     )())" and "(     )".

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

from collections import defaultdict as dd
d = dd(int)

n = int(input())
for i in range(n):
    s = input()
    f = 0
    ff = 0
    for j in range(len(s)):
        if s[ j ] == '(':
            f += 1
        elif s[ j ] == ')':
            f -= 1
        if f < 0:
            ff += 1
            f = 0
    if f == 0:
        d[ -ff ] += 1
    elif ff == 0:
        d[ f ] += 1

s = d[ 0 ] // 2
for k, v in list(d.items()):
    if k > 0:
        s += min( d[ k ], d[ -k ] )

print( s )


I found an interesting problem on https://codeforces.com/problemset/problem/1097/D:
Makoto has a big blackboard with a positive integer $n$ written on it. He will perform the following action exactly $k$ times:

Suppose the number currently written on the blackboard is $v$. He will randomly pick one of the divisors of $v$ (possibly $1$ and $v$) and replace $v$ with this divisor. As Makoto uses his famous random number generator (RNG) and as he always uses $58$ as his generator seed, each divisor is guaranteed to be chosen with equal probability.

He now wonders what is the expected value of the number written on the blackboard after $k$ steps.

It can be shown that this value can be represented as $\frac{P}{Q}$ where $P$ and $Q$ are coprime integers and $Q \not\equiv 0 \pmod{10^9+7}$. Print the value of $P \cdot Q^{-1}$ modulo $10^9+7$.

-----Input-----

The only line of the input contains two integers $n$ and $k$ ($1 \leq n \leq 10^{15}$, $1 \leq k \leq 10^4$).

-----Output-----

Print a single integer — the expected value of the number on the blackboard after $k$ steps as $P \cdot Q^{-1} \pmod{10^9+7}$ for $P$, $Q$ defined above.

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

Output
3

Input
6 2

Output
875000008

Input
60 5

Output
237178099

-----Note-----

In the first example, after one step, the number written on the blackboard is $1$, $2$, $3$ or $6$ — each occurring with equal probability. Hence, the answer is $\frac{1+2+3+6}{4}=3$.

In the second example, the answer is equal to $1 \cdot \frac{9}{16}+2 \cdot \frac{3}{16}+3 \cdot \frac{3}{16}+6 \cdot \frac{1}{16}=\frac{15}{8}$.

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

def primeFactor(N):
    i = 2
    ret = {}
    n = N
    mrFlg = 0
    if n < 0:
        ret[-1] = 1
        n = -n
    if n == 0:
        ret[0] = 1
    while i**2 <= n:
        k = 0
        while n % i == 0:
            n //= i
            k += 1
            ret[i] = k
        if i == 2:
            i = 3
        else:
            i += 2
        if i == 101 and n >= (2**20):
            def findFactorRho(N):
                # print("FFF", N)
                def gcd(a, b):
                    if b == 0:
                        return a
                    else:
                        return gcd(b, a % b)
                def f(x, c):
                    return ((x ** 2) + c) % N
                semi = [N]
                for c in range(1, 11):
                    x=2
                    y=2
                    d=1
                    while d == 1:
                        x = f(x, c)
                        y = f(f(y, c), c)
                        d = gcd(abs(x-y), N)
                    if d != N:
                        if isPrimeMR(d):
                            return d
                        elif isPrimeMR(N//d):
                            return N//d
                        else:
                            semi.append(d)

                semi = list(set(semi))
                # print (semi)
                s = min(semi)
                for i in [2,3,5,7]:
                    while True:
                        t = int(s**(1/i)+0.5)
                        if t**i == s:
                            s = t
                            if isPrimeMR(s):
                                return s
                        else:
                            break

                i = 3
                while True:
                    if s % i == 0:
                        return i
                    i += 2

            while True:
                if isPrimeMR(n):
                    ret[n] = 1
                    n = 1
                    break
                else:
                    mrFlg...


I found an interesting problem on https://codeforces.com/problemset/problem/1099/A:
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain.

Initially, snowball is at height $h$ and it has weight $w$. Each second the following sequence of events happens: snowball's weights increases by $i$, where $i$ — is the current height of snowball, then snowball hits the stone (if it's present at the current height), then snowball moves one meter down. If the snowball reaches height zero, it stops.

There are exactly two stones on the mountain. First stone has weight $u_1$ and is located at height $d_1$, the second one — $u_2$ and $d_2$ respectively. When the snowball hits either of two stones, it loses weight equal to the weight of that stone. If after this snowball has negative weight, then its weight becomes zero, but the snowball continues moving as before. [Image]

Find the weight of the snowball when it stops moving, that is, it reaches height 0.

-----Input-----

First line contains two integers $w$ and $h$ — initial weight and height of the snowball ($0 \le w \le 100$; $1 \le h \le 100$).

Second line contains two integers $u_1$ and $d_1$ — weight and height of the first stone ($0 \le u_1 \le 100$; $1 \le d_1 \le h$).

Third line contains two integers $u_2$ and $d_2$ — weight and heigth of the second stone ($0 \le u_2 \le 100$; $1 \le d_2 \le h$; $d_1 \ne d_2$). Notice that stones always have different heights.

-----Output-----

Output a single integer — final weight of the snowball after it reaches height 0.

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

Output
8
Input
4 3
9 2
0 1

Output
1

-----Note-----

In the first example, initially a snowball of weight 4 is located at a height of 3, there are two stones of weight 1, at a height of 1 and 2, respectively. The following events occur sequentially:   The weight of the snowball increases by 3 (current height), becomes equal to 7.  The snowball moves one meter down, the current height becomes equal to 2.  The weight of the...

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

w,h = list(map(int, input().split()))
u1,d1 = list(map(int, input().split()))
u2, d2 = list(map(int, input().split()))

for i in range(h, -1, -1):
    w += i
    if i == d1:
        w -= u1
    if i == d2:
        w -= u2
    w = max(w, 0)
print(w)


I found an interesting problem on https://codeforces.com/problemset/problem/1099/B:
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw $n$ squares in the snow with a side length of $1$. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length $1$, parallel to the coordinate axes, with vertices at integer points.

In order to draw a segment, Sofia proceeds as follows. If she wants to draw a vertical segment with the coordinates of the ends $(x, y)$ and $(x, y+1)$. Then Sofia looks if there is already a drawn segment with the coordinates of the ends $(x', y)$ and $(x', y+1)$ for some $x'$. If such a segment exists, then Sofia quickly draws a new segment, using the old one as a guideline. If there is no such segment, then Sofia has to take a ruler and measure a new segment for a long time. Same thing happens when Sofia wants to draw a horizontal segment, but only now she checks for the existence of a segment with the same coordinates $x$, $x+1$ and the differing coordinate $y$.

For example, if Sofia needs to draw one square, she will have to draw two segments using a ruler:  [Image]

After that, she can draw the remaining two segments, using the first two as a guide:  [Image]

If Sofia needs to draw two squares, she will have to draw three segments using a ruler:  [Image]

After that, she can draw the remaining four segments, using the first three as a guide:  [Image]

Sofia is in a hurry, so she wants to minimize the number of segments that she will have to draw with a ruler without a guide. Help her find this minimum number.

-----Input-----

The only line of input contains a single integer $n$ ($1 \le n \le 10^{9}$), the number of squares that Sofia wants to draw.

-----Output-----

Print single integer, the minimum number of segments that Sofia will have to draw with a ruler without a guide in order to draw $n$ squares in the manner described above.

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

Output
2

Input
2

Output
3

Input
4

Output
4

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

n = int( input() )

a = 0
b = 0

while a * b < n:
    if a == b:
        a += 1
    else:
        b += 1

print( a + b )


I found an interesting problem on https://codeforces.com/problemset/problem/1099/C:
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.

Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.

For example, consider the following string:  [Image]

This string can encode the message «happynewyear». For this, candy canes and snowflakes should be used as follows:   candy cane 1: remove the letter w,  snowflake 1: repeat the letter p twice,  candy cane 2: leave the letter n,  snowflake 2: remove the letter w,  snowflake 3: leave the letter e.

 [Image]

Please note that the same string can encode different messages. For example, the string above can encode «hayewyar», «happpppynewwwwwyear», and other messages.

Andrey knows that messages from Irina usually have a length of $k$ letters. Help him to find out if a given string can encode a message of $k$ letters, and if so, give an example of such a message.

-----Input-----

The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters «*» and «?», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed $200$.

The second line contains an integer number $k$ ($1 \leq k \leq 200$), the required message length.

-----Output-----

Print any message of length $k$ that the given string can encode, or «Impossible» if such a message does not exist.

-----Examples-----
Input
hw?ap*yn?eww*ye*ar
12

Output
happynewyear

Input
ab?a
2

Output
aa
Input
ab?a
3

Output
aba
Input
ababb
5

Output
ababb
Input
ab?a
1

Output
Impossible

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

a = input()
k = int(input())

ml = 0
for i in a:
    if i == '?' or i == '*':
        ml -= 1
    else:
        ml += 1

if k < ml:
    print('Impossible')
    import sys
    return

dl = k - ml
t = ''
n = len(a)
for i in range(n):
    if i + 1 < n and a[i + 1] == '?':
        if dl <= 0: continue
        t += a[i]
        dl -= 1
        continue
    if i + 1 < n and a[i + 1] == '*':
        if dl <= 0: continue
        while dl > 0:
            t += a[i]
            dl -= 1
        continue
    if a[i] not in '?*':
        t += a[i]

if len(t) == k:
    print(t)
else:
    print('Impossible')


I found an interesting problem on https://codeforces.com/problemset/problem/1100/A:
This morning, Roman woke up and opened the browser with $n$ opened tabs numbered from $1$ to $n$. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.

He decided to accomplish this by closing every $k$-th ($2 \leq k \leq n - 1$) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be $b$) and then close all tabs with numbers $c = b + i \cdot k$ that satisfy the following condition: $1 \leq c \leq n$ and $i$ is an integer (it may be positive, negative or zero).

For example, if $k = 3$, $n = 14$ and Roman chooses $b = 8$, then he will close tabs with numbers $2$, $5$, $8$, $11$ and $14$.

After closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it $e$) and the amount of remaining social network tabs ($s$). Help Roman to calculate the maximal absolute value of the difference of those values $|e - s|$ so that it would be easy to decide what to do next.

-----Input-----

The first line contains two integers $n$ and $k$ ($2 \leq k < n \leq 100$) — the amount of tabs opened currently and the distance between the tabs closed.

The second line consists of $n$ integers, each of them equal either to $1$ or to $-1$. The $i$-th integer denotes the type of the $i$-th tab: if it is equal to $1$, this tab contains information for the test, and if it is equal to $-1$, it's a social network tab.

-----Output-----

Output a single integer — the maximum absolute difference between the amounts of remaining tabs of different types $|e - s|$.

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

Output
2

Input
14 3
-1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1

Output
9

-----Note-----

In the first example we can choose $b = 1$ or $b = 3$. We will delete then one tab of each type and the remaining tabs are then all contain test...

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

n, k = (int(x) for x in input().split())
tabs = [int(x) for x in input().split()]

#print(n, k, tabs)

mods = [sum(tabs[i::k]) for i in range(k)]

#print(mods)

summods = sum(mods)
ans = -1
for i in range(k):
	cand = abs(summods - mods[i])
	if cand > ans:
		ans = cand

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1100/B:
Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $n$ problems of distinct difficulty, the difficulties are numbered from $1$ to $n$.

To hold a round Arkady needs $n$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from $1$ to $n$ and puts it into the problems pool.

At each moment when Arkady can choose a set of $n$ new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.

You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 10^5$) — the number of difficulty levels and the number of problems Arkady created.

The second line contains $m$ integers $a_1, a_2, \ldots, a_m$ ($1 \le a_i \le n$) — the problems' difficulties in the order Arkady created them.

-----Output-----

Print a line containing $m$ digits. The $i$-th digit should be $1$ if Arkady held the round after creation of the $i$-th problem, and $0$ otherwise.

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

Output
00100000001

Input
4 8
4 1 3 3 2 3 3 3

Output
00001000

-----Note-----

In the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem.

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

from collections import deque
n,m=[int(i) for i in input().split()]
a=[int(i) for i in input().split()]
b=[deque([]) for i in range(n+1)]
for i in range(m):
	b[a[i]].append(i)
#print(b)
o=False
count=0
indp=0
while o==False:
	ind=0
	for i in range(1,n+1):
		if len(b[i])==0:
			o=True
			break
		ind=max(b[i].popleft(),ind)
	if o==True:
		for i in range(indp,m):
			print(0,end='')
		break
	for i in range(indp,ind):
		print(0,end='')
	indp=ind+1
	print(1,end='')
print()


I found an interesting problem on https://codeforces.com/problemset/problem/1100/C:
NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: [Image]

It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.

He managed to calculate the number of outer circles $n$ and the radius of the inner circle $r$. NN thinks that, using this information, you can exactly determine the radius of the outer circles $R$ so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that.

Help NN find the required radius for building the required picture.

-----Input-----

The first and the only line of the input file contains two numbers $n$ and $r$ ($3 \leq n \leq 100$, $1 \leq r \leq 100$) — the number of the outer circles and the radius of the inner circle respectively.

-----Output-----

Output a single number $R$ — the radius of the outer circle required for building the required picture.

Your answer will be accepted if its relative or absolute error does not exceed $10^{-6}$.

Formally, if your answer is $a$ and the jury's answer is $b$. Your answer is accepted if and only when $\frac{|a-b|}{max(1, |b|)} \le 10^{-6}$.

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

Output
6.4641016

Input
6 1

Output
1.0000000

Input
100 100

Output
3.2429391

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

import math

n,r = [int(x) for x in input().split()]

x = math.sin(math.pi/n)

y = (x*r)/(1-x)

print(y)


I found an interesting problem on https://codeforces.com/problemset/problem/1100/E:
Andrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to insidious taxi drivers.

The mayor of the city decided to change the direction of certain roads so that the taxi drivers wouldn't be able to increase the cost of the trip endlessly. More formally, if the taxi driver is on a certain crossroads, they wouldn't be able to reach it again if he performs a nonzero trip.

Traffic controllers are needed in order to change the direction the road goes. For every road it is known how many traffic controllers are needed to change the direction of the road to the opposite one. It is allowed to change the directions of roads one by one, meaning that each traffic controller can participate in reversing two or more roads.

You need to calculate the minimum number of traffic controllers that you need to hire to perform the task and the list of the roads that need to be reversed.

-----Input-----

The first line contains two integers $n$ and $m$ ($2 \leq n \leq 100\,000$, $1 \leq m \leq 100\,000$) — the number of crossroads and the number of roads in the city, respectively.

Each of the following $m$ lines contain three integers $u_{i}$, $v_{i}$ and $c_{i}$ ($1 \leq u_{i}, v_{i} \leq n$, $1 \leq c_{i} \leq 10^9$, $u_{i} \ne v_{i}$) — the crossroads the road starts at, the crossroads the road ends at and the number of traffic controllers required to reverse this road.

-----Output-----

In the first line output two integers the minimal amount of traffic controllers required to complete the task and amount of roads $k$ which should be reversed. $k$ should not be minimized.

In the next line output $k$ integers separated by spaces — numbers of roads, the directions of which should be reversed. The roads are numerated from $1$ in the order they are written in the...

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

# problem http://codeforces.com/contest/1100/problem/E
import copy
import sys

def find_loop(g, w, k, n):
    visited = [False] * n
    visited_int = [False] * n
    for i in range(n):
        if visited[i]:
            continue
        stack = [g[i][:]]
        path = [i]
        visited[i] = True
        visited_int[i] = True
        while stack:
            if not stack[-1]:
                stack.pop()
                visited_int[path[-1]] = False
                path.pop()
                continue
            nxt = stack[-1][-1]
            stack[-1].pop()
            if w[(path[-1], nxt)] <= k:
                continue
            if visited_int[nxt]:
                return True
            if visited[nxt]:
                continue
            visited[nxt] = True
            visited_int[nxt] = True
            stack.append(g[nxt][:])
            path.append(nxt)
    return False

def top_sort(g, w, k, n):
    visited = [False] * n
    order = [-1] * n
    cnt = 0
    for i in range(n):
        if visited[i]:
            continue
        stack = [g[i][:]]
        path = [i]
        visited[i] = True
        while stack:
            if not stack[-1]:
                order[path[-1]] = cnt
                path.pop()
                stack.pop()
                cnt += 1
                continue
            nxt = stack[-1][-1]
            stack[-1].pop()
            if w[(path[-1], nxt)] <= k:
                continue
            if visited[nxt]:
                continue
            visited[nxt] = True
            stack.append(g[nxt][:])
            path.append(nxt)

    to_reverse = []
    for a, b in list(w.items()):
        if b > k:
            continue
        if order[a[0]] < order[a[1]]:
            to_reverse.append(a)
    return to_reverse

def __starting_point():
    n, m = list(map(int, input().split()))
    w = {}
    g = [[] for _ in range(n)]
    w_tmp = {}
    c_m = 0
    kk = [0]
    lines = sys.stdin.readlines()
    for i, line in enumerate(lines): #range(1, m + 1):
        u, v, c =...


I found an interesting problem on https://codeforces.com/problemset/problem/1101/A:
You are given $q$ queries in the following form:

Given three integers $l_i$, $r_i$ and $d_i$, find minimum positive integer $x_i$ such that it is divisible by $d_i$ and it does not belong to the segment $[l_i, r_i]$.

Can you answer all the queries?

Recall that a number $x$ belongs to segment $[l, r]$ if $l \le x \le r$.

-----Input-----

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

Then $q$ lines follow, each containing a query given in the format $l_i$ $r_i$ $d_i$ ($1 \le l_i \le r_i \le 10^9$, $1 \le d_i \le 10^9$). $l_i$, $r_i$ and $d_i$ are integers.

-----Output-----

For each query print one integer: the answer to this query.

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

Output
6
4
1
3
10

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

from sys import stdin
n=int(stdin.readline().strip())
for i in range(n):
    s=list(map(int,stdin.readline().strip().split()))
    if s[0]>s[2]:
        print(s[2])
        continue
    x=s[1]//s[2]
    x+=1
    print(x*s[2])


I found an interesting problem on https://codeforces.com/problemset/problem/1101/B:
An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code $091$), a colon (ASCII code $058$), some (possibly zero) vertical line characters (ASCII code $124$), another colon, and a closing bracket (ASCII code $093$). The length of the accordion is the number of characters in it.

For example, [::], [:||:] and [:|||:] are accordions having length $4$, $6$ and $7$. (:|:), {:||:}, [:], ]:||:[ are not accordions.

You are given a string $s$. You want to transform it into an accordion by removing some (possibly zero) characters from it. Note that you may not insert new characters or reorder existing ones. Is it possible to obtain an accordion by removing characters from $s$, and if so, what is the maximum possible length of the result?

-----Input-----

The only line contains one string $s$ ($1 \le |s| \le 500000$). It consists of lowercase Latin letters and characters [, ], : and |.

-----Output-----

If it is not possible to obtain an accordion by removing some characters from $s$, print $-1$. Otherwise print maximum possible length of the resulting accordion.

-----Examples-----
Input
|[a:b:|]

Output
4

Input
|]:[|:]

Output
-1

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

s = input()
t_d = 0
try:
    left = -1
    was_b = False
    for i in range(len(s)):
        if s[i] == '[' and not was_b:
            was_b = True
            continue
        if s[i] == ':' and was_b:
            left = i
            break
        t_d += 1
    if left == -1:
        raise ArithmeticError()
    right = -1
    was_b = False
    for i in range(len(s) - 1, -1, -1):
        if s[i] == ']' and not was_b:
            was_b = True
            continue
        if s[i] == ':' and was_b:
            right = i
            break
        t_d += 1
    if right == -1 or right <= left:
        raise ArithmeticError()
    for i in range(left + 1, right):
        if s[i] != '|':
            t_d += 1
    print(len(s) - t_d)
except:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1101/D:
You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$.

Let's denote the function $g(x, y)$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $x$ to vertex $y$ (including these two vertices). Also let's denote $dist(x, y)$ as the number of vertices on the simple path between vertices $x$ and $y$, including the endpoints. $dist(x, x) = 1$ for every vertex $x$.

Your task is calculate the maximum value of $dist(x, y)$ among such pairs of vertices that $g(x, y) > 1$.

-----Input-----

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

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ $(1 \le a_i \le 2 \cdot 10^5)$ — the numbers written on vertices.

Then $n - 1$ lines follow, each containing two integers $x$ and $y$ $(1 \le x, y \le n, x \ne y)$ denoting an edge connecting vertex $x$ with vertex $y$. It is guaranteed that these edges form a tree.

-----Output-----

If there is no pair of vertices $x, y$ such that $g(x, y) > 1$, print $0$. Otherwise print the maximum value of $dist(x, y)$ among such pairs.

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

Output
1

Input
3
2 3 4
1 3
2 3

Output
2

Input
3
1 1 1
1 2
2 3

Output
0

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

import math
import sys

def get_primes(n):
    result = set()
    while n % 2 == 0:
        result.add(2)
        n = n / 2

    for i in range(3, int(math.sqrt(n)) + 1, 2):

        while n % i == 0:
            result.add(i)
            n = n / i

    if n > 2:
        result.add(n)
    return list(result)

def calc(w, t, n):
    stack = []
    stack.append((t[0], dict([(p, [0]) for p in get_primes(w[0])])))
    max_length = 0
    visited = [False] * n
    visited[0] = True
    while stack:
        if stack[-1][0]:
            nxt = stack[-1][0][-1]
            stack[-1][0].pop()
            if visited[nxt]:
                continue
            else:
                visited[nxt] = True
            stack.append((t[nxt], dict([(p, [0]) for p in get_primes(w[nxt])])))
        else:
            last = stack[-1][1]
            stack.pop()
            if last:
                max_length = max(max_length, 1 + max([sum(v) for _, v in list(last.items())]))
            if stack:
                for k, v in list(last.items()):
                    if k in list(stack[-1][1].keys()):
                        stack[-1][1][k].append(max(v) + 1)
                        stack[-1][1][k].sort(reverse=True)
                        if len(stack[-1][1][k]) > 2:
                            del stack[-1][1][k][-1]
    return max_length

# def __starting_point():
#     print(primeFactors(100))

def __starting_point():
    n = int(input())
    weights = list(map(int, input().split()))
    lines = sys.stdin.readlines()
    tree = [[] for _ in range(n)]
    for line in lines:
        x, y = list(map(int, line.split()))
        tree[x - 1].append(y - 1)
        tree[y - 1].append(x - 1)

    print(calc(weights, tree, n))

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1101/E:
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.

Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).

A bill $x \times y$ fits into some wallet $h \times w$ if either $x \le h$ and $y \le w$ or $y \le h$ and $x \le w$. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.

Now you are asked to perform the queries of two types:

  $+~x~y$ — Polycarp earns a bill of size $x \times y$;  $?~h~w$ — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $h \times w$.

It is guaranteed that there is at least one query of type $1$ before the first query of type $2$ and that there is at least one query of type $2$ in the input data.

For each query of type $2$ print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.

-----Input-----

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

Each of the next $n$ lines contains a query of one of these two types:

  $+~x~y$ ($1 \le x, y \le 10^9$) — Polycarp earns a bill of size $x \times y$;  $?~h~w$ ($1 \le h, w \le 10^9$) — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $h \times w$.

It is guaranteed that there is at least one query of type $1$ before the first query of type $2$ and that there is at least one query of type $2$ in the input data.

-----Output-----

For each query of type $2$ print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.

-----Example-----
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1...

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


I found an interesting problem on https://codeforces.com/problemset/problem/1101/G:
You are given an array $a_1, a_2, \dots, a_n$ of integer numbers.

Your task is to divide the array into the maximum number of segments in such a way that:

  each element is contained in exactly one segment;  each segment contains at least one element;  there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $0$.

Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists.

-----Input-----

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

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

-----Output-----

Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists.

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

Output
2

Input
3
1 2 3

Output
-1

Input
3
3 1 10

Output
3

-----Note-----

In the first example $2$ is the maximum number. If you divide the array into $\{[5], [5, 7, 2]\}$, the XOR value of the subset of only the second segment is $5 \oplus 7 \oplus 2 = 0$. $\{[5, 5], [7, 2]\}$ has the value of the subset of only the first segment being $5 \oplus 5 = 0$. However, $\{[5, 5, 7], [2]\}$ will lead to subsets $\{[5, 5, 7]\}$ of XOR $7$, $\{[2]\}$ of XOR $2$ and $\{[5, 5, 7], [2]\}$ of XOR $5 \oplus 5 \oplus 7 \oplus 2 = 5$.

Let's take a look at some division on $3$ segments — $\{[5], [5, 7], [2]\}$. It will produce subsets:

  $\{[5]\}$, XOR $5$;  $\{[5, 7]\}$, XOR $2$;  $\{[5], [5, 7]\}$, XOR $7$;  $\{[2]\}$, XOR $2$;  $\{[5], [2]\}$, XOR $7$;  $\{[5, 7], [2]\}$, XOR $0$;  $\{[5], [5, 7], [2]\}$, XOR $5$;

As you can see, subset $\{[5, 7], [2]\}$ has its XOR equal to $0$, which is unacceptable. You can check that for other divisions of size $3$ or $4$, non-empty subset with $0$ XOR always exists.

The second example has no suitable divisions.

The third example array can be divided into $\{[3], [1], [10]\}$. No subset of these...

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

import sys
from math import *
from fractions import gcd
readints=lambda:list(map(int, input().strip('\n').split()))

n=int(input())
arr = list(readints())
arr.sort()

pref=0
basis=[]

for v in arr:
    pref = pref^v
    for b in basis:
        v = min(v, v^b)
    if v>0:
        basis.append(v)

if pref==0:
    print(-1)
else:
    print(len(basis))


I found an interesting problem on https://codeforces.com/problemset/problem/1102/A:
You are given an integer sequence $1, 2, \dots, n$. You have to divide it into two sets $A$ and $B$ in such a way that each element belongs to exactly one set and $|sum(A) - sum(B)|$ is minimum possible.

The value $|x|$ is the absolute value of $x$ and $sum(S)$ is the sum of elements of the set $S$.

-----Input-----

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

-----Output-----

Print one integer — the minimum possible value of $|sum(A) - sum(B)|$ if you divide the initial sequence $1, 2, \dots, n$ into two sets $A$ and $B$.

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

Output
0

Input
5

Output
1

Input
6

Output
1

-----Note-----

Some (not all) possible answers to examples:

In the first example you can divide the initial sequence into sets $A = \{1, 2\}$ and $B = \{3\}$ so the answer is $0$.

In the second example you can divide the initial sequence into sets $A = \{1, 3, 4\}$ and $B = \{2, 5\}$ so the answer is $1$.

In the third example you can divide the initial sequence into sets $A = \{1, 4, 5\}$ and $B = \{2, 3, 6\}$ so the answer is $1$.

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

n = int(input())
s = n * (n + 1) // 2
print(s % 2)


I found an interesting problem on https://codeforces.com/problemset/problem/1102/B:
You are given an array $a$ consisting of $n$ integer numbers.

You have to color this array in $k$ colors in such a way that:   Each element of the array should be colored in some color;  For each $i$ from $1$ to $k$ there should be at least one element colored in the $i$-th color in the array;  For each $i$ from $1$ to $k$ all elements colored in the $i$-th color should be distinct.

Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $c_1, c_2, \dots c_n$, where $1 \le c_i \le k$ and $c_i$ is the color of the $i$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 5000$) — the length of the array $a$ and the number of colors, respectively.

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

-----Output-----

If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $c_1, c_2, \dots c_n$, where $1 \le c_i \le k$ and $c_i$ is the color of the $i$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.

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

Output
YES
1 1 2 2

Input
5 2
3 2 1 2 3

Output
YES
2 1 1 2 1

Input
5 2
2 1 1 2 1

Output
NO

-----Note-----

In the first example the answer $2~ 1~ 2~ 1$ is also acceptable.

In the second example the answer $1~ 1~ 1~ 2~ 2$ is also acceptable.

There exist other acceptable answers for both examples.

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

from operator import itemgetter
n,k=map(int,input().split())
a=list(map(int,input().split()))
c=[0]*5001
for i in range (n):
	x=a[i]
	c[x]+=1

flag=0
ar=[([0]*3) for i in range (n)]
for i in range (n):
	ar[i][0]=a[i]
	ar[i][1]=i

ar=sorted(ar,key=itemgetter(0))
#print(ar)
for i in range (5001):
	if(c[i]>k):
		flag=1
		break

if(flag==0):
	co=1
	for i in range (n):
		if(co>k):
			co=1
		ar[i][2]=co
		co+=1
	print("YES")
	ar=sorted(ar,key=itemgetter(1))
	for i in range (n):
		print(ar[i][2],end=" ")

	print()

else:
	print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1102/C:
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.

There are $n$ doors, the $i$-th door initially has durability equal to $a_i$.

During your move you can try to break one of the doors. If you choose door $i$ and its current durability is $b_i$ then you reduce its durability to $max(0, b_i - x)$ (the value $x$ is given).

During Slavik's move he tries to repair one of the doors. If he chooses door $i$ and its current durability is $b_i$ then he increases its durability to $b_i + y$ (the value $y$ is given). Slavik cannot repair doors with current durability equal to $0$.

The game lasts $10^{100}$ turns. If some player cannot make his move then he has to skip it.

Your goal is to maximize the number of doors with durability equal to $0$ at the end of the game. You can assume that Slavik wants to minimize the number of such doors. What is the number of such doors in the end if you both play optimally?

-----Input-----

The first line of the input contains three integers $n$, $x$ and $y$ ($1 \le n \le 100$, $1 \le x, y \le 10^5$) — the number of doors, value $x$ and value $y$, respectively.

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

-----Output-----

Print one integer — the number of doors with durability equal to $0$ at the end of the game, if you and Slavik both play optimally.

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

Output
6

Input
5 3 3
1 2 4 2 3

Output
2

Input
5 5 6
1 2 6 10 3

Output
2

-----Note-----

Clarifications about the optimal strategy will be ignored.

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

# cook your dish here
for _ in range(1):
    n,x,y = map(int,input().split())
    a = list(map(int,input().split()))
    if x>y:
        print(n)
    else:
        c=0
        for val in a:
            if val <= x:
               c+=1
        print((c+1)//2)


I found an interesting problem on https://codeforces.com/problemset/problem/1102/D:
You are given a string $s$ consisting of exactly $n$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.

Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').

Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.

Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.

It is guaranteed that the answer exists.

-----Input-----

The first line of the input contains one integer $n$ ($3 \le n \le 3 \cdot 10^5$, $n$ is divisible by $3$) — the number of characters in $s$.

The second line contains the string $s$ consisting of exactly $n$ characters '0', '1' and '2'.

-----Output-----

Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.

Because $n$ is divisible by $3$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.

-----Examples-----
Input
3
121

Output
021

Input
6
000000

Output
001122

Input
6
211200

Output
211200

Input
6
120110

Output
120120

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

n=int(input())
s1=str(input())
count1=s1.count('0')
count2=s1.count('1')
count3=s1.count('2')
s=[]
for i in s1:
    s.append(i)
finish=n//3
tcount1=0
tcount2=0
tcount3=0
for i in range(n):
    if(s[i]=='0'):
        if(tcount1==n//3):
            if(count2<finish and tcount2<finish):
                s[i]='1'
                count2+=1
                tcount2+=1
                count1-=1
            elif(count3<finish and tcount3<finish):
                s[i]='2'
                count3+=1
                tcount3+=1
                count1-=1
            else:
                tcount1+=1
        else:
            tcount1+=1
    elif(s[i]=='1'):
        if(count2>n//3):
            if(count1<n//3 and tcount1<n//3):
                s[i]='0'
                count1+=1
                tcount1+=1
                count2-=1
            elif(tcount2==n//3):
                s[i]='2'
                count3+=1
                tcount3+=1
                count2-=1
            else:
                tcount2+=1
        else:
            tcount2+=1
    else:
        if(count3>n//3):
            if(count1<n//3 and tcount1<n//3):
                s[i]='0'
                count1+=1
                tcount1+=1
                count3-=1
            elif(count2<n//3 and tcount2<n//3):
                s[i]='1'
                count2+=1
                tcount2+=1
                count3-=1
            else:
                tcount3+=1
        else:
            tcount3+=1
    #print(tcount1,tcount2,tcount3)
ans=''
for i in s:
    ans+=i
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1102/E:
You are given an array $a$ consisting of $n$ integers. Let's denote monotonic renumeration of array $a$ as an array $b$ consisting of $n$ integers such that all of the following conditions are met:

  $b_1 = 0$;  for every pair of indices $i$ and $j$ such that $1 \le i, j \le n$, if $a_i = a_j$, then $b_i = b_j$ (note that if $a_i \ne a_j$, it is still possible that $b_i = b_j$);  for every index $i \in [1, n - 1]$ either $b_i = b_{i + 1}$ or $b_i + 1 = b_{i + 1}$.

For example, if $a = [1, 2, 1, 2, 3]$, then two possible monotonic renumerations of $a$ are $b = [0, 0, 0, 0, 0]$ and $b = [0, 0, 0, 0, 1]$.

Your task is to calculate the number of different monotonic renumerations of $a$. The answer may be large, so print it modulo $998244353$.

-----Input-----

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

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

-----Output-----

Print one integer — the number of different monotonic renumerations of $a$, taken modulo $998244353$.

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

Output
2

Input
2
100 1

Output
2

Input
4
1 3 3 7

Output
4

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

class SegmentTree(object):
    __slots__ = ["elem_size", "tree", "default", "op"]

    def __init__(self, a: list, default: int, op):
        import math
        real_size = len(a)
        self.elem_size = elem_size = 1 << math.ceil(math.log(real_size, 2))
        self.tree = tree = [default] * (elem_size * 2)
        tree[elem_size:elem_size+real_size] = a
        self.default = default
        self.op = op

        for i in range(elem_size - 1, 0, -1):
            tree[i] = op(tree[i << 1], tree[(i << 1)+1])

    def get_value(self, x: int, y: int) -> int:
        l, r = x + self.elem_size, y + self.elem_size
        tree, result, op = self.tree, self.default, self.op
        while l < r:
            if l & 1:
                result = op(tree[l], result)
                l += 1
            if r & 1:
                r -= 1
                result = op(tree[r], result)
            l, r = l >> 1, r >> 1

        return result

    def set_value(self, i: int, value: int) -> None:
        k = self.elem_size + i
        self.tree[k] = value
        self.update(k)

    def update(self, i: int) -> None:
        op, tree = self.op, self.tree
        while i > 1:
            i >>= 1
            tree[i] = op(tree[i << 1], tree[(i << 1) + 1])

def __starting_point():
    from collections import defaultdict
    N = int(input())
    a = list(map(int, input().split()))
    index_dict = defaultdict(list)
    for i, n in enumerate(a):
        index_dict[n].append(i)

    last_num = 0
    ans = []
    append = ans.append
    segtree = SegmentTree([10**6]*(N+1), 10**6, min)
    getv, setv = segtree.get_value, segtree.set_value

    for i, n in enumerate(a):
        if not index_dict[n]:
            continue
        last_num = min(last_num+1, getv(i+1, N+1))
        for j in index_dict[n]:
            setv(j, last_num)
        append(last_num)
        index_dict[n] = []

    mod = 998244353

    ans = pow(2, len(set(ans))-1, mod)
    print(ans)
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1102/F:
You are given a matrix $a$, consisting of $n$ rows and $m$ columns. Each cell contains an integer in it.

You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: firstly visit all cells of the first column from the top row to the bottom one, then the same for the second column and so on. During the traversal you write down the sequence of the numbers on the cells in the same order you visited them. Let that sequence be $s_1, s_2, \dots, s_{nm}$.

The traversal is $k$-acceptable if for all $i$ ($1 \le i \le nm - 1$) $|s_i - s_{i + 1}| \ge k$.

Find the maximum integer $k$ such that there exists some order of rows of matrix $a$ that it produces a $k$-acceptable traversal.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 16$, $1 \le m \le 10^4$, $2 \le nm$) — the number of rows and the number of columns, respectively.

Each of the next $n$ lines contains $m$ integers ($1 \le a_{i, j} \le 10^9$) — the description of the matrix.

-----Output-----

Print a single integer $k$ — the maximum number such that there exists some order of rows of matrix $a$ that it produces an $k$-acceptable traversal.

-----Examples-----
Input
4 2
9 9
10 8
5 3
4 3

Output
5

Input
2 4
1 2 3 4
10 3 7 3

Output
0

Input
6 1
3
6
2
5
1
4

Output
3

-----Note-----

In the first example you can rearrange rows as following to get the $5$-acceptable traversal:

5 3

10 8

4 3

9 9

Then the sequence $s$ will be $[5, 10, 4, 9, 3, 8, 3, 9]$. Each pair of neighbouring elements have at least $k = 5$ difference between them.

In the second example the maximum $k = 0$, any order is $0$-acceptable.

In the third example the given order is already $3$-acceptable, you can leave it as it is.

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

import sys
import copy

input = sys.stdin.readline

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

#n=15
#m=10000
#MAT=[list(range(j*j,j*j*(m+1),j*j)) for j in range(1,n+1)]

if n==1:
    ANS=10**10
    for i in range(1,m):
        if ANS>abs(MAT[0][i]-MAT[0][i-1]):
            ANS=abs(MAT[0][i]-MAT[0][i-1])
    print(ANS)
    return

EDGE0=[[10**10]*n for i in range(n)]#iが0行目,jが最終行
EDGE1=[[10**10]*n for i in range(n)]
MAX=0
MIN=0

if m!=1:
    for i in range(n):
        for j in range(n):

            EDGE1[i][j]=EDGE1[j][i]=min([abs(MAT[i][k]-MAT[j][k]) for k in range(m)])

            if EDGE1[i][j]>MAX:
                MAX=EDGE1[i][j]

            EDGE0[i][j]=min([abs(MAT[i][k]-MAT[j][k-1]) for k in range(1,m)])
else:
    for i in range(n):
        for j in range(n):

            EDGE1[i][j]=EDGE1[j][i]=min([abs(MAT[i][k]-MAT[j][k]) for k in range(m)])

            if EDGE1[i][j]>MAX:
                MAX=EDGE1[i][j]

def Hamilton(start,USED,rest,last,weight):
    #print(start,USED,rest,last,weight,last*(1<<n)+USED)
    if MEMO[last*(1<<n)+USED]!=2:
        return MEMO[last*(1<<n)+USED]
    if rest==1:
        for i in range(n):
            if USED & (1<<i)==0:
                final=i
                break

        if EDGE0[start][final]>=weight and EDGE1[last][final]>=weight:
            #print(start,USED,rest,last,weight)

            MEMO[last*(1<<n)+USED]=1
            return 1
        else:
            #print(start,USED,weight,"!")
            MEMO[last*(1<<n)+USED]=0
            return 0

    for j in range(n):
        if USED & (1<<j)==0 and EDGE1[last][j]>=weight:

            NEXT=USED+(1<<j)
            if Hamilton(start,NEXT,rest-1,j,weight)==1:
                #print(start,USED,rest,last,weight)
                MEMO[last*(1<<n)+USED]=1
                return 1
    else:
        #print(start,USED,weight,"?")
        MEMO[last*(1<<n)+USED]=0
        return 0

while MAX!=MIN:
   ...


I found an interesting problem on https://codeforces.com/problemset/problem/1104/A:
Vasya has his favourite number $n$. He wants to split it to some non-zero digits. It means, that he wants to choose some digits $d_1, d_2, \ldots, d_k$, such that $1 \leq d_i \leq 9$ for all $i$ and $d_1 + d_2 + \ldots + d_k = n$.

Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different digits among $d_1, d_2, \ldots, d_k$. Help him!

-----Input-----

The first line contains a single integer $n$ — the number that Vasya wants to split ($1 \leq n \leq 1000$).

-----Output-----

In the first line print one integer $k$ — the number of digits in the partition. Note that $k$ must satisfy the inequality $1 \leq k \leq n$. In the next line print $k$ digits $d_1, d_2, \ldots, d_k$ separated by spaces. All digits must satisfy the inequalities $1 \leq d_i \leq 9$.

You should find a partition of $n$ in which the number of different digits among $d_1, d_2, \ldots, d_k$ will be minimal possible among all partitions of $n$ into non-zero digits. Among such partitions, it is allowed to find any. It is guaranteed that there exists at least one partition of the number $n$ into digits.

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

Output
1
1
Input
4

Output
2
2 2

Input
27

Output
3
9 9 9

-----Note-----

In the first test, the number $1$ can be divided into $1$ digit equal to $1$.

In the second test, there are $3$ partitions of the number $4$ into digits in which the number of different digits is $1$. This partitions are $[1, 1, 1, 1]$, $[2, 2]$ and $[4]$. Any of these partitions can be found. And, for example, dividing the number $4$ to the digits $[1, 1, 2]$ isn't an answer, because it has $2$ different digits, that isn't the minimum possible number.

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

n = int(input())
print(n)
for i in range(n):
	print(1, end = ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/1104/B:
Two people are playing a game with a string $s$, consisting of lowercase latin letters.

On a player's turn, he should choose two consecutive equal letters in the string and delete them.

For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses.

Your task is to determine which player will win if both play optimally.

-----Input-----

The only line contains the string $s$, consisting of lowercase latin letters ($1 \leq |s| \leq 100\,000$), where $|s|$ means the length of a string $s$.

-----Output-----

If the first player wins, print "Yes". If the second player wins, print "No".

-----Examples-----
Input
abacaba

Output
No

Input
iiq

Output
Yes

Input
abba

Output
No

-----Note-----

In the first example the first player is unable to make a turn, so he loses.

In the second example first player turns the string into "q", then second player is unable to move, so he loses.

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

s = '^'+input()+'$'
n = len(s)
N = [*list(range(1,n+1))]
P = [*list(range(-1,n-1))]

count = 0

i = 0
while N[i] != n:
    if s[i] == s[N[i]]:
        P[N[N[i]]] = P[i]
        N[P[i]] = N[N[i]]
        i = P[i]
        count += 1
    else:
        i = N[i]

print('Yes' if count%2 else 'No')

#print(count)
#i = 0
#while i != n:
#    print(s[i], end='')
#    i = N[i]
#print()


I found an interesting problem on https://codeforces.com/problemset/problem/1105/A:
Salem gave you $n$ sticks with integer positive lengths $a_1, a_2, \ldots, a_n$.

For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from $a$ to $b$ is $|a - b|$, where $|x|$ means the absolute value of $x$.

A stick length $a_i$ is called almost good for some integer $t$ if $|a_i - t| \le 1$.

Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer $t$ and the total cost of changing is minimum possible. The value of $t$ is not fixed in advance and you can choose it as any positive integer.

As an answer, print the value of $t$ and the minimum cost. If there are multiple optimal choices for $t$, print any of them.

-----Input-----

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

The second line contains $n$ integers $a_i$ ($1 \le a_i \le 100$) — the lengths of the sticks.

-----Output-----

Print the value of $t$ and the minimum possible cost. If there are multiple optimal choices for $t$, print any of them.

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

Output
3 7

Input
5
1 1 2 2 3

Output
2 0

-----Note-----

In the first example, we can change $1$ into $2$ and $10$ into $4$ with cost $|1 - 2| + |10 - 4| = 1 + 6 = 7$ and the resulting lengths $[2, 4, 4]$ are almost good for $t = 3$.

In the second example, the sticks lengths are already almost good for $t = 2$, so we don't have to do anything.

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

n = int(input())
arr = [int(x) for x in input().split()]
t = []
for i in range(101):
    s = 0
    for j in arr:
        s += max(0, abs(j - i) - 1)
    t.append(s)
p = t[1:].index(min(t)) + 1
print(p, min(t))


I found an interesting problem on https://codeforces.com/problemset/problem/1105/B:
Given a string $s$ of length $n$ and integer $k$ ($1 \le k \le n$). The string $s$ has a level $x$, if $x$ is largest non-negative integer, such that it's possible to find in $s$:  $x$ non-intersecting (non-overlapping) substrings of length $k$,  all characters of these $x$ substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings).

A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers $i$ and $j$ ($1 \le i \le j \le n$), denoted as $s[i \dots j]$ = "$s_{i}s_{i+1} \dots s_{j}$".

For example, if $k = 2$, then:  the string "aabb" has level $1$ (you can select substring "aa"),  the strings "zzzz" and "zzbzz" has level $2$ (you can select two non-intersecting substrings "zz" in each of them),  the strings "abed" and "aca" have level $0$ (you can't find at least one substring of the length $k=2$ containing the only distinct character).

Zuhair gave you the integer $k$ and the string $s$ of length $n$. You need to find $x$, the level of the string $s$.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the length of the string and the value of $k$.

The second line contains the string $s$ of length $n$ consisting only of lowercase Latin letters.

-----Output-----

Print a single integer $x$ — the level of the string.

-----Examples-----
Input
8 2
aaacaabb

Output
2

Input
2 1
ab

Output
1

Input
4 2
abab

Output
0

-----Note-----

In the first example, we can select $2$ non-intersecting substrings consisting of letter 'a': "(aa)ac(aa)bb", so the level is $2$.

In the second example, we can select either substring "a" or "b" to get the answer $1$.

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

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

anslevel = 0

for c in range(ord('a'), ord('z') + 1):
    ch = chr(c)
    nowLen, level = 0, 0
    for i in s:
        if i == ch:
            nowLen += 1
            if nowLen == k:
                nowLen = 0
                level += 1
        else:
            nowLen = 0
    anslevel = max(anslevel, level)

print(anslevel)


I found an interesting problem on https://codeforces.com/problemset/problem/1105/C:
Ayoub had an array $a$ of integers of size $n$ and this array had two interesting properties:   All the integers in the array were between $l$ and $r$ (inclusive).  The sum of all the elements was divisible by $3$.

Unfortunately, Ayoub has lost his array, but he remembers the size of the array $n$ and the numbers $l$ and $r$, so he asked you to find the number of ways to restore the array.

Since the answer could be very large, print it modulo $10^9 + 7$ (i.e. the remainder when dividing by $10^9 + 7$). In case there are no satisfying arrays (Ayoub has a wrong memory), print $0$.

-----Input-----

The first and only line contains three integers $n$, $l$ and $r$ ($1 \le n \le 2 \cdot 10^5 , 1 \le l \le r \le 10^9$) — the size of the lost array and the range of numbers in the array.

-----Output-----

Print the remainder when dividing by $10^9 + 7$ the number of ways to restore the array.

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

Output
3

Input
3 2 2

Output
1

Input
9 9 99

Output
711426616

-----Note-----

In the first example, the possible arrays are : $[1,2], [2,1], [3, 3]$.

In the second example, the only possible array is $[2, 2, 2]$.

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


I found an interesting problem on https://codeforces.com/problemset/problem/1105/D:
Kilani is playing a game with his friends. This game can be represented as a grid of size $n \times m$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).

The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $i$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $s_i$ (where $s_i$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that.

The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.

-----Input-----

The first line contains three integers $n$, $m$ and $p$ ($1 \le n, m \le 1000$, $1 \le p \le 9$) — the size of the grid and the number of players.

The second line contains $p$ integers $s_i$ ($1 \le s \le 10^9$) — the speed of the expansion for every player.

The following $n$ lines describe the game grid. Each of them consists of $m$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $x$ ($1 \le x \le p$) denotes the castle owned by player $x$.

It is guaranteed, that each player has at least one castle on the grid.

-----Output-----

Print $p$ integers — the number of cells controlled by each player after the game ends.

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

Output
6 3

Input
3 4 4
1 1 1 1
....
#...
1234

Output
1 4 3 3

-----Note-----

The picture below show the game before it started,...

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

n, m, p=map(int, input().split())
s=list(map(int, input().split()))
a=[]
front=[set() for i in range(p)]
for i in range(n):
    a.append([(int(0) if ch=='.' else (-1 if ch=='#' else (int(ch) if not front[int(ch)-1].add( (i, j) ) else -99 ))) for j, ch in enumerate(input())])

move=[(-1, 0), (1, 0), (0, -1), (0, 1)]
i=0
blocked=[False]*p
activeplayers=p

i=0
while activeplayers>0:
    if blocked[i]:
        i=(i+1)%p
        continue
    aset=front[i]
    mademove=False
    for gtime in range(s[i]):
        newset=set()
        for x,y in aset:
            for dx, dy in move:
                if 0<=x+dx<n and 0<=y+dy<m:
                    if a[x+dx][y+dy]==0:
                        newset.add( (x+dx, y+dy) )
                        a[x+dx][y+dy]=(i+1)
                        mademove=True
        aset=newset
        if len(aset)==0:
            mademove=False
            break
    front[i]=aset
    if not mademove:
        blocked[i]=True
        activeplayers=activeplayers-1
    i=(i+1)%p

res=[0]*p

for i in range(n):
    for j in range(m):
        if a[i][j]>0:
            res[int(a[i][j])-1]=res[int(a[i][j])-1]+1

for i in range(p):
    print(res[i], end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/1105/E:
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.

Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types:

  $1$ — Hiasat can change his handle.  $2$ $s$ — friend $s$ visits Hiasat's profile.

The friend $s$ will be happy, if each time he visits Hiasat's profile his handle would be $s$.

Hiasat asks you to help him, find the maximum possible number of happy friends he can get.

-----Input-----

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

Then $n$ lines follow, each denoting an event of one of two types:   $1$ — Hiasat can change his handle.  $2$ $s$ — friend $s$ ($1 \le |s| \le 40$) visits Hiasat's profile.

It's guaranteed, that each friend's name consists only of lowercase Latin letters.

It's guaranteed, that the first event is always of the first type and each friend will visit Hiasat's profile at least once.

-----Output-----

Print a single integer — the maximum number of happy friends.

-----Examples-----
Input
5 3
1
2 motarack
2 mike
1
2 light

Output
2

Input
4 3
1
2 alice
2 bob
2 tanyaromanova

Output
1

-----Note-----

In the first example, the best way is to change the handle to the "motarack" in the first event and to the "light" in the fourth event. This way, "motarack" and "light" will be happy, but "mike" will not.

In the second example, you can choose either "alice", "bob" or "tanyaromanova" and only that friend will be happy.

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

import time

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

names={None:0}

count={i:0 for i in range(1, m+1)}

a=[0]*(n+1)

for i in range(n):
    l=list(input().split())
    if l[0]=='2':
        if l[1] not in names:
            names[l[1]]=len(names)
        a[i]=names[l[1]]
        count[a[i]]=count[a[i]]+1
    # else a[i] stays 0

dense=[set() for _ in range(m+1)]

bulk=set()

# filling dense array of arrays
for i in range(n):
    if a[i]==0:
        bulk.clear()
        continue
    if a[i] in bulk: continue
    for j in bulk:
        dense[j].add(a[i])
        dense[a[i]].add(j)
    bulk.add(a[i])

res=0
happy=set()
unhappy=set()
mindep=99

independent=set()
dependent=set()
for i in range(1, m+1):
    if len(dense[i])==0: independent.add(i)
    else:
        dependent.add(i)
        if len(dense[i])<mindep:
            mindep=len(dense[i])

# print([i for i in dependent if mindep==len(dense[i])])

for k in list(dependent):
    # iterate to... too sly
    happy.clear()
    unhappy.clear()
    bulk.clear()
    bulk.update(dependent)
    happy.add(k)
    bulk.remove(k)
    for j in dense[k]:
        if j in bulk:
            unhappy.add(j)
            bulk.remove(j)

    # now making least connected happy
    while bulk:
        mini = min([len(dense[i]) for i in bulk])
        for i in list(bulk):
            if len(dense[i])==mini and (i in bulk):
                happy.add(i)
                bulk.remove(i)
                for j in dense[i]:
                    if j in bulk:
                        unhappy.add(j)
                        bulk.remove(j)
                continue

    res=max(res,len(happy))

print(res+len(independent))


I found an interesting problem on https://codeforces.com/problemset/problem/1106/A:
Lunar New Year is approaching, and you bought a matrix with lots of "crosses".

This matrix $M$ of size $n \times n$ contains only 'X' and '.' (without quotes). The element in the $i$-th row and the $j$-th column $(i, j)$ is defined as $M(i, j)$, where $1 \leq i, j \leq n$. We define a cross appearing in the $i$-th row and the $j$-th column ($1 < i, j < n$) if and only if $M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = $ 'X'.

The following figure illustrates a cross appearing at position $(2, 2)$ in a $3 \times 3$ matrix.

X.X

.X.

X.X

Your task is to find out the number of crosses in the given matrix $M$. Two crosses are different if and only if they appear in different rows or columns.

-----Input-----

The first line contains only one positive integer $n$ ($1 \leq n \leq 500$), denoting the size of the matrix $M$.

The following $n$ lines illustrate the matrix $M$. Each line contains exactly $n$ characters, each of them is 'X' or '.'. The $j$-th element in the $i$-th line represents $M(i, j)$, where $1 \leq i, j \leq n$.

-----Output-----

Output a single line containing only one integer number $k$ — the number of crosses in the given matrix $M$.

-----Examples-----
Input
5
.....
.XXX.
.XXX.
.XXX.
.....

Output
1

Input
2
XX
XX

Output
0

Input
6
......
X.X.X.
.X.X.X
X.X.X.
.X.X.X
......

Output
4

-----Note-----

In the first sample, a cross appears at $(3, 3)$, so the answer is $1$.

In the second sample, no crosses appear since $n < 3$, so the answer is $0$.

In the third sample, crosses appear at $(3, 2)$, $(3, 4)$, $(4, 3)$, $(4, 5)$, so the answer is $4$.

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

m = int(input())
l = []
for i in range(m):
    l.append(list(input()))

ans = 0
for i in range(1, m - 1):
    for k in range(1, m - 1):
        if l[i][k] == 'X' and l[i - 1][k - 1] == 'X' and l[i - 1][k + 1] == 'X' and l[i + 1][k - 1] == 'X' and l[i + 1][k + 1] == 'X':
            ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1106/B:
Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's".

The restaurant "Alice's" serves $n$ kinds of food. The cost for the $i$-th kind is always $c_i$. Initially, the restaurant has enough ingredients for serving exactly $a_i$ dishes of the $i$-th kind. In the New Year's Eve, $m$ customers will visit Alice's one after another and the $j$-th customer will order $d_j$ dishes of the $t_j$-th kind of food. The $(i + 1)$-st customer will only come after the $i$-th customer is completely served.

Suppose there are $r_i$ dishes of the $i$-th kind remaining (initially $r_i = a_i$). When a customer orders $1$ dish of the $i$-th kind, the following principles will be processed. If $r_i > 0$, the customer will be served exactly $1$ dish of the $i$-th kind. The cost for the dish is $c_i$. Meanwhile, $r_i$ will be reduced by $1$. Otherwise, the customer will be served $1$ dish of the cheapest available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by $1$. If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is $0$.

If the customer doesn't leave after the $d_j$ dishes are served, the cost for the customer will be the sum of the cost for these $d_j$ dishes.

Please determine the total cost for each of the $m$ customers.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \leq n, m \leq 10^5$), representing the number of different kinds of food and the number of customers, respectively.

The second line contains $n$ positive integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^7$), where $a_i$ denotes the initial remain of the $i$-th kind of dishes.

The third line contains $n$ positive integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 10^6$), where $c_i$ denotes...

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

import sys
#sys.setrecursionlimit(200000)
input = sys.stdin.readline
n,m = map(int,input().split())
a = list(map(int,input().split()))
c = list(map(int,input().split()))
z = list(range(n))
d = []
for i,j,k in zip(a,c,z):
        d.append([j,i,k])
d.sort(key=lambda x : -x[0])
for i in range(m):
        x,y = map(int,input().split())
        x-=1
        ans = 0
        if a[x]:
                if a[x] >= y:
                        print(c[x]*y)
                        a[x] -= y
                        continue
                else:
                        ans += a[x]*c[x]
                        y -= a[x]
                        a[x] = 0
        while d and y>0:
                q,w,e = d.pop()
                w = a[e]
                if w >= y:
                        ans += q*y
                        a[e] = w-y
                        y = 0
                        d.append([q,w-y,e])
                else:
                        ans += w*q
                        a[e] = 0
                        y-= w
        if y:
                print(0)
        else:
                print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1106/C:
Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.

There are $n$ positive integers $a_1, a_2, \ldots, a_n$ on Bob's homework paper, where $n$ is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least $2$ numbers. Suppose the numbers are divided into $m$ groups, and the sum of the numbers in the $j$-th group is $s_j$. Bob's aim is to minimize the sum of the square of $s_j$, that is $$\sum_{j = 1}^{m} s_j^2.$$

Bob is puzzled by this hard problem. Could you please help him solve it?

-----Input-----

The first line contains an even integer $n$ ($2 \leq n \leq 3 \cdot 10^5$), denoting that there are $n$ integers on Bob's homework paper.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^4$), describing the numbers you need to deal with.

-----Output-----

A single line containing one integer, denoting the minimum of the sum of the square of $s_j$, which is $$\sum_{i = j}^{m} s_j^2,$$ where $m$ is the number of groups.

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

Output
164

Input
6
1 1 1 2 2 2

Output
27

-----Note-----

In the first sample, one of the optimal solutions is to divide those $4$ numbers into $2$ groups $\{2, 8\}, \{5, 3\}$. Thus the answer is $(2 + 8)^2 + (5 + 3)^2 = 164$.

In the second sample, one of the optimal solutions is to divide those $6$ numbers into $3$ groups $\{1, 2\}, \{1, 2\}, \{1, 2\}$. Thus the answer is $(1 + 2)^2 + (1 + 2)^2 + (1 + 2)^2 = 27$.

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

n = int(input())
a = [int(x) for x in input().split()]
a.sort()
print(sum((x + y)**2 for x, y in zip(a[:n//2], a[:(n//2)-1:-1])))


I found an interesting problem on https://codeforces.com/problemset/problem/1106/D:
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.

The park can be represented as a connected graph with $n$ nodes and $m$ bidirectional edges. Initially Bob is at the node $1$ and he records $1$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $a_1, a_2, \ldots, a_n$ is recorded.

Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.

A sequence $x$ is lexicographically smaller than a sequence $y$ if and only if one of the following holds:   $x$ is a prefix of $y$, but $x \ne y$ (this is impossible in this problem as all considered sequences have the same length);  in the first position where $x$ and $y$ differ, the sequence $x$ has a smaller element than the corresponding element in $y$.

-----Input-----

The first line contains two positive integers $n$ and $m$ ($1 \leq n, m \leq 10^5$), denoting the number of nodes and edges, respectively.

The following $m$ lines describe the bidirectional edges in the graph. The $i$-th of these lines contains two integers $u_i$ and $v_i$ ($1 \leq u_i, v_i \leq n$), representing the nodes the $i$-th edge connects.

Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.

-----Output-----

Output a line containing the lexicographically smallest sequence $a_1, a_2, \ldots, a_n$ Bob can record.

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

Output
1 2 3

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

Output
1 4 3 2 5

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

Output
1 4 3 7 9 8 6 5 2 10

-----Note-----

In the first sample, Bob's optimal wandering path could be $1 \rightarrow 2...

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

from collections import defaultdict, deque
from bisect import insort
n, m = map(int, input().split())
d = defaultdict(list)
visited = [False]*(n+1)
for _ in range(m):
    u, v = map(int, input().split())
    insort(d[u], v)
    insort(d[v], u)
z = deque([1])
visited[1] = True
while z:
    front = z.popleft()
    print(front, end = ' ')
    for i in d[front]:
        if not visited[i]:
            insort(z, i)
            visited[i] = True


I found an interesting problem on https://codeforces.com/problemset/problem/1107/A:
You are given a sequence $s$ consisting of $n$ digits from $1$ to $9$.

You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.

More formally: if the resulting division of the sequence is $t_1, t_2, \dots, t_k$, where $k$ is the number of element in a division, then for each $i$ from $1$ to $k-1$ the condition $t_{i} < t_{i + 1}$ (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.

For example, if $s=654$ then you can divide it into parts $[6, 54]$ and it will be suitable division. But if you will divide it into parts $[65, 4]$ then it will be bad division because $65 > 4$. If $s=123$ then you can divide it into parts $[1, 23]$, $[1, 2, 3]$ but not into parts $[12, 3]$.

Your task is to find any suitable division for each of the $q$ independent queries.

-----Input-----

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

The first line of the $i$-th query contains one integer number $n_i$ ($2 \le n_i \le 300$) — the number of digits in the $i$-th query.

The second line of the $i$-th query contains one string $s_i$ of length $n_i$ consisting only of digits from $1$ to $9$.

-----Output-----

If the sequence of digits in the $i$-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line "NO" for this query.

Otherwise in the first line of the answer to this query print "YES", on the second line print $k_i$ — the number of parts in your division of the $i$-th query sequence and in the third line print $k_i$ strings $t_{i, 1}, t_{i, 2}, \dots, t_{i, k_i}$ — your division. Parts should be...

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

from sys import stdin
cases=int(stdin.readline().strip())
for i in range(cases):
    n=int(stdin.readline().strip())
    s=stdin.readline().strip()
    if n>2 or s[0]<s[1]:
        print("YES")
        print(2)
        print(s[0],s[1::])
    else:
        print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1107/B:
Today at the lesson of mathematics, Petya learns about the digital root.

The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.

Let's denote the digital root of $x$ as $S(x)$. Then $S(5)=5$, $S(38)=S(3+8=11)=S(1+1=2)=2$, $S(10)=S(1+0=1)=1$.

As a homework Petya got $n$ tasks of the form: find $k$-th positive number whose digital root is $x$.

Petya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all $n$ tasks from Petya's homework.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^3$) — the number of tasks in Petya's homework. The next $n$ lines contain two integers $k_i$ ($1 \le k_i \le 10^{12}$) and $x_i$ ($1 \le x_i \le 9$) — $i$-th Petya's task in which you need to find a $k_i$-th positive number, the digital root of which is $x_i$.

-----Output-----

Output $n$ lines, $i$-th line should contain a single integer — the answer to the $i$-th problem.

-----Example-----
Input
3
1 5
5 2
3 1

Output
5
38
19

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

for _ in[0]*int(input()):
 k,x=list(map(int,input().split()))
 print(x+(k-1)*9)


I found an interesting problem on https://codeforces.com/problemset/problem/1107/C:
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.

You are playing the game on the new generation console so your gamepad have $26$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.

You are given a sequence of hits, the $i$-th hit deals $a_i$ units of damage to the opponent's character. To perform the $i$-th hit you have to press the button $s_i$ on your gamepad. Hits are numbered from $1$ to $n$.

You know that if you press some button more than $k$ times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.

To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of $a_i$ over all $i$ for the hits which weren't skipped.

Note that if you skip the hit then the counter of consecutive presses the button won't reset.

Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the number of hits and the maximum number of times you can push the same button in a row.

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

The third line of the input contains the string $s$ consisting of exactly $n$ lowercase Latin letters — the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).

-----Output-----

Print one integer $dmg$ — the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.

-----Examples-----
Input
7 3
1 5 16 18 7 2 10
baaaaca

Output
54

Input
5 5
2 4 1 3...

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

n,k=map(int,input().split())
a=list(map(int,input().split()))
s=input()
b=[[s[i],a[i]] for i in range(n)]
ans=0
temp=[]
c=b[0][0]
for i in b:
    if i[0]!=c:
        c=i[0]
        temp.sort(reverse=True)
        ans+=(sum(temp[:min(len(temp),k)]))
        temp.clear()
    if i[0]==c:
        temp.append(i[1])
temp.sort(reverse=True)
ans+=(sum(temp[:min(len(temp),k)]))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1107/D:
You are given a binary matrix $A$ of size $n \times n$. Let's denote an $x$-compression of the given matrix as a matrix $B$ of size $\frac{n}{x} \times \frac{n}{x}$ such that for every $i \in [1, n], j \in [1, n]$ the condition $A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil]$ is met.

Obviously, $x$-compression is possible only if $x$ divides $n$, but this condition is not enough. For example, the following matrix of size $2 \times 2$ does not have any $2$-compression:

 $01$   $10$

For the given matrix $A$, find maximum $x$ such that an $x$-compression of this matrix is possible.

Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.

-----Input-----

The first line contains one number $n$ ($4 \le n \le 5200$) — the number of rows and columns in the matrix $A$. It is guaranteed that $n$ is divisible by $4$.

Then the representation of matrix follows. Each of $n$ next lines contains $\frac{n}{4}$ one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from $0$ to $9$ or as uppercase Latin letters from $A$ to $F$). Binary representation of each of these numbers denotes next $4$ elements of the matrix in the corresponding row. For example, if the number $B$ is given, then the corresponding elements are 1011, and if the number is $5$, then the corresponding elements are 0101.

Elements are not separated by whitespaces.

-----Output-----

Print one number: maximum $x$ such that an $x$-compression of the given matrix is possible.

-----Examples-----
Input
8
E7
E7
E7
00
00
E7
E7
E7

Output
1

Input
4
7
F
F
F

Output
1

-----Note-----

The first example corresponds to the matrix:  $11100111$   $11100111$   $11100111$   $00000000$   $00000000$   $11100111$   $11100111$   $11100111$

It is easy to see that the answer on this example is $1$.

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

import sys
from math import gcd

n = int(sys.stdin.readline())
matrix = [[] for _ in range(n)]
for i in range(n):
	matrix[i] = bin((1<<n) | int(sys.stdin.readline(), 16))[3:]

ans = 0
i = 0

while(i<n):
	j = i+1
	while(j<n and matrix[i]==matrix[j]): #Recorro por filas
		j+=1
	ans = gcd(ans,j-i)

	col = 0
	while(col<n):
		l = col + 1
		while(l<n and matrix[i][col]==matrix[i][l]): #Recorro por columnas
			l+=1
		ans = gcd(ans, col-l)
		col = l
	i = j

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1107/E:
Vasya has a string $s$ of length $n$ consisting only of digits 0 and 1. Also he has an array $a$ of length $n$.

Vasya performs the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue together the remaining parts (any of them can be empty). For example, if he erases substring 111 from string 111110 he will get the string 110. Vasya gets $a_x$ points for erasing substring of length $x$.

Vasya wants to maximize his total points, so help him with this!

-----Input-----

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

The second line contains string $s$, consisting only of digits 0 and 1.

The third line contains $n$ integers $a_1, a_2, \dots a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the number of points for erasing the substring of length $i$.

-----Output-----

Print one integer — the maximum total points Vasya can get.

-----Examples-----
Input
7
1101001
3 4 9 100 1 2 3

Output
109

Input
5
10101
3 10 15 15 15

Output
23

-----Note-----

In the first example the optimal sequence of erasings is: 1101001 $\rightarrow$ 111001 $\rightarrow$ 11101 $\rightarrow$ 1111 $\rightarrow$ $\varnothing$.

In the second example the optimal sequence of erasings is: 10101 $\rightarrow$ 1001 $\rightarrow$ 11 $\rightarrow$ $\varnothing$.

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

import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline

n = int(input())
s = input()
a = list(map(int, input().split()))
N = len(a)
dp = [[[-1] * N for i in range(N)] for j in range(N)]

def calc(l, r, k):
    if dp[l][r][k] != -1:
        return dp[l][r][k]

    if l == r:
        return a[k]

    tmp = 0
    for i in range(l, r):
        tmp = max(tmp, calc(l, i, 0) + calc(i + 1, r, k))
        if s[i] == s[r]:
            tmp = max(tmp, calc(i + 1, r - 1, 0) + calc(l, i, k + 1))

    dp[l][r][k] = tmp
    return tmp

print(calc(0, n - 1, 0))


I found an interesting problem on https://codeforces.com/problemset/problem/1107/F:
Vasya wants to buy himself a nice new car. Unfortunately, he lacks some money. Currently he has exactly 0 burles.

However, the local bank has $n$ credit offers. Each offer can be described with three numbers $a_i$, $b_i$ and $k_i$. Offers are numbered from $1$ to $n$. If Vasya takes the $i$-th offer, then the bank gives him $a_i$ burles at the beginning of the month and then Vasya pays bank $b_i$ burles at the end of each month for the next $k_i$ months (including the month he activated the offer). Vasya can take the offers any order he wants.

Each month Vasya can take no more than one credit offer. Also each credit offer can not be used more than once. Several credits can be active at the same time. It implies that Vasya pays bank the sum of $b_i$ over all the $i$ of active credits at the end of each month.

Vasya wants to buy a car in the middle of some month. He just takes all the money he currently has and buys the car of that exact price.

Vasya don't really care what he'll have to pay the bank back after he buys a car. He just goes out of the country on his car so that the bank can't find him anymore.

What is the maximum price that car can have?

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 500$) — the number of credit offers.

Each of the next $n$ lines contains three integers $a_i$, $b_i$ and $k_i$ ($1 \le a_i, b_i, k_i \le 10^9$).

-----Output-----

Print one integer — the maximum price of the car.

-----Examples-----
Input
4
10 9 2
20 33 1
30 115 1
5 3 2

Output
32

Input
3
40 1 2
1000 1100 5
300 2 1

Output
1337

-----Note-----

In the first example, the following sequence of offers taken is optimal: 4 $\rightarrow$ 3.

The amount of burles Vasya has changes the following way: 5 $\rightarrow$ 32 $\rightarrow$ -86 $\rightarrow$ .... He takes the money he has in the middle of the second month (32 burles) and buys the car.

The negative amount of money means that Vasya has to pay the bank that amount of burles.

In the second example, the following sequence of offers...

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

n = int(input())
if n == 0:
    print('0')
else:
    data = []
    ans = 0
    for i in range(n):
        line = list(map(lambda entry: int(entry), input().split()))
        x = line[0]-line[1]*line[2]
        if x > 0:
            ans += x
            line[0] -= x
        data.append((line[0], line[1]))
    data.sort(key = lambda entry: -entry[1])
    dp = [[0 for i in range(n)]]
    for j in range(n):
        x = data[j][0]
        nextline = [max(x, dp[-1][0])]
        for i in range(1, n):
            x -= data[j][1]
            nextline.append(max(x + dp[-1][i - 1], nextline[-1], dp[-1][i]))
        dp.append(nextline)
    ans += dp[n][n-1]
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1107/G:
Vasya got really tired of these credits (from problem F) and now wants to earn the money himself! He decided to make a contest to gain a profit.

Vasya has $n$ problems to choose from. They are numbered from $1$ to $n$. The difficulty of the $i$-th problem is $d_i$. Moreover, the problems are given in the increasing order by their difficulties. The difficulties of all tasks are pairwise distinct. In order to add the $i$-th problem to the contest you need to pay $c_i$ burles to its author. For each problem in the contest Vasya gets $a$ burles.

In order to create a contest he needs to choose a consecutive subsegment of tasks.

So the total earnings for the contest are calculated as follows:   if Vasya takes problem $i$ to the contest, he needs to pay $c_i$ to its author;  for each problem in the contest Vasya gets $a$ burles;  let $gap(l, r) = \max\limits_{l \le i < r} (d_{i + 1} - d_i)^2$. If Vasya takes all the tasks with indices from $l$ to $r$ to the contest, he also needs to pay $gap(l, r)$. If $l = r$ then $gap(l, r) = 0$.

Calculate the maximum profit that Vasya can earn by taking a consecutive segment of tasks.

-----Input-----

The first line contains two integers $n$ and $a$ ($1 \le n \le 3 \cdot 10^5$, $1 \le a \le 10^9$) — the number of proposed tasks and the profit for a single problem, respectively.

Each of the next $n$ lines contains two integers $d_i$ and $c_i$ ($1 \le d_i, c_i \le 10^9, d_i < d_{i+1}$).

-----Output-----

Print one integer — maximum amount of burles Vasya can earn.

-----Examples-----
Input
5 10
1 15
5 3
6 11
7 2
11 22

Output
13

Input
3 5
1 8
2 19
3 11

Output
0

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

import sys
it = iter(sys.stdin.readlines())
input = it.__next__
n, k = list(map(int, input().split()))
d, c = [0] * n, [0] * n
for i in range(n):
    a, b = list(map(int, input().split()))
    d[i], c[i] = a, k - b

p, r, pre, suf, sm, mx = list(range(n)), [0] * n, c[:], c[:], c[:], c[:]

def find(x):
    if x != p[x]:
        p[x] = find(p[x])
    return p[x]

def union(x, y, w):
    x, y = find(x), find(y)
    z = y if r[y] > r[x] else x
    r[x] += r[x] == r[y]
    mx[z] = max(mx[x], mx[y], suf[x] + pre[y])
    pre[z] = max(pre[x], sm[x] + pre[y])
    suf[z] = max(suf[x] + sm[y], suf[y])
    sm[z] = sm[x] + sm[y]
    p[x] = p[y] = z
    return mx[z] - w ** 2

ans = max(0, max(c))
for w, i in sorted((d[i + 1] - d[i], i) for i in range(n - 1)):
    ans = max(ans, union(i, i + 1, w))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1108/A:
You are given two segments $[l_1; r_1]$ and $[l_2; r_2]$ on the $x$-axis. It is guaranteed that $l_1 < r_1$ and $l_2 < r_2$. Segments may intersect, overlap or even coincide with each other. [Image] The example of two segments on the $x$-axis.

Your problem is to find two integers $a$ and $b$ such that $l_1 \le a \le r_1$, $l_2 \le b \le r_2$ and $a \ne b$. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment $[l_1; r_1]$ and the second one belongs to the segment $[l_2; r_2]$.

It is guaranteed that the answer exists. If there are multiple answers, you can print any of them.

You have to answer $q$ independent queries.

-----Input-----

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

Each of the next $q$ lines contains four integers $l_{1_i}, r_{1_i}, l_{2_i}$ and $r_{2_i}$ ($1 \le l_{1_i}, r_{1_i}, l_{2_i}, r_{2_i} \le 10^9, l_{1_i} < r_{1_i}, l_{2_i} < r_{2_i}$) — the ends of the segments in the $i$-th query.

-----Output-----

Print $2q$ integers. For the $i$-th query print two integers $a_i$ and $b_i$ — such numbers that $l_{1_i} \le a_i \le r_{1_i}$, $l_{2_i} \le b_i \le r_{2_i}$ and $a_i \ne b_i$. Queries are numbered in order of the input.

It is guaranteed that the answer exists. If there are multiple answers, you can print any.

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

Output
2 1
3 4
3 2
1 2
3 7

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

def fastio():
	import sys
	from io import StringIO
	from atexit import register
	nonlocal input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()

MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))

n, = I()
while n:
	n -= 1
	a, b, c, d = I()
	if a != c:
		print(a, c)
	elif b != d:
		print(b, d)
	elif a != d:
		print(a, d)
	else:
		print(b, c)