I found an interesting problem on https://codeforces.com/problemset/problem/922/D:
Pushok the dog has been chasing Imp for a few hours already. $48$

Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.

While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and $t_{i} = s$ and $t_{j} = h$.

The robot is off at the moment. Imp knows that it has a sequence of strings t_{i} in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.

Help Imp to find the maximum noise he can achieve by changing the order of the strings.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of strings in robot's memory.

Next n lines contain the strings t_1, t_2, ..., t_{n}, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 10^5.

-----Output-----

Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.

-----Examples-----
Input
4
ssh
hs
s
hhhs

Output
18

Input
2
h
s

Output
1

-----Note-----

The optimal concatenation in the first sample is ssshhshhhs.

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

def key(x):
    try:
        return x.count('h') / x.count('s')
    except ZeroDivisionError:
        return 10**9

n = int(input())
t = ''.join(sorted((input() for _ in range(n)), key=key))

res, cnt = 0, 0
for ti in t:
    if ti == 's':
        cnt += 1
    if ti == 'h':
        res += cnt
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/923/A:
Alice and Bob begin their day with a quick game. They first choose a starting number X_0 ≥ 3 and try to reach one million by the process described below.

Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.

Formally, he or she selects a prime p < X_{i} - 1 and then finds the minimum X_{i} ≥ X_{i} - 1 such that p divides X_{i}. Note that if the selected prime p already divides X_{i} - 1, then the number does not change.

Eve has witnessed the state of the game after two turns. Given X_2, help her determine what is the smallest possible starting number X_0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.

-----Input-----

The input contains a single integer X_2 (4 ≤ X_2 ≤ 10^6). It is guaranteed that the integer X_2 is composite, that is, is not prime.

-----Output-----

Output a single integer — the minimum possible X_0.

-----Examples-----
Input
14

Output
6

Input
20

Output
15

Input
8192

Output
8191

-----Note-----

In the first test, the smallest possible starting number is X_0 = 6. One possible course of the game is as follows:   Alice picks prime 5 and announces X_1 = 10  Bob picks prime 7 and announces X_2 = 14.

In the second case, let X_0 = 15.   Alice picks prime 2 and announces X_1 = 16  Bob picks prime 5 and announces X_2 = 20.

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

from math import floor, sqrt
import bisect

import math

def rwh_primes2(n):
    # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Input n>=6, Returns a list of primes, 2 <= p < n """
    correction = (n%6>1)
    n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]
    sieve = [True] * (n//3)
    sieve[0] = False
    for i in range(int(n**0.5)//3+1):
      if sieve[i]:
        k=3*i+1|1
        sieve[      ((k*k)//3)      ::2*k]=[False]*((n//6-(k*k)//6-1)//k+1)
        sieve[(k*k+4*k-2*k*(i&1))//3::2*k]=[False]*((n//6-(k*k+4*k-2*k*(i&1))//6-1)//k+1)
    return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]]

k = int(input())

primes = rwh_primes2(k)

a = 1
p2 = 2
for i in primes[::-1]:
    if k%i == 0:
        p2 = i
        break

xx = range(k-p2+1, k+1)
#print(list(xx))
if p2>240:
    p1 = primes[bisect.bisect_left(primes, int(math.ceil(xx[0]/2)))]
    print(p1+1)
else:
    ans = k
    p1 = 1
    for x1 in xx:
        for i in primes[::-1]:

            if i >= x1:
                continue

            if x1 % i == 0:
                p1 = i
                break
        ans = min(ans, x1-p1+1)

    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/923/B:
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume V_{i} and put it in her garden.

Each day, every pile will shrink a little due to melting. More precisely, when the temperature on a given day is T_{i}, each pile will reduce its volume by T_{i}. If this would reduce the volume of a pile to or below zero, it disappears forever. All snow piles are independent of each other.

Note that the pile made on day i already loses part of its volume on the same day. In an extreme case, this may mean that there are no piles left at the end of a particular day.

You are given the initial pile sizes and the temperature on each day. Determine the total volume of snow melted on each day.

-----Input-----

The first line contains a single integer N (1 ≤ N ≤ 10^5) — the number of days.

The second line contains N integers V_1, V_2, ..., V_{N} (0 ≤ V_{i} ≤ 10^9), where V_{i} is the initial size of a snow pile made on the day i.

The third line contains N integers T_1, T_2, ..., T_{N} (0 ≤ T_{i} ≤ 10^9), where T_{i} is the temperature on the day i.

-----Output-----

Output a single line with N integers, where the i-th integer represents the total volume of snow melted on day i.

-----Examples-----
Input
3
10 10 5
5 7 2

Output
5 12 4

Input
5
30 25 20 15 10
9 10 12 4 13

Output
9 20 35 11 25

-----Note-----

In the first sample, Bob first makes a snow pile of volume 10, which melts to the size of 5 on the same day. On the second day, he makes another pile of size 10. Since it is a bit warmer than the day before, the first pile disappears completely while the second pile shrinks to 3. At the end of the second day, he has only a single pile of size 3. On the third day he makes a smaller pile than usual, but as the temperature dropped too, both piles survive till the end of the day.

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

import heapq
heap = []
n = int(input())
V = list(map(int, input().split()))
T = list(map(int, input().split()))
tmp = 0
for i in range(n):
    ans = 0
    heapq.heappush(heap, tmp+V[i])
    while len(heap) and heap[0]<=tmp+T[i]:
        ans += heapq.heappop(heap)-tmp
    tmp += T[i]
    ans += T[i]*len(heap)
    print(ans, end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/923/D:
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:   A $\rightarrow$ BC  B $\rightarrow$ AC  C $\rightarrow$ AB  AAA $\rightarrow$ empty string

Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.

-----Input-----

The first line contains a string S (1 ≤ |S| ≤ 10^5). The second line contains a string T (1 ≤ |T| ≤ 10^5), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.

The third line contains the number of queries Q (1 ≤ Q ≤ 10^5).

The following Q lines describe queries. The i-th of these lines contains four space separated integers a_{i}, b_{i}, c_{i}, d_{i}. These represent the i-th query: is it possible to create T[c_{i}..d_{i}] from S[a_{i}..b_{i}] by applying the above transitions finite amount of times?

Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.

It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.

-----Output-----

Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.

-----Example-----
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3

Output
10011

-----Note-----

In the first query we can achieve the result, for instance, by using transitions $A A B \rightarrow A A A C \rightarrow \operatorname{AAA} A B \rightarrow A B$.

The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'.

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

def pref_counts(string, char):
    result = [0]
    for c in string:
        result.append(result[-1] + (c == char))
    return result

def left_counts(string, char):
    result = [0]
    for c in string:
        result.append(result[-1] + 1 if c == char else 0)
    return result

s = input().replace("C", "B")
t = input().replace("C", "B")
s_bcounts, t_bcounts = pref_counts(s, "B"), pref_counts(t, "B")
s_lcounts, t_lcounts = left_counts(s, "A"), left_counts(t, "A")
for i in range(int(input())):
    a, b, c, d = list(map(int, input().split()))
    s_b = s_bcounts[b] - s_bcounts[a - 1]
    t_b = t_bcounts[d] - t_bcounts[c - 1]
    s_a = min(s_lcounts[b], b - a + 1)
    t_a = min(t_lcounts[d], d - c + 1)
    answer = False
    if s_b & 1 == t_b & 1:
        if s_b < t_b:
            answer = s_a - (s_b == 0) >= t_a
        elif s_b == t_b:
            answer = s_a >= t_a and (s_a - t_a) % 3 == 0
    print(int(answer), end = "")


I found an interesting problem on https://codeforces.com/problemset/problem/924/A:
There is a rectangular grid of n rows of m initially-white cells each.

Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows R_{i} and a non-empty subset of columns C_{i} are chosen. For each row r in R_{i} and each column c in C_{i}, the intersection of row r and column c is coloured black.

There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i, j) (i < j) exists such that $R_{i} \cap R_{j} \neq \varnothing$ or $C_{i} \cap C_{j} \neq \varnothing$, where [Image] denotes intersection of sets, and $\varnothing$ denotes the empty set.

You are to determine whether a valid sequence of operations exists that produces a given final grid.

-----Input-----

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and columns of the grid, respectively.

Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup.

-----Output-----

If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes).

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

-----Examples-----
Input
5 8
.#.#..#.
.....#..
.#.#..#.
#.#....#
.....#..

Output
Yes

Input
5 5
..#..
..#..
#####
..#..
..#..

Output
No

Input
5 9
........#
#........
..##.#...
.......#.
....#.#.#

Output
No

-----Note-----

For the first example, the desired setup can be produced by 3 operations, as is shown below.

 [Image]

For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column.

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

BLACK, WHITE = "#", "."
n, m = list(map(int, input().split()))
blacks = [{i for i, c in enumerate(input()) if c == BLACK} for i in range(n)]
answer = "Yes"
for i in range(n):
    for j in range(i):
        if blacks[i] & blacks[j] and blacks[i] != blacks[j]:
            answer = "No"
print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/924/B:
An atom of element X can exist in n distinct states with energies E_1 < E_2 < ... < E_{n}. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme.

Three distinct states i, j and k are selected, where i < j < k. After that the following process happens:   initially the atom is in the state i, we spend E_{k} - E_{i} energy to put the atom in the state k, the atom emits a photon with useful energy E_{k} - E_{j} and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy E_{j} - E_{i}, the process repeats from step 1.

Let's define the energy conversion efficiency as $\eta = \frac{E_{k} - E_{j}}{E_{k} - E_{i}}$, i. e. the ration between the useful energy of the photon and spent energy.

Due to some limitations, Arkady can only choose such three states that E_{k} - E_{i} ≤ U.

Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.

-----Input-----

The first line contains two integers n and U (3 ≤ n ≤ 10^5, 1 ≤ U ≤ 10^9) — the number of states and the maximum possible difference between E_{k} and E_{i}.

The second line contains a sequence of integers E_1, E_2, ..., E_{n} (1 ≤ E_1 < E_2... < E_{n} ≤ 10^9). It is guaranteed that all E_{i} are given in increasing order.

-----Output-----

If it is not possible to choose three states that satisfy all constraints, print -1.

Otherwise, print one real number η — the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10^{ - 9}.

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

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

Output
0.5

Input
10 8
10 13 15 16 17 19 20 22 24 25

Output
0.875

Input
3 1
2 5 10

Output
-1

-----Note-----

In the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes...

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

n, v = list(map(int, input().split()))
l = list(map(int, input().split()))
ans = [-1]
for i in range(n - 2):
    uk1 = i + 2
    uk2 = n - 1
    while (uk2 - uk1 > 1):
        if l[(uk2 + uk1) // 2] - l[i] <= v:
            uk1 = (uk2 + uk1) // 2
        else:
            uk2 = (uk2 + uk1) // 2
    if l[uk2] - l[i] <= v:
        ans.append((l[uk2] - l[i + 1]) / (l[uk2] - l[i]))
    elif l[uk1] - l[i] <= v:
        ans.append((l[uk1] - l[i + 1]) / (l[uk1] - l[i]))
print(max(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/924/C:
Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.

Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to m_{i}.

Define d_{i} as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of d_{i} over all days. There are no marks on the channel before the first day.

-----Input-----

The first line contains a single positive integer n (1 ≤ n ≤ 10^5) — the number of days.

The second line contains n space-separated integers m_1, m_2, ..., m_{n} (0 ≤ m_{i} < i) — the number of marks strictly above the water on each day.

-----Output-----

Output one single integer — the minimum possible sum of the number of marks strictly below the water level among all days.

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

Output
6

Input
5
0 1 2 1 2

Output
1

Input
5
0 1 1 2 2

Output
0

-----Note-----

In the first example, the following figure shows an optimal case. [Image]

Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0 + 0 + 2 + 0 + 3 + 1 = 6.

In the second example, the following figure shows an optimal case. [Image]

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

n = int(input())
l = list(map(int,input().split()))
dp = [1 for i in range(n)]
m=0
for i in range(1,n):
    dp[i] = max(dp[i-1],l[i]+1)
for i in range(n-2,-1,-1):
    dp[i] = max(dp[i],dp[i+1]-1)
ans=0
for i in range(n):
    ans+=dp[i]-l[i]-1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/925/A:
In the year of $30XX$ participants of some world programming championship live in a single large hotel. The hotel has $n$ floors. Each floor has $m$ sections with a single corridor connecting all of them. The sections are enumerated from $1$ to $m$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $n$ and width $m$. We can denote sections with pairs of integers $(i, j)$, where $i$ is the floor, and $j$ is the section number on the floor.

The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $(1, x)$, $(2, x)$, $\ldots$, $(n, x)$ for some $x$ between $1$ and $m$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $v$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.

You are to process $q$ queries. Each query is a question "what is the minimum time needed to go from a room in section $(x_1, y_1)$ to a room in section $(x_2, y_2)$?"

-----Input-----

The first line contains five integers $n, m, c_l, c_e, v$ ($2 \leq n, m \leq 10^8$, $0 \leq c_l, c_e \leq 10^5$, $1 \leq c_l + c_e \leq m - 1$, $1 \leq v \leq n - 1$) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively.

The second line contains $c_l$ integers $l_1, \ldots, l_{c_l}$ in increasing order ($1 \leq l_i \leq m$), denoting the positions of the stairs. If $c_l = 0$, the second line is empty.

The third line contains $c_e$ integers $e_1, \ldots, e_{c_e}$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $l_i$ and $e_i$...

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

import sys
input=sys.stdin.readline
import math
import bisect
n,m,cl,ce,v=list(map(int,input().split()))
l=[int(i) for i in input().split() if i!='\n' ]
e=[int(i) for i in input().split() if i!='\n']
q=int(input())
for i in range(q):
        x1,y1,x2,y2=list(map(int,input().split()))
        lft,neareststa,sta,nearestele=0,0,0,0
        if x2==x1 and y1==y2:
            output=0
        elif x2==x1:
            output=abs(y2-y1)
        else:
            lft=math.ceil(abs((x2-x1))/v)
            sta=abs(x2-x1)
            if cl>0:
                nearestele=bisect.bisect_left(l,y1)
                if len(l)>nearestele:
                    first=abs(l[nearestele]-y1)+abs(y2-l[nearestele])
                else:
                    first=1000000000001
                if nearestele!=0:
                    second=abs(l[nearestele-1]-y1)+abs(y2-l[nearestele-1])
                else:
                    second=1000000000001
                nearestele=min(first,second)
            else:
                nearestele=1000000000001
            if ce>0:
                neareststa=bisect.bisect_left(e,y1)
                if len(e)>neareststa:
                    first=abs(e[neareststa]-y1)+abs(y2-e[neareststa])
                else:
                    first=1000000000001
                if neareststa!=0:
                    second=abs(e[neareststa-1]-y1)+abs(y2-e[neareststa-1])
                else:
                    second=1000000000001
                neareststa=min(first,second)
            else:
                neareststa=1000000000001
            output=min(lft+neareststa,sta+nearestele)
        sys.stdout.write(str(output)+'\n')


I found an interesting problem on https://codeforces.com/problemset/problem/925/B:
One department of some software company has $n$ servers of different specifications. Servers are indexed with consecutive integers from $1$ to $n$. Suppose that the specifications of the $j$-th server may be expressed with a single integer number $c_j$ of artificial resource units.

In order for production to work, it is needed to deploy two services $S_1$ and $S_2$ to process incoming requests using the servers of the department. Processing of incoming requests of service $S_i$ takes $x_i$ resource units.

The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service $S_i$ is deployed using $k_i$ servers, then the load is divided equally between these servers and each server requires only $x_i / k_i$ (that may be a fractional number) resource units.

Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.

Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services.

-----Input-----

The first line contains three integers $n$, $x_1$, $x_2$ ($2 \leq n \leq 300\,000$, $1 \leq x_1, x_2 \leq 10^9$) — the number of servers that the department may use, and resource units requirements for each of the services.

The second line contains $n$ space-separated integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 10^9$) — the number of resource units provided by each of the servers.

-----Output-----

If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes).

Otherwise print the word "Yes" (without the quotes).

In the second line print two integers $k_1$ and $k_2$ ($1 \leq k_1, k_2 \leq n$) — the number of servers used for each of the services.

In the third line print $k_1$ integers, the indices of the servers...

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

# python3

def readline(): return tuple(map(int, input().split()))

def ceil_div(num, den): return (num - 1) // den + 1

def main():
    n, x1, x2 = readline()
    c = readline()

    xx = (x1, x2)

    servers = sorted(enumerate(c, start=1), key=lambda p: p[1])
    for (i, a) in enumerate(servers):
        for (j, x) in enumerate(xx):
            kj = ceil_div(x, a[1])
            if i + kj < n and (n - i - kj) * servers[i + kj][1] >= sum(xx) - x:
                print("Yes")
                l1 = servers[i:i+kj]
                l2 = servers[i+kj:]
                if j: l1, l2 = l2, l1
                print(len(l1), len(l2))
                print(" ".join(str(d[0]) for d in l1))
                print(" ".join(str(d[0]) for d in l2))
                return
    print("No")

main()

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/925/C:
Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence $a_1, \ldots, a_n$. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence $b_1, \ldots, b_n$ using the following rules:

  $b_1 = a_1$;

 $b_i = a_i \oplus a_{i - 1}$ for all $i$ from 2 to $n$, where $x \oplus y$ is the bitwise XOR of $x$ and $y$.

It is easy to see that the original sequence can be obtained using the rule $a_i = b_1 \oplus \ldots \oplus b_i$.

However, some time later Vitya discovered that the integers $b_i$ in the cypher got shuffled, and it can happen that when decrypted using the rule mentioned above, it can produce a sequence that is not increasing. In order to save his reputation in the scientific community, Vasya decided to find some permutation of integers $b_i$ so that the sequence $a_i = b_1 \oplus \ldots \oplus b_i$ is strictly increasing. Help him find such a permutation or determine that it is impossible.

-----Input-----

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

The second line contains $n$ integers $b_1, \ldots, b_n$ ($1 \leq b_i < 2^{60}$).

-----Output-----

If there are no valid permutations, print a single line containing "No".

Otherwise in the first line print the word "Yes", and in the second line print integers $b'_1, \ldots, b'_n$ — a valid permutation of integers $b_i$. The unordered multisets $\{b_1, \ldots, b_n\}$ and $\{b'_1, \ldots, b'_n\}$ should be equal, i. e. for each integer $x$ the number of occurrences of $x$ in the first multiset should be equal to the number of occurrences of $x$ in the second multiset. Apart from this, the sequence $a_i = b'_1 \oplus \ldots \oplus b'_i$ should be strictly increasing.

If there are multiple answers, print any of them.

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

Output
No

Input
6
4 7 7 12 31 61

Output
Yes
4 12 7 31 7 61

-----Note-----

In the first example no permutation is valid.

In...

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

n=int(input())
s=[[] for i in range(60)]
for b in list(map(int,input().split())):
	for i in range(59,-1,-1):
		if b>>i&1:
			s[i].append(b)
			break
ans=[]
cur=0
for i in range(n):
	fl=False
	for j in range(60):
		if s[j]!=[] and cur>>j&1==0:
			ans.append(s[j][-1])
			cur^=s[j][-1]
			s[j].pop()
			fl=True
			break
	if not fl:
		print('No')
		return
print('Yes')
print(' '.join(str(i) for i in ans))


I found an interesting problem on https://codeforces.com/problemset/problem/926/A:
A positive integer is called a 2-3-integer, if it is equal to 2^{x}·3^{y} for some non-negative integers x and y. In other words, these integers are such integers that only have 2 and 3 among their prime divisors. For example, integers 1, 6, 9, 16 and 108 — are 2-3 integers, while 5, 10, 21 and 120 are not.

Print the number of 2-3-integers on the given segment [l, r], i. e. the number of sich 2-3-integers t that l ≤ t ≤ r.

-----Input-----

The only line contains two integers l and r (1 ≤ l ≤ r ≤ 2·10^9).

-----Output-----

Print a single integer the number of 2-3-integers on the segment [l, r].

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

Output
7

Input
100 200

Output
5

Input
1 2000000000

Output
326

-----Note-----

In the first example the 2-3-integers are 1, 2, 3, 4, 6, 8 and 9.

In the second example the 2-3-integers are 108, 128, 144, 162 and 192.

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

l,r = list(map(int,input().split()))
n=0
count=0
for pow2 in range(0,33):
    for pow3 in range(0,33):
        n = (2**pow2) * (3**pow3)
        if n<=r and n>=l:
            count+=1
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/926/B:
There are n points on a straight line, and the i-th point among them is located at x_{i}. All these coordinates are distinct.

Determine the number m — the smallest number of points you should add on the line to make the distances between all neighboring points equal.

-----Input-----

The first line contains a single integer n (3 ≤ n ≤ 100 000) — the number of points.

The second line contains a sequence of integers x_1, x_2, ..., x_{n} ( - 10^9 ≤ x_{i} ≤ 10^9) — the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.

-----Output-----

Print a single integer m — the smallest number of points you should add on the line to make the distances between all neighboring points equal.

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

Output
1

Input
6
100 200 400 300 600 500

Output
0

Input
4
10 9 0 -1

Output
8

-----Note-----

In the first example you can add one point with coordinate 0.

In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.

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

def nod(a, b):
    if (b == 0):
        return a;
    else:
        return nod(b, a%b);

def main():
    n = int(input());
    arr = [int(i) for i in input().split()]
    arr.sort()
    no = 0;
    for i in range(1, n):
        no = nod(arr[i] - arr[i-1], no)
    ans = 0;
    for i in range(1, n):
        ans += -1 + (arr[i] - arr[i-1]) // no
    print(ans)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/926/C:
A camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means that the corresponding column is black.

You think that this photo can contain a zebra. In this case the whole photo should consist of several (possibly, only one) alternating black and white stripes of equal width. For example, the photo [0, 0, 0, 1, 1, 1, 0, 0, 0] can be a photo of zebra, while the photo [0, 0, 0, 1, 1, 1, 1] can not, because the width of the black stripe is 3, while the width of the white stripe is 4. Can the given photo be a photo of zebra or not?

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100 000) — the width of the photo.

The second line contains a sequence of integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 1) — the description of the photo. If a_{i} is zero, the i-th column is all black. If a_{i} is one, then the i-th column is all white.

-----Output-----

If the photo can be a photo of zebra, print "YES" (without quotes). Otherwise, print "NO".

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

-----Examples-----
Input
9
0 0 0 1 1 1 0 0 0

Output
YES

Input
7
0 0 0 1 1 1 1

Output
NO

Input
5
1 1 1 1 1

Output
YES

Input
8
1 1 1 0 0 0 1 1

Output
NO

Input
9
1 1 0 1 1 0 1 1 0

Output
NO

-----Note-----

The first two examples are described in the statements.

In the third example all pixels are white, so the photo can be a photo of zebra.

In the fourth example the width of the first stripe is equal to three (white color), the width of the second stripe is equal to three (black), and the width of the third stripe is equal to two (white). Thus, not all stripes have equal length, so this photo is not a photo of zebra.

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

n = int(input())
a = list(map(int, input().split()))
cnt = 0
cnt1 = 0
cnt2 = 0
p = -1
flag = True
for i in range(n):
    if a[i] == 1:
        if p != 1:
            if cnt != cnt1 and cnt != 0:
                flag = False
            cnt = cnt1
            p = 1
            cnt1 = 0
        cnt1 += 1
    if a[i] == 0:
        if p != 0:
            if cnt != cnt1 and cnt != 0:
                flag = False
            cnt = cnt1
            cnt1 = 0
            p = 0
        cnt1 += 1
if cnt != cnt1 and cnt != 0:
    flag = False
if flag:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/926/D:
A classroom in a school has six rows with 3 desks in each row. Two people can use the same desk: one sitting on the left and one sitting on the right.

Some places are already occupied, and some places are vacant. Petya has just entered the class and wants to occupy the most convenient place. The conveniences of the places are shown on the picture: [Image]

Here, the desks in the top row are the closest to the blackboard, while the desks in the bottom row are the furthest from the blackboard.

You are given a plan of the class, where '*' denotes an occupied place, '.' denotes a vacant place, and the aisles are denoted by '-'.

Find any of the most convenient vacant places for Petya.

-----Input-----

The input consists of 6 lines. Each line describes one row of desks, starting from the closest to the blackboard. Each line is given in the following format: two characters, each is '*' or '.' — the description of the left desk in the current row; a character '-' — the aisle; two characters, each is '*' or '.' — the description of the center desk in the current row; a character '-' — the aisle; two characters, each is '*' or '.' — the description of the right desk in the current row. So, the length of each of the six lines is 8.

It is guaranteed that there is at least one vacant place in the classroom.

-----Output-----

Print the plan of the classroom after Petya takes one of the most convenient for him places. Mark this place with the letter 'P'. There should be exactly one letter 'P' in the plan. Petya can only take a vacant place. In all other places the output should coincide with the input.

If there are multiple answers, print...

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/926/E:
You are given a sequence of positive integers a_1, a_2, ..., a_{n}.

While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a single integer x + 1 on their place. This way the number of elements in the sequence is decreased by 1 on each step.

You stop performing the operation when there is no pair of equal consecutive elements.

For example, if the initial sequence is [5, 2, 1, 1, 2, 2], then after the first operation you get [5, 2, 2, 2, 2], after the second — [5, 3, 2, 2], after the third — [5, 3, 3], and finally after the fourth you get [5, 4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.

Determine the final sequence after you stop performing the operation.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 2·10^5) — the number of elements in the sequence.

The second line contains the sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

In the first line print a single integer k — the number of elements in the sequence after you stop performing the operation.

In the second line print k integers — the sequence after you stop performing the operation.

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

Output
2
5 4
Input
4
1000000000 1000000000 1000000000 1000000000

Output
1
1000000002
Input
7
4 10 22 11 12 5 6

Output
7
4 10 22 11 12 5 6

-----Note-----

The first example is described in the statements.

In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].

In the third example there are no two equal consecutive elements initially, so the sequence does not change.

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

n, m = int(input()), 0
b = [int(t) for t in input().split()]
a = []
for i in range(n):
	a.append(b[i])
	while len(a) > 1 and a[-2] == a[-1]:
		del a[-1]
		a[-1] += 1
print(len(a))
print(" ".join([str(t) for t in a]))


I found an interesting problem on https://codeforces.com/problemset/problem/926/F:
A sum of p rubles is charged from Arkady's mobile phone account every day in the morning. Among the following m days, there are n days when Arkady will top up the account: in the day d_{i} he will deposit t_{i} rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following m days.

Determine the number of days starting from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment (i. e. in evening). Initially the account's balance is zero rubles.

-----Input-----

The first line contains three integers n, p and m (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 10^9, 1 ≤ m ≤ 10^9, n ≤ m) — the number of days Arkady will top up the account, the amount of the daily payment, and the number of days you should check.

The i-th of the following n lines contains two integers d_{i} and t_{i} (1 ≤ d_{i} ≤ m, 1 ≤ t_{i} ≤ 10^9) — the index of the day when Arkady will make the i-th top up, and the amount he will deposit on this day. It is guaranteed that the indices of the days are distinct and are given in increasing order, i. e. d_{i} > d_{i} - 1 for all i from 2 to n.

-----Output-----

Print the number of days from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment.

-----Examples-----
Input
3 6 7
2 13
4 20
7 9

Output
3

Input
5 4 100
10 70
15 76
21 12
30 100
67 85

Output
26

-----Note-----

In the first example the balance will change as following (remember, initially the balance is zero):  in the first day 6 rubles will be charged, the balance in the evening will be equal to  - 6;  in the second day Arkady will deposit 13 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 1;  in the third day 6 rubles will be charged, the balance in the evening will be equal to  - 5;  in the fourth day Arkady will deposit 20 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 9;  in...

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

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

ans = 0
curb = 0
curd = 1
for i in range(0, n):
    #print(curb)
    tday, tplus = input().split()
    tday = int(tday)
    tplus = int(tplus)
    if curb < 0:
        ans += (tday - curd)
        curb -= p * (tday - curd)
    elif curb - p * (tday - curd) < 0:
        curb -= p * (tday - curd)
        x = -curb
        xx = x // p
        if xx * p < x:
            xx += 1
        x = xx
        ans += x
    else:
        curb -= p * (tday - curd)
    curd = tday
    #print(curb)
    curb += tplus

tday = m + 1
if curb < 0:
    ans += (tday - curd)
    curb -= p * (tday - curd)
elif curb - p * (tday - curd) < 0:
    curb -= p * (tday - curd)
    x = -curb
    xx = x // p
    if xx * p < x:
        xx += 1
    x = xx
    ans += x

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/926/G:
A flower shop has got n bouquets, and the i-th bouquet consists of a_{i} flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets.

Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.

Determine the maximum possible number of large bouquets Vasya can make.

-----Input-----

The first line contains a single positive integer n (1 ≤ n ≤ 10^5) — the number of initial bouquets.

The second line contains a sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — the number of flowers in each of the initial bouquets.

-----Output-----

Print the maximum number of large bouquets Vasya can make.

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

Output
2

Input
6
2 2 6 8 6 12

Output
0

Input
3
11 4 10

Output
1

-----Note-----

In the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme.

In the second example it is not possible to form a single bouquet with odd number of flowers.

In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11 + 4 + 10 = 25.

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

n = int(input())
mas = list(map(int, input().split()))
r1 = [i for i in mas if i % 2 == 0]
r2 = [i for i in mas if i % 2 != 0]
r1 = len(r1)
r2 = len(r2)
if min(r1, r2) == r2:
    k = r2
else:
    k = r1 + ( (r2 - r1) //3)
print(k)


I found an interesting problem on https://codeforces.com/problemset/problem/926/H:
Arkady decided to buy roses for his girlfriend.

A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.

Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is b_{i}, and its color is c_{i} ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).

Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.

-----Input-----

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.

The second line contains a sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10 000), where b_{i} equals the beauty of the i-th rose.

The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where c_{i} denotes the color of the i-th rose: 'W' denotes white, 'O'  — orange, 'R' — red.

-----Output-----

Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.

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

Output
11

Input
5 2
10 20 14 20 11
RRRRR

Output
-1

Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW

Output
28

-----Note-----

In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.

In the second example Arkady can not buy a bouquet because all roses have the same color.

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

n,k=map(int,input().split())
cost=list(map(int,input().split()))
s=input()
#return
a=[]
b=[]
c=[]
#print(n,k,cost)
kek1=0
kek2=0
kek3=0
for i in range(n):
    if (s[i]==chr(ord("W"))):
        kek1+=1
        a.append(cost[i])
    if (s[i]==chr(ord("O"))):
        kek2+=1
        b.append(cost[i])
    if (s[i]==chr(ord("R"))):
        kek3+=1
        c.append(cost[i])
a=sorted(a)
a=list(reversed(a))
b=sorted(b)
b=list(reversed(b))
c=sorted(c)
c=list(reversed(c))

pref_a=[]
pref_b=[]
pref_c=[]

if (kek1!=0):
    pref_a.append(a[0])
    for i in range(1,len(a)):
        pref_a.append(pref_a[len(pref_a)-1]+a[i])

if (kek2!=0):
    pref_b.append(b[0])
    for i in range(1,len(b)):
        pref_b.append(pref_b[len(pref_b)-1]+b[i])

if (kek3!=0):
    pref_c.append(c[0])
    for i in range(1,len(c)):
        pref_c.append(pref_c[len(pref_c)-1]+c[i])

inf=10**20
ans=-inf
for i in range(0,min(k-1,kek2)):
    cur=pref_b[i]
    left_k=k-(i+1)

    res_a=-inf
    res_c=-inf
    if (kek1):
        if (kek1>=left_k):
            res_a=pref_a[left_k-1]
    if (kek3):
        if (kek3>=left_k):
            res_c=pref_c[left_k-1]

    cur+=max(res_a,res_c)
    ans=max(ans,cur)

if (ans<-(10**18)):
    ans=-1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/926/I:
Polycarp has a strict daily schedule. He has n alarms set for each day, and the i-th alarm rings each day at the same time during exactly one minute.

Determine the longest time segment when Polycarp can sleep, i. e. no alarm rings in that period. It is possible that Polycarp begins to sleep in one day, and wakes up in another.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of alarms.

Each of the next n lines contains a description of one alarm. Each description has a format "hh:mm", where hh is the hour when the alarm rings, and mm is the minute of that hour when the alarm rings. The number of hours is between 0 and 23, and the number of minutes is between 0 and 59. All alarm times are distinct. The order of the alarms is arbitrary.

Each alarm starts ringing in the beginning of the corresponding minute and rings for exactly one minute (i. e. stops ringing in the beginning of the next minute). Polycarp can start sleeping instantly when no alarm is ringing, and he wakes up at the moment when some alarm starts ringing.

-----Output-----

Print a line in format "hh:mm", denoting the maximum time Polycarp can sleep continuously. hh denotes the number of hours, and mm denotes the number of minutes. The number of minutes should be between 0 and 59. Look through examples to understand the format better.

-----Examples-----
Input
1
05:43

Output
23:59

Input
4
22:00
03:21
16:03
09:59

Output
06:37

-----Note-----

In the first example there is only one alarm which rings during one minute of a day, and then rings again on the next day, 23 hours and 59 minutes later. Polycarp can sleep all this time.

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

n = int(input())
x = []
for i in range (n):
    a, b = map(int, (input().split(':')))
    x.append(a*60 + b);
x = sorted(x)
x.append(x[0] + 24*60)
m = 0
for i in range(n):
    m = max(m, x[i+1] - x[i]-1)
x = str(m // 60)
y = str(m % 60)
if len(x) < 2:
    x = '0' + x
if len(y) < 2:
    y = '0' + y
s = x + ':' + y
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/928/A:
When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.

Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins s and t are considered similar if we can transform s to t via a sequence of operations of the following types:   transform lowercase letters to uppercase and vice versa;  change letter «O» (uppercase latin letter) to digit «0» and vice versa;  change digit «1» (one) to any letter among «l» (lowercase latin «L»), «I» (uppercase latin «i») and vice versa, or change one of these letters to other.

For example, logins «Codeforces» and «codef0rces» as well as «OO0OOO00O0OOO0O00OOO0OO_lol» and «OO0OOO0O00OOO0O00OO0OOO_1oI» are considered similar whereas «Codeforces» and «Code_forces» are not.

You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones.

-----Input-----

The first line contains a non-empty string s consisting of lower and uppercase latin letters, digits and underline symbols («_») with length not exceeding 50  — the login itself.

The second line contains a single integer n (1 ≤ n ≤ 1 000) — the number of existing logins.

The next n lines describe the existing logins, following the same constraints as the user login (refer to the first line of the input). It's guaranteed that no two existing logins are similar.

-----Output-----

Print «Yes» (without quotes), if user can register via this login, i.e. none of the existing logins is similar with it.

Otherwise print «No» (without...

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

ss = input()
st = ""
for j in range(len(ss)):
    c = ss[j]
    if 'A' <= c <= 'Z':
        c = chr(ord(c) + ord('a') - ord('A'))
    if c == 'o':
        c = '0'
    if c == 'l' or c == 'i':
        c = '1'
    st += c
s = st
n = int(input())
for i in range(n):
    ss = input()
    st = ""
    for j in range(len(ss)):
        c = ss[j]
        if 'A' <= c <= 'Z':
            c = chr(ord(c) + ord('a') - ord('A'))
        if c == 'o':
            c = '0'
        if c == 'l' or c == 'i':
            c = '1'
        st += c
    if s == st:
        print("No")
        return
print("Yes")


I found an interesting problem on https://codeforces.com/problemset/problem/928/B:
There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.

More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to n where n is the total number of messages in the chat.

Each message might contain a link to an earlier message which it is a reply to. When opening a message x or getting a link to it, the dialogue is shown in such a way that k previous messages, message x and k next messages are visible (with respect to message x). In case there are less than k messages somewhere, they are yet all shown.

Digging deep into your message history, you always read all visible messages and then go by the link in the current message x (if there is one) and continue reading in the same manner.

Determine the number of messages you'll read if your start from message number t for all t from 1 to n. Calculate these numbers independently. If you start with message x, the initial configuration is x itself, k previous and k next messages. Messages read multiple times are considered as one.

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 10^5, 0 ≤ k ≤ n) — the total amount of messages and the number of previous and next messages visible.

The second line features a sequence of integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} < i), where a_{i} denotes the i-th message link destination or zero, if there's no link from i. All messages are listed in chronological order. It's guaranteed that the link from message x goes to message with number strictly less than x.

-----Output-----

Print n integers with i-th denoting the number of distinct messages you can read starting from message i and traversing the links while possible.

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

Output
1 2 2 3 3 3

Input
10 1
0 1 0 3 4 5 2 3 7 0

Output
2 3 3 4 5 6 6 6 8 2

Input
2 2
0 1

Output
2 2

-----Note-----

Consider i = 6...

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

def count_unic_mess(crt, display, array, n, result_arr):
    low_bound = 0 if crt - display < 0 else crt - display

    high_bound = n if crt + display + 1 > n else crt + display + 1

    result = high_bound - low_bound

    if array[crt] == 0:
        result_arr.append(result)
        return result

    ref = array[crt] - 1
    high_bound_ref = n if ref + display + 1 > n else ref + display + 1

    if high_bound_ref >= low_bound:
        result += result_arr[ref] - high_bound_ref + low_bound
    else:
        result += result_arr[ref]

    result_arr.append(result)
    return result

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

links = [int(x) for x in input().split(' ')]
count_arr = []

for i in range(n):
    print(count_unic_mess(i, k, links, n, count_arr), end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/928/C:
Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity.

A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with length not exceeding 10 and version — positive integer from 1 to 10^6. Each project (keep in mind that it is determined by both its name and version) might depend on other projects. For sure, there are no cyclic dependencies.

You're given a list of project descriptions. The first of the given projects is the one being developed by Polycarp at this moment. Help Polycarp determine all projects that his project depends on (directly or via a certain chain).

It's possible that Polycarp's project depends on two different versions of some project. In this case collision resolving is applied, i.e. for each such project the system chooses the version that minimizes the distance from it to Polycarp's project. If there are several options, the newer (with the maximum version) is preferred. This version is considered actual; other versions and their dependencies are ignored.

More formal, choose such a set of projects of minimum possible size that the following conditions hold:   Polycarp's project is chosen;  Polycarp's project depends (directly or indirectly) on all other projects in the set;  no two projects share the name;  for each project x that some other project in the set depends on we have either x or some y with other version and shorter chain to Polycarp's project chosen. In case of ties the newer one is chosen.

Output all Polycarp's project's dependencies (Polycarp's project itself should't be printed) in lexicographical order.

-----Input-----

The first line contains an only integer n (1 ≤ n ≤ 1 000) — the number of projects in Vaja.

The following lines contain the project descriptions. Each project is described by a line consisting of its name and version separated by space. The next line...

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

N=int(input())
Slide=dict()
SlideList=[list()]*N
ItogInformation=set()
GoodNameTags=set()

NewName,NewVer=input().split()
NewVer=int(NewVer)

GoodNameTags.add(NewName)

Slide[0]=NewName+' '+str(NewVer)
Slide[NewName+' '+str(NewVer)]=0
NewNum=int(input())
SlideList[0]=[0]*(NewNum+2)
SlideList[0][1]=NewNum

for i in range(1,NewNum+1):
    Name,Ver=input().split()
    SlideList[0][i+1]=Name+' '+Ver

for j in range(1,N):
    input()
    NewName,NewVer=input().split()
    NewVer=int(NewVer)
    Slide[j]=NewName+' '+str(NewVer)
    Slide[NewName+' '+str(NewVer)]=j
    NewNum=int(input())
    SlideList[j]=[0]*(NewNum+2)
    SlideList[j][1]=NewNum
    for i in range(1,NewNum+1):
        Name,Ver=input().split()
        SlideList[j][i+1]=Name+' '+Ver

ListOfNeed=set()
ListOfRead=set()
ListOfRead.add(Slide[0])

while len(ListOfRead)!=0:
    ListOfNeed=ListOfRead.copy()
    ListOfRead=set()
    found=dict()
    for i in ListOfNeed:
        for j in range(SlideList[Slide[i]][1]):
            Name,Ver=SlideList[Slide[i]][j+2].split()
            Ver=int(Ver)
            key=found.pop(Name, -1)
            if key==-1 or key<Ver:
                found[Name]=Ver
            else:
                found[Name]=key
    for i in list(found.keys()):
        if not (i in GoodNameTags):
            GoodNameTags.add(i)
            ListOfRead.add(i+' '+str(found[i]))
            ItogInformation.add(i+' '+str(found[i]))

Otvet=list(ItogInformation)
Otvet.sort()

print(len(Otvet))
for i in range(len(Otvet)):
    print(Otvet[i])


I found an interesting problem on https://codeforces.com/problemset/problem/928/D:
Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor.

Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces».

With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols?

A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.».

-----Input-----

The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·10^5. It's guaranteed that all lines are non-empty.

-----Output-----

Print a single integer — the minimum number of clicks.

-----Examples-----
Input
snow affects sports such as skiing, snowboarding, and snowmachine travel.
snowboarding is a recreational activity and olympic and paralympic sport.

Output
141

Input
'co-co-co,...

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

import sys
import re

SEPARATORS = "[.,? !'-]"

class TrieNode(object):
    def __init__(self):
        self.terminal = False
        self.go = {}
        self.count = 0

def insert(node, s):
    nodes = [node]
    unique, auto = 0, 0
    for c in s:
        if c not in node.go:
            node.go[c] = TrieNode()
        node = node.go[c]
        nodes.append(node)

        if node.count == 1:
            unique += 1
        if node.terminal:
            auto = max(unique - 2, 0)

    if not node.terminal:
        node.terminal = True
        for node in nodes:
            node.count += 1
    return auto

root = TrieNode()
answer = 0
for line in sys.stdin:
    answer += len(line)
    for word in [_f for _f in re.split(SEPARATORS, line.strip()) if _f]:
        answer -= insert(root, word)
print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/929/A:
Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.

Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x_1 километров вдоль улицы, второй — в точке x_2 и так далее, n-й велопрокат находится в точке x_{n}. Школа Аркадия находится в точке x_1 (то есть там же, где и первый велопрокат), а дом — в точке x_{n} (то есть там же, где и n-й велопрокат). Известно, что x_{i} < x_{i} + 1 для всех 1 ≤ i < n.

Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.

За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы.

Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.

-----Входные данные-----

В первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде.

В следующей строке следует последовательность целых чисел x_1, x_2, ..., x_{n} (0 ≤ x_1 < x_2 < ... < x_{n} ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.

-----Выходные данные-----

Если...

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

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

count = 1
cur_s = 0

for i in range(n - 1):
    next_dist = xs[i + 1] - xs[i]
    if next_dist > k:
        count = -1
        break
    elif next_dist + cur_s > k:
        cur_s = next_dist
        count += 1
    else:
        cur_s += next_dist

print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/929/B:
В самолёте есть n рядов мест. Если смотреть на ряды сверху, то в каждом ряду есть 3 места слева, затем проход между рядами, затем 4 центральных места, затем ещё один проход между рядами, а затем ещё 3 места справа.

Известно, что некоторые места уже заняты пассажирами. Всего есть два вида пассажиров — статусные (те, которые часто летают) и обычные.

Перед вами стоит задача рассадить ещё k обычных пассажиров так, чтобы суммарное число соседей у статусных пассажиров было минимально возможным. Два пассажира считаются соседями, если они сидят в одном ряду и между ними нет других мест и прохода между рядами. Если пассажир является соседним пассажиром для двух статусных пассажиров, то его следует учитывать в сумме соседей дважды.

-----Входные данные-----

В первой строке следуют два целых числа n и k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10·n) — количество рядов мест в самолёте и количество пассажиров, которых нужно рассадить.

Далее следует описание рядов мест самолёта по одному ряду в строке. Если очередной символ равен '-', то это проход между рядами. Если очередной символ равен '.', то это свободное место. Если очередной символ равен 'S', то на текущем месте будет сидеть статусный пассажир. Если очередной символ равен 'P', то на текущем месте будет сидеть обычный пассажир.

Гарантируется, что количество свободных мест не меньше k. Гарантируется, что все ряды удовлетворяют описанному в условии формату.

-----Выходные данные-----

В первую строку выведите минимальное суммарное число соседей у статусных пассажиров.

Далее выведите план рассадки пассажиров, который минимизирует суммарное количество соседей у статусных пассажиров, в том же формате, что и во входных данных. Если в свободное место нужно посадить одного из k пассажиров, выведите строчную букву 'x' вместо символа '.'.

-----Примеры-----
Входные данные
1 2
SP.-SS.S-S.S

Выходные данные
5
SPx-SSxS-S.S

Входные данные
4 9
PP.-PPPS-S.S
PSP-PPSP-.S.
.S.-S..P-SS.
P.S-P.PP-PSP

Выходные...

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

#   TaskB

import sys

n, k = list(map(int, sys.stdin.readline().split()))

my_list = list()

for i in range(n):
    my_list.append(input())

def left(i, my_list):
    return my_list[i] == '.' and \
           ((i - 1) < 0 or
            my_list[i - 1] == '.' or
            my_list[i - 1] == 'P' or
            my_list[i - 1] == '-' or
            my_list[i - 1] == 'x')

def right(i, my_list):
    return my_list[i] == '.' and \
           ((i + 1) >= len(my_list) or
            my_list[i + 1] == '.' or
            my_list[i + 1] == 'P' or
            my_list[i + 1] == '-' or
            my_list[i + 1] == 'x')

while k > 0:
    for index in range(n):
        cur_list = my_list[index]
        for i, _ in enumerate(cur_list):
            if left(i, cur_list) and right(i, cur_list):
                k = k - 1
                try:
                    part3 = cur_list[(i + 1):]
                except:
                    part3 = ''
                cur_list = cur_list[:i] + 'x' + part3
                my_list[index] = cur_list
                if k == 0:
                    break
            if k == 0:
                break
        if k == 0:
            break
    if k == 0:
        break

    for index in range(n):
        cur_list = my_list[index]
        for i, _ in enumerate(cur_list):
            if ((not left(i, cur_list) and cur_list[i] == '.') and right(i, cur_list)) or (left(i, cur_list) and (not right(i, cur_list)) and cur_list[i] == '.'):
                k = k - 1
                try:
                    part3 = cur_list[(i + 1):]
                except:
                    part3 = ''
                cur_list = cur_list[:i] + 'x' + part3
                my_list[index] = cur_list
                if k == 0:
                    break
            if k == 0:
                break
        if k == 0:
            break
    if k == 0:
        break

    for index in range(n):
        cur_list = my_list[index]
        for i, _ in enumerate(cur_list):
            if cur_list[i] == '.':
                k = k - 1
    ...


I found an interesting problem on https://codeforces.com/problemset/problem/929/C:
Завтра у хоккейной команды, которой руководит Евгений, важный матч. Евгению нужно выбрать шесть игроков, которые выйдут на лед в стартовом составе: один вратарь, два защитника и три нападающих.

Так как это стартовый состав, Евгения больше волнует, насколько красива будет команда на льду, чем способности игроков. А именно, Евгений хочет выбрать такой стартовый состав, чтобы номера любых двух игроков из стартового состава отличались не более, чем в два раза. Например, игроки с номерами 13, 14, 10, 18, 15 и 20 устроят Евгения, а если, например, на лед выйдут игроки с номерами 8 и 17, то это не устроит Евгения.

Про каждого из игроков вам известно, на какой позиции он играет (вратарь, защитник или нападающий), а также его номер. В хоккее номера игроков не обязательно идут подряд. Посчитайте число различных стартовых составов из одного вратаря, двух защитников и трех нападающих, которые может выбрать Евгений, чтобы выполнялось его условие красоты.

-----Входные данные-----

Первая строка содержит три целых числа g, d и f (1 ≤ g ≤ 1 000, 1 ≤ d ≤ 1 000, 1 ≤ f ≤ 1 000) — число вратарей, защитников и нападающих в команде Евгения.

Вторая строка содержит g целых чисел, каждое в пределах от 1 до 100 000 — номера вратарей.

Третья строка содержит d целых чисел, каждое в пределах от 1 до 100 000 — номера защитников.

Четвертая строка содержит f целых чисел, каждое в пределах от 1 до 100 000 — номера нападающих.

Гарантируется, что общее количество игроков не превосходит 1 000, т. е. g + d + f ≤ 1 000. Все g + d + f номеров игроков различны.

-----Выходные данные-----

Выведите одно целое число — количество возможных стартовых составов.

-----Примеры-----
Входные данные
1 2 3
15
10 19
20 11 13

Выходные данные
1

Входные данные
2 3 4
16 40
20 12 19
13 21 11 10

Выходные данные
6

-----Примечание-----

В первом примере всего один вариант для выбора состава, который удовлетворяет описанным условиям, поэтому ответ 1.

Во втором примере подходят следующие игровые сочетания (в порядке...

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

import math
def main():
    g, d, f = map(int, input().split())
    lst1 = list(map(int, input().split()))
    lst2 = list(map(int, input().split()))
    lst3 = list(map(int, input().split()))
    lst0 = []
    precounted = []
    ans = 0

    lst0 += [(c, 1) for c in lst1]
    lst0 += [(c, 2) for c in lst2]
    lst0 += [(c, 3) for c in lst3]

    lst0.sort()

    for i in range(len(lst0)):

        if len(precounted) == 0:
            a1, a2, a3 = (0, 0, 0)
        else:
            a1, a2, a3 = precounted[len(precounted) - 1]

        if (lst0[i][1] == 1):
            a1 += 1
        elif (lst0[i][1] == 2):
            a2 += 1
        else:
            a3 += 1

        precounted.append((a1, a2, a3))

        def product(iterable):
            prod = 1
            for n in iterable:
                prod *= n
            return prod

        def npr(n, r):
            assert 0 <= r <= n
            return product(range(n - r + 1, n + 1))

        def ncr(r, n):
            if r > n:
                return 0
            assert 0 <= r <= n
            if r > n // 2:
                r = n - r
            return npr(n, r) // math.factorial(r)

    for i in range(len(lst0) - 1):
        l = i + 1
        r = len(lst0)
        while l + 1 < r:
            m = (l + r) // 2
            if lst0[i][0] * 2 >= lst0[m][0]:
                l = m
            else:
                r = m
        max_possible_num = lst0[l][0]
        max_possible_ind = l

        a1 = precounted[max_possible_ind][0] - precounted[i][0]
        a2 = precounted[max_possible_ind][1] - precounted[i][1]
        a3 = precounted[max_possible_ind][2] - precounted[i][2]
        n1 = 1
        n2 = 2
        n3 = 3

        if lst0[i][1] == 1:
            n1 -= 1
        elif lst0[i][1] == 2:
            n2 -= 1
        else:
            n3 -= 1
        ans += ncr(n1, a1) * ncr(n2, a2) * ncr(n3, a3)

    print(ans)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/930/A:
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is p_{i}-th inflorescence and p_{i} < i.

Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to p_{a}-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.

Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.

-----Input-----

First line of input contains single integer number n (2 ≤ n ≤ 100 000)  — number of inflorescences.

Second line of input contains sequence of n - 1 integer numbers p_2, p_3, ..., p_{n} (1 ≤ p_{i} < i), where p_{i} is number of inflorescence into which the apple from i-th inflorescence rolls down.

-----Output-----

Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest.

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

Output
1

Input
5
1 2 2 2

Output
3

Input
18
1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4

Output
4

-----Note-----

In first example Arcady will be able to collect only one apple, initially...

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

import threading
from sys import setrecursionlimit, exc_info

def main():
    try:
        n = int(input())
        par = list(map(int, input().split()))

        gr = [[] for i in range(n)]
        for i in range(n - 1):
            gr[par[i] - 1].append(i + 1)

        cnt = [0] * n

        def dfs(v, depth=0):
            cnt[depth] += 1
            while depth >= len(cnt):
                pass
            for u in gr[v]:
                dfs(u, depth + 1)

        dfs(0)
        print(sum([x % 2 for x in cnt]))
    except:
        print(exc_info()[0])

setrecursionlimit(100000000)
threading.stack_size(102400000)
thread = threading.Thread(target=main)
thread.start()


I found an interesting problem on https://codeforces.com/problemset/problem/931/A:
Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the point x_1 = a, another one is in the point x_2 = b.

Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2, the third — by 3 and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to 1 + 2 + 3 = 6.

The friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point.

-----Input-----

The first line contains a single integer a (1 ≤ a ≤ 1000) — the initial position of the first friend.

The second line contains a single integer b (1 ≤ b ≤ 1000) — the initial position of the second friend.

It is guaranteed that a ≠ b.

-----Output-----

Print the minimum possible total tiredness if the friends meet in the same point.

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

Output
1

Input
101
99

Output
2

Input
5
10

Output
9

-----Note-----

In the first example the first friend should move by one to the right (then the meeting happens at point 4), or the second friend should move by one to the left (then the meeting happens at point 3). In both cases, the total tiredness becomes 1.

In the second example the first friend should move by one to the left, and the second friend should move by one to the right. Then they meet in the point 100, and the total tiredness becomes 1 + 1 = 2.

In the third example one of the optimal ways is the following. The first friend should move three times to the right, and the second friend — two times to the left. Thus the friends meet in the point 8, and the total tiredness becomes 1 + 2 + 3 + 1 + 2 = 9.

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

a=int(input())
b = int(input())
s = 1
ans = 0
for i in range(abs(b-a)//2):
    ans += s*2
    s +=1
if abs(b-a)%2==1:
    ans += s
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/931/B:
The last stage of Football World Cup is played using the play-off system.

There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over.

Arkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids a and b can meet.

-----Input-----

The only line contains three integers n, a and b (2 ≤ n ≤ 256, 1 ≤ a, b ≤ n) — the total number of teams, and the ids of the teams that Arkady is interested in.

It is guaranteed that n is such that in each round an even number of team advance, and that a and b are not equal.

-----Output-----

In the only line print "Final!" (without quotes), if teams a and b can meet in the Final.

Otherwise, print a single integer — the number of the round in which teams a and b can meet. The round are enumerated from 1.

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

Output
1

Input
8 2 6

Output
Final!

Input
8 7 5

Output
2

-----Note-----

In the first example teams 1 and 2 meet in the first round.

In the second example teams 2 and 6 can only meet in the third round, which is the Final, if they win all their opponents in earlier rounds.

In the third example the teams with ids 7 and 5 can meet in the second round, if they win their opponents in the first round.

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

import math

n, a, b = tuple(map(int, input().split()))

def mr(k,n):
    a = [0]
    for i in range(n//k):
        a.extend([i]*k)
    return a

rounds = {r : mr(2**r, 258) for r in range(1,10)}
#print(len(rounds[1]))

def sol(a, b):
    for i in range(1, 10):
        if rounds[i][a] == rounds[i][b]:
            return i
    return 0

a = sol(a,b)

print(a if a != int(math.log(n,2)) else "Final!")


I found an interesting problem on https://codeforces.com/problemset/problem/931/C:
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.

Kirill has already made his measurements, and has got the following integer values: x_1, x_2, ..., x_{n}. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.

Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y_1, y_2, ..., y_{n} in her work, that the following conditions are met:  the average value of x_1, x_2, ..., x_{n} is equal to the average value of y_1, y_2, ..., y_{n}; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work.

Help Anya to write such a set of measurements that the conditions above are met.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100 000) — the numeber of measurements made by Kirill.

The second line contains a sequence of integers x_1, x_2, ..., x_{n} ( - 100 000 ≤ x_{i} ≤ 100 000) — the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x_1, x_2, ..., x_{n} does not exceed...

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

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

ln = len(set(x))

if ln <= 2 and max(x) - min(x) <= 1:
    print(n)
    print(' '.join(map(str, x)))

else:
    abc = sorted(set(x))

    if len(abc) == 2:
        abc.insert(1, (abc[0] + abc[1]) // 2)

    co = [x.count(el) for el in abc]

    ans = n
    a, b, c = co
    ans_co = [a, b, c]

    while b >= 2:
        b -= 2
        a += 1
        c += 1

        s = min(a, co[0]) + min(b, co[1]) + min(c, co[2])
        if s < ans:
            ans = s
            ans_co = [a, b, c]

    a, b, c = co

    while min(a, c) > 0:
        a -= 1
        c -= 1
        b += 2

        s = min(a, co[0]) + min(b, co[1]) + min(c, co[2])
        if s < ans:
            ans = s
            ans_co = [a, b, c]

    print(ans)
    print(' '.join([' '.join([str(abc[j]) for i in range(ans_co[j])]) for j in range(3)]).strip())


I found an interesting problem on https://codeforces.com/problemset/problem/932/C:
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:

 $f(i, j) = \left\{\begin{array}{ll}{P [ i ]} & {\text{if} j = 1} \\{f(P [ i ], j - 1)} & {\text{otherwise}} \end{array} \right.$

Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.

For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.

-----Input-----

The only line contains three integers N, A, B (1 ≤ N ≤ 10^6, 1 ≤ A, B ≤ N).

-----Output-----

If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.

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

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

Output
1 2 3

-----Note-----

In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5

In the second example, g(1) = g(2) = g(3) = 1

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

n,a,b=map(int,input().split())
p=[i+1 for i in range(n)]
f=0
a,b=min(a,b),max(a,b)
for i in range(0,n+1,a):
	if (n-i)%b==0:
		x=((n-i)//b)
		f=1
		break
if f:
	for i in range(0,b*x,b):
		p[i:i+b]=[p[i+b-1]]+p[i:i+b-1]
	for j in range(b*x,n,a):
		p[j:j+a]=[p[j+a-1]]+p[j:j+a-1]
	print(*p)

else:
	print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/932/E:
You have a team of N people. For a particular task, you can pick any non-empty subset of people. The cost of having x people for the task is x^{k}.

Output the sum of costs over all non-empty subsets of people.

-----Input-----

Only line of input contains two integers N (1 ≤ N ≤ 10^9) representing total number of people and k (1 ≤ k ≤ 5000).

-----Output-----

Output the sum of costs for all non empty subsets modulo 10^9 + 7.

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

Output
1

Input
3 2

Output
24

-----Note-----

In the first example, there is only one non-empty subset {1} with cost 1^1 = 1.

In the second example, there are seven non-empty subsets.

- {1} with cost 1^2 = 1

- {2} with cost 1^2 = 1

- {1, 2} with cost 2^2 = 4

- {3} with cost 1^2 = 1

- {1, 3} with cost 2^2 = 4

- {2, 3} with cost 2^2 = 4

- {1, 2, 3} with cost 3^2 = 9

The total cost is 1 + 1 + 4 + 1 + 4 + 4 + 9 = 24.

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

n, k = map(int, input().split())
m = int(1e9 + 7)
r = 0
p = pow(2, n, m)
a = [1] + [0] * k
for i in range(k):
    for j in range(i, -1, -1):
        a[j + 1] += a[j]
        a[j] = a[j] * j % m
for i in range(k + 1):
    r = (r + p * a[i]) % m
    p = p * 500000004 * (n - i) % m
print(r)


I found an interesting problem on https://codeforces.com/problemset/problem/933/A:
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.

A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a_1, a_2, ..., a_{n}.

Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse a_{l}, a_{l} + 1, ..., a_{r} so that the length of the longest non-decreasing subsequence of the new sequence is maximum.

A non-decreasing subsequence is a sequence of indices p_1, p_2, ..., p_{k}, such that p_1 < p_2 < ... < p_{k} and a_{p}_1 ≤ a_{p}_2 ≤ ... ≤ a_{p}_{k}. The length of the subsequence is k.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence.

The second line contains n space-separated integers, describing the original sequence a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 2, i = 1, 2, ..., n).

-----Output-----

Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.

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

Output
4

Input
10
1 1 2 2 2 1 1 2 2 1

Output
9

-----Note-----

In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.

In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9.

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

n = int(input())
a = list(map(int, input().split()))
dp = [0] * 4
for j in range(n):
	dp = [dp[i] if i == 0 else max(dp[i], dp[i - 1]) for i in range(4)]
	dp = [dp[i] + (1 if i % 2 == a[j] - 1 else 0) for i in range(4)]
print(max(dp))


I found an interesting problem on https://codeforces.com/problemset/problem/933/B:
In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.

Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...

Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients strictly less than k, whose remainder is p when divided by (x + k). That is, f(x) = q(x)·(x + k) + p, where q(x) is a polynomial (not necessarily with integer coefficients).

-----Input-----

The only line of input contains two space-separated integers p and k (1 ≤ p ≤ 10^18, 2 ≤ k ≤ 2 000).

-----Output-----

If the polynomial does not exist, print a single integer -1, or output two lines otherwise.

In the first line print a non-negative integer d — the number of coefficients in the polynomial.

In the second line print d space-separated integers a_0, a_1, ..., a_{d} - 1, describing a polynomial $f(x) = \sum_{i = 0}^{d - 1} a_{i} \cdot x^{i}$ fulfilling the given requirements. Your output should satisfy 0 ≤ a_{i} < k for all 0 ≤ i ≤ d - 1, and a_{d} - 1 ≠ 0.

If there are many possible solutions, print any of them.

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

Output
7
0 1 0 0 1 1 1

Input
2018 214

Output
3
92 205 1

-----Note-----

In the first example, f(x) = x^6 + x^5 + x^4 + x = (x^5 - x^4 + 3x^3 - 6x^2 + 12x - 23)·(x + 2) + 46.

In the second example, f(x) = x^2 + 205x + 92 = (x - 9)·(x + 214) + 2018.

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

p, k = list(map(int, input().split()))
a = ''
cnt = 0
while p != 0:
    cnt += 1
    a += str(p % k) + ' '
    p -= p % k
    p //= -k
print(cnt)
print(a)


I found an interesting problem on https://codeforces.com/problemset/problem/933/C:
Firecrackers scare Nian the monster, but they're wayyyyy too noisy! Maybe fireworks make a nice complement.

Little Tommy is watching a firework show. As circular shapes spread across the sky, a splendid view unfolds on the night of Lunar New Year's eve.

A wonder strikes Tommy. How many regions are formed by the circles on the sky? We consider the sky as a flat plane. A region is a connected part of the plane with positive area, whose bound consists of parts of bounds of the circles and is a curve or several curves without self-intersections, and that does not contain any curve other than its boundaries. Note that exactly one of the regions extends infinitely.

-----Input-----

The first line of input contains one integer n (1 ≤ n ≤ 3), denoting the number of circles.

The following n lines each contains three space-separated integers x, y and r ( - 10 ≤ x, y ≤ 10, 1 ≤ r ≤ 10), describing a circle whose center is (x, y) and the radius is r. No two circles have the same x, y and r at the same time.

-----Output-----

Print a single integer — the number of regions on the plane.

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

Output
4

Input
3
0 0 2
3 0 2
6 0 2

Output
6

Input
3
0 0 2
2 0 2
1 1 2

Output
8

-----Note-----

For the first example, $000$

For the second example, [Image]

For the third example, $\text{Q)}$

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/934/A:
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.

Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a_1, a_2, ..., a_{n}, and Banban's have brightness b_1, b_2, ..., b_{m} respectively.

Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.

Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.

You are asked to find the brightness of the chosen pair if both of them choose optimally.

-----Input-----

The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 50).

The second line contains n space-separated integers a_1, a_2, ..., a_{n}.

The third line contains m space-separated integers b_1, b_2, ..., b_{m}.

All the integers range from  - 10^9 to 10^9.

-----Output-----

Print a single integer — the brightness of the chosen pair.

-----Examples-----
Input
2 2
20 18
2 14

Output
252

Input
5 3
-1 0 1 2 3
-1 0 1

Output
2

-----Note-----

In the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself.

In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself.

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

n,m = list(map(int,input().split()))
l = list(map(int,input().split()))
x = list(map(int,input().split()))
d = {}
for i in l:
	for j in x:
		d[(i,j)] = i*j

c = -9999999999999999999
for i in d:
	if(d[i] > c):
		c = d[i]
		y = i[0]

l.remove(y)
c = -9999999999999999999
for i in l:
	for j in x:
		c = max(c,i*j)
print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/934/B:
Apart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside.

Big Banban is hesitating over the amount of money to give out. He considers loops to be lucky since it symbolizes unity and harmony.

He would like to find a positive integer n not greater than 10^18, such that there are exactly k loops in the decimal representation of n, or determine that such n does not exist.

A loop is a planar area enclosed by lines in the digits' decimal representation written in Arabic numerals. For example, there is one loop in digit 4, two loops in 8 and no loops in 5. Refer to the figure below for all exact forms.

 $0123456789$

-----Input-----

The first and only line contains an integer k (1 ≤ k ≤ 10^6) — the desired number of loops.

-----Output-----

Output an integer — if no such n exists, output -1; otherwise output any such n. In the latter case, your output should be a positive decimal integer not exceeding 10^18.

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

Output
462
Input
6

Output
8080

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

k = int(input())
if k > 36:
	print(-1)
else:
	v = k // 2
	n = k % 2
	print(v * '8' + n * '6')


I found an interesting problem on https://codeforces.com/problemset/problem/935/A:
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.

Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.

Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.

-----Input-----

The input consists of a single line containing a positive integer n (2 ≤ n ≤ 10^5) — the number of employees in Fafa's company.

-----Output-----

Print a single integer representing the answer to the problem.

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

Output
1

Input
10

Output
3

-----Note-----

In the second sample Fafa has 3 ways:  choose only 1 employee as a team leader with 9 employees under his responsibility.  choose 2 employees as team leaders with 4 employees under the responsibility of each of them.  choose 5 employees as team leaders with 1 employee under the responsibility of each of them.

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

n = int(input())
ans = 0
for i in range(1, n):
    if (n - i) % i == 0:
        ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/935/B:
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.

The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation x = y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0, 0), (1, 1), (2, 2), ...). The wall and the gates do not belong to any of the kingdoms.

Fafa is at the gate at position (0, 0) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from (x, y) to (x, y + 1)) and 'R' (move one step right, from (x, y) to (x + 1, y)).

Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point (0, 0), i. e. he is initially on the side he needs.

-----Input-----

The first line of the input contains single integer n (1 ≤ n ≤ 10^5) — the number of moves in the walking sequence.

The second line contains a string S of length n consisting of the characters 'U' and 'R' describing the required moves. Fafa will follow the sequence S in order from left to right.

-----Output-----

On a single line, print one integer representing the number of silver coins Fafa needs to pay at the gates to follow the sequence S.

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

Output
0

Input
6
RURUUR

Output
1

Input
7
URRRUUU

Output
2

-----Note-----

The figure below describes the third sample. The red arrows represent the sequence of moves Fafa will follow. The green gates represent the gates at...

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

N = int(input())
moves = input()

# print(N)
# print(moves)

pos_x, pos_y = 0, 0
coins = 0
kingdom = None
for m in moves:
    if m == "R":
        pos_x += 1
    else:
        pos_y += 1
    if pos_x < pos_y:
        if kingdom == "lower":
            coins += 1
        kingdom = "upper"
    if pos_x > pos_y:
        if kingdom == "upper":
            coins += 1
        kingdom = "lower"

print(coins)


I found an interesting problem on https://codeforces.com/problemset/problem/935/C:
Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius R. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.

The world is represented as an infinite 2D plane. The flat is centered at (x_1, y_1) and has radius R and Fafa's laptop is located at (x_2, y_2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area.

-----Input-----

The single line of the input contains 5 space-separated integers R, x_1, y_1, x_2, y_2 (1 ≤ R ≤ 10^5, |x_1|, |y_1|, |x_2|, |y_2| ≤ 10^5).

-----Output-----

Print three space-separated numbers x_{ap}, y_{ap}, r where (x_{ap}, y_{ap}) is the position which Fifa chose for the access point and r is the radius of its range.

Your answer will be considered correct if the radius does not differ from optimal more than 10^{ - 6} absolutely or relatively, and also the radius you printed can be changed by no more than 10^{ - 6} (absolutely or relatively) in such a way that all points outside the flat and Fafa's laptop position are outside circle of the access point range.

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

Output
3.7677669529663684 3.7677669529663684 3.914213562373095

Input
10 5 5 5 15

Output
5.0 5.0 10.0

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

def main():
    R, x1, y1, x2, y2 = list(map(int, input().split()))

    if (x1 - x2) ** 2 + (y1 - y2) ** 2 >= R ** 2:
        return x1, y1, R

    if x1 == x2 and y1 == y2:
        return x1 + 0.5 * R, y1, 0.5 * R

    vx = x1 - x2
    vy = y1 - y2
    vnorm = (vx**2 + vy**2) ** 0.5
    r = R / vnorm

    return (0.5 * (x1 + x2 + vx * r),
            0.5 * (y1 + y2 + vy * r),
            0.5 * (R + vnorm))

def __starting_point():
    x, y, R = main()
    print(x, y, R)

__starting_point()