I found an interesting problem on https://codeforces.com/problemset/problem/630/B:
The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.

Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.

You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times.

-----Input-----

The only line of the input contains a pair of integers n (1000 ≤ n ≤ 10 000) and t (0 ≤ t ≤ 2 000 000 000) — the number of transistors in the initial time and the number of seconds passed since the initial time.

-----Output-----

Output one number — the estimate of the number of transistors in a dence integrated circuit in t seconds since the initial time. The relative error of your answer should not be greater than 10^{ - 6}.

-----Examples-----
Input
1000 1000000

Output
1011.060722383550382782399454922040

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

n, t = map(int, input().split())
print(n*pow(1.000000011, t))


I found an interesting problem on https://codeforces.com/problemset/problem/630/C:
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.

Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.

-----Input-----

The only line of input contains one integer n (1 ≤ n ≤ 55) — the maximum length of a number that a door-plate can hold.

-----Output-----

Output one integer — the maximum number of offices, than can have unique lucky numbers not longer than n digits.

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

Output
6

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/630/D:
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cell is in form of a hexagon.

Some of magic effects are able to affect several field cells at once, cells that are situated not farther than n cells away from the cell in which the effect was applied. The distance between cells is the minimum number of cell border crosses on a path from one cell to another.

It is easy to see that the number of cells affected by a magic effect grows rapidly when n increases, so it can adversely affect the game performance. That's why Petya decided to write a program that can, given n, determine the number of cells that should be repainted after effect application, so that game designers can balance scale of the effects and the game performance. Help him to do it. Find the number of hexagons situated not farther than n cells away from a given cell. [Image]

-----Input-----

The only line of the input contains one integer n (0 ≤ n ≤ 10^9).

-----Output-----

Output one integer — the number of hexagons situated not farther than n cells away from a given cell.

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

Output
19

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/630/E:
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.

A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit.

More formally, if a game designer selected cells having coordinates (x_1, y_1) and (x_2, y_2), where x_1 ≤ x_2 and y_1 ≤ y_2, then all cells having center coordinates (x, y) such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2 will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to OX axis, all hexagon centers have integer coordinates and for each integer x there are cells having center with such x coordinate and for each integer y there are cells having center with such y coordinate. It is guaranteed that difference x_2 - x_1 is divisible by 2.

Working on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map.

Help him implement counting of these units before painting.

 [Image]

-----Input-----

The only line of input contains four integers x_1, y_1, x_2, y_2 ( - 10^9 ≤ x_1 ≤ x_2 ≤ 10^9,  - 10^9 ≤ y_1 ≤ y_2 ≤ 10^9) — the coordinates of the centers of two cells.

-----Output-----

Output one integer — the number of cells to be filled.

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

Output
13

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/630/F:
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.

-----Input-----

The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.

-----Output-----

Output one integer — the number of different variants of group composition.

-----Examples-----
Input
7

Output
29

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/630/G:
Because of budget cuts one IT company established new non-financial reward system instead of bonuses.

Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting feature gets "I suggested a new feature" pennant on his table.

Because of the limited budget of the new reward system only 5 "I fixed a critical bug" pennants and 3 "I suggested a new feature" pennants were bought.

In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded "I fixed a critical bug" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded "I suggested a new feature" pennants is passed on to his table.

One man can have several pennants of one type and of course he can have pennants of both types on his table. There are n tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.

-----Input-----

The only line of the input contains one integer n (1 ≤ n ≤ 500) — the number of tables in the IT company.

-----Output-----

Output one integer — the amount of ways to place the pennants on n tables.

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

Output
24

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

n = int(input())

#C(n + 5 - 1, n - 1) = C(n + 4, 5)

ans1 = 1
for i in range(5):
	ans1 *= (n + 4 - i)
for i in range(1, 6):
	ans1 //= i

ans2 = 1
for i in range(3):
	ans2 *= (n + 2 - i)
for i in range(1, 4):
	ans2 //= i

print(ans1 * ans2)


I found an interesting problem on https://codeforces.com/problemset/problem/630/H:
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n^2 intersections.

The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Obviously this requirement is satisfied by the following scheme: each bench is placed on a cross of paths and each path contains not more than one bench.

Help the park administration count the number of ways to place the benches.

-----Input-----

The only line of the input contains one integer n (5 ≤ n ≤ 100) — the number of east to west paths and north to south paths.

-----Output-----

Output one integer — the number of ways to place the benches.

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

Output
120

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/630/I:
To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.

The parking lot before the office consists of one line of (2n - 2) parking spaces. Unfortunately the total number of cars is greater than the parking lot capacity. Furthermore even amount of cars of each make is greater than the amount of parking spaces! That's why there are no free spaces on the parking lot ever.

Looking on the straight line of cars the company CEO thought that parking lot would be more beautiful if it contained exactly n successive cars of the same make. Help the CEO determine the number of ways to fill the parking lot this way.

-----Input-----

The only line of the input contains one integer n (3 ≤ n ≤ 30) — the amount of successive cars of the same make.

-----Output-----

Output one integer — the number of ways to fill the parking lot by cars of four makes using the described way.

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

Output
24

-----Note-----

Let's denote car makes in the following way: A — Aston Martin, B —   Bentley, M — Mercedes-Maybach, Z — Zaporozhets. For n = 3 there are the following appropriate ways to fill the parking lot: AAAB AAAM AAAZ ABBB AMMM AZZZ BBBA BBBM BBBZ BAAA BMMM BZZZ MMMA MMMB MMMZ MAAA MBBB MZZZ ZZZA ZZZB ZZZM ZAAA ZBBB ZMMM

Originally it was planned to grant sport cars of Ferrari, Lamborghini, Maserati and Bugatti makes but this idea was renounced because it is impossible to drive these cars having small road clearance on the worn-down roads of IT City.

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/630/J:
IT City company developing computer games invented a new way to reward its employees. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is divisible by all numbers from 2 to 10 every developer of this game gets a small bonus.

A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that n people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.

-----Input-----

The only line of the input contains one integer n (1 ≤ n ≤ 10^18) — the prediction on the number of people who will buy the game.

-----Output-----

Output one integer showing how many numbers from 1 to n are divisible by all numbers from 2 to 10.

-----Examples-----
Input
3000

Output
1

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/630/K:
IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible by any number from 2 to 10 every developer of this game gets a small bonus.

A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that n people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.

-----Input-----

The only line of the input contains one integer n (1 ≤ n ≤ 10^18) — the prediction on the number of people who will buy the game.

-----Output-----

Output one integer showing how many numbers from 1 to n are not divisible by any number from 2 to 10.

-----Examples-----
Input
12

Output
2

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


I found an interesting problem on https://codeforces.com/problemset/problem/630/L:
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.

A young hacker Vasya disassembled the program and found the algorithm that transforms the shown number into the activation code. Note: it is clear that Vasya is a law-abiding hacker, and made it for a noble purpose — to show the developer the imperfection of their protection.

The found algorithm looks the following way. At first the digits of the number are shuffled in the following order <first digit><third digit><fifth digit><fourth digit><second digit>. For example the shuffle of 12345 should lead to 13542. On the second stage the number is raised to the fifth power. The result of the shuffle and exponentiation of the number 12345 is 455 422 043 125 550 171 232. The answer is the 5 last digits of this result. For the number 12345 the answer should be 71232.

Vasya is going to write a keygen program implementing this algorithm. Can you do the same?

-----Input-----

The only line of the input contains a positive integer five digit number for which the activation code should be found.

-----Output-----

Output exactly 5 digits without spaces between them — the found activation code of the program.

-----Examples-----
Input
12345

Output
71232

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/630/M:
Vasya started working in a machine vision company of IT City. Vasya's team creates software and hardware for identification of people by their face.

One of the project's know-how is a camera rotating around its optical axis on shooting. People see an eye-catching gadget — a rotating camera — come up to it to see it better, look into it. And the camera takes their photo at that time. What could be better for high quality identification?

But not everything is so simple. The pictures from camera appear rotated too (on clockwise camera rotation frame the content becomes rotated counter-clockwise). But the identification algorithm can work only with faces that are just slightly deviated from vertical.

Vasya was entrusted to correct the situation — to rotate a captured image so that image would be minimally deviated from vertical. Requirements were severe. Firstly, the picture should be rotated only on angle divisible by 90 degrees to not lose a bit of information about the image. Secondly, the frames from the camera are so huge and FPS is so big that adequate rotation speed is provided by hardware FPGA solution only. And this solution can rotate only by 90 degrees clockwise. Of course, one can apply 90 degrees turn several times but for the sake of performance the number of turns should be minimized.

Help Vasya implement the program that by the given rotation angle of the camera can determine the minimum number of 90 degrees clockwise turns necessary to get a picture in which up direction deviation from vertical is minimum.

The next figure contains frames taken from an unrotated camera, then from rotated 90 degrees clockwise, then from rotated 90 degrees counter-clockwise. Arrows show direction to "true up". [Image]

The next figure shows 90 degrees clockwise turn by FPGA hardware. [Image]

-----Input-----

The only line of the input contains one integer x ( - 10^18 ≤ x ≤ 10^18) — camera angle in degrees. Positive value denotes clockwise camera rotation, negative —...

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/630/N:
The Department of economic development of IT City created a model of city development till year 2100.

To prepare report about growth perspectives it is required to get growth estimates from the model.

To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.

The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.

-----Input-----

The only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax^2 + bx + c = 0 equation.

-----Output-----

In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10^{ - 6}.

-----Examples-----
Input
1 30 200

Output
-10.000000000000000
-20.000000000000000

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/630/O:
Petya has recently started working as a programmer in the IT city company that develops computer games.

Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.

A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c.

The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector.

Enumerate the arrow points coordinates in counter-clockwise order starting from the tip.

 [Image]

-----Input-----

The only line of the input contains eight integers px, py, vx, vy ( - 1000 ≤ px, py, vx, vy ≤ 1000, vx^2 + vy^2 > 0), a, b, c, d (1 ≤ a, b, c, d ≤ 1000, a > c).

-----Output-----

Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10^{ - 9}.

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

Output
8.000000000000 11.000000000000
4.000000000000 8.000000000000
6.000000000000 8.000000000000
6.000000000000 3.000000000000
10.000000000000 3.000000000000
10.000000000000...

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

px, py, vx, vy, a, b, c, d = map(int, input().split())

v = (vx**2 + vy**2)**.5

print('{} {}'.format(px + vx/v*b, py + vy/v*b))
print('{} {}'.format(px - vy/v*a/2, py + vx/v*a/2))
print('{} {}'.format(px - vy/v*c/2, py + vx/v*c/2))
print('{} {}'.format(px - vy/v*c/2 - vx/v*d, py + vx/v*c/2 - vy/v*d))
print('{} {}'.format(px + vy/v*c/2 - vx/v*d, py - vx/v*c/2 - vy/v*d))
print('{} {}'.format(px + vy/v*c/2, py - vx/v*c/2))
print('{} {}'.format(px + vy/v*a/2, py - vx/v*a/2))


I found an interesting problem on https://codeforces.com/problemset/problem/630/P:
It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.

A "star" figure having n ≥ 5 corners where n is a prime number is constructed the following way. On the circle of radius r n points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts. [Image]

-----Input-----

The only line of the input contains two integers n (5 ≤ n < 10^9, n is prime) and r (1 ≤ r ≤ 10^9) — the number of the star corners and the radius of the circumcircle correspondingly.

-----Output-----

Output one number — the star area. The relative error of your answer should not be greater than 10^{ - 7}.

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

Output
108.395919545675

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

from math import*
n, r = map(int, input().split())
x=360/n
a=x/4/180*pi
b=x*3/4/180*pi
x=tan(a)
y=tan(b)
S = (r**2)*sin(a)*cos(a)/2
S1 = (r*sin(a)/tan(b))*r*sin(a)/2
S2=S-S1
print(S2*2*n)


I found an interesting problem on https://codeforces.com/problemset/problem/630/Q:
IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal.

The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length. [Image]

-----Input-----

The only line of the input contains three integers l_3, l_4, l_5 (1 ≤ l_3, l_4, l_5 ≤ 1000) — the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly.

-----Output-----

Output one number — the total volume of the pyramids. Absolute or relative error should not be greater than 10^{ - 9}.

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

Output
38.546168065709

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

import math

def DegToRad(x):
	return (math.acos(-1) / 180) * x

l3, l4, l5 = map(int, input().split())
v3 = l3 * l3 * l3 * math.sqrt(2) / 12
v4 = l4 * l4 * l4 * math.sqrt(2) / 6
a = l5; b = a / math.sqrt(2 - 2 * math.cos(DegToRad(72))); h = math.sqrt(a * a - b * b); s = b * b * math.sin(DegToRad(72)) * 2.5; v5 = s * h / 3;
print(v3 + v4 + v5)


I found an interesting problem on https://codeforces.com/problemset/problem/630/R:
There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor.

The game is played on a square field consisting of n × n cells. Initially all cells are empty. On each turn a player chooses and paint an empty cell that has no common sides with previously painted cells. Adjacent corner of painted cells is allowed. On the next turn another player does the same, then the first one and so on. The player with no cells to paint on his turn loses.

The professor have chosen the field size n and allowed the student to choose to be the first or the second player in the game. What should the student choose to win the game? Both players play optimally.

-----Input-----

The only line of the input contains one integer n (1 ≤ n ≤ 10^18) — the size of the field.

-----Output-----

Output number 1, if the player making the first turn wins when both players play optimally, otherwise print number 2.

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

Output
1
Input
2

Output
2

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

import sys
def fact(n):
	ret = 1
	for x in range(1, n + 1):
		ret = ret * x
	return ret

def C(n, k):
	return fact(n) // (fact(k) * (fact(n - k)))
n = int(input())
if n % 2 == 1:
	print(1)
else:
	print(2)


I found an interesting problem on https://codeforces.com/problemset/problem/631/A:
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.

We define function f(x, l, r) as a bitwise OR of integers x_{l}, x_{l} + 1, ..., x_{r}, where x_{i} is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n. [Image]

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the length of the arrays.

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

The third line contains n integers b_{i} (0 ≤ b_{i} ≤ 10^9).

-----Output-----

Print a single integer — the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n.

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

Output
22
Input
10
13 2 7 11 8 4 9 8 5 1
5 7 18 9 2 3 0 11 8 6

Output
46

-----Note-----

Bitwise OR of two non-negative integers a and b is the number c = a OR b, such that each of its digits in binary notation is 1 if and only if at least one of a or b have 1 in the corresponding position in binary notation.

In the first sample, one of the optimal answers is l = 2 and r = 4, because f(a, 2, 4) + f(b, 2, 4) = (2 OR 4 OR 3) + (3 OR 3 OR 12) = 7 + 15 = 22. Other ways to get maximum value is to choose l = 1 and r = 4, l = 1 and r = 5, l = 2 and r = 4, l = 2 and r = 5, l = 3 and r = 4, or l = 3 and r = 5.

In the second sample, the maximum value is obtained for l = 1 and r = 9.

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

n = int(input())
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))
answer1 = 0
answer2 = 0
for i in range(n):
    answer1 |= s1[i]
    answer2 |= s2[i]
print(answer1 + answer2)


I found an interesting problem on https://codeforces.com/problemset/problem/631/B:
Kris works in a large company "Blake Technologies". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the printing.

Printer works with a rectangular sheet of paper of size n × m. Consider the list as a table consisting of n rows and m columns. Rows are numbered from top to bottom with integers from 1 to n, while columns are numbered from left to right with integers from 1 to m. Initially, all cells are painted in color 0.

Your program has to support two operations:   Paint all cells in row r_{i} in color a_{i};  Paint all cells in column c_{i} in color a_{i}.

If during some operation i there is a cell that have already been painted, the color of this cell also changes to a_{i}.

Your program has to print the resulting table after k operation.

-----Input-----

The first line of the input contains three integers n, m and k (1  ≤  n,  m  ≤ 5000, n·m ≤ 100 000, 1 ≤ k ≤ 100 000) — the dimensions of the sheet and the number of operations, respectively.

Each of the next k lines contains the description of exactly one query:   1 r_{i} a_{i} (1 ≤ r_{i} ≤ n, 1 ≤ a_{i} ≤ 10^9), means that row r_{i} is painted in color a_{i};  2 c_{i} a_{i} (1 ≤ c_{i} ≤ m, 1 ≤ a_{i} ≤ 10^9), means that column c_{i} is painted in color a_{i}.

-----Output-----

Print n lines containing m integers each — the resulting table after all operations are applied.

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

Output
3 1 3
2 2 2
0 1 0

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

Output
1 1 1
1 0 1
1 1 1
1 0 1
1 1 1

-----Note-----

The figure below shows all three operations for the first sample step by step. The cells that were painted on the corresponding step are marked gray.  [Image]

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

import sys
n, m, k = [int(x) for x in input().split()]
lines, columns = [(0, 0, i, 1) for i in range(n)], [(0, 0, i, 2) for i in range(m)]
for i, line in enumerate(sys.stdin):
    t, r, c = [int(x) for x in line.split()]
    if t == 1:
        lines[r-1] = (i, c, r-1, 1)
    else:
        columns[r-1] = (i, c, r-1, 2)
strings = lines + columns
strings.sort()
matrix = [[0] * m for i in range(n)]
for i, c, r, t in strings:
    if t == 1:
        matrix[r] = [c for i in range(m)]
    else:
        for j in range(n):
            matrix[j][r] = c

for i in range(n):
    sys.stdout.write(' '.join(map(str, matrix[i])) + '\n')


I found an interesting problem on https://codeforces.com/problemset/problem/631/C:
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first r_{i} numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).

Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence a_{i} of length n and the description of each manager, that is value r_{i} and his favourite order. You are asked to speed up the process and determine how the final report will look like.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.

The second line contains n integers a_{i} (|a_{i}| ≤ 10^9) — the initial report before it gets to the first manager.

Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers t_{i} and r_{i} ($t_{i} \in \{1,2 \}$, 1 ≤ r_{i} ≤ n), meaning that the i-th manager sorts the first r_{i} numbers either in the non-descending (if t_{i} = 1) or non-ascending (if t_{i} = 2) order.

-----Output-----

Print n integers — the final report, which will be passed to Blake by manager number m.

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

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

Output
2 4 1 3

-----Note-----

In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.

In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After...

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

3

class StdReader:
	def read_int(self):
		return int(self.read_string())

	def read_ints(self, sep = None):
		return [int(i) for i in self.read_strings(sep)]

	def read_float(self):
		return float(self.read_string())

	def read_floats(self, sep = None):
		return [float(i) for i in self.read_strings(sep)]

	def read_string(self):
		return input()

	def read_strings(self, sep = None):
		return self.read_string().split(sep)

reader = StdReader()

def part_sort(a, i, j, reverse=False):
	a[i:j] = sorted(a[i:j], reverse=reverse)

def part_sorted(b, i, j, reverse=False):
	a = list(b)
	part_sort(a, i, j, reverse)
	return a

def main():
	n, m = reader.read_ints()
	a = reader.read_ints()

	ops = []
	for i in range(m):
		t, r = reader.read_ints()
		op = (t, r)

		while ops and op[1] >= ops[-1][1]:
			ops.pop()

		ops.append(op)

	# newops = []
	# prevt = None
	# for op in ops:
	# 	if prevt is None or prevt != op[0]:
	# 		newops.append(op)
	# 		# max_r = max(max_r, op[1])

	# 	prevt = op[0]

	# ops = newops

	max_r = ops[0][1]
	b = sorted(a[:max_r])
	bl = 0
	br = max_r - 1

	for i in range(len(ops)):
		t, r = ops[i]

		r1 = 0
		if i < len(ops) - 1:
			t1, r1 = ops[i+1]

		k = r - r1

		if t == 1:
			for p in range(k):
				a[r - 1 - p] = b[br]
				br -= 1
		else:
			for p in range(k):
				a[r - 1 - p] = b[bl]
				bl += 1

	# for op in ops:
	# 	t, r = op
	# 	reverse = t != 1
	# 	part_sort(a, 0, r, reverse=reverse)

	for ai in a:
		print(ai, end=' ')

def __starting_point():
	main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/631/D:
Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve.

All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (l_{i}, c_{i}), where l_{i} is the length of the i-th block and c_{i} is the corresponding letter. Thus, the string s may be written as the sequence of pairs $\langle(l_{1}, c_{1}),(l_{2}, c_{2}), \ldots,(l_{n}, c_{n}) \rangle$.

Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if t_{p}t_{p} + 1...t_{p} + |s| - 1 = s, where t_{i} is the i-th character of string t.

Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as $\langle(4, a) \rangle$, $\langle(3, a),(1, a) \rangle$, $\langle(2, a),(2, a) \rangle$...

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of blocks in the strings t and s, respectively.

The second line contains the descriptions of n parts of string t in the format "l_{i}-c_{i}" (1 ≤ l_{i} ≤ 1 000 000) — the length of the i-th part and the corresponding lowercase English letter.

The second line contains the descriptions of m parts of string s in the...

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

def ziped(a):
	p = []
	for i in a:
		x = int(i.split('-')[0])
		y = i.split('-')[1]
		if len(p) > 0 and p[-1][1] == y:
			p[-1][0] += x
		else:
			p.append([x, y])
	return p

def solve(a, b , c):
	ans = 0
	if len(b) == 1:
		for token in a:
			if c(token, b[0]):
				ans += token[0] - b[0][0] + 1
		return ans

	if len(b) == 2:
		for i in range(len(a) - 1):
			if c(a[i], b[0]) and c(a[i + 1], b[-1]):
				ans += 1
		return ans

	v = b[1 : -1] + [[100500, '#']] + a
	p = [0] * len(v)
	for i in range(1, len(v)):
		j = p[i - 1]
		while j > 0 and v[i] != v[j]:
			j = p[j - 1]
		if v[i] == v[j]:
			j += 1
		p[i] = j

	for i in range(len(v) - 1):
		if p[i] == len(b) - 2 and c(v[i - p[i]], b[0]) and c(v[i + 1], b[-1]):
			ans += 1
	return ans

n, m = list(map(int, input().split()))
a = ziped(input().split())
b = ziped(input().split())
print(solve(a, b, lambda x, y: x[1] == y[1] and x[0] >= y[0]))


I found an interesting problem on https://codeforces.com/problemset/problem/632/A:
Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.

She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and also she gave a half of an apple to some of them as a gift (if the number of apples at the moment of purchase was odd), until she sold all the apples she had.

So each buyer took some integral positive number of apples, but maybe he didn't pay for a half of an apple (if the number of apples at the moment of the purchase was odd).

For each buyer grandma remembers if she gave a half of an apple as a gift or not. The cost of an apple is p (the number p is even).

Print the total money grandma should have at the end of the day to check if some buyers cheated her.

-----Input-----

The first line contains two integers n and p (1 ≤ n ≤ 40, 2 ≤ p ≤ 1000) — the number of the buyers and the cost of one apple. It is guaranteed that the number p is even.

The next n lines contains the description of buyers. Each buyer is described with the string half if he simply bought half of the apples and with the string halfplus if grandma also gave him a half of an apple as a gift.

It is guaranteed that grandma has at least one apple at the start of the day and she has no apples at the end of the day.

-----Output-----

Print the only integer a — the total money grandma should have at the end of the day.

Note that the answer can be 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.

-----Examples-----
Input
2 10
half
halfplus

Output
15

Input
3 10
halfplus
halfplus
halfplus

Output
55

-----Note-----

In the first sample at the start of the day the grandma had two apples. First she sold one apple and then she sold a half of the second apple and gave a half of the second apple as a present to the second buyer.

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

n, p = [int(x) for x in input().split()]
guys = [input() == 'halfplus' for i in range(n)]
cur = 0
S = 0
for guy in reversed(guys):
    S += p*cur + guy*p//2
    cur = 2 * cur + 1 if guy else 2 *  cur
print(S)


I found an interesting problem on https://codeforces.com/problemset/problem/632/B:
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength p_{i}.

The way to split up game pieces is split into several steps:

  First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.  Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.  Alice will get all the pieces marked A and Bob will get all the pieces marked B.

The strength of a player is then the sum of strengths of the pieces in the group.

Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 5·10^5) — the number of game pieces.

The second line contains n integers p_{i} (1 ≤ p_{i} ≤ 10^9) — the strength of the i-th piece.

The third line contains n characters A or B — the assignment of teams after the first step (after Alice's step).

-----Output-----

Print the only integer a — the maximum strength Bob can achieve.

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

Output
11

Input
5
1 2 3 4 5
AAAAA

Output
15

Input
1
1
B

Output
1

-----Note-----

In the first sample Bob should flip the suffix of length one.

In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.

In the third sample Bob should do nothing.

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

def cnt(step):
    temp_total, ans = total, 0
    for i in range(N)[::step]:
        if chars[i] == 'A':
            temp_total += strengths[i]
        else:
            temp_total -= strengths[i]
        ans = max(temp_total, ans)
    return ans

N = int(input())
strengths = [int(_) for _ in input().split()]
chars = list(input())

total = 0
for i, c in enumerate(chars):
    if c == 'B':
        total += strengths[i]

print(max([total, cnt(1), cnt(-1)]))


I found an interesting problem on https://codeforces.com/problemset/problem/632/C:
You're given a list of n strings a_1, a_2, ..., a_{n}. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.

Given the list of strings, output the lexicographically smallest concatenation.

-----Input-----

The first line contains integer n — the number of strings (1 ≤ n ≤ 5·10^4).

Each of the next n lines contains one string a_{i} (1 ≤ |a_{i}| ≤ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5·10^4.

-----Output-----

Print the only string a — the lexicographically smallest string concatenation.

-----Examples-----
Input
4
abba
abacaba
bcd
er

Output
abacabaabbabcder

Input
5
x
xx
xxa
xxaa
xxaaa

Output
xxaaaxxaaxxaxxx

Input
3
c
cb
cba

Output
cbacbc

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

from functools import cmp_to_key
print(''.join((sorted((input() for _ in range(int(input()))), key=cmp_to_key(lambda a, b: 1 if a + b > b + a else-1)))))


I found an interesting problem on https://codeforces.com/problemset/problem/632/D:
You are given array a with n elements and the number m. Consider some subsequence of a and the value of least common multiple (LCM) of its elements. Denote LCM as l. Find any longest subsequence of a with the value l ≤ m.

A subsequence of a is an array we can get by erasing some elements of a. It is allowed to erase zero or all elements.

The LCM of an empty array equals 1.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 10^6) — the size of the array a and the parameter from the problem statement.

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

-----Output-----

In the first line print two integers l and k_{max} (1 ≤ l ≤ m, 0 ≤ k_{max} ≤ n) — the value of LCM and the number of elements in optimal subsequence.

In the second line print k_{max} integers — the positions of the elements from the optimal subsequence in the ascending order.

Note that you can find and print any subsequence with the maximum length.

-----Examples-----
Input
7 8
6 2 9 2 7 2 3

Output
6 5
1 2 4 6 7

Input
6 4
2 2 2 3 3 3

Output
2 3
1 2 3

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

import sys

n, m = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
B, C = [0]*(m+1), [0]*(m+1)
for a in A:
    if a <= m: B[a] += 1
for i in range(2, m + 1):
    for j in range(i, m+1, i):
        C[j] += B[i]

k, l = 1, 0
for i in range(2, m+1):
    if C[i] > l:
        l = C[i]
        k = i
print(k, l + B[1])
for i, a in enumerate(A):
    if k%a == 0: sys.stdout.write(str(i+1) + ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/633/A:
Dante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots.

For every bullet that hits the shield, Ebony deals a units of damage while Ivory deals b units of damage. In order to break the shield Dante has to deal exactly c units of damage. Find out if this is possible.

-----Input-----

The first line of the input contains three integers a, b, c (1 ≤ a, b ≤ 100, 1 ≤ c ≤ 10 000) — the number of units of damage dealt by Ebony gun and Ivory gun, and the total number of damage required to break the shield, respectively.

-----Output-----

Print "Yes" (without quotes) if Dante can deal exactly c damage to the shield and "No" (without quotes) otherwise.

-----Examples-----
Input
4 6 15

Output
No

Input
3 2 7

Output
Yes

Input
6 11 6

Output
Yes

-----Note-----

In the second sample, Dante can fire 1 bullet from Ebony and 2 from Ivory to deal exactly 1·3 + 2·2 = 7 damage. In the third sample, Dante can fire 1 bullet from ebony and no bullets from ivory to do 1·6 + 0·11 = 6 damage.

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

line = [int(x) for x in input().strip().split(" ")]
a = line[0]
b = line[1]
c = line[2]

def doable(a, b, c):
	for i in range((c//a)+1):
		t = c-(i*a)
		# print("t: %s" % (t))
		if t%b==0:
			return True
	return False

if doable(a, b, c):
	print("Yes")
else:
	print("No")


I found an interesting problem on https://codeforces.com/problemset/problem/633/B:
Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer m and asks for the number of positive integers n, such that the factorial of n ends with exactly m zeroes. Are you among those great programmers who can solve this problem?

-----Input-----

The only line of input contains an integer m (1 ≤ m ≤ 100 000) — the required number of trailing zeroes in factorial.

-----Output-----

First print k — the number of values of n such that the factorial of n ends with m zeroes. Then print these k integers in increasing order.

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

Output
5
5 6 7 8 9
Input
5

Output
0

-----Note-----

The factorial of n is equal to the product of all integers from 1 to n inclusive, that is n! = 1·2·3·...·n.

In the first sample, 5! = 120, 6! = 720, 7! = 5040, 8! = 40320 and 9! = 362880.

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

n = int(input())

def zrs(n):
    ret = 0
    while n >= 5:
        n //= 5
        ret += n
    return ret

def bins(n):
    a,b = 1, n * 5 +1
    while a < b:
        mid = (a+b) // 2
        guess = zrs(mid)
        #print (guess)
        #print(a,b)
        if guess < n:
            a = mid +1
        elif guess > n:
            b = mid -1
        else:
            return mid
    return 0

x = bins(n)
x = x - x%5

if x == 0:
    print('0')
else:
    print('5')
    print(' '.join(map(str,list(range(x, x+5)))))


I found an interesting problem on https://codeforces.com/problemset/problem/633/D:
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if   the sequence consists of at least two elements  f_0 and f_1 are arbitrary  f_{n} + 2 = f_{n} + 1 + f_{n} for all n ≥ 0.

You are given some sequence of integers a_1, a_2, ..., a_{n}. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.

-----Input-----

The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence a_{i}.

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

-----Output-----

Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.

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

Output
3

Input
5
28 35 7 14 21

Output
4

-----Note-----

In the first sample, if we rearrange elements of the sequence as  - 1, 2, 1, the whole sequence a_{i} would be Fibonacci-ish.

In the second sample, the optimal way to rearrange elements is $7$, $14$, $21$, $35$, 28.

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

from collections import Counter

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

for q in s:
    s[q] -= 1

    for a in s:
        if s[a]:
            t = [a]
            s[a] -= 1
            b = q + a

            while s.get(b, 0):
                s[b] -= 1
                t.append(b)
                a, b = b, a + b

            n = max(n, len(t))

            for c in t:
                s[c] += 1
    s[q] += 1

print(n + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/634/A:
A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.

The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.

Determine if it is possible for the islanders to arrange the statues in the desired order.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 200 000) — the total number of islands.

The second line contains n space-separated integers a_{i} (0 ≤ a_{i} ≤ n - 1) — the statue currently placed on the i-th island. If a_{i} = 0, then the island has no statue. It is guaranteed that the a_{i} are distinct.

The third line contains n space-separated integers b_{i} (0 ≤ b_{i} ≤ n - 1) — the desired statues of the ith island. Once again, b_{i} = 0 indicates the island desires no statue. It is guaranteed that the b_{i} are distinct.

-----Output-----

Print "YES" (without quotes) if the rearrangement can be done in the existing network, and "NO" otherwise.

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

Output
YES

Input
2
1 0
0 1

Output
YES

Input
4
1 2 3 0
0 3 2 1

Output
NO

-----Note-----

In the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3.

In the second sample, the islanders can simply move statue 1 from island 1 to island 2.

In the third sample, no sequence of movements results in the desired position.

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

3.5
n=int(input())
a=input().split()
b=input().split()
a.remove('0')
b.remove('0')
k=a.index(b[0])
a=a[k:]+a[:k]
if a==b:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/635/A:
Paul is at the orchestra. The string section is arranged in an r × c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.

Two pictures are considered to be different if the coordinates of corresponding rectangles are different.

-----Input-----

The first line of input contains four space-separated integers r, c, n, k (1 ≤ r, c, n ≤ 10, 1 ≤ k ≤ n) — the number of rows and columns of the string section, the total number of violas, and the minimum number of violas Paul would like in his photograph, respectively.

The next n lines each contain two integers x_{i} and y_{i} (1 ≤ x_{i} ≤ r, 1 ≤ y_{i} ≤ c): the position of the i-th viola. It is guaranteed that no location appears more than once in the input.

-----Output-----

Print a single integer — the number of photographs Paul can take which include at least k violas.

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

Output
4

Input
3 2 3 3
1 1
3 1
2 2

Output
1

Input
3 2 3 2
1 1
3 1
2 2

Output
4

-----Note-----

We will use '*' to denote violinists and '#' to denote violists.

In the first sample, the orchestra looks as follows

*#

**

 Paul can take a photograph of just the viola, the 1 × 2 column containing the viola, the 2 × 1 row containing the viola, or the entire string section, for 4 pictures total.

In the second sample, the orchestra looks as follows

#*

*#

#*

 Paul must take a photograph of the entire section.

In the third sample, the orchestra looks the same as in the second sample.

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

r, c, n, k = list(map(int, input().split()))
alt = []
count = 0
for i in range(n):
    a, b = list(map(int, input().split()))
    alt.append([a - 1, b - 1])
for x1 in range(r):
    for x2 in range(x1 + 1):
        for y1 in range(c):
            for y2 in range(y1 + 1):
                d = 0
                for i in range(n):
                    if (alt[i][0] <= x1 and alt[i][0] >= x2 and alt[i][1] <= y1 and alt[i][1] >= y2):
                        d += 1
                if d >= k:
                    count += 1
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/637/A:
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.

Help guys determine the winner photo by the records of likes.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the total likes to the published photoes.

The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1 000 000), where a_{i} is the identifier of the photo which got the i-th like.

-----Output-----

Print the identifier of the photo which won the elections.

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

Output
2

Input
9
100 200 300 200 100 300 300 100 200

Output
300

-----Note-----

In the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second).

Thus, the winner is the photo with identifier 2, as it got:  more likes than the photo with id 3;  as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier.

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

n = int(input())
line = input().split()
maxi = line[0]
mas = {}
mas[maxi] = 1
for i in range(1, n):
    a = line[i]
    if not a in mas:
        mas[a] = 1
    else:
        mas[a] += 1
    if (mas[a] > mas[maxi]):
        maxi = a
print(maxi)


I found an interesting problem on https://codeforces.com/problemset/problem/637/B:
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.

Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.

-----Output-----

Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.

-----Examples-----
Input
4
alex
ivan
roman
ivan

Output
ivan
roman
alex

Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina

Output
alina
maria
ekaterina
darya

-----Note-----

In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:   alex

Then Polycarpus writes to friend by name "ivan" and the list looks as follows:  ivan  alex

Polycarpus writes the third message to friend by name "roman" and the list looks as follows:  roman  ivan  alex

Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:  ivan  roman  alex

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

n = int(input())
a = [input() for i in range(n)]
was = set()
for name in a[::-1]:
    if name not in was:
        was.add(name)
        print(name)


I found an interesting problem on https://codeforces.com/problemset/problem/637/C:
During a New Year special offer the "Sudislavl Bars" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar "Mosquito Shelter". Of course, all the promocodes differ.

As the "Mosquito Shelter" opens only at 9, and partying in Sudislavl usually begins at as early as 6, many problems may arise as to how to type a promotional code without errors. It is necessary to calculate such maximum k, that the promotional code could be uniquely identified if it was typed with no more than k errors. At that, k = 0 means that the promotional codes must be entered exactly.

A mistake in this problem should be considered as entering the wrong numbers. For example, value "123465" contains two errors relative to promocode "123456". Regardless of the number of errors the entered value consists of exactly six digits.

-----Input-----

The first line of the output contains number n (1 ≤ n ≤ 1000) — the number of promocodes.

Each of the next n lines contains a single promocode, consisting of exactly 6 digits. It is guaranteed that all the promocodes are distinct. Promocodes can start from digit "0".

-----Output-----

Print the maximum k (naturally, not exceeding the length of the promocode), such that any promocode can be uniquely identified if it is typed with at most k mistakes.

-----Examples-----
Input
2
000000
999999

Output
2

Input
6
211111
212111
222111
111111
112111
121111

Output
0

-----Note-----

In the first sample k < 3, so if a bar customer types in value "090909", then it will be impossible to define which promocode exactly corresponds to it.

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

def main():
    n, l, k = int(input()), [], 0
    if n < 2:
        print(6)
        return
    for _ in range(n):
        a = input()
        for b in l:
            x = sum(u == v for u, v in zip(a, b))
            if k < x:
                k = x
                if k > 4:
                    print(0)
                    return
        l.append(a)
    print(2 - k // 2)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/637/D:
A sportsman starts from point x_{start} = 0 and runs to point with coordinate x_{finish} = m (on a straight line). Also, the sportsman can jump — to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a length of not more than d meters. Running and jumping is permitted only in the direction from left to right. He can start andfinish a jump only at the points with integer coordinates in which there are no obstacles. To overcome some obstacle, it is necessary to land at a point which is strictly to the right of this obstacle.

On the way of an athlete are n obstacles at coordinates x_1, x_2, ..., x_{n}. He cannot go over the obstacles, he can only jump over them. Your task is to determine whether the athlete will be able to get to the finish point.

-----Input-----

The first line of the input containsd four integers n, m, s and d (1 ≤ n ≤ 200 000, 2 ≤ m ≤ 10^9, 1 ≤ s, d ≤ 10^9) — the number of obstacles on the runner's way, the coordinate of the finishing point, the length of running before the jump and the maximum length of the jump, correspondingly.

The second line contains a sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ m - 1) — the coordinates of the obstacles. It is guaranteed that the starting and finishing point have no obstacles, also no point can have more than one obstacle, The coordinates of the obstacles are given in an arbitrary order.

-----Output-----

If the runner cannot reach the finishing point, print in the first line of the output "IMPOSSIBLE" (without the quotes).

If the athlete can get from start to finish, print any way to do this in the following format:  print a line of form "RUN X>" (where "X" should be a positive integer), if the athlete should run for "X" more meters;  print a line of form "JUMP Y" (where "Y" should be a positive integer), if the sportsman starts a jump and should remain in air for "Y" more meters.

All commands "RUN" and "JUMP"...

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

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

beg = [float('-inf')]
end = [float('-inf')]

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

for x in sorted(a):
	if (x - end[-1] > s + 1):
		beg.append(x)
		end.append(x)
	else:
		end[-1] = x

last = 0
R = []
J = []

for i in range(1, len(beg)):
	R.append(beg[i] - 1 - last)
	last = (beg[i] - 1)

	J.append(end[i] + 1 - last)
	last = (end[i] + 1)

ok = True
for x in J:
	if (x > d):
		ok = False
for x in R:
	if (x < s):
		ok = False

if ok:
	for i in range(len(R)):
		print('RUN', R[i])
		print('JUMP', J[i])
	if (last < m):
		print('RUN', m - last)
else:
	print('IMPOSSIBLE')


I found an interesting problem on https://codeforces.com/problemset/problem/638/A:
The main street of Berland is a straight line with n houses built along it (n is an even number). The houses are located at both sides of the street. The houses with odd numbers are at one side of the street and are numbered from 1 to n - 1 in the order from the beginning of the street to the end (in the picture: from left to right). The houses with even numbers are at the other side of the street and are numbered from 2 to n in the order from the end of the street to its beginning (in the picture: from right to left). The corresponding houses with even and odd numbers are strictly opposite each other, that is, house 1 is opposite house n, house 3 is opposite house n - 2, house 5 is opposite house n - 4 and so on. [Image]

Vasya needs to get to house number a as quickly as possible. He starts driving from the beginning of the street and drives his car to house a. To get from the beginning of the street to houses number 1 and n, he spends exactly 1 second. He also spends exactly one second to drive the distance between two neighbouring houses. Vasya can park at any side of the road, so the distance between the beginning of the street at the houses that stand opposite one another should be considered the same.

Your task is: find the minimum time Vasya needs to reach house a.

-----Input-----

The first line of the input contains two integers, n and a (1 ≤ a ≤ n ≤ 100 000) — the number of houses on the street and the number of the house that Vasya needs to reach, correspondingly. It is guaranteed that number n is even.

-----Output-----

Print a single integer — the minimum time Vasya needs to get from the beginning of the street to house a.

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

Output
2

Input
8 5

Output
3

-----Note-----

In the first sample there are only four houses on the street, two houses at each side. House 2 will be the last at Vasya's right.

The second sample corresponds to picture with n = 8. House 5 is the one before last at Vasya's left.

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

n,a = list(map(int,input().split()))
k = 0
for i in range(1,n,2):
    k+=1
    if i==a:
        print(k)
k = 0
for i in range(n,1,-2):
    k+=1
    if i==a:
        print(k)


I found an interesting problem on https://codeforces.com/problemset/problem/638/C:
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads.

In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day.

Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are.

-----Input-----

The first line of the input contains a positive integer n (2 ≤ n ≤ 200 000) — the number of cities in Berland.

Each of the next n - 1 lines contains two numbers u_{i}, v_{i}, meaning that the i-th road connects city u_{i} and city v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}).

-----Output-----

First print number k — the minimum number of days needed to repair all the roads in Berland.

In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number d_{i} — the number of roads that should be repaired on the i-th day, and then d_{i} space-separated integers — the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one.

If there are multiple variants, you can print any of them.

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

Output
2
2 2 1
1 3

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

Output
3
1 1
2 2 3
2 4 5

-----Note-----

In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 — on the second day.

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

import sys
import threading
from collections import defaultdict

def put():
    return map(int, input().split())

def dfs(i, p, m):
    cnt = 1
    z = 0
    for j in tree[i]:
        if j==p: continue
        if cnt==m: cnt+=1
        index = edge_index[(i,j)]
        ans[cnt].append(index)
        z = max(dfs(j,i,cnt), z)
        cnt+=1
    return max(z,cnt-1)

def solve():
    l = dfs(1,0,0)
    print(l)
    for i in range(1, l+1):
        print(len(ans[i]), *ans[i])

n = int(input())
edge_index = defaultdict()
ans = [[] for i in range(n+1)]
tree = [[] for i in range(n+1)]
for i in range(n-1):
    x,y = put()
    edge_index[(x,y)]=i+1
    edge_index[(y,x)]=i+1
    tree[x].append(y)
    tree[y].append(x)

max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start()


I found an interesting problem on https://codeforces.com/problemset/problem/638/D:
A super computer has been built in the Turtle Academy of Sciences. The computer consists of n·m·k CPUs. The architecture was the paralellepiped of size n × m × k, split into 1 × 1 × 1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer number from 1 to n, the line number from 1 to m and the column number from 1 to k.

In the process of the Super Computer's work the CPUs can send each other messages by the famous turtle scheme: CPU (x, y, z) can send messages to CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) (of course, if they exist), there is no feedback, that is, CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) cannot send messages to CPU (x, y, z).

Over time some CPUs broke down and stopped working. Such CPUs cannot send messages, receive messages or serve as intermediates in transmitting messages. We will say that CPU (a, b, c) controls CPU (d, e, f) , if there is a chain of CPUs (x_{i}, y_{i}, z_{i}), such that (x_1 = a, y_1 = b, z_1 = c), (x_{p} = d, y_{p} = e, z_{p} = f) (here and below p is the length of the chain) and the CPU in the chain with number i (i < p) can send messages to CPU i + 1.

Turtles are quite concerned about the denial-proofness of the system of communication between the remaining CPUs. For that they want to know the number of critical CPUs. A CPU (x, y, z) is critical, if turning it off will disrupt some control, that is, if there are two distinctive from (x, y, z) CPUs: (a, b, c) and (d, e, f), such that (a, b, c) controls (d, e, f) before (x, y, z) is turned off and stopped controlling it after the turning off.

-----Input-----

The first line contains three integers n, m and k (1 ≤ n, m, k ≤ 100) — the dimensions of the Super Computer.

Then n blocks follow, describing the current state of the processes. The blocks correspond to the layers of the Super Computer in the order from 1 to n. Each block consists of m lines, k characters in each — the description of a layer in the format of an...

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

def safe(pos):
    return pos[0] >= 0 and pos[0] < n and pos[1] >= 0 and pos[1] < m and pos[2] >= 0 and pos[2] < p
def CPU_status(pos, number):
    return safe(pos) and super_computer[pos[0]][pos[1]][pos[2]] == number
def critical(x,y,z):
    if super_computer[x][y][z] != '0':
        current = [x,y,z]
        for i in range(3):
            parent = current.copy()
            parent[i]-=1
            if CPU_status(parent, '1'):
                for j in range(3):
                    child, alt = current.copy(), parent.copy()
                    child[j]+=1
                    alt[j]+=1
                    if CPU_status(child, '1') and (CPU_status(alt, '0') or j == i):
                            return 1
    return 0
n, m, p = map(int, input().split())
super_computer, crit = ([], 0)
for i in range(n):
    super_computer.append([input() for _ in range(m)])
    if i != n-1:
        input()
for i in range(n):
    for j in range(m):
        for k in range(p):
            crit += critical(i,j,k)
print(crit)


I found an interesting problem on https://codeforces.com/problemset/problem/639/A:
Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer t_{i}. The bigger this value is, the better the friendship is. No two friends have the same value t_{i}.

Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.

The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them — those with biggest t_{i}.

Your task is to handle queries of two types:  "1 id" — Friend id becomes online. It's guaranteed that he wasn't online before.  "2 id" — Check whether friend id is displayed by the system. Print "YES" or "NO" in a separate line.

Are you able to help Limak and answer all queries of the second type?

-----Input-----

The first line contains three integers n, k and q (1 ≤ n, q ≤ 150 000, 1 ≤ k ≤ min(6, n)) — the number of friends, the maximum number of displayed online friends and the number of queries, respectively.

The second line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 10^9) where t_{i} describes how good is Limak's relation with the i-th friend.

The i-th of the following q lines contains two integers type_{i} and id_{i} (1 ≤ type_{i} ≤ 2, 1 ≤ id_{i} ≤ n) — the i-th query. If type_{i} = 1 then a friend id_{i} becomes online. If type_{i} = 2 then you should check whether a friend id_{i} is displayed.

It's guaranteed that no two queries of the first type will have the same id_{i} becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (type_{i} = 2) so the output won't be empty.

-----Output-----

For each query of the second type print one line with the answer — "YES" (without quotes) if the given friend...

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

from collections import deque
from math import *
n, k ,q = list(map(int, input().split()))
A = []
lens = 0
B = list(map(int, input().split()))
for i in range(q):
    per1,per2 = list(map(int, input().split()))
    if per1 == 1:
        if lens < k:
            A.append([per2, B[per2-1]])
            lens += 1
        else:
            c = float('infinity')
            r = 0
            for i in range(k):
                if A[i][1] < c:
                    c = A[i][1]
                    r = i
            if B[per2 -1] > A[r][1]:

                A[r] = [per2, B[per2-1]]
    else:
        si = True
        for i in range(lens):
            if A[i][0] == per2:
                si = False
                break
        if si:
            print('NO')
        else:
            print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/639/B:
A tree is a connected undirected graph consisting of n vertices and n  -  1 edges. Vertices are numbered 1 through n.

Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:

  The tree had exactly n vertices.  The tree had diameter d. In other words, d was the biggest distance between two vertices.  Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.

The distance between two vertices of the tree is the number of edges on the simple path between them.

Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".

-----Input-----

The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.

-----Output-----

If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).

Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.

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

Output
1 2
1 3
3 4
3 5
Input
8 5 2

Output
-1

Input
8 4 2

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

-----Note-----

Below you can see trees printed to the output in the first sample and the third sample.

 [Image]

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

import string

i = input()
i = i.split(' ')
n, d, h = list([int(x) for x in i])

def check(n, d, h):
    if d > 2 * h:
        print(-1)
        return

    if d < h:
        print(-1)
        return
    if n < d + 1 or n < h + 1:
        print(-1)
        return
    if d == 1 and n > 2:
        print(-1)
        return

out = []
#h
check(n, d, h)
c = 0
# print('h')
for i in range(h):
    out.append(str(c + 1) + ' ' + str(c + 2))
    # print(out[-1])
    c += 1
c += 1
c1 = 0
# print('d')
for i in range(d - h):
    out.append(str(c1 + 1) + ' ' + str(c + 1))
    # print(out[-1])
    c1 = c
    c += 1

c += 1
# print('n')
if d == h:
    s = 2
else:
    s = 1

for i in range(n - c + 1):
    out.append(str(s) + ' ' + str(c))
    # print(out[-1])

    c += 1

for el in out:
    print(el)


I found an interesting problem on https://codeforces.com/problemset/problem/639/C:
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.

He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally:

Let a_0, a_1, ..., a_{n} denote the coefficients, so $P(x) = \sum_{i = 0}^{n} a_{i} \cdot x^{i}$. Then, a polynomial P(x) is valid if all the following conditions are satisfied:  a_{i} is integer for every i;  |a_{i}| ≤ k for every i;  a_{n} ≠ 0.

Limak has recently got a valid polynomial P with coefficients a_0, a_1, a_2, ..., a_{n}. He noticed that P(2) ≠ 0 and he wants to change it. He is going to change one coefficient to get a valid polynomial Q of degree n that Q(2) = 0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 10^9) — the degree of the polynomial and the limit for absolute values of coefficients.

The second line contains n + 1 integers a_0, a_1, ..., a_{n} (|a_{i}| ≤ k, a_{n} ≠ 0) — describing a valid polynomial $P(x) = \sum_{i = 0}^{n} a_{i} \cdot x^{i}$. It's guaranteed that P(2) ≠ 0.

-----Output-----

Print the number of ways to change one coefficient to get a valid polynomial Q that Q(2) = 0.

-----Examples-----
Input
3 1000000000
10 -9 -3 5

Output
3

Input
3 12
10 -9 -3 5

Output
2

Input
2 20
14 -7 19

Output
0

-----Note-----

In the first sample, we are given a polynomial P(x) = 10 - 9x - 3x^2 + 5x^3.

Limak can change one coefficient in three ways:  He can set a_0 =  - 10. Then he would get Q(x) =  - 10 - 9x - 3x^2 + 5x^3 and indeed Q(2) =  - 10 - 18 - 12 + 40 = 0.  Or he can set a_2 =  - 8. Then Q(x) = 10 - 9x - 8x^2 + 5x^3 and indeed Q(2) = 10 - 18 - 32 + 40 = 0.  Or he can set a_1 =  - 19. Then Q(x) = 10 - 19x - 3x^2 + 5x^3 and indeed Q(2) = 10 - 38 - 12 + 40 = 0.

In the second sample, we are given the same polynomial. This time though, k is equal to 12 instead of 10^9. Two first of...

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

def convert_to_binary(coef):
    res = []
    n = len(coef)
    carry = 0
    i = 0
    while i < n + 1000:
        if i >= n and not carry:
            break
        cur = carry
        if i < n:
            cur += coef[i]

        mod = cur % 2
        div = cur // 2
#        print(cur, div, mod)

        res.append(mod)

        carry = div

        i += 1
    return res, carry

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

b, carry = convert_to_binary(coef)
ref = False
if carry < 0:
    b, carry = convert_to_binary(list([-x for x in coef]))
    ref = True

last = len(b) - 1
while b[last] != 1:
    last -= 1

ans = 0
for i in range(0, n + 1):
    if last - i > 40:
        continue

    cur = 0
    for j in range(i, last + 1):
        cur += b[j] * (2 ** (j - i))

    new_coef = coef[i] - cur
    if ref:
        new_coef = coef[i] + cur

    if abs(new_coef) > k:
        if b[i] == 1:
            break
        continue

    if i == n and new_coef == 0:
        if b[i] == 1:
            break
        continue

    ans += 1
    if b[i] == 1:
        break

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/641/A:
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.

The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.

Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers d_{i} (1 ≤ d_{i} ≤ 10^9) — the length of the jump from the i-th cell.

-----Output-----

Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).

-----Examples-----
Input
2
><
1 2

Output
FINITE

Input
3
>><
2 1 1

Output
INFINITE

-----Note-----

In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.

Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite.

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

n = int(input())
cells = input()
lengths = list(map(int, input().split()))
visited = set()
i = 0
while (i not in visited) and (i < n) and (i > -1):
	visited.add(i)
	if cells[i] == '>':
		i += lengths[i]
	else:
		i -= lengths[i]
	#print('new', i)

if (i < n) and (i >= 0):
	print("INFINITE")
else:
	print("FINITE")


I found an interesting problem on https://codeforces.com/problemset/problem/641/B:
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.

That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.

Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.

Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.

-----Input-----

The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 100, 1 ≤ q ≤ 10 000) — dimensions of the matrix and the number of turns in the experiment, respectively.

Next q lines contain turns descriptions, one per line. Each description starts with an integer t_{i} (1 ≤ t_{i} ≤ 3) that defines the type of the operation. For the operation of first and second type integer r_{i} (1 ≤ r_{i} ≤ n) or c_{i} (1 ≤ c_{i} ≤ m) follows, while for the operations of the third type three integers r_{i}, c_{i} and x_{i} (1 ≤ r_{i} ≤ n, 1 ≤ c_{i} ≤ m,  -...

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

m,n,q = map(int,input().split())
inps = [map(lambda x: int(x)-1,input().split()) for _ in range(q)]
matrix = [[-1]*n for _ in range(m)]
for x in reversed(inps):
    t,c,*cc = x
    if t == 0:
        matrix[c] = [matrix[c][-1]] + matrix[c][:-1]
    elif t == 1:
        new = [matrix[i][c] for i in range(m)]
        for i,x in enumerate([new[-1]] + new[:-1]):
            matrix[i][c] = x
    elif t == 2:
        matrix[c][cc[0]] = cc[1]
for x in matrix:
    print(' '.join(map(lambda v: str(v+1), x)))


I found an interesting problem on https://codeforces.com/problemset/problem/641/D:
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.

Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and different dices may have different probability distributions.

We throw both dices simultaneously and then calculate values max(a, b) and min(a, b), where a is equal to the outcome of the first dice, while b is equal to the outcome of the second dice. You don't know the probability distributions for particular values on each dice, but you know the probability distributions for max(a, b) and min(a, b). That is, for each x from 1 to n you know the probability that max(a, b) would be equal to x and the probability that min(a, b) would be equal to x. Find any valid probability distribution for values on the dices. It's guaranteed that the input data is consistent, that is, at least one solution exists.

-----Input-----

First line contains the integer n (1 ≤ n ≤ 100 000) — the number of different values for both dices.

Second line contains an array consisting of n real values with up to 8 digits after the decimal point  — probability distribution for max(a, b), the i-th of these values equals to the probability that max(a, b) = i. It's guaranteed that the sum of these values for one dice is 1. The third line contains the description of the distribution min(a, b) in the same format.

-----Output-----

Output two descriptions of the probability distribution for a on the first line and for b on the second line.

The answer will be considered correct if each value of max(a, b) and min(a, b) probability distribution values does not differ by more than 10^{ - 6} from ones given in input. Also, probabilities should be non-negative and their sums should differ from 1 by no more than 10^{ - 6}.

-----Examples-----
Input
2
0.25 0.75
0.75 0.25

Output
0.5 0.5
0.5 0.5

Input
3
0.125 0.25 0.625
0.625 0.25...

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

n = int(input())
mx = list(map(float, input().split()))
mn = list(map(float, input().split())) + [0]

for i in range(1, n):
    mx[i] += mx[i - 1]
for i in range(n - 2, -1, -1):
    mn[i] += mn[i + 1]

a, b = [0] * (n + 1), [0] * (n + 1)
for i in range(n):
    p = mx[i]
    s = 1 + mx[i] - mn[i + 1]
    a[i] = (s - max(s * s - 4 * p, 0) ** 0.5) / 2
    b[i] = (s + max(s * s - 4 * p, 0) ** 0.5) / 2
print(*(a[i] - a[i - 1] for i in range(n)))
print(*(b[i] - b[i - 1] for i in range(n)))


I found an interesting problem on https://codeforces.com/problemset/problem/641/E:
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.

Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types:

  Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer.  Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset.  Count the number of instances of the given integer that are stored in the multiset.

But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example.

  First Artem adds integer 5 to the multiset at the 1-st moment of time.  Then Artem adds integer 3 to the multiset at the moment 5.  Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1.  Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0.  Then Artem goes back in time again and removes 5 from the multiset at moment 3.  Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3.

Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.

Help Artem implement time travellers multiset.

-----Input-----

The first line of the input contains a...

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

from bisect import *
u, v = {}, {}
for q in range(int(input())):
    a, t, x = list(map(int, input().split()))
    if x not in u: u[x], v[x] = [], []
    if a < 3: insort([v, u][-a][x], t)
    else: print(bisect(u[x], t) - bisect(v[x], t))


I found an interesting problem on https://codeforces.com/problemset/problem/643/A:
Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color t_{i}.

For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.

There are $\frac{n \cdot(n + 1)}{2}$ non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls.

The second line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ n) where t_{i} is the color of the i-th ball.

-----Output-----

Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color.

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

Output
7 3 0 0

Input
3
1 1 1

Output
6 0 0

-----Note-----

In the first sample, color 2 is dominant in three intervals:  An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color.  An interval [4, 4] contains one ball, with color 2 again.  An interval [2, 4] contains two balls of color 2 and one ball of color 1.

There are 7 more intervals and color 1 is dominant in all of them.

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

n = int(input())
s = [int(i) for i in input().split()]

answer = [0 for i in range(n)]
p = n
for j in range(n):
    a = [0] * p
    domin = s[0]
    answer[domin - 1] += 1
    a[domin - 1] += 1
    for i in range(1, n):
        a[s[i] - 1] += 1
        if a[s[i] - 1] > a[domin - 1] or (a[s[i] - 1] == a[domin - 1] and s[i] < domin):
            domin = s[i]
        answer[domin - 1] += 1
    s.pop(0)
    n -= 1
print(*answer)


I found an interesting problem on https://codeforces.com/problemset/problem/643/B:
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.

Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:   There is no road between a and b.  There exists a sequence (path) of n distinct cities v_1, v_2, ..., v_{n} that v_1 = a, v_{n} = b and there is a road between v_{i} and v_{i} + 1 for $i \in \{1,2, \ldots, n - 1 \}$.

On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u_1, u_2, ..., u_{n} that u_1 = c, u_{n} = d and there is a road between u_{i} and u_{i} + 1 for $i \in \{1,2, \ldots, n - 1 \}$.

Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.

Given n, k and four distinct cities a, b, c, d, can you find possible paths (v_1, ..., v_{n}) and (u_1, ..., u_{n}) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.

-----Input-----

The first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively.

The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).

-----Output-----

Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v_1, v_2, ..., v_{n} where v_1 = a and v_{n} = b. The second line should contain n distinct integers u_1, u_2, ..., u_{n} where u_1 = c and u_{n} = d.

Two paths generate at most 2n - 2 roads: (v_1, v_2), (v_2, v_3), ..., (v_{n} - 1, v_{n}), (u_1, u_2), (u_2, u_3), ..., (u_{n} - 1, u_{n}). Your answer will be considered wrong if contains more than k distinct...

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

import sys
n, k = map(int, input().split())
a, b, c, d = map(int, input().split())
if(k<n+1 or n==4):
    print(-1)
    return
ans = [a, c]
l = [i for i in range(1, n+1) if (i!=a and i!=b and i!=c and i!=d)]
for i in l:
    ans.append(i)
ans.extend([d, b])
for i in ans:
    print(i, end=' ')
print()
ans[0], ans[1] = ans[1], ans[0]
ans[n-2], ans[n-1] = ans[n-1], ans[n-2]
for i in ans:
    print(i, end=' ')
print('\n')


I found an interesting problem on https://codeforces.com/problemset/problem/644/A:
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.

New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall

We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.

Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.

-----Input-----

The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.

-----Output-----

If there is no way to assigns seats to parliamentarians in a proper way print -1.

Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.

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

Output
0 3
1 2

Input
8 4 3

Output
7 8 3
0 1 4
6 0 5
0 2 0

Input
10 2 2

Output
-1

-----Note-----

In the first sample there are many other possible solutions. For example, 3 2

0 1

and 2 1

3 0

The following assignment 3 2

1 0

is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.

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

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

if n > a * b:
    print(-1)
else:
    for i in range(a):
        for j in range(b):
            val = i * b + 1
            val += (j if i % 2 == 0 else b - 1 - j)
            print(val if val <= n else 0, end = ' ')
        print()


I found an interesting problem on https://codeforces.com/problemset/problem/644/B:
In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment t_{i} and needs to be processed for d_{i} units of time. All t_{i} are guaranteed to be distinct.

When a query appears server may react in three possible ways:   If server is free and query queue is empty, then server immediately starts to process this query.  If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue.  If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed.

As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.

For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.

-----Input-----

The first line of the input contains two integers n and b (1 ≤ n, b ≤ 200 000) — the number of queries and the maximum possible size of the query queue.

Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers t_{i} and d_{i} (1 ≤ t_{i}, d_{i} ≤ 10^9), where t_{i} is the moment of time when the i-th query appears and d_{i} is the time server needs to process it. It is guaranteed that t_{i} - 1 < t_{i} for all i > 1.

-----Output-----

Print the sequence of n integers e_1, e_2, ..., e_{n}, where e_{i} is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or  - 1 if the corresponding query will be rejected.

-----Examples-----
Input
5 1
2 9
4 8
10 9
15 2
19 1

Output
11 19 -1 21 22

Input
4 1
2 8
4 8
10 9
15 2

Output
10 18 27 -1

-----Note-----

Consider the first sample.   The server will...

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

from collections import deque

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

q = deque()
for _ in range(n):
    t, d = map(int, input().split())
    while q and q[0] <= t:
        q.popleft()
    if len(q) == b + 1:
        print(-1, end = ' ')
    else:
        if q:
            t = q[-1]
        print(t + d, end = ' ')
        q.append(t + d)