I found an interesting problem on https://codeforces.com/problemset/problem/777/B:
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.

Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if n = 3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.

Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.

Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of digits in the cards Sherlock and Moriarty are going to use.

The second line contains n digits — Sherlock's credit card number.

The third line contains n digits — Moriarty's credit card number.

-----Output-----

First print the minimum possible number of flicks Moriarty will get. Then print the maximum possible number of flicks that Sherlock can get from...

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

n = int(input())
sherlock = [int(i) for i in list(input())]
moriarty = [int(i) for i in list(input())]

pairs = []
for i in range(n):
    for j in range(n):
        pairs.append((moriarty[j]-sherlock[i], i, j))

pairs = sorted(pairs)

sherlock_marked = [False] * n
moriarty_marked = [False] * n

avoided = 0

for pair in pairs:
    if pair[0] < 0:
        continue

    if not sherlock_marked[pair[1]] and not moriarty_marked[pair[2]]:
        sherlock_marked[pair[1]] = True
        moriarty_marked[pair[2]] = True
        avoided += 1

sherlock_marked = [False] * n
moriarty_marked = [False] * n

flicked = 0

for pair in pairs:
    if pair[0] < 1:
        continue

    if not sherlock_marked[pair[1]] and not moriarty_marked[pair[2]]:
        sherlock_marked[pair[1]] = True
        moriarty_marked[pair[2]] = True
        flicked += 1

print(n - avoided)
print(flicked)


I found an interesting problem on https://codeforces.com/problemset/problem/777/C:
During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables.

Now she has a table filled with integers. The table consists of n rows and m columns. By a_{i}, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in non-decreasing order in the column j if a_{i}, j ≤ a_{i} + 1, j for all i from 1 to n - 1.

Teacher gave Alyona k tasks. For each of the tasks two integers l and r are given and Alyona has to answer the following question: if one keeps the rows from l to r inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such j that a_{i}, j ≤ a_{i} + 1, j for all i from l to r - 1 inclusive.

Alyona is too small to deal with this task and asks you to help!

-----Input-----

The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 100 000) — the number of rows and the number of columns in the table respectively. Note that your are given a constraint that bound the product of these two integers, i.e. the number of elements in the table.

Each of the following n lines contains m integers. The j-th integers in the i of these lines stands for a_{i}, j (1 ≤ a_{i}, j ≤ 10^9).

The next line of the input contains an integer k (1 ≤ k ≤ 100 000) — the number of task that teacher gave to Alyona.

The i-th of the next k lines contains two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n).

-----Output-----

Print "Yes" to the i-th line of the output if the table consisting of rows from l_{i} to r_{i} inclusive is sorted in non-decreasing order in at least one column. Otherwise, print "No".

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

Output
Yes
No
Yes
Yes
Yes
No

-----Note-----

In the sample, the whole table is not sorted in any column. However, rows 1–3 are sorted in column 1, while rows 4–5 are sorted in column 3.

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

#!/usr/bin/env python3
def ri():
    return list(map(int, input().split()))

n, m = ri()
a = []
for i in range(n):
    a.append(list(ri()))

t = [[0 for i in range(m)] for j in range(n)]
T = [0 for i in range(n)]

for i in range(m):
    for j in range(n-1):
        if a[j][i] > a[j+1][i]:
            t[j+1][i] = 0
        else:
            t[j+1][i] = t[j][i] + 1
for i in range(n):
    T[i] = max(t[i])

k = int(input())
ans = []
for i in range(k):
    l, r = ri()
    l = l-1
    r = r-1
    if T[r] >= r-l:
        ans.append("Yes")
    else:
        ans.append("No")

print('\n'.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/777/D:
Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.

The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).

Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of hashtags being edited now.

Each of the next n lines contains exactly one hashtag of positive length.

It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500 000.

-----Output-----

Print the resulting hashtags in any of the optimal solutions.

-----Examples-----
Input
3
#book
#bigtown
#big

Output
#b
#big
#big

Input
3
#book
#cool
#cold

Output
#book
#co
#cold

Input
4
#car
#cart
#art
#at

Output
#
#
#art
#at

Input
3
#apple
#apple
#fruit

Output
#apple
#apple
#fruit

-----Note-----

Word a_1, a_2, ..., a_{m} of length m is lexicographically not greater than word b_1, b_2, ..., b_{k} of length k, if one of two conditions hold:   at first position i, such...

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

n = int(input())

inp = [0] * n

for i in range(n):
	inp[i] = input()

def common_str(a, b):
	l = 1
	for i in range(1, len(a)):
		if a[i] != b[i]:
			break
		l += 1

	return a[:l]

for i in range(n - 1, 0, -1):
	if inp[i] < inp[i - 1]:
		inp[i - 1] = common_str(inp[i], inp[i - 1])

print('\n'.join(inp))


I found an interesting problem on https://codeforces.com/problemset/problem/777/E:
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.

There are n rings in factory's stock. The i-th ring has inner radius a_{i}, outer radius b_{i} and height h_{i}. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:  Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if b_{j} ≤ b_{i}.  Rings should not fall one into the the other. That means one can place ring j on the ring i only if b_{j} > a_{i}.  The total height of all rings used should be maximum possible.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of rings in factory's stock.

The i-th of the next n lines contains three integers a_{i}, b_{i} and h_{i} (1 ≤ a_{i}, b_{i}, h_{i} ≤ 10^9, b_{i} > a_{i}) — inner radius, outer radius and the height of the i-th ring respectively.

-----Output-----

Print one integer — the maximum height of the tower that can be obtained.

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

Output
6

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

Output
4

-----Note-----

In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.

In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4.

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

aux = [(9e9, 0, 0)]
n = int(input())

for i in range(n):
    a, b, h = map(int, input().split())
    aux.append((b, a, h)) #sort padrao eh pelo item 0 da tupla

aux.sort(reverse=True)

s, p = [0], [0] *(n + 1)

for i in range(1, n + 1):
    while aux[s[-1]][1] >= aux[i][0]:
        s.pop()

    p[i] = p[s[-1]] + aux[i][2]
    s.append(i)
print(max(p))


I found an interesting problem on https://codeforces.com/problemset/problem/779/A:
In Berland each high school student is characterized by academic performance — integer value between 1 and 5.

In high school 0xFF there are two groups of pupils: the group A and the group B. Each group consists of exactly n students. An academic performance of each student is known — integer value between 1 and 5.

The school director wants to redistribute students between groups so that each of the two groups has the same number of students whose academic performance is equal to 1, the same number of students whose academic performance is 2 and so on. In other words, the purpose of the school director is to change the composition of groups, so that for each value of academic performance the numbers of students in both groups are equal.

To achieve this, there is a plan to produce a series of exchanges of students between groups. During the single exchange the director selects one student from the class A and one student of class B. After that, they both change their groups.

Print the least number of exchanges, in order to achieve the desired equal numbers of students for each academic performance.

-----Input-----

The first line of the input contains integer number n (1 ≤ n ≤ 100) — number of students in both groups.

The second line contains sequence of integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 5), where a_{i} is academic performance of the i-th student of the group A.

The third line contains sequence of integer numbers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 5), where b_{i} is academic performance of the i-th student of the group B.

-----Output-----

Print the required minimum number of exchanges or -1, if the desired distribution of students can not be obtained.

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

Output
1

Input
6
1 1 1 1 1 1
5 5 5 5 5 5

Output
3

Input
1
5
3

Output
-1

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

Output
4

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

from collections import Counter

n = int(input().strip())
ca = Counter([int(x) for x in input().strip().split(' ')])
cb = Counter([int(x) for x in input().strip().split(' ')])
cnt = 0

for i in range(1, 6):
    if (ca[i] + cb[i]) % 2 != 0:
        print(-1)
        return
    else:
        cnt += abs(ca[i] - (ca[i] + cb[i]) / 2)
print(int(cnt/2))


I found an interesting problem on https://codeforces.com/problemset/problem/779/B:
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10^{k}.

In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10^{k}. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 10^3 = 1000.

Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10^{k}. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).

It is guaranteed that the answer exists.

-----Input-----

The only line of the input contains two integer numbers n and k (0 ≤ n ≤ 2 000 000 000, 1 ≤ k ≤ 9).

It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.

-----Output-----

Print w — the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10^{k}. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).

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

Output
1

Input
100 9

Output
2

Input
10203049 2

Output
3

-----Note-----

In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number.

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

l = input().split()
k = int(l[1]) ; n = l[0]
n = n[::-1]
def compute() :
	j = 0 ; i = 0 ; ans  = 0
	if len(n) <= k  :
		return len(n)-1
	while j < k and i < len(n) :
		if  n[i] != '0' :
			ans += 1
		else: j+= 1
		i += 1
	if i == len(n) and j < k :
		return len(n)-1
	else:
		return ans
print(compute())


I found an interesting problem on https://codeforces.com/problemset/problem/779/C:
Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is a_{i}, and after a week of discounts its price will be b_{i}.

Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.

Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.

-----Input-----

In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·10^5, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now.

The second line contains sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^4) — prices of items during discounts (i.e. right now).

The third line contains sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^4) — prices of items after discounts (i.e. after a week).

-----Output-----

Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.

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

Output
10

Input
5 3
3 4 7 10 3
4 5 5 12 5

Output
25

-----Note-----

In the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.

In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25.

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

n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = sorted([(a[i]-b[i], a[i], b[i]) for i in range(n)])
total = 0
for e in c[:k]:
    total += e[1]
for e in c[k:]:
    total += min(e[1], e[2])
print(total)


I found an interesting problem on https://codeforces.com/problemset/problem/780/A:
Andryusha is an orderly boy and likes to keep things in their place.

Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.

Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?

-----Input-----

The first line contains the single integer n (1 ≤ n ≤ 10^5) — the number of sock pairs.

The second line contains 2n integers x_1, x_2, ..., x_2n (1 ≤ x_{i} ≤ n), which describe the order in which Andryusha took the socks from the bag. More precisely, x_{i} means that the i-th sock Andryusha took out was from pair x_{i}.

It is guaranteed that Andryusha took exactly two socks of each pair.

-----Output-----

Print single integer — the maximum number of socks that were on the table at the same time.

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

Output
1

Input
3
2 1 1 3 2 3

Output
2

-----Note-----

In the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.

In the second example Andryusha behaved as follows:   Initially the table was empty, he took out a sock from pair 2 and put it on the table.  Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table.  Socks (1, 2) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe.  Sock (2) was on the...

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

import sys

a = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
# your code goes here
table = set([])
lenTabel = 0
for sock in arr:
    # print(table)
    if sock in table:
        table.remove(sock)
    else:
        table.add(sock)
        # print(table)
        # print("{} ini panjang".format(len(table)))
        lenTabel = len(table) if (len(table) > lenTabel) else lenTabel
print(lenTabel)


I found an interesting problem on https://codeforces.com/problemset/problem/780/B:
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.

At some points on the road there are n friends, and i-th of them is standing at the point x_{i} meters and can move with any speed no greater than v_{i} meters per second in any of the two directions along the road: south or north.

You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.

-----Input-----

The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends.

The second line contains n integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^9) — the current coordinates of the friends, in meters.

The third line contains n integers v_1, v_2, ..., v_{n} (1 ≤ v_{i} ≤ 10^9) — the maximum speeds of the friends, in meters per second.

-----Output-----

Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road.

Your answer will be considered correct, if its absolute or relative error isn't greater than 10^{ - 6}. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$ holds.

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

Output
2.000000000000

Input
4
5 10 3 2
2 3 2 4

Output
1.400000000000

-----Note-----

In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds.

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

def check(f, speed, t):
    inter = (f[0] - speed[0] * t, f[0] + speed[0] * t)
    for i in range(1, len(f)):
        cur = (f[i] - speed[i] * t, f[i] + speed[i] * t)
        if cur[0] > inter[1] or inter[0] > cur[1]:
            return False
        else:
            inter = (max(cur[0], inter[0]), min(cur[1], inter[1]))
    return True

def binsearch(fr, sp):
    inf = 0
    sup = 10 ** 10
    while sup - inf > 10 ** (-6):
        if check(fr, sp, (sup + inf) / 2):
            sup = (sup + inf) / 2
        else:
            inf = (sup + inf) / 2
    return inf if check(fr, sp, inf) else sup

n = int(input())
x = list(map(int, input().split()))
v = list(map(int, input().split()))
print(binsearch(x, v))


I found an interesting problem on https://codeforces.com/problemset/problem/780/C:
Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.

The park consists of n squares connected with (n - 1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if a, b and c are distinct squares that a and b have a direct path between them, and b and c have a direct path between them, then balloon colors on these three squares are distinct.

Andryusha wants to use as little different colors as possible. Help him to choose the colors!

-----Input-----

The first line contains single integer n (3 ≤ n ≤ 2·10^5) — the number of squares in the park.

Each of the next (n - 1) lines contains two integers x and y (1 ≤ x, y ≤ n) — the indices of two squares directly connected by a path.

It is guaranteed that any square is reachable from any other using the paths.

-----Output-----

In the first line print single integer k — the minimum number of colors Andryusha has to use.

In the second line print n integers, the i-th of them should be equal to the balloon color on the i-th square. Each of these numbers should be within range from 1 to k.

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

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

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

Output
3
1 2 3 1 2

-----Note-----

In the first sample the park consists of three squares: 1 → 3 → 2. Thus, the balloon colors have to be distinct. [Image] Illustration for the first sample.

In the second example there are following triples of consequently connected squares:   1 → 3 → 2  1 → 3 → 4  1 → 3 → 5  2 → 3 → 4  2 → 3 → 5  4 → 3 → 5  We can see that each pair of squares is encountered in some triple, so all colors have to be distinct. [Image]...

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

n=int(input())
from collections import defaultdict,deque
g=defaultdict(list)
from sys import stdin
for i in range(n-1):
    h,m=list(map(int, stdin.readline().split()))
    g[h-1].append(m-1)
    g[m-1].append(h-1)
vis=[0]*n
c=[0]*n
c[0]=1
q=deque()
q.append(0)
while q:
    node=q.popleft()
    vis[node]=1
    s=set()
    for i in g[node]:
        if vis[i]==1:
            s.add(c[i])
    p=[]
    s.add(c[node])
    l=len(s)
    j=0
    k=1
    while l+j<=len(g[node])+2:
        r=0
        while r==0:
            if k not in s:
                p.append(k)
                r=1
            k+=1
        j+=1
    j=0
    for i in g[node]:
        if vis[i]==0:
            c[i]=p[j]
            j+=1
            q.append(i)

print(max(c))
print(*c)


I found an interesting problem on https://codeforces.com/problemset/problem/780/D:
Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.

Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that:   the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN",  or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB".

Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.

Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of clubs in the league.

Each of the next n lines contains two words — the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have...

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

n = int(input())
first = {}
second = set()
s1 = [0] * n
ans = [0] * n
for i in range(n):
    a, b = input().split()
    a = a[:3]
    b = b[0]
    s1[i] = b
    if a in first.keys():
        first[a].append(i)
    else:
        first[a] = [i]
        ans[i] = a
F = True
for name in first.keys():
    if not F:
        break
    if len(first[name]) > 1:
        for i in first[name]:
            c = name[:2] + s1[i]
            if c in second:
                F = False
                break
            else:
                second.add(c)
                ans[i] = c
        first[name] = 0

def process(name):
    nonlocal F
    if F == False:
        return
    if first[name] != 0 and name in second:
        t = first[name][0]
        c = name[:2] + s1[t]
        if c in second:
            F = False
            return
        else:
            second.add(c)
            ans[t] = c
            first[name] = 0
            if c in first.keys() and first[c] != 0:
                process(c)

for name in first.keys():
    process(name)

if F:
    print('YES')
    for i in range(n):
        print(ans[i])
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/784/A:
-----Input-----

The input contains a single integer a (1 ≤ a ≤ 30).

-----Output-----

Output a single integer.

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

Output
27

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/784/B:
Programmers' kids solve this riddle in 5-10 minutes. How fast can you do it?

-----Input-----

The input contains a single integer n (0 ≤ n ≤ 2000000000).

-----Output-----

Output a single integer.

-----Examples-----
Input
11

Output
2

Input
14

Output
0

Input
61441

Output
2

Input
571576

Output
10

Input
2128506

Output
3

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/784/C:
DO YOU EXPECT ME TO FIND THIS OUT?

WHAT BASE AND/XOR LANGUAGE INCLUDES string?

DON'T BYTE OF MORE THAN YOU CAN CHEW

YOU CAN ONLY DISTORT THE LARGEST OF MATHEMATICS SO FAR

SAYING "ABRACADABRA" WITHOUT A MAGIC AND WON'T DO YOU ANY GOOD

THE LAST STACK RUPTURES. ALL DIE. OH, THE EMBARRASSMENT!

I HAVE NO ARRAY AND I MUST SCREAM

ELEMENTS MAY NOT BE STORED IN WEST HYPERSPACE

-----Input-----

The first line of input data contains a single integer n (1 ≤ n ≤ 10).

The second line of input data contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 11).

-----Output-----

Output a single integer.

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

Output
4

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

input()
a=list(map(int, input().split()))
print(max(a)^a[-1])


I found an interesting problem on https://codeforces.com/problemset/problem/784/D:
-----Input-----

The only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive.

-----Output-----

Output "Yes" or "No".

-----Examples-----
Input
373

Output
Yes

Input
121

Output
No

Input
436

Output
Yes

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/784/E:
[Image]

-----Input-----

The input consists of four lines, each line containing a single digit 0 or 1.

-----Output-----

Output a single digit, 0 or 1.

-----Example-----
Input
0
1
1
0

Output
0

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/784/F:
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...

You are given an array of integers. Sort it in non-descending order.

-----Input-----

The input consists of a single line of space-separated integers. The first number is n (1 ≤ n ≤ 10) — the size of the array. The following n numbers are the elements of the array (1 ≤ a_{i} ≤ 100).

-----Output-----

Output space-separated elements of the sorted array.

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

Output
1 2 3

-----Note-----

Remember, this is a very important feature, and you have to make sure the customers appreciate it!

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

l = list(map(int, input().split()))
n = l[0]
del(l[0])
a = 0
for i in range(10**7):
  a += 1
# for i in range(n):
#   l[i] = str(l[i])
l.sort()
print(*l)


I found an interesting problem on https://codeforces.com/problemset/problem/784/G:
In this problem you will write a simple generator of Brainfuck (https://en.wikipedia.org/wiki/Brainfuck) calculators.

You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of evaluating this expression.

We use a fairly standard Brainfuck interpreter for checking the programs:

 30000 memory cells.

 memory cells store integers from 0 to 255 with unsigned 8-bit wraparound.

 console input (, command) is not supported, but it's not needed for this problem.

-----Input-----

The only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive. The calculations result is guaranteed to be an integer between 0 and 255, inclusive (results of intermediary calculations might be outside of these boundaries).

-----Output-----

Output a Brainfuck program which, when executed, will print the result of evaluating this expression. The program must be at most 5000000 characters long (including the non-command characters), and its execution must be complete in at most 50000000 steps.

-----Examples-----
Input
2+3

Output
++>
+++>
<[<+>-]<
++++++++++++++++++++++++++++++++++++++++++++++++.

Input
9-7

Output
+++++++++>
+++++++>
<[<->-]<
++++++++++++++++++++++++++++++++++++++++++++++++.

-----Note-----

You can download the source code of the Brainfuck interpreter by the link http://assets.codeforces.com/rounds/784/bf.cpp. We use this code to interpret outputs.

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

import re

s = input()
ops = re.split('([+-])', s)
assert len(ops) % 2 == 1
ops = ['+'] + ops

total = 0
for i in range(0, len(ops), 2):
    if ops[i] == '+':
        total += int(ops[i+1])
    elif ops[i] == '-':
        total -= int(ops[i+1])
    else:
        assert False

for b in bytes(str(total), 'ascii'):
    print('+' * b + '.>')


I found an interesting problem on https://codeforces.com/problemset/problem/785/A:
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:

  Tetrahedron. Tetrahedron has 4 triangular faces.  Cube. Cube has 6 square faces.  Octahedron. Octahedron has 8 triangular faces.  Dodecahedron. Dodecahedron has 12 pentagonal faces.  Icosahedron. Icosahedron has 20 triangular faces.

All five kinds of polyhedrons are shown on the picture below:

 [Image]

Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.

Each of the following n lines of the input contains a string s_{i} — the name of the i-th polyhedron in Anton's collection. The string can look like this:

  "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.  "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.  "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.  "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.  "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.

-----Output-----

Output one number — the total number of faces in all the polyhedrons in Anton's collection.

-----Examples-----
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron

Output
42

Input
3
Dodecahedron
Octahedron
Octahedron

Output
28

-----Note-----

In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.

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

n = int(str(input()).strip())
d = {'Tetrahedron': 4, 'Cube': 6, 'Octahedron': 8, 'Dodecahedron': 12, 'Icosahedron': 20}
ans = 0
for _ in range(n):
    ans += d[str(input()).strip()]
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/785/B:
Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.

Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l_{1, }i, r_{1, }i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l_{2, }i, r_{2, }i).

Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.

The distance between periods (l_1, r_1) and (l_2, r_2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l_1 ≤ i ≤ r_1 and l_2 ≤ j ≤ r_2. In particular, when the periods intersect, the distance between them is 0.

Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number!

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes.

Each of the following n lines of the input contains two integers l_{1, }i and r_{1, }i (1 ≤ l_{1, }i ≤ r_{1, }i ≤ 10^9) — the i-th variant of a period of time when Anton can attend chess classes.

The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes.

Each of the following m lines of the input contains two integers l_{2, }i and r_{2, }i (1 ≤ l_{2, }i ≤ r_{2, }i ≤ 10^9) — the i-th variant of a period of time when Anton can attend programming classes.

-----Output-----

Output one integer — the maximal possible distance between time periods.

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

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

n = int(input())
lc = 0
rc = 10 ** 9 + 1
for i in range(n):
    l, r = map(int, input().split())
    lc = max(l, lc)
    rc = min(r, rc)
m = int(input())
lp = 0
rp = 10 ** 9 + 1
for i in range(m):
    l, r = map(int, input().split())
    lp = max(l, lp)
    rp = min(r, rp)
print(max(0, lp - rc, lc - rp))


I found an interesting problem on https://codeforces.com/problemset/problem/785/C:
Anton likes to listen to fairy tales, especially when Danik, Anton's best friend, tells them. Right now Danik tells Anton a fairy tale:

"Once upon a time, there lived an emperor. He was very rich and had much grain. One day he ordered to build a huge barn to put there all his grain. Best builders were building that barn for three days and three nights. But they overlooked and there remained a little hole in the barn, from which every day sparrows came through. Here flew a sparrow, took a grain and flew away..."

More formally, the following takes place in the fairy tale. At the beginning of the first day the barn with the capacity of n grains was full. Then, every day (starting with the first day) the following happens:  m grains are brought to the barn. If m grains doesn't fit to the barn, the barn becomes full and the grains that doesn't fit are brought back (in this problem we can assume that the grains that doesn't fit to the barn are not taken into account).  Sparrows come and eat grain. In the i-th day i sparrows come, that is on the first day one sparrow come, on the second day two sparrows come and so on. Every sparrow eats one grain. If the barn is empty, a sparrow eats nothing.

Anton is tired of listening how Danik describes every sparrow that eats grain from the barn. Anton doesn't know when the fairy tale ends, so he asked you to determine, by the end of which day the barn will become empty for the first time. Help Anton and write a program that will determine the number of that day!

-----Input-----

The only line of the input contains two integers n and m (1 ≤ n, m ≤ 10^18) — the capacity of the barn and the number of grains that are brought every day.

-----Output-----

Output one integer — the number of the day when the barn will become empty for the first time. Days are numbered starting with one.

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

Output
4

Input
8 1

Output
5

-----Note-----

In the first sample the capacity of the barn is five grains and two grains are brought every day. The following...

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

n, m = map(int, input().split())
tl = m
tr = n
while tr - tl > 1:
    mid = (tr + tl) // 2
    val = (mid - m) * (mid - m + 1) // 2
    bef = (mid - m) * (mid - m - 1) // 2
    if val >= n or n - bef <= mid:
        tr = mid
    else:
        tl = mid
print (tr)


I found an interesting problem on https://codeforces.com/problemset/problem/785/D:
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).

On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:

  It is not empty (that is n ≠ 0).  The length of the sequence is even.  First $\frac{n}{2}$ charactes of the sequence are equal to "(".  Last $\frac{n}{2}$ charactes of the sequence are equal to ")".

For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.

Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.

Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 10^9 + 7.

Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!

-----Input-----

The only line of the input contains a string s — the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.

-----Output-----

Output one number — the answer for the task modulo 10^9 + 7.

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

Output
6

Input
()()()

Output
7

Input
)))

Output
0

-----Note-----

In the first sample the following subsequences are possible:

  If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".  If we delete...

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

t = input()
n, m = len(t) + 1, 1000000007
a, b = 0, t.count(')') - 1
f = [1] * n
for i in range(2, n): f[i] = i * f[i - 1] % m
g = [pow(q, m - 2, m) for q in f]
s = 0
for q in t:
    if b < 0: break
    if q == '(':
        a += 1
        s += f[a + b] * g[a] * g[b]
    else: b -= 1
print(s % m)


I found an interesting problem on https://codeforces.com/problemset/problem/787/A:
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....  [Image]

The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.

-----Input-----

The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).

The second line contains two integers c and d (1 ≤ c, d ≤ 100).

-----Output-----

Print the first time Rick and Morty will scream at the same time, or  - 1 if they will never scream at the same time.

-----Examples-----
Input
20 2
9 19

Output
82

Input
2 1
16 12

Output
-1

-----Note-----

In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.

In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.

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

line = input()
a, b = line.split()
a, b = int(a), int(b)

line = input()
c, d = line.split()
c, d = int(c), int(d)

x = b

x_count = 1

y = d
y_count = 1
while y != x and y <= 10100 and x <= 10100:
    if y > x:
        x = b + (x_count * a)
        x_count = x_count + 1
    else:
        y = d + (y_count * c)
        y_count = y_count + 1

if y == x:
    print(y)
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/787/B:
Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them.

There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.

Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility). [Image]

Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world).

Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2^{n} possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.

-----Input-----

The first line of input contains two integers n and m (1 ≤ n, m ≤ 10^4) — number of universes and number of groups respectively.

The next m lines contain the information about the groups. i-th of them first contains an integer k (number of times someone joined i-th group, k > 0) followed by k integers v_{i}, 1, v_{i}, 2, ..., v_{i}, k. If v_{i}, j is negative, it means that Rick from universe number  - v_{i}, j has joined this group and otherwise it means that Morty from universe number v_{i}, j has joined it.

Sum of k for all groups does not exceed 10^4.

-----Output-----

In a single line print the answer to Summer's question. Print "YES" if...

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

import sys

def solve():
    n, m = map(int, input().split())

    for i in range(m):
        k, *a = [int(j) for j in input().split()]
        a.sort(key=abs)
        # print(a)

        if k == 1:
            print('YES')
            return

        for j in range(len(a) - 1):
            if a[j] == -a[j + 1]:
                break
        else:
            print('YES')
            return

    print('NO')

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def __starting_point():
    solve()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/788/A:
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:$f(l, r) = \sum_{i = l}^{r - 1}|a [ i ] - a [ i + 1 ]|\cdot(- 1)^{i - l}$

In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.

-----Input-----

The first line contains single integer n (2 ≤ n ≤ 10^5) — the size of the array a.

The second line contains n integers a_1, a_2, ..., a_{n} (-10^9 ≤ a_{i} ≤ 10^9) — the array elements.

-----Output-----

Print the only integer — the maximum value of f.

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

Output
3
Input
4
1 5 4 7

Output
6

-----Note-----

In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].

In the second case maximal value of f is reachable only on the whole array.

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

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

def sign(n):
    return [1, -1][n % 2]

b1 = [abs(a[i]-a[i-1]) for i in range(1, len(a))]
b1 = [sign(i)*b1[i] for i in range(len(b1))]
b2 = [-x for x in b1]

max_ending_here = b1[0]
max_so_far = b1[0]

for i, x in enumerate(b1):
    if i == 0:
        continue

    if i % 2 == 1:
        max_ending_here += x
    else:
        if x > max_ending_here + x:
            max_ending_here = x
        else:
            max_ending_here += x

    max_so_far = max(max_so_far, max_ending_here)

b1 = b2

max_ending_here = b1[0]
max_so_far2 = b1[0]

for i, x in enumerate(b1):
    if i == 0:
        continue

    if i % 2 == 0:
        max_ending_here += x
    else:
        if x > max_ending_here + x:
            max_ending_here = x
        else:
            max_ending_here += x

    max_so_far2 = max(max_so_far2, max_ending_here)

print(max(max_so_far, max_so_far2))


I found an interesting problem on https://codeforces.com/problemset/problem/788/C:
Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration $\frac{a_{i}}{1000}$. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration $\frac{n}{1000}$. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass.

Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well.

Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration $\frac{n}{1000}$. Assume that the friends have unlimited amount of each Coke type.

-----Input-----

The first line contains two integers n, k (0 ≤ n ≤ 1000, 1 ≤ k ≤ 10^6) — carbon dioxide concentration the friends want and the number of Coke types.

The second line contains k integers a_1, a_2, ..., a_{k} (0 ≤ a_{i} ≤ 1000) — carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration.

-----Output-----

Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration $\frac{n}{1000}$, or -1 if it is impossible.

-----Examples-----
Input
400 4
100 300 450 500

Output
2

Input
50 2
100 25

Output
3

-----Note-----

In the first sample case, we can achieve concentration $\frac{400}{1000}$ using one liter of Coke of types $\frac{300}{1000}$ and $\frac{500}{1000}$: $\frac{300 + 500}{1000 + 1000} = \frac{400}{1000}$.

In the second case, we can achieve concentration $\frac{50}{1000}$ using two liters of $\frac{25}{1000}$ type and one liter of $\frac{100}{1000}$ type: $\frac{25 + 25 + 100}{3 \cdot 1000} = \frac{50}{1000}$.

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

from collections import deque
n, k = list(map(int, input().split()))
d = set(int(x)-n for x in input().split())

q = deque()
q.append(0)

visited = {i : False for i in range(-1000, 1001)}
dist = {i : 0 for i in range(-1000, 1001)}

ans = -1
visited[0] = True
found = False
while q:
    u = q.popleft()
    for i in d:
    	if i + u == 0:

    		ans = dist[u] + 1
    		found = True
    		break
    	if i + u <= 1000 and i + u >= -1000 and not visited[i + u]:
    		visited[i + u] = True
    		dist[i + u] = dist[u] + 1
    		q.append(i + u)

    if found:
    	break

print (ans)


I found an interesting problem on https://codeforces.com/problemset/problem/789/A:
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.

She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are w_{i} pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.

Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^9) — the number of different pebble types and number of pebbles Anastasia can place in one pocket.

The second line contains n integers w_1, w_2, ..., w_{n} (1 ≤ w_{i} ≤ 10^4) — number of pebbles of each type.

-----Output-----

The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.

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

Output
3

Input
5 4
3 1 8 9 7

Output
5

-----Note-----

In the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.

Optimal sequence of actions in the second sample case:   In the first day Anastasia collects 8 pebbles of the third type.  In the second day she collects 8 pebbles of the fourth type.  In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.  In the fourth day she collects 7 pebbles of the fifth type.  In the fifth day she collects 1 pebble of the second type.

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

n, k = map(int, input().split())
days = 0
w = list(map(int, input().split()))
for wi in w:
    days += (wi - 1) // k + 1
print((days - 1) // 2 + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/789/B:
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.

You are given geometric progression b defined by two integers b_1 and q. Remind that a geometric progression is a sequence of integers b_1, b_2, b_3, ..., where for each i > 1 the respective term satisfies the condition b_{i} = b_{i} - 1·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b_1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a_1, a_2, ..., a_{m}, and an integer l.

Masha writes all progression terms one by one onto the board (including repetitive) while condition |b_{i}| ≤ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.

But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.

-----Input-----

The first line of input contains four integers b_1, q, l, m (-10^9 ≤ b_1, q ≤ 10^9, 1 ≤ l ≤ 10^9, 1 ≤ m ≤ 10^5) — the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively.

The second line contains m distinct integers a_1, a_2, ..., a_{m} (-10^9 ≤ a_{i} ≤ 10^9) — numbers that will never be written on the board.

-----Output-----

Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.

-----Examples-----
Input
3 2 30 4
6 14 25 48

Output
3
Input
123 1 2143435 4
123 11 -5453 141245

Output
0
Input
123 1 2143435 4
54343 -13 6 124

Output
inf

-----Note-----

In the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because...

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

import sys

def solve():
    b1, q, L, m = map(int, input().split())
    a = [int(i) for i in input().split()]

    a = set(a)

    if b1 == 0:
        print(0 if b1 in a else 'inf')
        return

    if q == 1:
        if abs(b1) > L or b1 in a:
            print(0)
        else:
            print('inf')
    elif q == -1:
        if abs(b1) > L or (b1 in a and -b1 in a):
            print(0)
        else:
            print('inf')
    elif q == 0:
        if abs(b1) > L:
            print(0)
        elif 0 in a:
            print(0 if b1 in a else 1)
        else:
            print('inf')
    else:
        b = b1
        ans = 0

        while abs(b) <= L:
            if b not in a:
                ans += 1
            b *= q

        print(ans)

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def __starting_point():
    solve()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/791/A:
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.

Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.

Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.

After how many full years will Limak become strictly larger (strictly heavier) than Bob?

-----Input-----

The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 10) — the weight of Limak and the weight of Bob respectively.

-----Output-----

Print one integer, denoting the integer number of years after which Limak will become strictly larger than Bob.

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

Output
2

Input
4 9

Output
3

Input
1 1

Output
1

-----Note-----

In the first sample, Limak weighs 4 and Bob weighs 7 initially. After one year their weights are 4·3 = 12 and 7·2 = 14 respectively (one weight is tripled while the other one is doubled). Limak isn't larger than Bob yet. After the second year weights are 36 and 28, so the first weight is greater than the second one. Limak became larger than Bob after two years so you should print 2.

In the second sample, Limak's and Bob's weights in next years are: 12 and 18, then 36 and 36, and finally 108 and 72 (after three years). The answer is 3. Remember that Limak wants to be larger than Bob and he won't be satisfied with equal weights.

In the third sample, Limak becomes larger than Bob after the first year. Their weights will be 3 and 2 then.

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

def inl():
    l = list(map(int , input().split()))
    return l

x , y = map(int , input().split())
l = 0
while 1:
    x *= 3
    y *= 2
    l += 1
    if(x > y):
        print(l)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/792/A:
There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a_1, a_2, ..., a_{n}. All coordinates are pairwise distinct.

It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.

It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs.

Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.

-----Input-----

The first line contains one integer number n (2 ≤ n ≤ 2·10^5).

The second line contains n integer numbers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9). All numbers a_{i} are pairwise distinct.

-----Output-----

Print two integer numbers — the minimal distance and the quantity of pairs with this distance.

-----Examples-----
Input
4
6 -3 0 4

Output
2 1

Input
3
-2 0 2

Output
2 2

-----Note-----

In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance.

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

n = int(input())
a = list(map(int, input().split()))
a.sort()
m = a[1] - a[0]
cnt = 0
for i in range(1, len(a)):
    if a[i] - a[i - 1] == m:
        cnt += 1
    elif a[i] - a[i - 1] < m:
        m = a[i] - a[i - 1]
        cnt = 1
ans = str(m) + " " + str(cnt)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/792/B:
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out a_{i} people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.

For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and a_{i} = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.

You have to write a program which prints the number of the child to be eliminated on every step.

-----Input-----

The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1).

The next line contains k integer numbers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.

-----Examples-----
Input
7 5
10 4 11 4 1

Output
4 2 5 6 1

Input
3 2
2 5

Output
3 2

-----Note-----

Let's consider first example:   In the first step child 4 is eliminated, child 5 becomes the leader.  In the second step child 2 is eliminated, child 3 becomes the leader.  In the third step child 5 is eliminated, child 6 becomes the leader.  In the fourth step child 6 is eliminated, child 7 becomes the leader.  In the final step child 1 is eliminated, child 3 becomes the leader.

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

n,k = list(map(int,input().split()))
a = [int(x) for x in input().split()]
v = [i for i in range(1,n+1)]
val = 0
ans = ""
for i in a:
	i %= len(v)
	val += i
	if val>=len(v): val -= len(v)
	ans += str(v[val]) + ' '
	del v[val]

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/792/D:
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.

In the picture you can see a complete binary tree with n = 15. [Image]

Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.

You have to write a program that for given n answers q queries to the tree.

Each query consists of an integer number u_{i} (1 ≤ u_{i} ≤ n) and a string s_{i}, where u_{i} is the number of vertex, and s_{i} represents the path starting from this vertex. String s_{i} doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from s_{i} have to be processed from left to right, considering that u_{i} is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by s_{i} ends.

For example, if u_{i} = 4 and s_{i} = «UURL», then the answer is 10.

-----Input-----

The first line contains two integer numbers n and q (1 ≤ n ≤ 10^18, q ≥ 1). n is such that n + 1 is a power of 2.

The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains u_{i} (1 ≤ u_{i} ≤ n), the second contains...

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

n, q = list(map(int,input().split()))
par = n // 2 + 1
par = len(list(bin(par)[2:]))
for i in range(q):
    ui = int(input())
    si = input()
    temp = bin(ui)[2:]
    now = len(temp)
    num = list((par - now) * "0" + temp)
    now = par - now
    for i in range(len(num)):
        if str(num[i]) == '1':
            now = i
    for i in si:
        if i == "U":
            if now == 0:
                continue
            num[now] = 0
            now -= 1
            num[now] = 1
        elif i == "L":
            if str(num[-1]) == '1':
                continue
            num[now] = 0
            now += 1
            num[now] = 1
        else:
            if str(num[-1]) == '1':
                continue
            now += 1
            num[now] = 1
    for i in range(par):
        num[i] = str(num[i])
    print(int("".join(num),2))


I found an interesting problem on https://codeforces.com/problemset/problem/792/E:
There are n boxes with colored balls on the table. Colors are numbered from 1 to n. i-th box contains a_{i} balls, all of which have color i. You have to write a program that will divide all balls into sets such that:  each ball belongs to exactly one of the sets,  there are no empty sets,  there is no set containing two (or more) balls of different colors (each set contains only balls of one color),  there are no two sets such that the difference between their sizes is greater than 1.

Print the minimum possible number of sets.

-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 500).

The second line contains n integer numbers a_1, a_2, ... , a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

Print one integer number — the minimum possible number of sets.

-----Examples-----
Input
3
4 7 8

Output
5

Input
2
2 7

Output
4

-----Note-----

In the first example the balls can be divided into sets like that: one set with 4 balls of the first color, two sets with 3 and 4 balls, respectively, of the second color, and two sets with 4 balls of the third color.

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

# Returns the number of coins that is necessary for paying the amount
# with the two types of coins that have value of coin and coin + 1
def pay(coin, amount):
    if amount // coin < amount % coin:
        return -1;
    if amount < coin * (coin + 1):
        return amount // coin
    return (amount - 1) // (coin + 1) + 1;

def pay_all(coin):
    sum = 0
    for i in range(n):
        p = pay(coin, a[i])
        if p == -1:
            return -1
        sum += p
    return sum

n = int(input())
a = list(map(int, input().split()))
amin = min(a)
coin = amin
k = 1
p = -1
while p == -1:
    p = pay_all(coin)
    if p == -1 and amin % coin == 0:
        p = pay_all(coin - 1)
    k += 1
    coin = amin // k
print(p)


I found an interesting problem on https://codeforces.com/problemset/problem/792/F:
Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.

Vova's character can learn new spells during the game. Every spell is characterized by two values x_{i} and y_{i} — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage x and mana cost y for z seconds, then he will deal x·z damage and spend y·z mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously.

Also Vova can fight monsters. Every monster is characterized by two values t_{j} and h_{j} — monster kills Vova's character in t_{j} seconds and has h_{j} health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones.

Vova's character kills a monster, if he deals h_{j} damage to it in no more than t_{j} seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in t_{j} seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight.

You have to write a program which can answer two types of queries:

  1 x y — Vova's character learns new spell which deals x damage per second and costs y mana per second.  2 t h — Vova fights the monster which kills his character in t seconds and has h health points.

Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game.

For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.

-----Input-----

The first line contains two...

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

#!/usr/bin/env python3

# solution after hint
# (instead of best hit/mana spell store convex hull of spells)
# O(n^2) instead of O(n log n)

[q, m] = list(map(int, input().strip().split()))
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]

mod = 10**6

j = 0
spell_chull = [(0, 0)]  # lower hull _/

def is_right(xy0, xy1, xy):
	(x0, y0) = xy0
	(x1, y1) = xy1
	(x, y) = xy
	return (x0 - x) * (y1 - y) >= (x1 - x) * (y0 - y)

def in_chull(x, y):
	i = 0
	if x > spell_chull[-1][0]:
		return False
	while spell_chull[i][0] < x:
		i += 1
	if spell_chull[i][0] == x:
		return spell_chull[i][1] <= y
	else:
		return is_right(spell_chull[i - 1], spell_chull[i], (x, y))

def add_spell(x, y):
	nonlocal spell_chull
	if in_chull(x, y):
		return
	i_left = 0
	while i_left < len(spell_chull) - 1 and not is_right(spell_chull[i_left + 1], spell_chull[i_left], (x, y)):
		i_left += 1
	i_right = i_left + 1
	while i_right < len(spell_chull) - 1 and is_right(spell_chull[i_right + 1], spell_chull[i_right], (x, y)):
		i_right += 1
	if i_right == len(spell_chull) - 1 and x >= spell_chull[-1][0]:
		i_right += 1
	spell_chull = spell_chull[:i_left + 1] + [(x, y)] + spell_chull[i_right:]

for i, qi in enumerate(qis):
	(k, a, b) = qi
	x = (a + j) % mod + 1
	y = (b + j) % mod + 1
	if k == 1:
		add_spell(x, y)
	else:  #2
		if in_chull(y / x, m / x):
			print ('YES')
			j = i + 1
		else:
			print ('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/796/A:
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us.

 [Image]

The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: house i and house i + 1 (1 ≤ i < n) are exactly 10 meters away. In this village, some houses are occupied, and some are not. Indeed, unoccupied houses can be purchased.

You will be given n integers a_1, a_2, ..., a_{n} that denote the availability and the prices of the houses. If house i is occupied, and therefore cannot be bought, then a_{i} equals 0. Otherwise, house i can be bought, and a_{i} represents the money required to buy it, in dollars.

As Zane has only k dollars to spare, it becomes a challenge for him to choose the house to purchase, so that he could live as near as possible to his crush. Help Zane determine the minimum distance from his crush's house to some house he can afford, to help him succeed in his love.

-----Input-----

The first line contains three integers n, m, and k (2 ≤ n ≤ 100, 1 ≤ m ≤ n, 1 ≤ k ≤ 100) — the number of houses in the village, the house where the girl lives, and the amount of money Zane has (in dollars), respectively.

The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 100) — denoting the availability and the prices of the houses.

It is guaranteed that a_{m} = 0 and that it is possible to purchase some house with no more than k dollars.

-----Output-----

Print one integer — the minimum distance, in meters, from the house where the girl Zane likes lives to the house Zane can buy.

-----Examples-----
Input
5 1 20
0 27 32 21 19

Output
40
Input
7 3 50
62 0 0 0 99 33 22

Output
30
Input
10 5 100
1 0 1 0 0 0 0 0 1 1

Output
20

-----Note-----

In the first sample, with k = 20 dollars, Zane can buy only house 5. The distance from house m = 1 to house 5 is 10 + 10 + 10 + 10 = 40 meters.

In the second sample, Zane can buy houses 6 and...

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

import sys

def solve():
    n, m, k = map(int, input().split())
    m = m - 1
    a = [int(i) for i in input().split()]

    min_d = 10**9

    for i in range(n):
        if 0 < a[i] <= k:
            min_d = min(min_d, abs((m - i)) * 10)

    ans = min_d
    print(ans)

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def __starting_point():
    solve()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/796/B:
Zane the wizard is going to perform a magic show shuffling the cups.

There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.

The problematic bone is initially at the position x = 1. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions x = u_{i} and x = v_{i}. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.

Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at x = 4 and the one at x = 6, they will not be at the position x = 5 at any moment during the operation. [Image]

Zane’s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.

-----Input-----

The first line contains three integers n, m, and k (2 ≤ n ≤ 10^6, 1 ≤ m ≤ n, 1 ≤ k ≤ 3·10^5) — the number of cups, the number of holes on the table, and the number of swapping operations, respectively.

The second line contains m distinct integers h_1, h_2, ..., h_{m} (1 ≤ h_{i} ≤ n) — the positions along the x-axis where there is a hole on the table.

Each of the next k lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — the positions of the cups to be swapped.

-----Output-----

Print one integer — the final position along the x-axis of the bone.

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

Output
1
Input
5 1 2
2
1 2
2 4

Output
2

-----Note-----

In...

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

n, m, k = [int(x) for x in input().strip().split(' ')]
holes = set([int(x) for x in input().strip().split(' ')])
bone = 1
fall = bone in holes
i = 0
while i < k and not fall:
    a, b = [int(x) for x in input().strip().split(' ')]
    if a == bone:
        bone = b
    elif b == bone:
        bone = a
    fall = bone in holes
    i += 1

print(bone)


I found an interesting problem on https://codeforces.com/problemset/problem/796/C:
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. [Image]

There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength a_{i}.

Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.

When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.

To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met:  Bank x is online. That is, bank x is not hacked yet.  Bank x is neighboring to some offline bank.  The strength of bank x is less than or equal to the strength of Inzane's computer.

Determine the minimum strength of the computer Inzane needs to hack all the banks.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 3·10^5) — the total number of banks.

The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — the strengths of the banks.

Each of the next n - 1 lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — meaning that there is a wire directly connecting banks u_{i} and v_{i}.

It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate...

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

import sys

def solve():
    n = int(sys.stdin.readline().rstrip())
    a = [int(i) for i in sys.stdin.readline().split()]
    Adj = [[] for i in range(n)]

    for i in range(n - 1):
        u, v = map(int, sys.stdin.readline().split())
        u, v = u-1, v-1
        Adj[u].append(v)
        Adj[v].append(u)

    max_v = max(a)
    max_n = a.index(max_v)
    num_m = sum(ai == max_v for ai in a)

    if num_m == 1:
        ans = max_v

        rinsetu = [False] * n

        for u in Adj[max_n]:
            rinsetu[u] = True

        rinsetu[max_n] = True

        for u in range(n):
            if rinsetu[u]:
                continue
            if a[u] == max_v - 1:
                ans = max_v + 1
                break
    else:
        for u in range(n):
            cnt = 0

            if a[u] == max_v:
                cnt += 1

            for v in Adj[u]:
                if a[v] == max_v:
                    cnt += 1

            if cnt == num_m:
                ans = max_v + 1
                break
        else:
            ans = max_v + 2

    print(ans)

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def __starting_point():
    solve()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/796/D:
Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own.

Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be possible to reach a police station by traveling at most d kilometers along the roads. [Image]

There are n cities in the country, numbered from 1 to n, connected only by exactly n - 1 roads. All roads are 1 kilometer long. It is initially possible to travel from a city to any other city using these roads. The country also has k police stations located in some cities. In particular, the city's structure satisfies the requirement enforced by the previously mentioned law. Also note that there can be multiple police stations in one city.

However, Zane feels like having as many as n - 1 roads is unnecessary. The country is having financial issues, so it wants to minimize the road maintenance cost by shutting down as many roads as possible.

Help Zane find the maximum number of roads that can be shut down without breaking the law. Also, help him determine such roads.

-----Input-----

The first line contains three integers n, k, and d (2 ≤ n ≤ 3·10^5, 1 ≤ k ≤ 3·10^5, 0 ≤ d ≤ n - 1) — the number of cities, the number of police stations, and the distance limitation in kilometers, respectively.

The second line contains k integers p_1, p_2, ..., p_{k} (1 ≤ p_{i} ≤ n) — each denoting the city each police station is located in.

The i-th of the following n - 1 lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — the cities directly connected by the road with index i.

It is guaranteed that it is possible to travel from one city to any other city using only the roads. Also, it is possible from any city to reach a police station within d kilometers.

-----Output-----

In the first line, print one integer s that denotes the maximum number of roads that can be shut down.

In the...

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

import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
from functools import lru_cache   #use @lru_cache(None)
if os.path.exists('in.txt'): sys.stdin=open('in.txt','r')
if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w')
#
def input(): return sys.stdin.readline()
def mapi(arg=0): return map(int if arg==0 else str,input().split())
#------------------------------------------------------------------

n,k,d = mapi()
plc = list(mapi())
gr = defaultdict(list)
for i in range(1,n):
    u,v = mapi()
    gr[u].append([v,i])
    gr[v].append([u,i])
q = deque()
for i in plc:
    q.append((i,0))
vis = {}
res = [0]*(n+1)
while q:
    tmp,par = q.popleft()
    if tmp in vis:
        continue
    vis[tmp] = 1
    for item in gr[tmp]:
        if item[0] != par:
            if item[0] in vis:
                res[item[1]] = 1
            else:
                q.append((item[0],tmp))
cnt = 0
ans = []
for i in range(1,n+1):
    if res[i]==1:
        cnt+=1
        ans.append(i)
print(cnt)
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/797/B:
You are given sequence a_1, a_2, ..., a_{n} of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.

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

You should write a program which finds sum of the best subsequence.

-----Input-----

The first line contains integer number n (1 ≤ n ≤ 10^5).

The second line contains n integer numbers a_1, a_2, ..., a_{n} ( - 10^4 ≤ a_{i} ≤ 10^4). The sequence contains at least one subsequence with odd sum.

-----Output-----

Print sum of resulting subseqeuence.

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

Output
3

Input
3
2 -5 -3

Output
-1

-----Note-----

In the first example sum of the second and the fourth elements is 3.

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

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

oc=0
ps=0
pmo=1e6
nmo=-1e6

for x in a:
    if x>0:
        ps+=x
    if x%2==1 and x>0 and pmo>x:
        pmo=x
    if x%2==1 and x>0:
        oc+=1
    if x%2==1 and x<0 and nmo<x:
        nmo=x

if oc%2==1:
    print(ps)
else:
    print(max(ps-pmo,ps+nmo))


I found an interesting problem on https://codeforces.com/problemset/problem/797/C:
Petya recieved a gift of a string s with length up to 10^5 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game has two possible moves:  Extract the first character of s and append t with this character.  Extract the last character of t and append u with this character.

Petya wants to get strings s and t empty and string u lexicographically minimal.

You should write a program that will help Petya win the game.

-----Input-----

First line contains non-empty string s (1 ≤ |s| ≤ 10^5), consisting of lowercase English letters.

-----Output-----

Print resulting string u.

-----Examples-----
Input
cab

Output
abc

Input
acdb

Output
abdc

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

def s_has_smaller(s_cnt_local, c):
    for i in range(ord('a'), ord(c)):
        if s_cnt_local[i] > 0:
            return True
    return False

s = list(input())
s.reverse()

t = []
u = []

s_cnt = [0] * (ord('z')+1)
for x in s:
    s_cnt[ord(x)] += 1

while s or t:
    # print('+'*10)
    # print(s)
    # print(t)
    # print(u)
    # print(s_cnt)
    # print(t_cnt)
    if not s:
        while t:
            u.append(t.pop())
    elif not t:
        x = s.pop()
        s_cnt[ord(x)] -= 1
        t.append(x)
    else:
        if s_has_smaller(s_cnt, t[-1]):
            x = s.pop()
            s_cnt[ord(x)] -= 1
            t.append(x)
        else:
            x = t.pop()
            u.append(x)

print("".join(u))


I found an interesting problem on https://codeforces.com/problemset/problem/797/D:
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:  Set pointer to the root of a tree.  Return success if the value in the current vertex is equal to the number you are looking for  Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for  Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for  Return fail if you try to go to the vertex that doesn't exist

Here is the pseudo-code of the described algorithm:

bool find(TreeNode t, int x) {

    if (t == null)

        return false;

    if (t.value == x)

        return true;

    if (x < t.value)

        return find(t.left, x);

    else

        return find(t.right, x);

}

find(root, x);

The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.

Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.

If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.

-----Input-----

First line contains integer number n (1 ≤ n ≤ 10^5) — number of vertices in the tree.

Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 10^9) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number  - 1 is set instead. Note that different...

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

#!/usr/bin/env python3

# solution after hint:(
# though it was not necessary

# reduced recursion version

n = int(input().strip())
vlrs = [tuple(map(int, input().strip().split())) for _ in range(n)]
# shift numeration
vlrs = [(v, l - (0 if l < 0 else 1), r - (0 if r < 0 else 1)) for v, l, r in vlrs]

isroot = [True for _ in range(n)]
for v, l, r in vlrs:
	if l != -1:
		isroot[l] = False
	if r != -1:
		isroot[r] = False

root = isroot.index(True)
vs = [v for v, l, r in vlrs]
vmin = min(vs)
vmax = max(vs)

found = set()
def DFS(U, vl, vr):
	while vlrs[U].count(-1) == 1:
		v, L, R = vlrs[U]
		if vl <= v <= vr:
			found.add(v)
		if L != -1:
			U, vl, vr = L, vl, min(v, vr)
		else:
			U, vl, vr = R, max(v, vl), vr
	v, L, R = vlrs[U]
	if vl <= v <= vr:
		found.add(v)
	if L != -1 and R != -1:
		DFS(L, vl, min(v, vr))
		DFS(R, max(v, vl), vr)

DFS(root, vmin, vmax)

res = sum(1 for v in vs if v not in found)

print (res)


I found an interesting problem on https://codeforces.com/problemset/problem/799/A:
In some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take d minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven.

Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get n cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.

-----Input-----

The only line contains four integers n, t, k, d (1 ≤ n, t, k, d ≤ 1 000) — the number of cakes needed, the time needed for one oven to bake k cakes, the number of cakes baked at the same time, the time needed to build the second oven.

-----Output-----

If it is reasonable to build the second oven, print "YES". Otherwise print "NO".

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

Output
YES

Input
8 6 4 6

Output
NO

Input
10 3 11 4

Output
NO

Input
4 2 1 4

Output
YES

-----Note-----

In the first example it is possible to get 8 cakes in 12 minutes using one oven. The second oven can be built in 5 minutes, so after 6 minutes the first oven bakes 4 cakes, the second oven bakes 4 more ovens after 11 minutes. Thus, it is reasonable to build the second oven.

In the second example it doesn't matter whether we build the second oven or not, thus it takes 12 minutes to bake 8 cakes in both cases. Thus, it is unreasonable to build the second oven.

In the third example the first oven bakes 11 cakes in 3 minutes, that is more than needed 10. It is unreasonable to build the second oven, because its building takes more time that baking the needed number of cakes using the only oven.

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

n, t, k, d = list(map( int, input().split() ))
clk = 0
s = 0
while s < n:
  s += k
  clk += t
clk2 = 0
lb, ub = 0, int( 1e10 )
while lb <= ub:
  mid = lb + ub >> 1
  s = mid // t * k + max( 0, mid - d ) // t * k
  if s >= n:
    clk2 = mid
    ub = mid - 1
  else:
    lb = mid + 1

print( [ "NO", "YES" ][ clk > clk2 ] )


I found an interesting problem on https://codeforces.com/problemset/problem/799/D:
In one of the games Arkady is fond of the game process happens on a rectangular field. In the game process Arkady can buy extensions for his field, each extension enlarges one of the field sizes in a particular number of times. Formally, there are n extensions, the i-th of them multiplies the width or the length (by Arkady's choice) by a_{i}. Each extension can't be used more than once, the extensions can be used in any order.

Now Arkady's field has size h × w. He wants to enlarge it so that it is possible to place a rectangle of size a × b on it (along the width or along the length, with sides parallel to the field sides). Find the minimum number of extensions needed to reach Arkady's goal.

-----Input-----

The first line contains five integers a, b, h, w and n (1 ≤ a, b, h, w, n ≤ 100 000) — the sizes of the rectangle needed to be placed, the initial sizes of the field and the number of available extensions.

The second line contains n integers a_1, a_2, ..., a_{n} (2 ≤ a_{i} ≤ 100 000), where a_{i} equals the integer a side multiplies by when the i-th extension is applied.

-----Output-----

Print the minimum number of extensions needed to reach Arkady's goal. If it is not possible to place the rectangle on the field with all extensions, print -1. If the rectangle can be placed on the initial field, print 0.

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

Output
1

Input
3 3 3 3 5
2 3 5 4 2

Output
0

Input
5 5 1 2 3
2 2 3

Output
-1

Input
3 4 1 1 3
2 3 2

Output
3

-----Note-----

In the first example it is enough to use any of the extensions available. For example, we can enlarge h in 5 times using the second extension. Then h becomes equal 10 and it is now possible to place the rectangle on the field.

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

import sys

MAXV = 100010
d = [0] * MAXV

a, b, h, w, n = list(map(int,input().split()))

arr = input().split()

for it in range(n):
    arr[it] = int(arr[it])

# print(arr)
# print(a, b, h, w, n)

def solve(a, b, h, w, z, product, it):
    # print(">", a, b, h, w, z, product, it)
    k = 0
    if a % h:
        k = a // h + 1
    else:
        k = a // h

    if k <= z and (product // z) * w >= b:
        print(it)
        return

arr = sorted(arr)
arr = arr[::-1]
# print(arr)

d[1] = 1
solve(a, b, h, w, 1, 1, 0)
solve(a, b, w, h, 1, 1, 0)
product = 1
xxx = 0

for it in range(1, n + 1):
    # arr[it - 1] = int(arr[it - 1])
    product *= arr[it - 1]
    # print("=", arr[it - 1])

    for j in reversed(list(range(1, MAXV))):
        if not d[j]:
            continue

        x = j * arr[it - 1]
        # x = min(x, MAXV - 1)
        if x < MAXV:
            d[x] = 1
        else:
            if xxx:
                xxx = min(x, xxx)
            else:
                xxx = x
    if xxx:
        solve(a, b, h, w, xxx, product, it)
        solve(a, b, w, h, xxx, product, it)

    for j in range(MAXV):
        if d[j]:
            solve(a, b, h, w, j, product, it)
            solve(a, b, w, h, j, product, it)

print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/801/A:
Tonio has a keyboard with only two letters, "V" and "K".

One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximum number of times "VK" can appear as a substring (i. e. a letter "K" right after a letter "V") in the resulting string.

-----Input-----

The first line will contain a string s consisting only of uppercase English letters "V" and "K" with length not less than 1 and not greater than 100.

-----Output-----

Output a single integer, the maximum number of times "VK" can appear as a substring of the given string after changing at most one character.

-----Examples-----
Input
VK

Output
1

Input
VV

Output
1

Input
V

Output
0

Input
VKKKKKKKKKVVVVVVVVVK

Output
3

Input
KVKV

Output
1

-----Note-----

For the first case, we do not change any letters. "VK" appears once, which is the maximum number of times it could appear.

For the second case, we can change the second character from a "V" to a "K". This will give us the string "VK". This has one occurrence of the string "VK" as a substring.

For the fourth case, we can change the fourth character from a "K" to a "V". This will give us the string "VKKVKKKKKKVVVVVVVVVK". This has three occurrences of the string "VK" as a substring. We can check no other moves can give us strictly more occurrences.

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

import sys

def solve():
    s = [ch for ch in input()]
    ans = ''.join(s).count('VK')

    for i in range(len(s)):
        if s[i] == 'V':
            s[i] = 'K'

            tmp = ''.join(s).count('VK')
            ans = max(ans, tmp)

            s[i] = 'V'
        else:
            s[i] = 'V'

            tmp = ''.join(s).count('VK')
            ans = max(ans, tmp)

            s[i] = 'K'

    print(ans)

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def __starting_point():
    solve()
__starting_point()