I found an interesting problem on https://codeforces.com/problemset/problem/1085/D:
You are given a tree (an undirected connected graph without cycles) and an integer $s$.

Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is $s$. At the same time, he wants to make the diameter of the tree as small as possible.

Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.

Find the minimum possible diameter that Vanya can get.

-----Input-----

The first line contains two integer numbers $n$ and $s$ ($2 \leq n \leq 10^5$, $1 \leq s \leq 10^9$) — the number of vertices in the tree and the sum of edge weights.

Each of the following $n−1$ lines contains two space-separated integer numbers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$) — the indexes of vertices connected by an edge. The edges are undirected.

It is guaranteed that the given edges form a tree.

-----Output-----

Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to $s$.

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

Formally, let your answer be $a$, and the jury's answer be $b$. Your answer is considered correct if $\frac {|a-b|} {max(1, b)} \leq 10^{-6}$.

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

Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6

Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5

Output
3.333333333333333333

-----Note-----

In the first example it is necessary to put weights like this: [Image]

It is easy to see that the diameter of this tree is $2$. It can be proved that it is the minimum possible diameter.

In the second example it is necessary to put weights like this: [Image]

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

n, s = list(map(int, input().split()))
a = [0 for i in range(n)]
for i in range(n-1):
    x, y = list(map(int, input().split()))
    a[x-1]+=1
    a[y-1]+=1
counter = 0
for i in a:
    if (i==1):
        counter+=1
print((2*s)/counter)


I found an interesting problem on https://codeforces.com/problemset/problem/1088/B:
You're given an array $a$. You should repeat the following operation $k$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.

-----Input-----

The first line contains integers $n$ and $k$ $(1 \le n,k \le 10^5)$, the length of the array and the number of operations you should perform.

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

-----Output-----

Print the minimum non-zero element before each operation in a new line.

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

Output
1
1
1
0
0

Input
4 2
10 3 5 3

Output
3
2

-----Note-----

In the first sample:

In the first step: the array is $[1,2,3]$, so the minimum non-zero element is 1.

In the second step: the array is $[0,1,2]$, so the minimum non-zero element is 1.

In the third step: the array is $[0,0,1]$, so the minimum non-zero element is 1.

In the fourth and fifth step: the array is $[0,0,0]$, so we printed 0.

In the second sample:

In the first step: the array is $[10,3,5,3]$, so the minimum non-zero element is 3.

In the second step: the array is $[7,0,2,0]$, so the minimum non-zero element is 2.

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

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

nums.sort()

subbed = 0
i = 0

while k > 0:
    valid = (i < n)

    if not valid:
        print(0)
        k -= 1
        continue

    num = nums[i]
    i += 1

    if num == subbed:
        continue

    tosub = num-subbed
    print(tosub)

    k -= 1
    subbed = num


I found an interesting problem on https://codeforces.com/problemset/problem/1089/F:
You are given a positive integer $n$.

Find a sequence of fractions $\frac{a_i}{b_i}$, $i = 1 \ldots k$ (where $a_i$ and $b_i$ are positive integers) for some $k$ such that:

$$ \begin{cases} \text{$b_i$ divides $n$, $1 < b_i < n$ for $i = 1 \ldots k$} \\ \text{$1 \le a_i < b_i$ for $i = 1 \ldots k$} \\ \text{$\sum\limits_{i=1}^k \frac{a_i}{b_i} = 1 - \frac{1}{n}$} \end{cases} $$

-----Input-----

The input consists of a single integer $n$ ($2 \le n \le 10^9$).

-----Output-----

In the first line print "YES" if there exists such a sequence of fractions or "NO" otherwise.

If there exists such a sequence, next lines should contain a description of the sequence in the following format.

The second line should contain integer $k$ ($1 \le k \le 100\,000$) — the number of elements in the sequence. It is guaranteed that if such a sequence exists, then there exists a sequence of length at most $100\,000$.

Next $k$ lines should contain fractions of the sequence with two integers $a_i$ and $b_i$ on each line.

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

Output
NO

Input
6

Output
YES
2
1 2
1 3

-----Note-----

In the second example there is a sequence $\frac{1}{2}, \frac{1}{3}$ such that $\frac{1}{2} + \frac{1}{3} = 1 - \frac{1}{6}$.

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

from math import sqrt

def phi(u):
	ans = u
	for i in range(2, int(sqrt(n)) + 1):
		if u % i == 0:
			while u % i == 0:
				u = u / i
			ans = ans - int(ans / i)
	if n > 1:
		ans = ans - int(ans / n)
	return ans

def binpow(u, a, mod):
	ans = 1
	if a == 0:
		return 1;
	while a > 0:
		if a % 2 == 0:
			u = (u ** 2) % mod
			a = int(a / 2)
		else :
			ans = (ans * u) % mod
			a = a - 1
	return int(ans)

n = int(input())

b1 = 1
b2 = 0
nn = n
for i in range(2, int(sqrt(n)) + 1):
	if n%i == 0 :
		while nn % i == 0:
			b1 = b1 * i
			nn = nn / i
		b2 = int(n / b1)
		break

if b2 < 2:
	print("NO")
	return
a1 = b1 - binpow(b2, phi(b1) - 1, b1)
a2 = b2 - int((a1*b2+1)/b1)
print("YES")
print(2)
print(a1, b1)
print(a2, b2)


I found an interesting problem on https://codeforces.com/problemset/problem/1089/G:
Berland State University invites people from all over the world as guest students. You can come to the capital of Berland and study with the best teachers in the country.

Berland State University works every day of the week, but classes for guest students are held on the following schedule. You know the sequence of seven integers $a_1, a_2, \dots, a_7$ ($a_i = 0$ or $a_i = 1$):  $a_1=1$ if and only if there are classes for guest students on Sundays;  $a_2=1$ if and only if there are classes for guest students on Mondays;  ...   $a_7=1$ if and only if there are classes for guest students on Saturdays.

The classes for guest students are held in at least one day of a week.

You want to visit the capital of Berland and spend the minimum number of days in it to study $k$ days as a guest student in Berland State University. Write a program to find the length of the shortest continuous period of days to stay in the capital to study exactly $k$ days as a guest student.

-----Input-----

The first line of the input contains integer $t$ ($1 \le t \le 10\,000$) — the number of test cases to process. For each test case independently solve the problem and print the answer.

Each test case consists of two lines. The first of them contains integer $k$ ($1 \le k \le 10^8$) — the required number of days to study as a guest student. The second line contains exactly seven integers $a_1, a_2, \dots, a_7$ ($a_i = 0$ or $a_i = 1$) where $a_i=1$ if and only if classes for guest students are held on the $i$-th day of a week.

-----Output-----

Print $t$ lines, the $i$-th line should contain the answer for the $i$-th test case — the length of the shortest continuous period of days you need to stay to study exactly $k$ days as a guest student.

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

Output
8
233333332
1

-----Note-----

In the first test case you must arrive to the capital of Berland on Monday, have classes on this day, spend a week until next Monday and have classes on the next...

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

from sys import stdin
for _ in range(int(stdin.readline())):
    K=int(stdin.readline())
    lst=[*map(int,stdin.readline().split())]
    ans,item=[],0
    for i,x in enumerate(lst):
        if x==1:ans.append(i);item+=1
    res=100000000000000000000000
    for i,x in enumerate(ans):
        k=K
        elem=0
        if k<=item-i:elem=ans[i+k-1]-x+1
        else:
            elem+=(7-x)
            k-=(item-i)
            elem+=((k//item)*7)
            k=k%item
            if k==0:elem-=(7-ans[-1]-1)
            else:elem+=ans[k-1]+1
        res=min(res,elem)
    print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1089/J:
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.

You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings.

Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.

Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below:  A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process.  A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive.  A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does...

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

def main():
	t = int(input())
	reserved = set(input().split())

	lines = int(input())
	code = ''
	for i in range(lines):
		code += input() + '\n'

	def is_word(suspect):
		if suspect[0].isdigit(): return False
		for x in suspect:
			if (not x.isalpha()) and (not x in {'_', '$'}) and (not x.isdigit()):
				return False
		return True

	def is_token(suspect):
		if suspect in reserved: return True
		if is_word(suspect): return True
		if suspect.isdigit(): return True
		return False

	def remove_comments(code):
		rez = ''
		state = None
		for i in range(len(code)):
			if code[i] == '#':
				state = 'comment'
			elif code[i] == '\n':
				rez += code[i]
				state = None
			else:
				if state != 'comment':
					rez += code[i]
		return rez

	code = remove_comments(code)
	code = code.replace('\n', ' ')

	def split(code):
		tokens = []
		i = 0
		while i < len(code):
			if code[i] == ' ':
				i += 1
				continue
			for l in range(min(len(code), 90), 0, -1):
				if is_token(code[i:i + l]):
					tokens.append(code[i:i + l])
					i += l
					break
			else:
				return []
		return tokens

	def minmize(tokens):
		all = []
		pref = [chr(i + ord('a')) for i in range(26)]
		all.extend(pref)
		for ext in range(3):
			cur = []
			for i in range(26):
				for p in pref:
					cur.append(p + chr(i + ord('a')))
			cur.sort()
			all.extend(cur)
			pref = cur[::]

		all.reverse()
		zip = dict()
		for i in range(len(tokens)):
			if not tokens[i] in reserved and not tokens[i][0].isdigit():
				if not zip.get(tokens[i], None):
					while all[-1] in reserved:
						all.pop()
					zip[tokens[i]] = all[-1]
					all.pop()
				tokens[i] = zip[tokens[i]]
		return tokens

	tokens = (minmize(split(code)))

	def cmp(a, b):
		if len(a) != len(b): return False
		for i in range(len(a)):
			if a[i] != b[i]: return False
		return True

	final = []
	for i in range(len(tokens)):
		p = 0
		for j in range(i - 1, -1, -1):
			if len(''.join(tokens[j:i + 1])) > 23:
				p = j
				break

		st = ''
		if i and (not cmp(tokens[p:i + 1], split(''.join(final[p:i]) +...


I found an interesting problem on https://codeforces.com/problemset/problem/1089/L:
The kingdom of Lazyland is the home to $n$ idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland.

Today $k$ important jobs for the kingdom ($k \le n$) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the $i$-th idler has chosen the job $a_i$.

Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes $b_i$ minutes to persuade the $i$-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him?

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 10^5$) — the number of idlers and the number of jobs.

The second line of the input contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le k$) — the jobs chosen by each idler.

The third line of the input contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le 10^9$) — the time the King needs to spend to persuade the $i$-th idler.

-----Output-----

The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done.

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

Output
10

Input
3 3
3 1 2
5 3 4

Output
0

-----Note-----

In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6.

In the second example each job was chosen by some idler, so there is no need to persuade anyone.

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

n_k = input().split()
n = int(n_k[0])
k = int(n_k[1])
N = input().split()
T = input().split()
Svoboda = []
if len(set(N)) == n:
    s = 0
else:
    dict47 = {}
    j = 0
    for i in N:
        if i not in dict47:
            temp = {int(i): int(T[j])}
            dict47[i] = int(T[j])
        elif dict47.get(i) < int(T[j]):
            Svoboda.append(int(dict47.get(i)))
            dict47[i] = int(T[j])
        else:
            Svoboda.append(int(T[j]))
        j += 1
j = int(len(set(N)))
s = 0
Svoboda.sort()
for i in range(0, len(Svoboda)):
    if j < k:
        s += int(Svoboda[i])
        j += 1
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1090/A:
A conglomerate consists of $n$ companies. To make managing easier, their owners have decided to merge all companies into one. By law, it is only possible to merge two companies, so the owners plan to select two companies, merge them into one, and continue doing so until there is only one company left.

But anti-monopoly service forbids to merge companies if they suspect unfriendly absorption. The criterion they use is the difference in maximum salaries between two companies. Merging is allowed only if the maximum salaries are equal.

To fulfill the anti-monopoly requirements, the owners can change salaries in their companies before merging. But the labor union insists on two conditions: it is only allowed to increase salaries, moreover all the employees in one company must get the same increase.

Sure enough, the owners want to minimize the total increase of all salaries in all companies. Help them find the minimal possible increase that will allow them to merge companies into one.

-----Input-----

The first line contains a single integer $n$ — the number of companies in the conglomerate ($1 \le n \le 2 \cdot 10^5$). Each of the next $n$ lines describes a company.

A company description start with an integer $m_i$ — the number of its employees ($1 \le m_i \le 2 \cdot 10^5$). Then $m_i$ integers follow: the salaries of the employees. All salaries are positive and do not exceed $10^9$.

The total number of employees in all companies does not exceed $2 \cdot 10^5$.

-----Output-----

Output a single integer — the minimal total increase of all employees that allows to merge all companies.

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

Output
13

-----Note-----

One of the optimal merging strategies is the following. First increase all salaries in the second company by $2$, and merge the first and the second companies. Now the conglomerate consists of two companies with salaries $[4, 3, 4, 3]$ and $[1, 1, 1]$. To merge them, increase the salaries in the second of those by $3$. The total increase is $2 +...

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

n = int(input())
a = []
m = []
e = 0
for i in range(n):
    a.append(list(map(int, input().split())))
    m.append([a[-1][0], max(a[-1][1:])])
    e = max(e, m[-1][1])
s = 0
for i in range(n):
    s += m[i][0] * (e - m[i][1])
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1090/D:
Vasya had an array of $n$ integers, each element of the array was from $1$ to $n$. He chose $m$ pairs of different positions and wrote them down to a sheet of paper. Then Vasya compared the elements at these positions, and wrote down the results of the comparisons to another sheet of paper. For each pair he wrote either "greater", "less", or "equal".

After several years, he has found the first sheet of paper, but he couldn't find the second one. Also he doesn't remember the array he had. In particular, he doesn't remember if the array had equal elements. He has told this sad story to his informatics teacher Dr Helen.

She told him that it could be the case that even if Vasya finds his second sheet, he would still not be able to find out whether the array had two equal elements.

Now Vasya wants to find two arrays of integers, each of length $n$. All elements of the first array must be distinct, and there must be two equal elements in the second array. For each pair of positions Vasya wrote at the first sheet of paper, the result of the comparison must be the same for the corresponding elements of the first array, and the corresponding elements of the second array.

Help Vasya find two such arrays of length $n$, or find out that there are no such arrays for his sets of pairs.

-----Input-----

The first line of input contains two integers $n$, $m$ — the number of elements in the array and number of comparisons made by Vasya ($1 \le n \le 100\,000$, $0 \le m \le 100\,000$).

Each of the following $m$ lines contains two integers $a_i$, $b_i$  — the positions of the $i$-th comparison ($1 \le a_i, b_i \le n$; $a_i \ne b_i$). It's guaranteed that any unordered pair is given in the input at most once.

-----Output-----

The first line of output must contain "YES" if there exist two arrays, such that the results of comparisons would be the same, and all numbers in the first one are distinct, and the second one contains two equal numbers. Otherwise it must contain "NO".

If the arrays exist, the second line must...

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

def read(type = 1):
    if type:
        file = open("input.dat", "r")
        line = list(map(int, file.readline().split()))
        n = line[0]
        m = line[1]
        a = []
        for i in range(m):
            line = tuple(map(int, file.readline().split()))
            if line[0] < line[1]:
                a.append(line)
            else:
                a.append([line[1], line[0]])
        file.close()
    else:
        line = list(map(int, input().strip().split()))
        n = line[0]
        m = line[1]
        a = []
        for i in range(m):
            line = tuple(map(int, input().strip().split()))
            if line[0] < line[1]:
                a.append(line)
            else:
                a.append([line[1], line[0]])

    return n, m, a

def write(sol, x):
    print("YES")
    print(" ".join(map(str, sol[1:-1])))
    sol[x[1]] = sol[x[0]]
    print(" ".join(map(str, sol[1:-1])))

def solve(a):
    if len(a) == n * (n-1) // 2:
        print("NO")
        return 0
    a = sorted(a, key = lambda x: (x[0], x[1]))
    x = [1,2]
    for t in a:
        if list(t) != x:
            break
        if x[1] == n:
            x[0] += 1
            x[1] = x[0] + 1
        else:
            x[1] += 1
    sol = [0 for i in range(n+2)]
    sol[x[0]] = 1
    sol[x[1]] = 2
    v = 3
    for i in range(1,n+1):
        if i not in x:
            sol[i] = v
            v += 1
    write(sol, x)

n, m, a = read(0)
solve(a)


I found an interesting problem on https://codeforces.com/problemset/problem/1090/M:
There are $n$ houses along the road where Anya lives, each one is painted in one of $k$ possible colors.

Anya likes walking along this road, but she doesn't like when two adjacent houses at the road have the same color. She wants to select a long segment of the road such that no two adjacent houses have the same color.

Help Anya find the longest segment with this property.

-----Input-----

The first line contains two integers $n$ and $k$ — the number of houses and the number of colors ($1 \le n \le 100\,000$, $1 \le k \le 100\,000$).

The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ — the colors of the houses along the road ($1 \le a_i \le k$).

-----Output-----

Output a single integer — the maximum number of houses on the road segment having no two adjacent houses of the same color.

-----Example-----
Input
8 3
1 2 3 3 2 1 2 2

Output
4

-----Note-----

In the example, the longest segment without neighboring houses of the same color is from the house 4 to the house 7. The colors of the houses are $[3, 2, 1, 2]$ and its length is 4 houses.

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

n, k = list(map(int, input().split()))
c = list(map(int, input().split()))
m = 1
z = 0
e = 0
while e < n:
    while e + 1 < n and c[e] != c[e + 1]:
        e += 1
    m = max(m, e - z + 1)
    while e + 1 < n and c[e] == c[e + 1]:
        e += 1
    z = e
    e += 1
print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/1091/A:
Alice and Bob are decorating a Christmas Tree.

Alice wants only $3$ types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have $y$ yellow ornaments, $b$ blue ornaments and $r$ red ornaments.

In Bob's opinion, a Christmas Tree will be beautiful if:  the number of blue ornaments used is greater by exactly $1$ than the number of yellow ornaments, and  the number of red ornaments used is greater by exactly $1$ than the number of blue ornaments.

That is, if they have $8$ yellow ornaments, $13$ blue ornaments and $9$ red ornaments, we can choose $4$ yellow, $5$ blue and $6$ red ornaments ($5=4+1$ and $6=5+1$).

Alice wants to choose as many ornaments as possible, but she also wants the Christmas Tree to be beautiful according to Bob's opinion.

In the example two paragraphs above, we would choose $7$ yellow, $8$ blue and $9$ red ornaments. If we do it, we will use $7+8+9=24$ ornaments. That is the maximum number.

Since Alice and Bob are busy with preparing food to the New Year's Eve, they are asking you to find out the maximum number of ornaments that can be used in their beautiful Christmas Tree!

It is guaranteed that it is possible to choose at least $6$ ($1+2+3=6$) ornaments.

-----Input-----

The only line contains three integers $y$, $b$, $r$ ($1 \leq y \leq 100$, $2 \leq b \leq 100$, $3 \leq r \leq 100$) — the number of yellow, blue and red ornaments.

It is guaranteed that it is possible to choose at least $6$ ($1+2+3=6$) ornaments.

-----Output-----

Print one number — the maximum number of ornaments that can be used.

-----Examples-----
Input
8 13 9

Output
24
Input
13 3 6

Output
9

-----Note-----

In the first example, the answer is $7+8+9=24$.

In the second example, the answer is $2+3+4=9$.

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

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

x = min(y,b-1,r-2)
print(3*x+3)


I found an interesting problem on https://codeforces.com/problemset/problem/1091/B:
Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point $T$, which coordinates to be found out.

Bob travelled around the world and collected clues of the treasure location at $n$ obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?

As everyone knows, the world is a two-dimensional plane. The $i$-th obelisk is at integer coordinates $(x_i, y_i)$. The $j$-th clue consists of $2$ integers $(a_j, b_j)$ and belongs to the obelisk $p_j$, where $p$ is some (unknown) permutation on $n$ elements. It means that the treasure is located at $T=(x_{p_j} + a_j, y_{p_j} + b_j)$. This point $T$ is the same for all clues.

In other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.

Your task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.

Note that you don't need to find the permutation. Permutations are used only in order to explain the problem.

-----Input-----

The first line contains an integer $n$ ($1 \leq n \leq 1000$) — the number of obelisks, that is also equal to the number of clues.

Each of the next $n$ lines contains two integers $x_i$, $y_i$ ($-10^6 \leq x_i, y_i \leq 10^6$) — the coordinates of the $i$-th obelisk. All coordinates are distinct, that is $x_i \neq x_j$ or $y_i \neq y_j$ will be satisfied for every $(i, j)$ such that $i \neq j$.

Each of the next $n$ lines contains two integers $a_i$, $b_i$ ($-2 \cdot 10^6 \leq a_i, b_i \leq 2 \cdot 10^6$) — the direction of the $i$-th clue. All coordinates are distinct, that is $a_i \neq a_j$ or $b_i \neq b_j$ will be satisfied for every $(i, j)$...

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

n=int(input())
sum1=0
sum2=0
for i in range(2*n):
    a,b=map(int,input().split())
    sum1+=a
    sum2+=b
print(int(sum1/n),int(sum2/n))


I found an interesting problem on https://codeforces.com/problemset/problem/1091/C:
There are $n$ people sitting in a circle, numbered from $1$ to $n$ in the order in which they are seated. That is, for all $i$ from $1$ to $n-1$, the people with id $i$ and $i+1$ are adjacent. People with id $n$ and $1$ are adjacent as well.

The person with id $1$ initially has a ball. He picks a positive integer $k$ at most $n$, and passes the ball to his $k$-th neighbour in the direction of increasing ids, that person passes the ball to his $k$-th neighbour in the same direction, and so on until the person with the id $1$ gets the ball back. When he gets it back, people do not pass the ball any more.

For instance, if $n = 6$ and $k = 4$, the ball is passed in order $[1, 5, 3, 1]$.

Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $1 + 5 + 3 = 9$.

Find and report the set of possible fun values for all choices of positive integer $k$. It can be shown that under the constraints of the problem, the ball always gets back to the $1$-st player after finitely many steps, and there are no more than $10^5$ possible fun values for given $n$.

-----Input-----

The only line consists of a single integer $n$ ($2 \leq n \leq 10^9$) — the number of people playing with the ball.

-----Output-----

Suppose the set of all fun values is $f_1, f_2, \dots, f_m$.

Output a single line containing $m$ space separated integers $f_1$ through $f_m$ in increasing order.

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

Output
1 5 9 21

Input
16

Output
1 10 28 64 136

-----Note-----

In the first sample, we've already shown that picking $k = 4$ yields fun value $9$, as does $k = 2$. Picking $k = 6$ results in fun value of $1$. For $k = 3$ we get fun value $5$ and with $k = 1$ or $k = 5$ we get $21$.  [Image]

In the second sample, the values $1$, $10$, $28$, $64$ and $136$ are achieved for instance for $k = 16$, $8$, $4$, $10$ and $11$, respectively.

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/1091/D:
Let $n$ be an integer. Consider all permutations on integers $1$ to $n$ in lexicographic order, and concatenate them into one big sequence $p$. For example, if $n = 3$, then $p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$. The length of this sequence will be $n \cdot n!$.

Let $1 \leq i \leq j \leq n \cdot n!$ be a pair of indices. We call the sequence $(p_i, p_{i+1}, \dots, p_{j-1}, p_j)$ a subarray of $p$. Its length is defined as the number of its elements, i.e., $j - i + 1$. Its sum is the sum of all its elements, i.e., $\sum_{k=i}^j p_k$.

You are given $n$. Find the number of subarrays of $p$ of length $n$ having sum $\frac{n(n+1)}{2}$. Since this number may be large, output it modulo $998244353$ (a prime number).

-----Input-----

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

-----Output-----

Output a single integer — the number of subarrays of length $n$ having sum $\frac{n(n+1)}{2}$, modulo $998244353$.

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

Output
9

Input
4

Output
56

Input
10

Output
30052700

-----Note-----

In the first sample, there are $16$ subarrays of length $3$. In order of appearance, they are:

$[1, 2, 3]$, $[2, 3, 1]$, $[3, 1, 3]$, $[1, 3, 2]$, $[3, 2, 2]$, $[2, 2, 1]$, $[2, 1, 3]$, $[1, 3, 2]$, $[3, 2, 3]$, $[2, 3, 1]$, $[3, 1, 3]$, $[1, 3, 1]$, $[3, 1, 2]$, $[1, 2, 3]$, $[2, 3, 2]$, $[3, 2, 1]$.

Their sums are $6$, $6$, $7$, $6$, $7$, $5$, $6$, $6$, $8$, $6$, $7$, $5$, $6$, $6$, $7$, $6$. As $\frac{n(n+1)}{2} = 6$, the answer is $9$.

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

t = int(input())
res = t
i = 2
while(i<=t):
    res = (res-1)*i%998244353
    i+=1
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1091/E:
Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if $a$ is a friend of $b$, then $b$ is also a friend of $a$. Each user thus has a non-negative amount of friends.

This morning, somebody anonymously sent Bob the following link: graph realization problem and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them.

-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 5 \cdot 10^5$), the number of people on the network excluding Bob.

The second line contains $n$ numbers $a_1,a_2, \dots, a_n$ ($0 \leq a_i \leq n$), with $a_i$ being the number of people that person $i$ is a friend of.

-----Output-----

Print all possible values of $a_{n+1}$ — the amount of people that Bob can be friend of, in increasing order.

If no solution exists, output $-1$.

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

Output
3

Input
4
1 1 1 1

Output
0 2 4

Input
2
0 2

Output
-1

Input
35
21 26 18 4 28 2 15 13 16 25 6 32 11 5 31 17 9 3 24 33 14 27 29 1 20 4 12 7 10 30 34 8 19 23 22

Output
13 15 17 19 21

-----Note-----

In the first test case, the only solution is that everyone is friends with everyone. That is why Bob should have $3$ friends.

In the second test case, there are three possible solutions (apart from symmetries):   $a$ is friend of $b$, $c$ is friend of $d$, and Bob has no friends, or  $a$ is a friend of $b$ and both $c$ and $d$ are friends with Bob, or  Bob is friends of everyone.

The third case is impossible to solve, as the second person needs to be a friend with everybody, but the first one is a complete stranger.

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

def main():
    n=int(input())
    a=list(map(int,input().split()))
    a.sort(reverse=True)
    mod=sum(a)%2
    counts=[0]*(n+1)
    for guy in a:
        counts[guy]+=1
    cumcounts=[0]*(n+1)
    cumcounts[0]=counts[0]
    for i in range(n):
        cumcounts[i+1]=cumcounts[i]+counts[i+1]
    partialsums=[0]*(n+1)
    curr=0
    for i in range(n):
        curr+=(i+1)*counts[i+1]
        partialsums[i+1]=curr
    partialsums.append(0)
    cumcounts.append(0)
    sumi=0
    diffs=[0]*n
    altdiffs=[0]*n
    for i in range(n):
        sumi+=a[i]
        rhs=i*(i+1)
        if a[i]>i:
            rhs+=partialsums[i]+(i+1)*(n-i-1-cumcounts[i])
        else:
            rhs+=partialsums[a[i]-1]+a[i]*(n-i-1-cumcounts[a[i]-1])
        diffs[i]=sumi-rhs

        rhs2=(i+1)*(i+2)
        if a[i]>i+1:
            rhs2+=partialsums[i+1]+(i+2)*(n-i-1-cumcounts[i+1])
        else:
            rhs2+=partialsums[a[i]-1]+a[i]*(n-i-1-cumcounts[a[i]-1])
        altdiffs[i]=sumi-rhs2
    mini=max(diffs)
    maxi=-max(altdiffs)
    mini=max(mini,0)
    maxi=min(maxi,n)
    out=""
    if mini%2!=mod:
        mini+=1
    if maxi%2==mod:
        maxi+=1
    for guy in range(mini,maxi,2):
        out+=str(guy)+" "
    if mini>maxi:
        print(-1)
    else:
        print(out)
main()


I found an interesting problem on https://codeforces.com/problemset/problem/1091/F:
Bob is a duck. He wants to get to Alice's nest, so that those two can duck! [Image] Duck is the ultimate animal! (Image courtesy of See Bang)

The journey can be represented as a straight line, consisting of $n$ segments. Bob is located to the left of the first segment, while Alice's nest is on the right of the last segment. Each segment has a length in meters, and also terrain type: grass, water or lava.

Bob has three movement types: swimming, walking and flying. He can switch between them or change his direction at any point in time (even when he is located at a non-integer coordinate), and doing so doesn't require any extra time. Bob can swim only on the water, walk only on the grass and fly over any terrain. Flying one meter takes $1$ second, swimming one meter takes $3$ seconds, and finally walking one meter takes $5$ seconds.

Bob has a finite amount of energy, called stamina. Swimming and walking is relaxing for him, so he gains $1$ stamina for every meter he walks or swims. On the other hand, flying is quite tiring, and he spends $1$ stamina for every meter flown. Staying in place does not influence his stamina at all. Of course, his stamina can never become negative. Initially, his stamina is zero.

What is the shortest possible time in which he can reach Alice's nest?

-----Input-----

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

The second line contains $n$ integers $l_1, l_2, \dots, l_n$ ($1 \leq l_i \leq 10^{12}$). The $l_i$ represents the length of the $i$-th terrain segment in meters.

The third line contains a string $s$ consisting of $n$ characters "G", "W", "L", representing Grass, Water and Lava, respectively.

It is guaranteed that the first segment is not Lava.

-----Output-----

Output a single integer $t$ — the minimum time Bob needs to reach Alice.

-----Examples-----
Input
1
10
G

Output
30

Input
2
10 10
WL

Output
40

Input
2
1 2
WL

Output
8

Input
3
10 10 10
GLW

Output
80

-----Note-----

In the first...

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

n=int(input())
l=list(map(lambda x:int(x)*2,input().split(" ")))
t=list(map(lambda x:"GWL".index(x),input()))
mins=[0 for i in range(0,n+1)]
for i in range(n-1,-1,-1):
	if t[i]!=2:mins[i]=max(mins[i+1]-l[i],0)
	else:mins[i]=mins[i+1]+l[i]
curs=ans=st=0
for i in range(0,n):
	if(t[i]==0):
		curs+=l[i];ans+=l[i]*5
		if(curs>mins[i+1]):
			ol=(curs-mins[i+1])//2
			ol=min(ol,l[i])
			ans-=4*ol;curs-=2*ol
	if(t[i]==1):
		st=1;curs+=l[i];ans+=l[i]*3
	if(t[i]==2):
		if(curs<l[i]):
			ol=l[i]-curs;curs=l[i]
			ans+=ol*(3 if st else 5)
		curs-=l[i];ans+=l[i]
if curs>0:ans-=curs//2*2
print(ans//2)


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

Your task is to construct such a string $s$ of length $n$ that for each $i$ from $1$ to $k$ there is at least one $i$-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minimal frequency of some letter (the frequency of a letter is the number of occurrences of this letter in a string). If there are several possible answers, you can print any.

You have to answer $t$ independent queries.

-----Input-----

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

The next $t$ lines are contain queries, one per line. The $i$-th line contains two integers $n_i$ and $k_i$ ($1 \le n_i \le 100, 1 \le k_i \le min(n_i, 26)$) — the length of the string in the $i$-th query and the number of characters in the $i$-th query.

-----Output-----

Print $t$ lines. In the $i$-th line print the answer to the $i$-th query: any string $s_i$ satisfying the conditions in the problem statement with constraints from the $i$-th query.

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

Output
cbcacab
abcd
baabab

-----Note-----

In the first example query the maximum possible minimal frequency is $2$, it can be easily seen that the better answer doesn't exist. Other examples of correct answers: "cbcabba", "ccbbaaa" (any permutation of given answers is also correct).

In the second example query any permutation of first four letters is acceptable (the maximum minimal frequency is $1$).

In the third example query any permutation of the given answer is acceptable (the maximum minimal frequency is $3$).

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

t=int(input())
f="abcdefghijklmnopqrstuvwxyz"
for i in range(t):
    n,k=list(map(int,input().split()))
    g=f[:k]
    s=""
    for j in range(n):
        s+=g[j%k]
    print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1092/B:
There are $n$ students in a university. The number of students is even. The $i$-th student has programming skill equal to $a_i$.

The coach wants to form $\frac{n}{2}$ teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equal (otherwise they cannot understand each other and cannot form a team).

Students can solve problems to increase their skill. One solved problem increases the skill by one.

The coach wants to know the minimum total number of problems students should solve to form exactly $\frac{n}{2}$ teams (i.e. each pair of students should form a team). Your task is to find this number.

-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 100$) — the number of students. It is guaranteed that $n$ is even.

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

-----Output-----

Print one number — the minimum total number of problems students should solve to form exactly $\frac{n}{2}$ teams.

-----Examples-----
Input
6
5 10 2 3 14 5

Output
5

Input
2
1 100

Output
99

-----Note-----

In the first example the optimal teams will be: $(3, 4)$, $(1, 6)$ and $(2, 5)$, where numbers in brackets are indices of students. Then, to form the first team the third student should solve $1$ problem, to form the second team nobody needs to solve problems and to form the third team the second student should solve $4$ problems so the answer is $1 + 4 = 5$.

In the second example the first student should solve $99$ problems to form a team with the second one.

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

n = int(input())
a = sorted([int(i) for i in input().split()])

s = 0
for i in range(0,n,2):
	s += abs(a[i+1]-a[i])

print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1092/C:
Ivan wants to play a game with you. He picked some string $s$ of length $n$ consisting only of lowercase Latin letters.

You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $1$ to $n-1$), but he didn't tell you which strings are prefixes and which are suffixes.

Ivan wants you to guess which of the given $2n-2$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!

-----Input-----

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

The next $2n-2$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $1$ to $n-1$ consisting only of lowercase Latin letters. They can be given in arbitrary order.

It is guaranteed that there are exactly $2$ strings of each length from $1$ to $n-1$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $n$.

-----Output-----

Print one string of length $2n-2$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $i$-th character of this string should be 'P' if the $i$-th of the input strings is the prefix and 'S' otherwise.

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

-----Examples-----
Input
5
ba
a
abab
a
aba
baba
ab
aba

Output
SPPSPSPS

Input
3
a
aa
aa
a

Output
PPSS

Input
2
a
c

Output
PS

-----Note-----

The only string which Ivan can guess in the first example is "ababa".

The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.

In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP"...

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/1092/D1:
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.

The current state of the wall can be respresented by a sequence $a$ of $n$ integers, with $a_i$ being the height of the $i$-th part of the wall.

Vova can only use $2 \times 1$ bricks to put in the wall (he has infinite supply of them, however).

Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some $i$ the current height of part $i$ is the same as for part $i + 1$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $1$ of the wall or to the right of part $n$ of it).

The next paragraph is specific to the version 1 of the problem.

Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.

Vova is a perfectionist, so he considers the wall completed when:

  all parts of the wall has the same height;  the wall has no empty spaces inside it.

Can Vova complete the wall using any amount of bricks (possibly zero)?

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the initial heights of the parts of the wall.

-----Output-----

Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).

Print "NO" otherwise.

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

Output
YES

Input
3
4 5 3

Output
YES

Input
2
10 10

Output
YES

Input
3
1 2 3

Output
NO

-----Note-----

In the first example Vova can put a brick on parts 2 and 3 to make the wall $[2, 2, 2, 2, 5]$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $[5, 5, 5, 5, 5]$.

In the second example Vova can put a brick vertically on...

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

n=int(input())
a=list(map(int,input().split()))
b=[0]*1000000
sp=-1

for i in range(n):
    sp=sp+1
    b[sp]=a[i]
    if sp>0:

        if ((b[sp]+b[sp-1])%2)==0:
            sp=sp-2

if sp<=0:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1092/D2:
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.

The current state of the wall can be respresented by a sequence $a$ of $n$ integers, with $a_i$ being the height of the $i$-th part of the wall.

Vova can only use $2 \times 1$ bricks to put in the wall (he has infinite supply of them, however).

Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some $i$ the current height of part $i$ is the same as for part $i + 1$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $1$ of the wall or to the right of part $n$ of it).

Note that Vova can't put bricks vertically.

Vova is a perfectionist, so he considers the wall completed when:  all parts of the wall has the same height;  the wall has no empty spaces inside it.

Can Vova complete the wall using any amount of bricks (possibly zero)?

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the initial heights of the parts of the wall.

-----Output-----

Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).

Print "NO" otherwise.

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

Output
YES

Input
3
4 5 3

Output
NO

Input
2
10 10

Output
YES

-----Note-----

In the first example Vova can put a brick on parts 2 and 3 to make the wall $[2, 2, 2, 2, 5]$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $[5, 5, 5, 5, 5]$.

In the second example Vova can put no bricks in the wall.

In the third example the wall is already complete.

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

n=int(input())
b=-1
a=input().split()
l,r=[],True
for i in a:
    tmp=int(i)
    b=max(b,tmp)
    if l==[] or l[-1]>tmp: l.append(tmp)
    elif l[-1]==tmp: l.pop()
    else: r=False;break;

print("YES" if r and (len(l)==0 or (len(l)==1 and l[0]>=b)) else "NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1092/E:
You are given a forest — an undirected graph with $n$ vertices such that each its connected component is a tree.

The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.

You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.

If there are multiple correct answers, print any of them.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 1000$, $0 \le m \le n - 1$) — the number of vertices of the graph and the number of edges, respectively.

Each of the next $m$ lines contains two integers $v$ and $u$ ($1 \le v, u \le n$, $v \ne u$) — the descriptions of the edges.

It is guaranteed that the given graph is a forest.

-----Output-----

In the first line print the diameter of the resulting tree.

Each of the next $(n - 1) - m$ lines should contain two integers $v$ and $u$ ($1 \le v, u \le n$, $v \ne u$) — the descriptions of the added edges.

The resulting graph should be a tree and its diameter should be minimal possible.

For $m = n - 1$ no edges are added, thus the output consists of a single integer — diameter of the given tree.

If there are multiple correct answers, print any of them.

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

Output
2
4 2

Input
2 0

Output
1
1 2

Input
3 2
1 3
2 3

Output
2

-----Note-----

In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.

Edge (1, 2) is the only option you have for the second example. The diameter is 1.

You can't add any edges in the third example. The diameter is already 2.

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

import sys
sys.setrecursionlimit(10000)
class Tree():
   def __init__(self, nodes):
     self.root = None

class Node():
  def __init__(self, val):
    self.parent = None
    self.val = val
    self.children = []
  def add(self, child):
    self.children.append(child)
  def get_max_dist(self, parent,dist):
     max_dist = dist
     for i in self.children:
        if i != parent:
           d = i.get_max_dist(self, dist+1)
           if max_dist < d:
              max_dist = d
     return max_dist
  def get_dist(self):
     return self.get_max_dist(self, 0)
  def get_count_ch(self, parent):
     count = len(self.children)
     for i in self.children:
        if i != parent:
           count += i.get_count_ch(self)-1
     return count
  def calc_child(self):
     return (self.get_count_ch(None),len(self.children), self.val)

class Forest():
  def __init__(self, count):
    self.nodes = []
    self.count = count
    self.set_nodes = set()
  def build(self):
    roots = []
    max_dist = []
    #diam = []
    list_root = []
    for i in self.nodes:
       tree =(list([x.get_dist() for x in i]))
       ma = max(tree)
       max_dist.append(ma)
       #diam.append(ma)
       m = i[tree.index(min(tree))]
       roots.append(m)#.val)
    if len(roots) > 1:
       ind = max_dist.index(max(max_dist))
       if len(roots) > 1 and ind != 0:
          roots[0], roots[ind] = roots[ind], roots[0]
    s = set()
    for i in self.nodes:
      for j in i:
        s.add(j.val)
    r = list(set(range(1, n+1))-s)

    if len(roots) > 0:# and len(diam) > 0:
       for i in range(1, len(roots)):
          self.add(roots[0].val, roots[i].val)
          list_root.append((roots[0].val, roots[i].val))
       #print(roots + r)

       for i in r:
         self.add(roots[0].val, i)
         list_root.append((roots[0].val, i))
    else:
       if len(r) == 1:
          print(0)
          return
       elif len(r) > 1:
          for i in range(1, len(r)):
             self.add(r[0], r[i])
             list_root.append((r[0],...


I found an interesting problem on https://codeforces.com/problemset/problem/1092/F:
You are given a tree consisting exactly of $n$ vertices. Tree is a connected undirected graph with $n-1$ edges. Each vertex $v$ of this tree has a value $a_v$ assigned to it.

Let $dist(x, y)$ be the distance between the vertices $x$ and $y$. The distance between the vertices is the number of edges on the simple path between them.

Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be $v$. Then the cost of the tree is $\sum\limits_{i = 1}^{n} dist(i, v) \cdot a_i$.

Your task is to calculate the maximum possible cost of the tree if you can choose $v$ arbitrarily.

-----Input-----

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

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

Each of the next $n - 1$ lines describes an edge of the tree. Edge $i$ is denoted by two integers $u_i$ and $v_i$, the labels of vertices it connects ($1 \le u_i, v_i \le n$, $u_i \ne v_i$).

It is guaranteed that the given edges form a tree.

-----Output-----

Print one integer — the maximum possible cost of the tree if you can choose any vertex as $v$.

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

Output
121

Input
1
1337

Output
0

-----Note-----

Picture corresponding to the first example: [Image]

You can choose the vertex $3$ as a root, then the answer will be $2 \cdot 9 + 1 \cdot 4 + 0 \cdot 1 + 3 \cdot 7 + 3 \cdot 10 + 4 \cdot 1 + 4 \cdot 6 + 4 \cdot 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121$.

In the second example tree consists only of one vertex so the answer is always $0$.

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

import traceback
import sys
sys.setrecursionlimit(200010)

try:
    # alpha = "abcdefghijklmnopqrstuvwxyz"

    n = int(input())
    a = [0]
    a.extend(list(map(int, input().split())))
    D = [[] for i in range(n+1)]
    for i in range(n-1):
        e1,e2 = (map(int, input().split()))
        D[e1].append(e2)
        D[e2].append(e1)

    # for i in range(1,n+1):
    #     if i not in D:
    #         D[i] = []

    visited = [False for i in range(n+1)]
    cost = [a[i] for i in range(n+1)]
    parent = [0 for i in range(n+1)]
    val = 0

    def dfs(s, depth):
        nonlocal visited
        nonlocal cost
        nonlocal val
        nonlocal a
        nonlocal D
        stack = [(s,depth)]
        while stack:
            s, depth = stack[-1]
            if visited[s]:
                stack.pop()
                cost[parent[s]]+=cost[s]
                continue
            else:
                visited[s] = True
                val += depth*a[s]
            for i in D[s]:
                if not visited[i]:
                    parent[i] = s
                    stack.append((i, depth+1))
                    # cost[s]+=cost[i]

    dfs(1, 0)

    # ans = 1
    max_cost = val
    # print(max_cost)
    visited = [False for i in range(n+1)]
    cost[0] = sum(a)
    def trav(s, some_val):
        nonlocal cost
        nonlocal visited
        nonlocal max_cost
        nonlocal D
        stack = [(s,some_val)]
        while stack:
            s, some_val = stack.pop()
            visited[s] = True
            # print(some_val, s)
            if some_val>max_cost:
                max_cost = some_val

            for i in D[s]:
                if not visited[i]:
                    # print(i, some_val, cost[s], cost[i])
                    stack.append((i, some_val+(cost[0]-cost[i])-cost[i] ))

    trav(1, val)
    print(max_cost)
except Exception as ex:
    traceback.print_tb(ex.__traceback__)
    print(ex)


I found an interesting problem on https://codeforces.com/problemset/problem/1093/A:
Mishka got a six-faced dice. It has integer numbers from $2$ to $7$ written on its faces (all numbers on faces are different, so this is an almost usual dice).

Mishka wants to get exactly $x$ points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls Mishka makes.

Mishka doesn't really care about the number of rolls, so he just wants to know any number of rolls he can make to be able to get exactly $x$ points for them. Mishka is very lucky, so if the probability to get $x$ points with chosen number of rolls is non-zero, he will be able to roll the dice in such a way. Your task is to print this number. It is guaranteed that at least one answer exists.

Mishka is also very curious about different number of points to score so you have to answer $t$ independent queries.

-----Input-----

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

Each of the next $t$ lines contains one integer each. The $i$-th line contains one integer $x_i$ ($2 \le x_i \le 100$) — the number of points Mishka wants to get.

-----Output-----

Print $t$ lines. In the $i$-th line print the answer to the $i$-th query (i.e. any number of rolls Mishka can make to be able to get exactly $x_i$ points for them). It is guaranteed that at least one answer exists.

-----Example-----
Input
4
2
13
37
100

Output
1
3
8
27

-----Note-----

In the first query Mishka can roll a dice once and get $2$ points.

In the second query Mishka can roll a dice $3$ times and get points $5$, $5$ and $3$ (for example).

In the third query Mishka can roll a dice $8$ times and get $5$ points $7$ times and $2$ points with the remaining roll.

In the fourth query Mishka can roll a dice $27$ times and get $2$ points $11$ times, $3$ points $6$ times and $6$ points $10$ times.

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

t = int(input())
for i in range(t):
    n = int(input())
    print(n // 2)


I found an interesting problem on https://codeforces.com/problemset/problem/1093/B:
You are given a string $s$ consisting only of lowercase Latin letters.

You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.

Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.

You have to answer $t$ independent queries.

-----Input-----

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

Each of the next $t$ lines contains one string. The $i$-th line contains a string $s_i$ consisting only of lowercase Latin letter. It is guaranteed that the length of $s_i$ is from $1$ to $1000$ (inclusive).

-----Output-----

Print $t$ lines. In the $i$-th line print the answer to the $i$-th query: -1 if it is impossible to obtain a good string by rearranging the letters of $s_i$ and any good string which can be obtained from the given one (by rearranging the letters) otherwise.

-----Example-----
Input
3
aa
abacaba
xdd

Output
-1
abaacba
xdd

-----Note-----

In the first query we cannot rearrange letters to obtain a good string.

Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".

In the third query we can do nothing to obtain a good string.

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

read = lambda: [int(i) for i in input().split()]

t = int(input())
while t > 0:
    t -= 1
    s = input()
    s_sort = sorted(s)
    if s_sort[0] == s_sort[-1]:
        print(-1)
    else:
        print(''.join(s_sort))


I found an interesting problem on https://codeforces.com/problemset/problem/1093/C:
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.

There were $n$ classes of that subject during the semester and on $i$-th class professor mentioned some non-negative integer $a_i$ to the students. It turned out, the exam was to tell the whole sequence back to the professor.

Sounds easy enough for those who attended every class, doesn't it?

Obviously Mishka didn't attend any classes. However, professor left some clues on the values of $a$ to help out students like Mishka:   $a$ was sorted in non-decreasing order ($a_1 \le a_2 \le \dots \le a_n$);  $n$ was even;  the following sequence $b$, consisting of $\frac n 2$ elements, was formed and given out to students: $b_i = a_i + a_{n - i + 1}$.

Professor also mentioned that any sequence $a$, which produces sequence $b$ with the presented technique, will be acceptable.

Help Mishka to pass that last exam. Restore any sorted sequence $a$ of non-negative integers, which produces sequence $b$ with the presented technique. It is guaranteed that there exists at least one correct sequence $a$, which produces the given sequence $b$.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the length of sequence $a$. $n$ is always even.

The second line contains $\frac n 2$ integers $b_1, b_2, \dots, b_{\frac n 2}$ ($0 \le b_i \le 10^{18}$) — sequence $b$, where $b_i = a_i + a_{n - i + 1}$.

It is guaranteed that there exists at least one correct sequence $a$, which produces the given sequence $b$.

-----Output-----

Print $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^{18}$) in a single line.

$a_1 \le a_2 \le \dots \le a_n$ should be satisfied.

$b_i = a_i + a_{n - i + 1}$ should be satisfied for all valid $i$.

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

Output
2 3 3 3

Input
6
2 1 2

Output
0 0 1 1 1 2

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

n = int(input())
b = list(map(int, input().split(' ')))

a = [0] * n

minV = 0
maxV = b[0]

m = n //2

a[n - 1] = b[0]

i = 1
j = n - 2

while(i < m):
  if(b[i] - minV > 0 and b[i] - minV <= maxV):
    a[i] = minV
    a[j] = b[i] - minV
    maxV = min(maxV, b[i] - minV)
  else:
    a[i] = b[i] - maxV
    a[j] = maxV
    minV = max(minV, b[i] - maxV)

  i += 1
  j -= 1

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


I found an interesting problem on https://codeforces.com/problemset/problem/1093/D:
You are given an undirected unweighted graph consisting of $n$ vertices and $m$ edges.

You have to write a number on each vertex of the graph. Each number should be $1$, $2$ or $3$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.

Calculate the number of possible ways to write numbers $1$, $2$ and $3$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $998244353$.

Note that you have to write exactly one number on each vertex.

The graph does not have any self-loops or multiple edges.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 3 \cdot 10^5$) — the number of tests in the input.

The first line of each test contains two integers $n$ and $m$ ($1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$) — the number of vertices and the number of edges, respectively. Next $m$ lines describe edges: $i$-th line contains two integers $u_i$, $ v_i$ ($1 \le u_i, v_i \le n; u_i \neq v_i$) — indices of vertices connected by $i$-th edge.

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

-----Output-----

For each test print one line, containing one integer — the number of possible ways to write numbers $1$, $2$, $3$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $998244353$.

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

Output
4
0

-----Note-----

Possible ways to distribute numbers in the first test:   the vertex $1$ should contain $1$, and $2$ should contain $2$;  the vertex $1$ should contain $3$, and $2$ should contain $2$;  the vertex $1$ should contain $2$, and $2$ should contain $1$;  the vertex $1$ should contain $2$, and $2$ should contain $3$.

In the second test there is no way to distribute numbers.

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

from sys import stdin,stdout
from collections import defaultdict
import sys, threading
sys.setrecursionlimit(122500) # max depth of recursion
threading.stack_size(2**25)
def main():
    def power(x, p):
        re = 1
        mode= 998244353
        while p:
            if p & 1:
                re = re * x % mode
            x = x * x % mode
            p >>= 1
        return re;

    def dfs(node,col):
        visited[node]=True
        c[col]+=1
        color[node]=col
        for j in dic[node]:
            if not visited[j]:
                if not dfs(j, col ^ 1):
                    return False
            else:
                if color[j]==color[node]:
                    return False
        return True

    t=int(stdin.readline())
    for _ in range(t):
        mod=998244353
        n,m=list(map(int,stdin.readline().split()))
        dic=defaultdict(list)
        for i in range(m):
            u,v=list(map(int,stdin.readline().split()))
            dic[u].append(v)
            dic[v].append(u)
        visited=[False]*(n+1)
        color=[-1]*(n+1)
        c=[0]*2
        result=1
        flag=0
        #print(dic)
        for i in range(1,n+1):
            if not visited[i]:
                res=dfs(i,0)
                if not res:
                    flag=1
                    break
                else:
                    result=(result*(power(2,c[0])+power(2,c[1])))%mod
                    c[0]=0
                    c[1]=0
        if flag==1:
            stdout.write("0\n")
        else:
            stdout.write(str(result)+"\n")
threading.Thread(target=main).start()


I found an interesting problem on https://codeforces.com/problemset/problem/1093/F:
Vasya has got an array consisting of $n$ integers, and two integers $k$ and $len$ in addition. All numbers in the array are either between $1$ and $k$ (inclusive), or equal to $-1$. The array is good if there is no segment of $len$ consecutive equal numbers.

Vasya will replace each $-1$ with some number from $1$ to $k$ (inclusive) in such a way that the resulting array is good. Tell him the number of ways to do this replacement. Since the answer may be large, print it modulo $998244353$.

-----Input-----

The first line contains three integers $n, k$ and $len$ ($1 \le n \le 10^5, 1 \le k \le 100, 1 \le len \le n$).

The second line contains $n$ numbers — the array. Each number is either $-1$ or between $1$ and $k$ (inclusive).

-----Output-----

Print one integer — the number of ways to replace each $-1$ with some number from $1$ to $k$ (inclusive) so the array is good. The answer may be large, so print it modulo $998244353$.

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

Output
2

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

Output
0

Input
10 42 7
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1

Output
645711643

-----Note-----

Possible answers in the first test:   $[1, 2, 1, 1, 2]$;  $[1, 2, 1, 2, 2]$.

There is no way to make the array good in the second test, since first two elements are equal.

There are too many answers in the third test, so we won't describe any of them.

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

def vasya_and_array():
    n,k,leng = [int(x) for x in input().split()]
    if(leng==1):
        return 0
    a = [int(x) for x in input().split()]
    mod = 998244353
    a.insert(0,0)
    dp = [[0 for x in range((k+1))] for y in range(n+1)]
    sumdp = [0 for _ in range(n+1)]
    sumdp[0]=1
    count = [0 for _ in range(k+1)]

    for i in range(1,n+1):
        for j in range(1,k+1):
            if(a[i]==-1 or a[i]==j):
                dp[i][j] = sumdp[i-1]
                count[j]+=1
                if(count[j] >= leng):
                    dp[i][j]-=(sumdp[i-leng] - dp[i-leng][j])
                dp[i][j]%=mod
                sumdp[i]+=dp[i][j]
                sumdp[i]%=mod
            else:
                count[j]=0

    return (sumdp[n])

print(vasya_and_array())


I found an interesting problem on https://codeforces.com/problemset/problem/1095/A:
Polycarp loves ciphers. He has invented his own cipher called repeating.

Repeating cipher is used for strings. To encrypt the string $s=s_{1}s_{2} \dots s_{m}$ ($1 \le m \le 10$), Polycarp uses the following algorithm:

  he writes down $s_1$ ones,  he writes down $s_2$ twice,  he writes down $s_3$ three times,  ...  he writes down $s_m$ $m$ times.

For example, if $s$="bab" the process is: "b" $\to$ "baa" $\to$ "baabbb". So the encrypted $s$="bab" is "baabbb".

Given string $t$ — the result of encryption of some string $s$. Your task is to decrypt it, i. e. find the string $s$.

-----Input-----

The first line contains integer $n$ ($1 \le n \le 55$) — the length of the encrypted string. The second line of the input contains $t$ — the result of encryption of some string $s$. It contains only lowercase Latin letters. The length of $t$ is exactly $n$.

It is guaranteed that the answer to the test exists.

-----Output-----

Print such string $s$ that after encryption it equals $t$.

-----Examples-----
Input
6
baabbb

Output
bab
Input
10
ooopppssss

Output
oops
Input
1
z

Output
z

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

n = int(input())
a = list(input())
ans = ''
pos = 0
count = 1
while pos < n:
    ans += a[pos]
    for i in range(count):
        pos += 1
    count += 1
print(ans)


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

Let instability of the array be the following value: $\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$.

You have to remove exactly one element from this array to minimize instability of the resulting $(n-1)$-elements array. Your task is to calculate the minimum possible instability.

-----Input-----

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

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

-----Output-----

Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $a$.

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

Output
2

Input
2
1 100000

Output
0

-----Note-----

In the first example you can remove $7$ then instability of the remaining array will be $3 - 1 = 2$.

In the second example you can remove either $1$ or $100000$ then instability of the remaining array will be $100000 - 100000 = 0$ and $1 - 1 = 0$ correspondingly.

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

n = int(input())
s = list(map(int, input().split()))
M = max(s)
m = min(s)
i = M - m
s.remove(M)
M1 = max(s)
i1 = M1 - m
s.append(M)
s.remove(m)
m1 = min(s)
i2 = M - m1
print(min(i,i1,i2))


I found an interesting problem on https://codeforces.com/problemset/problem/1095/D:
There are $n$ kids, numbered from $1$ to $n$, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as $p_1$, $p_2$, ..., $p_n$ (all these numbers are from $1$ to $n$ and are distinct, so $p$ is a permutation). Let the next kid for a kid $p_i$ be kid $p_{i + 1}$ if $i < n$ and $p_1$ otherwise. After the dance, each kid remembered two kids: the next kid (let's call him $x$) and the next kid for $x$. Each kid told you which kids he/she remembered: the kid $i$ remembered kids $a_{i, 1}$ and $a_{i, 2}$. However, the order of $a_{i, 1}$ and $a_{i, 2}$ can differ from their order in the circle. [Image] Example: 5 kids in a circle, $p=[3, 2, 4, 1, 5]$ (or any cyclic shift). The information kids remembered is: $a_{1,1}=3$, $a_{1,2}=5$; $a_{2,1}=1$, $a_{2,2}=4$; $a_{3,1}=2$, $a_{3,2}=4$; $a_{4,1}=1$, $a_{4,2}=5$; $a_{5,1}=2$, $a_{5,2}=3$.

You have to restore the order of the kids in the circle using this information. If there are several answers, you may print any. It is guaranteed that at least one solution exists.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.

-----Input-----

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

The next $n$ lines contain $2$ integers each. The $i$-th line contains two integers $a_{i, 1}$ and $a_{i, 2}$ ($1 \le a_{i, 1}, a_{i, 2} \le n, a_{i, 1} \ne a_{i, 2}$) — the kids the $i$-th kid remembered, given in arbitrary order.

-----Output-----

Print $n$ integers $p_1$, $p_2$, ..., $p_n$ — permutation of integers from $1$ to $n$, which corresponds to the order of kids in the circle. If there are several answers, you may print any (for example, it doesn't matter which kid is the first in the circle). It is guaranteed that at least one solution exists.

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

Output
3 2 4 1 5

Input
3
2 3
3 1
1 2

Output
3 1 2

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

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

n = ii()
if n == 3:
    ans = [1, 2, 3]
else:
    a = [None] + [li() for i in range(n)]
    ans = []
    i = 1
    while 1:
        ans.append(i)
        j = a[i][0]
        if a[i][1] not in a[j]:
            j = a[i][1]
        i = j
        if i == 1: break
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1095/E:
You are given a bracket sequence $s$ consisting of $n$ opening '(' and closing ')' brackets.

A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.

You can change the type of some bracket $s_i$. It means that if $s_i = $ ')' then you can change it to '(' and vice versa.

Your task is to calculate the number of positions $i$ such that if you change the type of the $i$-th bracket, then the resulting bracket sequence becomes regular.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 10^6$) — the length of the bracket sequence.

The second line of the input contains the string $s$ consisting of $n$ opening '(' and closing ')' brackets.

-----Output-----

Print one integer — the number of positions $i$ such that if you change the type of the $i$-th bracket, then the resulting bracket sequence becomes regular.

-----Examples-----
Input
6
(((())

Output
3

Input
6
()()()

Output
0

Input
1
)

Output
0

Input
8
)))(((((

Output
0

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

def isregular(s):
    ls=0
    rs=0
    for char in s:
        if char=="(":
            ls+=1
        else:
            rs+=1
        if rs>ls:
            return False
    if ls==rs:
        return True
    return False
n=int(input())
s=input()
if n%2==1:
    print(0)
else:
    a=s.count("(")
    b=n-a
    diff=[0]
    for i in range(n):
        if s[i]=="(":
            diff.append(diff[-1]+1)
        else:
            diff.append(diff[-1]-1)
    if a==b+2:
        if -1 in diff:
            print(0)
        else:
            backdiff=diff[::-1]
            last=backdiff.index(1)
            print(s[-last:].count("("))
    elif b==a+2:
        if -3 in diff:
            print(0)
        else:
            first=diff.index(-1)
            print(s[:first].count(")"))
    else:
        print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/1095/F:
You are given an undirected graph consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is $a_i$. Initially there are no edges in the graph.

You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices $x$ and $y$ is $a_x + a_y$ coins. There are also $m$ special offers, each of them is denoted by three numbers $x$, $y$ and $w$, and means that you can add an edge connecting vertices $x$ and $y$ and pay $w$ coins for it. You don't have to use special offers: if there is a pair of vertices $x$ and $y$ that has a special offer associated with it, you still may connect these two vertices paying $a_x + a_y$ coins for it.

What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 2 \cdot 10^5$) — the number of vertices in the graph and the number of special offers, respectively.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{12}$) — the numbers written on the vertices.

Then $m$ lines follow, each containing three integers $x$, $y$ and $w$ ($1 \le x, y \le n$, $1 \le w \le 10^{12}$, $x \ne y$) denoting a special offer: you may add an edge connecting vertex $x$ and vertex $y$, and this edge will cost $w$ coins.

-----Output-----

Print one integer — the minimum number of coins you have to pay to make the graph connected.

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

Output
5

Input
4 0
1 3 3 7

Output
16

Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15

Output
18

-----Note-----

In the first example it is possible to connect $1$ to $2$ using special offer $2$, and then $1$ to $3$ without using any offers.

In next two examples the optimal answer may be achieved without using special offers.

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

n, m = map(int, input().split())
a = list(map(int, input().split()))
e = []
for _ in range(m) :
    u, v, w = map(int, input().split())
    e.append((u-1, v-1, w))
a = sorted(zip(a, range(n)), key = lambda x : x[0])
for i in range(1, n) :
    e.append((a[0][1], a[i][1], a[0][0] + a[i][0]))

fa = list(range(n))
rk = [0] * n

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

def unite(u, v) :
    u, v = map(find, (u, v))
    if u == v : return False
    if rk[u] < rk[v] : u, v = v, u
    fa[v] = u
    if rk[u] == rk[v] : rk[u] += 1
    return True

e.sort(key = lambda x : x[2])

ans = 0
cnt = 1
for ee in e :
    if cnt == n : break
    if unite(ee[0], ee[1]) :
        ans += ee[2]
        cnt += 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1096/A:
You are given a range of positive integers from $l$ to $r$.

Find such a pair of integers $(x, y)$ that $l \le x, y \le r$, $x \ne y$ and $x$ divides $y$.

If there are multiple answers, print any of them.

You are also asked to answer $T$ independent queries.

-----Input-----

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

Each of the next $T$ lines contains two integers $l$ and $r$ ($1 \le l \le r \le 998244353$) — inclusive borders of the range.

It is guaranteed that testset only includes queries, which have at least one suitable pair.

-----Output-----

Print $T$ lines, each line should contain the answer — two integers $x$ and $y$ such that $l \le x, y \le r$, $x \ne y$ and $x$ divides $y$. The answer in the $i$-th line should correspond to the $i$-th query from the input.

If there are multiple answers, print any of them.

-----Example-----
Input
3
1 10
3 14
1 10

Output
1 7
3 9
5 10

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

t = int(input())
for i in range(t):
	l, r = list(map(int, input().split()))
	print(l, 2 * l)


I found an interesting problem on https://codeforces.com/problemset/problem/1096/B:
You are given a string $s$ of length $n$ consisting only of lowercase Latin letters.

A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not.

Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one).

It is guaranteed that there is at least two different characters in $s$.

Note that you can remove the whole string and it is correct. Also note that you should remove at least one character.

Since the answer can be rather large (not very large though) print it modulo $998244353$.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.

-----Input-----

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

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

It is guaranteed that there is at least two different characters in $s$.

-----Output-----

Print one integer — the number of ways modulo $998244353$ to remove exactly one substring from $s$ in such way that all remaining characters are equal.

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

Output
6

Input
7
aacdeee

Output
6
Input
2
az

Output
3

-----Note-----

Let $s[l; r]$ be the substring of $s$ from the position $l$ to the position $r$ inclusive.

Then in the first example you can remove the following substrings:   $s[1; 2]$;  $s[1; 3]$;  $s[1; 4]$;  $s[2; 2]$;  $s[2; 3]$;  $s[2; 4]$.

In the second example you can remove the following substrings:   $s[1; 4]$;  $s[1; 5]$;  $s[1; 6]$;  $s[1; 7]$;  $s[2; 7]$;  $s[3; 7]$.

In the third example you can remove the following substrings:   $s[1; 1]$;  $s[1; 2]$;  $s[2; 2]$.

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

#
import collections, atexit, math, sys, bisect

sys.setrecursionlimit(1000000)
def getIntList():
    return list(map(int, input().split()))

try :
    #raise ModuleNotFoundError
    import numpy
    def dprint(*args, **kwargs):
        #print(*args, **kwargs, file=sys.stderr)
        # in python 3.4 **kwargs is invalid???
        print(*args,  file=sys.stderr)
    dprint('debug mode')
except Exception:
    def dprint(*args, **kwargs):
        pass

inId = 0
outId = 0
if inId>0:
    dprint('use input', inId)
    sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件
if outId>0:
    dprint('use output', outId)
    sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件
    atexit.register(lambda :sys.stdout.close())     #idle 中不会执行 atexit

N, = getIntList()
#print(N)
s = input()

for a in range(1,1000000):
    if s[a] !=s[0]:
        break

for b in range(N-2,-1,-1):
    if s[b] !=s[N-1]:
        break
dprint(a,b)
base = 998244353
if s[0] != s[N-1]:
    print( a + N - b )
else:
    print( (a+1) * (N-b) % base )


I found an interesting problem on https://codeforces.com/problemset/problem/1096/C:
You are given an angle $\text{ang}$.

The Jury asks You to find such regular $n$-gon (regular polygon with $n$ vertices) that it has three vertices $a$, $b$ and $c$ (they can be non-consecutive) with $\angle{abc} = \text{ang}$ or report that there is no such $n$-gon. [Image]

If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed $998244353$.

-----Input-----

The first line contains single integer $T$ ($1 \le T \le 180$) — the number of queries.

Each of the next $T$ lines contains one integer $\text{ang}$ ($1 \le \text{ang} < 180$) — the angle measured in degrees.

-----Output-----

For each query print single integer $n$ ($3 \le n \le 998244353$) — minimal possible number of vertices in the regular $n$-gon or $-1$ if there is no such $n$.

-----Example-----
Input
4
54
50
2
178

Output
10
18
90
180

-----Note-----

The answer for the first query is on the picture above.

The answer for the second query is reached on a regular $18$-gon. For example, $\angle{v_2 v_1 v_6} = 50^{\circ}$.

The example angle for the third query is $\angle{v_{11} v_{10} v_{12}} = 2^{\circ}$.

In the fourth query, minimal possible $n$ is $180$ (not $90$).

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

import sys
from math import gcd
from itertools import groupby as gb
from itertools import permutations as perm
from collections import Counter as C
from collections import defaultdict as dd
sys.setrecursionlimit(10**5)

T = int(input())
for i in range(T):
    ang = int(input())
    g = gcd(ang, 180)
    gg = 180 // g
    a = ang // g
    if gg - a == 1:
        print(gg*2)
    else:
        print(gg)


I found an interesting problem on https://codeforces.com/problemset/problem/1096/D:
Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length $n$ consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements.

Vasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is $0$, and removing $i$-th character increases the ambiguity by $a_i$ (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still $4$ even though you delete it from the string had).

Vasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!

Recall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

-----Input-----

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

The second line contains one string $s$ of length $n$, consisting of lowercase Latin letters — the statement written by Vasya.

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

-----Output-----

Print minimum possible ambiguity of the statement after Vasya deletes some (possibly zero) characters so the resulting statement is easy.

-----Examples-----
Input
6
hhardh
3 2 9 11 7 1

Output
5

Input
8
hhzarwde
3 2 6 9 4 8 7 1

Output
4

Input
6
hhaarr
1 2 3 4 5 6

Output
0

-----Note-----

In the first example, first two characters are removed so the result is ardh.

In the second example, $5$-th character is...

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

_ = input()
s = input()
a = list(map(int, input().split()))

hard = "hard"

dp = [0]*4
for i in range(len(s)):
    if s[i] == hard[0]:
        dp[0] += a[i]
    for j in range(1, 4):
        if s[i] == hard[j]:
            # If same letter, either leave as-is (extend prefix) or remove it
            dp[j] = min(dp[j-1], dp[j] + a[i])

print(min(dp))


I found an interesting problem on https://codeforces.com/problemset/problem/1096/E:
Hasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are $p$ players doing penalty shoot-outs. Winner is the one who scores the most. In case of ties, one of the top-scorers will be declared as the winner randomly with equal probability.

They have just finished the game and now are waiting for the result. But there's a tiny problem! The judges have lost the paper of scores! Fortunately they have calculated sum of the scores before they get lost and also for some of the players they have remembered a lower bound on how much they scored. However, the information about the bounds is private, so Hasan only got to know his bound.

According to the available data, he knows that his score is at least $r$ and sum of the scores is $s$.

Thus the final state of the game can be represented in form of sequence of $p$ integers $a_1, a_2, \dots, a_p$ ($0 \le a_i$) — player's scores. Hasan is player number $1$, so $a_1 \ge r$. Also $a_1 + a_2 + \dots + a_p = s$. Two states are considered different if there exists some position $i$ such that the value of $a_i$ differs in these states.

Once again, Hasan doesn't know the exact scores (he doesn't know his exact score as well). So he considers each of the final states to be equally probable to achieve.

Help Hasan find the probability of him winning.

It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$, $P \le Q$. Report the value of $P \cdot Q^{-1} \pmod {998244353}$.

-----Input-----

The only line contains three integers $p$, $s$ and $r$ ($1 \le p \le 100$, $0 \le r \le s \le 5000$) — the number of players, the sum of scores of all players and Hasan's score, respectively.

-----Output-----

Print a single integer — the probability of Hasan winning.

It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$, $P \le Q$. Report the value of $P \cdot Q^{-1} \pmod...

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

base=998244353;
def power(x, y):
    if(y==0):
        return 1
    t=power(x, y//2)
    t=(t*t)%base
    if(y%2):
        t=(t*x)%base
    return t;
def inverse(x):
    return power(x, base-2)
f=[1]
iv=[1]
for i in range(1, 5555):
    f.append((f[i-1]*i)%base)
    iv.append(inverse(f[i]))
def C(n, k):
    return (f[n]*iv[k]*iv[n-k])%base
def candy(n, k):
    # print(n, k)
    return C(n+k-1, k-1)
def count_game(k, n, x): #k players, n points total, no player can have x point or more
    if(k==0):
        if(n==0):
            return 1
        else:
            return 0
    ans=0
    for i in range(0, k+1):
        t=n-x*i
        # print(i, C(k, i))
        if(t<0):
            break
        if(i%2):
            ans=(ans-C(k, i)*candy(t, k))%base
        else:
            ans=(ans+C(k, i)*candy(t, k))%base
    return ans
p, s, r= list(map(int, input().split()))
gamesize=count_game(p, s-r, int(1e18))
gamesize=inverse(gamesize)
ans=0;
for q in range(r, s+1):
    for i in range(0, p): #exactly i people have the same score
        t=s-(i+1)*q
        if(t<0):
            break
        # print(q, i, count_game(p-i-1, t, q));
        ans=(ans+C(p-1, i)*count_game(p-i-1, t, q)*gamesize*inverse(i+1))%base
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1096/F:
A permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array. An inversion in a permutation $p$ is a pair of indices $(i, j)$ such that $i > j$ and $a_i < a_j$. For example, a permutation $[4, 1, 3, 2]$ contains $4$ inversions: $(2, 1)$, $(3, 1)$, $(4, 1)$, $(4, 3)$.

You are given a permutation $p$ of size $n$. However, the numbers on some positions are replaced by $-1$. Let the valid permutation be such a replacement of $-1$ in this sequence back to numbers from $1$ to $n$ in such a way that the resulting sequence is a permutation of size $n$.

The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.

Calculate the expected total number of inversions in the resulting valid permutation.

It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$. Report the value of $P \cdot Q^{-1} \pmod {998244353}$.

-----Input-----

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

The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($-1 \le p_i \le n$, $p_i \ne 0$) — the initial sequence.

It is guaranteed that all elements not equal to $-1$ are pairwise distinct.

-----Output-----

Print a single integer — the expected total number of inversions in the resulting valid permutation.

It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$. Report the value of $P \cdot Q^{-1} \pmod {998244353}$.

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

Output
499122179

Input
2
1 2

Output
0

Input
2
-1 -1

Output
499122177

-----Note-----

In the first example two resulting valid permutations are possible:

  $[3, 1, 2]$ — $2$ inversions;  $[3, 2, 1]$ — $3$ inversions.

The expected value is $\frac{2 \cdot 1 + 3 \cdot 1}{2} = 2.5$.

In the second example no $-1$ are present, thus the only valid permutation is possible — the given one....

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

n = int(input())

L = [int(x) for x in input().split()]
D = {}
J = []
S = []
T = [0]*(n+1)
for i in range(n):
    if L[i] > 0:
        D[L[i]] = i
        J.append(L[i])
        T[i+1] = T[i]
    else:
        T[i+1] = T[i]+1

def I(J):
    if len(J) <= 1:
        return J, 0
    else:
        a = J[:len(J)//2]
        b = J[len(J)//2:]
        a, ai = I(a)
        b, bi = I(b)
        c = []
        i = 0
        j = 0
        inversions = ai + bi
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            c.append(a[i])
            i += 1
        else:
            c.append(b[j])
            j += 1
            inversions += (len(a)-i)
    c += a[i:]
    c += b[j:]
    return c, inversions

for i in range(1,n+1):
    if not i in D:
        S.append(i)

total = len(S)
num = 1
denom = 1
if total > 0:
    themostimportantsum = 0
    for i in J:
        low = 0
        high = total-1
        while high-low > 1:
            guess = (high+low)//2
            if S[guess] > i:
                high = guess
            else:
                low = guess
        if S[low] > i:
            smaller = low
        elif S[high] > i:
            smaller = high
        else:
            smaller = high+1
        #D[i] is the position of i in the list
        #T[D[i]] is how many -1s there are to the left of it
        themostimportantsum += T[D[i]]*(total-smaller)+(total-T[D[i]])*(smaller)
        num = themostimportantsum+total
        denom = total

num =(denom*(((total)*(total-1))//2)+2*num)%998244353
denom *= 2
if num == denom:
    if I(J)[1] == 0:
        print(0)
    else:
        print(I(J)[1]%998244353)
else:
    num += denom*I(J)[1]
    print(((num-denom)*pow(denom%998244353,998244351,998244353))%998244353)


I found an interesting problem on https://codeforces.com/problemset/problem/1097/A:
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".

To play Mau-Mau, you need a pack of $52$ cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or Hearts — H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).

At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.

In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.

-----Input-----

The first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand.

Each string is two characters long. The first character denotes the rank and belongs to the set $\{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}$. The second character denotes the suit and belongs to the set $\{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}$.

All the cards in the input are different.

-----Output-----

If it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO".

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

-----Examples-----
Input
AS
2H 4C TH JH AD

Output
YES

Input
2H
3D 4C AC KD AS

Output
NO

Input
4D
AS AC AD AH 5H

Output
YES

-----Note-----

In the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces.

In the second example, you cannot play any card.

In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table.

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

import sys
import math

def read_int():
	return int(input().strip())

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

def read_string():
	return input().strip()

def read_string_list(delim=" "):
	return input().strip().split(delim)

###### Author : Samir Vyas #######
###### Write Code Below    #######

table_c = read_string()

cards = read_string_list()

for c in cards:
	if c[0] == table_c[0] or c[1] == table_c[1]:
		print("YES")
		return

print("NO")