I found an interesting problem on https://codeforces.com/problemset/problem/538/D:
Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.

Igor's chessboard is a square of size n × n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves.

Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to n. Let's assign to each square a pair of integers (x, y) — the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (dx, dy); using this move, the piece moves from the field (x, y) to the field (x + dx, y + dy). You can perform the move if the cell (x + dx, y + dy) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (x, y) and (x + dx, y + dy) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess).

Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 50).

The next n lines contain n characters each describing the position offered by Igor. The j-th character of the i-th string can have the following values: o — in this case the field (i, j) is occupied by a piece and the field may or may not be attacked by some other piece; x — in this case field (i, j) is...

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

n = int(input())
b = [input() for i in range(n)]
h = [[False] * n for i in range(n)]
p = [[i, j] for i in range(n) for j in range(n) if b[i][j] == 'o']
v = [['.'] * (2 * n - 1) for i in range(2 * n - 1)]
def on(x, y):
    return x in range(n) and y in range(n)
def proc(dx, dy):
    for pi in p:
        if on(pi[0] + dx, pi[1] + dy) and b[pi[0] + dx][pi[1] + dy] == '.':
            return
    v[dx + n - 1][dy + n - 1] = 'x'
    for pi in p:
        if on(pi[0] + dx, pi[1] + dy):
            h[pi[0] + dx][pi[1] + dy] = True
for i in range(-(n - 1), n):
    for j in range(-(n - 1), n):
        proc(i, j)
if any(b[i][j] == 'x' and not h[i][j] for i in range(n) for j in range(n)):
    print('NO')
else:
    print('YES')
    v[n - 1][n - 1] = 'o'
    for vi in v:
        print(''.join(vi))


I found an interesting problem on https://codeforces.com/problemset/problem/538/E:
Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.

There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to m are placed in such a way that each number appears exactly in one leaf.

Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.

Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.

-----Input-----

The first line contains a single integer n — the number of nodes in the tree (1 ≤ n ≤ 2·10^5).

Each of the next n - 1 lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n) — the ends of the edge of the tree; the edge leads from node u_{i} to node v_{i}. It is guaranteed that the described graph is a rooted tree, and the root is the node 1.

-----Output-----

Print two space-separated integers — the maximum possible and the minimum possible result of the game.

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

Output
3...

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

import sys
fin = sys.stdin
n = int(fin.readline())
ut = [-1] * n
vc = [[] for i in range(0, n)]
cvc = [[] for i in range(0, n)]
nr = [0] * n
for i in range(0, n - 1):
    a, b = [int(number) for number in fin.readline().split()]
    a -= 1
    b -= 1
    vc[a].append(b)
    cvc[b].append(a)
    nr[a] += 1
size = [0] * n
mx = [0] * n
def nonzero(x):
    if not x:
        return 0
    return 1
stk = []
size = [0] * n
for i in range(0, n):
    if nr[i] == 0:
        stk.append(i)
        size[i] = 1
order = []
while nonzero(stk):
    x = stk.pop(-1)
    order.append(x)
    for p in cvc[x]:
        nr[p] -= 1
        if nr[p] == 0:
            stk.append(p)
h = [0] * n
for i in range(n - 1, -1, -1):
    x = order[i]
    for p in vc[x]:
        h[p] = h[x] + 1
#parcurg
for x in order:
    for p in vc[x]:
        size[x] += size[p]
#maximum
def solv(tp, mx):
    for x in order:
        if h[x] % 2 == tp:
            r = 999999999
            for p in vc[x]:
                r = min(r, size[p] - mx[p] + 1)
            if r == 999999999:
                r = 1
            mx[x] = r
        else:
            r = 0
            for p in vc[x]:
                r += size[p] - mx[p]
            mx[x] = r + 1
solv(0, mx)
print(size[0] - mx[0] + 1, end = ' ')
solv(1, mx)
print(size[0] - mx[0] + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/538/F:
Andrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment.

The teacher gave Andrew an array of n numbers a_1, ..., a_{n}. After that he asked Andrew for each k from 1 to n - 1 to build a k-ary heap on the array and count the number of elements for which the property of the minimum-rooted heap is violated, i.e. the value of an element is less than the value of its parent.

Andrew looked up on the Wikipedia that a k-ary heap is a rooted tree with vertices in elements of the array. If the elements of the array are indexed from 1 to n, then the children of element v are elements with indices k(v - 1) + 2, ..., kv + 1 (if some of these elements lie outside the borders of the array, the corresponding children are absent). In any k-ary heap every element except for the first one has exactly one parent; for the element 1 the parent is absent (this element is the root of the heap). Denote p(v) as the number of the parent of the element with the number v. Let's say that for a non-root element v the property of the heap is violated if a_{v} < a_{p}(v).

Help Andrew cope with the task!

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 2·10^5).

The second line contains n space-separated integers a_1, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9).

-----Output-----

in a single line print n - 1 integers, separate the consecutive numbers with a single space — the number of elements for which the property of the k-ary heap is violated, for k = 1, 2, ..., n - 1.

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

Output
3 2 1 0

Input
6
2 2 2 2 2 2

Output
0 0 0 0 0

-----Note-----

Pictures with the heaps for the first sample are given below; elements for which the property of the heap is violated are marked with red. [Image] [Image] $\therefore$ [Image]

In the second sample all elements are equal, so the property holds for all pairs.

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

import sys

def myargsort(a):
    b = list(zip(a, list(range(0, len(a)))))
    b.sort()
    r = [pr[1] for pr in b]
    return r

fin = sys.stdin
n = int(fin.readline())
a = [int(number) for number in fin.readline().split()]
p = myargsort(a)
p.reverse()
j = 0
aib = [0] * (n + 1)

def ultb(x):
    return -(x ^ (-x)) // 2

def add(p, a, aib, n):
    while p <= n:
        aib[p] += a
        p += ultb(p)
def suma(p, aib):
    r = 0
    while p > 0:
        r += aib[p]
        p -= ultb(p)
    return r

for i in range(0, n):
    add(i + 1, 1, aib, n)
r = [0] * (n + 1)
for i in range(0, n):
    if i > 0 and a[i - 1] > a[i]:
        r[1] += 1
    while j < n and a[p[j]] == a[p[i]]:
        add(p[j] + 1, -1, aib, n)
        j += 1
    k = 2
    while k < n and p[i] * k + 1 < n:
        dr = min(n, p[i] * k + k + 1)
        st = p[i] * k + 2
        r[k] += suma(dr, aib) - suma(st - 1, aib)
        k += 1
print(*r[1:n])


I found an interesting problem on https://codeforces.com/problemset/problem/540/A:
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.

 [Image]

The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of disks on the combination lock.

The second line contains a string of n digits — the original state of the disks.

The third line contains a string of n digits — Scrooge McDuck's combination that opens the lock.

-----Output-----

Print a single integer — the minimum number of moves Scrooge McDuck needs to open the lock.

-----Examples-----
Input
5
82195
64723

Output
13

-----Note-----

In the sample he needs 13 moves:

  1 disk: $8 \rightarrow 7 \rightarrow 6$  2 disk: $2 \rightarrow 3 \rightarrow 4$  3 disk: $1 \rightarrow 0 \rightarrow 9 \rightarrow 8 \rightarrow 7$  4 disk: $9 \rightarrow 0 \rightarrow 1 \rightarrow 2$  5 disk: $5 \rightarrow 4 \rightarrow 3$

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

n = int(input())

a, b = input(), input()

s = 0

for i in range(n):
	tmp = ord(a[i]) - ord(b[i])
	tmp %= 10
	if tmp > 5:
		s += 10 - tmp
	else:
		s += tmp

print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/540/B:
Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.

Vova has already wrote k tests and got marks a_1, ..., a_{k}. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.

-----Input-----

The first line contains 5 space-separated integers: n, k, p, x and y (1 ≤ n ≤ 999, n is odd, 0 ≤ k < n, 1 ≤ p ≤ 1000, n ≤ x ≤ n·p, 1 ≤ y ≤ p). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games.

The second line contains k space-separated integers: a_1, ..., a_{k} (1 ≤ a_{i} ≤ p) — the marks that Vova got for the tests he has already written.

-----Output-----

If Vova cannot achieve the desired result, print "-1".

Otherwise, print n - k space-separated integers — the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.

-----Examples-----
Input
5 3 5 18 4
3 5 4

Output
4 1

Input
5 3 5 16 4
5 5 5

Output
-1

-----Note-----

The median of sequence a_1, ..., a_{n} where n is odd (in this problem n is always odd) is the element staying on (n + 1) / 2 position in the sorted list of a_{i}.

In...

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

n, k, p, x, y = [int(k) for k in input().split()]
scores = [int(k) for k in input().split()] #k numbers here
s = sum(scores)
number_needed = (n-1)/2
B = x - s
done = False

while not done:
    num_above = 0
    num_below = 0
    for i in scores:
        if i >= y:
            num_above +=1
        else:
            num_below += 1
    num_needed_above = int(number_needed + 1 - num_above)
    num_needed_below = int(number_needed - num_below)
    if num_needed_below < 0:
        print(-1)
        break
    if num_needed_above  < 0 :
        num_needed_above = 0
        num_needed_below = n - k
    #print(num_needed_above, num_needed_below)
    rem_sum = y*num_needed_above + 1*num_needed_below
    if rem_sum <= B:
        for i in range(num_needed_below):
            print(1, end = " ")
        for i in range(num_needed_above):
            print(y, end = " ")
        #print(y, num_needed_above,num_needed_below, rem_sum)
        done = True
    else:
        y = y+1
        if y > p:
            print(-1)
            break
    #print(num_needed_above,num_needed_below, rem_sum)


I found an interesting problem on https://codeforces.com/problemset/problem/540/C:
You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.

The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.

Let's number the rows with integers from 1 to n from top to bottom and the columns with integers from 1 to m from left to right. Let's denote a cell on the intersection of the r-th row and the c-th column as (r, c).

You are staying in the cell (r_1, c_1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (r_2, c_2) since the exit to the next level is there. Can you do this?

-----Input-----

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

Each of the next n lines describes the initial state of the level of the cave, each line consists of m characters "." (that is, intact ice) and "X" (cracked ice).

The next line contains two integers, r_1 and c_1 (1 ≤ r_1 ≤ n, 1 ≤ c_1 ≤ m) — your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (r_1, c_1), that is, the ice on the starting cell is initially cracked.

The next line contains two integers r_2 and c_2 (1 ≤ r_2 ≤ n, 1 ≤ c_2 ≤ m) — the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one.

-----Output-----

If you can reach the destination, print 'YES', otherwise print 'NO'.

-----Examples-----
Input
4...

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

def pick(D, v):
	return D[v[0]][v[1]]

def getNeighbours(A, x, y, t='.'):
	neighbours = []
	if x > 0 and A[x-1][y] == t:
		neighbours.append((x-1, y))
	if y > 0 and A[x][y-1] == t:
		neighbours.append((x, y-1))
	if x < len(A)-1 and A[x+1][y] == t:
		neighbours.append((x+1, y))
	if y < len(A[0])-1 and A[x][y+1] == t:
		neighbours.append((x, y+1))
	return neighbours

def countNeighbours(A, x, y, t='.'):
	return len(getNeighbours(A, x, y, t))

def hasPath(A, xs, ys, xe, ye):
	# Pre-set end-location 'dot'
	A[xe][ye] = '.'

	D = [[-1 for _ in range(len(A[0]))] for _ in range(len(A))]
	D[xs][ys] = 0
	Q = [(xs, ys)]

	# BFS
	while len(Q) > 0:
		u = Q.pop()
		for v in getNeighbours(A, *u):
			if pick(D, v) == -1:
				Q.insert(0, v)
				D[v[0]][v[1]] = pick(D, u) + 1

	return D[xe][ye] != -1

def solve(A, r1, c1, r2, c2):
	if r1 == r2 and c1 == c2:
		if countNeighbours(A, r1, c1) > 0:
			return True
		else:
			return False
	elif (r2, c2) in getNeighbours(A, r1, c1) or (r2, c2) in getNeighbours(A, r1, c1, 'X'):
		if A[r2][c2] == 'X':
			return True
		else:
			if countNeighbours(A, r2, c2) > 0:
				return True
			else:
				return False
	elif A[r2][c2] == '.':
		if countNeighbours(A, r2, c2) >= 2 and hasPath(A, r1, c1, r2, c2):
			return True
		else:
			return False
	elif A[r2][c2] == 'X':
		if countNeighbours(A, r2, c2) > 0 and hasPath(A, r1, c1, r2, c2):
			return True
		else:
			return False

def main():
	n, m = list(map(int, input().split()))
	A = [list(input()) for _ in range(n)]
	r1, c1 = [int(w)-1 for w in input().split()]
	r2, c2 = [int(w)-1 for w in input().split()]

	ans = solve(A, r1, c1, r2, c2)
	print('YES' if ans else 'NO')

main()


I found an interesting problem on https://codeforces.com/problemset/problem/540/D:
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.

-----Input-----

The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.

-----Output-----

Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10^{ - 9}.

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

Output
0.333333333333 0.333333333333 0.333333333333

Input
2 1 2

Output
0.150000000000 0.300000000000 0.550000000000

Input
1 1 3

Output
0.057142857143 0.657142857143 0.285714285714

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

r, s, p = [int(x) for x in input().split()]
dp = [[[0 for i in range(105)] for j in range(105)] for k in range(105)]

dp[r][s][p] = 1

for i in range(r, -1, -1):
    for j in range(s, -1, -1):
        for k in range(p,-1, -1):

            dnr = i * j + j * k + i * k

            if i > 0 and j > 0:
                dp[i][j - 1][k] += (i * j * dp[i][j][k]) / dnr
            if j > 0 and k > 0:
                dp[i][j][k - 1] += (j * k * dp[i][j][k]) / dnr
            if k > 0 and i > 0:
                dp[i - 1][j][k] += (k * i * dp[i][j][k]) / dnr

roc, sci, pap = [0] * 3

for i in range(105):
    roc += dp[i][0][0]
    sci += dp[0][i][0]
    pap += dp[0][0][i]

print(roc, sci, pap)


I found an interesting problem on https://codeforces.com/problemset/problem/540/E:
There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and p_{i} > p_{j}.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of swap operations applied to the sequence.

Each of the next n lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 10^9, a_{i} ≠ b_{i}) — the arguments of the swap operation.

-----Output-----

Print a single integer — the number of inversions in the resulting sequence.

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

Output
4

Input
3
1 6
3 4
2 5

Output
15

-----Note-----

In the first sample the sequence is being modified as follows: $\{1,2,3,4,5, \ldots \} \rightarrow \{1,4,3,2,5, \ldots \} \rightarrow \{2,4,3,1,5 \ldots \}$. It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4).

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

import sys
from collections import defaultdict

class BIT():
    def __init__(self, n):
        self.n = n
        self.tree = [0] * n

    def _get_sum(self, r):
        '''
        sum on interval [0, r)
        '''
        result = 0
        while r > 0:
            result += self.tree[r-1]
            r &= (r - 1)
        return result

    def get_sum(self, l, r):
        '''
        sum on interval [l, r)
        '''
        return self._get_sum(r) - self._get_sum(l)

    def add(self, i, value=1):
        while i < self.n:
            self.tree[i] += value
            i |= (i + 1)

reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__

n = int(input())
swaps = []
for _ in range(n):
    i, j = list(map(int, input().split()))
    swaps.append(i)
    swaps.append(j)

pos = defaultdict(list)
for i, val in enumerate(swaps):
    pos[val].append(i)

c = 0
prev = -1
compr = [0] * (2*n)
decompr = {}
for val in sorted(swaps):
    if prev == val: continue
    for j in pos[val]:
        compr[j] = c
    decompr[c] = val
    c += 1
    prev = val

arr = list(range(c))
for t in range(n):
    i, j = compr[t<<1], compr[t<<1|1]
    arr[i], arr[j] = arr[j], arr[i]

bit = BIT(c)
total_inv = 0
for i, val in enumerate(arr):
    total_inv += bit.get_sum(val+1, c)
    if i != val:
        total_inv += abs(decompr[val] - decompr[i]) - abs(val - i)
    bit.add(val)
print(total_inv)


I found an interesting problem on https://codeforces.com/problemset/problem/541/C:
Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function $g : \{1,2, \ldots, n \} \rightarrow \{1,2, \ldots, n \}$, that for any $x \in \{1,2, \ldots, n \}$ the formula g(g(x)) = g(x) holds.

Let's denote as f^{(}k)(x) the function f applied k times to the value x. More formally, f^{(1)}(x) = f(x), f^{(}k)(x) = f(f^{(}k - 1)(x)) for each k > 1.

You are given some function $f : \{1,2, \ldots, n \} \rightarrow \{1,2, \ldots, n \}$. Your task is to find minimum positive integer k such that function f^{(}k)(x) is idempotent.

-----Input-----

In the first line of the input there is a single integer n (1 ≤ n ≤ 200) — the size of function f domain.

In the second line follow f(1), f(2), ..., f(n) (1 ≤ f(i) ≤ n for each 1 ≤ i ≤ n), the values of a function.

-----Output-----

Output minimum k such that function f^{(}k)(x) is idempotent.

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

Output
1

Input
3
2 3 3

Output
2

Input
3
2 3 1

Output
3

-----Note-----

In the first sample test function f(x) = f^{(1)}(x) is already idempotent since f(f(1)) = f(1) = 1, f(f(2)) = f(2) = 2, f(f(3)) = f(3) = 2, f(f(4)) = f(4) = 4.

In the second sample test:   function f(x) = f^{(1)}(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2;  function f(x) = f^{(2)}(x) is idempotent since for any x it is true that f^{(2)}(x) = 3, so it is also true that f^{(2)}(f^{(2)}(x)) = 3.

In the third sample test:   function f(x) = f^{(1)}(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2;  function f(f(x)) = f^{(2)}(x) isn't idempotent because f^{(2)}(f^{(2)}(1)) = 2 but f^{(2)}(1) = 3;  function f(f(f(x))) = f^{(3)}(x) is idempotent since it is identity function: f^{(3)}(x) = x for any $x \in \{1,2,3 \}$ meaning that the formula f^{(3)}(f^{(3)}(x)) = f^{(3)}(x) also holds.

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

n = int(input())
f = list(map(int, input().split()))
for i in range(n):
    f[i] -= 1

def gcd(a, b):
    while (a != 0 and b != 0):
        a, b = b, a % b
    return a + b

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

ans = 1
minn = 0

for i in range(n):
    vis = [False] * n
    cur = i
    st, pr = 0, 0
    while not vis[cur]:
        vis[cur] = True
        cur = f[cur]
        st += 1
    fs = cur
    cur = i
    while cur != fs:
        pr += 1
        cur = f[cur]
    minn = max(minn, pr)
    ans = lcm(ans, st - pr)

print(((max(0, minn - 1))// ans + 1) * ans)


I found an interesting problem on https://codeforces.com/problemset/problem/543/A:
Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly a_{i} bugs in every line of code that he writes.

Let's call a sequence of non-negative integers v_1, v_2, ..., v_{n} a plan, if v_1 + v_2 + ... + v_{n} = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v_1 lines of the given task, then the second programmer writes v_2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total.

Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod.

-----Input-----

The first line contains four integers n, m, b, mod (1 ≤ n, m ≤ 500, 0 ≤ b ≤ 500; 1 ≤ mod ≤ 10^9 + 7) — the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer.

The next line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 500) — the number of bugs per line for each programmer.

-----Output-----

Print a single integer — the answer to the problem modulo mod.

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

Output
10

Input
3 6 5 1000000007
1 2 3

Output
0

Input
3 5 6 11
1 2 1

Output
0

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

def main():
    n, m, b, mod = list(map(int, input().split()))
    row_zero = [1] + [0] * b
    b += 1
    dp = [[0] * b for _ in range(m)]
    for a in list(map(int, input().split())):
        cur = row_zero
        for nxt in dp:
            for i, u in zip(list(range(a, b)), cur):
                nxt[i] = (nxt[i] + u) % mod
            cur = nxt
    print(sum(dp[-1]) % mod)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/544/A:
You are given a string q. A sequence of k strings s_1, s_2, ..., s_{k} is called beautiful, if the concatenation of these strings is string q (formally, s_1 + s_2 + ... + s_{k} = q) and the first characters of these strings are distinct.

Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.

-----Input-----

The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.

The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.

-----Output-----

If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s_1, s_2, ..., s_{k}.

If there are multiple possible answers, print any of them.

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

Output
YES
abca

Input
2
aaacas

Output
YES
aaa
cas

Input
4
abc

Output
NO

-----Note-----

In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.

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

k, q, v, s = int(input()), input(), 'YES', set()
for ch in q:
    if k == 0 or ch in s:
        v += ch
    else:
        v += '\n' + ch
        s.add(ch)
        k -= 1
print('NO' if k else v)


I found an interesting problem on https://codeforces.com/problemset/problem/544/E:
You have multiset of n strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position i and some letter c of the English alphabet, such that this string is the only string in the multiset that has letter c in position i.

For example, a multiset of strings {"abc", "aba", "adc", "ada"} are not easy to remember. And multiset {"abc", "ada", "ssa"} is easy to remember because:   the first string is the only string that has character c in position 3;  the second string is the only string that has character d in position 2;  the third string is the only string that has character s in position 2.

You want to change your multiset a little so that it is easy to remember. For a_{ij} coins, you can change character in the j-th position of the i-th string into any other lowercase letter of the English alphabet. Find what is the minimum sum you should pay in order to make the multiset of strings easy to remember.

-----Input-----

The first line contains two integers n, m (1 ≤ n, m ≤ 20) — the number of strings in the multiset and the length of the strings respectively. Next n lines contain the strings of the multiset, consisting only of lowercase English letters, each string's length is m.

Next n lines contain m integers each, the i-th of them contains integers a_{i}1, a_{i}2, ..., a_{im} (0 ≤ a_{ij} ≤ 10^6).

-----Output-----

Print a single number — the answer to the problem.

-----Examples-----
Input
4 5
abcde
abcde
abcde
abcde
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Output
3

Input
4 3
abc
aba
adc
ada
10 10 10
10 1 10
10 10 10
10 1 10

Output
2

Input
3 3
abc
ada
ssa
1 1 1
1 1 1
1 1 1

Output
0

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

from sys import stdin
n,m=list(map(int,stdin.readline().strip().split()))
s=[]
for i in range(n):
    s.append(list(map(ord,list(stdin.readline().strip()))))
    for j in range(m):
        s[-1][j]=s[-1][j]-97
ct=[tuple(map(int,stdin.readline().strip().split())) for i in range(n)]
mc=[[0 for i in range(22)] for j in range(22)]
c=[[0 for i in range(22)] for i in  range(22)]
maxmask=1<<n
maxx=10**8
dp=[maxx for i in range(maxmask)]
for i in range(n):
    for j in range(m):
        mx=0
        for k in range(n):
            if s[i][j]==s[k][j]:
                mc[i][j]|=(1<<k)
                c[i][j]+=ct[k][j]
                mx=max(mx,ct[k][j])
        c[i][j]-=mx
dp[0]=0
for i in range(1,maxmask):
    for j in range(n):
        if i & (1<<j):
            lb=j
            break
    mask=i
    for j in range(m):
        dp[mask]=min(dp[mask],dp[mask ^(1<<lb)]+ct[lb][j],dp[mask & (mask ^ mc[lb][j])]+c[lb][j])
print(dp[(1<<n)-1])


I found an interesting problem on https://codeforces.com/problemset/problem/545/A:
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.

There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an n × n matrix А: there is a number on the intersection of the і-th row and j-th column that describes the result of the collision of the і-th and the j-th car:    - 1: if this pair of cars never collided.  - 1 occurs only on the main diagonal of the matrix.  0: if no car turned over during the collision.  1: if only the i-th car turned over during the collision.  2: if only the j-th car turned over during the collision.  3: if both cars turned over during the collision.

Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100) — the number of cars.

Each of the next n lines contains n space-separated integers that determine matrix A.

It is guaranteed that on the main diagonal there are  - 1, and  - 1 doesn't appear anywhere else in the matrix.

It is guaranteed that the input is correct, that is, if A_{ij} = 1, then A_{ji} = 2, if A_{ij} = 3, then A_{ji} = 3, and if A_{ij} = 0, then A_{ji} = 0.

-----Output-----

Print the number of good cars and in the next line print their space-separated indices in the increasing order.

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

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

Output
0

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

n = int(input())
ar = []
for i in range(n):
    ar.append(list(map(int, input().split())))
ans = [0] * n
for i in range(n):
    for j in range(n):
        if ar[i][j] == 1 or ar[i][j] == 3:
            ans[i] = 1
        if ar[i][j] == 2:
            ans[j] = 1
ans1 = []
for i in range(n):
    if ans[i] == 0:
        ans1.append(i + 1)
print(len(ans1))
for i in range(len(ans1)):
    print(ans1[i], end = ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/545/B:
Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:

We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that s_{i} isn't equal to t_{i}.

As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t.

It's time for Susie to go to bed, help her find such string p or state that it is impossible.

-----Input-----

The first line contains string s of length n.

The second line contains string t of length n.

The length of string n is within range from 1 to 10^5. It is guaranteed that both strings contain only digits zero and one.

-----Output-----

Print a string of length n, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line "impossible" (without the quotes).

If there are multiple possible answers, print any of them.

-----Examples-----
Input
0001
1011

Output
0011

Input
000
111

Output
impossible

-----Note-----

In the first sample different answers are possible, namely — 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101.

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

s = input()
t = input()

n = len(s)
dist = 0

for i in range(n):
    if (s[i] !=t[i]):
        dist += 1

if dist%2==1:
    print("impossible")
else:
    p = ""
    flag = 0
    for i in range(n):
        if (s[i] != t[i] and flag == 0):
            p += s[i]
            flag = flag^1
        elif (s[i] != t[i] and flag == 1):
            p += t[i]
            flag = flag^1
        elif (s[i] == t[i]):
            p += s[i]
    print(p)


I found an interesting problem on https://codeforces.com/problemset/problem/545/C:
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.

There are n trees located along the road at points with coordinates x_1, x_2, ..., x_{n}. Each tree has its height h_{i}. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [x_{i} - h_{i}, x_{i}] or [x_{i};x_{i} + h_{i}]. The tree that is not cut down occupies a single point with coordinate x_{i}. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.

-----Input-----

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

Next n lines contain pairs of integers x_{i}, h_{i} (1 ≤ x_{i}, h_{i} ≤ 10^9) — the coordinate and the height of the і-th tree.

The pairs are given in the order of ascending x_{i}. No two trees are located at the point with the same coordinate.

-----Output-----

Print a single number — the maximum number of trees that you can cut down by the given rules.

-----Examples-----
Input
5
1 2
2 1
5 10
10 9
19 1

Output
3

Input
5
1 2
2 1
5 10
10 9
20 1

Output
4

-----Note-----

In the first sample you can fell the trees like that:   fell the 1-st tree to the left — now it occupies segment [ - 1;1]  fell the 2-nd tree to the right — now it occupies segment [2;3]  leave the 3-rd tree — it occupies point 5  leave the 4-th tree — it occupies point 10  fell the 5-th tree to the right — now it occupies segment [19;20]

In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].

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

n = int(input())
x = [0] * (n + 1)
h = [0] * (n + 1)

for i in range(n):
    x[i], h[i] = (int(c) for c in input().split())

h[n] = 1
x[n] = x[n-1] + h[n-1] + 1

if n == 1:
    print(1)
    return

left = [0] * n
right = [0] * n

left[0] = 1
if x[0] + h[0] < x[1]:
    right[0] = 1

for i in range(1, n):
    if x[i] + h[i] < x[i + 1]:
        right[i] = max(right[i-1], left[i-1]) + 1
    else:
        right[i] = max(right[i-1], left[i-1])

    if x[i] - h[i] > x[i-1] + h[i-1]:
        left[i] = max(right[i-1], left[i-1]) + 1
    elif x[i] - h[i] > x[i-1]:
        left[i] = left[i-1] + 1
    else:
        left[i] = max(right[i-1], left[i-1])

print(max(left[n-1], right[n-1]))


I found an interesting problem on https://codeforces.com/problemset/problem/545/D:
Little girl Susie went shopping with her mom and she wondered how to improve service quality.

There are n people in the queue. For each person we know time t_{i} needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed.

Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.

-----Input-----

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

The next line contains n integers t_{i} (1 ≤ t_{i} ≤ 10^9), separated by spaces.

-----Output-----

Print a single number — the maximum number of not disappointed people in the queue.

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

Output
4

-----Note-----

Value 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-

n = int(input())
T = sorted(list(map(int,input().split())))

total_time = 0
ans = 0
for i in range(n):
    if total_time <= T[i]:
        total_time += T[i]
        ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/545/E:
Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.

Let's assume that we are given a connected weighted undirected graph G = (V, E) (here V is the set of vertices, E is the set of edges). The shortest-path tree from vertex u is such graph G_1 = (V, E_1) that is a tree with the set of edges E_1 that is the subset of the set of edges of the initial graph E, and the lengths of the shortest paths from u to any vertex to G and to G_1 are the same.

You are given a connected weighted undirected graph G and vertex u. Your task is to find the shortest-path tree of the given graph from vertex u, the total weight of whose edges is minimum possible.

-----Input-----

The first line contains two numbers, n and m (1 ≤ n ≤ 3·10^5, 0 ≤ m ≤ 3·10^5) — the number of vertices and edges of the graph, respectively.

Next m lines contain three integers each, representing an edge — u_{i}, v_{i}, w_{i} — the numbers of vertices connected by an edge and the weight of the edge (u_{i} ≠ v_{i}, 1 ≤ w_{i} ≤ 10^9). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices.

The last line of the input contains integer u (1 ≤ u ≤ n) — the number of the start vertex.

-----Output-----

In the first line print the minimum total weight of the edges of the tree.

In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order.

If there are multiple answers, print any of them.

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

Output
2
1 2

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

Output
4
2 3 4

-----Note-----

In the first sample there are two possible shortest path trees:

  with edges 1 – 3...

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

from collections import defaultdict, deque, Counter, OrderedDict
import bisect, sys, threading
from heapq import *

def main():
    n, m = list(map(int, input().split()))
    adj = [[] for i in range(n + 1)]

    for i in range(m):
        a, b, c = list(map(int, input().split()))
        adj[a].append((b, c, i))
        adj[b].append((a, c, i))
    v = int(input())

    visited, ans, tw = [0] * (n + 1), [], 0
    Q = [(0, 0, v, 0)]

    while Q:
        w, lew, u, ei = heappop(Q)
        if visited[u]: continue
        visited[u] = 1
        ans.append(str(ei + 1))
        tw += lew
        for to, we, eii in adj[u]:
            if not visited[to]:
                heappush(Q, (we + w, we, to, eii))

    print(tw)
    print(" ".join(ans[1:]))

def __starting_point():
    """sys.setrecursionlimit(200000)
    threading.stack_size(10240000)"""
    thread = threading.Thread(target=main)
    thread.start()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/546/A:
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).

He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?

-----Input-----

The first line contains three positive integers k, n, w (1  ≤  k, w  ≤  1000, 0 ≤ n ≤ 10^9), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants.

-----Output-----

Output one integer — the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0.

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

Output
13

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


I found an interesting problem on https://codeforces.com/problemset/problem/546/B:
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin.

For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors.

Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.

-----Input-----

First line of input consists of one integer n (1 ≤ n ≤ 3000).

Next line consists of n integers a_{i} (1 ≤ a_{i} ≤ n), which stand for coolness factor of each badge.

-----Output-----

Output single integer — minimum amount of coins the colonel has to pay.

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

Output
1
Input
5
1 2 3 2 5

Output
2

-----Note-----

In first sample test we can increase factor of first badge by 1.

In second sample test we can increase factors of the second and the third badge by 1.

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

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

assert(len(bs) == n)

bs = sorted(bs)

last = -1
cost = 0
for b in bs:
    if b <= last:
        diff = last - b
        b += diff + 1
        cost += diff + 1
    last = b

print(cost)


I found an interesting problem on https://codeforces.com/problemset/problem/546/C:
Two bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game.

The rules are following. On each turn a fight happens. Each of them picks card from the top of his stack and puts on the table. The one whose card value is bigger wins this fight and takes both cards from the table to the bottom of his stack. More precisely, he first takes his opponent's card and puts to the bottom of his stack, and then he puts his card to the bottom of his stack. If after some turn one of the player's stack becomes empty, he loses and the other one wins.

You have to calculate how many fights will happen and who will win the game, or state that game won't end.

-----Input-----

First line contains a single integer n (2 ≤ n ≤ 10), the number of cards.

Second line contains integer k_1 (1 ≤ k_1 ≤ n - 1), the number of the first soldier's cards. Then follow k_1 integers that are the values on the first soldier's cards, from top to bottom of his stack.

Third line contains integer k_2 (k_1 + k_2 = n), the number of the second soldier's cards. Then follow k_2 integers that are the values on the second soldier's cards, from top to bottom of his stack.

All card values are different.

-----Output-----

If somebody wins in this game, print 2 integers where the first one stands for the number of fights before end of game and the second one is 1 or 2 showing which player has won.

If the game won't end and will continue forever output  - 1.

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

Output
6 2
Input
3
1 2
2 1 3

Output
-1

-----Note-----

First sample:  [Image]

Second sample:  [Image]

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

import sys

n = int(input())
d1 = list(map(int, input().split(" ")))
d2 = list(map(int, input().split(" ")))
k1 = d1[0]
k2 = d2[0]
d1.remove(d1[0])
d2.remove(d2[0])

moves = 0

while True:
    if moves > 500000:
        print(-1)
        return
    a = d1[0]
    d1.remove(d1[0])
    b = d2[0]
    d2.remove(d2[0])
    if a > b:
        moves += 1
        d1.append(b)
        d1.append(a)
        if len(d2) == 0:
            print(str(moves) + " 1")
            return
    if b > a:
        moves +=1
        d2.append(a)
        d2.append(b)
        if len(d1) == 0:
            print(str(moves) + " 2")
            return


I found an interesting problem on https://codeforces.com/problemset/problem/546/E:
In the country there are n cities and m bidirectional roads between them. Each city has an army. Army of the i-th city consists of a_{i} soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at moving along at most one road.

Check if is it possible that after roaming there will be exactly b_{i} soldiers in the i-th city.

-----Input-----

First line of input consists of two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 200).

Next line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 100).

Next line contains n integers b_1, b_2, ..., b_{n} (0 ≤ b_{i} ≤ 100).

Then m lines follow, each of them consists of two integers p and q (1 ≤ p, q ≤ n, p ≠ q) denoting that there is an undirected road between cities p and q.

It is guaranteed that there is at most one road between each pair of cities.

-----Output-----

If the conditions can not be met output single word "NO".

Otherwise output word "YES" and then n lines, each of them consisting of n integers. Number in the i-th line in the j-th column should denote how many soldiers should road from city i to city j (if i ≠ j) or how many soldiers should stay in city i (if i = j).

If there are several possible answers you may output any of them.

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

Output
YES
1 0 0 0
2 0 0 0
0 5 1 0
0 0 2 1

Input
2 0
1 2
2 1

Output
NO

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

from collections import defaultdict
import sys

N, M = input().split(' ')
N, M = int(N), int(M)
A = input().split(' ')
A = list(map(int, A))
B = input().split(' ')
B = list(map(int, B))

if (sum(A) != sum(B)):
    print('NO')
    return

neighbours = defaultdict(lambda: defaultdict(int))
flow = defaultdict(int)

def left(i):
    return 'l ' + str(i)

def right(i):
    return 'r ' + str(i)

for i in range(1, N+1):
    for j in range(1, N+1):
        flow[left(i), right(j)] = 0
        flow[right(i), left(j)] = 0

for i, capacity in enumerate(A):
    neighbours['source'][left(i + 1)] = capacity
for i, capacity in enumerate(B):
    neighbours[right(i + 1)]['sink'] = capacity
for i in range(1, N+1):
    neighbours[left(i)][right(i)] = float('inf')

for m in range(M):
    p, q = input().split(' ')
    p, q = int(p), int(q)
    neighbours[left(p)][right(q)] = float('inf')
    neighbours[left(q)][right(p)] = float('inf')

def search():
    visited = set()
    def dfs(v):
        if v in visited:
            return False
        if v == 'sink':
            return ['sink']
        visited.add(v)
        for n in neighbours[v]:
            capacity = neighbours[v][n]
            if capacity > 0:
                res = dfs(n)
                if res:
                    return [v] + res
    return dfs('source')

total_flow = 0

def augment_edge(a, b, amount):
    neighbours[a][b] -= amount
    neighbours[b][a] += amount
    flow[a, b] += amount

def augment(path):
    capacity = float('inf')
    for i in range(len(path) - 1):
        capacity = min(capacity, neighbours[path[i]][path[i+1]])
    # print('augment', path, capacity)
    for i in range(len(path) - 1):
        augment_edge(path[i], path[i+1], capacity)
    nonlocal total_flow
    total_flow += capacity

while True:
    res = search()
    if res is None:
        break
    else:
        augment(res)

if (total_flow == sum(A)):
    print("YES")
    for i in range(1, N+1):
        for j in range(1, N+1):
            print(flow[left(i), right(j)] - flow[right(j),...


I found an interesting problem on https://codeforces.com/problemset/problem/547/A:
Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h_1 and height of Abol is h_2. Each second, Mike waters Abol and Xaniar.

 [Image]

So, if height of Xaniar is h_1 and height of Abol is h_2, after one second height of Xaniar will become $(x_{1} h_{1} + y_{1}) \operatorname{mod} m$ and height of Abol will become $(x_{2} h_{2} + y_{2}) \operatorname{mod} m$ where x_1, y_1, x_2 and y_2 are some integer numbers and $a \operatorname{mod} b$ denotes the remainder of a modulo b.

Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a_1 and height of Abol is a_2.

Mike has asked you for your help. Calculate the minimum time or say it will never happen.

-----Input-----

The first line of input contains integer m (2 ≤ m ≤ 10^6).

The second line of input contains integers h_1 and a_1 (0 ≤ h_1, a_1 < m).

The third line of input contains integers x_1 and y_1 (0 ≤ x_1, y_1 < m).

The fourth line of input contains integers h_2 and a_2 (0 ≤ h_2, a_2 < m).

The fifth line of input contains integers x_2 and y_2 (0 ≤ x_2, y_2 < m).

It is guaranteed that h_1 ≠ a_1 and h_2 ≠ a_2.

-----Output-----

Print the minimum number of seconds until Xaniar reaches height a_1 and Abol reaches height a_2 or print -1 otherwise.

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

Output
3

Input
1023
1 2
1 0
1 2
1 1

Output
-1

-----Note-----

In the first sample, heights sequences are following:

Xaniar: $4 \rightarrow 0 \rightarrow 1 \rightarrow 2$

Abol: $0 \rightarrow 3 \rightarrow 4 \rightarrow 1$

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

mod = int(input())
h1, a1 = map(int, input().split())
x1, y1 = map(int, input().split())
h2, a2 = map(int, input().split())
x2, y2 = map(int, input().split())

q1 = 0
while h1 != a1:
    h1 = (h1 * x1 + y1) % mod
    q1 += 1
    if q1 > 2 * mod:
        print(-1)
        return

q2 = 0
t2 = h2
while t2 != a2:
    t2 = (t2 * x2 + y2) % mod
    q2 += 1
    if q2 > 2 * mod:
        print(-1)
        return

if q1 == q2:
    print(q1)
    return

c1 = 1
h1 = (a1 * x1 + y1) % mod
while h1 != a1:
    h1 = (h1 * x1 + y1) % mod
    c1 += 1
    if c1 > 2 * mod:
        print(-1)
        return

c2 = 0
nx2 = 1
ny2 = 0

for i in range(c1):
    nx2 = (nx2 * x2) % mod
    ny2 = (ny2 * x2 + y2) % mod

for i in range(q1):
    h2 = (h2 * x2 + y2) % mod

while h2 != a2:
    h2 = (h2 * nx2 + ny2) % mod
    c2 += 1
    if c2 > 2 * mod:
        print(-1)
        return

print(q1 + c1 * c2)


I found an interesting problem on https://codeforces.com/problemset/problem/548/A:
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s.

 [Image]

He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k messages in his own bag, each was a palindrome string and all those strings had the same length.

He asked you to help him and tell him if he has worn his own back-bag. Check if the given string s is a concatenation of k palindromes of the same length.

-----Input-----

The first line of input contains string s containing lowercase English letters (1 ≤ |s| ≤ 1000).

The second line contains integer k (1 ≤ k ≤ 1000).

-----Output-----

Print "YES"(without quotes) if he has worn his own back-bag or "NO"(without quotes) otherwise.

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

Output
NO

Input
saddastavvat
2

Output
YES

-----Note-----

Palindrome is a string reading the same forward and backward.

In the second sample, the faxes in his back-bag can be "saddas" and "tavvat".

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

import math
def main():
    s = input()
    k = int(input())
    ns = len(s)
    if ns % k != 0:
        print('NO')
        return
    k = int(ns/k)
    while len(s)>0:
        crt = s[:k]
        crt1 = crt[::-1]
        s = s[k:]
        if crt != crt1:
            print('NO')
            return
    print('YES')

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/548/B:
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. [Image]

They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.

Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.

Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.

-----Input-----

The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000).

The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes).

The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.

-----Output-----

After each round, print the current score of the bears.

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

Output
3
4
3
3
4

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

n, m, q = map(int, input().split())
def csum(row):
    return max(map(len, "".join(map(str, row)).split("0")))

grid = ["".join(input().split()) for i in range(n)]
score = [max(map(len, row.split("0"))) for row in grid]
for i in range(q):
    i, j = map(int, input().split())
    row = grid[i-1]
    row = row[:j-1] + ("1" if row[j-1] == "0" else "0") + row[j:]
    grid[i-1] = row
    score[i-1] = csum(row)
    print(max(score))


I found an interesting problem on https://codeforces.com/problemset/problem/549/A:
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them.

In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 × 2 square, such that from the four letters of this square you can make word "face".

You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.

-----Input-----

The first line contains two space-separated integers, n and m (1 ≤ n, m ≤ 50) — the height and the width of the image, respectively.

Next n lines define the image. Each line contains m lowercase Latin letters.

-----Output-----

In the single line print the number of faces on the image.

-----Examples-----
Input
4 4
xxxx
xfax
xcex
xxxx

Output
1

Input
4 2
xx
cf
ae
xx

Output
1

Input
2 3
fac
cef

Output
2

Input
1 4
face

Output
0

-----Note-----

In the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column:  [Image]

In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.

In the third sample two faces are shown:  $\text{fac}$

In the fourth sample the image has no faces on it.

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

a,b=input().split()
n=int(a)
m=int(b)
t=["" for j in range(n)]
for i in range(n):
	t[i]=input()
v=0

def test(a,b,c,d):
	g=[0 for i in range(200)]
	g[ord(a)]+=1
	g[ord(b)]+=1
	g[ord(c)]+=1
	g[ord(d)]+=1
	return (g[ord('f')]*g[ord('a')]*g[ord('c')]*g[ord('e')]==1)

for i in range(n-1):
	for j in range(m-1):
		if test(t[i][j],t[i+1][j],t[i][j+1],t[i+1][j+1]):v+=1
print(v)


I found an interesting problem on https://codeforces.com/problemset/problem/549/C:
There are n cities in Westeros. The i-th city is inhabited by a_{i} people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.

The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.

Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.

-----Input-----

The first line contains two positive space-separated integers, n and k (1 ≤ k ≤ n ≤ 2·10^5) — the initial number of cities in Westeros and the number of cities at which the game ends.

The second line contains n space-separated positive integers a_{i} (1 ≤ a_{i} ≤ 10^6), which represent the population of each city in Westeros.

-----Output-----

Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.

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

Output
Stannis

Input
3 1
2 2 1

Output
Daenerys

Input
6 3
5 20 12 7 14 101

Output
Stannis

-----Note-----

In the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.

In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins.

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

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

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

cnt1 = 0
for i in range(n):
    cnt1 += a[i] % 2
ans = ['Daenerys' , 'Stannis']
if(n == k):
    print(ans[sum(a)%2])
    return
if(cnt1 > (n - k)//2 and (n - cnt1) > (n - k)//2):
    print(ans[(n - k) % 2])
else:
    if(cnt1 > (n - k) //2):
        cnt0 = n - cnt1
        print(ans[(sum(a) - ((n - k) - cnt0))%2])

    else:

        print(ans[(sum(a) - cnt1)%2])


I found an interesting problem on https://codeforces.com/problemset/problem/549/D:
The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.

Let's consider a rectangular image that is represented with a table of size n × m. The table elements are integers that specify the brightness of each pixel in the image.

A feature also is a rectangular table of size n × m. Each cell of a feature is painted black or white.

To calculate the value of the given feature at the given image, you must perform the following steps. First the table of the feature is put over the table of the image (without rotations or reflections), thus each pixel is entirely covered with either black or white cell. The value of a feature in the image is the value of W - B, where W is the total brightness of the pixels in the image, covered with white feature cells, and B is the total brightness of the pixels covered with black feature cells.

Some examples of the most popular Haar features are given below.  [Image]

Your task is to determine the number of operations that are required to calculate the feature by using the so-called prefix rectangles.

A prefix rectangle is any rectangle on the image, the upper left corner of which coincides with the upper left corner of the image.

You have a variable value, whose value is initially zero. In one operation you can count the sum of pixel values at any prefix rectangle, multiply it by any integer and add to variable value.

You are given a feature. It is necessary to calculate the minimum number of operations required to calculate the values of this attribute at an arbitrary image. For a better understanding of the statement, read the explanation of the first sample.

-----Input-----

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — the number of rows and columns in the feature.

Next n lines contain the description of the feature. Each...

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

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

a = []
k = []

n, m = map(int, input().split())
for i in range(n + 1):
    if i < n:
        a.append([-1 if c == 'B' else 1 for c in input()])
    k.append([0 for j in range(m + 1)])

ans = 0

for i in range(n - 1, -1, -1):
    add = 0
    for j in range(m - 1, -1, -1):
        k[i][j] = add + k[i + 1][j]
        if k[i][j] != a[i][j]:
            ans += 1
            add += a[i][j] - k[i][j]
            k[i][j] = a[i][j]

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/549/E:
Berlanders like to eat cones after a hard day. Misha Square and Sasha Circle are local authorities of Berland. Each of them controls its points of cone trade. Misha has n points, Sasha — m. Since their subordinates constantly had conflicts with each other, they decided to build a fence in the form of a circle, so that the points of trade of one businessman are strictly inside a circle, and points of the other one are strictly outside. It doesn't matter which of the two gentlemen will have his trade points inside the circle.

Determine whether they can build a fence or not.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 10000), numbers of Misha's and Sasha's trade points respectively.

The next n lines contains pairs of space-separated integers M_{x}, M_{y} ( - 10^4 ≤ M_{x}, M_{y} ≤ 10^4), coordinates of Misha's trade points.

The next m lines contains pairs of space-separated integers S_{x}, S_{y} ( - 10^4 ≤ S_{x}, S_{y} ≤ 10^4), coordinates of Sasha's trade points.

It is guaranteed that all n + m points are distinct.

-----Output-----

The only output line should contain either word "YES" without quotes in case it is possible to build a such fence or word "NO" in the other case.

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

Output
NO

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

Output
YES

-----Note-----

In the first sample there is no possibility to separate points, because any circle that contains both points ( - 1, 0), (1, 0) also contains at least one point from the set (0,  - 1), (0, 1), and vice-versa: any circle that contains both points (0,  - 1), (0, 1) also contains at least one point from the set ( - 1, 0), (1, 0)

In the second sample one of the possible solution is shown below. Misha's points are marked with red colour and Sasha's are marked with blue. [Image]

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


I found an interesting problem on https://codeforces.com/problemset/problem/549/G:
Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of n Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, so each person agrees to swap places with the person right behind him for just 1 dollar. More formally, if person a stands just behind person b, then person a can pay person b 1 dollar, then a and b get swapped. Of course, if person a has zero dollars, he can not swap places with person b.

Residents of Berland are strange people. In particular, they get upset when there is someone with a strictly smaller sum of money in the line in front of them.

Can you help the residents of Berland form such order in the line so that they were all happy? A happy resident is the one who stands first in the line or the one in front of who another resident stands with not less number of dollars. Note that the people of Berland are people of honor and they agree to swap places only in the manner described above.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 200 000) — the number of residents who stand in the line.

The second line contains n space-separated integers a_{i} (0 ≤ a_{i} ≤ 10^9), where a_{i} is the number of Berland dollars of a man standing on the i-th position in the line. The positions are numbered starting from the end of the line.

-----Output-----

If it is impossible to make all the residents happy, print ":(" without the quotes. Otherwise, print in the single line n space-separated integers, the i-th of them must be equal to the number of money of the person on position i in the new line. If there are multiple answers, print any of them.

-----Examples-----
Input
2
11 8

Output
9 10
Input
5
10 9 7 10 6

Output
:(

Input
3
12 3 3

Output
4 4 10

-----Note-----

In the first sample two residents should swap places, after that the first resident has 10 dollars and he is at...

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

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

for i in range(len(line)):
    line[i]+=i
line.sort()
for i in range(len(line)):
    line[i]-=i

impossivel = False
for i in range(len(line)-1):
    if(line[i]>line[i+1]):
        impossivel = True
        break
if(impossivel):
    print(":(")
else:
    print(" ".join([str(i) for i in line]))


I found an interesting problem on https://codeforces.com/problemset/problem/549/H:
The determinant of a matrix 2 × 2 is defined as follows:$\operatorname{det} \left(\begin{array}{ll}{a} & {b} \\{c} & {d} \end{array} \right) = a d - b c$

A matrix is called degenerate if its determinant is equal to zero.

The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements.

You are given a matrix $A = \left(\begin{array}{ll}{a} & {b} \\{c} & {d} \end{array} \right)$. Consider any degenerate matrix B such that norm ||A - B|| is minimum possible. Determine ||A - B||.

-----Input-----

The first line contains two integers a and b (|a|, |b| ≤ 10^9), the elements of the first row of matrix A.

The second line contains two integers c and d (|c|, |d| ≤ 10^9) the elements of the second row of matrix A.

-----Output-----

Output a single real number, the minimum possible value of ||A - B||. Your answer is considered to be correct if its absolute or relative error does not exceed 10^{ - 9}.

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

Output
0.2000000000

Input
1 0
0 1

Output
0.5000000000

-----Note-----

In the first sample matrix B is $\left(\begin{array}{ll}{1.2} & {1.8} \\{2.8} & {4.2} \end{array} \right)$

In the second sample matrix B is $\left(\begin{array}{ll}{0.5} & {0.5} \\{0.5} & {0.5} \end{array} \right)$

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

import sys
A, B, C, D = [int(i) for i in sys.stdin.read().split()]
if A == 0 and B == 0 and C == 0 and D == 0:
    print(0)
else:
    k1 = abs(A + D + B + C)
    k2 = abs(A + D - B - C)
    k3 = abs(A - D + B - C)
    k4 = abs(A - D - B + C)
    print(abs(A * D - B * C) / max(k1, k2, k3, k4))


I found an interesting problem on https://codeforces.com/problemset/problem/550/A:
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).

-----Input-----

The only line of input contains a string s of length between 1 and 10^5 consisting of uppercase Latin letters.

-----Output-----

Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.

-----Examples-----
Input
ABA

Output
NO

Input
BACFAB

Output
YES

Input
AXBYBXA

Output
NO

-----Note-----

In the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".

In the second sample test there are the following occurrences of the substrings: BACFAB.

In the third sample test there is no substring "AB" nor substring "BA".

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

s=input()
ab=0
ba=0
aba=0
bab=0
n=len(s)
if n<4:
	print("NO")
else:
	for i in range(n-1):
		if s[i:i+2]=="AB":ab+=1
	for i in range(n-1):
		if s[i:i+2]=="BA":ba+=1
	for i in range(n-2):
		if s[i:i+3]=="ABA":aba+=1
	for i in range(n-2):
		if s[i:i+3]=="BAB":bab+=1
	if ab==0 or ba==0:
		print("NO")
	elif ab==1 and ba==1:
		if bab==1 or aba==1:
			print("NO")
		else:
			print("YES")
	elif ab==1 and ba==2:
		if bab==1 and aba==1:print("NO")
		else:print("YES")
	elif ab==2 and ba==1:
		if bab==1 and aba==1:print("NO")
		else:print("YES")
	else:print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/550/B:
You have n problems. You have estimated the difficulty of the i-th one as integer c_{i}. Now you want to prepare a problemset for a contest, using some of the problems you've made.

A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must be at least l and at most r. Also, you think that the difference between difficulties of the easiest and the hardest of the chosen problems must be at least x.

Find the number of ways to choose a problemset for the contest.

-----Input-----

The first line contains four integers n, l, r, x (1 ≤ n ≤ 15, 1 ≤ l ≤ r ≤ 10^9, 1 ≤ x ≤ 10^6) — the number of problems you have, the minimum and maximum value of total difficulty of the problemset and the minimum difference in difficulty between the hardest problem in the pack and the easiest one, respectively.

The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^6) — the difficulty of each problem.

-----Output-----

Print the number of ways to choose a suitable problemset for the contest.

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

Output
2

Input
4 40 50 10
10 20 30 25

Output
2

Input
5 25 35 10
10 10 20 10 20

Output
6

-----Note-----

In the first example two sets are suitable, one consisting of the second and third problem, another one consisting of all three problems.

In the second example, two sets of problems are suitable — the set of problems with difficulties 10 and 30 as well as the set of problems with difficulties 20 and 30.

In the third example any set consisting of one problem of difficulty 10 and one problem of difficulty 20 is suitable.

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

from itertools import *
n, l, r, x = map(lambda x: int(x), input().split())
c = sorted(list(map(lambda x: int(x), input().split())))
variants = []
for i in range(2, n + 1):
    variants.extend(list(combinations(c, i)))
counter = 0
for i in range(len(variants)):
    sum_var = sum(variants[i])
    if sum_var >= l and sum_var <= r and (variants[i][-1] - variants[i][0]) >= x:
        counter += 1
print (counter)


I found an interesting problem on https://codeforces.com/problemset/problem/550/C:
You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes.

Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-negative integer, doesn't have leading zeroes and is divisible by 8. After the removing, it is forbidden to rearrange the digits.

If a solution exists, you should print it.

-----Input-----

The single line of the input contains a non-negative integer n. The representation of number n doesn't contain any leading zeroes and its length doesn't exceed 100 digits.

-----Output-----

Print "NO" (without quotes), if there is no such way to remove some digits from number n.

Otherwise, print "YES" in the first line and the resulting number after removing digits from number n in the second line. The printed number must be divisible by 8.

If there are multiple possible answers, you may print any of them.

-----Examples-----
Input
3454

Output
YES
344

Input
10

Output
YES
0

Input
111111

Output
NO

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

n1 = input()
n = []
for i in n1:
    n.append(int(i))
k = len(n)

for i in range(k):
    if (n[i] % 8) == 0:
        print("YES")
        print(n[i])
        return

if k > 1:
    for i in range(k):
        t = n[i] * 10
        for j in range(i+1, k):
            if (t+n[j]) % 8 == 0:
                print("YES")
                print(t+n[j])
                return
if k > 2:
    for i in range(k):
        t = n[i]*100
        for j in range(i+1, k):
            l = n[j]*10
            for e in range(j+1, k):
                #print(t, l, n[e])
                if (t+l+n[e]) % 8 == 0:
                    print("YES")
                    print(t+l+n[e])
                    return
print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/550/D:
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.

Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.

-----Input-----

The single line of the input contains integer k (1 ≤ k ≤ 100) — the required degree of the vertices of the regular graph.

-----Output-----

Print "NO" (without quotes), if such graph doesn't exist.

Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.

The description of the made graph must start with numbers n and m — the number of vertices and edges respectively.

Each of the next m lines must contain two integers, a and b (1 ≤ a, b ≤ n, a ≠ b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.

The constructed graph must contain at most 10^6 vertices and 10^6 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 10^6 vertices and at most 10^6 edges).

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

Output
YES
2 1
1 2

-----Note-----

In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.

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

import math,string,itertools,fractions,heapq,collections,re,array,bisect
from itertools import chain, dropwhile, permutations, combinations
from collections import defaultdict, deque

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

def main1(k):
    # works correctly, but too slow and generates many more vertices than necessary.
    # doesn't pass the time constraint with this implementation. (prints 10^5 lines)
    # ==> use the editorial solution below.
    if k%2==0:
        print("NO")
        return
    print("YES")
    n = 2*(k**2-k+1)
    m = n*k//2
    print(n, m)
    i = 0
    g = [[] for i in range(n+1)]
    print(1,n//2+1)
    off = 1
    for j in range(0,k-1,2):
        j1 = off + j+1
        j2 = off + j+2
        print(off,j1)
        print(off,j2)
        l1 = off + k + j*(k-1)
        l2 = off + k + (j+1)*(k-1)
        for l in range(k-1):
            print(j1, l1+l)
            print(j2, l2+l)
            for m in range(k-1):
                print(l1+l,l2+m)
    off = n//2+1
    for j in range(0,k-1,2):
        j1 = off + j+1
        j2 = off + j+2
        print(off,j1)
        print(off,j2)
        l1 = off + k + j*(k-1)
        l2 = off + k + (j+1)*(k-1)
        for l in range(k-1):
            print(j1, l1+l)
            print(j2, l2+l)
            for m in range(k-1):
                print(l1+l,l2+m)

def main(k):
    # following the editorial algo
    if k%2==0:
        print("NO")
        return
    print("YES")
    if k==1:
        print("2 1")
        print("1 2")
        return
    n = 2*k+4
    m = n*k//2
    e = []
    e.extend([(1,n//2+1)])
    off = 1
    for j in range(off+1,off+k):
        e.extend([(off, j)])
    for j in range(off+1,off+k):
        for i in range(j+1,off+k):
            if (i==j+1 and (j-off)%2==1):# or (j==off+1 and i==off+k-1):
            #if (i==j+1 and i%2==0) or (j==off+1 and i==off+k-1):
                continue
            e.extend([(j,i)])
        e.extend([(j,off+k),(j,off+k+1)])
    e.extend([(off+k,off+k+1)])
    off = n//2+1
    for j in...


I found an interesting problem on https://codeforces.com/problemset/problem/550/E:
Implication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false.

Implication is written by using character '$\rightarrow$', and the arguments and the result of the implication are written as '0' (false) and '1' (true). According to the definition of the implication:

$0 \rightarrow 0 = 1$

$0 \rightarrow 1 = 1$

$1 \rightarrow 0 = 0$

$1 \rightarrow 1 = 1$

When a logical expression contains multiple implications, then when there are no brackets, it will be calculated from left to fight. For example,

$0 \rightarrow 0 \rightarrow 0 =(0 \rightarrow 0) \rightarrow 0 = 1 \rightarrow 0 = 0$.

When there are brackets, we first calculate the expression in brackets. For example,

$0 \rightarrow(0 \rightarrow 0) = 0 \rightarrow 1 = 1$.

For the given logical expression $a_{1} \rightarrow a_{2} \rightarrow a_{3} \rightarrow \cdots \cdots a_{n}$ determine if it is possible to place there brackets so that the value of a logical expression is false. If it is possible, your task is to find such an arrangement of brackets.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100 000) — the number of arguments in a logical expression.

The second line contains n numbers a_1, a_2, ..., a_{n} ($a_{i} \in \{0,1 \}$), which means the values of arguments in the expression in the order they occur.

-----Output-----

Print "NO" (without the quotes), if it is impossible to place brackets in the expression so that its value was equal to 0.

Otherwise, print "YES" in the first line and the logical expression with the required arrangement of brackets in the second line.

The expression should only contain characters '0', '1', '-' (character with ASCII code 45), '>' (character with ASCII code 62), '(' and ')'. Characters '-' and '>' can occur in an expression only paired like that: ("->") and represent implication. The total number of logical arguments (i.e. digits '0' and '1') in the expression must be equal to...

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

x = int(input())

seq = list(map(int, input().split(' ')))

if seq == [0]:
    print("YES")
    print(0)

elif seq == [0, 0]:
    print("NO")

elif seq == [1, 0]:
    print("YES")
    print('1->0')

elif seq == [0, 0, 0]:
    print("YES")
    print("(0->0)->0")

elif seq == [1, 0, 0]:
    print("NO")

elif seq[x-1] == 1:
    print("NO")

#ENDS IN 1

elif seq[x-2] == 1:
    print("YES")

    print('->'.join([str(x) for x in seq]))

#ENDS IN 10

elif seq == [1] * (x-2) + [0, 0]:
    print("NO")

#000 BELOW
elif seq[x-3] == 0:
    a = ('->'.join([str(x) for x in seq][0:x-3]))
    print("YES")

    print(a + '->(0->0)->0')

#100
else:
    last = 0
    for i in range(x-1):
        if seq[i] == 0 and seq[i+1] == 1:
            last = i
    seq[last] = '(0'
    seq[last+1] = '(1'
    seq[x-2] = '0))'
    print("YES")
    print('->'.join([str(x) for x in seq]))


I found an interesting problem on https://codeforces.com/problemset/problem/552/A:
Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right.

In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100) — the number of rectangles.

Each of the following n lines contains four integers x_1, y_1, x_2, y_2 (1 ≤ x_1 ≤ x_2 ≤ 100, 1 ≤ y_1 ≤ y_2 ≤ 100), where x_1 and y_1 are the number of the column and row of the lower left cell and x_2 and y_2 are the number of the column and row of the upper right cell of a rectangle.

-----Output-----

In a single line print the sum of all values in the cells of the table.

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

Output
10

Input
2
1 1 3 3
1 1 3 3

Output
18

-----Note-----

Note to the first sample test:

Values of the table in the first three rows and columns will be as follows:

121

121

110

So, the sum of values will be equal to 10.

Note to the second sample test:

Values of the table in the first three rows and columns will be as follows:

222

222

222

So, the sum of values will be equal to 18.

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

n = int(input())
ans = 0
for i in range(n):
	x1, y1, x2, y2 = map(int, input().split())
	ans += (abs(x2 - x1) + 1) * (abs(y2 - y1) + 1)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/552/B:
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers.

Vanya wants to know how many digits he will have to write down as he labels the books.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^9) — the number of books in the library.

-----Output-----

Print the number of digits needed to number all the books.

-----Examples-----
Input
13

Output
17

Input
4

Output
4

-----Note-----

Note to the first test. The books get numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, which totals to 17 digits.

Note to the second sample. The books get numbers 1, 2, 3, 4, which totals to 4 digits.

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

n = int(input())

def countd(n):
    d = 0
    while n >= 10**d:
        d += 1
    count = 0
    while d > 0:
        tens = 10 ** (d - 1)
        count += (n - tens + 1) * d
        n = tens - 1
        d -= 1
    return count

print(countd(n))


I found an interesting problem on https://codeforces.com/problemset/problem/552/C:
Vanya has a scales for weighing loads and weights of masses w^0, w^1, w^2, ..., w^100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance.

-----Input-----

The first line contains two integers w, m (2 ≤ w ≤ 10^9, 1 ≤ m ≤ 10^9) — the number defining the masses of the weights and the mass of the item.

-----Output-----

Print word 'YES' if the item can be weighted and 'NO' if it cannot.

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

Output
YES

Input
100 99

Output
YES

Input
100 50

Output
NO

-----Note-----

Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1.

Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100.

Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input.

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

w, m = list(map(int, str.split(input())))
bits = [0] * 100
for i in range(100):

    m, bits[i] = divmod(m, w)

for i in range(99):

    if 1 < bits[i] < w - 1:

        print("NO")
        return

    if bits[i] == w - 1:

        bits[i] = 0
        bits[i + 1] += 1
        carry = 0
        for j in range(i + 1, 100):

            carry, bits[j] = divmod(bits[j] + carry, w)

print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/552/D:
Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane.

Next n lines contain two integers each x_{i}, y_{i} ( - 100 ≤ x_{i}, y_{i} ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide.

-----Output-----

In the first line print an integer — the number of triangles with the non-zero area among the painted points.

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

Output
3

Input
3
0 0
1 1
2 0

Output
1

Input
1
1 1

Output
0

-----Note-----

Note to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).

Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).

Note to the third sample test. A single point doesn't form a single triangle.

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

__author__ = 'JS'
n = int(input())
k = [0] * 2015
X = [0] * 2015
Y = [0] * 2015
eps = 1e-12
for i in range (n):
    X[i], Y[i] = list(map(int, input().split(" ")))
ans = (n-2) * (n-1) * n // 6
sum = 0
for i in range (n):
    tot = 0
    cnt = 0
    for j in range (i+1, n):
        if X[i] != X[j]:
            k[tot] = (Y[j] - Y[i]) / (X[j] - X[i])
            tot += 1
        else:
            cnt += 1
    #cnt -= 1
    sum += (cnt - 1) * cnt // 2
    k = sorted(k[:tot]) + k[tot:]
    cnt = 1
    for j in range (1, tot):
        if abs(k[j] - k[j-1]) < eps:
           cnt += 1
        else:
            sum += (cnt - 1) * cnt // 2
            cnt = 1
    sum += (cnt -1) * cnt // 2
ans -= sum
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/552/E:
Vanya is doing his maths homework. He has an expression of form $x_{1} \diamond x_{2} \diamond x_{3} \diamond \ldots \diamond x_{n}$, where x_1, x_2, ..., x_{n} are digits from 1 to 9, and sign [Image] represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.

-----Input-----

The first line contains expression s (1 ≤ |s| ≤ 5001, |s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs  +  and  * .

The number of signs  *  doesn't exceed 15.

-----Output-----

In the first line print the maximum possible value of an expression.

-----Examples-----
Input
3+5*7+8*4

Output
303

Input
2+3*5

Output
25

Input
3*4*5

Output
60

-----Note-----

Note to the first sample test. 3 + 5 * (7 + 8) * 4 = 303.

Note to the second sample test. (2 + 3) * 5 = 25.

Note to the third sample test. (3 * 4) * 5 = 60 (also many other variants are valid, for instance, (3) * 4 * 5 = 60).

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

input_str = input()
str = '1*' + input_str + '*1'
str_len = len(str)
ans = 0

for i in range(2, str_len, 2):
    if (str[i - 1] == '*'):
        for j in range(i + 1, str_len, 2):
            if str[j] == '*':
                ans = max(ans, eval(str[:i] + '(' + str[i:j] + ')' + str[j:]))

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/554/A:
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?

Please help Haruhi solve this problem.

-----Input-----

The first line of input will be a single string s (1 ≤ |s| ≤ 20). String s consists only of lowercase English letters.

-----Output-----

Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.

-----Examples-----
Input
a

Output
51

Input
hi

Output
76

-----Note-----

In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.

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/554/B:
Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.

Return the maximum number of rows that she can make completely clean.

-----Input-----

The first line of input will be a single integer n (1 ≤ n ≤ 100).

The next n lines will describe the state of the room. The i-th line will contain a binary string with n characters denoting the state of the i-th row of the room. The j-th character on this line is '1' if the j-th square in the i-th row is clean, and '0' if it is dirty.

-----Output-----

The output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean.

-----Examples-----
Input
4
0101
1000
1111
0101

Output
2

Input
3
111
111
111

Output
3

-----Note-----

In the first sample, Ohana can sweep the 1st and 3rd columns. This will make the 1st and 4th row be completely clean.

In the second sample, everything is already clean, so Ohana doesn't need to do anything.

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

def main():
    n = int(input())
    lines = []
    d = {}
    for _ in range(n):
        l = input()
        if l not in d:
            d[l] = 0
        d[l] +=1
    ans = max(d.values())
    print(ans)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/556/A:
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.

Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.

Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

-----Input-----

First line of the input contains a single integer n (1 ≤ n ≤ 2·10^5), the length of the string that Andreid has.

The second line contains the string of length n consisting only from zeros and ones.

-----Output-----

Output the minimum length of the string that may remain after applying the described operations several times.

-----Examples-----
Input
4
1100

Output
0

Input
5
01010

Output
1

Input
8
11101111

Output
6

-----Note-----

In the first sample test it is possible to change the string like the following: $1100 \rightarrow 10 \rightarrow(\text{empty})$.

In the second sample test it is possible to change the string like the following: $01010 \rightarrow 010 \rightarrow 0$.

In the third sample test it is possible to change the string like the following: $11101111 \rightarrow 111111$.

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

n = int(input())
s = input()
k = 0
for i in s:
    if i == '0':
        k +=1
print(abs(n - 2 * k))