I found an interesting problem on https://codeforces.com/problemset/problem/579/B:
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.

Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one.

Can you determine who will be each person’s teammate?

-----Input-----

There are 2n lines in the input.

The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed.

The i-th line (i > 1) contains i - 1 numbers a_{i}1, a_{i}2, ... , a_{i}(i - 1). Here a_{ij} (1 ≤ a_{ij} ≤ 10^6, all a_{ij} are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)

-----Output-----

Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.

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

Output
2 1 4 3

Input
3
487060
3831 161856
845957 794650 976977
83847 50566 691206 498447
698377 156232 59015 382455 626960

Output
6 5 4 3 2 1

-----Note-----

In the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.

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

import sys; sys.setrecursionlimit(1000000); import math
def solve():
    n, = rv()
    l = list()
    already = [-1] * (2 * n)
    for i in range(2 * n - 1):
        temp, = rl(1)
        for j, val in enumerate(temp):
            l.append((val, i + 1, j))
    l.sort(key = lambda x : -x[0])
    for tup in l:
        f, s = tup[1], tup[2]
        if already[f] == -1  and already[s] == -1:
            already[f] = s
            already[s] = f
    print(' '.join(map(str, [val + 1 for val in already])))

def rv(): return list(map(int, input().split()))
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()


I found an interesting problem on https://codeforces.com/problemset/problem/580/A:
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes a_{i} money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence a_{i}. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.

Help Kefa cope with this task!

-----Input-----

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

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

-----Output-----

Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.

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

Output
3
Input
3
2 2 9

Output
3

-----Note-----

In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.

In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.

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

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

ans = 1
now = 1
for i in range(1, n):
    if arr[i] >= arr[i - 1]:
        now += 1
    else:
        ans = max(ans, now)
        now = 1

ans = max(ans, now)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/580/B:
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.

Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!

-----Input-----

The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 10^5, $1 \leq d \leq 10^{9}$) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.

Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type m_{i}, s_{i} (0 ≤ m_{i}, s_{i} ≤ 10^9) — the amount of money and the friendship factor, respectively.

-----Output-----

Print the maximum total friendship factir that can be reached.

-----Examples-----
Input
4 5
75 5
0 100
150 20
75 1

Output
100

Input
5 100
0 7
11 32
99 10
46 8
87 54

Output
111

-----Note-----

In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.

In the second sample test we can take all the friends.

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

n, d = map(int, input().split())
friends = [(0, 0)]
for i in range(n):
    money, cute = map(int, input().split())
    friends.append((money, cute))
friends.sort()
sumcute = [0 for i in range(n + 1)]
for i in range(1, n + 1):
    sumcute[i] = sumcute[i - 1] + friends[i][1]
l = 1
r = 1
ans = 0
while r != len(sumcute):
    while r != len(sumcute) - 1 and friends[r + 1][0] - friends[l][0] < d:
        r += 1
    ans = max(sumcute[r] - sumcute[l - 1], ans)
    if r == len(sumcute) - 1: r += 1
    l += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/580/C:
Kefa decided to celebrate his first big salary by going to the restaurant.

He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.

The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.

Your task is to help Kefa count the number of restaurants where he can go.

-----Input-----

The first line contains two integers, n and m (2 ≤ n ≤ 10^5, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.

The second line contains n integers a_1, a_2, ..., a_{n}, where each a_{i} either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).

Next n - 1 lines contains the edges of the tree in the format "x_{i} y_{i}" (without the quotes) (1 ≤ x_{i}, y_{i} ≤ n, x_{i} ≠ y_{i}), where x_{i} and y_{i} are the vertices of the tree, connected by an edge.

It is guaranteed that the given set of edges specifies a tree.

-----Output-----

A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.

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

Output
2

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

Output
2

-----Note-----

Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.

Note to the first sample test:...

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

__author__ = 'User'
n, m = list(map(int, input().split()))
cat = [0] + list(map(int, input().split()))
arr = [[] for i in range(n + 1)]
for i in range(n - 1):
    a, b = list(map(int, input().split()))
    arr[a].append(b)
    arr[b].append(a)
counter = [0] * n
c = 0
i = 0
queue = [(1, 0)]
#print(arr)
while i < len(queue):
    j = 0
    if len(arr[queue[i][0]]) == 1 and queue[i][1] == arr[queue[i][0]][0]:
        c += 1
    else:
        for j in arr[queue[i][0]]:
            if j != queue[i][1]:
                if cat[j] != 0:
                    cat[j] += cat[queue[i][0]]
                if cat[j] <= m:
                    queue.append((j, queue[i][0]))
    i += 1
print(c)
#print(queue)
#print(cat)
#print(arr)


I found an interesting problem on https://codeforces.com/problemset/problem/581/A:
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.

According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.

Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.

Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.

Can you help him?

-----Input-----

The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.

-----Output-----

Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.

Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.

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

Output
1 1

Input
2 3

Output
2 0

Input
7 3

Output
3 2

-----Note-----

In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.

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

a, b = [int(x) for x in input().split()]
a, b = min(a,b), max(a,b)
print(a, (b-a)//2)


I found an interesting problem on https://codeforces.com/problemset/problem/581/B:
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.

Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.

The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.

Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).

-----Input-----

The first line of the input contains a single number n (1 ≤ n ≤ 10^5) — the number of houses in the capital of Berland.

The second line contains n space-separated positive integers h_{i} (1 ≤ h_{i} ≤ 10^9), where h_{i} equals the number of floors in the i-th house.

-----Output-----

Print n integers a_1, a_2, ..., a_{n}, where number a_{i} is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then a_{i} should be equal to zero.

All houses are numbered from left to right, starting from one.

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

Output
3 2 0 2 0
Input
4
3 2 1 4

Output
2 3 4 0

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

import sys

#sys.stdin = open('input.txt')
#sys.stdout = open('output.txt', 'w')

n = int(input())
h = [int(i) for i in input().split()]
h = h[::-1]
ans = []
curmax = h[0] - 1
for i in range(n):
	if h[i] <= curmax:
		ans.append(curmax + 1 - h[i])
	else:
		ans.append(0)
	curmax = max(curmax, h[i])

ans = ans[::-1]
for x in ans:
	print(x, end = ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/581/C:
Petya loves computer games. Finally a game that he's been waiting for so long came out!

The main character of this game has n different skills, each of which is characterized by an integer a_{i} from 0 to 100. The higher the number a_{i} is, the higher is the i-th skill of the character. The total rating of the character is calculated as the sum of the values of $\lfloor \frac{a_{i}}{10} \rfloor$ for all i from 1 to n. The expression ⌊ x⌋ denotes the result of rounding the number x down to the nearest integer.

At the beginning of the game Petya got k improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if a_4 = 46, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused.

Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.

-----Input-----

The first line of the input contains two positive integers n and k (1 ≤ n ≤ 10^5, 0 ≤ k ≤ 10^7) — the number of skills of the character and the number of units of improvements at Petya's disposal.

The second line of the input contains a sequence of n integers a_{i} (0 ≤ a_{i} ≤ 100), where a_{i} characterizes the level of the i-th skill of the character.

-----Output-----

The first line of the output should contain a single non-negative integer — the maximum total rating of the character that Petya can get using k or less improvement units.

-----Examples-----
Input
2 4
7 9

Output
2

Input
3 8
17 15 19

Output
5

Input
2 2
99 100

Output
20

-----Note-----

In the first test case the optimal strategy is as follows. Petya has to improve the first skill to 10 by spending 3 improvement units, and the second skill to 10, by spending one improvement unit. Thus,...

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

n, k = [int(x) for x in input().split()]
l = [int(x) for x in input().split()]
assert len(l) == n
assert all(0 <= x <= 100 for x in l)
f = [10-l[i]%10 for i in range(n) if l[i]%10]
f.sort()
cur = sum(x // 10 for x in l)
for x in f:
    if k >= x:
        cur += 1
        k -= x
print(min(cur + k // 10, 10 * n))
#print(cur + k // 10)


I found an interesting problem on https://codeforces.com/problemset/problem/581/D:
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.

Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.

Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.

-----Input-----

The first line of the input contains six positive integers x_1, y_1, x_2, y_2, x_3, y_3 (1 ≤ x_1, y_1, x_2, y_2, x_3, y_3 ≤ 100), where x_{i} and y_{i} determine the length and width of the logo of the i-th company respectively.

-----Output-----

If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).

If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:  the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,  the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,  the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,

Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.

See the samples to better understand the statement.

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

Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC

Input
4 4 2 6 4...

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

x1, y1, x2, y2, x3, y3 = [int(s) for s in input().split()]

def print_logos(top, bottom, h1, h2):
    top_line = ""
    if 'a' in top:
        top_line += (x1 if top['a'] else y1) * "A"
    if 'b' in top:
        top_line += (x2 if top['b'] else y2) * "B"
    if 'c' in top:
        top_line += (x3 if top['c'] else y3) * "C"

    print(len(top_line))

    for i in range(h1):
        print(top_line)

    bottom_line = ""
    if 'a' in bottom:
        bottom_line += (x1 if bottom['a'] else y1) * "A"
    if 'b' in bottom:
        bottom_line += (x2 if bottom['b'] else y2) * "B"
    if 'c' in bottom:
        bottom_line += (x3 if bottom['c'] else y3) * "C"

    for i in range(h2):
        print(bottom_line)

done = False

for a in [True, False]: # flip logo 1
    if done:
        break
    for b in [True, False]: # flip logo 2
        if done: break

        for c in [True, False]: # flip logo 3
            # try 3 side-by-side
            width  = (x1 if a else y1) + (x2 if b else y2) + (x3 if c else y3)
            # all heights are correct
            if width == (y1 if a else x1) and \
               width == (y2 if b else x2) and \
               width == (y3 if c else x3):
                   # success!
                   print_logos({'a': a, 'b': b, 'c': c}, {}, y1 if a else x1, 0)
                   done = True
                   break

            # otherwise, try combinations [a, b] c, [a, c] b and [b, c] a

            # [a, b], c
            width = (x1 if a else y1) + (x2 if b else y2)
            if width == (x3 if c else y3) and \
               (y1 if a else x1) == (y2 if b else x2) and \
               (y1 if a else x1) + (y3 if c else x3) == width:
                   print_logos({'a': a, 'b': b}, {'c': c}, y1 if a else x1, y3 if c else x3)
                   done = True
                   break

            # [a, c], b
            width = (x1 if a else y1) + (x3 if c else y3)
            if width == (x2 if b else y2) and \
               (y1 if a else x1) == (y3 if c else x3) and \
              ...


I found an interesting problem on https://codeforces.com/problemset/problem/582/A:
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula  $g_{ij} = \operatorname{gcd}(a_{i}, a_{j})$

Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as $\operatorname{gcd}(x, y)$. For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: [Image]

Given all the numbers of the GCD table G, restore array a.

-----Input-----

The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n^2 space-separated numbers — the elements of the GCD table of G for array a.

All the numbers in the table are positive integers, not exceeding 10^9. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.

-----Output-----

In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.

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

Output
4 3 6 2
Input
1
42

Output
42
Input
2
1 1 1 1

Output
1 1

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

from collections import Counter
from fractions import gcd
input()
g, v = Counter(list(map(int, input().split()))), []
while g:
    x = max(g)
    g[x] -= 1
    for y in v:
        g[gcd(x, y)] -= 2
    v.append(x)
    g += Counter()
print(' '.join(map(str, v)))


I found an interesting problem on https://codeforces.com/problemset/problem/582/B:
You are given an array of positive integers a_1, a_2, ..., a_{n} × T of length n × T. We know that for any i > n it is true that a_{i} = a_{i} - n. Find the length of the longest non-decreasing sequence of the given array.

-----Input-----

The first line contains two space-separated integers: n, T (1 ≤ n ≤ 100, 1 ≤ T ≤ 10^7). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 300).

-----Output-----

Print a single number — the length of a sought sequence.

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

Output
5

-----Note-----

The array given in the sample looks like that: 3, 1, 4, 2, 3, 1, 4, 2, 3, 1, 4, 2. The elements in bold form the largest non-decreasing subsequence.

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

f = lambda: list(map(int, input().split()))
n, m = f()
t = list(f())
s = [0] * 301
d = s[:]
for i in t: d[i] += 1
for i in t * min(m, 2 * n): s[i] = max(s[:i + 1]) + 1
print(max(s) + max((m - n * 2) * max(d), 0))


I found an interesting problem on https://codeforces.com/problemset/problem/583/A:
City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.

Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.

Road repairs are planned for n^2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.

According to the schedule of road works tell in which days at least one road will be asphalted.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 50) — the number of vertical and horizontal roads in the city.

Next n^2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers h_{i}, v_{i} (1 ≤ h_{i}, v_{i} ≤ n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the h_{i}-th horizontal and v_{i}-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct.

-----Output-----

In the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1.

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

Output
1 4

Input
1
1 1

Output
1

-----Note-----

In the sample the brigade acts like that:  On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road;  On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been...

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

n=int(input())
sa=set()
sb=set()
l=[]
for i in range(n*n):
  a,b=list(map(int,input().split()))
  if not(a in sa) and not(b in sb):
    l+=[str(i+1)]
    sa.add(a)
    sb.add(b)
print(' '.join(l))


I found an interesting problem on https://codeforces.com/problemset/problem/583/B:
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least a_{i} any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.

The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.

It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.

-----Input-----

The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.

-----Output-----

Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.

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

Output
1

Input
5
4 2 3 0 1

Output
3

Input
7
0 3 1 0 5 2 6

Output
2

-----Note-----

In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.

In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth...

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

def getNum(n, arr):
    st1 = []
    st2 = []
    worth = 0
    count = 0

    for i in range(n):
        if arr[i] <= worth:
            worth += 1
        else:
            st1.append(arr[i])

    if len(st1) == 0:
        return count

    count += 1
    while len(st1) != 0:
        if st1[-1] <= worth:
            st1.pop()
            worth += 1
        else:
            st2.append(st1.pop())

        if len(st1) == 0:
            if len(st2) == 0:
                return count

            st1 = st2
            st2 = []
            count += 1

    return count

n = int(input())

arr = list(map(int, input().split()))

print(getNum(n, arr))


I found an interesting problem on https://codeforces.com/problemset/problem/584/B:
Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.

More formally, there are 3n gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the circle by numbers from 0 to 3n - 1, let the gnome sitting on the i-th place have a_{i} coins. If there is an integer i (0 ≤ i < n) such that a_{i} + a_{i} + n + a_{i} + 2n ≠ 6, then Tanya is satisfied.

Count the number of ways to choose a_{i} so that Tanya is satisfied. As there can be many ways of distributing coins, print the remainder of this number modulo 10^9 + 7. Two ways, a and b, are considered distinct if there is index i (0 ≤ i < 3n), such that a_{i} ≠ b_{i} (that is, some gnome got different number of coins in these two ways).

-----Input-----

A single line contains number n (1 ≤ n ≤ 10^5) — the number of the gnomes divided by three.

-----Output-----

Print a single number — the remainder of the number of variants of distributing coins that satisfy Tanya modulo 10^9 + 7.

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

Output
20
Input
2

Output
680

-----Note-----

20 ways for n = 1 (gnome with index 0 sits on the top of the triangle, gnome 1 on the right vertex, gnome 2 on the left vertex): [Image]

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/584/C:
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.

More formally, you are given two strings s_1, s_2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and b are different. Then your task will be to find any string s_3 of length n, such that f(s_1, s_3) = f(s_2, s_3) = t. If there is no such string, print  - 1.

-----Input-----

The first line contains two integers n and t (1 ≤ n ≤ 10^5, 0 ≤ t ≤ n).

The second line contains string s_1 of length n, consisting of lowercase English letters.

The third line contain string s_2 of length n, consisting of lowercase English letters.

-----Output-----

Print a string of length n, differing from string s_1 and from s_2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.

-----Examples-----
Input
3 2
abc
xyc

Output
ayd
Input
1 0
c
b

Output
-1

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

def f(sa, sb):
    ans = 0
    for i in range(len(sa)):
        ans += sa[i] != sb[i]
    return ans

def third(a0, b0):
    if a0 != "a" and b0 != "a":
        return "a"
    if a0 != "b" and b0 != "b":
        return "b"
    if a0 != "c" and b0 != "c":
        return "c"
n, t = list(map(int, input().split()))
s1 = input()
s2 = input()
sovp = n - f(s1, s2) #совпадающих из нашей строки
needsovp = n - t #необходимо совпадающих
ans = [0] * n
need1r = needsovp - sovp
need2r = needsovp - sovp
if sovp >= needsovp:
    for i in range(n):
        if s1[i] != s2[i]:
            ans[i] = third(s1[i], s2[i])
        elif needsovp > 0:
            ans[i] = s1[i]
            needsovp -= 1
        else:
            ans[i] = third(s1[i], s2[i])
    if not(f("".join(ans), s1) == f("".join(ans), s2) == t):
        print(-1)
    else:
        print(*ans, sep="")
else:
    for i in range(n):
        if s1[i] != s2[i]:
            if need1r > 0:
                need1r -= 1
                ans[i] = s1[i]
            elif need2r > 0:
                need2r -= 1
                ans[i] = s2[i]
            else:
                ans[i] = third(s1[i], s2[i])
        else:
            ans[i] = s1[i]
    if not(f("".join(ans), s1) == f("".join(ans), s2) == t):
        print(-1)
    else:
        print(*ans, sep="")


I found an interesting problem on https://codeforces.com/problemset/problem/584/D:
Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.

More formally, you are given an odd numer n. Find a set of numbers p_{i} (1 ≤ i ≤ k), such that

 1 ≤ k ≤ 3

 p_{i} is a prime

 $\sum_{i = 1}^{k} p_{i} = n$

The numbers p_{i} do not necessarily have to be distinct. It is guaranteed that at least one possible solution exists.

-----Input-----

The single line contains an odd number n (3 ≤ n < 10^9).

-----Output-----

In the first line print k (1 ≤ k ≤ 3), showing how many numbers are in the representation you found.

In the second line print numbers p_{i} in any order. If there are multiple possible solutions, you can print any of them.

-----Examples-----
Input
27

Output
3
5 11 11

-----Note-----

A prime is an integer strictly larger than one that is divisible only by one and by itself.

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

import math
def Prost(n):
    for i in range(2,int(math.sqrt(n))+1):
        if n%i==0:
            return False
    else:
        return True
n = int(input())
r=0
if Prost(n):
    print(1)
    print(n)
else:
    for i in range(n-1,n-300,-1):
        if Prost(i):
            r=i
            break

    k=n-r
    if (k==2):
        print(2)
        print(r,k)
    else:
        for i in range(2,k):
            if Prost(i) and Prost(k-i):
                print(3)
                print(r,i,k-i)
                break


I found an interesting problem on https://codeforces.com/problemset/problem/584/E:
Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.

More formally, we have two permutations, p and s of numbers from 1 to n. We can swap p_{i} and p_{j}, by paying |i - j| coins for it. Find and print the smallest number of coins required to obtain permutation s from permutation p. Also print the sequence of swap operations at which we obtain a solution.

-----Input-----

The first line contains a single number n (1 ≤ n ≤ 2000) — the length of the permutations.

The second line contains a sequence of n numbers from 1 to n — permutation p. Each number from 1 to n occurs exactly once in this line.

The third line contains a sequence of n numbers from 1 to n — permutation s. Each number from 1 to n occurs once in this line.

-----Output-----

In the first line print the minimum number of coins that you need to spend to transform permutation p into permutation s.

In the second line print number k (0 ≤ k ≤ 2·10^6) — the number of operations needed to get the solution.

In the next k lines print the operations. Each line must contain two numbers i and j (1 ≤ i, j ≤ n, i ≠ j), which means that you need to swap p_{i} and p_{j}.

It is guaranteed that the solution exists.

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

Output
3
2
4 3
3 1

-----Note-----

In the first sample test we swap numbers on positions 3 and 4 and permutation p becomes 4 2 3 1. We pay |3 - 4| = 1 coins for that. On second turn we swap numbers on positions 1 and 3 and get permutation 3241 equal to s. We pay |3 - 1| = 2 coins for that. In total we pay three coins.

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

n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = {}
for i in range(n):
    c[b[i]] = i
b = []
for i in range(n):
    a[i] = c[a[i]]
print(sum(abs(a[i] - i) for i in range(n)) >> 1)

while True:
    for i in range(n):
        if a[i] < i:
            for j in range(a[i], i):
                if a[j] >= i:
                    a[i], a[j] = a[j], a[i]
                    b += [(i+1, j+1)]
                    break
            break
    else:
        break

print(len(b))
for e in b:
    print(*e)


I found an interesting problem on https://codeforces.com/problemset/problem/585/C:
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.

You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.

-----Input-----

The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 10^18, xy > 1) — the number of oranges and apples that were initially in the bag.

-----Output-----

Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 10^6 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 10^6 characters. If there are several possible answers, you are allowed to print any of them.

If the sequence of cards that meet the problem statement does not not exist, print a single...

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

def gcd(a,b):

    if b==0:

        return a

    else:

        return gcd(b, a%b)

def solve(x, y, a, b):

    ans=""

    while not x==1 or not y==1:

        if x < y:

            x,y,a,b=y,x,b,a

        ans+=str((x-1)//y)+a

        x = x - (x-1)//y * y

    print (ans)

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

if gcd(x,y)>1:

    print ("Impossible")

else:

    solve(x,y, "A", "B")

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/586/A:
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.

One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).

The University works in such a way that every day it holds exactly n lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks).

The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the n pairs she knows if there will be a class at that time or not.

Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university.

Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home.

Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair.

-----Input-----

The first line of the input contains a positive integer n (1 ≤ n ≤ 100) — the number of lessons at the university.

The second line contains n numbers a_{i} (0 ≤ a_{i} ≤ 1). Number a_{i} equals 0, if Alena doesn't have the i-th pairs, otherwise it is equal to 1. Numbers a_1, a_2, ..., a_{n} are separated by spaces.

-----Output-----

Print a single number — the number of pairs during which Alena stays at the university.

-----Examples-----
Input
5
0 1 0 1 1

Output
4

Input
7
1 0 1 0 0 1...

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

input()
pprev, prev = None, None
ans = 0
for i in input().split():
    if i == '1':
        ans += 1
        if prev == '0' and pprev == '1':
            ans += 1
    pprev, prev = prev, i
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/586/B:
A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.

The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each row. Laurenty lives in the very last house of the second row. The only shop in town is placed in the first house of the first row.

The first and second rows are separated with the main avenue of the city. The adjacent houses of one row are separated by streets.

Each crosswalk of a street or an avenue has some traffic lights. In order to cross the street, you need to press a button on the traffic light, wait for a while for the green light and cross the street. Different traffic lights can have different waiting time.

The traffic light on the crosswalk from the j-th house of the i-th row to the (j + 1)-th house of the same row has waiting time equal to a_{ij} (1 ≤ i ≤ 2, 1 ≤ j ≤ n - 1). For the traffic light on the crossing from the j-th house of one row to the j-th house of another row the waiting time equals b_{j} (1 ≤ j ≤ n). The city doesn't have any other crossings.

The boy wants to get to the store, buy the products and go back. The main avenue of the city is wide enough, so the boy wants to cross it exactly once on the way to the store and exactly once on the way back home. The boy would get bored if he had to walk the same way again, so he wants the way home to be different from the way to the store in at least one crossing. [Image] Figure to the first sample.

Help Laurenty determine the minimum total time he needs to wait at the crossroads.

-----Input-----

The first line of the input contains integer n (2 ≤ n ≤ 50) — the number of houses in each row.

Each of the next two lines contains n - 1 space-separated integer — values a_{ij} (1 ≤ a_{ij} ≤ 100).

The last line contains n space-separated integers b_{j} (1 ≤ b_{j} ≤ 100).

-----Output-----

Print a single integer — the...

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

n = int(input())

shop_row = [0] + list(map(int, input().split()))
house_row = list(map(int, input().split())) + [0]
perek = list(map(int, input().split()))

for i in range(len(house_row) - 2, -1, -1):
    house_row[i] += house_row[i + 1]
for i in range(1, len(shop_row)):
    shop_row[i] += shop_row[i - 1]
rez = [None] * n
for i in range(n):
    rez[i] = house_row[i] + shop_row[i] + perek[i]
rez.sort()

if len(rez) > 1:
    print(rez[0] + rez[1])
else:
    print(rez[0] + rez[0])


I found an interesting problem on https://codeforces.com/problemset/problem/588/A:
Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly a_{i} kilograms of meat. [Image]

There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for p_{i} dollars per kilogram. Malek knows all numbers a_1, ..., a_{n} and p_1, ..., p_{n}. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.

Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days.

-----Input-----

The first line of input contains integer n (1 ≤ n ≤ 10^5), the number of days.

In the next n lines, i-th line contains two integers a_{i} and p_{i} (1 ≤ a_{i}, p_{i} ≤ 100), the amount of meat Duff needs and the cost of meat in that day.

-----Output-----

Print the minimum money needed to keep Duff happy for n days, in one line.

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

Output
10

Input
3
1 3
2 1
3 2

Output
8

-----Note-----

In the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.

In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day.

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

n = int(input())
minn = 101
ans = 0
for i in range(n):
    a, p = input().split()
    a = int(a)
    p = int(p)
    if p < minn:
        minn = p
    ans += minn*a
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/588/B:
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a^2 is a divisor of x. [Image]

Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to give her a lovely number from his store. He wants this number to be as big as possible.

Malek always had issues in math, so he asked for your help. Please tell him what is the biggest lovely number in his store.

-----Input-----

The first and only line of input contains one integer, n (1 ≤ n ≤ 10^12).

-----Output-----

Print the answer in one line.

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

Output
10

Input
12

Output
6

-----Note-----

In first sample case, there are numbers 1, 2, 5 and 10 in the shop. 10 isn't divisible by any perfect square, so 10 is lovely.

In second sample case, there are numbers 1, 2, 3, 4, 6 and 12 in the shop. 12 is divisible by 4 = 2^2, so 12 is not lovely, while 6 is indeed lovely.

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

import sys

#sys.stdin = open("input.txt")
#sys.stdout = open("output.txt", "w")

n = int(input())

di = [1]
i = 2
while n > 1:
	if i*i > n:
		break
	if n % i == 0:
		di += [i]
		while n % i == 0 and n > 1:
			n //= i
	i += 1

if n != 1:
	di += [n]

ans = 1
for item in di:
	ans *= item
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/590/B:
A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.

We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x_1, y_1), and the distress signal came from the point (x_2, y_2).

Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed $v_{\operatorname{max}}$ meters per second.

Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (v_{x}, v_{y}) for the nearest t seconds, and then will change to (w_{x}, w_{y}). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x, y), while its own velocity relative to the air is equal to zero and the wind (u_{x}, u_{y}) is blowing, then after $T$ seconds the new position of the dirigible will be $(x + \tau \cdot u_{x}, y + \tau \cdot u_{y})$.

Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.

It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.

-----Input-----

The first line of the input contains four integers x_1, y_1, x_2, y_2 (|x_1|,  |y_1|,  |x_2|,  |y_2| ≤ 10 000) — the coordinates of the...

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

scan=lambda:list(map(int,input().split()))
x1,y1,x2,y2=scan()
vmx,t=scan()
vx,vy=scan()
wx,wy=scan()
lb,ub,EPS=0,1e15,1e-8
while ub-lb>EPS:
	mid=(lb+ub)/2
	xx,yy=(vx*mid,vy*mid) if t-mid>EPS else (vx*t+wx*(mid-t),vy*t+wy*(mid-t))
	if vmx*mid-((x2-x1-xx)**2+(y2-y1-yy)**2)**.5>EPS:ub=mid
	else:lb=mid
print("%.8f"%ub)


I found an interesting problem on https://codeforces.com/problemset/problem/590/C:
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.

Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.

Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.

It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.

-----Input-----

The first line of the input contains the dimensions of the map n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns respectively.

Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.

-----Output-----

Print a single integer — the minimum number of cells you need to build a road inside in order...

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

#!/usr/bin/env python3
#
# Three States
#
import sys, os
from collections import deque
from pprint import pprint

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

n, m = read_ints()
s = [read_str() for _ in range(n)]

t = [set(), set(), set()]

for i in range(n):
	for j in range(m):
		if s[i][j] in '123':
			for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
				if 0 <= ii < n and 0 <= jj < m:
					if s[ii][jj] in '123.' and s[i][j] != s[ii][jj]:
						t[int(s[i][j]) - 1].add((i, j))
						break

z = [[[1e18] * 3 for j in range(m)] for i in range(n)]
ans = 1e18
for root in range(3):
	q = deque()
	vi = [[False] * m for _ in range(n)]
	for i, j in t[root]:
		q.append((i, j, 0))
		vi[i][j] = True
		z[i][j][root] = 0
	dist = [1e18] * 3
	dist[root] = 0
	while q:
		i, j, d = q.popleft()
		for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
			if 0 <= ii < n and 0 <= jj < m and not vi[ii][jj]:
				if s[ii][jj] == '.':
					vi[ii][jj] = True
					q.append((ii, jj, d + 1))
					z[ii][jj][root] = min(z[ii][jj][root], d + 1)
				elif s[ii][jj] != s[i][j] and s[ii][jj] in '123':
					dist[int(s[ii][jj]) - 1] = min(dist[int(s[ii][jj]) - 1], d)
	ans = min(ans, sum(dist))

if ans >= 1e18:
	print(-1)
else:
	for i in range(n):
		for j in range(m):
			if s[i][j] == '.':
				ans = min(ans, sum(z[i][j]) - 2)
	print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/591/A:
Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second.

The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.

Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.

-----Input-----

The first line of the input contains a single integer l (1 ≤ l ≤ 1 000) — the length of the corridor where the fight takes place.

The second line contains integer p, the third line contains integer q (1 ≤ p, q ≤ 500) — the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively.

-----Output-----

Print a single real number — the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10^{ - 4}.

Namely: let's assume that your answer equals 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...

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

n = int(input())
p = int(input())
q = int(input())
print(p*n/(p+q))


I found an interesting problem on https://codeforces.com/problemset/problem/591/B:
The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.

For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters x_{i} by y_{i}, and all the letters y_{i} by x_{i}. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that x_{i} coincides with y_{i}. The version of the name received after the work of the last designer becomes the new name of the corporation.

Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.

Satisfy Arkady's curiosity and tell him the final version of the name.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the length of the initial name and the number of designers hired, respectively.

The second line consists of n lowercase English letters and represents the original name of the corporation.

Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters x_{i} and y_{i}.

-----Output-----

Print the new name of the corporation.

-----Examples-----
Input
6 1
police
p m

Output
molice

Input
11 6
abacabadaba
a b
b c
a d
e g
f a
b b

Output
cdcbcdcfcdc

-----Note-----

In the second sample the name of the corporation consecutively changes as follows: $\text{abacabadaba} \rightarrow...

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

from math import sqrt, pow, log, log2, log10, exp
from copy import deepcopy
from fractions import gcd

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

def read_int():
    return read_ints()[0]

def read_floats():
    return list(map(float, input().split()))

def read_float():
    return read_floats()[0]

def format_list(l):
    return ' '.join(list(map(str, l)))

def one_dim_array(n, value=0):
    return [deepcopy(value) for x in range(n)]

def two_dim_array(n, m, value=0):
    return [[deepcopy(value) for x in range(m)] for x in range(n)]

def is_prime(n):
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    for i in range(3, sqrt(n) + 1):
        if n % i == 0:
            return False
    return True

def max_len_sublist(l, f):
    start, max_length, length = 0, 0, 0
    for i in range(1, len(l)):
        if f(l[i], l[i - 1]):
            length += 1
        else:
            if max_length < length:
                start = i - length
                max_length = length
            length = 0
    return start, max_length

def tf_to_yn(b):
    return 'YES' if b else 'NO'

def longest_non_descent_subsequence(s, restore_sequence=False):
    d = one_dim_array(len(s), 0)
    for i in range(len(s)):
        possible = [d[j] + 1 if s[j] <= s[i] else 1 for j in range(i)]
        d[i] = 1 if len(possible) == 0 else max(possible)

    if not restore_sequence:
        return d[-1] if len(d) != 0 else 0

def update_ch(ch, f, t):
    addedf = False
    addedt = False
    for key in list(ch.keys()):
        value = ch[key]
        if value == f:
            ch[key] = t
            addedf = True
        if value == t:
            ch[key] = f
            addedt = True
    if not addedf:
        ch[f] = t
    if not addedt:
        ch[t] = f

    return ch

n, m = read_ints()
s = list(input())
ch = {}

for i in range(1, m + 1):
    f, t = input().split()
    if f != t:
        update_ch(ch, f, t)

def map_with_ch(ch, x):
    if x in ch:
        return ch[x]
    else:
    ...


I found an interesting problem on https://codeforces.com/problemset/problem/592/A:
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».

This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.  $8$

Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.

There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.

Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.

Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.

Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.

-----Input-----

The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to...

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

board = [input(),input(),input(),input(),input(),input(),input(),input()]
b = -99
for i in range(8):
    for j in range(7,-1,-1):
        piece = board[j][i]
        if piece == 'W':
            break
        if piece == 'B':
            b = max(b,j)
            break
b = 7-b
w = 99
for i in range(8):
    for j in range(8):
        piece = board[j][i]
        if piece == 'B':
            break
        if piece == 'W':
            w = min(w,j)
if b < w:
    print('B')
else:
    print('A')


I found an interesting problem on https://codeforces.com/problemset/problem/592/B:
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.

Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.

 [Image]

Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.

Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?

-----Input-----

The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.

-----Output-----

Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.

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

Output
9

Input
3

Output
1

-----Note-----

One of the possible solutions for the first sample is shown on the picture above.

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/592/C:
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today.

 [Image]

Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.

While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes).

Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L.

Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today?

-----Input-----

The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·10^18) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively.

-----Output-----

Print the answer to the problem as an irreducible fraction [Image]. Follow the format of the samples output.

The fraction [Image] (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d.

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

Output
3/10

Input
7 1 2

Output
3/7

-----Note-----

In the first sample Willman and Bolt will tie in case 1, 6...

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

t, w, b = map(int, input().split())

def gcd(a, b):
    if b == 0: return a
    return gcd(b, a % b)

def lcm(a, b):
    return a // gcd(a, b) * b

add = min(w, b) - 1
l = lcm(w, b)

cnt = t // l

ans = add + cnt + cnt * add
ans -= max(0, l * cnt + add - t)

g = gcd(ans, t)
if g != 0:
    ans //= g
    t //= g

print(ans, end='')
print('/', end='')
print(t)


I found an interesting problem on https://codeforces.com/problemset/problem/592/D:
Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces.  [Image]

However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.

You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively.

Then follow n - 1 lines, describing the road system. Each line contains two city numbers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n) - the ends of the road i.

The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order.

-----Output-----

First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number.

Then print the minimum possible time needed to scare all humans in cities being attacked,...

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

from collections import deque
n,m = [int(x) for x in input().split()]
adj = [[] for x in range(n+1)]
for _ in range(1,n):
	a,b = [int(x) for x in input().split()]
	adj[a].append(b)
	adj[b].append(a)
chaos = [int(x) for x in input().split()]
s = chaos[0]
chaos = set(chaos)
cc = [0]*(n+1)
st = deque()
st.append((s,-1))
while len(st):
	u,e = st.pop()
	if u<0:
		if e>=0:
			cc[e] += cc[-u]
		continue
	if u in chaos:
		cc[u] +=1
	st.append((-u,e))

	for v in adj[u]:
		if v!=e:
			st.append((v,u))

#dfs(s,-1)
adj = [list([v for v in u if cc[v]>0]) for u in adj]
a = (s,0)
st = deque()
st.append((a[0],-1,0))
while len(st):
	u,e,h = st.pop()
	if h>a[1]:
		a = (u,h)
	elif h==a[1] and u<a[0]:
		a = (u,h)
	for v in adj[u]:
		if v!=e:
			st.append((v,u,h+1))
b = a
a = (a[0],0)
st = deque()
st.append((a[0],-1,0))
while len(st):
	u,e,h = st.pop()
	if h>a[1]:
		a = (u,h)
	elif h==a[1] and u<a[0]:
		a = (u,h)
	for v in adj[u]:
		if v!=e:
			st.append((v,u,h+1))
print(min(a[0],b[0]))
print(2*(n-cc.count(0))-a[1])


I found an interesting problem on https://codeforces.com/problemset/problem/593/A:
Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.

Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.

-----Input-----

The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input.

-----Output-----

Print a single integer — the maximum possible total length of words in Andrew's article.

-----Examples-----
Input
4
abb
cacc
aaa
bbb

Output
9
Input
5
a
a
bcbcb
cdecdecdecdecdecde
aaaa

Output
6

-----Note-----

In the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.

In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}.

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

n=int(input())
t=[[0 for i in range(26)] for j in range(26)]
for i in range(n):
	s=input()
	g=[0 for j in range(26)]
	for j in s:
		g[ord(j)-ord('a')]+=1
	nb=0
	for j in g:
		if j>0:nb+=1
	if nb==1:
		l=0
		for j in range(26):
			if g[j]>0:l=j
		for j in range(26):
			if l!=j:
				t[l][j]+=len(s)
				t[j][l]+=len(s)
	elif nb==2:
		l1=-1
		l2=-1
		for j in range(26):
			if g[j]>0:
				if l1==-1:l1=j
				else:l2=j
		t[l1][l2]+=len(s)
		t[l2][l1]+=len(s)
nb=0
for i in range(26):
	for j in range(26):
		nb=max(t[i][j],nb)
print(nb)


I found an interesting problem on https://codeforces.com/problemset/problem/593/B:
The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y = k_{i}·x + b_{i}. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between x_1 < x_2. In other words, is it true that there are 1 ≤ i < j ≤ n and x', y', such that:   y' = k_{i} * x' + b_{i}, that is, point (x', y') belongs to the line number i;  y' = k_{j} * x' + b_{j}, that is, point (x', y') belongs to the line number j;  x_1 < x' < x_2, that is, point (x', y') lies inside the strip bounded by x_1 < x_2.

You can't leave Anton in trouble, can you? Write a program that solves the given task.

-----Input-----

The first line of the input contains an integer n (2 ≤ n ≤ 100 000) — the number of lines in the task given to Anton. The second line contains integers x_1 and x_2 ( - 1 000 000 ≤ x_1 < x_2 ≤ 1 000 000) defining the strip inside which you need to find a point of intersection of at least two lines.

The following n lines contain integers k_{i}, b_{i} ( - 1 000 000 ≤ k_{i}, b_{i} ≤ 1 000 000) — the descriptions of the lines. It is guaranteed that all lines are pairwise distinct, that is, for any two i ≠ j it is true that either k_{i} ≠ k_{j}, or b_{i} ≠ b_{j}.

-----Output-----

Print "Yes" (without quotes), if there is at least one intersection of two distinct lines, located strictly inside the strip. Otherwise print "No" (without quotes).

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

Output
NO
Input
2
1 3
1 0
-1 3

Output
YES
Input
2
1 3
1 0
0 2

Output
YES
Input
2
1 3
1 0
0 3

Output
NO

-----Note-----

In the first sample there are intersections located on the border of the strip, but there are no intersections located strictly inside it. [Image]

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

n = int(input())
x1, x2 = list(map(int, input().split(" ")))

def intercepts(k, b):
    y1 = k*x1+b
    y2 = k*x2+b
    return [y1, y2]

inter=[]
for i in range (n):
    k, b = list(map(int, input().split(" ")))
    inter += [intercepts(k, b)]

inter.sort()
right=[]

for i in range (n):
    intercept = inter[i]
    right += [intercept[1]]

right2=[]
for thing in right:
    right2+=[thing]
right.sort()

if right == right2:
    print("NO")
else:
    print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/595/A:
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.

Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·m from left to right, then the j-th flat of the i-th floor has windows 2·j - 1 and 2·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.

Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of floors in the house and the number of flats on each floor respectively.

Next n lines describe the floors from top to bottom and contain 2·m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.

-----Output-----

Print a single integer — the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.

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

Output
3

Input
1 3
1 1 0 1 0 0

Output
2

-----Note-----

In the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.

In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off.

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

read = lambda: list(map(int, input().split()))
n, m = read()
a = [list(read()) for i in range(n)]
cnt = 0
for i in range(n):
    for j in range(m):
        if a[i][2 * j + 1] == 1 or a[i][2 * j] == 1:
            cnt += 1
print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/595/B:
Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits.

Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a_1, a_2, ..., a_{n} / k and b_1, b_2, ..., b_{n} / k. Let's split the phone number into blocks of length k. The first block will be formed by digits from the phone number that are on positions 1, 2,..., k, the second block will be formed by digits from the phone number that are on positions k + 1, k + 2, ..., 2·k and so on. Pasha considers a phone number good, if the i-th block doesn't start from the digit b_{i} and is divisible by a_{i} if represented as an integer.

To represent the block of length k as an integer, let's write it out as a sequence c_1, c_2,...,c_{k}. Then the integer is calculated as the result of the expression c_1·10^{k} - 1 + c_2·10^{k} - 2 + ... + c_{k}.

Pasha asks you to calculate the number of good phone numbers of length n, for the given k, a_{i} and b_{i}. As this number can be too big, print it modulo 10^9 + 7.

-----Input-----

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ min(n, 9)) — the length of all phone numbers and the length of each block, respectively. It is guaranteed that n is divisible by k.

The second line of the input contains n / k space-separated positive integers — sequence a_1, a_2, ..., a_{n} / k (1 ≤ a_{i} < 10^{k}).

The third line of the input contains n / k space-separated positive integers — sequence b_1, b_2, ..., b_{n} / k (0 ≤ b_{i} ≤ 9).

-----Output-----

Print a single integer — the number of good phone numbers of length n modulo 10^9 + 7.

-----Examples-----
Input
6 2
38 56 49
7 3 4

Output
8

Input
8 2
1 22 3 44
5 4 3 2

Output
32400

-----Note-----

In the first test sample good phone numbers are: 000000, 000098, 005600, 005698, 380000, 380098, 385600, 385698.

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

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

def calc_ans(k,a,b):
	div = (10**k-1)//a + 1

	b_min = b*10**(k-1)
	b_max = (b+1)*10**(k-1) - 1

	d_min_inc = math.ceil(b_min/a)
	d_max_inc = math.floor(b_max/a)
	# if d_min_inc*a > b_max:
	# 	return div
	# else:

	# print (k,a,b,div,div - (d_max_inc - d_min_inc + 1))

	return div - (d_max_inc - d_min_inc + 1)

p = 10**9 + 7

ans = 1
for ai,bi in zip(a,b):
	ans = (ans*calc_ans(k, ai, bi)) % p

print(ans)

def easy_calc(k,a,b):
	ans = 0
	for i in range(10**k):
		c = str(i)
		first = int(c[0]) if len(c) == k else 0
		if i%a == 0 and not first==b:
			ans += 1
	return ans

# import random
# for i in range(100):
# 	k = random.randrange(4,5)
# 	a = random.randrange(1,10**k)
# 	b = random.randrange(0, 10)
# 	if easy_calc(k,a,b) != calc_ans(k,a,b):
# 		print(k,a,b, easy_calc(k,a,b), calc_ans(k,a,b))
# 		1/0


I found an interesting problem on https://codeforces.com/problemset/problem/596/A:
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices.

Now Wilbur is wondering, if the remaining n vertices of the initial rectangle give enough information to restore the area of the planned swimming pool.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 4) — the number of vertices that were not erased by Wilbur's friend.

Each of the following n lines contains two integers x_{i} and y_{i} ( - 1000 ≤ x_{i}, y_{i} ≤ 1000) —the coordinates of the i-th vertex that remains. Vertices are given in an arbitrary order.

It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes.

-----Output-----

Print the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print  - 1.

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

Output
1

Input
1
1 1

Output
-1

-----Note-----

In the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square.

In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area.

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

n = int(input())
xset = set()
yset = set()
for i in range(n):
    x, y = list(map(int, input().split()))
    xset.add(x)
    yset.add(y)
if len(xset) == 2 and len(yset) == 2:
    xset = list(xset)
    yset = list(yset)
    print(abs(xset[0] - xset[1]) * abs(yset[0] - yset[1]))
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/596/B:
Wilbur the pig is tinkering with arrays again. He has the array a_1, a_2, ..., a_{n} initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements a_{i}, a_{i} + 1, ... , a_{n} or subtract 1 from all elements a_{i}, a_{i} + 1, ..., a_{n}. His goal is to end up with the array b_1, b_2, ..., b_{n}.

Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the array a_{i}. Initially a_{i} = 0 for every position i, so this array is not given in the input.

The second line of the input contains n integers b_1, b_2, ..., b_{n} ( - 10^9 ≤ b_{i} ≤ 10^9).

-----Output-----

Print the minimum number of steps that Wilbur needs to make in order to achieve a_{i} = b_{i} for all i.

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

Output
5
Input
4
1 2 2 1

Output
3

-----Note-----

In the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.

In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1.

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

n = int(input())
b = list(map(int, input().split()))
cur = 0
cnt = 0
for i in range(n):
	cnt += abs(cur - b[i])
	cur = b[i]
print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/596/C:
Wilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y also belong to this set.

Now Wilbur wants to number the points in the set he has, that is assign them distinct integer numbers from 1 to n. In order to make the numbering aesthetically pleasing, Wilbur imposes the condition that if some point (x, y) gets number i, then all (x',y') from the set, such that x' ≥ x and y' ≥ y must be assigned a number not less than i. For example, for a set of four points (0, 0), (0, 1), (1, 0) and (1, 1), there are two aesthetically pleasing numberings. One is 1, 2, 3, 4 and another one is 1, 3, 2, 4.

Wilbur's friend comes along and challenges Wilbur. For any point he defines it's special value as s(x, y) = y - x. Now he gives Wilbur some w_1, w_2,..., w_{n}, and asks him to find an aesthetically pleasing numbering of the points in the set, such that the point that gets number i has it's special value equal to w_{i}, that is s(x_{i}, y_{i}) = y_{i} - x_{i} = w_{i}.

Now Wilbur asks you to help him with this challenge.

-----Input-----

The first line of the input consists of a single integer n (1 ≤ n ≤ 100 000) — the number of points in the set Wilbur is playing with.

Next follow n lines with points descriptions. Each line contains two integers x and y (0 ≤ x, y ≤ 100 000), that give one point in Wilbur's set. It's guaranteed that all points are distinct. Also, it is guaranteed that if some point (x, y) is present in the input, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y, are also present in the input.

The last line of the input contains n integers. The i-th of them is w_{i} ( - 100 000 ≤ w_{i} ≤ 100 000) — the required special value of the point that gets number i in any aesthetically pleasing numbering.

-----Output-----

If there exists an aesthetically pleasant numbering of points in the set, such that s(x_{i}, y_{i}) = y_{i}...

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

from collections import defaultdict

def solve():
    N = int(input())

    maxx = 0
    maxy = 0
    WS = defaultdict(list)

    for i in range(N):
        x, y = list(map(int, input().split()))
        WS[y - x].append((x, y))
        maxx = max(maxx, x)
        maxy = max(maxy, y)

    for w in WS:
        WS[w].sort(reverse=True)

    W = list(map(int, input().split()))

    ans = [None] * N

    mx = [0] * (maxy + 1)
    my = [0] * (maxx + 1)

    for i in range(N):
        w = W[i]
        if WS[w]:
            ans[i] = ax, ay = WS[w].pop()
            if mx[ay] == ax and my[ax] == ay:
                mx[ay] = ax + 1
                my[ax] = ay + 1

            else:
                print('NO')
                return
        else:
            print('NO')
            return

    print('YES')
    for a in ans:
        print(a[0], a[1])

def __starting_point():
    solve()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/597/A:
Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a ≤ x ≤ b and x is divisible by k.

-----Input-----

The only line contains three space-separated integers k, a and b (1 ≤ k ≤ 10^18; - 10^18 ≤ a ≤ b ≤ 10^18).

-----Output-----

Print the required number.

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

Output
10

Input
2 -4 4

Output
5

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

k, a, b = map(int, input().split())
print(b // k - (a - 1) // k)


I found an interesting problem on https://codeforces.com/problemset/problem/597/B:
A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values — the start time l_{i} and the finish time r_{i} (l_{i} ≤ r_{i}).

Restaurant management can accept and reject orders. What is the maximal number of orders the restaurant can accept?

No two accepted orders can intersect, i.e. they can't share even a moment of time. If one order ends in the moment other starts, they can't be accepted both.

-----Input-----

The first line contains integer number n (1 ≤ n ≤ 5·10^5) — number of orders. The following n lines contain integer values l_{i} and r_{i} each (1 ≤ l_{i} ≤ r_{i} ≤ 10^9).

-----Output-----

Print the maximal number of orders that can be accepted.

-----Examples-----
Input
2
7 11
4 7

Output
1

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

Output
3

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

Output
2

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

n=int(input())
a=[]
for i in range(n):
	a.append(tuple(map(int,input().split())))
a.sort(key=lambda x:x[1])
cnt=0;cur=-10
i=0
while i<n:
	if cur<a[i][0]:
		cur=a[i][1]
		cnt+=1
	i+=1
print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/598/A:
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.

For example, for n = 4 the sum is equal to  - 1 - 2 + 3 - 4 =  - 4, because 1, 2 and 4 are 2^0, 2^1 and 2^2 respectively.

Calculate the answer for t values of n.

-----Input-----

The first line of the input contains a single integer t (1 ≤ t ≤ 100) — the number of values of n to be processed.

Each of next t lines contains a single integer n (1 ≤ n ≤ 10^9).

-----Output-----

Print the requested sum for each of t integers n given in the input.

-----Examples-----
Input
2
4
1000000000

Output
-4
499999998352516354

-----Note-----

The answer for the first sample is explained in the statement.

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

t = int(input())
for i in range(t):
    n = int(input())
    result = n * (n + 1) // 2
    j = 1
    while j <= n:
        result -= 2 * j
        j *= 2
    print(result)


I found an interesting problem on https://codeforces.com/problemset/problem/598/B:
You are given a string s and should process m queries. Each query is described by two 1-based indices l_{i}, r_{i} and integer k_{i}. It means that you should cyclically shift the substring s[l_{i}... r_{i}] k_{i} times. The queries should be processed one after another in the order they are given.

One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.

For example, if the string s is abacaba and the query is l_1 = 3, r_1 = 6, k_1 = 1 then the answer is abbacaa. If after that we would process the query l_2 = 1, r_2 = 4, k_2 = 2 then we would get the string baabcaa.

-----Input-----

The first line of the input contains the string s (1 ≤ |s| ≤ 10 000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters.

Second line contains a single integer m (1 ≤ m ≤ 300) — the number of queries.

The i-th of the next m lines contains three integers l_{i}, r_{i} and k_{i} (1 ≤ l_{i} ≤ r_{i} ≤ |s|, 1 ≤ k_{i} ≤ 1 000 000) — the description of the i-th query.

-----Output-----

Print the resulting string s after processing all m queries.

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

Output
baabcaa

-----Note-----

The sample is described in problem statement.

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

string = [e for e in input()]
n = int(input())

for i in range(n):
    l, r, k = map(int, input().split())
    l -= 1
    r -= 1
    k %= r - l + 1
    old_string = string[l:r + 1]
    for j in range(l, r + 1):
        string[j] = old_string[j - l - k]

print(''.join(string))


I found an interesting problem on https://codeforces.com/problemset/problem/598/C:
You are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them.

Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 and π. For example, opposite directions vectors have angle equals to π.

-----Input-----

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

The i-th of the following n lines contains two integers x_{i} and y_{i} (|x|, |y| ≤ 10 000, x^2 + y^2 > 0) — the coordinates of the i-th vector. Vectors are numbered from 1 to n in order of appearing in the input. It is guaranteed that no two vectors in the input share the same direction (but they still can have opposite directions).

-----Output-----

Print two integer numbers a and b (a ≠ b) — a pair of indices of vectors with the minimal non-oriented angle. You can print the numbers in any order. If there are many possible answers, print any.

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

Output
3 4

Input
6
-1 0
0 -1
1 0
1 1
-4 -5
-4 -6

Output
6 5

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

import sys
# sys.stdin = open('ivo.in')

def getkos(x, y):
    temp = (x[0] * y[0] + x[1] * y[1])
    mul = -1 if temp < 0 else 1
    return (mul * temp ** 2, (x[0] ** 2 + x[1] ** 2) * (y[0] ** 2 + y[1] ** 2))

class Drob:
    def __init__(self, num, denom):
        self.num = num
        self.denom = denom

    def __lt__(self, object):
        return self.num * object.denom < object.num * self.denom

n = int(sys.stdin.readline())

positive = []
negative = []
for i in range(n):
    x = tuple(map(int, sys.stdin.readline().split())) + (i,)
    if x[1] > 0:
        positive.append(x)
    else:
        negative.append(x)

positive.sort(key=lambda x: ((-1 if x[0] > 0 else 1) * x[0]**2 / (x[1] ** 2 +  x[0] ** 2)))
negative.sort(key=lambda x: ((1 if x[0] > 0 else -1) * x[0]**2 / (x[1] ** 2 +  x[0] ** 2)))
#negative.sort(key=lambda x,y: x[0] - y[0] if x[0] != y[0] else (y[1] - x[1]) * x[0])

all = positive + negative
# print(all)
biggest = [-1.1, 1]
bi = 0
bj = 1
for i in range(n):
    nxt = (i + 1) % n
    prev = (i + n - 1) % n

    kos1 = getkos(all[i], all[nxt])
    if kos1[1] * biggest[0] < kos1[0] * biggest[1]:
        biggest = kos1
        bi = all[i][2]
        bj = all[nxt][2]
    kos2 = getkos(all[i], all[prev])
    if kos2[1] * biggest[0] < kos2[0] * biggest[1]:
        biggest = kos2
        bi = all[i][2]
        bj = all[prev][2]
    # print("{} kos1: {} kos2: {}".format(i, kos1, kos2))

# print(biggest)
print("%d %d" % (bi + 1, bj+ 1))


I found an interesting problem on https://codeforces.com/problemset/problem/598/D:
Igor is in the museum and he wants to see as many pictures as possible.

Museum can be represented as a rectangular field of n × m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.

At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.

For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.

-----Input-----

First line of the input contains three integers n, m and k (3 ≤ n, m ≤ 1000, 1 ≤ k ≤ min(n·m, 100 000)) — the museum dimensions and the number of starting positions to process.

Each of the next n lines contains m symbols '.', '*' — the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum.

Each of the last k lines contains two integers x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) — the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns — from left to right. It is guaranteed that all starting positions are empty cells.

-----Output-----

Print k integers — the maximum number of pictures, that Igor can see if he starts in corresponding position.

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

Output
6
4
10

Input
4 4 1
****
*..*
*.**
****
3 2

Output
8

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

import sys

def get_array(): return list(map(int, sys.stdin.readline().split()))
def get_ints(): return list(map(int, sys.stdin.readline().split()))
def input(): return sys.stdin.readline().strip('\n')

cells = []

''' Using Pajenegod's dfs '''
def dfs(x,y):
    nonlocal c
    q = [(x,y)]

    while q:
        x, y = q.pop()
        if x >= n or x < 0 or y >= m or y < 0:
            continue
        if l[x][y] == '*':
            c += 1
            continue
        if visited[x][y]:
            continue

        visited[x][y] = 1
        cells.append((x,y))
        q.append((x+1,y))
        q.append((x,y+1))
        q.append((x-1,y))
        q.append((x,y-1))

n , m , k = get_ints()
l = []
for i in range(n):
    l.append(list(input()))

visited = []
out = []

for i in range(n+10):
    visited.append([0]*(m+10))
    out.append([-1]*(m+10))

for i in range(n):
    for j in range(m):
        if not visited[i][j] and l[i][j] == '.':
            c = 0
            dfs(i,j)
            for x in cells:
                if visited[x[0]][x[1]] and out[x[0]][x[1]] == -1:
                    out[x[0]][x[1]] = c
            cells.clear()
for i in range(k):
    x , y = get_ints()
    x , y = x-1 , y-1
    print(out[x][y])


I found an interesting problem on https://codeforces.com/problemset/problem/598/F:
Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon.

The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles.

-----Input-----

The first line contains integers n and m (3 ≤ n ≤ 1000;1 ≤ m ≤ 100). The following n lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.

The following m lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.

All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 10^5 by absolute values.

-----Output-----

Print m lines, the i-th line should contain the length of common part of the given n-gon and the i-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10^{ - 6}.

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

Output
1.41421356237309514547
1.00000000000000000000
0.00000000000000000000

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

def main():
    from math import hypot
    n, m = list(map(int, input().split()))
    vertices = list(tuple(map(float, input().split())) for _ in range(n))
    ax, ay = vertices[-1]
    for i, (bx, by) in enumerate(vertices):
        vertices[i], ax, ay = (bx, by, bx - ax, by - ay), bx, by
    for _ in range(m):
        x0, y0, x1, y1 = list(map(float, input().split()))
        x1 -= x0
        y1 -= y0
        bx, by = vertices[-1][:2]
        tmp = (bx - x0) * y1 - (by - y0) * x1
        t = -1 if tmp < 0 else 1 if tmp > 0 else 0
        res = []
        for bx, by, abx, aby in vertices:
            s, tmp = t, (bx - x0) * y1 - (by - y0) * x1
            t = -1 if tmp < 0 else 1 if tmp > 0 else 0
            if s != t:
                res.append((((bx - x0) * aby - (by - y0) * abx) / (x1 * aby - y1 * abx), s - t))
        res.sort()
        t, w = 0, 0.
        for i, (tmp, s) in enumerate(res, -1):
            if t:
                w += tmp - res[i][0]
            t += s
        print(w * hypot(x1, y1))

def __starting_point():
    main()

__starting_point()