I found an interesting problem on https://codeforces.com/problemset/problem/336/C:
Vasily the bear has got a sequence of positive integers a_1, a_2, ..., a_{n}. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum.

The beauty of the written out numbers b_1, b_2, ..., b_{k} is such maximum non-negative integer v, that number b_1 and b_2 and ... and b_{k} is divisible by number 2^{v} without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b_1 and b_2 and ... and b_{k} is divisible by 2^{v} without a remainder), the beauty of the written out numbers equals -1.

Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.

Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&", in Pascal — by "and".

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_1 < a_2 < ... < a_{n} ≤ 10^9).

-----Output-----

In the first line print a single integer k (k > 0), showing how many numbers to write out. In the second line print k integers b_1, b_2, ..., b_{k} — the numbers to write out. You are allowed to print numbers b_1, b_2, ..., b_{k} in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them.

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

Output
2
4 5

Input
3
1 2 4

Output
1
4

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

import functools
n = int(input())

nums = list(map(int, input().split()))

bits = ["{0:b}".format(num) for num in nums]

def possible(v):
    possible_vals = [
        nums[x]
        for x in range(n)
        if len(bits[x]) > v and bits[x][len(bits[x])-v-1] == '1'
    ]
    if len(possible_vals) == 0:
        return False, []
    res = functools.reduce((lambda x, y: x&y), possible_vals, pow(2, v+1)-1)
    return bool(res & ((1 << (v+1))-1) == (1 << v)), possible_vals

for x in range(30, -1, -1):
    p, vals = possible(x)
    if p:
        print(len(vals))
        print(' '.join(list(map(str, vals))))
        break


I found an interesting problem on https://codeforces.com/problemset/problem/337/A:
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).

The shop assistant told the teacher that there are m puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of f_1 pieces, the second one consists of f_2 pieces and so on.

Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let A be the number of pieces in the largest puzzle that the teacher buys and B be the number of pieces in the smallest such puzzle. She wants to choose such n puzzles that A - B is minimum possible. Help the teacher and find the least possible value of A - B.

-----Input-----

The first line contains space-separated integers n and m (2 ≤ n ≤ m ≤ 50). The second line contains m space-separated integers f_1, f_2, ..., f_{m} (4 ≤ f_{i} ≤ 1000) — the quantities of pieces in the puzzles sold in the shop.

-----Output-----

Print a single integer — the least possible difference the teacher can obtain.

-----Examples-----
Input
4 6
10 12 10 7 5 22

Output
5

-----Note-----

Sample 1. The class has 4 students. The shop sells 6 puzzles. If Ms. Manana buys the first four puzzles consisting of 10, 12, 10 and 7 pieces correspondingly, then the difference between the sizes of the largest and the smallest puzzle will be equal to 5. It is impossible to obtain a smaller difference. Note that the teacher can also buy puzzles 1, 3, 4 and 5 to obtain the difference 5.

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

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

f = list(map(int, input().split()))
f.sort()

lpd = f[n - 1] - f[0]

for i in range(1, m - n + 1, 1):
    if f[i + n - 1] - f[i] < lpd:
        lpd = f[i + n - 1] - f[i]

print(lpd)


I found an interesting problem on https://codeforces.com/problemset/problem/337/B:
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the screen as possible and fits within it completely. Thus, he may have to zoom the movie in or out, but Manao will always change the frame proportionally in both dimensions.

Calculate the ratio of empty screen (the part of the screen not occupied by the movie) to the total screen size. Print the answer as an irreducible fraction p / q.

-----Input-----

A single line contains four space-separated integers a, b, c, d (1 ≤ a, b, c, d ≤ 1000).

-----Output-----

Print the answer to the problem as "p/q", where p is a non-negative integer, q is a positive integer and numbers p and q don't have a common divisor larger than 1.

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

Output
1/3

Input
4 3 2 2

Output
1/4

-----Note-----

Sample 1. Manao's monitor has a square screen. The movie has 3:2 horizontal to vertical length ratio. Obviously, the movie occupies most of the screen if the width of the picture coincides with the width of the screen. In this case, only 2/3 of the monitor will project the movie in the horizontal dimension: [Image]

Sample 2. This time the monitor's width is 4/3 times larger than its height and the movie's frame is square. In this case, the picture must take up the whole monitor in the vertical dimension and only 3/4 in the horizontal dimension: [Image]

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

import sys

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

class Fraction:
    def __init__(self, p = 0, q = 1, reduced = True):
        if type(p) == int:
            self.p = p
            if type(q) == int:
                self.q = q
        elif type(p) == Fraction:
            self.p = p.p
            self.q = p.q
        else:
            i = p.find(' ')
            if i == -1:
                i = p.find('/')
            if i == -1:
                self.p = int(p)
                self.q = 1
            else:
                self.p = int(p[:i])
                self.q = int(p[i + 1:])
        if reduced:
            self.reduce()

    def reduce(self):
        g = gcd(self.p, self.q)
        self.p //= g
        self.q //= g

    def __str__(self):
        if self.q == 1:
            return(str(self.p))
        else:
            return(str(self.p) + '/' + str(self.q))

    def __lt__(self, other):
        self.reduce()
        if type(other) == float or type(other) == int:
            return self.p < other * self.q
        else:
            other.reduce()
            return self.p * other.q < self.q * other.p

    def __le__(self, other):
        self.reduce()
        if type(other) == float or type(other) == int:
            return self.p <= other * self.q
        else:
            other.reduce()
            return self.p * other.q <= self.q * other.p

    def __gt__(self, other):
        self.reduce()
        if type(other) == float or type(other) == int:
            return self.p > other * self.q
        else:
            other.reduce()
            return self.p * other.q > self.q * other.p

    def __ge__(self, other):
        self.reduce()
        if type(other) == float or type(other) == int:
            return self.p >= other * self.q
        else:
            other.reduce()
            return self.p * other.q >= self.q * other.p

    def __eq__(self, other):
        self.reduce()
        if type(other) == float or type(other) == int:
            return self.p == other *...


I found an interesting problem on https://codeforces.com/problemset/problem/337/C:
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero.

Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (10^9 + 9).

-----Input-----

The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 10^9; 0 ≤ m ≤ n).

-----Output-----

Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (10^9 + 9).

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

Output
3

Input
5 4 2

Output
6

-----Note-----

Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points.

Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4.

Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number.

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/337/D:
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.

The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.

Manao has heard of m settlements affected by the Book of Evil. Their numbers are p_1, p_2, ..., p_{m}. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.

-----Input-----

The first line contains three space-separated integers n, m and d (1 ≤ m ≤ n ≤ 100000; 0 ≤ d ≤ n - 1). The second line contains m distinct space-separated integers p_1, p_2, ..., p_{m} (1 ≤ p_{i} ≤ n). Then n - 1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers a_{i} and b_{i} representing the ends of this path.

-----Output-----

Print a single number — the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.

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

Output
3

-----Note-----

Sample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5.

 [Image]

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

from collections import defaultdict
import sys
input=sys.stdin.readline

class graph:
    def __init__(self,n,mark):
        self.d=defaultdict(list)
        self.n=n
        self.mark=mark

    def add(self,s,d):
        self.d[s].append(d)
        self.d[d].append(s)

    def bfs(self,s,dis):
        marked=s
        visited=[False]*self.n
        visited[s]=True
        q=[s]
        while q:
            s=q.pop(0)
            if(s in mark):
                marked=s
            for i in self.d[s]:
                if(visited[i]==False):
                    q.append(i)
                    visited[i]=True
                    dis[i]+=dis[s]+1
        return marked

n,m,k=list(map(int,input().split()))
mrk=[int(x) for x in input().split()]
mark={}
for i in mrk:
    mark[i-1]=1

g=graph(n,mark)

for i in range(n-1):
    a,b=list(map(int,input().split()))
    g.add(a-1,b-1)
dis=[0]*n
u=g.bfs(0,dis)
dis=[0]*n
d=g.bfs(u,dis)
#print(dis)
temp=[0]*n
x=g.bfs(d,temp)
#print(temp)
count=0
for i in range(n):
    if(temp[i]<=k and dis[i]<=k):
        count+=1
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/338/D:
Consider a table G of size n × m such that G(i, j) = GCD(i, j) for all 1 ≤ i ≤ n, 1 ≤ j ≤ m. GCD(a, b) is the greatest common divisor of numbers a and b.

You have a sequence of positive integer numbers a_1, a_2, ..., a_{k}. We say that this sequence occurs in table G if it coincides with consecutive elements in some row, starting from some position. More formally, such numbers 1 ≤ i ≤ n and 1 ≤ j ≤ m - k + 1 should exist that G(i, j + l - 1) = a_{l} for all 1 ≤ l ≤ k.

Determine if the sequence a occurs in table G.

-----Input-----

The first line contains three space-separated integers n, m and k (1 ≤ n, m ≤ 10^12; 1 ≤ k ≤ 10000). The second line contains k space-separated integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ 10^12).

-----Output-----

Print a single word "YES", if the given sequence occurs in table G, otherwise print "NO".

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

Output
YES

Input
100 8 5
5 2 1 2 1

Output
NO

Input
100 100 7
1 2 3 4 5 6 7

Output
NO

-----Note-----

Sample 1. The tenth row of table G starts from sequence {1, 2, 1, 2, 5, 2, 1, 2, 1, 10}. As you can see, elements from fifth to ninth coincide with sequence a.

Sample 2. This time the width of table G equals 8. Sequence a doesn't occur there.

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

'''
Created on Aug 28, 2016

@author: Md. Rezwanul Haque
'''
def gcd(a,b):
    if b == 0:
        return a
    return gcd(b, a%b)
def extend_euclid(a,b):
    if b == 0:
        return 1,0
    else:
        y,x = extend_euclid(b, a%b)
        y = y - (a//b)*x
        return x,y

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

lcm = 1
for i in a:
    lcm = (lcm*i)//gcd(lcm, i)
    if lcm>n:
        print('NO')
        return
j = 0
m1 = 1
s = True
for i in range(k):
    x,y = extend_euclid(m1, a[i])
    res = m1*x + a[i]*y
    if (-i-j)%res != 0:
        s = False
        break
    res = (-i-j)//res
    x,y = x*res , y*res
    j += m1*x
    t = m1*a[i]
    if j>t:
        j -= (j//t)*t
    if j<0:
        j += ((-j+t-1)//t)*t
    if j == 0:
        j = t
    m1 = (m1*a[i])//gcd(m1, a[i])

if j+k-1 >m or s == False:
    print('NO')
    return
b = [gcd(lcm, j+i) for i in range(k)]
for i in range(k):
    if (a[i] != b[i]):
        print('NO')
        return
print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/339/A:
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.

The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.

You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.

-----Input-----

The first line contains a non-empty string s — the sum Xenia needs to count. String s contains no spaces. It only contains digits and characters "+". Besides, string s is a correct sum of numbers 1, 2 and 3. String s is at most 100 characters long.

-----Output-----

Print the new sum that Xenia can count.

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

Output
1+2+3

Input
1+1+3+1+3

Output
1+1+1+3+3

Input
2

Output
2

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

arr = list(map(int, input().split('+')))
arr.sort()
for i in arr[:-1]:
    print(str(i), end='+')
print(arr[-1])


I found an interesting problem on https://codeforces.com/problemset/problem/339/B:
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.

Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number a_{i} and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.

-----Input-----

The first line contains two integers n and m (2 ≤ n ≤ 10^5, 1 ≤ m ≤ 10^5). The second line contains m integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ n). Note that Xenia can have multiple consecutive tasks in one house.

-----Output-----

Print a single integer — the time Xenia needs to complete all tasks.

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

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

Output
6

Input
4 3
2 3 3

Output
2

-----Note-----

In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.

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

n, m = map(int, input().split())
a = (1,) + tuple(map(int, input().split()))
ans = 0
for i in range(1, len(a)):
    ans += (a[i] - a[i - 1] + n) % n
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/339/C:
Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of m weights on the scalepans.

Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes i-th should be different from the (i + 1)-th weight for any i (1 ≤ i < m). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.

You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay m weights on the scales or to say that it can't be done.

-----Input-----

The first line contains a string consisting of exactly ten zeroes and ones: the i-th (i ≥ 1) character in the line equals "1" if Xenia has i kilo weights, otherwise the character equals "0". The second line contains integer m (1 ≤ m ≤ 1000).

-----Output-----

In the first line print "YES", if there is a way to put m weights on the scales by all rules. Otherwise, print in the first line "NO". If you can put m weights on the scales, then print in the next line m integers — the weights' weights in the order you put them on the scales.

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

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

Output
YES
8 10 8

Input
1000000000
2

Output
NO

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

__author__ = 'ratnesh.mishra'

weights = list(map(int, input()))

weights = [cnt for cnt, x in enumerate(weights, 1) if x]

m = int(input())

state = [(0, 0, 0, [])]

res = "NO"
while state:
    w, b, k, l = state.pop()

    if k == m:
        res = 'YES\n' + ' '.join(map(str, l))
        break

    for wt in weights:
        if wt != w and wt > b:
            state.append((wt, wt-b, k+1, l+[wt]))

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/339/D:
Xenia the beginner programmer has a sequence a, consisting of 2^{n} non-negative integers: a_1, a_2, ..., a_2^{n}. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.

Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a_1 or a_2, a_3 or a_4, ..., a_2^{n} - 1 or a_2^{n}, consisting of 2^{n} - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.

Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.

You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment a_{p} = b. After each query, you need to print the new value v for the new sequence a.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 10^5). The next line contains 2^{n} integers a_1, a_2, ..., a_2^{n} (0 ≤ a_{i} < 2^30). Each of the next m lines contains queries. The i-th line contains integers p_{i}, b_{i} (1 ≤ p_{i} ≤ 2^{n}, 0 ≤ b_{i} < 2^30) — the i-th query.

-----Output-----

Print m integers — the i-th integer denotes value v for sequence a after the i-th query.

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

Output
1
3
3
3

-----Note-----

For more information on the bit operations, you can...

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

from operator import or_, xor
import sys

n, m = list(map(int, input().split()))
t = [list(map(int, input().split()))]
for i in range(n):
    t += [[(or_, xor)[i & 1](*t[i][j: j + 2]) for j in range(0, len(t[i]), 2)]]

for s in sys.stdin:
    p, b = s.split()
    p = int(p) - 1
    t[0][p] = int(b)
    for j in range(n):
        p >>= 1
        t[j + 1][p] = (or_, xor)[j & 1](*t[j][p << 1: (p << 1) + 2])
    sys.stdout.write(str(t[-1][0]) + '\n')


I found an interesting problem on https://codeforces.com/problemset/problem/340/A:
Iahub and his friend Floyd have started painting a wall. Iahub is painting the wall red and Floyd is painting it pink. You can consider the wall being made of a very large number of bricks, numbered 1, 2, 3 and so on.

Iahub has the following scheme of painting: he skips x - 1 consecutive bricks, then he paints the x-th one. That is, he'll paint bricks x, 2·x, 3·x and so on red. Similarly, Floyd skips y - 1 consecutive bricks, then he paints the y-th one. Hence he'll paint bricks y, 2·y, 3·y and so on pink.

After painting the wall all day, the boys observed that some bricks are painted both red and pink. Iahub has a lucky number a and Floyd has a lucky number b. Boys wonder how many bricks numbered no less than a and no greater than b are painted both red and pink. This is exactly your task: compute and print the answer to the question.

-----Input-----

The input will have a single line containing four integers in this order: x, y, a, b. (1 ≤ x, y ≤ 1000, 1 ≤ a, b ≤ 2·10^9, a ≤ b).

-----Output-----

Output a single integer — the number of bricks numbered no less than a and no greater than b that are painted both red and pink.

-----Examples-----
Input
2 3 6 18

Output
3

-----Note-----

Let's look at the bricks from a to b (a = 6, b = 18). The bricks colored in red are numbered 6, 8, 10, 12, 14, 16, 18. The bricks colored in pink are numbered 6, 9, 12, 15, 18. The bricks colored in both red and pink are numbered with 6, 12 and 18.

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

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

def lcm(a, b):
    return a * b / gcd(a, b)

x, y, a, b = list(map(int, input().split(' ')))
l = lcm(x, y)
print(int(b // l - (a - 1) // l))


I found an interesting problem on https://codeforces.com/problemset/problem/340/B:
Iahub has drawn a set of n points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one which has all four vertices in the set of special points. Given the set of special points, please calculate the maximal area of a special quadrilateral.

-----Input-----

The first line contains integer n (4 ≤ n ≤ 300). Each of the next n lines contains two integers: x_{i}, y_{i} ( - 1000 ≤ x_{i}, y_{i} ≤ 1000) — the cartesian coordinates of ith special point. It is guaranteed that no three points are on the same line. It is guaranteed that no two points coincide.

-----Output-----

Output a single real number — the maximal area of a special quadrilateral. The answer will be considered correct if its absolute or relative error does't exceed 10^{ - 9}.

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

Output
16.000000

-----Note-----

In the test example we can choose first 4 points to be the vertices of the quadrilateral. They form a square by side 4, so the area is 4·4 = 16.

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

import sys
s, n = 0, int(input())
t = list(map(int, sys.stdin.read().split()))
p = [(t[2 * i], t[2 * i + 1]) for i in range(n)]
for x, i in enumerate(p, 1):
    for j in p[x:]:
        a = b = 0
        for k in p:
            d = (i[0] - k[0]) * (j[1] - k[1]) - (i[1] - k[1]) * (j[0] - k[0])
            a, b = min(d, a), max(d, b)
        if a and b: s = max(s, b - a)
print(s / 2)


I found an interesting problem on https://codeforces.com/problemset/problem/340/C:
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a_1, a_2, ..., a_{n}. The number a_{k} represents that the kth destination is at distance a_{k} kilometers from the starting point. No two destinations are located in the same place.

Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.

The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once.

Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.

-----Input-----

The first line contains integer n (2 ≤ n ≤ 10^5). Next line contains n distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^7).

-----Output-----

Output two integers — the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.

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

Output
22 3

-----Note-----

Consider 6 possible routes:  [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5;  [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7;  [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7;  [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8;  [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9;  [5, 3,...

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

from fractions import Fraction
n=int(input())
a=[int(i) for i in input().split()]
a=sorted(a)
s=[]
s.append(0)
for i in range(n):
    s.append(s[-1]+a[i])
ans=0
for i in range(1,n+1):
    ans+=s[n]-s[i-1]-(n-i+1)*a[i-1]
ans=ans*2+sum(a)
ans=Fraction(ans,n)
print("{0:d} {1:d}".format(ans.numerator,ans.denominator))


I found an interesting problem on https://codeforces.com/problemset/problem/340/D:
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a_1, a_2, ..., a_{n} in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).

procedure bubbleSortGraph()

    build a graph G with n vertices and 0 edges

    repeat

        swapped = false

        for i = 1 to n - 1 inclusive do:

            if a[i] > a[i + 1] then

                add an undirected edge in G between a[i] and a[i + 1]

                swap( a[i], a[i + 1] )

                swapped = true

            end if

        end for

    until not swapped

    /* repeat the algorithm as long as swapped value is true. */

end procedure

For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.

-----Input-----

The first line of the input contains an integer n (2 ≤ n ≤ 10^5). The next line contains n distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n).

-----Output-----

Output a single integer — the answer to the problem.

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

Output
2

-----Note-----

Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].

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

import math
import sys
from bisect import bisect_right, bisect_left, insort_right
from collections import Counter, defaultdict
from heapq import heappop, heappush
from itertools import accumulate, permutations, combinations
from sys import stdout

R = lambda: map(int, input().split())
n = int(input())
arr = list(R())
tps = [(0, 0)]
for x in arr:
    i = bisect_left(tps, (x, -1)) - 1
    tps.insert(i + 1, (x, tps[i][1] + 1))
    if i + 2 < len(tps) and tps[i + 1][1] >= tps[i + 2][1]:
        del tps[i + 2]
print(max(x[1] for x in tps))


I found an interesting problem on https://codeforces.com/problemset/problem/340/E:
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.

The girl finds an important permutation for the research. The permutation contains n distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n). She replaces some of permutation elements with -1 value as a revenge.

When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element a_{k} which has value equal to k (a_{k} = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (10^9 + 7).

-----Input-----

The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1.

It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.

-----Output-----

Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (10^9 + 7).

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

Output
2

-----Note-----

For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.

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

MOD = 10**9+7
n = int(input())

notUsed = set(range(1, n+1))
chairs = set()
for i, a in enumerate(map(int, input().split()), 1):
    if a == -1:
        chairs.add(i)
    else:
        notUsed -= {a}
fixed = len(chairs & notUsed)

m = len(notUsed)
U = m
fact = [0]*(U+1)
fact[0] = 1
for i in range(1, U+1):
    fact[i] = fact[i-1]*i % MOD

invfact = [0]*(U+1)
invfact[U] = pow(fact[U], MOD-2, MOD)
for i in reversed(list(range(U))):
    invfact[i] = invfact[i+1]*(i+1) % MOD

def nCr(n, r):
    if r < 0 or n < r:
        return 0
    return fact[n]*invfact[r]*invfact[n-r]

ans = fact[m]
for k in range(1, fixed+1):
    ans += nCr(fixed, k)*fact[m-k]*(-1)**k
    ans %= MOD
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/342/A:
Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:  a < b < c;  a divides b, b divides c.

Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has $\frac{n}{3}$ groups of three.

Help Xenia, find the required partition or else say that it doesn't exist.

-----Input-----

The first line contains integer n (3 ≤ n ≤ 99999) — the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7.

It is guaranteed that n is divisible by 3.

-----Output-----

If the required partition exists, print $\frac{n}{3}$ groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them.

If there is no solution, print -1.

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

Output
-1

Input
6
2 2 1 1 4 6

Output
1 2 4
1 2 6

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

n = int(input())
arr = list(map(int, input().split()))
mp = dict()
mp[1] = 0
mp[2] = 0
mp[3] = 0
mp[4] = 0
mp[6] = 0
for num in arr:
    if num == 1:
        mp[1] = mp[1] + 1
    elif num == 2:
        mp[2] = mp[2] + 1
    elif num == 3:
        mp[3] = mp[3] + 1
    elif num == 4:
        mp[4] = mp[4] + 1
    elif num == 6:
        mp[6] = mp[6] + 1

sum0 = 0
sum1 = 0
sum2 = 0

if mp[1] != n//3:
    print(-1)
else:
    while True:
        flag = True
        if mp[2] > 0 and mp[4] > 0:
            sum0 = sum0 + 1
            flag = False
            mp[2] = mp[2] - 1
            mp[4] = mp[4] - 1
        elif mp[2] > 0 and mp[6] > 0:
            sum1 = sum1 + 1
            flag = False
            mp[2] = mp[2] - 1
            mp[6] = mp[6] - 1
        elif mp[3] > 0 and mp[6] > 0:
            sum2 = sum2 + 1
            flag = False
            mp[3] = mp[3] - 1
            mp[6] = mp[6] - 1
        if flag == True:
            break

    if sum0 + sum1 + sum2 != n//3:
        print(-1)
    else:
        for i in range(sum0):
            print(1, " ", 2, " ", 4)
        for i in range(sum1):
            print(1, " ", 2, " ", 6)
        for i in range(sum2):
            print(1, " ", 3, " ", 6)


I found an interesting problem on https://codeforces.com/problemset/problem/342/B:
Xenia the vigorous detective faced n (n ≥ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right.

Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x - 1 or x + 1 (if x = 1 or x = n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.

But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step t_{i} (steps are numbered from 1) Xenia watches spies numbers l_{i}, l_{i} + 1, l_{i} + 2, ..., r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.

You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps).

-----Input-----

The first line contains four integers n, m, s and f (1 ≤ n, m ≤ 10^5; 1 ≤ s, f ≤ n; s ≠ f; n ≥ 2). Each of the following m lines contains three integers t_{i}, l_{i}, r_{i} (1 ≤ t_{i} ≤ 10^9, 1 ≤ l_{i} ≤ r_{i} ≤ n). It is guaranteed that t_1 < t_2 < t_3 < ... < t_{m}.

-----Output-----

Print k characters in a line: the i-th character in the line must represent the spies' actions on step i. If on step i the spy with the note must pass the note to the spy with a lesser number, the i-th character should equal "L". If on step i the spy with the note must pass it to the spy with a larger number, the i-th character must equal...

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

n, m, s, f = map(int, input().split())
data = {}
for _ in range(m):
    t, l, r = map(int, input().split())
    data[t] = (l, r)
k = 1
curr = s
while curr != f:
    if k in data:
        if data[k][0] <= curr <= data[k][1]:
            print('X', end='')
        else:
            if 1 < curr < n:
                if curr > f:
                    if data[k][0] <= curr - 1 <= data[k][1]:
                        print('X', end='')
                    else:
                        print('L', end='')
                        curr -= 1
                else:
                    if data[k][0] <= curr + 1 <= data[k][1]:
                        print('X', end='')
                    else:
                        print('R', end='')
                        curr += 1
            elif curr == 1:
                if data[k][0] <= 2 <= data[k][1]:
                    print('X', end='')
                else:
                    print('R', end='')
                    curr = 2
            elif curr == n:
                if data[k][0] <= curr-1 <= data[k][1]:
                    print('X', end='')
                else:
                    print('L', end='')
                    curr -= 1
    else:
        if curr > f:
            print('L', end='')
            curr -= 1
        else:
            print('R', end='')
            curr += 1
    k += 1

# Mon Aug 12 2019 14:53:46 GMT+0300 (MSK)


I found an interesting problem on https://codeforces.com/problemset/problem/342/C:
A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius r (the cupboard's top) and two walls of height h (the cupboard's sides). The cupboard's depth is r, that is, it looks like a rectangle with base r and height h + r from the sides. The figure below shows what the cupboard looks like (the front view is on the left, the side view is on the right). [Image]

Xenia got lots of balloons for her birthday. The girl hates the mess, so she wants to store the balloons in the cupboard. Luckily, each balloon is a sphere with radius $\frac{r}{2}$. Help Xenia calculate the maximum number of balloons she can put in her cupboard.

You can say that a balloon is in the cupboard if you can't see any part of the balloon on the left or right view. The balloons in the cupboard can touch each other. It is not allowed to squeeze the balloons or deform them in any way. You can assume that the cupboard's walls are negligibly thin.

-----Input-----

The single line contains two integers r, h (1 ≤ r, h ≤ 10^7).

-----Output-----

Print a single integer — the maximum number of balloons Xenia can put in the cupboard.

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

Output
3

Input
1 2

Output
5

Input
2 1

Output
2

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/343/A:
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.

However, all Mike has is lots of identical resistors with unit resistance R_0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:   one resistor;  an element and one resistor plugged in sequence;  an element and one resistor plugged in parallel.  [Image]

With the consecutive connection the resistance of the new element equals R = R_{e} + R_0. With the parallel connection the resistance of the new element equals $R = \frac{1}{\frac{1}{R_{e}} + \frac{1}{R_{0}}}$. In this case R_{e} equals the resistance of the element being connected.

Mike needs to assemble an element with a resistance equal to the fraction $\frac{a}{b}$. Determine the smallest possible number of resistors he needs to make such an element.

-----Input-----

The single input line contains two space-separated integers a and b (1 ≤ a, b ≤ 10^18). It is guaranteed that the fraction $\frac{a}{b}$ is irreducible. It is guaranteed that a solution always exists.

-----Output-----

Print a single number — the answer to the problem.

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

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

Output
1

Input
3 2

Output
3

Input
199 200

Output
200

-----Note-----

In the first sample, one resistor is enough.

In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance $\frac{1}{\frac{1}{1} + \frac{1}{1}} + 1 = \frac{3}{2}$. We cannot make this element using two resistors.

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

a,b = list(map(int,input().split()))
n = 0
while not (a == 0 or b == 0):
    if a > b:
        n += a // b
        a = a % b
    else:
        n += b // a
        b = b % a
print(n)


I found an interesting problem on https://codeforces.com/problemset/problem/343/B:
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.

The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): [Image]

Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.

To understand the problem better please read the notes to the test samples.

-----Input-----

The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≤ n ≤ 100000). The i-th (1 ≤ i ≤ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.

-----Output-----

Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.

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

Output
Yes

Input
+-

Output
No

Input
++

Output
Yes

Input
-

Output
No

-----Note-----

The first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the...

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

s=input()
x=1
if(len(s)%2==1):
    print("No")

else:
    x=len(s)-1
    start=1
    while(len(s)!=x):
        x=len(s)
        n=x
        for i in range(max(start,1),x):
            l=i-1
            r=i
            if(s[l]==s[r]):
                while(l>=0 and r<n and s[l]==s[r]):
                    r+=1
                    l-=1
                l+=1
                r-=1
                s=s[:l]+s[r+1:]
                start=l
                break

    if(len(s)==0):
        print("Yes")
    else:
        print("No")


I found an interesting problem on https://codeforces.com/problemset/problem/344/A:
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.

Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. [Image]

Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.

-----Input-----

The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.

-----Output-----

On the single line of the output print the number of groups of magnets.

-----Examples-----
Input
6
10
10
10
01
10
10

Output
3

Input
4
01
01
10
10

Output
2

-----Note-----

The first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.

The second testcase has two groups, each consisting of two magnets.

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

n = int(input())
s = []
x = 1
s.append('09')
for i in range(1, n + 1):
    s.append(input())
    if s[i - 1][1] == s[i][0]:
        x += 1
print(x)


I found an interesting problem on https://codeforces.com/problemset/problem/344/B:
Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule.

A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — the number of bonds the atom must form with other atoms. An atom can form one or multiple bonds with any other atom, but it cannot form a bond with itself. The number of bonds of an atom in the molecule must be equal to its valence number. [Image]

Mike knows valence numbers of the three atoms. Find a molecule that can be built from these atoms according to the stated rules, or determine that it is impossible.

-----Input-----

The single line of the input contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 10^6) — the valence numbers of the given atoms.

-----Output-----

If such a molecule can be built, print three space-separated integers — the number of bonds between the 1-st and the 2-nd, the 2-nd and the 3-rd, the 3-rd and the 1-st atoms, correspondingly. If there are multiple solutions, output any of them. If there is no solution, print "Impossible" (without the quotes).

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

Output
0 1 1

Input
3 4 5

Output
1 3 2

Input
4 1 1

Output
Impossible

-----Note-----

The first sample corresponds to the first figure. There are no bonds between atoms 1 and 2 in this case.

The second sample corresponds to the second figure. There is one or more bonds between each pair of atoms.

The third sample corresponds to the third figure. There is no solution, because an atom cannot form bonds with itself.

The configuration in the fourth figure is impossible as each atom must have at least one atomic bond.

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/346/B:
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.

You are given two strings s_1, s_2 and another string called virus. Your task is to find the longest common subsequence of s_1 and s_2, such that it doesn't contain virus as a substring.

-----Input-----

The input contains three strings in three separate lines: s_1, s_2 and virus (1 ≤ |s_1|, |s_2|, |virus| ≤ 100). Each string consists only of uppercase English letters.

-----Output-----

Output the longest common subsequence of s_1 and s_2 without virus as a substring. If there are multiple answers, any of them will be accepted.

If there is no valid common subsequence, output 0.

-----Examples-----
Input
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ

Output
ORZ

Input
AA
A
A

Output
0

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

# coding=utf-8
from functools import reduce

a = input()
b = input()
c = input()

alen = len(a)
blen = len(b)
clen = len(c)

kmpnext = [0]*(clen+1)
i = 1
j = 0
while i < clen:
	while j > 0 and c[i]!=c[j]:
		j = kmpnext[j]
	if c[i] == c[j]:
		j+=1
	kmpnext[i+1] = j
	i+=1
#print(kmpnext)

f = [[[0 for i in range(clen+2)] for i in range(blen+2)] for i in range(alen+2)]
g = [[[0 for i in range(clen+2)] for i in range(blen+2)] for i in range(alen+2)]
h = [[[0 for i in range(clen+2)] for i in range(blen+2)] for i in range(alen+2)]

f[0][0][0] = 0
g[0][0][0] = (-1,-1,-1)
h[0][0][0] = 1
m = (0,0,0)

for i in range(alen):
	for j in range(blen):
		for k in range(clen):
			if h[i][j][k] == 0:
				#print(i,j,k)
				continue
			if f[i+1][j][k] < f[i][j][k] or h[i+1][j][0] == 0:
				f[i+1][j][k] = f[i][j][k]
				g[i+1][j][k] = g[i][j][k]
				h[i+1][j][k] = 1
			if f[i][j+1][k] < f[i][j][k] or h[i][j+1][0] == 0:
				f[i][j+1][k] = f[i][j][k]
				g[i][j+1][k] = g[i][j][k]
				h[i][j+1][k] = 1

			if a[i] == b[j]:
				#print(i,j,a[i],b[j])
				kt = k
				while kt != 0 and a[i] != c[kt]:
					kt = kmpnext[kt]
				if a[i] == c[kt]:
					if f[i+1][j+1][kt+1] < f[i][j][k] + 1:
						f[i+1][j+1][kt+1] = f[i][j][k] + 1
						g[i+1][j+1][kt+1] = (i,j,k)
						h[i+1][j+1][kt+1] = 1
				else:
					if f[i+1][j+1][0] < f[i][j][k] + 1:
						f[i+1][j+1][0] = f[i][j][k] + 1
						g[i+1][j+1][0] = (i,j,k)
						h[i+1][j+1][0] = 1

			#print(i,j,k,f[i][j][k],g[i][j][k])

for i in range(alen+1):
	for j in range(blen+1):
		for k in range(clen):
			if f[i][j][k] > f[m[0]][m[1]][m[2]]:
				m = (i,j,k)
if f[m[0]][m[1]][m[2]] == 0:
	print(0)
else:
	ans = ""
	t = m
	t = g[t[0]][t[1]][t[2]]
	while t != (-1,-1,-1):
		ans = a[t[0]] + ans
		t = g[t[0]][t[1]][t[2]]
	print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/347/A:
You want to arrange n integers a_1, a_2, ..., a_{n} in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.

More formally, let's denote some arrangement as a sequence of integers x_1, x_2, ..., x_{n}, where sequence x is a permutation of sequence a. The value of such an arrangement is (x_1 - x_2) + (x_2 - x_3) + ... + (x_{n} - 1 - x_{n}).

Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value.

-----Input-----

The first line of the input contains integer n (2 ≤ n ≤ 100). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 1000).

-----Output-----

Print the required sequence x_1, x_2, ..., x_{n}. Sequence x should be the lexicographically smallest permutation of a that corresponds to an arrangement of the largest possible value.

-----Examples-----
Input
5
100 -100 50 0 -50

Output
100 -50 0 50 -100

-----Note-----

In the sample test case, the value of the output arrangement is (100 - ( - 50)) + (( - 50) - 0) + (0 - 50) + (50 - ( - 100)) = 200. No other arrangement has a larger value, and among all arrangements with the value of 200, the output arrangement is the lexicographically smallest one.

Sequence x_1, x_2, ... , x_{p} is lexicographically smaller than sequence y_1, y_2, ... , y_{p} if there exists an integer r (0 ≤ r < p) such that x_1 = y_1, x_2 = y_2, ... , x_{r} = y_{r} and x_{r} + 1 < y_{r} + 1.

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

n = int(input())
list1 = list(map(int, input().split()))
print(max(list1), " ".join(map(str, sorted(list1)[1:-1])), min(list1))


I found an interesting problem on https://codeforces.com/problemset/problem/347/B:
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.

A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a_0, a_1, ..., a_{n} - 1 if and only if a_{i} = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.

You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5). The second line contains n integers a_0, a_1, ..., a_{n} - 1 — the given permutation.

-----Output-----

Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.

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

Output
3

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

n = int(input())
a = [int(x) for x in input().split()]
ans = 0
flag = True
for i in range(n):
    if a[i] == i:
        ans += 1
    elif a[a[i]] == i and flag:
        ans += 2
        flag = False
if flag and ans < n:
    ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/349/A:
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the number of people in the line. The next line contains n integers, each of them equals 25, 50 or 100 — the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.

-----Output-----

Print "YES" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print "NO".

-----Examples-----
Input
4
25 25 50 50

Output
YES

Input
2
25 100

Output
NO

Input
4
50 50 25 25

Output
NO

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

def f():
    n = int(input())
    t = list(map(int, input().split()))
    a, b = 0, 0
    for i in t:
        if i == 25: a += 1
        elif i == 50:
            b += 1
            a -= 1
        else:
            if b > 0:
                b -= 1
                a -= 1
            else: a -= 3
        if a < 0: return 1
    return 0

print('YNEOS'[f() :: 2])


I found an interesting problem on https://codeforces.com/problemset/problem/349/B:
Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has.

Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires a_{d} liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.

Help Igor find the maximum number he can write on the fence.

-----Input-----

The first line contains a positive integer v (0 ≤ v ≤ 10^6). The second line contains nine positive integers a_1, a_2, ..., a_9 (1 ≤ a_{i} ≤ 10^5).

-----Output-----

Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1.

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

Output
55555

Input
2
9 11 1 12 5 8 9 10 6

Output
33

Input
0
1 1 1 1 1 1 1 1 1

Output
-1

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

v = int(input())
a = list(map(int, input().split()))
m = list(enumerate(a, 1))
k = sorted(m, key=lambda x:(-x[1], x[0]))[-1]
t = v // k[1]
v -= t * k[1]
num = [k[0]] * t
for i in range(t):
    if v + k[1] > min(a):
        num[i] = list(q for q in m if q[1] <= v + k[1])[-1][0]
        v -= a[num[i] - 1] - k[1]
    else:
        break;
print(''.join(map(str, num)) or -1)


I found an interesting problem on https://codeforces.com/problemset/problem/350/A:
Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.

Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time (in seconds).

Let's suppose that Valera will set v seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most v seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, a seconds, an inequality 2a ≤ v holds.

As a result, Valera decided to set v seconds TL, that the following conditions are met:  v is a positive integer;  all correct solutions pass the system testing;  at least one correct solution passes the system testing with some "extra" time;  all wrong solutions do not pass the system testing;  value v is minimum among all TLs, for which points 1, 2, 3, 4 hold.

Help Valera and find the most suitable TL or else state that such TL doesn't exist.

-----Input-----

The first line contains two integers n, m (1 ≤ n, m ≤ 100). The second line contains n space-separated positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100) — the running time of each of the n correct solutions in seconds. The third line contains m space-separated positive integers b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ 100) — the running time of each of m wrong solutions in seconds.

-----Output-----

If there is a valid TL value, print it. Otherwise, print -1.

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

Output
5
Input
3 1
3 4 5
6

Output
-1

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

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

ans = max(max(A), min(A) * 2)
if min(B) <= ans:
	print(-1)
else:
	print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/350/B:
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.

Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.

Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.

Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v_1, v_2, ..., v_{k} (k ≥ 1) and meet the following conditions:  Objects with numbers v_1, v_2, ..., v_{k} - 1 are mountains and the object with number v_{k} is the hotel.  For any integer i (1 ≤ i < k), there is exactly one ski track leading from object v_{i}. This track goes to object v_{i} + 1.  The path contains as many objects as possible (k is maximal).

Help Valera. Find such path that meets all the criteria of our hero!

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the number of objects.

The second line contains n space-separated integers type_1, type_2, ..., type_{n} — the types of the objects. If type_{i} equals zero, then the i-th object is the mountain. If type_{i} equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.

The third line of the input contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ n) — the description of the ski tracks. If number a_{i} equals zero, then there is no such object v, that has a ski track built from v to i. If number a_{i} doesn't equal zero, that means that there is a track built from object a_{i} to object i.

-----Output-----

In the first line print k — the maximum possible path length for Valera. In...

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

import sys
def Z(s):
    return int(s)-1

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

Hotels=[False]*(n)

Rep=[0]*(n+1)
Chains=[]

Type=list(map(int,sys.stdin.readline().split()))
for i in range(n):
    if(Type[i]==1):
        Hotels[i]=True
A=list(map(Z,sys.stdin.readline().split()))

for item in A:
    Rep[item]+=1
for i in range(n):
    if(Hotels[i]):
        Chains.append([i])
        x=A[i]
        if(x==-1):
            continue
        while(A[x]!=-1 and Rep[x]<=1):
            Chains[-1].append(x)
            x=A[x]
        if(Rep[x]<=1):
            Chains[-1].append(x)

if(n==1):
    print(1)
    print(1)
else:

    X=max(Chains,key=len)

    sys.stdout.write(str(len(X))+"\n")
    sys.stdout.write(str(X[-1]+1))

    for i in range(len(X)-2,-1,-1):
        sys.stdout.write(" "+str(X[i]+1))


I found an interesting problem on https://codeforces.com/problemset/problem/350/C:
You've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains n bombs, the i-th bomb is at point with coordinates (x_{i}, y_{i}). We know that no two bombs are at the same point and that no bomb is at point with coordinates (0, 0). Initially, the robot is at point with coordinates (0, 0). Also, let's mark the robot's current position as (x, y). In order to destroy all the bombs, the robot can perform three types of operations:  Operation has format "1 k dir". To perform the operation robot have to move in direction dir k (k ≥ 1) times. There are only 4 directions the robot can move in: "R", "L", "U", "D". During one move the robot can move from the current point to one of following points: (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) (corresponding to directions). It is forbidden to move from point (x, y), if at least one point on the path (besides the destination point) contains a bomb.  Operation has format "2". To perform the operation robot have to pick a bomb at point (x, y) and put it in a special container. Thus, the robot can carry the bomb from any point to any other point. The operation cannot be performed if point (x, y) has no bomb. It is forbidden to pick a bomb if the robot already has a bomb in its container.  Operation has format "3". To perform the operation robot have to take a bomb out of the container and destroy it. You are allowed to perform this operation only if the robot is at point (0, 0). It is forbidden to perform the operation if the container has no bomb.

Help the robot and find the shortest possible sequence of operations he can perform to destroy all bombs on the coordinate plane.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of bombs on the coordinate plane. Next n lines contain two integers each. The i-th line contains numbers (x_{i}, y_{i}) ( - 10^9 ≤ x_{i}, y_{i} ≤ 10^9) — the coordinates of the i-th bomb. It is guaranteed that no two bombs are located at the same point and no bomb...

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

def f(i, j):
    x, y = str(abs(i)), str(abs(j))
    l, r, u, d = ' L', ' R', ' U', ' D'
    if i < 0: l, r = r, l
    if j < 0: u, d = d, u
    if i:
        if j: return ['1 ' + x + r, '1 ' + y + u, '2', '1 ' + x + l, '1 ' + y + d, '3']
        else: return ['1 ' + x + r, '2', '1 ' + x + l, '3']
    else: return ['1 ' + y + u, '2', '1 ' + y + d, '3']

p, n = [], int(input())
t = [(abs(i) + abs(j), i, j) for i, j in tuple(map(int, input().split()) for i in range(n))]
t.sort()
for r, i, j in t:
    p += f(i, j)
print(len(p))
print('\n'.join(p))


I found an interesting problem on https://codeforces.com/problemset/problem/351/A:
Jeff got 2n real numbers a_1, a_2, ..., a_2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows:  choose indexes i and j (i ≠ j) that haven't been chosen yet;  round element a_{i} to the nearest integer that isn't more than a_{i} (assign to a_{i}: ⌊ a_{i} ⌋);  round element a_{j} to the nearest integer that isn't less than a_{j} (assign to a_{j}: ⌈ a_{j} ⌉).

Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 2000). The next line contains 2n real numbers a_1, a_2, ..., a_2n (0 ≤ a_{i} ≤ 10000), given with exactly three digits after the decimal point. The numbers are separated by spaces.

-----Output-----

In a single line print a single real number — the required difference with exactly three digits after the decimal point.

-----Examples-----
Input
3
0.000 0.500 0.750 1.000 2.000 3.000

Output
0.250

Input
3
4469.000 6526.000 4864.000 9356.383 7490.000 995.896

Output
0.279

-----Note-----

In the first test case you need to perform the operations as follows: (i = 1, j = 4), (i = 2, j = 3), (i = 5, j = 6). In this case, the difference will equal |(0 + 0.5 + 0.75 + 1 + 2 + 3) - (0 + 0 + 1 + 1 + 2 + 3)| = 0.25.

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

n = int(input())

l = list(map(float, input().split()))

l = sorted([x - int(x) for x in l if x - int(x) != 0])

o = 2*n - len(l)

su = sum(l)

ans = 0xFFFFFFFFFFFFFFF

for i in range(n + 1):

    if i + o >= n:

        ans = min(ans, abs(i-su))

print("%.3f" % ans)


I found an interesting problem on https://codeforces.com/problemset/problem/352/A:
Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?

Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^3). The next line contains n integers a_1, a_2, ..., a_{n} (a_{i} = 0 or a_{i} = 5). Number a_{i} represents the digit that is written on the i-th card.

-----Output-----

In a single line print the answer to the problem — the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1.

-----Examples-----
Input
4
5 0 5 0

Output
0

Input
11
5 5 5 5 5 5 5 5 0 5 5

Output
5555555550

-----Note-----

In the first test you can make only one number that is a multiple of 90 — 0.

In the second test you can make number 5555555550, it is a multiple of 90.

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/352/B:
One day Jeff got hold of an integer sequence a_1, a_2, ..., a_{n} of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold:

  x occurs in sequence a.  Consider all positions of numbers x in the sequence a (such i, that a_{i} = x). These numbers, sorted in the increasing order, must form an arithmetic progression.

Help Jeff, find all x that meet the problem conditions.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5). The next line contains integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5). The numbers are separated by spaces.

-----Output-----

In the first line print integer t — the number of valid x. On each of the next t lines print two integers x and p_{x}, where x is current suitable value, p_{x} is the common difference between numbers in the progression (if x occurs exactly once in the sequence, p_{x} must equal 0). Print the pairs in the order of increasing x.

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

Output
1
2 0

Input
8
1 2 1 3 1 2 1 5

Output
4
1 2
2 4
3 0
5 0

-----Note-----

In the first test 2 occurs exactly once in the sequence, ergo p_2 = 0.

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

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

N = 100001
d = [-1] * N
p = [-1] * N
for i in range(n):
  if p[a[i]] == -1:
    d[a[i]] = 0
  else:
    if i - p[a[i]] != d[a[i]]:
      if d[a[i]] == 0:
        d[a[i]] = i - p[a[i]]
      else:
        d[a[i]] = -1
  p[a[i]] = i

count = 0
for i in range(N):
  if d[i] != -1:
    count += 1
print(count)
print('\n'.join("{0} {1}".format(i, d[i]) for i in range(N) if d[i] != -1))


I found an interesting problem on https://codeforces.com/problemset/problem/353/A:
Valera has got n domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.

To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100), denoting the number of dominoes Valera has. Next n lines contain two space-separated integers x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ 6). Number x_{i} is initially written on the upper half of the i-th domino, y_{i} is initially written on the lower half.

-----Output-----

Print a single number — the minimum required number of seconds. If Valera can't do the task in any time, print  - 1.

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

Output
0

Input
1
2 3

Output
-1

Input
3
1 4
2 3
4 4

Output
1

-----Note-----

In the first test case the sum of the numbers on the upper halves equals 10 and the sum of the numbers on the lower halves equals 6. Both numbers are even, so Valera doesn't required to do anything.

In the second sample Valera has only one piece of domino. It is written 3 on the one of its halves, therefore one of the sums will always be odd.

In the third case Valera can rotate the first piece, and after that the sum on the upper halves will be equal to 10, and the sum on the lower halves will be equal to 8.

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

n = int(input());
d = [];
for i in range (0, n):
    tmp = input().split();
    (x, y) = (tmp[0], tmp[1]);
    d.append((x, y));

xSum = 0;
ySum = 0;
for (x, y) in d :
    xSum += int(x);
    ySum += int(y);
if xSum % 2 == 0 and ySum % 2 == 0 :
    print((0));
elif (xSum + ySum) % 2 == 1 :
    print((-1));
else :
    result = False;
    for (x, y) in d :
        if (int(x) + int(y)) % 2 == 1 :
            result = True;
    if result == True :
        print((1));
    else :
        print((-1));


I found an interesting problem on https://codeforces.com/problemset/problem/353/B:
Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap.

Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer — the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.

Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100). The second line contains 2·n space-separated integers a_{i} (10 ≤ a_{i} ≤ 99), denoting the numbers on the cubes.

-----Output-----

In the first line print a single number — the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2·n numbers b_{i} (1 ≤ b_{i} ≤ 2). The numbers mean: the i-th cube belongs to the b_{i}-th heap in your division.

If there are multiple optimal ways to split the cubes into the heaps, print any of them.

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

Output
1
2 1

Input
2
13 24 13 45

Output
4
1 2 2 1

-----Note-----

In the first test case Valera can put the first cube in the first heap, and second cube — in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.

In the second test case Valera can obtain numbers 1313, 1345, 2413, 2445. Note, that if he put the first and the third cubes in the...

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

n=int(input())
arr=list(map(int,input().split()))
g=[[] for i in range(100)]
for i in range(2*n):
    g[arr[i]].append(i)
x=0
y=0
curr=1
r=[]
for i in range(10,100):
    if len(g[i])==1:
        arr[g[i][0]]=curr
        if curr==1:
            x+=1
        else:
            y+=1
        curr=3-curr
    if len(g[i])>1:
        arr[g[i][0]]=1
        arr[g[i][1]]=2
        x+=1
        y+=1
        for j in range(2,len(g[i])):
            r.append(g[i][j])
for i in range(len(r)):
    arr[r[i]]=2-(i%2)
print(x*y)
print(*arr)


I found an interesting problem on https://codeforces.com/problemset/problem/353/C:
Valera has array a, consisting of n integers a_0, a_1, ..., a_{n} - 1, and function f(x), taking an integer from 0 to 2^{n} - 1 as its single argument. Value f(x) is calculated by formula $f(x) = \sum_{i = 0}^{n - 1} a_{i} \cdot b i t(i)$, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.

For example, if n = 4 and x = 11 (11 = 2^0 + 2^1 + 2^3), then f(x) = a_0 + a_1 + a_3.

Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≤ x ≤ m.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the number of array elements. The next line contains n space-separated integers a_0, a_1, ..., a_{n} - 1 (0 ≤ a_{i} ≤ 10^4) — elements of array a.

The third line contains a sequence of digits zero and one without spaces s_0s_1... s_{n} - 1 — the binary representation of number m. Number m equals $\sum_{i = 0}^{n - 1} 2^{i} \cdot s_{i}$.

-----Output-----

Print a single integer — the maximum value of function f(x) for all $x \in [ 0 . . m ]$.

-----Examples-----
Input
2
3 8
10

Output
3

Input
5
17 0 10 2 1
11010

Output
27

-----Note-----

In the first test case m = 2^0 = 1, f(0) = 0, f(1) = a_0 = 3.

In the second sample m = 2^0 + 2^1 + 2^3 = 11, the maximum value of function equals f(5) = a_0 + a_2 = 17 + 10 = 27.

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

'''input
2
3 8
10
'''
from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict
from bisect import bisect_left

# main starts
n = int(stdin.readline().strip())
arr = list(map(int, stdin.readline().split()))
barr = list(stdin.readline().strip())
prefix = [0] * n
prefix[0] = arr[0]
for i in range(1, n):
	prefix[i] = prefix[i - 1] + arr[i]
mx = 0
temp = 0
for i in range(n - 1, -1, -1):
	if barr[i] == '1':
		if i >= 1:
			mx = max(mx, temp + prefix[i -1])
		temp += arr[i]
	# print(temp, mx)
mx = max(mx, temp)
print(mx)


I found an interesting problem on https://codeforces.com/problemset/problem/353/D:
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.

Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.

Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.

Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.

-----Input-----

The first line contains a sequence of letters without spaces s_1s_2... s_{n} (1 ≤ n ≤ 10^6), consisting of capital English letters M and F. If letter s_{i} equals M, that means that initially, the line had a boy on the i-th position. If letter s_{i} equals F, then initially the line had a girl on the i-th position.

-----Output-----

Print a single integer — the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.

-----Examples-----
Input
MFM

Output
1

Input
MMFF

Output
3

Input
FFMMM

Output
0

-----Note-----

In the first test case the sequence of changes looks as follows: MFM  →  FMM.

The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.

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

t = input()[:: -1]
i = t.find('F')
if i < 0:
     print(0)
else:
    j = t.find('M', i + 1)
    if j < 0:
        print(0)
    else:
        s, t = 0, t[j:t.rfind('M') + 1]
        for k in t:
            if k == 'M':
                s += 1
            else:
                s = max(s - 1, 0)
        print(s + t.count('F') + j - i - 1)


I found an interesting problem on https://codeforces.com/problemset/problem/355/B:
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.

Public transport is not free. There are 4 types of tickets:   A ticket for one ride on some bus or trolley. It costs c_1 burles;  A ticket for an unlimited number of rides on some bus or on some trolley. It costs c_2 burles;  A ticket for an unlimited number of rides on all buses or all trolleys. It costs c_3 burles;  A ticket for an unlimited number of rides on all buses and trolleys. It costs c_4 burles.

Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.

-----Input-----

The first line contains four integers c_1, c_2, c_3, c_4 (1 ≤ c_1, c_2, c_3, c_4 ≤ 1000) — the costs of the tickets.

The second line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of buses and trolleys Vasya is going to use.

The third line contains n integers a_{i} (0 ≤ a_{i} ≤ 1000) — the number of times Vasya is going to use the bus number i.

The fourth line contains m integers b_{i} (0 ≤ b_{i} ≤ 1000) — the number of times Vasya is going to use the trolley number i.

-----Output-----

Print a single number — the minimum sum of burles Vasya will have to spend on the tickets.

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

Output
12

Input
4 3 2 1
1 3
798
1 2 3

Output
1

Input
100 100 8 100
3 5
7 94 12
100 1 47 0 42

Output
16

-----Note-----

In the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2·1) + 3 + 7 = 12 burles.

In the second sample the profitable strategy is to buy one ticket of the fourth type.

In the third sample the profitable strategy is to buy two tickets of...

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

c1,c2,c3,c4 = list(map(int, input().split()))
n,m = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
suma = sum(min(c1*x, c2) for x in a)
sumb = sum(min(c1*x, c2) for x in b)
print(min(min(suma,c3) + min(sumb, c3), c4))


I found an interesting problem on https://codeforces.com/problemset/problem/356/C:
A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.

The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.

However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number.

After all the swaps each compartment should either have no student left, or have a company of three or four students.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^6) — the number of compartments in the carriage. The second line contains n integers a_1, a_2, ..., a_{n} showing how many students ride in each compartment (0 ≤ a_{i} ≤ 4). It is guaranteed that at least one student is riding in the train.

-----Output-----

If no sequence of swapping seats with other people leads to the desired result, print number "-1" (without the quotes). In another case, print the smallest number of people you need to persuade to swap places.

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

Output
2

Input
3
4 1 1

Output
2

Input
4
0 3 0 4

Output
0

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


I found an interesting problem on https://codeforces.com/problemset/problem/357/A:
At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to m points. We know that c_1 schoolchildren got 1 point, c_2 children got 2 points, ..., c_{m} children got m points. Now you need to set the passing rate k (integer from 1 to m): all schoolchildren who got less than k points go to the beginner group and those who get at strictly least k points go to the intermediate group. We know that if the size of a group is more than y, then the university won't find a room for them. We also know that if a group has less than x schoolchildren, then it is too small and there's no point in having classes with it. So, you need to split all schoolchildren into two groups so that the size of each group was from x to y, inclusive.

Help the university pick the passing rate in a way that meets these requirements.

-----Input-----

The first line contains integer m (2 ≤ m ≤ 100). The second line contains m integers c_1, c_2, ..., c_{m}, separated by single spaces (0 ≤ c_{i} ≤ 100). The third line contains two space-separated integers x and y (1 ≤ x ≤ y ≤ 10000). At least one c_{i} is greater than 0.

-----Output-----

If it is impossible to pick a passing rate in a way that makes the size of each resulting groups at least x and at most y, print 0. Otherwise, print an integer from 1 to m — the passing rate you'd like to suggest. If there are multiple possible answers, print any of them.

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

Output
3

Input
5
0 3 3 4 2
3 10

Output
4

Input
2
2 5
3 6

Output
0

-----Note-----

In the first sample the beginner group has 7 students, the intermediate group has 6 of them.

In the second sample another correct answer is 3.

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

maximum = input()
m_int = list(map(int,input().split()))
size = list(map(int,input().split()))
x = size[0]
y = size[1]

beginner = []
intermediate = []
for i in range(len(m_int)):
    beginner.append(m_int[i])
    if sum(beginner) > y or sum(m_int[i+1:]) < x:
        del beginner[-1]
        break

for j in range(len(beginner),len(m_int)):
    intermediate.append(m_int[j])

if (sum(intermediate) < x or sum(intermediate) > y) or (sum(beginner) < x or sum(beginner) > y):
    passing_rate = 0
else:
    passing_rate = i+1
print(passing_rate)


I found an interesting problem on https://codeforces.com/problemset/problem/357/B:
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:  overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland).

The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance.

You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.

-----Input-----

The first line contains two space-separated integers n (3 ≤ n ≤ 10^5) and m (1 ≤ m ≤ 10^5) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.

-----Output-----

Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.

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

Output
1 2 3 3 2...

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

def __starting_point():
    n, m = map(int, input().split() )
    color = dict()
    for i in range(m):
        d = list(map(int, input().split()))
        temp = dict()
        for j in range(3) :
            if d[j] in color:
                temp[color[d[j]]] =1
        for j in range(3) :
            if  d[j] not in color :
                for k in range(3):
                    if k+1 not in temp:
                        color[d[j]] = k+1
                        temp[k+1] =1
                        break
    for i in range(n) :
        print(color[i+1],end=' ')
    print()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/358/A:
Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.

The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively connect them by semi-circus in a certain order: first connect the first point with the second one, then connect the second point with the third one, then the third one with the fourth one and so on to the n-th point. Two points with coordinates (x_1, 0) and (x_2, 0) should be connected by a semi-circle that passes above the abscissa axis with the diameter that coincides with the segment between points. Seryozha needs to find out if the line on the picture intersects itself. For clarifications, see the picture Seryozha showed to Dima (the left picture has self-intersections, the right picture doesn't have any). [Image]

Seryozha is not a small boy, so the coordinates of the points can be rather large. Help Dima cope with the problem.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^3). The second line contains n distinct integers x_1, x_2, ..., x_{n} ( - 10^6 ≤ x_{i} ≤ 10^6) — the i-th point has coordinates (x_{i}, 0). The points are not necessarily sorted by their x coordinate.

-----Output-----

In the single line print "yes" (without the quotes), if the line has self-intersections. Otherwise, print "no" (without the quotes).

-----Examples-----
Input
4
0 10 5 15

Output
yes

Input
4
0 15 5 10

Output
no

-----Note-----

The first test from the statement is on the picture to the left, the second test is on the picture to the right.

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

n = int( input() )
l = [int(x) for x in input().split()]
found = False

if n<4:
	print("no")
else:
        for i in range(n-2):
                a= min(l[i], l[i+1])
                b= max(l[i], l[i+1])
                for j in range(i+1, n-1, 1):
                        c=min(l[j], l[j+1])
                        d=max(l[j],l[j+1])

                        if c<a and a<d and b>d:
                                found = True
                                break
                        if c<b and b<d and a<c:
                                found = True
                                break
                if found:
                        break
        if found:
                print("yes")
        else:
                print("no")


I found an interesting problem on https://codeforces.com/problemset/problem/358/B:
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.

Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word_1<3word_2<3 ... word_{n}<3.

Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.

Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 10^5.

The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 10^5. A text message can contain only small English letters, digits and signs more and less.

-----Output-----

In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.

-----Examples-----
Input
3
i
love
you
<3i<3love<23you<3

Output
yes

Input
7
i
am
not
main
in
the
family
<3i<>3am<3the<3<main<3in<3the<3><3family<3

Output
no

-----Note-----

Please note that Dima got a good old kick in the pants for the second sample from the statement.

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

def main():
    from sys import stdin
    l = stdin.read().splitlines()
    sms = iter(l[-1])
    l[0] = l[-1] = ''
    good = set("abcdefghijklmnopqrstuvwxyz0123456789<>")
    try:
        for a in "<3".join(l):
            b = next(sms)
            while b != a:
                b = next(sms)
                if b not in good:
                    print('no')
                    return
    except StopIteration:
        print('no')
    else:
        try:
            while True:
                b = next(sms)
                if b not in good:
                    print('no')
                    return
        except StopIteration:
            print('yes')

def __starting_point():
    main()

__starting_point()