I found an interesting problem on https://codeforces.com/problemset/problem/257/A:
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has a_{i} sockets.

Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity.

What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter.

-----Input-----

The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 50) — number a_{i} stands for the number of sockets on the i-th supply-line filter.

-----Output-----

Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1.

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

Output
1

Input
4 7 2
3 3 2 4

Output
2

Input
5 5 1
1 3 1 2 1

Output
-1

-----Note-----

In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices.

One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets...

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

n, m, k = map(int, input().split())
t = list(map(int, input().split()))
t.sort(reverse = True)

m -= k
i = 0
if m > 0:
    while i < n:
        m -= t[i] - 1
        i += 1
        if m <= 0: break

print(i if m <= 0 else -1)


I found an interesting problem on https://codeforces.com/problemset/problem/257/B:
Petya and Vasya decided to play a little. They found n red cubes and m blue cubes. The game goes like that: the players take turns to choose a cube of some color (red or blue) and put it in a line from left to right (overall the line will have n + m cubes). Petya moves first. Petya's task is to get as many pairs of neighbouring cubes of the same color as possible. Vasya's task is to get as many pairs of neighbouring cubes of different colors as possible.

The number of Petya's points in the game is the number of pairs of neighboring cubes of the same color in the line, the number of Vasya's points in the game is the number of neighbouring cubes of the different color in the line. Your task is to calculate the score at the end of the game (Petya's and Vasya's points, correspondingly), if both boys are playing optimally well. To "play optimally well" first of all means to maximize the number of one's points, and second — to minimize the number of the opponent's points.

-----Input-----

The only line contains two space-separated integers n and m (1 ≤ n, m ≤ 10^5) — the number of red and blue cubes, correspondingly.

-----Output-----

On a single line print two space-separated integers — the number of Petya's and Vasya's points correspondingly provided that both players play optimally well.

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

Output
2 1

Input
2 4

Output
3 2

-----Note-----

In the first test sample the optimal strategy for Petya is to put the blue cube in the line. After that there will be only red cubes left, so by the end of the game the line of cubes from left to right will look as [blue, red, red, red]. So, Petya gets 2 points and Vasya gets 1 point.

If Petya would choose the red cube during his first move, then, provided that both boys play optimally well, Petya would get 1 point and Vasya would get 2 points.

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

a, b = map(int, input().split())
print(a + b - 1 - min(a, b), min(a, b))


I found an interesting problem on https://codeforces.com/problemset/problem/257/C:
Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this angle.

As you spend lots of time "glued to the screen", your vision is impaired. So you have to write a program that will pass the check for you.

-----Input-----

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

Next n lines contain two space-separated integers each: x_{i}, y_{i} (|x_{i}|, |y_{i}| ≤ 1000) — the coordinates of the i-th mannequin. It is guaranteed that the origin of the coordinates has no mannequin. It is guaranteed that no two mannequins are located in the same point on the plane.

-----Output-----

Print a single real number — the value of the sought angle in degrees. The answer will be considered valid if the relative or absolute error doesn't exceed 10^{ - 6}.

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

Output
90.0000000000

Input
3
2 0
0 2
-2 2

Output
135.0000000000

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

Output
270.0000000000

Input
2
2 1
1 2

Output
36.8698976458

-----Note-----

Solution for the first sample test is shown below:  [Image]

Solution for the second sample test is shown below:  [Image]

Solution for the third sample test is shown below:  [Image]

Solution for the fourth sample test is shown below:  $\#$

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

import math

n = int(input())

coors = [[int(item) for item in input().split(' ')] for i in range(n)]

def get_pos(item):
    (x, y) = item

    deg = math.degrees(math.atan(abs(math.inf if x == 0 else y / x)))

    if y < 0:
        if x >= 0:
            return 360 - deg
        else:
            return 180 + deg
    else:
        if x >= 0:
            return deg
        else:
            return 180 - deg

angles = [get_pos(item) for item in coors]

angles.sort()

t = [angles[0] + 360 - angles[-1]]

for i in range(1, n):
    t.append(angles[i] - angles[i - 1])

print(360 - max(t))


I found an interesting problem on https://codeforces.com/problemset/problem/257/D:
Vasya has found a piece of paper with an array written on it. The array consists of n integers a_1, a_2, ..., a_{n}. Vasya noticed that the following condition holds for the array a_{i} ≤ a_{i} + 1 ≤ 2·a_{i} for any positive integer i (i < n).

Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a_1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the size of the array. The second line contains space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — the original array.

It is guaranteed that the condition a_{i} ≤ a_{i} + 1 ≤ 2·a_{i} fulfills for any positive integer i (i < n).

-----Output-----

In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number a_{i}. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a_1. If there are multiple solutions, you are allowed to print any of them.

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

Output
+++-
Input
3
3 3 5

Output
++-

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

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

temp_sgn=1
sgns=[]
curr_sum=0
for i in range(n):
	if(curr_sum>=a[n-i-1]):
		sgns.append(1)
		sgns.append(-1)
		curr_sum-=a[n-i-1]
	else:
		sgns.append(-1)
		sgns.append(1)
		curr_sum-=a[n-i-1]
		curr_sum*=-1
sgns.reverse()
ans=[]
for i in range(2*n):
	if(i%2==0):
		ans.append(temp_sgn*sgns[i])
	else:
		temp_sgn*=sgns[i]
for x in ans:
	if(x==1):
		print('+',end='')
	else:
		print('-',end='')


I found an interesting problem on https://codeforces.com/problemset/problem/259/A:
The Little Elephant loves chess very much.

One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8 × 8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doesn't have any side-adjacent cells with the same color and the upper left cell is white. To play chess, they want to make the board they have a proper chessboard. For that the friends can choose any row of the board and cyclically shift the cells of the chosen row, that is, put the last (rightmost) square on the first place in the row and shift the others one position to the right. You can run the described operation multiple times (or not run it at all).

For example, if the first line of the board looks like that "BBBBBBWW" (the white cells of the line are marked with character "W", the black cells are marked with character "B"), then after one cyclic shift it will look like that "WBBBBBBW".

Help the Little Elephant and his friend to find out whether they can use any number of the described operations to turn the board they have into a proper chessboard.

-----Input-----

The input consists of exactly eight lines. Each line contains exactly eight characters "W" or "B" without any spaces: the j-th character in the i-th line stands for the color of the j-th cell of the i-th row of the elephants' board. Character "W" stands for the white color, character "B" stands for the black color.

Consider the rows of the board numbered from 1 to 8 from top to bottom, and the columns — from 1 to 8 from left to right. The given board can initially be a proper chessboard.

-----Output-----

In a single line print "YES" (without the quotes), if we can make the board a proper chessboard and "NO" (without the quotes)...

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

board = []
for cont in range(0,8):
    board.append(input())
l = True
for row in board:
    for cont in range(0,7):
        if row[cont] == row[cont+1]:
            l = False
            break
    if l is False:
        break

if l:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/259/B:
Little Elephant loves magic squares very much.

A magic square is a 3 × 3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15. $\left. \begin{array}{|c|c|c|} \hline 4 & {9} & {2} \\ \hline 3 & {5} & {7} \\ \hline 8 & {1} & {6} \\ \hline \end{array} \right.$

The Little Elephant remembered one magic square. He started writing this square on a piece of paper, but as he wrote, he forgot all three elements of the main diagonal of the magic square. Fortunately, the Little Elephant clearly remembered that all elements of the magic square did not exceed 10^5.

Help the Little Elephant, restore the original magic square, given the Elephant's notes.

-----Input-----

The first three lines of the input contain the Little Elephant's notes. The first line contains elements of the first row of the magic square. The second line contains the elements of the second row, the third line is for the third row. The main diagonal elements that have been forgotten by the Elephant are represented by zeroes.

It is guaranteed that the notes contain exactly three zeroes and they are all located on the main diagonal. It is guaranteed that all positive numbers in the table do not exceed 10^5.

-----Output-----

Print three lines, in each line print three integers — the Little Elephant's magic square. If there are multiple magic squares, you are allowed to print any of them. Note that all numbers you print must be positive and not exceed 10^5.

It is guaranteed that there exists at least one magic square that meets the conditions.

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

Output
1 1 1
1 1 1
1 1 1

Input
0 3 6
5 0 5
4 7 0

Output
6 3 6
5 5 5
4 7 4

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/260/C:
Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.

Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i + 1, i + 2, i + 3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i = n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on.

For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i = 3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4, 1, 2, 3, 4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.

At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x — the number of the box, where he put the last of the taken out balls.

He asks you to help to find the initial arrangement of the balls in the boxes.

-----Input-----

The first line of the input contains two integers n and x (2 ≤ n ≤ 10^5, 1 ≤ x ≤ n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a_1, a_2, ..., a_{n}, where integer a_{i} (0 ≤ a_{i} ≤ 10^9, a_{x} ≠ 0) represents the number of balls in the box with index i after Vasya completes all the actions.

Please, do not use...

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

n, x = map(int, input().split())
t = list(map(int, input().split()))
m = min(t[: x])
if m == 0:
    i = x - 1
    while t[i]: i -= 1
    t[i + 1: x] = [j - 1 for j in t[i + 1: x]]
    t[i] = x - i - 1
else:
    t[: x] = [i - 1 for i in t[: x]]
    m = min(t)
    if m: t = [i - m for i in t]
    i = n - 1
    while t[i]: i -= 1
    t[i + 1: ] = [j - 1 for j in t[i + 1: ]]
    t[i] = x + m * n + n - i - 1
print(' '.join(map(str, t)))


I found an interesting problem on https://codeforces.com/problemset/problem/261/B:
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters.

Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (a_{i}) represents the number of meters the guest is going to take up if he sits at the restaurant table.

Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than p. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table.

Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible n! orders of guests in the queue. Help Maxim, calculate this number.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 50) — the number of guests in the restaurant. The next line contains integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 50) — the guests' sizes in meters. The third line contains integer p (1 ≤ p ≤ 50) — the table's length in meters.

The numbers in the lines are separated by single spaces.

-----Output-----

In a single line print a real number — the answer to the problem. The answer will be considered correct, if the absolute or relative error doesn't exceed 10^{ - 4}.

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

Output
1.3333333333

-----Note-----

In the first sample the people will come in the following orders:   (1, 2, 3) — there will be two people in the restaurant;  (1, 3, 2) — there will be one person in the restaurant;  (2,...

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

import math

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

sum=0;
for x in range(n):
	sum+=a[x]
if(sum<=p):
	print(n)
else:
	ans=0
	for i in range(n):
		dp = [[[0 for z in range(55)] for y in range(55)] for x in range(55)]
		dp[-1][0][0]=1
		for j in range(n):
			if(j==i):

				for k in range(n):
					for z in range(p+1):
						dp[j][k][z]=dp[j-1][k][z]
				continue

			for k in range(n):

				for z in range(p+1):

					if(z+a[j]<=p):
						dp[j][k+1][z+a[j]]+=dp[j-1][k][z]
					dp[j][k][z]+=dp[j-1][k][z]

		for k in range(n):
			for z in range(p+1):
				if(z+a[i]>p):
					ans+=k*dp[n-1][k][z]*math.factorial(k)*math.factorial(n-k-1)

	print(ans/math.factorial(n))


I found an interesting problem on https://codeforces.com/problemset/problem/261/C:
Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size (m + 1) × (m + 1):

[Image]

Maxim asks you to count, how many numbers m (1 ≤ m ≤ n) are there, such that the sum of values in the cells in the row number m + 1 of the resulting matrix equals t.

Expression (x xor y) means applying the operation of bitwise excluding "OR" to numbers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by character "^", in Pascal — by "xor".

-----Input-----

A single line contains two integers n and t (1 ≤ n, t ≤ 10^12, t ≤ n + 1).

Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

-----Output-----

In a single line print a single integer — the answer to the problem.

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

Output
1

Input
3 2

Output
1

Input
3 3

Output
0

Input
1000000000000 1048576

Output
118606527258

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

n, t = map(int, input().split())
s = bin(n + 2)[2:]
l = len(s)

if t & (t - 1):
    ans = 0
else:
    t = t.bit_length()
    f = [[0] * (l + 1) for i in range(l + 1)]
    for i in range(l + 1):
        f[i][0] = f[i][i] = 1
        for j in range(1, i):
            f[i][j] = f[i - 1][j - 1] + f[i - 1][j]

    ans = c = 0
    for i in range(l):
        if s[i] == '1':
            if t - c <= l - i - 1:
                ans += f[l - i - 1][t - c]
            c += 1
    if t == 1: ans -= 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/262/A:
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.

Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Roma's got n positive integers. He wonders, how many of those integers have not more than k lucky digits? Help him, write the program that solves the problem.

-----Input-----

The first line contains two integers n, k (1 ≤ n, k ≤ 100). The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the numbers that Roma has.

The numbers in the lines are separated by single spaces.

-----Output-----

In a single line print a single integer — the answer to the problem.

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

Output
3

Input
3 2
447 44 77

Output
2

-----Note-----

In the first sample all numbers contain at most four lucky digits, so the answer is 3.

In the second sample number 447 doesn't fit in, as it contains more than two lucky digits. All other numbers are fine, so the answer is 2.

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

n, k = map(int, input().split())
print(len([i for i in input().split() if i.count('4') + i.count('7') <= k]))


I found an interesting problem on https://codeforces.com/problemset/problem/262/B:
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.

Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.

The operation of changing a number's sign is the operation of multiplying this number by -1.

Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.

-----Input-----

The first line contains two integers n and k (1 ≤ n, k ≤ 10^5), showing, how many numbers are in the sequence and how many swaps are to be made.

The second line contains a non-decreasing sequence, consisting of n integers a_{i} (|a_{i}| ≤ 10^4).

The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.

-----Output-----

In the single line print the answer to the problem — the maximum total income that we can obtain after exactly k changes.

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

Output
3

Input
3 1
-1 -1 1

Output
1

-----Note-----

In the first sample we can get sequence [1, 1, 1], thus the total income equals 3.

In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.

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

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

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

c=0
for x in lis:
    if x<0:
        c+=1

if c==n:
    for i in range(n):
        if k==0:
            break
        k-=1
        lis[i]=-lis[i]
    if k%2==1:
        lis[n-1]=-(lis[n-1])
elif c==0:
    if k%2==1:
        lis[0]=-lis[0]
else:
    i=0
    while i in range(n):
        if lis[i]>0 or k==0:
            break
        k-=1
        lis[i]=-lis[i]
        i+=1
    if k%2==1:
        if lis[i]>lis[i-1]:
            lis[i-1]=-lis[i-1]
        else:
            lis[i]=-lis[i]

print(sum(lis))


I found an interesting problem on https://codeforces.com/problemset/problem/263/A:
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:  Swap two neighboring matrix rows, that is, rows with indexes i and i + 1 for some integer i (1 ≤ i < 5).  Swap two neighboring matrix columns, that is, columns with indexes j and j + 1 for some integer j (1 ≤ j < 5).

You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.

-----Input-----

The input consists of five lines, each line contains five integers: the j-th integer in the i-th line of the input represents the element of the matrix that is located on the intersection of the i-th row and the j-th column. It is guaranteed that the matrix consists of 24 zeroes and a single number one.

-----Output-----

Print a single integer — the minimum number of moves needed to make the matrix beautiful.

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

Output
3

Input
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0

Output
1

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

mat = [list(map(int, input().split())) for x in range(5)]

pos = (0,0)
mid = (2,2)

for i in range(5):
    for j in range(5):
        if mat[i][j] == 1:
            pos = i,j

res = abs(mid[0] - pos[0]), abs(mid[1] - pos[1])
print(sum(res))


I found an interesting problem on https://codeforces.com/problemset/problem/263/C:
One day Vasya came up to the blackboard and wrote out n distinct integers from 1 to n in some order in a circle. Then he drew arcs to join the pairs of integers (a, b) (a ≠ b), that are either each other's immediate neighbors in the circle, or there is number c, such that a and с are immediate neighbors, and b and c are immediate neighbors. As you can easily deduce, in the end Vasya drew 2·n arcs.

For example, if the numbers are written in the circle in the order 1, 2, 3, 4, 5 (in the clockwise direction), then the arcs will join pairs of integers (1, 2), (2, 3), (3, 4), (4, 5), (5, 1), (1, 3), (2, 4), (3, 5), (4, 1) and (5, 2).

Much time has passed ever since, the numbers we wiped off the blackboard long ago, but recently Vasya has found a piece of paper with 2·n written pairs of integers that were joined with the arcs on the board. Vasya asks you to find the order of numbers in the circle by these pairs.

-----Input-----

The first line of the input contains a single integer n (5 ≤ n ≤ 10^5) that shows, how many numbers were written on the board. Next 2·n lines contain pairs of integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}) — the numbers that were connected by the arcs.

It is guaranteed that no pair of integers, connected by a arc, occurs in the input more than once. The pairs of numbers and the numbers in the pairs are given in the arbitrary order.

-----Output-----

If Vasya made a mistake somewhere and there isn't any way to place numbers from 1 to n on the circle according to the statement, then print a single number "-1" (without the quotes). Otherwise, print any suitable sequence of n distinct integers from 1 to n.

If there are multiple solutions, you are allowed to print any of them. Specifically, it doesn't matter which number you write first to describe the sequence of the order. It also doesn't matter whether you write out the numbers in the clockwise or counter-clockwise direction.

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

Output
1 2 3 4 5...

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

#!/usr/local/bin/python3

import sys

DEBUG = '-d' in sys.argv

def debug(*args, **kwargs):
    if DEBUG:
        print(*args, file=sys.stderr, **kwargs)

    return None

def main():
    n = int(input())

    cnt = [0] * (n + 1)
    edge = []

    for i in range(0, n + 1):
        edge.append(set())

    for i in range(0, 2 * n):
        s, t = map(int, input().split())
        edge[s].add(t)
        edge[t].add(s)
        cnt[s] += 1
        cnt[t] += 1

    c4 = 0
    for i in range(1, n + 1):
        if cnt[i] == 4:
            c4 += 1

    if c4 != n:
        print(-1)
    else:
        for v2 in edge[1]:
            for v3 in edge[1]:
                if v2 in edge[v3]:
                    mark = [True] * (n + 1)
                    mark[1] = False
                    mark[v2] = False
                    res = [1, v2]
                    i = v3
                    try:
                        while True:
                            res.append(i)
                            mark[i] = False
                            if len(res) == n:
                                print(' '.join([str(x) for x in res]))
                                return
                            for e in edge[i]:
                                if e != i and mark[e] and res[-2] in edge[e]:
                                    i = e
                                    break
                            if not mark[i]:
                                raise StopIteration
                    except StopIteration:
                        pass

        print(-1)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/263/D:
You've got a undirected graph G, consisting of n nodes. We will consider the nodes of the graph indexed by integers from 1 to n. We know that each node of graph G is connected by edges with at least k other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least k + 1.

A simple cycle of length d (d > 1) in graph G is a sequence of distinct graph nodes v_1, v_2, ..., v_{d} such, that nodes v_1 and v_{d} are connected by an edge of the graph, also for any integer i (1 ≤ i < d) nodes v_{i} and v_{i} + 1 are connected by an edge of the graph.

-----Input-----

The first line contains three integers n, m, k (3 ≤ n, m ≤ 10^5; 2 ≤ k ≤ n - 1) — the number of the nodes of the graph, the number of the graph's edges and the lower limit on the degree of the graph node. Next m lines contain pairs of integers. The i-th line contains integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}) — the indexes of the graph nodes that are connected by the i-th edge.

It is guaranteed that the given graph doesn't contain any multiple edges or self-loops. It is guaranteed that each node of the graph is connected by the edges with at least k other nodes of the graph.

-----Output-----

In the first line print integer r (r ≥ k + 1) — the length of the found cycle. In the next line print r distinct integers v_1, v_2, ..., v_{r} (1 ≤ v_{i} ≤ n) — the found simple cycle.

It is guaranteed that the answer exists. If there are multiple correct answers, you are allowed to print any of them.

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

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

Output
4
3 4 1 2

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

def f():
    n, m, k = map(int, input().split())
    p = [[] for i in range(n + 1)]
    for i in range(m):
        a, b = map(int, input().split())
        p[a].append(b)
        p[b].append(a)
    t, r = [0] * (n + 1), [1]
    x = t[1] = 1
    i = 0 - k
    while True:
        for y in p[x]:
            if t[y] == 2: return r[r.index(y): ]
            if t[y]: continue
            t[y], x = 1, y
            r.append(x)
            i += 1
            if i >= 0: t[r[i]] = 2
            break
t = f()
print(len(t))
print(' '.join(map(str, t)))


I found an interesting problem on https://codeforces.com/problemset/problem/264/B:
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a_1, a_2, ..., a_{n} are good.

Now she is interested in good sequences. A sequence x_1, x_2, ..., x_{k} is called good if it satisfies the following three conditions:  The sequence is strictly increasing, i.e. x_{i} < x_{i} + 1 for each i (1 ≤ i ≤ k - 1).  No two adjacent elements are coprime, i.e. gcd(x_{i}, x_{i} + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).  All elements of the sequence are good integers.

Find the length of the longest good sequence.

-----Input-----

The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of good integers. The second line contains a single-space separated list of good integers a_1, a_2, ..., a_{n} in strictly increasing order (1 ≤ a_{i} ≤ 10^5; a_{i} < a_{i} + 1).

-----Output-----

Print a single integer — the length of the longest good sequence.

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

Output
4

Input
9
1 2 3 5 6 7 8 9 10

Output
4

-----Note-----

In the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4.

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

n = int(input())
a = list(map(int, input().split()))
dp = [1] * (n + 5)
tmax = [0 for _ in range(100005)]
p = [[] for _ in range(100005)]
p[1] = [1]
for i in range(2, 100001):
    if p[i]==[]:
        for j in range(i, 100001, i):
            p[j].append(i)

for i in range(len(a)):
    dp[i] = max(tmax[j] for j in p[a[i]]) + 1
    for j in p[a[i]]: tmax[j] = max(tmax[j], dp[i])
print(max(dp))


I found an interesting problem on https://codeforces.com/problemset/problem/265/A:
There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string s. The i-th (1-based) character of s represents the color of the i-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively.

Initially Squirrel Liss is standing on the first stone. You perform instructions one or more times.

Each instruction is one of the three types: "RED", "GREEN", or "BLUE". After an instruction c, if Liss is standing on a stone whose colors is c, Liss will move one stone forward, else she will not move.

You are given a string t. The number of instructions is equal to the length of t, and the i-th character of t represents the i-th instruction.

Calculate the final position of Liss (the number of the stone she is going to stand on in the end) after performing all the instructions, and print its 1-based position. It is guaranteed that Liss don't move out of the sequence.

-----Input-----

The input contains two lines. The first line contains the string s (1 ≤ |s| ≤ 50). The second line contains the string t (1 ≤ |t| ≤ 50). The characters of each string will be one of "R", "G", or "B". It is guaranteed that Liss don't move out of the sequence.

-----Output-----

Print the final 1-based position of Liss in a single line.

-----Examples-----
Input
RGB
RRR

Output
2

Input
RRRBGBRBBB
BBBRR

Output
3

Input
BRRBGBRGRBGRGRRGGBGBGBRGBRGRGGGRBRRRBRBBBGRRRGGBBB
BBRBGGRGRGBBBRBGRBRBBBBRBRRRBGBBGBBRRBBGGRBRRBRGRB

Output
15

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

str1=input()
str2=input()
cpos=0

for i in str2:
    if i==str1[cpos]:
        cpos+=1

print(cpos+1)


I found an interesting problem on https://codeforces.com/problemset/problem/265/B:
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is h_{i}. Liss wants to eat all nuts.

Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:  Walk up or down one unit on a tree.  Eat a nut on the top of the current tree.  Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h > h_{i} + 1.

Compute the minimal time (in seconds) required to eat all nuts.

-----Input-----

The first line contains an integer n (1  ≤  n ≤ 10^5) — the number of trees.

Next n lines contains the height of trees: i-th line contains an integer h_{i} (1 ≤ h_{i} ≤ 10^4) — the height of the tree with the number i.

-----Output-----

Print a single integer — the minimal time required to eat all nuts in seconds.

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

Output
5

Input
5
2
1
2
1
1

Output
14

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

n = int(input())
cur = 0
sum = 0
for i in range(n):
  nxt = int(input())
  sum += abs(nxt - cur)
  cur = nxt
  sum += 1
  if i + 1 < n: sum += 1
print (sum)


I found an interesting problem on https://codeforces.com/problemset/problem/266/A:
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table.

The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue.

-----Output-----

Print a single integer — the answer to the problem.

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

Output
1

Input
5
RRRRR

Output
4

Input
4
BRBG

Output
0

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

n = int( input().split()[0] )
s = input().split()[0]
c = 'A'
answer = 0
for i in range( 0, len( s ) ):
	if s[i] != c:
		answer += 1
	c = s[i]
print( n - answer )


I found an interesting problem on https://codeforces.com/problemset/problem/266/B:
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each second.

Let's describe the process more precisely. Let's say that the positions in the queue are sequentially numbered by integers from 1 to n, at that the person in the position number 1 is served first. Then, if at time x a boy stands on the i-th position and a girl stands on the (i + 1)-th position, then at time x + 1 the i-th position will have a girl and the (i + 1)-th position will have a boy. The time is given in seconds.

You've got the initial position of the children, at the initial moment of time. Determine the way the queue is going to look after t seconds.

-----Input-----

The first line contains two integers n and t (1 ≤ n, t ≤ 50), which represent the number of children in the queue and the time after which the queue will transform into the arrangement you need to find.

The next line contains string s, which represents the schoolchildren's initial arrangement. If the i-th position in the queue contains a boy, then the i-th character of string s equals "B", otherwise the i-th character equals "G".

-----Output-----

Print string a, which describes the arrangement after t seconds. If the i-th position has a boy after the needed time, then the i-th character a must equal "B", otherwise it must equal "G".

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

Output
GBGGB

Input
5 2
BGGBG

Output
GGBGB

Input
4 1
GGGB

Output
GGGB

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

n,k=[ int(x) for x in input().split(' ') ]
current=input()

def turn(str):
	temp=list(str)
	for i in range(1,len(str)) :
		if str[i] == 'G' and str[i-1] == 'B' :
			temp[i-1]='G'
			temp[i]='B'
	ret=''
	for i in temp :
		ret+=i
	return ret

for i in range(k):
	current=turn(current)

print(current)


I found an interesting problem on https://codeforces.com/problemset/problem/267/A:
You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).

You've got some number of pairs (a_{i}, b_{i}). How many operations will be performed for each of them?

-----Input-----

The first line contains the number of pairs n (1  ≤  n  ≤  1000). Then follow n lines, each line contains a pair of positive integers a_{i}, b_{i} (1  ≤  a_{i},  b_{i}  ≤  10^9).

-----Output-----

Print the sought number of operations for each pair on a single line.

-----Examples-----
Input
2
4 17
7 987654321

Output
8
141093479

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

__author__ = 'markdaniel'

def main():
    num1, num2 = [int(x) for x in input().split(' ')]
    maxval = max(num1, num2)
    minval = min(num1, num2)
    ops = 0
    while maxval > 0 and minval > 0:
        remainderMultiple = ((maxval - minval) // minval)
        maxval -= remainderMultiple * minval
        ops += remainderMultiple
        maxval -= minval
        ops += 1
        if maxval < minval:
            temp = maxval
            maxval = minval
            minval = temp

    return ops

def __starting_point():
    cases = int(input())
    for i in range(cases):
        print(main())
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/268/A:
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.

There are n teams taking part in the national championship. The championship consists of n·(n - 1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.

You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.

-----Input-----

The first line contains an integer n (2 ≤ n ≤ 30). Each of the following n lines contains a pair of distinct space-separated integers h_{i}, a_{i} (1 ≤ h_{i}, a_{i} ≤ 100) — the colors of the i-th team's home and guest uniforms, respectively.

-----Output-----

In a single line print the number of games where the host team is going to play in the guest uniform.

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

Output
1

Input
4
100 42
42 100
5 42
100 5

Output
5

Input
2
1 2
1 2

Output
0

-----Note-----

In the first test case the championship consists of 6 games. The only game with the event in question is the game between teams 2 and 1 on the stadium of team 2.

In the second test sample the host team will have to wear guest uniform in the games between teams: 1 and 2, 2 and 1, 2 and 3, 3 and 4, 4 and 2 (the host team is written first).

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

n = int(input())
a, b = [0] * n, [0] * n

for i in range(n):
    a[i], b[i] = list(map(int, input().split()))
s = 0
for j in a:
    s += b.count(j)
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/268/B:
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequence), or all pressed buttons return to the initial position. When all buttons are pressed into the lock at once, the lock opens.

Consider an example with three buttons. Let's say that the opening sequence is: {2, 3, 1}. If you first press buttons 1 or 3, the buttons unpress immediately. If you first press button 2, it stays pressed. If you press 1 after 2, all buttons unpress. If you press 3 after 2, buttons 3 and 2 stay pressed. As soon as you've got two pressed buttons, you only need to press button 1 to open the lock.

Manao doesn't know the opening sequence. But he is really smart and he is going to act in the optimal way. Calculate the number of times he's got to push a button in order to open the lock in the worst-case scenario.

-----Input-----

A single line contains integer n (1 ≤ n ≤ 2000) — the number of buttons the lock has.

-----Output-----

In a single line print the number of times Manao has to push a button in the worst-case scenario.

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

Output
3

Input
3

Output
7

-----Note-----

Consider the first test sample. Manao can fail his first push and push the wrong button. In this case he will already be able to guess the right one with his second push. And his third push will push the second right button. Thus, in the worst-case scenario he will only need 3 pushes.

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

n = int(input())
print((n*n + 5)*n // 6)


I found an interesting problem on https://codeforces.com/problemset/problem/268/C:
Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions:  The coordinates of each point in the set are integers.  For any two points from the set, the distance between them is a non-integer.

Consider all points (x, y) which satisfy the inequations: 0 ≤ x ≤ n; 0 ≤ y ≤ m; x + y > 0. Choose their subset of maximum size such that it is also a beautiful set of points.

-----Input-----

The single line contains two space-separated integers n and m (1 ≤ n, m ≤ 100).

-----Output-----

In the first line print a single integer — the size k of the found beautiful set. In each of the next k lines print a pair of space-separated integers — the x- and y- coordinates, respectively, of a point from the set.

If there are several optimal solutions, you may print any of them.

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

Output
3
0 1
1 2
2 0

Input
4 3

Output
4
0 3
2 1
3 0
4 2

-----Note-----

Consider the first sample. The distance between points (0, 1) and (1, 2) equals $\sqrt{2}$, between (0, 1) and (2, 0) — $\sqrt{5}$, between (1, 2) and (2, 0) — $\sqrt{5}$. Thus, these points form a beautiful set. You cannot form a beautiful set with more than three points out of the given points. Note that this is not the only solution.

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

'''
def main():
	from sys import stdin,stdout
def __starting_point():
	main()
'''
#Journey to moon
'''
def main():
	from sys import stdin,stdout
	import collections
	N,I =map(int,stdin.readline().split())
	visited=list(0 for x in range(N))
	G=collections.defaultdict(list)
	groups=[0]
	for _ in range(I):
		a,b=map(int,stdin.readline().split())
		G[a].append(b)
		G[b].append(a)
	q=collections.deque()
	flag=0
	for i in range(N):
		if not visited[i]:
			q.append(i)
			visited[i]=flag+1
			groups[flag]+=1
			while len(q):
				top=q.popleft()
				for j in G[top]:
					if visited[j]!=visited[top]:
						visited[j]=flag+1
						groups[flag]+=1
						q.append(j)
			flag+=1
			groups.append(0)
	counter=0
	for i in range(len(groups)-1):
		for j in range(i+1,len(groups)):
			counter+=groups[i]*groups[j]
	stdout.write(str(counter))
def __starting_point():
	main()
'''
#Djikstra's
'''
import collections
class Graph:
	def __init__(self):
		self.nodes=set()
		self.edges=collections.defaultdict(list)
		self.distances = {}

	def add_node(self, value):
		self.nodes.add(value)

	def add_edge(self, from_node, to_node, distance):
		self.edges[from_node].append(to_node)
		self.edges[to_node].append(from_node)
		self.distances[(from_node, to_node)] = distance
		self.distances[(to_node, from_node)] = distance

def dijsktra(graph, initial):
	visited = {initial: 0}
	path = {}

	nodes = set(graph.nodes)

	while nodes:
		min_node = None
		for node in nodes:
			if node in visited:
				if min_node is None:
					min_node = node
				elif visited[node] < visited[min_node]:
					min_node = node

		if min_node is None:
			break

		nodes.remove(min_node)
		current_weight = visited[min_node]

		for edge in graph.edges[min_node]:
			weight = current_weight + graph.distances[(min_node, edge)]
			if edge not in visited or weight < visited[edge]:
				visited[edge] = weight
				path[edge] = min_node

	return visited, path

def main():
	from sys import stdin,stdout
	for _ in...


I found an interesting problem on https://codeforces.com/problemset/problem/269/A:
Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.

From the top view each magical box looks like a square with side length equal to 2^{k} (k is an integer, k ≥ 0) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2^{k} - 1 into one box of side length 2^{k}, or as in the following figure:

 [Image]

Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes.

-----Input-----

The first line of input contains an integer n (1 ≤ n ≤ 10^5), the number of different sizes of boxes Emuskald has. Each of following n lines contains two integers k_{i} and a_{i} (0 ≤ k_{i} ≤ 10^9, 1 ≤ a_{i} ≤ 10^9), which means that Emuskald has a_{i} boxes with side length 2^{k}_{i}. It is guaranteed that all of k_{i} are distinct.

-----Output-----

Output a single integer p, such that the smallest magical box that can contain all of Emuskald’s boxes has side length 2^{p}.

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

Output
3

Input
1
0 4

Output
1

Input
2
1 10
2 2

Output
3

-----Note-----

Picture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture.

In the second test case, we can put all four small boxes into a box with side length 2.

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

import copy
import itertools
import string
import sys

###

def powmod(x, p, m):
	if p <= 0:
		return 1
	if p <= 1:
		return x%m
	return powmod(x*x%m, p//2, m) * (x%m)**(p%2) % m

###

def to_basex(num, x):
	while num > 0:
		yield num % x
		num //= x

def from_basex(it, x):
	ret = 0
	p = 1
	for d in it:
		ret += d*p
		p *= x
	return ret

###

def l4(x):
	ret = 1
	while x > 4:
		ret += 1
		x += 3
		x //= 4
	return ret

def core():
	n = int(input())
	# print(n)
	ans = 0
	for _ in range(n):
		k, a = (int(x) for x in input().split())
		# print(k, a)

		ans = max(ans, l4(a) + k)
	print(ans)

core()


I found an interesting problem on https://codeforces.com/problemset/problem/269/B:
Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length.

Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line.

Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left.

Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders.

-----Input-----

The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 5000, n ≥ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number s_{i} (1 ≤ s_{i} ≤ m), and one real number x_{i} (0 ≤ x_{i} ≤ 10^9), the species and position of the i-th plant. Each x_{i} will contain no more than 6 digits after the decimal point.

It is guaranteed that all x_{i} are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their x_{i} coordinates (x_{i} < x_{i} + 1, 1 ≤ i < n).

-----Output-----

Output a single integer — the minimum number of plants to be replanted.

-----Examples-----
Input
3 2
2 1
1 2.0
1 3.100

Output
1

Input
3 3
1 5.0
2 5.5
3 6.0

Output
0

Input
6 3
1 14.284235
2...

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

import math
import sys
input=sys.stdin.readline
#t=int(input())
t=1
for _ in range(t):
    #n=int(input())
    n,m=list(map(int,input().split()))
    #l=list(map(int,input().split()))
    l=[]
    for __ in range(n):
        s,x=list(map(float,input().split()))
        l.append(int(s))
    dp=[0]*(n+1)
    for i in range(n):
        j=l[i]
        for j1 in range(j,-1,-1):
            dp[j]=max(dp[j],1+dp[j1])
    maxi=max(dp[:])
    print(n-maxi)


I found an interesting problem on https://codeforces.com/problemset/problem/270/A:
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.

He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.

Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a?

-----Input-----

The first line of input contains an integer t (0 < t < 180) — the number of tests. Each of the following t lines contains a single integer a (0 < a < 180) — the angle the robot can make corners at measured in degrees.

-----Output-----

For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible.

-----Examples-----
Input
3
30
60
90

Output
NO
YES
YES

-----Note-----

In the first test case, it is impossible to build the fence, since there is no regular polygon with angle $30^{\circ}$.

In the second test case, the fence is a regular triangle, and in the last test case — a square.

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

for i in range(int(input())):print('NO' if 360%(180-int(input())) else 'YES')


I found an interesting problem on https://codeforces.com/problemset/problem/270/B:
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.

Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.

Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the a_{i}-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.

Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold:   thread x is not updated (it has no new messages);  the list order 1, 2, ..., n changes to a_1, a_2, ..., a_{n}.

-----Input-----

The first line of input contains an integer n, the number of threads (1 ≤ n ≤ 10^5). The next line contains a list of n space-separated integers a_1, a_2, ..., a_{n} where a_{i} (1 ≤ a_{i} ≤ n) is the old position of the i-th thread in the new list. It is guaranteed that all of the a_{i} are distinct.

-----Output-----

Output a single integer — the number of threads that surely contain a new message.

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

Output
2

Input
3
1 2 3

Output
0

Input
4
4 3 2 1

Output
3

-----Note-----

In the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.

In the second test case, there may be no new messages at all, since the thread order hasn't...

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

n=int(input())
l=[int(i) for i in input().split()]
ans=0
f=0
#l.insert0(10000000000000,0)
for i in range(n-1,0,-1):
    if l[i]<l[i-1]:
        print(i)
        f=1
        break
if not f:
    print(f)


I found an interesting problem on https://codeforces.com/problemset/problem/271/A:
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.

Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.

-----Input-----

The single line contains integer y (1000 ≤ y ≤ 9000) — the year number.

-----Output-----

Print a single integer — the minimum year number that is strictly larger than y and all it's digits are distinct. It is guaranteed that the answer exists.

-----Examples-----
Input
1987

Output
2013

Input
2013

Output
2014

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

for i in range(int(input()) + 1, 10000):
    if len(set(list(str(i)))) == 4:
        print(i)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/271/B:
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.

You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not.

A matrix is prime if at least one of the two following conditions fulfills:  the matrix has a row with prime numbers only;  the matrix has a column with prime numbers only;

Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.

-----Input-----

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

Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 10^5.

The numbers in the lines are separated by single spaces.

-----Output-----

Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.

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

Output
1

Input
2 3
4 8 8
9 2 9

Output
3

Input
2 2
1 3
4 2

Output
0

-----Note-----

In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.

In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.

In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.

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

from bisect import bisect_left

def sieve(r):
    D = dict()
    yield 2
    for q in range(3,r,2):
        p = D.pop(q, None)
        if not p:
            D[q*q] = q
            yield q
        else:
            x = p + q
            while x in D or not (x&1):
                x += p
            D[x] = p

primes = list(sieve(1000003))
II = lambda: list(map(int, input().split()))
n,m = II()
grid = [[primes[bisect_left(primes, x)] - x for x in II()] for _ in range(n)]
print(min(min(sum(row) for row in grid), min(sum(col) for col in zip(*grid))))


I found an interesting problem on https://codeforces.com/problemset/problem/271/C:
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set U_{i} = (u_{i}, 1, u_{i}, 2, ..., u_{i}, |U_{i}|). Here and below we'll presuppose that the set elements are written in the increasing order.

We'll say that the secret is safe if the following conditions are hold:  for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets U_{i} and U_{j} is an empty set;  the union of sets U_1, U_2, ..., U_{k} is set (1, 2, ..., n);  in each set U_{i}, its elements u_{i}, 1, u_{i}, 2, ..., u_{i}, |U_{i}| do not form an arithmetic progression (in particular, |U_{i}| ≥ 3 should hold).

Let us remind you that the elements of set (u_1, u_2, ..., u_{s}) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills u_{i} + d = u_{i} + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.

Your task is to find any partition of the set of words into subsets U_1, U_2, ..., U_{k} so that the secret is safe. Otherwise indicate that there's no such partition.

-----Input-----

The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 10^6) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.

-----Output-----

If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret.

If there are multiple solutions, print any of them.

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

Output
3 1 2 1 1 2 3 2 2 3 1

Input
5 2

Output
-1

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

n,k=map(int,input().split())
if n//k <3:
    print("-1")
    return
ans=list()
for i in range(n):
    if i<2*k:
        ans.append(i // 2 + 1)
    elif (i//k)%2==0:
        ans.append(i%k+1)
    else :
        ans.append(k-i%k)
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/271/D:
You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad.

A substring s[l...r] (1 ≤ l ≤ r ≤ |s|) of string s  =  s_1s_2...s_{|}s| (where |s| is the length of string s) is string  s_{l}s_{l} + 1...s_{r}.

The substring s[l...r] is good, if among the letters  s_{l}, s_{l} + 1, ..., s_{r} there are at most k bad ones (look at the sample's explanation to understand it more clear).

Your task is to find the number of distinct good substrings of the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their content is different, i.e. s[x...y] ≠ s[p...q].

-----Input-----

The first line of the input is the non-empty string s, consisting of small English letters, the string's length is at most 1500 characters.

The second line of the input is the string of characters "0" and "1", the length is exactly 26 characters. If the i-th character of this string equals "1", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on.

The third line of the input consists a single integer k (0 ≤ k ≤ |s|) — the maximum acceptable number of bad characters in a good substring.

-----Output-----

Print a single integer — the number of distinct good substrings of string s.

-----Examples-----
Input
ababab
01000000000000000000000000
1

Output
5

Input
acbacbacaa
00000000000000000000000000
2

Output
8

-----Note-----

In the first example there are following good substrings: "a", "ab", "b", "ba", "bab".

In the second example there are following good substrings: "a", "aa", "ac", "b", "ba", "c", "ca", "cb".

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

s = input()
a = input()
k = int(input())
S=sorted(s[i:] for i in range(len(s)))
p=''
r=0
for e in S:
    t=0
    s=0
    for i in range(len(e)):
        if i >= len(p) or e[i] != p[i]:
          s=1
        if a[ord(e[i])-ord('a')]=='0':
          t+=1
        if t > k:
          break
        if s:
          r+=1
    p = e
print(r)


I found an interesting problem on https://codeforces.com/problemset/problem/271/E:
There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top and b in the bottom as (a, b).

Each of the three horses can paint the special cards. If you show an (a, b) card to the gray horse, then the horse can paint a new (a + 1, b + 1) card. If you show an (a, b) card, such that a and b are even integers, to the white horse, then the horse can paint a new $(\frac{a}{2}, \frac{b}{2})$ card. If you show two cards (a, b) and (b, c) to the gray-and-white horse, then he can paint a new (a, c) card.

Polycarpus really wants to get n special cards (1, a_1), (1, a_2), ..., (1, a_{n}). For that he is going to the horse land. He can take exactly one (x, y) card to the horse land, such that 1 ≤ x < y ≤ m. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards?

Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires.

-----Input-----

The first line contains two integers n, m (1 ≤ n ≤ 10^5, 2 ≤ m ≤ 10^9). The second line contains the sequence of integers a_1, a_2, ..., a_{n} (2 ≤ a_{i} ≤ 10^9). Note, that the numbers in the sequence can coincide.

The numbers in the lines are separated by single spaces.

-----Output-----

Print a single integer — the answer to the problem.

Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

Output
11

Input
1 6
7

Output
14

Input
2 10
13 7

Output
36

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

# written with help of editorial
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

g = 0
for x in a:
    g = gcd(g, x - 1)

answer = 0

def process(x):
    nonlocal answer
    if x % 2 == 0:
        return 0
    for i in range(30):
        v = 2 ** i * x
        if v > m:
            break
        answer += m - v

for i in range(1, g + 1):
    if i * i > g:
        break
    if g % i:
        continue
    process(i)
    if i * i != g:
        process(g // i)

print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/272/A:
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.

To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.

For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.

Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100) — the number of Dima's friends. Dima himself isn't considered to be his own friend. The second line contains n positive integers, not exceeding 5, representing, how many fingers the Dima's friends will show.

The numbers in the lines are separated by a single space.

-----Output-----

In a single line print the answer to the problem.

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

Output
3

Input
1
2

Output
2

Input
2
3 5

Output
3

-----Note-----

In the first sample Dima can show 1, 3 or 5 fingers. If Dima shows 3 fingers, then the counting-out will go like that: Dima, his friend, Dima, his friend.

In the second sample Dima can show 2 or 4 fingers.

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

sa=int(input())
sa2=input().split(' ')
sa3=[int(x) for x in sa2]
sumx=sum(sa3)

t=0
for sa4 in range(1, 6):
    if (sumx+sa4)%(sa+1)!=1:
        t+=1
print(t)


I found an interesting problem on https://codeforces.com/problemset/problem/272/B:
Dima got into number sequences. Now he's got sequence a_1, a_2, ..., a_{n}, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence:  f(0) = 0;  f(2·x) = f(x);  f(2·x + 1) = f(x) + 1.

Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤ n) are there, such that f(a_{i}) = f(a_{j}). Help him, count the number of such pairs.

-----Input-----

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

The numbers in the lines are separated by single spaces.

-----Output-----

In a single line print the answer to the problem.

Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

Output
3

Input
3
5 3 1

Output
1

-----Note-----

In the first sample any pair (i, j) will do, so the answer is 3.

In the second sample only pair (1, 2) will do.

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

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

def f( n ):
    return ( sum( [ 1  for i in n if i == '1' ] ) )

cnt = {}

for i in range( n ):
    tmp = f( bin( a[i] )[2:] )
    if tmp not in cnt:
        cnt[ tmp ] = 1
    else:
        cnt[ tmp ] += 1

#print( cnt )

ans = 0
for i in cnt:
    ans += int( cnt[i] * ( cnt[i] - 1 ) / 2 )

print( ans )


I found an interesting problem on https://codeforces.com/problemset/problem/272/C:
Dima's got a staircase that consists of n stairs. The first stair is at height a_1, the second one is at a_2, the last one is at a_{n} (1 ≤ a_1 ≤ a_2 ≤ ... ≤ a_{n}).

Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width w_{i} and height h_{i}. Dima throws each box vertically down on the first w_{i} stairs of the staircase, that is, the box covers stairs with numbers 1, 2, ..., w_{i}. Each thrown box flies vertically down until at least one of the two following events happen:  the bottom of the box touches the top of a stair;  the bottom of the box touches the top of a box, thrown earlier.

We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width w_{i} cannot touch the stair number w_{i} + 1.

You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the number of stairs in the staircase. The second line contains a non-decreasing sequence, consisting of n integers, a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9; a_{i} ≤ a_{i} + 1).

The next line contains integer m (1 ≤ m ≤ 10^5) — the number of boxes. Each of the following m lines contains a pair of integers w_{i}, h_{i} (1 ≤ w_{i} ≤ n; 1 ≤ h_{i} ≤ 10^9) — the size of the i-th thrown box.

The numbers in the lines are separated by spaces.

-----Output-----

Print m integers — for each box the height, where the bottom of the box will be after landing. Print the answers for the boxes in the order, in which the boxes are given in the input.

Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

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

_ = input()
a = list(map(int, input().split(' ')))
m = input()

res = list()

for _ in range(int(m)):
    w, h = map(int, input().split(' '))
    #print(w, h)
    cmax = max(a[0], a[w-1])
    res.append(cmax)
    # for x in range(w):
    #     a[x] = cmax + h
    a[0] = cmax + h
    a[w-1] = cmax + h

    #print(a)

print('\n'.join(map(str, res)))


I found an interesting problem on https://codeforces.com/problemset/problem/272/D:
Little Dima has two sequences of points with integer coordinates: sequence (a_1, 1), (a_2, 2), ..., (a_{n}, n) and sequence (b_1, 1), (b_2, 2), ..., (b_{n}, n).

Now Dima wants to count the number of distinct sequences of points of length 2·n that can be assembled from these sequences, such that the x-coordinates of points in the assembled sequence will not decrease. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence.

Dima considers two assembled sequences (p_1, q_1), (p_2, q_2), ..., (p_{2·}n, q_{2·}n) and (x_1, y_1), (x_2, y_2), ..., (x_{2·}n, y_{2·}n) distinct, if there is such i (1 ≤ i ≤ 2·n), that (p_{i}, q_{i}) ≠ (x_{i}, y_{i}).

As the answer can be rather large, print the remainder from dividing the answer by number m.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). The third line contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^9). The numbers in the lines are separated by spaces.

The last line contains integer m (2 ≤ m ≤ 10^9 + 7).

-----Output-----

In the single line print the remainder after dividing the answer to the problem by number m.

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

Output
1

Input
2
1 2
2 3
11

Output
2

-----Note-----

In the first sample you can get only one sequence: (1, 1), (2, 1).

In the second sample you can get such sequences : (1, 1), (2, 2), (2, 1), (3, 2); (1, 1), (2, 1), (2, 2), (3, 2). Thus, the answer is 2.

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

from collections import defaultdict

def factorial(n, m, rep):
    r = 1
    for i in range(2, n + 1):
        j = i
        while j % 2 == 0 and rep > 0:
            j = j// 2
            rep -= 1
        r *= j
        r %= m
    return r

n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
m=int(input())
ans=1
d=defaultdict(lambda:0)
e=defaultdict(lambda:0)

i=0
while(i<n):
    d[a[i]]+=1
    d[b[i]]+=1
    if a[i]==b[i]:
        e[a[i]]+=1
    i+=1
ans=1
for j in d:
    k=d[j]
    rep=e[j]
    ans=(ans*factorial(k,m,rep))
    ans=ans%m
print(int(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/274/A:
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.

You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.

-----Input-----

The first line of the input contains two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^9). The next line contains a list of n distinct positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

All the numbers in the lines are separated by single spaces.

-----Output-----

On the only line of the output print the size of the largest k-multiple free subset of {a_1, a_2, ..., a_{n}}.

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

Output
3

-----Note-----

In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.

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

'''def bSearch(a,x,n):
	low = 0
	high = n-1
	flag = False
	while(low <= high and flag == False):
		mid = (low+high)//2
		if(a[mid] == x):
			flag = True
		else:
			if(x < a[mid]):
				high = mid - 1
			else:
				low = mid + 1
	return flag

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

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

s = []
m = 0
a = sorted(a)

for i in a:
	if(i % k != 0):
		s.append(i)
		m += 1
	elif(bSearch(s,i/k,m) == False):
		s.append(i)
		m += 1

print(m)
#print(s)'''

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

a = list(map(int,input().split()))
a = sorted(a)
s = []
d = {}
m = 0

for i in a:
	if(i % k != 0):
		s.append(i)
		m += 1
		d[i] = 1
	elif((i//k) not in d):
		s.append(i)
		d[i] = 1
		m += 1

print(m)
#print(d)
#print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/275/A:
Lenny is playing a game on a 3 × 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.

Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.

-----Input-----

The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.

-----Output-----

Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".

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

Output
001
010
100

Input
1 0 1
8 8 8
2 0 3

Output
010
011
100

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/275/B:
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. [Image]

You're given a painted grid in the input. Tell Lenny if the grid is convex or not.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.

It's guaranteed that the grid has at least one black cell.

-----Output-----

On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.

-----Examples-----
Input
3 4
WWBW
BWWW
WWWB

Output
NO

Input
3 1
B
B
W

Output
YES

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

n, m = list(map(int, input().split()))
c = [input() for _ in ' ' * n]
def sol(n, m):
    for i in range(n):
        count = 0
        for j in range(1, m):
            if c[i][j] != c[i][j - 1]:
                count += 1
        if count > 2:
            return False
        if count == 2 and c[i][0]=='B':
            return False

    for j in range(m):
        count = 0
        for i in range(1, n):
            if c[i][j] != c[i - 1][j]:
                count += 1
        if count > 2:
            return False
        if count == 2 and c[0][j]=='B':
            return False

    for i in range(n):
        for j in range(m):
            if c[i][j] == 'B':
                for x in range(i, n):
                    for y in range(m):
                        if c[x][y] == 'B':
                            if c[i][y] == 'W' and c[x][j] == 'W':
                                return False
    return True

print('NYOE S'[sol(n, m)::2])


I found an interesting problem on https://codeforces.com/problemset/problem/276/A:
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.

The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers f_{i} and t_{i}. Value t_{i} shows the time the Rabbits need to lunch in the i-th restaurant. If time t_{i} exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal f_{i} - (t_{i} - k). Otherwise, the Rabbits get exactly f_{i} units of joy.

Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.

-----Input-----

The first line contains two space-separated integers — n (1 ≤ n ≤ 10^4) and k (1 ≤ k ≤ 10^9) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — f_{i} (1 ≤ f_{i} ≤ 10^9) and t_{i} (1 ≤ t_{i} ≤ 10^9) — the characteristics of the i-th restaurant.

-----Output-----

In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.

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

Output
4

Input
4 6
5 8
3 6
2 3
2 2

Output
3

Input
1 5
1 7

Output
-1

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

sa=input().split(' ')
rs=int(sa[0])
k=int(sa[1])
joy=-99999999999999999999999999999999999
for x in range(rs):
    sa2=input().split(' ')
    f_i=int(sa2[0])
    t_i=int(sa2[1])
    if t_i>k:
        joy=max(joy, f_i-(t_i-k))
    else:
        joy=max(joy, f_i)
print(joy)


I found an interesting problem on https://codeforces.com/problemset/problem/276/B:
The Little Girl loves problems on games very much. Here's one of them.

Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:  The players move in turns; In one move the player can remove an arbitrary letter from string s.  If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.

Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.

-----Input-----

The input contains a single line, containing string s (1 ≤ |s|  ≤  10^3). String s consists of lowercase English letters.

-----Output-----

In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.

-----Examples-----
Input
aba

Output
First

Input
abca

Output
Second

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

m = list(input())

d = {}

for c in m:
    if c in d:
        d[c] += 1
    else:
        d[c] = 1

cnt = 0

for c in d:
    if d[c] % 2:
        cnt += 1

if not cnt:
    print('First')
else:
    if cnt % 2:
        print('First')
    else:
        print('Second')


I found an interesting problem on https://codeforces.com/problemset/problem/276/C:
The little girl loves the problems on array queries very much.

One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). You need to find for each query the sum of elements of the array with indexes from l_{i} to r_{i}, inclusive.

The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.

-----Input-----

The first line contains two space-separated integers n (1 ≤ n ≤ 2·10^5) and q (1 ≤ q ≤ 2·10^5) — the number of elements in the array and the number of queries, correspondingly.

The next line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 2·10^5) — the array elements.

Each of the following q lines contains two space-separated integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) — the i-th query.

-----Output-----

In a single line print a single integer — the maximum sum of query replies after the array elements are reordered.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

Output
25

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

Output
33

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

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

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

C=[0]*n

for i in range(q):
    l,r=list(map(int,input().split()))
    C[l-1]+=1
    if(r!=n):
        C[r]-=1

for i in range(1,n):
    C[i]+=C[i-1]

C.sort()
A.sort()

ans=0
for i in range(n):
    ans+=C[i]*A[i]
print(int(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/276/D:
A little girl loves problems on bitwise operations very much. Here's one of them.

You are given two integers l and r. Let's consider the values of $a \oplus b$ for all pairs of integers a and b (l ≤ a ≤ b ≤ r). Your task is to find the maximum value among all considered ones.

Expression $x \oplus y$ means applying bitwise excluding or operation to integers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is represented as "^", in Pascal — as «xor».

-----Input-----

The single line contains space-separated integers l and r (1 ≤ l ≤ r ≤ 10^18).

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

-----Output-----

In a single line print a single integer — the maximum value of $a \oplus b$ for all pairs of integers a, b (l ≤ a ≤ b ≤ r).

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

Output
3

Input
8 16

Output
31

Input
1 1

Output
0

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

# miracle!!
# cannot believe!!

(l, r) = list(map(int, input().split()))

bl = (r-l).bit_length()

print((((r^l)>>bl)+1<<bl)-1)


I found an interesting problem on https://codeforces.com/problemset/problem/278/A:
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations:

 d_1 is the distance between the 1-st and the 2-nd station;

 d_2 is the distance between the 2-nd and the 3-rd station;

...

 d_{n} - 1 is the distance between the n - 1-th and the n-th station;

 d_{n} is the distance between the n-th and the 1-st station.

The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.

-----Input-----

The first line contains integer n (3 ≤ n ≤ 100) — the number of stations on the circle line. The second line contains n integers d_1, d_2, ..., d_{n} (1 ≤ d_{i} ≤ 100) — the distances between pairs of neighboring stations. The third line contains two integers s and t (1 ≤ s, t ≤ n) — the numbers of stations, between which you need to find the shortest distance. These numbers can be the same.

The numbers in the lines are separated by single spaces.

-----Output-----

Print a single number — the length of the shortest path between stations number s and t.

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

Output
5

Input
4
5 8 2 100
4 1

Output
15

Input
3
1 1 1
3 1

Output
1

Input
3
31 41 59
1 1

Output
0

-----Note-----

In the first sample the length of path 1 → 2 → 3 equals 5, the length of path 1 → 4 → 3 equals 13.

In the second sample the length of path 4 → 1 is 100, the length of path 4 → 3 → 2 → 1 is 15.

In the third sample the length of path 3 → 1 is 1, the length of path 3 → 2 → 1 is 2.

In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.

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

n=int(input())
l=[int (i) for i in input().split(" ")]
p=[int (i) for i in input().split(" ")]
sum1=0
sum2=0
a=max(p)
b=min(p)
sum1+=sum(l[b-1:a-1])
sum2+=sum(l)-sum1
print(min(sum1,sum2))


I found an interesting problem on https://codeforces.com/problemset/problem/278/B:
Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems.

You've got the titles of n last problems — the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.

A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s_1s_2... s_{|}s| (where |s| is the length of string s) is string s_{l}s_{l} + 1... s_{r}.

String x = x_1x_2... x_{p} is lexicographically smaller than string y = y_1y_2... y_{q}, if either p < q and x_1 = y_1, x_2 = y_2, ... , x_{p} = y_{p}, or there exists such number r (r < p, r < q), that x_1 = y_1, x_2 = y_2, ... , x_{r} = y_{r} and x_{r} + 1 < y_{r} + 1. The string characters are compared by their ASCII codes.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 30) — the number of titles you've got to consider. Then follow n problem titles, one per line. Each title only consists of lowercase English letters (specifically, it doesn't contain any spaces) and has the length from 1 to 20, inclusive.

-----Output-----

Print a string, consisting of lowercase English letters — the lexicographically minimum shortest original title.

-----Examples-----
Input
5
threehorses
goodsubstrings
secret
primematrix
beautifulyear

Output
j

Input
4
aa
bdefghijklmn
opqrstuvwxyz
c

Output
ab

-----Note-----

In the first sample the first 9 letters of the English alphabet (a, b, c, d, e, f, g, h, i) occur in the problem titles, so the answer is letter j.

In the second sample the titles contain 26 English letters, so the shortest original title cannot have length 1. Title aa occurs as a substring in the first title.

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

n=int(input())

l=[]

for i in range(n):

	l+=[input()]

s="+".join(l)

q="abcdefghijklmnopqrstuvwxyz"

for i in q:

	if i not in s:

		print(i)

		break

else:

	for i in q:

		for j in q:

			if i+j not in s:

				print(i+j)

				return

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/279/A:
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1,  - 1)], [( - 1,  - 1), (2,  - 1)], [(2,  - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.

Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).

-----Input-----

The first line contains two space-separated integers x and y (|x|, |y| ≤ 100).

-----Output-----

Print a single integer, showing how many times Valera has to turn.

-----Examples-----
Input
0 0

Output
0

Input
1 0

Output
0

Input
0 1

Output
2

Input
-1 -1

Output
3

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

# python 3
"""
From tutorial: The starting position can be anywhere with a footprint. The footprints can be categorized into 3 types.

only L s
only R s
R s followed by L s

In case 1, we end in the left of all footprints.
In case 2, we end in the right of all footprints.
In case 3, we either end in the rightmost R or the leftmost L

Mine is different from the tutorial, based on intuition, hard to prove its correctness.
"""

def point_on_spiral(x_int, y_int) -> int:
    if x_int == 0 and y_int == 0 or x_int == 1 and y_int == 0:
        return 0
    count = 0
    x_prev, y_prev = 0, 0
    while True:
        spiral, count_mod_4 = divmod(count + 4, 4)
        if count_mod_4 == 0:
            x_curr, y_curr = spiral, -(spiral - 1)
        elif count_mod_4 == 1:
            x_curr, y_curr = spiral, spiral
        elif count_mod_4 == 2:
            x_curr, y_curr = -spiral, spiral
        else:
            x_curr, y_curr = -spiral, -spiral
        dist_to_prev = abs(x_int - x_prev) + abs(y_int - y_prev)
        dist_to_curr = abs(x_int - x_curr) + abs(y_int - y_curr)
        dist_prev_curr = abs(x_curr - x_prev) + abs(y_curr - y_prev)

        if dist_to_curr + dist_to_prev == dist_prev_curr:
            # print(x_prev, y_prev), (x_curr, y_curr), (x_int, y_int)
            return count
        count += 1
        x_prev, y_prev = x_curr, y_curr

def __starting_point():
    """
    Inside of this is the test.
    Outside is the API
    """
    x, y = list(map(int, input().split()))

    print(point_on_spiral(x, y))

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/279/B:
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs a_{i} minutes to read the i-th book.

Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.

Print the maximum number of books Valera can read.

-----Input-----

The first line contains two integers n and t (1 ≤ n ≤ 10^5; 1 ≤ t ≤ 10^9) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^4), where number a_{i} shows the number of minutes that the boy needs to read the i-th book.

-----Output-----

Print a single integer — the maximum number of books Valera can read.

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

Output
3

Input
3 3
2 2 3

Output
1

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

l = 0
r = -1
segL, time = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
segSum = 0
segments = []

##while r < segL-1:
##    r += 1
##    segSum += a[r]
##    if segSum == time:
##        segments.append(r+1-l)
##    elif segSum > time:
##        segments.append(r-l)
##        while segSum > time or l < r:
##            # Shifting l to the right
##            # until reaching next suitable segment sum
##            segSum -= a[l]
##            l += 1
##        #segments.append(r+1-l)
##
##[1,2,5,3,7,4,5]

while r < segL-1:
    r += 1
    segSum += a[r]
    if segSum == time:
        segments.append(r+1-l)
        segSum -= a[l]
        l += 1
    elif segSum > time:
        segments.append(r-l)
        while segSum >= time:
            segSum -= a[l]
            l += 1
else:
    segments.append(r+1-l)

print(max(segments))