I found an interesting problem on https://codeforces.com/problemset/problem/417/B:
During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check.

Each participant is identified by some unique positive integer k, and each sent solution A is characterized by two numbers: x — the number of different solutions that are sent before the first solution identical to A, and k — the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same x.

It is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number x (x > 0) of the participant with number k, then the testing system has a solution with number x - 1 of the same participant stored somewhere before.

During the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so.

-----Input-----

The first line of the input contains an integer n (1 ≤ n ≤ 10^5) — the number of solutions. Each of the following n lines contains two integers separated by space x and k (0 ≤ x ≤ 10^5; 1 ≤ k ≤ 10^5) — the number of previous unique solutions and the identifier of the participant.

-----Output-----

A single line of the output should contain «YES» if the data is in chronological order, and «NO» otherwise.

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

Output
YES

Input
4
0 1
1 2
1 1
0 2

Output
NO

Input
4
0 1
1 1
0 1
0 2

Output
YES

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

sol=int(input())
list1=[]
for i in range(10**5+1):
    list1.append([])
for i in range(sol):
    a,b=input().split()
    b=int(b)
    list1[b].append(a)
i=0
v=True
while i<10**5+1 and v:
    j=0
    z=-1
    while j<len(list1[i]) and v:
        if (int(list1[i][j])-z)==1:
            z=int(list1[i][j])
        elif int(list1[i][j])-z>1:
            v=False
        j+=1
    i+=1
if v==True:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/417/C:
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.

The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.

Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.

-----Input-----

The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).

-----Output-----

In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}). The numbers a_{i} and b_{i} mean, that in the i-th match the team with number a_{i} won against the team with number b_{i}. You can assume, that the teams are numbered from 1 to n.

If a tournir that meets the conditions of the problem does not exist, then print -1.

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

Output
3
1 2
2 3
3 1

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

n, k = [int(i) for i in input().split()]
if k > n // 2 or n < 3 or n == 2*k:
    print(-1)
    return
print(n * k)
arr = list(range(1, n + 1)) + list(range(1, n // 2 + 1))
for i in range(arr[arr.index(max(arr))] ):
    for j in range(1, k + 1):
        print(arr[i], arr[j + i])


I found an interesting problem on https://codeforces.com/problemset/problem/417/E:
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.

Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 10^8.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 100)  — the size of the table.

-----Output-----

Print the table that meets the condition: n lines containing m integers, separated by spaces. If there are multiple possible answers, you are allowed to print anyone. It is guaranteed that there exists at least one correct answer.

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

Output
1
Input
1 2

Output
3 4

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

"""
Codeforces Round 241 Div 1 Problem E

Author  : chaotic_iak
Language: Python 3.3.4
"""

class InputHandlerObject(object):
    inputs = []

    def getInput(self, n = 0):
        res = ""
        inputs = self.inputs
        if not inputs: inputs.extend(input().split(" "))
        if n == 0:
            res = inputs[:]
            inputs[:] = []
        while n > len(inputs):
            inputs.extend(input().split(" "))
        if n > 0:
            res = inputs[:n]
            inputs[:n] = []
        return res
InputHandler = InputHandlerObject()
g = InputHandler.getInput

############################## SOLUTION ##############################
n,m = [int(x) for x in g()]

def sqr(n):
    if n == 1:
        return [1]
    if n == 2:
        return [4,3]
    if n % 2:
        return [(n+1)//2, 2] + [1] * (n-2)
    return [(n-2)//2] + [1] * (n-1)

a = sqr(n)
b = sqr(m)
for i in range(n):
    res = [str(a[i]*x) for x in b]
    print(" ".join(res))


I found an interesting problem on https://codeforces.com/problemset/problem/420/A:
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?

The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.

There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.

-----Input-----

The first line contains a non-empty name that needs to be checked. The name contains at most 10^5 large English letters. The name will be written with the next sans serif font: $\text{ABCDEFGHI JKLMNOPQRSTUVWXYZ}$

-----Output-----

Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes).

-----Examples-----
Input
AHA

Output
YES

Input
Z

Output
NO

Input
XO

Output
NO

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

s=input()
z=['A','H','M','T','U','V','W','O','I','X','Y']

f1=True
if (s[::-1]==s):
    f1=True
else:
    f1=False

sa=set()
v=True
for i in range (0,len(s)):
    sa.add(s[i])

sals=list(sa)
for i in range (0,len(sals)):
    if (sals[i] in z):
        v=True
    else:
        v=False
        break

if (f1==True and v==True):
    print ("YES")
else:
    print ("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/420/B:
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.

One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.

You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).

-----Input-----

The first line contains integers n and m (1 ≤ n, m ≤ 10^5) — the number of team participants and the number of messages. Each of the next m lines contains a message in the format:  '+ id': the record means that the person with number id (1 ≤ id ≤ n) has logged on to the meeting.  '- id': the record means that the person with number id (1 ≤ id ≤ n) has logged off from the meeting.

Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.

-----Output-----

In the first line print integer k (0 ≤ k ≤ n) — how many people can be leaders. In the next line, print k integers in the increasing order — the numbers of the people who can be leaders.

If the data is such that no member of the team can be a leader,...

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

#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
'''
Created on 13/09/2018

@author: ernesto
'''

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

posibles_jefes = set(range(1, n + 1))
anteriores = set()
posteriores = set()
continuos = [True] * (n + 1)
mencionados = set()
posibles_jefes_mencionados = set()
ultimo_en_salir = [True] * (n + 1)
ultima_salida_inesperada = None

ops = []

if(m > 1):
    for _ in range(0, m):
        s, n_s = [x for x in input().strip().split(" ")]
        n = int(n_s)
        ops.append((s, n))
    for i in range(0, m):
        op, num = ops[i]
        cont = False
        if op == '+':
            cont = not i or (ops[i - 1][0] == '-' and ops[i - 1][1] == num)
            posteriores.add(num)
        if op == '-':
            cont = i == m - 1 or (ops[i + 1][0] == '+' and ops[i + 1][1] == num)
            if num not in mencionados:
                anteriores.add(num)
                ultima_salida_inesperada = num
            posteriores.discard(num)
            ultimo_en_salir[num] &= not posteriores
        continuos[num] &= cont
        mencionados.add(num)
#    print("anteriores {} posteriores {} continuos {} ops {}".format(anteriores, posteriores, continuos, ops))
    if not anteriores and not posteriores:
        assert ultima_salida_inesperada is None
        if ops[0][0] == '+' and ops[-1][0] == '-' and ops[0][1] == ops[-1][1] and continuos[ops[0][1]] and ultimo_en_salir[ops[0][1]]:
            posibles_jefes_mencionados.add(ops[0][1])
    else:
        if not posteriores:
            assert ultima_salida_inesperada is not None
            posibles_jefes_filtrados = list([x for x in anteriores if continuos[x] and ultimo_en_salir[x] and ultima_salida_inesperada == x])
            assert len(posibles_jefes_filtrados) <= 1
            if(posibles_jefes_filtrados):
                assert posibles_jefes_filtrados[0] == ops[-1][1]
                posibles_jefes_mencionados.add(ops[-1][1])
        else:
            if not anteriores:
                assert...


I found an interesting problem on https://codeforces.com/problemset/problem/420/C:
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!'

The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least p of n coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects?

Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting.

-----Input-----

The first line contains integers n and p (3 ≤ n ≤ 3·10^5; 0 ≤ p ≤ n) — the number of coders in the F company and the minimum number of agreed people.

Each of the next n lines contains two integers x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ n) — the numbers of coders named by the i-th coder. It is guaranteed that x_{i} ≠ i,  y_{i} ≠ i,  x_{i} ≠ y_{i}.

-----Output-----

Print a single integer –– the number of possible two-suspect sets. Note that the order of the suspects doesn't matter, that is, sets (1, 2) и (2, 1) are considered identical.

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

Output
6

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

Output
1

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

from collections import defaultdict
from bisect import bisect_left as lower
import sys
input = sys.stdin.readline
def put():
    return list(map(int, input().split()))

try:
    n,m = put()
    cnt, mp, ans = [0]*n, defaultdict(), [0]*n
    for _ in range(n):
        x,y = put()
        x,y = x-1,y-1
        key = (min(x,y), max(x,y))
        if key in mp:
            mp[key]+=1
        else:
            mp[key]=1
        cnt[x]+=1
        cnt[y]+=1

except:
    print('lol')

for (x,y),val in list(mp.items()):
    if cnt[x]+cnt[y]>= m and cnt[x]+cnt[y]-val<m:
        ans[x]-=1
        ans[y]-=1

scnt = cnt.copy()
scnt.sort()
for i in range(n):
    ans[i]+= n-lower(scnt, m-cnt[i])
    if 2*cnt[i]>=m:
        ans[i]-=1

print(sum(ans)//2)


I found an interesting problem on https://codeforces.com/problemset/problem/421/A:
Pasha has two hamsters: Arthur and Alexander. Pasha put n apples in front of them. Pasha knows which apples Arthur likes. Similarly, Pasha knows which apples Alexander likes. Pasha doesn't want any conflict between the hamsters (as they may like the same apple), so he decided to distribute the apples between the hamsters on his own. He is going to give some apples to Arthur and some apples to Alexander. It doesn't matter how many apples each hamster gets but it is important that each hamster gets only the apples he likes. It is possible that somebody doesn't get any apples.

Help Pasha distribute all the apples between the hamsters. Note that Pasha wants to distribute all the apples, not just some of them.

-----Input-----

The first line contains integers n, a, b (1 ≤ n ≤ 100; 1 ≤ a, b ≤ n) — the number of apples Pasha has, the number of apples Arthur likes and the number of apples Alexander likes, correspondingly.

The next line contains a distinct integers — the numbers of the apples Arthur likes. The next line contains b distinct integers — the numbers of the apples Alexander likes.

Assume that the apples are numbered from 1 to n. The input is such that the answer exists.

-----Output-----

Print n characters, each of them equals either 1 or 2. If the i-h character equals 1, then the i-th apple should be given to Arthur, otherwise it should be given to Alexander. If there are multiple correct answers, you are allowed to print any of them.

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

Output
1 1 2 2

Input
5 5 2
3 4 1 2 5
2 3

Output
1 1 1 1 1

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

R = lambda: list(map(int, input().split()))
G = lambda: map(int, input().split())
n, a, b = G()
A = R()
B = R()
result = [-1 for i in range(n + 1)]
for i in range(a):
    result[A[i]] = 1
for i in range(1, n + 1):
    if result[i] == -1:
        result[i] = 2
for i in range(1, n + 1):
    print(result[i], end = ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/424/A:
Pasha has many hamsters and he makes them work out. Today, n hamsters (n is even) came to work out. The hamsters lined up and each hamster either sat down or stood up.

For another exercise, Pasha needs exactly $\frac{n}{2}$ hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster ether sit down or stand up. How many minutes will he need to get what he wants if he acts optimally well?

-----Input-----

The first line contains integer n (2 ≤ n ≤ 200; n is even). The next line contains n characters without spaces. These characters describe the hamsters' position: the i-th character equals 'X', if the i-th hamster in the row is standing, and 'x', if he is sitting.

-----Output-----

In the first line, print a single integer — the minimum required number of minutes. In the second line, print a string that describes the hamsters' position after Pasha makes the required changes. If there are multiple optimal positions, print any of them.

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

Output
1
XxXx

Input
2
XX

Output
1
xX

Input
6
xXXxXx

Output
0
xXXxXx

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

#! /usr/bin/env python

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

cnt = s.count('x')
ans = cnt - n // 2;
if ans > 0:
    tmp = ans;
    for i, x in enumerate(s):
        if x == 'x':
            s[i] = 'X'
            tmp -= 1
            if tmp == 0:
                break
elif ans < 0:
    ans = -ans;
    tmp = ans;
    for i, x in enumerate(s):
        if x == 'X':
            s[i] = 'x'
            tmp -= 1
            if tmp == 0:
                break
print(ans)
print(''.join(s))


I found an interesting problem on https://codeforces.com/problemset/problem/424/B:
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.

The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (x_{i}, y_{i}) with the population of k_{i} people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.

Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.

-----Input-----

The first line of the input contains two integers n and s (1 ≤ n ≤ 10^3; 1 ≤ s < 10^6) — the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers — the x_{i} and y_{i} coordinate values of the i-th location and the number k_{i} of people in it (1 ≤ k_{i} < 10^6). Each coordinate is an integer and doesn't exceed 10^4 in its absolute value.

It is guaranteed that no two locations are at the same point and no location is at point (0; 0).

-----Output-----

In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number — the minimum radius of the circle that the city needs to expand to in order to become a megacity.

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

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

Output
2.8284271

Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1

Output
1.4142136

Input
2 1
1 1 999997
2 2 1

Output
-1

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

import math
import sys

n,p = list(map(int,input().split()))
cities=[]
for i in range(n):
    x,y,pi = list(map(int,input().split()))
    cities.append(((x,y),pi))

sorted_cities = sorted(cities,key=lambda data: math.sqrt(data[0][0]**2+data[0][1]**2))
for i in range(n):
    if p < 1000000:
        p+=sorted_cities[i][1]
        if p>= 1000000:
            print(math.sqrt(sorted_cities[i][0][0]**2+sorted_cities[i][0][1]**2))
            return
print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/424/C:
People in the Tomskaya region like magic formulas very much. You can see some of them below.

Imagine you are given a sequence of positive integer numbers p_1, p_2, ..., p_{n}. Lets write down some magic formulas:$q_{i} = p_{i} \oplus(i \operatorname{mod} 1) \oplus(i \operatorname{mod} 2) \oplus \cdots \oplus(i \operatorname{mod} n)$$Q = q_{1} \oplus q_{2} \oplus \ldots \oplus q_{n}$

Here, "mod" means the operation of taking the residue after dividing.

The expression $x \oplus y$ means applying the bitwise xor (excluding "OR") operation to integers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal — by "xor".

People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence p, calculate the value of Q.

-----Input-----

The first line of the input contains the only integer n (1 ≤ n ≤ 10^6). The next line contains n integers: p_1, p_2, ..., p_{n} (0 ≤ p_{i} ≤ 2·10^9).

-----Output-----

The only line of output should contain a single integer — the value of Q.

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

Output
3

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

from functools import reduce
from itertools import accumulate
from operator import xor
n = int(input())
res = reduce(xor, map(int, input().split()))
pre = [*accumulate(range(n + 1), xor)]
for i in range(1, n + 1):
    res ^= pre[n % i]
    if (n // i) & 1:
        res ^= pre[i - 1]
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/425/A:
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation:

$f(a, l, r) = \sum_{i = l}^{r} a [ i ] ; m(a) = \operatorname{max}_{1 \leq l \leq r \leq n} f(a, l, r)$

A swap operation is the following sequence of actions:

  choose two indexes i, j (i ≠ j);  perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp.

What maximum value of function m(a) can Sereja get if he is allowed to perform at most k swap operations?

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 200; 1 ≤ k ≤ 10). The next line contains n integers a[1], a[2], ..., a[n] ( - 1000 ≤ a[i] ≤ 1000).

-----Output-----

In a single line print the maximum value of m(a) that Sereja can get if he is allowed to perform at most k swap operations.

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

Output
32

Input
5 10
-1 -1 -1 -1 -1

Output
-1

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

read_line = lambda: [int(i) for i in input().split()]
n, k = read_line()
x = read_line()
print(max(sum(sorted(x[l:r] + sorted(x[:l] + x[r:])[-k:])[l-r:]) for l in range(n) for r in range(l + 1, n + 1)))


I found an interesting problem on https://codeforces.com/problemset/problem/425/B:
Sereja has an n × m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size h × w, then the component must contain exactly hw cells.

A connected component of the same values is a set of cells of the table that meet the following conditions:  every two cells of the set have the same value;  the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table);  it is impossible to add any cell to the set unless we violate the two previous conditions.

Can Sereja change the values of at most k cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case?

-----Input-----

The first line contains integers n, m and k (1 ≤ n, m ≤ 100; 1 ≤ k ≤ 10). Next n lines describe the table a: the i-th of them contains m integers a_{i}1, a_{i}2, ..., a_{im} (0 ≤ a_{i}, j ≤ 1) — the values in the cells of the i-th row.

-----Output-----

Print -1, if it is impossible to meet the requirement. Otherwise, print the minimum number of cells which should be changed.

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

Output
1

Input
3 4 1
1 0 0 0
0 1 1 1
1 1 1 0

Output
-1

Input
3 4 1
1 0 0 1
0 1 1 0
1 0 0 1

Output
0

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

read_line = lambda: [int(i) for i in input().split()]

n, m, k = read_line()
a = [read_line() for i in range(n)]
if n < m:
    n, m, a = m, n, list(zip(*a))

xs = []
for y in a:
    x = 0
    for b in y:
        x = 2 * x + b
    xs.append(x)

def work(y):
    tot = 0
    for x in xs:
        c = bin(x ^ y).count('1')
        tot += min(c, m - c)
    return tot

ans = min(list(map(work, xs if m > k else list(range(1<<m)))))

print(ans if ans <= k else -1)


I found an interesting problem on https://codeforces.com/problemset/problem/426/A:
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and n water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that this player lost.

As soon as Sereja's friends heard of the game, they wanted to play it. Sereja, on the other hand, wanted to find out whether his friends can play the game in such a way that there are no losers. You are given the volumes of all mugs and the cup. Also, you know that Sereja has (n - 1) friends. Determine if Sereja's friends can play the game so that nobody loses.

-----Input-----

The first line contains integers n and s (2 ≤ n ≤ 100; 1 ≤ s ≤ 1000) — the number of mugs and the volume of the cup. The next line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10). Number a_{i} means the volume of the i-th mug.

-----Output-----

In a single line, print "YES" (without the quotes) if his friends can play in the described manner, and "NO" (without the quotes) otherwise.

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

Output
YES

Input
3 4
3 1 3

Output
YES

Input
3 4
4 4 4

Output
NO

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

n,m = list(map(int,input().split()))
a=list(map(int,input().split()))
if sum(a) - max(a) <= m :
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/426/B:
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties:

  the upper half of matrix c (rows with numbers from 1 to x) exactly matches b;  the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1).

Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?

-----Input-----

The first line contains two integers, n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains m integers — the elements of matrix a. The i-th line contains integers a_{i}1, a_{i}2, ..., a_{im} (0 ≤ a_{ij} ≤ 1) — the i-th row of the matrix a.

-----Output-----

In the single line, print the answer to the problem — the minimum number of rows of matrix b.

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

Output
2

Input
3 3
0 0 0
0 0 0
0 0 0

Output
3

Input
8 1
0
1
1
0
0
1
1
0

Output
2

-----Note-----

In the first test sample the answer is a 2 × 3 matrix b:

001

110

If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:

001

110

110

001

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

n, m = tuple(map(int, str.split(input())))
a = list([input() for _ in range(n)])
while n % 2 == 0 and all([a[i] == a[-i - 1] for i in range(n // 2)]):

    n //= 2
    a = a[:n]

print(n)


I found an interesting problem on https://codeforces.com/problemset/problem/427/A:
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.

Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.

If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.

Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.

-----Input-----

The first line of input will contain an integer n (1 ≤ n ≤ 10^5), the number of events. The next line will contain n space-separated integers.

If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.

-----Output-----

Print a single integer, the number of crimes which will go untreated.

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

Output
2

Input
8
1 -1 1 -1 -1 1 1 1

Output
1

Input
11
-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1

Output
8

-----Note-----

Lets consider the second example:  Firstly one person is hired.  Then crime appears, the last hired person will investigate this crime.  One more person is hired.  One more crime appears, the last hired person will investigate this crime.  Crime appears. There is no free policeman at the time, so this crime will go untreated.  One more person is hired.  One more person is hired.  One more person is hired.

The answer is one, as one crime (on step 5) will go untreated.

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

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

police = 0
occur = 0

for i in range(n):
    police += events[i]
    if police < 0 :
        occur += 1
        police = 0
print(occur)


I found an interesting problem on https://codeforces.com/problemset/problem/427/B:
The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.

For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.

Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,

  The chosen c prisoners has to form a contiguous segment of prisoners.  Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer.

Find the number of ways you can choose the c prisoners.

-----Input-----

The first line of input will contain three space separated integers n (1 ≤ n ≤ 2·10^5), t (0 ≤ t ≤ 10^9) and c (1 ≤ c ≤ n). The next line will contain n space separated integers, the i^{th} integer is the severity i^{th} prisoner's crime. The value of crime severities will be non-negative and will not exceed 10^9.

-----Output-----

Print a single integer — the number of ways you can choose the c prisoners.

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

Output
2

Input
1 1 1
2

Output
0

Input
11 4 2
2 2 0 7 3 2 2 4 9 1 4

Output
6

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

n, t, c = [int(i) for i in input().split()]
h = [int(i) for i in input().split()]
res = 0
cnt = 0
for i in h:
    if i > t:
        cnt = 0
    else:
        cnt += 1
    if cnt >= c:
        res += 1
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/427/C:
Your city has n junctions. There are m one-way roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions.

To ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction i can protect junction j if either i = j or the police patrol car can go to j from i and then come back to i.

Building checkposts costs some money. As some areas of the city are more expensive than others, building checkpost at some junctions might cost more money than other junctions.

You have to determine the minimum possible money needed to ensure the security of all the junctions. Also you have to find the number of ways to ensure the security in minimum price and in addition in minimum number of checkposts. Two ways are different if any of the junctions contains a checkpost in one of them and do not contain in the other.

-----Input-----

In the first line, you will be given an integer n, number of junctions (1 ≤ n ≤ 10^5). In the next line, n space-separated integers will be given. The i^{th} integer is the cost of building checkpost at the i^{th} junction (costs will be non-negative and will not exceed 10^9).

The next line will contain an integer m (0 ≤ m ≤ 3·10^5). And each of the next m lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n; u ≠ v). A pair u_{i}, v_{i} means, that there is a one-way road which goes from u_{i} to v_{i}. There will not be more than one road between two nodes in the same direction.

-----Output-----

Print two integers separated by spaces. The first one is the minimum possible money needed to ensure the security of all the junctions. And the second one is the number of ways you can ensure the security modulo 1000000007 (10^9 + 7).

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

Output
3 1

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

Output
8 2

Input
10
1 3 2 2 1 3 1 4 10 10
12
1 2
2 3
3 1
3 4
4 5
5 6
5 7
6 4
7 3
8 9
9 10
10 9

Output
15 6

Input
2
7 91
2
1 2
2 1

Output
7 1

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

mod = 10**9+7
import sys
input = sys.stdin.readline
from collections import deque

class Graph(object):
	"""docstring for Graph"""
	def __init__(self,n,d): # Number of nodes and d is True if directed
		self.n = n
		self.graph = [[] for i in range(n)]
		self.parent = [-1 for i in range(n)]
		self.directed = d

	def addEdge(self,x,y):
		self.graph[x].append(y)
		if not self.directed:
			self.graph[y].append(x)

	def bfs(self, root): # NORMAL BFS
		queue = [root]
		queue = deque(queue)
		vis = [0]*self.n
		while len(queue)!=0:
			element = queue.popleft()
			vis[element] = 1
			for i in self.graph[element]:
				if vis[i]==0:
					queue.append(i)
					self.parent[i] = element
					vis[i] = 1

	def dfs(self, root, vis): # Iterative DFS
		stack=[root]
		stack2=[]
		while len(stack)!=0: # INITIAL TRAVERSAL
			element = stack.pop()
			if vis[element]:
				continue
			vis[element] = 1
			stack2.append(element)
			for i in self.graph[element]:
				if vis[i]==0:
					self.parent[i] = element
					stack.append(i)
		return stack2[::-1],vis

	def dfs2(self, root, vis): # Iterative DFS
		stack=[root]
		stack2=[]
		cost = 10**18
		count = 0
		while len(stack)!=0: # INITIAL TRAVERSAL
			element = stack.pop()
			if vis[element]:
				continue

			if costs[element]<cost:
				cost = costs[element]
				count = 1
			elif costs[element]==cost:
				count += 1
			vis[element] = 1
			stack2.append(element)
			for i in self.graph[element]:
				if vis[i]==0:
					self.parent[i] = element
					stack.append(i)
		return cost, count, vis

	def count_scc(self, root):
		vis = [0]*self.n
		stack = []
		for i in range(self.n):
			if not vis[i]:
				a, vis = self.dfs(i, vis)
				stack.extend(a)

		g = [[] for i in range(self.n)]
		for i in range(self.n):
			for j in self.graph[i]:
				g[j].append(i)
		self.graph = g

		vis = [0]*self.n
		a1 = 0
		a2 = 1
		# print (stack)
		# print (self.graph)
		count = 0
		while len(stack)!=0:
			e = stack.pop()
			if not vis[e]:
				a,b,vis = self.dfs2(e, vis)
				a1 += a
				count += 1
				a2 =...


I found an interesting problem on https://codeforces.com/problemset/problem/429/C:
Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food.

Iahub asks Iahubina: can you build a rooted tree, such that

  each internal node (a node with at least one son) has at least two sons;  node i has c_{i} nodes in its subtree?

Iahubina has to guess the tree. Being a smart girl, she realized that it's possible no tree can follow Iahub's restrictions. In this way, Iahub will eat all the food. You need to help Iahubina: determine if there's at least one tree following Iahub's restrictions. The required tree must contain n nodes.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 24). Next line contains n positive integers: the i-th number represents c_{i} (1 ≤ c_{i} ≤ n).

-----Output-----

Output on the first line "YES" (without quotes) if there exist at least one tree following Iahub's restrictions, otherwise output "NO" (without quotes).

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

Output
YES
Input
5
1 1 5 2 1

Output
NO

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

def DFS(x):
    for i in range(x):
        if(Seen[i][x]):
            continue
        if(Rem[i]>=C[x]):
            if(Rem[i]==C[x] and len(Children[i])==0):
                continue
            Rem[i]-=C[x]
            Parent[x]=i
            Children[i].append(x)
            return True
    for i in range(x):
        if(Seen[i][x]):
            continue
        Y=[]
        for j in range(len(Children[i])):
            child=Children[i][j]
            Parent[child]=-1
            Rem[i]+=C[child]
            Seen[i][child]=True
            Seen[child][i]=True
            if(DFS(child)):
                Seen[i][child]=False
                Seen[child][i]=False
                continue
            Seen[i][child]=False
            Seen[child][i]=False
            Parent[child]=i
            Rem[i]-=C[child]
            Y.append(child)
        Children[i]=list(Y)
        if(Rem[i]>=C[x]):
            if(Rem[i]==C[x] and len(Children[i])==0):
                continue
            Rem[i]-=C[x]
            Children[i].append(x)
            Parent[x]=i
            return True
    return False

n=int(input())

C=list(map(int,input().split()))
Rem=[-1]*n
Parent=[-1]*n
Children=[]
Seen=[]
for i in range(n):
    Seen.append([False]*n)
C.sort(reverse=True)

if(C[0]!=n or C.count(2)>0):
    print("NO")

else:
    for i in range(n):
        Rem[i]=C[i]-1
        Children.append([])
    Parent[0]=0
    Ans="YES"
    for i in range(1,n):
        if(DFS(i)==False):
            Ans="NO"
            break
    for i in range(n):
        if(Rem[i]!=0 and C[i]!=1):
            Ans="NO"
            break
    print(Ans)


I found an interesting problem on https://codeforces.com/problemset/problem/429/D:
Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be the one qualified, he tells Iahub the following task.

You're given an (1-based) array a with n elements. Let's define function f(i, j) (1 ≤ i, j ≤ n) as (i - j)^2 + g(i, j)^2. Function g is calculated by the following pseudo-code:

int g(int i, int j) {

    int sum = 0;

    for (int k = min(i, j) + 1; k <= max(i, j); k = k + 1)

        sum = sum + a[k];

    return sum;

}

Find a value min_{i} ≠ j  f(i, j).

Probably by now Iahub already figured out the solution to this problem. Can you?

-----Input-----

The first line of input contains a single integer n (2 ≤ n ≤ 100000). Next line contains n integers a[1], a[2], ..., a[n] ( - 10^4 ≤ a[i] ≤ 10^4).

-----Output-----

Output a single integer — the value of min_{i} ≠ j  f(i, j).

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

Output
1

Input
2
1 -1

Output
2

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

import sys
max_Int = int(1e9)

class splitFeature:
    def __init__(self, position, value):
        self.position = position
        self.value = value

def bruteForce(features, left, right):
    min_distance = max_Int
    for i in range(left, right):
        for j in range(i+1, right):
            min_distance = min(min_distance,
                               (features[i].position - features[j].position)**2 + (features[i].value - features[j].value)**2)
    return min_distance

def enhanceData(features, left, right, mid, min_distance):
    selected_population = []
    for i in range(left, right):
        if (features[i].position - features[mid].position) ** 2 <= min_distance:
            selected_population.append(features[i])
    selected_population.sort(key = lambda x: x.value)
    l = len(selected_population)
    result = max_Int
    for i in range(l):
        for j in range(i+1, l):
            if (selected_population[i].value - selected_population[j].value) ** 2 >= min_distance:
                break
            distance = (selected_population[i].position - selected_population[j].position)**2 + (selected_population[i].value - selected_population[j].value)**2
            result = min(result, distance)
    return result

def analyzeData(features, left, right):
    if right - left <= 3:
        return bruteForce(features, left, right)
    mid = (left + right) // 2
    min_distance = min(analyzeData(features, left, mid),
                       analyzeData(features, mid+1, right))
    return min(min_distance,
               enhanceData(features, left, right, mid, min_distance))

def main():
    n = int(input())
    A = list(map(int, input().split()))
    features = []
    for i in range(n):
        if (i > 0):
            A[i] += A[i-1]
        features.append(splitFeature(i , A[i]))
    print(analyzeData(features, 0, n))

main()


I found an interesting problem on https://codeforces.com/problemset/problem/430/B:
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game?

There are n balls put in a row. Each ball is colored in one of k colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color x. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color.

For example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls.

Iahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy.

-----Input-----

The first line of input contains three integers: n (1 ≤ n ≤ 100), k (1 ≤ k ≤ 100) and x (1 ≤ x ≤ k). The next line contains n space-separated integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ k). Number c_{i} means that the i-th ball in the row has color c_{i}.

It is guaranteed that the initial row of balls will never contain three or more contiguous balls of the same color.

-----Output-----

Print a single integer — the maximum number of balls Iahub can destroy.

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

Output
6

Input
1 1 1
1

Output
0

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

import sys

f = sys.stdin
#f = open('H:\\Portable Python 3.2.5.1\\tests\\test_445B1.txt')
n, k, x, = list(map(int, f.readline().split()))

r = [int(it) for it in  f.readline().split()]

#print(n, k, x)

#print(r)

def collaps(r,k):
    n = len(r)
    max_collaps = 0
    if n<k:
        return 0
    elif n==1 and k==1:
        return 1
    elif n==1 and k>1:
        return 0
    else:
        i = 1
        g = 1
        col = r[0]
        while (i<n):
            if r[i]==col:
                g += 1
            else:
                if g>=k:
                    max_collaps += g
                    col = r[i]
                    for kk in range(g):
                        # print(i-1, r)
                        del r[i-1]
                        i -= 1
                    n = len(r)
                    if n>1:
                        g = 1
                        i = 1
                        col = r[0]
                        continue
                    else: break
                else:
                    g = 1
                    col = r[i]
            #print(i, r, r[i],col, g, max_collaps)
            i += 1

        if g>=k:
            max_collaps += g
        #print(6575, i, g, max_collaps)
        return max_collaps

r1 = r[:]

nn = 0 # Новый ряд
res = 0
c1 = 0
for m in range(len(r)) :
    if (nn == 0) and (r[m]==x):
        r1 = r[:]
        r1.insert(m,x)
        c1 = collaps(r1,3)-1
        #print(m, c1)
        if  c1>res:     res = c1
        nn = 1
    elif (r[m]!=x):
        nn = 0
    # print(m, nn, c1, res)

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/431/A:
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.

In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly a_{i} calories on touching the i-th strip.

You've got a string s, describing the process of the game and numbers a_1, a_2, a_3, a_4. Calculate how many calories Jury needs to destroy all the squares?

-----Input-----

The first line contains four space-separated integers a_1, a_2, a_3, a_4 (0 ≤ a_1, a_2, a_3, a_4 ≤ 10^4).

The second line contains string s (1 ≤ |s| ≤ 10^5), where the і-th character of the string equals "1", if on the i-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip.

-----Output-----

Print a single integer — the total number of calories that Jury wastes.

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

Output
13

Input
1 5 3 2
11221

Output
13

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

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


I found an interesting problem on https://codeforces.com/problemset/problem/431/B:
Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks.

There is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory shower door. As soon as the shower opens, the first person from the line enters the shower. After a while the first person leaves the shower and the next person enters the shower. The process continues until everybody in the line has a shower.

Having a shower takes some time, so the students in the line talk as they wait. At each moment of time the students talk in pairs: the (2i - 1)-th man in the line (for the current moment) talks with the (2i)-th one.

Let's look at this process in more detail. Let's number the people from 1 to 5. Let's assume that the line initially looks as 23154 (person number 2 stands at the beginning of the line). Then, before the shower opens, 2 talks with 3, 1 talks with 5, 4 doesn't talk with anyone. Then 2 enters the shower. While 2 has a shower, 3 and 1 talk, 5 and 4 talk too. Then, 3 enters the shower. While 3 has a shower, 1 and 5 talk, 4 doesn't talk to anyone. Then 1 enters the shower and while he is there, 5 and 4 talk. Then 5 enters the shower, and then 4 enters the shower.

We know that if students i and j talk, then the i-th student's happiness increases by g_{ij} and the j-th student's happiness increases by g_{ji}. Your task is to find such initial order of students in the line that the total happiness of all students will be maximum in the end. Please note that some pair of students may have a talk several times. In the example above students 1 and 5 talk while they wait for the shower to open and while 3 has a shower.

-----Input-----

The input consists of five lines, each line contains five space-separated integers: the j-th number in the i-th line shows g_{ij} (0 ≤ g_{ij} ≤ 10^5). It is guaranteed that g_{ii} = 0 for all i.

Assume that the...

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

def str(l, l1, l2, l3, l4):
    s = [l, l1, l2, l3, l4]
    return s
def count(u):
    sum = 0
    lim = 0
    while lim != 5:
        for i in range(0, len(u) - 1, 2):
            sum += a[u[i]-1][u[i+1]-1]
            sum += a[u[i+1]-1][u[i]-1]
        u = u[1:]
        lim += 1
    return sum
a = []
u = [1, 2, 3, 4 ,5]
for i in range(5):
    a.append(list(map(int, input().split())))
b = []
c = []
o = set()
for i in range(1, 6):
    for j in range(1, 6):
        for k in range(1, 6):
            for l in range(1, 6):
                for p in range(1, 6):
                    o.add(i)
                    o.add(j)
                    o.add(k)
                    o.add(l)
                    o.add(p)
                    if len(o) == 5:
                        b.append(str(i, j, k, l, p))
                    o = set()
for i in range(len(b)):
    c.append(count(b[i]))
c = sorted(c)
print(c[-1])


I found an interesting problem on https://codeforces.com/problemset/problem/431/C:
Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree.

A k-tree is an infinite rooted tree where:

  each vertex has exactly k children;  each edge has some weight;  if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k.

The picture below shows a part of a 3-tree.

 [Image]

    As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?".

Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (10^9 + 7).

-----Input-----

A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k).

-----Output-----

Print a single integer — the answer to the problem modulo 1000000007 (10^9 + 7).

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

Output
3

Input
3 3 3

Output
1

Input
4 3 2

Output
6

Input
4 5 2

Output
7

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

b = [False] * 101
x = [0] * 101
def count(w, k1):
    if w == 0:
        return 1
    elif w < 0:
        return 0

    ans = 0
    for i in range(1, k1+1):
        if w-i < 0:
            break
        if b[w - i]:
            ans = ans + x[w - i];
        else:
            x[w-i] =  count(w - i, k1)
            ans = ans + x[w - i];
            b[w - i] = True;
    b[w] = True;
    x[w] = ans;
    return ans;

n, k, d = map(int,input().split())
x[0] = 1;
ans = count(n, k);
b = [False] * 101
x = [0] * 101
x[0] = 1;
ans = ans - count(n, min(k, d-1));
print(ans % 1000000007)


I found an interesting problem on https://codeforces.com/problemset/problem/431/D:
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2·n there are exactly m numbers which binary representation contains exactly k digits one".

The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 10^18.

-----Input-----

The first line contains two space-separated integers, m and k (0 ≤ m ≤ 10^18; 1 ≤ k ≤ 64).

-----Output-----

Print the required number n (1 ≤ n ≤ 10^18). If there are multiple answers, print any of them.

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

Output
1

Input
3 2

Output
5

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

import math

m, k = list(map(int, input().strip(' ').split(' ')))

def solve(x):
    ans = 0
    tot = 0
    for i in reversed(list(range(int(math.log2(x)+1)))):
        if x & (1 << i):
            ans += math.comb(i, k-tot)
            tot += 1
            if tot > k:
                return ans
    return ans

def judge(x):
    return solve(x*2)-solve(x) >= m

l, r = 1, 2
while not judge(r):
    l, r = r, r*2
ans = -1
while l <= r:
    mid = (l+r) >> 1
    if judge(mid):
        ans, r = mid, mid-1
    else:
        l = mid+1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/432/A:
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.

The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?

-----Input-----

The first line contains two integers, n and k (1 ≤ n ≤ 2000; 1 ≤ k ≤ 5). The next line contains n integers: y_1, y_2, ..., y_{n} (0 ≤ y_{i} ≤ 5), where y_{i} shows the number of times the i-th person participated in the ACM ICPC world championship.

-----Output-----

Print a single number — the answer to the problem.

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

Output
1

Input
6 4
0 1 2 3 4 5

Output
0

Input
6 5
0 0 0 0 0 0

Output
2

-----Note-----

In the first sample only one team could be made: the first, the fourth and the fifth participants.

In the second sample no teams could be created.

In the third sample two teams could be created. Any partition into two teams fits.

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

def read():
    return map(int, input().split())

n, k = read()
a = list(read())
a.sort()
i = 0
ans = 0
while i + 2 < len(a):
    if a[i]+k<=5 and a[i+1]+k<=5 and a[i+2]+k<=5:
        ans += 1
        i+=3
    else:
        i+=1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/432/B:
Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color x_{i} and the kit for away games of this team has color y_{i} (x_{i} ≠ y_{i}).

In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n - 1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.

Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ 10^5; x_{i} ≠ y_{i}) — the color numbers for the home and away kits of the i-th team.

-----Output-----

For each team, print on a single line two space-separated integers — the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input.

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

Output
2 0
2 0

Input
3
1 2
2 1
1 3

Output
3 1
4 0
2 2

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

def main():
    n = int(input())
    teams = [list(map(int, input().split())) for _ in range(n)]
    ans = [[n - 1, 0] for _ in range(n)]
    home = [0] * ((10 ** 5) + 1)

    for i in range(n):
        home[teams[i][0]] += 1

    for i in range(n):
        ans[i][0] += home[teams[i][1]]
        ans[i][1] = n - 1 - home[teams[i][1]]

    for i in range(n):
        ans[i] = '{} {}'.format(ans[i][0], ans[i][1])

    print('\n'.join(ans))

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/432/C:
You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times):

  choose two indexes, i and j (1 ≤ i < j ≤ n; (j - i + 1) is a prime number);  swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments: tmp = a[i], a[i] = a[j], a[j] = tmp (tmp is a temporary variable).

You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5). The next line contains n distinct integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ n).

-----Output-----

In the first line, print integer k (0 ≤ k ≤ 5n) — the number of used operations. Next, print the operations. Each operation must be printed as "i j" (1 ≤ i < j ≤ n; (j - i + 1) is a prime).

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

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

Output
1
1 3

Input
2
1 2

Output
0

Input
4
4 2 3 1

Output
3
2 4
1 2
2 4

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

import sys
import collections as cc
import bisect as bi
input=sys.stdin.readline
I=lambda:list(map(int,input().split()))
pr=[]
N=10**6+3
ss=[0]*(N)
ss[0]=1
for i in range(2,N):
	if ss[i]==0:
		ss[i]=i
		pr.append(i)
		for j in range(2*i,N,i):
			ss[j]=i
n,=I()
l=I()
f={}
ans=0
an=[]
for i in range(n):
	f[l[i]]=i
for i in range(n):
	while l[i]!=i+1	:
		ans+=1
		now=f[i+1]
		dis=now-i+1
		temp=bi.bisect(pr,dis)
		temp=pr[temp-1]
		#print(l[i],i+1,temp)
		f[l[now]],f[l[now-temp+1]]=f[l[now-temp+1]],f[l[now]]
		l[now-temp+1],l[now]=l[now],l[now-temp+1]
		an.append([now+1,now-temp+2])
print(ans)
for i in an:
	print(*i[::-1])


I found an interesting problem on https://codeforces.com/problemset/problem/432/D:
You have a string s = s_1s_2...s_{|}s|, where |s| is the length of string s, and s_{i} its i-th character.

Let's introduce several definitions:  A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string s_{i}s_{i} + 1...s_{j}.  The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l].  The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|].

Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring.

-----Input-----

The single line contains a sequence of characters s_1s_2...s_{|}s| (1 ≤ |s| ≤ 10^5) — string s. The string only consists of uppercase English letters.

-----Output-----

In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers l_{i} c_{i}. Numbers l_{i} c_{i} mean that the prefix of the length l_{i} matches the suffix of length l_{i} and occurs in string s as a substring c_{i} times. Print pairs l_{i} c_{i} in the order of increasing l_{i}.

-----Examples-----
Input
ABACABA

Output
3
1 4
3 2
7 1

Input
AAA

Output
3
1 3
2 2
3 1

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

s = ' ' + input()
n = len(s)
r, c = [-1] * n, [1] * n
for i in range(1, n):
    r[i] = r[i - 1] + 1
    while r[i] and s[r[i]]  != s[i]:
        r[i] = r[r[i] - 1] + 1
d, n = [], n - 1
for i in range(n, 1, -1): c[r[i]] += c[i]
while n > 0:
  d.append(str(n) + ' ' + str(c[n]))
  n = r[n]
print(len(d))
d.reverse()
print('\n'.join(d))


I found an interesting problem on https://codeforces.com/problemset/problem/432/E:
You have an n × m rectangle table, its cells are not initially painted. Your task is to paint all cells of the table. The resulting picture should be a tiling of the table with squares. More formally:  each cell must be painted some color (the colors are marked by uppercase Latin letters);  we will assume that two cells of the table are connected if they are of the same color and share a side; each connected region of the table must form a square.

Given n and m, find lexicographically minimum coloring of the table that meets the described properties.

-----Input-----

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

-----Output-----

Print lexicographically minimum coloring of the table that meets the described conditions.

One coloring (let's call it X) is considered lexicographically less than the other one (let's call it Y), if:  consider all the table cells from left to right and from top to bottom (first, the first cell in the first row, then the second cell in the first row and so on);  let's find in this order the first cell that has distinct colors in two colorings;  the letter that marks the color of the cell in X, goes alphabetically before the letter that marks the color of the cell in Y.

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

Output
ABA

Input
2 2

Output
AA
AA

Input
3 4

Output
AAAB
AAAC
AAAB

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

import sys
input = sys.stdin.readline

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

ANS=[[-1]*m for i in range(n)]

for i in range(n):
    for j in range(m):
        if ANS[i][j]==-1:
            for koma in ["A","B","C","D","E","F"]:
                for k,l in [(i-1,j),(i,j-1),(i+1,j),(i,j+1)]:
                    if 0<=k<n and 0<=l<m and ANS[k][l]==koma:
                        break
                else:
                    nkoma=koma
                    break

            MAXlength=1
            if nkoma=="A":
                for length in range(1,101):
                    if i+length>=n or j+length>=m:
                        break

                    for k,l in [(i-1,j+length),(i+length,j-1)]:
                        if 0<=k<n and 0<=l<m and ANS[k][l]==nkoma:
                            break
                        if 0<=i<n and ANS[i][j+length]!=-1:
                            break
                    else:
                        MAXlength=length+1

            elif nkoma=="B":
                for length in range(1,101):
                    if i+length>=n or j+length>=m:
                        break

                    flag=0
                    if 0<=i-1<n and ANS[i-1][j+length]=="A":
                        flag=1
                    if 0<=j-1<m and ANS[i+length][j-1]==nkoma:
                        break
                    if 0<=i<n and ANS[i][j+length]!=-1:
                        break

                    if flag==1:
                        MAXlength=length+1
                    else:
                        break

            for k in range(i,i+MAXlength):
                for l in range(j,j+MAXlength):
                    ANS[k][l]=nkoma

for a in ANS:
    print("".join(a))


I found an interesting problem on https://codeforces.com/problemset/problem/433/A:
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.

Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.

But unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 100) — the number of apples. The second line contains n integers w_1, w_2, ..., w_{n} (w_{i} = 100 or w_{i} = 200), where w_{i} is the weight of the i-th apple.

-----Output-----

In a single line print "YES" (without the quotes) if it is possible to divide all the apples between his friends. Otherwise print "NO" (without the quotes).

-----Examples-----
Input
3
100 200 100

Output
YES

Input
4
100 100 100 200

Output
NO

-----Note-----

In the first test sample Kitahara Haruki can give the first and the last apple to Ogiso Setsuna and the middle apple to Touma Kazusa.

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

n = int(input())
a = sorted([int(x) for x in input().split()], reverse=True)
b1 = 0
b2 = 0
for i in a:
    if b1 >= b2:
        b2 += i
    else:
        b1 += i
if b1 == b2:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/433/B:
Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is v_{i}. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:  She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her $\sum_{i = l}^{r} v_{i}$.  Let u_{i} be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her $\sum_{i = l}^{r} u_{i}$.

For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 10^5). The second line contains n integers: v_1, v_2, ..., v_{n} (1 ≤ v_{i} ≤ 10^9) — costs of the stones.

The third line contains an integer m (1 ≤ m ≤ 10^5) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.

-----Output-----

Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.

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

Output
24
9
28

Input
4
5 5 2 3
10
1 2 4
2 1 4
1 1 1
2 1 4
2 1 2
1 1 1
1 3 3
1 1 3
1 4 4
1 2 2

Output
10
15
5
15
5
5
2
12
3
5

-----Note-----

Please note that the answers to the questions may overflow 32-bit integer type.

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

n = int(input())
us = list(map(int, input().split(" ")))
os = us[:]
os.sort()

for i in range(1,len(os)):
    os[i] += os[i-1]
    us[i] += us[i-1]
os = [0]+os
us = [0]+us

res = []

q = int(input())
for i in range(q):
    t, l, r = list(map(int, input().split(" ")))
    if t == 1:
        res.append(str(us[r] - us[l-1]))
    else:
        res.append(str(os[r] - os[l-1]))

print("\n".join(res))


I found an interesting problem on https://codeforces.com/problemset/problem/433/C:
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory.

Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work.

Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page a_{i}. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is $\sum_{i = 1}^{m - 1}|a_{i + 1} - a_{i}|$.

Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≤ x, y ≤ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place.

Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.

-----Input-----

The first line of input contains two integers n and m (1 ≤ n, m ≤ 10^5).

The next line contains m integers separated by spaces: a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ n).

-----Output-----

Print a single integer — the minimum number of pages Ryouko needs to turn.

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

Output
3

Input
10 5
9 4 3 8 8

Output
6

-----Note-----

In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3,...

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 = {}
for ai in a:
    b[ai] = []
amt = 0
for i in range(1, len(a)):
    amt += abs(a[i]-a[i-1])
    if a[i]-a[i-1]:
        b[a[i]] += [a[i-1]]
        b[a[i-1]] += [a[i]]
diff = 0
for bi in b:
    if b[bi]:
        center = sorted(b[bi])[len(b[bi])//2]
        sum = 0
        for page in b[bi]:
            sum += abs(page-center)-abs(page-bi)
        diff = min(diff, sum)
print(amt+diff)


I found an interesting problem on https://codeforces.com/problemset/problem/435/A:
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups.

The bus stop queue has n groups of people. The i-th group from the beginning has a_{i} people. Every 30 minutes an empty bus arrives at the bus stop, it can carry at most m people. Naturally, the people from the first group enter the bus first. Then go the people from the second group and so on. Note that the order of groups in the queue never changes. Moreover, if some group cannot fit all of its members into the current bus, it waits for the next bus together with other groups standing after it in the queue.

Your task is to determine how many buses is needed to transport all n groups to the dacha countryside.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 100). The next line contains n integers: a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ m).

-----Output-----

Print a single integer — the number of buses that is needed to transport all n groups to the dacha countryside.

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

Output
3

Input
3 4
1 2 1

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()))
ans = 1
avt = m
i = 0
while i < n:
    if a[i] <= avt:
        avt -= a[i]
        i+=1
    else:
        ans += 1
        avt = m
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/435/B:
Pasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer.

Help Pasha count the maximum number he can get if he has the time to make at most k swaps.

-----Input-----

The single line contains two integers a and k (1 ≤ a ≤ 10^18; 0 ≤ k ≤ 100).

-----Output-----

Print the maximum number that Pasha can get if he makes at most k swaps.

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

Output
9190

Input
300 0

Output
300

Input
1034 2

Output
3104

Input
9090000078001234 6

Output
9907000008001234

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

l = input().split()
a = list(map(int, l[0]))
k = int(l[1])
n = len(a)
def rshift(a, l, r):
  t = a[r]
  for i in range(r, l, -1):
    a[i] = a[i - 1]
  a[l] = t
for i in range(n - 1):
  if k == 0:
    break
  j = min(n - 1, i + k)
  m = max(a[i + 1:j + 1])
  if m > a[i]:
    x = i + a[i + 1:j + 1].index(m) + 1
    rshift(a, i, x)
    k -= x - i
print(''.join(map(str, a)))


I found an interesting problem on https://codeforces.com/problemset/problem/435/C:
In this problem, your task is to use ASCII graphics to paint a cardiogram.

A cardiogram is a polyline with the following corners:$(0 ; 0),(a_{1} ; a_{1}),(a_{1} + a_{2} ; a_{1} - a_{2}),(a_{1} + a_{2} + a_{3} ; a_{1} - a_{2} + a_{3}), \ldots,(\sum_{i = 1}^{n} a_{i} ; \sum_{i = 1}^{n}(- 1)^{i + 1} a_{i})$

That is, a cardiogram is fully defined by a sequence of positive integers a_1, a_2, ..., a_{n}.

Your task is to paint a cardiogram by given sequence a_{i}.

-----Input-----

The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000). It is guaranteed that the sum of all a_{i} doesn't exceed 1000.

-----Output-----

Print max |y_{i} - y_{j}| lines (where y_{k} is the y coordinate of the k-th point of the polyline), in each line print $\sum_{i = 1}^{n} a_{i}$ characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.

Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.

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

Output
      / \
   / \ /   \
  /       \
 /         \
          \ /

Input
3
1 5 1

Output
 / \
  \
   \
    \
     \ /

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

import sys
from math import *

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

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

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

n = mint()
y = 0
x = 0
a = []
t = 0
mx = dict()
my = 10**9
for i in mints():
	for j in range(i):
		if t == 0:
			a.append((x,y,'/'))
			mx[y] = max(mx.get(y, -1), x)
			my = min(my, y)
			y -= 1
		else:
			y += 1
			a.append((x,y,'\\'))
			mx[y] = max(mx.get(y, -1), x)
			my = min(my, y)
		x += 1
	t ^= 1
i = 0
b = []
while (my+i) in mx:
	b.append([' ']*(mx[my+i]+1))
	i += 1
for i in a:
	b[i[1]-my][i[0]] = i[2]
for i in b:
	print(*(i+[' ']*(x-len(i))),sep='')


I found an interesting problem on https://codeforces.com/problemset/problem/436/A:
The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem. [Image]

One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of h_{i} centimeters above the floor of the house, its mass is m_{i}. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most x centimeter high jumps. When Om Nom eats a candy of mass y, he gets stronger and the height of his jump increases by y centimeters.

What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?

-----Input-----

The first line contains two integers, n and x (1 ≤ n, x ≤ 2000) — the number of sweets Evan has and the initial height of Om Nom's jump.

Each of the following n lines contains three integers t_{i}, h_{i}, m_{i} (0 ≤ t_{i} ≤ 1; 1 ≤ h_{i}, m_{i} ≤ 2000) — the type, height and the mass of the i-th candy. If number t_{i} equals 0, then the current candy is a caramel drop, otherwise it is a fruit drop.

-----Output-----

Print a single integer — the maximum number of candies Om Nom can eat.

-----Examples-----
Input
5 3
0 2 4
1 3 1
0 8 3
0 20 10
1 5 5

Output
4

-----Note-----

One of the possible ways to eat 4 candies is to eat them in the order: 1, 5, 3, 2. Let's assume the following scenario:  Initially, the height of Om Nom's jump equals 3. He can reach candies 1 and 2. Let's assume that he eats candy 1. As the mass of this candy equals 4, the height of his jump will rise to 3 + 4 = 7.  Now Om Nom can reach candies 2 and 5. Let's assume that he eats candy 5. Then the height of his jump will be 7 + 5 = 12.  At this moment, Om Nom can reach two candies, 2 and 3. He won't eat candy 2 as its type matches the type of the previously eaten candy. Om Nom eats candy 3, the height of his jump is 12 + 3 = 15.  Om Nom eats candy 2, the height of his jump is 15 + 1 = 16. He cannot reach candy 4.

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

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

cs = []

for i in range(n):

    cs.append([int(x) for x in input().split()])

    if cs[-1][0] > 0:

        cs[-1][0] = 1

def try_eat(t0):

    h0 = x

    used = set()

    while True:

        m0 = 0

        i0 = -1

        for i, (t, h, m) in enumerate(cs):

            if t != t0 and h <= h0 and m > m0 and i not in used:

                m0 = m

                i0 = i

        if i0 == -1:

            break

        used.add(i0)

        h0 += cs[i0][2]

        t0 = 1 - t0

    return len(used)

print(max(try_eat(0), try_eat(1)))

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/436/B:
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all. [Image]

The park can be represented as a rectangular n × m field. The park has k spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.

Om Nom isn't yet sure where to start his walk from but he definitely wants:  to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders);  to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park).

We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.

Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.

-----Input-----

The first line contains three integers n, m, k (2 ≤ n, m ≤ 2000; 0 ≤ k ≤ m(n - 1)).

Each of the next n lines contains m characters — the description of the park. The characters in the i-th line describe the i-th row of the park field. If the character in the line equals ".", that means that the corresponding cell of the field is...

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

def f():
    n, m, k = list(map(int, input().split()))
    s = []
    a = []
    for i in range(n):
        s.append(input())
    for j in range(m):
        ans = 0
        for i in range(n):
            if i + i < n and s[i + i][j] == 'U':
                ans += 1
            if j - i >= 0 and s[i][j - i] == 'R':
                ans += 1
            if j + i < m and s[i][j + i] == 'L':
                ans += 1
        a.append(ans)
    print(' '.join(map(str, a)))
f()


I found an interesting problem on https://codeforces.com/problemset/problem/436/C:
During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same.

 [Image]

When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A:

  You can transmit the whole level A. Then you need to transmit n·m bytes via the network.  You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit d_{A}, B·w bytes, where d_{A}, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate d_{A}, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other.

Your task is to find a way to transfer all the k levels and minimize the traffic.

-----Input-----

The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters.

-----Output-----

In the first line print the required minimum number of transferred bytes.

Then print k pairs of integers x_1, y_1, x_2, y_2, ..., x_{k}, y_{k}, describing the way to transfer levels. Pair x_{i}, y_{i} means that level x_{i} needs to be transferred by way y_{i}. If y_{i} equals 0, that means that the level must be transferred...

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

def put():
    return list(map(int, input().split()))
def diff(x,y):
    ans = 0
    for i in range(n*m):
        if s[x][i]!= s[y][i]:
            ans+=1
    return ans
def find(i):
    if i==p[i]:
        return i
    p[i] = find(p[i])
    return p[i]
def union(i,j):
    if rank[i]>rank[j]:
        i,j = j,i
    elif rank[i]==rank[j]:
        rank[j]+=1
    p[i]= j
def dfs(i,p):
    if i!=0:
        print(i,p)
    for j in tree[i]:
        if j!=p:
            dfs(j,i)

n,m,k,w = put()
s = ['']*k
for i in range(k):
    for j in range(n):
        s[i]+=input()
edge = []
k+=1
rank = [0]*(k)
p = list(range(k))
cost = 0
tree = [[] for i in range(k)]

for i in range(k):
    for j in range(i+1,k):
        if i==0:
            z=n*m
        else:
            z = diff(i-1,j-1)*w
        edge.append((z,i,j))

edge.sort()
for z,i,j in edge:
    u = find(i)
    v = find(j)
    if u!=v:
        union(u,v)
        cost+= z
        tree[i].append(j)
        tree[j].append(i)

print(cost)
dfs(0,-1)


I found an interesting problem on https://codeforces.com/problemset/problem/437/A:
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.

Fortunately the child knows how to solve such complicated test. The child will follow the algorithm:

  If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great.  If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice).

You are given a multiple-choice questions, can you predict child's choose?

-----Input-----

The first line starts with "A." (without quotes), then followed the description of choice A. The next three lines contains the descriptions of the other choices in the same format. They are given in order: B, C, D. Please note, that the description goes after prefix "X.", so the prefix mustn't be counted in description's length.

Each description is non-empty and consists of at most 100 characters. Each character can be either uppercase English letter or lowercase English letter, or "_".

-----Output-----

Print a single line with the child's choice: "A", "B", "C" or "D" (without quotes).

-----Examples-----
Input
A.VFleaKing_is_the_author_of_this_problem
B.Picks_is_the_author_of_this_problem
C.Picking_is_the_author_of_this_problem
D.Ftiasch_is_cute

Output
D

Input
A.ab
B.abcde
C.ab
D.abc

Output
C

Input
A.c
B.cc
C.c
D.c

Output
B

-----Note-----

In the first sample, the first choice has length 39, the second one has length 35, the third one has length 37, and the last one has length 15. The choice D (length 15) is twice shorter than all other choices', so it is great choice. There is no other great choices so the child will choose D.

In the second sample, no choice is great, so the child will choose the luckiest choice C.

In the...

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

v = [input()[2:] for i in range(4)]
l = [(len(s),s) for s in v]

min_l, min_s = min(l)[0], min(l)[1]
max_l, max_s = max(l)[0], max(l)[1]

min_ind = 0
max_ind = 0

for i in range(4):
    if i != v.index(min_s) and len(v[i]) / min_l >= 2:
        min_ind += 1
    if i != v.index(max_s) and max_l / len(v[i]) >= 2:
        max_ind += 1

if min_ind == 3 and max_ind != 3:
    print(chr(65 + v.index(min_s)))
elif max_ind == 3 and min_ind != 3:
    print(chr(65 + v.index(max_s)))
else:print('C')


I found an interesting problem on https://codeforces.com/problemset/problem/437/B:
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.

Fortunately, Picks remembers something about his set S:  its elements were distinct integers from 1 to limit;  the value of $\sum_{x \in S} \text{lowbit}(x)$ was equal to sum; here lowbit(x) equals 2^{k} where k is the position of the first one in the binary representation of x. For example, lowbit(10010_2) = 10_2, lowbit(10001_2) = 1_2, lowbit(10000_2) = 10000_2 (binary representation).

Can you help Picks and find any set S, that satisfies all the above conditions?

-----Input-----

The first line contains two integers: sum, limit (1 ≤ sum, limit ≤ 10^5).

-----Output-----

In the first line print an integer n (1 ≤ n ≤ 10^5), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them.

If it's impossible to find a suitable set, print -1.

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

Output
2
4 5

Input
4 3

Output
3
2 3 1

Input
5 1

Output
-1

-----Note-----

In sample test 1: lowbit(4) = 4, lowbit(5) = 1, 4 + 1 = 5.

In sample test 2: lowbit(1) = 1, lowbit(2) = 2, lowbit(3) = 1, 1 + 2 + 1 = 4.

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

def lowbit(x):
	return x & (-x)

def solve():
	nonlocal sum, limit, list
	while(limit > 0 and sum!=0):
		if(sum-lowbit(limit)>=0):
			sum-=lowbit(limit)
			list.add(limit)
		limit-=1
	if(sum==0):
		return True
	return False

sum, limit = tuple(int(i) for i in input().split())
list = set()

if(solve()):
	s = str(len(list)) + "\n"
	for i in list:
		s += str(i) + " "
	print (s[:len(s)-1])
else:
	print (-1)


I found an interesting problem on https://codeforces.com/problemset/problem/437/C:
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.

The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as v_{i}. The child spend v_{f}_1 + v_{f}_2 + ... + v_{f}_{k} energy for removing part i where f_1, f_2, ..., f_{k} are the parts that are directly connected to the i-th and haven't been removed.

Help the child to find out, what is the minimum total energy he should spend to remove all n parts.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v_1, v_2, ..., v_{n} (0 ≤ v_{i} ≤ 10^5). Then followed m lines, each line contains two integers x_{i} and y_{i}, representing a rope from part x_{i} to part y_{i} (1 ≤ x_{i}, y_{i} ≤ n; x_{i} ≠ y_{i}).

Consider all the parts are numbered from 1 to n.

-----Output-----

Output the minimum total energy the child should spend to remove all n parts of the toy.

-----Examples-----
Input
4 3
10 20 30 40
1 4
1 2
2 3

Output
40

Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4

Output
400

Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4

Output
160

-----Note-----

One of the optimal sequence of actions in the first sample is:  First, remove part 3, cost of the action is 20.  Then, remove part 2, cost of the action is 10.  Next, remove part 4, cost of the action is 10.  At last, remove part 1, cost of the action is 0.

So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.

In the second sample, the child will spend 400 no matter in what order he will remove the parts.

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

def main():
    n, m = map(int, input().split())
    vv = list(map(int, input().split()))
    print(sum(min(vv[i - 1] for i in map(int, input().split())) for _ in range(m)))

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/437/D:
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains a_{i} animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.

Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).

After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p ≠ q)? Can you answer his question?

-----Input-----

The first line contains two integers n and m (2 ≤ n ≤ 10^5; 0 ≤ m ≤ 10^5). The second line contains n integers: a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^5). Then follow m lines, each line contains two integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ n; x_{i} ≠ y_{i}), denoting the road between areas x_{i} and y_{i}.

All roads are bidirectional, each pair of areas is connected by at most one road.

-----Output-----

Output a real number — the value of $\frac{\sum_{p, q, p \neq q} f(p, q)}{n(n - 1)}$.

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

-----Examples-----
Input
4 3
10 20 30 40
1 3
2 3
4 3

Output
16.666667

Input
3 3
10 20 30
1 2
2 3
3 1

Output
13.333333

Input
7 8
40 20 10 30 20 50 40
1 2
2 3
3 4
4 5
5 6
6 7
1 4
5 7

Output
18.571429

-----Note-----

Consider the first sample. There are 12 possible situations:

  p = 1, q = 3, f(p, q) = 10.  p = 2, q = 3, f(p, q) = 20.  p = 4, q = 3, f(p, q) = 30.  p = 1, q = 2, f(p, q) = 10.  p = 2, q = 4, f(p, q) = 20.  p = 4, q = 1, f(p, q) = 10.

Another 6 cases are symmetrical to the above. The average is $\frac{(10 + 20...

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

n, m = list(map(int, input().split()))
p, c = list(range(n + 1)), [1] * (n + 1)
v = [0] + list(map(int, input().split()))
s, e = 0, [()] * m
for i in range(m):
    x, y = list(map(int, input().split()))
    e[i] = (x, y, min(v[x], v[y]))
e.sort(key = lambda x: x[2], reverse = True)
q = [[i] for i in range(n + 1)]
for l, r, v in e:
    l, r = p[l], p[r]
    if l == r: continue
    if len(q[l]) > len(q[r]): l, r = r, l
    q[r].extend(q[l])
    for t in q[l]: p[t] = r
    s += c[l] * c[r] * v
    c[r] += c[l]
print(s * 2 / (n * (n - 1)))


I found an interesting problem on https://codeforces.com/problemset/problem/439/A:
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.

Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, i^{th} song will take t_{i} minutes exactly.

The Comedian, Churu will crack jokes. All his jokes are of 5 minutes exactly.

People have mainly come to listen Devu. But you know that he needs rest of 10 minutes after each song. On the other hand, Churu being a very active person, doesn't need any rest.

You as one of the organizers should make an optimal sсhedule for the event. For some reasons you must follow the conditions:  The duration of the event must be no more than d minutes;  Devu must complete all his songs;  With satisfying the two previous conditions the number of jokes cracked by Churu should be as many as possible.

If it is not possible to find a way to conduct all the songs of the Devu, output -1. Otherwise find out maximum number of jokes that Churu can crack in the grand event.

-----Input-----

The first line contains two space separated integers n, d (1 ≤ n ≤ 100; 1 ≤ d ≤ 10000). The second line contains n space-separated integers: t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 100).

-----Output-----

If there is no way to conduct all the songs of Devu, output -1. Otherwise output the maximum number of jokes that Churu can crack in the grand event.

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

Output
5

Input
3 20
2 1 1

Output
-1

-----Note-----

Consider the first example. The duration of the event is 30 minutes. There could be maximum 5 jokes in the following way:  First Churu cracks a joke in 5 minutes.  Then Devu performs the first song for 2 minutes.  Then Churu cracks 2 jokes in 10 minutes.  Now Devu performs second song for 2 minutes.  Then Churu cracks 2 jokes in 10 minutes.  Now finally Devu will perform his last song in 1 minutes.

Total time spent is 5 + 2 + 10 + 2 + 10 + 1 = 30...

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

n, d = [int(c) for c in input().split()]
t = sum([int(c) for c in input().split()])

breaks = (n - 1) * 10

if t + breaks > d:
    print(-1)
else:
    free = d - (t + breaks)
    print(2*(n - 1) + (free // 5))


I found an interesting problem on https://codeforces.com/problemset/problem/439/B:
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the i^{th} subject has c_{i} chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.

Let us say that his initial per chapter learning power of a subject is x hours. In other words he can learn a chapter of a particular subject in x hours.

Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.

You can teach him the n subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.

Please be careful that answer might not fit in 32 bit data type.

-----Input-----

The first line will contain two space separated integers n, x (1 ≤ n, x ≤ 10^5). The next line will contain n space separated integers: c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^5).

-----Output-----

Output a single integer representing the answer to the problem.

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

Output
11

Input
4 2
5 1 2 1

Output
10

Input
3 3
1 1 1

Output
6

-----Note-----

Look at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2 × 1 = 2 hours. Hence you will need to spend 12 + 2 = 14 hours.

Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3 × 1 = 3 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2...

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

buf = input().split(" ")
n = int(buf[0])
k = int(buf[1])

buf = input().split(" ")
for i in range(n):
    buf[i] = int(buf[i])
buf = sorted(buf)

wyn = 0
for i in range(n):
    wyn += buf[i]*k
    k = max(1, k-1)

print(wyn)