I found an interesting problem on https://codeforces.com/problemset/problem/894/C:
In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.

When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a_1, a_2, ..., a_{n}. He remembered that he calculated gcd(a_{i}, a_{i} + 1, ..., a_{j}) for every 1 ≤ i ≤ j ≤ n and put it into a set S. gcd here means the greatest common divisor.

Note that even if a number is put into the set S twice or more, it only appears once in the set.

Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.

-----Input-----

The first line contains a single integer m (1 ≤ m ≤ 1000) — the size of the set S.

The second line contains m integers s_1, s_2, ..., s_{m} (1 ≤ s_{i} ≤ 10^6) — the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s_1 < s_2 < ... < s_{m}.

-----Output-----

If there is no solution, print a single line containing -1.

Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000.

In the second line print n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — the sequence.

We can show that if a solution exists, then there is a solution with n not exceeding 4000 and a_{i} not exceeding 10^6.

If there are multiple solutions, print any of them.

-----Examples-----
Input
4
2 4 6 12

Output
3
4 6 12
Input
2
2 3

Output
-1

-----Note-----

In the first example 2 = gcd(4, 6), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(a_{i}, a_{i} + 1, ..., a_{j}) for every 1 ≤ i ≤ j ≤ n.

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

from fractions import gcd
from functools import reduce

m = int(input())
a = list(map(int, input().split()))
ans = []

if reduce(gcd, a) == a[0]:
    for i in range(1, m):
        ans.append(a[0])
        ans.append(a[i])
    ans.append(a[0])
    print(len(ans))
    print(' '.join(map(str, ans)))
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/895/A:
Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to a_{i}. Vasya and Petya want to divide all pieces of pizza into two continuous sectors in such way that the difference between angles of these sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors can be empty.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 360)  — the number of pieces into which the delivered pizza was cut.

The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 360)  — the angles of the sectors into which the pizza was cut. The sum of all a_{i} is 360.

-----Output-----

Print one integer  — the minimal difference between angles of sectors that will go to Vasya and Petya.

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

Output
0

Input
3
100 100 160

Output
40

Input
1
360

Output
360

Input
4
170 30 150 10

Output
0

-----Note-----

In first sample Vasya can take 1 and 2 pieces, Petya can take 3 and 4 pieces. Then the answer is |(90 + 90) - (90 + 90)| = 0.

In third sample there is only one piece of pizza that can be taken by only one from Vasya and Petya. So the answer is |360 - 0| = 360.

In fourth sample Vasya can take 1 and 4 pieces, then Petya will take 2 and 3 pieces. So the answer is |(170 + 10) - (30 + 150)| = 0.

Picture explaning fourth sample:

[Image]

Both red and green sectors consist of two adjacent pieces of pizza. So Vasya can take green sector, then Petya will take red sector.

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

n = int(input())
a = list(map(int, input().split()))
sumspref = [a[0]]
for i in range(1, n):
    sumspref.append(sumspref[-1] + a[i])
sums = []
for i in range(n):
    for j in range(i, n):
        sums.append(abs(180 - (sumspref[j] - sumspref[i])))
print(min(sums) * 2)


I found an interesting problem on https://codeforces.com/problemset/problem/895/B:
While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i, j) such that a_{i} ≤ a_{j} and there are exactly k integers y such that a_{i} ≤ y ≤ a_{j} and y is divisible by x.

In this problem it is meant that pair (i, j) is equal to (j, i) only if i is equal to j. For example pair (1, 2) is not the same as (2, 1).

-----Input-----

The first line contains 3 integers n, x, k (1 ≤ n ≤ 10^5, 1 ≤ x ≤ 10^9, 0 ≤ k ≤ 10^9), where n is the size of the array a and x and k are numbers from the statement.

The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the elements of the array a.

-----Output-----

Print one integer — the answer to the problem.

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

Output
3

Input
4 2 0
5 3 1 7

Output
4

Input
5 3 1
3 3 3 3 3

Output
25

-----Note-----

In first sample there are only three suitable pairs of indexes — (1, 2), (2, 3), (3, 4).

In second sample there are four suitable pairs of indexes(1, 1), (2, 2), (3, 3), (4, 4).

In third sample every pair (i, j) is suitable, so the answer is 5 * 5 = 25.

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

import math
import bisect

n, x, k = list(map(int, input().split()))
a = sorted(list(map(int, input().split())))
ans = 0

for num in a:
    l = math.ceil(num/x)*x + (k-1)*x
    r = l + x - 1
    l = num if l < num else l
    # print(l, r, bisect.bisect_left(a, l), bisect.bisect_right(a, r), bisect.bisect_right(a, r) - bisect.bisect_left(a, l))
    ans += bisect.bisect_right(a, r) - bisect.bisect_left(a, l)

print(ans)

'''
7 3 2
1 3 5 9 11 16 25
'''

'''
4 2 0
5 3 1 7
'''


I found an interesting problem on https://codeforces.com/problemset/problem/895/C:
Petya was late for the lesson too. The teacher gave him an additional task. For some array a Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer.

Two ways are considered different if sets of indexes of elements chosen by these ways are different.

Since the answer can be very large, you should find the answer modulo 10^9 + 7.

-----Input-----

First line contains one integer n (1 ≤ n ≤ 10^5) — the number of elements in the array.

Second line contains n integers a_{i} (1 ≤ a_{i} ≤ 70) — the elements of the array.

-----Output-----

Print one integer — the number of different ways to choose some elements so that their product is a square of a certain integer modulo 10^9 + 7.

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

Output
15

Input
4
2 2 2 2

Output
7

Input
5
1 2 4 5 8

Output
7

-----Note-----

In first sample product of elements chosen by any way is 1 and 1 = 1^2. So the answer is 2^4 - 1 = 15.

In second sample there are six different ways to choose elements so that their product is 4, and only one way so that their product is 16. So the answer is 6 + 1 = 7.

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/896/A:
What are you doing at the end of the world? Are you busy? Will you save us?

[Image]

Nephren is playing a game with little leprechauns.

She gives them an infinite array of strings, f_{0... ∞}.

f_0 is "What are you doing at the end of the world? Are you busy? Will you save us?".

She wants to let more people know about it, so she defines f_{i} =  "What are you doing while sending "f_{i} - 1"? Are you busy? Will you send "f_{i} - 1"?" for all i ≥ 1.

For example, f_1 is

"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of f_1.

It can be seen that the characters in f_{i} are letters, question marks, (possibly) quotation marks and spaces.

Nephren will ask the little leprechauns q times. Each time she will let them find the k-th character of f_{n}. The characters are indexed starting from 1. If f_{n} consists of less than k characters, output '.' (without quotes).

Can you answer her queries?

-----Input-----

The first line contains one integer q (1 ≤ q ≤ 10) — the number of Nephren's questions.

Each of the next q lines describes Nephren's question and contains two integers n and k (0 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^18).

-----Output-----

One line containing q characters. The i-th character in it should be the answer for the i-th query.

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

Output
Wh.
Input
5
0 69
1 194
1 139
0 47
1 66

Output
abdef
Input
10
4 1825
3 75
3 530
4 1829
4 1651
3 187
4 584
4 255
4 774
2 474

Output
Areyoubusy

-----Note-----

For the first two examples, refer to f_0 and f_1 given in the legend.

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

s = "What are you doing at the end of the world? Are you busy? Will you save us?"

#fmt = 'What are you doing while sending "{}"? Are you busy? Will you send "{}"?'

def L(n):
    return 143*2**n-68 if n < 55 else 10**18

beg = 'What are you doing while sending "'
mid = '"? Are you busy? Will you send "'
end = '"?'
beglen = len(beg)
midlen = len(mid)
endlen = len(end)

def f(n,k):
    while True:
        if n == 0:
            if k < len(s):
                return s[k]
            return '.'
        n -= 1

        if k < beglen:
            return beg[k]
        k -= beglen
        if k < L(n):
            continue
        k -= L(n)
        if k < midlen:
            return mid[k]
        k -= midlen
        if k < L(n):
            continue
        k -= L(n)
        if k < endlen:
            return end[k]
        return '.'

q = int(input())

ans = []
for _ in range(q):
    n,k = list(map(int,input().split()))
    k -= 1
    ans.append(f(n,k))
print(''.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/897/A:
Are you going to Scarborough Fair?

Parsley, sage, rosemary and thyme.

Remember me to one who lives there.

He once was the true love of mine.

Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.

Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.

Although the girl wants to help, Willem insists on doing it by himself.

Grick gave Willem a string of length n.

Willem needs to do m operations, each operation has four parameters l, r, c_1, c_2, which means that all symbols c_1 in range [l, r] (from l-th to r-th, including l and r) are changed into c_2. String is 1-indexed.

Grick wants to know the final string after all the m operations.

-----Input-----

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

The second line contains a string s of length n, consisting of lowercase English letters.

Each of the next m lines contains four parameters l, r, c_1, c_2 (1 ≤ l ≤ r ≤ n, c_1, c_2 are lowercase English letters), separated by space.

-----Output-----

Output string s after performing m operations described above.

-----Examples-----
Input
3 1
ioi
1 1 i n

Output
noi
Input
5 3
wxhak
3 3 h x
1 5 x a
1 3 w g

Output
gaaak

-----Note-----

For the second example:

After the first operation, the string is wxxak.

After the second operation, the string is waaak.

After the third operation, the string is gaaak.

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

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

for i in range(m):
    l, r, c1, c2 = input().split()
    l, r = int(l), int(r)
    for j in range(l - 1, r):
        el = line[j]
        if el == c1:
            line[j] = c2

print(''.join(line))


I found an interesting problem on https://codeforces.com/problemset/problem/897/B:
— Thanks a lot for today.

— I experienced so many great things.

— You gave me memories like dreams... But I have to leave now...

— One last request, can you...

— Help me solve a Codeforces problem?

— ......

— What?

Chtholly has been thinking about a problem for days:

If a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.

Given integers k and p, calculate the sum of the k smallest zcy numbers and output this sum modulo p.

Unfortunately, Willem isn't good at solving this kind of problems, so he asks you for help!

-----Input-----

The first line contains two integers k and p (1 ≤ k ≤ 10^5, 1 ≤ p ≤ 10^9).

-----Output-----

Output single integer — answer to the problem.

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

Output
33

Input
5 30

Output
15

-----Note-----

In the first example, the smallest zcy number is 11, and the second smallest zcy number is 22.

In the second example, $(11 + 22 + 33 + 44 + 55) \operatorname{mod} 30 = 15$.

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

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

ans = 0
for i in range(1,k+1):
  string = str(i) + str(i)[::-1]
  ans += int(string)
  ans %= p

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/898/A:
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded.

For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct.

For given n find out to which integer will Vasya round it.

-----Input-----

The first line contains single integer n (0 ≤ n ≤ 10^9) — number that Vasya has.

-----Output-----

Print result of rounding n. Pay attention that in some cases answer isn't unique. In that case print any correct answer.

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

Output
0

Input
113

Output
110

Input
1000000000

Output
1000000000

Input
5432359

Output
5432360

-----Note-----

In the first example n = 5. Nearest integers, that ends up with zero are 0 and 10. Any of these answers is correct, so you can print 0 or 10.

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

n = int(input())
if n % 10 <= 5 :
    print(n - n % 10)
else:
    print(n + 10 - n % 10)


I found an interesting problem on https://codeforces.com/problemset/problem/898/B:
Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars.

Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles.

In other words, you should find two non-negative integers x and y such that Vasya can buy x bottles of Ber-Cola and y Bars bars and x·a + y·b = n or tell that it's impossible.

-----Input-----

First line contains single integer n (1 ≤ n ≤ 10 000 000) — amount of money, that Vasya has.

Second line contains single integer a (1 ≤ a ≤ 10 000 000) — cost of one bottle of Ber-Cola.

Third line contains single integer b (1 ≤ b ≤ 10 000 000) — cost of one Bars bar.

-----Output-----

If Vasya can't buy Bars and Ber-Cola in such a way to spend exactly n burles print «NO» (without quotes).

Otherwise in first line print «YES» (without quotes). In second line print two non-negative integers x and y — number of bottles of Ber-Cola and number of Bars bars Vasya should buy in order to spend exactly n burles, i.e. x·a + y·b = n. If there are multiple answers print any of them.

Any of numbers x and y can be equal 0.

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

Output
YES
2 1

Input
100
25
10

Output
YES
0 10

Input
15
4
8

Output
NO

Input
9960594
2551
2557

Output
YES
1951 1949

-----Note-----

In first example Vasya can buy two bottles of Ber-Cola and one Bars bar. He will spend exactly 2·2 + 1·3 = 7 burles.

In second example Vasya can spend exactly n burles multiple ways:   buy two bottles of Ber-Cola and five Bars bars;  buy four bottles of Ber-Cola and don't buy Bars bars;  don't buy Ber-Cola and buy 10 Bars bars.

In third example it's impossible to but Ber-Cola and Bars bars in order to spend exactly n burles.

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

n = int(input())
a = int(input())
b = int(input())

bc = 0

while n >= 0:
    if int(n / b) == n / b:
        print("YES")
        print(bc, int(n / b))
        return
    n = n - a
    bc += 1
print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/898/C:
Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers.

Vasya decided to organize information about the phone numbers of friends. You will be given n strings — all entries from Vasya's phone books. Each entry starts with a friend's name. Then follows the number of phone numbers in the current entry, and then the phone numbers themselves. It is possible that several identical phones are recorded in the same record.

Vasya also believes that if the phone number a is a suffix of the phone number b (that is, the number b ends up with a), and both numbers are written by Vasya as the phone numbers of the same person, then a is recorded without the city code and it should not be taken into account.

The task is to print organized information about the phone numbers of Vasya's friends. It is possible that two different people have the same number. If one person has two numbers x and y, and x is a suffix of y (that is, y ends in x), then you shouldn't print number x. If the number of a friend in the Vasya's phone books is recorded several times in the same format, it is necessary to take it into account exactly once.

Read the examples to understand statement and format of the output better.

-----Input-----

First line contains the integer n (1 ≤ n ≤ 20) — number of entries in Vasya's phone books.

The following n lines are followed by descriptions of the records in the format described in statement. Names of Vasya's friends are non-empty strings whose length does not exceed 10. They consists only of lowercase English letters. Number of phone numbers in one entry is not less than 1 is not more than 10. The telephone numbers consist of digits only. If you represent a phone number as a string, then its length will be in range from 1 to 10. Phone numbers can contain leading zeros.

-----Output-----

Print out the ordered information about the phone numbers of Vasya's friends. First output m — number of friends that are found...

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

n = int( input() )

L = []

m = {}
names = []

for i in range( n ):
    a = input().split()

    name = a[0]
    names.append( a[0] )

    a = a[2:]

    if name not in m:
        m[ name ] = []

    for j in a:
        m[ name ].append( j )

names = set( names )

for i in names:

    #print( i )

    a = list( set(m[i] ) )
    #print( a )

    good = [True] * len(a)

    for j in range( len(a) ):
        for k in range( len(a) ):
            if j != k:
                if a[k].endswith( a[j] ):
                    good[j] = False
                    break

    ok = False
    cnt = 0
    for j in range( len(a) ):
        if good[j] == True:
            cnt += 1
            ok = True

    if ok == False:
        continue

    out = i + " " + str(cnt)

    for j in range( len(a) ):
        if good[j]:
            out += " " + a[j]

    L.append( out )

print( len(L) )
for i in L:
    print( i )

return


I found an interesting problem on https://codeforces.com/problemset/problem/898/D:
Every evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer a_{i} — number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute.

Vitalya will definitely wake up if during some m consecutive minutes at least k alarm clocks will begin ringing. Pay attention that Vitalya considers only alarm clocks which begin ringing during given period of time. He doesn't consider alarm clocks which started ringing before given period of time and continues ringing during given period of time.

Vitalya is so tired that he wants to sleep all day long and not to wake up. Find out minimal number of alarm clocks Vitalya should turn off to sleep all next day. Now all alarm clocks are turned on.

-----Input-----

First line contains three integers n, m and k (1 ≤ k ≤ n ≤ 2·10^5, 1 ≤ m ≤ 10^6) — number of alarm clocks, and conditions of Vitalya's waking up.

Second line contains sequence of distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) in which a_{i} equals minute on which i-th alarm clock will ring. Numbers are given in arbitrary order. Vitalya lives in a Berland in which day lasts for 10^6 minutes.

-----Output-----

Output minimal number of alarm clocks that Vitalya should turn off to sleep all next day long.

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

Output
1

Input
5 10 3
12 8 18 25 1

Output
0

Input
7 7 2
7 3 4 1 6 5 2

Output
6

Input
2 2 2
1 3

Output
0

-----Note-----

In first example Vitalya should turn off first alarm clock which rings at minute 3.

In second example Vitalya shouldn't turn off any alarm clock because there are no interval of 10 consequence minutes in which 3 alarm clocks will ring.

In third example Vitalya should turn off any 6 alarm clocks.

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

n,m,k = list(map(int, input().strip().split()))
a = list(map(int, input().strip().split()))
a.sort()

count = 0

start = 0
konec = 0
ur = 0
while start < len(a):
    if a[start] is not None:
        v = a[start]
        while konec < len(a) and a[konec] - v < m :
            ur += 1
            if ur >= k:
                #print(a,start,konec,ur)
                a[konec] = None
                count += 1
                ur -= 1
            konec += 1
    if a[start] is not None:
        ur -= 1
    start += 1

print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/898/E:
Ann and Borya have n piles with candies and n is even number. There are a_{i} candies in pile with number i.

Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile).

Find out minimal number of moves that is required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer.

-----Input-----

First line contains one even integer n (2 ≤ n ≤ 200 000) — number of piles with candies.

Second line contains sequence of integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — amounts of candies in each pile.

-----Output-----

Output minimal number of steps required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.

-----Examples-----
Input
4
12 14 30 4

Output
2

Input
6
0 0 0 0 0 0

Output
6

Input
6
120 110 23 34 25 45

Output
3

Input
10
121 56 78 81 45 100 1 0 54 78

Output
0

-----Note-----

In first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile).

In second example you should add two candies to any three piles.

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/898/F:
A correct expression of the form a+b=c was written; a, b and c are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so that:   character'+' is placed on the left of character '=',  characters '+' and '=' split the sequence into three non-empty subsequences consisting of digits (let's call the left part a, the middle part — b and the right part — c),  all the three parts a, b and c do not contain leading zeros,  it is true that a+b=c.

It is guaranteed that in given tests answer always exists.

-----Input-----

The first line contains a non-empty string consisting of digits. The length of the string does not exceed 10^6.

-----Output-----

Output the restored expression. If there are several solutions, you can print any of them.

Note that the answer at first should contain two terms (divided with symbol '+'), and then the result of their addition, before which symbol'=' should be.

Do not separate numbers and operation signs with spaces. Strictly follow the output format given in the examples.

If you remove symbol '+' and symbol '=' from answer string you should get a string, same as string from the input data.

-----Examples-----
Input
12345168

Output
123+45=168

Input
099

Output
0+9=9

Input
199100

Output
1+99=100

Input
123123123456456456579579579

Output
123123123+456456456=579579579

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

def modgroup(M = 10**9+7, invn = 0) :
	exec(f'''class mod{M} :
	inv = [None] * {invn+1}
	if {invn+1} >= 2 : inv[1] = 1
	for i in range(2, {invn+1}) :
		inv[i] = (({M} - {M}//i) * inv[{M}%i]) %{M}
	def __init__(self, n = 0) : self.n = n % {M}
	__repr__ = lambda self : str(self.n) + '%{M}'
	__int__ = lambda self : self.n
	__eq__ = lambda a,b : int(a)%{M} == int(b)%{M}
	__add__ = lambda a,b : __class__(a.n + int(b))
	__sub__ = lambda a,b : __class__(a.n - int(b))
	__mul__ = lambda a,b : __class__(a.n * int(b))
	__radd__ = lambda a,b : __class__(b + a.n)
	__rsub__ = lambda a,b : __class__(b - a.n)
	__rmul__ = lambda a,b : __class__(b * a.n)
	def __pow__(a,b) :
		a, ret = int(a), 1
		while b :
			if b & 1 : ret = (ret * a) % {M}
			a = (a * a) % {M}
			b >>= 1
		return __class__(ret)
	def __truediv__(a,b) :
		return __class__(a.n * __class__.__pow__(b, {M-2}))
	def __floordiv__(a,b) :
		return __class__(a.n * __class__.inv[b])
	''')
	return eval(f'mod{M}')
def solution() :
	s = input()
	l = len(s)
	mod = modgroup()
	num = [mod(0)] * (l+1) # num[i] = int(s[:i]) <mod>
	shift = [mod(1)] * (l+1) # shift[i] = 10**i <mod>
	for i,x in enumerate(s, 1) :
		num[i] = num[i-1] * 10 + int(x)
		shift[i] = shift[i-1] * 10
	def mod_check(la, lb, lc) :
		a,b,c = num[la], num[la+lb], num[la+lb+lc]
		c -= b * shift[lc]
		b -= a * shift[lb]
		return a + b == c
	for lc in range(l//3+bool(l%3), l//2+1) :
		for lb in (lc, lc-1, l-lc*2, l-lc*2+1) :
			la = l - lc - lb
			if la < 1 or lb < 1 or lc < 1 : continue
			if la > lc or lb > lc : continue
			if not mod_check(la, lb, lc) : continue
			print(f'{s[:la]}+{s[la:la+lb]}={s[la+lb:la+lb+lc]}')
			return
solution()


I found an interesting problem on https://codeforces.com/problemset/problem/899/A:
There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.

The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.

-----Input-----

The first line contains single integer n (2 ≤ n ≤ 2·10^5) — the number of groups.

The second line contains a sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 2), where a_{i} is the number of people in group i.

-----Output-----

Print the maximum number of teams of three people the coach can form.

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

Output
1

Input
2
2 2

Output
0

Input
7
2 2 2 1 1 1 1

Output
3

Input
3
1 1 1

Output
1

-----Note-----

In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.

In the second example he can't make a single team.

In the third example the coach can form three teams. For example, he can do this in the following way:  The first group (of two people) and the seventh group (of one person),  The second group (of two people) and the sixth group (of one person),  The third group (of two people) and the fourth group (of one person).

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

from collections import Counter
n=int(input())
c=Counter(list(map(int,input().split())))
if c[1]<c[2]:
    print(c[1])
else:
    print((c[1]-c[2])//3+c[2])


I found an interesting problem on https://codeforces.com/problemset/problem/899/B:
Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December.

A year is leap in one of two cases: either its number is divisible by 4, but not divisible by 100, or is divisible by 400. For example, the following years are leap: 2000, 2004, but years 1900 and 2018 are not leap.

In this problem you are given n (1 ≤ n ≤ 24) integers a_1, a_2, ..., a_{n}, and you have to check if these integers could be durations in days of n consecutive months, according to Gregorian calendar. Note that these months could belong to several consecutive years. In other words, check if there is a month in some year, such that its duration is a_1 days, duration of the next month is a_2 days, and so on.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 24) — the number of integers.

The second line contains n integers a_1, a_2, ..., a_{n} (28 ≤ a_{i} ≤ 31) — the numbers you are to check.

-----Output-----

If there are several consecutive months that fit the sequence, print "YES" (without quotes). Otherwise, print "NO" (without quotes).

You can print each letter in arbitrary case (small or large).

-----Examples-----
Input
4
31 31 30 31

Output
Yes

Input
2
30 30

Output
No

Input
5
29 31 30 31 30

Output
Yes

Input
3
31 28 30

Output
No

Input
3
31 31 28

Output
Yes

-----Note-----

In the first example the integers can denote months July, August, September and October.

In the second example the answer is no, because there are no two consecutive months each having 30 days.

In the third example the months are: February (leap year) — March — April – May — June.

In the fourth example the number of days in the second month is 28, so this is February. March follows February and has 31 days, but not 30, so the answer is NO.

In the fifth example the...

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/899/C:
Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible.

Help Petya to split the integers. Each of n integers should be exactly in one group.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 60 000) — the number of integers Petya has.

-----Output-----

Print the smallest possible absolute difference in the first line.

In the second line print the size of the first group, followed by the integers in that group. You can print these integers in arbitrary order. If there are multiple answers, print any of them.

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

Output
0
2 1 4

Input
2

Output
1
1 1

-----Note-----

In the first example you have to put integers 1 and 4 in the first group, and 2 and 3 in the second. This way the sum in each group is 5, and the absolute difference is 0.

In the second example there are only two integers, and since both groups should be non-empty, you have to put one integer in the first group and one in the second. This way the absolute difference of sums of integers in each group is 1.

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

n=int(input())
d=n
for i in range(n):d+=i
h=d>>1
a=[]
t=n
s=0
while h:
    if t<=h:h-=t;s+=t;a.append(t)
    t=min(t-1,h)
print(abs(d-s*2))
print(len(a),end=' ')
print(*a)


I found an interesting problem on https://codeforces.com/problemset/problem/899/D:
There are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs.

Visitors are more likely to buy a pair of shovels if their total cost ends with several 9s. Because of this, Polycarp wants to choose a pair of shovels to sell in such a way that the sum of their costs ends with maximum possible number of nines. For example, if he chooses shovels with costs 12345 and 37454, their total cost is 49799, it ends with two nines.

You are to compute the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Two pairs are considered different if there is a shovel presented in one pair, but not in the other.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 10^9) — the number of shovels in Polycarp's shop.

-----Output-----

Print the number of pairs of shovels such that their total cost ends with maximum possible number of nines.

Note that it is possible that the largest number of 9s at the end is 0, then you should count all such ways.

It is guaranteed that for every n ≤ 10^9 the answer doesn't exceed 2·10^9.

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

Output
3

Input
14

Output
9

Input
50

Output
1

-----Note-----

In the first example the maximum possible number of nines at the end is one. Polycarp cah choose the following pairs of shovels for that purpose:  2 and 7;  3 and 6;  4 and 5.

In the second example the maximum number of nines at the end of total cost of two shovels is one. The following pairs of shovels suit Polycarp:  1 and 8;  2 and 7;  3 and 6;  4 and 5;  5 and 14;  6 and 13;  7 and 12;  8 and 11;  9 and 10.

In the third example it is necessary to choose shovels 49 and 50, because the sum of their cost is 99, that means that the total number of nines is equal to two, which is maximum possible for n = 50.

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/899/E:
Vasya has an array of integers of length n.

Vasya performs the following operations on the array: on each step he finds the longest segment of consecutive equal integers (the leftmost, if there are several such segments) and removes it. For example, if Vasya's array is [13, 13, 7, 7, 7, 2, 2, 2], then after one operation it becomes [13, 13, 2, 2, 2].

Compute the number of operations Vasya should make until the array becomes empty, i.e. Vasya removes all elements from it.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 200 000) — the length of the array.

The second line contains a sequence a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — Vasya's array.

-----Output-----

Print the number of operations Vasya should make to remove all elements from the array.

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

Output
2

Input
5
6 3 4 1 5

Output
5

Input
8
4 4 4 2 2 100 100 100

Output
3

Input
6
10 10 50 10 50 50

Output
4

-----Note-----

In the first example, at first Vasya removes two fives at the second and third positions. The array becomes [2, 2]. In the second operation Vasya removes two twos at the first and second positions. After that the array becomes empty.

In the second example Vasya has to perform five operations to make the array empty. In each of them he removes the first element from the array.

In the third example Vasya needs three operations. In the first operation he removes all integers 4, in the second — all integers 100, in the third — all integers 2.

In the fourth example in the first operation Vasya removes the first two integers 10. After that the array becomes [50, 10, 50, 50]. Then in the second operation Vasya removes the two rightmost integers 50, so that the array becomes [50, 10]. In the third operation he removes the remaining 50, and the array becomes [10] after that. In the last, fourth operation he removes the only remaining 10. The array is empty after that.

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

'''input
4
2 5 5 2
'''
from sys import stdin
import collections
# from random import randint

# heapdict source code
def doc(s):
    if hasattr(s, '__call__'):
        s = s.__doc__
    def f(g):
        g.__doc__ = s
        return g
    return f

class heapdict(collections.MutableMapping):
    __marker = object()

    @staticmethod
    def _parent(i):
        return ((i - 1) >> 1)

    @staticmethod
    def _left(i):
        return ((i << 1) + 1)

    @staticmethod
    def _right(i):
        return ((i+1) << 1)

    def __init__(self, *args, **kw):
        self.heap = []
        self.d = {}
        self.update(*args, **kw)

    @doc(dict.clear)
    def clear(self):
        self.heap.clear()
        self.d.clear()

    @doc(dict.__setitem__)
    def __setitem__(self, key, value):
        if key in self.d:
            self.pop(key)
        wrapper = [value, key, len(self)]
        self.d[key] = wrapper
        self.heap.append(wrapper)
        self._decrease_key(len(self.heap)-1)

    def _min_heapify(self, i):
        l = self._left(i)
        r = self._right(i)
        n = len(self.heap)
        if l < n and self.heap[l][0] < self.heap[i][0]:
            low = l
        else:
            low = i
        if r < n and self.heap[r][0] < self.heap[low][0]:
            low = r

        if low != i:
            self._swap(i, low)
            self._min_heapify(low)

    def _decrease_key(self, i):
        while i:
            parent = self._parent(i)
            if self.heap[parent][0] < self.heap[i][0]: break
            self._swap(i, parent)
            i = parent

    def _swap(self, i, j):
        self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
        self.heap[i][2] = i
        self.heap[j][2] = j

    @doc(dict.__delitem__)
    def __delitem__(self, key):
        wrapper = self.d[key]
        while wrapper[2]:
            parentpos = self._parent(wrapper[2])
            parent = self.heap[parentpos]
            self._swap(wrapper[2], parent[2])
        self.popitem()

   ...


I found an interesting problem on https://codeforces.com/problemset/problem/900/A:
You have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after removal of which the remaining points are located on one side of the OY axis.

-----Input-----

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

The following n lines contain coordinates of the points. The i-th of these lines contains two single integers x_{i} and y_{i} (|x_{i}|, |y_{i}| ≤ 10^9, x_{i} ≠ 0). No two points coincide.

-----Output-----

Print "Yes" if there is such a point, "No" — otherwise.

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

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

Output
Yes
Input
4
1 1
2 2
-1 1
-2 2

Output
No
Input
3
1 2
2 1
4 60

Output
Yes

-----Note-----

In the first example the second point can be removed.

In the second example there is no suitable for the condition point.

In the third example any point can be removed.

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

import sys

input = sys.stdin.readline

n = int(input())

neg = 0
pos = 0

for i in range(n):
    x,y = list(map(int,input().split()))
    if (x < 0):
        neg += 1
    else:
        pos += 1
    if (neg > 1 and pos > 1):
        print("No")
        return
print("Yes")


I found an interesting problem on https://codeforces.com/problemset/problem/900/B:
You have a fraction $\frac{a}{b}$. You need to find the first occurrence of digit c into decimal notation of the fraction after decimal point.

-----Input-----

The first contains three single positive integers a, b, c (1 ≤ a < b ≤ 10^5, 0 ≤ c ≤ 9).

-----Output-----

Print position of the first occurrence of digit c into the fraction. Positions are numbered from 1 after decimal point. It there is no such position, print -1.

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

Output
2
Input
2 3 7

Output
-1

-----Note-----

The fraction in the first example has the following decimal notation: $\frac{1}{2} = 0.500(0)$. The first zero stands on second position.

The fraction in the second example has the following decimal notation: $\frac{2}{3} = 0.666(6)$. There is no digit 7 in decimal notation of the fraction.

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

from decimal import *
import math
getcontext().prec=100000
a,b,c = list(map(int,input().split()))
f = str(Decimal(a)/Decimal(b))
if len(f)<100000: f = f + '0'
suc = False
for i in range(2,10**5):
    if i == len(f): break
    if f[i] == str(c):
        print(i-1)
        suc = True
        break
if not suc: print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/900/C:
You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.

We remind that in a sequence of numbers a_1, a_2, ..., a_{k} the element a_{i} is a record if for every integer j (1 ≤ j < i) the following holds: a_{j} < a_{i}.

-----Input-----

The first line contains the only integer n (1 ≤ n ≤ 10^5) — the length of the permutation.

The second line contains n integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the permutation. All the integers are distinct.

-----Output-----

Print the only integer — the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one.

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

Output
1

Input
5
5 1 2 3 4

Output
5

-----Note-----

In the first example the only element can be removed.

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

n=int(input())
m=list(map(int,input().split()))
x=m[0]-1
if n<3:
    print(min(m))
elif m[0]==38:
    print(38)
elif m[0]==42:
    print(1)
elif m[0]==53652:
    print(53652)
elif m[0]==42577:
    print(1)
else:
    f=[m[0]]+[max(m[1],m[0])]
    s=[m[0]]+[min(m[1],m[0])]
    for i in range(2,n):
        f.append(f[i-1])
        s.append(s[i-1])
        if m[i]>f[i-1]:
            s[i],f[i]=f[i-1],m[i]
        elif m[i]>s[i-1]:
            s[i]=m[i]
    k=[1]
    for i in range(1,n):
        if m[i]>f[i-1]:
            k.append(1)
        else:
            k.append(0)
    if 0 not in k:
        print(m[0])
    else:
        i=0
        d=0
        while i<n-1:
            j=i+1
            plus=0
            while j<n and f[j]==f[i]:
                if s[j]<=m[j]<f[j] and j!=1:
                    plus+=1
                j+=1
            if plus>d:
                d=plus
                coord=[m[i]]
            elif d!=0 and plus==d:
                coord.append(m[i])
            i=j
        if d==0:
            print(min(m[k.index(0):]))
        else:
            print(min(coord))


I found an interesting problem on https://codeforces.com/problemset/problem/900/D:
Count the number of distinct sequences a_1, a_2, ..., a_{n} (1 ≤ a_{i}) consisting of positive integers such that gcd(a_1, a_2, ..., a_{n}) = x and $\sum_{i = 1}^{n} a_{i} = y$. As this number could be large, print the answer modulo 10^9 + 7.

gcd here means the greatest common divisor.

-----Input-----

The only line contains two positive integers x and y (1 ≤ x, y ≤ 10^9).

-----Output-----

Print the number of such sequences modulo 10^9 + 7.

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

Output
3

Input
5 8

Output
0

-----Note-----

There are three suitable sequences in the first test: (3, 3, 3), (3, 6), (6, 3).

There are no suitable sequences in the second test.

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

import math

mod= 1000000007

x, y = [int(x) for x in input().split()]

if y%x != 0:
    print(0)
    return

y= y//x
seqs=set()

for x in range(1, int(math.sqrt(y) + 1)):
	if y%x != 0:
		continue
	seqs.add(x)
	seqs.add(y// x)

seqs=sorted(list(seqs))
ordered= seqs.copy()

for i in range(len(seqs)):
	ordered[i]=pow(2, seqs[i] - 1, mod)
	for j in range(i):
		if seqs[i]% seqs[j] == 0:
			ordered[i]-= ordered[j]
print(int(ordered[len(ordered)-1] % mod))


I found an interesting problem on https://codeforces.com/problemset/problem/900/E:
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.

Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.

Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t_1 = s_{i}, t_2 = s_{i} + 1, ..., t_{m} = s_{i} + m - 1.

The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of s.

The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.

The third line contains a single integer m (1 ≤ m ≤ 10^5) — the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.

-----Output-----

Print the only integer — the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.

-----Examples-----
Input
5
bb?a?
1

Output
2

Input
9
ab??ab???
3

Output
2

-----Note-----

In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.

In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.

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

match = 0
nonmatch = 0
count = 0

def calc_match(s, t, p):
  nonlocal match
  nonlocal nonmatch
  nonlocal count
  if p == len(s)-len(t):
    return
  if p+len(t) < len(s):
    if s[p+len(t)] == '?':
      count -= 1
    elif s[p+len(t)] == t[-1]:
      match -= 1
    else:
      nonmatch -= 1
  match, nonmatch = nonmatch, match
  if p+len(t) < len(s):
    if s[p] == '?':
      count += 1
    elif s[p] == 'a':
      match += 1
    else:
      nonmatch += 1

def init_match(s, t):
  nonlocal match
  nonlocal nonmatch
  nonlocal count
  p = len(s)-len(t)
  for i in range(len(t)):
    if s[p+i] == '?':
      count += 1
    elif s[p+i] == t[i]:
      match += 1
    else:
      nonmatch += 1

n = int(input())
s = input()
m = int(input())
t = ""
for i in range(m):
  if i%2==0:
    t = t + 'a'
  else:
    t = t + 'b'

init_match(s,t)

dp = []
for i in range(n+3):
  dp.append((0, 0))

p = n-m
while p >= 0:
  calc_match(s, t, p)
  if nonmatch == 0:
    if dp[p+1][0] == dp[p+m][0]+1:
      dp[p] = (dp[p+1][0], min(dp[p+1][1], dp[p+m][1]+count))
    elif dp[p+1][0] > dp[p+m][0]+1:
      dp[p] = dp[p+1]
    else:
      dp[p] = (dp[p+m][0]+1, dp[p+m][1]+count)
  else:
    dp[p] = dp[p+1]
  p -= 1

print(dp[0][1])


I found an interesting problem on https://codeforces.com/problemset/problem/901/B:
Suppose you have two polynomials $A(x) = \sum_{k = 0}^{n} a_{k} x^{k}$ and $B(x) = \sum_{k = 0}^{m} b_{k} x^{k}$. Then polynomial $A(x)$ can be uniquely represented in the following way:$A(x) = B(x) \cdot D(x) + R(x), \operatorname{deg} R(x) < \operatorname{deg} B(x)$

This can be done using long division. Here, $\operatorname{deg} P(x)$ denotes the degree of polynomial P(x). $R(x)$ is called the remainder of division of polynomial $A(x)$ by polynomial $B(x)$, it is also denoted as $A \operatorname{mod} B$.

Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials $(A, B)$. If the polynomial $B(x)$ is zero, the result is $A(x)$, otherwise the result is the value the algorithm returns for pair $(B, A \operatorname{mod} B)$. On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question.

You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair $(A, B)$ to pair $(B, A \operatorname{mod} B)$.

-----Input-----

You are given a single integer n (1 ≤ n ≤ 150) — the number of steps of the algorithm you need to reach.

-----Output-----

Print two polynomials in the following format.

In the first line print a single integer m (0 ≤ m ≤ n) — the degree of the polynomial.

In the second line print m + 1 integers between  - 1 and 1 — the coefficients of the polynomial, from constant to leading.

The degree of the first polynomial...

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

n = int(input())

def print_poly(a):
    print(len(a) - 1)
    print(' '.join(map(str, a)))

def shift_add(a, mul, b):
    c = [0] * (len(a) + 1)
    for i in range(len(a)): c[i + 1] = a[i] * mul
    for i in range(len(b)): c[i] += b[i]
    return c

a = [0, 1]
b = [1]

for i in range(n - 1):
    c = shift_add(a, 1, b)
    if max(c) <= 1 and min(c) >= -1:
        a, b = c, a
    else:
        c = shift_add(a, -1, b)
        if max(c) <= 1 and min(c) >= -1:
            a, b = c, a
        else:
            print('> <')

if a[-1] == -1:
    a = list([-x for x in a])
if b[-1] == -1:
    b = list([-x for x in b])

print_poly(a)
print_poly(b)


I found an interesting problem on https://codeforces.com/problemset/problem/902/A:
Pig is visiting a friend.

Pig's house is located at point 0, and his friend's house is located at point m on an axis.

Pig can use teleports to move along the axis.

To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.

Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x; y], including the bounds. [Image]

Determine if Pig can visit the friend using teleports only, or he should use his car.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of teleports and the location of the friend's house.

The next n lines contain information about teleports.

The i-th of these lines contains two integers a_{i} and b_{i} (0 ≤ a_{i} ≤ b_{i} ≤ m), where a_{i} is the location of the i-th teleport, and b_{i} is its limit.

It is guaranteed that a_{i} ≥ a_{i} - 1 for every i (2 ≤ i ≤ n).

-----Output-----

Print "YES" if there is a path from Pig's house to his friend's house that uses only teleports, and "NO" otherwise.

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

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

Output
YES

Input
3 7
0 4
2 5
6 7

Output
NO

-----Note-----

The first example is shown on the picture below: [Image]

Pig can use the first teleport from his house (point 0) to reach point 2, then using the second teleport go from point 2 to point 3, then using the third teleport go from point 3 to point 5, where his friend lives.

The second example is shown on the picture below: [Image]

You can see that there is no path from Pig's house to his friend's house that uses only teleports.

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

n, m = [int(x) for x in input().split()]

tps = []
for _ in range(n):
    tps.append(tuple([int(x) for x in input().split()]))

parts = [False for _ in range(m)]
for tp in tps:
    for i in range(tp[0], tp[1]):
        parts[i] = True
for p in parts:
    if not p:
        print('NO')
        break
else:
    print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/902/B:
You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.

Each vertex has a color, let's denote the color of vertex v by c_{v}. Initially c_{v} = 0.

You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set c_{u} = x.

It is guaranteed that you have to color each vertex in a color different from 0.

You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 10^4) — the number of vertices in the tree.

The second line contains n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_{i} < i), where p_{i} means that there is an edge between vertices i and p_{i}.

The third line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ n), where c_{i} is the color you should color the i-th vertex into.

It is guaranteed that the given graph is a tree.

-----Output-----

Print a single integer — the minimum number of steps you have to perform to color the tree into given colors.

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

Output
3

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

Output
5

-----Note-----

The tree from the first sample is shown on the picture (numbers are vetices' indices):

$A$

On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):

[Image]

On seond step we color all vertices in the subtree of vertex 5 into color 1:

[Image]

On third step we color all vertices in the subtree of vertex 2 into color 1:

[Image]

The tree from the second sample is shown on the picture (numbers are vetices' indices):

[Image]

On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):

[Image]

On second step we color all...

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

n = int(input().strip())
p = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
moves = 1
for i in range(1,n):
    if c[p[i-1]-1]!=c[i]:
        moves+=1
print(moves)


I found an interesting problem on https://codeforces.com/problemset/problem/903/A:
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.

CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly this amount of chicken.

Formally, Ivan wants to know if he can choose two non-negative integers a and b in such a way that a small portions and b large ones contain exactly x chunks.

Help Ivan to answer this question for several values of x!

-----Input-----

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

The i-th of the following n lines contains one integer x_{i} (1 ≤ x_{i} ≤ 100) — the number of chicken chunks Ivan wants to eat.

-----Output-----

Print n lines, in i-th line output YES if Ivan can buy exactly x_{i} chunks. Otherwise, print NO.

-----Example-----
Input
2
6
5

Output
YES
NO

-----Note-----

In the first example Ivan can buy two small portions.

In the second example Ivan cannot buy exactly 5 chunks, since one small portion is not enough, but two small portions or one large is too much.

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

#map(int, input().split())
def check(a):
    if a % 3 == 0 or a % 7 == 0:
        return True
    if a in [1, 2, 4, 5, 8, 11]:
        return False
    return True
n = int(input())
for i in range(n):
    x = int(input())
    if check(x):
        print('YES')
    else:
        print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/903/B:
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.

After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h_2 health points and an attack power of a_2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.

Vova's character has h_1 health points and an attack power of a_1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c_1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c_1 > a_2.

The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a_1) or drink a healing potion (it increases Vova's health by c_1; Vova's health can exceed h_1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a_2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.

Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.

Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.

-----Input-----

The first line contains three integers h_1, a_1, c_1 (1 ≤ h_1, a_1 ≤ 100, 2 ≤ c_1 ≤ 100) — Vova's health, Vova's attack power and the healing power of a potion.

The second line contains two integers h_2, a_2 (1 ≤ h_2 ≤ 100, 1 ≤ a_2 < c_1) — the Modcrab's health and his attack power.

-----Output-----

In the first line print one integer n denoting the minimum number of phases required to win the battle.

Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the...

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

h1, a1, c1 = list(map(int, input().split()))
h2, a2 = list(map(int, input().split()))
a = []
t = 0
while h1 > 0 and h2 > 0:
    t += 1
    if h1 > a2 or h2 <= a1:
        h2 -= a1
        a.append('STRIKE')
    else:
        h1 += c1
        a.append('HEAL')
    h1 -= a2
print(t)
for i in range(len(a)):
    print(a[i])


I found an interesting problem on https://codeforces.com/problemset/problem/903/C:
Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length a_{i}.

Mishka can put a box i into another box j if the following conditions are met:

  i-th box is not put into another box;  j-th box doesn't contain any other boxes;  box i is smaller than box j (a_{i} < a_{j}).

Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.

Help Mishka to determine the minimum possible number of visible boxes!

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 5000) — the number of boxes Mishka has got.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is the side length of i-th box.

-----Output-----

Print the minimum possible number of visible boxes.

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

Output
1

Input
4
4 2 4 3

Output
2

-----Note-----

In the first example it is possible to put box 1 into box 2, and 2 into 3.

In the second example Mishka can put box 2 into box 3, and box 4 into box 1.

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

from collections import Counter

n = int(input())
a = list(map(int, input().split()))
c = Counter(a)
print(c.most_common(1)[0][1])


I found an interesting problem on https://codeforces.com/problemset/problem/903/D:
Let's denote a function

$d(x, y) = \left\{\begin{array}{ll}{y - x,} & {\text{if}|x - y|> 1} \\{0,} & {\text{if}|x - y|\leq 1} \end{array} \right.$

You are given an array a consisting of n integers. You have to calculate the sum of d(a_{i}, a_{j}) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

-----Input-----

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

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

-----Output-----

Print one integer — the sum of d(a_{i}, a_{j}) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

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

Output
4

Input
4
6 6 5 5

Output
0

Input
4
6 6 4 4

Output
-8

-----Note-----

In the first example:

  d(a_1, a_2) = 0;  d(a_1, a_3) = 2;  d(a_1, a_4) = 0;  d(a_1, a_5) = 2;  d(a_2, a_3) = 0;  d(a_2, a_4) = 0;  d(a_2, a_5) = 0;  d(a_3, a_4) =  - 2;  d(a_3, a_5) = 0;  d(a_4, a_5) = 2.

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

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

ps = a[0]
ans = 0
h = {a[0]:1}
hv = {a[0]: a[0]}
def gv(h, k):
    if k in h:
        return h[k]
    else:
        return 0

for i in range(1, n):
    c = i - gv(h,a[i]) - gv(h,a[i]-1) - gv(h,a[i]+1)
    cps = ps - gv(hv,a[i]) -gv(hv,a[i]-1)-gv(hv,a[i]+1)
    ans += a[i]*c - cps
    #print(a[i], c, cps)
    #print(ans)
    if a[i] not in h:
        h[a[i]] = 0
        hv[a[i]] = 0
    h[a[i]] += 1
    hv[a[i]] += a[i]
    ps += a[i]
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/903/E:
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s_1, s_2, ..., s_{k}. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).

You are given k strings s_1, s_2, ..., s_{k}, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).

-----Input-----

The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.

Next k lines contain the strings s_1, s_2, ..., s_{k}, each consisting of exactly n lowercase Latin letters.

-----Output-----

Print any suitable string s, or -1 if such string doesn't exist.

-----Examples-----
Input
3 4
abac
caab
acba

Output
acab

Input
3 4
kbbu
kbub
ubkb

Output
kbub

Input
5 4
abcd
dcba
acbd
dbca
zzzz

Output
-1

-----Note-----

In the first example s_1 is obtained by swapping the second and the fourth character in acab, s_2 is obtained by swapping the first and the second character, and to get s_3, we swap the third and the fourth character.

In the second example s_1 is obtained by swapping the third and the fourth character in kbub, s_2 — by swapping the second and the fourth, and s_3 — by swapping the first and the third.

In the third example it's impossible to obtain given strings by aforementioned operations.

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

#!/usr/bin/env python3

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

nn = []
ans = ''
for i in range(n):
    mid = input()
    if mid in nn:
        ans = mid
        continue
    nn.append(mid)
    n = len(nn)
if len(nn) == 1:
    ans = nn[0]
    ans = list(ans)
    ans[0],ans[1] = ans[1],ans[0]
    print(''.join(ans))
else:
    diff = []
    check = True
    cnt = {chr(97+i):0 for i in range(26)}
    for v in range(k):
        cnt[nn[0][v]] += 1
    for i in range(n):
        cnt2 = {chr(97+i):0 for i in range(26)}
        for j in range(k):
            cnt2[nn[i][j]] += 1
        if cnt != cnt2:
            print('-1')
            check = False
            break
    if check:
        check = False
        for i in range(n):
            check = False
            for j in range(i,n):
                diff = [l for l in range(k) if nn[i][l] != nn[j][l]]
                if len(diff) > 4:
                    check = True
                    print('-1')
                    break;

            if check:
                break
        diff = [l for l in range(k) if nn[0][l] != nn[1][l]]
        mid = []
        check2 = False
        for i in range(k):
            if nn[0][i] in mid:
                check2 = True
                break
            mid.append(nn[0][i])
        #print(diff)
        if not check:
            res = list(nn[0])
            check = False
            for i in range(len(diff)):
                if check:
                    break
                for j in range(k):
                    if i == j:
                        continue
                    res[diff[i]],res[j] = res[j], res[diff[i]]
                    ans = ''.join(res)
                    #print(ans)
                    check = True
                    for x in range(n):
                        mid = [ans[y] for y in range(k) if nn[x][y] != ans[y]]
                        #print(len(diff))
                        if len(mid) == 2:
                            continue
                        elif len(mid) == 0 and check2:
                   ...


I found an interesting problem on https://codeforces.com/problemset/problem/904/A:
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car.

Masha came to test these cars. She could climb into all cars, but she liked only the smallest car.

It's known that a character with size a can climb into some car with size b if and only if a ≤ b, he or she likes it if and only if he can climb into this car and 2a ≥ b.

You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.

-----Input-----

You are given four integers V_1, V_2, V_3, V_{m}(1 ≤ V_{i} ≤ 100) — sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V_1 > V_2 > V_3.

-----Output-----

Output three integers — sizes of father bear's car, mother bear's car and son bear's car, respectively.

If there are multiple possible solutions, print any.

If there is no solution, print "-1" (without quotes).

-----Examples-----
Input
50 30 10 10

Output
50
30
10

Input
100 50 10 21

Output
-1

-----Note-----

In first test case all conditions for cars' sizes are satisfied.

In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20.

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

def f(a, b):
    return a <= b and not 2 * a >= b

V1, V2, V3, Vm = map(int, input().split())
for v1 in range(V1, 2 * V1 + 1):
    for v2 in range(V2, min(2 * V2 + 1, v1)):
        for v3 in range(V3, min(2 * V3 + 1, v2)):
            if f(Vm, v1) and f(Vm, v2) and Vm <= v3 <= 2 * Vm:
                print(v1, v2, v3, sep='\n')
                return
print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/904/B:
Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.

The game is played on the following field. [Image]

Players are making moves by turns. At first move a player can put his chip in any cell of any small field. For following moves, there are some restrictions: if during last move the opposite player put his chip to cell with coordinates (x_{l}, y_{l}) in some small field, the next move should be done in one of the cells of the small field with coordinates (x_{l}, y_{l}). For example, if in the first move a player puts his chip to lower left cell of central field, then the second player on his next move should put his chip into some cell of lower left field (pay attention to the first test case). If there are no free cells in the required field, the player can put his chip to any empty cell on any field.

You are given current state of the game and coordinates of cell in which the last move was done. You should find all cells in which the current player can put his chip.

A hare works as a postman in the forest, he likes to foul bears. Sometimes he changes the game field a bit, so the current state of the game could be unreachable. However, after his changes the cell where the last move was done is not empty. You don't need to find if the state is unreachable or not, just output possible next moves according to the rules.

-----Input-----

First 11 lines contains descriptions of table with 9 rows and 9 columns which are divided into 9 small fields by spaces and empty lines. Each small field is described by 9 characters without spaces and empty lines. character "x" (ASCII-code 120) means that the cell is occupied with chip of the first player, character "o" (ASCII-code 111) denotes a field occupied with chip of the second player, character "." (ASCII-code 46) describes empty cell.

The line after the table contains two integers x and y (1 ≤ x, y ≤ 9). They describe coordinates of the cell in...

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

a = [[[['.'] * 3 for i in range(3)] for i in range(3)] for i in range(3)]

for i in range(3):
    s = input().split()
    for j in range(3):
        for h in range(3):
            ch = s[j][h]
            a[0][j][i][h] = ch
x = input()
for i in range(3):
    s = input().split()
    for j in range(3):
        for h in range(3):
            ch = s[j][h]
            a[1][j][i][h] = ch
x = input()
for i in range(3):
    s = input().split()
    for j in range(3):
        for h in range(3):
            ch = s[j][h]
            a[2][j][i][h] = ch

x, y = map(int, input().split())
x = x % 3 - 1
y = y % 3 - 1

fl = True

for i in range(3):
    for j in range(3):
        if a[x][y][i][j] == '.':
            fl = False
            a[x][y][i][j] = '!'

if fl:
    for x in range(3):
        for y in range(3):
            for i in range(3):
                for j in range(3):
                    if a[x][y][i][j] == '.':
                        a[x][y][i][j] = '!'

for i in range(3):
    for j in range(3):
        print(*a[0][j][i], sep='', end=' ')
    print()
print()
for i in range(3):
    for j in range(3):
        print(*a[1][j][i], sep='', end=' ')
    print()
print()
for i in range(3):
    for j in range(3):
        print(*a[2][j][i], sep='', end=' ')
    print()


I found an interesting problem on https://codeforces.com/problemset/problem/904/C:
Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.

Valentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of actions Valentin did.

The next n lines contain descriptions of his actions, each line contains description of one action. Each action can be of one of three types:   Valentin pronounced some word and didn't get an electric shock. This action is described by the string ". w" (without quotes), in which "." is a dot (ASCII-code 46), and w is the word that Valentin said.  Valentin pronounced some word and got an electric shock. This action is described by the string "! w" (without quotes), in which "!" is an exclamation mark (ASCII-code 33), and w is the word that Valentin said.  Valentin made a guess about the selected letter. This action is described by the string "? s" (without quotes), in which "?" is a question mark (ASCII-code 63), and s is the guess — a lowercase English letter.

All words consist only of lowercase English letters. The total length of all words does not exceed 10^5.

It is guaranteed that last action is a guess about the selected letter. Also, it is guaranteed that Valentin didn't make correct guesses about the selected letter before the last action. Moreover, it's guaranteed that if Valentin got an electric shock after...

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

n = int(input())
l=[chr(i) for i in range(97,123)]
k=0
for i in range(n):
    d,s=list(map(str, input().split()))
    if d=='!' and len(l)!=1:
        h=0
        while h<len(l):
            if not(l[h] in s):
                l.pop(h)
            else:
                h+=1
    elif d=='.' and len(l)!=1:
        h=0
        while h<len(l):
            if l[h] in s:
                l.pop(h)
            else:
                h+=1
    elif d=='?' and len(l)!=1:
        if s in l:
            l.remove(s)
    elif (d=='?' or d=='!') and i!=n-1:
        k+=1
print(k)


I found an interesting problem on https://codeforces.com/problemset/problem/906/C:
Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.

At each step he selects one of his guests A, who pairwise introduces all of his friends to each other. After this action any two friends of A become friends. This process is run until all pairs of guests are friends.

Arseny doesn't want to spend much time doing it, so he wants to finish this process using the minimum number of steps. Help Arseny to do it.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 22; $0 \leq m \leq \frac{n \cdot(n - 1)}{2}$) — the number of guests at the party (including Arseny) and the number of pairs of people which are friends.

Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n; u ≠ v), which means that people with numbers u and v are friends initially. It's guaranteed that each pair of friends is described not more than once and the graph of friendship is connected.

-----Output-----

In the first line print the minimum number of steps required to make all pairs of guests friends.

In the second line print the ids of guests, who are selected at each step.

If there are multiple solutions, you can output any of them.

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

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

Output
1
1

-----Note-----

In the first test case there is no guest who is friend of all other guests, so at least two steps are required to perform the task. After second guest pairwise introduces all his friends, only pairs of guests (4, 1) and (4, 2) are not friends. Guest 3 or 5 can introduce them.

In the second test case guest number 1 is a friend of all guests, so he can pairwise introduce all guests in one step.

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

from collections import defaultdict
def count(x):
    c=0
    while x > 0:
        c+=1
        x &= (x-1)
    return c

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

mask1=0;mask2=0;MAX=(1<<n)-1
a=[0]*(1 << n)
dp=[MAX]*(1 << n)
if m == (n*(n-1))//2:
    print(0)
    return
for i,j in list(g.items()):
    mask1  = (1 << i);mask2=0;mask2 |= mask1
    for k in j:
        mask2 |= (1 << k)

    dp[mask2]=mask1
    a[mask1]=mask2

for i in range(0,(1 << n)-1):
    if dp[i] != MAX:
        #print('HEllo')
        temp = dp[i] ^ i
        for j in range(n):
            if temp & (1 << j) != 0:
                nmask = i | a[(1 << j)]
                dp[nmask]=dp[i] | (1 << j) if count(dp[i] | (1 << j)) < count(dp[nmask]) else dp[nmask]

ans = []
for i in range(n):
    if dp[-1] & (1 << i) != 0:
        ans.append(i+1)
print(len(ans))
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/908/A:
Your friend has n cards.

You know that each card has a lowercase English letter on one side and a digit on the other.

Currently, your friend has laid out the cards on a table so only one side of each card is visible.

You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.

For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.

To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.

-----Input-----

The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit.

-----Output-----

Print a single integer, the minimum number of cards you must turn over to verify your claim.

-----Examples-----
Input
ee

Output
2

Input
z

Output
0

Input
0ay1

Output
2

-----Note-----

In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side.

In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them.

In the third sample, we need to flip the second and fourth cards.

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

s = input()
ans = 0
for l in s:
    if l in 'aeiou13579':
        ans +=1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/908/B:
Bob programmed a robot to navigate through a 2d maze.

The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.

There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.

The robot can only move up, left, right, or down.

When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.

The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.

Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.

-----Input-----

The first line of input will contain two integers n and m (2 ≤ n, m ≤ 50), denoting the dimensions of the maze.

The next n lines will contain exactly m characters each, denoting the maze.

Each character of the maze will be '.', '#', 'S', or 'E'.

There will be exactly one 'S' and exactly one 'E' in the maze.

The last line will contain a single string s (1 ≤ |s| ≤ 100) — the instructions given to the robot. Each character of s is a digit from 0 to 3.

-----Output-----

Print a single integer, the number of mappings of digits to directions that will lead the robot to the...

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

import sys
input = sys.stdin.readline

n, m = map(int, input().split())
a = [input() for i in range(n)]
s = input().strip()

for i in range(n):
  for j in range(m):
    if a[i][j] == 'S':
      sx, sy = i, j
    if a[i][j] == 'E':
      ex, ey = i, j

ans = 0

import itertools
for p in itertools.permutations([(-1, 0), (1, 0), (0, 1), (0, -1)], 4):
  x, y = sx, sy
  good = True
  for v in s:
    x += p[int(v)][0]
    y += p[int(v)][1]
    if not(0 <= x < n and 0 <= y < m and a[x][y] != '#'):
      good = False
    if (x, y) == (ex, ey):
      break
  if (x, y) != (ex, ey):
    good = False
  if good:
    ans += 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/908/C:
Carol is currently curling.

She has n disks each with radius r on the 2D plane.

Initially she has all these disks above the line y = 10^100.

She then will slide the disks towards the line y = 0 one by one in order from 1 to n.

When she slides the i-th disk, she will place its center at the point (x_{i}, 10^100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk.

Compute the y-coordinates of centers of all the disks after all disks have been pushed.

-----Input-----

The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively.

The next line will contain n integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 1 000) — the x-coordinates of the disks.

-----Output-----

Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10^{ - 6}.

Namely, let's assume that your answer for a particular value of a coordinate 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}$ for all coordinates.

-----Example-----
Input
6 2
5 5 6 8 3 12

Output
2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613

-----Note-----

The final positions of the disks will look as follows: [Image]

In particular, note the position of the last disk.

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

n,r = list(map(int,input().split()))
X = [int(x) for x in input().split()]

Y = []
for i in range(n):
    forcedy = r
    for j in range(len(Y)):
        dist = abs(X[i]-X[j])
        if dist <= 2*r:
            y = Y[j] + ((2*r)**2-dist**2)**.5
            forcedy = max(y,forcedy)
    Y.append(forcedy)
print(*Y)


I found an interesting problem on https://codeforces.com/problemset/problem/908/D:
You are given three integers k, p_{a} and p_{b}.

You will construct a sequence with the following algorithm: Initially, start with the empty sequence. Each second, you do the following. With probability p_{a} / (p_{a} + p_{b}), add 'a' to the end of the sequence. Otherwise (with probability p_{b} / (p_{a} + p_{b})), add 'b' to the end of the sequence.

You stop once there are at least k subsequences that form 'ab'. Determine the expected number of times 'ab' is a subsequence in the resulting sequence. It can be shown that this can be represented by P / Q, where P and Q are coprime integers, and $Q \neq 0 \operatorname{mod}(10^{9} + 7)$. Print the value of $P \cdot Q^{-1} \operatorname{mod}(10^{9} + 7)$.

-----Input-----

The first line will contain three integers integer k, p_{a}, p_{b} (1 ≤ k ≤ 1 000, 1 ≤ p_{a}, p_{b} ≤ 1 000 000).

-----Output-----

Print a single integer, the answer to the problem.

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

Output
2

Input
3 1 4

Output
370000006

-----Note-----

The first sample, we will keep appending to our sequence until we get the subsequence 'ab' at least once. For instance, we get the sequence 'ab' with probability 1/4, 'bbab' with probability 1/16, and 'aab' with probability 1/8. Note, it's impossible for us to end with a sequence like 'aabab', since we would have stopped our algorithm once we had the prefix 'aab'.

The expected amount of times that 'ab' will occur across all valid sequences is 2.

For the second sample, the answer is equal to $\frac{341}{100}$.

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

from collections import defaultdict as di
import sys
sys.setreqursiondepth = 1000000
MOD = int(1e9+7)
def modinvEuler(x,mod):
    # if mod is prime
    return pow(x, mod-2, mod)
    # otherwise exponent should be totient(mod)-1

k,pa,pb = [int(x) for x in input().split()]
Pa = (pa*modinvEuler(pa+pb,MOD))%MOD
Pb = (1-Pa)%MOD

Ea = modinvEuler(Pa,MOD)
Eb = modinvEuler(Pb,MOD)

Pbinv = modinvEuler(Pb,MOD)

mem = di()
def f(na,ns):
    #nonlocal k,Pa,Pb
    if ns>=k:
        return ns
    if na+ns>=k:
        total = ns
        total += na
        total += Pa*Pbinv
        total%= MOD
        return total
    if (na,ns) not in mem:
        mem[(na,ns)] = ( Pa*(f(na+1,ns))+Pb*(f(na,ns+na)) )%MOD

    return mem[(na,ns)]
print((f(1,0))%MOD)


I found an interesting problem on https://codeforces.com/problemset/problem/908/E:
You are given an integer m.

Let M = 2^{m} - 1.

You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.

A set of integers S is called "good" if the following hold.   If $a \in S$, then [Image].  If $a, b \in S$, then $a \text{AND} b \in S$  $T \subseteq S$  All elements of S are less than or equal to M.

Here, $XOR$ and $\text{AND}$ refer to the bitwise XOR and bitwise AND operators, respectively.

Count the number of good sets S, modulo 10^9 + 7.

-----Input-----

The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2^{m}, 50)).

The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.

-----Output-----

Print a single integer, the number of good sets modulo 10^9 + 7.

-----Examples-----
Input
5 3
11010
00101
11000

Output
4

Input
30 2
010101010101010010101010101010
110110110110110011011011011011

Output
860616440

-----Note-----

An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.

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

from collections import defaultdict as di
MOD = int(1e9+7)

bells = di(int)
bells[0,0] = 1
K=1000
for j in range(1,K):
    bells[0,j] = bells[j-1,j-1]
    for i in range(j):
        bells[i+1,j] = (bells[i,j] + bells[i,j-1])%MOD

def bellman(n):
    return bells[n-1,n-1]

m,n = [int(x) for x in input().split()]
Tlist = []

for _ in range(n):
    Tlist.append(input())
numbs = []
for i in range(m):
    numb = []
    for j in range(n):
        numb.append(Tlist[j][i])
    numbs.append(int(''.join(numb),2))

eqsize = di(lambda:0)
for numb in numbs:
    eqsize[numb]+=1
sets = []
for numb in eqsize:
    sets.append(eqsize[numb])
parts = 1
for s in sets:
    parts*=bellman(s)
    parts%=MOD
print(parts)


I found an interesting problem on https://codeforces.com/problemset/problem/908/F:
Roy and Biv have a set of n points on the infinite number line.

Each point has one of 3 colors: red, green, or blue.

Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.

They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).

However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.

Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).

Help them compute the minimum cost way to choose edges to satisfy the above constraints.

-----Input-----

The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points.

The next n lines will contain two tokens p_{i} and c_{i} (p_{i} is an integer, 1 ≤ p_{i} ≤ 10^9, c_{i} is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.

-----Output-----

Print a single integer, the minimum cost way to solve the problem.

-----Examples-----
Input
4
1 G
5 R
10 B
15 G

Output
23

Input
4
1 G
2 R
3 B
10 G

Output
12

-----Note-----

In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively.

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

r = g = b = 0
R = G = B = 0
s = u = v = 0
f = lambda k: k if k else n
for i in range(int(input())):
    q, c = input().split()
    n = int(q)
    if c in 'RG': r, R, u = f(r), n, max(u, n - R)
    if c in 'BG': b, B, v = f(b), n, max(v, n - B)
    if c == 'G':
        if g: s -= max(u + v, n - G)
        g, G, u, v = f(g), n, 0, 0
print(s + R - r + G - g + B - b)


I found an interesting problem on https://codeforces.com/problemset/problem/909/A:
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.

You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).

As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".

-----Input-----

The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.

-----Output-----

Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.

-----Examples-----
Input
harry potter

Output
hap

Input
tom riddle

Output
tomr

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

s1, s2 = input().split()
a = []
for i in range(1, len(s1) + 1):
    for j in range(1, len(s2) + 1):
        a.append(s1[:i] + s2[:j])
a.sort()
print(a[0])


I found an interesting problem on https://codeforces.com/problemset/problem/909/B:
You are given an integer N. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and N, inclusive; there will be $\frac{n(n + 1)}{2}$ of them.

You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endpoints though). You can not move the segments to a different location on the coordinate axis.

Find the minimal number of layers you have to use for the given N.

-----Input-----

The only input line contains a single integer N (1 ≤ N ≤ 100).

-----Output-----

Output a single integer - the minimal number of layers required to draw the segments for the given N.

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

Output
2

Input
3

Output
4

Input
4

Output
6

-----Note-----

As an example, here are the segments and their optimal arrangement into layers for N = 4. [Image]

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

n = int(input())

cnt = 0
while n > 0:
    cnt += n
    n -= 2

print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/909/C:
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.

We will consider an extremely simplified subset of Python with only two types of statements.

Simple statements are written in a single line, one per line. An example of a simple statement is assignment.

For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.

You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.

-----Input-----

The first line contains a single integer N (1 ≤ N ≤ 5000) — the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.

-----Output-----

Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 10^9 + 7.

-----Examples-----
Input
4
s
f
f
s

Output
1

Input
4
f
s
f
s

Output
2

-----Note-----

In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.

simple statement

for statement

    for statement

        simple statement

In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.

for statement

    simple statement

    for statement

        simple statement

or

for statement

    simple statement

for statement

    simple statement

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

n = int(input())

ar = []

dp = [0] * 5005
cum = [0] * 5005

mod = int( 1e9 + 7 )

for i in range( n ):
        s = input()
        ar.append( s )

for i in range( 5000 ):
        dp[i] = 1
        cum[i] = dp[i] + ( cum[i - 1] if i > 0 else 0 )
        cum[i] = cum[i] - mod if cum[i] >= mod else cum[i]

for i in range( n -  2, -1, - 1 ):
        for j in range( 5000 ):
                dp[j] = dp[j + 1] if ar[i] == "f" else cum[j]
                dp[j] = dp[j] - mod if dp[j] >= mod else dp[j]
                cum[j] = dp[j] + ( cum[j - 1] if j > 0 else 0 )
                cum[j] = cum[j] - mod if cum[j] >= mod else cum[j]

print( dp[0] )