I found an interesting problem on https://codeforces.com/problemset/problem/556/B:
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.

Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.

Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.

Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 1000) — the number of gears.

The second line contains n digits a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ n - 1) — the sequence of active teeth: the active tooth of the i-th gear contains number a_{i}.

-----Output-----

In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.

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

Output
Yes

Input
5
4 2 1 4 3

Output
Yes

Input
4
0 2 3 1

Output
No

-----Note-----

In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.

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

import sys

n = int(input())
a = list(map(int,input().split()))
for i in range(n+1) :
          for j in range(n) :
                    if j%2 : a[j]-=1
                    else : a[j]+=1
                    a[j]%=n
          if a==list(range(n)) :
                    print('Yes')
                    return
print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/556/E:
Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom.

A bar of chocolate can be presented as an n × n table, where each cell represents one piece of chocolate. The columns of the table are numbered from 1 to n from left to right and the rows are numbered from top to bottom. Let's call the anti-diagonal to be a diagonal that goes the lower left corner to the upper right corner of the table. First Andrewid eats all the pieces lying below the anti-diagonal. Then he performs the following q actions with the remaining triangular part: first, he chooses a piece on the anti-diagonal and either direction 'up' or 'left', and then he begins to eat all the pieces starting from the selected cell, moving in the selected direction until he reaches the already eaten piece or chocolate bar edge.

After each action, he wants to know how many pieces he ate as a result of this action.

-----Input-----

The first line contains integers n (1 ≤ n ≤ 10^9) and q (1 ≤ q ≤ 2·10^5) — the size of the chocolate bar and the number of actions.

Next q lines contain the descriptions of the actions: the i-th of them contains numbers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ n, x_{i} + y_{i} = n + 1) — the numbers of the column and row of the chosen cell and the character that represents the direction (L — left, U — up).

-----Output-----

Print q lines, the i-th of them should contain the number of eaten pieces as a result of the i-th action.

-----Examples-----
Input
6 5
3 4 U
6 1 L
2 5 L
1 6 U
4 3 U

Output
4
3
2
1
2

Input
10 6
2 9 U
10 1 U
1 10 U
8 3 L
10 1 L
6 5 U

Output
9
1
10
6
0
2

-----Note-----

Pictures to the sample tests:

[Image]

The pieces that were eaten in the same action are painted the same color. The pieces lying on the anti-diagonal contain the numbers of the action as a result of which these pieces were eaten.

In the second sample test the Andrewid tries to start eating chocolate for the second time during his fifth action, starting from the...

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

import sys
from bisect import bisect

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

def solve():
	n, q = list(map(int, input().split()))
	was = set()
	Q = [None]*q
	all = [0]*(2*q)
	for i in range(q):
		x, y, t = input().split()
		x, y = int(x), int(y)
		Q[i] = (x, y, t)
		all[2*i] = x
		all[2*i+1] = y
	all.sort()
	i = 0
	p = -1
	for j in range(2*q):
		v = all[j]
		if v != p:
			all[i] = v
			i += 1
		p = v
	sz = i
	all = all[:sz]
	V = [0]*(2*sz)
	H = [0]*(2*sz)
	for x, y, t in Q:
		if (x,y) in was:
			print(0)
		else:
			was.add((x,y))
			if t == 'L':
				TA = H
				TB = V
			else:
				x, y = y, x
				TA = V
				TB = H
			v = bisect(all, y) - 1 + sz
			r = 0
			while v > 0:
				r = max(r, TA[v])
				v //= 2
			c = x - r
			print(c)
			r = bisect(all, x) - 1 + sz
			l = bisect(all, x - c) + sz
			while l <= r:
				if l % 2 == 1:
					TB[l] = max(TB[l], y)
				if r % 2 == 0:
					TB[r] = max(TB[r], y)
				l = (l+1)//2
				r = (r-1)//2

solve()


I found an interesting problem on https://codeforces.com/problemset/problem/557/A:
Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there.

At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma.

They also decided that there must be given at least min_1 and at most max_1 diplomas of the first degree, at least min_2 and at most max_2 diplomas of the second degree, and at least min_3 and at most max_3 diplomas of the third degree.

After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree.

Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations.

It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree.

-----Input-----

The first line of the input contains a single integer n (3 ≤ n ≤ 3·10^6) — the number of schoolchildren who will participate in the Olympiad.

The next line of the input contains two integers min_1 and max_1 (1 ≤ min_1 ≤ max_1 ≤ 10^6) — the minimum and maximum limits on the number of diplomas of the first degree that can be distributed.

The third line of the input contains two integers min_2 and max_2 (1 ≤ min_2 ≤ max_2 ≤ 10^6) — the minimum and maximum limits on the number of diplomas of the...

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

n = int(input())
m_1, mx_1 = list(map(int, input().split()))
m_2, mx_2 = list(map(int, input().split()))
m_3, mx_3 = list(map(int, input().split()))
ans = [m_1, m_2, m_3]
s = sum(ans)
if s == n:
    print(*ans)
else:
    ans[0] += min(n - s, mx_1 - m_1)
    if ans[0] == mx_1:
        s += mx_1 - m_1
        ans[1] += min(n - s, mx_2 - m_2)
        if ans[1] == mx_2:
            s += mx_2 - m_2
            ans[2] += min(n - s, mx_3 - m_3)
    print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/557/B:
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most a_{i} milliliters of water.

It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows:  Pasha can boil the teapot exactly once by pouring there at most w milliliters of water;  Pasha pours the same amount of water to each girl;  Pasha pours the same amount of water to each boy;  if each girl gets x milliliters of water, then each boy gets 2x milliliters of water.

In the other words, each boy should get two times more water than each girl does.

Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.

-----Input-----

The first line of the input contains two integers, n and w (1 ≤ n ≤ 10^5, 1 ≤ w ≤ 10^9) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters.

The second line of the input contains the sequence of integers a_{i} (1 ≤ a_{i} ≤ 10^9, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters.

-----Output-----

Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{ - 6}.

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

Output
3
Input
3 18
4 4 4 2 2 2

Output
18
Input
1 5
2 3

Output
4.5

-----Note-----

Pasha also has candies that he is going to give to girls but that is another task...

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

__author__ = 'Andrey'
n, w = map(int, input().split())
volumes = list(map(int, input().split()))
volumes.sort()
m = -1
if volumes[0] * 2 <= volumes[n]:
    possible = 3 * n * volumes[0]
    if possible <= w:
        m = max(m, possible)
if volumes[n] / 2 <= volumes[0]:
    possible = volumes[n] / 2 * 3 * n
    if possible <= w:
        m = max(m, possible)
if w / (3 * n) <= volumes[0] and 2 * w / (3 * n) <= volumes[n]:
    m = max(m, w)
print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/557/C:
Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable.

In total the table Arthur bought has n legs, the length of the i-th leg is l_{i}.

Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number d_{i} — the amount of energy that he spends to remove the i-th leg.

A table with k legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with 5 legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths.

Your task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 10^5) — the initial number of legs in the table Arthur bought.

The second line of the input contains a sequence of n integers l_{i} (1 ≤ l_{i} ≤ 10^5), where l_{i} is equal to the length of the i-th leg of the table.

The third line of the input contains a sequence of n integers d_{i} (1 ≤ d_{i} ≤ 200), where d_{i} is the number of energy units that Arthur spends on removing the i-th leg off the table.

-----Output-----

Print a single integer — the minimum number of energy units that Arthur needs to spend in order to make the table stable.

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

Output
2

Input
3
2 4 4
1 1 1

Output
0

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

Output
8

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

f = lambda: map(int, input().split())
k, n = 1, f()
s = sorted(zip(f(), f()), key=lambda q: q[0])

t = [0] * 201
for l, d in s: t[d] += 1

j = [i for i in range(201) if t[i]]
j.reverse()

S = sum(i * t[i] for i in j)
L, D = s.pop()
t[D] -= 1
s.reverse()
s.append((0, 0))

m = 0
for l, d in s:
    if l < L:
        L = l
        for i in j:
            if t[i] > k - 2:
                D += i * (k - 1)
                break
            D += i * t[i]
            k -= t[i]
        m = max(m, D)
        k = D = 0
    k += 1
    D += d

    t[d] -= 1
    if not t[d]: j.remove(d)

print(S - m)


I found an interesting problem on https://codeforces.com/problemset/problem/557/D:
After Vitaly was expelled from the university, he became interested in the graph theory.

Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.

Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.

Two ways to add edges to the graph are considered equal if they have the same sets of added edges.

Since Vitaly does not study at the university, he asked you to help him with this task.

-----Input-----

The first line of the input contains two integers n and m ($3 \leq n \leq 10^{5}, 0 \leq m \leq \operatorname{min}(\frac{n(n - 1)}{2}, 10^{5})$ — the number of vertices in the graph and the number of edges in the graph.

Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.

It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.

-----Output-----

Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.

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

Output
1 2

Input
3 3
1 2
2 3
3 1

Output
0 1

Input
3 0

Output
3 1

-----Note-----

The simple cycle is a cycle that...

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

def main():
    N, M = (int(i) for i in input().split())

    par = [i for i in range(N)]
    size = [1 for i in range(N)]

    def find(x):
        if par[x] == x:
            return x
        else:
            par[x] = find(par[x])
            size[x] = size[par[x]]
            return par[x]

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

    def union(x, y):
        x = find(x)
        y = find(y)
        if x == y:
            return
        if size[x] < size[y]:
            x, y = y, x
        size[x] += size[y]
        par[y] = x

    def get_size(x):
        return size[find(x)]

    G = [[] for _ in range(N)]
    for _ in range(M):
        a, b = (int(i) for i in input().split())
        G[a-1].append(b-1)
        G[b-1].append(a-1)
        union(a-1, b-1)

    S = [False]*4
    for i in range(N):
        S[min(3, get_size(i))] = True
        if S[3]:
            break
    t = 0
    if S[3]:
        t = 1
    elif S[2]:
        t = 2
    else:
        t = 3

    color = [-1]*N

    def dfs(s):
        stack = [s]
        color[s] = 0
        b = 1
        w = 0
        while stack:
            v = stack.pop()
            for u in G[v]:
                if color[u] != -1:
                    if color[u] == color[v]:
                        return False, b*w
                    continue
                color[u] = color[v] ^ 1
                if color[u] == 0:
                    b += 1
                else:
                    w += 1
                stack.append(u)
        return True, b*(b-1)//2 + w*(w-1)//2

    is_bipartite, _ = dfs(0)
    if is_bipartite:
        w = 0
        if t == 3:
            w = N*(N-1)*(N-2)//3//2
        elif t == 2:
            used = [False]*N
            for i in range(N):
                if not used[find(i)] and get_size(i) == 2:
                    w += (N-2)
                    used[find(i)] = True
        elif t == 1:
            used = [False]*N
            color = [-1]*N
            for i in range(N):
                if not used[find(i)] and get_size(i) >=...


I found an interesting problem on https://codeforces.com/problemset/problem/558/A:
Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.

Lala Land has exactly n apple trees. Tree number i is located in a position x_{i} and has a_{i} apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x = 0 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing.

What is the maximum number of apples he can collect?

-----Input-----

The first line contains one number n (1 ≤ n ≤ 100), the number of apple trees in Lala Land.

The following n lines contains two integers each x_{i}, a_{i} ( - 10^5 ≤ x_{i} ≤ 10^5, x_{i} ≠ 0, 1 ≤ a_{i} ≤ 10^5), representing the position of the i-th tree and number of apples on it.

It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0.

-----Output-----

Output the maximum number of apples Amr can collect.

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

Output
10
Input
3
-2 2
1 4
-1 3

Output
9
Input
3
1 9
3 5
7 10

Output
9

-----Note-----

In the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples.

In the second sample test the optimal solution is to go left to x =  - 1, collect apples from there, then the direction will be reversed, Amr has to go to x = 1, collect apples from there, then the direction will be reversed and Amr goes to the final tree x =  - 2.

In the third sample test the optimal solution is to go right to x = 1, collect apples from there, then...

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

n = int(input())

a = []
b = []

for i in range(n):
	x,y = map(int,input().split())
	if x >= 0:
		a.append((x,y))
	else:
		b.append((x,y))

a.sort(key=lambda tup:tup[0])
b.sort(key=lambda tup:tup[0])
b = b[::-1]

minLength = min(len(a),len(b))

total = 0

for i in range(minLength):
	total += b[i][1] + a[i][1]

if(len(a) > minLength):
	total += a[minLength][1]
elif(len(b) > minLength):
	total += b[minLength][1]

print(total)


I found an interesting problem on https://codeforces.com/problemset/problem/558/B:
Amr has got a large array of size n. Amr doesn't like large arrays so he intends to make it smaller.

Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array.

Help Amr by choosing the smallest subsegment possible.

-----Input-----

The first line contains one number n (1 ≤ n ≤ 10^5), the size of the array.

The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^6), representing elements of the array.

-----Output-----

Output two integers l, r (1 ≤ l ≤ r ≤ n), the beginning and the end of the subsegment chosen respectively.

If there are several possible answers you may output any of them.

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

Output
1 5
Input
5
1 2 2 3 1

Output
2 3
Input
6
1 2 2 1 1 2

Output
1 5

-----Note-----

A subsegment B of an array A from l to r is an array of size r - l + 1 where B_{i} = A_{l} + i - 1 for all 1 ≤ i ≤ r - l + 1

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

N = int(input())
A = [int(x) for x in input().split()]
bucket = dict()
for i, num in enumerate(A):
    if num in bucket:
        bucket[num].append(i)
    else:
        bucket[num] = [i]
#print(bucket)
sorted_buckets = sorted((-len(val), val[-1]-val[0], val) for _, val in list(bucket.items()))
print(sorted_buckets[0][2][0]+1, sorted_buckets[0][2][-1]+1)


I found an interesting problem on https://codeforces.com/problemset/problem/558/C:
Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.

Amr has n different types of chemicals. Each chemical i has an initial volume of a_{i} liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.

To do this, Amr can do two different kind of operations.   Choose some chemical i and double its current volume so the new volume will be 2a_{i}  Choose some chemical i and divide its volume by two (integer division) so the new volume will be $\lfloor \frac{a_{i}}{2} \rfloor$

Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?

-----Input-----

The first line contains one number n (1 ≤ n ≤ 10^5), the number of chemicals.

The second line contains n space separated integers a_{i} (1 ≤ a_{i} ≤ 10^5), representing the initial volume of the i-th chemical in liters.

-----Output-----

Output one integer the minimum number of operations required to make all the chemicals volumes equal.

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

Output
2
Input
3
3 5 6

Output
5

-----Note-----

In the first sample test, the optimal solution is to divide the second chemical volume by two, and multiply the third chemical volume by two to make all the volumes equal 4.

In the second sample test, the optimal solution is to divide the first chemical volume by two, and divide the second and the third chemical volumes by two twice to make all the volumes equal 1.

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

from collections import Counter

def main():
    input()
    aa = list(map(int, input().split()))
    le, l = max(aa).bit_length(), []
    for i, a in enumerate(aa):
        j = le - a.bit_length()
        aa[i] = a << j
        l.append(j)
    mi, ma = min(aa), max(aa)
    a = mask = (1 << le) - 1
    if mi == ma:
        while mi == mi & a:
            mask = a
            a &= a << 1
    else:
        while mi != ma or not (mi & 1):
            mask &= mask << 1
            mi >>= 1
            ma >>= 1
    mask ^= (1 << le) - 1
    le, cnt = mask.bit_length(), Counter()
    for a, i in zip(aa, l):
        a &= mask
        if a:
            a = a.bit_length()
        cnt[i, a] += 1
    res = [0] * (le + 1)
    for (i, a), c in list(cnt.items()):
        if a:
            base, baseidx = (a - i) * c, le - a
        else:
            base, baseidx = 0, le - i
        j = base
        for i in range(baseidx - 1, -1, -1):
            j += c
            res[i] += j
        j = base
        for i in range(baseidx, le + 1):
            res[i] += j
            j += c
    print(min(res))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/558/D:
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.

Let's index all the nodes of the tree such that   The root is number 1  Each internal node i (i ≤ 2^{h} - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1

The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out!

In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.

Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.

-----Input-----

The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 10^5), the height of the tree and the number of questions respectively.

The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2^{i} - 1 ≤ L ≤ R ≤ 2^{i} - 1, $\text{ans} \in \{0,1 \}$), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0...

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


I found an interesting problem on https://codeforces.com/problemset/problem/559/A:
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to $120^{\circ}$. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.

He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.

-----Input-----

The first and the single line of the input contains 6 space-separated integers a_1, a_2, a_3, a_4, a_5 and a_6 (1 ≤ a_{i} ≤ 1000) — the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists.

-----Output-----

Print a single integer — the number of triangles with the sides of one 1 centimeter, into which the hexagon is split.

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

Output
6

Input
1 2 1 2 1 2

Output
13

-----Note-----

This is what Gerald's hexagon looks like in the first sample:

$\theta$

And that's what it looks like in the second sample:

$A$

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

a,b,c,d,e,f = map(int,input().split())
print((a+b+c)**2-a*a-c*c-e*e)


I found an interesting problem on https://codeforces.com/problemset/problem/559/B:
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:   They are equal.  If we split string a into two halves of the same size a_1 and a_2, and string b into two halves of the same size b_1 and b_2, then one of the following is correct:   a_1 is equivalent to b_1, and a_2 is equivalent to b_2  a_1 is equivalent to b_2, and a_2 is equivalent to b_1

As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.

Gerald has already completed this home task. Now it's your turn!

-----Input-----

The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.

-----Output-----

Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.

-----Examples-----
Input
aaba
abaa

Output
YES

Input
aabb
abab

Output
NO

-----Note-----

In the first sample you should split the first string into strings "aa" and "ba", the second one — into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".

In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa".

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

def read_list(t): return [t(x) for x in input().split()]
def read_line(t): return t(input())
def read_lines(t, N): return [t(input()) for _ in range(N)]

def smallest(s):
    len_s = len(s)
    if len_s & 1:
        return s
    s1 = smallest(s[:len_s//2])
    s2 = smallest(s[len_s//2:])
    return s1 + s2 if s1 < s2 else s2 + s1

S1 = read_line(str)
S2 = read_line(str)
print('YES' if smallest(S1) == smallest(S2) else 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/560/A:
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?

-----Input-----

The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion.

The second line contains n distinct space-separated numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — the values of the banknotes.

-----Output-----

Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print  - 1.

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

Output
-1

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

d = input()
d = int(d)
st1 = input()
notes = [ int(i) for i in st1.split(" ") ]

def unfortunate_sum(notes):
    if 1 in notes:
        print(-1)
        return
    else:
        print(1)
        return

unfortunate_sum(notes)


I found an interesting problem on https://codeforces.com/problemset/problem/560/B:
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an a_1 × b_1 rectangle, the paintings have shape of a a_2 × b_2 and a_3 × b_3 rectangles.

Since the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough?

-----Input-----

The first line contains two space-separated numbers a_1 and b_1 — the sides of the board. Next two lines contain numbers a_2, b_2, a_3 and b_3 — the sides of the paintings. All numbers a_{i}, b_{i} in the input are integers and fit into the range from 1 to 1000.

-----Output-----

If the paintings can be placed on the wall, print "YES" (without the quotes), and if they cannot, print "NO" (without the quotes).

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

Output
YES

Input
5 5
3 3
3 3

Output
NO

Input
4 2
2 3
1 2

Output
YES

-----Note-----

That's how we can place the pictures in the first test:

[Image]

And that's how we can do it in the third one.

[Image]

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

# mukulchandel
a1,b1=list(map(int,input().split()))
a2,b2=list(map(int,input().split()))
a3,b3=list(map(int,input().split()))
if a1>=(a2+a3) and b1>=max(b2,b3):
    print("YES")
elif a1>=(a2+b3) and b1>=max(b2,a3):
    print("YES")
elif a1>=(b2+a3) and b1>=max(a2,b3):
    print("YES")
elif a1>=(b2+b3) and b1>=max(a2,a3):
    print("YES")
elif b1>=(a2+a3) and a1>=max(b2,b3):
    print("YES")
elif b1>=(a2+b3) and a1>=max(b2,a3):
    print("YES")
elif b1>=(b2+a3) and a1>=max(a2,b3):
    print("YES")
elif b1>=(b2+b3) and a1>=max(a2,a3):
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/566/A:
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.

There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as $\operatorname{lcp}(a, b)$. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.

Find the matching between students and pseudonyms with the maximum quality.

-----Input-----

The first line contains number n (1 ≤ n ≤ 100 000) — the number of students in the summer school.

Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating.

The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating.

The total length of all the names and pseudonyms doesn't exceed 800 000 characters.

-----Output-----

In the first line print the maximum possible quality of matching pseudonyms to students.

In the next n lines describe the optimal matching. Each line must have the form a b (1 ≤ a, b ≤ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input.

The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.

-----Examples-----
Input
5
gennady
galya
boris
bill
toshik
bilbo
torin
gendalf
smaug
galadriel

Output
11
4 1
2 5
1 3
5...

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

import sys

SIGMA = 26

nodes = []
pairs = []
res = 0

class Node:
    def __init__(self):
        self.ch = {}
        self.a = []
        self.b = []
        self.d = 0

    def add(self, s, i):
        t = self
        for c in s:
            v = ord(c) - ord('a')
            if not v in t.ch:
                t.ch[v] = Node()
                t.ch[v].d = t.d + 1
                nodes.append(t.ch[v])
            t = t.ch[v]
        t.a.append(i)

    def inc(self, s, i):
        t = self
        for c in s:
            v = ord(c) - ord('a')
            if not v in t.ch:
                break
            t = t.ch[v]
        t.b.append(i)

    def solve(self):
        nonlocal pairs
        nonlocal res
        for i in range(SIGMA):
            if i in self.ch:
                self.a.extend(self.ch[i].a)
                self.b.extend(self.ch[i].b)
        k = min(len(self.a), len(self.b))
        for i in range(k):
            pairs.append(str(self.a[-1]) + ' ' + str(self.b[-1]))
            self.a.pop()
            self.b.pop()
            res += self.d
        return res

sys.setrecursionlimit(2000000)
_input = sys.stdin.readlines()
_input = [s[:-1] for s in _input]
N = int(_input[0])
A = _input[1 : N + 1]
B = _input[N + 1 :]
T = Node()
nodes.append(T)
for i, s in enumerate(A):
    T.add(s, i + 1)
for i, s in enumerate(B):
    T.inc(s, i + 1)
for n in reversed(nodes):
    n.solve()
print(res)
print('\n'.join(pairs))


I found an interesting problem on https://codeforces.com/problemset/problem/566/B:
A Large Software Company develops its own social network. Analysts have found that during the holidays, major sporting events and other significant events users begin to enter the network more frequently, resulting in great load increase on the infrastructure.

As part of this task, we assume that the social network is 4n processes running on the n servers. All servers are absolutely identical machines, each of which has a volume of RAM of 1 GB = 1024 MB ^{(1)}. Each process takes 100 MB of RAM on the server. At the same time, the needs of maintaining the viability of the server takes about 100 more megabytes of RAM. Thus, each server may have up to 9 different processes of social network.

Now each of the n servers is running exactly 4 processes. However, at the moment of peak load it is sometimes necessary to replicate the existing 4n processes by creating 8n new processes instead of the old ones. More formally, there is a set of replication rules, the i-th (1 ≤ i ≤ 4n) of which has the form of a_{i} → (b_{i}, c_{i}), where a_{i}, b_{i} and c_{i} (1 ≤ a_{i}, b_{i}, c_{i} ≤ n) are the numbers of servers. This means that instead of an old process running on server a_{i}, there should appear two new copies of the process running on servers b_{i} and c_{i}. The two new replicated processes can be on the same server (i.e., b_{i} may be equal to c_{i}) or even on the same server where the original process was (i.e. a_{i} may be equal to b_{i} or c_{i}). During the implementation of the rule a_{i} → (b_{i}, c_{i}) first the process from the server a_{i} is destroyed, then appears a process on the server b_{i}, then appears a process on the server c_{i}.

There is a set of 4n rules, destroying all the original 4n processes from n servers, and creating after their application 8n replicated processes, besides, on each of the n servers will be exactly 8 processes. However, the rules can only be applied consecutively, and therefore the amount of RAM of the servers imposes limitations on the procedure for the...

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

from collections import deque
import random

class CodeforcesTask566BSolution:
    def __init__(self):
        self.result = ''
        self.n = 0
        self.rules = []

    def read_input(self):
        self.n = int(input())
        self.rules = [[int(x) for x in input().split(" ")] + [y + 1] for y in range(self.n * 4)]

    def process_task(self):

        loads = [4] * self.n
        random.shuffle(self.rules)
        to_use = deque(self.rules)
        order = []
        res = True
        ba = 0
        while to_use and res:
            moving = to_use.popleft()
            loads[moving[0] - 1] -= 1
            if loads[moving[1] - 1] < 9 and loads[moving[2] - 1] < 9 + (-1 if moving[2] == moving[1] else 0):
                ba = 0
                loads[moving[1] - 1] += 1
                loads[moving[2] - 1] += 1
                order.append(moving[3])
            else:
                ba += 1
                loads[moving[0] - 1] += 1
                to_use.append(moving)
            if ba > self.n * 12:
                res = False
        self.result = "NO" if not res else f"YES\n{' '.join([str(x) for x in order])}"

    def get_result(self):
        return self.result

def __starting_point():
    Solution = CodeforcesTask566BSolution()
    Solution.read_input()
    Solution.process_task()
    print(Solution.get_result())

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/566/F:
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.

Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.

Let's define a divisibility graph for a set of positive integers A = {a_1, a_2, ..., a_{n}} as follows. The vertices of the given graph are numbers from set A, and two numbers a_{i} and a_{j} (i ≠ j) are connected by an edge if and only if either a_{i} is divisible by a_{j}, or a_{j} is divisible by a_{i}.

You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^6), that sets the size of set A.

The second line contains n distinct positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — elements of subset A. The numbers in the line follow in the ascending order.

-----Output-----

Print a single number — the maximum size of a clique in a divisibility graph for set A.

-----Examples-----
Input
8
3 4 6 8 10 18 21 24

Output
3

-----Note-----

In the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.

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

N = int(input())
List = [int(x) for x in input().split()]
MAX = 1000001
dp = [0] * MAX
for i in List:
    dp[i] += 1
for i in range(N):
    if(dp[List[i]]):
        for j in range(List[i]*2,MAX, List[i]):
            if(dp[j]):
                dp[j] = max(dp[j], dp[List[i]]+1)
print(max(dp))


I found an interesting problem on https://codeforces.com/problemset/problem/567/A:
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position x_{i} — a coordinate on the Ox axis. No two cities are located at a single point.

Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).

Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.

For each city calculate two values min_{i} and max_{i}, where min_{i} is the minimum cost of sending a letter from the i-th city to some other city, and max_{i} is the the maximum cost of sending a letter from the i-th city to some other city

-----Input-----

The first line of the input contains integer n (2 ≤ n ≤ 10^5) — the number of cities in Lineland. The second line contains the sequence of n distinct integers x_1, x_2, ..., x_{n} ( - 10^9 ≤ x_{i} ≤ 10^9), where x_{i} is the x-coordinate of the i-th city. All the x_{i}'s are distinct and follow in ascending order.

-----Output-----

Print n lines, the i-th line must contain two integers min_{i}, max_{i}, separated by a space, where min_{i} is the minimum cost of sending a letter from the i-th city, and max_{i} is the maximum cost of sending a letter from the i-th city.

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

Output
3 12
3 9
4 7
5 12

Input
2
-1 1

Output
2 2
2 2

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


I found an interesting problem on https://codeforces.com/problemset/problem/567/B:
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.

Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 10^6. Thus, the system logs events of two forms:  "+ r_{i}" — the reader with registration number r_{i} entered the room;  "- r_{i}" — the reader with registration number r_{i} left the room.

The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.

Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.

Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

-----Input-----

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ r_{i}" or "- r_{i}", where r_{i} is an integer from 1 to 10^6, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers).

It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system,...

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

n = int(input())
col = 0
max = 0
p = []
q = []
e = []
for i in range(n):
    a, b = list(input().split())
    b = int(b)
    q.append([a, b])
    if a == '-' and b not in p:
        col += 1
        e.append(b)
    p.append(b)
for i in range(n):
    if col >= max:
        max = col
    if q[i][0] == '+':
        e.append(q[i][1])
        col += 1
    else:
        e.remove(q[i][1])
        col -= 1
    if col >= max:
        max = col
print(max)


I found an interesting problem on https://codeforces.com/problemset/problem/567/C:
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.

He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.

A subsequence of length three is a combination of three such indexes i_1, i_2, i_3, that 1 ≤ i_1 < i_2 < i_3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.

A geometric progression with common ratio k is a sequence of numbers of the form b·k^0, b·k^1, ..., b·k^{r} - 1.

Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.

-----Input-----

The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·10^5), showing how many numbers Polycarp's sequence has and his favorite number.

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

-----Output-----

Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.

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

Output
4
Input
3 1
1 1 1

Output
1
Input
10 3
1 2 6 2 3 6 9 18 3 9

Output
6

-----Note-----

In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.

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

n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
z = dict()
s = 0
for i in range(n):
    if not a[i] in z:
        z[a[i]] = [0, 0, 0]
    if a[i] % (k * k) == 0 and a[i] // k in z:
        q = z[a[i] // k][1]
        z[a[i]][2] += z[a[i] // k][1]
        s += q
    if a[i] % k == 0 and a[i] // k in z:
        z[a[i]][1] += z[a[i] // k][0]
    z[a[i]][0] += 1
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/567/D:
Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of n square cells (that is, on a 1 × n table).

At the beginning of the game Alice puts k ships on the field without telling their positions to Bob. Each ship looks as a 1 × a rectangle (that is, it occupies a sequence of a consecutive squares of the field). The ships cannot intersect and even touch each other.

After that Bob makes a sequence of "shots". He names cells of the field and Alice either says that the cell is empty ("miss"), or that the cell belongs to some ship ("hit").

But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a "miss".

Help Bob catch Alice cheating — find Bob's first move, such that after it you can be sure that Alice cheated.

-----Input-----

The first line of the input contains three integers: n, k and a (1 ≤ n, k, a ≤ 2·10^5) — the size of the field, the number of the ships and the size of each ship. It is guaranteed that the n, k and a are such that you can put k ships of size a on the field, so that no two ships intersect or touch each other.

The second line contains integer m (1 ≤ m ≤ n) — the number of Bob's moves.

The third line contains m distinct integers x_1, x_2, ..., x_{m}, where x_{i} is the number of the cell where Bob made the i-th shot. The cells are numbered from left to right from 1 to n.

-----Output-----

Print a single integer — the number of such Bob's first move, after which you can be sure that Alice lied. Bob's moves are numbered from 1 to m in the order the were made. If the sought move doesn't exist, then print "-1".

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

Output
3

Input
5 1 3
2
1 5

Output
-1

Input
5 1 3
1
3

Output
1

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

n,k,a=list(map(int,input().split()))
m=int(input())+1
x=list(map(int,input().split()))+[0]
l,r=0,m
while r-l>1:
	d=(l+r)//2
	y=sorted(x[:d])
	if sum((q-p)//(a+1) for p,q in zip([0]+y,y+[n+1]))>=k:l=d
	else:r=d
print(r%m-(r==m))


I found an interesting problem on https://codeforces.com/problemset/problem/567/E:
Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer.

Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest.

The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer.

-----Input-----

The first lines contain four integers n, m, s and t (2 ≤ n ≤ 10^5; 1 ≤ m ≤ 10^5; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t).

Next m lines contain the roads. Each road is given as a group of three integers a_{i}, b_{i}, l_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}; 1 ≤ l_{i} ≤ 10^6) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city a_{i} to city b_{i}.

The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads.

-----Output-----

Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input).

If the president...

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

from heapq import *
from collections import defaultdict
def D(v,g):
	h,p,o=[],defaultdict(lambda:1e99),[]
	heappush(h,(0,v))
	while h:
		l,w=heappop(h)
		if w in p:continue
		p[w]=l
		o.append(w)
		for u,L in g[w]:
			heappush(h,(L+l,u))
	return p,o
n,m,s,t=list(map(int,input().split()))
r=[]
g={i+1:[] for i in range(n)}
G={i+1:[] for i in range(n)}
for _ in range(m):
	a,b,l=list(map(int,input().split()))
	r.append((a,b,l))
	g[a].append((b,l))
	G[b].append((a,l))
S,o=D(s,g)
T,_=D(t,G)
L=S[t]
H={v:[w for w,l in e if S[v]+T[w]+l==L] for v,e in list(g.items())}
B,A=set(),{s}
for v in o:
	if not H[v]:continue
	if 1==len(A)==len(H[v]):B.add(v)
	A.update(H[v])
	A.remove(v)
print('\n'.join("YES" if a in B and S[a]+T[b]+l==L else "CAN "+str(S[a]+T[b]+l-L+1) if S[a]+T[b]+1<L else "NO" for a,b,l in r))


I found an interesting problem on https://codeforces.com/problemset/problem/567/F:
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.

The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.

The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:

  [1, 2, 2, 3, 4, 4, 3, 1];  [1, 1];  [2, 2, 1, 1];  [1, 2, 3, 3, 2, 1].

Suddenly, k more requirements appeared. Each of the requirements has the form: "h[x_{i}] sign_{i} h[y_{i}]", where h[t] is the height of the t-th block, and a sign_{i} is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ 2n) and sign sign_{i}.

Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.

-----Input-----

The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements.

Next k lines contain listed additional requirements, one per line in the...

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

def check(l, r, a, b):
    if a < 0 or b >= 2 * N:
        return 0
    def val(p):
        if p in [a, b]: return '0'
        if l <= p and p < r: return '1'
        return '-1'
    for i in range(K):
        x, y = val(A[i]), val(C[i])
        if A[i] in [a, b] or C[i] in [a, b]:
            if not eval(x + B[i] + y):
                return 0
    return 1

N, K = list(map(int, input().split()))
tmp = [input().split() for i in range(K)]
try: A, B, C = list(zip(*tmp))
except: A, B, C = [], [], []
A = [int(x) - 1 for x in A]
B = ['==' if x is '=' else x for x in B]
C = [int(x) - 1 for x in C]

dp = []
for i in range(N + 1):
    dp.append([0] * (2 * N + 1))

dp[N][0] = 1
for i in range(N, 0, -1):
    for j in range(0, 2 * (N - i) + 3):
        d, k = 0, j + 2 * i - 2
        if check(j, k, j - 2, j - 1): d += dp[i][j - 2]
        if check(j, k, j - 1, k): d += dp[i][j - 1]
        if check(j, k, k, k + 1): d += dp[i][j]
        dp[i - 1][j] = d

print(sum(dp[0]) // 3)


I found an interesting problem on https://codeforces.com/problemset/problem/568/A:
Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this!

Let us remind you that a number is called prime if it is integer larger than one, and is not divisible by any positive integer other than itself and one.

Rikhail calls a number a palindromic if it is integer, positive, and its decimal representation without leading zeros is a palindrome, i.e. reads the same from left to right and right to left.

One problem with prime numbers is that there are too many of them. Let's introduce the following notation: π(n) — the number of primes no larger than n, rub(n) — the number of palindromic numbers no larger than n. Rikhail wants to prove that there are a lot more primes than palindromic ones.

He asked you to solve the following problem: for a given value of the coefficient A find the maximum n, such that π(n) ≤ A·rub(n).

-----Input-----

The input consists of two positive integers p, q, the numerator and denominator of the fraction that is the value of A ($A = \frac{p}{q}$, $p, q \leq 10^{4}, \frac{1}{42} \leq \frac{p}{q} \leq 42$).

-----Output-----

If such maximum number exists, then print it. Otherwise, print "Palindromic tree is better than splay tree" (without the quotes).

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

Output
40

Input
1 42

Output
1

Input
6 4

Output
172

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

import sys
input=sys.stdin.readline

def rr(n):
    a=set([])
    # Create a boolean array "prime[0..n]" and initialize
    #  all entries it as true. A value in prime[i] will
    # finally be false if i is Not a prime, else true.
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):

        # If prime[p] is not changed, then it is a prime
        if (prime[p] == True):

            # Update all multiples of p
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1

    # Print all prime numbers
    for p in range(2, n+1):
        if prime[p]:
            a.add(p)
    return a

def pal(a):
    if str(a)==str(a)[::-1]:
        return 1
    return 0

p,q=list(map(int,input().split()))
n=1500000
a=rr(n)
b=[]
c=0
d=0
for i in range(1,n+1):
    if i in a:
        c+=1
    d+=pal(i)
    b.append([c/d,i])
e=-1
for i in range(len(b)-1,-1,-1):
    if b[i][0]<=p/q:
        e=b[i][1]
        break
if e==-1:
    print("Palindromic tree is better than splay tree")
else:
    print(e)


I found an interesting problem on https://codeforces.com/problemset/problem/568/B:
Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation.

A set ρ of pairs (a, b) of elements of some set A is called a binary relation on set A. For two elements a and b of the set A we say that they are in relation ρ, if pair $(a, b) \in \rho$, in this case we use a notation $a \stackrel{\rho}{\sim} b$.

Binary relation is equivalence relation, if: It is reflexive (for any a it is true that $a \stackrel{\rho}{\sim} a$); It is symmetric (for any a, b it is true that if $a \stackrel{\rho}{\sim} b$, then $b \stackrel{\rho}{\sim} a$); It is transitive (if $a \stackrel{\rho}{\sim} b$ and $b \stackrel{\rho}{\sim} c$, than $a \stackrel{\rho}{\sim} c$).

Little Johnny is not completely a fool and he noticed that the first condition is not necessary! Here is his "proof":

Take any two elements, a and b. If $a \stackrel{\rho}{\sim} b$, then $b \stackrel{\rho}{\sim} a$ (according to property (2)), which means $a \stackrel{\rho}{\sim} a$ (according to property (3)).

It's very simple, isn't it? However, you noticed that Johnny's "proof" is wrong, and decided to show him a lot of examples that prove him wrong.

Here's your task: count the number of binary relations over a set of size n such that they are symmetric, transitive, but not an equivalence relations (i.e. they are not reflexive).

Since their number may be very large (not 0, according to Little Johnny), print the remainder of integer division of this number by 10^9 + 7.

-----Input-----

A single line contains a single integer n (1 ≤ n ≤ 4000).

-----Output-----

In a single line print the answer to the problem modulo 10^9 + 7.

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

Output
1

Input
2

Output
3

Input
3

Output
10

-----Note-----

If n = 1 there is only one such relation — an empty one, i.e. $\rho = \varnothing$. In other words, for a single...

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/569/A:
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.

Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is T seconds. Lesha downloads the first S seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For q seconds of real time the Internet allows you to download q - 1 seconds of the track.

Tell Lesha, for how many times he will start the song, including the very first start.

-----Input-----

The single line contains three integers T, S, q (2 ≤ q ≤ 10^4, 1 ≤ S < T ≤ 10^5).

-----Output-----

Print a single integer — the number of times the song will be restarted.

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

Output
2

Input
5 4 7

Output
1

Input
6 2 3

Output
1

-----Note-----

In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.

In the second test, the song is almost downloaded, and Lesha will start it only once.

In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case.

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

t, s, q = map(int, input().split())
i = 0
while(s < t):
    s *= q; i += 1
print(i)


I found an interesting problem on https://codeforces.com/problemset/problem/569/B:
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.

During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.

You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.

-----Input-----

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

The second line contains n numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5) — the initial inventory numbers of the items.

-----Output-----

Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.

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

Output
1 3 2

Input
4
2 2 3 3

Output
2 1 3 4

Input
1
2

Output
1

-----Note-----

In the first test the numeration is already a permutation, so there is no need to change anything.

In the second test there are two pairs of equal numbers, in each pair you need to replace one number.

In the third test you need to replace 2 by 1, as the numbering should start from one.

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

def read_list(t): return [t(x) for x in input().split()]
def read_line(t): return t(input())
def read_lines(t, N): return [t(input()) for _ in range(N)]

N = read_line(int)
A = read_list(int)
unused = list(set(range(1, N+1)) - set(A))
cur = 0
used = [False] * (N+1)

for i, a in enumerate(A):
    if a > N or used[a]:
        A[i] = unused[cur]
        used[A[i]] = True
        cur += 1
    else:
        used[a] = True
print(*A)


I found an interesting problem on https://codeforces.com/problemset/problem/570/A:
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.

The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.

At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.

Determine who will win the elections.

-----Input-----

The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively.

Each of the next m lines contains n non-negative integers, the j-th number in the i-th line a_{ij} (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ a_{ij} ≤ 10^9) denotes the number of votes for candidate j in city i.

It is guaranteed that the total number of people in all the cities does not exceed 10^9.

-----Output-----

Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.

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

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

Output
1

-----Note-----

Note to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.

Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the...

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

n, m = list(map(int, input().split()))
p = [0] * n
for i in range(m):
    a = list(map(int, input().split()))
    q = max(a)
    for t in range(n):
        if a[t] == q:
            r = t
            break
    p[t] += 1
q = max(p)
for i in range(n):
    if p[i] == q:
        print(i + 1)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/570/B:
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a.

Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen with the same probability), after which the winner is the player, whose number was closer to c. The boys agreed that if m and a are located on the same distance from c, Misha wins.

Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number n. You need to determine which value of a Andrew must choose, so that the probability of his victory is the highest possible.

More formally, you need to find such integer a (1 ≤ a ≤ n), that the probability that $|c - a|<|c - m|$ is maximal, where c is the equiprobably chosen integer from 1 to n (inclusive).

-----Input-----

The first line contains two integers n and m (1 ≤ m ≤ n ≤ 10^9) — the range of numbers in the game, and the number selected by Misha respectively.

-----Output-----

Print a single number — such value a, that probability that Andrew wins is the highest. If there are multiple such values, print the minimum of them.

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

Output
2
Input
4 3

Output
2

-----Note-----

In the first sample test: Andrew wins if c is equal to 2 or 3. The probability that Andrew wins is 2 / 3. If Andrew chooses a = 3, the probability of winning will be 1 / 3. If a = 1, the probability of winning is 0.

In the second sample test: Andrew wins if c is equal to 1 and 2. The probability that Andrew wins is 1 / 2. For other choices of a the probability of winning is less.

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

def main():
    n, m = [int(t) for t in input().split()]

    if n == 1:
        print(1)
    elif m <= n / 2.0:
        print(m + 1)
    else:
        print(m - 1)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/570/C:
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.

Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.

You need to process m queries, the i-th results in that the character at position x_{i} (1 ≤ x_{i} ≤ n) of string s is assigned value c_{i}. After each operation you have to calculate and output the value of f(s).

Help Daniel to process all queries.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.

The second line contains string s, consisting of n lowercase English letters and period signs.

The following m lines contain the descriptions of queries. The i-th line contains integer x_{i} and c_{i} (1 ≤ x_{i} ≤ n, c_{i} — a lowercas English letter or a period sign), describing the query of assigning symbol c_{i} to position x_{i}.

-----Output-----

Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.

-----Examples-----
Input
10 3
.b..bz....
1 h
3 c
9 f

Output
4
3
1

Input
4 4
.cc.
2 .
3 .
2 a
1 a

Output
1
3
1
1

-----Note-----

Note to the first sample test (replaced periods are enclosed in square brackets).

The original string is ".b..bz....". after the first query f(hb..bz....) = 4    ("hb[..]bz...."  →  "hb.bz[..].."  →  "hb.bz[..]."  →  "hb.bz[..]"  →  "hb.bz.") after the second query f(hbс.bz....) = 3    ("hbс.bz[..].."  →  "hbс.bz[..]."  →  "hbс.bz[..]"  →  "hbс.bz.") after...

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

from sys import stdin
input = stdin.readline

n,m = list(map(int,input().split()))
s = list((0,1)[c == '.'] for c in list(input()))

res = 0
cnt = 0
for k in s:
	if k == 1:
		cnt += 1
	else:
		res += max(cnt-1,0)
		cnt = 0
res += max(0,cnt-1)

for i in range(m):
    x,c = input().split()
    x = int(x)
    nc = (0,1)[c == '.']
    if s[x-1] != nc:
        diff = 0
        if x < n:
            if s[int(x)] == 1: diff += 1
        if x > 1:
            if s[int(x-2)] == 1: diff += 1
        if nc == 1:
            res += diff
        else:
            res -= diff
    s[x-1] = nc
    print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/571/A:
You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick.

Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them.

-----Input-----

The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·10^5, 0 ≤ l ≤ 3·10^5).

-----Output-----

Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it.

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

Output
4

Input
1 2 3 1

Output
2

Input
10 2 1 7

Output
0

-----Note-----

In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter.

In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions.

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

a, b, c, d = list(map(int, input().split(' ')))

ans = -(d+1) * (d+2) * (d+3) // 6
for l1 in range(0, d+1):
    minx = min(d-l1, a-b-c+l1)
    if minx < 0:
        continue;
    else:
        ans += (minx + 1) * (minx + 2) // 2

a, b, c = b, c, a
for l1 in range(0, d+1):
    minx = min(d-l1, a-b-c+l1)
    if minx < 0:
        continue;
    else:
        ans += (minx + 1) * (minx + 2) // 2

a, b, c = b, c, a
for l1 in range(0, d+1):
    minx = min(d-l1, a-b-c+l1)
    if minx < 0:
        continue;
    else:
        ans += (minx + 1) * (minx + 2) // 2

print(-ans)


I found an interesting problem on https://codeforces.com/problemset/problem/572/A:
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.

-----Input-----

The first line contains two integers n_{A}, n_{B} (1 ≤ n_{A}, n_{B} ≤ 10^5), separated by a space — the sizes of arrays A and B, correspondingly.

The second line contains two integers k and m (1 ≤ k ≤ n_{A}, 1 ≤ m ≤ n_{B}), separated by a space.

The third line contains n_{A} numbers a_1, a_2, ... a_{n}_{A} ( - 10^9 ≤ a_1 ≤ a_2 ≤ ... ≤ a_{n}_{A} ≤ 10^9), separated by spaces — elements of array A.

The fourth line contains n_{B} integers b_1, b_2, ... b_{n}_{B} ( - 10^9 ≤ b_1 ≤ b_2 ≤ ... ≤ b_{n}_{B} ≤ 10^9), separated by spaces — elements of array B.

-----Output-----

Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).

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

Output
YES

Input
3 3
3 3
1 2 3
3 4 5

Output
NO

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

Output
YES

-----Note-----

In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).

In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: $3 < 3$.

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

na, nb = map(int, input().split())
k, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
if a[k - 1] < b[nb - m]:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/572/B:
In this task you need to process a set of stock exchange orders and use them to create order book.

An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price p_{i}, direction d_{i} — buy or sell, and integer q_{i}. This means that the participant is ready to buy or sell q_{i} stocks at price p_{i} for one stock. A value q_{i} is also known as a volume of an order.

All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.

An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.

An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.

You are given n stock exhange orders. Your task is to print order book of depth s for these orders.

-----Input-----

The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth.

Next n lines contains a letter d_{i} (either 'B' or 'S'), an integer p_{i} (0 ≤ p_{i} ≤ 10^5) and an integer q_{i} (1 ≤ q_{i} ≤ 10^4) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.

-----Output-----

Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.

-----Examples-----
Input
6 2
B 10 3
S 50 2
S 40 1
S 50 6
B 20 4
B 25 10

Output
S 50 8
S 40 1
B 25 10
B 20 4

-----Note-----

Denote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two...

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

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

buyorder = []
sellorder = []

for i in range(n):
    line = input()
    order = line.split()
    order[1] = int(order[1])
    order[2] = int(order[2])

    if order[0] == "B" :
        for m in buyorder:
            if m[1] == order[1]:
                m[2] += order[2]
                break
        else:
            buyorder.append(order)
    else:
        for m in sellorder:
            if m[1] == order[1]:
                m[2] += order[2]
                break
        else:
            sellorder.append(order)

buyorder.sort(key= lambda data : data[1], reverse = True)
sellorder.sort(key= lambda data : data[1], reverse = False)

if len(sellorder)<s:
    sellorder.sort(key= lambda data : data[1], reverse = True)
    for i in sellorder:
        print(i[0], i[1], i[2])
else:
    newsell = []
    for i in range(s):
        newsell.append(sellorder[i])
    newsell.sort(key= lambda data : data[1], reverse = True)
    for i in range(s):
        print(newsell[i][0], newsell[i][1], newsell[i][2])

if len(buyorder)<s:
    for i in buyorder:
        print(i[0], i[1], i[2])
else:
    for i in range(s):
        print(buyorder[i][0], buyorder[i][1], buyorder[i][2])


I found an interesting problem on https://codeforces.com/problemset/problem/573/A:
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size a_{i} dollars.

Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?

-----Input-----

First line of input contains an integer n (2 ≤ n ≤ 10^5), the number of players.

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

-----Output-----

Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.

-----Examples-----
Input
4
75 150 75 50

Output
Yes

Input
3
100 150 250

Output
No

-----Note-----

In the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.

It can be shown that in the second sample test there is no way to make all bids equal.

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

n = int(input())
a = [int(x) for x in input().split()]
for i in range(n):
	while a[i] % 2 == 0:
		a[i] /= 2
	while a[i] % 3 == 0:
		a[i] /= 3
print('Yes' if all(x == a[0] for x in a) else 'No')


I found an interesting problem on https://codeforces.com/problemset/problem/574/A:
Limak is a grizzly bear who desires power and adoration. He wants to win in upcoming elections and rule over the Bearland.

There are n candidates, including Limak. We know how many citizens are going to vote for each candidate. Now i-th candidate would get a_{i} votes. Limak is candidate number 1. To win in elections, he must get strictly more votes than any other candidate.

Victory is more important than everything else so Limak decided to cheat. He will steal votes from his opponents by bribing some citizens. To bribe a citizen, Limak must give him or her one candy - citizens are bears and bears like candies. Limak doesn't have many candies and wonders - how many citizens does he have to bribe?

-----Input-----

The first line contains single integer n (2 ≤ n ≤ 100) - number of candidates.

The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000) - number of votes for each candidate. Limak is candidate number 1.

Note that after bribing number of votes for some candidate might be zero or might be greater than 1000.

-----Output-----

Print the minimum number of citizens Limak must bribe to have strictly more votes than any other candidate.

-----Examples-----
Input
5
5 1 11 2 8

Output
4

Input
4
1 8 8 8

Output
6

Input
2
7 6

Output
0

-----Note-----

In the first sample Limak has 5 votes. One of the ways to achieve victory is to bribe 4 citizens who want to vote for the third candidate. Then numbers of votes would be 9, 1, 7, 2, 8 (Limak would have 9 votes). Alternatively, Limak could steal only 3 votes from the third candidate and 1 vote from the second candidate to get situation 9, 0, 8, 2, 8.

In the second sample Limak will steal 2 votes from each candidate. Situation will be 7, 6, 6, 6.

In the third sample Limak is a winner without bribing any citizen.

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

N = int(input())
votes = [int(x) for i, x in enumerate(input().split())]
my = votes[0]
old = my
votes = sorted(votes[1:], key=lambda x: -x)
while my <= votes[0]:
    votes[0] -= 1
    my += 1
    i = 0
    while i + 1 < len(votes) and votes[i] < votes[i + 1]:
        votes[i], votes[i + 1] = votes[i + 1], votes[i]
        i += 1
print(my - old)


I found an interesting problem on https://codeforces.com/problemset/problem/574/B:
Do you know a story about the three musketeers? Anyway, you will learn about its origins now.

Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.

There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.

Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.

-----Input-----

The first line contains two space-separated integers, n and m (3 ≤ n ≤ 4000, 0 ≤ m ≤ 4000) — respectively number of warriors and number of pairs of warriors knowing each other.

i-th of the following m lines contains two space-separated integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}). Warriors a_{i} and b_{i} know each other. Each pair of warriors will be listed at most once.

-----Output-----

If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print "-1" (without the quotes).

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

Output
2

Input
7 4
2 1
3 6
5 1
1 7

Output
-1

-----Note-----

In the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1 because he knows warrior 4. Sum of recognitions is 0 + 1 + 1 = 2.

The other possible triple is 2, 3, 4 but it has greater sum of recognitions, equal to 1 + 1 + 1 = 3.

In the second sample there is no triple of warriors knowing each other.

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

def main():
    import sys

    tokens = [int(i) for i in sys.stdin.read().split()]
    tokens.reverse()

    n, m = tokens.pop(), tokens.pop()
    degree = [0] * n
    edges = [None] * m
    graph = [set() for i in range(n)]
    for i in range(m):
        a, b = tokens.pop() - 1, tokens.pop() - 1
        degree[a] += 1; degree[b] += 1
        edges[i] = (a, b)
        graph[a].add(b)
        graph[b].add(a)

    result = 10 ** 9
    for a, b in edges:
        if degree[a] > degree[b]: a, b = b, a
        for c in graph[a]:
            if c in graph[b]:
                result = min(result, degree[a] + degree[b] + degree[c])

    if result == 10 ** 9:
        print(-1)
    else:
        print(result - 6)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/575/H:
Sasha and Ira are two best friends. But they aren’t just friends, they are software engineers and experts in artificial intelligence. They are developing an algorithm for two bots playing a two-player game. The game is cooperative and turn based. In each turn, one of the players makes a move (it doesn’t matter which player, it's possible that players turns do not alternate).

Algorithm for bots that Sasha and Ira are developing works by keeping track of the state the game is in. Each time either bot makes a move, the state changes. And, since the game is very dynamic, it will never go back to the state it was already in at any point in the past.

Sasha and Ira are perfectionists and want their algorithm to have an optimal winning strategy. They have noticed that in the optimal winning strategy, both bots make exactly N moves each. But, in order to find the optimal strategy, their algorithm needs to analyze all possible states of the game (they haven’t learned about alpha-beta pruning yet) and pick the best sequence of moves.

They are worried about the efficiency of their algorithm and are wondering what is the total number of states of the game that need to be analyzed?

-----Input-----

The first and only line contains integer N.  1 ≤ N ≤ 10^6

-----Output-----

Output should contain a single integer – number of possible states modulo 10^9 + 7.

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

Output
19

-----Note-----

Start: Game is in state A.   Turn 1: Either bot can make a move (first bot is red and second bot is blue), so there are two possible states after the first turn – B and C.  Turn 2: In both states B and C, either bot can again make a turn, so the list of possible states is expanded to include D, E, F and G.  Turn 3: Red bot already did N=2 moves when in state D, so it cannot make any more moves there. It can make moves when in state E, F and G, so states I, K and M are added to the list. Similarly, blue bot cannot make a move when in state G, but can when in D, E and F, so states H, J and L are added. ...

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

def f(n, mod=10**9+7):
    ans = 1
    for i in range(1, n + 1): ans = ans * i % mod
    return ans

def g(n, mod=10**9+7):
    num1 = f(n * 2)
    den1 = f(n) ** 2 % mod
    return num1 * pow(den1, mod - 2, mod) % mod

n = int(input()) + 1
print(g(n) - 1)


I found an interesting problem on https://codeforces.com/problemset/problem/577/A:
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i × j. The rows and columns are numbered starting from 1.

You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.

-----Input-----

The single line contains numbers n and x (1 ≤ n ≤ 10^5, 1 ≤ x ≤ 10^9) — the size of the table and the number that we are looking for in the table.

-----Output-----

Print a single number: the number of times x occurs in the table.

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

Output
2

Input
6 12

Output
4

Input
5 13

Output
0

-----Note-----

A table for the second sample test is given below. The occurrences of number 12 are marked bold.  [Image]

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

n, m = map(int, input().split())
answer = 0
for i in range(1, n + 1):
    if m % i == 0 and m // i <= n:
        answer += 1
print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/577/B:
You are given a sequence of numbers a_1, a_2, ..., a_{n}, and a number m.

Check if it is possible to choose a non-empty subsequence a_{i}_{j} such that the sum of numbers in this subsequence is divisible by m.

-----Input-----

The first line contains two numbers, n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ 10^3) — the size of the original sequence and the number such that sum should be divisible by it.

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

-----Output-----

In the single line print either "YES" (without the quotes) if there exists the sought subsequence, or "NO" (without the quotes), if such subsequence doesn't exist.

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

Output
YES

Input
1 6
5

Output
NO

Input
4 6
3 1 1 3

Output
YES

Input
6 6
5 5 5 5 5 5

Output
YES

-----Note-----

In the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5.

In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist.

In the third sample test you need to choose two numbers 3 on the ends.

In the fourth sample test you can take the whole subsequence.

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

n, m = (int(i) for i in input().split())
numbers = [int(i) for i in input().split()]
results = {0}

res_update = results.update

for i in numbers:
    tmp_results = set()
    for j in results:
        if (j+i) % m == 0:
            print('YES')
            return
        tmp_results.add((j+i) % m)
    res_update(tmp_results)
print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/578/A:
There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – ....

We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.

-----Input-----

Only one line containing two positive integers a and b (1 ≤ a, b ≤ 10^9).

-----Output-----

Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10^{ - 9}. If there is no such x then output  - 1 as the answer.

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

Output
1.000000000000

Input
1 3

Output
-1

Input
4 1

Output
1.250000000000

-----Note-----

You can see following graphs for sample 1 and sample 3.  [Image]  [Image]

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

def main():
    a, b = list(map(int, input().split()))
    n = a // b
    if n:
        n -= n + 1 & 1
        print("{:.12f}".format((a + b) / (n + 1)))
    else:
        print("-1")

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/578/B:
You are given n numbers a_1, a_2, ..., a_{n}. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make [Image] as large as possible, where $1$ denotes the bitwise OR.

Find the maximum possible value of [Image] after performing at most k operations optimally.

-----Input-----

The first line contains three integers n, k and x (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 10, 2 ≤ x ≤ 8).

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

-----Output-----

Output the maximum value of a bitwise OR of sequence elements after performing operations.

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

Output
3

Input
4 2 3
1 2 4 8

Output
79

-----Note-----

For the first sample, any possible choice of doing one operation will result the same three numbers 1, 1, 2 so the result is $1|1|2 = 3$.

For the second sample if we multiply 8 by 3 two times we'll get 72. In this case the numbers will become 1, 2, 4, 72 so the OR value will be 79 and is the largest possible result.

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

__author__ = 'kitkat'
import sys

#sys.stdin = open("in.txt")
try:
    while True:
        n, k, x = list(map(int, input().split(" ")))
        val = [0] + list(map(int, input().split(" ")))
        res = 0
        L = [0 for i in range(200003)]
        R = [0 for i in range(200003)]
        for i in range(1, n+1, 1):
            L[i] = L[i-1] | val[i]
            R[n-i+1] = R[n-i+2] | val[n-i+1]
        for i in range(1, n+1, 1):
            for j in range(k):
                val[i] *= x
        for i in range(1, n+1, 1):
            res = max(res, L[i-1] | R[i+1] | val[i])
        print(res)
except EOFError:
    pass


I found an interesting problem on https://codeforces.com/problemset/problem/579/A:
You are a lover of bacteria. You want to raise some bacteria in a box.

Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.

What is the minimum number of bacteria you need to put into the box across those days?

-----Input-----

The only line containing one integer x (1 ≤ x ≤ 10^9).

-----Output-----

The only line containing one integer: the answer.

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

Output
2

Input
8

Output
1

-----Note-----

For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.

For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.

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

import sys

lines = sys.stdin.read().split("\n")
# n, k = map(int, lines[0].split(" "))
# n = int(lines[0])
# nums = list(map(int, lines[1].split(" ")))

n = int(lines[0])
print(sum(map(int, bin(n)[2:])))