I found an interesting problem on https://codeforces.com/problemset/problem/304/B:
Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows:

 Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year.  [Image]

In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February.

Look at the sample to understand what borders are included in the aswer.

-----Input-----

The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≤ yyyy ≤ 2038 and yyyy:mm:dd is a legal date).

-----Output-----

Print a single integer — the answer to the problem.

-----Examples-----
Input
1900:01:01
2038:12:31

Output
50768

Input
1996:03:09
1991:11:12

Output
1579

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

from datetime import date
y1,m1,d1=list(map(int,input().split(':')))
y2,m2,d2=list(map(int,input().split(':')))

a=date(y1,m1,d1)
b=date(y2,m2,d2)
print(abs((b-a).days))


I found an interesting problem on https://codeforces.com/problemset/problem/305/A:
Unfortunately, Vasya can only sum pairs of integers (a, b), such that for any decimal place at least one number has digit 0 in this place. For example, Vasya can sum numbers 505 and 50, but he cannot sum 1 and 4.

Vasya has a set of k distinct non-negative integers d_1, d_2, ..., d_{k}.

Vasya wants to choose some integers from this set so that he could sum any two chosen numbers. What maximal number of integers can he choose in the required manner?

-----Input-----

The first input line contains integer k (1 ≤ k ≤ 100) — the number of integers.

The second line contains k distinct space-separated integers d_1, d_2, ..., d_{k} (0 ≤ d_{i} ≤ 100).

-----Output-----

In the first line print a single integer n the maximum number of the chosen integers. In the second line print n distinct non-negative integers — the required integers.

If there are multiple solutions, print any of them. You can print the numbers in any order.

-----Examples-----
Input
4
100 10 1 0

Output
4
0 1 10 100
Input
3
2 70 3

Output
2
2 70

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

n, t, p = int(input()), set(input().split()), []
if '100' in t:
    p.append('100')
    t.remove('100')
if '0' in t:
    p.append('0')
    t.remove('0')
k = len(p)
for i in range(10, 100, 10):
    if str(i) in t:
        p.append(str(i))
        break
for i in range(1, 10):
    if str(i) in t:
        p.append(str(i))
        break
if k == len(p) and t: p.append(t.pop())
print(len(p))
print(' '.join(p))


I found an interesting problem on https://codeforces.com/problemset/problem/305/B:
A continued fraction of height n is a fraction of form $a_{1} + \frac{1}{a_{2} + \frac{1}{\ldots + \frac{1}{a_{n}}}}$. You are given two rational numbers, one is represented as [Image] and the other one is represented as a finite fraction of height n. Check if they are equal.

-----Input-----

The first line contains two space-separated integers p, q (1 ≤ q ≤ p ≤ 10^18) — the numerator and the denominator of the first fraction.

The second line contains integer n (1 ≤ n ≤ 90) — the height of the second fraction. The third line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^18) — the continued fraction.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

-----Output-----

Print "YES" if these fractions are equal and "NO" otherwise.

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

Output
YES

Input
9 4
3
2 3 1

Output
YES

Input
9 4
3
1 2 4

Output
NO

-----Note-----

In the first sample $2 + \frac{1}{4} = \frac{9}{4}$.

In the second sample $2 + \frac{1}{3 + \frac{1}{1}} = 2 + \frac{1}{4} = \frac{9}{4}$.

In the third sample $1 + \frac{1}{2 + \frac{1}{4}} = \frac{13}{9}$.

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

s = input()
a = s.split()
p = int(a[0])
q = int(a[1])
n = input()
s = input()
se = s.split()
for c in se:
    e = int(c)
    t1 = p-e*q
    t2 = q
    p = t2
    q = t1
if q == 0:
    print('YES')
else :
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/305/C:
Ivan has got an array of n non-negative integers a_1, a_2, ..., a_{n}. Ivan knows that the array is sorted in the non-decreasing order.

Ivan wrote out integers 2^{a}_1, 2^{a}_2, ..., 2^{a}_{n} on a piece of paper. Now he wonders, what minimum number of integers of form 2^{b} (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2^{v} - 1 for some integer v (v ≥ 0).

Help Ivan, find the required quantity of numbers.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5). The second input line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 2·10^9). It is guaranteed that a_1 ≤ a_2 ≤ ... ≤ a_{n}.

-----Output-----

Print a single integer — the answer to the problem.

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

Output
0

Input
1
3

Output
3

-----Note-----

In the first sample you do not need to add anything, the sum of numbers already equals 2^3 - 1 = 7.

In the second sample you need to add numbers 2^0, 2^1, 2^2.

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

n=int(input())
a=list(map(int,input().split()))
st=set()
for e in a :
    while(e in st):
        st.remove(e)
        e+=1
    st.add(e)
print(max(st)-len(st)+1)


I found an interesting problem on https://codeforces.com/problemset/problem/306/A:
Polycarpus has got n candies and m friends (n ≥ m). He wants to make a New Year present with candies to each friend. Polycarpus is planning to present all candies and he wants to do this in the fairest (that is, most equal) manner. He wants to choose such a_{i}, where a_{i} is the number of candies in the i-th friend's present, that the maximum a_{i} differs from the least a_{i} as little as possible.

For example, if n is divisible by m, then he is going to present the same number of candies to all his friends, that is, the maximum a_{i} won't differ from the minimum one.

-----Input-----

The single line of the input contains a pair of space-separated positive integers n, m (1 ≤ n, m ≤ 100;n ≥ m) — the number of candies and the number of Polycarpus's friends.

-----Output-----

Print the required sequence a_1, a_2, ..., a_{m}, where a_{i} is the number of candies in the i-th friend's present. All numbers a_{i} must be positive integers, total up to n, the maximum one should differ from the minimum one by the smallest possible value.

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

Output
4 4 4
Input
15 4

Output
3 4 4 4
Input
18 7

Output
2 2 2 3 3 3 3

-----Note-----

Print a_{i} in any order, separate the numbers by spaces.

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

I=[int(i) for i in input().split()]
conf, friend = I[0], I[1]
answer=[]
ans=""
mod=conf%friend
for i in range(friend): answer.append(int((conf-mod)/friend))
for i in range(mod): answer[i]+=1
for i in range(friend): ans+=str(answer[i])+" "
print(ans[:-1])


I found an interesting problem on https://codeforces.com/problemset/problem/312/A:
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.

-----Input-----

The first line of the input contains an integer n (1 ≤ n ≤ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesn’t exceed 100.

-----Output-----

For each sentence, output "Freda's" if the sentence was said by Freda, "Rainbow's" if the sentence was said by Rainbow, or "OMG>.< I don't know!" if liouzhou_101 can’t recognize whose sentence it is. He can’t recognize a sentence if it begins with "miao." and ends with "lala.", or satisfies neither of the conditions.

-----Examples-----
Input
5
I will go to play with you lala.
wow, welcome.
miao.lala.
miao.
miao .

Output
Freda's
OMG>.< I don't know!
OMG>.< I don't know!
Rainbow's
OMG>.< I don't know!

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

n = int(input())
for i in range(n):
    S = input()
    flag1 = len(S) >= 5 and S[:5] == "miao."
    flag2 = len(S) >= 5 and S[-5:] == "lala."
    if flag1 and flag2:
        print("OMG>.< I don't know!")
    elif flag2:
        print("Freda's")
    elif flag1:
        print("Rainbow's")
    else:
        print("OMG>.< I don't know!")


I found an interesting problem on https://codeforces.com/problemset/problem/312/B:
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is $\frac{a}{b}$ for SmallR while $\frac{c}{d}$ for Zanoes. The one who shoots in the target first should be the winner.

Output the probability that SmallR will win the match.

-----Input-----

A single line contains four integers $a, b, c, d(1 \leq a, b, c, d \leq 1000,0 < \frac{a}{b} < 1,0 < \frac{c}{d} < 1)$.

-----Output-----

Print a single real number, the probability that SmallR will win the match.

The answer will be considered correct if the absolute or relative error doesn't exceed 10^{ - 6}.

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

Output
0.666666666667

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/313/A:
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money.

Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance.

Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift.

-----Input-----

The single line contains integer n (10 ≤ |n| ≤ 10^9) — the state of Ilya's bank account.

-----Output-----

In a single line print an integer — the maximum state of the bank account that Ilya can get.

-----Examples-----
Input
2230

Output
2230

Input
-10

Output
0

Input
-100003

Output
-10000

-----Note-----

In the first test sample Ilya doesn't profit from using the present.

In the second test sample you can delete digit 1 and get the state of the account equal to 0.

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/313/B:
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.

You've got string s = s_1s_2... s_{n} (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers l_{i}, r_{i} (1 ≤ l_{i} < r_{i} ≤ n). The answer to the query l_{i}, r_{i} is the number of such integers i (l_{i} ≤ i < r_{i}), that s_{i} = s_{i} + 1.

Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.

-----Input-----

The first line contains string s of length n (2 ≤ n ≤ 10^5). It is guaranteed that the given string only consists of characters "." and "#".

The next line contains integer m (1 ≤ m ≤ 10^5) — the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers l_{i}, r_{i} (1 ≤ l_{i} < r_{i} ≤ n).

-----Output-----

Print m integers — the answers to the queries in the order in which they are given in the input.

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

Output
1
1
5
4

Input
#..###
5
1 3
5 6
1 5
3 6
3 4

Output
1
1
2
2
0

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

string=input()
#dp represents a list of the counts to each point in the string
n=int(input())
a,b=[0 for i in range(n)],[0 for i in range(n)]
for i in range(n):
    a[i],b[i]=map(int,input().split())
dp=[0]*(len(string))
for i in range(len(string)-1):
    if string[i]==string[i+1]:
        dp[i+1]=dp[i]+1
    else:
        dp[i+1]=dp[i]

for i in range(n):
    print(dp[b[i]-1]-dp[a[i]-1])


I found an interesting problem on https://codeforces.com/problemset/problem/313/C:
Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve.

He's got a square 2^{n} × 2^{n}-sized matrix and 4^{n} integers. You need to arrange all these numbers in the matrix (put each number in a single individual cell) so that the beauty of the resulting matrix with numbers is maximum.

The beauty of a 2^{n} × 2^{n}-sized matrix is an integer, obtained by the following algorithm:  Find the maximum element in the matrix. Let's denote it as m.  If n = 0, then the beauty of the matrix equals m. Otherwise, a matrix can be split into 4 non-intersecting 2^{n} - 1 × 2^{n} - 1-sized submatrices, then the beauty of the matrix equals the sum of number m and other four beauties of the described submatrices.

As you can see, the algorithm is recursive.

Help Ilya, solve the problem and print the resulting maximum beauty of the matrix.

-----Input-----

The first line contains integer 4^{n} (1 ≤ 4^{n} ≤ 2·10^6). The next line contains 4^{n} integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the numbers you need to arrange in the 2^{n} × 2^{n}-sized matrix.

-----Output-----

On a single line print the maximum value of the beauty of the described matrix.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

Output
13

Input
4
1 2 3 4

Output
14

-----Note-----

Consider the second sample. You need to arrange the numbers in the matrix as follows:

1 2

3 4

Then the beauty of the matrix will equal: 4 + 1 + 2 + 3 + 4 = 14.

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

def arr_inp():
    return [float(x) for x in input().split()]

def solve(n):
    nonlocal s
    if n == 1:
        s += a[0]
        return
    else:
        solve(n // 4)
    s += sum(a[:n])

n, a, s = int(input()), arr_inp(), 0
a = sorted(a, reverse=True)
while (a):
    s += sum(a)
    n //= 4
    a = a[:n]

print(int(s))


I found an interesting problem on https://codeforces.com/problemset/problem/315/A:
Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.

Sereja knows that the i-th bottle is from brand a_{i}, besides, you can use it to open other bottles of brand b_{i}. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.

Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ 1000) — the description of the i-th bottle.

-----Output-----

In a single line print a single integer — the answer to the problem.

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

Output
4

Input
4
1 2
2 3
3 4
4 1

Output
0

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

n = int(input())
e = 0
a = []
b = [ [] for i in range(1001) ]
for i in range(n):
    s,t = map(int,input().split())
    a.append([i,s])
    b[t].append(i)
for i in range(len(a)):
    c1 = 0
    for j in range(len(b[a[i][1]])):
        if (b[a[i][1]][j] != i):
            c1 = -1
    if (c1 != -1):
        e = e + 1
print(e)


I found an interesting problem on https://codeforces.com/problemset/problem/315/B:
Sereja has got an array, consisting of n integers, a_1, a_2, ..., a_{n}. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:  Make v_{i}-th array element equal to x_{i}. In other words, perform the assignment a_{v}_{i} = x_{i}.  Increase each array element by y_{i}. In other words, perform n assignments a_{i} = a_{i} + y_{i} (1 ≤ i ≤ n).  Take a piece of paper and write out the q_{i}-th array element. That is, the element a_{q}_{i}.

Help Sereja, complete all his operations.

-----Input-----

The first line contains integers n, m (1 ≤ n, m ≤ 10^5). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the original array.

Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer t_{i} (1 ≤ t_{i} ≤ 3) that represents the operation type. If t_{i} = 1, then it is followed by two integers v_{i} and x_{i}, (1 ≤ v_{i} ≤ n, 1 ≤ x_{i} ≤ 10^9). If t_{i} = 2, then it is followed by integer y_{i} (1 ≤ y_{i} ≤ 10^4). And if t_{i} = 3, then it is followed by integer q_{i} (1 ≤ q_{i} ≤ n).

-----Output-----

For each third type operation print value a_{q}_{i}. Print the values in the order, in which the corresponding queries follow in the input.

-----Examples-----
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9

Output
2
9
11
20
30
40
39

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

# coding: utf-8

from sys import stdin

N, M = list(map(int, input().split()))

A = [int(a) for a in stdin.readline().split()]

globalIncreaser = 0

for i in range(M):
    op = [int(a) for a in stdin.readline().split()]
    opcode = op[0]

    if opcode == 1:
        opcode, v, x = op
        A[v - 1] = x - globalIncreaser

    elif opcode == 2:
        opcode, y = op
        globalIncreaser += y

    elif opcode == 3:
        opcode, q = op
        print(A[q - 1] + globalIncreaser)


I found an interesting problem on https://codeforces.com/problemset/problem/316/A1:
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.

The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.

And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure:

  if s_{i} = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively);  if s_{i} is a digit (between 0 to 9, inclusively), then it means that there is digit s_{i} on position i in code;  if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits.  The length of the safe code coincides with the length of the hint.

For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".

After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using...

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

s=input()

ans=1
x=0
z="ABCDEFGHIJ"
L={}
for item in z:
    L[item]=False;
n=len(s)
for i in range(n):
    if(s[i] in "ABCDEFGHIJ" and i==0):
        ans*=9
        x+=1
        L[s[i]]=True
    elif(s[i] in "ABCDEFGHIJ" and not(L[s[i]])):
        ans*=(10-x)
        x+=1
        L[s[i]]=True
    elif(s[i]=="?" and i==0):
        ans*=9
    elif(s[i]=="?"):
        ans*=10

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/316/B1:
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.

(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.

The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.

Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked...

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

import sys
sys.setrecursionlimit(100000)
def solve():
    n, x, = rv()
    x -= 1
    a, = rl(1)
    a = [val - 1 for val in a]
    nxt = [True] * n
    index = [-1] * n
    for i in range(len(a)):
        index[i] = get(i, a, nxt)
    curindex = index[x] - 1
    others = list()
    for i in range(n):
        if not bad(i, a, x) and nxt[i]:
            others.append(index[i])
    others.sort()
    possible = [False] * (n + 1)
    possible[0] = True
    for val in others:
        pcopy = list(possible)
        for i in range(n + 1):
            if possible[i]:
                both = i + val
                if both < n + 1:
                    pcopy[both] = True
        possible = pcopy
    res = list()
    for i in range(n + 1):
        if possible[i]:
            comb = i + curindex
            if comb < n:
                res.append(comb)
    print('\n'.join(map(str, [val + 1 for val in res])))

def bad(index, a, x):
    if index == x: return True
    if a[index] == x: return True
    if a[index] == -1: return False
    return bad(a[index], a, x)

def get(index, a, nxt):
    if a[index] == -1:
        return 1
    else:
        nxt[a[index]] = False
        return get(a[index], a, nxt) + 1

def prt(l): return print(' '.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()


I found an interesting problem on https://codeforces.com/problemset/problem/316/D3:
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). [Image]  Figure 1. The initial position for n = 5.

After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. [Image]  Figure 2. The example of a throw.

In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.

Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise.

-----Input-----

The first line contains a single number n —...

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/316/E1:
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:

You are given a sequence of integers a_1, a_2, ..., a_{n}. Your task is to perform on it m consecutive operations of the following type:  For given numbers x_{i} and v_{i} assign value v_{i} to element a_{x}_{i}.  For given numbers l_{i} and r_{i} you've got to calculate sum $\sum_{x = 0}^{r_{i} - l_{i}}(f_{x} \cdot a_{l_{i} + x})$, where f_0 = f_1 = 1 and at i ≥ 2: f_{i} = f_{i} - 1 + f_{i} - 2.  For a group of three numbers l_{i} r_{i} d_{i} you should increase value a_{x} by d_{i} for all x (l_{i} ≤ x ≤ r_{i}).

Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 2·10^5) — the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^5). Then follow m lines, each describes an operation. Each line starts with an integer t_{i} (1 ≤ t_{i} ≤ 3) — the operation type:   if t_{i} = 1, then next follow two integers x_{i} v_{i} (1 ≤ x_{i} ≤ n, 0 ≤ v_{i} ≤ 10^5);  if t_{i} = 2, then next follow two integers l_{i} r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n);  if t_{i} = 3, then next follow three integers l_{i} r_{i} d_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n, 0 ≤ d_{i} ≤ 10^5).

The input limits for scoring 30 points are (subproblem E1):   It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type.

The input limits for scoring 70 points are (subproblems E1+E2):   It is guaranteed that there will be queries of the 1-st and 2-nd type only.

The input limits for scoring 100 points are (subproblems E1+E2+E3):   No extra limitations.

-----Output-----

For each query print the calculated sum modulo 1000000000 (10^9).

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

Output
12
32
8
50

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

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

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

f = [1,1]
for i in range(2,n+1):
    f.append(f[i-1] + f[i-2])
    f[i] %= 10 ** 9

for q in range(m):
    z,l,r = map(int,input().split())
    if z == 1:
        a[l-1] = r
    else:
        s = 0
        for j in range(l-1,r):
            s += (a[j] * f[j-l+1])
            s %= 10 ** 9
        print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/316/G1:
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).

A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s_1s_2... s_{|}s| (|s| is a length of s) is string s_{l}s_{l} + 1... s_{r}.

Consider a number of occurrences  of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.

We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].

-----Input-----

The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers p_{i}, l_{i}, r_{i}, separated by single spaces (0 ≤ l_{i} ≤ r_{i} ≤ |p_{i}|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.

The input limits for scoring 30 points are (subproblem G1):   0 ≤ n ≤ 10.  The length of string s and the maximum length of string p is  ≤ 200.

The input limits for scoring 70 points are (subproblems G1+G2):   0 ≤ n ≤ 10.  The length of string s and the maximum length of string p is  ≤ 2000.

The input limits for scoring 100 points are (subproblems G1+G2+G3):   0 ≤ n ≤ 10.  The length of string s and the maximum length of string p is  ≤ 50000.

-----Output-----

Print a single...

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

def count(p, s):
    start = 0
    c = 0
    while True:
        try:
            pos = s.index(p, start)
            c += 1
            start = pos + 1
        except ValueError:
            return c

s = input()
n = int(input())

pravs = []
for i in range(n):
    p, l, r = input().split()
    l = int(l); r = int(r)
    pravs.append((p, l, r))

var = set()
for l in range(len(s)):
    for r in range(l+1, len(s)+1):
        pods = s[l:r]
        for prav in pravs:
            if not prav[1] <= count(pods, prav[0]) <= prav[2]:
                break
        else:
            var.add(pods)

print(len(var))


I found an interesting problem on https://codeforces.com/problemset/problem/317/A:
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.

Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, (x + y).

What is the minimum number of such operations one has to perform in order to make the given pair of integers m-perfect?

-----Input-----

Single line of the input contains three integers x, y and m ( - 10^18 ≤ x, y, m ≤ 10^18).

Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preffered to use the cin, cout streams or the %I64d specifier.

-----Output-----

Print the minimum number of operations or "-1" (without quotes), if it is impossible to transform the given pair to the m-perfect one.

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

Output
2

Input
-1 4 15

Output
4

Input
0 -1 5

Output
-1

-----Note-----

In the first sample the following sequence of operations is suitable: (1, 2) $\rightarrow$ (3, 2) $\rightarrow$ (5, 2).

In the second sample: (-1, 4) $\rightarrow$ (3, 4) $\rightarrow$ (7, 4) $\rightarrow$ (11, 4) $\rightarrow$ (15, 4).

Finally, in the third sample x, y cannot be made positive, hence there is no proper sequence of operations.

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

x, y, m = list(map(int, input().split()))
if max(x, y) >= m:
    print(0)
elif x <= 0 and y <= 0:
    print(-1)
else:
    if x > y:
        x, y = y, x
    ans, st = 0, 0
    add = 0
    if x <= 0:
        st = (0 - x + y - 1) // y
        x += y * st
    ans = st + (m - x + y - 1) // y
    while y < m:
        x, y = y, x + y
        add += 1
        ans = min(ans, add + st + (m - x + y - 1) // y)
    ans = min(ans, add + st)
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/317/D:
Vasya and Petya wrote down all integers from 1 to n to play the "powers" game (n can be quite large; however, Vasya and Petya are not confused by this fact).

Players choose numbers in turn (Vasya chooses first). If some number x is chosen at the current turn, it is forbidden to choose x or all of its other positive integer powers (that is, x^2, x^3, ...) at the next turns. For instance, if the number 9 is chosen at the first turn, one cannot choose 9 or 81 later, while it is still allowed to choose 3 or 27. The one who cannot make a move loses.

Who wins if both Vasya and Petya play optimally?

-----Input-----

Input contains single integer n (1 ≤ n ≤ 10^9).

-----Output-----

Print the name of the winner — "Vasya" or "Petya" (without quotes).

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

Output
Vasya

Input
2

Output
Petya

Input
8

Output
Petya

-----Note-----

In the first sample Vasya will choose 1 and win immediately.

In the second sample no matter which number Vasya chooses during his first turn, Petya can choose the remaining number and win.

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

from sys import stdin, stdout
import math, collections
mod = 10**9+7

def isPower(n):
    if (n <= 1):
        return True
    for x in range(2, (int)(math.sqrt(n)) + 1):
        p = x
        while (p <= n):
            p = p * x
            if (p == n):
                return True

    return False
n = int(input())
arr = [0,1,2,1,4,3,2,1,5,6,2,1,8,7,5,9,8,7,3,4,7,4,2,1,10,9,3,6,11,12]
ans = arr[int(math.log(n, 2))]
s = int(math.log(n, 2))
for i in range(3, int(n**0.5)+1):
    if not isPower(i):
        ans^=arr[int(math.log(n, i))]
        s+=int(math.log(n, i))
ans^=((n-s)%2)
print("Vasya" if ans else "Petya")


I found an interesting problem on https://codeforces.com/problemset/problem/318/A:
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the following sequence of numbers: firstly all odd integers from 1 to n (in ascending order), then all even integers from 1 to n (also in ascending order). Help our hero to find out which number will stand at the position number k.

-----Input-----

The only line of input contains integers n and k (1 ≤ k ≤ n ≤ 10^12).

Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

-----Output-----

Print the number that will stand at the position number k after Volodya's manipulations.

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

Output
5
Input
7 7

Output
6

-----Note-----

In the first sample Volodya's sequence will look like this: {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}. The third place in the sequence is therefore occupied by the number 5.

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

import sys
from math import ceil
my_file = sys.stdin
#my_file = open("input.txt", "r")
line = my_file.readline().split()
n, k = int(line[0]), int(line[1])

if n%2 == 0:
    if k <= n/2:
        print(k*2-1)
    else:
        print(int((k-n/2)*2))
else:
    if k <= ceil(n/2):
        print(k*2-1)
    else:
        print(int((k-ceil(n/2))*2))


I found an interesting problem on https://codeforces.com/problemset/problem/318/B:
Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.

Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.

For simplicity, let us assume that Volodya's text can be represented as a single string.

-----Input-----

Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 10^6 characters.

-----Output-----

Print exactly one number — the number of powerful substrings of the given string.

Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

-----Examples-----
Input
heavymetalisheavymetal

Output
3
Input
heavymetalismetal

Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou

Output
3

-----Note-----

In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.

In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal".

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

s = input()
l = len(s)
k = [ 0 for i in range(l) ]

start = 0
while True:
    temp = s.find("heavy",start,l)
    if temp==-1:
        break
    else:
        k[temp] = 1
        start = temp+1

start = 0
while True:
    temp = s.find("metal",start,l)
    if temp==-1:
        break
    else:
        k[temp] = 2
        start = temp+1

sol = 0
ones = 0
for i in range(l):
    if k[i]==1:
        ones+=1
    elif k[i]==2:
        sol+=ones

print(sol)


I found an interesting problem on https://codeforces.com/problemset/problem/319/A:
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2^{n} members and coincidentally Natalia Fan Club also has 2^{n} members. Each member of MDC is assigned a unique id i from 0 to 2^{n} - 1. The same holds for each member of NFC.

One of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers (a, b) such that member a from MDC dances with member b from NFC.

The complexity of a pairs' assignment is the number of pairs of dancing pairs (a, b) and (c, d) such that a < c and b > d.

You are given a binary number of length n named x. We know that member i from MDC dances with member $i \oplus x$ from NFC. Your task is to calculate the complexity of this assignment modulo 1000000007 (10^9 + 7).

Expression $x \oplus y$ denotes applying «XOR» to numbers x and y. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as «^», in Pascal — «xor».

-----Input-----

The first line of input contains a binary number x of lenght n, (1 ≤ n ≤ 100).

This number may contain leading zeros.

-----Output-----

Print the complexity of the given dance assignent modulo 1000000007 (10^9 + 7).

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

Output
6

Input
01

Output
2

Input
1

Output
1

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

#!/usr/bin/env python3
p = 1000000007
s = input()
print(int(s,2) * pow(2, len(s) - 1) % p)


I found an interesting problem on https://codeforces.com/problemset/problem/320/A:
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not.

You're given a number. Determine if it is a magic number or not.

-----Input-----

The first line of input contains an integer n, (1 ≤ n ≤ 10^9). This number doesn't contain leading zeros.

-----Output-----

Print "YES" if n is a magic number or print "NO" if it's not.

-----Examples-----
Input
114114

Output
YES

Input
1111

Output
YES

Input
441231

Output
NO

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

from re import match

print(match(r"^(14?4?)*$", input()) and 'YES' or 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/320/B:
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I_1 from our set to interval I_2 from our set if there is a sequence of successive moves starting from I_1 so that we can reach I_2.

Your program should handle the queries of the following two types:  "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval?

Answer all the queries. Note, that initially you have an empty set of intervals.

-----Input-----

The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 10^9 by their absolute value.

It's guaranteed that all queries are correct.

-----Output-----

For each query of the second type print "YES" or "NO" on a separate line depending on the answer.

-----Examples-----
Input
5
1 1 5
1 5 11
2 1 2
1 2 9
2 1 2

Output
NO
YES

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

path = []
n = int(input())
for it in range(0, n):
	data = list(map(int, input().split(' ')))
	if data[0] == 1:
		path.append(data[1:])
	else:
		vis = [False] * (len(path) + 1)
		que = [data[1] - 1]
		while len(que):
			p = que[0]
			del que[0]
			for i, v in enumerate(path):
				if (v[0] < path[p][0] < v[1] or v[0] < path[p][1] < v[1]) and not vis[i]:
					vis[i] = True
					que.append(i)
		print('YES' if vis[data[2] -1] else 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/321/A:
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all:  'U': go up, (x, y)  →  (x, y+1);  'D': go down, (x, y)  →  (x, y-1);  'L': go left, (x, y)  →  (x-1, y);  'R': go right, (x, y)  →  (x+1, y).

The robot will do the operations in s from left to right, and repeat it infinite times. Help Fox Ciel to determine if after some steps the robot will located in (a, b).

-----Input-----

The first line contains two integers a and b, ( - 10^9 ≤ a, b ≤ 10^9). The second line contains a string s (1 ≤ |s| ≤ 100, s only contains characters 'U', 'D', 'L', 'R') — the command.

-----Output-----

Print "Yes" if the robot will be located at (a, b), and "No" otherwise.

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

Output
Yes

Input
1 2
RU

Output
No

Input
-1 1000000000
LRRLU

Output
Yes

Input
0 0
D

Output
Yes

-----Note-----

In the first and second test case, command string is "RU", so the robot will go right, then go up, then right, and then up and so on.

The locations of its moves are (0, 0)  →  (1, 0)  →  (1, 1)  →  (2, 1)  →  (2, 2)  →  ...

So it can reach (2, 2) but not (1, 2).

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

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

def L(): return list(R())

from collections import Counter

import math
import sys

from itertools import permutations

import bisect

a,b=R()

s=S()
l=len(s)
step=[]

x,y=0,0

d={'U':(0,1), 'D':(0,-1), 'L':(-1,0), 'R':(1,0)}

step.append((0,0))

for i in range(l):
    dx,dy=d[s[i]]
    x+=dx
    y+=dy

    step.append((x,y))

tx,ty=step[l]

for j in range(l):
    xj,yj=step[j]

    if tx==0 and ty==0:
        if a==xj and b==yj:
            print('Yes')
            return

        else:
            continue

    if tx==0 and (a!=xj or (b-yj)%ty!=0 or ((b-yj)%ty==0 and (b-yj)/ty<0)):
        continue

    if ty==0 and (b!=yj or (a-xj)%tx!=0 or ((a-xj)%tx==0 and (a-xj)/tx<0)):
        continue

    if tx==0 or ty==0:
        print('Yes')
        return

    if (a-xj)%tx==0 and (b-yj)%ty==0 and (a-xj)/tx==(b-yj)/ty>=0:
        print('Yes')
        return

print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/321/B:
Fox Ciel is playing a card game with her friend Jiro.

Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.

Now is Ciel's battle phase, Ciel can do the following operation many times:  Choose one of her cards X. This card mustn't be chosen before.  If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then:   If Y's position is Attack, then (X's strength)  ≥  (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength).  If Y's position is Defense, then (X's strength)  >  (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage.

Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of cards Jiro and Ciel have.

Each of the next n lines contains a string position and an integer strength (0 ≤ strength ≤ 8000) — the position and strength of Jiro's current card. Position is the string "ATK" for attack, and the string "DEF" for defense.

Each of the next m lines contains an integer strength (0 ≤ strength ≤ 8000) — the strength of Ciel's current card.

-----Output-----

Output an integer: the maximal damage Jiro can get.

-----Examples-----
Input
2 3
ATK 2000
DEF 1700
2500
2500
2500

Output
3000

Input
3 4
ATK 10
ATK 100
ATK 1000
1
11
101
1001

Output
992

Input
2 4
DEF 0
ATK 0
0
0
1
1

Output
1

-----Note-----

In the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack "ATK 2000" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the "DEF 1700"...

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

n, m = map(int, input().split())
a, d = [1e9], [1e9]
for x in range(n):
    p, s = input().split()
    [d, a][p < 'B'].append(int(s))
v = [int(input()) for y in range(m)]
for q in [a, d, v]: q.sort()
s = sum(v)
i = j = 0
for t in v:
    if t > d[i]: s, i = s - t, i + 1
    elif t >= a[j]: s, j = s - a[j], j + 1
if i + j - n: s = 0
print(max(s, sum(max(0, y - x) for x, y in zip(a, v[::-1]))))


I found an interesting problem on https://codeforces.com/problemset/problem/322/A:
Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:  either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before);  or the girl in the dancing pair must dance for the first time.

Help Fox Ciel to make a schedule that they can dance as many songs as possible.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of boys and girls in the dancing room.

-----Output-----

In the first line print k — the number of songs during which they can dance. Then in the following k lines, print the indexes of boys and girls dancing during songs chronologically. You can assume that the boys are indexed from 1 to n, and the girls are indexed from 1 to m.

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

Output
2
1 1
2 1

Input
2 2

Output
3
1 1
1 2
2 2

-----Note-----

In test case 1, there are 2 boys and 1 girl. We can have 2 dances: the 1st boy and 1st girl (during the first song), the 2nd boy and 1st girl (during the second song).

And in test case 2, we have 2 boys with 2 girls, the answer is 3.

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

def Comp(n,m):
    count = n+m-1
    print(str(count))
    print("1 1")
    for i in range(2,m+1):
        print("1 "+str(i))
    for i in range(2,n+1):
        print(str(i)+" 1")

Comp(*list(map(int,input().split())))


I found an interesting problem on https://codeforces.com/problemset/problem/322/B:
Fox Ciel has some flowers: r red flowers, g green flowers and b blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets:

  To make a "red bouquet", it needs 3 red flowers.  To make a "green bouquet", it needs 3 green flowers.  To make a "blue bouquet", it needs 3 blue flowers.  To make a "mixing bouquet", it needs 1 red, 1 green and 1 blue flower.

Help Fox Ciel to find the maximal number of bouquets she can make.

-----Input-----

The first line contains three integers r, g and b (0 ≤ r, g, b ≤ 10^9) — the number of red, green and blue flowers.

-----Output-----

Print the maximal number of bouquets Fox Ciel can make.

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

Output
6

Input
4 4 4

Output
4

Input
0 0 0

Output
0

-----Note-----

In test case 1, we can make 1 red bouquet, 2 green bouquets and 3 blue bouquets.

In test case 2, we can make 1 red, 1 green, 1 blue and 1 mixing bouquet.

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/323/A:
You are given a cube of size k × k × k, which consists of unit cubes. Two unit cubes are considered neighbouring, if they have common face.

Your task is to paint each of k^3 unit cubes one of two colours (black or white), so that the following conditions must be satisfied:  each white cube has exactly 2 neighbouring cubes of white color;  each black cube has exactly 2 neighbouring cubes of black color.

-----Input-----

The first line contains integer k (1 ≤ k ≤ 100), which is size of the cube.

-----Output-----

Print -1 if there is no solution. Otherwise, print the required painting of the cube consequently by layers. Print a k × k matrix in the first k lines, showing how the first layer of the cube should be painted. In the following k lines print a k × k matrix — the way the second layer should be painted. And so on to the last k-th layer. Note that orientation of the cube in the space does not matter.

Mark a white unit cube with symbol "w" and a black one with "b". Use the format of output data, given in the test samples. You may print extra empty lines, they will be ignored.

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

Output
-1

Input
2

Output
bb
ww

bb
ww

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

K = int(input())
print(("-1" if K & 1 else "".join(["wb\n"[2 if k == K else (min(j, k, K - 1 - j,
    K - 1 - k) ^ i) & 1] for i in range(2) for j in range(K) for k in range(K +
        1)]) * (K >> 1)))


I found an interesting problem on https://codeforces.com/problemset/problem/325/A:
You are given n rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).

Your task is to determine if the rectangles form a square. In other words, determine if the set of points inside or on the border of at least one rectangle is precisely equal to the set of points inside or on the border of some square.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 5). Next n lines contain four integers each, describing a single rectangle: x_1, y_1, x_2, y_2 (0 ≤ x_1 < x_2 ≤ 31400, 0 ≤ y_1 < y_2 ≤ 31400) — x_1 and x_2 are x-coordinates of the left and right edges of the rectangle, and y_1 and y_2 are y-coordinates of the bottom and top edges of the rectangle.

No two rectangles overlap (that is, there are no points that belong to the interior of more than one rectangle).

-----Output-----

In a single line print "YES", if the given rectangles form a square, or "NO" otherwise.

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

Output
YES

Input
4
0 0 2 3
0 3 3 5
2 0 5 2
3 2 5 5

Output
NO

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

n = int(input())
sq = [None]  * 51
sqsum  = 0
for i in range(n):
    sq[i]= list(map(int,input().split()))
    sqsum+=(sq[i][3]-sq[i][1])*(sq[i][2]-sq[i][0])
maxx = max(map(lambda x:x[2],sq[:n]))
minx = min(map(lambda x:x[0],sq[:n]))
maxy = max(map(lambda x:x[3],sq[:n]))
miny =  min(map(lambda x:x[1],sq[:n]))
area = (maxy-miny)*(maxx-minx)

if maxx-minx!=maxy-miny or area!=sqsum:
    print("NO")
else:
    print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/325/B:
Daniel is organizing a football tournament. He has come up with the following tournament format:   In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even.  Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be $\frac{x \cdot(x - 1)}{2}$ games), and the tournament ends.

For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games.

Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^18), the number of games that should be played.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

-----Output-----

Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1.

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

Output
3
4

Input
25

Output
20

Input
2

Output
-1

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

def f(x, k):
    return x * (x - 1) // 2 + ((2 ** k) - 1) * x

res = []
n = int(input())
for k in range(0, 64):
    l = 1
    r = 2 ** 100
    while l < r:
        m = (l + r) // 2
        cur = f(m, k)
        if cur < n:
            l = m + 1
        else:
            r = m
    if f(l, k) != n or l % 2 == 0:
        continue
    cand = (2 ** k) * l
    if not (cand in res):
        res.append(cand)
if len(res) == 0:
    res.append(-1)
for x in sorted(res):
    print(x)


I found an interesting problem on https://codeforces.com/problemset/problem/325/E:
Piegirl found the red button. You have one last chance to change the inevitable end.

The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2·i) modulo n or node (2·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once.

Your task is to find any such order and print it. If there is no such order, print -1.

-----Input-----

Input consists of a single integer n (2 ≤ n ≤ 10^5).

-----Output-----

Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.

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

Output
0 1 0

Input
3

Output
-1
Input
4

Output
0 1 3 2 0

Input
16

Output
0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0

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

# METO Bot 0.9.9.1
n=int(input())
if n&1:
	print(-1)
else:
	D,R=[False]*(10**6),[0]*(10**6)
	i,j=0,0
	while True:
		D[j]=True
		R[i]=j
		i+=1
		if not D[(j+n)>>1]:
			j=(j+n)>>1
		elif not D[j>>1]:
			j=j>>1
		else:
			break
	print(" ".join(str(R[i]) for i in range(n,-1,-1)))


I found an interesting problem on https://codeforces.com/problemset/problem/327/A:
Iahub got bored, so he invented a game to be played on paper.

He writes n integers a_1, a_2, ..., a_{n}. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values a_{k} for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.

The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.

-----Input-----

The first line of the input contains an integer n (1 ≤ n ≤ 100). In the second line of the input there are n integers: a_1, a_2, ..., a_{n}. It is guaranteed that each of those n values is either 0 or 1.

-----Output-----

Print an integer — the maximal number of 1s that can be obtained after exactly one move.

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

Output
4

Input
4
1 0 0 1

Output
4

-----Note-----

In the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1].

In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.

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

n, t = int(input()), list(map(int, input().split()))
k = t.count(1)
t = [1 - 2 * i for i in t]

m, s = -1, 0

for i in range(n):
    s = max(s, 0)
    s += t[i]
    m = max(m, s)

print(k + m)


I found an interesting problem on https://codeforces.com/problemset/problem/327/C:
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.

Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (10^9 + 7). Two ways are different, if the set of deleted positions in s differs.

Look at the input part of the statement, s is given in a special form.

-----Input-----

In the first line you're given a string a (1 ≤ |a| ≤ 10^5), containing digits only. In the second line you're given an integer k (1 ≤ k ≤ 10^9). The plate s is formed by concatenating k copies of a together. That is n = |a|·k.

-----Output-----

Print a single integer — the required number of ways modulo 1000000007 (10^9 + 7).

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

Output
4

Input
13990
2

Output
528

Input
555
2

Output
63

-----Note-----

In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.

In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.

In the third case, except deleting all digits, any choice will do. Therefore there are 2^6 - 1 = 63 possible ways to delete digits.

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

A = input()
n = int(input())
m = 1000000007
a = len(A)

x = pow(2,a*n,m)-1+m
y = pow(2,a,m)-1+m
f = x*pow(y,m-2,m)%m

s = 0
for r in range(a):
	if A[r] in '05':
		s = (s+pow(2,r,m))%m
print((s*f)%m)


I found an interesting problem on https://codeforces.com/problemset/problem/328/A:
Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.

Arithmetic progression is a sequence a_1, a_1 + d, a_1 + 2d, ..., a_1 + (n - 1)d, where a_1 and d are any numbers.

Geometric progression is a sequence b_1, b_2 = b_1q, ..., b_{n} = b_{n} - 1q, where b_1 ≠ 0, q ≠ 0, q ≠ 1.

Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer.

-----Input-----

The first line contains exactly four integer numbers between 1 and 1000, inclusively.

-----Output-----

Print the required number. If the given sequence is arithmetic progression, print the next progression element. Similarly, if the given sequence is geometric progression, print the next progression element.

Print 42 if the given sequence is not an arithmetic or geometric progression.

-----Examples-----
Input
836 624 412 200

Output
-12

Input
1 334 667 1000

Output
1333

-----Note-----

This problem contains very weak pretests!

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

import sys

def solve():
    a = list(map(int, input().split()))
    diffs = list()
    for i in range(3):
        diffs.append(a[i+1]-a[i])
    if diffs[0] == diffs[1] == diffs[2]:
        return a[3] + diffs[0]
    # print(diffs)
    if a[1] / a[0] == a[2] / a[1] == a[3] / a[2]:
        val = a[3] * diffs[2] / diffs[1]
        if abs(val - int(val)) < 1e-6:
            return int(val)
    return 42

if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/328/B:
Do you remember how Kai constructed the word "eternity" using pieces of ice as components?

Little Sheldon plays with pieces of ice, each piece has exactly one digit between 0 and 9. He wants to construct his favourite number t. He realized that digits 6 and 9 are very similar, so he can rotate piece of ice with 6 to use as 9 (and vice versa). Similary, 2 and 5 work the same. There is no other pair of digits with similar effect. He called this effect "Digital Mimicry".

Sheldon favourite number is t. He wants to have as many instances of t as possible. How many instances he can construct using the given sequence of ice pieces. He can use any piece at most once.

-----Input-----

The first line contains integer t (1 ≤ t ≤ 10000). The second line contains the sequence of digits on the pieces. The length of line is equal to the number of pieces and between 1 and 200, inclusive. It contains digits between 0 and 9.

-----Output-----

Print the required number of instances.

-----Examples-----
Input
42
23454

Output
2

Input
169
12118999

Output
1

-----Note-----

This problem contains very weak pretests.

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

num = input()
str = input()
d = dict()
used = dict()
num = num.replace('5', '2')
str = str.replace('5', '2')
num = num.replace('9', '6')
str = str.replace('9', '6')
res = 10 ** 1000
for i in num:
    res = min(res, str.count(i) // num.count(i))
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/329/A:
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n × n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door!

Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.

The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile — then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.

You would like to purify all n × n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell.

Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.

-----Input-----

The first line will contain a single integer n (1 ≤ n ≤ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise.

-----Output-----

If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum...

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

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

results = []
thing = True
for i in range(n):
    hit = False
    for j in range(n):
        if l[i][j] != "E":
            results.append(f"{i + 1} {j + 1}")
            hit = True
            break
    if not hit:
        thing = False
        break
if not thing:
    results = []
    thing = True
    for j in range(n):
        hit = False
        for i in range(n):
            if l[i][j] != "E":
                results.append(f"{i + 1} {j + 1}")
                hit = True
                break
        if not hit:
            thing = False
            break

if thing:
    for r in results:
        print(r)
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/330/A:
You are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows: [Image]

The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.

Please output the maximum number of cake cells that the cakeminator can eat.

-----Input-----

The first line contains two integers r and c (2 ≤ r, c ≤ 10), denoting the number of rows and the number of columns of the cake. The next r lines each contains c characters — the j-th character of the i-th line denotes the content of the cell at row i and column j, and is either one of these:   '.' character denotes a cake cell with no evil strawberry;  'S' character denotes a cake cell with an evil strawberry.

-----Output-----

Output the maximum number of cake cells that the cakeminator can eat.

-----Examples-----
Input
3 4
S...
....
..S.

Output
8

-----Note-----

For the first example, one possible way to eat the maximum number of cake cells is as follows (perform 3 eats). [Image]  [Image]  [Image]

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

def main(r,c,seq):
	answer = 0
	for i in range(r):
		k = seq[i].count(1)
		if k==0:
			for j in range(c):
				item = seq[i][j]
				if item==0:
					seq[i][j]=2
					answer+=1
	for i in range(c):
		temp = 0
		for j in range(r):
			item = seq[j][i]
			if item==0:
				temp+=1
			elif item==1:
				temp=0
				break

		answer+=temp

	return answer

def init():
	r,c = list(map(int, input().split()))
	seq = []
	for i in range(r):
		temp = []
		for item in input():
			if item=='S':
				temp+=[1]
			else:
				temp+=[0]
		seq.append(temp)

	print(main(r,c,seq))

init()


I found an interesting problem on https://codeforces.com/problemset/problem/330/B:
A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given m pairs of cities — roads cannot be constructed between these pairs of cities.

Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.

-----Input-----

The first line consists of two integers n and m $(1 \leq n \leq 10^{3}, 0 \leq m < \frac{n}{2})$.

Then m lines follow, each consisting of two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}), which means that it is not possible to construct a road connecting cities a_{i} and b_{i}. Consider the cities are numbered from 1 to n.

It is guaranteed that every pair of cities will appear at most once in the input.

-----Output-----

You should print an integer s: the minimum number of roads that should be constructed, in the first line. Then s lines should follow, each consisting of two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}), which means that a road should be constructed between cities a_{i} and b_{i}.

If there are several solutions, you may print any of them.

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

Output
3
1 2
4 2
2 3

-----Note-----

This is one possible solution of the example:  [Image]

These are examples of wrong solutions: [Image]  The above solution is wrong because it doesn't use the minimum number of edges (4 vs 3). In addition, it also tries to construct a road between cities 1 and 3, while the input specifies that it is not allowed to construct a road between the pair. [Image]  The above solution is wrong because you need to traverse at least 3 roads to go from city 1 to city 3, whereas in your country it must be possible to go from any city to another by traversing at most 2...

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

def main():
    n,m = map(int,input().split())
    ch = [True]*(n+1)
    for i in range(m):
        a,b = map(int,input().split())
        a,b = a-1,b-1
        ch[a] = ch[b] = False
    cen = ch.index(True)+1
    print(n-1)
    for i in range(1,n+1):
        if i == cen: continue
        print(cen,i)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/331/A1:
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?

 — Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?

At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.

Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal a_{i} — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!

The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:   The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;  the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;  and of course, the walk should be successful: there must be at least two trees in the woodland belt left.

Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?

-----Input-----

The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers a_{i} — the esthetic appeals of each tree. All esthetic appeals do not exceed 10^9 in their absolute value.  to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);  to get 100 points, you need to solve the problem with constraints: n ≤ 3·10^5 (subproblems A1+A2).

-----Output-----

In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.

In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.

If there are multiple solutions, print any of them. It is guaranteed that...

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

n=int(input())
a=tuple(map(int,input().split()))
c={}
p={}
s=x=y=0
m=-1e18
for i in range(0,len(a)):
    d=c.get(a[i])
    if d!=None and s-d+a[i]*2>m:
        m=s-d+a[i]*2
        x,y=p.get(a[i]),i
    if(a[i]>0):s+=a[i]
    if p.get(a[i])==None:
        p[a[i]]=i
        c[a[i]]=s
a=[str(i+1) for i in range(0,len(a)) if i!=x and i!=y and (a[i]<0 or i<x or i>y)]
print(m,len(a))
print(" ".join(a))


I found an interesting problem on https://codeforces.com/problemset/problem/331/C1:
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.

The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:

"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"

Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.

-----Input-----

The single line contains the magic integer n, 0 ≤ n.

  to get 20 points, you need to solve the problem with constraints: n ≤ 10^6 (subproblem C1);  to get 40 points, you need to solve the problem with constraints: n ≤ 10^12 (subproblems C1+C2);  to get 100 points, you need to solve the problem with constraints: n ≤ 10^18 (subproblems C1+C2+C3).

-----Output-----

Print a single integer — the minimum number of subtractions that turns the magic number to a zero.

-----Examples-----
Input
24

Output
5

-----Note-----

In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:

 24 → 20 → 18 → 10 → 9 → 0

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

n,k=int(input()),0
while n:n-=int(max(str(n)));k+=1
print(k)


I found an interesting problem on https://codeforces.com/problemset/problem/332/A:
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!

Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index b_{i} from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index b_{i}, then this person acted like that:  he pointed at the person with index (b_{i} + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y);  if j ≥ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player b_{i} on the current turn, then he had drunk a glass of juice;  the turn went to person number (b_{i} + 1) mod n.

The person who was pointed on the last turn did not make any actions.

The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.

You can assume that in any scenario, there is enough juice for everybody.

-----Input-----

The first line contains a single integer n (4 ≤ n ≤ 2000) — the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns.

-----Output-----

Print a single integer — the number of glasses of juice Vasya could have drunk if he had played...

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

n = int(input())
string = input()
count = 0
i = n
while i < len(string):
    flag = False
    if string[i - 1] == string[i - 2] and string [i - 2] == string[i - 3] and i >= 3:
        flag = True
    if flag:
        count += 1
    i += n
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/332/B:
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.

This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k) and sign all laws with numbers lying in the segments [a; a + k - 1] and [b; b + k - 1] (borders are included).

As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.

-----Input-----

The first line contains two integers n and k (2 ≤ n ≤ 2·10^5, 0 < 2k ≤ n) — the number of laws accepted by the parliament and the length of one segment in the law list, correspondingly. The next line contains n integers x_1, x_2, ..., x_{n} — the absurdity of each law (1 ≤ x_{i} ≤ 10^9).

-----Output-----

Print two integers a, b — the beginning of segments that mr. Boosch should choose. That means that the president signs laws with numbers from segments [a; a + k - 1] and [b; b + k - 1]. If there are multiple solutions, print the one with the minimum number a. If there still are multiple solutions, print the one with the minimum b.

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

Output
1 4

Input
6 2
1 1 1 1 1 1

Output
1 3

-----Note-----

In the first sample mr. Boosch signs laws with numbers from segments [1;2] and [4;5]. The total absurdity of the signed laws equals 3 + 6 + 1 + 6 = 16.

In the...

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

n, k = map(int, input().split())
a = list(map(int, input().split()))
sums = [0]
for x in a: sums.append(x + sums[-1])
S = l = r = ans = pos = 0
for i in range(k, n - k + 1):
    (prev, cur, nex) = (sums[i - k], sums[i], sums[i + k])
    dif = cur - prev
    if dif > S:
        S = dif
        pos = i - k
    dif = nex - cur
    if S + dif > ans:
        ans = S + dif
        l = pos
        r = i
print(l + 1, r + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/333/A:
Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.

One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?

The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of n marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least n marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.

-----Input-----

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

Please, do not use the %lld specifier to read or write 64 bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

-----Output-----

In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with.

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

Output
1

Input
4

Output
2

-----Note-----

In the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change.

In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three...

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

n=int(input())
r=3
while(1):
    if(n%r):
        print((n-1)//r+1)
        break
    else:
        r*=3


I found an interesting problem on https://codeforces.com/problemset/problem/334/A:
Gerald has n younger brothers and their number happens to be even. One day he bought n^2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n^2 he has exactly one bag with k candies.

Help him give n bags of candies to each brother so that all brothers got the same number of candies.

-----Input-----

The single line contains a single integer n (n is even, 2 ≤ n ≤ 100) — the number of Gerald's brothers.

-----Output-----

Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers — the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n^2. You can print the numbers in the lines in any order.

It is guaranteed that the solution exists at the given limits.

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

Output
1 4
2 3

-----Note-----

The sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.

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

def get_candies(n):
    result = []
    bags = list(range(1, n**2 +1))

    for i in range(n):
        each = []
        for times in range(int(n / 2)):
            each.append(bags[0])
            each.append(bags[-1])
            bags = bags[1:len(bags)-1]
        each.sort()
        result.append(each)

    return result

def main():
    n = int(input())

    result = get_candies(n)

    for i in range(len(result)):
        string = ""
        for value in result[i]:
            string += str(value)
            string += " "
        print(string)

#import doctest
#doctest.testmod()
main()


I found an interesting problem on https://codeforces.com/problemset/problem/334/B:
Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three integers x_1, x_2, x_3 and three more integers y_1, y_2, y_3, such that x_1 < x_2 < x_3, y_1 < y_2 < y_3 and the eight point set consists of all points (x_{i}, y_{j}) (1 ≤ i, j ≤ 3), except for point (x_2, y_2).

You have a set of eight points. Find out if Gerald can use this set?

-----Input-----

The input consists of eight lines, the i-th line contains two space-separated integers x_{i} and y_{i} (0 ≤ x_{i}, y_{i} ≤ 10^6). You do not have any other conditions for these points.

-----Output-----

In a single line print word "respectable", if the given set of points corresponds to Gerald's decency rules, and "ugly" otherwise.

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

Output
respectable

Input
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0

Output
ugly

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

Output
ugly

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/335/A:
Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.

-----Input-----

The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000).

-----Output-----

On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1.

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

Output
2
baan

Input
banana
3

Output
3
nab

Input
banana
2

Output
-1

-----Note-----

In the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana".

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

s = input()
n = int(input())
cnt = {}
for c in s:
    if cnt.get(c) == None:
        cnt[c] = 1
    else:
        cnt[c] += 1

if (n < len(cnt)):
    print(-1)
else:
    ansNum = 0;
    while(True):
        ansNum+=1
        l = 0;
        char = []
        for c, v in cnt.items():
            need = (v + ansNum -1)//ansNum
            l+= need
            char.append((c, need))
        if (l > n):
            continue
        print(ansNum)
        ans = "".join([str(c[0])*c[1] for c in char])
        ans = ans + 'a'*(n - len(ans))
        print(ans)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/335/C:
In a far away land, there are two cities near a river. One day, the cities decide that they have too little space and would like to reclaim some of the river area into land.

The river area can be represented by a grid with r rows and exactly two columns — each cell represents a rectangular area. The rows are numbered 1 through r from top to bottom, while the columns are numbered 1 and 2.

Initially, all of the cells are occupied by the river. The plan is to turn some of those cells into land one by one, with the cities alternately choosing a cell to reclaim, and continuing until no more cells can be reclaimed.

However, the river is also used as a major trade route. The cities need to make sure that ships will still be able to sail from one end of the river to the other. More formally, if a cell (r, c) has been reclaimed, it is not allowed to reclaim any of the cells (r - 1, 3 - c), (r, 3 - c), or (r + 1, 3 - c).

The cities are not on friendly terms, and each city wants to be the last city to reclaim a cell (they don't care about how many cells they reclaim, just who reclaims a cell last). The cities have already reclaimed n cells. Your job is to determine which city will be the last to reclaim a cell, assuming both choose cells optimally from current moment.

-----Input-----

The first line consists of two integers r and n (1 ≤ r ≤ 100, 0 ≤ n ≤ r). Then n lines follow, describing the cells that were already reclaimed. Each line consists of two integers: r_{i} and c_{i} (1 ≤ r_{i} ≤ r, 1 ≤ c_{i} ≤ 2), which represent the cell located at row r_{i} and column c_{i}. All of the lines describing the cells will be distinct, and the reclaimed cells will not violate the constraints above.

-----Output-----

Output "WIN" if the city whose turn it is to choose a cell can guarantee that they will be the last to choose a cell. Otherwise print "LOSE".

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

Output
WIN

Input
12 2
4 1
8 1

Output
WIN

Input
1 1
1 2

Output
LOSE

-----Note-----

In the first example, there are 3 possible...

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

r,n = [int(x) for x in input().split()]
cells = [[int(x) for x in input().split()] for i in range(n)]
cells.sort()
#print(cells)
out = False

res = {True:"WIN",False:"LOSE"}

if len(cells) == 0: print(res[r%2 == 1])
else:
    out = False
    #print(cells[0][0] > 1)
    #print(cells[-1][0] < r)
    for i in range(1,n):
        out ^= ((cells[i][0]-cells[i-1][0]-1)%2) ^ (cells[i][1] != cells[i-1][1])
    dif = abs((cells[0][0]-1)-(r-cells[-1][0]))
    #print(out,dif)
    hi,lo = max(cells[0][0]-1,r-cells[-1][0]),min(cells[0][0]-1,r-cells[-1][0])
    #print(out,dif,lo,hi)
    if lo > 1:
        if dif == 0:
            print(res[out])
        elif dif == 1 and lo % 2 == 0:
            print(res[not out])
        else:
            print(res[True])
    elif lo == 0:
        if hi == 0: print(res[out])
        elif hi == 1:
            print(res[not out])
        else:
            print(res[True])
    elif lo == 1:
        if hi == 1:
            print(res[out])
        else:
            print(res[True])


I found an interesting problem on https://codeforces.com/problemset/problem/336/A:
Vasily the bear has a favorite rectangle, it has one vertex at point (0, 0), and the opposite vertex at point (x, y). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes.

Vasya also loves triangles, if the triangles have one vertex at point B = (0, 0). That's why today he asks you to find two points A = (x_1, y_1) and C = (x_2, y_2), such that the following conditions hold:  the coordinates of points: x_1, x_2, y_1, y_2 are integers. Besides, the following inequation holds: x_1 < x_2;  the triangle formed by point A, B and C is rectangular and isosceles ($\angle A B C$ is right);  all points of the favorite rectangle are located inside or on the border of triangle ABC;  the area of triangle ABC is as small as possible.

Help the bear, find the required points. It is not so hard to proof that these points are unique.

-----Input-----

The first line contains two integers x, y ( - 10^9 ≤ x, y ≤ 10^9, x ≠ 0, y ≠ 0).

-----Output-----

Print in the single line four integers x_1, y_1, x_2, y_2 — the coordinates of the required points.

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

Output
0 15 15 0

Input
-10 5

Output
-15 0 0 15

-----Note-----

[Image]

Figure to the first sample

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

x,y=list(map(int,input().split()))
x1,x2,y1,y2=0,0,0,0
if x<0:
    if y<0:
        x1=x+y
        y2=y+x
    else:
        x1=x-y
        y2=y-x
else:
    if y<0:
        x2=x-y
        y1=y-x
    else:
        x2=x+y
        y1=y+x
print(x1,y1,x2,y2)


I found an interesting problem on https://codeforces.com/problemset/problem/336/B:
One beautiful day Vasily the bear painted 2m circles of the same radius R on a coordinate plane. Circles with numbers from 1 to m had centers at points (2R - R, 0), (4R - R, 0), ..., (2Rm - R, 0), respectively. Circles with numbers from m + 1 to 2m had centers at points (2R - R, 2R), (4R - R, 2R), ..., (2Rm - R, 2R), respectively.

Naturally, the bear painted the circles for a simple experiment with a fly. The experiment continued for m^2 days. Each day of the experiment got its own unique number from 0 to m^2 - 1, inclusive.

On the day number i the following things happened:   The fly arrived at the coordinate plane at the center of the circle with number $v = \lfloor \frac{i}{m} \rfloor + 1$ ($\lfloor \frac{x}{y} \rfloor$ is the result of dividing number x by number y, rounded down to an integer).  The fly went along the coordinate plane to the center of the circle number $u = m + 1 +(i \operatorname{mod} m)$ ($x \text{mod} y$ is the remainder after dividing number x by number y). The bear noticed that the fly went from the center of circle v to the center of circle u along the shortest path with all points lying on the border or inside at least one of the 2m circles. After the fly reached the center of circle u, it flew away in an unknown direction.

Help Vasily, count the average distance the fly went along the coordinate plane during each of these m^2 days.

-----Input-----

The first line contains two integers m, R (1 ≤ m ≤ 10^5, 1 ≤ R ≤ 10).

-----Output-----

In a single line print a single real number — the answer to the problem. The answer will be considered correct if its absolute or relative error doesn't exceed 10^{ - 6}.

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

Output
2.0000000000

Input
2 2

Output
5.4142135624

-----Note-----

[Image]

Figure to the second sample

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