I found an interesting problem on https://codeforces.com/problemset/problem/616/A:
You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.

The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.

As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().

-----Input-----

The first line contains a non-negative integer a.

The second line contains a non-negative integer b.

The numbers a, b may contain leading zeroes. Each of them contains no more than 10^6 digits.

-----Output-----

Print the symbol "<" if a < b and the symbol ">" if a > b. If the numbers are equal print the symbol "=".

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

Output
<

Input
11
10

Output
>

Input
00012345
12345

Output
=

Input
0123
9

Output
>

Input
0123
111

Output
>

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

a = str(input())
b = str(input())

a = a.lstrip('0')

b = b.lstrip('0')
flag = True

if len(a) > len(b):
    print(">")
    flag = False
elif len(a) < len(b):
    print('<')
    flag = False

if flag:
    flag1 = True

    for i in range(len(a)):
        if (int(a[i]) > int(b[i])):
            print('>')
            flag1 = False
            break
        if  (int(a[i]) < int(b[i])):
            print("<")
            flag1 = False
            break

    if (flag1):
        print('=')


I found an interesting problem on https://codeforces.com/problemset/problem/616/B:
Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.

Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from 1 to n and the avenues are numbered with integers from 1 to m. The cost of dinner in the restaurant at the intersection of the i-th street and the j-th avenue is c_{ij}.

Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.

-----Input-----

The first line contains two integers n, m (1 ≤ n, m ≤ 100) — the number of streets and avenues in Munhattan.

Each of the next n lines contains m integers c_{ij} (1 ≤ c_{ij} ≤ 10^9) — the cost of the dinner in the restaurant on the intersection of the i-th street and the j-th avenue.

-----Output-----

Print the only integer a — the cost of the dinner for Jack and Emma.

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

Output
2

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

Output
1

-----Note-----

In the first example if Emma chooses the first or the third streets Jack can choose an avenue with the cost of the dinner 1. So she chooses the second street and Jack chooses any avenue. The cost of the dinner is 2.

In the second example regardless of Emma's choice Jack can choose a restaurant with the cost of the dinner 1.

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

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

mat = []
maxi = 0
for i in range(n):
    a = list(map(int, input().split()))
    mini = min(a)
    maxi = max(maxi, mini)
print(maxi)


I found an interesting problem on https://codeforces.com/problemset/problem/616/C:
You are given a rectangular field of n × m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.

Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.

For each impassable cell (x, y) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (x, y). You should do it for each impassable cell independently.

The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be "." if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces.

To make your output faster it is recommended to build the output as an array of n strings having length m and print it as a sequence of lines. It will be much faster than writing character-by-character.

As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

-----Input-----

The first line contains two integers n, m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the field.

Each of the next n lines contains m symbols: "." for empty cells, "*" for impassable cells.

-----Output-----

Print the answer as a matrix as described above. See the examples to precise the format of the output.

-----Examples-----
Input
3 3
*.*
.*.
*.*

Output
3.3
.5.
3.3

Input
4 5
**..*
..***
.*.*.
*.*.*

Output
46..3
..732
.6.4.
5.4.3

-----Note-----

In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If...

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

"""
	Author		: Arif Ahmad
	Date  		:
	Algo  		:
	Difficulty	:
"""
from sys import stdin, stdout
from collections import deque

g = None # contains the actual graph
h = None # h[x][y] represents the component in which cell (x,y) belongs
r = None
c = None
visited = None
total = None
comp = None
dx = [-1, 0, 0, 1]
dy = [0, -1, 1, 0]

def bfs(x, y):
	nonlocal total

	q = deque([(x, y)])
	total += 1
	visited[x][y] = True
	h[x][y] = comp
	while q:
		x, y = q.pop()
		#print('comp:', comp, 'cell:', x, y)
		for k in range(4):
			#print('loop:', k)
			nx = x + dx[k]
			ny = y + dy[k]
			#print(visited)
			#print('new cell:', nx, ny, 'check:', nx>=0 , nx<r , ny>=0 , ny<c , visited[nx][ny]==False , g[nx][ny]=='.')
			if nx>=0 and nx<r and ny>=0 and ny<c and visited[nx][ny]==False and g[nx][ny]=='.':
				q.appendleft((nx, ny))
				total += 1
				visited[nx][ny] = True
				h[nx][ny] = comp

def main():
	nonlocal g, h, r, c, visited, comp, total

	r, c = [int(_) for _ in stdin.readline().split()]

	g = []
	for i in range(r):
		line = stdin.readline()
		g.append(list(line))

	component = []
	h = [[-1 for i in range(c)] for j in range(r)]
	visited = [[False for i in range(c)] for j in range(r)]
	#print(visited)

	for i in range(r):
		for j in range(c):
			if visited[i][j] == False and g[i][j] == '.':
				comp = len(component)
				total = 0
				#print('calling bfs', i, j)
				bfs(i, j)
				component.append(total)

	for x in range(r):
		for y in range(c):
			if g[x][y] == '*':
				ans = 0
				idx = set()
				for k in range(4):
					nx = x + dx[k]
					ny = y + dy[k]
					if nx>=0 and nx<r and ny>=0 and ny<c and g[nx][ny]=='.':
						idx.add(h[nx][ny])
				for item in idx:
					#print(component[item])
					ans += component[item]
				ans += 1
				ans %= 10
				g[x][y] = str(ans)

	#print(component)
	for i in range(r):
		stdout.write(''.join(g[i]))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/616/D:
The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.

Find any longest k-good segment.

As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

-----Input-----

The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·10^5) — the number of elements in a and the parameter k.

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

-----Output-----

Print two integers l, r (1 ≤ l ≤ r ≤ n) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.

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

Output
1 5

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

Output
3 7

Input
3 1
1 2 3

Output
1 1

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

import sys
n, m = list(map(int, sys.stdin.readline().split()))
vis = [0] * 1000005
num = list(map(int, sys.stdin.readline().split()))
flag = 0
temp = num[0]
for i in range(n):
    if num[i] != temp:
        flag = 1
        break
if flag == 0:
    print("{0} {1}".format(1, n))
else:
    l = 0
    r = 0
    al = 0
    ar = 0
    ans = 0
    now = 0
    for i in range(n):
        vis[num[i]] += 1
        if vis[num[i]] == 1:
            now += 1
        while now > m:
            vis[num[l]] -= 1
            if vis[num[l]] == 0:
                now -= 1
            l += 1
        if i - l + 1 > ar - al + 1:
            ar = i
            al = l
    print('{0} {1}'.format(al+1, ar+1))


I found an interesting problem on https://codeforces.com/problemset/problem/616/E:
Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m. As the result can be very large, you should print the value modulo 10^9 + 7 (the remainder when divided by 10^9 + 7).

The modulo operator a mod b stands for the remainder after dividing a by b. For example 10 mod 3 = 1.

-----Input-----

The only line contains two integers n, m (1 ≤ n, m ≤ 10^13) — the parameters of the sum.

-----Output-----

Print integer s — the value of the required sum modulo 10^9 + 7.

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

Output
4

Input
4 4

Output
1

Input
1 1

Output
0

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

import math

n, m = map(int, input().split())
mod = pow(10, 9) + 7
ans = 0
if n < m:
    ans = n * (m - n) % mod
    m = n
ns = int(math.sqrt(n))
x = [0] * ns
f = 1
for i in range(ns):
    if i + 1 > m:
        f = 0
        break
    x[i] = n // (i + 1)
    ans += (n - x[i] * (i + 1))
    ans %= mod
for i in range(ns + 1, max(ns + 1, x[-1] + 1)):
    ans += n % i
    ans %= mod
if f:
    for i in range(ns - 1):
        if x[i + 1] >= m:
            continue
        c = x[i] - x[i + 1]
        ans += ((n - x[i] * (i + 1)) * c + (i + 1) * c * (c - 1) // 2)
        ans %= mod
        if x[i] >= m > x[i + 1]:
            c = x[i] - m
            ans -= ((n - x[i] * (i + 1)) * c + (i + 1) * c * (c - 1) // 2)
            ans %= mod
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/617/A:
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.

-----Input-----

The first line of the input contains an integer x (1 ≤ x ≤ 1 000 000) — The coordinate of the friend's house.

-----Output-----

Print the minimum number of steps that elephant needs to make to get from point 0 to point x.

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

Output
1

Input
12

Output
3

-----Note-----

In the first sample the elephant needs to make one step of length 5 to reach the point x.

In the second sample the elephant can get to point x if he moves by 3, 5 and 4. There are other ways to get the optimal answer but the elephant cannot reach x in less than three moves.

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/617/B:
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces.

You are asked to calculate the number of ways he can do it. Two ways to break chocolate are considered distinct if one of them contains a break between some two adjacent pieces and the other one doesn't.

Please note, that if Bob doesn't make any breaks, all the bar will form one piece and it still has to have exactly one nut.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 100) — the number of pieces in the chocolate bar.

The second line contains n integers a_{i} (0 ≤ a_{i} ≤ 1), where 0 represents a piece without the nut and 1 stands for a piece with the nut.

-----Output-----

Print the number of ways to break the chocolate into multiple parts so that each part would contain exactly one nut.

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

Output
1

Input
5
1 0 1 0 1

Output
4

-----Note-----

In the first sample there is exactly one nut, so the number of ways equals 1 — Bob shouldn't make any breaks.

In the second sample you can break the bar in four ways:

10|10|1

1|010|1

10|1|01

1|01|01

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

n = int(input())
lst = list(map(int, input().split()))
ans = 1
cnt = 0
if 1 in lst:
    p = lst.index(1)
    for i in range(p, n):
        if lst[i] == 1:
            if cnt != 0:
                ans *= cnt
                cnt = 0
        cnt += 1
    print(ans)
else:
    print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/617/C:
A flowerbed has many flowers and two fountains.

You can adjust the water pressure and set any values r_1(r_1 ≥ 0) and r_2(r_2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r_1 and r_2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r_1, or the distance to the second fountain doesn't exceed r_2. It's OK if some flowers are watered by both fountains.

You need to decrease the amount of water you need, that is set such r_1 and r_2 that all the flowers are watered and the r_1^2 + r_2^2 is minimum possible. Find this minimum value.

-----Input-----

The first line of the input contains integers n, x_1, y_1, x_2, y_2 (1 ≤ n ≤ 2000,  - 10^7 ≤ x_1, y_1, x_2, y_2 ≤ 10^7) — the number of flowers, the coordinates of the first and the second fountain.

Next follow n lines. The i-th of these lines contains integers x_{i} and y_{i} ( - 10^7 ≤ x_{i}, y_{i} ≤ 10^7) — the coordinates of the i-th flower.

It is guaranteed that all n + 2 points in the input are distinct.

-----Output-----

Print the minimum possible value r_1^2 + r_2^2. Note, that in this problem optimal answer is always integer.

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

Output
6

Input
4 0 0 5 0
9 4
8 3
-1 0
1 4

Output
33

-----Note-----

The first sample is (r_1^2 = 5, r_2^2 = 1): $0^{\circ}$ The second sample is (r_1^2 = 1, r_2^2 = 32): [Image]

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

#!/usr/bin/env python3

from collections import namedtuple
from functools   import reduce
from operator    import itemgetter

Point = namedtuple("Point", "x y d1 d2")

try:
    while True:
        n, x1, y1, x2, y2 = list(map(int, input().split()))
        points = [Point(x1, y1, 0, 1e18)]
        for i in range(n):
            x, y = list(map(int, input().split()))
            points.append(Point(x, y, (x - x1)**2 + (y - y1)**2, (x - x2)**2 + (y - y2)**2))
        result = 1e18
        l2 = itemgetter(3)
        result = reduce(
            min,
            list(map(
                lambda a: min(
                    result, a.d1 + reduce(max, list(map(l2, [p for p in points if p.d1 > a.d1])), 0)
                ),
                points,
            )),
        )
        print(result)

except EOFError:
    pass


I found an interesting problem on https://codeforces.com/problemset/problem/617/D:
There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this polyline may consist of.

-----Input-----

Each of the three lines of the input contains two integers. The i-th line contains integers x_{i} and y_{i} ( - 10^9 ≤ x_{i}, y_{i} ≤ 10^9) — the coordinates of the i-th point. It is guaranteed that all points are distinct.

-----Output-----

Print a single number — the minimum possible number of segments of the polyline.

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

Output
1

Input
-1 -1
-1 3
4 3

Output
2

Input
1 1
2 3
3 2

Output
3

-----Note-----

The variant of the polyline in the first sample: [Image] The variant of the polyline in the second sample: $1$ The variant of the polyline in the third sample: $\because$

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/618/A:
Your friend recently gave you some slimes for your birthday. You have n slimes all initially with value 1.

You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other n - 1 slimes one by one. When you add a slime, you place it at the right of all already placed slimes. Then, while the last two slimes in the row have the same value v, you combine them together to create a slime with value v + 1.

You would like to see what the final state of the row is after you've added all n slimes. Please print the values of the slimes in the row from left to right.

-----Input-----

The first line of the input will contain a single integer, n (1 ≤ n ≤ 100 000).

-----Output-----

Output a single line with k integers, where k is the number of slimes in the row after you've finished the procedure described in the problem statement. The i-th of these numbers should be the value of the i-th slime from the left.

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

Output
1

Input
2

Output
2

Input
3

Output
2 1

Input
8

Output
4

-----Note-----

In the first sample, we only have a single slime with value 1. The final state of the board is just a single slime with value 1.

In the second sample, we perform the following steps:

Initially we place a single slime in a row by itself. Thus, row is initially 1.

Then, we will add another slime. The row is now 1 1. Since two rightmost slimes have the same values, we should replace these slimes with one with value 2. Thus, the final state of the board is 2.

In the third sample, after adding the first two slimes, our row is 2. After adding one more slime, the row becomes 2 1.

In the last sample, the steps look as follows:   1  2  2 1  3  3 1  3 2  3 2 1  4

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

n = int(input())

v = []
for i in range(n):
    v.append(1)

    while len(v) >= 2 and v[-2] == v[-1]:
        x = v.pop()
        v.pop()
        v.append(x+1)

print(' '.join([str(x) for x in v]))


I found an interesting problem on https://codeforces.com/problemset/problem/620/A:
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x_1, y_1) and should go to the point (x_2, y_2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps the robot should make to get the finish position.

-----Input-----

The first line contains two integers x_1, y_1 ( - 10^9 ≤ x_1, y_1 ≤ 10^9) — the start position of the robot.

The second line contains two integers x_2, y_2 ( - 10^9 ≤ x_2, y_2 ≤ 10^9) — the finish position of the robot.

-----Output-----

Print the only integer d — the minimal number of steps to get the finish position.

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

Output
5

Input
3 4
6 1

Output
3

-----Note-----

In the first example robot should increase both of its coordinates by one four times, so it will be in position (4, 4). After that robot should simply increase its y coordinate and get the finish position.

In the second example robot should simultaneously increase x coordinate and decrease y coordinate by one three times.

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

#author="_rabbit"
a,b=list(map(int,input().split()))
c,d=list(map(int,input().split()))
print(max(abs(a-c),abs(b-d)))


I found an interesting problem on https://codeforces.com/problemset/problem/620/B:
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (https://en.wikipedia.org/wiki/Seven-segment_display). [Image]

Max starts to type all the values from a to b. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator.

For example if a = 1 and b = 3 then at first the calculator will print 2 segments, then — 5 segments and at last it will print 5 segments. So the total number of printed segments is 12.

-----Input-----

The only line contains two integers a, b (1 ≤ a ≤ b ≤ 10^6) — the first and the last number typed by Max.

-----Output-----

Print the only integer a — the total number of printed segments.

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

Output
12

Input
10 15

Output
39

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

a, b = map(int, input().split())
ary = str(list(range(a, b + 1)))
zero = ary.count('0')
one = ary.count('1')
two = ary.count('2')
three = ary.count('3')
four = ary.count('4')
five = ary.count('5')
six = ary.count('6')
seven = ary.count('7')
eight = ary.count('8')
nine = ary.count('9')
ans = zero*6 + one*2 + two*5 + three*5 + four*4 + five*5 + six*6 + seven*3 + eight*7 + nine*6
print (ans)


I found an interesting problem on https://codeforces.com/problemset/problem/620/C:
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type a_{i}.

Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.

Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.

As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 3·10^5) — the number of pearls in a row.

The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) – the type of the i-th pearl.

-----Output-----

On the first line print integer k — the maximal number of segments in a partition of the row.

Each of the next k lines should contain two integers l_{j}, r_{j} (1 ≤ l_{j} ≤ r_{j} ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment.

Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type.

If there are several optimal solutions print any of them. You can print the segments in any order.

If there are no correct partitions of the row print the number "-1".

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

Output
1
1 5

Input
5
1 2 3 4 5

Output
-1

Input
7
1 2 1 3 1 2 1

Output
2
1 3
4 7

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

3

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

r = []
s = set()
l = 0
for i, x in enumerate(a):
  if x in s:
    r.append([l + 1, i + 1])
    l = i + 1
    s = set()
  else:
    s.add(x)
if l == 0:
  print(-1)
else:
  if s:
    r[-1][1] = n
  print(len(r))
  print('\n'.join('{0} {1}'.format(p, q) for (p, q) in r))


I found an interesting problem on https://codeforces.com/problemset/problem/620/D:
Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a s_{a} as close as possible to the sum of the elements in the array b s_{b}. So he wants to minimize the value v = |s_{a} - s_{b}|.

In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5, 1, 3, 2, 4] and the array b is [3, 3, 2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2, 1, 3, 2, 4] and the new array b [3, 3, 5].

Professor doesn't want to make more than two swaps. Find the minimal value v and some sequence of no more than two swaps that will lead to the such value v. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 2000) — the number of elements in the array a.

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

The third line contains integer m (1 ≤ m ≤ 2000) — the number of elements in the array b.

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

-----Output-----

In the first line print the minimal value v = |s_{a} - s_{b}| that can be got with no more than two swaps.

The second line should contain the number of swaps k (0 ≤ k ≤ 2).

Each of the next k lines should contain two integers x_{p}, y_{p} (1 ≤ x_{p} ≤ n, 1 ≤ y_{p} ≤ m) — the index of the element in the array a and the index of the element in the array b in the p-th swap.

If there are several optimal solutions print any of them. Print the swaps in order the professor did them.

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

Output
1
2
1 1
4 2

Input
5
1 2 3 4 5
1
15

Output
0
0

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

Output
1
1
3 1

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

from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))

sum_a, sum_b = sum(a), sum(b)
delta = sum_b - sum_a
ans = abs(delta)
ans_swap = []

for i in range(n):
    for j in range(m):
        if abs((sum_a - a[i] + b[j]) - (sum_b + a[i] - b[j])) < ans:
            ans = abs((sum_a - a[i] + b[j]) - (sum_b + a[i] - b[j]))
            ans_swap = [(i+1, j+1)]

d = dict()
for i in range(m):
    for j in range(i+1, m):
        d[b[i]+b[j]] = (i+1, j+1)

minf, inf = -10**13, 10**13
val = [minf, minf] + sorted(d.keys()) + [inf, inf]

for i in range(n):
    for j in range(i+1, n):
        ap = a[i] + a[j]
        req = (delta + ap*2) >> 1
        k = bisect_left(val, req)

        for k in range(k-1, k+2):
            if abs(delta + ap*2 - val[k]*2) < ans:
                ans = abs(delta + ap*2 - val[k]*2)
                ans_swap = [(i+1, d[val[k]][0]), (j+1, d[val[k]][1])]

print(ans)
print(len(ans_swap))
for x, y in ans_swap:
    print(x, y)


I found an interesting problem on https://codeforces.com/problemset/problem/621/A:
Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark.

Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.

-----Input-----

The first line of the input contains one integer, n (1 ≤ n ≤ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 10^9, inclusive.

-----Output-----

Print the maximum possible even sum that can be obtained if we use some of the given integers.

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

Output
6
Input
5
999999999 999999999 999999999 999999999 999999999

Output
3999999996

-----Note-----

In the first sample, we can simply take all three integers for a total sum of 6.

In the second sample Wet Shark should take any four out of five integers 999 999 999.

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

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

for x in a:
    if x % 2 == 0:
        evens.append(x)
    else:
        odds.append(x)

ret = sum(evens)

odds.sort()

i = len(odds)-1

while i-1 >= 0:
    ret += odds[i] + odds[i-1]
    i -= 2

print(ret)


I found an interesting problem on https://codeforces.com/problemset/problem/621/B:
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.

Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.

-----Input-----

The first line of the input contains n (1 ≤ n ≤ 200 000) — the number of bishops.

Each of next n lines contains two space separated integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ 1000) — the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.

-----Output-----

Output one integer — the number of pairs of bishops which attack each other.

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

Output
6

Input
3
1 1
2 3
3 5

Output
0

-----Note-----

In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.

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

n = int(input())
a = [True]*1999
a1 = [0]*1999
b = [True]*1999
b1 = [0]*1999
ans = 0
for i in range(n):
    x,y = map(int,input().split())
    d = x - y
    s = x + y
    k = d + 999
    l = s - 2
    if a[k]:
        a[k] = False
        a1[k] += 1
    else:
        #print('!!!')
        ans += a1[k]
        a1[k] += 1
    if b[l]:
        b[l] = False
        b1[l] += 1
    else:
        #print('!!!')
        ans += b1[l]
        b1[l] += 1
#print(a)
#print(a1)
#print(b)
#print(b1)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/621/C:
There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too.

Each shark will grow some number of flowers s_{i}. For i-th shark value s_{i} is random integer equiprobably chosen in range from l_{i} to r_{i}. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product s_{i}·s_{j} is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.

At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.

-----Input-----

The first line of the input contains two space-separated integers n and p (3 ≤ n ≤ 100 000, 2 ≤ p ≤ 10^9) — the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime.

The i-th of the following n lines contains information about i-th shark — two space-separated integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 10^9), the range of flowers shark i can produce. Remember that s_{i} is chosen equiprobably among all integers from l_{i} to r_{i}, inclusive.

-----Output-----

Print a single real number — the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

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

-----Examples-----
Input
3 2
1 2
420 421
420420 420421

Output
4500.0

Input
3 5
1 4
2 3
11 14

Output
0.0

-----Note-----

A prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.

Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the...

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

n,p=list(map(int,input().split()))
z=1
a=[]
b=[]
for i in range(0,n):
    x,y=list(map(int,input().split()))
    a.append(int(y/p)-int((x-1)/p))
    b.append(y-x+1)
ans=0
for i in range (0,n):
    pz=a[(i+1)%n]
    z=b[(i+1)%n]
    py=a[i]
    y=b[i]
    px=a[(i-1+n)%n]
    x=b[(i-1+n)%n]
    ans+=((x*z*py*2000 + px*pz*(y-py)*2000 + px*(y-py)*(z-pz)*1000 + pz*(x-px)*(y-py)*1000))/float(x*y*z)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/621/D:
Wet Shark asked Rat Kwesh to generate three positive real numbers x, y and z, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point.

Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to earn a lot of cheese. He will hand the three numbers x, y and z to Rat Kwesh, and Rat Kwesh will pick one of the these twelve options:  a_1 = x^{y}^{z};  a_2 = x^{z}^{y};  a_3 = (x^{y})^{z};  a_4 = (x^{z})^{y};  a_5 = y^{x}^{z};  a_6 = y^{z}^{x};  a_7 = (y^{x})^{z};  a_8 = (y^{z})^{x};  a_9 = z^{x}^{y};  a_10 = z^{y}^{x};  a_11 = (z^{x})^{y};  a_12 = (z^{y})^{x}.

Let m be the maximum of all the a_{i}, and c be the smallest index (from 1 to 12) such that a_{c} = m. Rat's goal is to find that c, and he asks you to help him. Rat Kwesh wants to see how much cheese he gets, so he you will have to print the expression corresponding to that a_{c}.

-----Input-----

The only line of the input contains three space-separated real numbers x, y and z (0.1 ≤ x, y, z ≤ 200.0). Each of x, y and z is given with exactly one digit after the decimal point.

-----Output-----

Find the maximum value of expression among x^{y}^{z}, x^{z}^{y}, (x^{y})^{z}, (x^{z})^{y}, y^{x}^{z}, y^{z}^{x}, (y^{x})^{z}, (y^{z})^{x}, z^{x}^{y}, z^{y}^{x}, (z^{x})^{y}, (z^{y})^{x} and print the corresponding expression. If there are many maximums, print the one that comes first in the list.

x^{y}^{z} should be outputted as x^y^z (without brackets), and (x^{y})^{z} should be outputted as (x^y)^z (quotes for clarity).

-----Examples-----
Input
1.1 3.4 2.5

Output
z^y^x

Input
2.0 2.0 2.0

Output
x^y^z

Input
1.9 1.8 1.7

Output
(x^y)^z

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

import math

s = ['x^y^z',
     'x^z^y',
     '(x^y)^z',
     '(x^z)^y',
     'y^x^z',
     'y^z^x',
     '(y^x)^z',
     '(y^z)^x',
     'z^x^y',
     'z^y^x',
     '(z^x)^y',
     '(z^y)^x']

x, y, z = map(float, input().split())

ma = float('-inf')
c = -1

if x > 1:
    if ma < z * math.log(y) + math.log(math.log(x)):
        ma = z * math.log(y) + math.log(math.log(x))
        c = 0

    if ma < y * math.log(z) + math.log(math.log(x)):
        ma = y * math.log(z) + math.log(math.log(x))
        c = 1

    if ma < math.log(y) + math.log(z) + math.log(math.log(x)):
        ma = math.log(y) + math.log(z) + math.log(math.log(x))
        c = 2

if y > 1:
    if ma < z * math.log(x) + math.log(math.log(y)):
        ma = z * math.log(x) + math.log(math.log(y))
        c = 4

    if ma < x * math.log(z) + math.log(math.log(y)):
        ma = x * math.log(z) + math.log(math.log(y))
        c = 5

    if ma < math.log(x) + math.log(z) + math.log(math.log(y)):
        ma = math.log(x) + math.log(z) + math.log(math.log(y))
        c = 6

if z > 1:
    if ma < y * math.log(x) + math.log(math.log(z)):
        ma = y * math.log(x) + math.log(math.log(z))
        c = 8

    if ma < x * math.log(y) + math.log(math.log(z)):
        ma = x * math.log(y) + math.log(math.log(z))
        c = 9

    if ma < math.log(x) + math.log(y) + math.log(math.log(z)):
        ma = math.log(x) + math.log(y) + math.log(math.log(z))
        c = 10

# if max(x , y, z) <= 1
if c == -1:
    if ma < x ** (y ** z):
        ma = x ** (y ** z)
        c = 0

    if ma < x ** (z ** y):
        ma = x ** (z ** y)
        c = 1

    if ma < (x ** y) ** z:
        ma = (x ** y) ** z
        c = 2

    if ma < y ** (x ** z):
        ma = y ** (x ** z)
        c = 4

    if ma < y ** (z ** x):
        ma = y ** (z ** x)
        c = 5

    if ma < (y ** x) ** z:
        ma = (y ** x) ** z
        c = 6

    if ma < z ** (x ** y):
        ma = z ** (x ** y)
        c = 8

    if ma < z ** (y ** x):
  ...


I found an interesting problem on https://codeforces.com/problemset/problem/621/E:
There are b blocks of digits. Each one consisting of the same n digits, which are given to you in the input. Wet Shark must choose exactly one digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit 1 from the first block and digit 2 from the second block, he gets the integer 12.

Wet Shark then takes this number modulo x. Please, tell him how many ways he can choose one digit from each block so that he gets exactly k as the final result. As this number may be too large, print it modulo 10^9 + 7.

Note, that the number of ways to choose some digit in the block is equal to the number of it's occurrences. For example, there are 3 ways to choose digit 5 from block 3 5 6 7 8 9 5 1 1 1 1 5.

-----Input-----

The first line of the input contains four space-separated integers, n, b, k and x (2 ≤ n ≤ 50 000, 1 ≤ b ≤ 10^9, 0 ≤ k < x ≤ 100, x ≥ 2) — the number of digits in one block, the number of blocks, interesting remainder modulo x and modulo x itself.

The next line contains n space separated integers a_{i} (1 ≤ a_{i} ≤ 9), that give the digits contained in each block.

-----Output-----

Print the number of ways to pick exactly one digit from each blocks, such that the resulting integer equals k modulo x.

-----Examples-----
Input
12 1 5 10
3 5 6 7 8 9 5 1 1 1 1 5

Output
3

Input
3 2 1 2
6 2 2

Output
0

Input
3 2 1 2
3 1 2

Output
6

-----Note-----

In the second sample possible integers are 22, 26, 62 and 66. None of them gives the remainder 1 modulo 2.

In the third sample integers 11, 13, 21, 23, 31 and 33 have remainder 1 modulo 2. There is exactly one way to obtain each of these integers, so the total answer is 6.

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

R = lambda : list(map(int, input().split()))
n,b,k,x = R()
v = list(R())
mod = 10**9+7

arr_0 = [0]*x
for bd in v:
    arr_0[bd%x]+=1

def cross(arr1,arr2,x,mod):
    arr = [0]*len(arr1)
    for i in range(len(arr1)):
        for j in range(len(arr2)):
            arr[(i+j)%x] += arr1[i]*arr2[j]
    for i in range(len(arr)):
        arr[i] %= mod
    return arr

def move(arr,s,x):
    m = pow(10,s,x)
    res = [0]*x
    for i in range(x):
        res[(i*m)%x]+=arr[i]
    return res

def solve(b,x,arr_0,mod):
    if b==1:
        return arr_0
    if b%2==1:
        sol = solve(b-1,x,arr_0,mod)
        return cross(move(sol,1,x),arr_0,x,mod)
    else:
        sol = solve(b//2,x,arr_0,mod)
        return cross(move(sol,b//2,x),sol,x,mod)

sol = solve(b,x,arr_0,mod)
print(sol[k])


I found an interesting problem on https://codeforces.com/problemset/problem/622/A:
Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not digits. For example number 10 first appears in the sequence in position 55 (the elements are numerated from one).

Find the number on the n-th position of the sequence.

-----Input-----

The only line contains integer n (1 ≤ n ≤ 10^14) — the position of the number to find.

Note that the given number is too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

-----Output-----

Print the element in the n-th position of the sequence (the elements are numerated from one).

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

Output
2

Input
5

Output
2

Input
10

Output
4

Input
55

Output
10

Input
56

Output
1

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

import collections
import math

#n ,m = map(int, input().split())
n = int(input())
x = int((math.sqrt(1 + 8 * n) - 1) / 2)
t = (x + 1) * x // 2
if t == n:
    print(x)
else:
    print(n - t)


I found an interesting problem on https://codeforces.com/problemset/problem/622/B:
You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes.

Note that you should find only the time after a minutes, see the examples to clarify the problem statement.

You can read more about 24-hour format here https://en.wikipedia.org/wiki/24-hour_clock.

-----Input-----

The first line contains the current time in the format hh:mm (0 ≤ hh < 24, 0 ≤ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes).

The second line contains integer a (0 ≤ a ≤ 10^4) — the number of the minutes passed.

-----Output-----

The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed).

See the examples to check the input/output format.

-----Examples-----
Input
23:59
10

Output
00:09

Input
20:20
121

Output
22:21

Input
10:10
0

Output
10:10

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

import datetime
import time

t = input()
M = input()
h, m = list(map(int, t.split(':')))

H,M = divmod(int(M), 60)

a = datetime.datetime(100, 1, 1, h, m, 00)
b = a + datetime.timedelta(0,0,0,0,M,H,0)
print(b.strftime('%H:%M'))


I found an interesting problem on https://codeforces.com/problemset/problem/622/C:
You are given array a with n integers and m queries. The i-th query is given with three integers l_{i}, r_{i}, x_{i}.

For the i-th query find any position p_{i} (l_{i} ≤ p_{i} ≤ r_{i}) so that a_{p}_{i} ≠ x_{i}.

-----Input-----

The first line contains two integers n, m (1 ≤ n, m ≤ 2·10^5) — the number of elements in a and the number of queries.

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

Each of the next m lines contains three integers l_{i}, r_{i}, x_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n, 1 ≤ x_{i} ≤ 10^6) — the parameters of the i-th query.

-----Output-----

Print m lines. On the i-th line print integer p_{i} — the position of any number not equal to x_{i} in segment [l_{i}, r_{i}] or the value  - 1 if there is no such number.

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

Output
2
6
-1
4

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

# -*- coding: utf-8 -*-
"""
Created on Tue May 17 15:26:55 2016

@author: Alex
"""
from sys import stdin

n,m = [int(i) for i in input().split()]
l = [int(i) for i in stdin.readline().split()]
prev = [-1 for i in range(n)]
re = []
for i in range(n-1):
    if l[i] != l[i+1]:
        prev[i+1] = i
    else:
        prev[i+1] = prev[i]
for _ in range(m):
    le,ri,xi = [int(i) for i in stdin.readline().split()]
    i = ri-1
    if l[i]!=xi:
        re.append(str(ri))
    else:
        if prev[i]<le-1:
            re.append('-1')
        else:
            re.append(str(prev[i]+1))
print('\n'.join(re))


I found an interesting problem on https://codeforces.com/problemset/problem/622/D:
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.

Let number i be in positions x_{i}, y_{i} (x_{i} < y_{i}) in the permuted array a. Let's define the value d_{i} = y_{i} - x_{i} — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum $s = \sum_{i = 1}^{n}(n - i) \cdot|d_{i} + i - n$.

-----Input-----

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

-----Output-----

Print 2n integers — the permuted array a that minimizes the value of the sum s.

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

Output
1 1 2 2

Input
1

Output
1 1

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

import collections
import math

n  = int(input())
arr = [0] * (2 * n)
l, r = 0, 0
for i in range(1, n):
    if i % 2 == 1:
        arr[l] = arr[l + n - i] = i
        l += 1
    else:
        arr[n + r] = arr[n + r + n - i] = i
        r += 1
for i in range(2):
    while arr[l]:
        l += 1
    arr[l] = n
print(' '.join(str(x) for x in arr))


I found an interesting problem on https://codeforces.com/problemset/problem/623/A:
One day student Vasya was sitting on a lecture and mentioned a string s_1s_2... s_{n}, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:   G has exactly n vertices, numbered from 1 to n.  For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters s_{i} and s_{j} are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.

Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.

-----Input-----

The first line of the input contains two integers n and m $(1 \leq n \leq 500,0 \leq m \leq \frac{n(n - 1)}{2})$ — the number of vertices and edges in the graph found by Petya, respectively.

Each of the next m lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.

-----Output-----

In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.

If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.

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

Output
Yes
aa

Input
4 3
1 2
1 3
1...

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

# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 1/17/20

"""

import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, M, edges):
    if M == N*(N-1)//2:
        return 'a' * N

    g = collections.defaultdict(list)
    for u, v in edges:
        g[u].append(v)
        g[v].append(u)

    s = ['', 'a', 'b', 'c']
    for u in range(1, N+1):
        mark = [3 for _ in range(N + 1)]
        mark[0] = 0
        mark[u] = 1
        for v in g[u]:
            mark[v] = 1

        for u in range(1, N+1):
            if mark[u] == 3:
                for v in g[u]:
                    if mark[v] == 1:
                        mark[v] = 2

        a, b, c = mark.count(1), mark.count(2), mark.count(3)
        if a*(a-1)//2 + b*(b-1)//2 + c*(c-1)//2 + a*b + b*c != M:
            continue

        if any([abs(mark[u] - mark[v]) > 1 for u, v in edges]):
            continue

        return ''.join([s[mark[v]] for v in range(1, N+1)])

    return None

N, M = map(int, input().split())
edges = []
for i in range(M):
    u, v = map(int, input().split())
    edges.append((u, v))

s = solve(N, M, edges)
if s:
    print('Yes')
    print(s)
else:
    print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/624/A:
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other with speed v_1 and v_2, respectively. Luke has width d and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive.

-----Input-----

The first line of the input contains four integers d, L, v_1, v_2 (1 ≤ d, L, v_1, v_2 ≤ 10 000, d < L) — Luke's width, the initial position of the second press and the speed of the first and second presses, respectively.

-----Output-----

Print a single real value — the maximum period of time Luke can stay alive for. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

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

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

Output
1.00000000000000000000

Input
1 9 1 2

Output
2.66666666666666650000

-----Note-----

In the first sample Luke should stay exactly in the middle of the segment, that is at coordinates [2;4], as the presses move with the same speed.

In the second sample he needs to occupy the position $[ 2 \frac{2}{3} ; 3 \frac{2}{3} ]$. In this case both presses move to his edges at the same time.

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

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 missingdays <missingdays@missingdays>
#
# Distributed under terms of the MIT license.

"""

"""

def read_list():
    return [int(i) for i in input().split()]
def new_list(n):
    return [0 for i in range(n)]
def new_matrix(n, m=0):
    return [[0 for i in range(m)] for i in range(n)]

d, l, v1, v2 = read_list()

t = l / (v1+v2)

t -= d / (v1+v2)

print(t)


I found an interesting problem on https://codeforces.com/problemset/problem/624/B:
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:   the i-th letter occurs in the string no more than a_{i} times;  the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.

-----Input-----

The first line of the input contains a single integer n (2  ≤  n  ≤  26) — the number of letters in the alphabet.

The next line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.

-----Output-----

Print a single integer — the maximum length of the string that meets all the requirements.

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

Output
11

Input
3
1 1 2

Output
3

-----Note-----

For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".

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

n = int(input())
a = list(map(int, input().split()))
a.sort()
for i in range(n - 2, -1, -1):
    a[i] = max(min(a[i], a[i + 1] - 1), 0)
print(sum(a))


I found an interesting problem on https://codeforces.com/problemset/problem/625/A:
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated.

Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plastic liter bottle, that costs a rubles, or in glass liter bottle, that costs b rubles. Also, you may return empty glass bottle and get c (c < b) rubles back, but you cannot return plastic bottles.

Kolya has n rubles and he is really hungry, so he wants to drink as much kefir as possible. There were no plastic bottles in his 1984, so Kolya doesn't know how to act optimally and asks for your help.

-----Input-----

First line of the input contains a single integer n (1 ≤ n ≤ 10^18) — the number of rubles Kolya has at the beginning.

Then follow three lines containing integers a, b and c (1 ≤ a ≤ 10^18, 1 ≤ c < b ≤ 10^18) — the cost of one plastic liter bottle, the cost of one glass liter bottle and the money one can get back by returning an empty glass bottle, respectively.

-----Output-----

Print the only integer — maximum number of liters of kefir, that Kolya can drink.

-----Examples-----
Input
10
11
9
8

Output
2

Input
10
5
6
1

Output
2

-----Note-----

In the first sample, Kolya can buy one glass bottle, then return it and buy one more glass bottle. Thus he will drink 2 liters of kefir.

In the second sample, Kolya can buy two plastic bottle and get two liters of kefir, or he can buy one liter glass bottle, then return it and buy one plastic bottle. In both cases he will drink two liters of kefir.

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

n=int(input())
a=int(input())
b=int(input())
c=int(input())
r=n//a
if n > c:
    r=max(r,(r-b+c)//a+1,(n-c)//(b-c)+((n-c)%(b-c)+c)//a)
print(r)


I found an interesting problem on https://codeforces.com/problemset/problem/625/B:
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.

This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.

Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.

Substring is a continuous subsequence of a string.

-----Input-----

The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.

-----Output-----

Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.

-----Examples-----
Input
intellect
tell

Output
1
Input
google
apple

Output
0
Input
sirisiri
sir

Output
2

-----Note-----

In the first sample AI's name may be replaced with "int#llect".

In the second sample Gogol can just keep things as they are.

In the third sample one of the new possible names of AI may be "s#ris#ri".

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

main = input()
sub = input()

ans = main.count(sub)
print (ans)


I found an interesting problem on https://codeforces.com/problemset/problem/625/C:
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.

Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:  every integer from 1 to n^2 appears in the table exactly once;  in each row numbers are situated in increasing order;  the sum of numbers in the k-th column is maximum possible.

Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.

-----Input-----

The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.

-----Output-----

First print the sum of the integers in the k-th column of the required table.

Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.

If there are multiple suitable table, you are allowed to print any.

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

Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Input
5 3

Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13

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

N, k = map(int, input().split())
a = [ [0] * (N + 1) for i in range(N + 1) ]
x = N * (k - 1) + 1
S = 0
for i in range(1, N + 1):
    S += x
    a[i][k] = x
    x += 1
    for j in range(k + 1, N + 1):
        a[i][j] = x
        x += 1
x = 1
for i in range(1, N + 1):
    for j in range(1, k):
        a[i][j] = x
        x += 1
print(S)
for i in range(1, N + 1):
    print(*a[i][1:])


I found an interesting problem on https://codeforces.com/problemset/problem/626/A:
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.

-----Input-----

The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.

The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.

-----Output-----

Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.

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

Output
2

Input
4
DLUU

Output
0

Input
7
RLRLRLR

Output
12

-----Note-----

In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.

Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.

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

n = int(input())
s = input()

ret = 0
for i in range(n):
    for j in range(i+1, n+1):
        count = {}
        for k in range(i, j):
            count[s[k]] = count.get(s[k], 0) + 1
        eq = len(count) > 1
        if "U" in count or "D" in count:
            if "D" not in count or "U" not in count:
                eq = False
            else:
                eq &= count["U"] == count["D"]
        if "L" in count or "R" in count:
            if "R" not in count or "L" not in count:
                eq = False
            else:
                eq &= count["L"] == count["R"]
        ret += eq
print(ret)


I found an interesting problem on https://codeforces.com/problemset/problem/626/B:
Catherine has a deck of n cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions:   take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color;  take any two (not necessarily adjacent) cards with the same color and exchange them for a new card with that color.

She repeats this process until there is only one card left. What are the possible colors for the final card?

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 200) — the total number of cards.

The next line contains a string s of length n — the colors of the cards. s contains only the characters 'B', 'G', and 'R', representing blue, green, and red, respectively.

-----Output-----

Print a single string of up to three characters — the possible colors of the final card (using the same symbols as the input) in alphabetical order.

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

Output
G

Input
3
GRG

Output
BR

Input
5
BBBBB

Output
B

-----Note-----

In the first sample, Catherine has one red card and one blue card, which she must exchange for a green card.

In the second sample, Catherine has two green cards and one red card. She has two options: she can exchange the two green cards for a green card, then exchange the new green card and the red card for a blue card. Alternatively, she can exchange a green and a red card for a blue card, then exchange the blue card and remaining green card for a red card.

In the third sample, Catherine only has blue cards, so she can only exchange them for more blue cards.

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

# You lost the game.
n = int(input())
ch = str(input())
r = ""
R = ch.count("R")
B = ch.count("B")
G = ch.count("G")
if R and B and G:
    print("BGR")
elif (R >= 2 and B >= 2) or (G >= 2 and R >= 2) or (G >= 2 and B >= 2):
    print("BGR")
elif R >= 2 and (B == 1 or G == 1):
    print("BG")
elif B >= 2 and (R == 1 or G == 1):
    print("GR")
elif G >= 2 and (B == 1 or R == 1):
    print("BR")
elif B and G:
    print("R")
elif R and G:
    print("B")
elif B and R:
    print("G")
elif B:
    print("B")
elif G:
    print("G")
else:
    print("R")


I found an interesting problem on https://codeforces.com/problemset/problem/626/C:
Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. n of the students use pieces made of two blocks and m of the students use pieces made of three blocks.

The students don’t want to use too many blocks, but they also want to be unique, so no two students’ towers may contain the same number of blocks. Find the minimum height necessary for the tallest of the students' towers.

-----Input-----

The first line of the input contains two space-separated integers n and m (0 ≤ n, m ≤ 1 000 000, n + m > 0) — the number of students using two-block pieces and the number of students using three-block pieces, respectively.

-----Output-----

Print a single integer, denoting the minimum possible height of the tallest tower.

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

Output
9

Input
3 2

Output
8

Input
5 0

Output
10

-----Note-----

In the first case, the student using two-block pieces can make a tower of height 4, and the students using three-block pieces can make towers of height 3, 6, and 9 blocks. The tallest tower has a height of 9 blocks.

In the second case, the students can make towers of heights 2, 4, and 8 with two-block pieces and towers of heights 3 and 6 with three-block pieces, for a maximum height of 8 blocks.

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

t2, t3 = list(map(int,input().split(' ')))

left = 2*(t2)-10
right = 3*(t2+t3)+10
while right-left != 1:
    guess = int((left+right)/2)
    work2 = int(guess/2)-int(guess/6)
    work3 = int(guess/3)-int(guess/6)
    work6 = int(guess/6)
    if max(0,t2-work2)+max(0,t3-work3) <= work6:
        right = guess
    else:
        left = guess
print(right)


I found an interesting problem on https://codeforces.com/problemset/problem/626/D:
Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds.

Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?

-----Input-----

The first line of input contains a single integer n (2 ≤ n ≤ 2000) — the number of balls in the jar.

The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 5000) — the number written on the ith ball. It is guaranteed that no two balls have the same number.

-----Output-----

Print a single real value — the probability that Jerry has a higher total, given that Andrew wins the first two rounds and Jerry wins the third. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

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

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

Output
0.0000000000

Input
3
1 2 10

Output
0.0740740741

-----Note-----

In the first case, there are only two balls. In the first two rounds, Andrew must have drawn the 2 and Jerry must have drawn the 1, and vice versa in the final round. Thus, Andrew's sum is 5 and Jerry's sum is 4, so Jerry never has a higher total.

In the second case, each game could've had three outcomes — 10 - 2, 10 - 1, or 2 - 1. Jerry has a higher total if and only if Andrew won 2 - 1 in...

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

MAX_N = 5001

a = [0] * MAX_N;
raz = [0] * (MAX_N + 10);
s = [0] * (MAX_N + 10);

n = int(input())

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

for i in range(n):
    for j in range(n):
        if a[i] - a[j] > 0:
            raz[a[i] - a[j]] += 1

for i in range(1, MAX_N + 1):
     s[i] = s[i - 1] + raz[i]

ans = 0;

for i in range(1, MAX_N):
    if raz[i] == 0:
        continue
    for j in range(1, MAX_N):
        if i + j > MAX_N:
            break
        if raz[j] == 0:
            continue
        ans += raz[i] * raz[j] * (s[MAX_N] - s[i + j])

ans = ans * 1.0
ans /= s[MAX_N]
ans /= s[MAX_N]
ans /= s[MAX_N]

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/627/A:
Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)?

-----Input-----

The first line of the input contains two integers s and x (2 ≤ s ≤ 10^12, 0 ≤ x ≤ 10^12), the sum and bitwise xor of the pair of positive integers, respectively.

-----Output-----

Print a single integer, the number of solutions to the given conditions. If no solutions exist, print 0.

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

Output
4

Input
3 3

Output
2

Input
5 2

Output
0

-----Note-----

In the first sample, we have the following solutions: (2, 7), (3, 6), (6, 3), (7, 2).

In the second sample, the only solutions are (1, 2) and (2, 1).

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

s, x = list(map(int, input().split()))
print(0 if s < x or (s - x) & (2 * x + 1) else 2 ** bin(x).count('1') - 2 * (s == x))


I found an interesting problem on https://codeforces.com/problemset/problem/627/B:
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.

Initially, no orders are pending. The factory receives updates of the form d_{i}, a_{i}, indicating that a_{i} new orders have been placed for the d_{i}-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.

As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day p_{i}. Help the owner answer his questions.

-----Input-----

The first line contains five integers n, k, a, b, and q (1 ≤ k ≤ n ≤ 200 000, 1 ≤ b < a ≤ 10 000, 1 ≤ q ≤ 200 000) — the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively.

The next q lines contain the descriptions of the queries. Each query is of one of the following two forms:   1 d_{i} a_{i} (1 ≤ d_{i} ≤ n, 1 ≤ a_{i} ≤ 10 000), representing an update of a_{i} orders on day d_{i}, or  2 p_{i} (1 ≤ p_{i} ≤ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day p_{i}?

It's guaranteed that the input will contain at least one query of the second type.

-----Output-----

For each query of the second type, print a line containing a single integer — the maximum number of orders that the factory can fill over all n days.

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

Output
3
6
4

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

Output
7
1

-----Note-----

Consider the first sample.

We...

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

import sys
from math import *

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

def mint():
	return int(minp())

def mints():
	return list(map(int, minp().split()))

def add(a,x,v):
	while x<len(a):
		a[x] += v
		x |= x+1
def get(a,x):
	r = 0
	while x>=0:
		r += a[x]
		x = (x&(x+1))-1
	return r

n, k, a, b, q = mints()
h1 = [0]*n
h2 = [0]*n
z = [0]*n
for i in range(q):
	t = tuple(mints())
	if t[0] == 1:
		p = z[t[1]-1]
		pp = p + t[2]
		add(h1, t[1]-1, min(a,pp)-min(a,p))
		add(h2, t[1]-1, min(b,pp)-min(b,p))
		z[t[1]-1] = pp
	else:
		print(get(h2,t[1]-2)+get(h1,n-1)-get(h1,t[1]+k-2))


I found an interesting problem on https://codeforces.com/problemset/problem/627/C:
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.

Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point x_{i} on the number line and sells an unlimited amount of fuel at a price of p_{i} dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.

-----Input-----

The first line of input contains three space separated integers d, n, and m (1 ≤ n ≤ d ≤ 10^9, 1 ≤ m ≤ 200 000) — the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively.

Each of the next m lines contains two integers x_{i}, p_{i} (1 ≤ x_{i} ≤ d - 1, 1 ≤ p_{i} ≤ 10^6) — the position and cost of gas at the i-th gas station. It is guaranteed that the positions of the gas stations are distinct.

-----Output-----

Print a single integer — the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.

-----Examples-----
Input
10 4 4
3 5
5 8
6 3
8 4

Output
22

Input
16 5 2
8 2
5 1

Output
-1

-----Note-----

In the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2·5 + 4·3 = 22 dollars.

In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.

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

destination, max_gas_tank_volume, gas_prices_number = list(map(int, input().split()))
start_point = 0
gas_prices = {start_point:0}
for i in range(gas_prices_number):
    coordinate, price = list(map(int, input().split()))
    gas_prices[coordinate] = price
points = sorted(list(gas_prices.keys()), reverse = True)
current_point = start_point
count = 0
gas_tank_volume = max_gas_tank_volume
reachable_points = []
while current_point != destination:
    farthest_reachable_point = current_point + max_gas_tank_volume
    while points and points[-1] <= farthest_reachable_point:
        reachable_points.append(points.pop())
    if reachable_points:
        cheaper_reachable_points = sorted([point for point in reachable_points if gas_prices[point] < gas_prices[current_point]])
        next_point = cheaper_reachable_points[0] if cheaper_reachable_points else min(reachable_points, key = lambda point: gas_prices[point])
        if farthest_reachable_point >= destination and (current_point == start_point or gas_prices[next_point] >= gas_prices[current_point]):
            next_point = destination
        else:
            reachable_points = [point for point in reachable_points if point > next_point]
    else:
        if farthest_reachable_point >= destination:
            next_point = destination
        else:
            count = -1
            break
    distantion = next_point - current_point
    if next_point != destination and gas_prices[current_point] <= gas_prices[next_point]:
        required_gas_volume = max_gas_tank_volume
    else:
        required_gas_volume = distantion
    if required_gas_volume > gas_tank_volume:
        count += (required_gas_volume - gas_tank_volume)*gas_prices[current_point]
        gas_tank_volume = required_gas_volume
    current_point = next_point
    gas_tank_volume -= distantion
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/627/D:
For his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent a_{i} minutes building the i-th ball in the tree.

Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to search his whole tree to determine this; Jacob knows that she will examine the first k nodes in a DFS-order traversal of the tree. She will then assign Jacob a grade equal to the minimum a_{i} she finds among those k nodes.

Though Jacob does not have enough time to rebuild his model, he can choose the root node that his teacher starts from. Furthermore, he can rearrange the list of neighbors of each node in any order he likes. Help Jacob find the best grade he can get on this assignment.

A DFS-order traversal is an ordering of the nodes of a rooted tree, built by a recursive DFS-procedure initially called on the root of the tree. When called on a given node v, the procedure does the following:   Print v.  Traverse the list of neighbors of the node v in order and iteratively call DFS-procedure on each one. Do not call DFS-procedure on node u if you came to node v directly from u.

-----Input-----

The first line of the input contains two positive integers, n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ n) — the number of balls in Jacob's tree and the number of balls the teacher will inspect.

The second line contains n integers, a_{i} (1 ≤ a_{i} ≤ 1 000 000), the time Jacob used to build the i-th ball.

Each of the next n - 1 lines contains two integers u_{i}, v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) representing a connection in Jacob's tree between balls u_{i} and v_{i}.

-----Output-----

Print a single integer — the maximum grade Jacob can get by picking the right root of the tree and rearranging the list of neighbors.

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

Output
3

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

Output
1

-----Note-----

In the first sample, Jacob can root the tree at node...

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

import sys
input = sys.stdin.readline
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
g = [[] for _ in range(n)]
for i in range(n - 1):
	u, v = map(int, input().split())
	g[u-1].append(v-1)
	g[v-1].append(u-1)

stack = [0]
done = [False] * n
par = [0] * n
order = []
while len(stack) > 0:
	x = stack.pop()
	done[x] = True
	order.append(x)
	for i in g[x]:
		if done[i] == False:
			par[i] = x
			stack.append(i)
order = order[::-1]
sub = [0] * n
for i in order:
	sub[i] = 1
	for j in g[i]:
		if par[j] == i:
			sub[i] += sub[j]

def good(guess):
	cnt = [0] * n
	for i in order:
		if a[i] < guess:
			continue
		cnt[i] = 1
		opt = 0
		for j in g[i]:
			if par[j] == i:
				if cnt[j] == sub[j]:
					cnt[i] += cnt[j]
				else:
					opt = max(opt, cnt[j])
		cnt[i] += opt
	if cnt[0] >= k:
		return True
	up = [0] * n
	for i in order[::-1]:
		if a[i] < guess:
			continue
		opt, secondOpt = 0, 0
		total = 1
		for j in g[i]:
			val, size = 0, 0
			if par[j] == i:
				val = cnt[j]
				size = sub[j]
			else:
				val = up[i]
				size = n - sub[i]
			if val == size:
				total += val
			else:
				if opt < val:
					opt, secondOpt = val, opt
				elif secondOpt < val:
					secondOpt = val

		for j in g[i]:
			if par[j] == i:
				up[j] = total
				add = opt
				if sub[j] == cnt[j]:
					up[j] -= cnt[j]
				elif cnt[j] == opt:
					add = secondOpt
				up[j] += add
	for i in range(n):
		if a[i] < guess:
			continue
		total, opt = 1, 0
		for j in g[i]:
			val, size = 0, 0
			if par[j] == i:
				val = cnt[j]
				size = sub[j]
			else:
				val = up[i]
				size = n - sub[i]
			if val == size:
				total += val
			else:
				opt = max(opt, val)
		if total + opt >= k:
			return True
	return False

l, r = 0, max(a)
while l < r:
	mid = (l + r + 1) // 2
	if good(mid):
		l = mid
	else:
		r = mid - 1
print(l)


I found an interesting problem on https://codeforces.com/problemset/problem/628/A:
A tennis tournament with n participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.

The tournament takes place in the following way (below, m is the number of the participants of the current round):  let k be the maximal power of the number 2 such that k ≤ m,  k participants compete in the current round and a half of them passes to the next round, the other m - k participants pass to the next round directly,  when only one participant remains, the tournament finishes.

Each match requires b bottles of water for each participant and one bottle for the judge. Besides p towels are given to each participant for the whole tournament.

Find the number of bottles and towels needed for the tournament.

Note that it's a tennis tournament so in each match two participants compete (one of them will win and the other will lose).

-----Input-----

The only line contains three integers n, b, p (1 ≤ n, b, p ≤ 500) — the number of participants and the parameters described in the problem statement.

-----Output-----

Print two integers x and y — the number of bottles and towels need for the tournament.

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

Output
20 15

Input
8 2 4

Output
35 32

-----Note-----

In the first example will be three rounds:  in the first round will be two matches and for each match 5 bottles of water are needed (two for each of the participants and one for the judge),  in the second round will be only one match, so we need another 5 bottles of water,  in the third round will also be only one match, so we need another 5 bottles of water.

So in total we need 20 bottles of water.

In the second example no participant will move on to some round directly.

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

#!/usr/bin/env python
n, b, p = list(map(int, input().split()))
b_sum = 0
p_sum = p * n
import math
while n > 1:
    b_sum += (2 * b + 1) * int(math.log2(n))
    n -= int(math.log2(n))
print(b_sum, p_sum)


I found an interesting problem on https://codeforces.com/problemset/problem/628/B:
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.

You are given a string s consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.

A substring of a string is a nonempty sequence of consecutive characters.

For example if string s is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.

As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

-----Input-----

The only line contains string s (1 ≤ |s| ≤ 3·10^5). The string s contains only digits from 0 to 9.

-----Output-----

Print integer a — the number of substrings of the string s that are divisible by 4.

Note that the answer can be huge, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

-----Examples-----
Input
124

Output
4

Input
04

Output
3

Input
5810438174

Output
9

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

3

s = input()
# s = '124'
n = len(s)

ans = 0

for i in reversed(list(range(1, n))):
	if int(s[i])%2 == 0:
		if int(s[i-1:i+1])%4 == 0:
			ans += i
		if int(s[i])%4 == 0:
			ans += 1

if int(s[0])%4 == 0: ans += 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/628/C:
Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only.

The distance between two letters is defined as the difference between their positions in the alphabet. For example, $\operatorname{dist}(c, e) = \operatorname{dist}(e, c) = 2$, and $\operatorname{dist}(a, z) = \operatorname{dist}(z, a) = 25$.

Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, $\operatorname{dist}(a f, d b) = \operatorname{dist}(a, d) + \operatorname{dist}(f, b) = 3 + 4 = 7$, and $\text{dist(bear, roar)} = 16 + 10 + 0 + 0 = 26$.

Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that $\operatorname{dist}(s, s^{\prime}) = k$. Find any s' satisfying the given conditions, or print "-1" if it's impossible to do so.

As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

-----Input-----

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

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

-----Output-----

If there is no string satisfying the given conditions then print "-1" (without the quotes).

Otherwise, print any nice string s' that $\operatorname{dist}(s, s^{\prime}) = k$.

-----Examples-----
Input
4 26
bear

Output
roar
Input
2 7
af

Output
db

Input
3 1000
hey

Output
-1

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

def check(s, k):
    ans = 0
    for i in range(len(s)):
        ans += abs(ord(s[i]) - ord(k[i]))
    return ans

n, k = list(map(int, input().split()))
s = input()
cnt = 0
for i in s:
    cnt += max(ord('z') - ord(i), ord(i) - ord('a'))
if k > cnt:
    print(-1)
    return
else:
    ans = ''
    cr = 0
    while k != 0:
        ps1 = ord(s[cr]) - ord('a')
        ps2 = ord('z') - ord(s[cr])
        if ps1 > k:
            ans += chr(ord(s[cr]) - k)
            k = 0
        elif ps2 > k:
            ans += chr(ord(s[cr]) + k)
            k = 0
        else:
            if ps2 >= ps1:
                ans += 'z'
                k -= ps2
            else:
                ans += 'a'
                k -= ps1
        cr += 1
ans += s[len(ans):]
print(ans)
#print(check(ans, s))


I found an interesting problem on https://codeforces.com/problemset/problem/628/D:
Consider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else.

For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic.

Find the number of d-magic numbers in the segment [a, b] that are multiple of m. Because the answer can be very huge you should only find its value modulo 10^9 + 7 (so you should find the remainder after dividing by 10^9 + 7).

-----Input-----

The first line contains two integers m, d (1 ≤ m ≤ 2000, 0 ≤ d ≤ 9) — the parameters from the problem statement.

The second line contains positive integer a in decimal presentation (without leading zeroes).

The third line contains positive integer b in decimal presentation (without leading zeroes).

It is guaranteed that a ≤ b, the number of digits in a and b are the same and don't exceed 2000.

-----Output-----

Print the only integer a — the remainder after dividing by 10^9 + 7 of the number of d-magic numbers in segment [a, b] that are multiple of m.

-----Examples-----
Input
2 6
10
99

Output
8

Input
2 0
1
9

Output
4

Input
19 7
1000
9999

Output
6

-----Note-----

The numbers from the answer of the first example are 16, 26, 36, 46, 56, 76, 86 and 96.

The numbers from the answer of the second example are 2, 4, 6 and 8.

The numbers from the answer of the third example are 1767, 2717, 5757, 6707, 8797 and 9747.

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

#!/usr/bin/env python3

def addmod(left, right, modulo=1000000007):
    res = left + right
    if res >= modulo:
        res -= modulo
    return res

def counter(a, m, d):
    res = [0, ] * (2*m)
    res[0] = 1
    shift = 1
    for pos in range(len(a), 0, -1):
        ptype = pos & 1
        cur = int(a[pos-1])
        tres = [0, ] * (2*m)
        for i in range(10):
            if ptype==1 and i == d:
                continue
            if ptype==0 and i != d:
                continue
            k = (i * shift) % m
            for j in range(m):
                k2 = k*2
                j2 = j*2
                if i < cur:
                    tres[k2+0] = addmod(tres[k2+0], addmod(res[j2+0], res[j2+1]))
                elif i == cur:
                    tres[k2+0] = addmod(tres[k2+0], res[j2+0])
                    tres[k2+1] = addmod(tres[k2+1], res[j2+1])
                else:
                    tres[k2+1] = addmod(tres[k2+1], addmod(res[j2+0], res[j2+1]))
                k = k+1 if k+1<m else 0
        res = tres
        shift = (shift * 10) % m
    return res[0]

def solver(ifs):
    m, d = list(map(int, ifs.readline().split()))
    a = ifs.readline().strip()
    b = ifs.readline().strip()
    res = counter(b, m, d)
    if a != '0':
        a = str(int(a) - 1)
        if len(a) < len(b):
            a = '0' + a
        modulo = 1000000007
        res = addmod(res, modulo - counter(a, m, d))
    print(res)

def main():
    import sys
    if sys.version_info.major == 3:
        from io import StringIO as StreamIO
    else:
         from io import BytesIO as StreamIO

    with StreamIO(sys.stdin.read()) as ifs, StreamIO() as ofs:
        _stdout = sys.stdout
        sys.stdout = ofs
        solver(ifs)
        sys.stdout = _stdout
        sys.stdout.write(ofs.getvalue())
    return 0

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/629/A:
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!

The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?

Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.

-----Input-----

In the first line of the input, you are given a single integer n (1 ≤ n ≤ 100) — the length of the side of the cake.

Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.

-----Output-----

Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.

-----Examples-----
Input
3
.CC
C..
C.C

Output
4

Input
4
CC..
C..C
.CC.
.CC.

Output
9

-----Note-----

If we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are:   (1, 2) and (1, 3)  (3, 1) and (3, 3)  Pieces that share the same column are:   (2, 1) and (3, 1)  (1, 3) and (3, 3)

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

n = int(input())
a = [0]*n
for i in range(n):
    a[i] = input().strip()
ans = 0
for i in range(n):
    s = 0
    for j in range(n):
        if a[i][j]=='C':
            s+=1
        # print(a[i][j])
    ans += s*(s-1)//2

for i in range(n):
    s = 0
    for j in range(n):
        if a[j][i]=='C':
            s+=1
    ans += s*(s-1)//2
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/629/B:
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from a_{i} to b_{i}. Of course, Famil Door wants to have as many friends celebrating together with him as possible.

Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.

Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.

Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers a_{i} and b_{i} (1 ≤ a_{i} ≤ b_{i} ≤ 366), providing that the i-th friend can come to the party from day a_{i} to day b_{i} inclusive.

-----Output-----

Print the maximum number of people that may come to Famil Door's party.

-----Examples-----
Input
4
M 151 307
F 343 352
F 117 145
M 24 128

Output
2

Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200

Output
4

-----Note-----

In the first sample, friends 3 and 4 can come on any day in range [117, 128].

In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.

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

n = int(input())
d = 367
F = [0 for i in range(d)]
M = [0 for i in range(d)]
for i in range(n):
    sex, l, r = input().split()
    l, r = int(l), int(r)
    if sex == 'F':
        for j in range(l, r+1): F[j] += 1
    else:
        for j in range(l, r+1): M[j] += 1
print(2*max(min(F[i], M[i]) for i in range(d)))


I found an interesting problem on https://codeforces.com/problemset/problem/629/C:
As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings!

The sequence of round brackets is called valid if and only if:   the total number of opening brackets is equal to the total number of closing brackets;  for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets.

Gabi bought a string s of length m (m ≤ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s.

Now he wonders, how many pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 10^9 + 7.

-----Input-----

First line contains n and m (1 ≤ m ≤ n ≤ 100 000, n - m ≤ 2000) — the desired length of the string and the length of the string bought by Gabi, respectively.

The second line contains string s of length m consisting of characters '(' and ')' only.

-----Output-----

Print the number of pairs of string p and q such that p + s + q is a valid sequence of round brackets modulo 10^9 + 7.

-----Examples-----
Input
4 1
(

Output
4

Input
4 4
(())

Output
1

Input
4 3
(((

Output
0

-----Note-----

In the first sample there are four different valid pairs:   p = "(", q = "))"  p = "()", q = ")"  p = "", q = "())"  p = "", q = ")()"

In the second sample the only way to obtain a desired string is choose empty p and q.

In the third sample there is no way to get a valid sequence of brackets.

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

n, m = list(map(int, input().split()))
s = input()
mod = 10 ** 9 + 7
c, b, ans, d, k = 0, 0, 0, [[1]], n - m
for i in s:
    c += (i == '(') * 2 - 1
    b = min(c, b)
for i in range(n - m):
    nd = d[-1][1:] + [0] * 2
    for j in range(1, i + 2):
        nd[j] = (nd[j] + d[-1][j - 1]) % mod
    d.append(nd)
for i in range(k + 1):
    for j in range(-b, min(k - i - c, i) + 1):
        ans = (ans + d[i][j] * d[k - i][j + c]) % mod
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/629/D:
As you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake.

Simple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has n simple cakes and he is going to make a special cake placing some cylinders on each other.

However, there are some additional culinary restrictions. The cakes are numbered in such a way that the cake number i can be placed only on the table or on some cake number j where j < i. Moreover, in order to impress friends Babaei will put the cake i on top of the cake j only if the volume of the cake i is strictly greater than the volume of the cake j.

Babaei wants to prepare a birthday cake that has a maximum possible total volume. Help him find this value.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of simple cakes Babaei has.

Each of the following n lines contains two integers r_{i} and h_{i} (1 ≤ r_{i}, h_{i} ≤ 10 000), giving the radius and height of the i-th cake.

-----Output-----

Print the maximum volume of the cake that Babaei can make. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

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

-----Examples-----
Input
2
100 30
40 10

Output
942477.796077000

Input
4
1 1
9 7
1 4
10 7

Output
3983.539484752

-----Note-----

In first sample, the optimal way is to choose the cake number 1.

In second sample, the way to get the maximum volume is to use cakes with indices 1, 2 and 4.

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

from sys import *
t = list(map(int, stdin.read().split()))
p = [t[i + 1] * t[i] ** 2 for i in range(1, len(t), 2)]
k = {v: j for j, v in enumerate(sorted(set(p)))}
d = [0] * (len(k) + 1)
for v in p:
    j = k[v]
    i = j + 1
    q = 0
    while j > 0:
        q = max(d[j], q)
        j -= j & -j
    q += v
    while i < len(d):
        d[i] = max(d[i], q)
        i += i & -i
print(max(d) * 3.14159265)


I found an interesting problem on https://codeforces.com/problemset/problem/630/A:
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using a calculator, but we need people who are able to think, not just follow the instructions."

Could you pass the interview in the machine vision company in IT City?

-----Input-----

The only line of the input contains a single integer n (2 ≤ n ≤ 2·10^18) — the power in which you need to raise number 5.

-----Output-----

Output the last two digits of 5^{n} without spaces between them.

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

Output
25

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

import re, sys, string, operator, functools, fractions, collections
sys.setrecursionlimit(10**7)
dX= [-1, 1, 0, 0,-1, 1,-1, 1]
dY= [ 0, 0,-1, 1, 1,-1,-1, 1]
RI=lambda x=' ': list(map(int,input().split(x)))
RS=lambda x=' ': input().rstrip().split(x)
mod=int(1e9+7)
eps=1e-6
#################################################
print(25)