I found an interesting problem on https://codeforces.com/problemset/problem/234/C:
Scientists say a lot about the problems of global warming and cooling of the Earth. Indeed, such natural phenomena strongly influence all life on our planet.

Our hero Vasya is quite concerned about the problems. He decided to try a little experiment and observe how outside daily temperature changes. He hung out a thermometer on the balcony every morning and recorded the temperature. He had been measuring the temperature for the last n days. Thus, he got a sequence of numbers t_1, t_2, ..., t_{n}, where the i-th number is the temperature on the i-th day.

Vasya analyzed the temperature statistics in other cities, and came to the conclusion that the city has no environmental problems, if first the temperature outside is negative for some non-zero number of days, and then the temperature is positive for some non-zero number of days. More formally, there must be a positive integer k (1 ≤ k ≤ n - 1) such that t_1 < 0, t_2 < 0, ..., t_{k} < 0 and t_{k} + 1 > 0, t_{k} + 2 > 0, ..., t_{n} > 0. In particular, the temperature should never be zero. If this condition is not met, Vasya decides that his city has environmental problems, and gets upset.

You do not want to upset Vasya. Therefore, you want to select multiple values of temperature and modify them to satisfy Vasya's condition. You need to know what the least number of temperature values needs to be changed for that.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of days for which Vasya has been measuring the temperature.

The second line contains a sequence of n integers t_1, t_2, ..., t_{n} (|t_{i}| ≤ 10^9) — the sequence of temperature values. Numbers t_{i} are separated by single spaces.

-----Output-----

Print a single integer — the answer to the given task.

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

Output
1

Input
5
0 -1 1 2 -5

Output
2

-----Note-----

Note to the first sample: there are two ways to change exactly one number so that the sequence met Vasya's condition. You can either replace the first number...

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

import sys
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
n = int(input())
l = list(map(int,input().split()))
a = [0 for i in range(n)]
b = [0 for i in range(n)]
if l[0]>=0:
    a[0]=1
for i in range(1,n):
    if l[i]>=0:
        a[i]=a[i-1]+1
    else:
        a[i]=a[i-1]

for i in range(n-2,-1,-1):
    if l[i+1]<=0:
        b[i]=b[i+1]+1
    else:
        b[i]=b[i+1]

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


I found an interesting problem on https://codeforces.com/problemset/problem/234/F:
Vasya should paint a fence in front of his own cottage. The fence is a sequence of n wooden boards arranged in a single row. Each board is a 1 centimeter wide rectangle. Let's number the board fence using numbers 1, 2, ..., n from left to right. The height of the i-th board is h_{i} centimeters.

Vasya has a 1 centimeter wide brush and the paint of two colors, red and green. Of course, the amount of the paint is limited. Vasya counted the area he can paint each of the colors. It turned out that he can not paint over a square centimeters of the fence red, and he can not paint over b square centimeters green. Each board of the fence should be painted exactly one of the two colors. Perhaps Vasya won't need one of the colors.

In addition, Vasya wants his fence to look smart. To do this, he should paint the fence so as to minimize the value that Vasya called the fence unattractiveness value. Vasya believes that two consecutive fence boards, painted different colors, look unattractive. The unattractiveness value of a fence is the total length of contact between the neighboring boards of various colors. To make the fence look nice, you need to minimize the value as low as possible. Your task is to find what is the minimum unattractiveness Vasya can get, if he paints his fence completely. $1$

The picture shows the fence, where the heights of boards (from left to right) are 2,3,2,4,3,1. The first and the fifth boards are painted red, the others are painted green. The first and the second boards have contact length 2, the fourth and fifth boards have contact length 3, the fifth and the sixth have contact length 1. Therefore, the unattractiveness of the given painted fence is 2+3+1=6.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 200) — the number of boards in Vasya's fence.

The second line contains two integers a and b (0 ≤ a, b ≤ 4·10^4) — the area that can be painted red and the area that can be painted green, correspondingly.

The third line contains a sequence of n integers h_1, h_2,...

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

r = open('input.txt')
w = open('output.txt', mode='w')

f = lambda: map(int, r.readline().split())

f()
a, b = f()
if a > b: a, b = b, a
n = 40001
u, v = [n] * n, [n] * n
x = s = 0
u[0] = v[0] = 0

for y in f():
    s += y
    p = []
    h = min(x, y)
    for d in range(min(s, a), max(0, s - b - y) - 1, -1):
        t = v[d]

        if u[d] != n:
            u[d + y] = min(u[d], u[d + y])
            v[d] = min(t, u[d] + h)
            u[d] = n

        if t != n:
            u[d + y] = min(u[d + y], t + h)
    x = y

i = max(s - b, 0)
j = min(s, a) + 1

d = min(u[i:j] + v[i:j]) if i < j else n
w.write(str(d if d < n else -1))

w.close()
r.close()


I found an interesting problem on https://codeforces.com/problemset/problem/235/A:
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.

But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find the maximum possible least common multiple of these three integers?

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 10^6) — the n mentioned in the statement.

-----Output-----

Print a single integer — the maximum possible LCM of three not necessarily distinct positive integers that are not greater than n.

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

Output
504

Input
7

Output
210

-----Note-----

The least common multiple of some positive integers is the least positive integer which is multiple for each of them.

The result may become very large, 32-bit integer won't be enough. So using 64-bit integers is recommended.

For the last example, we can chose numbers 7, 6, 5 and the LCM of them is 7·6·5 = 210. It is the maximum value we can get.

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

def main():
    n = int(input())
    print(n if n < 3 else ((n - 1) * (n * (n - 2) if n & 1 else (n - 3) * (n if n % 3 else n - 2))))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/236/A:
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.

But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names.

This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.

-----Input-----

The first line contains a non-empty string, that contains only lowercase English letters — the user name. This string contains at most 100 letters.

-----Output-----

If it is a female by our hero's method, print "CHAT WITH HER!" (without the quotes), otherwise, print "IGNORE HIM!" (without the quotes).

-----Examples-----
Input
wjmzbmr

Output
CHAT WITH HER!

Input
xiaodao

Output
IGNORE HIM!

Input
sevenkplus

Output
CHAT WITH HER!

-----Note-----

For the first example. There are 6 distinct characters in "wjmzbmr". These characters are: "w", "j", "m", "z", "b", "r". So wjmzbmr is a female and you should print "CHAT WITH HER!".

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

# -*- coding: utf-8 -*-
"""
Created on Thu Oct 10 12:43:24 2013

@author: azimkhan
"""

a = input()
s = []

for c in a.lower():
    if (not c in s):
        s.append(c)

l = len (s)

print("CHAT WITH HER!" if (l % 2 == 0) else "IGNORE HIM!")


I found an interesting problem on https://codeforces.com/problemset/problem/236/B:
Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum:

$\sum_{i = 1}^{a} \sum_{j = 1}^{b} \sum_{k = 1}^{c} d(i \cdot j \cdot k)$

Find the sum modulo 1073741824 (2^30).

-----Input-----

The first line contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 100).

-----Output-----

Print a single integer — the required sum modulo 1073741824 (2^30).

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

Output
20

Input
5 6 7

Output
1520

-----Note-----

For the first example.

  d(1·1·1) = d(1) = 1;  d(1·1·2) = d(2) = 2;  d(1·2·1) = d(2) = 2;  d(1·2·2) = d(4) = 3;  d(2·1·1) = d(2) = 2;  d(2·1·2) = d(4) = 3;  d(2·2·1) = d(4) = 3;  d(2·2·2) = d(8) = 4.

So the result is 1 + 2 + 2 + 3 + 2 + 3 + 3 + 4 = 20.

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/237/A:
Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at h_{i} hours m_{i} minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.

Valera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe.

Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5), that is the number of cafe visitors.

Each of the following n lines has two space-separated integers h_{i} and m_{i} (0 ≤ h_{i} ≤ 23; 0 ≤ m_{i} ≤ 59), representing the time when the i-th person comes into the cafe.

Note that the time is given in the chronological order. All time is given within one 24-hour period.

-----Output-----

Print a single integer — the minimum number of cashes, needed to serve all clients next day.

-----Examples-----
Input
4
8 0
8 10
8 10
8 45

Output
2

Input
3
0 12
10 11
22 22

Output
1

-----Note-----

In the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.

In the second sample all visitors will come in different times, so it will be enough one cash.

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

n = int(input())
maxx = 1
x = input().split()
A = [x]
res = 1
for i in range(n - 1):
    y = input().split()
    if y == A [-1]:
        res += 1
    else:
        res = 1
    A.append(y)
    if res > maxx:
        maxx = res

print(maxx)


I found an interesting problem on https://codeforces.com/problemset/problem/237/C:
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors.

Consider positive integers a, a + 1, ..., b (a ≤ b). You want to find the minimum integer l (1 ≤ l ≤ b - a + 1) such that for any integer x (a ≤ x ≤ b - l + 1) among l integers x, x + 1, ..., x + l - 1 there are at least k prime numbers.

Find and print the required minimum l. If no value l meets the described limitations, print -1.

-----Input-----

A single line contains three space-separated integers a, b, k (1 ≤ a, b, k ≤ 10^6; a ≤ b).

-----Output-----

In a single line print a single integer — the required minimum l. If there's no solution, print -1.

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

Output
3

Input
6 13 1

Output
4

Input
1 4 3

Output
-1

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

def f(a, b):

    t = [1] * (b + 1)

    for i in range(3, int(b ** 0.5) + 1):

        if t[i]: t[i * i :: 2 * i] = [0] * ((b - i * i) // (2 * i) + 1)

    return [i for i in range(3, b + 1, 2) if t[i] and i > a]

a, b, k = list(map(int, input().split()))

p = f(a - 1, b)

if 3 > a and b > 1: p = [2] + p

if k > len(p): print(-1)

elif len(p) == k: print(max(p[k - 1] - a + 1, b - p[0] + 1))

else: print(max(p[k - 1] - a + 1, b - p[len(p) - k] + 1, max(p[i + k] - p[i] for i in range(len(p) - k))))

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/237/E:
You desperately need to build some string t. For that you've got n more strings s_1, s_2, ..., s_{n}. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that:  choose any non-empty string from strings s_1, s_2, ..., s_{n};  choose an arbitrary character from the chosen string and write it on a piece of paper;  remove the chosen character from the chosen string.

Note that after you perform the described operation, the total number of characters in strings s_1, s_2, ..., s_{n} decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.

There are other limitations, though. For each string s_{i} you know number a_{i} — the maximum number of characters you are allowed to delete from string s_{i}. You also know that each operation that results in deleting a character from string s_{i}, costs i rubles. That is, an operation on string s_1 is the cheapest (it costs 1 ruble), and the operation on string s_{n} is the most expensive one (it costs n rubles).

Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.

-----Input-----

The first line of the input contains string t — the string that you need to build.

The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string s_{i} and integer a_{i} (0 ≤ a_{i} ≤ 100). Number a_{i} represents the maximum number of characters that can be deleted from string s_{i}.

All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.

-----Output-----

Print a single number — the...

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

from heapq import heappush, heappop
class MinCostFlow:
    INF = 10**18

    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]

    def add_edge(self, fr, to, cap, cost):
        G = self.G
        G[fr].append([to, cap, cost, len(G[to])])
        G[to].append([fr, 0, -cost, len(G[fr])-1])

    def flow(self, s, t, f):
        N = self.N; G = self.G
        INF = MinCostFlow.INF

        res = 0
        H = [0]*N
        prv_v = [0]*N
        prv_e = [0]*N

        while f:
            dist = [INF]*N
            dist[s] = 0
            que = [(0, s)]

            while que:
                c, v = heappop(que)
                if dist[v] < c:
                    continue
                for i, (w, cap, cost, _) in enumerate(G[v]):
                    if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w]:
                        dist[w] = r = dist[v] + cost + H[v] - H[w]
                        prv_v[w] = v; prv_e[w] = i
                        heappush(que, (r, w))
            if dist[t] == INF:
                return -1

            for i in range(N):
                H[i] += dist[i]

            d = f; v = t
            while v != s:
                d = min(d, G[prv_v[v]][prv_e[v]][1])
                v = prv_v[v]
            f -= d
            res += d * H[t]
            v = t
            while v != s:
                e = G[prv_v[v]][prv_e[v]]
                e[1] -= d
                G[v][e[3]][1] += d
                v = prv_v[v]
        return res

T = input()
need = [0] * 30
for t in T:
    need[ord(t) - ord('a')] += 1
have = [[0] * 30 for _ in range(110)]
N = int(input())
a = [0] * 110

for i in range(N):
    v = input().split()
    S = v[0]
    a[i] = int(v[1])
    for s in S:
        have[i][ord(s)-ord('a')] += 1

V = 30 + N + 10
flow = MinCostFlow(V)

start = 30 + N + 5
target = 30 + N + 6
for c in range(26):
    flow.add_edge(start, c, need[c], 0)
    for j in range(N):
        flow.add_edge(c, 30+j, have[j][c], 0)

for i in range(N):
    flow.add_edge(30+i, target,...


I found an interesting problem on https://codeforces.com/problemset/problem/238/A:
A sequence of non-negative integers a_1, a_2, ..., a_{n} of length n is called a wool sequence if and only if there exists two integers l and r (1 ≤ l ≤ r ≤ n) such that $a_{l} \oplus a_{l + 1} \oplus \cdots \oplus a_{r} = 0$. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0.

The expression $x \oplus y$ means applying the operation of a bitwise xor to numbers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as "^", in Pascal — as "xor".

In this problem you are asked to compute the number of sequences made of n integers from 0 to 2^{m} - 1 that are not a wool sequence. You should print this number modulo 1000000009 (10^9 + 9).

-----Input-----

The only line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 10^5).

-----Output-----

Print the required number of sequences modulo 1000000009 (10^9 + 9) on the only line of output.

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

Output
6

-----Note-----

Sequences of length 3 made of integers 0, 1, 2 and 3 that are not a wool sequence are (1, 3, 1), (1, 2, 1), (2, 1, 2), (2, 3, 2), (3, 1, 3) and (3, 2, 3).

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

n, m = map(int, input().split())
mod = 1000000009
upper = pow(2, m, mod)
s = 1
for i in range(0, n):
    s = (s * (upper - i - 1)) % mod
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/239/A:
Valera had two bags of potatoes, the first of these bags contains x (x ≥ 1) potatoes, and the second — y (y ≥ 1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.

Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.

-----Input-----

The first line of input contains three integers y, k, n (1 ≤ y, k, n ≤ 10^9; $\frac{n}{k}$  ≤ 10^5).

-----Output-----

Print the list of whitespace-separated integers — all possible values of x in ascending order. You should print each possible value of x exactly once.

If there are no such values of x print a single integer -1.

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

Output
-1

Input
10 6 40

Output
2 8 14 20 26

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

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

a=(k-(y%k))%k
if(a==0):
    a+=k
done=False
while(a+y<=n):
    print(a,end=" ")
    done=True
    a+=k
if(not done):
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/239/B:
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts.  Current character pointer (CP);  Direction pointer (DP) which can point left or right;

Initially CP points to the leftmost character of the sequence and DP points to the right.

We repeat the following steps until the first moment that CP points to somewhere outside the sequence.  If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one.  If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence.

If at any moment the CP goes outside of the sequence the execution is terminated.

It's obvious the every program in this language terminates after some steps.

We have a sequence s_1, s_2, ..., s_{n} of "<", ">" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence s_{l}, s_{l} + 1, ..., s_{r} as an independent program in this language.

-----Input-----

The first line of input contains two integers n and q (1 ≤ n, q ≤ 100) — represents the length of the sequence s and the number of queries.

The second line contains s, a sequence of "<", ">" and digits (0..9) written from left to right. Note, that the characters of s are not separated with spaces.

The next q lines each contains two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) — the i-th query.

-----Output-----

For...

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

n, q = list(map(int, input().split()))
s = input()
for _ in range(q):
    l, r = list(map(int, input().split()))
    t = list(s[l-1:r])
    p, d = 0, 1
    res = [0] * 10
    while 0 <= p < len(t):
        if '0' <= t[p] <= '9':
            k = int(t[p])
            res[k] += 1
            if k > 0:
                t[p] = str(k-1)
                p += d
            else:
                t.pop(p)
                if d == -1:
                    p += d
        else:
            d = -1 if t[p] == '<' else 1
            if 0 <= p+d < len(t) and not ('0' <= t[p+d] <= '9'):
                t.pop(p)
                if d == -1:
                    p += d
            else:
                p += d
    print(*res)


I found an interesting problem on https://codeforces.com/problemset/problem/241/A:
There are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c_1, c_2, ..., c_{n}. The Old Peykan wants to travel from city c_1 to c_{n} using roads. There are (n - 1) one way roads, the i-th road goes from city c_{i} to city c_{i} + 1 and is d_{i} kilometers long.

The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time.

Each city c_{i} (except for the last city c_{n}) has a supply of s_{i} liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly k hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times.

Initially (at time zero) the Old Peykan is at city c_1 and s_1 liters of fuel is transferred to it's empty tank from c_1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities.

Find the minimum time the Old Peykan needs to reach city c_{n}.

-----Input-----

The first line of the input contains two space-separated integers m and k (1 ≤ m, k ≤ 1000). The value m specifies the number of roads between cities which is equal to n - 1.

The next line contains m space-separated integers d_1, d_2, ..., d_{m} (1 ≤ d_{i} ≤ 1000) and the following line contains m space-separated integers s_1, s_2, ..., s_{m} (1 ≤ s_{i} ≤ 1000).

-----Output-----

In the only line of the output print a single integer — the minimum time required for The Old Peykan to reach city c_{n} from city c_1.

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

Output
10

Input
2 3
5 6
5 5

Output
14

-----Note-----

In the second sample above, the Old Peykan stays in c_1 for 3 hours.

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

import math

class CodeforcesTask241ASolution:
    def __init__(self):
        self.result = ''
        self.m_k = []
        self.distances = []
        self.supplies = []

    def read_input(self):
        self.m_k = [int(x) for x in input().split(" ")]
        self.distances = [int(x) for x in input().split(" ")]
        self.supplies = [int(x) for x in input().split(" ")]

    def process_task(self):
        travel_time = sum(self.distances)
        position = 0
        fuel = self.supplies[0]
        max_supply = self.supplies[0]
        while position < self.m_k[0]:
            if fuel >= self.distances[position]:
                fuel -= self.distances[position]
                position += 1
                if position == self.m_k[0]:
                    break
                fuel += self.supplies[position]
                max_supply = max(max_supply, self.supplies[position])
            else:
                tanking = self.distances[position] - fuel
                tanking_rounds = tanking // max_supply + int(math.ceil(tanking % max_supply / max_supply))
                fuel += tanking_rounds * max_supply
                travel_time += tanking_rounds * self.m_k[1]
        self.result = str(travel_time)

    def get_result(self):
        return self.result

def __starting_point():
    Solution = CodeforcesTask241ASolution()
    Solution.read_input()
    Solution.process_task()
    print(Solution.get_result())

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/242/A:
Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.

At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.

-----Input-----

The single line contains four integers x, y, a, b (1 ≤ a ≤ x ≤ 100, 1 ≤ b ≤ y ≤ 100). The numbers on the line are separated by a space.

-----Output-----

In the first line print integer n — the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers c_{i}, d_{i} — the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (c_{i}, d_{i}) in the strictly increasing order.

Let us remind you that the pair of numbers (p_1, q_1) is less than the pair of numbers (p_2, q_2), if p_1 < p_2, or p_1 = p_2 and also q_1 < q_2.

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

Output
3
2 1
3 1
3 2

Input
2 4 2 2

Output
0

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

#149 Heads or Tails

data = input().split(" ")
x = int(data[0])
y = int(data[1])
a = int(data[2])
b = int(data[3])
counter = 0
for i in range(a, x+1):
	for j in range(b, y+1):
		if j < i:
			counter += 1
if counter == 0:
	print(0)
else:
	print(counter)
	for i in range(a, x+1):
		for j in range(b, y+1):
			if j < i:
				print("%s %s" %(i, j))
				noAnswer = False


I found an interesting problem on https://codeforces.com/problemset/problem/242/B:
A coordinate line has n segments, the i-th segment starts at the position l_{i} and ends at the position r_{i}. We will denote such a segment as [l_{i}, r_{i}].

You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.

Formally we will assume that segment [a, b] covers segment [c, d], if they meet this condition a ≤ c ≤ d ≤ b.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 10^9) — the borders of the i-th segment.

It is guaranteed that no two segments coincide.

-----Output-----

Print a single integer — the number of the segment that covers all other segments in the set. If there's no solution, print -1.

The segments are numbered starting from 1 in the order in which they appear in the input.

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

Output
-1

Input
6
1 5
2 3
1 10
7 10
7 7
10 10

Output
3

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

import sys
f = sys.stdin
#f = open("input.txt", "r")
n = int(f.readline().strip())
l, r = [], []
for line in f:
    l.append(int(line.strip().split()[0]))
    r.append(int(line.strip().split()[1]))
ls = list(set(l))
rs = list(set(r))
ls.sort(); rs.sort(reverse=True)
ind = -1
for i in range(n):
    if l[i] <= ls[0] and r[i] >= rs[0]:
        ind = i+1
print(ind)


I found an interesting problem on https://codeforces.com/problemset/problem/242/C:
The black king is standing on a chess field consisting of 10^9 rows and 10^9 columns. We will consider the rows of the field numbered with integers from 1 to 10^9 from top to bottom. The columns are similarly numbered with integers from 1 to 10^9 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).

You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers r_{i}, a_{i}, b_{i} (a_{i} ≤ b_{i}), denoting that cells in columns from number a_{i} to number b_{i} inclusive in the r_{i}-th row are allowed.

Your task is to find the minimum number of moves the king needs to get from square (x_0, y_0) to square (x_1, y_1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.

Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.

-----Input-----

The first line contains four space-separated integers x_0, y_0, x_1, y_1 (1 ≤ x_0, y_0, x_1, y_1 ≤ 10^9), denoting the initial and the final positions of the king.

The second line contains a single integer n (1 ≤ n ≤ 10^5), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers r_{i}, a_{i}, b_{i} (1 ≤ r_{i}, a_{i}, b_{i} ≤ 10^9, a_{i} ≤ b_{i}), denoting that cells in columns from number a_{i} to number b_{i} inclusive in the r_{i}-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily.

It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 10^5.

-----Output-----

If there is no...

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

from collections import deque

x_start, y_start, x_end, y_end = [int(x) for x in input().split()]
n = int(input())
moves = {}
for _ in range(n):
    r, a, b = [int(x) for x in input().split()]
    for j in range(a, b + 1):
        moves[(r, j)] = -1

p_start = x_start, y_start
d = deque([p_start])
moves[p_start] = 0
while d:
    x1, y1 = d.popleft()
    m = moves[(x1, y1)]
    for p2 in [(x1 + dx, y1 + dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1]]:
        if (p2 in moves) and (moves[p2] == -1):
            d.append(p2)
            moves[p2] = m + 1

print(moves[(x_end, y_end)])


I found an interesting problem on https://codeforces.com/problemset/problem/244/A:
One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k.

There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 ≤ i ≤ k) child wrote the number a_{i} (1 ≤ a_{i} ≤ n·k). All numbers a_{i} accidentally turned out to be different.

Now the children wonder, how to divide the orange so as to meet these conditions:  each child gets exactly n orange segments;  the i-th child gets the segment with number a_{i} for sure;  no segment goes to two children simultaneously.

Help the children, divide the orange and fulfill the requirements, described above.

-----Input-----

The first line contains two integers n, k (1 ≤ n, k ≤ 30). The second line contains k space-separated integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ n·k), where a_{i} is the number of the orange segment that the i-th child would like to get.

It is guaranteed that all numbers a_{i} are distinct.

-----Output-----

Print exactly n·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces.

You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.

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

Output
2 4
1 3

Input
3 1
2

Output
3 2 1

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

#CF Round 150. Div II Prob. A - Dividing Orange
import sys

In = sys.stdin
n, k = [int(x) for x in In.readline().split()]
arr, s, cnt = [int(x) for x in In.readline().split()], set(), 1;
s.update(arr)
for i in range(k):
    c = [arr[i]]
    for j in range(n - 1):
        while (cnt in s):
            cnt += 1;
        c.append(cnt)
        cnt += 1;
    sep = ' '
    print (sep.join(map(str, c)))


I found an interesting problem on https://codeforces.com/problemset/problem/244/B:
Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if x = 4, and y = 7, then numbers 47, 744, 4 are lucky.

Let's call a positive integer a undoubtedly lucky, if there are such digits x and y (0 ≤ x, y ≤ 9), that the decimal representation of number a (without leading zeroes) contains only digits x and y.

Polycarpus has integer n. He wants to know how many positive integers that do not exceed n, are undoubtedly lucky. Help him, count this number.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^9) — Polycarpus's number.

-----Output-----

Print a single integer that says, how many positive integers that do not exceed n are undoubtedly lucky.

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

Output
10

Input
123

Output
113

-----Note-----

In the first test sample all numbers that do not exceed 10 are undoubtedly lucky.

In the second sample numbers 102, 103, 104, 105, 106, 107, 108, 109, 120, 123 are not undoubtedly lucky.

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

#CF Round 150. Div II Prob. A - Dividing Orange
import sys

dp = [[[-1 for j in range(3)] for i in range (1 << 10)] for k in range(11)]

In = sys.stdin
n = In.readline().strip()

def go (idx, mask, equal):
    if dp[idx][mask][equal] != -1:
        return dp[idx][mask][equal]
    if bin(mask).count("1") > 2:
        return 0
    if idx == len(n):
        return 1
    res = 0
    if idx == 0 or equal == 2:
        res += go(idx + 1, mask, 2)
    elif equal == 1 and int(n[idx]) == 0:
        res += go(idx + 1, mask | 1, 1)
    else:
        res += go(idx + 1, mask | 1, 0)
    for i in range(1, 10):
        if equal == 1 and i > int(n[idx]):
            break
        elif equal == 1 and i == int(n[idx]):
            res += go(idx + 1, mask | (1 << i), 1)
        else:
            res += go(idx + 1, mask | (1 << i), 0)
    dp[idx][mask][equal] = res
    return res

print(go(0, 0, 1)  - 1)


I found an interesting problem on https://codeforces.com/problemset/problem/245/C:
Two pirates Polycarpus and Vasily play a very interesting game. They have n chests with coins, the chests are numbered with integers from 1 to n. Chest number i has a_{i} coins.

Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer x (2·x + 1 ≤ n) and take a coin from each chest with numbers x, 2·x, 2·x + 1. It may turn out that some chest has no coins, in this case the player doesn't take a coin from this chest. The game finishes when all chests get emptied.

Polycarpus isn't a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily's moves.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of chests with coins. The second line contains a sequence of space-separated integers: a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000), where a_{i} is the number of coins in the chest number i at the beginning of the game.

-----Output-----

Print a single integer — the minimum number of moves needed to finish the game. If no sequence of turns leads to finishing the game, print -1.

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

Output
-1

Input
3
1 2 3

Output
3

-----Note-----

In the first test case there isn't a single move that can be made. That's why the players won't be able to empty the chests.

In the second sample there is only one possible move x = 1. This move should be repeated at least 3 times to empty the third chest.

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

t = int(input())
line = input()
lis = line.split()
lis = [int(i) for i in lis]
if t==1 or t%2==0 :
    print("-1")
    quit()
count = 0
i = t
while i >= 4 :
    if i%2 == 1 :
        p = i-1
        q = int(p/2)
        count = count + lis[i-1]
        lis[p-1] = lis[p-1] - lis[i-1]
        if lis[p-1] < 0 :
            lis[p-1] = 0
        lis[q-1] = lis[q-1] - lis[i-1]
        if lis[q-1] < 0 :
            lis[q-1] = 0
        lis[i-1] = 0
    else :
        p = i+1
        q = int(i/2)
        count = count + lis[i-1]
        lis[p-1] = lis[p-1] - lis[i-1]
        if lis[p-1] < 0 :
            lis[p-1] = 0
        lis[q-1] = lis[q-1] - lis[i-1]
        if lis[q-1] < 0 :
            lis[q-1] = 0
        lis[i-1] = 0
    i = i-1
m = max(lis[0], lis[1], lis[2])
count = count + m
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/245/E:
Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen.

On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, each time a visitor left the club, Polycarpus put character "-" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended.

Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.

-----Input-----

The only line of the input contains a sequence of characters "+" and "-", the characters are written one after another without any separators. The characters are written in the order, in which the corresponding events occurred. The given sequence has length from 1 to 300 characters, inclusive.

-----Output-----

Print the sought minimum number of people

-----Examples-----
Input
+-+-+

Output
1

Input
---
Output
3

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

c, v1, v2 = 0, 0, 0
for ch in input():
    c += 1 if ch == '+' else -1
    v1, v2 = min(v1, c), max(v2, c)
print(v2 - v1)


I found an interesting problem on https://codeforces.com/problemset/problem/246/A:
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a_1, a_2, ..., a_{n} in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number n and array a.

loop integer variable i from 1 to n - 1

    loop integer variable j from i to n - 1

        if (a_{j} > a_{j} + 1), then swap the values of elements a_{j} and a_{j} + 1

But Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of n doesn't exist, print -1.

-----Input-----

You've got a single integer n (1 ≤ n ≤ 50) — the size of the sorted array.

-----Output-----

Print n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100) — the counter-example, for which Valera's algorithm won't work correctly. If the counter-example that meets the described conditions is impossible to give, print -1.

If there are several counter-examples, consisting of n numbers, you are allowed to print any of them.

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

Output
-1

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

import sys

n = int(sys.stdin.readline())

if(n <= 2):
	print(-1)
	return

res = []
for i in range(2, n + 1):
	res.append(str(i))

res.append(str(1))
print(" ".join(res))


I found an interesting problem on https://codeforces.com/problemset/problem/246/B:
Polycarpus has an array, consisting of n integers a_1, a_2, ..., a_{n}. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times:

  he chooses two elements of the array a_{i}, a_{j} (i ≠ j);  he simultaneously increases number a_{i} by 1 and decreases number a_{j} by 1, that is, executes a_{i} = a_{i} + 1 and a_{j} = a_{j} - 1.

The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times.

Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.

-----Input-----

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

-----Output-----

Print a single integer — the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.

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

Output
1

Input
3
1 4 1

Output
3

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

n = int(input())
print(n - (sum(map(int, input().split())) % n != 0))


I found an interesting problem on https://codeforces.com/problemset/problem/246/C:
General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants.

All soldiers in the battalion have different beauty that is represented by a positive integer. The value a_{i} represents the beauty of the i-th soldier.

On each of k days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of k days the beauty of the sent detachment should be unique. In other words, all k beauties of the sent detachments must be distinct numbers.

Help Payne choose k detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty.

-----Input-----

The first line contains two integers n, k (1 ≤ n ≤ 50; 1 ≤ k ≤  $\frac{n(n + 1)}{2}$) — the number of soldiers and the number of days in the pageant, correspondingly. The second line contains space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^7) — the beauties of the battalion soldiers.

It is guaranteed that Payne's battalion doesn't have two soldiers with the same beauty.

-----Output-----

Print k lines: in the i-th line print the description of the detachment that will participate in the pageant on the i-th day. The description consists of integer c_{i} (1 ≤ c_{i} ≤ n) — the number of soldiers in the detachment on the i-th day of the pageant and c_{i} distinct integers p_{1, }i, p_{2, }i, ..., p_{c}_{i}, i — the beauties of the soldiers in the detachment on the i-th day of the pageant. The beauties of the soldiers are allowed to print in any order.

Separate numbers on the lines by spaces. It is guaranteed that there is the solution that meets the problem conditions. If there are multiple solutions,...

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

import sys
def fastio():
    from io import StringIO
    from atexit import register
    nonlocal input
    sys.stdin = StringIO(sys.stdin.read())
    input = lambda : sys.stdin.readline().rstrip('\r\n')
    sys.stdout = StringIO()
    register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()

def debug(*var, sep = ' ', end = '\n'):
    print(*var, file=sys.stderr, end = end, sep = sep)

INF = 10**20
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br

n, k = I()
a = I()
a.sort(reverse = 1)

p = [0] * (n + 1)
for i in range(1, n + 1):
    p[i] += p[i - 1] + a[i - 1]

s = set()
window = 1
ans = []
while k and window <= n:
    for i in range(window, n + 1):
        print(window, *ans, a[i - 1])
        k -= 1
        if not k:
            break
    ans.append(a[window - 1])
    window += 1


I found an interesting problem on https://codeforces.com/problemset/problem/246/D:
You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer c_{i}.

Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {c_{u} :  c_{u} ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.

Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color.

-----Input-----

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 10^5) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^5) — the colors of the graph vertices. The numbers on the line are separated by spaces.

Next m lines contain the description of the edges: the i-th line contains two space-separated integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}) — the numbers of the vertices, connected by the i-th edge.

It is guaranteed that the given graph has no self-loops or multiple edges.

-----Output-----

Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.

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

Output
3

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

Output
2

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

from collections import defaultdict

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

res = defaultdict(set)
for _ in range(m):
    u, v = map(lambda x: int(x) - 1, input().split())
    if c[u] != c[v]:
        res[c[u]].add(c[v])
        res[c[v]].add(c[u])

res_count = -1
res_color = -1
for color in c:
    count = res[color]
    if res_count == -1 or res_count < len(count):
        res_count = len(count)
        res_color = color
    elif res_count == len(count) and color < res_color:
        res_color = color

print(res_color)


I found an interesting problem on https://codeforces.com/problemset/problem/248/A:
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.

Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.

And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.

Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.

Your task is to write a program that will determine the required number of seconds t.

-----Input-----

The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 10^4). Then follow n lines, each containing two integers l_{i} and r_{i} (0 ≤...

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

n = int(input())
left = []
right = []

for i in range(n):
    l, r = input().split()

    left.append(l)
    right.append(r)

left_0 = left.count('0')
left_1 = left.count('1')
right_0 = right.count('0')
right_1 = right.count('1')

print(min(left_0, left_1) + min(right_0, right_1))


I found an interesting problem on https://codeforces.com/problemset/problem/248/B:
Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.

Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.

A number's length is the number of digits in its decimal representation without leading zeros.

-----Input-----

A single input line contains a single integer n (1 ≤ n ≤ 10^5).

-----Output-----

Print a single integer — the answer to the problem without leading zeroes, or "-1" (without the quotes), if the number that meet the problem condition does not exist.

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

Output
-1

Input
5

Output
10080

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/248/C:
It's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And yet, the notion of a giveaway is foreign to him. The combination of these features makes the Robo-Wallace the perfect footballer — as soon as the ball gets to him, he can just aim and hit the goal. He followed this tactics in the first half of the match, but he hit the goal rarely. The opposing team has a very good goalkeeper who catches most of the balls that fly directly into the goal. But Robo-Wallace is a quick thinker, he realized that he can cheat the goalkeeper. After all, they are playing in a football box with solid walls. Robo-Wallace can kick the ball to the other side, then the goalkeeper will not try to catch the ball. Then, if the ball bounces off the wall and flies into the goal, the goal will at last be scored.

Your task is to help Robo-Wallace to detect a spot on the wall of the football box, to which the robot should kick the ball, so that the ball bounces once and only once off this wall and goes straight to the goal. In the first half of the match Robo-Wallace got a ball in the head and was severely hit. As a result, some of the schemes have been damaged. Because of the damage, Robo-Wallace can only aim to his right wall (Robo-Wallace is standing with his face to the opposing team's goal).

The football box is rectangular. Let's introduce a two-dimensional coordinate system so that point (0, 0) lies in the lower left corner of the field, if you look at the box above. Robo-Wallace is playing for the team, whose goal is to the right. It is an improvised football field, so the gate of Robo-Wallace's rivals may be not in the middle of the left wall. [Image]

In the given coordinate system you are given:   y_1, y_2 — the y-coordinates of the side pillars of the goalposts of...

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

from math import atan, asin
y1, y2, yw, xb, yb, r = map(float, input().split())
x = xb * (yw - y1 - 2*r) / (2*yw - y1 - yb - 3*r)
alpha = atan(x / (yw - y1 - 2*r))
beta = asin(r / (y2 - y1 - r))
print ('-1' if alpha < beta else '{0:.10f}'.format(x))


I found an interesting problem on https://codeforces.com/problemset/problem/248/D:
For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!"Dr. Suess, How The Grinch Stole Christmas

Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street.

The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets).

After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food.

The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas...

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

def check(n, casas):
    #print('n:',n)
    nonlocal T,N,street
    current = n
    time = T
    need = 0
    last_house = 0

    for ind, i in enumerate(street):
        time -= 1

        if i == 'S':
            current += 1

        elif i == 'H':
            need += 1
            if need == 1:
                last_house = ind

        if need > 0 and current >= need:
            #print('p',time, ind-last_house)
            current -= need
            casas -= need
            need = 0

            if casas > 0:
                if (ind-last_house)*2 >= N-last_house-1:
                    time -= N-last_house-1 + N-ind-1

                    return time >= 0

                time -= (ind-last_house)*2
            else:
                time -= ind-last_house

        #print('lugar:',i,ind,current, time, need, last_house)

        if casas == 0:
            break

    #print(time)
    return time >= 0 and casas == 0

N,T = [int(i) for i in input().split()]

street = input().rstrip('.')
N = len(street)
C = street.count('H')
S = street.count('S')
l = max(C-S, 0)
r = 500005
#print(N, C)
while l < r:
    mid = (l+r)//2
    if check(mid, C):
        r = mid
    else:
        l = mid + 1

print(l if l < 500005 else -1)


I found an interesting problem on https://codeforces.com/problemset/problem/250/A:
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value a_{i}, the company's profit on the i-th day. If a_{i} is negative, then the company suffered losses on the i-th day.

Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the n days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.

It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (a_{i} < 0), he loses his temper and his wrath is terrible.

Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.

Write a program that, given sequence a_{i}, will print the minimum number of folders.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100), n is the number of days. The second line contains a sequence of integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 100), where a_{i} means the company profit on the i-th day. It is possible that the company has no days with the negative a_{i}.

-----Output-----

Print an integer k — the required minimum number of folders. In the second line print a sequence of integers b_1, b_2, ..., b_{k}, where b_{j} is the number of day reports in the j-th folder.

If there are multiple ways to sort the reports into k days, print any of them.

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

Output
3
5 3 3
Input
5
0 -1 100 -1 0

Output
1
5

-----Note-----

Here goes a way to sort the reports from the first sample into three...

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

P=print
I=input
I()
a=b=0
t=[]
for x in map(int,I().split()):
	if x<0:
		if b==2:t+=[a];b=1;a=0
		else:b+=1
	a+=1
if a:t+=[a]
P(len(t))
for x in t:P(x,end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/250/B:
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full.

Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000"  →  "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address.

Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0.

You can see examples of zero block shortenings below:

  "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::";  "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0";  "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0";  "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000";  "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::".

It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.

The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.

You've got several short records of IPv6 addresses. Restore their full record.

-----Input-----

The first line contains a single...

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

import re

n = int(input())
for i in range(n):
    s = input().strip()
    group_count = s.count(':') + 1
    s = re.sub('::', ':' + (9 - group_count) * '0000:', s)
    groups = s.split(':')
    for i, group in enumerate(groups):
        if len(group) < 4:
            groups[i] = (4 - len(group)) * '0' + group
    print(':'.join(groups))


I found an interesting problem on https://codeforces.com/problemset/problem/250/C:
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.

On the i-th day the festival will show a movie of genre a_{i}. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a_1, a_2, ..., a_{n} at least once.

Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.

As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.

Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.

Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.

-----Input-----

The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 10^5), where n is the number of movies and k is the number of genres.

The second line of the input contains a sequence of n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ k), where a_{i} is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.

-----Output-----

Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.

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

Output
3
Input
7 3
3 1 3 2 3 1 2

Output
1

-----Note-----

In...

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

import sys
from math import *

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return list(map(int, minp().split()))

n, k = mints()
a = list(mints())
i = 0
c = [0]*(k+1)
while i < n:
	j = i
	while j < n and a[j] == a[i]:
		j += 1
	if i - 1 >= 0:
		if j < n:
			if a[i-1] != a[j]:
				c[a[i]] += 1
			else:
				c[a[i]] += 2
		else:
			c[a[i]] += 1
	elif j < n:
			c[a[i]] += 1
	i = j
z = 1
for i in range(k+1):
	if c[z] < c[i]:
		z = i
print(z)


I found an interesting problem on https://codeforces.com/problemset/problem/250/D:
Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages.

The river banks can be assumed to be vertical straight lines x = a and x = b (0 < a < b).

The west village lies in a steppe at point O = (0, 0). There are n pathways leading from the village to the river, they end at points A_{i} = (a, y_{i}). The villagers there are plain and simple, so their pathways are straight segments as well.

The east village has reserved and cunning people. Their village is in the forest on the east bank of the river, but its exact position is not clear. There are m twisted paths leading from this village to the river and ending at points B_{i} = (b, y'_{i}). The lengths of all these paths are known, the length of the path that leads from the eastern village to point B_{i}, equals l_{i}.

The villagers want to choose exactly one point on the left bank of river A_{i}, exactly one point on the right bank B_{j} and connect them by a straight-line bridge so as to make the total distance between the villages (the sum of |OA_{i}| + |A_{i}B_{j}| + l_{j}, where |XY| is the Euclidean distance between points X and Y) were minimum. The Euclidean distance between points (x_1, y_1) and (x_2, y_2) equals $\sqrt{(x_{1} - x_{2})^{2} +(y_{1} - y_{2})^{2}}$.

Help them and find the required pair of points.

-----Input-----

The first line contains integers n, m, a, b (1 ≤ n, m ≤ 10^5, 0 < a < b < 10^6).

The second line contains n integers in the ascending order: the i-th integer determines the coordinate of point A_{i} and equals y_{i} (|y_{i}| ≤ 10^6).

The third line contains m integers in the ascending order: the i-th integer determines the coordinate of point B_{i} and equals y'_{i} (|y'_{i}| ≤ 10^6).

The fourth line contains m more integers: the i-th of them determines the length of the path that connects the eastern village and point B_{i}, and equals l_{i} (1 ≤ l_{i} ≤ 10^6).

It is guaranteed, that there is...

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

import sys
from itertools import *
from math import *
def solve():
    n,m,leftbank,rightbank = map(int, input().split())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    l = list(map(int, input().split()))
    smallx = leftbank
    smallxsquared = smallx * smallx
    rightbankminusleftbanksquared = (rightbank -leftbank)*(rightbank - leftbank)
    leftbest, rightbest, distbest = -1, -1, 100000000
    for i, bcord, length in zip(count(), b, l):
        wanty = bcord * smallx / rightbank
        ll , rr = 0, n - 1
        while ll < rr:
            mm = (ll + rr + 1) // 2
            if a[mm] > wanty: rr = mm - 1
            else: ll = mm
        for pos in range(ll, ll + 2):
            if pos < n:
                first = sqrt(smallxsquared + a[pos] * a[pos])
                second = sqrt(rightbankminusleftbanksquared + (bcord - a[pos]) * (bcord - a[pos]))
                totaldist = first + second + length
                if totaldist < distbest:
                    distbest = totaldist
                    leftbest = pos
                    rightbest = i
    print(leftbest + 1, rightbest + 1)

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


I found an interesting problem on https://codeforces.com/problemset/problem/250/E:
Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path.

Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each floor is surrounded by a concrete wall on the left and on the right.

Now Joe is on the n-th floor and in the first cell, counting from left to right. At each moment of time, Joe has the direction of his gaze, to the right or to the left (always one direction of the two). Initially, Joe looks to the right.

Joe moves by a particular algorithm. Every second he makes one of the following actions:   If the cell directly under Joe is empty, then Joe falls down. That is, he moves to this cell, the gaze direction is preserved.  Otherwise consider the next cell in the current direction of the gaze.   If the cell is empty, then Joe moves into it, the gaze direction is preserved.  If this cell has bricks, then Joe breaks them with his forehead (the cell becomes empty), and changes the direction of his gaze to the opposite.  If this cell has a concrete wall, then Joe just changes the direction of his gaze to the opposite (concrete can withstand any number of forehead hits).

Joe calms down as soon as he reaches any cell of the first floor.

The figure below shows an example Joe's movements around the house.

 [Image]

Determine how many seconds Joe will need to calm down.

-----Input-----

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

Next n lines contain the description of Joe's house. The i-th of these lines contains the description of the (n - i + 1)-th floor of the house — a line that consists of m characters: "." means an empty cell, "+" means bricks and "#" means a concrete wall.

It is guaranteed that the first cell of the n-th floor is empty.

-----Output-----

Print a single number — the number of seconds Joe needs to reach the first floor; or else, print word...

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

n, m = [int(i) for i in input().split()]
current_floor = list(input())

x, t, direction = 0, 0, 1

for i in range(n-1):
    floor = list(input())
    l, r = x, x
    wall = 0
    while True:
        t += 1
        if floor[x] == '.':
            break
        if (x + direction == m) or (x + direction < 0) or (current_floor[x+direction] == '#'):
            wall += 1
            direction = -direction
            if wall == 2:
                print("Never")
                return
        elif current_floor[x+direction] == '+':
            wall = 0
            current_floor[x+direction] = '.'
            direction = -direction
        elif l <= x+direction and x+direction <= r:
            if direction == 1:
                t += r-x-1
                x = r
            else:
                t += x-l-1
                x = l
        else:
            x += direction
            r = max(r, x)
            l = min(l, x)
    current_floor, floor = floor, current_floor
print(t)


I found an interesting problem on https://codeforces.com/problemset/problem/251/B:
Little Petya likes permutations a lot. Recently his mom has presented him permutation q_1, q_2, ..., q_{n} of length n.

A permutation a of length n is a sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n), all integers there are distinct.

There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length n. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules:  Before the beginning of the game Petya writes permutation 1, 2, ..., n on the blackboard. After that Petya makes exactly k moves, which are described below.  During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2.  Let's assume that the board contains permutation p_1, p_2, ..., p_{n} at the given moment. Then Petya removes the written permutation p from the board and writes another one instead: p_{q}_1, p_{q}_2, ..., p_{q}_{n}. In other words, Petya applies permutation q (which he has got from his mother) to permutation p.  All actions are similar to point 1, except that Petya writes permutation t on the board, such that: t_{q}_{i} = p_{i} for all i from 1 to n. In other words, Petya applies a permutation that is inverse to q to permutation p.

We know that after the k-th move the board contained Masha's permutation s_1, s_2, ..., s_{n}. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the k-th move. Note that the game has exactly k moves, that is, throughout the game the coin was tossed exactly k times.

Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding.

-----Input-----

The first line contains two integers n and k (1 ≤ n, k ≤ 100). The second line contains n space-separated integers q_1, q_2, ..., q_{n} (1 ≤ q_{i} ≤ n) — the permutation that...

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

import sys
from math import *

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return list(map(int, minp().split()))

n, k = mints()
q = list(mints())
for i in range(n):
	q[i] -= 1
s = list(mints())
a = [i for i in range(1,n+1)]
d = [0]*n
b = [False]*(k+1)
c = [False]*(k+1)
e = [10000]*2
f = [10000]*2
for i in range(k+1):
	#print(a)
	b[i] = (a == s)
	if b[i]:
		e[i%2] = min(e[i%2], i)
	for j in range(n):
		d[j] = a[q[j]]
	a,d = d,a
#print('====')
a = [i for i in range(1,n+1)]
for i in range(k+1):
	#print(a)
	c[i] = (a == s)
	if c[i]:
		f[i%2] = min(f[i%2], i)
	for j in range(n):
		d[q[j]] = a[j]
	a,d = d,a
#print('====')
#print(e)
#print(f)
if e[0] == 0:
	print('NO')
elif e[1] == 1:
	if f[1] == 1 and k > 1:
		print('NO')
	elif k%2 == 1 or f[k%2] <= k:
		print('YES')
	else:
		print('NO')
elif f[1] == 1:
	if k%2 == 1 or e[k%2] <= k:
		print('YES')
	else:
		print('NO')
else:
	if e[k%2] <= k or f[k%2] <= k:
		print('YES')
	else:
		print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/252/A:
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.

The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 2^30.

-----Output-----

Print a single integer — the required maximal xor of a segment of consecutive elements.

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

Output
3

Input
3
1 2 7

Output
7

Input
4
4 2 4 8

Output
14

-----Note-----

In the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.

The second sample contains only one optimal segment, which contains exactly one array element (element with index three).

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

import itertools
import functools
def allSubArrays(xs):
    n = len(xs)
    indices = list(range(n+1))
    for i,j in itertools.combinations(indices,2):
        yield xs[i:j]
n=int(input())
my_list=list(map(int,input().split(" ")))
list_=list(allSubArrays(my_list))
for i in range(len(list_)):
    list_[i]=functools.reduce(lambda x,y:x^y,list_[i])
print(max(list_))


I found an interesting problem on https://codeforces.com/problemset/problem/252/B:
Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya must swap some two integers even if the original array meets all requirements.

Array a (the array elements are indexed from 1) consisting of n elements is called sorted if it meets at least one of the following two conditions:  a_1 ≤ a_2 ≤ ... ≤ a_{n};  a_1 ≥ a_2 ≥ ... ≥ a_{n}.

Help Petya find the two required positions to swap or else say that they do not exist.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5). The second line contains n non-negative space-separated integers a_1, a_2, ..., a_{n} — the elements of the array that Petya's mother presented him. All integers in the input do not exceed 10^9.

-----Output-----

If there is a pair of positions that make the array unsorted if swapped, then print the numbers of these positions separated by a space. If there are several pairs of positions, print any of them. If such pair does not exist, print -1. The positions in the array are numbered with integers from 1 to n.

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

Output
-1

Input
2
1 2

Output
-1

Input
4
1 2 3 4

Output
1 2

Input
3
1 1 1

Output
-1

-----Note-----

In the first two samples the required pairs obviously don't exist.

In the third sample you can swap the first two elements. After that the array will look like this: 2 1 3 4. This array is unsorted.

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

import sys

def solve():
    n, = rv()
    a, = rl(1)
    for i in range(min(10, n - 1)):
        for j in range(max(i + 1, n - 10), n):
            if a[i] != a[j]:
                a[i], a[j] = a[j], a[i]
                if notsorted(a):
                    print(i + 1, j + 1)
                    return
                a[i], a[j] = a[j], a[i]
    count = 0
    for i in range(n - 1):
        if a[i] != a[i + 1]:
            a[i], a[i + 1] = a[i + 1], a[i]
            if notsorted(a):
                print(i + 1, i + 2)
                return
            a[i], a[i + 1] = a[i + 1], a[i]
            count += 1
        if count == 100: break
    print(-1)

def notsorted(a):
    first, second = True, True
    for i in range(len(a) - 1):
        if a[i] > a[i + 1]:
            first = False
            break
    for i in range(len(a) - 1):
        if a[i] < a[i + 1]:
            second = False
            break
    return True if not first and not second else False

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/253/A:
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i < n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible.

Help the children and tell them how to form the line.

-----Input-----

The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.

-----Output-----

Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl.

Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.

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

Output
GBGBGB

Input
4 2

Output
BGBGBB

-----Note-----

In the first sample another possible answer is BGBGBG.

In the second sample answer BBGBGB is also optimal.

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

from itertools import *

inStr=next(open('input.txt'))
n=int(inStr.split()[0])
m=int(inStr.split()[1])

boys=repeat('B', n)
girls=repeat('G', m)

if n>m:
    pairs = zip_longest(boys, girls)
else:
    pairs = zip_longest(girls, boys)
result = (y for x in pairs for y in x if y is not None)
ans = ''.join(result)
open('output.txt', 'w').write(ans)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/253/B:
One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as n measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result x, and the largest result y, then the inequality y ≤ 2·x must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes.

Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.

-----Input-----

The first line contains integer n (2 ≤ n ≤ 10^5) — the number of measurements Vasya made. The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 5000) — the results of the measurements. The numbers on the second line are separated by single spaces.

-----Output-----

Print a single integer — the minimum number of results Vasya will have to remove.

-----Examples-----
Input
6
4 5 3 8 3 7

Output
2

Input
4
4 3 2 4

Output
0

-----Note-----

In the first sample you can remove the fourth and the sixth measurement results (values 8 and 7). Then the maximum of the remaining values will be 5, and the minimum one will be 3. Or else, you can remove the third and fifth results (both equal 3). After that the largest remaining result will be 8, and...

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

import sys
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))

n, = I()
from bisect import bisect_right as br

l = I()

l.sort()
ans = MOD
for i in range(n):
	k = l[i]
	j = br(l, 2*l[i])
	ans = min(ans, n - (j - i))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/253/C:
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.

As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?

Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains a_{i} characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).

Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there,...

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

import sys
sys.stdin = open('input.txt')
sys.stdout = open('output.txt','w')

n = int(input())
a = list(map(int, input().split()))
r1, c1, r2, c2 = list(map(int, input().split()))
r1 -= 1 ; r2 -= 1 ; c1 -= 1 ; c2 -= 1
sign = 1 if r2 - r1 >= 0 else -1
for i in range(abs(r2 - r1) + 1):
    c1 = min(c1, a[r1 + sign * i])
res1 = 0
for i in range(min(r1, r2)):
    tmp = (min(r1, r2) - i) * 2
    if c1 > max(c2, a[i]) and a[i] <= min(a[i:min(r1, r2)]):
        tmp -= c1 - c2 - abs(a[i] - c2)
    res1 = min(res1, tmp)
res2 = 0
for i in range(max(r1, r2)+1, n):
    tmp = (i - max(r1, r2)) * 2
    if c1 > max(c2, a[i]) and a[i] <= min(a[max(r1, r2):i]):
        tmp -= c1 - c2 - abs(a[i] - c2)
    res2 = min(res2, tmp)
print(min(res1, res2) + abs(r2 - r1) + abs(c1 - c2))


I found an interesting problem on https://codeforces.com/problemset/problem/254/B:
In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number i should be prepared by p_{i} people for t_{i} days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it.

For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd.

In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time.

-----Input-----

The first line contains integer n — the number of Olympiads in 2013 (1 ≤ n ≤ 100). Each of the following n lines contains four integers m_{i}, d_{i}, p_{i} and t_{i} — the month and day of the Olympiad (given without leading zeroes), the needed number of the jury members and the time needed to prepare the i-th Olympiad (1 ≤ m_{i} ≤ 12, d_{i} ≥ 1, 1 ≤ p_{i}, t_{i} ≤ 100), d_{i} doesn't exceed the number of days in month m_{i}. The Olympiads are given in the arbitrary order. Several Olympiads can take place in one day.

Use the modern (Gregorian) calendar in the solution. Note that all...

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/255/A:
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a_1, a_2, ..., a_{n}. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise a_{i} times.

Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the n-th exercise.

Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 20). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 25) — the number of times Greg repeats the exercises.

-----Output-----

Print word "chest" (without the quotes), if the chest gets the most exercise, "biceps" (without the quotes), if the biceps gets the most exercise and print "back" (without the quotes) if the back gets the most exercise.

It is guaranteed that the input is such that the answer to the problem is unambiguous.

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

Output
biceps

Input
3
5 1 10

Output
back

Input
7
3 3 2 7 9 6 8

Output
chest

-----Note-----

In the first sample Greg does 2 chest, 8 biceps and zero back exercises, so the biceps gets the most exercises.

In the second sample Greg does 5 chest, 1 biceps and 10 back exercises, so the back gets the most exercises.

In the third sample Greg does 18 chest, 12 biceps and 8 back exercises, so the chest gets the most exercise.

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

input()
l = [int(x) for x in input().split()]
a = sum(l[0::3])
b = sum(l[1::3])
c = sum(l[2::3])
if a > b and a > c:
	print('chest')
elif b > a and b > c:
	print('biceps')
else:
	print('back')


I found an interesting problem on https://codeforces.com/problemset/problem/255/B:
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime:  Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.  Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.

The input for the new algorithm is string s, and the algorithm works as follows:  If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string.  If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm.

Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s.

-----Input-----

The first line contains a non-empty string s.

It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 10^6 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.

-----Output-----

In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s.

-----Examples-----
Input
x

Output
x

Input
yxyxy

Output
y

Input
xxxxxy

Output
xxxx

-----Note-----

In the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change.

In the...

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

from collections import Counter
def get_ans():
    c = Counter(input())
    x = c['x']
    y = c['y']
    if x > y:
        return 'x'*(x-y)
    elif y > x:
        return 'y'*(y-x)
    else:
        return ''
ans = get_ans()
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/255/C:
Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as:  a_1 = p, where p is some integer;  a_{i} = a_{i} - 1 + ( - 1)^{i} + 1·q (i > 1), where q is some integer.

Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression.

Sequence s_1,  s_2,  ...,  s_{k} is a subsequence of sequence b_1,  b_2,  ...,  b_{n}, if there is such increasing sequence of indexes i_1, i_2, ..., i_{k} (1  ≤  i_1  <  i_2  < ...   <  i_{k}  ≤  n), that b_{i}_{j}  =  s_{j}. In other words, sequence s can be obtained from b by crossing out some elements.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 4000). The next line contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^6).

-----Output-----

Print a single integer — the length of the required longest subsequence.

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

Output
2

Input
4
10 20 10 30

Output
3

-----Note-----

In the first test the sequence actually is the suitable subsequence.

In the second test the following subsequence fits: 10, 20, 10.

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

n=int(input())
b=list(map(int,input().split()))
dp=[[1]*n for i in range(n)]
d,k={},0
for i in range(n):
	if b[i] not in d:
		d[b[i]]=k
		k+=1
	b[i]=d[b[i]]
d.clear()
for i in range(n):
	for j in range(i):
		dp[i][b[j]]=max(1+dp[j][b[i]],dp[i][b[j]])
ans=0
for l in dp:
	ans=max(ans,max(l))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/255/D:
Mr. Bender has a digital table of size n × n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy.

We'll consider the table rows numbered from top to bottom from 1 to n, and the columns — numbered from left to right from 1 to n. Initially there is exactly one switched on cell with coordinates (x, y) (x is the row number, y is the column number), and all other cells are switched off. Then each second we switch on the cells that are off but have the side-adjacent cells that are on.

For a cell with coordinates (x, y) the side-adjacent cells are cells with coordinates (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1).

In how many seconds will Mr. Bender get happy?

-----Input-----

The first line contains four space-separated integers n, x, y, c (1 ≤ n, c ≤ 10^9; 1 ≤ x, y ≤ n; c ≤ n^2).

-----Output-----

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

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

Output
0

Input
9 3 8 10

Output
2

-----Note-----

Initially the first test has one painted cell, so the answer is 0. In the second test all events will go as is shown on the figure. [Image].

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

x, y, n, c = 0, 0, 0, 0
def suma_impares(m):
	return m * m
def suma_n(m):
	return m * (m - 1) // 2
def cnt(t):
	u, d, l, r = x + t, x - t, y - t, y + t
	suma = t ** 2 + (t + 1) ** 2
	if u > n: suma -= suma_impares(u - n)
	if d < 1: suma -= suma_impares(1 - d)
	if l < 1: suma -= suma_impares(1 - l)
	if r > n: suma -= suma_impares(r - n)
	if 1 - l > x - 1 and 1 - d > y - 1:
		suma += suma_n(2 - l - x)
	if r - n > x - 1 and 1 - d > n - y:
		suma += suma_n(r - n - x + 1)
	if 1 - l > n - x and u - n > y - 1:
		suma += suma_n(1 - l - n + x)
	if u - n > n - y and r - n > n - x:
		suma += suma_n(u - n - n + y)
	return suma

n, x, y, c = input().split()
n, x, y, c = int(n), int(x), int(y), int(c)
#for i in range(10):
#	print(i, cnt(i))
ini, fin = 0, int(1e9)
cont = int(1e9)
while cont > 0:
	m = ini
	paso = cont // 2
	m += paso
	if cnt(m) < c:
		ini = m + 1
		cont -= paso + 1
	else:
		cont = paso
print(ini)