I found an interesting problem on https://codeforces.com/problemset/problem/358/D:
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more.

Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?

Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.

Help Inna maximize the total joy the hares radiate. :)

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a_1 a_2 ... a_{n}. The second line contains b_1, b_2, ..., b_{n}. The third line contains c_1, c_2, ..., c_{n}. The following limits are fulfilled: 0 ≤ a_{i}, b_{i}, c_{i} ≤ 10^5.

Number a_{i} in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number b_{i} in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number с_{i} in the third line shows the joy that hare number i radiates if both his adjacent hares are full.

-----Output-----

In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.

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

Output
13

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

Output
44

Input
3
1 1 1
1 2 1
1 1 1

Output
4

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

n=int(input())
a=list(map(int,input().strip().split()))
b=list(map(int,input().strip().split()))
c=list(map(int,input().strip().split()))
d1,d2=a[0],b[0]
for i in range(1,n):
    d1,d2=max(d1+b[i],d2+a[i]),max(d1+c[i],d2+b[i])
print (d1)


I found an interesting problem on https://codeforces.com/problemset/problem/359/A:
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns — from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).

Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table.

Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x_1, y_1), an arbitrary corner of the table (x_2, y_2) and color all cells of the table (p, q), which meet both inequations: min(x_1, x_2) ≤ p ≤ max(x_1, x_2), min(y_1, y_2) ≤ q ≤ max(y_1, y_2).

Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.

-----Input-----

The first line contains exactly two integers n, m (3 ≤ n, m ≤ 50).

Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers a_{i}1, a_{i}2, ..., a_{im}. If a_{ij} equals zero, then cell (i, j) isn't good. Otherwise a_{ij} equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.

-----Output-----

Print a single number — the minimum number of operations Simon needs to carry out his idea.

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

Output
4

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

Output
2

-----Note-----

In the first sample, the sequence of operations can be like this: [Image]   For the first time you need to choose cell (2, 2) and corner (1, 1).  For the second time you need to choose cell (2, 2) and corner (3, 3).  For the third time you need to choose cell (2, 2) and corner (3, 1).  For the fourth time you need to choose cell (2, 2) and corner (1, 3).

In the second sample the sequence of operations can be like this: [Image]   For the...

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

'''
Created on Jan 28, 2015

@author: mohamed265
'''
t = input().split()
n = int(t[0])
m = int(t[1])
slon = 9999
for i in range(n):
    t = input().split()
    for j in range(m):
        if t[j] == '1':
            if i == 0 or i == n - 1 or j == 0 or j == m - 1:
                slon = 2
            else:
                slon = min(4, slon)
print(slon)


I found an interesting problem on https://codeforces.com/problemset/problem/359/B:
A permutation p is an ordered group of numbers p_1,   p_2,   ...,   p_{n}, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p_1,   p_2,   ...,   p_{n}.

Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: $\sum_{i = 1}^{n}|a_{2 i - 1} - a_{2i}|-|\sum_{i = 1}^{n} a_{2 i - 1} - a_{2i}|= 2 k$.

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n).

-----Output-----

Print 2n integers a_1, a_2, ..., a_2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them.

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

Output
1 2
Input
2 1

Output
3 2 1 4

Input
4 0

Output
2 7 4 6 1 3 5 8

-----Note-----

Record |x| represents the absolute value of number x.

In the first sample |1 - 2| - |1 - 2| = 0.

In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2.

In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.

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

n,k = list(map(int, input().split()))
A = [i for i in range(0, (2*n)+1)]
for i in range(1,k+1):
    A[2*i], A[2*i-1] = A[2*i-1], A[2*i]
print(" ".join(map(str, A[1:])))


I found an interesting problem on https://codeforces.com/problemset/problem/359/C:
Simon has a prime number x and an array of non-negative integers a_1, a_2, ..., a_{n}.

Simon loves fractions very much. Today he wrote out number $\frac{1}{x^{a} 1} + \frac{1}{x^{a_{2}}} + \ldots + \frac{1}{x^{a_{n}}}$ on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: $\frac{s}{t}$, where number t equals x^{a}_1 + a_2 + ... + a_{n}. Now Simon wants to reduce the resulting fraction.

Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (10^9 + 7).

-----Input-----

The first line contains two positive integers n and x (1 ≤ n ≤ 10^5, 2 ≤ x ≤ 10^9) — the size of the array and the prime number.

The second line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_1 ≤ a_2 ≤ ... ≤ a_{n} ≤ 10^9).

-----Output-----

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

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

Output
8

Input
3 3
1 2 3

Output
27

Input
2 2
29 29

Output
73741817

Input
4 5
0 0 0 0

Output
1

-----Note-----

In the first sample $\frac{1}{4} + \frac{1}{4} = \frac{4 + 4}{16} = \frac{8}{16}$. Thus, the answer to the problem is 8.

In the second sample, $\frac{1}{3} + \frac{1}{9} + \frac{1}{27} = \frac{243 + 81 + 27}{729} = \frac{351}{729}$. The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.

In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.

In the fourth sample $\frac{1}{1} + \frac{1}{1} + \frac{1}{1} + \frac{1}{1} = \frac{4}{1}$. Thus, the answer to the problem is 1.

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

n,x=list(map(int,input().split()))
l=list(map(int,input().split()))
from collections import Counter
l.sort()
gcd=sum(l[:n-1])
m=10**9+7
s=sum(l)
l1=[]
for i in l:
    l1.append(s-i-gcd)
c=Counter(l1)
l2=[]
for i in c:
    l2.append(i)
l2.sort()
z=True
while z:
    z=False
    for i in c.copy():
        a=c[i]
        b=0
        while a%x==0 and a!=0:
            z=True
            a//=x
            b+=1
        if z:
            c[i+b]+=a
            c[i]=0
y=l[-1]
for i in c:
    if c[i]:
        y=min(y,i)
gcd+=y
print(pow(x,min(s,gcd),m))


I found an interesting problem on https://codeforces.com/problemset/problem/359/D:
Simon has an array a_1, a_2, ..., a_{n}, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold:  there is integer j (l ≤ j ≤ r), such that all integers a_{l}, a_{l} + 1, ..., a_{r} are divisible by a_{j};  value r - l takes the maximum value among all pairs for which condition 1 is true;

Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 3·10^5).

The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6).

-----Output-----

Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order.

-----Examples-----
Input
5
4 6 9 3 6

Output
1 3
2

Input
5
1 3 5 7 9

Output
1 4
1

Input
5
2 3 5 7 11

Output
5 0
1 2 3 4 5

-----Note-----

In the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.

In the second sample all numbers are divisible by number 1.

In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5).

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

n = int(input()) + 1
t = [1] + list(map(int, input().split())) + [1]
p = [True] * n
s, q = 0, list(range(1, n))
for i in range(1, n):
    if p[i]:
        a = b = i
        d = t[i]
        if d == 1:
            s, q = n - 2, [1]
            break
        while t[a - 1] % d == 0: a -= 1
        while t[b + 1] % d == 0:
            b += 1
            p[b] = False
        d = b - a
        if d > s: s, q = d, [a]
        elif d == s != 0: q.append(a)
print(len(q), s)
print(' '.join(map(str, q)))


I found an interesting problem on https://codeforces.com/problemset/problem/361/A:
Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.

Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.

-----Input-----

The single line contains two integers, n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000).

-----Output-----

Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.

If there are multiple suitable tables, you are allowed to print any of them.

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

Output
1 3
3 1

Input
4 7

Output
2 1 0 4
4 0 2 1
1 3 3 0
0 3 2 2

-----Note-----

In the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.

In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.

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

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

ind=0
for i in range(N):
    for j in range(N):
        if(j!=N-1):
            if(j==i):
                print(k,end=" ")
            else:
                print(0,end=" ")
        else:
            if(j==i):
                print(k)
            else:
                print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/361/B:
Levko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n.

Let’s assume that value gcd(a, b) shows the greatest common divisor of numbers a and b. Levko assumes that element p_{i} of permutation p_1, p_2, ... , p_{n} is good if gcd(i, p_{i}) > 1. Levko considers a permutation beautiful, if it has exactly k good elements. Unfortunately, he doesn’t know any beautiful permutation. Your task is to help him to find at least one of them.

-----Input-----

The single line contains two integers n and k (1 ≤ n ≤ 10^5, 0 ≤ k ≤ n).

-----Output-----

In a single line print either any beautiful permutation or -1, if such permutation doesn’t exist.

If there are multiple suitable permutations, you are allowed to print any of them.

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

Output
2 4 3 1
Input
1 1

Output
-1

-----Note-----

In the first sample elements 4 and 3 are good because gcd(2, 4) = 2 > 1 and gcd(3, 3) = 3 > 1. Elements 2 and 1 are not good because gcd(1, 2) = 1 and gcd(4, 1) = 1. As there are exactly 2 good elements, the permutation is beautiful.

The second sample has no beautiful permutations.

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

import itertools
import math
import random

import time
def timer(f):
    def tmp(*args, **kwargs):
        t = time.time()
        res = f(*args, **kwargs)
        print("Время выполнения функции: %f" % (time.time()-t))
        return res

    return tmp

def genArray(length, lower, upper):
    return [random.randint(lower, upper) for i in range(length)]

#print(genArray(5, 4, 9))

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

n, k = map(int, input().split(' '))
k = n-k

if k == 0:
    print(-1)
    return
else:
    array = [0 for i in range(n)]
    for j in range(k):
        array[j] = (j-1)%(k)+1
    for j in range(k, n):
        array[j] = j+1

ar = [i+1 for i in range(n)]
#print(ar)
#print(array)

total = 0
for i in range(n):
    if gcd(ar[i], array[i])==1:
        total+=1

#print(total)

str = array.__str__().replace('[', '').replace(']', '').replace(',', '')
print(str)


I found an interesting problem on https://codeforces.com/problemset/problem/362/A:
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.

Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.

Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.

Please see the test case analysis.

-----Input-----

The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.

-----Output-----

For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.

-----Examples-----
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......

........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#

Output
YES
NO

-----Note-----

Consider the first board from the sample. We will assume the rows and columns of the matrix...

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

n = int (input())
for i in range(n):
    if (i):
        input()
    x1 = y1 = x2 = y2 = 0
    s = [input() for i in range(8)]
    for i in range(8):
        for j in range(8):
            if (s[i][j] == 'K'):
                x1, y1, x2, y2 = x2, y2, i, j
    if (abs(x1-x2) % 4 == 0 and abs(y1-y2) % 4 == 0):
        print ("YES")
    else:
        print ("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/362/B:
Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.

Now Petya is on the first stair of the staircase, consisting of n stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number n without touching a dirty stair once.

One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 10^9, 0 ≤ m ≤ 3000) — the number of stairs in the staircase and the number of dirty stairs, correspondingly. The second line contains m different space-separated integers d_1, d_2, ..., d_{m} (1 ≤ d_{i} ≤ n) — the numbers of the dirty stairs (in an arbitrary order).

-----Output-----

Print "YES" if Petya can reach stair number n, stepping only on the clean stairs. Otherwise print "NO".

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

Output
NO
Input
10 5
2 4 5 7 9

Output
YES

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

n, m = map(int,input().split())
if m >= 1:
    gr = list(map(int, input().split()))
    gr.sort()
k = 1
if (m >= 1 and gr[0] == 1) or (m >= 1 and gr[m-1]) == n:
    print('NO')
else:
    for i in range(m-2):
        if gr[i] == gr[i+1] - 1 == gr[i+2] - 2:
            print('NO')
            k = 0
            break
    if k == 1:
        print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/362/C:
Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decreasing order. for (int i = 1; i < n; i = i + 1)

{

   int j = i;

   while (j > 0 && a[j] < a[j - 1])

   {

      swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1]

      j = j - 1;

   }

}

Petya uses this algorithm only for sorting of arrays that are permutations of numbers from 0 to n - 1. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.

It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 5000) — the length of the permutation. The second line contains n different integers from 0 to n - 1, inclusive — the actual permutation.

-----Output-----

Print two integers: the minimum number of times the swap function is executed and the number of such pairs (i, j) that swapping the elements of the input permutation with indexes i and j leads to the minimum number of the executions.

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

Output
3 2

Input
5
1 2 3 4 0

Output
3 4

-----Note-----

In the first sample the appropriate pairs are (0, 3) and (0, 4).

In the second sample the appropriate pairs are (0, 4), (1, 4), (2, 4) and (3, 4).

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

arr = [0 for i in range(5001)]

def insertion_sort(n, a):
    def modify(t):
        while t > 0:
            arr[t] += 1
            t -= t & (-t)

    def query(t):
        res = 0
        while t < 5001:
            res += arr[t]
            t += t & (-t)
        return res

    s = 0
    ans = 0
    way = 0

    for i in range(n):
        a[i] += 1

    for i in range(n):
        nonlocal arr
        arr = [0 for j in range(5001)]
        for j in range(i + 1, n):
            if a[i] < a[j]:
                continue
            s += 1
            tmp = 1 + 2 * query(a[j])
            if tmp > ans:
                ans = tmp
                way = 1
            elif tmp == ans:
                way += 1
            modify(a[j])

    return s - ans, way

def __starting_point():
    n = int(input())
    a = list(map(int, input().split()))
    result = insertion_sort(n, a)
    print(*result)

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/363/A:
You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban — an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about them. Let's have a look at the Soroban's construction. [Image]

Soroban consists of some number of rods, each rod contains five beads. We will assume that the rods are horizontal lines. One bead on each rod (the leftmost one) is divided from the others by a bar (the reckoning bar). This single bead is called go-dama and four others are ichi-damas. Each rod is responsible for representing a single digit from 0 to 9. We can obtain the value of a digit by following simple algorithm:  Set the value of a digit equal to 0.  If the go-dama is shifted to the right, add 5.  Add the number of ichi-damas shifted to the left.

Thus, the upper rod on the picture shows digit 0, the middle one shows digit 2 and the lower one shows 7. We will consider the top rod to represent the last decimal digit of a number, so the picture shows number 720.

Write the program that prints the way Soroban shows the given number n.

-----Input-----

The first line contains a single integer n (0 ≤ n < 10^9).

-----Output-----

Print the description of the decimal digits of number n from the last one to the first one (as mentioned on the picture in the statement), one per line. Print the beads as large English letters 'O', rod pieces as character '-' and the reckoning bar as '|'. Print as many rods, as many digits are in the decimal representation of number n without leading zeroes. We can assume that number 0 has no leading zeroes.

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

Output
O-|OO-OO

Input
13

Output
O-|OOO-O
O-|O-OOO

Input
720

Output
O-|-OOOO
O-|OO-OO
-O|OO-OO

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

'''
Created on Nov 11, 2013

@author: Ismael
'''
import sys

def printDigitSoroban(digit):
    if(digit == 0):
        print("O-|-OOOO")
    elif(digit == 1):
        print("O-|O-OOO")
    elif(digit == 2):
        print("O-|OO-OO")
    elif(digit == 3):
        print("O-|OOO-O")
    elif(digit == 4):
        print("O-|OOOO-")
    elif(digit == 5):
        print("-O|-OOOO")
    elif(digit == 6):
        print("-O|O-OOO")
    elif(digit == 7):
        print("-O|OO-OO")
    elif(digit == 8):
        print("-O|OOO-O")
    elif(digit == 9):
        print("-O|OOOO-")

def convert(x):
    if(x == 0):
        printDigitSoroban(0)
    while(x>=1):
        digit = x%10
        printDigitSoroban(digit)
        x //= 10

def main():
    f = sys.stdin
    n = int(f.readline())
    convert(n)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/363/B:
There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is h_{i} meters, distinct planks can have distinct heights. [Image] Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1]

Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly k consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such k consecutive planks that the sum of their heights is minimal possible.

Write the program that finds the indexes of k consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).

-----Input-----

The first line of the input contains integers n and k (1 ≤ n ≤ 1.5·10^5, 1 ≤ k ≤ n) — the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 100), where h_{i} is the height of the i-th plank of the fence.

-----Output-----

Print such integer j that the sum of the heights of planks j, j + 1, ..., j + k - 1 is the minimum possible. If there are multiple such j's, print any of them.

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

Output
3

-----Note-----

In the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8.

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

minimum = pow(10, 19)
index = 0

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

dp = [0]+[fence[0]]+[0]*(n-1)
for t in range(2, n+1):
    dp[t] = dp[t-1]+fence[t-1]

for u in range(n-k+1):
    value = dp[u+k]-dp[u]
    if value < minimum:
        index = u
        minimum = value

print(index+1)


I found an interesting problem on https://codeforces.com/problemset/problem/363/C:
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.

In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).

Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.

-----Input-----

The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.

-----Output-----

Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters.

If there are multiple solutions, print any of them.

-----Examples-----
Input
helloo

Output
hello

Input
woooooow

Output
woow

-----Note-----

The second valid answer to the test from the statement is "heloo".

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

import sys
import math

s = input()
l = len(s)

p = '1'
k = 0
v = 1
res = []
for i in range(l):
    if(p != s[i]):
        p = s[i]
        if(v == 1):
            k = 0
        v = 1
        res.append(p)
    else:
        v += 1
        if(v == 2):
            if(k % 2 == 0):
                res.append(p)
                k = 1
            else:
                 k = 0

print("".join(res))


I found an interesting problem on https://codeforces.com/problemset/problem/363/D:
A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.

The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs p_{j} rubles.

In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has b_{i} personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.

Each boy can rent at most one bike, one cannot give his bike to somebody else.

What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?

-----Input-----

The first line of the input contains three integers n, m and a (1 ≤ n, m ≤ 10^5; 0 ≤ a ≤ 10^9). The second line contains the sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^4), where b_{i} is the amount of the i-th boy's personal money. The third line contains the sequence of integers p_1, p_2, ..., p_{m} (1 ≤ p_{j} ≤ 10^9), where p_{j} is the price for renting the j-th bike.

-----Output-----

Print two integers r and s, where r is the maximum number of schoolboys that can rent a bike and s is the minimum total personal money needed to rent r bikes. If the schoolchildren cannot rent any bikes, then r = s = 0.

-----Examples-----
Input
2 2 10
5 5
7 6

Output
2 3

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

Output
3 8

-----Note-----

In the first sample both schoolchildren can rent a bike. For instance, they can split the shared budget in half (5 rubles each). In this case one of them will have to pay 1 ruble from the personal money and the other one will have to pay 2 rubles from the personal money. In total, they spend 3 rubles of their personal money. This way of distribution of money minimizes the amount of spent personal money.

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

import sys

cases = False

# Pre-defined function
# Begin
def fast_pow(a:int, b:int):
    res = 1
    while b > 0:
        if b & 1:
            res *= a
        a *= a
        b >>= 1
    return res

def c2(n):
    return n * (n-1) // 2

def get():
    return list(map(int, input().split()))

def bits(n: int):
    return list(bin(n)).count('1')

def main(test_case = False):
    n = int(input()) if test_case else 1
    for _ in range(n):
        test()

def flush():
    sys.stdout.flush()

def parr(arr):
    print(*arr, sep=' ')

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

def ext_gcd(a: int, b: int):
    if (b == 0):
        return [a, [1, 0]]

    res = ext_gcd(b, a % b)
    g = res[0]
    x1 = res[1][0]
    y1 = res[1][1]
    x = y1
    y = x1 - y1 * (a // b)

    return [g, [x, y]]

# End

b = []
p = []
n = m = a = 0

def check(cnt):
    if cnt == 0:
        return True
    x = b[-cnt:]
    y = p[:cnt]
    s = a
    i = 0
    while i < cnt and s >= 0:
        s -= max(0, y[i]-x[i])
        i += 1
    return s >= 0

def test():
    nonlocal n, m, a, b, p
    n, m, a = get()
    b = sorted(get())
    p = sorted(get())

    left = 0
    right = min(n, m)

    ans = -1

    while left <= right:
        mid = (left + right) // 2
        if check(mid):
            ans = max(ans, mid)
            left = mid + 1
        else:
            right = mid - 1

    if ans == -1:
        print(0, 0)
        return

    # print(ans)

    t = 0
    x = b[-ans:]
    y = p[:ans]
    i = 0
    while i < ans:
        t += min(x[i], y[i])
        a -= max(0, y[i]-x[i])
        i += 1
    print(ans, max(0, t-a))

main(cases)


I found an interesting problem on https://codeforces.com/problemset/problem/364/A:
You have a string of decimal digits s. Let's define b_{ij} = s_{i}·s_{j}. Find in matrix b the number of such rectangles that the sum b_{ij} for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.

A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j) such that x ≤ i ≤ y, z ≤ j ≤ t.

-----Input-----

The first line contains integer a (0 ≤ a ≤ 10^9), the second line contains a string of decimal integers s (1 ≤ |s| ≤ 4000).

-----Output-----

Print a single integer — the answer to a problem.

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

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

Output
6

Input
16
439873893693495623498263984765

Output
40

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

from collections import Counter
def __starting_point():
	a = int(input())
	seq = list(input())
	n = len(seq)
	seq = [int(x) for x in seq]

	curr_sum = 0
	cum_sum = [0]
	sum_pairs = list()

	for i in seq:
		curr_sum += i
		cum_sum.append(curr_sum)
	for i in range(1, n+1):
		for j in range(i, n+1):
			if i <= j:
				sum_pairs.append(cum_sum[j]-cum_sum[i-1])

	freq = Counter(sum_pairs)

	unique_sum = list(freq.keys())
	unique_sum = set(unique_sum)
	ans = 0
	# print(fre÷q)

	for i in unique_sum:
		if i!=0 and a%i==0 and a//i in freq:
			if i != a//i:
				ans += (freq[i]*freq[a//i])
			else:
				ans += (freq[i]*(freq[i]))
				freq.pop(i)

	if a == 0:
		ans = (freq[0]*len(sum_pairs))+(freq[0]*(len(sum_pairs) - freq[0]))

	# print(sum_pairs)
	print(ans)

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/365/A:
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a).

-----Input-----

The first line contains integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9). The i-th of the following n lines contains integer a_{i} without leading zeroes (1 ≤ a_{i} ≤ 10^9).

-----Output-----

Print a single integer — the number of k-good numbers in a.

-----Examples-----
Input
10 6
1234560
1234560
1234560
1234560
1234560
1234560
1234560
1234560
1234560
1234560

Output
10

Input
2 1
1
10

Output
1

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

#!/usr/bin/env python3

n, k = tuple(map(int, input().split()))
a = []
for i in range(n):
    a.append(input())

r = 0
for s in a:
    f = True
    for i in range(k + 1):
        if str(i) not in s:
            f = False
            break
    if f:
        r = r + 1

print(r)


I found an interesting problem on https://codeforces.com/problemset/problem/365/B:
You have array a_1, a_2, ..., a_{n}. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good if a_{i} = a_{i} - 1 + a_{i} - 2, for all i (l + 2 ≤ i ≤ r).

Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l_1, r_1], is longer than segment [l_2, r_2], if len([l_1, r_1]) > len([l_2, r_2]).

Your task is to find a good segment of the maximum length in array a. Note that a segment of length 1 or 2 is always good.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of elements in the array. The second line contains integers: a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9).

-----Output-----

Print the length of the longest good segment in array a.

-----Examples-----
Input
10
1 2 3 5 8 13 21 34 55 89

Output
10

Input
5
1 1 1 1 1

Output
2

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

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

if n < 3:
  print(n)
  return

l, r = 0, 2
max_len = r - l
while r < n:
  while r < n and a[r] == a[r - 2] + a[r - 1]:
    r += 1
  max_len = max(max_len, r - l)
  l = r - 1
  r += 1

print(max_len)


I found an interesting problem on https://codeforces.com/problemset/problem/366/A:
Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards...

There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can bribe a guard by a chocolate bar or a box of juice. For each guard you know the minimum price of the chocolate bar she can accept as a gift and the minimum price of the box of juice she can accept as a gift. If a chocolate bar for some guard costs less than the minimum chocolate bar price for this guard is, or if a box of juice for some guard costs less than the minimum box of juice price for this guard is, then the guard doesn't accept such a gift.

In order to pass through a guardpost, one needs to bribe both guards.

The shop has an unlimited amount of juice and chocolate of any price starting with 1. Dima wants to choose some guardpost, buy one gift for each guard from the guardpost and spend exactly n rubles on it.

Help him choose a post through which he can safely sneak Inna or otherwise say that this is impossible. Mind you, Inna would be very sorry to hear that!

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 10^5) — the money Dima wants to spend. Then follow four lines describing the guardposts. Each line contains four integers a, b, c, d (1 ≤ a, b, c, d ≤ 10^5) — the minimum price of the chocolate and the minimum price of the juice for the first guard and the minimum price of the chocolate and the minimum price of the juice for the second guard, correspondingly.

-----Output-----

In a single line of the output print three space-separated integers: the number of the guardpost, the cost of the first present and the cost of the second present. If there is no guardpost Dima can sneak Inna through at such conditions, print -1 in a single line.

The guardposts are numbered from 1 to 4 according to the order given in the input.

If there are multiple solutions,...

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

L = lambda: list(map(int, input().split()))
I = lambda: int(input())

n, t = I(), [L() for i in range(4)]
p = [min(i[0], i[1]) + min(i[2], i[3]) for i in t]
x = min(p)
if x > n: print(-1)
else:
    k = p.index(x)
    p = min(t[k][0], t[k][1])
    print(k + 1, p, n - p)


I found an interesting problem on https://codeforces.com/problemset/problem/366/B:
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.

Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.

Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.

Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.

-----Input-----

The first line of the input contains two integers n, k (1 ≤ k ≤ n ≤ 10^5). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^3), where a_{i} is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task.

It is guaranteed that n is divisible by k.

-----Output-----

In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.

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

Output
1

Input
10 5
1 3 5 7 9 9 4 1 8 5

Output
3

-----Note-----

Explanation of the first example.

If Dima starts from the first task, Inna tells him off with power 3,...

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

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

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

print(min((sum(t[i :: k]), i) for i in range(k))[1] + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/366/C:
Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something.

Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit salad, so she wants to take some fruits from the fridge for it. Inna follows a certain principle as she chooses the fruits: the total taste to the total calories ratio of the chosen fruits must equal k. In other words, $\frac{\sum_{j = 1}^{m} a_{j}}{\sum_{j = 1}^{m} b_{j}} = k$ , where a_{j} is the taste of the j-th chosen fruit and b_{j} is its calories.

Inna hasn't chosen the fruits yet, she is thinking: what is the maximum taste of the chosen fruits if she strictly follows her principle? Help Inna solve this culinary problem — now the happiness of a young couple is in your hands!

Inna loves Dima very much so she wants to make the salad from at least one fruit.

-----Input-----

The first line of the input contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10). The second line of the input contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100) — the fruits' tastes. The third line of the input contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 100) — the fruits' calories. Fruit number i has taste a_{i} and calories b_{i}.

-----Output-----

If there is no way Inna can choose the fruits for the salad, print in the single line number -1. Otherwise, print a single integer — the maximum possible sum of the taste values of the chosen fruits.

-----Examples-----
Input
3 2
10 8 1
2 7 1

Output
18

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

Output
-1

-----Note-----

In the first test sample we can get the total taste of the fruits equal to 18 if we choose fruit number 1 and fruit number 2, then the total calories will equal 9. The condition $\frac{18}{9} = 2 = k$ fulfills, that's exactly what Inna wants.

In the second test sample we cannot choose the fruits so as to follow Inna's principle.

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

from sys import stdin,stdout
Pi = lambda x: stdout.write(str(x) + '\n')
Ps = lambda x: stdout.write(str(x))
S = lambda x: x*(x+1) // 2
I = lambda x: 1+(2*x)
R = lambda:stdin.readline()
Ri = lambda x:list(map(int,x.split()))
Rs = lambda x:list(map(str,x.split()))
Rf = lambda x:list(map(float,x.split()))
MaxN = int(1e5) + 10
# dp,A = []
def f(i,x,n,k,dp,A,B):
	if i==n:
		if x==0:return 0
		return -1000000
	if dp[i][x+MaxN]!=-1:return dp[i][x+MaxN]
	op1 = f(i+1, x+A[i]-B[i]*k,n,k,dp,A,B)+A[i]
	op2 = f(i+1, x,n,k,dp,A,B)
	dp[i][x+MaxN] = max(op2,op1)
	return dp[i][x+MaxN]

def main():
	# t = int(R())
	for x in stdin:
		n,x = Ri(x)
		A = list(Ri(R()))
		B = list(Ri(R()))
		dp = []
		for i in range(110):
			dp.append([-1]*(MaxN*2))
		ans = f(0,0,n,x,dp,A,B)
		if ans < 1:ans = -1
		Pi(ans)

def __starting_point():
	main()

# 60 == 360

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/366/E:
Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with n strings and m frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the i-th string holding it on the j-th fret the guitar produces a note, let's denote it as a_{ij}. We know that Dima's guitar can produce k distinct notes. It is possible that some notes can be produced in multiple ways. In other words, it is possible that a_{ij} = a_{pq} at (i, j) ≠ (p, q).

Dima has already written a song — a sequence of s notes. In order to play the song, you need to consecutively produce the notes from the song on the guitar. You can produce each note in any available way. Dima understood that there are many ways to play a song and he wants to play it so as to make the song look as complicated as possible (try to act like Cobein).

We'll represent a way to play a song as a sequence of pairs (x_{i}, y_{i}) (1 ≤ i ≤ s), such that the x_{i}-th string on the y_{i}-th fret produces the i-th note from the song. The complexity of moving between pairs (x_1, y_1) and (x_2, y_2) equals $|x_{1} - x_{2}|$ + $|y_{1} - y_{2}|$. The complexity of a way to play a song is the maximum of complexities of moving between adjacent pairs.

Help Dima determine the maximum complexity of the way to play his song! The guy's gotta look cool!

-----Input-----

The first line of the input contains four integers n, m, k and s (1 ≤ n, m ≤ 2000, 1 ≤ k ≤ 9, 2 ≤ s ≤ 10^5).

Then follow n lines, each containing m integers a_{ij} (1 ≤ a_{ij} ≤ k). The number in the i-th row and the j-th column (a_{ij}) means a note that the guitar produces on the i-th string and the j-th fret.

The last line of the input contains s integers q_{i} (1 ≤ q_{i} ≤ k) — the sequence of notes of the song.

-----Output-----

In a single line print a single number — the maximum possible complexity of the song.

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

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

def solution() : # 最大的距离来自于角落附近的点
	n,m,k,s = map(int, input().split())
	dis = lambda a,b : abs(a[0] - b[0]) + abs(a[1] - b[1])
	corner = [(0,0), (0,m-1), (n-1,0), (n-1,m-1)]
	vertex = [[(n,m), (n,-1), (-1,m), (-1,-1)] for _ in range(k+1)]
	for i in range(n) :
		for j,note in enumerate(map(int, input().split())) :
			vertex[note] = [
				(i,j) if dis((i,j), c) < dis(v, c) else v
				for v,c in zip(vertex[note], corner)]
	maxdis = [[-1] * (k+1) for _ in range(k+1)]
	pairs = [(0,3),(3,0),(1,2),(2,1)]
	for i in range(1, k+1) :
		for j in range(i, k+1) :
			vi,vj = vertex[i],vertex[j]
			maxdis[i][j] = max(dis(vi[a], vj[b]) for a,b in pairs)
			maxdis[j][i] = maxdis[i][j]
	s = list(map(int, input().split()))
	print(max(maxdis[s[i]][s[i+1]] for i in range(len(s) - 1)))
solution()


I found an interesting problem on https://codeforces.com/problemset/problem/367/B:
Sereja has two sequences a and b and number p. Sequence a consists of n integers a_1, a_2, ..., a_{n}. Similarly, sequence b consists of m integers b_1, b_2, ..., b_{m}. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence a_{q}, a_{q} + p, a_{q} + 2p, ..., a_{q} + (m - 1)p by rearranging elements.

Sereja needs to rush to the gym, so he asked to find all the described positions of q.

-----Input-----

The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·10^5, 1 ≤ p ≤ 2·10^5). The next line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). The next line contains m integers b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ 10^9).

-----Output-----

In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.

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

Output
2
1 3

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

Output
2
1 2

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

from collections import Counter

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

def try_from(start, a, b):
    result = []
    seq = a[start::p]
    i = 0
    if len(seq) < len(b):
        return []

    counts_a = Counter(seq[:len(b)])
    counts_b = Counter(b)
    if counts_a == counts_b:
        result.append(start)

    for i in range(1, len(seq) - len(b) + 1):
        counts_a[seq[i-1]] -= 1
        counts_a[seq[i+len(b) - 1]] += 1
        if not counts_a[seq[i-1]]:
            del counts_a[seq[i-1]]

        ok = counts_a == counts_b
        #ok = sorted(seq[i:i+len(b)]) == sorted(b)

        if ok:
            result.append(start + p * i)

    return [x + 1 for x in result]

result = []
for start in range(p):
    result += try_from(start, a, b)

print(len(result))
print(' '.join(map(str, sorted(result))))

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/367/C:
Let's call an array consisting of n integer numbers a_1, a_2, ..., a_{n}, beautiful if it has the following property:

  consider all pairs of numbers x, y (x ≠ y), such that number x occurs in the array a and number y occurs in the array a;  for each pair x, y must exist some position j (1 ≤ j < n), such that at least one of the two conditions are met, either a_{j} = x, a_{j} + 1 = y, or a_{j} = y, a_{j} + 1 = x.

Sereja wants to build a beautiful array a, consisting of n integers. But not everything is so easy, Sereja's friend Dima has m coupons, each contains two integers q_{i}, w_{i}. Coupon i costs w_{i} and allows you to use as many numbers q_{i} as you want when constructing the array a. Values q_{i} are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array a of n elements. After that he takes w_{i} rubles from Sereja for each q_{i}, which occurs in the array a. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.

Help Sereja, find the maximum amount of money he can pay to Dima.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 2·10^6, 1 ≤ m ≤ 10^5). Next m lines contain pairs of integers. The i-th line contains numbers q_{i}, w_{i} (1 ≤ q_{i}, w_{i} ≤ 10^5).

It is guaranteed that all q_{i} are distinct.

-----Output-----

In a single line print maximum amount of money (in rubles) Sereja can pay.

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

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

Output
5

Input
100 3
1 2
2 1
3 1

Output
4

Input
1 2
1 1
2 100

Output
100

-----Note-----

In the first sample Sereja can pay 5 rubles, for example, if Dima constructs the following array: [1, 2, 1, 2, 2]. There are another optimal arrays for this test.

In the third sample Sereja can pay 100 rubles, if Dima constructs the following array: [2].

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

n,m = list(map(int,input().split()))
q = [0] * (m)
w = [0] * (m)
for i in range(m):
    q[i],w[i] = [int(x) for x in input().split()]
    #print(q[i],w[i])
w.sort(reverse = True)
#print(*w)
s = 0
v = 0
#print("n=",n)
for i in range(m):
    i=i+1
    if (i % 2 == 1): v = i*(i-1)//2 + 1
    else: v=i*i//2
    i=i-1
    #print("i=",i," v=",v,"w[i]=",w[i])
    if(v>n): break
    s+=w[i]
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/368/A:
Sereja owns a restaurant for n people. The restaurant hall has a coat rack with n hooks. Each restaurant visitor can use a hook to hang his clothes on it. Using the i-th hook costs a_{i} rubles. Only one person can hang clothes on one hook.

Tonight Sereja expects m guests in the restaurant. Naturally, each guest wants to hang his clothes on an available hook with minimum price (if there are multiple such hooks, he chooses any of them). However if the moment a guest arrives the rack has no available hooks, Sereja must pay a d ruble fine to the guest.

Help Sereja find out the profit in rubles (possibly negative) that he will get tonight. You can assume that before the guests arrive, all hooks on the rack are available, all guests come at different time, nobody besides the m guests is visiting Sereja's restaurant tonight.

-----Input-----

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

-----Output-----

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

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

Output
3

Input
2 1
2 1
10

Output
-5

-----Note-----

In the first test both hooks will be used, so Sereja gets 1 + 2 = 3 rubles.

In the second test both hooks will be used but Sereja pays a fine 8 times, so the answer is 3 - 8 =  - 5.

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

M = lambda: map(int, input().split())
L = lambda: list(map(int, input().split()))
I = lambda: int(input())
n, d = M()
a, k = sorted(L()), I()
print(sum(a) + (n - k) * d if n < k else sum(a[: k]))


I found an interesting problem on https://codeforces.com/problemset/problem/368/B:
Sereja has an array a, consisting of n integers a_1, a_2, ..., a_{n}. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l_1, l_2, ..., l_{m} (1 ≤ l_{i} ≤ n). For each number l_{i} he wants to know how many distinct numbers are staying on the positions l_{i}, l_{i} + 1, ..., n. Formally, he want to find the number of distinct numbers among a_{l}_{i}, a_{l}_{i} + 1, ..., a_{n}.?

Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each l_{i}.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 10^5). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5) — the array elements.

Next m lines contain integers l_1, l_2, ..., l_{m}. The i-th line contains integer l_{i} (1 ≤ l_{i} ≤ n).

-----Output-----

Print m lines — on the i-th line print the answer to the number l_{i}.

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

Output
6
6
6
6
6
5
4
3
2
1

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

import sys
input = lambda: sys.stdin.readline()
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
mark = [0] * 100001
ans = [0] * 100001
for i in range(n-1, -1, -1):
	ans[i] = ans[i+1] + 1 - mark[a[i]]
	mark[a[i]] = 1
for i in range(m):
	print(ans[int(input())-1])


I found an interesting problem on https://codeforces.com/problemset/problem/370/A:
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8 × 8 table. A field is represented by a pair of integers (r, c) — the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules:  A rook moves any number of fields horizontally or vertically.  A bishop moves any number of fields diagonally.  A king moves one field in any direction — horizontally, vertically or diagonally.  [Image] The pieces move like that

Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field (r_1, c_1) to field (r_2, c_2)? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem.

-----Input-----

The input contains four integers r_1, c_1, r_2, c_2 (1 ≤ r_1, c_1, r_2, c_2 ≤ 8) — the coordinates of the starting and the final field. The starting field doesn't coincide with the final one.

You can assume that the chessboard rows are numbered from top to bottom 1 through 8, and the columns are numbered from left to right 1 through 8.

-----Output-----

Print three space-separated integers: the minimum number of moves the rook, the bishop and the king (in this order) is needed to move from field (r_1, c_1) to field (r_2, c_2). If a piece cannot make such a move, print a 0 instead of the corresponding number.

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

Output
2 1 3

Input
5 5 5 6

Output
1 0 1

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

def stessocolore(x1,y1,x2,y2):
    if (x1+y1)%2 == (x2+y2)%2:
        return True
    else:
        return False
x1, y1, x2, y2 = map(int, input().split())
if x1 == x2 or y1 == y2:
    rook = 1
else:
    rook = 2
king = max([abs(x1-x2),abs(y1-y2)])
if stessocolore(x1,y1,x2,y2):
    if (x1-y1) == (x2-y2) or x1+y1 == x2+y2:
        bish = 1
    else:
        bish = 2
else:
    bish = 0

print(rook, bish, king)


I found an interesting problem on https://codeforces.com/problemset/problem/370/B:
Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains m_{i} numbers.

During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct.

You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 100) — the number of the players. Then follow n lines, each line describes a player's card. The line that describes a card starts from integer m_{i} (1 ≤ m_{i} ≤ 100) that shows how many numbers the i-th player's card has. Then follows a sequence of integers a_{i}, 1, a_{i}, 2, ..., a_{i}, m_{i} (1 ≤ a_{i}, k ≤ 100) — the numbers on the i-th player's card. The numbers in the lines are separated by single spaces.

It is guaranteed that all the numbers on each card are distinct.

-----Output-----

Print n lines, the i-th line must contain word "YES" (without the quotes), if the i-th player can win, and "NO" (without the quotes) otherwise.

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

Output
YES
NO
YES

Input
2
1 1
1 1

Output
NO
NO

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

n = int(input())
p = list()
for i in range(n):
	p.append(set([int(x) for x in input().split()[1:]]))
for i in range(n):
	for j in range(n):
		if i != j:
			if p[i].issuperset(p[j]):
				print("NO")
				break
	else:
		print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/370/C:
A Christmas party in city S. had n children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to m, and the children are numbered from 1 to n. Then the i-th child has both mittens of color c_{i}.

The Party had Santa Claus ('Father Frost' in Russian), his granddaughter Snow Girl, the children danced around the richly decorated Christmas tree. In fact, everything was so bright and diverse that the children wanted to wear mittens of distinct colors. The children decided to swap the mittens so that each of them got one left and one right mitten in the end, and these two mittens were of distinct colors. All mittens are of the same size and fit all the children.

The children started exchanging the mittens haphazardly, but they couldn't reach the situation when each child has a pair of mittens of distinct colors. Vasily Petrov, the dad of one of the children, noted that in the general case the children's idea may turn out impossible. Besides, he is a mathematician and he came up with such scheme of distributing mittens that the number of children that have distinct-colored mittens was maximum. You task is to repeat his discovery. Note that the left and right mittens are different: each child must end up with one left and one right mitten.

-----Input-----

The first line contains two integers n and m — the number of the children and the number of possible mitten colors (1 ≤ n ≤ 5000, 1 ≤ m ≤ 100). The second line contains n integers c_1, c_2, ... c_{n}, where c_{i} is the color of the mittens of the i-th child (1 ≤ c_{i} ≤ m).

-----Output-----

In the first line, print the maximum number of children who can end up with a distinct-colored pair of mittens. In the next n lines print the way the mittens can be distributed in this case. On the i-th of these lines print two space-separated integers: the color of the left and the color of the right mitten...

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

3

def readln(): return tuple(map(int, input().split()))

n, m = readln()
cnt = [0] * (m + 1)
for c in readln():
    cnt[c] += 1
ans = [0] * n
j = 0
for _ in range(1, m + 1):
    v = max(cnt)
    i = cnt.index(v)
    while cnt[i]:
        ans[j] = i
        cnt[i] -= 1
        j += 2
        if j >= n:
            j = 1
print(len([1 for i in range(n) if ans[i] != ans[(i + 1) % n]]))
for i in range(n):
    print(ans[i], ans[(i + 1) % n])


I found an interesting problem on https://codeforces.com/problemset/problem/370/D:
Innocentius has a problem — his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus.

Innocentius is touch-typing a program that paints a white square one-pixel wide frame on the black screen. As the monitor is broken, some pixels that should be white remain black. Polycarpus should look at what the program displayed on the screen and guess the position and size of the frame Innocentius has painted. Polycarpus doesn't like the game but Innocentius persuaded brother to play as "the game is good for the imagination and attention".

Help Polycarpus, automatize his part in the gaming process. Write the code that finds such possible square frame that:  the frame's width is 1 pixel,  the frame doesn't go beyond the borders of the screen,  all white pixels of the monitor are located on the frame,  of all frames that satisfy the previous three conditions, the required frame must have the smallest size.

Formally, a square frame is represented by such pixels of the solid square, that are on the square's border, that is, are not fully surrounded by the other pixels of the square. For example, if the frame's size is d = 3, then it consists of 8 pixels, if its size is d = 2, then it contains 4 pixels and if d = 1, then the frame is reduced to a single pixel.

-----Input-----

The first line contains the resolution of the monitor as a pair of integers n, m (1 ≤ n, m ≤ 2000). The next n lines contain exactly m characters each — the state of the monitor pixels at the moment of the game. Character "." (period, ASCII code 46) corresponds to the black pixel, and character "w" (lowercase English letter w) corresponds to the white pixel. It is guaranteed that at least one pixel of the monitor is white.

-----Output-----

Print the monitor screen. Represent the sought frame by characters "+" (the "plus" character). The pixels that has become...

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

from itertools import chain
# To draw square: if point isn't 'w', draw '+'
def draw_square(scr, square_a, ymin, xmin):
    for i in range(square_a + 1):
        if scr[ymin][xmin + i] != 'w':
            scr[ymin] = scr[ymin][:xmin + i] + '+' + scr[ymin][xmin + i + 1:]
        if scr[ymin + square_a][xmin + i] != 'w':
            scr[ymin + square_a] = scr[ymin + square_a][:xmin + i] + '+' + scr[ymin + square_a][xmin + i + 1:]
        if scr[ymin + i][xmin] != 'w':
            scr[ymin + i] = scr[ymin + i][:xmin] + '+' + scr[ymin + i][xmin + 1:]
        if scr[ymin + i][xmin + square_a] != 'w':
            scr[ymin + i] = scr[ymin + i][:xmin + square_a] + '+' + scr[ymin + i][xmin + square_a + 1:]
    return scr
# To find the side length of a square, and if there is some point beside the edge of a square it'll print '-1'
def find_a(pixel, y, x):
    ymax = xmax = 0
    ymin = y
    xmin = x
    ymaxl = []
    yminl = []
    xmaxl = []
    xminl = []
    count_pixel = len(pixel) // 2
    for i in range(count_pixel):
        if ymax < pixel[2 * i]:
            ymax = pixel[2 * i]
        if ymin > pixel[2 * i]:
            ymin = pixel[2 * i]
        if xmax < pixel[2 * i + 1]:
            xmax = pixel[2 * i + 1]
        if xmin > pixel[2 * i + 1]:
            xmin = pixel[2 * i + 1]
    for i in range(count_pixel):
        f = True
        if pixel[2 * i] == ymax:
            f = False
            ymaxl.append(pixel[2 * i])
            ymaxl.append(pixel[2 * i + 1])
        if pixel[2 * i] == ymin:
            f = False
            yminl.append(pixel[2 * i])
            yminl.append(pixel[2 * i + 1])
        if pixel[2 * i + 1] == xmax:
            f = False
            xmaxl.append(pixel[2 * i])
            xmaxl.append(pixel[2 * i + 1])
        if pixel[2 * i + 1] == xmin:
            f = False
            xminl.append(pixel[2 * i])
            xminl.append(pixel[2 * i + 1])
        # if some point beside the edge of a square: like the 'x'
        # 5 7
        # .......
        # .+++...
        # .+x+...
  ...


I found an interesting problem on https://codeforces.com/problemset/problem/371/A:
This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2.

Array a is k-period if its length is divisible by k and there is such array b of length k, that a is represented by array b written exactly $\frac{n}{k}$ times consecutively. In other words, array a is k-periodic, if it has period of length k.

For example, any array is n-periodic, where n is the array length. Array [2, 1, 2, 1, 2, 1] is at the same time 2-periodic and 6-periodic and array [1, 2, 1, 1, 2, 1, 1, 2, 1] is at the same time 3-periodic and 9-periodic.

For the given array a, consisting only of numbers one and two, find the minimum number of elements to change to make the array k-periodic. If the array already is k-periodic, then the required value equals 0.

-----Input-----

The first line of the input contains a pair of integers n, k (1 ≤ k ≤ n ≤ 100), where n is the length of the array and the value n is divisible by k. The second line contains the sequence of elements of the given array a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 2), a_{i} is the i-th element of the array.

-----Output-----

Print the minimum number of array elements we need to change to make the array k-periodic. If the array already is k-periodic, then print 0.

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

Output
1

Input
8 4
1 1 2 1 1 1 2 1

Output
0

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

Output
3

-----Note-----

In the first sample it is enough to change the fourth element from 2 to 1, then the array changes to [2, 1, 2, 1, 2, 1].

In the second sample, the given array already is 4-periodic.

In the third sample it is enough to replace each occurrence of number two by number one. In this case the array will look as [1, 1, 1, 1, 1, 1, 1, 1, 1] — this array is simultaneously 1-, 3- and 9-periodic.

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

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

print(sum(min(x.count(1), x.count(2)) for x in (a[i::k] for i in range(k))))


I found an interesting problem on https://codeforces.com/problemset/problem/371/B:
Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox, how are you going to do that?", the curious bears asked. "It's easy", said the fox. "If the mass of a certain piece is divisible by two, then I can eat exactly a half of the piece. If the mass of a certain piece is divisible by three, then I can eat exactly two-thirds, and if the mass is divisible by five, then I can eat four-fifths. I'll eat a little here and there and make the pieces equal".

The little bears realize that the fox's proposal contains a catch. But at the same time they realize that they can not make the two pieces equal themselves. So they agreed to her proposal, but on one condition: the fox should make the pieces equal as quickly as possible. Find the minimum number of operations the fox needs to make pieces equal.

-----Input-----

The first line contains two space-separated integers a and b (1 ≤ a, b ≤ 10^9).

-----Output-----

If the fox is lying to the little bears and it is impossible to make the pieces equal, print -1. Otherwise, print the required minimum number of operations. If the pieces of the cheese are initially equal, the required number is 0.

-----Examples-----
Input
15 20

Output
3

Input
14 8

Output
-1

Input
6 6

Output
0

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

import sys
#sys.stdin = open('prefrev.in', 'r')
#sys.stdout = open('prefrev.out', 'w')
n, m = map(int, input().split())
divs=[2,3,5]
ar=[0]*6
br=[0]*6
tn=n; tm=m
for i in divs:
    while tn % i == 0 and tn > 0:
        ar[i] += 1
        tn //= i
    while tm % i == 0 and tm > 0:
        br[i] += 1
        tm //= i
print
if tn != tm:
    print('-1')
else:
    #print('ok')
    ans = 2e9
    for i in range(min(br[2], ar[2])+1):
        for j in range(min(br[3], ar[3])+1):
            for k in range(min(br[5],ar[5])+1):
                if ar[2]-i+br[2]-i+ar[3]-j+br[3]-j+ar[5]-k+br[5]-k<ans:
                    ans=ar[2]-i+br[2]-i+ar[3]-j+br[3]-j+ar[5]-k+br[5]-k
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/371/C:
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (bread), 'S' (sausage) и 'C' (cheese). The ingredients in the recipe go from bottom to top, for example, recipe "ВSCBS" represents the hamburger where the ingredients go from bottom to top as bread, sausage, cheese, bread and sausage again.

Polycarpus has n_{b} pieces of bread, n_{s} pieces of sausage and n_{c} pieces of cheese in the kitchen. Besides, the shop nearby has all three ingredients, the prices are p_{b} rubles for a piece of bread, p_{s} for a piece of sausage and p_{c} for a piece of cheese.

Polycarpus has r rubles and he is ready to shop on them. What maximum number of hamburgers can he cook? You can assume that Polycarpus cannot break or slice any of the pieces of bread, sausage or cheese. Besides, the shop has an unlimited number of pieces of each ingredient.

-----Input-----

The first line of the input contains a non-empty string that describes the recipe of "Le Hamburger de Polycarpus". The length of the string doesn't exceed 100, the string contains only letters 'B' (uppercase English B), 'S' (uppercase English S) and 'C' (uppercase English C).

The second line contains three integers n_{b}, n_{s}, n_{c} (1 ≤ n_{b}, n_{s}, n_{c} ≤ 100) — the number of the pieces of bread, sausage and cheese on Polycarpus' kitchen. The third line contains three integers p_{b}, p_{s}, p_{c} (1 ≤ p_{b}, p_{s}, p_{c} ≤ 100) — the price of one piece of bread, sausage and cheese in the shop. Finally, the fourth line contains integer r (1 ≤ r ≤ 10^12) — the number of rubles Polycarpus has.

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

-----Output-----

Print the maximum number of hamburgers...

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

recipe = input()
rb = rs = rc = 0
nb, ns, nc = list(map(int, input().split()))
pb, ps, pc = list(map(int, input().split()))
r = int(input())

for ch in recipe:
  if ch == "B":
    rb += 1
  elif ch == "S":
    rs += 1
  else:
    rc += 1

a = 0
b = 10 ** 12 + 1000

def doable(n):
  return r >= pb*max(0, rb*n-nb) + ps*max(0, rs*n-ns) + pc*max(0, rc*n-nc)

res = 0
while a <= b:
  m = (a+b) // 2
  if doable(m):
    res = m
    a = m + 1
  else:
    b = m - 1

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/371/D:
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is a_{i} liters. [Image]

Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.

Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries:  Add x_{i} liters of water to the p_{i}-th vessel;  Print the number of liters of water in the k_{i}-th vessel.

When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.

-----Input-----

The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·10^5). The second line contains n integers a_1, a_2, ..., a_{n} — the vessels' capacities (1 ≤ a_{i} ≤ 10^9). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·10^5). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 p_{i} x_{i}", the query of the second type is represented as "2 k_{i}" (1 ≤ p_{i} ≤ n, 1 ≤ x_{i} ≤ 10^9, 1 ≤ k_{i} ≤ n).

-----Output-----

For each query, print on a single line the number of liters of water in the corresponding vessel.

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

Output
4
5
8

Input
3
5 10 8
6
1 1 12
2 2
1 1 6
1 3 2
2 2
2 3

Output
7
10
5

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

n=int(input());
water=(n+2)*[0];
vol=[int(i) for i in input().split()];
trace=(n+2)*[0];
next = [i+1 for i in range(n+2)];
m=int(input());
out=[]
for i in range(m):
	c=[int(i) for i in input().split()];
	if c[0]==1 :
		w=c[2];
		k=c[1]-1;
		r=0;
		while((w>0)and(k<n)):
			if(w<=vol[k]-water[k]):
				water[k]=water[k]+w;
				break;
			else:
				w=w-(vol[k]-water[k]);
				water[k]=vol[k];
				trace[r]=k;
				r=r+1;
				k=next[k];
		for j in range(r):
			next[trace[j]]=k;
	if c[0]==2:
		out.append(water[c[1]-1]);
for i in out:
	print(i)


I found an interesting problem on https://codeforces.com/problemset/problem/371/E:
Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!

The President of Berland was forced to leave only k of the currently existing n subway stations.

The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate x_{i}. In such case the distance between stations i and j is calculated by a simple formula |x_{i} - x_{j}|.

Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!

Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is $\frac{n \cdot(n - 1)}{2}$) and divided by the speed of the train.

Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.

-----Input-----

The first line of the input contains integer n (3 ≤ n ≤ 3·10^5) — the number of the stations before the innovation. The second line contains the coordinates of the stations x_1, x_2, ..., x_{n} ( - 10^8 ≤ x_{i} ≤ 10^8). The third line contains integer k (2 ≤ k ≤ n - 1) — the number of stations after the innovation.

The station coordinates are distinct and not necessarily sorted.

-----Output-----

Print a sequence of k distinct integers t_1, t_2, ..., t_{k} (1 ≤ t_{j} ≤ n) — the numbers of the stations that should be left after the innovation in arbitrary order. Assume that...

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

from sys import stdin

n = int(stdin.readline())
a = [int(x) for x in stdin.readline().split()]
a = sorted([(a[x],str(x+1)) for x in range(n)])
k = int(stdin.readline())

sums = [0]
for x in a:
    sums.append(sums[-1]+x[0])

total = 0
s = 0

for x in range(k):
    total += a[x][0]*x-s
    s += a[x][0]

low = total
lowInd = 0

#print(total)

for x in range(n-k):
    s -= a[x][0]
    total -= s-a[x][0]*(k-1)
    total += a[x+k][0]*(k-1)-s
    s += a[x+k][0]
    if total < low:
        low = total
        lowInd = x+1

out = []

for x in range(lowInd,lowInd+k):
    out.append(a[x][1])
print(' '.join(out))


I found an interesting problem on https://codeforces.com/problemset/problem/373/A:
Cucumber boy is fan of Kyubeat, a famous music game.

Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel.

Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail.

You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing.

-----Input-----

The first line contains a single integer k (1 ≤ k ≤ 5) — the number of panels Cucumber boy can press with his one hand.

Next 4 lines contain 4 characters each (digits from 1 to 9, or period) — table of panels. If a digit i was written on the panel, it means the boy has to press that panel in time i. If period was written on the panel, he doesn't have to press that panel.

-----Output-----

Output "YES" (without quotes), if he is able to press all the panels in perfect timing. If not, output "NO" (without quotes).

-----Examples-----
Input
1
.135
1247
3468
5789

Output
YES

Input
5
..1.
1111
..1.
..1.

Output
YES

Input
1
....
12.1
.2..
.2..

Output
NO

-----Note-----

In the third sample boy cannot press all panels in perfect timing. He can press all the panels in timing in time 1, but he cannot press the panels in time 2 in timing with his two hands.

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

k = int(input())
s = ''
n = list()
for i in range(4):
    a = input()
    s = s + a
for i in range(1,10):
    n.append(s.count(str(i)))
if max(n)> 2*k:
    print ('NO')
else:
    print ('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/373/B:
We'll define S(n) for positive integer n as follows: the number of the n's digits in the decimal base. For example, S(893) = 3, S(114514) = 6.

You want to make a consecutive integer sequence starting from number m (m, m + 1, ...). But you need to pay S(n)·k to add the number n to the sequence.

You can spend a cost up to w, and you want to make the sequence as long as possible. Write a program that tells sequence's maximum length.

-----Input-----

The first line contains three integers w (1 ≤ w ≤ 10^16), m (1 ≤ m ≤ 10^16), k (1 ≤ k ≤ 10^9).

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

-----Output-----

The first line should contain a single integer — the answer to the problem.

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

Output
9

Input
77 7 7

Output
7

Input
114 5 14

Output
6

Input
1 1 2

Output
0

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

w, m, k = map(int, input().split())
L = len(str(m))
end = m
flag = False
while True:
    if w > (10 ** L - end) * k * L:
        w -= (10 ** L - end) * k * L
        end = 10 ** L
        L += 1
        #if w < L * k:
            #print(end - m)
            #flag = True
            #break
        #else:
            #w -= L * k
            #end = 10 ** L + 1
    else:
        end += w // (L * k)
        break

if not(flag):
    print(end - m)


I found an interesting problem on https://codeforces.com/problemset/problem/374/A:
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n × m chessboard, a very tasty candy and two numbers a and b.

Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types:

  move the candy from position (x, y) on the board to position (x - a, y - b);  move the candy from position (x, y) on the board to position (x + a, y - b);  move the candy from position (x, y) on the board to position (x - a, y + b);  move the candy from position (x, y) on the board to position (x + a, y + b).

Naturally, Dima doesn't allow to move the candy beyond the chessboard borders.

Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position (i, j) to one of the chessboard corners. Help them cope with the task!

-----Input-----

The first line of the input contains six integers n, m, i, j, a, b (1 ≤ n, m ≤ 10^6; 1 ≤ i ≤ n; 1 ≤ j ≤ m; 1 ≤ a, b ≤ 10^6).

You can assume that the chessboard rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. Position (i, j) in the statement is a chessboard cell on the intersection of the i-th row and the j-th column. You can consider that the corners are: (1, m), (n, 1), (n, m), (1, 1).

-----Output-----

In a single line print a single integer — the minimum number of moves needed to get the candy.

If Inna and the pony cannot get the candy playing by Dima's rules, print on a single line "Poor Inna and pony!" without the quotes.

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

Output
2

Input
5 5 2 3 1 1

Output
Poor Inna and pony!

-----Note-----

Note to sample 1:

Inna and the pony can move the candy to position (1 + 2,...

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

3

def readln(): return list(map(int, input().split()))

n, m, i, j, a, b = readln()

def solve(w, h):
    if w == 0 and h == 0:
        return 0
    if w == 0 and a < n and h % 2 == 0:
        return h
    if h == 0 and b < m and w % 2 == 0:
        return w
    if w == 0 or h == 0:
        return 1 << 30
    if (w + h) % 2 == 0:
        return max(w, h)
    return 1 << 30

ans = min([1 << 30] + [solve(abs(i - p) // a, abs(j - q) // b) for p, q in ((1, 1), (1, m), (n, 1), (n, m)) if abs(i - p) % a == 0 and abs(j - q) % b == 0])
print('Poor Inna and pony!' if ans == 2**30 else ans)


I found an interesting problem on https://codeforces.com/problemset/problem/374/B:
Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.

Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9.

For instance, Inna can alter number 14545181 like this: 14545181 → 1945181 → 194519 → 19919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine.

Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.

-----Input-----

The first line of the input contains integer a (1 ≤ a ≤ 10^100000). Number a doesn't have any zeroes.

-----Output-----

In a single line print a single integer — the answer to the problem. It is guaranteed that the answer to the problem doesn't exceed 2^63 - 1.

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

-----Examples-----
Input
369727

Output
2

Input
123456789987654321

Output
1

Input
1

Output
1

-----Note-----

Notes to the samples

In the first sample Inna can get the following numbers: 369727 → 99727 → 9997, 369727 → 99727 → 9979.

In the second sample, Inna can act like this: 123456789987654321 → 12396789987654321 → 1239678998769321.

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


I found an interesting problem on https://codeforces.com/problemset/problem/374/C:
Inna and Dima bought a table of size n × m in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A".

Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows:

  initially, Inna chooses some cell of the table where letter "D" is written;  then Inna can move to some side-adjacent table cell that contains letter "I"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter "M"; then she can go to a side-adjacent cell that contains letter "A". Then Inna assumes that she has gone through her sweetheart's name;  Inna's next move can be going to one of the side-adjacent table cells that contains letter "D" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter "D" she always goes to the letter "I", from the letter "I" she always goes the to letter "M", from the letter "M" she always goes to the letter "A", and from the letter "A" she always goes to the letter "D".

Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.

-----Input-----

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

Then follow n lines that describe Inna and Dima's table. Each line contains m characters. Each character is one of the following four characters: "D", "I", "M", "A".

Note that it is not guaranteed that the table contains at least one letter "D".

-----Output-----

If Inna cannot go through name DIMA once, print on a single line "Poor Dima!" without the quotes. If there is the infinite number of names DIMA Inna can go through, print "Poor Inna!" without the quotes. Otherwise print a single integer — the maximum number of times Inna can go through name...

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

import sys
n, m = map(int, input().split())
m += 1
d = {'I': 0, 'M': 1, 'A': 2, 'D': 3, '\n': -7}
t = list(map(d.get, sys.stdin.read())) + [-7] * m
p = [[] for q in t]
c = [0] * len(t)
for a in range(n * m):
    for b in (a - m, a + m, a - 1, a + 1):
        if abs(t[b] - t[a] + 1) == 2:
            p[a].append(b)
            c[b] += 1
s = [i for i, q in enumerate(c) if not q]
while s:
    a = s.pop()
    for b in p[a]:
        t[b] = max(t[b], t[a] + 1)
        c[b] -= 1
        if c[b] == 0: s.append(b)
k = max(t) - 2 >> 2
print('Poor Inna!' if any(c) else k if k > 0 else 'Poor Dima!')


I found an interesting problem on https://codeforces.com/problemset/problem/375/A:
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.

Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.

-----Input-----

The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 10^6 characters.

-----Output-----

Print a number in the decimal notation without leading zeroes — the result of the permutation.

If it is impossible to rearrange the digits of the number a in the required manner, print 0.

-----Examples-----
Input
1689

Output
1869

Input
18906

Output
18690

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

ans=[1,6,8,9]
rem=[]
from collections import *
al=defaultdict(int)
for i in range(len(ans)):
    for j in range(len(ans)):
        for m in range(len(ans)):
            for t in range(len(ans)):
                re=[i,j,m,t]
                if(len(set(re))==4):
                    q=pow(10,3)*ans[i]+(pow(10,2)*ans[j])+(pow(10,1)*ans[m])+(ans[t])
                    if(al[q%7]==0):

                        rem.append([q%7,q])

                        al[q%7]=1

s=input()
rem.sort()
ans=[]
for i in range(len(s)):
    ans.append(int(s[i]))
count=0
ans.remove(1)
ans.remove(6)
ans.remove(8)
ans.remove(9)
i=0

while(i<len(ans)):

    if(i==0):
        while(i<len(ans) and ans[i]==0):
            count+=1
            i+=1
        i+=1
    else:
        i+=1
temp=[]
for i in range(count,len(ans)):
    temp.append(ans[i])
fin=0
if(len(temp)==0):
    s=str(rem[0][1])+'0'*count
    print(s)
    return
else:
    for i in range(len(temp)):
        fin=fin+(pow(10,len(temp)-i-1,7)*(temp[i]%7)%7)
        fin%=7

    if(fin==0):
        m=''.join(map(str,temp))+str(rem[fin][1])+('0'*count)
    if(fin==1):
         m=''.join(map(str,temp))+str(rem[3][1])+('0'*count)
    if(fin==2):
         m=''.join(map(str,temp))+str(rem[6][1])+('0'*count)

    if(fin==3):
        m=''.join(map(str,temp))+str(rem[2][1])+('0'*count)
    if(fin==4):
        m=''.join(map(str,temp))+str(rem[5][1])+('0'*count)
    if(fin==5):
        m=''.join(map(str,temp))+str(rem[1][1])+('0'*count)
    if(fin==6):
        m=''.join(map(str,temp))+str(rem[4][1])+('0'*count)

    print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/376/A:
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.

The decoding of the lever description is given below.

  If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.  If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.  If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.

Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.

-----Input-----

The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 10^6), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.

To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.

-----Output-----

Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.

-----Examples-----
Input
=^==

Output
balance

Input
9===^==1

Output
left

Input
2==^7==

Output
right

Input
41^52==

Output
balance

-----Note-----

As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.

The pictures to the examples:

 [Image]

 [Image]

 [Image]

 $\Delta \Delta \Delta \Delta$

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

s = input()
for i in range(len(s)):
    if s[i] == '^':
        o = i
l = s[0:o]
r = s[o+1:len(s)]
l_sum = r_sum = 0
for i in range(len(l)):
    if not (l[i] == '='):
        l_sum += int(l[i]) * (len(l) - i)

for i in range(len(r)):
    if not (r[i] == '='):
        r_sum += int(r[i]) * (i+1)# + 1)
if l_sum < r_sum:
    print('right')
elif l_sum > r_sum:
    print('left')
else:
    print('balance')


I found an interesting problem on https://codeforces.com/problemset/problem/376/B:
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.

This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 100; 0 ≤ m ≤ 10^4). The next m lines contain the debts. The i-th line contains three integers a_{i}, b_{i}, c_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}; 1 ≤ c_{i} ≤ 100), which mean that person a_{i} owes person b_{i} c_{i} rubles.

Assume that the people are numbered by integers from 1 to n.

It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x).

-----Output-----

Print a single integer — the minimum sum of debts in the optimal rearrangement.

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

Output
10

Input
3 0

Output
0

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

Output
0

-----Note-----

In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10.

In the second sample, there are no debts.

In the third sample, you can annul all the debts.

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

n,m=list(map(int,input().split()))
d=[0]*n
for i in range(m):
    a,b,c=list(map(int,input().split()))
    d[a-1]-=c
    d[b-1]+=c
ans=0
for i in range(n):
    if d[i]>0: ans+=d[i]
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/377/A:
Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.

Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.

-----Input-----

The first line contains three integers n, m, k (1 ≤ n, m ≤ 500, 0 ≤ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.

Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.

-----Output-----

Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").

It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.

-----Examples-----
Input
3 4 2
#..#
..#.
#...

Output
#.X#
X.#.
#...

Input
5 4 5
#...
#.#.
.#..
...#
.#.#

Output
#XXX
#X#.
X#..
...#
.#.#

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

from collections import deque,namedtuple
dx = [0,0,1,-1]
dy = [1,-1,0,0]

def main():
    n,m,limit = map(int,input().split())
    a,sx,sy,tot = [],0,0,0
    for i in range(n):
        s,t = input(),[]
        for j,c in enumerate(s):
            if c == '.':
                sx,sy = i,j
                tot += 1
                c = 'X'
            t.append(c)
        a.append(t[:])

    dq,done = deque([(sx,sy)]),0
    while len(dq) > 0:
        now = dq.pop()
        if done >= tot - limit:
            break
        if(a[now[0]][now[1]] == 'X'):
            done += 1
        a[now[0]][now[1]] = '.'
        for i in range(4):
            tx,ty = dx[i] + now[0],dy[i] + now[1]
            if 0 <= tx < n and 0 <= ty < m and a[tx][ty] == 'X':
                dq.append((tx,ty))
    for i in a:
        print("".join(i))

def __starting_point():
    main()
__starting_point()