I found an interesting problem on https://codeforces.com/problemset/problem/599/A:
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d_1 meter long road between his house and the first shop and a d_2 meter long road between his house and the second shop. Also, there is a road of length d_3 directly connecting these two shops to each other. Help Patrick calculate the minimum distance that he needs to walk in order to go to both shops and return to his house. [Image]

Patrick always starts at his house. He should visit both shops moving only along the three existing roads and return back to his house. He doesn't mind visiting the same shop or passing the same road multiple times. The only goal is to minimize the total distance traveled.

-----Input-----

The first line of the input contains three integers d_1, d_2, d_3 (1 ≤ d_1, d_2, d_3 ≤ 10^8) — the lengths of the paths.   d_1 is the length of the path connecting Patrick's house and the first shop;  d_2 is the length of the path connecting Patrick's house and the second shop;  d_3 is the length of the path connecting both shops.

-----Output-----

Print the minimum distance that Patrick will have to walk in order to visit both shops and return to his house.

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

Output
60

Input
1 1 5

Output
4

-----Note-----

The first sample is shown on the picture in the problem statement. One of the optimal routes is: house $\rightarrow$ first shop $\rightarrow$ second shop $\rightarrow$ house.

In the second sample one of the optimal routes is: house $\rightarrow$ first shop $\rightarrow$ house $\rightarrow$ second shop $\rightarrow$ house.

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

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

ans = a+b

ans = min(ans,min(a,b)+c)

ans*=2

ans=min(ans,a+b+c)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/599/B:
While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a_1, a_2, ..., a_{m} of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f_1, f_2, ..., f_{n} of length n and for each number a_{i} got number b_{i} = f_{a}_{i}. To finish the prank he erased the initial sequence a_{i}.

It's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the lengths of sequences f_{i} and b_{i} respectively.

The second line contains n integers, determining sequence f_1, f_2, ..., f_{n} (1 ≤ f_{i} ≤ n).

The last line contains m integers, determining sequence b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ n).

-----Output-----

Print "Possible" if there is exactly one sequence a_{i}, such that b_{i} = f_{a}_{i} for all i from 1 to m. Then print m integers a_1, a_2, ..., a_{m}.

If there are multiple suitable sequences a_{i}, print "Ambiguity".

If Spongebob has made a mistake in his calculations and no suitable sequence a_{i} exists, print "Impossible".

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

Output
Possible
3 2 1

Input
3 3
1 1 1
1 1 1

Output
Ambiguity

Input
3 3
1 2 1
3 3 3

Output
Impossible

-----Note-----

In the first sample 3 is replaced by 1 and vice versa, while 2 never changes. The answer exists and is unique.

In the second sample all numbers are replaced by 1, so it is impossible to unambiguously restore the original sequence.

In the third sample f_{i} ≠ 3 for all i, so no sequence a_{i} transforms into such b_{i} and we can say for sure that Spongebob has made a mistake.

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

n, m = map(int, input().split())
f = list(map(int, input().split()))
b = list(map(int, input().split()))
s1 = set(f)
s2 = set(b)
ans = []
if s2 <= s1:
    d = {}
    for i in range(len(f)):
        if f[i] in d:
            d[f[i]].append(i + 1)
        else:
            d[f[i]] = [i + 1]
    for u in b:
        if u in d and len(d[u]) > 1:
            print('Ambiguity')
            break
        elif u in d:
            ans.append(d[u][0])
    else:
        print('Possible')
        print(' '.join(map(str, ans)))
else:
    print('Impossible')


I found an interesting problem on https://codeforces.com/problemset/problem/599/C:
One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.

At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the height of the i-th castle is equal to h_{i}. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition h_{i} ≤ h_{i} + 1 holds for all i from 1 to n - 1.

Squidward suggested the following process of sorting castles:   Castles are split into blocks — groups of consecutive castles. Therefore the block from i to j will include castles i, i + 1, ..., j. A block may consist of a single castle.  The partitioning is chosen in such a way that every castle is a part of exactly one block.  Each block is sorted independently from other blocks, that is the sequence h_{i}, h_{i} + 1, ..., h_{j} becomes sorted.  The partitioning should satisfy the condition that after each block is sorted, the sequence h_{i} becomes sorted too. This may always be achieved by saying that the whole sequence is a single block.

Even Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of castles Spongebob, Patrick and Squidward made from sand during the day.

The next line contains n integers h_{i} (1 ≤ h_{i} ≤ 10^9). The i-th of these integers corresponds to the height of the i-th castle.

-----Output-----

Print the maximum possible number of blocks in a valid partitioning.

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

Output
3

Input
4
2 1 3 2

Output
2

-----Note-----

In the first sample the partitioning looks like...

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

__author__ = 'sandeepmellacheruvu'
n = int(input())
arr = list(map(int, input().split()))
sum = 0
blocks = 0
for ai, bi in zip(arr, sorted(arr)):
    sum += ai - bi
    if sum == 0:
        blocks += 1
print(blocks)


I found an interesting problem on https://codeforces.com/problemset/problem/599/D:
Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3 × 5 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3 × 5 table is 15 + 8 + 3 = 26.

-----Input-----

The first line of the input contains a single integer x (1 ≤ x ≤ 10^18) — the number of squares inside the tables Spongebob is interested in.

-----Output-----

First print a single integer k — the number of tables with exactly x distinct squares inside.

Then print k pairs of integers describing the tables. Print the pairs in the order of increasing n, and in case of equality — in the order of increasing m.

-----Examples-----
Input
26

Output
6
1 26
2 9
3 5
5 3
9 2
26 1

Input
2

Output
2
1 2
2 1

Input
8

Output
4
1 8
2 3
3 2
8 1

-----Note-----

In a 1 × 2 table there are 2 1 × 1 squares. So, 2 distinct squares in total. [Image]

In a 2 × 3 table there are 6 1 × 1 squares and 2 2 × 2 squares. That is equal to 8 squares in total. [Image]

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

x = int(input()) * 6
n, equ, ans = 0, False, []
while True:
	n += 1
	if n * (n + 1) * (2 * n - 1) > x:
		break
	if x % n != 0:
		continue
	if x % (n + 1) != 0:
		continue
	m = x // n // (n + 1) + n - 1
	if m % 3 != 0:
		continue
	m = m // 3
	if n <= m:
		ans.append([n, m])
		if n == m:
			equ = True

print(len(ans) * 2 - equ)
for p in ans:
	print("%d %d" % (p[0], p[1]))
if equ:
	ans.pop()
ans.reverse()
for p in ans:
	p.reverse();
	print("%d %d" % (p[0], p[1]))


I found an interesting problem on https://codeforces.com/problemset/problem/600/A:
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.

You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).

Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.

For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".

-----Input-----

The only line of input contains the string s (1 ≤ |s| ≤ 10^5). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.

-----Output-----

Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34).

If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.

-----Examples-----
Input
aba,123;1a;0

Output
"123,0"
"aba,1a"

Input
1;;01,a0,

Output
"1"
",01,a0,"

Input
1

Output
"1"
-

Input
a

Output
-
"a"

-----Note-----

In the second example the string s contains five words: "1", "", "01", "a0", "".

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

s = input()
a = []
b = []
tmp = ""
for i in s:
	if i == ',' or i == ';':
		if len(tmp) > 0 and tmp.isdigit() and (len(tmp) == 1 or tmp[0] != '0'):
			a.append(tmp)
		else:
			b.append(tmp)
		tmp = ''
	else:
		tmp = tmp + i
if len(tmp) > 0 and tmp.isdigit() and (len(tmp) == 1 or tmp[0] != '0'):
	a.append(tmp)
else:
	b.append(tmp)
if len(a) > 0:
	print("\"" + ','.join(a) + "\"")
else:
	print('-')
if len(b) > 0:
	print("\"" + ','.join(b) + "\"")
else:
	print('-')


I found an interesting problem on https://codeforces.com/problemset/problem/600/B:
You are given two arrays of integers a and b. For each element of the second array b_{j} you should find the number of elements in array a that are less than or equal to the value b_{j}.

-----Input-----

The first line contains two integers n, m (1 ≤ n, m ≤ 2·10^5) — the sizes of arrays a and b.

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

The third line contains m integers — the elements of array b ( - 10^9 ≤ b_{j} ≤ 10^9).

-----Output-----

Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value b_{j}.

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

Output
3 2 1 4

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

Output
4 2 4 2 5

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

#!/usr/bin/env python3
# 600B_query.py - Codeforces.com/problemset/problem/600/B by Sergey 2015

import unittest
import sys

###############################################################################
# Query Class (Main Program)
###############################################################################

def rbound(v, n):
    b = 0
    e = len(v)
    while b != e:
        mid = (b + e + 1) // 2
        if v[mid - 1] <= n:
            b = mid
        else:
            e = mid - 1
    return b

class Query:
    """ Query representation """

    def __init__(self, test_inputs=None):
        """ Default constructor """

        it = iter(test_inputs.split("\n")) if test_inputs else None

        def uinput():
            return next(it) if it else sys.stdin.readline().rstrip()

        # Reading single elements
        [self.n, self.m] = list(map(int, uinput().split()))

        # Reading a single line of multiple elements
        self.numa = list(map(int, uinput().split()))
        self.numb = list(map(int, uinput().split()))

        self.snuma = sorted(self.numa)

    def calculate(self):
        """ Main calcualtion function of the class """

        result = []
        for n in self.numb:
            result.append(rbound(self.snuma, n))

        return str(" ".join(map(str, result)))

###############################################################################
# Unit Tests
###############################################################################

class unitTests(unittest.TestCase):

    def test_single_test(self):
        """ Query class testing """

        # Constructor test
        test = "5 4\n1 3 5 7 9\n6 4 2 8"
        d = Query(test)
        self.assertEqual(d.n, 5)
        self.assertEqual(d.m, 4)

        # Sample test
        self.assertEqual(Query(test).calculate(), "3 2 1 4")

        # Sample test
        test = "5 5\n1 2 1 2 5\n3 1 4 1 5"
        self.assertEqual(Query(test).calculate(), "4 2 4 2 5")

        # Sample test
        test = ""
        #...


I found an interesting problem on https://codeforces.com/problemset/problem/600/C:
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.

You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.

You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.

-----Input-----

The only line contains string s (1 ≤ |s| ≤ 2·10^5) consisting of only lowercase Latin letters.

-----Output-----

Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.

-----Examples-----
Input
aabc

Output
abba

Input
aabcd

Output
abcba

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

#!/usr/bin/env python3

def solve(s):
    cnt = dict()
    for c in s:
        if c not in cnt:
            cnt[c] = 0
        cnt[c] += 1

    num_odd = 0
    odds = []
    for k, v in list(cnt.items()):
        if v%2:
            num_odd += 1
            odds.append(k)
    odds.sort()
    for i in range(num_odd//2):
        cnt[odds[i]] += 1
        cnt[odds[-i-1]] -= 1
    if len(s)%2 == 0:
        return create_palin(cnt)
    else:
        return create_palin_odd(cnt)

def create_palin(cnt):
    total = sum(v for k, v in list(cnt.items()))
    p = [None]*total

    lo = 0
    hi = total-1
    for k, v in sorted(cnt.items()):
        while v > 0:
            p[lo] = k
            p[hi] = k
            lo += 1
            hi -= 1
            v -= 2
    return str.join('', p)

def create_palin_odd(cnt):
    total = sum(v for k, v in list(cnt.items()))
    odd = [k for k, v in list(cnt.items()) if v%2 == 1][0]
    p = []
    for k, v in sorted(cnt.items()):
        how = v//2
        p += [k]*(v//2)
    p = p + [odd] + list(reversed(p))
    return str.join('', p)

def __starting_point():
    s = input()
    print(solve(s))

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/600/D:
You are given two circles. Find the area of their intersection.

-----Input-----

The first line contains three integers x_1, y_1, r_1 ( - 10^9 ≤ x_1, y_1 ≤ 10^9, 1 ≤ r_1 ≤ 10^9) — the position of the center and the radius of the first circle.

The second line contains three integers x_2, y_2, r_2 ( - 10^9 ≤ x_2, y_2 ≤ 10^9, 1 ≤ r_2 ≤ 10^9) — the position of the center and the radius of the second circle.

-----Output-----

Print the area of the intersection of the circles. The answer will be considered correct if the absolute or relative error doesn't exceed 10^{ - 6}.

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

Output
7.25298806364175601379

Input
0 0 5
11 0 5

Output
0.00000000000000000000

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

from math import pi
from decimal import *

getcontext().prec = 100

def cos(x):
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i-1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s

def acos(x):
    mn, mx = Decimal(0), Decimal(pi)
    for i in range(1000):
        md = (mn+mx)/2
        if cos(md) <= x:
            mx = md
        else:
            mn = md
    return mx;

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

    x1, y1, r1 = Decimal(x1), Decimal(y1), Decimal(r1)
    x2, y2, r2 = Decimal(x2), Decimal(y2), Decimal(r2)

    dcx, dcy = x2-x1, y2-y1
    d = dcx**2 + dcy**2

    if d >= (r1+r2)**2:
        print("0")
        return

    if d <= (r2-r1)**2:
        print("%.7f"%(Decimal(pi)*r1.min(r2)**2))
        return

    d = d.sqrt()

    ans = r1*r1*acos((d*d+r1*r1-r2*r2)/(2*d*r1)) + r2*r2*acos((d*d+r2*r2-r1*r1)/(2*d*r2))
    ans = ans - Decimal((d + r1 + r2) * (-d + r1 + r2) * (d + r1 - r2) * (d + r2 - r1)).sqrt()/2

    print("%.7f"%(ans))

main()


I found an interesting problem on https://codeforces.com/problemset/problem/600/E:
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.

Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.

The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.

For each vertex v find the sum of all dominating colours in the subtree of vertex v.

-----Input-----

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

The second line contains n integers c_{i} (1 ≤ c_{i} ≤ n), c_{i} — the colour of the i-th vertex.

Each of the next n - 1 lines contains two integers x_{j}, y_{j} (1 ≤ x_{j}, y_{j} ≤ n) — the edge of the tree. The first vertex is the root of the tree.

-----Output-----

Print n integers — the sums of dominating colours for each vertex.

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

Output
10 9 3 4

Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13

Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3

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

from collections import defaultdict

class SumDefaultdict(defaultdict):

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(int, *args, **kwargs)
        self.mx = max(self.values())
        self.mx_sum = sum(c for c, v in list(self.items()) if v == self.mx)

    def sumadd(self, map):
        for bb, val in list(map.items()):
            if val > 0:
                self[bb] += val
                if self[bb] > self.mx:
                    self.mx = self[bb]
                    self.mx_sum = bb
                elif self[bb] == self.mx:
                    self.mx_sum += bb

def go():
    n = int(input())
    c = list(map(int, input().split()))

    edges = [[] for _ in range(n)]
    for _ in range(n - 1):
        a, b = [int(x) - 1 for x in input().split()]
        edges[a].append(b)
        edges[b].append(a)

    depth = [0] + [None] * (n - 1)
    parent = [None] * n
    que = [0]
    index = 0
    while index < len(que):
        curr = que[index]
        for b in edges[curr]:
            if depth[b] is None:
                depth[b] = depth[curr] + 1
                parent[b] = curr
                que.append(b)
        index += 1

    order = sorted(((depth[i], i) for i in range(n)), reverse=True)

    cols = [SumDefaultdict({c[i]: 1}) for i in range(n)]
    answer = [0] * n
    for d, i in order:
        children = sorted([cols[b] for b in edges[i] if depth[b] > d], key=len, reverse=True)
        if children:
            for j in range(1, len(children)):
                children[0].sumadd(children[j])
            children[0].sumadd({c[i]: 1})
            cols[i] = children[0]
        # max_val = max(cols[i].values())
        answer[i] = cols[i].mx_sum

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

go()


I found an interesting problem on https://codeforces.com/problemset/problem/601/A:
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.

A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.

You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.

Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.

-----Input-----

The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively.

Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v).

You may assume that there is at most one railway connecting any two towns.

-----Output-----

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.

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

Output
2

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

Output
-1

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

Output
3

-----Note-----

In the first sample, the train can take the route $1 \rightarrow 3 \rightarrow 4$ and the bus can take the route $1 \rightarrow 2...

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

from collections import deque
n, m = tuple(map(int,input().split()))
li,s = deque([0]),set()

for i in range(m):
    a,b = map(int, input().split())
    a -= 1;b-=1
    s.add((a,b))
    s.add((b,a))
reach = (0, n-1) in s
d = [0]
d.extend([-1 for _ in range(n-1)])
while li:
    a =li.popleft()
    for b in range(n):
        if (not(reach and ((a, b) in s)))\
                and(reach or ((a, b) in s))\
                and (d[b] == -1 or d[b] > d[a] + 1):
            d[b] = d[a] + 1
            li.append(b)
print(d[n-1])


I found an interesting problem on https://codeforces.com/problemset/problem/602/A:
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.

You're given a number X represented in base b_{x} and a number Y represented in base b_{y}. Compare those two numbers.

-----Input-----

The first line of the input contains two space-separated integers n and b_{x} (1 ≤ n ≤ 10, 2 ≤ b_{x} ≤ 40), where n is the number of digits in the b_{x}-based representation of X.

The second line contains n space-separated integers x_1, x_2, ..., x_{n} (0 ≤ x_{i} < b_{x}) — the digits of X. They are given in the order from the most significant digit to the least significant one.

The following two lines describe Y in the same way: the third line contains two space-separated integers m and b_{y} (1 ≤ m ≤ 10, 2 ≤ b_{y} ≤ 40, b_{x} ≠ b_{y}), where m is the number of digits in the b_{y}-based representation of Y, and the fourth line contains m space-separated integers y_1, y_2, ..., y_{m} (0 ≤ y_{i} < b_{y}) — the digits of Y.

There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.

-----Output-----

Output a single character (quotes for clarity):   '<' if X < Y  '>' if X > Y  '=' if X = Y

-----Examples-----
Input
6 2
1 0 1 1 1 1
2 10
4 7

Output
=

Input
3 3
1 0 2
2 5
2 4

Output
<

Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0

Output
>

-----Note-----

In the first sample, X = 101111_2 = 47_10 = Y.

In the second sample, X = 102_3 = 21_5 and Y = 24_5 = 112_3, thus X < Y.

In the third sample, $X = FF 4007 A_{16}$ and Y = 4803150_9. We may notice that X starts with much larger digits and b_{x} is much larger than b_{y}, so X is clearly larger than Y.

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

3

def make_num(lst, bx):
	res = 0
	for elem in lst:
		res *= bx
		res += elem
	return res

n, bx = map(int, input().split())
num1  = make_num(map(int, input().split()), bx)

m, by = map(int, input().split())
num2  = make_num(map(int, input().split()), by)

if num1 < num2:
	print('<')
elif num1 == num2:
	print('=')
else:
	print('>')


I found an interesting problem on https://codeforces.com/problemset/problem/603/A:
Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.

However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.

Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.

-----Input-----

The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000).

The following line contains a binary string of length n representing Kevin's results on the USAICO.

-----Output-----

Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.

-----Examples-----
Input
8
10000011

Output
5

Input
2
01

Output
2

-----Note-----

In the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.

In the second sample, Kevin can flip the entire string and still have the same score.

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

n = int(input())
s = input()
x = 0
y = 1
for i in range (n - 1):
    if s[i] == s[i + 1]:
        x += 1
    if s[i] != s[i + 1]:
        y += 1
print(y + min(2, x))


I found an interesting problem on https://codeforces.com/problemset/problem/603/B:
As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that $f(k x \operatorname{mod} p) \equiv k \cdot f(x) \operatorname{mod} p$

for some function $f : \{0,1,2, \cdots, p - 1 \} \rightarrow \{0,1,2, \cdots, p - 1 \}$. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.)

It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 10^9 + 7.

-----Input-----

The input consists of two space-separated integers p and k (3 ≤ p ≤ 1 000 000, 0 ≤ k ≤ p - 1) on a single line. It is guaranteed that p is an odd prime number.

-----Output-----

Print a single integer, the number of distinct functions f modulo 10^9 + 7.

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

Output
3

Input
5 4

Output
25

-----Note-----

In the first sample, p = 3 and k = 2. The following functions work:   f(0) = 0, f(1) = 1, f(2) = 2.  f(0) = 0, f(1) = 2, f(2) = 1.  f(0) = f(1) = f(2) = 0.

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

MOD=int(1e9+7)
n,k=map(int,input().split())
if k<2:p=n-(1-k)
else:
	t=1
	a=k
	while a!=1:
		a=a*k%n
		t+=1
	p=(n-1)//t
print(pow(n,p,MOD))


I found an interesting problem on https://codeforces.com/problemset/problem/603/C:
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing a_{i} cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:

  Remove a single cow from a chosen non-empty pile.  Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.

The player who removes the last cow wins. Given n, k, and a sequence a_1, a_2, ..., a_{n}, help Kevin and Nicky find the winner, given that both sides play in optimal way.

-----Input-----

The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 10^9).

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

-----Output-----

Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).

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

Output
Kevin

Input
1 2
3

Output
Nicky

-----Note-----

In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.

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

f = lambda: map(int, input().split())
n, k = f()
s = 0
for a in f():
    d = 0
    while a & 1 << d == 0: d += 1
    t = (a == 3 << d) ^ (d & 1)
    x = a & 1 if a < 4 else 0 if a & 1 else 2 - t
    y = a if a < 3 else a & 1 ^ 1
    s ^= x if k & 1 else y
print('Kevin' if s else 'Nicky')


I found an interesting problem on https://codeforces.com/problemset/problem/604/A:
Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score.

Codeforces scores are computed as follows: If the maximum point value of a problem is x, and Kevin submitted correctly at minute m but made w wrong submissions, then his score on that problem is $\operatorname{max}(0.3 x,(1 - \frac{m}{250}) x - 50 w)$. His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack.

All arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.

-----Input-----

The first line of the input contains five space-separated integers m_1, m_2, m_3, m_4, m_5, where m_{i} (0 ≤ m_{i} ≤ 119) is the time of Kevin's last submission for problem i. His last submission is always correct and gets accepted.

The second line contains five space-separated integers w_1, w_2, w_3, w_4, w_5, where w_{i} (0 ≤ w_{i} ≤ 10) is Kevin's number of wrong submissions on problem i.

The last line contains two space-separated integers h_{s} and h_{u} (0 ≤ h_{s}, h_{u} ≤ 20), denoting the Kevin's numbers of successful and unsuccessful hacks, respectively.

-----Output-----

Print a single integer, the value of Kevin's final score.

-----Examples-----
Input
20 40 60 80 100
0 1 2 3 4
1 0

Output
4900

Input
119 119 119 119 119
0 0 0 0 0
10...

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

max_scores = [ 500, 1000, 1500, 2000, 2500 ]
corects = [ int(c) for c in input().split() ]
wrongs = [ int(w) for w in input().split() ]
shacks, unshacks = map(int, input().split())
final_score = shacks*100 - unshacks*50

def score(x, m, w):
  return max(0.3*x, (1-(m/250))*x-50*w)

for i in range(5):
  final_score += score(max_scores[i], corects[i], wrongs[i])
print(int(final_score))


I found an interesting problem on https://codeforces.com/problemset/problem/604/B:
Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection.

Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≤ i ≤ n) cowbell is an integer s_{i}. In fact, he keeps his cowbells sorted by size, so s_{i} - 1 ≤ s_{i} for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.

-----Input-----

The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 2·k ≤ 100 000), denoting the number of cowbells and the number of boxes, respectively.

The next line contains n space-separated integers s_1, s_2, ..., s_{n} (1 ≤ s_1 ≤ s_2 ≤ ... ≤ s_{n} ≤ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes s_{i} are given in non-decreasing order.

-----Output-----

Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.

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

Output
7

Input
4 3
2 3 5 9

Output
9

Input
3 2
3 5 7

Output
8

-----Note-----

In the first sample, Kevin must pack his two cowbells into the same box.

In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.

In the third sample, the optimal solution is {3, 5} and {7}.

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

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

t = k - (2*k - n)
res = 0
for i in range(t):
	res = max ( res, a[i] + a[2*t-1-i])
res = max(res, a[n-1])
print (res)


I found an interesting problem on https://codeforces.com/problemset/problem/605/A:
An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.

The second line contains n integers p_{i} (1 ≤ p_{i} ≤ n, p_{i} ≠ p_{j} if i ≠ j) — the sequence of the numbers of the cars in the train.

-----Output-----

Print a single integer — the minimum number of actions needed to sort the railway cars.

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

Output
2

Input
4
4 1 3 2

Output
2

-----Note-----

In the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.

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

n=int(input())
l=[n]*(n+1)
for c in [int(x) for x in input().split()]:l[c]=l[c-1]-1
print(min(l))


I found an interesting problem on https://codeforces.com/problemset/problem/605/C:
Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.

He has suggestions to work on n distinct projects. Mikhail has already evaluated that the participation in the i-th project will increase his experience by a_{i} per day and bring b_{i} dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time.

Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true.

For example, suppose Mikhail is suggested to work on three projects and a_1 = 6, b_1 = 2, a_2 = 1, b_2 = 3, a_3 = 2, b_3 = 6. Also, p = 20 and q = 20. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, a_1·2.5 + a_2·0 + a_3·2.5 = 6·2.5 + 1·0 + 2·2.5 = 20 and b_1·2.5 + b_2·0 + b_3·2.5 = 2·2.5 + 3·0 + 6·2.5 = 20.

-----Input-----

The first line of the input contains three integers n, p and q (1 ≤ n ≤ 100 000, 1 ≤ p, q ≤ 1 000 000) — the number of projects and the required number of experience and money.

Each of the next n lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 1 000 000) — the daily increase in experience and daily income for working on the i-th project.

-----Output-----

Print a real value — the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct,...

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

def get_bounds(points):

    if len(points) == 1:

        return points[:]

    points.sort()

    bounds = [points[0], points[1]]

    for xi, yi in points[2:]:

        while len(bounds) > 1 and not is_convex(bounds, xi, yi):

            del bounds[-1]

        bounds.append((xi, yi))

    return bounds

def is_convex(bounds, x2, y2):

    x1, y1 = bounds[-1]

    x0, y0 = bounds[-2]

    return (x1 - x0) * (y2 - y1) < (y1 - y0) * (x2 - x1)

def read_data():

    n, p, q = list(map(int, input().split()))

    ABs = []

    for i in range(n):

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

        ABs.append((a, b))

    return n, p, q, ABs

def solve(n, p, q, ABs):

    '''

    min sum(ds)

    s.t. sum(ds[i] * As[i]) >= p and sum(ds[i] * Bs[i]) >= q

    '''

    bounds = get_bounds(ABs)

    a0, b0 = bounds[0]

    if len(bounds) == 1:

        return max(p/a0, q/b0)

    record = float('Inf')

    for a1, b1 in bounds[1:]:

        steps = min(max(p/a0, q/b0), max(p/a1, q/b1))

        den = a0 * b1 - b0 * a1

        if den != 0:

            r0 = (b1 * p - a1 * q)/den

            r1 = - (b0 * p - a0 * q)/den

            if r0 > 0 and r1 > 0:

                steps = min(steps, r0 + r1)

        a0 = a1

        b0 = b1

        record = min(record, steps)

    return record

n, p, q, ABs = read_data()

print(solve(n, p, q, ABs))

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/606/A:
Carl is a beginner magician. He has a blue, b violet and c orange magic spheres. In one move he can transform two spheres of the same color into one sphere of any other color. To make a spell that has never been seen before, he needs at least x blue, y violet and z orange spheres. Can he get them (possible, in multiple actions)?

-----Input-----

The first line of the input contains three integers a, b and c (0 ≤ a, b, c ≤ 1 000 000) — the number of blue, violet and orange spheres that are in the magician's disposal.

The second line of the input contains three integers, x, y and z (0 ≤ x, y, z ≤ 1 000 000) — the number of blue, violet and orange spheres that he needs to get.

-----Output-----

If the wizard is able to obtain the required numbers of spheres, print "Yes". Otherwise, print "No".

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

Output
Yes

Input
5 6 1
2 7 2

Output
No

Input
3 3 3
2 2 2

Output
Yes

-----Note-----

In the first sample the wizard has 4 blue and 4 violet spheres. In his first action he can turn two blue spheres into one violet one. After that he will have 2 blue and 5 violet spheres. Then he turns 4 violet spheres into 2 orange spheres and he ends up with 2 blue, 1 violet and 2 orange spheres, which is exactly what he needs.

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

a, b, c = list(map(int, input().split()))
x, y, z = list(map(int, input().split()))
dx = [a - x, b - y, c - z]
splus = 0
sminus = 0
for i in dx:
    if i > 0:
        splus += i // 2
    else:
        sminus += -i
if sminus == 0 or splus >= sminus:
    print('Yes')
else:
    print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/606/B:
The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x_0, y_0) of a rectangular squared field of size x × y, after that a mine will be installed into one of the squares of the field. It is supposed to conduct exactly x·y tests, each time a mine is installed into a square that has never been used before. The starting cell of the robot always remains the same.

After placing the objects on the field the robot will have to run a sequence of commands given by string s, consisting only of characters 'L', 'R', 'U', 'D'. These commands tell the robot to move one square to the left, to the right, up or down, or stay idle if moving in the given direction is impossible. As soon as the robot fulfills all the sequence of commands, it will blow up due to a bug in the code. But if at some moment of time the robot is at the same square with the mine, it will also blow up, but not due to a bug in the code.

Moving to the left decreases coordinate y, and moving to the right increases it. Similarly, moving up decreases the x coordinate, and moving down increases it.

The tests can go on for very long, so your task is to predict their results. For each k from 0 to length(s) your task is to find in how many tests the robot will run exactly k commands before it blows up.

-----Input-----

The first line of the input contains four integers x, y, x_0, y_0 (1 ≤ x, y ≤ 500, 1 ≤ x_0 ≤ x, 1 ≤ y_0 ≤ y) — the sizes of the field and the starting coordinates of the robot. The coordinate axis X is directed downwards and axis Y is directed to the right.

The second line contains a sequence of commands s, which should be fulfilled by the robot. It has length from 1 to 100 000 characters and only consists of characters 'L', 'R', 'U', 'D'.

-----Output-----

Print the sequence consisting of (length(s) + 1) numbers. On the k-th position, starting with zero,...

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

#!/usr/bin/env python3

DELTAS = {
    'U': (-1, 0),
    'R': (0, 1),
    'D': (1, 0),
    'L': (0, -1),
}

try:
    while True:
        h, w, y, x = map(int, input().split())
        y -= 1
        x -= 1
        s = input()
        total = h * w - 1
        used = [[False] * w for i in range(h)]
        used[y][x] = True
        print(end="1 ")
        last = len(s) - 1
        for i, c in enumerate(s):
            dy, dx = DELTAS[c]
            ny = y + dy
            nx = x + dx
            if 0 <= ny < h and 0 <= nx < w:
                if i != last:
                    if used[ny][nx]:
                        print(end="0 ")
                    else:
                        print(end="1 ")
                        used[ny][nx] = True
                        total -= 1
                y = ny
                x = nx
            elif i != last:
                print(end="0 ")
        print(total)

except EOFError:
    pass


I found an interesting problem on https://codeforces.com/problemset/problem/608/A:
Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.

The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.

-----Input-----

The first line of input contains two integers n and s (1 ≤ n ≤ 100, 1 ≤ s ≤ 1000) — the number of passengers and the number of the top floor respectively.

The next n lines each contain two space-separated integers f_{i} and t_{i} (1 ≤ f_{i} ≤ s, 1 ≤ t_{i} ≤ 1000) — the floor and the time of arrival in seconds for the passenger number i.

-----Output-----

Print a single integer — the minimum amount of time in seconds needed to bring all the passengers to floor 0.

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

Output
11

Input
5 10
2 77
3 33
8 21
9 12
10 64

Output
79

-----Note-----

In the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:

1. Move to floor 5: takes 2 seconds.

2. Pick up passenger 3.

3. Move to floor 3: takes 2 seconds.

4. Wait for passenger 2 to arrive: takes 4 seconds.

5. Pick up passenger 2.

6. Go to floor 2: takes 1 second.

7. Pick up passenger 1.

8. Go to floor 0: takes 2 seconds.

This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds.

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

s, n = [int(i) for i in input().split()]
out = 0
for j in range(s):
	a, b = [int(i) for i in input().split()]
	out+=(n-a)
	out=max(out, b)
	n = a
out +=n
print(out)


I found an interesting problem on https://codeforces.com/problemset/problem/608/B:
Genos needs your help. He was asked to solve the following programming problem by Saitama:

The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as $\sum_{i = 1}^{|s|}|s_{i} - t_{i}|$, where s_{i} is the i-th character of s and t_{i} is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.

Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.

-----Input-----

The first line of the input contains binary string a (1 ≤ |a| ≤ 200 000).

The second line of the input contains binary string b (|a| ≤ |b| ≤ 200 000).

Both strings are guaranteed to consist of characters '0' and '1' only.

-----Output-----

Print a single integer — the sum of Hamming distances between a and all contiguous substrings of b of length |a|.

-----Examples-----
Input
01
00111

Output
3

Input
0011
0110

Output
2

-----Note-----

For the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.

The second sample case is described in the statement.

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/609/A:
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a_1, a_2, ..., a_{n} megabytes. The file size is equal to m megabytes.

Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.

-----Input-----

The first line contains positive integer n (1 ≤ n ≤ 100) — the number of USB flash drives.

The second line contains positive integer m (1 ≤ m ≤ 10^5) — the size of Sean's file.

Each of the next n lines contains positive integer a_{i} (1 ≤ a_{i} ≤ 1000) — the sizes of USB flash drives in megabytes.

It is guaranteed that the answer exists, i. e. the sum of all a_{i} is not less than m.

-----Output-----

Print the minimum number of USB flash drives to write Sean's file, if he can split the file between drives.

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

Output
2

Input
3
6
2
3
2

Output
3

Input
2
5
5
10

Output
1

-----Note-----

In the first example Sean needs only two USB flash drives — the first and the third.

In the second example Sean needs all three USB flash drives.

In the third example Sean needs only one USB flash drive and he can use any available USB flash drive — the first or the second.

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

r = lambda: int(input())
n = r()
m = r()
a = sorted([r() for i in range(n)], reverse = 1)
cnt = cur = i = 0
while cur < m:
    cur += a[i]
    cnt += 1
    i += 1
print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/609/B:
Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres.

In the bookshop, Jack decides to buy two books of different genres.

Based on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.

The books are given by indices of their genres. The genres are numbered from 1 to m.

-----Input-----

The first line contains two positive integers n and m (2 ≤ n ≤ 2·10^5, 2 ≤ m ≤ 10) — the number of books in the bookstore and the number of genres.

The second line contains a sequence a_1, a_2, ..., a_{n}, where a_{i} (1 ≤ a_{i} ≤ m) equals the genre of the i-th book.

It is guaranteed that for each genre there is at least one book of that genre.

-----Output-----

Print the only integer — the number of ways in which Jack can choose books.

It is guaranteed that the answer doesn't exceed the value 2·10^9.

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

Output
5

Input
7 4
4 2 3 1 2 4 3

Output
18

-----Note-----

The answer to the first test sample equals 5 as Sasha can choose:  the first and second books,  the first and third books,  the first and fourth books,  the second and third books,  the third and fourth books.

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

n,m=[int(i) for i in input().split()]
a=[int(i) for i in input().split()]
b=list(set(a))
num=0
for i in b:
    for t in b:
        if i!=t:
           num+=a.count(i)*a.count(t)
print(num//2)


I found an interesting problem on https://codeforces.com/problemset/problem/609/C:
In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are m_{i} tasks assigned to the i-th server.

In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression m_{a} - m_{b}, where a is the most loaded server and b is the least loaded one.

In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.

Write a program to find the minimum number of seconds needed to balance the load of servers.

-----Input-----

The first line contains positive number n (1 ≤ n ≤ 10^5) — the number of the servers.

The second line contains the sequence of non-negative integers m_1, m_2, ..., m_{n} (0 ≤ m_{i} ≤ 2·10^4), where m_{i} is the number of tasks assigned to the i-th server.

-----Output-----

Print the minimum number of seconds required to balance the load.

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

Output
2

Input
7
10 11 10 11 10 11 11

Output
0

Input
5
1 2 3 4 5

Output
3

-----Note-----

In the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2.

In the second example the load is already balanced.

A possible sequence of task movements for the third example is:  move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5);  then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4);  then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3).

The above sequence is one of several possible ways to balance the load of servers in three seconds.

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

diff=0
x = int(input())
l = list(map(int, input().split(' ')))
s = sum(l)
k = s//x
knum = (k+1)*x-s
kpnum = x - knum
a = knum * [k] + [k+1] * kpnum
a.sort()
l.sort()
for i in range(len(a)):
    diff += abs(a[i]-l[i])
print(int(diff/2))


I found an interesting problem on https://codeforces.com/problemset/problem/609/D:
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.

Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.

Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.

Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.

-----Input-----

First line contains four integers n, m, k, s (1 ≤ n ≤ 2·10^5, 1 ≤ k ≤ m ≤ 2·10^5, 1 ≤ s ≤ 10^9) — number of days, total number and required number of gadgets, number of burles Nura has.

Second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^6) — the cost of one dollar in burles on i-th day.

Third line contains n integers b_{i} (1 ≤ b_{i} ≤ 10^6) — the cost of one pound in burles on i-th day.

Each of the next m lines contains two integers t_{i}, c_{i} (1 ≤ t_{i} ≤ 2, 1 ≤ c_{i} ≤ 10^6) — type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.

-----Output-----

If Nura can't buy k gadgets print the only line with the number -1.

Otherwise the first line should contain integer d — the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers q_{i}, d_{i} — the number of gadget and the day gadget should be bought. All values q_{i} should be different, but the values d_{i} can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1...

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

from itertools import accumulate
import sys

def solve(f, g):
    n, m, k, s = [int(x) for x in f.readline().split()]
    a_price = [(int(x), i+1) for i, x in enumerate(f.readline().split())]
    b_price = [(int(x), i+1) for i, x in enumerate(f.readline().split())]

    a_gadgets = []
    b_gadgets = []
    for i, line in enumerate(f):
        t, price = [int(x) for x in line.split()]
        if t == 1:
            a_gadgets.append((price, i + 1))
        else:
            b_gadgets.append((price, i + 1))

    a_gadgets.sort()
    b_gadgets.sort()

    prefix_a = [0] + list(accumulate(gadget[0] for gadget in a_gadgets))
    prefix_b = [0] + list(accumulate(gadget[0] for gadget in b_gadgets))

    la = min(k, len(a_gadgets))
    lb = min(k, len(b_gadgets))
    min_price_for_k = [(prefix_a[i], prefix_b[k - i], i) for i in range(k-lb, la+1)]

    for i in range(1, n):
        a_price[i] = min(a_price[i], a_price[i-1])
        b_price[i] = min(b_price[i], b_price[i-1])

    def expence(day):
        return lambda x: a_price[day][0]*x[0] + b_price[day][0]*x[1]

    x, y = 0, n-1
    while x <= y-1:
        day = (x + y) // 2
        min_cost = min(min_price_for_k, key = expence(day))
        if expence(day)(min_cost) > s:
            x = day+1
        else:
            y = day
    min_cost = min(min_price_for_k, key = expence(x))
    if expence(x)(min_cost) > s:
        g.write('-1\n')
    else:
        g.write(str(x+1) + '\n')
        i1 = min_cost[-1]
        A, B = ' ' + str(a_price[x][1]) + '\n', ' ' + str(b_price[x][1]) + '\n'
        for i in range(i1):
            g.write(str(a_gadgets[i][1]) + A)
        for i in range(k - i1):
            g.write(str(b_gadgets[i][1]) + B)

solve(sys.stdin, sys.stdout)


I found an interesting problem on https://codeforces.com/problemset/problem/610/A:
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.

Pasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.

Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer x, such that the number of parts of length x in the first way differ from the number of parts of length x in the second way.

-----Input-----

The first line of the input contains a positive integer n (1 ≤ n ≤ 2·10^9) — the length of Pasha's stick.

-----Output-----

The output should contain a single integer — the number of ways to split Pasha's stick into four parts of positive integer length so that it's possible to make a rectangle by connecting the ends of these parts, but is impossible to form a square.

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

Output
1

Input
20

Output
4

-----Note-----

There is only one way to divide the stick in the first sample {1, 1, 2, 2}.

Four ways to divide the stick in the second sample are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Note that {5, 5, 5, 5} doesn't work.

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

n = int(input())
if n % 2 == 1:
    print(0)
else:
    n //= 2
    print((n - 1) // 2)


I found an interesting problem on https://codeforces.com/problemset/problem/610/B:
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains a_{i} liters of paint of color i.

Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.

Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has.

The second line of the input contains a sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.

-----Output-----

The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.

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

Output
12

Input
3
5 5 5

Output
15

Input
6
10 10 10 1 10 10

Output
11

-----Note-----

In the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.

In the second sample Vika can start to paint using any color.

In the third sample Vika should start painting using color number 5.

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

n = int(input())
a = list(map(int, input().split()))
minimum = min(a)
max_segment = 0
count = 0
a = a + a
for i in range(len(a)):
    if a[i] == minimum:
        max_segment = max(count, max_segment)
        count = 0
    else:
        count += 1
max_segment = max(count, max_segment)
print(minimum * n + max_segment)


I found an interesting problem on https://codeforces.com/problemset/problem/610/C:
The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vector is 1 or  - 1 and any two vectors are orthogonal. Just as a reminder, two vectors in n-dimensional space are considered to be orthogonal if and only if their scalar product is equal to zero, that is: $\sum_{i = 1}^{n} a_{i} \cdot b_{i} = 0$.

Danil quickly managed to come up with the solution for this problem and the teacher noticed that the problem can be solved in a more general case for 2^{k} vectors in 2^{k}-dimensinoal space. When Danil came home, he quickly came up with the solution for this problem. Can you cope with it?

-----Input-----

The only line of the input contains a single integer k (0 ≤ k ≤ 9).

-----Output-----

Print 2^{k} lines consisting of 2^{k} characters each. The j-th character of the i-th line must be equal to ' * ' if the j-th coordinate of the i-th vector is equal to  - 1, and must be equal to ' + ' if it's equal to  + 1. It's guaranteed that the answer always exists.

If there are many correct answers, print any.

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

Output
++**
+*+*
++++
+**+

-----Note-----

Consider all scalar products in example:  Vectors 1 and 2: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( + 1) + ( - 1)·( - 1) = 0  Vectors 1 and 3: ( + 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) + ( - 1)·( + 1) = 0  Vectors 1 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( - 1) + ( - 1)·( + 1) = 0  Vectors 2 and 3: ( + 1)·( + 1) + ( - 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) = 0  Vectors 2 and 4: ( + 1)·( + 1) + ( - 1)·( - 1) + ( + 1)·( - 1) + ( - 1)·( + 1) = 0  Vectors 3 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( + 1)·( - 1) + ( + 1)·( + 1) = 0

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

Not = lambda x: '+' if x == '*' else '*'
k = int(input())
n = 2 ** k
a = [['+'] * n for i in range(n)]
for p in range(k):
    n = 2 ** p
    for i in range(n):
        for j in range(n):
            a[i][j + n] = a[i][j]
            a[i + n][j] = a[i][j]
            a[i + n][j + n] = Not(a[i][j])
[print(''.join(map(str, i))) for i in a]


I found an interesting problem on https://codeforces.com/problemset/problem/611/A:
Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015.

Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016.

Limak wants to prove how responsible a bear he is. He is going to regularly save candies for the entire year 2016! He considers various saving plans. He can save one candy either on some fixed day of the week or on some fixed day of the month.

Limak chose one particular plan. He isn't sure how many candies he will save in the 2016 with his plan. Please, calculate it and tell him.

-----Input-----

The only line of the input is in one of the following two formats:   "x of week" where x (1 ≤ x ≤ 7) denotes the day of the week. The 1-st day is Monday and the 7-th one is Sunday.  "x of month" where x (1 ≤ x ≤ 31) denotes the day of the month.

-----Output-----

Print one integer — the number of candies Limak will save in the year 2016.

-----Examples-----
Input
4 of week

Output
52

Input
30 of month

Output
11

-----Note-----

Polar bears use the Gregorian calendar. It is the most common calendar and you likely use it too. You can read about it on Wikipedia if you want to – https://en.wikipedia.org/wiki/Gregorian_calendar. The week starts with Monday.

In the first sample Limak wants to save one candy on each Thursday (the 4-th day of the week). There are 52 Thursdays in the 2016. Thus, he will save 52 candies in total.

In the second sample Limak wants to save one candy on the 30-th day of each month. There is the 30-th day in exactly 11 months in the 2016 — all months but February. It means that Limak will save 11 candies in total.

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/611/B:
The year 2015 is almost over.

Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 2015_10 = 11111011111_2. Note that he doesn't care about the number of zeros in the decimal representation.

Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?

Assume that all positive integers are always written without leading zeros.

-----Input-----

The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 10^18) — the first year and the last year in Limak's interval respectively.

-----Output-----

Print one integer – the number of years Limak will count in his chosen interval.

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

Output
2

Input
2015 2015

Output
1

Input
100 105

Output
0

Input
72057594000000000 72057595000000000

Output
26

-----Note-----

In the first sample Limak's interval contains numbers 5_10 = 101_2, 6_10 = 110_2, 7_10 = 111_2, 8_10 = 1000_2, 9_10 = 1001_2 and 10_10 = 1010_2. Two of them (101_2 and 110_2) have the described property.

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

import itertools
import math
import bisect

one_zero = []
for i in range(2, 180):
    for k in range(1,i):
        one_zero.append(int('1'*k + '0' + '1'*(i-k-1), base = 2))

a, b = [int(x) for x in input().split()]
print(bisect.bisect_right(one_zero, b) - bisect.bisect_left(one_zero, a))


I found an interesting problem on https://codeforces.com/problemset/problem/611/C:
They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so.

Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right.

Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.

Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?

-----Input-----

The first line of the input contains two integers h and w (1 ≤ h, w ≤ 500) – the number of rows and the number of columns, respectively.

The next h lines describe a grid. Each line contains a string of the length w. Each character is either '.' or '#' — denoting an empty or forbidden cell, respectively.

The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of queries.

Each of the next q lines contains four integers r1_{i}, c1_{i}, r2_{i}, c2_{i} (1 ≤ r1_{i} ≤ r2_{i} ≤ h, 1 ≤ c1_{i} ≤ c2_{i} ≤ w) — the i-th query. Numbers r1_{i} and c1_{i} denote the row and the column (respectively) of the upper left cell of the rectangle. Numbers r2_{i} and c2_{i} denote the row and the column (respectively) of the bottom right cell of the rectangle.

-----Output-----

Print q integers, i-th should be equal to the number of ways to put a single domino inside the i-th rectangle.

-----Examples-----
Input
5 8
....#..#
.#......
##.#....
##..#.##
........
4
1 1 2 3
4 1 4 1
1 2 4 5
2 5 5 8

Output
4
0
10
15

Input
7...

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

H, W = list(map(int, input().split()))
grid = ["|" * (W+1)] + ["|" + input() for _ in range(H)]
Q = int(input())

hor = [[0 for _ in range(W+1)] for _ in range(H+1)]
ver = [[0 for _ in range(W+1)] for _ in range(H+1)]

for i in range(1, H+1):
    for j in range(1, W+1):
        hor[i][j] = hor[i-1][j] + hor[i][j-1] - hor[i-1][j-1]
        ver[i][j] = ver[i-1][j] + ver[i][j-1] - ver[i-1][j-1]
        if grid[i][j-1] == "." and grid[i][j] == ".":
            hor[i][j] += 1
        if grid[i-1][j] == "." and grid[i][j] == ".":
            ver[i][j] += 1

for _ in range(Q):
    r1, c1, r2, c2 = list(map(int, input().split()))

    answer = 0
    answer += ver[r2][c2] - ver[r1][c2] - ver[r2][c1-1] + ver[r1][c1-1]
    answer += hor[r2][c2] - hor[r2][c1] - hor[r1-1][c2] + hor[r1-1][c1]

    print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/612/A:
You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.

For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".

Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).

-----Input-----

The first line contains three positive integers n, p, q (1 ≤ p, q ≤ n ≤ 100).

The second line contains the string s consists of lowercase and uppercase latin letters and digits.

-----Output-----

If it's impossible to split the string s to the strings of length p and q print the only number "-1".

Otherwise in the first line print integer k — the number of strings in partition of s.

Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s — from left to right.

If there are several solutions print any of them.

-----Examples-----
Input
5 2 3
Hello

Output
2
He
llo

Input
10 9 5
Codeforces

Output
2
Codef
orces

Input
6 4 5
Privet

Output
-1

Input
8 1 1
abacabac

Output
8
a
b
a
c
a
b
a
c

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

n,p,q=list(map(int, input().split(" ")))
s = input()
asdf = False
for i in range(n//p+1):
    for j in range((n-i*p)//q+1):
        if i*p+j*q == n and asdf == False:
            print(i+j)
            asdf = True
            for a in range(i):
                print(s[a*p:(a+1)*p])
            for b in range(j):
                print(s[p*i+b*q:p*i+(b+1)*q])
if asdf == False:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/612/B:
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.

One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.

Find the time need to read file split to n fragments. The i-th sector contains the f_{i}-th fragment of the file (1 ≤ f_{i} ≤ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.

It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.

-----Input-----

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

The second line contains n different integers f_{i} (1 ≤ f_{i} ≤ n) — the number of the fragment written in the i-th sector.

-----Output-----

Print the only integer — the number of time units needed to read the file.

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

Output
3

Input
5
1 3 5 4 2

Output
10

-----Note-----

In the second example the head moves in the following way:  1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units  2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units  3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units  4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units

So the answer to the second example is 4 + 3 + 2 + 1 = 10.

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

n = int(input())
lst = list(map(int, input().split()))
d = []
for i in range(n):
    d.append((lst[i], i))
d.sort()
s = 0
for i in range(1, n):
    s += abs(d[i][1] - d[i - 1][1])
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/612/C:
You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.

The following definition of a regular bracket sequence is well-known, so you can be familiar with it.

Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s_1 and s_2 be a RBS then the strings <s_1>s_2, {s_1}s_2, [s_1]s_2, (s_1)s_2 are also RBS.

For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.

Determine the least number of replaces to make the string s RBS.

-----Input-----

The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 10^6.

-----Output-----

If it's impossible to get RBS from s print Impossible.

Otherwise print the least number of replaces needed to get RBS from s.

-----Examples-----
Input
[<}){}

Output
2
Input
{()}[]

Output
0
Input
]]

Output
Impossible

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

from collections import deque
import sys

strv = list(input())

if len(strv) % 2 != 0:
    print ("Impossible")
    return

openQ = deque([])

y=0

for brk in strv:
    if brk in ['[','{','(', '<']:
        openQ.append(brk)
    else:
        if len(openQ) >= 1:
            lastIn = openQ.pop()
            if brk=="}":
                if lastIn != "{":
                    y=y+1
            elif brk=="]":
                if lastIn != "[":
                        y=y+1
            elif brk==")":
                if lastIn != "(":
                        y=y+1
            elif brk==">":
                if lastIn != "<":
                        y=y+1
        else:
            y="Impossible"
            break

if len(openQ) == 0 :
    print(y)
else:
    print("Impossible")


I found an interesting problem on https://codeforces.com/problemset/problem/612/E:
A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q^2 = [2, 3, 4, 5, 1].

This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q^2 = p. If there are several such q find any of them.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^6) — the number of elements in permutation p.

The second line contains n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the elements of permutation p.

-----Output-----

If there is no permutation q such that q^2 = p print the number "-1".

If the answer exists print it. The only line should contain n different integers q_{i} (1 ≤ q_{i} ≤ n) — the elements of the permutation q. If there are several solutions print any of them.

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

Output
3 4 2 1

Input
4
2 1 3 4

Output
-1

Input
5
2 3 4 5 1

Output
4 5 1 2 3

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

import math
import sys
input = sys.stdin.readline

n = int(input())
a = [int(_) - 1 for _ in input().split()]
vis = [False] * n
cycles = [[] for _ in range(n + 1)]
for i in range(n):
    if vis[i]: continue
    cur = i
    cycle = []
    while not vis[cur]:
        vis[cur] = True
        cycle.append(cur)
        cur = a[cur]
    cycles[len(cycle)].append(cycle)
p = [0] * n
for i in range(n + 1):
    if i % 2 == 1:
        for j in cycles[i]:
            for k in range(i):
                p[j[k]] = j[(k + (i + 1) // 2) % i]
    else:
        if len(cycles[i]) % 2 == 1:
            print(-1)
            return
        for j in range(0, len(cycles[i]), 2):
            for k in range(i):
                p[cycles[i][j][k]] = cycles[i][j + 1][k]
                p[cycles[i][j + 1][k]] = cycles[i][j][(k + 1) % i]
print(' '.join([str(i + 1) for i in p]))


I found an interesting problem on https://codeforces.com/problemset/problem/613/A:
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.

Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.

Peter decided to tie his car to point P and now he is wondering what is the area of the region that will be cleared from snow. Help him.

-----Input-----

The first line of the input contains three integers — the number of vertices of the polygon n ($3 \leq n \leq 100000$), and coordinates of point P.

Each of the next n lines contains two integers — coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line.

All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.

-----Output-----

Print a single real value number — the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$.

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

Output
12.566370614359172464

Input
4 1 -1
0 0
1 2
2 0
1 1

Output
21.991148575128551812

-----Note-----

In the first sample snow will be removed from that area:

 $0$

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

import math

def dot(v1, v2):
    return v1[0]*v2[0] + v1[1]*v2[1]

def cross(v1, v2):
    return v1[0]*v2[1] - v1[1]*v2[0]

def mag(x,y):
    return math.sqrt(x**2 + y**2)

def main():
    PI = 3.141592653589793
    mags = []

    n, x0, y0 = map(int, input().split())

    x, y = x0, y0
    for i in range(n):
        x_, y_ = map(int, input().split())
        x_, y_ = x_ - x0, y_ - y0
        if i == 0:
            x1, y1 = x_ , y_
            x, y = x_, y_

        mags.append(mag(x_,y_))

        if dot([x,y],[x-x_, y-y_])*dot([x_,y_],[x_-x,y_-y]) > 0:
            mags.append(abs(cross([x,y],[x_-x,y_-y])) / mag(x-x_,y-y_))

        x, y = x_, y_

    if dot([x,y],[x-x1,y-y1])*dot([x1,y1],[x1-x,y1-y]) > 0:
        mags.append(abs(cross([x,y],[x1-x,y1-y])) / mag(x-x1,y-y1))

    print((max(mags)**2 - min(mags)**2) * PI)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/614/A:
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.

Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)

Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!

-----Input-----

The first line of the input contains three space-separated integers l, r and k (1 ≤ l ≤ r ≤ 10^18, 2 ≤ k ≤ 10^9).

-----Output-----

Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).

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

Output
1 2 4 8
Input
2 4 5

Output
-1

-----Note-----

Note to the first sample: numbers 2^0 = 1, 2^1 = 2, 2^2 = 4, 2^3 = 8 lie within the specified range. The number 2^4 = 16 is greater then 10, thus it shouldn't be printed.

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

l, r, k = map(int, input().split())
ans = []
nowa = 1;
while (nowa <= r):
    if (nowa >= l):
        ans.append(nowa)
    nowa *= k
if (len(ans) == 0):
    print(-1)
else:
    print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/614/B:
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!

There are exactly n distinct countries in the world and the i-th country added a_{i} tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.

Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.

-----Input-----

The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers a_{i} without leading zeroes — the number of tanks of the i-th country.

It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000.

-----Output-----

Print a single number without leading zeroes — the product of the number of tanks presented by each country.

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

Output
50
Input
4
1 1 10 11

Output
110
Input
5
0 3 1 100 1

Output
0

-----Note-----

In sample 1 numbers 10 and 1 are beautiful, number 5 is not not.

In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.

In sample 3 number 3 is not beautiful, all others are beautiful.

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

import operator
import functools
n = int(input())
a = input().split()
notpretty = 0

zero = False
for i in range(n):
	for j in range(len(a[i])):
		if (j == 0 and a[i][j]!='1') or (j!=0 and a[i][j]!='0'):
			#print(i, j, a[i][j])
			notpretty = i;
		if (j==0 and a[i][j]=='0'):
			zero = True
			break;
l = 0
if zero:
	print(0)
else:
	for i in range(n):
		if i != notpretty:
			l += len(a[i]) - 1
	print(a[notpretty], '0'*l, sep='')


I found an interesting problem on https://codeforces.com/problemset/problem/615/A:
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?

If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.

-----Input-----

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

Each of the next n lines contains x_{i} (0 ≤ x_{i} ≤ m) — the number of bulbs that are turned on by the i-th button, and then x_{i} numbers y_{ij} (1 ≤ y_{ij} ≤ m) — the numbers of these bulbs.

-----Output-----

If it's possible to turn on all m bulbs print "YES", otherwise print "NO".

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

Output
YES

Input
3 3
1 1
1 2
1 1

Output
NO

-----Note-----

In the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.

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

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time

(n, m) = (int(i) for i in input().split())

a = [ 0 for i in range(m) ]

for i in range(n):
    b   = [int(i) for i in input().split()]
    for j in b[1:]:
        a[j-1] = 1

start = time.time()

if 0 in a:
    print('NO')
else:
    print('YES')

finish = time.time()
#print(finish - start)


I found an interesting problem on https://codeforces.com/problemset/problem/615/B:
This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions:   Only segments already presented on the picture can be painted;  The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment;  The numbers of points from the beginning of the tail to the end should strictly increase.

Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.

Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.

-----Input-----

First line of the input contains two integers n and m(2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number segments on the picture respectively.

Then follow m lines, each containing two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.

-----Output-----

Print the maximum possible value of the hedgehog's beauty.

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

Output
9

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

Output
12

-----Note-----

The picture below...

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

n,m =list(map(int, input().split()))
#b=[]
d=[0]*n
f=[[] for i in range(n)]
#for i in range(n):
#	f+=[]
#print(f)
#print(d)
for i in range(m):
	#s=input().split()
	a=list(map(int, input().split()))
	d[a[0]-1]+=1
	d[a[1]-1]+=1
	a.sort()
	#a.reverse
	f[a[1]-1]+=[a[0]-1]

#print(f[4])
k=[1]*n
res = 0
for i in range(n):
	for j in f[i]:
		k[i]=max(k[i], k[j]+1)
	res = max(res, k[i]*d[i])

#	print(f)

print(res)
#b.sort
#print(b)# your code goes here# your code goes here


I found an interesting problem on https://codeforces.com/problemset/problem/615/C:
A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.

First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.

Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.

-----Input-----

First line of the input contains the string s — the coating that is present in the shop. Second line contains the string t — the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.

-----Output-----

The first line should contain the minimum needed number of coatings n or -1 if it's impossible to create the desired coating.

If the answer is not -1, then the following n lines should contain two integers x_{i} and y_{i} — numbers of ending blocks in the corresponding piece. If x_{i} ≤ y_{i} then this piece is used in the regular order, and if x_{i} > y_{i} piece is used in the reversed order. Print the pieces in the order they should be glued to get the string t.

-----Examples-----
Input
abc
cbaabc

Output
2
3 1
1 3

Input
aaabrytaaa
ayrat

Output
3
1 1
6 5
8 7

Input
ami
no

Output
-1

-----Note-----

In the first sample string "cbaabc" = "cba" + "abc".

In the second sample: "ayrat" = "a" + "yr" + "at".

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

def find_max_substr(t, s):
    l, r = 0, len(t)
    while l != r:
        m = (l + r) // 2
        if t[:m + 1] in s:
            l = m + 1
        else:
            r = m
    l1 = l
    rs = s[::-1]
    l, r = 0, len(t)
    while l != r:
        m = (l + r) // 2
        if t[:m + 1] in rs:
            l = m + 1
        else:
            r = m
    l2 = l
    if l1 >= l2:
        return s.find(t[:l1]) + 1, s.find(t[:l1]) + l1
    else:
        return s.find(t[:l2][::-1]) + l2, s.find(t[:l2][::-1]) + 1

s = input()
t = input()
if not set(t).issubset(set(s)):
    print(-1)
    return
a = []
while t:
    l, r = find_max_substr(t, s)
    a.append((l, r))
    t = t[abs(r - l) + 1:]
print(len(a))
for l, r in a:
    print(l, r)


I found an interesting problem on https://codeforces.com/problemset/problem/615/D:
Ayrat has number n, represented as it's prime factorization p_{i} of size m, i.e. n = p_1·p_2·...·p_{m}. Ayrat got secret information that that the product of all divisors of n taken modulo 10^9 + 7 is the password to the secret data base. Now he wants to calculate this value.

-----Input-----

The first line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of primes in factorization of n.

The second line contains m primes numbers p_{i} (2 ≤ p_{i} ≤ 200 000).

-----Output-----

Print one integer — the product of all divisors of n modulo 10^9 + 7.

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

Output
36

Input
3
2 3 2

Output
1728

-----Note-----

In the first sample n = 2·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1·2·3·6 = 36.

In the second sample 2·3·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1·2·3·4·6·12 = 1728.

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

n = int(input())
l = list(map(int, input().split()))
M = int(1e9+7)
counter = {}
num = 1
for elem in l:
    num = (num * elem) % M
    try:
        counter[elem]+=1
    except:
        counter[elem] = 2

d = 1
for elem in counter:
    d *= counter[elem]

res = pow(num, d//2, M)
checkodd = 1
for elem in counter:
    if counter[elem] % 2 == 0:
        checkodd = 0
        break
if checkodd:
    for elem in counter:
        for i in range(counter[elem] // 2):
            res = (res * elem) % M

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/615/E:
Ayrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined:

[Image] [Image] Ayrat is searching through the field. He started at point (0, 0) and is moving along the spiral (see second picture). Sometimes he forgets where he is now. Help Ayrat determine his location after n moves.

-----Input-----

The only line of the input contains integer n (0 ≤ n ≤ 10^18) — the number of Ayrat's moves.

-----Output-----

Print two integers x and y — current coordinates of Ayrat coordinates.

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

Output
-2 0

Input
7

Output
3 2

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

# Contest: 21 - Codeforces Rating >= 2200 (https://a2oj.com/ladder?ID=21)
# Problem: (25) Hexagons (Difficulty: 5) (http://codeforces.com/problemset/problem/615/E)

def rint():
    return int(input())

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

SIDES = [
    lambda c, v: (1 + 2 * c - v, 2 + 2 * v),
    lambda c, v: (-1 + c - 2 * v, 2 + 2 * c),
    lambda c, v: (-c - 2 - v, 2 * c - 2 * v),
    lambda c, v: (-1 - 2 * c + v, -2 - 2 * v),
    lambda c, v: (1 - c + 2 * v, -2 - 2 * c),
    lambda c, v: (2 + c + v, -2 * c + 2 * v),
]

n = rint()
if n == 0:
    print(0, 0)
    return
n -= 1
l, h = 0, 10**9
while h - l > 1:
    m = (h + l) // 2
    if 3 * m * (m + 1) > n:
        h = m - 1
    else:
        l = m
c = h if 3 * h * (h + 1) <= n else l
n -= 3 * c * (c + 1)

print(*SIDES[n // (c + 1)](c, n % (c + 1)))