I found an interesting problem on https://codeforces.com/problemset/problem/909/D:
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.

You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.

How many operations will you need to perform until the next operation does not have any points to delete?

-----Input-----

Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.

The number of the points is between 1 and 10^6.

-----Output-----

Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.

-----Examples-----
Input
aabb

Output
2

Input
aabcaa

Output
1

-----Note-----

In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.

In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied.

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

s = input()
n = 1

for i in range(1, len(s)):
  if s[i] != s[i-1]:
    n += 1

mas = [0] * n
col = [0] * n

count = 1
idx = 0
c = s[0]
for i in range(1, len(s)):
  if s[i] == s[i-1]:
    count += 1
  else:
    mas[idx] = count
    col[idx] = c
    idx += 1
    count = 1
    c = s[i]

mas[idx] = count
col[idx] = c

res = 0

while n > 1:
  newlen = n
  idx = -1

  for i in range(0, n):
    if (i == 0) or (i == n - 1):
      mas[i] -= 1
    elif mas[i] >= 2:
      mas[i] -= 2
    else:
      mas[i] = 0

    if mas[i] == 0:
      newlen -= 1
    else:
      if idx >= 0 and col[idx] == col[i]:
        mas[idx] += mas[i]
        newlen -= 1
      else:
        idx += 1
        mas[idx] = mas[i]
        col[idx] = col[i]
        type = i % 2

  n = newlen
  res += 1

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/909/E:
You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depends on have already completed.

Some of the tasks in the graph can only be executed on a coprocessor, and the rest can only be executed on the main processor. In one coprocessor call you can send it a set of tasks which can only be executed on it. For each task of the set, all tasks on which it depends must be either already completed or be included in the set. The main processor starts the program execution and gets the results of tasks executed on the coprocessor automatically.

Find the minimal number of coprocessor calls which are necessary to execute the given program.

-----Input-----

The first line contains two space-separated integers N (1 ≤ N ≤ 10^5) — the total number of tasks given, and M (0 ≤ M ≤ 10^5) — the total number of dependencies between tasks.

The next line contains N space-separated integers $E_{i} \in \{0,1 \}$. If E_{i} = 0, task i can only be executed on the main processor, otherwise it can only be executed on the coprocessor.

The next M lines describe the dependencies between tasks. Each line contains two space-separated integers T_1 and T_2 and means that task T_1 depends on task T_2 (T_1 ≠ T_2). Tasks are indexed from 0 to N - 1. All M pairs (T_1, T_2) are distinct. It is guaranteed that there are no circular dependencies between tasks.

-----Output-----

Output one line containing an integer — the minimal number of coprocessor calls necessary to execute the program.

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

Output
2

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

Output
1

-----Note-----

In the first test, tasks 1 and 3 can only be executed on the coprocessor. The dependency graph is linear, so the tasks must be executed in order 3 -> 2 -> 1 -> 0. You have to call...

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

n, m = [int(x) for x in input().split()]
tps = {i:int(t) for i, t in enumerate(input().split())}
deps = {i:0 for i in range(n)}
parents = {i:[] for i in range(n)}
leafs = {i for i in range(n)}
for i in range(m):
    x, y = [int(x) for x in input().split()]
    deps[x] += 1
    parents[y].append(x)
    if x in leafs:
        leafs.remove(x)

deep = {i:tps[i] for i in range(n)}
res = 0
while len(leafs) > 0:
    leaf = leafs.pop()
    if len(parents[leaf])==0:
        res = max(res, deep[leaf])
        continue
##    print(leaf, leafs)
    for parent in parents[leaf]:
        l = deep[leaf]
        if tps[parent] == 1 and tps[leaf] == 0:
            l += 1
        if deep[parent] < l:
            deep[parent] = l

        deps[parent] -= 1
        if deps[parent] == 0:
            leafs.add(parent)
##        print(leaf, parent, l, deps[parent], leafs, deep)

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/909/F:
Given an integer N, find two permutations:  Permutation p of numbers from 1 to N such that p_{i} ≠ i and p_{i} & i = 0 for all i = 1, 2, ..., N.  Permutation q of numbers from 1 to N such that q_{i} ≠ i and q_{i} & i ≠ 0 for all i = 1, 2, ..., N.

& is the bitwise AND operation.

-----Input-----

The input consists of one line containing a single integer N (1 ≤ N ≤ 10^5).

-----Output-----

For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them.

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

Output
NO
NO

Input
6

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

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

from math import log2, floor
n=int(input())
# n=100
if n%2:
	print('NO')
else:
	print("YES")
	k=floor(log2(n))+1
	res = [0 for i in range(n)]
	occupied = [0 for i in range(n)]
	switch = 0
	for i in range(n,0,-1):
		val = 2**k-1-i
		if val > n:
			k-=1
			val = 2**k-1-i
		if occupied[val-1]:
			while occupied[val-1]:
				k-=1
				val = 2**k-1-i
		val = 2**k-1-i
		occupied[val-1] = 1
		res[i-1] = val
	for i in res:
		print(i,end=' ')
	print()

if n in [1,2,3,4,5]:
	print('NO')
elif int(log2(n)) == log2(n):
	print('NO')
elif n == 6:
	print('YES')
	print('3 6 2 5 1 4')
else:
	print('YES')
	print('7 3 2 5 6 4 1',end=' ')
	for i in range(8,n+1):
		if int(log2(i)) == log2(i):
			print(min(i*2-1,n),end=' ')
		else:
			print(i-1,end=' ')
	print()


I found an interesting problem on https://codeforces.com/problemset/problem/910/A:
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.

For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.

Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.

-----Input-----

The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.

The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.

-----Output-----

If the frog can not reach the home, print -1.

In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.

-----Examples-----
Input
8 4
10010101

Output
2

Input
4 2
1001

Output
-1

Input
8 4
11100101

Output
3

Input
12 3
101111100101

Output
4

-----Note-----

In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).

In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.

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

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

a = [(n + 1)] * n

a[0] = 0
for i in range(1, n):
    if s[i] == '1':
        for j in range(max(0, i - d), i):
            a[i] = min(a[i], a[j] + 1)

print(a[n - 1] if a[n - 1] < n else -1)


I found an interesting problem on https://codeforces.com/problemset/problem/910/B:
Petya has equal wooden bars of length n. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length a and one top side of length b. A solid (i.e. continuous without breaks) piece of bar is needed for each side.

Determine a minimal number of wooden bars which are needed to make the frames for two doors. Petya can cut the wooden bars into any parts, but each side of each door should be a solid piece of a wooden bar (or a whole wooden bar).

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1 000) — the length of each wooden bar.

The second line contains a single integer a (1 ≤ a ≤ n) — the length of the vertical (left and right) sides of a door frame.

The third line contains a single integer b (1 ≤ b ≤ n) — the length of the upper side of a door frame.

-----Output-----

Print the minimal number of wooden bars with length n which are needed to make the frames for two doors.

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

Output
1

Input
5
3
4

Output
6

Input
6
4
2

Output
4

Input
20
5
6

Output
2

-----Note-----

In the first example one wooden bar is enough, since the total length of all six sides of the frames for two doors is 8.

In the second example 6 wooden bars is enough, because for each side of the frames the new wooden bar is needed.

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

import math
[n,a,b],r,i,j=[int(input())for x in range(3)],6,4,5
while i>=0:
	l,c,o=[b if x in[i,j]else a for x in range(6)],0,n
	for k in l:
		if o<k:
			o,c=n-k,c+1
		else:o-=k
	r=min(r,c if o==n else c+1)
	j-=1
	if i==j:i,j=i-1,5
print(r)


I found an interesting problem on https://codeforces.com/problemset/problem/910/C:
Petya has n positive integers a_1, a_2, ..., a_{n}.

His friend Vasya decided to joke and replaced all digits in Petya's numbers with a letters. He used the lowercase letters of the Latin alphabet from 'a' to 'j' and replaced all digits 0 with one letter, all digits 1 with another letter and so on. For any two different digits Vasya used distinct letters from 'a' to 'j'.

Your task is to restore Petya's numbers. The restored numbers should be positive integers without leading zeros. Since there can be multiple ways to do it, determine the minimum possible sum of all Petya's numbers after the restoration. It is guaranteed that before Vasya's joke all Petya's numbers did not have leading zeros.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1 000) — the number of Petya's numbers.

Each of the following lines contains non-empty string s_{i} consisting of lowercase Latin letters from 'a' to 'j' — the Petya's numbers after Vasya's joke. The length of each string does not exceed six characters.

-----Output-----

Determine the minimum sum of all Petya's numbers after the restoration. The restored numbers should be positive integers without leading zeros. It is guaranteed that the correct restore (without leading zeros) exists for all given tests.

-----Examples-----
Input
3
ab
de
aj

Output
47

Input
5
abcdef
ghij
bdef
accbd
g

Output
136542

Input
3
aa
jj
aa

Output
44

-----Note-----

In the first example, you need to replace the letter 'a' with the digit 1, the letter 'b' with the digit 0, the letter 'd' with the digit 2, the letter 'e' with the digit 3, and the letter 'j' with the digit 4. So after the restoration numbers will look like [10, 23, 14]. The sum of them is equal to 47, which is the minimum possible sum of the numbers after the correct restoration.

In the second example the numbers after the restoration can look like: [120468, 3579, 2468, 10024, 3].

In the second example the numbers after the restoration can look like: [11, 22, 11].

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

# Minimum Sum
from collections import defaultdict

n = int(input())
nums = []
digits = defaultdict(int)
heads = set()
for i in range(n):
    nums.append(input())
    w = 1
    heads.add(nums[-1][0])
    for c in range(len(nums[-1]), 0, -1):
        digits[nums[-1][c - 1]] += w
        w *= 10

matching_digits = {}
result = sorted(list(digits.items()), key=lambda i: i[1])

matching_digits[result[-1][0]] = 1

for i in range(len(result) - 1, 0, -1):
    if result[i - 1][0] not in heads:
        matching_digits[result[i - 1][0]] = 0
        break

v = 2
for i in range(len(result) - 1, 0, -1):
    if not result[i - 1][0] in matching_digits:
        matching_digits[result[i - 1][0]] = v
        v += 1

sum = 0
for num in nums:
    sum += int(''.join(str(matching_digits[c]) for c in num))

print(sum)


I found an interesting problem on https://codeforces.com/problemset/problem/911/A:
You are given an array of n integer numbers a_0, a_1, ..., a_{n} - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.

-----Input-----

The first line contains positive integer n (2 ≤ n ≤ 10^5) — size of the given array. The second line contains n integers a_0, a_1, ..., a_{n} - 1 (1 ≤ a_{i} ≤ 10^9) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.

-----Output-----

Print the only number — distance between two nearest minimums in the array.

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

Output
1

Input
3
5 6 5

Output
2

Input
9
2 1 3 5 4 1 2 3 1

Output
3

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

n = int(input())
A = [int(x) for x in input().split()]
mn = min(A)

I = [i for i in range(len(A)) if A[i] == mn]
mindiff = min(I[i]-I[i-1] for i in range(1,len(I)))
print(mindiff)


I found an interesting problem on https://codeforces.com/problemset/problem/911/B:
It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into a pieces, and the second one — into b pieces.

Ivan knows that there will be n people at the celebration (including himself), so Ivan has set n plates for the cakes. Now he is thinking about how to distribute the cakes between the plates. Ivan wants to do it in such a way that all following conditions are met:  Each piece of each cake is put on some plate;  Each plate contains at least one piece of cake;  No plate contains pieces of both cakes.

To make his guests happy, Ivan wants to distribute the cakes in such a way that the minimum number of pieces on the plate is maximized. Formally, Ivan wants to know the maximum possible number x such that he can distribute the cakes according to the aforementioned conditions, and each plate will contain at least x pieces of cake.

Help Ivan to calculate this number x!

-----Input-----

The first line contains three integers n, a and b (1 ≤ a, b ≤ 100, 2 ≤ n ≤ a + b) — the number of plates, the number of pieces of the first cake, and the number of pieces of the second cake, respectively.

-----Output-----

Print the maximum possible number x such that Ivan can distribute the cake in such a way that each plate will contain at least x pieces of cake.

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

Output
1

Input
4 7 10

Output
3

-----Note-----

In the first example there is only one way to distribute cakes to plates, all of them will have 1 cake on it.

In the second example you can have two plates with 3 and 4 pieces of the first cake and two plates both with 5 pieces of the second cake. Minimal number of pieces is 3.

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

from sys import stdin, stdout

INF = float('inf')

n, a, b = map(int, stdin.readline().split())

l, r = 1, 200
while r - l > 1:
    m = (l + r) >> 1

    if (b // m and a // m and a // m + b // m >= n):
        l = m
    else:
        r = m

stdout.write(str(l))


I found an interesting problem on https://codeforces.com/problemset/problem/911/C:
Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on.

When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if i-th garland is switched on during x-th second, then it is lit only during seconds x, x + k_{i}, x + 2k_{i}, x + 3k_{i} and so on.

Mishka wants to switch on the garlands in such a way that during each second after switching the garlands on there would be at least one lit garland. Formally, Mishka wants to choose three integers x_1, x_2 and x_3 (not necessarily distinct) so that he will switch on the first garland during x_1-th second, the second one — during x_2-th second, and the third one — during x_3-th second, respectively, and during each second starting from max(x_1, x_2, x_3) at least one garland will be lit.

Help Mishka by telling him if it is possible to do this!

-----Input-----

The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_{i} ≤ 1500) — time intervals of the garlands.

-----Output-----

If Mishka can choose moments of time to switch on the garlands in such a way that each second after switching the garlands on at least one garland will be lit, print YES.

Otherwise, print NO.

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

Output
YES

Input
4 2 3

Output
NO

-----Note-----

In the first example Mishka can choose x_1 = 1, x_2 = 2, x_3 = 1. The first garland will be lit during seconds 1, 3, 5, 7, ..., the second — 2, 4, 6, 8, ..., which already cover all the seconds after the 2-nd one. It doesn't even matter what x_3 is chosen. Our choice will lead third to be lit during seconds 1, 4, 7, 10, ..., though.

In the second example there is no way to choose such moments of time, there always be some seconds when no garland is lit.

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

k1,k2,k3=list(map(int,input().split()))
L=[k1,k2,k3]

if L.count(1) != 0:
    print("YES")
elif L.count(2) >= 2:
    print('YES')

elif L.count(3) == 3:
    print("YES")

elif L.count(4)==2 and L.count(2)==1:
    print("YES")
else: print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/911/D:
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_{i} < a_{j}. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).

You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].

After each query you have to determine whether the number of inversions is odd or even.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — the elements of the permutation. These integers are pairwise distinct.

The third line contains one integer m (1 ≤ m ≤ 2·10^5) — the number of queries to process.

Then m lines follow, i-th line containing two integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) denoting that i-th query is to reverse a segment [l_{i}, r_{i}] of the permutation. All queries are performed one after another.

-----Output-----

Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.

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

Output
odd
even

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

Output
odd
odd
odd
even

-----Note-----

The first example:

  after the first query a = [2, 1, 3], inversion: (2, 1);  after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2).

The second example:

  a = [1, 2, 4, 3], inversion: (4, 3);  a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);  a = [1, 2, 4, 3], inversion: (4, 3);  a = [1, 4, 2, 3], inversions: (3, 2), (4, 2).

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

n = int(input())
d = list(map(int, input().split()))
odd = 0
for i in range(n):
    for j in range(i, n):
        if(d[i]>d[j]): odd ^= 1

m = int(input())
ans = []
for i in range(m):
    l, r = list(map(int, input().split()))
    k = r-l+1
    if( (k*(k-1)/2) %2): odd ^= 1
    ans.append( "odd" if odd else "even")

print('\n'.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/911/E:
Let's suppose you have an array a, a stack s (initially empty) and an array b (also initially empty).

You may perform the following operations until both a and s are empty:

  Take the first element of a, push it into s and remove it from a (if a is not empty);  Take the top element from s, append it to the end of array b and remove it from s (if s is not empty).

You can perform these operations in arbitrary order.

If there exists a way to perform the operations such that array b is sorted in non-descending order in the end, then array a is called stack-sortable.

For example, [3, 1, 2] is stack-sortable, because b will be sorted if we perform the following operations:

  Remove 3 from a and push it into s;  Remove 1 from a and push it into s;  Remove 1 from s and append it to the end of b;  Remove 2 from a and push it into s;  Remove 2 from s and append it to the end of b;  Remove 3 from s and append it to the end of b.

After all these operations b = [1, 2, 3], so [3, 1, 2] is stack-sortable. [2, 3, 1] is not stack-sortable.

You are given k first elements of some permutation p of size n (recall that a permutation of size n is an array of size n where each integer from 1 to n occurs exactly once). You have to restore the remaining n - k elements of this permutation so it is stack-sortable. If there are multiple answers, choose the answer such that p is lexicographically maximal (an array q is lexicographically greater than an array p iff there exists some integer k such that for every i < k q_{i} = p_{i}, and q_{k} > p_{k}). You may not swap or change any of first k elements of the permutation.

Print the lexicographically maximal permutation p you can obtain.

If there exists no answer then output -1.

-----Input-----

The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k < n) — the size of a desired permutation, and the number of elements you are given, respectively.

The second line contains k integers p_1, p_2, ..., p_{k} (1 ≤ p_{i} ≤ n) — the first k elements of p. These integers...

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

import sys

n,k = map(int,input().split())
a = list(map(int,input().split()))
setofa = set(a)
s = []
f= False
ai = 0
ans = []
for i in range(1, n+1):
  if i in setofa:
    while ai < k and (len(s)==0 or s[-1]!=i):
      s.append(a[ai])
      ai += 1
    if len(s) == 0 or s[-1] != i:
      f = True
      break
    s.pop(-1)
    a += ans[::-1]
    ans = []
  else:
    if ai != k:
      s += a[ai:k]
      ai = k
    ans.append(i)

if f:
  print(-1)
else:
  print(' '.join(map(str, a + ans[::-1])))


I found an interesting problem on https://codeforces.com/problemset/problem/911/F:
You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps:   choose two leaves;  add the length of the simple path between them to the answer;  remove one of the chosen leaves from the tree.

Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex.

Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer!

-----Input-----

The first line contains one integer number n (2 ≤ n ≤ 2·10^5) — the number of vertices in the tree.

Next n - 1 lines describe the edges of the tree in form a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}). It is guaranteed that given graph is a tree.

-----Output-----

In the first line print one integer number — maximal possible answer.

In the next n - 1 lines print the operations in order of their applying in format a_{i}, b_{i}, c_{i}, where a_{i}, b_{i} — pair of the leaves that are chosen in the current operation (1 ≤ a_{i}, b_{i} ≤ n), c_{i} (1 ≤ c_{i} ≤ n, c_{i} = a_{i} or c_{i} = b_{i}) — choosen leaf that is removed from the tree in the current operation.

See the examples for better understanding.

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

Output
3
2 3 3
2 1 1

Input
5
1 2
1 3
2 4
2 5

Output
9
3 5 5
4 3 3
4 1 1
4 2 2

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

import sys
from collections import deque as dq
n = int(input())

ind = 0
inp = [int(x)-1 for line in sys.stdin.readlines() for x in line.split()]

coupl = [[] for _ in range(n)]
for _ in range(n-1):
    a,b = inp[ind],inp[ind+1]
    ind+=2
    coupl[a].append(b)
    coupl[b].append(a)

Q = dq()
found = [False]*n
master = 0
found[master] = True

dia1 = 0
Q.append(master)
while Q:
    node = Q.popleft()
    dia1 = node
    for nei in coupl[node]:
        if not found[nei]:
            found[nei] = True
            Q.append(nei)

dia2 = 0
Q.append((dia1,0))
dist1 = [0]*n
found = [False]*n
found[dia1] = True
while Q:
    node,d = Q.popleft()
    dia2 = node
    dist1[node]=d
    for nei in coupl[node]:
        if not found[nei]:
            found[nei] = True
            Q.append((nei,d+1))

Q = []
Q.append((dia2,0))
dist2 = [0]*n
found = [False]*n
found[dia2] = True
while Q:
    node,d = Q.pop()
    dist2[node]=d
    for nei in coupl[node]:
        if not found[nei]:
            found[nei] = True
            Q.append((nei,d+1))

neigs = [0]*n

leaves = []
for i in range(n):
    if i != dia1 and i != dia2 and len(coupl[i])==1:
        leaves.append(i)
    neigs[i]=len(coupl[i])
points = 0
lista = []

while leaves:
    node = leaves.pop()
    if dist1[node]<dist2[node]:
        lista.append((dia2,node,node))
        points += dist2[node]
    else:
        lista.append((dia1,node,node))
        points += dist1[node]
    for nei in coupl[node]:
        neigs[nei]-=1
        if neigs[nei]==1:
            leaves.append(nei)
leaves.append(dia2)
while leaves:
    node = leaves.pop()
    lista.append((dia1,node,node))
    points += dist1[node]
    for nei in coupl[node]:
        neigs[nei]-=1
        if neigs[nei]==1:
            leaves.append(nei)
print(points)
for l in lista:
    a,b,c = l
    print(a+1,b+1,c+1)


I found an interesting problem on https://codeforces.com/problemset/problem/912/A:
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.

Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green — one yellow and one blue, and for a blue ball, three blue crystals are enough.

Right now there are A yellow and B blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls.

-----Input-----

The first line features two integers A and B (0 ≤ A, B ≤ 10^9), denoting the number of yellow and blue crystals respectively at Grisha's disposal.

The next line contains three integers x, y and z (0 ≤ x, y, z ≤ 10^9) — the respective amounts of yellow, green and blue balls to be obtained.

-----Output-----

Print a single integer — the minimum number of crystals that Grisha should acquire in addition.

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

Output
2

Input
3 9
1 1 3

Output
1

Input
12345678 87654321
43043751 1000000000 53798715

Output
2147483648

-----Note-----

In the first sample case, Grisha needs five yellow and four blue crystals to create two yellow balls, one green ball, and one blue ball. To do that, Grisha needs to obtain two additional crystals: one yellow and one blue.

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

a, b = list(map(int, input().split()))
x, y, z = list(map(int, input().split()))

c = 2 * x + y
d = y + 3 * z

print(max(c - a, 0) + max(d - b, 0))


I found an interesting problem on https://codeforces.com/problemset/problem/912/B:
Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains n sweet candies from the good ol' bakery, each labeled from 1 to n corresponding to its tastiness. No two candies have the same tastiness.

The choice of candies has a direct effect on Grisha's happiness. One can assume that he should take the tastiest ones — but no, the holiday magic turns things upside down. It is the xor-sum of tastinesses that matters, not the ordinary sum!

A xor-sum of a sequence of integers a_1, a_2, ..., a_{m} is defined as the bitwise XOR of all its elements: $a_{1} \oplus a_{2} \oplus \ldots \oplus a_{m}$, here $\oplus$ denotes the bitwise XOR operation; more about bitwise XOR can be found here.

Ded Moroz warned Grisha he has more houses to visit, so Grisha can take no more than k candies from the bag. Help Grisha determine the largest xor-sum (largest xor-sum means maximum happiness!) he can obtain.

-----Input-----

The sole string contains two integers n and k (1 ≤ k ≤ n ≤ 10^18).

-----Output-----

Output one number — the largest possible xor-sum.

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

Output
7

Input
6 6

Output
7

-----Note-----

In the first sample case, one optimal answer is 1, 2 and 4, giving the xor-sum of 7.

In the second sample case, one can, for example, take all six candies and obtain the xor-sum of 7.

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

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

if k == 1:
    print(n)
else:
    print(int(bin(n)[2:].replace('0', '1'), 2))


I found an interesting problem on https://codeforces.com/problemset/problem/912/D:
While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size n × m, divided into cells of size 1 × 1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!).

The gift bundle also includes a square scoop of size r × r, designed for fishing. If the lower-left corner of the scoop-net is located at cell (x, y), all fishes inside the square (x, y)...(x + r - 1, y + r - 1) get caught. Note that the scoop-net should lie completely inside the pond when used.

Unfortunately, Sasha is not that skilled in fishing and hence throws the scoop randomly. In order to not frustrate Sasha, Misha decided to release k fishes into the empty pond in such a way that the expected value of the number of caught fishes is as high as possible. Help Misha! In other words, put k fishes in the pond into distinct cells in such a way that when the scoop-net is placed into a random position among (n - r + 1)·(m - r + 1) possible positions, the average number of caught fishes is as high as possible.

-----Input-----

The only line contains four integers n, m, r, k (1 ≤ n, m ≤ 10^5, 1 ≤ r ≤ min(n, m), 1 ≤ k ≤ min(n·m, 10^5)).

-----Output-----

Print a single number — the maximum possible expected number of caught fishes.

You answer is considered correct, is its absolute or relative error does not exceed 10^{ - 9}. Namely, let your answer be a, and the jury's answer be b. Your answer is considered correct, if $\frac{|a - b|}{\operatorname{max}(1,|b|)} \leq 10^{-9}$.

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

Output
2.0000000000

Input
12 17 9 40

Output
32.8333333333

-----Note-----

In the first example you can put the fishes in cells (2, 1), (2, 2), (2, 3). In this case, for any of four possible positions of the scoop-net (highlighted with light green), the number of fishes inside is equal to two, and so is the expected value. [Image]

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

import queue
q = queue.PriorityQueue()
n, m, r, k = map(int, input().split())
a = min(r, n - r + 1)
b = min(r, m - r + 1)
u = n - 2 * a + 2
v = m - 2 * b + 2
for i in range(1, a + 1): q.put((-b * i, i))
t = 0
while k:
    s, i = q.get()
    q.put((s + i, i))
    d = min((u if i == a else 2) * (v if s == -b * i else 2), k)
    t -= s * d
    k -= d
print(t / (n - r + 1) / (m - r + 1))


I found an interesting problem on https://codeforces.com/problemset/problem/913/A:
The following problem is well-known: given integers n and m, calculate $2^{n} \operatorname{mod} m$,

where 2^{n} = 2·2·...·2 (n factors), and $x \operatorname{mod} y$ denotes the remainder of division of x by y.

You are asked to solve the "reverse" problem. Given integers n and m, calculate $m \operatorname{mod} 2^{n}$.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^8).

The second line contains a single integer m (1 ≤ m ≤ 10^8).

-----Output-----

Output a single integer — the value of $m \operatorname{mod} 2^{n}$.

-----Examples-----
Input
4
42

Output
10

Input
1
58

Output
0

Input
98765432
23456789

Output
23456789

-----Note-----

In the first example, the remainder of division of 42 by 2^4 = 16 is equal to 10.

In the second example, 58 is divisible by 2^1 = 2 without remainder, and the answer is 0.

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

#!/usr/bin/env python3

def main():
    n = int(input())
    m = int(input())
    print(m % (1 << n) if m >> n else m)

try:
    while True:
        main()
except EOFError:
    pass


I found an interesting problem on https://codeforces.com/problemset/problem/913/B:
Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.

Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.

The definition of a rooted tree can be found here.

-----Input-----

The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer p_{i} (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ p_{i} ≤ i).

Vertex 1 is the root. It's guaranteed that the root has at least 2 children.

-----Output-----

Print "Yes" if the tree is a spruce and "No" otherwise.

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

Output
Yes

Input
7
1
1
1
2
2
2

Output
No

Input
8
1
1
1
1
3
3
3

Output
Yes

-----Note-----

The first example:

[Image]

The second example:

$8$

It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.

The third example:

[Image]

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

a = dict()
for i in range(int(input())-1):
	c = int(input())
	if (not c in a): a[c] = list()
	a[c].append(i+2)
for i in a:
	l = int()
	for j in a[i]:
		if (j not in a): l += 1
	if (l < 3):
		print("No")
		return
print("Yes")


I found an interesting problem on https://codeforces.com/problemset/problem/913/C:
A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.

Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2^{i} - 1 liters and costs c_{i} roubles. The number of bottles of each type in the store can be considered infinite.

You want to buy at least L liters of lemonade. How many roubles do you have to spend?

-----Input-----

The first line contains two integers n and L (1 ≤ n ≤ 30; 1 ≤ L ≤ 10^9) — the number of types of bottles in the store and the required amount of lemonade in liters, respectively.

The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^9) — the costs of bottles of different types.

-----Output-----

Output a single integer — the smallest number of roubles you have to pay in order to buy at least L liters of lemonade.

-----Examples-----
Input
4 12
20 30 70 90

Output
150

Input
4 3
10000 1000 100 10

Output
10

Input
4 3
10 100 1000 10000

Output
30

Input
5 787787787
123456789 234567890 345678901 456789012 987654321

Output
44981600785557577

-----Note-----

In the first example you should buy one 8-liter bottle for 90 roubles and two 2-liter bottles for 30 roubles each. In total you'll get 12 liters of lemonade for just 150 roubles.

In the second example, even though you need only 3 liters, it's cheaper to buy a single 8-liter bottle for 10 roubles.

In the third example it's best to buy three 1-liter bottles for 10 roubles each, getting three liters for 30 roubles.

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

n,L=[int(i) for i in input().split()]
c=[int(i) for i in input().split()]
costPerLemon=[]
ans=12345678901234567890

for i in range(n):
	costPerLemon.append(c[i]/2**i)

size=n
money=0
while size>1:
	target=min(costPerLemon)
	i=costPerLemon.index(target)

	times=int(L/(2**i))
	money+=c[i]*times
	L-=(2**i)*times

	ans=min(ans,money+c[i])
	size=i
	while len(costPerLemon)>size:
		costPerLemon.pop(-1)
money+=L*c[0]
ans=min(ans,money)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/913/D:
You are preparing for an exam on scheduling theory. The exam will last for exactly T milliseconds and will consist of n problems. You can either solve problem i in exactly t_{i} milliseconds or ignore it and spend no time. You don't need time to rest after solving a problem, either.

Unfortunately, your teacher considers some of the problems too easy for you. Thus, he assigned an integer a_{i} to every problem i meaning that the problem i can bring you a point to the final score only in case you have solved no more than a_{i} problems overall (including problem i).

Formally, suppose you solve problems p_1, p_2, ..., p_{k} during the exam. Then, your final score s will be equal to the number of values of j between 1 and k such that k ≤ a_{p}_{j}.

You have guessed that the real first problem of the exam is already in front of you. Therefore, you want to choose a set of problems to solve during the exam maximizing your final score in advance. Don't forget that the exam is limited in time, and you must have enough time to solve all chosen problems. If there exist different sets of problems leading to the maximum final score, any of them will do.

-----Input-----

The first line contains two integers n and T (1 ≤ n ≤ 2·10^5; 1 ≤ T ≤ 10^9) — the number of problems in the exam and the length of the exam in milliseconds, respectively.

Each of the next n lines contains two integers a_{i} and t_{i} (1 ≤ a_{i} ≤ n; 1 ≤ t_{i} ≤ 10^4). The problems are numbered from 1 to n.

-----Output-----

In the first line, output a single integer s — your maximum possible final score.

In the second line, output a single integer k (0 ≤ k ≤ n) — the number of problems you should solve.

In the third line, output k distinct integers p_1, p_2, ..., p_{k} (1 ≤ p_{i} ≤ n) — the indexes of problems you should solve, in any order.

If there are several optimal sets of problems, you may output any of them.

-----Examples-----
Input
5 300
3 100
4 150
4 80
2 90
2 300

Output
2
3
3 1 4

Input
2 100
1 787
2 788

Output
0
0

Input
2 100
2...

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

# https://codeforces.com/contest/913/problem/D
import heapq
from heapq import heappush as push_
from heapq import heappop  as pop_

class heapT():
    def __init__(self, T):
        self.Q     = []
        self.curT  = 0
        self.maxT  = T
        self.his   = []

    def push(self, t, index):
        push_(self.Q, (-t, index))
        self.his.append(index)
        self.curT += t

        while self.curT > self.maxT:
            self.pop()

    def pop(self):
        t, ind     = pop_(self.Q)
        self.his.append(ind)
        self.curT -= t * -1

    def normalize(self, length):
        while len(self.Q) > length:
            self.pop()

def solve(a, n, T):
    a    =  sorted(a, key=lambda x:x[0], reverse=True)
    H    =  heapT(T)

    max_ = -1
    pos  = None

    for ak, t, ind in a:
        H.push(t, ind)
        H.normalize(ak)

        if len(H.Q) >  max_:
            max_ = len(H.Q)
            pos  = len(H.his)

    d = {}
    if pos is not None:
        for x in H.his[:pos]:
            if x not in d:
                d[x] = 1
            else:
                del d[x]

    if len(d) > 0:
        print(len(d))
        print(len(d))
        print(' '.join([str(x+1) for x in d]))
    else:
        print('0'+'\n'+'0')

n, T =  list(map(int, input().split()))
a    =  [list(map(int, input().split())) + [_] for _ in range(n)]
solve(a, n, T)

#5 300
#3 100
#4 150
#4 80
#2 90
#2 300

#7 100
#5 30
#5 40
#6 20
#2 50
#2 40
#3 10
#4 10

#2 100
#1 787
#2 788


I found an interesting problem on https://codeforces.com/problemset/problem/913/E:
You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:   Operation AND ('&', ASCII code 38)  Operation OR ('|', ASCII code 124)  Operation NOT ('!', ASCII code 33)  Variables x, y and z (ASCII codes 120-122)  Parentheses ('(', ASCII code 40, and ')', ASCII code 41)

If more than one expression of minimum length exists, you should find the lexicographically smallest one.

Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:

E ::= E '|' T | T

T ::= T '&' F | F

F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'

-----Input-----

The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000).

The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of $x = \lfloor \frac{j}{4} \rfloor$, $y = \lfloor \frac{j}{2} \rfloor \operatorname{mod} 2$ and $z = j \operatorname{mod} 2$.

-----Output-----

You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.

-----Example-----
Input
4
00110011
00000111
11110000
00011111

Output
y
(y|z)&x
!x
x|y&z

-----Note-----

The truth table for the second function:

[Image]

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

x = int('00001111', 2)
y = int('00110011', 2)
z = int('01010101', 2)
E = set()
T = set()
F = {('x', x), ('y', y), ('z', z)}
prv = (set(), set(), set())
fam = 2 ** 8
tmpl = '#' * 99
ans = [tmpl] * fam
def cmpr(E):
    nonlocal ans
    ans = [tmpl] * fam
    for e in E:
        if len(ans[e[1]]) > len(e[0]) or len(ans[e[1]]) == len(e[0]) and ans[e[1]] > e[0]:
            ans[e[1]] = e[0]
    return set((j, i) for i, j in enumerate(ans) if j != tmpl)
while prv != (E, T, F):
    prv = E.copy(), T.copy(), F.copy()
    for f in prv[2]:
        F.add(('!' + f[0], ~f[1] & (fam - 1)))
        T.add(f)
        for t in prv[1]:
            T.add((t[0] + '&' + f[0], t[1] & f[1]))
    for t in prv[1]:
        E.add(t)
    for e in prv[0]:
        if e not in F:
            F.add(('(' + e[0] + ')', e[1]))
        for t in prv[1]:
            E.add((e[0] + '|' + t[0], e[1] | t[1]))
    E, T, F = cmpr(E), cmpr(T), cmpr(F)
cmpr(E)
n = int(input())
for i in range(n):
	print(ans[int(input(), 2)])


I found an interesting problem on https://codeforces.com/problemset/problem/913/G:
You are given n positive integers a_1, a_2, ..., a_{n}.

For every a_{i} you need to find a positive integer k_{i} such that the decimal notation of 2^{k}_{i} contains the decimal notation of a_{i} as a substring among its last min(100, length(2^{k}_{i})) digits. Here length(m) is the length of the decimal notation of m.

Note that you don't have to minimize k_{i}. The decimal notations in this problem do not contain leading zeros.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 2 000) — the number of integers a_{i}.

Each of the next n lines contains a positive integer a_{i} (1 ≤ a_{i} < 10^11).

-----Output-----

Print n lines. The i-th of them should contain a positive integer k_{i} such that the last min(100, length(2^{k}_{i})) digits of 2^{k}_{i} contain the decimal notation of a_{i} as a substring. Integers k_{i} must satisfy 1 ≤ k_{i} ≤ 10^50.

It can be shown that the answer always exists under the given constraints. If there are multiple answers, print any of them.

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

Output
3
1

Input
2
3
4857

Output
5
20

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

def dlog(x, n):
  bigMod = 5 ** n
  ans = [None, 0, 1, 3, 2][x % 5]
  val = 2 ** ans % bigMod
  mod, phi = 5, 4
  phiVal = 2 ** phi % bigMod
  for i in range(2, n + 1):
    nextMod = mod * 5
    while val % nextMod != x % nextMod:
      val = val * phiVal % bigMod
      ans += phi
    phi *= 5
    phiVal = (phiVal *
              phiVal % bigMod *
              phiVal % bigMod *
              phiVal % bigMod *
              phiVal % bigMod)
    mod = nextMod
  return ans

def main():
  inp = input()
  n = len(inp)
  a = int(inp)
  for m in range(n + 1):
    l = a * 10 ** m
    x, mod = l, 2 ** (n + m)
    if x % mod != 0:
      x += mod - x % mod
    if x % 5 == 0:
      x += mod
    if x < l + 10 ** m:
      assert x % mod == 0 and x % 5 != 0
      x = x // mod
      mod = 5 ** (n + m)
      print(n + m + dlog(x % mod, n + m))
      return
  assert False

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


I found an interesting problem on https://codeforces.com/problemset/problem/914/A:
Given an array a_1, a_2, ..., a_{n} of n integers, find the largest number in the array that is not a perfect square.

A number x is said to be a perfect square if there exists an integer y such that x = y^2.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array.

The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^6 ≤ a_{i} ≤ 10^6) — the elements of the array.

It is guaranteed that at least one element of the array is not a perfect square.

-----Output-----

Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.

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

Output
2

Input
8
1 2 4 8 16 32 64 576

Output
32

-----Note-----

In the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2.

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

def square(n):
    if n<0:
        return False
    lo=0
    hi=n
    while lo+1<hi:
        mid=(lo+hi)//2
        if mid*mid>n:
            hi=mid
        if mid*mid<n:
            lo=mid
        if mid*mid==n:
            return True
    if lo*lo==n or hi*hi==n:
        return True
    return False

n=int(input())
line=input().split()

best=-10**7
for i in range(n):
    a=int(line[i])
    if not square(a):
        best=max(best,a)
print (best)


I found an interesting problem on https://codeforces.com/problemset/problem/914/B:
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number a_{i} written on it.

They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that a_{j} < a_{i}.

A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.

-----Input-----

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

The next line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5), where a_{i} is the number on the i-th card.

-----Output-----

If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).

-----Examples-----
Input
3
4 5 7

Output
Conan

Input
2
1 1

Output
Agasa

-----Note-----

In the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.

In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.

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

n = int(input())
a = [int(i) for i in input().split()]
maxa = max(a)
cnt = a.count(maxa)
if n == cnt:
    if cnt % 2:
        print("Conan")
    else:
        print("Agasa")
    return
p = [0] * (10**5 + 1)
for i in a:
    p[i] += 1
for i in range(10**5, 0, -1):
    if p[i] % 2:
        print("Conan")
        break
else:
    print("Agasa")


I found an interesting problem on https://codeforces.com/problemset/problem/914/C:
The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer x and reduce it to the number of bits set to 1 in the binary representation of x. For example for number 13 it's true that 13_10 = 1101_2, so it has 3 bits set and 13 will be reduced to 3 in one operation.

He calls a number special if the minimum number of operations to reduce it to 1 is k.

He wants to find out how many special numbers exist which are not greater than n. Please help the Travelling Salesman, as he is about to reach his destination!

Since the answer can be large, output it modulo 10^9 + 7.

-----Input-----

The first line contains integer n (1 ≤ n < 2^1000).

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

Note that n is given in its binary representation without any leading zeros.

-----Output-----

Output a single integer — the number of special numbers not greater than n, modulo 10^9 + 7.

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

Output
3

Input
111111011
2

Output
169

-----Note-----

In the first sample, the three special numbers are 3, 5 and 6. They get reduced to 2 in one operation (since there are two set bits in each of 3, 5 and 6) and then to 1 in one more operation (since there is only one set bit in 2).

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

def reduce(n):
    n=bin(n)[2:]
    n=list(n)
    n=list(map(int,n))
    return sum(n)

def a(n,bits,dp):
    if(bits==0):
        return 1

    if(n=='0' or n==''):
        return 0
    if(bits>len(n)):
        return 0
    if(bits==len(n)):
        if(n=='1'*len(n)):
            #print(n,bits,1)
            return 1
        else:
            return 0
    """
    i=1
    while(i<len(n) and n[i]=='0'):
        i+=1

    x=dp[len(n)-1][bits] + a(n[i:],bits-1,dp)
    #print(n,bits,dp[len(n)-1][bits],x)
    return x%1000000007
    """
    ans=0
    while(bits!=0 and (n!='' and n!='0') and bits<len(n)):
        ans+=dp[len(n)-1][bits]
        i=1
        while(i<len(n) and n[i]=='0'):
            i+=1
        n=n[i:]
        bits-=1
    if(bits==0):
        ans+=1
    elif(bits==len(n) and n=='1'*len(n)):
        ans+=1
    return ans

n=(input())
k=int(input())

if(k>5):
    print(0)
elif(k==0):
    print(1)
elif(k==1):
    print(len(n)-1)

else:
    dp=[]
    dp.append([0,])
    for i in range(1,1002):
        dp.append([])

        for j in range(i):
            if(j==0):
                dp[i].append(1)
            else:
                dp[i].append((dp[i-1][j-1]+dp[i-1][j])%1000000007)
        dp[i].append(1)

    pos=[]
    for i in range(1,len(n)+1):
        count=0
        I=i
        while(i!=1):
            i=reduce(i)
            count+=1
        if(count==k-1):
            pos.append(I)
    ans=0
    for i in pos:
        ans+=a(n,i,dp)
    #print(dp)
    #print(a('10000',3,dp))

    #print(pos)
    print(ans%1000000007)


I found an interesting problem on https://codeforces.com/problemset/problem/915/A:
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly a_{i} each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden.

Luba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length a_{i} if she chooses the i-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden.

See the examples for better understanding.

-----Input-----

The first line of input contains two integer numbers n and k (1 ≤ n, k ≤ 100) — the number of buckets and the length of the garden, respectively.

The second line of input contains n integer numbers a_{i} (1 ≤ a_{i} ≤ 100) — the length of the segment that can be watered by the i-th bucket in one hour.

It is guaranteed that there is at least one bucket such that it is possible to water the garden in integer number of hours using only this bucket.

-----Output-----

Print one integer number — the minimum number of hours required to water the garden.

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

Output
2

Input
6 7
1 2 3 4 5 6

Output
7

-----Note-----

In the first test the best option is to choose the bucket that allows to water the segment of length 3. We can't choose the bucket that allows to water the segment of length 5 because then we can't water the whole garden.

In the second test we can choose only the bucket that allows us to water the segment of length 1.

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

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

lst = []
for x in input().split():
    lst.append(int(x))

i = 0
for x in lst:
    if k % x == 0:
        i = max(i, x)

print(k // i)


I found an interesting problem on https://codeforces.com/problemset/problem/915/B:
Luba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this segment as fast as possible.

Each second Luba can either try moving the cursor to the left or to the right (if the cursor is currently at the tab i, then she can move it to the tab max(i - 1, a) or to the tab min(i + 1, b)) or try closing all the tabs to the left or to the right of the cursor (if the cursor is currently at the tab i, she can close all the tabs with indices from segment [a, i - 1] or from segment [i + 1, b]). In the aforementioned expressions a and b denote the minimum and maximum index of an unclosed tab, respectively. For example, if there were 7 tabs initially and tabs 1, 2 and 7 are closed, then a = 3, b = 6.

What is the minimum number of seconds Luba has to spend in order to leave only the tabs with initial indices from l to r inclusive opened?

-----Input-----

The only line of input contains four integer numbers n, pos, l, r (1 ≤ n ≤ 100, 1 ≤ pos ≤ n, 1 ≤ l ≤ r ≤ n) — the number of the tabs, the cursor position and the segment which Luba needs to leave opened.

-----Output-----

Print one integer equal to the minimum number of seconds required to close all the tabs outside the segment [l, r].

-----Examples-----
Input
6 3 2 4

Output
5

Input
6 3 1 3

Output
1

Input
5 2 1 5

Output
0

-----Note-----

In the first test Luba can do the following operations: shift the mouse cursor to the tab 2, close all the tabs to the left of it, shift the mouse cursor to the tab 3, then to the tab 4, and then close all the tabs to the right of it.

In the second test she only needs to close all the tabs to the right of the current position of the cursor.

In the third test Luba doesn't need to do anything.

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

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

def main():
    n, pos, l, r = [int(_) for _ in input().split(' ')]
    if l is 1 and r == n:
        print(0)
        return
    if l is 1:
        print(abs(r - pos) + 1)
        return
    if r == n:
        print(abs(l - pos) + 1)
        return
    print(min(abs(l - pos), abs(r - pos)) + (r - l) + 2)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/915/C:
You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0.

It is allowed to leave a as it is.

-----Input-----

The first line contains integer a (1 ≤ a ≤ 10^18). The second line contains integer b (1 ≤ b ≤ 10^18). Numbers don't have leading zeroes. It is guaranteed that answer exists.

-----Output-----

Print the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can't have any leading zeroes. It is guaranteed that the answer exists.

The number in the output should have exactly the same length as number a. It should be a permutation of digits of a.

-----Examples-----
Input
123
222

Output
213

Input
3921
10000

Output
9321

Input
4940
5000

Output
4940

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

a = list(input())
b = int(input())
a.sort()
a = a[::-1]
prefix = ""
while(len(a) > 0):
	for i in range(len(a)):
		num = prefix + a[i] + "".join(sorted(a[:i] + a[i + 1:]))
		if (int(num) <= b):
			prefix += a[i]
			a = a[:i] + a[i+1:]
			break
print(prefix)


I found an interesting problem on https://codeforces.com/problemset/problem/915/D:
You are given a directed graph consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.

Can you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).

-----Input-----

The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.

Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).

-----Output-----

If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.

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

Output
YES

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

Output
NO

-----Note-----

In the first example you can remove edge $2 \rightarrow 3$, and the graph becomes acyclic.

In the second example you have to remove at least two edges (for example, $2 \rightarrow 1$ and $2 \rightarrow 3$) in order to make the graph acyclic.

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

have = False
cycle_begin, block_u, block_v = -1, -1, -1
g, mark, cycle = [], [], []

def dfs(u):
    nonlocal have, cycle_begin
    mark[u] = 1
    for v in g[u]:
        if u == block_u and v == block_v:
            continue
        if mark[v] == 0:
            if dfs(v):
                if have:
                    cycle.append(u)
                if u == cycle_begin:
                    have = False
                return True
        elif mark[v] == 1:
            have = True
            cycle_begin = v
            cycle.append(u)
            return True
    mark[u] = 2
    return False

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

g = [[] for _ in range(n)]
mark = [0 for _ in range(n)]

for _ in range(m):
    u, v = list(map(int, input().split()))
    u -= 1
    v -= 1
    g[u].append(v)

for i in range(n):
    if mark[i] == 0 and dfs(i):
        break

if cycle_begin == -1:
    print("YES")
else:
    cycle.append(cycle[0])
    for u in range(len(cycle) - 1, 0, -1):
        block_u = cycle[u]
        block_v = cycle[u - 1]
        mark = [0 for _ in range(n)]
        ok = True
        for u in range(n):
            if mark[u] == 0 and dfs(u):
                ok = False
                break
        if ok:
            print("YES")
            return

    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/916/A:
Jamie loves sleeping. One day, he decides that he needs to wake up at exactly hh: mm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh: mm is reached, and only then he will wake up. He wants to know what is the smallest number of times he needs to press the snooze button.

A time is considered lucky if it contains a digit '7'. For example, 13: 07 and 17: 27 are lucky, while 00: 48 and 21: 34 are not lucky.

Note that it is not necessary that the time set for the alarm and the wake-up time are on the same day. It is guaranteed that there is a lucky time Jamie can set so that he can wake at hh: mm.

Formally, find the smallest possible non-negative integer y such that the time representation of the time x·y minutes before hh: mm contains the digit '7'.

Jamie uses 24-hours clock, so after 23: 59 comes 00: 00.

-----Input-----

The first line contains a single integer x (1 ≤ x ≤ 60).

The second line contains two two-digit integers, hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).

-----Output-----

Print the minimum number of times he needs to press the button.

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

Output
2

Input
5
01 07

Output
0

-----Note-----

In the first sample, Jamie needs to wake up at 11:23. So, he can set his alarm at 11:17. He would press the snooze button when the alarm rings at 11:17 and at 11:20.

In the second sample, Jamie can set his alarm at exactly at 01:07 which is lucky.

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

def lucky(x):
    return (x % 10 == 7)
x = int(input())
h, m = list(map(int, input().split()))
t = 60 * h + m

ans = float('inf')
for hh in range(24):
    for mm in range(60):
        if lucky(hh) or lucky(mm):
            s = 60 * hh + mm
            while t < s:
                s -= 60 * 24

            r = t - s
            if r % x != 0:
                continue

            ans = min(ans,  r // x)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/916/B:
Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:

Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one.

To be more clear, consider all integer sequence with length k (a_1, a_2, ..., a_{k}) with $\sum_{i = 1}^{k} 2^{a_{i}} = n$. Give a value $y = \operatorname{max}_{1 \leq i \leq k} a_{i}$ to each sequence. Among all sequence(s) that have the minimum y value, output the one that is the lexicographically largest.

For definitions of powers and lexicographical order see notes.

-----Input-----

The first line consists of two integers n and k (1 ≤ n ≤ 10^18, 1 ≤ k ≤ 10^5) — the required sum and the length of the sequence.

-----Output-----

Output "No" (without quotes) in a single line if there does not exist such sequence. Otherwise, output "Yes" (without quotes) in the first line, and k numbers separated by space in the second line — the required sequence.

It is guaranteed that the integers in the answer sequence fit the range [ - 10^18, 10^18].

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

Output
Yes
3 3 2 1 0

Input
13 2

Output
No

Input
1 2

Output
Yes
-1 -1

-----Note-----

Sample 1:

2^3 + 2^3 + 2^2 + 2^1 + 2^0 = 8 + 8 + 4 + 2 + 1 = 23

Answers like (3, 3, 2, 0, 1) or (0, 1, 2, 3, 3) are not lexicographically largest.

Answers like (4, 1, 1, 1, 0) do not have the minimum y value.

Sample 2:

It can be shown there does not exist a sequence with length 2.

Sample 3:

$2^{-1} + 2^{-1} = \frac{1}{2} + \frac{1}{2} = 1$

Powers of 2:

If x > 0, then 2^{x} = 2·2·2·...·2 (x times).

If x = 0, then 2^{x} = 1.

If x < 0, then $2^{x} = \frac{1}{2^{-x}}$.

Lexicographical order:

Given two different sequences of the same length, (a_1, a_2, ... , a_{k}) and (b_1, b_2, ... , b_{k}), the first one is smaller than the second...

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

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

s = list()
b = list()
base = 0
while n > 0:
    s.append(n%2)
    b.append(base)
    n //= 2
    base += 1
s.reverse() # indicate existence
b.reverse() # indicate which power of 2
# print(s)
# print(b)

t = sum(s)
if t > k:
    print('No')
    return

pos = 0
while t < k:
    if pos+1 == len(s): # extend if necessary
        s.append(0)
        b.append(b[-1] - 1)

    if t + s[pos] <= k:
        t += s[pos]
        s[pos+1] += 2 * s[pos]
        s[pos] = 0
        pos += 1
    else:
        for i in range(len(s)-1, -1, -1):
            if s[i] > 0:
                while t < k:
                    if i+1 == len(s):
                        s.append(0)
                        b.append(b[-1] - 1)
                    s[i] -= 1
                    s[i+1] += 2
                    t += 1
                    i += 1
                break

res = list() # comply with answer form
for i in range(len(s)):
    for j in range(s[i]):
        res.append(b[i])
print('Yes')
print(' '.join(map(str, res)))


I found an interesting problem on https://codeforces.com/problemset/problem/918/A:
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters.  [Image]

Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the i-th letter of her name should be 'O' (uppercase) if i is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to n. Fibonacci sequence is the sequence f where  f_1 = 1,  f_2 = 1,  f_{n} = f_{n} - 2 + f_{n} - 1 (n > 2).

As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.

-----Input-----

The first and only line of input contains an integer n (1 ≤ n ≤ 1000).

-----Output-----

Print Eleven's new name on the first and only line of output.

-----Examples-----
Input
8

Output
OOOoOooO

Input
15

Output
OOOoOooOooooOoo

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

N = int(input())
fib = [0, 1]
while fib[-1] < 1000:
	fib.append(fib[-1] + fib[-2])
for i in range(1, N + 1):
	print("O" if i in fib else "o", end="")
print()


I found an interesting problem on https://codeforces.com/problemset/problem/918/B:
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers.

 [Image]

Each ip is of form "a.b.c.d" where a, b, c and d are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has m commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip.

Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.

-----Input-----

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

The next n lines contain the names and ips of the servers. Each line contains a string name, name of the server and a string ip, ip of the server, separated by space (1 ≤ |name| ≤ 10, name only consists of English lowercase letters). It is guaranteed that all ip are distinct.

The next m lines contain the commands in the configuration file. Each line is of form "command ip;" (1 ≤ |command| ≤ 10, command only consists of English lowercase letters). It is guaranteed that ip belongs to one of the n school servers.

-----Output-----

Print m lines, the commands in the configuration file after Dustin did his task.

-----Examples-----
Input
2 2
main 192.168.0.2
replica 192.168.0.1
block 192.168.0.1;
proxy 192.168.0.2;

Output
block 192.168.0.1;...

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

n, m = [int(i) for i in input().split()]
d = dict()
for i in range(n):
	a, b = [i.rstrip() for i in input().split()]
	d[b] = a
#print(d)
for i in range(m):
	a, b = [i.rstrip() for i in input().split()]
	b = b[:-1]
	print(a, " ", b, "; #", d[b], sep="")


I found an interesting problem on https://codeforces.com/problemset/problem/919/A:
We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $a$ yuan for $b$ kilos (You don't need to care about what "yuan" is), the same as $a/b$ yuan for a kilo.

Now imagine you'd like to buy $m$ kilos of apples. You've asked $n$ supermarkets and got the prices. Find the minimum cost for those apples.

You can assume that there are enough apples in all supermarkets.

-----Input-----

The first line contains two positive integers $n$ and $m$ ($1 \leq n \leq 5\,000$, $1 \leq m \leq 100$), denoting that there are $n$ supermarkets and you want to buy $m$ kilos of apples.

The following $n$ lines describe the information of the supermarkets. Each line contains two positive integers $a, b$ ($1 \leq a, b \leq 100$), denoting that in this supermarket, you are supposed to pay $a$ yuan for $b$ kilos of apples.

-----Output-----

The only line, denoting the minimum cost for $m$ kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed $10^{-6}$.

Formally, let your answer be $x$, and the jury's answer be $y$. Your answer is considered correct if $\frac{|x - y|}{\max{(1, |y|)}} \le 10^{-6}$.

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

Output
1.66666667

Input
2 1
99 100
98 99

Output
0.98989899

-----Note-----

In the first sample, you are supposed to buy $5$ kilos of apples in supermarket $3$. The cost is $5/3$ yuan.

In the second sample, you are supposed to buy $1$ kilo of apples in supermarket $2$. The cost is $98/99$ yuan.

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

n, m = [int(i) for i in input().split()]
ans = 10 ** 9
for i in range(n):
    a1, a2 = [int(i) for i in input().split()]
    ans = min(ans, a1 * m / a2)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/919/B:
We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer.

-----Input-----

A single line with a positive integer $k$ ($1 \leq k \leq 10\,000$).

-----Output-----

A single number, denoting the $k$-th smallest perfect integer.

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

Output
19

Input
2

Output
28

-----Note-----

The first perfect integer is $19$ and the second one is $28$.

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

import sys

#f = open('input', 'r')
f = sys.stdin

d = [[0] * 11 for _ in range(11)]

d[0][0] = 1
for i in range(10):
  for j in range(11):
    for k in range(10):
      if j+k <= 10:
        d[i+1][j+k] += d[i][j]

target = int(f.readline())
tt=target
target -= 1
val = 10
ans = ''
for i in range(10):
  ii=9-i
  for j in range(val+1):
    if j==10:
      continue
    jj=val-j
    if d[ii][jj] <= target:
      target -= d[ii][jj]
    else:
      val = jj
      ans += str(j)
      break
print(int(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/919/C:
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.

The classroom contains $n$ rows of seats and there are $m$ seats in each row. Then the classroom can be represented as an $n \times m$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $k$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.

-----Input-----

The first line contains three positive integers $n,m,k$ ($1 \leq n, m, k \leq 2\,000$), where $n,m$ represent the sizes of the classroom and $k$ is the number of consecutive seats you need to find.

Each of the next $n$ lines contains $m$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.

-----Output-----

A single number, denoting the number of ways to find $k$ empty seats in the same row or column.

-----Examples-----
Input
2 3 2
**.
...

Output
3

Input
1 2 2
..

Output
1

Input
3 3 4
.*.
*.*
.*.

Output
0

-----Note-----

In the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement.   $(1,3)$, $(2,3)$  $(2,2)$, $(2,3)$  $(2,1)$, $(2,2)$

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

n, m, k = list(map(int, input().split()))
s = []
up = [[0] * m] * n
left =[[0] * m] * n
ans = 0
for i in range(n):
    s.append(input())
    for j in range(m):
        if s[i][j] == '.':
            up[i][j] = (0 if i == 0 else up[i - 1][j]) + 1
            left[i][j] = (0 if j == 0 else left[i][j - 1]) + 1
        else:
            up[i][j] = 0
            left[i][j] = 0
        ans += up[i][j] >= k
        ans += left[i][j] >= k
if k == 1:
    ans //= 2
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/919/D:
You are given a graph with $n$ nodes and $m$ directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is $3$. Your task is find a path whose value is the largest.

-----Input-----

The first line contains two positive integers $n, m$ ($1 \leq n, m \leq 300\,000$), denoting that the graph has $n$ nodes and $m$ directed edges.

The second line contains a string $s$ with only lowercase English letters. The $i$-th character is the letter assigned to the $i$-th node.

Then $m$ lines follow. Each line contains two integers $x, y$ ($1 \leq x, y \leq n$), describing a directed edge from $x$ to $y$. Note that $x$ can be equal to $y$ and there can be multiple edges between $x$ and $y$. Also the graph can be not connected.

-----Output-----

Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.

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

Output
3

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

Output
-1

Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7

Output
4

-----Note-----

In the first sample, the path with largest value is $1 \to 3 \to 4 \to 5$. The value is $3$ because the letter 'a' appears $3$ times.

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

# NOT MY CODE
# https://codeforces.com/contest/919/submission/80857731

from types import GeneratorType

def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        to = f(*args, **kwargs)
        if stack:
            return to
        else:
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        return to
                    to = stack[-1].send(to)
    return wrappedfunc

import sys
input=sys.stdin.readline
from collections import defaultdict as dd
'''
def iscyclic(g):
    for i in range(1,n+1):
        if(
'''
n,m=list(map(int,input().split()))
s=input()
d=dd(list)
lol=0
for i in range(m):
    u,v=list(map(int,input().split()))
    if(u==v):
        lol=1
        print(-1)
        return
    d[u].append(v)
'''
if(iscyclic(d)):
    lol=1
    print(-1)
    return
'''
vis=[0]*(n+1)
rvis=[0]*(n+1)
cou=[0]
dp=[dd(int) for i in range(n+1)]
mx=[0]
h=[0]
#print(d)
@bootstrap
def dfs(u):
    if(h[0]==1):
        yield
    vis[u]=1
    rvis[u]=1
    for i in d[u]:
        if(h[0]==1):
            yield
        if(vis[i]==0):
            yield dfs(i)
            if(h[0]==1):
                yield
        elif(rvis[i]==True):
            h[0]=1
            yield
    rvis[u]=0
    if(h[0]==1):
        yield
    for i in d[u]:
        for j in dp[i]:
            dp[u][j]=max(dp[u][j],dp[i][j])
            mx[0]=max(mx[0],dp[u][j])
    dp[u][s[u-1]]+=1
    #print(u,dp[u])
    mx[0]=max(mx[0],dp[u][s[u-1]])
    yield
#print(dp)
for i in range(1,n+1):
    if(vis[i]==0):
        cou=[0]
        dfs(i)
if(h[0]):
    print(-1)
else:
    print(mx[0])


I found an interesting problem on https://codeforces.com/problemset/problem/919/E:
Given an integer $x$. Your task is to find out how many positive integers $n$ ($1 \leq n \leq x$) satisfy $$n \cdot a^n \equiv b \quad (\textrm{mod}\;p),$$ where $a, b, p$ are all known constants.

-----Input-----

The only line contains four integers $a,b,p,x$ ($2 \leq p \leq 10^6+3$, $1 \leq a,b < p$, $1 \leq x \leq 10^{12}$). It is guaranteed that $p$ is a prime.

-----Output-----

Print a single integer: the number of possible answers $n$.

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

Output
2

Input
4 6 7 13

Output
1

Input
233 233 10007 1

Output
1

-----Note-----

In the first sample, we can see that $n=2$ and $n=8$ are possible answers.

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

import sys

def calc(a, b, p, x):
    ans = 0
    power = pow(a, p - 2, p)
    a2, b2, s, d1 = 1, b, 0, -b
    prod = p * (p - 1)
    while s < p - 1:
        k = (d1 + s) % p
        L = x - s - (p - 1) * k
        ans += L // prod + 1
        d1 = (d1 * power) % p
        s += 1
    return str(ans)

a, b, p, x = list(map(int,sys.stdin.readline().split()))
sys.stdout.write(calc(a, b, p, x))


I found an interesting problem on https://codeforces.com/problemset/problem/920/A:
It is winter now, and Max decided it's about time he watered the garden.

The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed x_{i}), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed x_{i} is turned on, then after one second has passed, the bed x_{i} will be watered; after two seconds have passed, the beds from the segment [x_{i} - 1, x_{i} + 1] will be watered (if they exist); after j seconds have passed (j is an integer number), the beds from the segment [x_{i} - (j - 1), x_{i} + (j - 1)] will be watered (if they exist). Nothing changes during the seconds, so, for example, we can't say that the segment [x_{i} - 2.5, x_{i} + 2.5] will be watered after 2.5 seconds have passed; only the segment [x_{i} - 2, x_{i} + 2] will be watered at that moment.

 $\left. \begin{array}{|c|c|c|c|c|} \hline 1 & {2} & {3} & {4} & {5} \\ \hline \end{array} \right.$ The garden from test 1. White colour denotes a garden bed without a tap, red colour — a garden bed with a tap.

 $\left. \begin{array}{|c|c|c|c|c|} \hline 1 & {2} & {3} & {4} & {5} \\ \hline \end{array} \right.$ The garden from test 1 after 2 seconds have passed after turning on the tap. White colour denotes an unwatered garden bed, blue colour — a watered bed.

Max wants to turn on all the water taps at the same moment, and now he wonders, what is the minimum number of seconds that have to pass after he turns on some taps until the whole garden is watered. Help him to find the answer!

-----Input-----

The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 200).

Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ n ≤ 200, 1 ≤ k ≤ n) — the number of garden beds and water taps, respectively.

Next line contains k integers x_{i} (1 ≤ x_{i} ≤ n) — the location of i-th water tap. It is guaranteed that for each $i \in [ 2 ; k ]$ condition x_{i} - 1 < x_{i} holds.

It is...

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

import getpass
import sys
import math

def ria():
    return [int(i) for i in input().split()]

files = True

if getpass.getuser() == 'frohenk' and files:
    sys.stdin = open("test.in")

t = ria()[0]
for kekas in range(t):
    n, k = ria()
    ar = ria()
    maxi = max(ar[0], n - ar[len(ar) - 1] + 1)
    for j in range(1, k):
        maxi = max(maxi, 1 + math.floor((ar[j] - ar[j - 1]) / 2))
    print(maxi)


I found an interesting problem on https://codeforces.com/problemset/problem/920/B:
Recently n students from city S moved to city P to attend a programming camp.

They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.

i-th student comes to the end of the queue at the beginning of l_{i}-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of r_{i}-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea.

For each student determine the second he will use the teapot and get his tea (if he actually gets it).

-----Input-----

The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 1000).

Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 1000) — the number of students.

Then n lines follow. Each line contains two integer l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 5000) — the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea.

It is guaranteed that for every $i \in [ 2 ; n ]$ condition l_{i} - 1 ≤ l_{i} holds.

The sum of n over all test cases doesn't exceed 1000.

Note that in hacks you have to set t = 1.

-----Output-----

For each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.

-----Example-----
Input
2
2
1 3
1 4
3
1 5
1 1
2 3

Output
1 2
1 0 2

-----Note-----

The example contains 2 tests:

  During 1-st second, students 1 and 2 come to the queue, and...

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

from collections import deque
def solve(ar):
    res = []
    time = 0
    for l, r in ar:
        if r >= time:
            if time == 0:
                time = l + 1
                res.append(l)
            else:
                if l >= time: time = l
                res.append(time)
                time += 1
        else:
            res.append(0)
    return res

t = int(input())
for _ in range(t):
    n = int(input())
    a = []
    for i in range(n):
        a.append(deque(int(x) for x in input().split()))
    print(*solve(a))


I found an interesting problem on https://codeforces.com/problemset/problem/920/C:
You have an array a consisting of n integers. Each integer from 1 to n appears exactly once in this array.

For some indices i (1 ≤ i ≤ n - 1) it is possible to swap i-th element with (i + 1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the number of times you swap i-th element with (i + 1)-th (if the position is not forbidden).

Can you make this array sorted in ascending order performing some sequence of swapping operations?

-----Input-----

The first line contains one integer n (2 ≤ n ≤ 200000) — the number of elements in the array.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 200000) — the elements of the array. Each integer from 1 to n appears exactly once.

The third line contains a string of n - 1 characters, each character is either 0 or 1. If i-th character is 1, then you can swap i-th element with (i + 1)-th any number of times, otherwise it is forbidden to swap i-th element with (i + 1)-th.

-----Output-----

If it is possible to sort the array in ascending order using any sequence of swaps you are allowed to make, print YES. Otherwise, print NO.

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

Output
YES

Input
6
1 2 5 3 4 6
01010

Output
NO

-----Note-----

In the first example you may swap a_3 and a_4, and then swap a_4 and a_5.

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

def can_order(arr, ok):
    i = 0
    while i < len(ok):
        if not ok[i]:
            if i + 1 != arr[i + 1] and (i + 1 >= len(ok) or not ok[i + 1]):
                #print("Not okay and index", i, "==", arr[i])
                return False
            i += 1
        else:
            j = i
            while j < len(ok) and ok[j]:
                j += 1
            if sum(arr[i:j + 1]) != sum(range(i, j + 1)):
                #print(arr[i:j + 1])
                #print("arr[", i, ":", j + 1, "] ==", sum(arr[i:j + 1]))
                #print("sum(range(i, j)) ==", sum(range(i, j + 1)))
                return False
            i = j
    return True

def main():
    N = int(input())
    arr = [int(x) - 1 for x in input().split()]
    ok = [c == '1' for c in input()]
    print("YES" if can_order(arr, ok) else "NO")

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/920/E:
You are given an undirected graph consisting of n vertices and $\frac{n(n - 1)}{2} - m$ edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices.

You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 200000, $0 \leq m \leq \operatorname{min}(\frac{n(n - 1)}{2}, 200000)$).

Then m lines follow, each containing a pair of integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices.

-----Output-----

Firstly print k — the number of connected components in this graph.

Then print k integers — the sizes of components. You should output these integers in non-descending order.

-----Example-----
Input
5 5
1 2
3 4
3 2
4 2
2 5

Output
2
1 4

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

n,m = list(map(int,input().split()))
ae = [[] for _ in range(n)]
for _ in range(m):
    a,b = list(map(int,input().split()))
    ae[a-1].append(b-1)
    ae[b-1].append(a-1)
mn = -1
nbr = n
for i in range(n):
    if len(ae[i])<nbr:
        mn = i
        nbr = len(ae[i])
keep = ae[mn]
ok = n-len(keep)
while True:
    toDel = -1
    for i in keep:
        aeo = len(ae[i])
        for j in ae[i]:
            if j in keep:
                aeo -= 1
                if aeo<ok: break
        if aeo<ok:
            toDel = i
            break
    if toDel == -1:
        break
    else:
        keep.remove(i)
        ok += 1
out = [ok]
d = {}

if len(keep) == 1: out.append(1)
elif len(keep) == 0: out = out
else:
    keep.sort()
    for i in range(len(keep)):
        d[keep[i]] = i

    edg = [[] for _ in range(len(keep))]
    for i in range(len(keep)):
        for j in range(len(keep)):
            if i == j: continue
            edg[i].append(j)
            edg[j].append(i)

    for i in keep:
        for j in ae[i]:
            if j in keep:
                if d[j] in edg[d[i]]: edg[d[i]].remove(d[j])
                if d[i] in edg[d[j]]: edg[d[j]].remove(d[i])
    used = [False]*len(keep)
    uss = 0
    while uss<len(keep):
        fi = -1
        for i in range(len(keep)):
            if not used[i]:
                fi = i
                break
        bfs = [fi]
        used[fi] = True
        usn = 1
        uss += 1
        while len(bfs) > 0:
            temp = bfs.pop()
            for i in edg[temp]:
                if not used[i]:
                    used[i] = True
                    bfs.append(i)
                    uss += 1
                    usn += 1
        out.append(usn)

out.sort()
print(len(out))
print(' '.join(map(str,out)))


I found an interesting problem on https://codeforces.com/problemset/problem/920/G:
Let's denote as L(x, p) an infinite sequence of integers y such that gcd(p, y) = 1 and y > x (where gcd is the greatest common divisor of two integer numbers), sorted in ascending order. The elements of L(x, p) are 1-indexed; for example, 9, 13 and 15 are the first, the second and the third elements of L(7, 22), respectively.

You have to process t queries. Each query is denoted by three integers x, p and k, and the answer to this query is k-th element of L(x, p).

-----Input-----

The first line contains one integer t (1 ≤ t ≤ 30000) — the number of queries to process.

Then t lines follow. i-th line contains three integers x, p and k for i-th query (1 ≤ x, p, k ≤ 10^6).

-----Output-----

Print t integers, where i-th integer is the answer to i-th query.

-----Examples-----
Input
3
7 22 1
7 22 2
7 22 3

Output
9
13
15

Input
5
42 42 42
43 43 43
44 44 44
45 45 45
46 46 46

Output
187
87
139
128
141

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

prime_factors = [[] for _ in range(10**6 + 1)]
primes=[True for i in range(10**6+1)]
def generate_primes(n):

    for p in range(2,n+1):
        if primes[p]:
            prime_factors[p].append(p)
            for i in range(2 * p,n+1,p):
                primes[i] = False
                prime_factors[i].append(p)
generate_primes(10**6)
result = []
for _ in range(int(input())):
    x, p, k = map(int, input().split())
    arr = prime_factors[p]
    to_add = []
    to_subtract = []
    for i in range(1, 1 << len(arr)):
        mul = 1
        count = 0
        for j in range(len(arr)):
            if (1 << j) & i:
                count += 1
                mul *= arr[j]

        if count%2:
            to_add.append(mul)
        else:
            to_subtract.append(mul)
    count_before = 0
    for num in to_add:
        count_before += x//num

    for num in to_subtract:
        count_before -= x//num

    k += (x - count_before)

    low = 0
    high = 10**9
    answer = high
    while low <= high:
        mid = (high + low)//2
        temp_count = 0
        for num in to_add:
            temp_count += mid // num
        for num in to_subtract:
            temp_count -= mid // num
        temp_count = mid - temp_count
        if temp_count >= k:
            answer = min(answer, mid)
            high = mid - 1
        else:
            low = mid + 1
    result.append(answer)

print(*result, sep = "\n")


I found an interesting problem on https://codeforces.com/problemset/problem/922/A:
Imp likes his plush toy a lot.

 [Image]

Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.

Initially, Imp has only one original toy. He wants to know if it is possible to use machine to get exactly x copied toys and y original toys? He can't throw toys away, and he can't apply the machine to a copy if he doesn't currently have any copies.

-----Input-----

The only line contains two integers x and y (0 ≤ x, y ≤ 10^9) — the number of copies and the number of original toys Imp wants to get (including the initial one).

-----Output-----

Print "Yes", if the desired configuration is possible, and "No" otherwise.

You can print each letter in arbitrary case (upper or lower).

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

Output
Yes

Input
4 2

Output
No

Input
1000 1001

Output
Yes

-----Note-----

In the first example, Imp has to apply the machine twice to original toys and then twice to copies.

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

x, y = list(map(int, input().split()))
if y == 0:
    print("No")
elif y == 1 and x > 0:
    print("No")
elif y > x + 1:
    print("No")
elif (x - y) % 2 == 0:
    print('No')
else:
    print('Yes')


I found an interesting problem on https://codeforces.com/problemset/problem/922/B:
Imp is in a magic forest, where xorangles grow (wut?)

 [Image]

A xorangle of order n is such a non-degenerate triangle, that lengths of its sides are integers not exceeding n, and the xor-sum of the lengths is equal to zero. Imp has to count the number of distinct xorangles of order n to get out of the forest.

Formally, for a given integer n you have to find the number of such triples (a, b, c), that:

  1 ≤ a ≤ b ≤ c ≤ n;  $a \oplus b \oplus c = 0$, where $x \oplus y$ denotes the bitwise xor of integers x and y.  (a, b, c) form a non-degenerate (with strictly positive area) triangle.

-----Input-----

The only line contains a single integer n (1 ≤ n ≤ 2500).

-----Output-----

Print the number of xorangles of order n.

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

Output
1

Input
10

Output
2

-----Note-----

The only xorangle in the first sample is (3, 5, 6).

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

n = int(input())
counter = 0
for c in range(1, n + 1):
    for b in range(1, c + 1):
        if b >= c ^ b > c - b:
            counter += 1

print(counter)


I found an interesting problem on https://codeforces.com/problemset/problem/922/C:
Imp is watching a documentary about cave painting. [Image]

Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number n by all integers i from 1 to k. Unfortunately, there are too many integers to analyze for Imp.

Imp wants you to check whether all these remainders are distinct. Formally, he wants to check, if all $n \text{mod} i$, 1 ≤ i ≤ k, are distinct, i. e. there is no such pair (i, j) that:   1 ≤ i < j ≤ k,  $n \operatorname{mod} i = n \operatorname{mod} j$, where $x \operatorname{mod} y$ is the remainder of division x by y.

-----Input-----

The only line contains two integers n, k (1 ≤ n, k ≤ 10^18).

-----Output-----

Print "Yes", if all the remainders are distinct, and "No" otherwise.

You can print each letter in arbitrary case (lower or upper).

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

Output
No

Input
5 3

Output
Yes

-----Note-----

In the first sample remainders modulo 1 and 4 coincide.

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

n, k = list(map(int, input().split()))
c = 1
z = 1
ok = 1

for i in range(1, k + 1):
    c = z
    while z % i != 0:
        z += c
    if z > n + 10:
        ok = 0
        break
if (n + 1) % z == 0 and ok:
    print('Yes')
else:
    print('No')