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

It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in.

There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously.

For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed.

Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened.

-----Input-----

Two integers are given in the first string: the number of guests n and the number of guards k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ 26).

In the second string, n uppercase English letters s_1s_2... s_{n} are given, where s_{i} is the entrance used by the i-th guest.

-----Output-----

Output «YES» if at least one door was unguarded during some time, and «NO» otherwise.

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

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

Output
NO

Input
5 1
ABABB

Output
YES

-----Note-----

In the first sample case, the door A is opened right before the first...

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, k = rint()
s = input()
sl = {}
for i in range(len(s)):
    if not s[i] in sl:
        sl[s[i]] = [i,i]
    else:
        sl[s[i]][1] = i
cnt = 0
for i in range(len(s)):
    if sl[s[i]][0] == i:
        cnt+=1
    if cnt > k:
        print("YES")
        return
    if sl[s[i]][1] == i:
        cnt-=1

print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/835/A:
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v_1 milliseconds and has ping t_1 milliseconds. The second participant types one character in v_2 milliseconds and has ping t_2 milliseconds.

If connection ping (delay) is t milliseconds, the competition passes for a participant as follows:   Exactly after t milliseconds after the start of the competition the participant receives the text to be entered.  Right after that he starts to type it.  Exactly t milliseconds after he ends typing all the text, the site receives information about it.

The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.

Given the length of the text and the information about participants, determine the result of the game.

-----Input-----

The first line contains five integers s, v_1, v_2, t_1, t_2 (1 ≤ s, v_1, v_2, t_1, t_2 ≤ 1000) — the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant.

-----Output-----

If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship".

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

Output
First

Input
3 3 1 1 1

Output
Second

Input
4 5 3 1 5

Output
Friendship

-----Note-----

In the first example, information on the success of the first participant comes in 7 milliseconds, of the second participant — in 14 milliseconds. So, the first wins.

In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participant — in 5 milliseconds. So, the second wins.

In the third example, information on the success of the first participant comes in 22...

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

s,v1,v2,t1,t2 = map(int,input().split())
if s*v1 + 2*t1 < s*v2 + 2*t2:
    print('First')
elif s*v1 + 2*t1 > s*v2 + 2*t2:
    print('Second')
else:
    print('Friendship')


I found an interesting problem on https://codeforces.com/problemset/problem/835/B:
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.

You have to find the minimum number of digits in which these two numbers can differ.

-----Input-----

The first line contains integer k (1 ≤ k ≤ 10^9).

The second line contains integer n (1 ≤ n < 10^100000).

There are no leading zeros in n. It's guaranteed that this situation is possible.

-----Output-----

Print the minimum number of digits in which the initial number and n can differ.

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

Output
1

Input
3
99

Output
0

-----Note-----

In the first example, the initial number could be 12.

In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.

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

from sys import stdin, stdout

k = int(stdin.readline().rstrip())
n = int(stdin.readline().rstrip())

nList = list(map(int,list(str(n))))

nList.sort()
currentSum = sum(nList)

i=0
while currentSum<k:
    currentSum+=(9-nList[i])
    i+=1

print(i)


I found an interesting problem on https://codeforces.com/problemset/problem/835/C:
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (x_{i}, y_{i}), a maximum brightness c, equal for all stars, and an initial brightness s_{i} (0 ≤ s_{i} ≤ c).

Over time the stars twinkle. At moment 0 the i-th star has brightness s_{i}. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 ≤ c, and 0, otherwise.

You want to look at the sky q times. In the i-th time you will look at the moment t_{i} and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x_1i, y_1i) and the upper right — (x_2i, y_2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.

A star lies in a rectangle if it lies on its border or lies strictly inside it.

-----Input-----

The first line contains three integers n, q, c (1 ≤ n, q ≤ 10^5, 1 ≤ c ≤ 10) — the number of the stars, the number of the views and the maximum brightness of the stars.

The next n lines contain the stars description. The i-th from these lines contains three integers x_{i}, y_{i}, s_{i} (1 ≤ x_{i}, y_{i} ≤ 100, 0 ≤ s_{i} ≤ c ≤ 10) — the coordinates of i-th star and its initial brightness.

The next q lines contain the views description. The i-th from these lines contains five integers t_{i}, x_1i, y_1i, x_2i, y_2i (0 ≤ t_{i} ≤ 10^9, 1 ≤ x_1i < x_2i ≤ 100, 1 ≤ y_1i < y_2i ≤ 100) — the moment of the i-th view and the coordinates of the viewed rectangle.

-----Output-----

For each view print the total brightness of the viewed stars.

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

Output
3
0
3

Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51

Output
3
3
5
0

-----Note-----

Let's consider the first example.

At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.

At the second view, you can see only the second star. At moment 0 its brightness is...

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

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

stars = [ list( map(int,input().split()) ) for i in range(n)]
queries = [ list( map(int,input().split()) ) for i in range(q)]

prec = [[[0 for y in range(101)]for x in range(101)] for i in range(c+1)] #0, c
for x, y, s in stars:
  for t in range(c+1):
    prec[t][x][y] += s+t if s+t <= c else s+t-(c+1)

for s in range(len(prec)):
  for x in range(len(prec[s])):
    for y in range(len(prec[s][x])):
      if x and y:
        prec[s][x][y] += prec[s][x-1][y]+prec[s][x][y-1]-prec[s][x-1][y-1]

for t, x1, y1, x2, y2 in queries:
  s = t%(c+1)
  res = ( prec[s][x2][y2]-prec[s][x1-1][y2]-prec[s][x2][y1-1]+prec[s][x1-1][y1-1] )
  print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/835/D:
Palindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes.

A string is 1-palindrome if and only if it reads the same backward as forward.

A string is k-palindrome (k > 1) if and only if:   Its left half equals to its right half.  Its left and right halfs are non-empty (k - 1)-palindromes.

The left half of string t is its prefix of length ⌊|t| / 2⌋, and right half — the suffix of the same length. ⌊|t| / 2⌋ denotes the length of string t divided by 2, rounded down.

Note that each substring is counted as many times as it appears in the string. For example, in the string "aaa" the substring "a" appears 3 times.

-----Input-----

The first line contains the string s (1 ≤ |s| ≤ 5000) consisting of lowercase English letters.

-----Output-----

Print |s| integers — palindromic characteristics of string s.

-----Examples-----
Input
abba

Output
6 1 0 0

Input
abacaba

Output
12 4 1 0 0 0 0

-----Note-----

In the first example 1-palindromes are substring «a», «b», «b», «a», «bb», «abba», the substring «bb» is 2-palindrome. There are no 3- and 4-palindromes here.

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

class HString:
	def __init__(self, string, base=257, modulo=1000000007):
		self.__base, self.__modulo = base, modulo
		self.__prefix_hash, self.__base_pow, self.__size = [], [1], 0

		self += string

	def __add__(self, string):
		for ch in string:
			self.__base_pow.append((self.__base_pow[-1] * self.__base) % self.__modulo)
			if self.__size == 0: self.__prefix_hash.append(ord(ch))
			else: self.__prefix_hash.append((self.__prefix_hash[-1] * self.__base + ord(ch)) % self.__modulo)
			self.__size += 1
		return self

	def size(self): return self.__size

	def getModulo(self): return self.__modulo

	def getHashValue(self, st, en):
		value = self.__prefix_hash[en]
		if st > 0:
			value -= ((self.__prefix_hash[st-1] * self.__base_pow[en-st+1]) % self.__modulo)
			if value < 0: value += self.__modulo
		return value

def palindromic_characteristics(s):
	n, org, rev = len(s), HString(s), HString(s[::-1])
	palindrome_level = [[0 for _ in range(n)] for _ in range(n)]
	palindrome_level_count = [0 for _ in range(n + 1)]

	i, j = 0, 0
	while i < n:
		j = i
		while j < n:
			if org.getHashValue(i, j) == rev.getHashValue(n-1-j, n-1-i):
				mid = (i + j) // 2 + (i + j) % 2
				if i > mid-1: palindrome_level[i][j] = 1
				else: palindrome_level[i][j] = palindrome_level[i][mid-1] + 1
				palindrome_level_count[palindrome_level[i][j]] += 1
			j += 1
		i += 1

	for i in range(n-1, 0, -1): palindrome_level_count[i] += palindrome_level_count[i+1]
	return palindrome_level_count[1:]

s = input()
print(' '.join(map(str, palindromic_characteristics(s))))


I found an interesting problem on https://codeforces.com/problemset/problem/837/A:
You are given a text of single-space separated words, consisting of small and capital Latin letters.

Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.

Calculate the volume of the given text.

-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 200) — length of the text.

The second line contains text of single-space separated words s_1, s_2, ..., s_{i}, consisting only of small and capital Latin letters.

-----Output-----

Print one integer number — volume of text.

-----Examples-----
Input
7
NonZERO

Output
5

Input
24
this is zero answer text

Output
0

Input
24
Harbour Space University

Output
1

-----Note-----

In the first example there is only one word, there are 5 capital letters in it.

In the second example all of the words contain 0 capital letters.

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

import sys

def vol(i):
    ans = 0
    for j in i:
        if ('A'<= j<= 'Z'):
            ans += 1
    return ans

n = input()
gg = input().split()
ans = 0
for i in gg:
    ans = max(ans, vol(i))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/837/B:
The flag of Berland is such rectangular field n × m that satisfies following conditions:

  Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.  Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.  Each color should be used in exactly one stripe.

You are given a field n × m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).

-----Input-----

The first line contains two integer numbers n and m (1 ≤ n, m ≤ 100) — the sizes of the field.

Each of the following n lines consisting of m characters 'R', 'G' and 'B' — the description of the field.

-----Output-----

Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).

-----Examples-----
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG

Output
YES

Input
4 3
BRG
BRG
BRG
BRG

Output
YES

Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB

Output
NO

Input
4 4
RRRR
RRRR
BBBB
GGGG

Output
NO

-----Note-----

The field in the third example doesn't have three parralel stripes.

Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights — 2, 1 and 1.

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

n, m = list(map(int, input().split()))
fl = [input() for i in range(n)]
c1 = fl[0][0]
BOOL = False
for i in range(n):
    if fl[i][0] != c1:
        BOOL = True
        break
if BOOL:
    BOOL = False
    if n % 3 == 0:
        for i in range(n // 3)[:n//3]:
            for j in range(m):
                if fl[i][j] != c1:
                    BOOL = True
        c2 = fl[n//3][0]
        if not BOOL:
            for i in range(n)[n//3:-(n//3)]:
                for j in range(m):
                    if fl[i][j] != c2:
                        BOOL = True
        c3 = fl[-(n//3)][0]
        if not BOOL:
            for i in range(n)[-(n//3):]:
                for j in range(m):
                    if fl[i][j] != c3:
                        BOOL = True
        if c1 == c2 or c2 == c3 or c1 == c3:
            print('NO')
        else:
            if  BOOL:
                print('NO')
            else:
                print('YES')
    else:
        print('NO')
else:
    if m % 3 == 0:
        for i in range(m)[:m//3]:
            for j in range(n):
                if fl[j][i] != c1:
                    BOOL = True
        c2 = fl[0][m//3]
        if not BOOL:
            for i in range(m)[m//3:-(m//3)]:
                for j in range(n):
                    if fl[j][i] != c2:
                        BOOL = True
        c3 = fl[0][-(m//3)]
        if not BOOL:
            for i in range(m)[-(m//3):]:
                for j in range(n):
                    if fl[j][i] != c3:
                        BOOL = True
        if c1 == c2 or c2 == c3 or c1 == c3:
            print('NO')
        else:
            if  BOOL:
                print('NO')
            else:
                print('YES')
    else:
        print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/837/C:
One very important person has a piece of paper in the form of a rectangle a × b.

Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size x_{i} × y_{i}. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).

A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?

-----Input-----

The first line contains three integer numbers n, a and b (1 ≤ n, a, b ≤ 100).

Each of the next n lines contain two numbers x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ 100).

-----Output-----

Print the largest total area that can be occupied by two seals. If you can not select two seals, print 0.

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

Output
4

Input
4 10 9
2 3
1 1
5 10
9 11

Output
56

Input
3 10 10
6 6
7 7
20 5

Output
0

-----Note-----

In the first example you can rotate the second seal by 90 degrees. Then put impression of it right under the impression of the first seal. This will occupy all the piece of paper.

In the second example you can't choose the last seal because it doesn't fit. By choosing the first and the third seals you occupy the largest area.

In the third example there is no such pair of seals that they both can fit on a piece of paper.

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

n, a, b = list(map(int, input().split(' ')))
seals = []
for x in range(n):
    seals.append(list(map(int, input().split(' '))))
maxt = 0
ls = [a, b]
def condition(x, y):
    for i in [0, 1]:
        for j in [0, 1]:
            for k in [0, 1]:
                if x[i]+y[j] <= ls[k] and x[1-i] <= ls[1-k] and y[1-j] <= ls[1-k]:
                    return True
    return False
for x in seals:
    for y in seals:
        if x is not y and condition(x, y):
            total = x[0]*x[1] + y[0]*y[1]
            maxt = max(maxt, total)
print(maxt)


I found an interesting problem on https://codeforces.com/problemset/problem/837/E:
Vasya is studying number theory. He has denoted a function f(a, b) such that:  f(a, 0) = 0;  f(a, b) = 1 + f(a, b - gcd(a, b)), where gcd(a, b) is the greatest common divisor of a and b.

Vasya has two numbers x and y, and he wants to calculate f(x, y). He tried to do it by himself, but found out that calculating this function the way he wants to do that might take very long time. So he decided to ask you to implement a program that will calculate this function swiftly.

-----Input-----

The first line contains two integer numbers x and y (1 ≤ x, y ≤ 10^12).

-----Output-----

Print f(x, y).

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

Output
3

Input
6 3

Output
1

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

def gcd(a,b):
    #print(a,b)
    if b == 0:return a
    return gcd(b,a%b)
def kmm(a,b):
    return a*b//gcd(a,b)
a,b = list(map(int,input().split()))
t = 0
while b > 0:
    divi=[]
    for i in range(1,int(a**0.5)+1):
        if a%i == 0:
            divi.append(i)
            divi.append(a//i)
    divi.pop(0)
    mods = []
    for i in divi:
        mods.append(b%i)
    m = min(mods)
    #km = 1
    t += m
    b -= m
    b2 = b
    b //= gcd(a,b)
    a //= gcd(a,b2)
    #print(a,b)
    if a == 1:
        t+=b
        break
print(t)


I found an interesting problem on https://codeforces.com/problemset/problem/837/F:
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that y_{i} is equal to the sum of first i elements of array x (0 ≤ i ≤ m).

You have an infinite sequence of arrays A^0, A^1, A^2..., where A^0 is given in the input, and for each i ≥ 1 A^{i} = p(A^{i} - 1). Also you have a positive integer k. You have to find minimum possible i such that A^{i} contains a number which is larger or equal than k.

-----Input-----

The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 10^18). n is the size of array A^0.

The second line contains n integers A^0_0, A^0_1... A^0_{n} - 1 — the elements of A^0 (0 ≤ A^0_{i} ≤ 10^9). At least two elements of A^0 are positive.

-----Output-----

Print the minimum i such that A^{i} contains a number which is larger or equal than k.

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

Output
1

Input
3 6
1 1 1

Output
2

Input
3 1
1 0 1

Output
0

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

from sys import stdin, stdout
from math import factorial
from math import log10

def check(pw, values, k):
    n = len(values)

    matr = [[0 for i in range(n)] for j in range(n)]
    res = [[0 for i in range(n)] for j in range(n)]
    pp = [[0 for i in range(n)] for j in range(n)]

    for i in range(n):
        for j in range(n):
            matr[i][j] = int(i >= j)

    for i in range(n):
        res[i][i] = 1

    while pw:
        if pw & 1:
            for i in range(n):
                for j in range(n):
                    pp[i][j] = 0

            for i in range(n):
                for j in range(n):
                    for z in range(n):
                        pp[i][j] += res[i][z] * matr[z][j]

            for i in range(n):
                for j in range(n):
                    res[i][j] = pp[i][j]

        for i in range(n):
            for j in range(n):
                pp[i][j] = 0

        for i in range(n):
            for j in range(n):
                for z in range(n):
                    pp[i][j] += matr[i][z] * matr[z][j]

        for i in range(n):
            for j in range(n):
                matr[i][j] = pp[i][j]

        pw >>= 1

    ans = 0
    for i in range(n):
        ans += values[i] * res[i][0]

    return ans >= k

def stupid(values, n, k):
    ans = values[:]

    if max(ans) >= k:
        return 0

    cnt = 0
    while ans[-1] < k:
        for i in range(1, n):
            ans[i] += ans[i - 1]

        cnt += 1
        q = ans[-1]

    return cnt

def clever(values, n, k):
    if max(values) >= k:
        return 0

    l, r = 0, 10 ** 18 + 100

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

        if check(m, values, k):
            r = m
        else:
            l = m

    return r

def main():
    n, k = map(int, stdin.readline().split())
    values = list(map(int, stdin.readline().split()))[::-1]

    while not...


I found an interesting problem on https://codeforces.com/problemset/problem/838/D:
There is an airplane which has n rows from front to back. There will be m people boarding this airplane.

This airplane has an entrance at the very front and very back of the plane.

Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.

When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.

Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 10^9 + 7.

-----Input-----

The first line of input will contain two integers n, m (1 ≤ m ≤ n ≤ 1 000 000), the number of seats, and the number of passengers, respectively.

-----Output-----

Print a single number, the number of ways, modulo 10^9 + 7.

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

Output
128

-----Note-----

Here, we will denote a passenger by which seat they were assigned, and which side they came from (either "F" or "B" for front or back, respectively).

For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.

One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat.

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

mod = 1000000007
def power(a, p):
    res = 1
    while p > 0:
        if p % 2 == 1:
            res = (res * a) % mod
        a = (a * a) % mod
        p //= 2
    return res
n, m = map(int, input().split())
n += 1
res = (power(n * 2, m - 1)) * (n - m) * 2
print(res % mod)


I found an interesting problem on https://codeforces.com/problemset/problem/839/A:
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.

At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds a_{i} candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.

Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).

Print -1 if she can't give him k candies during n given days.

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).

The second line contains n integers a_1, a_2, a_3, ..., a_{n} (1 ≤ a_{i} ≤ 100).

-----Output-----

If it is impossible for Arya to give Bran k candies within n days, print -1.

Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.

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

Output
2
Input
3 17
10 10 10

Output
3
Input
1 9
10

Output
-1

-----Note-----

In the first sample, Arya can give Bran 3 candies in 2 days.

In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.

In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.

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

n, m = list(map(int, input().split()))
z = list(map(int, input().split()))
ans = 0
ctr = 0
left = 0
while ctr < m:
    if ans >= n:
        print(-1)
        return
    else:
        z[ans] += left
        ctr += min(8, z[ans])
        left = z[ans] - min(8, z[ans])
    ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/839/B:
Daenerys Targaryen has an army consisting of k groups of soldiers, the i-th group contains a_{i} soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has n rows, each of them has 8 seats. We call two seats neighbor, if they are in the same row and in seats {1, 2}, {3, 4}, {4, 5}, {5, 6} or {7, 8}.

 [Image] A row in the airplane

Daenerys Targaryen wants to place her army in the plane so that there are no two soldiers from different groups sitting on neighboring seats.

Your task is to determine if there is a possible arranging of her army in the airplane such that the condition above is satisfied.

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 10000, 1 ≤ k ≤ 100) — the number of rows and the number of groups of soldiers, respectively.

The second line contains k integers a_1, a_2, a_3, ..., a_{k} (1 ≤ a_{i} ≤ 10000), where a_{i} denotes the number of soldiers in the i-th group.

It is guaranteed that a_1 + a_2 + ... + a_{k} ≤ 8·n.

-----Output-----

If we can place the soldiers in the airplane print "YES" (without quotes). Otherwise print "NO" (without quotes).

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

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

Output
YES

Input
1 2
7 1

Output
NO

Input
1 2
4 4

Output
YES

Input
1 4
2 2 1 2

Output
YES

-----Note-----

In the first sample, Daenerys can place the soldiers like in the figure below:

 [Image]

In the second sample, there is no way to place the soldiers in the plane since the second group soldier will always have a seat neighboring to someone from the first group.

In the third example Daenerys can place the first group on seats (1, 2, 7, 8), and the second group an all the remaining seats.

In the fourth example she can place the first two groups on seats (1, 2) and (7, 8), the third group on seats (3), and the fourth group on seats (5, 6).

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

n, m = list(map(int, input().split()))
z = list(map(int, input().split()))
h = z[:]
double = 2 * n
four = n
jj = []
for i in range(len(h)):
    while four > 0 and h[i] >= 4:
        h[i] -= 4
        four -= 1
    if (h[i] != 0):
        jj.append(h[i])
ss = []
for i in range(len(jj)):
    while four > 0 and jj[i] >= 3:
        jj[i] -= 3
        four -= 1
    if jj[i] != 0:
        ss.append(jj[i])

tt = []
for i in range(len(ss)):
    while double > 0 and ss[i] >= 2:
        ss[i] -= 2
        double -= 1
    if ss[i]:
        tt.append(ss[i])

places = double + four * 2
gg = []
for i in range(len(tt)):
    while four > 0 and tt[i] >= 2:
        tt[i] -= 2
        places -= 1
        four -= 1
    if tt[i]:
        gg.append(tt[i])
if (sum(gg) <= places):
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/839/C:
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.

Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities.

Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities.

Then n - 1 lines follow. The i-th line of these lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — the cities connected by the i-th road.

It is guaranteed that one can reach any city from any other by the roads.

-----Output-----

Print a number — the expected length of their journey. The journey starts in the city 1.

Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$.

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

Output
1.500000000000000

Input
5
1 2
1 3
3 4
2 5

Output
2.000000000000000

-----Note-----

In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.

In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.

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

def dfs(start):
    visited = [0, True] + [False]*(n-1)
    stack = [(x, 1, 1/len(tree[start])) for x in tree[start]]
    while stack:
        v, l, p = stack.pop()
        if leafs[v]:
            L.append(l*p)
        if not visited[v]:
            visited[v] = True
            for u in tree[v]:
                if not visited[u]:
                    stack.append((u, l+1, p/(len(tree[v])-1)))

n = int(input())
tree = {x: [] for x in range(1, n+1)}
L = []
for _ in range(n-1):
    u, v = list(map(int, input().split()))
    tree[u].append(v)
    tree[v].append(u)
leafs = [False, True] + [len(tree[x]) == 1 for x in range(2, n+1)]
dfs(1)
print(sum(L))

"""
7
1 2
1 3
1 4
4 7
2 6
2 5
"""


I found an interesting problem on https://codeforces.com/problemset/problem/839/D:
Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers.

He has created a method to know how strong his army is. Let the i-th soldier’s strength be a_{i}. For some k he calls i_1, i_2, ..., i_{k} a clan if i_1 < i_2 < i_3 < ... < i_{k} and gcd(a_{i}_1, a_{i}_2, ..., a_{i}_{k}) > 1 . He calls the strength of that clan k·gcd(a_{i}_1, a_{i}_2, ..., a_{i}_{k}). Then he defines the strength of his army by the sum of strengths of all possible clans.

Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (10^9 + 7).

Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 200000) — the size of the army.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000000) — denoting the strengths of his soldiers.

-----Output-----

Print one integer — the strength of John Snow's army modulo 1000000007 (10^9 + 7).

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

Output
12

Input
4
2 3 4 6

Output
39

-----Note-----

In the first sample the clans are {1}, {2}, {1, 2} so the answer will be 1·3 + 1·3 + 2·3 = 12

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

n = int(input())
MAX = 1000005
mod = 1e9 + 7
po2 = [0]*(n+1)
po2[0] = 1
for v in range(1,n+1):
	po2[v] = (po2[v-1]*2)%mod
a = list(map(int,input().split()))
ta = [0]*MAX
for i in a:
	ta[i] += 1
cnt = [0]*MAX
for i in range(2,MAX):
	for j in range(i,MAX,i):
		cnt[i] += ta[j]
#print(ta[0:5],cnt[0:5])
ans = [0]*MAX
for i in range(MAX-1,0,-1):
	if cnt[i] == 0:
		continue
	ans[i] = (cnt[i]*po2[cnt[i]-1])%mod
	for j in range(i+i,MAX,i):
		ans[i] = (ans[i]+mod-ans[j])%mod
#print(ans[0:5])
endans = 0
for v in range(2,MAX):
	endans = (endans+v*ans[v])%mod
#print(po2)
print(int(endans))


I found an interesting problem on https://codeforces.com/problemset/problem/841/A:
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as s_{i} — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.

-----Input-----

The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.

Next line contains string s — colors of baloons.

-----Output-----

Answer to the task — «YES» or «NO» in a single line.

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

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

Output
YES

Input
6 3
aacaab

Output
NO

-----Note-----

In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.

In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».

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

n, k = map(int, input().split())
s = input()
flag = True
for i in range(n):
    if s.count(s[i]) > k:
        flag = False
if flag:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/841/B:
Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?

-----Input-----

First line of input data contains single integer n (1 ≤ n ≤ 10^6) — length of the array.

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

-----Output-----

Output answer in single line. "First", if first player wins, and "Second" otherwise (without quotes).

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

Output
First

Input
2
2 2

Output
Second

-----Note-----

In first sample first player remove whole array in one move and win.

In second sample first player can't make a move and lose.

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

from sys import stdin, stdout

n = int(stdin.readline().rstrip())
s = list(map(int,stdin.readline().rstrip().split()))
s = [i%2 for i in s]

if sum(s)==0:
    print('Second')
else:
    print('First')


I found an interesting problem on https://codeforces.com/problemset/problem/842/A:
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.

For each two integer numbers a and b such that l ≤ a ≤ r and x ≤ b ≤ y there is a potion with experience a and cost b in the store (that is, there are (r - l + 1)·(y - x + 1) potions).

Kirill wants to buy a potion which has efficiency k. Will he be able to do this?

-----Input-----

First string contains five integer numbers l, r, x, y, k (1 ≤ l ≤ r ≤ 10^7, 1 ≤ x ≤ y ≤ 10^7, 1 ≤ k ≤ 10^7).

-----Output-----

Print "YES" without quotes if a potion with efficiency exactly k can be bought in the store and "NO" without quotes otherwise.

You can output each of the letters in any register.

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

Output
YES
Input
1 5 6 10 1

Output
NO

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

3

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

l, r, x, y, k = read_ints()

if x * k <= r and y * k >= l and l // k + (l % k > 0) <= r // k:
	print('YES')
else:
	print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/842/B:
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.

The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is r_{i}, and the center is given as a pair (x_{i}, y_{i}).

Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.

-----Input-----

First string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust.

Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 10^5).

Each of next n lines contains three integer numbers x_{i}, y_{i} and r_{i} ( - 500 ≤ x_{i}, y_{i} ≤ 500, 0 ≤ r_{i} ≤ 500), where x_{i} and y_{i} are coordinates of the center of i-th peace of sausage, r_{i} — radius of i-th peace of sausage.

-----Output-----

Output the number of pieces of sausage that lay on the crust.

-----Examples-----
Input
8 4
7
7 8 1
-7 3 2
0 2 1
0 -2 2
-3 -3 1
0 6 2
5 3 1

Output
2

Input
10 8
4
0 0 9
0 0 10
1 0 1
1 0 2

Output
0

-----Note-----

Below is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.

 [Image]

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

r, d = list(map(int, input().split()))
n = int(input())
counter = 0
for i in range(n):
    x,y,r_k = list(map(int, input().split()))
    if (x**2 + y**2)**(1.0/2.0) - r_k >= r-d and (x**2 + y**2)**(1.0/2.0) + r_k <= r:
        counter += 1
print(counter)


I found an interesting problem on https://codeforces.com/problemset/problem/842/C:
Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex 1. There is an integer number written on each vertex of the tree; the number written on vertex i is equal to a_{i}.

Ilya believes that the beauty of the vertex x is the greatest common divisor of all numbers written on the vertices on the path from the root to x, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to 0 or leave all vertices unchanged. Now for each vertex Ilya wants to know the maximum possible beauty it can have.

For each vertex the answer must be considered independently.

The beauty of the root equals to number written on it.

-----Input-----

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

Next line contains n integer numbers a_{i} (1 ≤ i ≤ n, 1 ≤ a_{i} ≤ 2·10^5).

Each of next n - 1 lines contains two integer numbers x and y (1 ≤ x, y ≤ n, x ≠ y), which means that there is an edge (x, y) in the tree.

-----Output-----

Output n numbers separated by spaces, where i-th number equals to maximum possible beauty of vertex i.

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

Output
6 6

Input
3
6 2 3
1 2
1 3

Output
6 6 6

Input
1
10

Output
10

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

from sys import stdin
from fractions import gcd

n = int(stdin.readline().strip())
v = list(map(int, stdin.readline().strip().split()))

adj = [[] for _ in range(n)]
for _ in range(n-1):
    x, y = list(map(int, stdin.readline().strip().split()))
    adj[x-1].append(y-1)
    adj[y-1].append(x-1)

root_divisors = []
cnt = [0]*200001
d = 1
while d*d <= v[0]:
    if v[0] % d == 0:
        root_divisors.append(d)
        cnt[d] += 1
        if v[0]//d != d:
            root_divisors.append(v[0]//d)
            cnt[v[0]//d] += 1
    d += 1
s = [0]
visited = [False]*n
visited[0] = True
level = [1]*n
res1 = [0]*n
res2 = [0]*n
res1[0] = v[0]
d = 1
while s:
    x = s[-1]
    any_more = False
    while adj[x]:
        y = adj[x].pop()
        if not visited[y]:
            visited[y] = True
            any_more = True
            s.append(y)
            level[y] = level[x]+1
            res2[y] = gcd(res2[x], v[y])
            for d in root_divisors:
                if v[y] % d == 0:
                    cnt[d] += 1
                if cnt[d] == level[y] or cnt[d] == level[y]-1:
                    res1[y] = max(res1[y], res2[y], d)
            break
    if not any_more:
        s.pop()
        for d in root_divisors:
            if v[x] % d == 0:
                cnt[d] -= 1

print(' '.join(list(map(str, res1))))


I found an interesting problem on https://codeforces.com/problemset/problem/844/A:
Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.

String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

-----Input-----

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s).

Second line of input contains integer k (1 ≤ k ≤ 26).

-----Output-----

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

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

Output
0

Input
yahoo
5

Output
1

Input
google
7

Output
impossible

-----Note-----

In the first test case string contains 6 different letters, so we don't need to change anything.

In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.

In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

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

def sol():
	s = input()
	k = int(input())
	if k > len(s):
		print("impossible")
	else:
		s = set(s)
		print(max(0, k - len(s)))

sol()


I found an interesting problem on https://codeforces.com/problemset/problem/844/B:
You are given n × m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that:

  All cells in a set have the same color.  Every two cells in a set share row or column.

-----Input-----

The first line of input contains integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns correspondingly.

The next n lines of input contain descriptions of rows. There are m integers, separated by spaces, in each line. The number equals 0 if the corresponding cell is colored white and equals 1 if the corresponding cell is colored black.

-----Output-----

Output single integer  — the number of non-empty sets from the problem description.

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

Output
1

Input
2 3
1 0 1
0 1 0

Output
8

-----Note-----

In the second example, there are six one-element sets. Additionally, there are two two-element sets, the first one consists of the first and the third cells of the first row, the second one consists of the first and the third cells of the second row. To sum up, there are 8 sets.

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

n, m = list(map(int, input().split()))
arr = [[0 for i in range(m)] for i in range(n)]
for i in range(n):
	arr[i] = list(map(int, input().split()))
ans = n * m
for i in range(n):
	c0 = 0
	c1 = 0
	for j in range(m):
		if arr[i][j] == 1:
			c1 += 1
		else:
			c0 += 1
	ans += max(0, 2 ** (c1) - c1 - 1)
	ans += max(0, 2 ** (c0) - c0 - 1)
for i in range(m):
	c0 = 0
	c1 = 0
	for j in range(n):
		if arr[j][i] == 1:
			c1 += 1
		else:
			c0 += 1
	ans += max(0, 2 ** (c1) - c1 - 1)
	ans += max(0, 2 ** (c0) - c0 - 1)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/845/A:
Berland annual chess tournament is coming!

Organizers have gathered 2·n chess players who should be divided into two teams with n people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.

Thus, organizers should divide all 2·n players into two teams with n people each in such a way that the first team always wins.

Every chess player has its rating r_{i}. It is known that chess player with the greater rating always wins the player with the lower rating. If their ratings are equal then any of the players can win.

After teams assignment there will come a drawing to form n pairs of opponents: in each pair there is a player from the first team and a player from the second team. Every chess player should be in exactly one pair. Every pair plays once. The drawing is totally random.

Is it possible to divide all 2·n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing?

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 100).

The second line contains 2·n integers a_1, a_2, ... a_2n (1 ≤ a_{i} ≤ 1000).

-----Output-----

If it's possible to divide all 2·n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing, then print "YES". Otherwise print "NO".

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

Output
YES

Input
1
3 3

Output
NO

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

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

if a[len(a)//2 -1] < a[len(a)//2]:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/845/B:
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky.

The ticket is considered lucky if the sum of first three digits equals to the sum of last three digits.

-----Input-----

You are given a string consisting of 6 characters (all characters are digits from 0 to 9) — this string denotes Luba's ticket. The ticket can start with the digit 0.

-----Output-----

Print one number — the minimum possible number of digits Luba needs to replace to make the ticket lucky.

-----Examples-----
Input
000000

Output
0

Input
123456

Output
2

Input
111000

Output
1

-----Note-----

In the first example the ticket is already lucky, so the answer is 0.

In the second example Luba can replace 4 and 5 with zeroes, and the ticket will become lucky. It's easy to see that at least two replacements are required.

In the third example Luba can replace any zero with 3. It's easy to see that at least one replacement is required.

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

l=list(input())
a=[]
b=[]
for i in range(3):
    a.append(int(l[i]))
for i in range(3,6):
    b.append(int(l[i]))
a.sort()
b.sort()
s1=sum(a)
s2=sum(b)

if(s1==s2):
    print(0)
else:
    if(s1<s2):
        diff=s2-s1
        a.sort()
        b.sort(reverse=True)
        c=[]
        t=0
        for i in range(3):
            c.append(9-a[i])
            c.append(b[i])
        c.sort(reverse=True)
        for i in range(6):
            t=t+c[i]
            if(t>=diff):
                break
        print(i+1)
    else:

        diff=s1-s2
        t=0
        a.sort(reverse=True)
        b.sort()
        c=[]
        for i in range(3):
            c.append(a[i])
            c.append(9-b[i])
        c.sort(reverse=True)
        for i in range(6):

            t=t+c[i]
            if(t>=diff):
                break
        print(i+1)


I found an interesting problem on https://codeforces.com/problemset/problem/845/C:
Polycarp is a great fan of television.

He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment l_{i} and ends at moment r_{i}.

Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV.

Polycarp wants to check out all n shows. Are two TVs enough to do so?

-----Input-----

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

Each of the next n lines contains two integers l_{i} and r_{i} (0 ≤ l_{i} < r_{i} ≤ 10^9) — starting and ending time of i-th show.

-----Output-----

If Polycarp is able to check out all the shows using only two TVs then print "YES" (without quotes). Otherwise, print "NO" (without quotes).

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

Output
YES

Input
4
1 2
2 3
2 3
1 2

Output
NO

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

def lol(a):
    c = 0
    for x in a:
        if x[1]==1:
            c+=1
        else:
            c-=1
        if c>=3:
            return 0
    return 1

n = int(input())
a = []
for _ in range(n):
    x,y = map(int,input().split())
    a.append([x,1])
    a.append([y,2])
a = sorted(a)
print("YES" if lol(a) else "NO")


I found an interesting problem on https://codeforces.com/problemset/problem/845/D:
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types.

  speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type);  overtake is allowed: this sign means that after some car meets it, it can overtake any other car;  no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign);  no overtake allowed: some car can't overtake any other car after this sign.

Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well.

In the beginning of the ride overtake is allowed and there is no speed limit.

You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types:

  Polycarp changes the speed of his car to specified (this event comes with a positive integer number);  Polycarp's car overtakes the other car;  Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer);  Polycarp's car goes past the "overtake is allowed" sign;  Polycarp's car goes past the "no speed limit";  Polycarp's car goes past the "no overtake allowed";

It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).

After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?

-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 2·10^5) — number of...

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


I found an interesting problem on https://codeforces.com/problemset/problem/845/E:
The capital of Berland looks like a rectangle of size n × m of the square blocks of same size.

Fire!

It is known that k + 1 blocks got caught on fire (k + 1 ≤ n·m). Those blocks are centers of ignition. Moreover positions of k of these centers are known and one of these stays unknown. All k + 1 positions are distinct.

The fire goes the following way: during the zero minute of fire only these k + 1 centers of ignition are burning. Every next minute the fire goes to all neighbouring blocks to the one which is burning. You can consider blocks to burn for so long that this time exceeds the time taken in the problem. The neighbouring blocks are those that touch the current block by a side or by a corner.

Berland Fire Deparment wants to estimate the minimal time it takes the fire to lighten up the whole city. Remember that the positions of k blocks (centers of ignition) are known and (k + 1)-th can be positioned in any other block.

Help Berland Fire Department to estimate the minimal time it takes the fire to lighten up the whole city.

-----Input-----

The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^9, 1 ≤ k ≤ 500).

Each of the next k lines contain two integers x_{i} and y_{i} (1 ≤ x_{i} ≤ n, 1 ≤ y_{i} ≤ m) — coordinates of the i-th center of ignition. It is guaranteed that the locations of all centers of ignition are distinct.

-----Output-----

Print the minimal time it takes the fire to lighten up the whole city (in minutes).

-----Examples-----
Input
7 7 3
1 2
2 1
5 5

Output
3

Input
10 5 1
3 3

Output
2

-----Note-----

In the first example the last block can have coordinates (4, 4).

In the second example the last block can have coordinates (8, 3).

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

import sys
from collections import Counter
from operator import itemgetter
from heapq import heappop, heappush

n, m, k = list(map(int, input().split()))
points = [list(map(int, line.split())) for line in sys.stdin]
pts_sorted_x = sorted(points)
pts_sorted_y = sorted(points, key=itemgetter(1, 0))
inf = 10**9+1
OK = (inf, inf)

def solve2(imos, t):
    acc, cur = 0, 0

    for k in sorted(imos.keys()):
        if t < k:
            break
        if acc <= 0 and cur+1 < k or acc + imos[k] <= 0:
            acc = 0
            break
        acc += imos[k]

    return acc <= 0

def add_imos(imos, x, y):
    imos[x] += y
    if imos[x] == 0:
        del imos[x]

def solve(t, px=-1, py=-1):
    set_x = {1, n}
    set_y = {1, m}

    for x, y in points:
        set_x.update((max(1, x-t), max(1, x-t-1), min(n, x+t), min(n, x+t+1)))
        set_y.update((max(1, y-t), max(1, y-t-1), min(m, y+t), min(m, y+t+1)))

    ans_x = ans_y = inf
    pi, imos, hq = 0, Counter(), []
    if px != -1:
        imos[py] += 1
        imos[py+t*2+1] -= 1

    for cx in sorted(set_x):
        while hq and hq[0][0] < cx:
            add_imos(imos, hq[0][1], -1)
            add_imos(imos, hq[0][2], +1)
            heappop(hq)
        while pi < k and pts_sorted_x[pi][0]-t <= cx <= pts_sorted_x[pi][0]+t:
            x, y = pts_sorted_x[pi]
            add_imos(imos, max(1, y-t), 1)
            add_imos(imos, y+t+1, -1)
            heappush(hq, (x+t, max(1, y-t), y+t+1))
            pi += 1

        if solve2(imos, m):
            ans_x = cx
            break

    pi = 0
    imos.clear()
    hq.clear()
    if px != -1:
        imos[px] += 1
        imos[px+t*2+1] -= 1

    for cy in sorted(set_y):
        while hq and hq[0][0] < cy:
            add_imos(imos, hq[0][1], -1)
            add_imos(imos, hq[0][2], +1)
            heappop(hq)
        while pi < k and pts_sorted_y[pi][1]-t <= cy <= pts_sorted_y[pi][1]+t:
            x, y = pts_sorted_y[pi]
            add_imos(imos, max(1, x-t), 1)
            add_imos(imos, x+t+1, -1)
         ...


I found an interesting problem on https://codeforces.com/problemset/problem/846/A:
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job.

During all his career Hideo has produced n games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero) from his CV to make a better impression on employers. As a result there should be no unsuccessful game which comes right after successful one in his CV.

More formally, you are given an array s_1, s_2, ..., s_{n} of zeros and ones. Zero corresponds to an unsuccessful game, one — to a successful one. Games are given in order they were produced, and Hideo can't swap these values. He should remove some elements from this array in such a way that no zero comes right after one.

Besides that, Hideo still wants to mention as much games in his CV as possible. Help this genius of a man determine the maximum number of games he can leave in his CV.

-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 100).

The second line contains n space-separated integer numbers s_1, s_2, ..., s_{n} (0 ≤ s_{i} ≤ 1). 0 corresponds to an unsuccessful game, 1 — to a successful one.

-----Output-----

Print one integer — the maximum number of games Hideo can leave in his CV so that no unsuccessful game comes after a successful one.

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

Output
3

Input
6
0 1 0 0 1 0

Output
4

Input
1
0

Output
1

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

n = int(input())
a = [int(i) for i in input().split()]
answer = [0] * n
answer[0] = 1

for i in range(1, n):
    if a[i] == 1:
        answer[i] = max(answer) + 1
    else:
        temp_max = 0
        for j in range(i):
            if a[j] == 0 and answer[j] > temp_max:
                temp_max = answer[j]
        answer[i] = temp_max + 1

print(max(answer))


I found an interesting problem on https://codeforces.com/problemset/problem/846/B:
Polycarp takes part in a math show. He is given n tasks, each consists of k subtasks, numbered 1 through k. It takes him t_{j} minutes to solve the j-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order.

By solving subtask of arbitrary problem he earns one point. Thus, the number of points for task is equal to the number of solved subtasks in it. Moreover, if Polycarp completely solves the task (solves all k of its subtasks), he recieves one extra point. Thus, total number of points he recieves for the complete solution of the task is k + 1.

Polycarp has M minutes of time. What is the maximum number of points he can earn?

-----Input-----

The first line contains three integer numbers n, k and M (1 ≤ n ≤ 45, 1 ≤ k ≤ 45, 0 ≤ M ≤ 2·10^9).

The second line contains k integer numbers, values t_{j} (1 ≤ t_{j} ≤ 1000000), where t_{j} is the time in minutes required to solve j-th subtask of any task.

-----Output-----

Print the maximum amount of points Polycarp can earn in M minutes.

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

Output
6

Input
5 5 10
1 2 4 8 16

Output
7

-----Note-----

In the first example Polycarp can complete the first task and spend 1 + 2 + 3 + 4 = 10 minutes. He also has the time to solve one subtask of the second task in one minute.

In the second example Polycarp can solve the first subtask of all five tasks and spend 5·1 = 5 minutes. Also he can solve the second subtasks of two tasks and spend 2·2 = 4 minutes. Thus, he earns 5 + 2 = 7 points in total.

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

n, k, m = list(map(int, input().split()))
t = sorted(map(int, input().split()))
st = sum(t)
res = 0
for x in range(min(m//st,n)+1):
    rem = m - x*st
    r = x*(k+1)
    for i in range(k):
        div = min(rem//t[i], n-x)
        rem -= div*t[i]
        r += div
    res = max(res, r)
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/846/D:
Recently Luba bought a monitor. Monitor is a rectangular matrix of size n × m. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square k × k consisting entirely of broken pixels. She knows that q pixels are already broken, and for each of them she knows the moment when it stopped working. Help Luba to determine when the monitor became broken (or tell that it's still not broken even after all q pixels stopped working).

-----Input-----

The first line contains four integer numbers n, m, k, q (1 ≤ n, m ≤ 500, 1 ≤ k ≤ min(n, m), 0 ≤ q ≤ n·m) — the length and width of the monitor, the size of a rectangle such that the monitor is broken if there is a broken rectangle with this size, and the number of broken pixels.

Each of next q lines contain three integer numbers x_{i}, y_{i}, t_{i} (1 ≤ x_{i} ≤ n, 1 ≤ y_{i} ≤ m, 0 ≤ t_{ ≤ 10}^9) — coordinates of i-th broken pixel (its row and column in matrix) and the moment it stopped working. Each pixel is listed at most once.

We consider that pixel is already broken at moment t_{i}.

-----Output-----

Print one number — the minimum moment the monitor became broken, or "-1" if it's still not broken after these q pixels stopped working.

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

Output
8

Input
3 3 2 5
1 2 2
2 2 1
2 3 5
3 2 10
2 1 100

Output
-1

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

import sys
from operator import itemgetter

n, m, k, q = list(map(int, input().split()))
query = sorted((list(map(int, line.split()))
                for line in sys.stdin), key=itemgetter(2))
times = [q[2] for q in query]

def solve(ti):
    imos = [[0]*(m+1) for _ in range(n+1)]
    for i in range(ti):
        imos[query[i][0]][query[i][1]] += 1

    for i in range(n+1):
        for j in range(m):
            imos[i][j+1] += imos[i][j]
    for j in range(m+1):
        for i in range(n):
            imos[i+1][j] += imos[i][j]
    for i in range(k, n+1):
        for j in range(k, m+1):
            if imos[i][j] - imos[i-k][j] - imos[i][j-k] + imos[i-k][j-k] == k*k:
                return True
    return False

inf = len(times)+1
ok, ng = inf, 0
while abs(ok - ng) > 1:
    mid = (ok + ng) >> 1
    if mid >= k*k and solve(mid):
        ok = mid
    else:
        ng = mid

print(times[ok-1] if ok != inf else -1)


I found an interesting problem on https://codeforces.com/problemset/problem/846/E:
Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment.

Fortunately, chemical laws allow material transformations (yes, chemistry in Berland differs from ours). But the rules of transformation are a bit strange.

Berland chemists are aware of n materials, numbered in the order they were discovered. Each material can be transformed into some other material (or vice versa). Formally, for each i (2 ≤ i ≤ n) there exist two numbers x_{i} and k_{i} that denote a possible transformation: k_{i} kilograms of material x_{i} can be transformed into 1 kilogram of material i, and 1 kilogram of material i can be transformed into 1 kilogram of material x_{i}. Chemical processing equipment in BerSU allows only such transformation that the amount of resulting material is always an integer number of kilograms.

For each i (1 ≤ i ≤ n) Igor knows that the experiment requires a_{i} kilograms of material i, and the laboratory contains b_{i} kilograms of this material. Is it possible to conduct an experiment after transforming some materials (or none)?

-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 10^5) — the number of materials discovered by Berland chemists.

The second line contains n integer numbers b_1, b_2... b_{n} (1 ≤ b_{i} ≤ 10^12) — supplies of BerSU laboratory.

The third line contains n integer numbers a_1, a_2... a_{n} (1 ≤ a_{i} ≤ 10^12) — the amounts required for the experiment.

Then n - 1 lines follow. j-th of them contains two numbers x_{j} + 1 and k_{j} + 1 that denote transformation of (j + 1)-th material (1 ≤ x_{j} + 1 ≤ j, 1 ≤ k_{j} + 1 ≤ 10^9).

-----Output-----

Print YES if it is possible to conduct an experiment. Otherwise print NO.

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

Output
YES

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

Output
NO

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

import sys

# @profile
def main():
    f = sys.stdin
    # f = open('input.txt', 'r')
    # fo = open('log.txt', 'w')
    n = int(f.readline())
    # b = []
    # for i in range(n):
    #    b.append()
    b = list(map(int, f.readline().strip().split(' ')))
    a = list(map(int, f.readline().strip().split(' ')))
    # return
    b = [b[i] - a[i] for i in range(n)]
    c = [[0, 0]]
    for i in range(n - 1):
        line = f.readline().strip().split(' ')
        c.append([int(line[0]), int(line[1])])
    # print(c)
    for i in range(n - 1, 0, -1):
        # print(i)
        fa = c[i][0] - 1
        if b[i] >= 0:
            b[fa] += b[i]
        else:
            b[fa] += b[i] * c[i][1]
            if b[fa] < -1e17:
                print('NO')
                return 0
    # for x in b:
    #    fo.write(str(x) + '\n')
    if b[0] >= 0:
        print('YES')
    else:
        print('NO')

main()


I found an interesting problem on https://codeforces.com/problemset/problem/846/F:
You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed).

-----Input-----

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

-----Output-----

Print one number — the expected number of unique elements in chosen segment.

Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{ - 4} — formally, the answer is correct if $\operatorname{min}(|x - y|, \frac{|x - y|}{x}) \leq 10^{-4}$, where x is jury's answer, and y is your answer.

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

Output
1.500000

Input
2
2 2

Output
1.000000

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

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

lastocc=[0]*1000006
ans=[0]*n
ans[0]=1
lastocc[a[0]]=1

for i in range(1,n):
    ans[i]=ans[i-1]+(i+1-lastocc[a[i]])
    lastocc[a[i]]=i+1

print((2*sum(ans)-n)/(n*n))


I found an interesting problem on https://codeforces.com/problemset/problem/847/D:
A new dog show on TV is starting next week. On the show dogs are required to demonstrate bottomless stomach, strategic thinking and self-preservation instinct. You and your dog are invited to compete with other participants and naturally you want to win!

On the show a dog needs to eat as many bowls of dog food as possible (bottomless stomach helps here). Dogs compete separately of each other and the rules are as follows:

At the start of the show the dog and the bowls are located on a line. The dog starts at position x = 0 and n bowls are located at positions x = 1, x = 2, ..., x = n. The bowls are numbered from 1 to n from left to right. After the show starts the dog immediately begins to run to the right to the first bowl.

The food inside bowls is not ready for eating at the start because it is too hot (dog's self-preservation instinct prevents eating). More formally, the dog can eat from the i-th bowl after t_{i} seconds from the start of the show or later.

It takes dog 1 second to move from the position x to the position x + 1. The dog is not allowed to move to the left, the dog runs only to the right with the constant speed 1 distance unit per second. When the dog reaches a bowl (say, the bowl i), the following cases are possible:  the food had cooled down (i.e. it passed at least t_{i} seconds from the show start): the dog immediately eats the food and runs to the right without any stop,  the food is hot (i.e. it passed less than t_{i} seconds from the show start): the dog has two options: to wait for the i-th bowl, eat the food and continue to run at the moment t_{i} or to skip the i-th bowl and continue to run to the right without any stop.

After T seconds from the start the show ends. If the dog reaches a bowl of food at moment T the dog can not eat it. The show stops before T seconds if the dog had run to the right of the last bowl.

You need to help your dog create a strategy with which the maximum possible number of bowls of food will be eaten in T seconds.

-----Input-----

Two integer...

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

# using the min-heap
from heapq import heappush,heappop
bowels,Time = list(map(int,input().split()))
myLine = [-int(b) for b in input().split()]
gulp = []; eat = 0
for i in range(1,min(bowels+1,Time)):
    while gulp and -gulp[0] >= Time - i:
        # remove the bowel with the highest time penalty
        heappop(gulp)
    # Check if the option is viable
    if -myLine[i-1] < Time:
        # Remove the step penalty and store the remaining
        heappush(gulp,myLine[i-1] + i)
    eat = max(len(gulp),eat)
print (eat)


I found an interesting problem on https://codeforces.com/problemset/problem/847/E:
A game field is a strip of 1 × n square cells. In some cells there are Packmen, in some cells — asterisks, other cells are empty.

Packman can move to neighboring cell in 1 time unit. If there is an asterisk in the target cell then Packman eats it. Packman doesn't spend any time to eat an asterisk.

In the initial moment of time all Packmen begin to move. Each Packman can change direction of its move unlimited number of times, but it is not allowed to go beyond the boundaries of the game field. Packmen do not interfere with the movement of other packmen; in one cell there can be any number of packmen moving in any directions.

Your task is to determine minimum possible time after which Packmen can eat all the asterisks.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 10^5) — the length of the game field.

The second line contains the description of the game field consisting of n symbols. If there is symbol '.' in position i — the cell i is empty. If there is symbol '*' in position i — in the cell i contains an asterisk. If there is symbol 'P' in position i — Packman is in the cell i.

It is guaranteed that on the game field there is at least one Packman and at least one asterisk.

-----Output-----

Print minimum possible time after which Packmen can eat all asterisks.

-----Examples-----
Input
7
*..P*P*

Output
3

Input
10
.**PP.*P.*

Output
2

-----Note-----

In the first example Packman in position 4 will move to the left and will eat asterisk in position 1. He will spend 3 time units on it. During the same 3 time units Packman in position 6 will eat both of neighboring with it asterisks. For example, it can move to the left and eat asterisk in position 5 (in 1 time unit) and then move from the position 5 to the right and eat asterisk in the position 7 (in 2 time units). So in 3 time units Packmen will eat all asterisks on the game field.

In the second example Packman in the position 4 will move to the left and after 2 time units will eat asterisks in positions 3 and 2. Packmen...

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

from sys import stdin, stdout

n = int(stdin.readline())
s = stdin.readline().strip()

mins = []
packs = []

for i in range(len(s)):
    if s[i] == '*':
        mins.append(i)
    elif s[i] == 'P':
        packs.append(i)

l, r = -1, 2 * len(s) + 1
while r - l > 1:
    m = (l + r) >> 1

    test1 = mins[:]
    test2 = packs[:]

    while test2 and test1:
        cnt = m
        pos = test2.pop()

        if pos > test1[-1]:
            while test1 and abs(pos - test1[-1]) <= cnt:
                cnt -= abs(pos - test1[-1])
                pos = test1[-1]
                test1.pop()
        else:
            cntl, cntr = 0, 0

            if abs(test1[-1] - pos) > m:
                break

            lpos = (m + pos - test1[-1]) // 2
            rpos = m - 2 * abs(test1[-1] - pos)

            lb, rb = -1, len(test1)
            while rb - lb > 1:
                mb = (lb + rb) >> 1

                if pos - test1[mb] <= lpos:
                    rb = mb
                else:
                    lb = mb

            cntl = len(test1) - rb

            lb, rb = -1, len(test1)
            while rb - lb > 1:
                mb = (lb + rb) >> 1

                if pos - test1[mb] <= rpos:
                    rb = mb
                else:
                    lb = mb

            cntr = len(test1) - rb

            cnt = max(cntl, cntr)
            while test1 and cnt:
                test1.pop()
                cnt -= 1

    if not test1:
        r = m
    else:
        l = m

stdout.write(str(r))


I found an interesting problem on https://codeforces.com/problemset/problem/847/F:
The elections to Berland parliament are happening today. Voting is in full swing!

Totally there are n candidates, they are numbered from 1 to n. Based on election results k (1 ≤ k ≤ n) top candidates will take seats in the parliament.

After the end of the voting the number of votes for each candidate is calculated. In the resulting table the candidates are ordered by the number of votes. In case of tie (equal number of votes) they are ordered by the time of the last vote given. The candidate with ealier last vote stands higher in the resulting table.

So in the resulting table candidates are sorted by the number of votes (more votes stand for the higher place) and if two candidates have equal number of votes they are sorted by the time of last vote (earlier last vote stands for the higher place).

There is no way for a candidate with zero votes to take a seat in the parliament. So it is possible that less than k candidates will take a seat in the parliament.

In Berland there are m citizens who can vote. Each of them will vote for some candidate. Each citizen will give a vote to exactly one of n candidates. There is no option "against everyone" on the elections. It is not accepted to spoil bulletins or not to go to elections. So each of m citizens will vote for exactly one of n candidates.

At the moment a citizens have voted already (1 ≤ a ≤ m). This is an open election, so for each citizen it is known the candidate for which the citizen has voted. Formally, the j-th citizen voted for the candidate g_{j}. The citizens who already voted are numbered in chronological order; i.e. the (j + 1)-th citizen voted after the j-th.

The remaining m - a citizens will vote before the end of elections, each of them will vote for one of n candidates.

Your task is to determine for each of n candidates one of the three possible outcomes:

  a candidate will be elected to the parliament regardless of votes of the remaining m - a citizens;  a candidate has chance to be elected to the parliament after all n citizens have...

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

class State:
  __slots__ = ['candidate', 'votes', 'last_vote']

  def __init__(self, cand, votes, last):
    self.candidate = cand
    self.votes = votes
    self.last_vote = last

  def beats(self, other, extra):
    return self.votes + extra > other.votes

def main():
  candidates, seats, people, voted = map(int, input().split())
  votes = [0 for i in range(candidates)]
  last_vote = [0 for i in range(candidates)]

  if candidates == 1:
    print(1)
    return

  v = list(map(int, input().split()))
  for t in range(voted):
    cand = v[t] - 1
    votes[cand] += 1
    last_vote[cand] = t

  states = [State(i, votes[i], last_vote[i]) for i in range(candidates)]
  states = sorted(states, key = lambda x : (x.votes, -x.last_vote))
  res = [0 for i in range(candidates)]

  for i in range(candidates):
    if i < candidates - seats:
      low = candidates - seats
      if states[i].beats(states[low], people - voted):
        res[states[i].candidate] = 2
      else:
        res[states[i].candidate] = 3
    else:
      extra = people - voted
      other = i - 1
      place = i

      if extra == 0 and states[i].votes == 0:
        res[states[i].candidate] = 3
        continue

      while other >= 0 and extra > 0:
        needed = states[i].votes - states[other].votes + 1
        if needed <= extra:
          extra -= needed;
          place -= 1
          other -= 1
        else:
          break

      res[states[i].candidate] = (1 if place + seats >= candidates and states[i].votes > 0 else 2)

  for i in res:
    print(i, end = ' ')

main()


I found an interesting problem on https://codeforces.com/problemset/problem/847/K:
In the evening Polycarp decided to analyze his today's travel expenses on public transport.

The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops.

Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes.

It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment.

For example, if Polycarp made three consecutive trips: "BerBank" $\rightarrow$ "University", "University" $\rightarrow$ "BerMall", "University" $\rightarrow$ "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus.

Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction.

What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards?

-----Input-----

The first line contains five integers n, a, b, k, f (1 ≤ n ≤ 300, 1 ≤ b < a ≤ 100, 0 ≤ k ≤ 300, 1 ≤ f ≤ 1000) where:  n — the number of Polycarp trips,  a — the cost of a regualar single trip,  b — the cost of a trip after a transshipment,  k — the maximum number of travel cards Polycarp can buy,  f — the...

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

n,a,b,k,f = [int(i) for i in input().split()]
pred = "_"
d = dict()
for i in range(n):
    s1, s2 = [i for i in input().split()]
    pr = a
    if s1 == pred:
        pr = b

    if (s1, s2) in list(d.keys()):
        d[(s1, s2)] += pr
    elif (s2, s1) in list(d.keys()):
        d[(s2, s1)] += pr
    else:
        d[(s1, s2)] = pr

    pred = s2

cn = k
ans = sum(d.values())
for i in sorted(list(d.values()), reverse = True):
    if cn == 0 or i <= f:
        break
    ans = ans - i + f
    cn -= 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/847/M:
Vasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last n days. Assume that the average air temperature for each day is integral.

Vasya believes that if the average temperatures over the last n days form an arithmetic progression, where the first term equals to the average temperature on the first day, the second term equals to the average temperature on the second day and so on, then the average temperature of the next (n + 1)-th day will be equal to the next term of the arithmetic progression. Otherwise, according to Vasya's method, the temperature of the (n + 1)-th day will be equal to the temperature of the n-th day.

Your task is to help Vasya predict the average temperature for tomorrow, i. e. for the (n + 1)-th day.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 100) — the number of days for which the average air temperature is known.

The second line contains a sequence of integers t_1, t_2, ..., t_{n} ( - 1000 ≤ t_{i} ≤ 1000) — where t_{i} is the average temperature in the i-th day.

-----Output-----

Print the average air temperature in the (n + 1)-th day, which Vasya predicts according to his method. Note that the absolute value of the predicted temperature can exceed 1000.

-----Examples-----
Input
5
10 5 0 -5 -10

Output
-15

Input
4
1 1 1 1

Output
1

Input
3
5 1 -5

Output
-5

Input
2
900 1000

Output
1100

-----Note-----

In the first example the sequence of the average temperatures is an arithmetic progression where the first term is 10 and each following terms decreases by 5. So the predicted average temperature for the sixth day is  - 10 - 5 =  - 15.

In the second example the sequence of the average temperatures is an arithmetic progression where the first term is 1 and each following terms equals to the previous one. So the predicted average temperature in the fifth day is 1.

In the third example the average temperatures do not form an arithmetic progression, so the average...

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

n = int(input());
A = list(map(int, input().split()));
w = 1;
res = 0;
f = 0;
for q in range(0, n - 1):
    if f != 0 and A[q + 1] - A[q] != res:
        w = 0;
        break;
    elif f == 0:
        res = A[q + 1] - A[q];
        f = 1;
if w == 0:
    print(A[len(A) - 1]);
else:
    print(A[len(A) - 1] + res);


I found an interesting problem on https://codeforces.com/problemset/problem/848/D:
A never-ending, fast-changing and dream-like world unfolds, as the secret door opens.

A world is an unordered graph G, in whose vertex set V(G) there are two special vertices s(G) and t(G). An initial world has vertex set {s(G), t(G)} and an edge between them.

A total of n changes took place in an initial world. In each change, a new vertex w is added into V(G), an existing edge (u, v) is chosen, and two edges (u, w) and (v, w) are added into E(G). Note that it's possible that some edges are chosen in more than one change.

It's known that the capacity of the minimum s-t cut of the resulting graph is m, that is, at least m edges need to be removed in order to make s(G) and t(G) disconnected.

Count the number of non-similar worlds that can be built under the constraints, modulo 10^9 + 7. We define two worlds similar, if they are isomorphic and there is isomorphism in which the s and t vertices are not relabelled. Formally, two worlds G and H are considered similar, if there is a bijection between their vertex sets $f : V(G) \rightarrow V(H)$, such that:   f(s(G)) = s(H);  f(t(G)) = t(H);  Two vertices u and v of G are adjacent in G if and only if f(u) and f(v) are adjacent in H.

-----Input-----

The first and only line of input contains two space-separated integers n, m (1 ≤ n, m ≤ 50) — the number of operations performed and the minimum cut, respectively.

-----Output-----

Output one integer — the number of non-similar worlds that can be built, modulo 10^9 + 7.

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

Output
6

Input
4 4

Output
3

Input
7 3

Output
1196

Input
31 8

Output
64921457

-----Note-----

In the first example, the following 6 worlds are pairwise non-similar and satisfy the constraints, with s(G) marked in green, t(G) marked in blue, and one of their minimum cuts in light blue.

 [Image]

In the second example, the following 3 worlds satisfy the constraints.

 [Image]

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

mod = int(1e9 + 7)
n, m = map(int, input().split())
f = [ [0 for i in range(60)] for j in range(60) ]
g = [ [0 for i in range(60)] for j in range(60) ]
s = [ [0 for i in range(60)] for j in range(60) ]
inv = [ 1 ]
f[0][0] = s[0][0] = 1

def pow(x, exp) :
    res = 1
    for i in range(0, 31) :
        if exp & 1 : res = res * x % mod
        exp >>= 1
        if exp == 0 : break
        x = x * x % mod
    return res

for i in range(1, n + 1) :
    inv.append( pow(i, mod - 2) )

for node in range(1, n + 1) :
    for cut in range(1, n + 1) :
        tmp = 0
        for ln in range(node) :
            for lc in range(cut - 1, n + 1) :
                if f[ln][lc] == 0 : continue
                if lc == cut - 1 :
                    tmp = ( tmp + f[ln][lc] * s[node - ln - 1][cut - 1] ) % mod
                else :
                    tmp = ( tmp + f[ln][lc] * f[node - ln - 1][cut - 1] ) % mod
        cnt = 1
        if tmp != 0 :
            cn, cc = 0, 0
            for i in range(1, n + 1) :
                cn += node
                cc += cut
                cnt = cnt * (tmp + i - 1) % mod * inv[i] % mod
                if cn > n or cc > n : break
                for j in range(n - cn, -1, -1) :
                    for k in range(n - cc, -1, -1) :
                        if f[j][k] == 0 : continue
                        g[j + cn][k + cc] += f[j][k] * cnt
                        g[j + cn][k + cc] %= mod
            for i in range(n + 1) :
                for j in range(n + 1) :
                    f[i][j] = (f[i][j] + g[i][j]) % mod
                    g[i][j] = 0

    for cut in range(n, -1, -1) :
        s[node][cut] = ( s[node][cut + 1] + f[node][cut] ) % mod
print(f[n][m - 1])


I found an interesting problem on https://codeforces.com/problemset/problem/849/A:
Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?

Given an integer sequence a_1, a_2, ..., a_{n} of length n. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.

A subsegment is a contiguous slice of the whole sequence. For example, {3, 4, 5} and {1} are subsegments of sequence {1, 2, 3, 4, 5, 6}, while {1, 2, 4} and {7} are not.

-----Input-----

The first line of input contains a non-negative integer n (1 ≤ n ≤ 100) — the length of the sequence.

The second line contains n space-separated non-negative integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 100) — the elements of the sequence.

-----Output-----

Output "Yes" if it's possible to fulfill the requirements, and "No" otherwise.

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

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

Output
Yes

Input
5
1 0 1 5 1

Output
Yes

Input
3
4 3 1

Output
No

Input
4
3 9 9 3

Output
No

-----Note-----

In the first example, divide the sequence into 1 subsegment: {1, 3, 5} and the requirements will be met.

In the second example, divide the sequence into 3 subsegments: {1, 0, 1}, {5}, {1}.

In the third example, one of the subsegments must start with 4 which is an even number, thus the requirements cannot be met.

In the fourth example, the sequence can be divided into 2 subsegments: {3, 9, 9}, {3}, but this is not a valid solution because 2 is an even number.

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

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

if n % 2 == 1 and a[0] % 2 == 1 and a[-1] % 2 == 1:
    print('Yes')
else:
    print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/849/B:
Connect the countless points with lines, till we reach the faraway yonder.

There are n points on a coordinate plane, the i-th of which being (i, y_{i}).

Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes through at least one point in the set.

-----Input-----

The first line of input contains a positive integer n (3 ≤ n ≤ 1 000) — the number of points.

The second line contains n space-separated integers y_1, y_2, ..., y_{n} ( - 10^9 ≤ y_{i} ≤ 10^9) — the vertical coordinates of each point.

-----Output-----

Output "Yes" (without quotes) if it's possible to fulfill the requirements, and "No" otherwise.

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

-----Examples-----
Input
5
7 5 8 6 9

Output
Yes

Input
5
-1 -2 0 0 -5

Output
No

Input
5
5 4 3 2 1

Output
No

Input
5
1000000000 0 0 0 0

Output
Yes

-----Note-----

In the first example, there are five points: (1, 7), (2, 5), (3, 8), (4, 6) and (5, 9). It's possible to draw a line that passes through points 1, 3, 5, and another one that passes through points 2, 4 and is parallel to the first one.

In the second example, while it's possible to draw two lines that cover all points, they cannot be made parallel.

In the third example, it's impossible to satisfy both requirements at the same time.

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

def coef(a, b):
    ax, ay = a
    bx, by = b
    return (by-ay)/(bx-ax)

def coefl(line):
    return coef(line[0], line[1])

def fitline(c, line):
    if len(line) <= 1:
        return True
    return coef(line[0], line[1]) == coef(line[0], c)

def same(linea, lineb):
    linec = list(lineb)
    for p in linea:
        if not fitline(p, linec):
            return False
        linec.append(p)
    return True

def allpointsfit(linea, lineb, pointset):
    for p in pointset:
        if fitline(p, linea):
            linea.append(p)
        elif fitline(p, lineb):
            lineb.append(p)
        else:
            return False
    if len(linea) == 0 or len(lineb) == 0:
        return False
    if same(linea, lineb):
        return False
    fit = len(linea) == 1 or len(lineb) == 1 or (coefl(linea) == coefl(lineb))
    return fit

n = int(input())
a = [int(x) for x in input().split()]
ans = (len(set(a)) == 2)
points = [(idx+1, val) for idx, val in enumerate(a)]
ans = ans or allpointsfit([points[0], points[1]], [points[2]], points[3:])
ans = ans or allpointsfit([points[1], points[2]], [points[0]], points[3:])
ans = ans or allpointsfit([points[0], points[2]], [points[1]], points[3:])
ans = ans or allpointsfit([], [], points)
print('Yes' if ans else 'No')


I found an interesting problem on https://codeforces.com/problemset/problem/851/A:
Arpa is researching the Mexican wave.

There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0.

  At time 1, the first spectator stands.  At time 2, the second spectator stands.  ...  At time k, the k-th spectator stands.  At time k + 1, the (k + 1)-th spectator stands and the first spectator sits.  At time k + 2, the (k + 2)-th spectator stands and the second spectator sits.  ...  At time n, the n-th spectator stands and the (n - k)-th spectator sits.  At time n + 1, the (n + 1 - k)-th spectator sits.  ...  At time n + k, the n-th spectator sits.

Arpa wants to know how many spectators are standing at time t.

-----Input-----

The first line contains three integers n, k, t (1 ≤ n ≤ 10^9, 1 ≤ k ≤ n, 1 ≤ t < n + k).

-----Output-----

Print single integer: how many spectators are standing at time t.

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

Output
3

Input
10 5 7

Output
5

Input
10 5 12

Output
3

-----Note-----

In the following a sitting spectator is represented as -, a standing spectator is represented as ^.

  At t = 0  ---------- $\Rightarrow$ number of standing spectators = 0.  At t = 1  ^--------- $\Rightarrow$ number of standing spectators = 1.  At t = 2  ^^-------- $\Rightarrow$ number of standing spectators = 2.  At t = 3  ^^^------- $\Rightarrow$ number of standing spectators = 3.  At t = 4  ^^^^------ $\Rightarrow$ number of standing spectators = 4.  At t = 5  ^^^^^----- $\Rightarrow$ number of standing spectators = 5.  At t = 6  -^^^^^---- $\Rightarrow$ number of standing spectators = 5.  At t = 7  --^^^^^--- $\Rightarrow$ number of standing spectators = 5.  At t = 8  ---^^^^^-- $\Rightarrow$ number of standing spectators = 5.  At t = 9  ----^^^^^- $\Rightarrow$ number of standing spectators = 5.  At t = 10 -----^^^^^ $\Rightarrow$ number of standing spectators = 5.  At t = 11 ------^^^^ $\Rightarrow$ number of standing spectators = 4.  At t = 12 -------^^^ $\Rightarrow$ number of standing spectators = 3.  At t = 13 --------^^ $\Rightarrow$ number of...

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

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

def main():
    if t < k:
        return t
    elif k <= t <= n:
        return k
    else:
        return n + k - t

print(main())


I found an interesting problem on https://codeforces.com/problemset/problem/851/B:
Arpa is taking a geometry exam. Here is the last problem of the exam.

You are given three points a, b, c.

Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c.

Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not.

-----Input-----

The only line contains six integers a_{x}, a_{y}, b_{x}, b_{y}, c_{x}, c_{y} (|a_{x}|, |a_{y}|, |b_{x}|, |b_{y}|, |c_{x}|, |c_{y}| ≤ 10^9). It's guaranteed that the points are distinct.

-----Output-----

Print "Yes" if the problem has a solution, "No" otherwise.

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

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

Output
Yes

Input
1 1 0 0 1000 1000

Output
No

-----Note-----

In the first sample test, rotate the page around (0.5, 0.5) by $90^{\circ}$.

In the second sample test, you can't find any solution.

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

from math import sqrt

ax,ay,bx,by,cx,cy = [int(i) for i in input().split()]
if (ax-bx)**2+(ay-by)**2 != (bx-cx)**2+(by-cy)**2:
    print("No")
elif abs((ax-bx)*(bx-cx)+((ay-by)*(by-cy)))**2== ((ax-bx)**2+(ay-by)**2)* ((bx-cx)**2+(by-cy)**2):
    print("No")
else:
    print("Yes")


I found an interesting problem on https://codeforces.com/problemset/problem/852/C:
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property.

Bill’s property can be observed as a convex regular 2n-sided polygon A_0 A_1... A_2n - 1 A_2n,  A_2n =  A_0, with sides of the exactly 1 meter in length.

Court rules for removing part of his property are as follows:  Split every edge A_{k} A_{k} + 1,  k = 0... 2n - 1 in n equal parts of size 1 / n with points P_0, P_1, ..., P_{n} - 1  On every edge A_2k A_2k + 1,  k = 0... n - 1 court will choose one point B_2k =  P_{i} for some i = 0, ...,  n - 1 such that $\cup_{i = 0}^{n - 1} B_{2i} = \cup_{i = 0}^{n - 1} P_{i}$  On every edge A_2k + 1A_2k + 2,  k = 0...n - 1 Bill will choose one point B_2k + 1 =  P_{i} for some i = 0, ...,  n - 1 such that $\cup_{i = 0}^{n - 1} B_{2 i + 1} = \cup_{i = 0}^{n - 1} P_{i}$  Bill gets to keep property inside of 2n-sided polygon B_0 B_1... B_2n - 1

Luckily, Bill found out which B_2k points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep.

-----Input-----

The first line contains one integer number n (2 ≤ n ≤ 50000), representing number of edges of 2n-sided polygon.

The second line contains n distinct integer numbers B_2k (0 ≤ B_2k ≤ n - 1,  k = 0... n - 1) separated by a single space, representing points the court chose. If B_2k = i, the court chose point P_{i} on side A_2k A_2k + 1.

-----Output-----

Output contains n distinct integers separated by a single space representing points B_1, B_3, ..., B_2n - 1 Bill should choose in order to maximize the property area. If there are multiple solutions that maximize the area, return any of them.

-----Example-----
Input
3
0 1 2

Output
0 2 1

-----Note-----

To maximize area Bill should...

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

n = int(input())
a = input().split()
for i in range(n):
    a[i] = int(a[i])
b = []
for i in range(0, n-1):
    b.append((a[i]-(n-a[i+1]), i))
b.append((a[n-1]-(n-a[0]), n-1))
b = sorted(b)
ans = n*[0]
for i in range(n):
    # the line segment at index b[i][1]
    ans[b[i][1]] = i
for i in range(n):
    print(ans[i], end = ' ')