I found an interesting problem on https://codeforces.com/problemset/problem/400/A:
There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:

There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X" or "O". Then the player chooses two positive integers a and b (a·b = 12), after that he makes a table of size a × b from the cards he put on the table as follows: the first b cards form the first row of the table, the second b cards form the second row of the table and so on, the last b cards form the last (number a) row of the table. The player wins if some column of the table contain characters "X" on all cards. Otherwise, the player loses.

Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers a and b to choose. Help her win the game: print to her all the possible ways of numbers a, b that she can choose and win.

-----Input-----

The first line of the input contains integer t (1 ≤ t ≤ 100). This value shows the number of sets of test data in the input. Next follows the description of each of the t tests on a separate line.

The description of each test is a string consisting of 12 characters, each character is either "X", or "O". The i-th character of the string shows the character that is written on the i-th card from the start.

-----Output-----

For each test, print the answer to the test on a single line. The first number in the line must represent the number of distinct ways to choose the pair a, b. Next, print on this line the pairs in the format axb. Print the pairs in the order of increasing first parameter (a). Separate the pairs in the line by whitespaces.

-----Examples-----
Input
4
OXXXOXOOXOOX
OXOXOXOXOXOX
XXXXXXXXXXXX
OOOOOOOOOOOO

Output
3 1x12 2x6 4x3
4 1x12 2x6 3x4 6x2
6 1x12 2x6 3x4 4x3 6x2 12x1
0

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

T=int(input())

while T>=1:
    T-=1
    a=input()
    list=[]
    for i in range(1,13):
        if 12 % i==0:
            l=12//i
            for j in range(0,l):
                for k in range(0,i):
                    if a[k*l+j]!='X':
                        break
                else:
                    break
            else:
                continue
            list.append(i)
    print(len(list),end=' ')
    for i in range(0,len(list)):
        print(str(list[i])+'x'+str(12//list[i]),end=' ')
    print()


I found an interesting problem on https://codeforces.com/problemset/problem/400/B:
Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".

The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs:

  some dwarf in one of the chosen lines is located in the rightmost cell of his row;  some dwarf in the chosen lines is located in the cell with the candy.

The point of the game is to transport all the dwarves to the candy cells.

Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n ≤ 1000; 2 ≤ m ≤ 1000).

Next n lines each contain m characters — the game field for the "Candy Martix 2: Reload". Character "*" represents an empty cell of the field, character "G" represents a dwarf and character "S" represents a candy. The matrix doesn't contain other characters. It is guaranteed that each line contains exactly one character "G" and one character "S".

-----Output-----

In a single line print a single integer — either the minimum number of moves needed to achieve the aim of the game, or -1, if the aim cannot be achieved on the given game field.

-----Examples-----
Input
3 4
*G*S
G**S
*G*S

Output
2

Input
1 3
S*G

Output
-1

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

#!/usr/bin/env python3

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

n, m = read_ints()

best = 0
opts = set()

for _ in range(n):
	x = input()
	g = x.find('G')
	s = x.find('S')

	if s<g:
		best = float('inf')
		break
	else:
		opts.add(max(best, s-g))

if best == float('inf'):
	print(-1)
else:
	print(len(opts))


I found an interesting problem on https://codeforces.com/problemset/problem/400/C:
Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (x_{k}, y_{k}).

The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. [Image]

Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!

-----Input-----

The first line of the input contains fix integers n, m, x, y, z, p (1 ≤ n, m ≤ 10^9; 0 ≤ x, y, z ≤ 10^9; 1 ≤ p ≤ 10^5).

Each of the following p lines contains two integers x_{k}, y_{k} (1 ≤ x_{k} ≤ n; 1 ≤ y_{k} ≤ m) — the initial coordinates of the k-th candy. Two candies can lie on the same cell.

-----Output-----

For each of the p candies, print on a single line its space-separated new coordinates.

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

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

-----Note-----

Just for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:

QWER      REWQ

ASDF  ->  FDSA

ZXCV      VCXZ

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

from sys import stdin

def candy (a,b,c,d,e):
    if (e == 0): return a,b,c,d
    if (e == 1): return b,c-a,d,c
    if (e == 2): return c-a,d-b,c,d
    return (d-b, a, d, c)

def candy2 (a,b,c,e):
    if (e == 0): return a,b
    if (e ==1): return a, c-b

def main():
    '''
    Name: Kevin S. sanchez
    '''
    inp = stdin
    n, m, x, y, z, p = list(map(int, inp.readline().split()))
    n, m, x, y, z = n+1, m+1, x%4 , y % 2, (4-z)%4

    for i in range (0,p):
        u, v = list(map(int, inp.readline().split()))
        u, v, q, p =  candy(u,v,n,m,x)
        u,v = candy2(u,v,p,y)
        u,v,q,p = candy(u,v,q,p,z)

        print(u,v)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/400/D:
Dima took up the biology of bacteria, as a result of his experiments, he invented k types of bacteria. Overall, there are n bacteria at his laboratory right now, and the number of bacteria of type i equals c_{i}. For convenience, we will assume that all the bacteria are numbered from 1 to n. The bacteria of type c_{i} are numbered from $(\sum_{k = 1}^{i - 1} c_{k}) + 1$ to $\sum_{k = 1}^{i} c_{k}$.

With the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows m ways to move energy from some bacteria to another one. The way with number i can be described with integers u_{i}, v_{i} and x_{i} mean that this way allows moving energy from bacteria with number u_{i} to bacteria with number v_{i} or vice versa for x_{i} dollars.

Dima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost.

As for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix d with size k × k. Cell d[i][j] of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type i to bacteria with type j.

-----Input-----

The first line contains three integers n, m, k (1 ≤ n ≤ 10^5; 0 ≤ m ≤ 10^5; 1 ≤ k ≤ 500). The next line contains k integers c_1, c_2, ..., c_{k} (1 ≤ c_{i} ≤ n). Each of the next m lines contains three integers u_{i}, v_{i}, x_{i} (1 ≤ u_{i}, v_{i} ≤ 10^5; 0 ≤ x_{i} ≤ 10^4). It is guaranteed that $\sum_{i = 1}^{k} c_{i} = n$.

-----Output-----

If Dima's type-distribution is correct, print string «Yes», and then k lines: in the i-th line print integers d[i][1], d[i][2], ..., d[i][k] (d[i][i] = 0). If there is no way to move energy from bacteria i to bacteria j appropriate d[i][j] must equal to -1....

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

#!/usr/bin/env python3
from sys import stdin
from bisect import bisect_left, bisect_right

INF = int(1e9)

def find(par, a):
    if par[a] == a:
        return a
    par[a] = find(par, par[a])
    return par[a]

def union(par, rnk, a, b):
    a = find(par,a)
    b = find(par,b)
    if a==b:
        return

    if rnk[a]<rnk[b]:
        par[a] = b
    else:
        par[b] = a
        if rnk[a]==rnk[b]:
            rnk[a] += 1

def solve():
    n, m, k = map(int, stdin.readline().split())
    cnts = list(map(int, stdin.readline().split()))
    for i in range(1,k):
        cnts[i] += cnts[i-1]

    group = list(range(n))
    rnk = [0 for i in range(n)]
    adj = [[INF for j in range(k)] for i in range(k)]
    for i in range(m):
        u, v, x = map(int, stdin.readline().split())
        if x==0:
            union(group, rnk, u-1, v-1)
        tu = bisect_left(cnts, u)
        tv = bisect_left(cnts, v)
        adj[tu][tv] = min(adj[tu][tv], x)
        adj[tv][tu] = min(adj[tv][tu], x)

    p = 0
    for i in range(k):
        cur = group[p]
        while p<cnts[i]:
            if group[p]!=cur:
                print("No")
                return
            p += 1
    print("Yes")

    for p in range(k):
        for i in range(k):
            for j in range(k):
                adj[i][j] = min(adj[i][j], adj[i][p]+adj[p][j])

    for i in range(k):
        adj[i][i] = 0
        for j in range(k):
            if adj[i][j] == INF:
                adj[i][j] = -1

    for i in range(k):
        print(' '.join(map(lambda x: str(x), adj[i])))

solve()


I found an interesting problem on https://codeforces.com/problemset/problem/401/A:
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.

Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?

You can assume that initially Vanya had infinitely many cards with each integer number from  - x to x.

-----Input-----

The first line contains two integers: n (1 ≤ n ≤ 1000) — the number of found cards and x (1 ≤ x ≤ 1000) — the maximum absolute value of the number on a card. The second line contains n space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.

-----Output-----

Print a single number — the answer to the problem.

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

Output
1

Input
2 3
-2 -2

Output
2

-----Note-----

In the first sample, Vanya needs to find a single card with number -2.

In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value.

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

n, x = map(int, input().split())
s = sum(map(int, input().split()))
print((abs(s) + x - 1) // x)


I found an interesting problem on https://codeforces.com/problemset/problem/401/B:
Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.

Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.

Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.

Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.

-----Input-----

The first line contains two integers: x (1 ≤ x ≤ 4000) — the round Sereja is taking part in today, and k (0 ≤ k < 4000) — the number of rounds he took part in.

Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 num_2 num_1" (where num_2 is the identifier of this Div2 round, num_1 is the identifier of the Div1 round). It is guaranteed that num_1 - num_2 = 1. If Sereja took part in a usual Div2 round, then the corresponding line looks like: "2 num" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.

-----Output-----

Print in a single line two integers —...

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

def main():
	x, k = map(int, input().split())
	A = [0] * x
	mx = x - 1
	for i in range(k):
		s = list(map(int, input().split()))
		A[s[1] - 1] = 1
		if len(s) == 3:
			A[s[2] - 1] = 1
		mx -= len(s) - 1
	mn = 0
	for i in range(x - 1):
		if A[i] == 0:
			mn += 1
			if A[i + 1] == 0:
				A[i + 1] = 1
	print(mn, mx)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/401/C:
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.

For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:  there wouldn't be a pair of any side-adjacent cards with zeroes in a row;  there wouldn't be a group of three consecutive cards containing numbers one.

Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.

-----Input-----

The first line contains two integers: n (1 ≤ n ≤ 10^6) — the number of cards containing number 0; m (1 ≤ m ≤ 10^6) — the number of cards containing number 1.

-----Output-----

In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.

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

Output
101

Input
4 8

Output
110110110101

Input
4 10

Output
11011011011011

Input
1 5

Output
-1

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


I found an interesting problem on https://codeforces.com/problemset/problem/402/A:
You have a nuts and lots of boxes. The boxes have a wonderful feature: if you put x (x ≥ 0) divisors (the spacial bars that can divide a box) to it, you get a box, divided into x + 1 sections.

You are minimalist. Therefore, on the one hand, you are against dividing some box into more than k sections. On the other hand, you are against putting more than v nuts into some section of the box. What is the minimum number of boxes you have to use if you want to put all the nuts in boxes, and you have b divisors?

Please note that you need to minimize the number of used boxes, not sections. You do not have to minimize the number of used divisors.

-----Input-----

The first line contains four space-separated integers k, a, b, v (2 ≤ k ≤ 1000; 1 ≤ a, b, v ≤ 1000) — the maximum number of sections in the box, the number of nuts, the number of divisors and the capacity of each section of the box.

-----Output-----

Print a single integer — the answer to the problem.

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

Output
2

Input
3 10 1 3

Output
3

Input
100 100 1 1000

Output
1

-----Note-----

In the first sample you can act like this:   Put two divisors to the first box. Now the first box has three sections and we can put three nuts into each section. Overall, the first box will have nine nuts.  Do not put any divisors into the second box. Thus, the second box has one section for the last nut.

In the end we've put all the ten nuts into boxes.

The second sample is different as we have exactly one divisor and we put it to the first box. The next two boxes will have one section each.

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

k, a, b, v = list(map(int, input().split()))
outcome = 0
while a > 0:
    outcome += 1
    kn = min(k, b+1)
    a -= kn * v
    b = max(0, b - kn + 1)
print(outcome)


I found an interesting problem on https://codeforces.com/problemset/problem/402/B:
The Queen of England has n trees growing in a row in her garden. At that, the i-th (1 ≤ i ≤ n) tree from the left has height a_{i} meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all i (1 ≤ i < n), a_{i} + 1 - a_{i} = k, where k is the number the Queen chose.

Unfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes?

-----Input-----

The first line contains two space-separated integers: n, k (1 ≤ n, k ≤ 1000). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000) — the heights of the trees in the row.

-----Output-----

In the first line print a single integer p — the minimum number of minutes the gardener needs. In the next p lines print the description of his actions.

If the gardener needs to increase the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, then print in the corresponding line "+ j x". If the gardener needs to decrease the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, print on the corresponding line "- j x".

If there are multiple ways to make a row of trees beautiful in the minimum number of actions, you are allowed to print any of them.

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

Output
2
+ 3 2
- 4 1

Input
4 1
1 2 3 4

Output
0

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

n,k = list(map(int,input().split()))
alist = [int(x) for x in input().split()]

minchange=n
mina=1000

for a in range(1,1001):
    blist=[x*k+a for x in range(0,n)]
    change=0

    for i in range(0,n):
        if alist[i]!=blist[i]:
            change+=1

        if change>=minchange:
            break

    if change<minchange:
        minchange=change
        mina=a

blist=[x*k+mina for x in range(0,n)]
changelist=[]

for i in range(0,n):
        if alist[i]>blist[i]:
            changelist.append('- '+str(i+1)+' '+str(alist[i]-blist[i]))
        elif alist[i]<blist[i]:
            changelist.append('+ '+str(i+1)+' '+str(blist[i]-alist[i]))

print(minchange)

if minchange>0:
    for change in changelist:
        print(change)


I found an interesting problem on https://codeforces.com/problemset/problem/402/C:
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:   the graph contains exactly 2n + p edges;  the graph doesn't contain self-loops and multiple edges;  for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges.

A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.

Your task is to find a p-interesting graph consisting of n vertices.

-----Input-----

The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; $2 n + p \leq \frac{n(n - 1)}{2}$) — the number of vertices in the graph and the interest value for the appropriate test.

It is guaranteed that the required graph exists.

-----Output-----

For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.

Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.

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

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

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

for t in range(int(input())):
    n, p = map(int, input().split())
    i, j = 1, 2
    for k in range(2 * n + p):
        print(i, j)
        j += 1
        if j > n:
            i += 1
            j = i + 1


I found an interesting problem on https://codeforces.com/problemset/problem/404/A:
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.

Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:  on both diagonals of the square paper all letters are the same;  all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals.

Help Valera, write the program that completes the described task for him.

-----Input-----

The first line contains integer n (3 ≤ n < 300; n is odd). Each of the next n lines contains n small English letters — the description of Valera's paper.

-----Output-----

Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.

-----Examples-----
Input
5
xooox
oxoxo
soxoo
oxoxo
xooox

Output
NO

Input
3
wsw
sws
wsw

Output
YES

Input
3
xpx
pxp
xpe

Output
NO

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

def solve(arr, n):
    symbol = arr[0][0]
    for i in range(0,n):
        if arr[i][i] != symbol:
            return 'NO'
    j=0
    for i in range(n-1,-1,-1):
        if arr[i][j] != symbol:
            return 'NO'
        j+=1
    return 'YES'

n = int(input())

chars = []
while len(chars) < n:
    s = input()
    chars.append(list(s))

L = sum(chars,[])
amount = set(sum(chars,[]))

if len(amount) == 2 and L.count(L[0]) == n*2-1:
    print(solve(chars, n))
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/404/B:
Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.

As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters.

Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters.

-----Input-----

The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 10^5), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink.

The second line contains integer n (1 ≤ n ≤ 10^5) showing that Valera needs an extra drink n times.

-----Output-----

Print n lines, each line should contain two real numbers x_{i} and y_{i}, separated by a space. Numbers x_{i} and y_{i} in the i-th line mean that Valera is at point with coordinates (x_{i}, y_{i}) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10^{ - 4}.

Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.

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

Output
1.0000000000 2.0000000000
2.0000000000 0.0000000000

Input
4.147 2.8819
6

Output
2.8819000000 0.0000000000
4.1470000000 1.6168000000
3.7953000000 4.1470000000
0.9134000000 4.1470000000
0.0000000000 2.1785000000
0.7034000000...

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

def setPoint(point, a):
    p = point
    x = 0
    y = 0
    if p <= a:
        x = p
        y = 0
    elif p <= a*2:
        x = a
        y = p - a
    elif p <= a*3:
        x = a*3 - p
        y = a
    else:
        x = 0
        y = a*4 - p
    x = int(x*100000)/100000
    y = int(y*100000)/100000
    return str(x) + ' ' + str(y)

a, d = list(map(float, input().split()))
n = int(input())
curP = 0

for l in range(0, n):
    curP += d
    curP = curP % (a*4)
    print(setPoint(curP, a))


I found an interesting problem on https://codeforces.com/problemset/problem/404/C:
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.

One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.

Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.

-----Input-----

The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 10^5). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.

The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.

-----Output-----

If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 10^6) — the number of edges in the found graph.

In each of the next m lines print two space-separated integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}), denoting the edge that connects vertices with numbers a_{i} and b_{i}. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.

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

Output
3
1 2
1 3
3 2

Input
4 2
2 0 1 3

Output
3
1 3
1 4
2 3

Input
3 1
0 0 0

Output
-1

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

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

dmax = max(d)

nv = [[] for i in range(dmax+1)]
v = [0] * (dmax+1)

for i, dist in enumerate(d):
    nv[dist].append(i)
    v[dist] += 1

flag = True
if v[0] != 1 or v[1] > k:
    flag = False
else:
    for i in range(2, dmax+1):
        if v[i] > (k-1) * v[i-1] or v[i] == 0:
            flag = False
            break

if flag:
    print(n-1)
    for vrtx in nv[1]:
        print(nv[0][0] + 1, vrtx + 1)
    for i, vs in enumerate(nv[1:-1]):
        for j, vrtx in enumerate(vs):
            m = 0
            while m < (k-1):
                if (j*(k-1) + m) < len(nv[i+2]):
                    print(vrtx + 1, nv[i+2][j*(k-1) + m] + 1)
                    m += 1
                else:
                    break

else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/404/D:
Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.

For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.

Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.

-----Input-----

The first line contains sequence of characters without spaces s_1s_2... s_{n} (1 ≤ n ≤ 10^6), containing only characters "*", "?" and digits "0", "1" or "2". If character s_{i} equals "*", then the i-th cell of the field contains a bomb. If character s_{i} equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character s_{i}, that is equal to a digit, represents the digit written in the i-th square.

-----Output-----

Print a single integer — the number of ways Valera can fill the empty cells and get a correct field.

As the answer can be rather large, print it modulo 1000000007 (10^9 + 7).

-----Examples-----
Input
?01???

Output
4

Input
?

Output
2

Input
**12

Output
0

Input
1

Output
0

-----Note-----

In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.

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/405/A:
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.

There are n columns of toy cubes in the box arranged in a line. The i-th column contains a_{i} cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange. [Image]

Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the n columns after the gravity switch!

-----Input-----

The first line of input contains an integer n (1 ≤ n ≤ 100), the number of the columns in the box. The next line contains n space-separated integer numbers. The i-th number a_{i} (1 ≤ a_{i} ≤ 100) denotes the number of cubes in the i-th column.

-----Output-----

Output n integer numbers separated by spaces, where the i-th number is the amount of cubes in the i-th column after the gravity switch.

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

Output
1 2 2 3

Input
3
2 3 8

Output
2 3 8

-----Note-----

The first example case is shown on the figure. The top cube of the first column falls to the top of the last column; the top cube of the second column falls to the top of the third column; the middle cube of the first column falls to the top of the second column.

In the second example case the gravity switch does not change the heights of the columns.

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

input()
[print(x, end=' ') for x in sorted(list(map(int, input().split())))]


I found an interesting problem on https://codeforces.com/problemset/problem/405/B:
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".

Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.

After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. [Image]

Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string s_{i} is equal to   "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.

It is guaranteed that if s_{i} = s_{j} = "L" and i < j, then there exists such k that i < k < j and s_{k} = "R"; if s_{i} = s_{j} = "R" and i < j, then there exists such k that i < k < j and s_{k} = "L".

-----Output-----

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

-----Examples-----
Input
14
.L.R...LR..L..

Output
4

Input
5
R....

Output
0

Input
1
.

Output
1

-----Note-----

The first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.

In the second example case, all pieces fall down since the first piece...

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

n = int(input())
s = input()
c = n
k = 0
l, r = 0, 0
for i in range(n):
  if s[i] == '.':
    continue
  if s[i] == 'L':
    k -= 1
    l = i
  else:
    k += 1
    r = i
  if k < 0:
    c -= i + 1
    k = 0
  elif k == 0:
    c -= (l - r + 1) - (l - r + 1) % 2
if k > 0:
  c -= n - r
print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/405/C:
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.

The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.

Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: $\left(\begin{array}{l l l}{1} & {1} & {1} \\{0} & {1} & {1} \\{1} & {0} & {0} \end{array} \right)$

The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.

However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:   given a row index i, flip all the values in the i-th row in A;  given a column index i, flip all the values in the i-th column in A;  find the unusual square of A.

To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.

Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?

-----Input-----

The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line a_{ij} (0 ≤ a_{ij} ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.

The next line of input contains an integer q (1 ≤ q ≤ 10^6), the number of queries. Each of the next q lines describes a single query, which can be one of the following:   1 i — flip the values of the i-th row;  2 i — flip the...

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

from functools import reduce
def main():
    from sys import stdin
    from operator import xor
    from functools import reduce
    x, res = reduce(xor, (input()[i] == '1' for i in range(0, int(input()) * 2, 2))), []
    input()
    for s in stdin.read().splitlines():
        if s == '3':
            res.append("01"[x])
        else:
            x ^= True
    print(''.join(res))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/405/D:
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.

There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset Y from the remaining blocks, that the equality holds: $\sum_{x \in X}(x - 1) = \sum_{y \in Y}(s - y)$ "Are you kidding me?", asks Chris.

For example, consider a case where s = 8 and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: (1 - 1) + (4 - 1) + (5 - 1) = (8 - 3) + (8 - 6) = 7.

 $\left. \begin{array}{l l l l l l}{1} & {2} & {3} & {4} & {5} & {6} & {7} & {8} \end{array} \right.$

However, now Chris has exactly s = 10^6 blocks. Given the set X of blocks his teacher chooses, help Chris to find the required set Y!

-----Input-----

The first line of input contains a single integer n (1 ≤ n ≤ 5·10^5), the number of blocks in the set X. The next line contains n distinct space-separated integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^6), the numbers of the blocks in X.

Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

-----Output-----

In the first line of output print a single integer m (1 ≤ m ≤ 10^6 - n), the number of blocks in the set Y. In the next line output m distinct space-separated integers y_1, y_2, ..., y_{m} (1 ≤ y_{i} ≤ 10^6), such that the required equality holds. The sets X and Y should not intersect, i.e. x_{i} ≠ y_{j} for all i, j (1 ≤ i ≤ n; 1 ≤ j ≤ m). It is guaranteed that at least one solution always exists. If there are multiple solutions, output any of them.

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

Output
2
999993 1000000
Input
1
1

Output
1
1000000

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

import sys

def solve():
    n = int(input())
    s = 1000000
    xset = set(map(int, input().split()))
    res = set()
    wantother = 0
    for i in range(1, s + 1):
        opposite = s - i + 1
        if i in xset:
            if opposite not in xset:
                res.add(opposite)
            else:
                wantother+=1
    wantother /= 2
    for i in range(1, s + 1):
        if wantother == 0: break
        opposite = s - i + 1
        if i not in res and i not in xset and opposite not in xset:
            res.add(i)
            res.add(opposite)
            wantother-=1

    print(len(res))
    return " ".join(map(str, res))

if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/407/B:
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.

The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number p_{i}, where 1 ≤ p_{i} ≤ i.

In order not to get lost, Vasya decided to act as follows.   Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.  Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room p_{i}), otherwise Vasya uses the first portal.

Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^3) — the number of rooms. The second line contains n integers p_{i} (1 ≤ p_{i} ≤ i). Each p_{i} denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.

-----Output-----

Print a single number — the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (10^9 + 7).

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

Output
4

Input
4
1 1 2 3

Output
20

Input
5
1 1 1 1 1

Output
62

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/408/A:
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.

There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has k_{i} people. The j-th person standing in the queue to the i-th cashier has m_{i}, j items in the basket. Vasya knows that:  the cashier needs 5 seconds to scan one item;  after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change.

Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k_1, k_2, ..., k_{n} (1 ≤ k_{i} ≤ 100), where k_{i} is the number of people in the queue to the i-th cashier.

The i-th of the next n lines contains k_{i} space-separated integers: m_{i}, 1, m_{i}, 2, ..., m_{i}, k_{i} (1 ≤ m_{i}, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has.

-----Output-----

Print a single integer — the minimum number of seconds Vasya needs to get to the cashier.

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

Output
20

Input
4
1 4 3 2
100
1 2 2 3
1 9 1
7 8

Output
100

-----Note-----

In the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.

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

n=int(input())
k=list(map(int,input().split()))
now=0
m=100000000
for i in range(n):
    b=map(int,input().split())
    now=0
    for j in b:
        now+=j*5+15
    m=min(m,now)
print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/408/B:
Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter.

The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland.

Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of m pieces of paper in the garland. Calculate what the maximum total area of the pieces of paper in the garland Vasya can get.

-----Input-----

The first line contains a non-empty sequence of n (1 ≤ n ≤ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color.

The second line contains a non-empty sequence of m (1 ≤ m ≤ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make.

-----Output-----

Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer.

-----Examples-----
Input
aaabbac
aabbccac

Output
6

Input
a
z

Output
-1

-----Note-----

In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6.

In the second test sample Vasya cannot make a garland at all — he doesn't have a sheet of color z.

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

def main():
    import sys
    material = input()
    scheme = input()
    flag = True
    for i in range(len(scheme)):
        if flag:
            if not scheme[i] in material:
                print(-1)
                flag = False
    if flag:
        counter = 0
        SIZE = len(scheme) - 1
        saver = []
        result = 0
        while counter <= SIZE:
            saver += [scheme[counter]]
            if (scheme.count(scheme[counter]) <=
                material.count(scheme[counter])):
                result += scheme.count(scheme[counter])
            else:
                result += material.count(scheme[counter])
            while scheme[counter] in saver:
                if counter < SIZE:
                    counter += 1
                else:
                    print(result)
                    return
        print(result)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/409/C:
Salve, mi amice.

Et tu quidem de lapis philosophorum. Barba non facit philosophum. Labor omnia vincit. Non potest creatio ex nihilo. Necesse est partibus.

Rp:

    I Aqua Fortis

    I Aqua Regia

    II Amalgama

    VII Minium

    IV Vitriol

Misce in vitro et æstus, et nil admirari. Festina lente, et nulla tenaci invia est via.

Fac et spera,

Vale,

Nicolas Flamel

-----Input-----

The first line of input contains several space-separated integers a_{i} (0 ≤ a_{i} ≤ 100).

-----Output-----

Print a single integer.

-----Examples-----
Input
2 4 6 8 10

Output
1

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

requirements = (1, 1, 2, 7, 4)

ingrs = [int(x) for x in input().split(" ")]

min_count = 2**64

for i, x in enumerate(ingrs):
    if i >= len(requirements):
        continue
    min_count = min(int(x / requirements[i]), min_count)

print(min_count)


I found an interesting problem on https://codeforces.com/problemset/problem/409/D:
Little Petya wanted to give an April Fools Day present to some scientists. After some hesitation he decided to give them the array that he got as a present in Codeforces Round #153 (Div.2). The scientists rejoiced at the gift and decided to put some important facts to this array. Here are the first few of the facts: The highest mountain above sea level in the world is Mount Everest. Its peak rises to 8848 m.  The largest board game tournament consisted of 958 participants playing chapaev. The largest online maths competition consisted of 12766 participants. The Nile is credited as the longest river in the world. From its farthest stream in Burundi, it extends 6695 km in length. While not in flood, the main stretches of the Amazon river in South America can reach widths of up to 1100 km at its widest points. Angel Falls is the highest waterfall. Its greatest single drop measures 807 m. The Hotel Everest View above Namche, Nepal — the village closest to Everest base camp – is at a record height of 31962 m Uranium is the heaviest of all the naturally occurring elements. Its most common isotope has a nucleus containing 146 neutrons. The coldest permanently inhabited place is the Siberian village of Oymyakon, where the temperature of -68°C was registered in the twentieth century. The longest snake held in captivity is over 25 feet long. Its name is Medusa. Colonel Meow holds the world record for longest fur on a cat — almost 134 centimeters. Sea otters can have up to 10000 hairs per square inch. This is the most dense fur in the animal kingdom. The largest state of USA is Alaska; its area is 663268 square miles Alaska has a longer coastline than all of the other 49 U.S. States put together: it is 154103 miles long. Lake Baikal is the largest freshwater lake in the world. It reaches 1642 meters in depth and contains around one-fifth of the world’s unfrozen fresh water. The most colorful national flag is the one of Turkmenistan, with 106 colors.

-----Input-----

The input will contain a single integer between 1...

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

"""
Codeforces April Fools Contest 2014 Problem D

Author  : chaotic_iak
Language: Python 3.3.4
"""

class InputHandlerObject(object):
    inputs = []

    def getInput(self, n = 0):
        res = ""
        inputs = self.inputs
        if not inputs: inputs.extend(input().split(" "))
        if n == 0:
            res = inputs[:]
            inputs[:] = []
        while n > len(inputs):
            inputs.extend(input().split(" "))
        if n > 0:
            res = inputs[:n]
            inputs[:n] = []
        return res
InputHandler = InputHandlerObject()
g = InputHandler.getInput

############################## SOLUTION ##############################
answers = [1,0,0,1,0,1,0,1,1,1,0,0,1,0,1,0]

x = int(input())

# tests: 1 7 13 3 8 16 11 2 5 10 9 12- 12- 4 _ _
#if x not in [1,7,13,3,16,8,11,2,5,10] and x < 7: print(1/0)

print(answers[x-1])


I found an interesting problem on https://codeforces.com/problemset/problem/409/E:
$\text{A}$

-----Input-----

The input contains a single floating-point number x with exactly 6 decimal places (0 < x < 5).

-----Output-----

Output two integers separated by a single space. Each integer should be between 1 and 10, inclusive. If several solutions exist, output any of them. Solution will exist for all tests.

-----Examples-----
Input
1.200000

Output
3 2

Input
2.572479

Output
10 3

Input
4.024922

Output
9 9

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

r=float(input())
a=0
h=0
for i in range(1,11):
    for j in range(1,11):
        c=pow(j*j+i*i/4.,0.5)
        rtest=i*j*0.5/c
        if abs(rtest-r)<0.00001:
            a=i
            h=j
print(a,h)


I found an interesting problem on https://codeforces.com/problemset/problem/409/F:
-----Input-----

The input contains a single integer a (1 ≤ a ≤ 64).

-----Output-----

Output a single integer.

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

Output
1

Input
4

Output
2

Input
27

Output
5

Input
42

Output
6

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


I found an interesting problem on https://codeforces.com/problemset/problem/409/G:
-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of points on a plane.

Each of the next n lines contains two real coordinates x_{i} and y_{i} of the $i^{\text{th}}$ point, specified with exactly 2 fractional digits. All coordinates are between  - 1000 and 1000, inclusive.

-----Output-----

Output a single real number θ — the answer to the problem statement. The absolute or relative error of your answer should be at most 10^{ - 2}.

-----Examples-----
Input
8
-2.14 2.06
-1.14 2.04
-2.16 1.46
-2.14 0.70
-1.42 0.40
-0.94 -0.48
-1.42 -1.28
-2.16 -1.62

Output
5.410

Input
5
2.26 1.44
2.28 0.64
2.30 -0.30
1.58 0.66
3.24 0.66

Output
5.620

Input
8
6.98 2.06
6.40 1.12
5.98 0.24
5.54 -0.60
7.16 0.30
7.82 1.24
8.34 0.24
8.74 -0.76

Output
5.480

Input
5
10.44 2.06
10.90 0.80
11.48 -0.48
12.06 0.76
12.54 2.06

Output
6.040

Input
8
16.94 2.42
15.72 2.38
14.82 1.58
14.88 0.50
15.76 -0.16
16.86 -0.20
17.00 0.88
16.40 0.92

Output
6.040

Input
7
20.62 3.00
21.06 2.28
21.56 1.36
21.66 0.56
21.64 -0.52
22.14 2.32
22.62 3.04

Output
6.720

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

a=int(input());print(sum([float(input().split(' ')[1]) for i in range(a)])/a+5)


I found an interesting problem on https://codeforces.com/problemset/problem/409/H:
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?

-----Input-----

The input contains two integers a and b (0 ≤ a, b ≤ 10^3), separated by a single space.

-----Output-----

Output the sum of the given integers.

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

Output
19

Input
381 492

Output
873

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/409/I:
Golorps are mysterious creatures who feed on variables. Golorp's name is a program in some programming language. Some scientists believe that this language is Befunge; golorps are tantalizingly silent.

Variables consumed by golorps can take values from 0 to 9, inclusive. For each golorp its daily diet is defined by its name. Some golorps are so picky that they can't be fed at all. Besides, all golorps are very health-conscious and try to eat as little as possible. Given a choice of several valid sequences of variable values, each golorp will choose lexicographically smallest one.

For the purposes of this problem you can assume that a golorp consists of jaws and a stomach. The number of variables necessary to feed a golorp is defined by the shape of its jaws. Variables can get to the stomach only via the jaws.

A hungry golorp is visiting you. You know its name; feed it or figure out that it's impossible.

-----Input-----

The input is a single string (between 13 and 1024 characters long) — the name of the visiting golorp. All names are similar and will resemble the ones given in the samples. The name is guaranteed to be valid.

-----Output-----

Output lexicographically smallest sequence of variable values fit for feeding this golorp. Values should be listed in the order in which they get into the jaws. If the golorp is impossible to feed, output "false".

-----Examples-----
Input
?(_-_/___*__):-___>__.

Output
0010

Input
?(__-_+_/_____):-__>__,_____<__.

Output
false

Input
?(______________________/____+_______*__-_____*______-___):-__<___,___<____,____<_____,_____<______,______<_______.

Output
0250341

Input
?(__+___+__-___):-___>__.

Output
0101

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

"""
Codeforces April Fools Contest 2014 Problem I

Author  : chaotic_iak
Language: Python 3.3.4
"""

class InputHandlerObject(object):
    inputs = []

    def getInput(self, n = 0):
        res = ""
        inputs = self.inputs
        if not inputs: inputs.extend(input().split(" "))
        if n == 0:
            res = inputs[:]
            inputs[:] = []
        while n > len(inputs):
            inputs.extend(input().split(" "))
        if n > 0:
            res = inputs[:n]
            inputs[:n] = []
        return res
InputHandler = InputHandlerObject()
g = InputHandler.getInput

############################## SOLUTION ##############################

# ?(_/____+_______*__-_____*______-___):-__<___,___<____,____<_____,_____<______,______<_______.

golorp = input().split(":-")
golorp[0] = golorp[0][2:]

ct = 0
jaws = []
for x in range(len(golorp[0])):
    if golorp[0][x] == "_":
        ct += 1
    else:
        jaws.append(ct)
        ct = 0

ct = 0
conditionsraw = []
for x in range(len(golorp[1])):
    if golorp[1][x] == "_":
        ct += 1
    else:
        conditionsraw.append(ct)
        conditionsraw.append(golorp[1][x])
        ct = 0

conditions = []
for x in range(0, len(conditionsraw)//4):
    if conditionsraw[4*x+1] == ">":
        conditions.append((conditionsraw[4*x+2], conditionsraw[4*x]))
    else:
        conditions.append((conditionsraw[4*x], conditionsraw[4*x+2]))

inedges = [[-1]] * (max(jaws) + 1)
outedges = [[-1]] * (max(jaws) + 1)
val = [-1] * (max(jaws) + 1)
processed = [False] * (max(jaws) + 1)
for x in jaws:
    inedges[x] = []
    outedges[x] = []

for x, y in conditions:
    inedges[y].append(x)
    outedges[x].append(y)

for i in range(10):
    for x in jaws:
        if not inedges[x] and not processed[x]:
            val[x] += 1
            processed[x] = True
            for y in outedges[x]:
                val[y] = max(val[y], val[x])
                inedges[y].remove(x)

failure = False
for x in jaws:
    if not processed[x] or val[x] > 9:
        failure = True
       ...


I found an interesting problem on https://codeforces.com/problemset/problem/411/A:
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic check.

Web-developers of the company Q assume that a password is complex enough, if it meets all of the following conditions:  the password length is at least 5 characters;  the password contains at least one large English letter;  the password contains at least one small English letter;  the password contains at least one digit.

You are given a password. Please implement the automatic check of its complexity for company Q.

-----Input-----

The first line contains a non-empty sequence of characters (at most 100 characters). Each character is either a large English letter, or a small English letter, or a digit, or one of characters: "!", "?", ".", ",", "_".

-----Output-----

If the password is complex enough, print message "Correct" (without the quotes), otherwise print message "Too weak" (without the quotes).

-----Examples-----
Input
abacaba

Output
Too weak

Input
X12345

Output
Too weak

Input
CONTEST_is_STARTED!!11

Output
Correct

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

s = input()
print('Correct' if len(s) >= 5 and any([elem.isupper() for elem in s]) and any([elem.islower() for elem in s]) and any([elem.isdigit() for elem in s]) else 'Too weak')


I found an interesting problem on https://codeforces.com/problemset/problem/411/B:
The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.

At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.

The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.

-----Input-----

The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 100). Then follow n lines describing instructions. The i-th line contains m integers: x_{i}1, x_{i}2, ..., x_{im} (0 ≤ x_{ij} ≤ k), where x_{ij} is the instruction that must be executed by the i-th core at the j-th cycle. If x_{ij} equals 0, then the corresponding instruction is «do nothing». But if x_{ij} is a number from 1 to k, then the corresponding instruction is «write information to the memory cell number x_{ij}».

We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from...

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

n, m, k = map(int, input().split())
k += 1
dead = [0] * n  # time of deadlock
block = [False] * k  # ceil is blocked
t = [tuple(map(int, input().split())) for i in range(n)]
for j, s in enumerate(zip(*t), 1):
    q = [[] for i in range(k)]
    for core, ceil in enumerate(s):
        if dead[core] == 0: q[ceil].append(core)
    for ceil in range(1, k):
        if not q[ceil]: continue
        if block[ceil] or len(q[ceil]) > 1:
            for core in q[ceil]: dead[core] = j
            block[ceil] = True
print('\n'.join(map(str, dead)))


I found an interesting problem on https://codeforces.com/problemset/problem/411/C:
Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the half-backs and forwards (plays attack).

Two teams of company Q decided to battle each other. Let's enumerate players from both teams by integers from 1 to 4. The first and second player play in the first team, the third and the fourth one play in the second team. For each of the four players we know their game skills in defence and attack. The defence skill of the i-th player is a_{i}, the attack skill is b_{i}.

Before the game, the teams determine how they will play. First the players of the first team decide who will play in the attack, and who will play in the defence. Then the second team players do the same, based on the choice of their opponents.

We will define a team's defence as the defence skill of player of the team who plays defence. Similarly, a team's attack is the attack skill of the player of the team who plays attack. We assume that one team is guaranteed to beat the other one, if its defence is strictly greater than the opponent's attack and its attack is strictly greater than the opponent's defence.

The teams of company Q know each other's strengths and therefore arrange their teams optimally. Identify the team that is guaranteed to win (if both teams act optimally) or tell that there is no such team.

-----Input-----

The input contain the players' description in four lines. The i-th line contains two space-separated integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 100) — the defence and the attack skill of the i-th player, correspondingly.

-----Output-----

If the first team can win, print phrase "Team 1" (without the quotes), if the second team can win, print phrase "Team 2" (without the quotes). If no of the teams can definitely win, print "Draw" (without the...

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/412/A:
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.

The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.

Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.

Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!

-----Input-----

The first line contains two integers, n and k (1 ≤ k ≤ n ≤ 100) — the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'.

-----Output-----

In t lines, print the actions the programmers need to make. In the i-th line print:  "LEFT" (without the quotes), if the i-th action was "move the ladder to the...

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

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

s=input()

k-=1

Ans=""

if((k+1)>n//2):
    for j in range(k,n-1):
        Ans+="PRINT "+s[j]+"\n"
        Ans+="RIGHT\n"
    Ans+="PRINT "+s[n-1]+"\n"
    ind=n-1
    if(k>0):
        while(ind>=k):
            Ans+="LEFT\n"
            ind-=1
        for i in range(ind,0,-1):
            Ans+="PRINT "+s[i]+"\n"
            Ans+="LEFT\n"
        Ans+="PRINT "+s[0]+"\n"

else:
    for j in range(k,0,-1):
        Ans+="PRINT "+s[j]+"\n"
        Ans+="LEFT\n"
    Ans+="PRINT "+s[0]+"\n"
    ind=0
    if(k<n-1):
        while(ind<=k):
            Ans+="RIGHT\n"
            ind+=1
        for i in range(ind,n-1):
            Ans+="PRINT "+s[i]+"\n"
            Ans+="RIGHT\n"
        Ans+="PRINT "+s[n-1]+"\n"
sys.stdout.write(Ans)


I found an interesting problem on https://codeforces.com/problemset/problem/412/B:
The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the i-th computer it was a_{i} kilobits per second.

There will be k participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.

The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least k of n computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?

-----Input-----

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 100) — the number of computers and the number of participants, respectively. In the second line you have a space-separated sequence consisting of n integers: a_1, a_2, ..., a_{n} (16 ≤ a_{i} ≤ 32768); number a_{i} denotes the maximum data transfer speed on the i-th computer.

-----Output-----

Print a single integer — the maximum Internet speed value. It is guaranteed that the answer to the problem is always an integer.

-----Examples-----
Input
3 2
40 20 30

Output
30

Input
6 4
100 20 40 20 50 50

Output
40

-----Note-----

In the first test case the organizers can cut the first computer's speed to 30...

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

[n, k], speed = list(map(int, input().split())), sorted(map(int, input().split()), reverse = True)
print(speed[k - 1])


I found an interesting problem on https://codeforces.com/problemset/problem/412/D:
The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.

Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person x to his office for a reward, and then immediately invite person y, who has lent some money to person x, then they can meet. Of course, in such a situation, the joy of person x from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.

However, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.

-----Input-----

The first line contains space-separated integers n and m $(2 \leq n \leq 3 \cdot 10^{4} ; 1 \leq m \leq \operatorname{min}(10^{5}, \frac{n(n - 1)}{2}))$ — the number of employees in R1 and the number of debt relations. Each of the following m lines contains two space-separated integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}), these integers indicate that the person number a_{i} owes money to a person a number b_{i}. Assume that all the employees are numbered from 1 to n.

It is guaranteed that each pair of people p, q is mentioned in the input data at most once. In particular, the input data will not contain pairs p, q and q, p simultaneously.

-----Output-----

Print -1 if the described order does not exist. Otherwise, print the permutation of n distinct integers. The first number should denote the number of the person who goes to...

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

n, m = map(int,input().split())
g = [set() for i in range(n)]
for i in range(m):
    a, b = map(int,input().split())
    g[a-1].add(b-1)

c = [0] * n
for i in range(n):
    c[i] = i
for i in range(n):
    j = i
    while (j > 0)and(c[j] in g[c[j - 1]]):
        c[j], c[j-1] = c[j-1], c[j]
        j -= 1
for i in c:
    print(i + 1, end = ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/413/A:
Not so long ago company R2 bought company R1 and consequently, all its developments in the field of multicore processors. Now the R2 laboratory is testing one of the R1 processors.

The testing goes in n steps, at each step the processor gets some instructions, and then its temperature is measured. The head engineer in R2 is keeping a report record on the work of the processor: he writes down the minimum and the maximum measured temperature in his notebook. His assistant had to write down all temperatures into his notebook, but (for unknown reasons) he recorded only m.

The next day, the engineer's assistant filed in a report with all the m temperatures. However, the chief engineer doubts that the assistant wrote down everything correctly (naturally, the chief engineer doesn't doubt his notes). So he asked you to help him. Given numbers n, m, min, max and the list of m temperatures determine whether you can upgrade the set of m temperatures to the set of n temperatures (that is add n - m temperatures), so that the minimum temperature was min and the maximum one was max.

-----Input-----

The first line contains four integers n, m, min, max (1 ≤ m < n ≤ 100; 1 ≤ min < max ≤ 100). The second line contains m space-separated integers t_{i} (1 ≤ t_{i} ≤ 100) — the temperatures reported by the assistant.

Note, that the reported temperatures, and the temperatures you want to add can contain equal temperatures.

-----Output-----

If the data is consistent, print 'Correct' (without the quotes). Otherwise, print 'Incorrect' (without the quotes).

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

Output
Correct

Input
3 1 1 3
2

Output
Correct

Input
2 1 1 3
2

Output
Incorrect

-----Note-----

In the first test sample one of the possible initial configurations of temperatures is [1, 2].

In the second test sample one of the possible initial configurations of temperatures is [2, 1, 3].

In the third test sample it is impossible to add one temperature to obtain the minimum equal to 1 and the maximum equal to 3.

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

n, _, small, big =  list(map(int, input().split()))
m = list(map(int, input().split()))

diff = n - _

rd = 0

if (max(m) != big):
    rd += 1
if (min(m) != small):
    rd += 1

if min(m) < small or max(m) > big:
    print('Incorrect')
    return

#print('diff', diff)
#print('rd', rd)
#n - vsego
# m zapisal pomosh

if rd <= diff:
    print('Correct')
else:
    print('Incorrect')


I found an interesting problem on https://codeforces.com/problemset/problem/413/B:
The R2 company has n employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.

R2 has m Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the k-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification.

The R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee.

-----Input-----

The first line contains three space-separated integers n, m and k (2 ≤ n ≤ 2·10^4; 1 ≤ m ≤ 10; 1 ≤ k ≤ 2·10^5) — the number of the employees, the number of chats and the number of events in the log, correspondingly.

Next n lines contain matrix a of size n × m, consisting of numbers zero and one. The element of this matrix, recorded in the j-th column of the i-th line, (let's denote it as a_{ij}) equals 1, if the i-th employee is the participant of the j-th chat, otherwise the element equals 0. Assume that the employees are numbered from 1 to n and the chats are numbered from 1 to m.

Next k lines contain the description of the log events. The i-th line contains two space-separated integers x_{i} and y_{i} (1 ≤ x_{i} ≤ n; 1 ≤ y_{i} ≤ m) which mean that the employee number x_{i} sent one message to chat number y_{i}. It is guaranteed that employee number x_{i} is a participant of chat y_{i}. It is guaranteed that each chat contains at least two employees.

-----Output-----

Print in the single line n...

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

n, m, k = map(int, input().split())
chats_ = []
for i in range(n):
    a = list(map(int, input().split()))
    chats_.append(a)
sent = [0 for i in range(n)]
chats = [0 for i in range(m)]
for i in range(k):
    a, b = map(int, input().split())
    sent[a - 1] += 1
    chats[b - 1] += 1
for i in range(n):
    sum = 0
    for j in range(m):
        sum += chats_[i][j] * chats[j]
    sum -= sent[i]
    print(sum, end = ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/413/C:
'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2.

The finals will have n questions, m of them are auction questions and n - m of them are regular questions. Each question has a price. The price of the i-th question is a_{i} points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.

The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.

All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.

-----Input-----

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100; m ≤ min(n, 30)) — the total number of questions and the number of auction questions, correspondingly. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^7) — the prices of the questions. The third line contains m distinct integers b_{i} (1 ≤ b_{i} ≤ n) — the numbers of auction questions. Assume that the questions are...

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

from operator import itemgetter

R = lambda:list(map(int, input().split()))

n, m = R()

a = list(R())

b = [0] * n

for i in R():

  b[i - 1] = 1

a = sorted(enumerate(a), key=itemgetter(1), reverse=True)

s = sum(x for i, x in a if b[i] != 1)

for i, x in a:

  if b[i] == 1:

    s += s if s > x else x

print(s)

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/415/A:
Mashmokh works in a factory. At the end of each day he must turn off all of the lights.

The lights on the factory are indexed from 1 to n. There are n buttons in Mashmokh's room indexed from 1 to n as well. If Mashmokh pushes button with index i, then each light with index not less than i that is still turned on turns off.

Mashmokh is not very clever. So instead of pushing the first button he pushes some of the buttons randomly each night. He pushed m distinct buttons b_1, b_2, ..., b_{m} (the buttons were pushed consecutively in the given order) this night. Now he wants to know for each light the index of the button that turned this light off. Please note that the index of button b_{i} is actually b_{i}, not i.

Please, help Mashmokh, print these indices.

-----Input-----

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100), the number of the factory lights and the pushed buttons respectively. The next line contains m distinct space-separated integers b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ n).

It is guaranteed that all lights will be turned off after pushing all buttons.

-----Output-----

Output n space-separated integers where the i-th number is index of the button that turns the i-th light off.

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

Output
1 1 3 4 4

Input
5 5
5 4 3 2 1

Output
1 2 3 4 5

-----Note-----

In the first sample, after pressing button number 4, lights 4 and 5 are turned off and lights 1, 2 and 3 are still on. Then after pressing button number 3, light number 3 is turned off as well. Pressing button number 1 turns off lights number 1 and 2 as well so pressing button number 2 in the end has no effect. Thus button number 4 turned lights 4 and 5 off, button number 3 turned light 3 off and button number 1 turned light 1 and 2 off.

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

n, m = map(int, input().split())
clicks = list(map(int, input().split()))
lamps = [-1] * (n + 1)
pointer = n + 1
for i in range(m):
    for j in range(clicks[i], pointer):
        lamps[j] = clicks[i]
    pointer = min(pointer, clicks[i])
lamps = lamps[1:]
print(*lamps)


I found an interesting problem on https://codeforces.com/problemset/problem/415/B:
Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back w tokens then he'll get $\lfloor \frac{w \cdot a}{b} \rfloor$ dollars.

Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has n numbers x_1, x_2, ..., x_{n}. Number x_{i} is the number of tokens given to each worker on the i-th day. Help him calculate for each of n days the number of tokens he can save.

-----Input-----

The first line of input contains three space-separated integers n, a, b (1 ≤ n ≤ 10^5; 1 ≤ a, b ≤ 10^9). The second line of input contains n space-separated integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^9).

-----Output-----

Output n space-separated integers. The i-th of them is the number of tokens Mashmokh can save on the i-th day.

-----Examples-----
Input
5 1 4
12 6 11 9 1

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

Output
1 0 1
Input
1 1 1
1

Output
0

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

import sys

[n,a,b] = list(map(int, sys.stdin.readline().split()))

buttons = list(map(int, sys.stdin.readline().split()))

res = []

for x in buttons:
	money = int(1.0 * x * a / b)
	# print("money =", money)
	rest = x - 1.0 * money * b / a
	# print("rest =", rest)
	res.append(int(rest))

print(" ".join(map(str, res)))


I found an interesting problem on https://codeforces.com/problemset/problem/416/A:
A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show.

The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions:  Is it true that y is strictly larger than number x?  Is it true that y is strictly smaller than number x?  Is it true that y is larger than or equal to number x?  Is it true that y is smaller than or equal to number x?

On each question the host answers truthfully, "yes" or "no".

Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print "Impossible".

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 10000) — the number of questions (and answers). Next n lines each contain one question and one answer to it. The format of each line is like that: "sign x answer", where the sign is:  ">" (for the first type queries),  "<" (for the second type queries),  ">=" (for the third type queries),  "<=" (for the fourth type queries).

All values of x are integer and meet the inequation  - 10^9 ≤ x ≤ 10^9. The answer is an English letter "Y" (for "yes") or "N" (for "no").

Consequtive elements in lines are separated by a single space.

-----Output-----

Print any of such integers y, that the answers to all the queries are correct. The printed number y must meet the inequation  - 2·10^9 ≤ y ≤ 2·10^9. If there are many answers, print any of them. If such value doesn't exist, print word "Impossible" (without the quotes).

-----Examples-----
Input
4
>= 1 Y
< 3 N
<= -3 N
> 55 N

Output
17

Input
2
> 100 Y
< -100 Y

Output
Impossible

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/416/B:
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.

Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter t_{ij} units of time.

Order is important everywhere, so the painters' work is ordered by the following rules:  Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j + 1)-th painter (if j < n);  each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on;  each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest;  as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter.

Given that the painters start working at time 0, find for each picture the time when it is ready for sale.

-----Input-----

The first line of the input contains integers m, n (1 ≤ m ≤ 50000, 1 ≤ n ≤ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers t_{i}1, t_{i}2, ..., t_{in} (1 ≤ t_{ij} ≤ 1000), where t_{ij} is the time the j-th painter needs to work on the i-th picture.

-----Output-----

Print the sequence of m integers r_1, r_2, ..., r_{m}, where r_{i} is the moment when the n-th painter stopped working on the i-th picture.

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

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

Output
7 8 13 21

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

m, n=map(int, input().split())
a=[0]*8
for i in range(m):
    x=list(map(int, input().split()))
    for j in range(1, n+1):
        a[j]=max(a[j], a[j-1])+x[j-1]
    print(a[n], end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/416/C:
Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!

A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system.

There are n booking requests received by now. Each request is characterized by two numbers: c_{i} and p_{i} — the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly.

We know that for each request, all c_{i} people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment.

Unfortunately, there only are k tables in the restaurant. For each table, we know r_{i} — the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing.

Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 1000) — the number of requests from visitors. Then n lines follow. Each line contains two integers: c_{i}, p_{i} (1 ≤ c_{i}, p_{i} ≤ 1000) — the size of the group of visitors who will come by the i-th request and the total sum of money they will pay when they visit the restaurant, correspondingly.

The next line contains integer k (1 ≤ k ≤ 1000) — the number of tables in the restaurant. The last line contains k space-separated integers: r_1, r_2, ..., r_{k} (1 ≤ r_{i} ≤ 1000) — the maximum number of people that can sit at each table.

-----Output-----

In the first line print two integers: m, s — the number of accepted requests and the total money you get from these requests, correspondingly.

Then print m lines — each line must contain two space-separated integers: the number of the accepted...

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

n = int(input())
x = []
for i in range(n):
  c, p = map(int, input().split())
  x += [(p, c, i)]
k = int(input())
r = list(map(int, input().split()))
s = 0
q = []
for (v, c, a) in reversed(sorted(x)):
  p = -1
  u = 100000
  for  (j, z) in enumerate(r):
    if c <= z < u:
      p = j
      u = z
  if p > -1:
    r[p] = 0
    q += [(a, p)]
    s += v
print(len(q), s)
for (i, j) in q:
  print(i + 1, j + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/416/D:
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.

Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a_1, a_2, ..., a_{n}, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.

Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of a_{i} may be unknown. Such values are represented by number -1.

For a given sequence a = (a_1, a_2, ..., a_{n}), which consists of positive integers and values -1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values -1 may correspond to an arbitrary positive integer and the values a_{i} > 0 must be equal to the corresponding elements of sought consecutive record of the progressions.

Let us remind you that a finite sequence c is called an arithmetic progression if the difference c_{i} + 1 - c_{i} of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 2·10^5) — the number of elements in the sequence. The second line contains integer values a_1, a_2, ..., a_{n} separated by a space (1 ≤ a_{i} ≤ 10^9 or a_{i} =  - 1).

-----Output-----

Print the minimum number of arithmetic progressions that you need to write one after another to get sequence a. The positions marked as...

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

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

while i < n:
    ans += 1
    i1 = i
    while i1 < n and a[i1] == -1:
        i1 += 1
    if i1 == n:
        break
    i2 = i1 + 1
    while i2 < n and a[i2] == -1:
        i2 += 1
    if i2 == n:
        break
    dist = i2 - i1
    step = (a[i2] - a[i1]) // dist
    if (a[i2] - a[i1]) % dist != 0 or (step > 0 and a[i1] - (i1 - i) * step <= 0):
        i = i2
        continue
    i3 = i2 + 1
    while i3 < n:
        nxt = a[i2] + step * (i3 - i2)
        if nxt <= 0 or (a[i3] != -1 and a[i3] != nxt):
            break
        i3 += 1

    i = i3
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/417/A:
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds.

The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of c problems, the winners of the round are the first n people in the rating list. Each of the additional elimination rounds consists of d problems. The winner of the additional round is one person. Besides, k winners of the past finals are invited to the finals without elimination.

As a result of all elimination rounds at least n·m people should go to the finals. You need to organize elimination rounds in such a way, that at least n·m people go to the finals, and the total amount of used problems in all rounds is as small as possible.

-----Input-----

The first line contains two integers c and d (1 ≤ c, d ≤ 100) — the number of problems in the main and additional rounds, correspondingly. The second line contains two integers n and m (1 ≤ n, m ≤ 100). Finally, the third line contains an integer k (1 ≤ k ≤ 100) — the number of the pre-chosen winners.

-----Output-----

In the first line, print a single integer — the minimum number of problems the jury needs to prepare.

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

Output
2

Input
2 2
2 1
2

Output
0

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

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

s = max(n * m - k, 0)
res = 0
while s:
    if c > min(s, n) * d:
        res += min(s,n) * d
    else:
        res += c
    s -= min(s,n)
print(res)