I found an interesting problem on https://codeforces.com/problemset/problem/816/B:
To stay woke and attentive during classes, Karen needs some coffee! [Image]

Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".

She knows n coffee recipes. The i-th recipe suggests that coffee should be brewed between l_{i} and r_{i} degrees, inclusive, to achieve the optimal taste.

Karen thinks that a temperature is admissible if at least k recipes recommend it.

Karen has a rather fickle mind, and so she asks q questions. In each question, given that she only wants to prepare coffee with a temperature between a and b, inclusive, can you tell her how many admissible integer temperatures fall within the range?

-----Input-----

The first line of input contains three integers, n, k (1 ≤ k ≤ n ≤ 200000), and q (1 ≤ q ≤ 200000), the number of recipes, the minimum number of recipes a certain temperature must be recommended by to be admissible, and the number of questions Karen has, respectively.

The next n lines describe the recipes. Specifically, the i-th line among these contains two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 200000), describing that the i-th recipe suggests that the coffee be brewed between l_{i} and r_{i} degrees, inclusive.

The next q lines describe the questions. Each of these lines contains a and b, (1 ≤ a ≤ b ≤ 200000), describing that she wants to know the number of admissible integer temperatures between a and b degrees, inclusive.

-----Output-----

For each question, output a single integer on a line by itself, the number of admissible integer temperatures between a and b degrees, inclusive.

-----Examples-----
Input
3 2 4
91 94
92 97
97 99
92 94
93 97
95 96
90 100

Output
3
3
0
4

Input
2 1 1
1 1
200000 200000
90 100

Output
0

-----Note-----

In the first test case, Karen knows 3 recipes.  The first one recommends brewing the coffee between 91 and 94 degrees, inclusive.  The second one...

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

n,k,q = list(map(int,input().split()))
from itertools import accumulate
count = [0 for _ in range(200002)]

for _ in range(n):
    l,r = list(map(int,input().split()))
    count[l] += 1
    count[r+1] -= 1

ok = 0
count2 = [0 for _ in range(200002)]
for i,v in enumerate(count):
    ok += v
    if ok >= k:
        count2[i] = 1
    else:
        count2[i] = 0
prefixe = list(accumulate(count2))
res = []
for _ in range(q):
    l,r = list(map(int,input().split()))
    res.append(str(prefixe[r]-prefixe[l-1]))
print('\n'.join(res))


I found an interesting problem on https://codeforces.com/problemset/problem/817/A:
Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure.

Bottle with potion has two values x and y written on it. These values define four moves which can be performed using the potion:

  $(a, b) \rightarrow(a + x, b + y)$  $(a, b) \rightarrow(a + x, b - y)$  $(a, b) \rightarrow(a - x, b + y)$  $(a, b) \rightarrow(a - x, b - y)$

Map shows that the position of Captain Bill the Hummingbird is (x_1, y_1) and the position of the treasure is (x_2, y_2).

You task is to tell Captain Bill the Hummingbird whether he should accept this challenge or decline. If it is possible for Captain to reach the treasure using the potion then output "YES", otherwise "NO" (without quotes).

The potion can be used infinite amount of times.

-----Input-----

The first line contains four integer numbers x_1, y_1, x_2, y_2 ( - 10^5 ≤ x_1, y_1, x_2, y_2 ≤ 10^5) — positions of Captain Bill the Hummingbird and treasure respectively.

The second line contains two integer numbers x, y (1 ≤ x, y ≤ 10^5) — values on the potion bottle.

-----Output-----

Print "YES" if it is possible for Captain to reach the treasure using the potion, otherwise print "NO" (without quotes).

-----Examples-----
Input
0 0 0 6
2 3

Output
YES

Input
1 1 3 6
1 5

Output
NO

-----Note-----

In the first example there exists such sequence of moves:

  $(0,0) \rightarrow(2,3)$ — the first type of move  $(2,3) \rightarrow(0,6)$ — the third type of move

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

x1, y1, x2, y2 = map(int, input().split())
x, y = map(int, input().split())

deltaX = abs(x2-x1)
deltaY = abs(y2-y1)

# if (deltaY // y) == (deltaX // x):
# 	print("YES")
# elif (deltaY // x) == (deltaX // y):
# 	print("YES")
# elif (deltaX % x == 0) and (deltaY == 0):
# 	print("YES")
# elif (deltaY % y == 0) and (deltaX == 0):
# 	print("YES")
# elif deltaX == deltaY == 0:
# 	print("YES")
# else:
# 	print("NO")

if ((y2-y1)%(2*y) == 0) and ((x2-x1)%(2*x) == 0):
	print("YES")
elif ((x2-x-x1)%(2*x) == 0) and ((y2-y-y1)%(2*y) == 0):
	print("YES")
else:
	print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/817/B:
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i,  j,  k) (i < j < k), such that a_{i}·a_{j}·a_{k} is minimum possible, are there in the array? Help him with it!

-----Input-----

The first line of input contains a positive integer number n (3 ≤ n ≤ 10^5) — the number of elements in array a. The second line contains n positive integer numbers a_{i} (1 ≤ a_{i} ≤ 10^9) — the elements of a given array.

-----Output-----

Print one number — the quantity of triples (i,  j,  k) such that i,  j and k are pairwise distinct and a_{i}·a_{j}·a_{k} is minimum possible.

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

Output
4

Input
5
1 3 2 3 4

Output
2

Input
6
1 3 3 1 3 2

Output
1

-----Note-----

In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.

In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.

In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.

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

from collections import Counter
n = int(input())
a = list(map(int,input().split()))
a.sort()
b = list(set(a))
b.sort()
c = Counter(a)
if c[b[0]] >= 3:
    k = c[b[0]]
    print(int(k*(k-1)*(k-2)/6))
else:
    k = c[b[0]]
    if len(b) == 1:
        j = 0
    else:
        j = c[b[1]]
    if k == 2:
        print(j)
    elif k == 1:
        if j >= 3:
            print(int(j*(j-1)/2))
        elif j == 2:
            print(1)
        else:
            if len(b) <= 2:
                print(0)
            else:
                print(c[b[2]])


I found an interesting problem on https://codeforces.com/problemset/problem/817/C:
Ivan likes to learn different things about numbers, but he is especially interested in really big numbers. Ivan thinks that a positive integer number x is really big if the difference between x and the sum of its digits (in decimal representation) is not less than s. To prove that these numbers may have different special properties, he wants to know how rare (or not rare) they are — in fact, he needs to calculate the quantity of really big numbers that are not greater than n.

Ivan tried to do the calculations himself, but soon realized that it's too difficult for him. So he asked you to help him in calculations.

-----Input-----

The first (and the only) line contains two integers n and s (1 ≤ n, s ≤ 10^18).

-----Output-----

Print one integer — the quantity of really big numbers that are not greater than n.

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

Output
3

Input
25 20

Output
0

Input
10 9

Output
1

-----Note-----

In the first example numbers 10, 11 and 12 are really big.

In the second example there are no really big numbers that are not greater than 25 (in fact, the first really big number is 30: 30 - 3 ≥ 20).

In the third example 10 is the only really big number (10 - 1 ≥ 9).

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

# def sum_digits(n):
#     s = 0
#     while n:
#         s += n % 10
#         n //= 10
#     return s

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

# count = 0
# summ = sum_digits(n)
# # k = sum_digits(n - n%10 - 1)
# # print(k)
# for num in range(n, 9, -1):
# 	if num % 10 == 9:
# 		summ = sum_digits(num)
# 	# print(num, summ)
# 	if num - summ  >= s:
# 		count += 1
# 	summ -= 1

# print(count)

def sum_digits(n):
    s = 0
    while n:
        s += n % 10
        n //= 10
    return s

def binsearch(l, r, elem):
	n = r
	medium = (l + r ) // 2
	s = medium - sum_digits(medium)
	s1 = medium-1- sum_digits(medium-1)
	s2 = medium+1 - sum_digits(medium+1)
	# print(s,s2)
	while not(s2 >= elem and s < elem): #s >= elem and s1 < elem or
		# print(l,medium,r)
		if s < elem:
			l = medium
		elif s >= elem:
			r = medium
		k = medium
		medium = (l + r ) // 2
		if k == medium:
			break
		# print(l,medium,r)
		s = medium - sum_digits(medium)
		s2 = medium+1 - sum_digits(medium+1)
		# print(s,s2)

	s1 = medium-1 - sum_digits(medium-1)
	if s >= elem and s1 < elem:
		return medium
	elif s2 >= elem and s < elem:
		return medium + 1
	else:
		return 	n+1

n, s = list(map(int, input().split()))
# a = [i for i in range(n+1)]
if n == s:
	print(0)
else:

	y = binsearch( 0, n, s)
# print(y)
	print(n - y + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/817/D:
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.

For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array:   [1] (from index 1 to index 1), imbalance value is 0;  [1, 4] (from index 1 to index 2), imbalance value is 3;  [1, 4, 1] (from index 1 to index 3), imbalance value is 3;  [4] (from index 2 to index 2), imbalance value is 0;  [4, 1] (from index 2 to index 3), imbalance value is 3;  [1] (from index 3 to index 3), imbalance value is 0;

You have to determine the imbalance value of the array a.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 10^6) — size of the array a.

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

-----Output-----

Print one integer — the imbalance value of a.

-----Example-----
Input
3
1 4 1

Output
9

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

n = int(input())
a = list(map(int,input().split()))
left = [None for _ in range(n)]
right = [None for _ in range(n)]
left1 = [None for _ in range(n)]
right1 = [None for _ in range(n)]
class Stack(object):
    def __init__(self):
        self.c = []
    def push(self,new):
        self.c.append(new)
    def pop(self):
        return self.c.pop(-1)
    def vide(self):
        return self.c == []
    def peek(self):
        return self.c[-1]
def calculleft():
    s = Stack()
    for i in range(n):
        while not s.vide() and a[s.peek()] > a[i]:
            s.pop()
        if not s.vide():
            left[i] = s.peek()
        else:
            left[i] = -1
        s.push(i)

def calculright():
    s = Stack()
    for i in range(n-1,-1,-1):
        while not s.vide() and a[s.peek()] >= a[i]:
            s.pop()
        if not s.vide():
            right[i] = s.peek()
        else:
            right[i] = n
        s.push(i)

def calculleft1():
    s = Stack()
    for i in range(n):
        while not s.vide() and a[s.peek()] < a[i]:
            s.pop()
        if not s.vide():
            left1[i] = s.peek()
        else:
            left1[i] = -1
        s.push(i)

def calculright1():
    s = Stack()
    for i in range(n-1,-1,-1):
        while not s.vide() and a[s.peek()] <= a[i]:
            s.pop()
        if not s.vide():
            right1[i] = s.peek()
        else:
            right1[i] = n
        s.push(i)

res = 0
calculleft()
calculright()
calculleft1()
calculright1()

res2 = 0
for i in range(n):
    res += (i-left[i])*(right[i]-i)*a[i]
    res2 += (i-left1[i])*(right1[i]-i)*a[i]
print(res2-res)


I found an interesting problem on https://codeforces.com/problemset/problem/818/A:
There are n students who have taken part in an olympiad. Now it's time to award the students.

Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and certificates. The number of certificates must be exactly k times greater than the number of diplomas. The number of winners must not be greater than half of the number of all students (i.e. not be greater than half of n). It's possible that there are no winners.

You have to identify the maximum possible number of winners, according to these rules. Also for this case you have to calculate the number of students with diplomas, the number of students with certificates and the number of students who are not winners.

-----Input-----

The first (and the only) line of input contains two integers n and k (1 ≤ n, k ≤ 10^12), where n is the number of students and k is the ratio between the number of certificates and the number of diplomas.

-----Output-----

Output three numbers: the number of students with diplomas, the number of students with certificates and the number of students who are not winners in case when the number of winners is maximum possible.

It's possible that there are no winners.

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

Output
3 6 9

Input
9 10

Output
0 0 9

Input
1000000000000 5

Output
83333333333 416666666665 500000000002

Input
1000000000000 499999999999

Output
1 499999999999 500000000000

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

read = lambda: map(int, input().split())
n, k = read()
p = n // 2 // (k + 1)
print(p, p * k, n - p * (k + 1))


I found an interesting problem on https://codeforces.com/problemset/problem/818/B:
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a_1, a_2, ..., a_{n} of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.

The game consists of m steps. On each step the current leader with index i counts out a_{i} people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.

You are given numbers l_1, l_2, ..., l_{m} — indices of leaders in the beginning of each step. Child with number l_1 is the first leader in the game.

Write a program which will restore a possible permutation a_1, a_2, ..., a_{n}. If there are multiple solutions then print any of them. If there is no solution then print -1.

-----Input-----

The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).

The second line contains m integer numbers l_1, l_2, ..., l_{m} (1 ≤ l_{i} ≤ n) — indices of leaders in the beginning of each step.

-----Output-----

Print such permutation of n numbers a_1, a_2, ..., a_{n} that leaders in the game will be exactly l_1, l_2, ..., l_{m} if all the rules are followed. If there are multiple solutions print any of them.

If there is no permutation which satisfies all described conditions print -1.

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

Output
3 1 2 4

Input
3 3
3 1 2

Output
-1

-----Note-----

Let's follow leadership in the first example:   Child 2 starts.  Leadership goes from 2 to 2 + a_2 = 3.  Leadership goes from 3 to 3 + a_3 = 5. As it's greater than 4, it's going in a circle to 1.  Leadership goes from 1 to 1 + a_1 = 4.  Leadership goes from 4 to 4 + a_4 = 8. Thus in circle it still remains at 4.

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

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

n, m = R()
l = list(R())

a = [None] * n
b = [False] * n

c = set(range(1, n + 1))
for i in range(m - 1):
    j = l[i] - 1
    d = l[i + 1] - l[i]
    if d <= 0:
        d += n
    if a[j] != d:
        if a[j] is not None or b[d - 1]:
            print(-1)
            break
        a[j] = d
        b[d - 1] = True
        c.remove(d)
else:
    for i in range(n):
        if a[i] is None:
            a[i] = c.pop()
    print(*a)


I found an interesting problem on https://codeforces.com/problemset/problem/818/C:
Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss?

Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs to him as they all looked the same!

The storehouse is represented as matrix n × m. Every sofa takes two neighbouring by some side cells. No cell is covered by more than one sofa. There can be empty cells.

Sofa A is standing to the left of sofa B if there exist two such cells a and b that x_{a} < x_{b}, a is covered by A and b is covered by B. Sofa A is standing to the top of sofa B if there exist two such cells a and b that y_{a} < y_{b}, a is covered by A and b is covered by B. Right and bottom conditions are declared the same way.

Note that in all conditions A ≠ B. Also some sofa A can be both to the top of another sofa B and to the bottom of it. The same is for left and right conditions.

The note also stated that there are cnt_{l} sofas to the left of Grandpa Maks's sofa, cnt_{r} — to the right, cnt_{t} — to the top and cnt_{b} — to the bottom.

Grandpa Maks asks you to help him to identify his sofa. It is guaranteed that there is no more than one sofa of given conditions.

Output the number of Grandpa Maks's sofa. If there is no such sofa that all the conditions are met for it then output -1.

-----Input-----

The first line contains one integer number d (1 ≤ d ≤ 10^5) — the number of sofas in the storehouse.

The second line contains two integer numbers n, m (1 ≤ n, m ≤ 10^5) — the size of the storehouse.

Next d lines contains four integer numbers x_1, y_1, x_2, y_2 (1 ≤ x_1, x_2 ≤ n, 1 ≤ y_1, y_2 ≤ m) — coordinates of the i-th sofa. It is guaranteed that cells (x_1, y_1) and (x_2, y_2) have common side, (x_1, y_1)  ≠  (x_2, y_2) and no cell is covered by more than one sofa.

The last line contains four integer numbers cnt_{l}, cnt_{r}, cnt_{t}, cnt_{b} (0 ≤ cnt_{l}, cnt_{r},...

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

import sys
try:
    fin=open('in')
except:
    fin=sys.stdin
input=fin.readline

d = int(input())
n, m = map(int, input().split())
x1, y1, x2, y2 = [], [], [], []
T=[]
for _ in range(d):
    u, v, w, x = map(int, input().split())
    if u>w:u,w=w,u
    if v>x:v,x=x,v
    x1.append(u)
    y1.append(v)
    x2.append(-w)#the other direction pog?
    y2.append(-x)
    T.append([u,v,w,x])

x1.sort()
x2.sort()
y1.sort()
y2.sort()

req=list(map(int,input().split())) # x1,x2,y1,y2
import bisect
for i in range(len(T)):
    # binary search
    u,v,w,x=T[i]
    if req[0]==bisect.bisect_left(x1,w)-(u!=w):
        if req[1]==bisect.bisect_left(x2,-u)-(u!=w):
            if req[2]==bisect.bisect_left(y1,x)-(v!=x):
                if req[3]==bisect.bisect_left(y2,-v)-(v!=x):
                    print(i+1)
                    break
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/818/D:
Alice and Bob got very bored during a long car trip so they decided to play a game. From the window they can see cars of different colors running past them. Cars are going one after another.

The game rules are like this. Firstly Alice chooses some color A, then Bob chooses some color B (A ≠ B). After each car they update the number of cars of their chosen color that have run past them. Let's define this numbers after i-th car cnt_{A}(i) and cnt_{B}(i).

  If cnt_{A}(i) > cnt_{B}(i) for every i then the winner is Alice.  If cnt_{B}(i) ≥ cnt_{A}(i) for every i then the winner is Bob.  Otherwise it's a draw.

Bob knows all the colors of cars that they will encounter and order of their appearance. Alice have already chosen her color A and Bob now wants to choose such color B that he will win the game (draw is not a win). Help him find this color.

If there are multiple solutions, print any of them. If there is no such color then print -1.

-----Input-----

The first line contains two integer numbers n and A (1 ≤ n ≤ 10^5, 1 ≤ A ≤ 10^6) – number of cars and the color chosen by Alice.

The second line contains n integer numbers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^6) — colors of the cars that Alice and Bob will encounter in the order of their appearance.

-----Output-----

Output such color B (1 ≤ B ≤ 10^6) that if Bob chooses it then he will win the game. If there are multiple solutions, print any of them. If there is no such color then print -1.

It is guaranteed that if there exists any solution then there exists solution with (1 ≤ B ≤ 10^6).

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

Output
2

Input
5 2
2 2 4 5 3

Output
-1

Input
3 10
1 2 3

Output
4

-----Note-----

Let's consider availability of colors in the first example:   cnt_2(i) ≥ cnt_1(i) for every i, and color 2 can be the answer.  cnt_4(2) < cnt_1(2), so color 4 isn't the winning one for Bob.  All the other colors also have cnt_{j}(2) < cnt_1(2), thus they are not available.

In the third example every color is acceptable except for 10.

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

from sys import stdin, stdout

n, k = map(int, stdin.readline().split())
values = list(map(int, stdin.readline().split()))

sze = max(values)
used = [0 for i in range(sze + 1)]
challengers = [[] for i in range(n + 1)]

i = 0
cnt = 0

for i in range(n):
    if values[i] == k:
        cnt += 1
    elif used[values[i]] >= cnt:
        used[values[i]] += 1
        challengers[used[values[i]]].append(values[i])

for i in range(n, cnt - 1, -1):
    if len(challengers[i]):
        stdout.write(str(challengers[i][0]))
        break
else:
    stdout.write('-1')


I found an interesting problem on https://codeforces.com/problemset/problem/818/E:
Vova again tries to play some computer card game.

The rules of deck creation in this game are simple. Vova is given an existing deck of n cards and a magic number k. The order of the cards in the deck is fixed. Each card has a number written on it; number a_{i} is written on the i-th card in the deck.

After receiving the deck and the magic number, Vova removes x (possibly x = 0) cards from the top of the deck, y (possibly y = 0) cards from the bottom of the deck, and the rest of the deck is his new deck (Vova has to leave at least one card in the deck after removing cards). So Vova's new deck actually contains cards x + 1, x + 2, ... n - y - 1, n - y from the original deck.

Vova's new deck is considered valid iff the product of all numbers written on the cards in his new deck is divisible by k. So Vova received a deck (possibly not a valid one) and a number k, and now he wonders, how many ways are there to choose x and y so the deck he will get after removing x cards from the top and y cards from the bottom is valid?

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 10^9).

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the numbers written on the cards.

-----Output-----

Print the number of ways to choose x and y so the resulting deck is valid.

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

Output
4

Input
3 6
9 1 14

Output
1

-----Note-----

In the first example the possible values of x and y are:

  x = 0, y = 0;  x = 1, y = 0;  x = 2, y = 0;  x = 0, y = 1.

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

def gcd(a,b):
  if a == 0:
    return b
  return gcd(b%a,a)

n,k = [int(x) for x in input().split()]
a = [gcd(int(x),k) for x in input().split()]

if k == 1:
  print(((n+1)*(n+2))//2-n-1)
else:
  s = 0
  e = 0
  total = ((n+1)*(n+2))//2-1-n
  #print(total)
  #extra = {}
  c = 1

  while e < n:
    flag = False
    while c%k != 0 and e < n:
      total -= e-s
      c *= a[e]
      e += 1
    while c%k == 0 and s < e:
      c //= a[s]
      s += 1
  total -= e-s
  print(total)


I found an interesting problem on https://codeforces.com/problemset/problem/818/F:
Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.

Ivan decided that there should be exactly n_{i} vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph.

So the task Ivan gave you is: given q numbers n_1, n_2, ..., n_{q}, for each i tell the maximum number of edges in a graph with n_{i} vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops.

-----Input-----

The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct.

Then q lines follow, i-th line contains one positive integer n_{i} (1 ≤ n_{i} ≤ 2·10^9) — the number of vertices in i-th graph.

Note that in hacks you have to use q = 1.

-----Output-----

Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph.

-----Example-----
Input
3
3
4
6

Output
2
3
6

-----Note-----

In the first example it is possible to construct these graphs:  1 - 2, 1 - 3;  1 - 2, 1 - 3, 2 - 4;  1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6.

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

#! /usr/bin/env python

# http://codeforces.com/problemset/problem/818/F
# Problem name ::: F. Level Generation
# submission number

#212055293
#508427854

def newest_approach(n):
    from math import floor, ceil, sqrt

    quad_solv = sqrt(2*n+1/4)-1/2
    x = floor(quad_solv)
    y = ceil(quad_solv)

    xed = int(x*(x-1)/2 + n - x)
    xbr = n - x

    ybr = n - y
    yed = 2*ybr

    if xed > yed:
        print(xed)
        # print("nodes = %s :: edges = %s :: bridges = %s" % (n, xed, xbr))
    else:
        print(yed)
        # print("nodes = %s :: edges = %s :: bridges = %s" % (n, yed, ybr))

    return

def main():

    import sys

    data = [line.rstrip() for line in sys.stdin.readlines()]
    num_graphs = data[0]
    graph_sizes = [int(x) for x in data[1:]]

    for val in graph_sizes:
        # binary_search(val)
        # new_approach(val)
        newest_approach(val)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/819/A:
Sometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens.

All characters in this game are lowercase English letters. There are two players: Mister B and his competitor.

Initially the players have a string s consisting of the first a English letters in alphabetical order (for example, if a = 5, then s equals to "abcde").

The players take turns appending letters to string s. Mister B moves first.

Mister B must append exactly b letters on each his move. He can arbitrary choose these letters. His opponent adds exactly a letters on each move.

Mister B quickly understood that his opponent was just a computer that used a simple algorithm. The computer on each turn considers the suffix of string s of length a and generates a string t of length a such that all letters in the string t are distinct and don't appear in the considered suffix. From multiple variants of t lexicographically minimal is chosen (if a = 4 and the suffix is "bfdd", the computer chooses string t equal to "aceg"). After that the chosen string t is appended to the end of s.

Mister B soon found the game boring and came up with the following question: what can be the minimum possible number of different letters in string s on the segment between positions l and r, inclusive. Letters of string s are numerated starting from 1.

-----Input-----

First and only line contains four space-separated integers: a, b, l and r (1 ≤ a, b ≤ 12, 1 ≤ l ≤ r ≤ 10^9) — the numbers of letters each player appends and the bounds of the segment.

-----Output-----

Print one integer — the minimum possible number of different letters in the segment from position l to position r, inclusive, in string s.

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

Output
2
Input
4 2 2 6

Output
3
Input
3 7 4 6

Output
1

-----Note-----

In the first sample test one of optimal strategies generate string s = "abababab...", that's why answer is 2.

In the second sample test string s = "abcdbcaefg..." can...

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

def main(a, b, l, r):

    qL = (l - 1) // (2 * a + 2 * b)

    rL = (l - 1) % (2 * a + 2 * b) + 1

    qR = (r - 1) // (2 * a + 2 * b)

    rR = (r - 1) % (2 * a + 2 * b) + 1

    #print(qL, qR, rL, rR)

    if qL == qR:

        #In b segment

        if a < rL <= a + b and a < rR <= a + b:

            return 1

        if 2 * a + b < rL and 2 * a + b < rR:

            return 1

        #In a segment

        if 1 <= rL <= a and 1 <= rR <= a:

            return rR - rL + 1

        if a + b < rL <= 2 * a + b and a + b < rR <= 2 * a + b:

            return rR - rL + 1

        #In a + b segment

        if 1 <= rL <= a + b and 1 <= rR <= a + b:

            return a - rL + 1

        if a + b < rL and a + b < rR:

            return (2 * a + b) - rL + 1

        if a < rL <= a + b and a + b < rR <= 2 * a + b:

            return 1 + rR - (a + b)

        if a < rL <= a + b and 2 * a + b < rR:

            return 1 + a

        if 1 <= rL <= a and a + b < rR <= 2 * a + b:

            ans = a - rL + 1 + max(rR - (a + b + b), 0) + min(b, rR) - max(min(rR, b) - rL + 1, 0)

            return ans

        if 1 <= rL <= a and 2 * a + b < rR:

            return a - rL + 1 + a - max(b - rL + 1, 0)

    elif qL == qR - 1:

        #abababab

        newL = qL * (2 * a + 2 * b) + 1

        newR = (qR + 1) * (2 * a + 2 * b)

        if 1 <= rL <= a + b and a + b + 1 <= rR:

            return a + max(a - b, 0) + int(a <= b)

        if a + b + 1 <= rL <= 2 * (a + b) and (2 * a + 2 * b) + 1 <= rR <= a + b:

            return main(a, b, l - (a + b), r - (a + b))

        if 1 <= rL <= a and 1 <= rR <= a:

            return a + max(a - b, 0) + int(a <= b) + rR - max(rR - rL + 1, 0)

        if 1 <= rL <= a and a + 1 <= rR <= a + b:

            return a + max(a - b, 0) + int(a <= b)

        if a + 1 <= rL <= a + b and 1 <= rR <= a:

            return 1 + a

        if a + 1 <= rL <= a + b and a + 1 <= rR <= a + b:

            return 1 + a + max(a - b,...


I found an interesting problem on https://codeforces.com/problemset/problem/819/B:
Some time ago Mister B detected a strange signal from the space, which he started to study.

After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation.

Let's define the deviation of a permutation p as $\sum_{i = 1}^{i = n}|p [ i ] - i|$.

Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them.

Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example:

  k = 0: shift p_1, p_2, ... p_{n},  k = 1: shift p_{n}, p_1, ... p_{n} - 1,  ...,  k = n - 1: shift p_2, p_3, ... p_{n}, p_1.

-----Input-----

First line contains single integer n (2 ≤ n ≤ 10^6) — the length of the permutation.

The second line contains n space-separated integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct.

-----Output-----

Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them.

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

Output
0 0

Input
3
2 3 1

Output
0 1

Input
3
3 2 1

Output
2 1

-----Note-----

In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well.

In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift.

In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts.

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

def main():
    n=int(input())
    A=list(map(int,input().strip().split(' ')))

    def brutal(A):
        n=len(A)
        for i in range(n):
            temp=0
            pos=0
            neg=0
            for j in range(n):
                temp+=abs(A[j]-(j+i)%n)
                if A[j]-(j+i)%n>0:
                    pos+=1
                else:
                    neg+=1

            print(temp,i,pos,neg,'ans,shift,+ve,-ve')

    for i in range(len(A)):
        A[i]-=1

    ans=0
    pos=0
    neg=0
    change=[0 for i in range(len(A))]

    for i in range(len(A)):
        ans+=abs(A[i]-i)
        if A[i]-i>0:
            pos+=1
        else:
            neg+=1
        if A[i]-i>0:
            change[i]=A[i]-i
        elif A[i]==i:
            change[i]=0
        else:
            if A[i]!=0:
                change[i]=A[i]+n-i
            else:
                change[i]=0
    MIN=ans
    index=0
    #print(ans)
    collect=[[] for i in range(n)]
    for x in range(len(change)):
        collect[change[x]]+=[x]
    #print(collect)

    #print(ans,pos,neg)
    for s in range(1,n):
        ans-=abs(A[n-s]-n+1)
        ans+=abs(A[n-s]-0)
        neg-=1

        ans-=pos
        ans+=neg
        if A[n-s]>0:
            pos+=1
        else:
            neg+=1

        pos-=len(collect[s])
        neg+=len(collect[s])
        #print(ans,pos,neg)
        if ans<MIN:
            MIN=ans
            index=s
    print(MIN,index)
    #brutal(A)
main()


I found an interesting problem on https://codeforces.com/problemset/problem/820/A:
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.

At first day Mister B read v_0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v_0 pages, at second — v_0 + a pages, at third — v_0 + 2a pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than v_1 pages per day.

Also, to refresh his memory, every day, starting from the second, Mister B had to reread last l pages he read on the previous day. Mister B finished the book when he read the last page for the first time.

Help Mister B to calculate how many days he needed to finish the book.

-----Input-----

First and only line contains five space-separated integers: c, v_0, v_1, a and l (1 ≤ c ≤ 1000, 0 ≤ l < v_0 ≤ v_1 ≤ 1000, 0 ≤ a ≤ 1000) — the length of the book in pages, the initial reading speed, the maximum reading speed, the acceleration in reading speed and the number of pages for rereading.

-----Output-----

Print one integer — the number of days Mister B needed to finish the book.

-----Examples-----
Input
5 5 10 5 4

Output
1

Input
12 4 12 4 1

Output
3

Input
15 1 100 0 0

Output
15

-----Note-----

In the first sample test the book contains 5 pages, so Mister B read it right at the first day.

In the second sample test at first day Mister B read pages number 1 - 4, at second day — 4 - 11, at third day — 11 - 12 and finished the book.

In third sample test every day Mister B read 1 page of the book, so he finished in 15 days.

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

c, v0, v1, a, l = map(int, input().split())
cur = v0
rem = c
tmp = 0
res = 0
while rem > 0 :
    res += 1
    rem = rem - (cur - tmp)
    cur = min(cur + a, v1)
    tmp = l
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/820/B:
On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides).

That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices v_1, v_2, v_3 such that the angle $\angle v_{1} v_{2} v_{3}$ (where v_2 is the vertex of the angle, and v_1 and v_3 lie on its sides) is as close as possible to a. In other words, the value $|\angle v_{1} v_{2} v_{3} - a|$ should be minimum possible.

If there are many optimal solutions, Mister B should be satisfied with any of them.

-----Input-----

First and only line contains two space-separated integers n and a (3 ≤ n ≤ 10^5, 1 ≤ a ≤ 180) — the number of vertices in the polygon and the needed angle, in degrees.

-----Output-----

Print three space-separated integers: the vertices v_1, v_2, v_3, which form $\angle v_{1} v_{2} v_{3}$. If there are multiple optimal solutions, print any of them. The vertices are numbered from 1 to n in clockwise order.

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

Output
1 2 3

Input
4 67

Output
2 1 3

Input
4 68

Output
4 1 2

-----Note-----

In first sample test vertices of regular triangle can create only angle of 60 degrees, that's why every possible angle is correct.

Vertices of square can create 45 or 90 degrees angles only. That's why in second sample test the angle of 45 degrees was chosen, since |45 - 67| < |90 - 67|. Other correct answers are: "3 1 2", "3 2 4", "4 2 3", "4 3 1", "1 3 4", "1 4 2", "2 4 1", "4 1 3", "3 1 4", "3 4 2", "2 4 3", "2 3 1", "1 3 2", "1 2 4", "4 2 1".

In third sample test, on the contrary, the angle of 90 degrees was chosen, since |90 - 68| < |45 - 68|. Other correct answers are: "2 1 4", "3 2 1", "1 2 3", "4 3 2", "2 3 4", "1 4 3", "3 4 1".

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

I = lambda : map(int, input().split())
n, a = I()

exp = 999999999999
ans = 0

for i in range(1, n-1):
    newexp = abs((i*180.0)/(n*1.0) - a)
    if newexp < exp:
        ans = i
        exp = newexp

print(2, 1, 2+ans)


I found an interesting problem on https://codeforces.com/problemset/problem/821/A:
Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an n by n square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In other words, for every x, y such that 1 ≤ x, y ≤ n and a_{x}, y ≠ 1, there should exist two indices s and t so that a_{x}, y = a_{x}, s + a_{t}, y, where a_{i}, j denotes the integer in i-th row and j-th column.

Help Okabe determine whether a given lab is good!

-----Input-----

The first line of input contains the integer n (1 ≤ n ≤ 50) — the size of the lab.

The next n lines contain n space-separated integers denoting a row of the grid. The j-th integer in the i-th row is a_{i}, j (1 ≤ a_{i}, j ≤ 10^5).

-----Output-----

Print "Yes" if the given lab is good and "No" otherwise.

You can output each letter in upper or lower case.

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

Output
Yes

Input
3
1 5 2
1 1 1
1 2 3

Output
No

-----Note-----

In the first sample test, the 6 in the bottom left corner is valid because it is the sum of the 2 above it and the 4 on the right. The same holds for every number not equal to 1 in this table, so the answer is "Yes".

In the second sample test, the 5 cannot be formed as the sum of an integer in the same row and an integer in the same column. Thus the answer is "No".

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

import sys

def main():
    n = int(input())
    x = []
    for i in range(n):
        y = list(map(int,sys.stdin.readline().split()))
        x.append(y)

    for i in range(n):
        for j in range(n):
            if x[i][j] == 1:
                continue
            found = False
            for o in range(n):
                a = x[i][o]
                if o == j:
                    continue
                for p in range(n):
                    if p ==i:
                        continue
                    b = x[p][j]
                    if a+b == x[i][j]:
                        found = True
                        break
                if found:
                    break
            if not found:
                print("No")
                return
    print("Yes")

main()


I found an interesting problem on https://codeforces.com/problemset/problem/821/B:
Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees.

Consider the point (x, y) in the 2D plane such that x and y are integers and 0 ≤ x, y. There is a tree in such a point, and it has x + y bananas. There are no trees nor bananas in other points. Now, Okabe draws a line with equation $y = - \frac{x}{m} + b$. Okabe can select a single rectangle with axis aligned sides with all points on or under the line and cut all the trees in all points that are inside or on the border of this rectangle and take their bananas. Okabe's rectangle can be degenerate; that is, it can be a line segment or even a point.

Help Okabe and find the maximum number of bananas he can get if he chooses the rectangle wisely.

Okabe is sure that the answer does not exceed 10^18. You can trust him.

-----Input-----

The first line of input contains two space-separated integers m and b (1 ≤ m ≤ 1000, 1 ≤ b ≤ 10000).

-----Output-----

Print the maximum number of bananas Okabe can get from the trees he cuts.

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

Output
30

Input
2 3

Output
25

-----Note----- [Image]

The graph above corresponds to sample test 1. The optimal rectangle is shown in red and has 30 bananas.

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

from math import *

def sum(n):
    return (n * (n + 1)) // 2

m, b = [int(x) for x in input().strip().split()]
ans = 0
x = 0
y = 0
while True:
    if b < y:
        break
    x = m * (b - y)
    rans = sum(x) * (y + 1) + sum(y) * (x + 1)
    ans = max(ans, rans)
    y += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/821/C:
Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack.

Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to n. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.

That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.

Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.

-----Input-----

The first line of input contains the integer n (1 ≤ n ≤ 3·10^5) — the number of boxes.

Each of the next 2n lines of input starts with a string "add" or "remove". If the line starts with the "add", an integer x (1 ≤ x ≤ n) follows, indicating that Daru should add the box with number x to the top of the stack.

It is guaranteed that exactly n lines contain "add" operations, all the boxes added are distinct, and n lines contain "remove" operations. It is also guaranteed that a box is always added before it is required to be removed.

-----Output-----

Print the minimum number of times Daru needs to reorder the boxes to successfully complete all of Okabe's commands.

-----Examples-----
Input
3
add 1
remove
add 2
add 3
remove
remove

Output
1

Input
7
add 3
add 2
add 1
remove
add 4
remove
remove
remove
add 6
add 7
add 5
remove
remove
remove

Output
2

-----Note-----

In the first sample, Daru should reorder the boxes after adding box 3 to the stack.

In the second sample, Daru should reorder the boxes...

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

import sys

def main():
    n = int(input())
    n = n*2
    u = 0
    res = 0
    x = []
    for i in range(n):
        s = sys.stdin.readline()
        if s[0] == 'r':
            u+=1
            if len(x)==0:
                continue
            if x[-1] == u:
                x.pop()
            else:
                x = []
                res +=1
        else:
            a,b = s.split()
            x.append(int(b))
    print(res)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/822/A:
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom!

Leha came up with a task for himself to relax a little. He chooses two integers A and B and then calculates the greatest common divisor of integers "A factorial" and "B factorial". Formally the hacker wants to find out GCD(A!, B!). It's well known that the factorial of an integer x is a product of all positive integers less than or equal to x. Thus x! = 1·2·3·...·(x - 1)·x. For example 4! = 1·2·3·4 = 24. Recall that GCD(x, y) is the largest positive integer q that divides (without a remainder) both x and y.

Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?

-----Input-----

The first and single line contains two integers A and B (1 ≤ A, B ≤ 10^9, min(A, B) ≤ 12).

-----Output-----

Print a single integer denoting the greatest common divisor of integers A! and B!.

-----Example-----
Input
4 3

Output
6

-----Note-----

Consider the sample.

4! = 1·2·3·4 = 24. 3! = 1·2·3 = 6. The greatest common divisor of integers 24 and 6 is exactly 6.

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

from math import factorial
a, b = map(int, input().split())
print(factorial(min(a, b)))


I found an interesting problem on https://codeforces.com/problemset/problem/822/B:
Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?

Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s="ab?b" as a result, it will appear in t="aabrbb" as a substring.

Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol "?" should be considered equal to any other symbol.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ m ≤ 1000) — the length of the string s and the length of the string t correspondingly.

The second line contains n lowercase English letters — string s.

The third line contains m lowercase English letters — string t.

-----Output-----

In the first line print single integer k — the minimal number of symbols that need to be replaced.

In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one.

-----Examples-----
Input
3 5
abc
xaybz

Output
2
2 3

Input
4 10
abcd
ebceabazcd

Output
1
2

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

import sys
read=lambda:sys.stdin.readline().rstrip()
readi=lambda:int(sys.stdin.readline())
writeln=lambda x:sys.stdout.write(str(x)+"\n")
write=lambda x:sys.stdout.write(x)
n,m = list(map(int, read().split()))
s,t = read(), read()

mcnt, midx = -1, -1
for i in range(m-n+1):
    cnt = 0
    for j in range(n):
        if s[j] == t[j+i]:
            cnt += 1
    if cnt > mcnt:
        mcnt = cnt
        midx = i

k = 0
pos = []
for i in range(n):
    if s[i] != t[midx+i]:
        k += 1
        pos.append(str(i+1))

writeln(k)
if k:
    writeln(' '.join(pos))


I found an interesting problem on https://codeforces.com/problemset/problem/822/C:
It's well known that the best way to distract from something is to do one's favourite thing. Job is such a thing for Leha.

So the hacker began to work hard in order to get rid of boredom. It means that Leha began to hack computers all over the world. For such zeal boss gave the hacker a vacation of exactly x days. You know the majority of people prefer to go somewhere for a vacation, so Leha immediately went to the travel agency. There he found out that n vouchers left. i-th voucher is characterized by three integers l_{i}, r_{i}, cost_{i} — day of departure from Vičkopolis, day of arriving back in Vičkopolis and cost of the voucher correspondingly. The duration of the i-th voucher is a value r_{i} - l_{i} + 1.

At the same time Leha wants to split his own vocation into two parts. Besides he wants to spend as little money as possible. Formally Leha wants to choose exactly two vouchers i and j (i ≠ j) so that they don't intersect, sum of their durations is exactly x and their total cost is as minimal as possible. Two vouchers i and j don't intersect if only at least one of the following conditions is fulfilled: r_{i} < l_{j} or r_{j} < l_{i}.

Help Leha to choose the necessary vouchers!

-----Input-----

The first line contains two integers n and x (2 ≤ n, x ≤ 2·10^5) — the number of vouchers in the travel agency and the duration of Leha's vacation correspondingly.

Each of the next n lines contains three integers l_{i}, r_{i} and cost_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 2·10^5, 1 ≤ cost_{i} ≤ 10^9) — description of the voucher.

-----Output-----

Print a single integer — a minimal amount of money that Leha will spend, or print  - 1 if it's impossible to choose two disjoint vouchers with the total duration exactly x.

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

Output
5

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

Output
-1

-----Note-----

In the first sample Leha should choose first and third vouchers. Hereupon the total duration will be equal to (3 - 1 + 1) + (6 - 5 + 1) = 5 and the total cost will be 4 + 1 = 5.

In...

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

from sys import stdin, stdout

n, x = map(int, stdin.readline().split())
length = [[] for i in range(x + 1)]
mins = [[] for i in range(x + 1)]
challengers = []

for i in range(n):
    l, r, v = map(int, stdin.readline().split())

    if (r - l < x):
        length[r - l + 1].append((l, v))

for i in range(1, x + 1):
    if not len(length[i]):
        continue
    else:
        length[i].sort()
        mn = length[i][-1][-1]
        mins[i].append(mn)

        for j in range(len(length[i]) - 2, -1, -1):
            mn = min(mn, length[i][j][-1])
            mins[i].append(mn)

        mins[i] = mins[i][::-1]

INF = float('inf')
ans = INF

for i in range(1, x + 1):
    if not len(length[i]) or not len(length[x - i]):
        continue

    for j in range(len(length[i])):
        pos, v = length[i][j]

        l, r = -1, len(length[x - i])
        while (r - l > 1):
            m = (r + l) // 2

            if length[x - i][m][0] > pos + i - 1:
                r = m
            else:
                l = m

        if r != len(length[x - i]):
            ans = min(ans, v + mins[x - i][r])

if ans == INF:
    stdout.write('-1')
else:
    stdout.write(str(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/825/A:
Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm:

  Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones).  Digits are written one by one in order corresponding to number and separated by single '0' character.

Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number.

-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 89) — length of the string s.

The second line contains string s — sequence of '0' and '1' characters, number in its encoded format. It is guaranteed that the number corresponding to the string is positive and doesn't exceed 10^9. The string always starts with '1'.

-----Output-----

Print the decoded number.

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

Output
3

Input
9
110011101

Output
2031

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

N = int(input())
li = input().split('0')
for i in range(len(li)):
    li[i] = li[i].count('1')

if len(li) == 0:
    print ("0")
else:
    li = list(map(str,li))
    print("".join(li))


I found an interesting problem on https://codeforces.com/problemset/problem/825/B:
Alice and Bob play 5-in-a-row game. They have a playing field of size 10 × 10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts.

In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately.

Alice wins if some crosses in the field form line of length not smaller than 5. This line can be horizontal, vertical and diagonal.

-----Input-----

You are given matrix 10 × 10 (10 lines of 10 characters each) with capital Latin letters 'X' being a cross, letters 'O' being a nought and '.' being an empty cell. The number of 'X' cells is equal to the number of 'O' cells and there is at least one of each type. There is at least one empty cell.

It is guaranteed that in the current arrangement nobody has still won.

-----Output-----

Print 'YES' if it's possible for Alice to win in one turn by putting cross in some empty cell. Otherwise print 'NO'.

-----Examples-----
Input
XX.XX.....
.....OOOO.
..........
..........
..........
..........
..........
..........
..........
..........

Output
YES

Input
XXOXX.....
OO.O......
..........
..........
..........
..........
..........
..........
..........
..........

Output
NO

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

import os

def f():
    board = []
    for i in range(10):
        board.append(input())
    for i, row in enumerate(board):
        for j, c in enumerate(row):
            if c == '.':
                #horizonal
                d1 = d2 = 0
                b = j - 1
                while b >= 0:
                    if row[b] == 'X':
                        d1 += 1
                        b -= 1
                    else:
                        break
                b = j + 1
                while b <= 9:
                    if row[b] == 'X':
                        d2 += 1
                        b += 1
                    else:
                        break
                if d1 + d2 >= 4:
                    print('YES')
                    return
                #vertical
                d1 = d2 = 0
                a = i - 1
                while a >= 0:
                    if board[a][j] == 'X':
                        d1 += 1
                        a -= 1
                    else:
                        break
                a = i + 1
                while a <= 9:
                    if board[a][j] == 'X':
                        d2 += 1
                        a += 1
                    else:
                        break
                if d1 + d2 >= 4:
                    print('YES')
                    return
                #diagonal
                d1 = d2 = 0
                a = i - 1
                b = j - 1
                while a >= 0 and b >= 0:
                    if board[a][b] == 'X':
                        d1 += 1
                        a -= 1
                        b -= 1
                    else:
                        break
                a = i + 1
                b = j + 1
                while a <= 9 and b <= 9:
                    if board[a][b] == 'X':
                        d2 += 1
                        a += 1
                        b += 1
                    else:
                        break
                if d1 + d2 >= 4:
                   ...


I found an interesting problem on https://codeforces.com/problemset/problem/825/C:
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge).

Makes has chosen n problems to solve on Decoforces with difficulties a_1, a_2, ..., a_{n}. He can solve these problems in arbitrary order. Though he can solve problem i with difficulty a_{i} only if he had already solved some problem with difficulty $d \geq \frac{a_{i}}{2}$ (no matter on what online judge was it).

Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty k.

With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list.

For every positive integer y there exist some problem with difficulty y on at least one judge besides Decoforces.

Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another.

Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.

-----Input-----

The first line contains two integer numbers n, k (1 ≤ n ≤ 10^3, 1 ≤ k ≤ 10^9).

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

-----Output-----

Print minimum number of problems Makes should solve on other judges in order to solve all chosen problems on Decoforces.

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

Output
1

Input
4 20
10 3 6 3

Output
0

-----Note-----

In the first example Makes at first solves problems 1 and 2. Then in order to solve the problem with difficulty 9, he should solve problem with difficulty no less than 5. The only available are...

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

n, k = list(map(int, input().split()))
s = [int(i) for i in input().split()]
s.sort()
ans = 0
for i in s:
    while k<i/2:
        ans+=1
        k=2*k
    k = max(k, i)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/825/D:
You are given two strings s and t consisting of small Latin letters, string s can also contain '?' characters.

Suitability of string s is calculated by following metric:

Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings s, you choose the one with the largest number of non-intersecting occurrences of string t. Suitability is this number of occurrences.

You should replace all '?' characters with small Latin letters in such a way that the suitability of string s is maximal.

-----Input-----

The first line contains string s (1 ≤ |s| ≤ 10^6).

The second line contains string t (1 ≤ |t| ≤ 10^6).

-----Output-----

Print string s with '?' replaced with small Latin letters in such a way that suitability of that string is maximal.

If there are multiple strings with maximal suitability then print any of them.

-----Examples-----
Input
?aa?
ab

Output
baab

Input
??b?
za

Output
azbz

Input
abcd
abacaba

Output
abcd

-----Note-----

In the first example string "baab" can be transformed to "abab" with swaps, this one has suitability of 2. That means that string "baab" also has suitability of 2.

In the second example maximal suitability you can achieve is 1 and there are several dozens of such strings, "azbz" is just one of them.

In the third example there are no '?' characters and the suitability of the string is 0.

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

s = list(input())
t = input()
abc = 'abcdefghijklmnopqrstuvwxyz'
dabc ={}
for i in range(26):
	dabc[abc[i]] = i

lt = {}
ls = {}
dd = {}
ls['?'] = 0
for i in abc:
	lt[i] = 0
	ls[i] = 0
	dd[i] = 0
for letter in t:
	lt[letter] += 1
for letter in s:
	ls[letter] +=1

X = ls['?']
def check(ans):
	nonlocal ls, lt, abc, X
	return -sum(min(0, ls[l] - lt[l] * ans) for l in abc) <= X

start, end = [0, 2000000]
i = 0
while start < end:
	st = start + end
	ans = (st + st%2)//2
	if check(ans):
		start = ans
	else:
		end = ans - 1
ans = start

for letter in abc:
	dd[letter] = max(0, lt[letter] * ans - ls[letter])
	X -= max(0, lt[letter] * ans - ls[letter])

j = 0
for i in range(len(s)):
	if s[i] == '?':
		try:
			while dd[abc[j]] == 0:
				j +=1
			s[i] = abc[j]
			dd[abc[j]] -= 1
		except:
			s[i] = 'z'
print(''.join(s))


I found an interesting problem on https://codeforces.com/problemset/problem/825/E:
You are given a directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected.

You should assign labels to all vertices in such a way that:

  Labels form a valid permutation of length n — an integer sequence such that each integer from 1 to n appears exactly once in it.  If there exists an edge from vertex v to vertex u then label_{v} should be smaller than label_{u}.  Permutation should be lexicographically smallest among all suitable.

Find such sequence of labels to satisfy all the conditions.

-----Input-----

The first line contains two integer numbers n, m (2 ≤ n ≤ 10^5, 1 ≤ m ≤ 10^5).

Next m lines contain two integer numbers v and u (1 ≤ v, u ≤ n, v ≠ u) — edges of the graph. Edges are directed, graph doesn't contain loops or multiple edges.

-----Output-----

Print n numbers — lexicographically smallest correct permutation of labels of vertices.

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

Output
1 3 2

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

Output
4 1 2 3

Input
5 4
3 1
2 1
2 3
4 5

Output
3 1 2 4 5

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

from heapq import *

n, m = map(int, input().split())
g = [[] for _ in range(n + 1)]
out = [0] * (n + 1)
for _ in range(m):
	u, v = map(int, input().split())
	g[v].append(u)
	out[u] += 1

q = [-u for u in range(1, n + 1) if not out[u]]
heapify(q)
r = [0] * (n + 1)
c = n
while q:
	u = -heappop(q)
	r[u] = c
	c -= 1
	for v in g[u]:
		out[v] -= 1
		if not out[v]:
			heappush(q, -v)
print(*r[1:])


I found an interesting problem on https://codeforces.com/problemset/problem/825/F:
Ivan wants to write a letter to his friend. The letter is a string s consisting of lowercase Latin letters.

Unfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string s instead of the string itself.

The compressed version of string s is a sequence of strings c_1, s_1, c_2, s_2, ..., c_{k}, s_{k}, where c_{i} is the decimal representation of number a_{i} (without any leading zeroes) and s_{i} is some string consisting of lowercase Latin letters. If Ivan writes string s_1 exactly a_1 times, then string s_2 exactly a_2 times, and so on, the result will be string s.

The length of a compressed version is |c_1| + |s_1| + |c_2| + |s_2|... |c_{k}| + |s_{k}|. Among all compressed versions Ivan wants to choose a version such that its length is minimum possible. Help Ivan to determine minimum possible length.

-----Input-----

The only line of input contains one string s consisting of lowercase Latin letters (1 ≤ |s| ≤ 8000).

-----Output-----

Output one integer number — the minimum possible length of a compressed version of s.

-----Examples-----
Input
aaaaaaaaaa

Output
3

Input
abcab

Output
6

Input
cczabababab

Output
7

-----Note-----

In the first example Ivan will choose this compressed version: c_1 is 10, s_1 is a.

In the second example Ivan will choose this compressed version: c_1 is 1, s_1 is abcab.

In the third example Ivan will choose this compressed version: c_1 is 2, s_1 is c, c_2 is 1, s_2 is z, c_3 is 4, s_3 is ab.

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

def prefix(s):
    p = [0]
    for i in range(1, len(s)):
        j = p[-1]
        while j > 0 and s[j] != s[i]:
            j = p[j - 1]
        if s[i] == s[j]:
            j += 1
        p.append(j)
    return p

s = input()
n = len(s)
ans = [0] * (n + 1)
i = n - 1

while i >= 0:
    p = prefix(s[i:])
    ans[i] = 2 + ans[i + 1]
    for j in range(len(p)):
        z = 1
        if (j + 1) % (j + 1 - p[j]) == 0:
            z = (j + 1) // (j + 1 - p[j])
        res = len(str(z)) + (j + 1) // z + ans[i + j + 1]
        ans[i] = min(ans[i], res)
    i -= 1

print(ans[0])


I found an interesting problem on https://codeforces.com/problemset/problem/828/A:
In a small restaurant there are a tables for one person and b tables for two persons.

It it known that n groups of people come today, each consisting of one or two people.

If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person. If there are still none of them, the restaurant denies service to this group.

If a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.

You are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.

-----Input-----

The first line contains three integers n, a and b (1 ≤ n ≤ 2·10^5, 1 ≤ a, b ≤ 2·10^5) — the number of groups coming to the restaurant, the number of one-seater and the number of two-seater tables.

The second line contains a sequence of integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 2) — the description of clients in chronological order. If t_{i} is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.

-----Output-----

Print the total number of people the restaurant denies service to.

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

Output
0

Input
4 1 1
1 1 2 1

Output
2

-----Note-----

In the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. The third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, all clients are served.

In the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, it occupies one place at the two-seater table. It's impossible to seat the...

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

n, a, b = [int(s) for s in input().split()]
t = [int(s) for s in input().split()]
ans, c = 0, 0
for i in range(n):
    if t[i] == 1:
        if a>0:
            a-=1
        elif b>0:
            b-=1
            c+=1
        elif c>0:
            c-=1
        else:
            ans+=1
    else:
        if b>0:
            b-=1
        else:
            ans+=2
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/828/B:
Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.

You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet.

The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white.

-----Output-----

Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1.

-----Examples-----
Input
5 4
WWWW
WWWB
WWWB
WWBB
WWWW

Output
5

Input
1 2
BB

Output
-1

Input
3 3
WWW
WWW
WWW

Output
1

-----Note-----

In the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).

In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.

In the third example all cells are colored white, so it's sufficient to color any cell black.

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

def polycarp(n, m, l):
    left = min(l).find("B")
    if left == -1:
        return 1
    right = m - min([x[::-1] for x in l]).find("B") - 1
    top = bottom = -1
    for i in range(n):
        if l[i].find("B") != -1:
            top = i
            break
    for i in range(n - 1, -1, -1):
        if l[i].find("B") != -1:
            bottom = i
            break
    w = right - left + 1
    h = bottom - top + 1
    if w > n or h > m:
        return -1
    r = 0
    for i in range(top, bottom + 1):
        for j in range(left, right + 1):
            if l[i][j] == "W":
                r += 1
    if w > h:
        r += (w - h) * w
    else:
        r += (h - w) * h
    return r

n, m = list(map(int, input().strip().split()))
l = list()
for i in range(n):
    l.append(input().strip())
print(polycarp(n, m, l))


I found an interesting problem on https://codeforces.com/problemset/problem/828/C:
Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one.

Ivan knows some information about the string s. Namely, he remembers, that string t_{i} occurs in string s at least k_{i} times or more, he also remembers exactly k_{i} positions where the string t_{i} occurs in string s: these positions are x_{i}, 1, x_{i}, 2, ..., x_{i}, k_{i}. He remembers n such strings t_{i}.

You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings t_{i} and string s consist of small English letters only.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 10^5) — the number of strings Ivan remembers.

The next n lines contain information about the strings. The i-th of these lines contains non-empty string t_{i}, then positive integer k_{i}, which equal to the number of times the string t_{i} occurs in string s, and then k_{i} distinct positive integers x_{i}, 1, x_{i}, 2, ..., x_{i}, k_{i} in increasing order — positions, in which occurrences of the string t_{i} in the string s start. It is guaranteed that the sum of lengths of strings t_{i} doesn't exceed 10^6, 1 ≤ x_{i}, j ≤ 10^6, 1 ≤ k_{i} ≤ 10^6, and the sum of all k_{i} doesn't exceed 10^6. The strings t_{i} can coincide.

It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists.

-----Output-----

Print lexicographically minimal string that fits all the information Ivan remembers.

-----Examples-----
Input
3
a 4 1 3 5 7
ab 2 1 5
ca 1 4

Output
abacaba

Input
1
a 1 3

Output
aaa

Input
3
ab 1 1
aba 1 3
ab 2 3 5

Output
ababab

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

import math as mt
import sys,string
input=sys.stdin.readline
print=sys.stdout.write
import random
from collections import deque,defaultdict
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
t=I()
d=defaultdict(str)
ml=0
p=0
for _ in range(t):
    s=input().split()
    w=s[0]
    x=list(map(int,s[1::]))
    for i in range(1,len(x)):
        r=d[x[i]-1]
        if(len(r)<len(w)):
            d[x[i]-1]=w
    ml=max(ml,len(w)+x[-1]-1)
ans="a"*ml
ans=list(ans)
#print(d)
p=-1
z=sorted(list(d.keys()))
for i in z:
    if(i+len(d[i])>p):
        if(i>=p):
            for j in range(i,i+len(d[i])):
                ans[j]=d[i][j-i]
        else:
            leave=p-i
            f=max(i,p)
            #print(ans,"@",d[i],p,d[i][leave::])
            for j in range(leave,len(d[i])):
                ans[f]=d[i][j]
                f+=1
            #print(ans,"*")
        p=i+len(d[i])

for i in ans:
    print(i)


I found an interesting problem on https://codeforces.com/problemset/problem/830/A:
There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.

You are to determine the minimum time needed for all n people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.

-----Input-----

The first line contains three integers n, k and p (1 ≤ n ≤ 1 000, n ≤ k ≤ 2 000, 1 ≤ p ≤ 10^9) — the number of people, the number of keys and the office location.

The second line contains n distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — positions in which people are located initially. The positions are given in arbitrary order.

The third line contains k distinct integers b_1, b_2, ..., b_{k} (1 ≤ b_{j} ≤ 10^9) — positions of the keys. The positions are given in arbitrary order.

Note that there can't be more than one person or more than one key in the same point. A person and a key can be located in the same point.

-----Output-----

Print the minimum time (in seconds) needed for all n to reach the office with keys.

-----Examples-----
Input
2 4 50
20 100
60 10 40 80

Output
50

Input
1 2 10
11
15 7

Output
7

-----Note-----

In the first example the person located at point 20 should take the key located at point 40 and go with it to the office located at point 50. He spends 30 seconds. The person located at point 100 can take the key located at point 80 and go to the office with it. He spends 50 seconds. Thus, after 50 seconds everybody is in office with keys.

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

read = lambda: list(map(int, input().split()))
n, k, p = read()
a = list(read())
b = list(read())
a.sort()
b.sort()

def cal(a, b):
    return abs(a - b) + abs(b - p)

mi = 1e15
for _ in range(k - n + 1):
    ma = 0
    for __ in range(n):
        te = cal(a[__], b[_ + __])
        if te > ma:
            ma = te
    if ma < mi:
        mi = ma
print(mi)


I found an interesting problem on https://codeforces.com/problemset/problem/830/C:
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is a_{i} meters high.

Vladimir has just planted n bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing.

Vladimir wants to check the bamboos each d days (i.e. d days after he planted, then after 2d days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than k meters.

What is the maximum value d he can choose so that he can achieve what he wants without cutting off more than k meters of bamboo?

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^11) — the number of bamboos and the maximum total length of cut parts, in meters.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the required heights of bamboos, in meters.

-----Output-----

Print a single integer — the maximum value of d such that Vladimir can reach his goal.

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

Output
3

Input
3 40
10 30 50

Output
32

-----Note-----

In the first example Vladimir can check bamboos each 3 days. Then he will cut the first and the second bamboos after 3 days, and the third bamboo after 6 days. The total length of cut parts is 2 + 0 + 1 = 3 meters.

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

import itertools
import time

unfold = itertools.chain.from_iterable

t = time.time() + 1900
def jumps(a):
    d = speedup
    if time.time() > t:
        print(anss)
        return
    try:
        while True:
            c = (a + d - 1) // d
            d = (a + c - 2) // (c - 1)
            yield d
    except:
        return

#    while d < a - 1:
#        c = (a + d - 1) // d
#        d = (a + c - 2) // (c - 1)
#        yield d

def calc(d):
    return (d - 1) * len(a) - sum(i % d for i in a)

def ans1(D):
    for d in D:
        d -= 1
        if calc(d) <= k:
            return d
    return 1

def ans():
    for d, pd in zip(D, D[1:]):
        if time.time() > t:
            return anss
        d -= 1
        cd = calc(d)
        if cd <= k:
            return d
        if d == pd:
            continue
        cpd = calc(pd)
        if (d - pd) * (cd - cpd) >= ((cd - k) * (d - pd) + cd - cpd - 1):
            return d - ((cd - k) * (d - pd) + cd - cpd - 1) // (cd - cpd)
    return anss

n, k = map(int, input().split())
a = list(map(int, input().split()))
speedup = int(2 * max(a) ** 0.55)

lb = int(max(a) ** 0.1 + 10)

a = [i - 1 for i in a]
anss = ans1(sorted(range(2, lb + 1), reverse=True))
if anss <= lb / 2:
    print(anss)
    return

a = [i + 1 for i in a]
D = sorted(set(range(lb + 1, speedup + 1)).union(set([speedup, max(a) + k + 1]).union(set(
    unfold(map(jumps, a))))), reverse=True)

a = [i - 1 for i in a]
print(int(ans()))


I found an interesting problem on https://codeforces.com/problemset/problem/831/A:
Array of integers is unimodal, if:

  it is strictly increasing in the beginning;  after that it is constant;  after that it is strictly decreasing.

The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent.

For example, the following three arrays are unimodal: [5, 7, 11, 11, 2, 1], [4, 4, 2], [7], but the following three are not unimodal: [5, 5, 6, 6, 1], [1, 2, 1, 2], [4, 5, 5, 6].

Write a program that checks if an array is unimodal.

-----Input-----

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

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1 000) — the elements of the array.

-----Output-----

Print "YES" if the given array is unimodal. Otherwise, print "NO".

You can output each letter in any case (upper or lower).

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

Output
YES

Input
5
10 20 30 20 10

Output
YES

Input
4
1 2 1 2

Output
NO

Input
7
3 3 3 3 3 3 3

Output
YES

-----Note-----

In the first example the array is unimodal, because it is strictly increasing in the beginning (from position 1 to position 2, inclusively), that it is constant (from position 2 to position 4, inclusively) and then it is strictly decreasing (from position 4 to position 6, inclusively).

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

#!/usr/bin/env python3
from sys import stdin, stdout

def rint():
    return list(map(int, stdin.readline().split()))
#lines = stdin.readlines()

n = int(input())
a = list(rint())

if n == 1:
    print("YES")
    return

stage = 0
for i in range(n-1):
    diff = a[i+1] - a[i]
    if stage == 0:
        if diff > 0:
            pass
        elif diff == 0:
            stage = 1
        else:
            stage = 2
    elif stage == 1:
        if diff > 0 :
            print("NO")
            return
        elif diff == 0:
            pass
        else:
            stage = 2
    elif stage == 2:
        if diff > 0 or diff == 0:
            print("NO")
            return
        else:
            pass
print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/831/B:
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.

You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts in the same order.

You are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.

Since all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.

-----Input-----

The first line contains a string of length 26 consisting of distinct lowercase English letters. This is the first layout.

The second line contains a string of length 26 consisting of distinct lowercase English letters. This is the second layout.

The third line contains a non-empty string s consisting of lowercase and uppercase English letters and digits. This is the text typed in the first layout. The length of s does not exceed 1000.

-----Output-----

Print the text if the same keys were pressed in the second layout.

-----Examples-----
Input
qwertyuiopasdfghjklzxcvbnm
veamhjsgqocnrbfxdtwkylupzi
TwccpQZAvb2017

Output
HelloVKCup2017

Input
mnbvcxzlkjhgfdsapoiuytrewq
asdfghjklqwertyuiopzxcvbnm
7abaCABAABAcaba7

Output
7uduGUDUUDUgudu7

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

d = dict()
tr = dict()
alpha = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
for i in range(26):
    tr[alpha[2 * i + 1]] = alpha[2 * i]
r1 = input()
r2 = input()
for s in range(26):
    d[r1[s]] = r2[s]
    d[tr[r1[s]]] = tr[r2[s]]
text = input()
ans = ''
for i in text:
    if i in d.keys():
        ans += d[i]
    else:
        ans += i
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/831/C:
Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave a_{i} points.

Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n ≤ k) values b_1, b_2, ..., b_{n} (it is guaranteed that all values b_{j} are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. n < k. Note that the initial score wasn't announced.

Your task is to determine the number of options for the score the participant could have before the judges rated the participant.

-----Input-----

The first line contains two integers k and n (1 ≤ n ≤ k ≤ 2 000) — the number of jury members and the number of scores Polycarp remembers.

The second line contains k integers a_1, a_2, ..., a_{k} ( - 2 000 ≤ a_{i} ≤ 2 000) — jury's marks in chronological order.

The third line contains n distinct integers b_1, b_2, ..., b_{n} ( - 4 000 000 ≤ b_{j} ≤ 4 000 000) — the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.

-----Output-----

Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes).

-----Examples-----
Input
4 1
-5 5 0 20
10

Output
3

Input
2 2
-2000 -2000
3998000 4000000

Output
1

-----Note-----

The answer for the first example is 3 because initially the participant could have  - 10, 10 or 15 points.

In the second example there is only one correct initial score equaling to 4 002 000.

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

def read():
    return [int(x) for x in input().split()]

k,n = read()
a = read()
b = read()

sum = set()
tmp =[0]
for e in a:
    tmp.append(tmp[-1]+e)
    sum.add(tmp[-1])

ans = set()
for e in tmp[1:]:
    init = b[0]-e
    for bb in b[1:]:
        if bb - init not in sum:
            break
    else:
        ans.add(init)

print(len(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/832/A:
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.

Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players take turns crossing out exactly k sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than k sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.

-----Input-----

The first line contains two integers n and k (1 ≤ n, k ≤ 10^18, k ≤ n) — the number of sticks drawn by Sasha and the number k — the number of sticks to be crossed out on each turn.

-----Output-----

If Sasha wins, print "YES" (without quotes), otherwise print "NO" (without quotes).

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

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

Output
YES

Input
10 4

Output
NO

-----Note-----

In the first example Sasha crosses out 1 stick, and then there are no sticks. So Lena can't make a move, and Sasha wins.

In the second example Sasha crosses out 4 sticks, then Lena crosses out 4 sticks, and after that there are only 2 sticks left. Sasha can't make a move. The players make equal number of moves, so Sasha doesn't win.

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

a, b = list(map(int, input().split()))
c = a // b
if c % 2 == 1:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/832/B:
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..

There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.

Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.

Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.

A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.

The good letters are given to Petya. All the others are bad.

-----Input-----

The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.

The second line contains the pattern — a string s of lowercase English letters, characters "?" and "*" (1 ≤ |s| ≤ 10^5). It is guaranteed that character "*" occurs in s no more than once.

The third line contains integer n (1 ≤ n ≤ 10^5) — the number of query strings.

n lines follow, each of them contains single non-empty string consisting of lowercase English letters — a query string.

It is guaranteed that the total length of all query strings is not greater than 10^5.

-----Output-----

Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.

You can choose the case (lower or upper) for each letter arbitrary.

-----Examples-----
Input
ab
a?a
2
aaa
aab

Output
YES
NO

Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax

Output
NO
YES
NO
YES

-----Note-----

In the first example we can replace "?" with good letters "a"...

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

l=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
s1=input().strip()
s1=list(s1)
s2=[]
for i in l:
    if i not in s1:
        s2.append(i)
pattern=input().strip()
pattern=list(pattern)
if ("*" not in pattern):
    length_main=len(pattern)
    n=int(input().strip())
    for i in range(n):
        f=0
        string=input().strip()
        length=len(string)
        if (length_main==length):
            for j in range(length_main):
                if (string[j]!=pattern[j]):
                    if (pattern[j]!="?"):
                        print ('NO')
                        f=1
                        break
                    else:
                        if (string[j] not in s1):
                            print ('NO')
                            f=1
                            break
            if (f==0):
                print ("YES")
        else:
            print ('NO')
else:
    ind=pattern.index("*")
    length_main=len(pattern)
    n=int(input().strip())
    for i in range(n):
        string=input().strip()
        length=len(string)
        if (length<length_main-1):
            print ('NO')
        else:
            f=0
            for j in range(ind):
                if (string[j]!=pattern[j]):
                    if (pattern[j]!="?"):
                        print ('NO')
                        f=1
                        break
                    else:
                        if (string[j] not in s1):
                            print ('NO')
                            f=1
                            break
            if (f!=1):
                q=length_main-length
                for j in range(length_main-1,ind,-1):
                    if (string[j-q]!=pattern[j]):
                        if (pattern[j]!="?"):
                            print ('NO')
                            f=1
                            break
                        else:
                            if (string[j-q] not in s1):
                               ...


I found an interesting problem on https://codeforces.com/problemset/problem/832/C:
n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 10^6. For each person we know in which direction (left or right) he is facing, and his maximum speed.

You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed s: one to the right, and one to the left. Of course, the speed s is strictly greater than people's maximum speed.

The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray.

You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point 0, and there is a person that has run through point 10^6, is as small as possible. In other words, find the minimum time moment t such that there is a point you can place the bomb to so that at time moment t some person has run through 0, and some person has run through point 10^6.

-----Input-----

The first line contains two integers n and s (2 ≤ n ≤ 10^5, 2 ≤ s ≤ 10^6) — the number of people and the rays' speed.

The next n lines contain the description of people. The i-th of these lines contains three integers x_{i}, v_{i} and t_{i} (0 < x_{i} < 10^6, 1 ≤ v_{i} < s, 1 ≤ t_{i} ≤ 2) — the coordinate of the i-th person on the line, his maximum speed and the direction he will run to (1 is to the left, i.e. in the direction of coordinate decrease, 2 is to the right, i.e. in the direction of coordinate increase), respectively.

It is guaranteed that the points 0 and 10^6 will be reached independently of the bomb's position.

-----Output-----

Print the minimum time needed for both points 0 and 10^6 to be reached.

Your answer is considered correct if its absolute or relative error doesn't exceed 10^{ - 6}....

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

import math
leftpeople = set()
rightpeople = set()

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

def leftinterval(x0, v0, t):
    if x0 / v0 <= t:
        return (0, 10**6)
    if x0 / (vl + v0) > t:
        return (-1, -2)
    leftbound = x0
    rightbound = (vl * vl - v0 * v0) * t + x0 * v0
    rightbound /= vl
    rightbound = int(rightbound)
    if rightbound > 10**6:
        rightbound = 10**6
    return (leftbound, rightbound)
def rightinterval(x0, v0, t):
    if (10**6 - x0) / v0 <= t:
        return (0, 10**6)
    if (10**6 - x0) / (v0 + vl) > t:
        return (-1, -2)
    rightbound = x0
    leftbound = v0 * x0 + (10**6) * (vl - v0) - t * (vl * vl - v0 * v0)
    leftbound /= vl
    leftbound = math.ceil(leftbound)
    if(leftbound < 0):
        leftbound = 0
    return (leftbound, rightbound)

def check(t):
    events = []
    for item in leftpeople:
        temp = leftinterval(item[0], item[1], t)
        if(temp[0] > temp[1]):
            continue
        events.append((temp[0], 0, 0))
        events.append((temp[1], 1, 0))
        if(temp[1] - temp[0] == 10**6):
            break
    for item in rightpeople:
        temp = rightinterval(item[0], item[1], t)
        if(temp[0] > temp[1]):
            continue
        events.append((temp[0], 0, 1))
        events.append((temp[1], 1, 1))
        if(temp[1] - temp[0] == 10**6):
            break
    events.sort()
    opened = [0, 0]
    for item in events:
        color = item[2]
        action = item[1]
        if action == 0:
            if opened[(color + 1) % 2] > 0:
                return True
            opened[color] += 1
        else:
            opened[color] -= 1
    return False

for i in range(n):
    a, b, c = list(map(int, input().split()))
    if c == 1:
        leftpeople.add((a, b))
    if c == 2:
        rightpeople.add((a, b))

l = 0
r = 1e9
for i in range(50):
    m = (l + r) / 2
    if(check(m)):
        r = m
    else:
        l = m

print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/834/A:
[Image]

Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption.

Spinners in Sweetland have the form of V-shaped pieces of caramel. Each spinner can, well, spin around an invisible magic axis. At a specific point in time, a spinner can take 4 positions shown below (each one rotated 90 degrees relative to the previous, with the fourth one followed by the first one):

 [Image]

After the spinner was spun, it starts its rotation, which is described by a following algorithm: the spinner maintains its position for a second then majestically switches to the next position in clockwise or counter-clockwise order, depending on the direction the spinner was spun in.

Slastyona managed to have spinner rotating for exactly n seconds. Being fascinated by elegance of the process, she completely forgot the direction the spinner was spun in! Lucky for her, she managed to recall the starting position, and wants to deduct the direction given the information she knows. Help her do this.

-----Input-----

There are two characters in the first string – the starting and the ending position of a spinner. The position is encoded with one of the following characters: v (ASCII code 118, lowercase v), < (ASCII code 60), ^ (ASCII code 94) or > (ASCII code 62) (see the picture above for reference). Characters are separated by a single space.

In the second strings, a single number n is given (0 ≤ n ≤ 10^9) – the duration of the rotation.

It is guaranteed that the ending position of a spinner is a result of a n second spin in any of the directions, assuming the given starting position.

-----Output-----

Output cw, if the direction is clockwise, ccw – if counter-clockwise, and undefined otherwise.

-----Examples-----
Input
^ >
1

Output
cw

Input
< ^
3

Output
ccw

Input
^ v
6

Output
undefined

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

a = ['v', '<', '^', '>']
s, e = input().split()
n = int(input())
l = a.index(s)
r = l
n = n % 4
for i in range(n):
    if l == 0: l = 3
    else: l -= 1
    if r == 3: r = 0
    else: r += 1
if a[l] == e and a[r] == e:
    print('undefined')
elif a[l] == e:
    print('ccw')
elif a[r] == e:
    print('cw')