I found an interesting problem on https://codeforces.com/problemset/problem/501/A:
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contest started and Vasya submitted the problem d minutes after the contest started. As you know, on Codeforces the cost of a problem reduces as a round continues. That is, if you submit a problem that costs p points t minutes after the contest started, you get $\operatorname{max}(\frac{3p}{10}, p - \frac{p}{250} \times t)$ points.

Misha and Vasya are having an argument trying to find out who got more points. Help them to find out the truth.

-----Input-----

The first line contains four integers a, b, c, d (250 ≤ a, b ≤ 3500, 0 ≤ c, d ≤ 180).

It is guaranteed that numbers a and b are divisible by 250 (just like on any real Codeforces round).

-----Output-----

Output on a single line:

"Misha" (without the quotes), if Misha got more points than Vasya.

"Vasya" (without the quotes), if Vasya got more points than Misha.

"Tie" (without the quotes), if both of them got the same number of points.

-----Examples-----
Input
500 1000 20 30

Output
Vasya

Input
1000 1000 1 1

Output
Tie

Input
1500 1000 176 177

Output
Misha

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

def main():
	a, b, c, d = map(int, input().split())
	m = max((3*a/10),a - a/250 * c )
	v = max((3*b/10),b - b/250 * d )
	if m > v:
		print('Misha')
	elif v > m:
		print('Vasya')
	else:
		print('Tie')

def __starting_point():
	main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/501/B:
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.

Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.

-----Input-----

The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests.

Next q lines contain the descriptions of the requests, one per line.

Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.

The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.

-----Output-----

In the first line output the integer n — the number of users that changed their handles at least once.

In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.

Each user who changes the handle must occur exactly once in this description.

-----Examples-----
Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov

Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123

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

def main():
	q = int(input())
	old = []
	new = []
	for _ in range(q):
		a, b = list(input().split())
		#print(a, b)
		flag = 1
		for i in range(len(new)):
			if new[i] == a:
				new[i] = b
				flag = 0
				break
		if flag == 1:
			old.append(a)
			new.append(b)
	n = len(old)
	print(n)
	for i in range(n):
		print(old[i], new[i])

def __starting_point():
	main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/501/C:
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degree_{v} and s_{v}, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).

Next day Misha couldn't remember what graph he initially had. Misha has values degree_{v} and s_{v} left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 2^16), the number of vertices in the graph.

The i-th of the next lines contains numbers degree_{i} and s_{i} (0 ≤ degree_{i} ≤ n - 1, 0 ≤ s_{i} < 2^16), separated by a space.

-----Output-----

In the first line print number m, the number of edges of the graph.

Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b).

Edges can be printed in any order; vertices of the edge can also be printed in any order.

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

Output
2
1 0
2 0

Input
2
1 1
1 0

Output
1
0 1

-----Note-----

The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".

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

# 501C

__author__ = 'artyom'

read = lambda: map(int, input().split())
n = int(input())
graph = [set() for _ in range(n)]
degrees = []
adj = []
queue = []
for i in range(n):
  degree, s = read()
  degrees.append(degree)
  adj.append(s)
  if degree == 1:
    queue.append(i)

counter = 0
ans = ''
while queue:
  v = queue.pop()
  if degrees[v] == 0:
    continue
  s = adj[v]
  for u in graph[v]:
    s ^= u
  graph[s].add(v)
  graph[v].add(s)
  counter += 1
  ans += '\n' + str(s) + ' ' + str(v)
  degrees[s] -= 1
  if degrees[s] == 1:
    queue.append(s)

print(str(counter) + ans)


I found an interesting problem on https://codeforces.com/problemset/problem/501/D:
Let's define the sum of two permutations p and q of numbers 0, 1, ..., (n - 1) as permutation [Image], where Perm(x) is the x-th lexicographically permutation of numbers 0, 1, ..., (n - 1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.

For example, Perm(0) = (0, 1, ..., n - 2, n - 1), Perm(n! - 1) = (n - 1, n - 2, ..., 1, 0)

Misha has two permutations, p and q. Your task is to find their sum.

Permutation a = (a_0, a_1, ..., a_{n} - 1) is called to be lexicographically smaller than permutation b = (b_0, b_1, ..., b_{n} - 1), if for some k following conditions hold: a_0 = b_0, a_1 = b_1, ..., a_{k} - 1 = b_{k} - 1, a_{k} < b_{k}.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 200 000).

The second line contains n distinct integers from 0 to n - 1, separated by a space, forming permutation p.

The third line contains n distinct integers from 0 to n - 1, separated by spaces, forming permutation q.

-----Output-----

Print n distinct integers from 0 to n - 1, forming the sum of the given permutations. Separate the numbers by spaces.

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

Output
0 1

Input
2
0 1
1 0

Output
1 0

Input
3
1 2 0
2 1 0

Output
1 0 2

-----Note-----

Permutations of numbers from 0 to 1 in the lexicographical order: (0, 1), (1, 0).

In the first sample Ord(p) = 0 and Ord(q) = 0, so the answer is $\operatorname{Perm}((0 + 0) \operatorname{mod} 2) = \operatorname{Perm}(0) =(0,1)$.

In the second sample Ord(p) = 0 and Ord(q) = 1, so the answer is $\operatorname{Perm}((0 + 1) \operatorname{mod} 2) = \operatorname{Perm}(1) =(1,0)$.

Permutations of numbers from 0 to 2 in the lexicographical order: (0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0).

In the third sample Ord(p) = 3 and Ord(q) = 5, so the answer is $\operatorname{Perm}((3 + 5) \operatorname{mod} 6) = \operatorname{Perm}(2) =(1,0,2)$.

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

import sys

class SegmTree():
    def __init__(self, array=None):
        size = len(array)
        N = 1
        while N < size:
            N <<= 1
        self.N = N
        self.tree = [0] * (2*self.N)
        for i in range(size):
            self.tree[i+self.N] = array[i]
        self.build()

    def build(self):
        for i in range(self.N - 1, 0, -1):
            self.tree[i] = self.tree[i<<1] + self.tree[i<<1|1]

    def add(self, i, value=1):
        i += self.N
        while i > 0:
            self.tree[i] += value
            i >>= 1

    def get_sum(self, l, r):
        N = self.N
        l += N
        r += N
        result = 0
        while l < r:
            if l & 1:
                result += self.tree[l]
                l += 1
            if r & 1:
                r -= 1
                result += self.tree[r]
            l >>= 1
            r >>= 1
        return result

    def find_kth_nonzero(self, k):
        i = 1
        if k < 1 or k > self.tree[1]:
            return -1
        while i < self.N:
            i <<= 1
            if self.tree[i] < k:
                k -= self.tree[i]
                i |= 1
        return i - self.N

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

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

ord_p = [0] * n
ord_q = [0] * n

st = SegmTree([1] * n)
for i, val in enumerate(p):
    ord_p[i] = st.get_sum(0, val)
    st.add(val, -1)

st = SegmTree([1] * n)
for i, val in enumerate(q):
    ord_q[i] = st.get_sum(0, val)
    st.add(val, -1)

transfer = 0
for i in range(n-1, -1, -1):
    radix = n-i
    ord_p[i] = ord_p[i] + ord_q[i] + transfer
    if ord_p[i] < radix:
        transfer = 0
    else:
        transfer = 1
        ord_p[i] -= radix

st = SegmTree([1] * n)
for i in range(n):
    k = ord_p[i] + 1
    ord_q[i] = st.find_kth_nonzero(k)
    st.add(ord_q[i], -1)

print(*ord_q)


I found an interesting problem on https://codeforces.com/problemset/problem/505/A:
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into s to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.

You can choose any lowercase English letter, and insert it to any position of s, possibly to the beginning or the end of s. You have to insert a letter even if the given string is already a palindrome.

If it is possible to insert one lowercase English letter into s so that the resulting string will be a palindrome, print the string after the insertion. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one palindrome that can be obtained, you are allowed to print any of them.

-----Input-----

The only line of the input contains a string s (1 ≤ |s| ≤ 10). Each character in s is a lowercase English letter.

-----Output-----

If it is possible to turn s into a palindrome by inserting one lowercase English letter, print the resulting string in a single line. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one solution, any of them will be accepted.

-----Examples-----
Input
revive

Output
reviver

Input
ee

Output
eye
Input
kitayuta

Output
NA

-----Note-----

For the first sample, insert 'r' to the end of "revive" to obtain a palindrome "reviver".

For the second sample, there is more than one solution. For example, "eve" will also be accepted.

For the third sample, it is not possible to turn "kitayuta" into a palindrome by just inserting one letter.

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

import sys
s = input().strip()

def isPalin(n):
    if n[::-1] == n:
        return True
    return False

for i in range(len(s)+1):
    for j in "abcdefghijklmnopqrstuvwxyz":
        if isPalin(s[:i] + j + s[i:]):
            print(s[:i] + j + s[i:])
            return

print("NA")


I found an interesting problem on https://codeforces.com/problemset/problem/505/B:
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color c_{i}, connecting vertex a_{i} and b_{i}.

Mr. Kitayuta wants you to process the following q queries.

In the i-th query, he gives you two integers — u_{i} and v_{i}.

Find the number of the colors that satisfy the following condition: the edges of that color connect vertex u_{i} and vertex v_{i} directly or indirectly.

-----Input-----

The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively.

The next m lines contain space-separated three integers — a_{i}, b_{i} (1 ≤ a_{i} < b_{i} ≤ n) and c_{i} (1 ≤ c_{i} ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (a_{i}, b_{i}, c_{i}) ≠ (a_{j}, b_{j}, c_{j}).

The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries.

Then follows q lines, containing space-separated two integers — u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n). It is guaranteed that u_{i} ≠ v_{i}.

-----Output-----

For each query, print the answer in a separate line.

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

Output
2
1
0

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

Output
1
1
1
1
2

-----Note-----

Let's consider the first sample.  [Image]   The figure above shows the first sample.    Vertex 1 and vertex 2 are connected by color 1 and 2.  Vertex 3 and vertex 4 are connected by color 3.  Vertex 1 and vertex 4 are not connected by any single color.

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

from collections import defaultdict

def main():
    n, m = list(map(int, input().split()))
    edges = defaultdict(lambda: defaultdict(list))
    for _ in range(m):
        a, b, c = list(map(int, input().split()))
        d = edges[c]
        d[a].append(b)
        d[b].append(a)

    def dfs(t):
        chain.add(t)
        dd = color.get(t, ())
        for y in dd:
            if y not in chain:
                dfs(y)

    res = []
    chain = set()
    for _ in range(int(input())):
        a, b = list(map(int, input().split()))
        x = 0
        for color in list(edges.values()):
            chain.clear()
            dfs(a)
            if b in chain:
                x += 1
        res.append(str(x))
    print('\n'.join(res))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/505/D:
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.

Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.

Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (a_{i}, b_{i}) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (a_{i}, b_{i}), it will be possible to travel from city a_{i} to city b_{i} by using one or more teleportation pipes (but not necessarily from city b_{i} to city a_{i}). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.

-----Input-----

The first line contains two space-separated integers n and m (2 ≤ n ≤ 10^5, 1 ≤ m ≤ 10^5), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.

The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}), denoting that it must be possible to travel from city a_{i} to city b_{i} by using one or more teleportation pipes (but not necessarily from city b_{i} to city a_{i}). It is guaranteed that all pairs (a_{i}, b_{i}) are distinct.

-----Output-----

Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.

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

Output
3

Input
4 6
1...

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

def main():
    n, m = list(map(int, input().split()))
    n += 1
    cluster, dest, ab = list(range(n)), [0] * n, [[] for _ in range(n)]

    def root(x):
        if x != cluster[x]:
            cluster[x] = x = root(cluster[x])
        return x

    for _ in range(m):
        a, b = list(map(int, input().split()))
        ab[a].append(b)
        dest[b] += 1
        cluster[root(a)] = root(b)
    pool = [a for a, f in enumerate(dest) if not f]
    for a in pool:
        for b in ab[a]:
            dest[b] -= 1
            if not dest[b]:
                pool.append(b)
    ab = [True] * n
    for a, f in enumerate(dest):
        if f:
            ab[root(a)] = False
    print(n - sum(f and a == c for a, c, f in zip(list(range(n)), cluster, ab)))

def __starting_point():
    from sys import setrecursionlimit

    setrecursionlimit(100500)
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/507/A:
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.

Amr has n instruments, it takes a_{i} days to learn i-th instrument. Being busy, Amr dedicated k days to learn how to play the maximum possible number of instruments.

Amr asked for your help to distribute his free days between instruments so that he can achieve his goal.

-----Input-----

The first line contains two numbers n, k (1 ≤ n ≤ 100, 0 ≤ k ≤ 10 000), the number of instruments and number of days respectively.

The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 100), representing number of days required to learn the i-th instrument.

-----Output-----

In the first line output one integer m representing the maximum number of instruments Amr can learn.

In the second line output m space-separated integers: the indices of instruments to be learnt. You may output indices in any order.

if there are multiple optimal solutions output any. It is not necessary to use all days for studying.

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

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

Output
3
1 3 4
Input
1 3
4

Output
0

-----Note-----

In the first test Amr can learn all 4 instruments.

In the second test other possible solutions are: {2, 3, 5} or {3, 4, 5}.

In the third test Amr doesn't have enough time to learn the only presented instrument.

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

n, k = map(int, input().split())
l = [(int(x),i) for i,x in enumerate(input().split())]
l.sort()

days = 0
ans = []
for i in range(len(l)):
    days += l[i][0]

    if days <= k:
        ans.append(str(l[i][1]+1))

print(len(ans))
if len(ans) > 0:
    print(' '.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/507/B:
Amr loves Geometry. One day he came up with a very interesting problem.

Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y').

In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.

Help Amr to achieve his goal in minimum number of steps.

-----Input-----

Input consists of 5 space-separated integers r, x, y, x' y' (1 ≤ r ≤ 10^5,  - 10^5 ≤ x, y, x', y' ≤ 10^5), circle radius, coordinates of original center of the circle and coordinates of destination center of the circle respectively.

-----Output-----

Output a single integer — minimum number of steps required to move the center of the circle to the destination point.

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

Output
1

Input
1 1 1 4 4

Output
3

Input
4 5 6 5 6

Output
0

-----Note-----

In the first sample test the optimal way is to put a pin at point (0, 2) and rotate the circle by 180 degrees counter-clockwise (or clockwise, no matter).

[Image]

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

from math import sqrt
s = input().split()
s = [int(s) for s in s]
r,x,y,x1,y1 = s[0],s[1],s[2],s[3],s[4]
d = sqrt((x-x1)**2+(y-y1)**2)
ans = d // (r*2)
if d > ans*r*2:
    ans += 1
print(int(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/507/C:
Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.

Let's index all the leaf nodes from the left to the right from 1 to 2^{h}. The exit is located at some node n where 1 ≤ n ≤ 2^{h}, the player doesn't know where the exit is so he has to guess his way out!

Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules:  Character 'L' means "go to the left child of the current node";  Character 'R' means "go to the right child of the current node";  If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node;  If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command;  If he reached a leaf node that is not the exit, he returns to the parent of the current node;  If he reaches an exit, the game is finished.

Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit?

-----Input-----

Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2^{h}).

-----Output-----

Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm.

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

Output
2
Input
2 3

Output
5
Input
3 6

Output
10
Input
10 1024

Output
2046

-----Note-----

A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2^{h} nodes called leaves. Each node that is not a leaf has exactly two children, left and right one.

Following picture illustrates the sample test number 3. Nodes are labeled...

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

import math

def is_left_son(num):
    if num == num // 2 * 2:
        return True
    else:
        return False

def bin_search(place, depth):
    answer = ""
    length = 2 ** depth
    while length > 1:
        if place > length / 2:
            answer += "R"
            place -= length / 2
        else:
            answer += "L"
        length = length / 2
    return answer

def traverse(depth, route):
    answer = 0
    cur_vert = 1
    cur_dir = "L"
    while route:
        if route[0] == "R":
            cur_vert = cur_vert * 2 + 1
        else:
            cur_vert = cur_vert * 2
        if cur_dir == route[0]:
            answer += 1
        else:
            answer += 2**depth
        depth -= 1
        route = route[1:]
        cur_dir = "R" if is_left_son(cur_vert) else "L"
    return answer

h, n = (int(x) for x in input().split())
amount_visited = 0
cur_pos = 1
print(traverse(h, bin_search(n, h)))


I found an interesting problem on https://codeforces.com/problemset/problem/507/D:
Amr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't.

First he gave Amr two positive integers n and k. Then he asked Amr, how many integer numbers x > 0 exist such that:  Decimal representation of x (without leading zeroes) consists of exactly n digits;  There exists some integer y > 0 such that:   $y \operatorname{mod} k = 0$;  decimal representation of y is a suffix of decimal representation of x.

As the answer to this question may be pretty huge the teacher asked Amr to output only its remainder modulo a number m.

Can you help Amr escape this embarrassing situation?

-----Input-----

Input consists of three integers n, k, m (1 ≤ n ≤ 1000, 1 ≤ k ≤ 100, 1 ≤ m ≤ 10^9).

-----Output-----

Print the required number modulo m.

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

Output
4
Input
2 2 1000

Output
45
Input
5 3 1103

Output
590

-----Note-----

A suffix of a string S is a non-empty string that can be obtained by removing some number (possibly, zero) of first characters from S.

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

def get_input():
    hahaha=input()
    (n,k,m)=hahaha.split(sep=None, maxsplit=1000)
    return (int(n),int(k),int(m))
(n,k,m)=get_input()
f=[0 for i in range(k)]
s=0
for v in range(n):
    tens = 10**v%k
    f=[  (sum(   [f[(j+k-(x+1)*tens)%k] for x in range(9)] )+f[j])%m       for j in range(k)]
    for x in range(9):
        f[(x+1)*tens%k]+=1
    if n-v-1==0:
        s+=(f[0]%m)
    else:
        s+=f[0]*((10**(n-v-2)*9))%m
    f[0]=0
print(s%m)


I found an interesting problem on https://codeforces.com/problemset/problem/507/E:
Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.

Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads.

The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning.

The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan.

First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible.

Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional.

If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation.

Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired).

Can you help Walter complete his task and gain the gang's trust?

-----Input-----

The first line of input contains two integers n, m (2 ≤ n ≤ 10^5, $0 \leq m \leq \operatorname{min}(\frac{n(n - 1)}{2}, 10^{5})$), the...

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

from sys import *
from collections import *
s = stdin.read().split()
d = list(map(int, s))
n, m = d[:2]
g = [[] for i in range(n + 1)]
for j in range(m):
    i = 3 * j + 2
    g[d[i]].append((d[i + 1], d[i + 2], j))
    g[d[i + 1]].append((d[i], d[i + 2], j))
u, v = [-1] * n + [0], [1e9] * n + [0]
x, y = [0] * (n + 1), [0] * (n + 1)
q = deque([n])
while q:
    a = q.popleft()
    for b, k, i in g[a]:
        if v[b] == 1e9: q.append(b)
        if v[b] > v[a] and u[b] < u[a] + k:
            v[b] = v[a] + 1
            u[b] = u[a] + k
            x[b], y[b] = a, i
a, t = 1, [0] * m
while a != n: t[y[a]], a = 1, x[a]
l = []
for j in range(m):
    i = 3 * j + 2
    if d[i + 2] != t[j]:
        l.append(' '.join([s[i], s[i + 1], str(t[j])]))
print(len(l))
print('\n'.join(l))


I found an interesting problem on https://codeforces.com/problemset/problem/508/A:
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.

Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2 × 2 square consisting of black pixels is formed.

Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move.

Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2 × 2 square consisting of black pixels is formed.

-----Input-----

The first line of the input contains three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10^5) — the number of rows, the number of columns and the number of moves that Pasha is going to perform.

The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1 ≤ i ≤ n, 1 ≤ j ≤ m), representing the row number and column number of the pixel that was painted during a move.

-----Output-----

If Pasha loses, print the number of the move when the 2 × 2 square consisting of black pixels is formed.

If Pasha doesn't lose, that is, no 2 × 2 square consisting of black pixels is formed during the given k moves, print 0.

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

Output
4

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

Output
5

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

Output
0

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

def Main():
    string = (input()).split(" ")
    n = int(string[0])
    m = int(string[1])
    k = int(string[2])

    # exit immediately if smth wrong
    if k =="0" or n == "0" or m == "0":
        print ("0")
        return

    mas = []
    for i in range(n):
        mas.append([])
        for j in range(m):
            mas[i].append(0)

    act  = True
    l = 0
    while (act and k):
        string =(input()).split(" ")
        i = int(string[0])-1
        j = int(string[1])-1

    #   i = i -1
    #   j = j -1

        mas[i][j] = 1
        k = k - 1
        l = l + 1
        act = check(i,j,n,m,mas)

    if act == True:
        print ("0")
        return
    if act == False:
        while(k):
            string = input()
            k = k-1
        print(str(l))
        return

def check (i,j,n,m,mas):
    if i != 0:
        if j != 0:
            if mas[i-1][j-1] == 1:
                if mas[i-1][j] == 1:
                    if mas [i][j-1] == 1:
                        return False
    if i+1 != n:
        if j+1 != m:
            if mas[i+1][j+1] == 1:
                if mas[i][j+1] == 1:
                    if mas[i+1][j] == 1:
                        return False
    if i != 0:
        if j+1 != m:
            if mas[i-1][j+1] == 1:
                if mas[i-1][j] == 1:
                    if mas[i][j+1] == 1:
                        return False
    if i+1 != n:
        if j != 0:
            if mas[i+1][j-1] == 1:
                if mas[i][j-1] == 1:
                    if mas[i+1][j] == 1:
                        return False
    return True

def __starting_point():
    Main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/508/B:
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.

Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!

-----Input-----

The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 10^5, inclusive. The representation of n doesn't contain any leading zeroes.

-----Output-----

If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1.

Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.

-----Examples-----
Input
527

Output
572

Input
4573

Output
3574

Input
1357997531

Output
-1

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

arr = []
for i in input():
    arr.append(int(i))
ans1 = -1
n = len(arr)
for i, x in enumerate(arr):
    if x % 2 == 0:
        ans1 = i
if ans1 == -1:
    print(-1)
else:
    ans2 = -1
    for i in range(len(arr) - 1, -1, -1):
        if arr[i] % 2 == 0 and arr[i] < arr[len(arr) - 1]:
            ans2 = i
    if ans2 == -1:
        arr[n - 1], arr[ans1] = arr[ans1], arr[n - 1]
    else:
        arr[n - 1], arr[ans2] = arr[ans2], arr[n - 1]
    for i in arr:
        print(i, end = '')


I found an interesting problem on https://codeforces.com/problemset/problem/508/C:
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.

For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen w_{i} seconds after midnight, all w_{i}'s are distinct. Each visit lasts exactly one second.

What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.

-----Input-----

The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.

The next line contains m space-separated numbers w_{i} (1 ≤ i ≤ m, 1 ≤ w_{i} ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All w_{i}'s are distinct, they follow in the strictly increasing order.

-----Output-----

If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.

If that is impossible, print  - 1.

-----Examples-----
Input
1 8 3
10

Output
3

Input
2 10 1
5 8

Output
1

Input
1 1 3
10

Output
-1

-----Note-----

Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.

It takes exactly one second to light up a candle and only after that second this...

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

f = lambda: list(map(int, input().split()))
m, t, r = f()
p, s = [], 0
for w in f():
    p = [q for q in p if q > w]
    d = r - len(p)
    p += [w + t - i for i in range(d)]
    s += d
print(-1 if t < r else s)


I found an interesting problem on https://codeforces.com/problemset/problem/508/E:
Notice that the memory limit is non-standard.

Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2n. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur's favorite correct bracket sequence just to spite him.

All Arthur remembers about his favorite sequence is for each opening parenthesis ('(') the approximate distance to the corresponding closing one (')'). For the i-th opening bracket he remembers the segment [l_{i}, r_{i}], containing the distance to the corresponding closing bracket.

Formally speaking, for the i-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment [l_{i}, r_{i}].

Help Arthur restore his favorite correct bracket sequence!

-----Input-----

The first line contains integer n (1 ≤ n ≤ 600), the number of opening brackets in Arthur's favorite correct bracket sequence.

Next n lines contain numbers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} < 2n), representing the segment where lies the distance from the i-th opening bracket and the corresponding closing one.

The descriptions of the segments are given in the order in which the opening brackets occur in Arthur's favorite sequence if we list them from left to right.

-----Output-----

If it is possible to restore the correct bracket sequence by the given data, print any possible choice.

If Arthur got something wrong, and there are no sequences corresponding to the given information, print a single line "IMPOSSIBLE" (without the quotes).

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

Output
()()()()

Input
3
5 5
3 3
1 1

Output
((()))

Input
3
5 5
3 3
2 2

Output
IMPOSSIBLE

Input
3
2 3
1 4
1 4

Output
(())()

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

def main():
    lst = list(tuple(map(int, input().split())) for _ in range(int(input())))
    res = []
    try:
        for a, b in reversed(lst):
            w, tmp = 1, ['(']
            while w < a:
                x = res.pop()
                w += len(x)
                tmp.append(x)
            if w > b:
                raise IndexError
            else:
                tmp.append(')')
                res.append(''.join(tmp))
    except IndexError:
        print('IMPOSSIBLE')
        return
    print(''.join(reversed(res)))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/509/A:
An n × n table a is defined as follows:

  The first row and the first column contain ones, that is: a_{i}, 1 = a_{1, }i = 1 for all i = 1, 2, ..., n.  Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula a_{i}, j = a_{i} - 1, j + a_{i}, j - 1.

These conditions define all the values in the table.

You are given a number n. You need to determine the maximum value in the n × n table defined by the rules above.

-----Input-----

The only line of input contains a positive integer n (1 ≤ n ≤ 10) — the number of rows and columns of the table.

-----Output-----

Print a single line containing a positive integer m — the maximum value in the table.

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

Output
1
Input
5

Output
70

-----Note-----

In the second test the rows of the table look as follows: {1, 1, 1, 1, 1},  {1, 2, 3, 4, 5},  {1, 3, 6, 10, 15},  {1, 4, 10, 20, 35},  {1, 5, 15, 35, 70}.

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

n = int(input())
from math import factorial
print(factorial(2*(n-1)) // factorial(n-1) // factorial(n-1))


I found an interesting problem on https://codeforces.com/problemset/problem/509/B:
There are n piles of pebbles on the table, the i-th pile contains a_{i} pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.

In other words, let's say that b_{i}, c is the number of pebbles of color c in the i-th pile. Then for any 1 ≤ c ≤ k, 1 ≤ i, j ≤ n the following condition must be satisfied |b_{i}, c - b_{j}, c| ≤ 1. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then b_{i}, c is considered to be zero.

-----Input-----

The first line of the input contains positive integers n and k (1 ≤ n, k ≤ 100), separated by a space — the number of piles and the number of colors respectively.

The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100) denoting number of pebbles in each of the piles.

-----Output-----

If there is no way to paint the pebbles satisfying the given condition, output "NO" (without quotes) .

Otherwise in the first line output "YES" (without quotes). Then n lines should follow, the i-th of them should contain a_{i} space-separated integers. j-th (1 ≤ j ≤ a_{i}) of these integers should be equal to the color of the j-th pebble in the i-th pile. If there are several possible answers, you may output any of them.

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

Output
YES
1
1 4
1 2 4
1 2 3 4

Input
5 2
3 2 4 1 3

Output
NO

Input
5 4
3 2 4 3 5

Output
YES
1 2 3
1 3
1 2 3 4
1 3 4
1 1 2 3 4

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

import sys

n, k = list(map(int, input().split()))
keeps = list(map(int, input().split()))
min_k = min(keeps)
ans = [0] * n
for i in range(n):

    ans[i] = (['1'] * (min(min_k + 1, keeps[i])))
    j = 2
    while j <= k and len(ans[i]) < keeps[i]:
        ans[i].append(str(j))
        j += 1
    if len(ans[i]) < keeps[i]:
        print('NO')
        return
print('YES')
for i in range(n):
    print(' '.join(ans[i]))


I found an interesting problem on https://codeforces.com/problemset/problem/509/C:
Vasya had a strictly increasing sequence of positive integers a_1, ..., a_{n}. Vasya used it to build a new sequence b_1, ..., b_{n}, where b_{i} is the sum of digits of a_{i}'s decimal representation. Then sequence a_{i} got lost and all that remained is sequence b_{i}.

Vasya wonders what the numbers a_{i} could be like. Of all the possible options he likes the one sequence with the minimum possible last number a_{n}. Help Vasya restore the initial sequence.

It is guaranteed that such a sequence always exists.

-----Input-----

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

Next n lines contain integer numbers b_1, ..., b_{n}  — the required sums of digits. All b_{i} belong to the range 1 ≤ b_{i} ≤ 300.

-----Output-----

Print n integer numbers, one per line — the correct option for numbers a_{i}, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to b_{i}.

If there are multiple sequences with least possible number a_{n}, print any of them. Print the numbers without leading zeroes.

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

Output
1
2
3

Input
3
3
2
1

Output
3
11
100

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

n = int(input())
prv = 0
r = [0] * 500
p = 0
for i in range(n):
    x = int(input())
    if x > p:
        d = x - p
        i = 0
        while d > 0:
            e = min(d, 9 - r[i])
            r[i] += e
            d -= e
            i += 1
    else:
        d = p - x + 1
        i = 0
        s = 0
        while d > s or r[i] == 9:
            s += r[i]
            i += 1
        j = 0
        d = s - d
        while j < i:
            e = min(d, 9)
            r[j] = e
            d -= e
            j += 1
        while r[i] == 9:
            i += 1
        r[i] += 1
    s = ''.join(map(str, reversed(r)))
    print(s.lstrip('0'))
    p = x


I found an interesting problem on https://codeforces.com/problemset/problem/509/E:
When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.

Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.

Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.

More formally, let's define the function vowel(c) which is equal to 1, if c is a vowel, and to 0 otherwise. Let s_{i} be the i-th character of string s, and s_{i}..j be the substring of word s, staring at the i-th character and ending at the j-th character (s_{is}_{i} + 1... s_{j}, i ≤ j).

Then the simple prettiness of s is defined by the formula:$\operatorname{simple}(s) = \frac{\sum_{i = 1}^{|s|} \operatorname{vowel}(s_{i})}{|s|}$

The prettiness of s equals $\sum_{1 \leq i \leq j \leq|s|} \operatorname{simple}(s_{i . . j})$

Find the prettiness of the given song title.

We assume that the vowels are I, E, A, O, U, Y.

-----Input-----

The input contains a single string s (1 ≤ |s| ≤ 5·10^5) — the title of the song.

-----Output-----

Print the prettiness of the song with the absolute or relative error of at most 10^{ - 6}.

-----Examples-----
Input
IEAIAIO

Output
28.0000000

Input
BYOB

Output
5.8333333

Input
YISVOWEL

Output
17.0500000

-----Note-----

In the first sample all letters are vowels. The simple prettiness of each substring is 1. The word of length 7 has 28 substrings. So, the prettiness of the song equals to 28.

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

def sum_vowels(s, i, j):
	ans = 0

	for index in range(i, j + 1):
		if s[index] in "AEIOUY":
			ans += 1

	return ans

def __starting_point():
	s = input()
	n = len(s)

	ans = 0

	num = 0
	den_inv = 0
	prev_sum = sum_vowels(s, 0, n - 1)
	for i in range(int(n / 2)):
		num += prev_sum
		den_inv = 1 / (i + 1) + 1 / (n - i)

		ans += num * den_inv

		if s[i] in "AEIOUY": prev_sum -= 1
		if s[n - 1 - i] in "AEIOUY": prev_sum -= 1

	if (n % 2 == 1):
		i = int(n / 2)
		num += sum_vowels(s, i, i)
		den_inv = 1 / (i + 1)

		ans += num * den_inv

	print("{:.6f}".format(ans))
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/510/A:
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.

A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1, m), then goes down 2 rows to (3, m), then goes left to (3, 1) and so on.

Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').

Consider sample tests in order to understand the snake pattern.

-----Input-----

The only line contains two integers: n and m (3 ≤ n, m ≤ 50).

n is an odd number.

-----Output-----

Output n lines. Each line should contain a string consisting of m characters. Do not output spaces.

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

Output
###
..#
###

Input
3 4

Output
####
...#
####

Input
5 3

Output
###
..#
###
#..
###

Input
9 9

Output
#########
........#
#########
#........
#########
........#
#########
#........
#########

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

#!/usr/bin/env python3

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

i = 0
while i < n:
    print('#' * m)
    if i != n - 1:
        if i / 2 % 2 == 0:
            print('.' * (m - 1) + '#')
        else:
            print('#' + '.' * (m - 1))
    i += 2


I found an interesting problem on https://codeforces.com/problemset/problem/510/B:
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:

[Image]

Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.

The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d_1, d_2, ..., d_{k} a cycle if and only if it meets the following condition:

  These k dots are different: if i ≠ j then d_{i} is different from d_{j}.  k is at least 4.  All dots belong to the same color.  For all 1 ≤ i ≤ k - 1: d_{i} and d_{i} + 1 are adjacent. Also, d_{k} and d_1 should also be adjacent. Cells x and y are called adjacent if they share an edge.

Determine if there exists a cycle on the field.

-----Input-----

The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board.

Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.

-----Output-----

Output "Yes" if there exists a cycle, and "No" otherwise.

-----Examples-----
Input
3 4
AAAA
ABCA
AAAA

Output
Yes

Input
3 4
AAAA
ABCA
AADA

Output
No

Input
4 4
YYYR
BYBY
BBBY
BBBY

Output
Yes

Input
7 6
AAAAAB
ABBBAB
ABAAAB
ABABBB
ABAAAB
ABBBAB
AAAAAB

Output
Yes

Input
2 13
ABCDEFGHIJKLM
NOPQRSTUVWXYZ

Output
No

-----Note-----

In first sample test all 'A' form a cycle.

In second sample there is no such cycle.

The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).

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

#f = lambda: input()
#file = open("btest", "r")
#f = lambda:file.readline()

# n, m = map(int, f().split())

# g = []

# for i in range(n):
#     g.append(f())

# disco = [[False for _ in range(m)] for _ in range(n)]

# #print(disco)
# #print(parent)

# def found_cycle(w):
#     nonlocal disco
#     s = []
#     s.append(w)
#     while s:
#         v = s.pop()
#         if disco[v[0]][v[1]] == False:
#             if v[0] > 0 and g[v[0]-1][v[1]] == g[v[0]][v[1]]:
#                 s.append([v[0]-1, v[1]])

#             if v[0] < n-1 and g[v[0]+1][v[1]] == g[v[0]][v[1]]:
#                 s.append([v[0]+1, v[1]])

#             if v[1] > 0 and g[v[0]][v[1]-1] == g[v[0]][v[1]]:
#                 s.append([v[0], v[1]-1])

#             if v[1] < m-1 and g[v[0]][v[1]+1] == g[v[0]][v[1]]:
#                 s.append([v[0], v[1]+1])

#         else:
#             disco[v[0]][v[1]] = True
#     return False

# found = False
# for i in range(n):
#     if found:
#         break
#     for j in range(m):
#         if disco[i][j] == False:
#             found = found_cycle([i,j])
#             break

# if found:
#     print ("Yes")
# else:
#     print ("No")

#Editorial
import sys
sys.setrecursionlimit(10000)

#file = open("btest", "r")
#f = lambda:file.readline()
f = lambda:input()

n,m = list(map(int, f().split()))

matrix = []

disco = [[0 for _ in range(m)] for _ in range(n)]

for i in range(n):
    matrix.append(f())

def valid_node(i, j):
    return 0 <= i < n and 0 <= j < m

def dfs(i, j, p, k, cc = 0):
    if disco[i][j] == k:
        return True

    disco[i][j] = k

    res = False
    dd = [[0,1], [1,0], [-1,0], [0,-1]]
    for d in dd:
        if valid_node(i+ d[0], j+d[1]) and (i + d[0] != p[0] or j + d[1] != p[1]):
            if matrix[i + d[0]][j+ d[1]] == matrix[i][j]:
                res = res or dfs(i + d[0], j+d[1], [i,j], k, cc+1)

    return res

ok = False
k = 1
for i in range(n):
    for j in range(m):
        if...


I found an interesting problem on https://codeforces.com/problemset/problem/510/C:
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.

After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!

She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.

Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: s_{i} ≠ t_{i}. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters s_{i} and t_{i} according to their order in alphabet.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 100): number of names.

Each of the following n lines contain one string name_{i} (1 ≤ |name_{i}| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.

-----Output-----

If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).

Otherwise output a single word "Impossible" (without...

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

#return if sa contains a real prefix: sb
def isPrefix( sa , sb ):
    if len(sa) <= len(sb):
        return False
    return sa[0:len(sb)] == sb

def getOrder( sa , sb ):
    for i in range( 0 , min( len(sa) , len(sb) ) ):
        if sa[i] != sb[i]:
            return sa[i],sb[i]

test = False
if test:
    fp = open("C-4.in","r")
    n = int(fp.readline().strip())
    names = [ fp.readline().strip() for i in range(0,n)]
    fp.close()
else:
    n = int(input().strip())
    names = [ input().strip() for i in range(0,n)]

g = [[False]*26 for i in range(0,26)]

res = True
for i in range(1,n):
    if names[i-1] == names[i] or isPrefix( names[i] , names[i-1] ):
        continue
    elif isPrefix( names[i-1] , names[i] ):
        res = False
        break
    else:
        ca,cb = getOrder( names[i-1] , names[i] )
        #print(ca,"<",cb)
        if g[ord(cb)-ord('a')][ord(ca)-ord('a')]:
            res = False
            break
        else:
            g[ord(ca)-ord('a')][ord(cb)-ord('a')] = True

def printG():
    print("  abcdefghijklmnopqrstuvwxyz")
    for i in range(0,26):
        print( chr( ord("a") + i ) , "".join( [ "1" if x else "0" for x in g[i]] ) , sep = "")
#printG()

if not res:
    print("Impossible")
else:

    def getZeroIndegreeNode():
        for i in range(0,26):
            if not used[i] and indegree[i] == 0:
                return i
        return -1
    #topo sort
    theOrder = []
    indegree = [0] * 26
    used = [False] * 26

    #calc indegree
    for i in range(0,26):
        ithIndegree = 0
        for j in range(0,26):
            if g[j][i]: ithIndegree += 1
        indegree[i] = ithIndegree

    for i in range(0,26):
        zeroIndegreeNode = getZeroIndegreeNode()
        if zeroIndegreeNode == -1:
            res = False
            break
        else:
            used[zeroIndegreeNode] = True
            theOrder.append( chr( ord('a') + zeroIndegreeNode ) )
            for j in range(0,26):
                if g[zeroIndegreeNode][j]:
                    indegree[j] -=...


I found an interesting problem on https://codeforces.com/problemset/problem/510/D:
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.

There are also n cards, each card has 2 attributes: length l_{i} and cost c_{i}. If she pays c_{i} dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length l_{i}, i. e. from cell x to cell (x - l_{i}) or cell (x + l_{i}).

She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.

If this is possible, calculate the minimal cost.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 300), number of cards.

The second line contains n numbers l_{i} (1 ≤ l_{i} ≤ 10^9), the jump lengths of cards.

The third line contains n numbers c_{i} (1 ≤ c_{i} ≤ 10^5), the costs of cards.

-----Output-----

If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.

-----Examples-----
Input
3
100 99 9900
1 1 1

Output
2

Input
5
10 20 30 40 50
1 1 1 1 1

Output
-1

Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10

Output
6

Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026

Output
7237

-----Note-----

In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.

In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.

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

def main():
    input()
    acc = {0: 0}
    for p, c in zip(list(map(int, input().split())),
                    list(map(int, input().split()))):
        adds = []
        for b, u in acc.items():
            a = p
            while b:
                a, b = b, a % b
            adds.append((a, u + c))
        for a, u in adds:
            acc[a] = min(u, acc.get(a, 1000000000))
    print(acc.get(1, -1))

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/513/A:
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n_1 balls and second player's box contains exactly n_2 balls. In one move first player can take from 1 to k_1 balls from his box and throw them away. Similarly, the second player can take from 1 to k_2 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally.

-----Input-----

The first line contains four integers n_1, n_2, k_1, k_2. All numbers in the input are from 1 to 50.

This problem doesn't have subproblems. You will get 3 points for the correct submission.

-----Output-----

Output "First" if the first player wins and "Second" otherwise.

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

Output
Second

Input
2 1 1 1

Output
First

-----Note-----

Consider the first sample test. Each player has a box with 2 balls. The first player draws a single ball from his box in one move and the second player can either take 1 or 2 balls from his box in one move. No matter how the first player acts, the second player can always win if he plays wisely.

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

n, m, k1, k2 = map(int, input().split())
if n > m:
    print('First')
else:
    print('Second')


I found an interesting problem on https://codeforces.com/problemset/problem/513/B1:
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:$f(p) = \sum_{i = 1}^{n} \sum_{j = i}^{n} \operatorname{min}(p_{i}, p_{i + 1}, \ldots p_{j})$

Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).

-----Input-----

The single line of input contains two integers n and m (1 ≤ m ≤ cnt_{n}), where cnt_{n} is the number of permutations of length n with maximum possible value of f(p).

The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.  In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.  In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.

-----Output-----

Output n number forming the required permutation.

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

Output
2 1

Input
3 2

Output
1 3 2

-----Note-----

In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.

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

arc = []
def sv(a,b,c,n,v):
	if n < c//2:
		arc[a] = v
		if b-a>1: sv(a+1,b,c//2,n,v+1)
	else:
		arc[b-1] = v
		if b-a>1: sv(a,b-1,c//2,n-c//2,v+1)

n, m = list(map(int, input().split()))
arc = [0]*n
ssc = 1<<(n-1)
sv(0, n, ssc, m-1, 1)
print(' '.join(map(str, arc)))


I found an interesting problem on https://codeforces.com/problemset/problem/513/C:
Nowadays, most of the internet advertisements are not statically linked to a web page. Instead, what will be shown to the person opening a web page is determined within 100 milliseconds after the web page is opened. Usually, multiple companies compete for each ad slot on the web page in an auction. Each of them receives a request with details about the user, web page and ad slot and they have to respond within those 100 milliseconds with a bid they would pay for putting an advertisement on that ad slot. The company that suggests the highest bid wins the auction and gets to place its advertisement. If there are several companies tied for the highest bid, the winner gets picked at random.

However, the company that won the auction does not have to pay the exact amount of its bid. In most of the cases, a second-price auction is used. This means that the amount paid by the company is equal to the maximum of all the other bids placed for this ad slot.

Let's consider one such bidding. There are n companies competing for placing an ad. The i-th of these companies will bid an integer number of microdollars equiprobably randomly chosen from the range between L_{i} and R_{i}, inclusive. In the other words, the value of the i-th company bid can be any integer from the range [L_{i}, R_{i}] with the same probability.

Determine the expected value that the winner will have to pay in a second-price auction.

-----Input-----

The first line of input contains an integer number n (2 ≤ n ≤ 5). n lines follow, the i-th of them containing two numbers L_{i} and R_{i} (1 ≤ L_{i} ≤ R_{i} ≤ 10000) describing the i-th company's bid preferences.

This problem doesn't have subproblems. You will get 8 points for the correct submission.

-----Output-----

Output the answer with absolute or relative error no more than 1e - 9.

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

Output
5.7500000000

Input
3
2 5
3 4
1 6

Output
3.5000000000

-----Note-----

Consider the first example. The first company bids a random integer number of...

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

d = [list(map(int, input().split())) for i in range(int(input()))]
s = 0
for k in range(1, 10001):
    p = [min(max((k - l) / (r - l + 1), 1e-20), 1) for l, r in d]
    u = v = 1
    for r in p: u *= r
    for r in p:
        v *= r
        s += (u - v) * (r - 1) / r
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/513/G1:
You are given a permutation of n numbers p_1, p_2, ..., p_{n}. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements p_{l}, p_{l} + 1, ..., p_{r}. Your task is to find the expected value of the number of inversions in the resulting permutation.

-----Input-----

The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^9). The next line contains n integers p_1, p_2, ..., p_{n} — the given permutation. All p_{i} are different and in range from 1 to n.

The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.

  In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.  In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.  In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 10^9 will hold.

-----Output-----

Output the answer with absolute or relative error no more than 1e - 9.

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

Output
0.833333333333333

Input
3 4
1 3 2

Output
1.458333333333334

-----Note-----

Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability $\frac{1}{2}$, the interval will consist of a single element and the permutation will not be altered. With probability $\frac{1}{6}$ we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability $\frac{1}{6}$ the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to $\frac{1}{2} \cdot 0 +...

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

f = lambda: map(int, input().split())
g = lambda k: k * k - k >> 1
n, k = f()
p = list(f())

a = [[0] * n for i in range(n)]

for i in range(n):
    for j in range(i + 1, n):
        if p[i] > p[j]: a[i][j] = 1
        else: a[j][i] = 1

for t in range(k):
    b = [[0] * n for i in range(n)]
    for i in range(n):
        for j in range(i + 1, n):
            p = q = 0

            for x in range(j):
                d = min(i + 1, j - x, x + 1, j - i)
                p += d * a[x][j]
                q += d

            for y in range(i + 1, n):
                d = min(n - j, y - i, n - y, j - i)
                p += d * a[i][y]
                q += d

            for s in range(j, i + n):
                x, y = s - i, s - j
                d = min(i + 1, n - j, y + 1, n - x)
                p += d * a[x][y]
                q += d

            d = g(j - i) + g(i + 1) + g(n - j)
            b[i][j] = (p + d * a[i][j]) / (d + q)
    a = b
    for i in range(n):
        for j in range(i + 1, n):
            a[j][i] = 1 - a[i][j]

s = 0
for i in range(n):
    for j in range(i + 1, n): s += a[i][j]
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/514/A:
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t.

Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.

-----Input-----

The first line contains a single integer x (1 ≤ x ≤ 10^18) — the number that Luke Skywalker gave to Chewbacca.

-----Output-----

Print the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes.

-----Examples-----
Input
27

Output
22

Input
4545

Output
4444

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

S = list(input())
for i in range(len(S)):
    x = int(S[i])
    y = 9 - x
    if y < x and (y != 0 or i != 0):
        S[i] = str(y)
print(''.join(S))


I found an interesting problem on https://codeforces.com/problemset/problem/514/B:
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane.

Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x_0, y_0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x_0, y_0).

Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.

The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.

-----Input-----

The first line contains three integers n, x_0 и y_0 (1 ≤ n ≤ 1000,  - 10^4 ≤ x_0, y_0 ≤ 10^4) — the number of stormtroopers on the battle field and the coordinates of your gun.

Next n lines contain two integers each x_{i}, y_{i} ( - 10^4 ≤ x_{i}, y_{i} ≤ 10^4) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.

-----Output-----

Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers.

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

Output
2

Input
2 1 2
1 1
1 0

Output
1

-----Note-----

Explanation to the first and second samples from the statement, respectively:  [Image]

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

def isequal(a, b):
    return abs(a-b) <= 0.00000001
a, b, c = list(map(int, input().split(' ')))
slopes = []
for i in range(a):
    x, y = list(map(int, input().split(' ')))
    if x == b:
        slopes.append(90001)
    else:
        slopes.append((y-c)/(x-b))
print(len(set(slopes)))


I found an interesting problem on https://codeforces.com/problemset/problem/514/C:
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".

Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.

-----Input-----

The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·10^5, 0 ≤ m ≤ 3·10^5) — the number of the initial strings and the number of queries, respectively.

Next follow n non-empty strings that are uploaded to the memory of the mechanism.

Next follow m non-empty strings that are the queries to the mechanism.

The total length of lines in the input doesn't exceed 6·10^5. Each line consists only of letters 'a', 'b', 'c'.

-----Output-----

For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).

-----Examples-----
Input
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac

Output
YES
NO
NO

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

__author__ = 'Utena'
M=100000000000007
def hash(x):
    a=0
    for j1 in x:
        a=(a*1003+ord(j1))%M
    return a
def get(q):
    l=len(q)
    e=1
    h=hash(q)
    for j in range(1,l+1):
        aj=q[-j]
        a,b,c=((h+(e*(ord('a')-ord(aj))))+M*2)%M,((h+(e*(ord('b')-ord(aj))))+M*2)%M,((h+(e*(ord('c')-ord(aj))))+M*2)%M
        e=(e*1003)%M
        if aj=='a':
            if b in search[l] or c in search[l]:
                return 'YES'
        elif aj=='b':
            if a in search[l] or c in search[l]:
                return 'YES'
        elif aj=='c':
            if a in search[l] or b in search[l]:
                return 'YES'
    return 'NO'
ans=[]
n,m=map(int,input().split())
search=[set()for i in range(600001)]
for i in range(n):
    s=input()
    search[len(s)].add(hash(s))
for i in range(m):
    q=input()
    ans.append(get(q))
print('\n'.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/514/D:
An army of n droids is lined up in one row. Each droid is described by m integers a_1, a_2, ..., a_{m}, where a_{i} is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the army by destroying one detail of the i-th type (if the droid doesn't have details of this type, nothing happens to it).

A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most k shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?

-----Input-----

The first line contains three integers n, m, k (1 ≤ n ≤ 10^5, 1 ≤ m ≤ 5, 0 ≤ k ≤ 10^9) — the number of droids, the number of detail types and the number of available shots, respectively.

Next n lines follow describing the droids. Each line contains m integers a_1, a_2, ..., a_{m} (0 ≤ a_{i} ≤ 10^8), where a_{i} is the number of details of the i-th type for the respective robot.

-----Output-----

Print m space-separated integers, where the i-th number is the number of shots from the weapon of the i-th type that the robot should make to destroy the subsequence of consecutive droids of the maximum length.

If there are multiple optimal solutions, print any of them.

It is not necessary to make exactly k shots, the number of shots can be less.

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

Output
2 2

Input
3 2 4
1 2
1 3
2 2

Output
1 3

-----Note-----

In the first test the second, third and fourth droids will be destroyed.

In the second test the first and second droids will be destroyed.

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

from heapq import heappush, heappop
from sys import setrecursionlimit
from sys import stdin
from collections import defaultdict
setrecursionlimit(1000000007)
_data = iter(stdin.read().split('\n'))
def input():
    return next(_data)

n, m, k = [int(x) for x in input().split()]
a = tuple(tuple(-int(x) for x in input().split()) for i in range(n))
heaps = tuple([0] for _ in range(m))
removed = tuple(defaultdict(int) for _ in range(m))

rv = -1
rt = (0,) * m
t = [0] * m
p = 0
for i in range(n):
    ai = a[i]
    for j, v, heap in zip(range(m), ai, heaps):
        heappush(heap, v)
        t[j] = heap[0]
    while -sum(t) > k:
        ap = a[p]
        for j, v, heap, remd in zip(range(m), ap, heaps, removed):
            remd[v] += 1
            while heap[0] in remd:
                top = heappop(heap)
                if remd[top] == 1:
                   del remd[top]
                else:
                    remd[top] -= 1
            t[j] = heap[0]
        p += 1
    if rv < (i + 1) - p:
        rv = (i + 1) - p
        rt = tuple(t)
print(*map(lambda x: -x, rt))


I found an interesting problem on https://codeforces.com/problemset/problem/514/E:
When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to d_{i}. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most x from the root. The distance is the sum of the lengths of edges on the path between nodes.

But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' — you may ask. It's just that he feels superior knowing that only he can solve this problem.

Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo 10^9 + 7.

-----Input-----

The first line contains two space-separated integers n and x (1 ≤ n ≤ 10^5, 0 ≤ x ≤ 10^9) — the number of children of each node and the distance from the root within the range of which you need to count the nodes.

The next line contains n space-separated integers d_{i} (1 ≤ d_{i} ≤ 100) — the length of the edge that connects each node with its i-th child.

-----Output-----

Print a single number — the number of vertexes in the tree at distance from the root equal to at most x.

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

Output
8

-----Note-----

Pictures to the sample (the yellow color marks the nodes the distance to which is at most three) [Image]

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

# fast io
from sys import stdin
_data = iter(stdin.read().split('\n'))
input = lambda: next(_data)

N = 101
MOD = 1000000007

def mul_vec_mat(v, a):
    n = len(a[0])
    m = len(v)
    c = [0] * n
    for i in range(n):
        c[i] = sum(a[j][i] * v[j] % MOD for j in range(m)) % MOD
    return c

def mul_vec_sparse_mat(v, ta):
    n = len(ta)
    c = [0] * n
    for i in range(n):
        c[i] = sum(x * v[j] % MOD for j, x in ta[i]) % MOD
    return c

def mod_pow_kitamasa(a, x):
    n = len(a)

    # sparse matrix of a^T
    ta = [[] for i in range(n)]
    for i in range(n):
        for j in range(n):
            if a[i][j] != 0:
                ta[j].append((i, a[i][j]))

    r = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
    while x > 0:
        if x & 1:
            r[1] = mul_vec_mat(r[1], a)
        aa = [[0] * n for i in range(n)]
        aa[0] = a[0]
        aa[1] = mul_vec_mat(a[1], a)
        for i in range(2, n):
            aa[i] = mul_vec_sparse_mat(aa[i - 1], ta)
        a = aa
        x >>= 1
    for i in range(2, n):
        r[i] = mul_vec_sparse_mat(r[i - 1], ta)
    return r

_, x = [int(v) for v in input().split()]
a = [[0] * N for i in range(N)]
a[0][0] = 1
a[N - 1][0] = 1
for i in range(1, N - 1):
    a[i][i + 1] = 1
for d in map(int, input().split()):
    a[N - 1][N - d] += 1
a = mod_pow_kitamasa(a, x)
b = [0] * N
b[0] = 1
b[N - 1] = 1
print(sum(a[N - 1][i] * b[i] % MOD for i in range(N)) % MOD)


I found an interesting problem on https://codeforces.com/problemset/problem/518/B:
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.

The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".

Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.

-----Input-----

The first line contains line s (1 ≤ |s| ≤ 2·10^5), consisting of uppercase and lowercase English letters — the text of Tanya's message.

The second line contains line t (|s| ≤ |t| ≤ 2·10^5), consisting of uppercase and lowercase English letters — the text written in the newspaper.

Here |a| means the length of the string a.

-----Output-----

Print two integers separated by a space:  the first number is the number of times Tanya shouts "YAY!" while making the message,  the second number is the number of times Tanya says "WHOOPS" while making the message.

-----Examples-----
Input
AbC
DCbA

Output
3 0

Input
ABC
abc

Output
0 3

Input
abacaba
AbaCaBA

Output
3 4

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

x = input()
t = input()
d = dict()
for i in t:
    if i in d:
        d[i] += 1
    else:
        d[i] = 1
s = []
for i in x:
    s.append([i, 0])
s.sort(reverse = True)
ura = 0
opa = 0
for i in range(len(s)):
    if s[i][0] in d:
        if d[s[i][0]] > 0:
            ura += 1
            s[i][1] = 1
            d[s[i][0]] -= 1
for i in range(len(s)):
    if chr(ord(s[i][0]) - ord('a') + ord('A')) in d and s[i][1] == 0:
        if d[chr(ord(s[i][0]) - ord('a') + ord('A'))] > 0:
            opa += 1
            s[i][1] = 1
            d[chr(ord(s[i][0]) - ord('a') + ord('A'))] -= 1
for i in range(len(s)):
    if chr(ord(s[i][0]) - ord('A') + ord('a')) in d and s[i][1] == 0:
        if d[chr(ord(s[i][0]) - ord('A') + ord('a'))] > 0:
            opa += 1
            s[i][1] = 1
            d[chr(ord(s[i][0]) - ord('A') + ord('a'))] -= 1
print(ura, opa)


I found an interesting problem on https://codeforces.com/problemset/problem/518/C:
Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).

Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t - 1 gestures (if the icon is on the screen t), and then make another gesture — press the icon of the required application exactly once to launch it.

After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.

All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.

Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order?

Note that one application may be launched multiple times.

-----Input-----

The first line of the input contains...

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

def foo():
    n, m, k = list(map(int, input().split()))
    a, b = [0] * n, [0] * n
    a = list(map(int, input().split()))
    for i in range(n):
        a[i] -= 1
        b[a[i]] = i
    c = list(map(int, input().split()))
    answer = 0;
    for element in c:
        element -= 1
        answer += b[element] // k + 1
        if b[element]:
            a[b[element]], a[b[element] - 1] = a[b[element] - 1], a[b[element]]
            b[a[b[element]]] += 1
            b[element] -= 1
    return answer

print(foo())


I found an interesting problem on https://codeforces.com/problemset/problem/518/D:
Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor.

Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him.

Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds.

Your task is to help him solve this complicated task.

-----Input-----

The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point.

-----Output-----

Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10^{ - 6}.

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

Output
0.5

Input
1 0.50 4

Output
0.9375

Input
4 0.20 2

Output
0.4

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

def find_expected_people(people_count, probability, seconds):
    # the probability after i seconds to have k people on the escalator
    current_row = [0.] * (people_count + 1)
    current_row[0] = 1.

    for sec in range(1, seconds + 1):
        next_row = [x * (1. - probability) for x in current_row]
        next_row[-1] = current_row[-1]

        for person in range(people_count):
            next_row[person + 1] += current_row[person] * probability
        current_row = next_row

    return sum(index * value for index, value in enumerate(current_row))

def main():
    raw_input = input().split()
    people_count = int(raw_input[0])
    probability = float(raw_input[1])
    seconds = int(raw_input[2])

    print(find_expected_people(people_count, probability, seconds))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/518/F:
On a certain meeting of a ruling party "A" minister Pavel suggested to improve the sewer system and to create a new pipe in the city.

The city is an n × m rectangular squared field. Each square of the field is either empty (then the pipe can go in it), or occupied (the pipe cannot go in such square). Empty squares are denoted by character '.', occupied squares are denoted by character '#'.

The pipe must meet the following criteria:  the pipe is a polyline of width 1,  the pipe goes in empty squares,  the pipe starts from the edge of the field, but not from a corner square,  the pipe ends at the edge of the field but not in a corner square,  the pipe has at most 2 turns (90 degrees),  the border squares of the field must share exactly two squares with the pipe,  if the pipe looks like a single segment, then the end points of the pipe must lie on distinct edges of the field,  for each non-border square of the pipe there are exacly two side-adjacent squares that also belong to the pipe,  for each border square of the pipe there is exactly one side-adjacent cell that also belongs to the pipe.

Here are some samples of allowed piping routes:

           ....#            ....#            .*..#

           *****            ****.            .***.

           ..#..            ..#*.            ..#*.

           #...#            #..*#            #..*#

           .....            ...*.            ...*.

Here are some samples of forbidden piping routes:

           .**.#            *...#            .*.*#

           .....            ****.            .*.*.

           ..#..            ..#*.            .*#*.

           #...#            #..*#            #*.*#

           .....            ...*.            .***.

In these samples the pipes are represented by characters ' * '.

You were asked to write a program that calculates the number of distinct ways to make exactly one pipe in the city.

The two ways to make a pipe are considered distinct if they are distinct in at least one square.

-----Input-----

The first...

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

n, m = [int(x) for x in input().split()]
a = [[int(c == '.') for c in input()] for i in range(n)]

def rotate(a):
    n = len(a)
    m = len(a[0])
    b = [[0] * n for i in range(m)]
    for i in range(n):
        for j in range(m):
            b[j][n - 1 - i] = a[i][j]
    return b

def calc(a):
    n = len(a)
    m = len(a[0])
    alive = a[0][:]
    alive[0], alive[m - 1] = 0, 0
    ans_l, ans_r, ans_u = 0, 0, 0
    ans_bs = [0] * m
    for i in range(1, n - 1):
        s = 0
        for j in range(1, m - 1):
            if a[i][j]:
                if alive[j]:
                    ans_u += s - alive[j - 1]
                ans_bs[j] += s
                s += alive[j]
            else:
                s = 0
                ans_bs[j] = 0
                alive[j] = 0
        if a[i][m - 1]:
            ans_r += s
        s = 0
        for j in range(m - 2, 0, -1):
            if a[i][j]:
                if alive[j]:
                    ans_u += s - alive[j + 1]
                ans_bs[j] += s
                s += alive[j]
            else:
                s = 0
                ans_bs[j] = 0
                alive[j] = 0
        if a[i][0]:
            ans_l += s
    ans_u //= 2
    ans_b = sum(a[n - 1][i] * (ans_bs[i] + alive[i]) for i in range(1, m - 1))
    return ans_l, ans_r, ans_u, ans_b
ans = 0
ans_l, ans_r, ans_u, ans_b = calc(a)
ans += ans_l + ans_r + ans_u + ans_b
a = rotate(a)
ans_l, _, ans_u, ans_b = calc(a)
ans += ans_l + ans_u + ans_b
a = rotate(a)
ans_l, _, ans_u, _= calc(a)
ans += ans_l + ans_u
a = rotate(a)
_, _, ans_u, _= calc(a)
ans += ans_u
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/519/A:
A and B are preparing themselves for programming contests.

To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.

For each chess piece we know its weight:   the queen's weight is 9,  the rook's weight is 5,  the bishop's weight is 3,  the knight's weight is 3,  the pawn's weight is 1,  the king's weight isn't considered in evaluating position.

The player's weight equals to the sum of weights of all his pieces on the board.

As A doesn't like counting, he asked you to help him determine which player has the larger position weight.

-----Input-----

The input contains eight lines, eight characters each — the board's description.

The white pieces on the board are marked with uppercase letters, the black pieces are marked with lowercase letters.

The white pieces are denoted as follows: the queen is represented is 'Q', the rook — as 'R', the bishop — as'B', the knight — as 'N', the pawn — as 'P', the king — as 'K'.

The black pieces are denoted as 'q', 'r', 'b', 'n', 'p', 'k', respectively.

An empty square of the board is marked as '.' (a dot).

It is not guaranteed that the given chess position can be achieved in a real game. Specifically, there can be an arbitrary (possibly zero) number pieces of each type, the king may be under attack and so on.

-----Output-----

Print "White" (without quotes) if the weight of the position of the white pieces is more than the weight of the position of the black pieces, print "Black" if the weight of the black pieces is more than the weight of the white pieces and print "Draw" if the weights of the white and black pieces are equal.

-----Examples-----
Input
...QK...
........
........
........
........
........
........
...rk...

Output
White

Input
rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR

Output
Draw

Input
rppppppr
...k....
........
........
........
........
K...Q...
........

Output
Black

-----Note-----

In the first test sample the...

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

desk = [list(input()) for i in range(8)]
C = {'q' : 9, 'r' : 5, 'b' : 3, 'n' : 3, 'p' : 1, 'k' : 0, '.' : 0}
p1 = 0
p2 = 0
for x in desk:
    for x2 in x:
        if x2.isupper():
            p2 += C[x2.lower()]
        else:
            p1 += C[x2]
if p1 == p2:
    print('Draw')
else:
    print('White' if p2 > p1 else 'Black')


I found an interesting problem on https://codeforces.com/problemset/problem/519/B:
A and B are preparing themselves for programming contests.

B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.

Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.

However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.

Can you help B find out exactly what two errors he corrected?

-----Input-----

The first line of the input contains integer n (3 ≤ n ≤ 10^5) — the initial number of compilation errors.

The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the errors the compiler displayed for the first time.

The third line contains n - 1 space-separated integers b_1, b_2, ..., b_{n} - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one.

The fourth line contains n - 2 space-separated integers с_1, с_2, ..., с_{n} - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.

-----Output-----

Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.

-----Examples-----
Input
5
1 5 8 123 7
123 7 5 1
5 1 7

Output
8
123

Input
6
1 4 3 3 5 7
3 7 5 4 3
4 3 7 5

Output
1
3

-----Note-----

In the first test sample B first corrects the error number 8, then the error number...

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

n = int(input())
e = [sum(map(int, input().split())) for i in range(3)]
print(e[0] - e[1])
print(e[1] - e[2])


I found an interesting problem on https://codeforces.com/problemset/problem/519/C:
A and B are preparing themselves for programming contests.

An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solving problems together with experienced participants.

A believes that the optimal team of three people should consist of one experienced participant and two newbies. Thus, each experienced participant can share the experience with a large number of people.

However, B believes that the optimal team should have two experienced members plus one newbie. Thus, each newbie can gain more knowledge and experience.

As a result, A and B have decided that all the teams during the training session should belong to one of the two types described above. Furthermore, they agree that the total number of teams should be as much as possible.

There are n experienced members and m newbies on the training session. Can you calculate what maximum number of teams can be formed?

-----Input-----

The first line contains two integers n and m (0 ≤ n, m ≤ 5·10^5) — the number of experienced participants and newbies that are present at the training session.

-----Output-----

Print the maximum number of teams that can be formed.

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

Output
2

Input
4 5

Output
3

-----Note-----

Let's represent the experienced players as XP and newbies as NB.

In the first test the teams look as follows: (XP, NB, NB), (XP, NB, NB).

In the second test sample the teams look as follows: (XP, NB, NB), (XP, NB, NB), (XP, XP, NB).

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

n, m = list(map(int, input().split(" ")))
total = (n + m) / 3
cnt = 0
while cnt < total and n > 0 and m > 0 :
  cnt+=1
  if n < m :
    n-=1
    m-=2
  else :
    n-=2
    m-=1

if n < 0 or m < 0  : cnt-=1
print(cnt)