I found an interesting problem on https://codeforces.com/problemset/problem/439/C:
Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?

Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous).

If it is possible to partition the array, also give any possible way of valid partitioning.

-----Input-----

The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 10^5; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes).

If the required partition exists, print k lines after the first line. The i^{th} of them should contain the content of the i^{th} part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum.

As there can be multiple partitions, you are allowed to print any valid partition.

-----Examples-----
Input
5 5 3
2 6 10 5 9

Output
YES
1 9
1 5
1 10
1 6
1 2

Input
5 5 3
7 14 2 9 5

Output
NO

Input
5 3 1
1 2 3 7 5

Output
YES
3 5 1 3
1 7
1 2

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

n,k,p = list(map(int,input().split()))
l = list(map(int,input().split()))
even = list([x for x in l if x %2 ==0])
odd = list([x for x in l if x%2 == 1])

if (len(odd) - (k-p))% 2!=0:
    print("NO")
    return
ans = [[] for _ in range(k)]
for i in range(k-p):
    if odd:
        ans[i].append(odd.pop())
    else:
        print("NO")
        return

for i in range(k-p,k):
    if even:
        ans[i].append(even.pop())
    elif len(odd)>=2:
        ans[i].append(odd.pop())
        ans[i].append(odd.pop())
    else:
        print("NO")
        return

ans[0] += even + odd
print("YES")
for i in ans:
    print(len(i)," ".join(map(str,i)))


I found an interesting problem on https://codeforces.com/problemset/problem/439/D:
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother.

As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b.

Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.

You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.

-----Input-----

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 10^5). The second line will contain n space-separated integers representing content of the array a (1 ≤ a_{i} ≤ 10^9). The third line will contain m space-separated integers representing content of the array b (1 ≤ b_{i} ≤ 10^9).

-----Output-----

You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.

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

Output
3

Input
3 2
1 2 3
3 4

Output
4

Input
3 2
4 5 6
1 2

Output
0

-----Note-----

In example 1, you can increase a_1 by 1 and decrease b_2 by 1 and then again decrease b_2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.

In example 3, you don't need to do any operation, Devu's condition is already satisfied.

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

'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
# mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

file=1

def solve():

    n,m=mi()
    a=li()
    b=li()
    a.sort()
    b.sort()
    if b[-1]<=a[0]:
        print(0)
        return
    pre=[0]*n
    for i in range(1,n):
        pre[i]+=pre[i-1]
        pre[i]+=i*(a[i]-a[i-1])

    suff=[0]*m
    for i in range(m-2,-1,-1):
        suff[i]+=suff[i+1]
        suff[i]+=(m-i-1)*(b[i+1]-b[i])

    def fun(m1):
        x=bisect(a,m1)-1
        y=bisect(b,m1)-1
        ans=0
        if x==n:
            x-=1
        ans+=pre[x]
        ans+=(m1-a[x])*(x+1)
        # print(x,ans)
        if y>=(m-1):
            return ans
        if y==0:
            y-=1
        ans+=(b[y+1]-m1)*(m-y-1)
        ans+=suff[y+1]
        return ans

    l=1
    r=int(1e9+5)
    while(l<=r):
        mid=l+(r-l)//2
        x=fun(mid)
        if mid==1:
            x1=fun(mid+1)
            if(x>x1):
                l=mid+1
                ans=x1
            else:
                # print(mid)
                print(max(x,0))
                return

        x1=fun(mid-1)
        x2=fun(mid+1)
        if(x1<x2):
            if(x1<x):
                r=mid-1
                ans=x1
            else:
                # print(mid)
                print(max(x,0))
                return
        else:
            if(x2<x):
                l=mid+1
        ...


I found an interesting problem on https://codeforces.com/problemset/problem/439/E:
Today is Devu's birthday. For celebrating the occasion, he bought n sweets from the nearby market. He has invited his f friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each friend.

He wants to celebrate it in a unique style, so he would like to ensure following condition for the distribution of sweets. Assume that he has distributed n sweets to his friends such that i^{th} friend is given a_{i} sweets. He wants to make sure that there should not be any positive integer x > 1, which divides every a_{i}.

Please find the number of ways he can distribute sweets to his friends in the required way. Note that the order of distribution is important, for example [1, 2] and [2, 1] are distinct distributions. As the answer could be very large, output answer modulo 1000000007 (10^9 + 7).

To make the problem more interesting, you are given q queries. Each query contains an n, f pair. For each query please output the required number of ways modulo 1000000007 (10^9 + 7).

-----Input-----

The first line contains an integer q representing the number of queries (1 ≤ q ≤ 10^5). Each of the next q lines contains two space space-separated integers n, f (1 ≤ f ≤ n ≤ 10^5).

-----Output-----

For each query, output a single integer in a line corresponding to the answer of each query.

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

Output
2
6
9
10
20

-----Note-----

For first query: n = 6, f = 2. Possible partitions are [1, 5] and [5, 1].

For second query: n = 7, f = 2. Possible partitions are [1, 6] and [2, 5] and [3, 4] and [4, 3] and [5, 3] and [6, 1]. So in total there are 6 possible ways of partitioning.

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

import itertools
import functools
import operator

N = 100001
P = 10**9 + 7

fact = [1]
for i in range(1, N):
	fact.append(fact[-1] * i % P)

inv = [0, 1]
for i in range(2, N):
	inv.append(P - P // i * inv[P % i] % P)
inv_fact = [1]
for i in range(1, N):
	inv_fact.append(inv_fact[-1] * inv[i] % P)

least_div = [-1] * N
primes = []

for p in range(2, N):
	if least_div[p] == -1:
		primes.append(p)
		least_div[p] = p
	ldiv = least_div[p]
	for mult in primes:
		mark = mult * p
		if (mult > ldiv) or (mark >= N):
			break
		least_div[mark] = mult

t = int(input())

def powerset(iterable):
    s = list(iterable)
    return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s) + 1))

@functools.lru_cache(maxsize = None)
def factor(n):
	ret = []
	while n != 1:
		tmp = least_div[n]
		if not(ret and ret[-1] == tmp):
			ret.append(tmp)
		n //= tmp
	return ret

@functools.lru_cache(maxsize = None)
def solve(n, k):
	divs = factor(n)
	# print(divs)
	ret = 0
	for subset in powerset(divs):
		div = functools.reduce(operator.mul, subset, 1)
		# print(div, f(n // div, k))
		if n // div >= k:
			tmp = fact[n // div - 1] * inv_fact[n // div - k] % P * inv_fact[k - 1] % P
			ret += (-1 if len(subset) % 2 == 1 else 1) * tmp
			ret %= P
	return ret

for _ in range(t):
	n, k = map(int, input().split())
	print(solve(n, k))


I found an interesting problem on https://codeforces.com/problemset/problem/440/A:
Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom "Graph Theory". In total, the season has n episodes, numbered with integers from 1 to n.

Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which episode has Polycaprus forgotten to watch?

-----Input-----

The first line of the input contains integer n (2 ≤ n ≤ 100000) — the number of episodes in a season. Assume that the episodes are numbered by integers from 1 to n.

The second line contains n - 1 integer a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — the numbers of episodes that Polycarpus has watched. All values of a_{i} are distinct.

-----Output-----

Print the number of the episode that Polycarpus hasn't watched.

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

Output
4

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

"""
Codeforces Testing Round 10 Problem A

Author  : chaotic_iak
Language: Python 3.3.4
"""

def read(mode=2):
    # 0: String
    # 1: List of strings
    # 2: List of integers
    inputs = input().strip()
    if mode == 0:
        return inputs
    if mode == 1:
        return inputs.split()
    if mode == 2:
        return [int(x) for x in inputs.split()]

def write(s="\n"):
    if isinstance(s, list): s = " ".join(s)
    s = str(s)
    print(s, end="")

################################################### SOLUTION
n, = read()
a = read()
write(n*(n+1)//2 - sum(a))


I found an interesting problem on https://codeforces.com/problemset/problem/440/B:
Petya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configuration?

-----Input-----

The first line contains integer n (1 ≤ n ≤ 50000). The second line contains n non-negative numbers that do not exceed 10^9, the i-th written number is the number of matches in the i-th matchbox. It is guaranteed that the total number of matches is divisible by n.

-----Output-----

Print the total minimum number of moves.

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

Output
12

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

import itertools

n = int(input())

a = list(map(int, input().split()))
a = list(itertools.accumulate(a))

need_one = a[-1] // n

ans = 0
for i in range(len(a) - 1):
	ans += abs((i + 1) * need_one - a[i])

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/440/C:
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.

-----Input-----

The first line of the input contains integer n (1 ≤ n < 10^15).

-----Output-----

Print expected minimal number of digits 1.

-----Examples-----
Input
121

Output
6

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

n = int(input())

d = {n: 0}

u = 10 ** (len(str(n)) + 2) // 9

for i in range(len(str(n)) + 1, 0, -1):

    d, e = {}, d

    u //= 10

    for v, c in list(e.items()):

        lim = v//u

        for x in range(-1 - lim, 1 - lim):

            t = v + x * u

            d[t] = min(c + i * abs(x), d.get(t, 999))

print(d[0])

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/441/A:
Valera is a collector. Once he wanted to expand his collection with exactly one antique item.

Valera knows n sellers of antiques, the i-th of them auctioned k_{i} items. Currently the auction price of the j-th object of the i-th seller is s_{ij}. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.

Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.

-----Input-----

The first line contains two space-separated integers n, v (1 ≤ n ≤ 50; 10^4 ≤ v ≤ 10^6) — the number of sellers and the units of money the Valera has.

Then n lines follow. The i-th line first contains integer k_{i} (1 ≤ k_{i} ≤ 50) the number of items of the i-th seller. Then go k_{i} space-separated integers s_{i}1, s_{i}2, ..., s_{ik}_{i} (10^4 ≤ s_{ij} ≤ 10^6) — the current prices of the items of the i-th seller.

-----Output-----

In the first line, print integer p — the number of sellers with who Valera can make a deal.

In the second line print p space-separated integers q_1, q_2, ..., q_{p} (1 ≤ q_{i} ≤ n) — the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order.

-----Examples-----
Input
3 50000
1 40000
2 20000 60000
3 10000 70000 190000

Output
3
1 2 3

Input
3 50000
1 50000
3 100000 120000 110000
3 120000 110000 120000

Output
0

-----Note-----

In the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller.

In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him.

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

from sys import stdin

def main():
    '''
    Name KevinSS
    Code: A. Valera and Antique Items
    '''
    inp = stdin
    n, v = list(map(int, inp.readline().strip().split()))
    dicti = dict()
    sellers = list()

    for i in range(1,n+1):
        a = str(i)
        Items = [int(x) for x in inp.readline().strip().split()]
        dicti[a] = Items

    for i in range(1,n+1):
        flag = False
        for j in range(1,len(dicti[str(i)])):
            if (dicti[str(i)][j] < v) and flag == False:
                sellers.append(str(i))
                flag = True
    print(len(sellers))
    print(' '.join(sellers))

main()


I found an interesting problem on https://codeforces.com/problemset/problem/441/B:
Valera loves his garden, where n fruit trees grow.

This year he will enjoy a great harvest! On the i-th tree b_{i} fruit grow, they will ripen on a day number a_{i}. Unfortunately, the fruit on the tree get withered, so they can only be collected on day a_{i} and day a_{i} + 1 (all fruits that are not collected in these two days, become unfit to eat).

Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?

-----Input-----

The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day.

Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree.

-----Output-----

Print a single integer — the maximum number of fruit that Valera can collect.

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

Output
8

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

Output
60

-----Note-----

In the first sample, in order to obtain the optimal answer, you should act as follows.   On the first day collect 3 fruits from the 1-st tree.  On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree.  On the third day collect the remaining fruits from the 2-nd tree.

In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither.

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

total_plucked = 0
n,v = list(map(int,input().split()))
fruits = [0] * 3002
plucked = [0] * 30002
for _ in range(n):
    a,b = list(map(int,input().split()))
    fruits[a] = fruits[a] + b
for i in range(1,3002):
   plucked[i] = fruits[i - 1] if (fruits[i - 1] <= v) else v
   if(plucked[i] < v):
       pluck = fruits[i] if (fruits[i] <= v - plucked[i]) else v - plucked[i]
       plucked[i] += pluck
       fruits[i] -= pluck
   #print(fruits[i - 1],plucked[i])
   total_plucked += plucked[i]
print(total_plucked)


I found an interesting problem on https://codeforces.com/problemset/problem/441/C:
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).

Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x_1, y_1), (x_2, y_2), ..., (x_{r}, y_{r}), that:   r ≥ 2;  for any integer i (1 ≤ i ≤ r - 1) the following equation |x_{i} - x_{i} + 1| + |y_{i} - y_{i} + 1| = 1 holds;  each table cell, which belongs to the tube, must occur exactly once in the sequence.

Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled:   no pair of tubes has common cells;  each cell of the table belongs to some tube.

Help Valera to arrange k tubes on his rectangle table in a fancy manner.

-----Input-----

The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.

-----Output-----

Print k lines. In the i-th line print the description of the i-th tube: first print integer r_{i} (the number of tube cells), then print 2r_{i} integers x_{i}1, y_{i}1, x_{i}2, y_{i}2, ..., x_{ir}_{i}, y_{ir}_{i} (the sequence of table cells).

If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.

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

Output
3 1 1 1 2 1 3
3 2 1 2 2 2 3
3 3 1 3 2 3 3

Input
2 3 1

Output
6 1 1 1 2 1 3 2 3 2 2 2 1

-----Note-----

Picture for the first sample:  [Image]

Picture for the second sample:  [Image]

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

n,m,k = [int(i) for i in input().split()]
import sys
seq = []
rev = False
for i in range(n):
    l = list(zip([i+1]*m,range(1,m+1)))
    if rev:
        l.reverse()
    seq += l
    rev = not rev

for i in range(k-1):
    sys.stdout.write('2 ' + str(seq[i*2][0]) + ' ' + str(seq[i*2][1]) + ' ' + str(seq[i*2+1][0]) + ' ' + str(seq[i*2+1][1]) + '\n')

print(len(seq) - k*2 + 2,end=' ')
for a,b in seq[k*2-2:]:
    sys.stdout.write(str(a) + ' ' + str(b) + ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/442/A:
Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.

Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding n cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has).

The aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints.

A color hint goes like that: a player names some color and points at all the cards of this color.

Similarly goes the value hint. A player names some value and points at all the cards that contain the value.

Determine what minimum number of hints the other players should make for Borya to be certain about each card's color and value.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100) — the number of Borya's cards. The next line contains the descriptions of n cards. The description of each card consists of exactly two characters. The first character shows the color (overall this position can contain five distinct letters — R, G, B, Y, W). The second character shows the card's value (a digit from 1 to 5). Borya doesn't know exact order of the cards they lie in.

-----Output-----

Print a single integer — the minimum number of hints that the other players should make.

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

Output
0

Input
4
G4 R4 R3 B3

Output
2

Input
5
B1 Y1 W1 G1 R1

Output
4

-----Note-----

In the first sample Borya already knows for each card that it is a green three.

In the second sample we can show all fours and all red cards.

In the third sample you need to make hints about any four colors.

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

input()
p = {(1 << 'RGBYW'.index(c)) + (1 << int(k) + 4) for c, k in input().split()}
print(min(bin(t).count('1') for t in range(1024) if len({t & q for q in p}) == len(p)))


I found an interesting problem on https://codeforces.com/problemset/problem/442/B:
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.

Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of Andrey's friends. The second line contains n real numbers p_{i} (0.0 ≤ p_{i} ≤ 1.0) — the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point.

-----Output-----

Print a single real number — the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10^{ - 9}.

-----Examples-----
Input
4
0.1 0.2 0.3 0.8

Output
0.800000000000

Input
2
0.1 0.2

Output
0.260000000000

-----Note-----

In the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one.

In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1·0.8 + 0.9·0.2 = 0.26.

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

def __starting_point():
	N = int(input())
	probs = list(map(float, input().split()))
	probs.sort()
	P, S = 1.0, 0.0
	sol = 0.0
	for n in reversed(range(N)):
		# print(probs[n])
		if probs[n] == 1.0:
			sol = 1.0
			break
		if S > 1:
			# print(S + (probs[n]/(1 - probs[n])))
			break
		P, S = P*(1 - probs[n]), S + probs[n]/(1 - probs[n])
		# print(P, S, P*S)
		sol = P*S
	print(sol)
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/442/C:
Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points.

After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 5·10^5) — the number of elements in the array. The next line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^6) — the values of the array elements.

-----Output-----

In a single line print a single integer — the maximum number of points Artem can get.

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

Output
11

Input
5
1 2 3 4 5

Output
6

Input
5
1 100 101 100 1

Output
102

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

MAXN = 5 * 10**5 + 100
a = []
ans = 0

n = int(input())

a = list( map ( int, input().split() ) )
a.append(0)

a = [0] + a
n = n + 2
arr = []
arr.append( a[0] )
arr.append( a[1] )

i = 2
while i < n :
	ln = a[i]
	l1 = arr[-1]
	l0 = arr[-2]
	while l1 <= l0 and l1 <= ln :
		ans = ans + min ( l0 , ln )
		arr.pop()
		l1 = arr[-1]
		l0 = arr[-2]
	arr.append(ln)
	i = i + 1
for i in range ( 1 , len(arr) - 1 ) :
	ans += min ( arr[i - 1] , arr[i + 1] )

print (ans)


I found an interesting problem on https://codeforces.com/problemset/problem/443/A:
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.

Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.

-----Input-----

The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.

-----Output-----

Print a single number — the number of distinct letters in Anton's set.

-----Examples-----
Input
{a, b, c}

Output
3

Input
{b, a, b, a}

Output
2

Input
{}

Output
0

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

from sys import stdin as cin
from math import factorial as f
from itertools import combinations as comb
from collections import Counter as C

s = input()
s=s[1:]
n = len(s)
s = s[:n-1]

m = list(s.split(', '))
if m==['']:
    print(0)
else:

    #print(m,len(m))
    r = C(m)
    print(len(list(r)))


I found an interesting problem on https://codeforces.com/problemset/problem/443/B:
Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string.

Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be?

See notes for definition of a tandem repeat.

-----Input-----

The first line contains s (1 ≤ |s| ≤ 200). This string contains only small English letters. The second line contains number k (1 ≤ k ≤ 200) — the number of the added characters.

-----Output-----

Print a single number — the maximum length of the tandem repeat that could have occurred in the new string.

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

Output
6

Input
aaabbbb
2

Output
6

Input
abracadabra
10

Output
20

-----Note-----

A tandem repeat of length 2n is string s, where for any position i (1 ≤ i ≤ n) the following condition fulfills: s_{i} = s_{i} + n.

In the first sample Kolya could obtain a string aabaab, in the second — aaabbbbbb, in the third — abracadabrabracadabra.

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

s = input().rstrip()
k = int(input())
if k > len(s):
    print((len(s) + k) - ((len(s) + k) % 2 == 1))
else:
    aux = []

    for j in range(1, len(s)):
        i = len(s) - 1
        cnt = 0
        while i - j >= 0 and s[i] == s[i - j]:
            i -= 1
            cnt += 1
            if cnt == j:
                break
        diff = i - (len(s) - j - 1)
        if diff <= k:
            aux.append(2 * j)
    aux.append(2 * k)

    for i in range(len(s)):
        for j in range((len(s) - i) // 2):
            if s[i:i + j] == s[i + j:i + 2 * j]:
                aux.append(2 * j)

    print(max(aux))


I found an interesting problem on https://codeforces.com/problemset/problem/445/A:
DZY loves chessboard, and he enjoys playing with it.

He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.

You task is to find any suitable placement of chessmen on the given chessboard.

-----Input-----

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

Each of the next n lines contains a string of m characters: the j-th character of the i-th string is either "." or "-". A "." means that the corresponding cell (in the i-th row and the j-th column) is good, while a "-" means it is bad.

-----Output-----

Output must contain n lines, each line must contain a string of m characters. The j-th character of the i-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell.

If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.

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

Output
B

Input
2 2
..
..

Output
BW
WB

Input
3 3
.-.
---
--.
Output
B-B
---
--B

-----Note-----

In the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.

In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.

In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are.

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

n, m = map(int, input().split())
a = []
for i in range(n):
    a.append(input())
for i in range(n):
    for j in range(m):
        if a[i][j] is '.':
            print('W' if (i + j) % 2 else 'B', end = '')
        else:
            print('-', end = '')
    print()


I found an interesting problem on https://codeforces.com/problemset/problem/445/B:
DZY loves chemistry, and he enjoys mixing chemicals.

DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.

Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.

Find the maximum possible danger after pouring all the chemicals one by one in optimal order.

-----Input-----

The first line contains two space-separated integers n and m $(1 \leq n \leq 50 ; 0 \leq m \leq \frac{n(n - 1)}{2})$.

Each of the next m lines contains two space-separated integers x_{i} and y_{i} (1 ≤ x_{i} < y_{i} ≤ n). These integers mean that the chemical x_{i} will react with the chemical y_{i}. Each pair of chemicals will appear at most once in the input.

Consider all the chemicals numbered from 1 to n in some order.

-----Output-----

Print a single integer — the maximum possible danger.

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

Output
1

Input
2 1
1 2

Output
2

Input
3 2
1 2
2 3

Output
4

-----Note-----

In the first sample, there's only one way to pour, and the danger won't increase.

In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.

In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).

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

def dfs(i):
    used[i] = True;
    for j in graph[i]:
        if not used[j]:
            dfs(j)

n, m = list(map(int, input().split()))
graph = [[] for i in range(n)]
for i in range(m):
    a, b = list(map(int, input().split()))
    a -= 1;
    b -= 1;
    graph[a] += [b]
    graph[b] += [a]
used = [False for i in range(n)]
cc = 0
for i in range(n):
    if not used[i]:
        cc += 1;
        dfs(i)
print(1 << (n - cc))


I found an interesting problem on https://codeforces.com/problemset/problem/446/A:
DZY has a sequence a, consisting of n integers.

We'll call a sequence a_{i}, a_{i} + 1, ..., a_{j} (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment.

Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.

You only need to output the length of the subsegment you find.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5). The next line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

In a single line print the answer to the problem — the maximum length of the required subsegment.

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

Output
5

-----Note-----

You can choose subsegment a_2, a_3, a_4, a_5, a_6 and change its 3rd element (that is a_4) to 4.

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

def solve():
    size = int(input())
    ls = list(map(int, input().rstrip().split()))
    dp0 = [1 for i in range(size)]
    dp1 = [1 for i in range(size)]
    for i in range(1, size):
        dp0[i] = dp0[i - 1] + 1 if (ls[i - 1] < ls[i]) else 1
    for i in range(0, size - 1)[::-1]:
        dp1[i] = dp1[i + 1] + 1 if (ls[i + 1] > ls[i]) else 1
    best = max(max(dp0), max(dp1))
    for i in range(0, size):
        if i >= 1:
            best = max(best, dp0[i - 1] + 1)
        if i <= size - 2:
            best = max(best, dp1[i + 1] + 1)
        if i <= size - 2 and i >= 1:
            if ls[i - 1] + 1 < ls[i + 1]:
                best = max(best, dp0[i - 1] + dp1[i + 1] + 1)
    return best

def __starting_point():
    print(solve())

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/447/A:
DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number x_{i}, DZY will put it into the bucket numbered h(x_{i}), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b denotes taking a remainder after division a by b.

However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1.

-----Input-----

The first line contains two integers, p and n (2 ≤ p, n ≤ 300). Then n lines follow. The i-th of them contains an integer x_{i} (0 ≤ x_{i} ≤ 10^9).

-----Output-----

Output a single integer — the answer to the problem.

-----Examples-----
Input
10 5
0
21
53
41
53

Output
4

Input
5 5
0
1
2
3
4

Output
-1

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

__author__ = 'Adela'

def main():
    p, n = (int(k) for k in input().split())
    full = [False] * p
    for i in range(n):
        xi = int(input())
        mod = xi % p
        if full[mod]:
            print(i+1)
            return
        full[mod] = True

    print(-1)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/447/B:
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value w_{c}. For each special string s = s_1s_2... s_{|}s| (|s| is the length of the string) he represents its value with a function f(s), where $f(s) = \sum_{i = 1}^{|s|}(w_{s_{i}} \cdot i)$

Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?

-----Input-----

The first line contains a single string s (1 ≤ |s| ≤ 10^3).

The second line contains a single integer k (0 ≤ k ≤ 10^3).

The third line contains twenty-six integers from w_{a} to w_{z}. Each such number is non-negative and doesn't exceed 1000.

-----Output-----

Print a single integer — the largest possible value of the resulting string DZY could get.

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

Output
41

-----Note-----

In the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41.

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

s = input()
k = int(input())
w = list(map(int, input().split()))
c = chr(w.index(max(w)) + ord('a'))
def f(s):
  result = 0
  for i in range(len(s)):
    result += w[ord(s[i]) - ord('a')] * (i + 1)
  return result
print(f(s + c * k))


I found an interesting problem on https://codeforces.com/problemset/problem/448/A:
Bizon the Champion is called the Champion for a reason.

Bizon the Champion has recently got a present — a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a_1 first prize cups, a_2 second prize cups and a_3 third prize cups. Besides, he has b_1 first prize medals, b_2 second prize medals and b_3 third prize medals.

Naturally, the rewards in the cupboard must look good, that's why Bizon the Champion decided to follow the rules:  any shelf cannot contain both cups and medals at the same time;  no shelf can contain more than five cups;  no shelf can have more than ten medals.

Help Bizon the Champion find out if we can put all the rewards so that all the conditions are fulfilled.

-----Input-----

The first line contains integers a_1, a_2 and a_3 (0 ≤ a_1, a_2, a_3 ≤ 100). The second line contains integers b_1, b_2 and b_3 (0 ≤ b_1, b_2, b_3 ≤ 100). The third line contains integer n (1 ≤ n ≤ 100).

The numbers in the lines are separated by single spaces.

-----Output-----

Print "YES" (without the quotes) if all the rewards can be put on the shelves in the described manner. Otherwise, print "NO" (without the quotes).

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

Output
YES

Input
1 1 3
2 3 4
2

Output
YES

Input
1 0 0
1 0 0
1

Output
NO

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

from math import ceil
a, b, c = map(int, input().split())
d, e, f = map(int, input().split())
n = int(input())
k = a+b+c
l = d+e+f
if ceil(k/5) + ceil(l/10) <= n:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/448/B:
Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team.

At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), s and t. You need to transform word s into word t". The task looked simple to the guys because they know the suffix data structures well. Bizon Senior loves suffix automaton. By applying it once to a string, he can remove from this string any single character. Bizon Middle knows suffix array well. By applying it once to a string, he can swap any two characters of this string. The guys do not know anything about the suffix tree, but it can help them do much more.

Bizon the Champion wonders whether the "Bizons" can solve the problem. Perhaps, the solution do not require both data structures. Find out whether the guys can solve the problem and if they can, how do they do it? Can they solve it either only with use of suffix automaton or only with use of suffix array or they need both structures? Note that any structure may be used an unlimited number of times, the structures may be used in any order.

-----Input-----

The first line contains a non-empty word s. The second line contains a non-empty word t. Words s and t are different. Each word consists only of lowercase English letters. Each word contains at most 100 letters.

-----Output-----

In the single line print the answer to the problem. Print "need tree" (without the quotes) if word s cannot be transformed into word t even with use of both suffix array and suffix automaton. Print "automaton" (without the quotes) if you need only the suffix automaton to solve the problem. Print "array" (without the quotes) if you need only the suffix array to solve the problem. Print "both" (without the quotes), if you need both data structures to solve the problem.

It's guaranteed that if you can solve the problem only with use of suffix array, then it is impossible to solve it only with use of suffix automaton. This is also true for suffix...

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

s = input()
t = input()
a = [0] * 26
for c in s:
  a[ord(c) - ord('a')] += 1
b = [0] * 26
for c in t:
  b[ord(c) - ord('a')] += 1
if any(a[i] < b[i] for i in range(26)):
  print("need tree")
else:
  needAutomaton = (len(s) > len(t))
  needArray = False
  j = 0
  for i in range(len(t)):
    k = s.find(t[i], j)
    if k < j:
      needArray = True
      break
    j = k + 1
  if needAutomaton and needArray:
    print("both")
  elif needAutomaton:
    print("automaton")
  else:
    print("array")


I found an interesting problem on https://codeforces.com/problemset/problem/448/C:
Bizon the Champion isn't just attentive, he also is very hardworking.

Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of a_{i} meters.

Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 5000) — the number of fence planks. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

Print a single integer — the minimum number of strokes needed to paint the whole fence.

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

Output
3

Input
2
2 2

Output
2

Input
1
5

Output
1

-----Note-----

In the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.

In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.

In the third sample there is only one plank that can be painted using a single vertical stroke.

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

import sys
oo=1000000000000
ar=[]
def solve(l, r, val):
	if(r<l): return 0
	indx=l+ar[l:r+1].index(min(ar[l:r+1]))
	tot=r-l+1
	cur=ar[indx]-val+solve(l, indx-1, ar[indx])+solve(indx+1, r, ar[indx])
	return min(tot, cur)
sys.setrecursionlimit(10000)
n=int(input())
ar=list(map(int, input().split()))
print(solve(0, n-1, 0))


I found an interesting problem on https://codeforces.com/problemset/problem/448/D:
Bizon the Champion isn't just charming, he also is very smart.

While some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an n × m multiplication table, where the element on the intersection of the i-th row and j-th column equals i·j (the rows and columns of the table are numbered starting from 1). Then he was asked: what number in the table is the k-th largest number? Bizon the Champion always answered correctly and immediately. Can you repeat his success?

Consider the given multiplication table. If you write out all n·m numbers from the table in the non-decreasing order, then the k-th number you write out is called the k-th largest number.

-----Input-----

The single line contains integers n, m and k (1 ≤ n, m ≤ 5·10^5; 1 ≤ k ≤ n·m).

-----Output-----

Print the k-th largest number in a n × m multiplication table.

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

Output
2

Input
2 3 4

Output
3

Input
1 10 5

Output
5

-----Note-----

A 2 × 3 multiplication table looks like this:

1 2 3

2 4 6

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

def works(X,N,M,K):
    #in each row, how many numbers are < X
    res = 0
    n = 1
    div = X/M
    while n < div:
        res += M
        n += 1
    while n < N+1:
        res += (X-1)//n
        n += 1
    return res

def solve():
    N, M, K = [int(s) for s in input().split()]
    left = 1
    right = K+1
    #we want the smallest smallest such that there are AT LEAST K-1 smaller numbers
    while right - left > 1:
        middle = (left+right)//2
        if works(middle,N,M,K) < K:
            left = middle
        else:
            right = middle
    #if there are exactly K-1 elements less than right, then this is our answer
    return left

#for _ in range(getInt()):
print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/449/A:
Jzzhu has a big rectangular chocolate bar that consists of n × m unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements:

  each cut should be straight (horizontal or vertical);  each cut should go along edges of unit squares (it is prohibited to divide any unit chocolate square with cut);  each cut should go inside the whole chocolate bar, and all cuts must be distinct.

The picture below shows a possible way to cut a 5 × 6 chocolate for 5 times.

 [Image]

Imagine Jzzhu have made k cuts and the big chocolate is splitted into several pieces. Consider the smallest (by area) piece of the chocolate, Jzzhu wants this piece to be as large as possible. What is the maximum possible area of smallest piece he can get with exactly k cuts? The area of a chocolate piece is the number of unit squares in it.

-----Input-----

A single line contains three integers n, m, k (1 ≤ n, m ≤ 10^9; 1 ≤ k ≤ 2·10^9).

-----Output-----

Output a single integer representing the answer. If it is impossible to cut the big chocolate k times, print -1.

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

Output
6

Input
6 4 2

Output
8

Input
2 3 4

Output
-1

-----Note-----

In the first sample, Jzzhu can cut the chocolate following the picture below:

 [Image]

In the second sample the optimal division looks like this:

 [Image]

In the third sample, it's impossible to cut a 2 × 3 chocolate 4 times.

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

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

if n + m - 2 < k:
	print(-1)
	return

def divisors(n):
	div = set()

	for i in range(1, int(n ** (1 / 2)) + 1):
		if n % i == 0:
			div.add(i)
			div.add(n // i)

	return [*div]

def solve(n, m, k):
	div = divisors(n)
	ans = 0

	for i in div:
		if i - 1 > k: continue
		ans = max(ans, (n // i) * (m // (k - i + 2)))

	return ans

print(max(solve(n, m, k), solve(m, n, k)))


I found an interesting problem on https://codeforces.com/problemset/problem/450/A:
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least a_{i} candies.

Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm:

  Give m candies to the first child of the line.  If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home.  Repeat the first two steps while the line is not empty.

Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?

-----Input-----

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

-----Output-----

Output a single integer, representing the number of the last child.

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

Output
4

Input
6 4
1 1 2 2 3 3

Output
6

-----Note-----

Let's consider the first sample.

Firstly child 1 gets 2 candies and go home. Then child 2 gets 2 candies and go to the end of the line. Currently the line looks like [3, 4, 5, 2] (indices of the children in order of the line). Then child 3 gets 2 candies and go home, and then child 4 gets 2 candies and goes to the end of the line. Currently the line looks like [5, 2, 4]. Then child 5 gets 2 candies and goes home. Then child 2 gets two candies and goes home, and finally child 4 gets 2 candies and goes home.

Child 4 is the last one who goes home.

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

from math import ceil
n, m = map(int,input().split())
a = list(map(int,input().split()))
b = list()
for i in a:
    b.append(ceil(i/m))
x = max(b)
last = -1
i = 0
while i < n:
    if b[i] == x:
        last = i
    i += 1
print(last+1)


I found an interesting problem on https://codeforces.com/problemset/problem/450/B:
Jzzhu has invented a kind of sequences, they meet the following property:$f_{1} = x ; f_{2} = y ; \forall i(i \geq 2), f_{i} = f_{i - 1} + f_{i + 1}$

You are given x and y, please calculate f_{n} modulo 1000000007 (10^9 + 7).

-----Input-----

The first line contains two integers x and y (|x|, |y| ≤ 10^9). The second line contains a single integer n (1 ≤ n ≤ 2·10^9).

-----Output-----

Output a single integer representing f_{n} modulo 1000000007 (10^9 + 7).

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

Output
1

Input
0 -1
2

Output
1000000006

-----Note-----

In the first sample, f_2 = f_1 + f_3, 3 = 2 + f_3, f_3 = 1.

In the second sample, f_2 =  - 1;  - 1 modulo (10^9 + 7) equals (10^9 + 6).

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

from sys import stdin as cin
from fractions import gcd
mod = 1000000007
x,y = list(map(int,cin.readline().split()))
n = int(cin.readline())
k = n%6
if k==0:
    print((x-y)%mod)
elif k==1:
    print(x%mod)
elif k==2:
    print(y%mod)
elif k==3:
    print((y-x)%mod)
elif k==4:
    print(-x%mod)
elif k==5:
    print(-y%mod)


I found an interesting problem on https://codeforces.com/problemset/problem/451/A:
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks.

An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.

In the grid shown below, n = 3 and m = 3. There are n + m = 6 sticks in total (horizontal sticks are shown in red and vertical sticks are shown in green). There are n·m = 9 intersection points, numbered from 1 to 9.

 [Image]

The rules of the game are very simple. The players move in turns. Akshat won gold, so he makes the first move. During his/her move, a player must choose any remaining intersection point and remove from the grid all sticks which pass through this point. A player will lose the game if he/she cannot make a move (i.e. there are no intersection points remaining on the grid at his/her move).

Assume that both players play optimally. Who will win the game?

-----Input-----

The first line of input contains two space-separated integers, n and m (1 ≤ n, m ≤ 100).

-----Output-----

Print a single line containing "Akshat" or "Malvika" (without the quotes), depending on the winner of the game.

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

Output
Malvika

Input
2 3

Output
Malvika

Input
3 3

Output
Akshat

-----Note-----

Explanation of the first sample:

The grid has four intersection points, numbered from 1 to 4.

 [Image]

If Akshat chooses intersection point 1, then he will remove two sticks (1 - 2 and 1 - 3). The resulting grid will look like this.

 [Image]

Now there is only one remaining intersection point (i.e. 4). Malvika must choose it and remove both remaining sticks. After her move the grid will be empty.

In the empty grid, Akshat cannot make any move, hence he will lose.

Since all 4 intersection points of the grid are equivalent, Akshat will lose no matter which one he picks.

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

n,m=[int(x) for x in input().split()]
print("Akshat" if min(n,m)&1 else "Malvika")


I found an interesting problem on https://codeforces.com/problemset/problem/451/B:
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.

Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.

-----Input-----

The first line of the input contains an integer n (1 ≤ n ≤ 10^5) — the size of array a.

The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 10^9).

-----Output-----

Print "yes" or "no" (without quotes), depending on the answer.

If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them.

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

Output
yes
1 3

Input
4
2 1 3 4

Output
yes
1 2

Input
4
3 1 2 4

Output
no

Input
2
1 2

Output
yes
1 1

-----Note-----

Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted.

Sample 3. No segment can be reversed such that the array will be sorted.

Definitions

A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r].

If you have an array a of size n and you reverse its segment [l, r], the array will become:

a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].

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

n=input()
thelist=input()
final=[]
now=thelist.split()
for item in now:
    final.append(int(item))
begin=sorted(final)
indices=[]
i=0
length=len(final)
while i<length:
    if final[i] != begin[i]:
        indices.append(i)
    i+=1
all=len(indices)
if len(indices) !=0:
    x=indices[0]
    y=indices[all-1]
    switched=[]
    p=0
    while p<x:
        switched.append(final[p])
        p+=1
    j=0
    while j<= (y-x):
        switched.append(final[y-j])
        j+=1
    q=y+1
    while q<length:
        switched.append(final[q])
        q+=1
    switchable="yes"
    z=0
    while z<len(begin):
        if switched[z] != begin[z]:
            switchable="no"
            break
        z+=1
    if switchable=="yes":
        print("yes")
        print(x+1,y+1)
    else:
        print("no")

else:
    print("yes")
    print("1 1")


I found an interesting problem on https://codeforces.com/problemset/problem/451/D:
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".

Given a string, you have to find two values:  the number of good substrings of even length;  the number of good substrings of odd length.

-----Input-----

The first line of the input contains a single string of length n (1 ≤ n ≤ 10^5). Each character of the string will be either 'a' or 'b'.

-----Output-----

Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.

-----Examples-----
Input
bb

Output
1 2

Input
baab

Output
2 4

Input
babb

Output
2 5

Input
babaa

Output
2 7

-----Note-----

In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.

In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.

In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.

Definitions

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

A string s = s_1s_2... s_{n} is a palindrome if it is equal to string s_{n}s_{n} - 1... s_1.

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

t = input()
n = len(t)
t = [-1] + [i for i in range(n - 1) if t[i] != t[i + 1]] + [n - 1]
n = len(t) - 1
u, v = [0] * n, [0] * n
for i in range(n):
    d = t[i + 1] - t[i]
    k = d // 2
    u[i] = v[i] = k
    if d & 1:
        if t[i] & 1: v[i] += 1
        else: u[i] += 1
    i += 1
a = sum(u[i] for i in range(0, n, 2))
b = sum(v[i] for i in range(0, n, 2))
c = sum(u[i] for i in range(1, n, 2))
d = sum(v[i] for i in range(1, n, 2))
print(a * b + c * d, (a * (a + 1) + b * (b + 1) + c * (c + 1) + d * (d + 1)) // 2)


I found an interesting problem on https://codeforces.com/problemset/problem/452/A:
You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon.

You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it.

-----Input-----

First line contains an integer n (6 ≤ n ≤ 8) – the length of the string.

Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword).

-----Output-----

Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter).

-----Examples-----
Input
7
j......

Output
jolteon

Input
7
...feon

Output
leafeon

Input
7
.l.r.o.

Output
flareon

-----Note-----

Here's a set of names in a form you can paste into your solution:

["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"]

{"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}

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

def ok(x,y):
    if(len(x)!=len(y)):
        return False
    for i in range(len(x)):
        if(y[i]!='.' and x[i]!=y[i]):
            return False
    return True

n=int(input())

s=input()

L=['Vaporeon', 'Jolteon', 'Flareon', 'Espeon', 'Umbreon', 'Leafeon','Glaceon','Sylveon']

for i in range(len(L)):
    L[i]=L[i].lower()

for item in L:
    if(ok(item,s)):
        print(item)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/452/B:
You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.

A polyline defined by points p_1, p_2, p_3, p_4 consists of the line segments p_1 p_2, p_2 p_3, p_3 p_4, and its length is the sum of the lengths of the individual line segments.

-----Input-----

The only line of the input contains two integers n and m (0 ≤ n, m ≤ 1000). It is guaranteed that grid contains at least 4 different points.

-----Output-----

Print 4 lines with two integers per line separated by space — coordinates of points p_1, p_2, p_3, p_4 in order which represent the longest possible polyline.

Judge program compares your answer and jury's answer with 10^{ - 6} precision.

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

Output
1 1
0 0
1 0
0 1

Input
0 10

Output
0 1
0 10
0 0
0 9

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

import math
n, m = list(map(int, input().split()))
if n == 0 :
    print(0, 1)
    print(0, m)
    print(0, 0)
    print(0, m - 1)
elif m == 0 :
    print(1, 0)
    print(n, 0)
    print(0, 0)
    print(n - 1, 0)
else :
    l = math.sqrt((n - 1) ** 2 + m ** 2) + math.sqrt(n ** 2 + m ** 2) + math.sqrt(n ** 2 + (m - 1) ** 2)
    l1 = max(m, n) + math.sqrt(n * n + m * m) * 2
    l2 = math.sqrt(n ** 2 + m ** 2) + math.sqrt((n - 1) ** 2 + m ** 2) * 2
    l3 = math.sqrt(n ** 2 + m ** 2) + math.sqrt((m - 1) ** 2 + n ** 2) * 2
    ans = max(l, l1, l2, l3)
    if l == ans :
        print(1, 0)
        print(n, m)
        print(0, 0)
        print(n, m - 1)
    elif l1 == ans :
        if n > m :
            print(n, m)
            print(0, 0)
            print(n, 0)
            print(0, m)
        else :
            print(n, m)
            print(0, 0)
            print(0, m)
            print(n, 0)
    elif l2 == ans :
        print(1, 0)
        print(n, m)
        print(0, 0)
        print(n - 1, m)
    else :
        print(0, 1)
        print(n, m)
        print(0, 0)
        print(n, m - 1)


I found an interesting problem on https://codeforces.com/problemset/problem/452/C:
Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards.

The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful.

You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case.

-----Input-----

First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks.

-----Output-----

On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10^{ - 6}.

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

Output
0.6666666666666666

Input
4 4

Output
0.4000000000000000

Input
1 2

Output
1.0000000000000000

-----Note-----

In the first sample, with probability $\frac{1}{3}$ Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed.

With the remaining $\frac{2}{3}$ probability he took two different cards, and the probability of pulling off the trick is $\frac{1}{2}$.

The resulting probability is $\frac{1}{3} \times 1 + \frac{2}{3} \times \frac{1}{2} = \frac{2}{3}$

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

n, m = map(int, input().split())
t = m * n
print(1 if t == 1 else (2 * t - (m + n)) / (n * (t - 1)))


I found an interesting problem on https://codeforces.com/problemset/problem/452/D:
You have k pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has n_1 washing machines, n_2 drying machines and n_3 folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before it is dried. Moreover, after a piece of laundry is washed, it needs to be immediately moved into a drying machine, and after it is dried, it needs to be immediately moved into a folding machine.

It takes t_1 minutes to wash one piece of laundry in a washing machine, t_2 minutes to dry it in a drying machine, and t_3 minutes to fold it in a folding machine. Find the smallest number of minutes that is enough to wash, dry and fold all the laundry you have.

-----Input-----

The only line of the input contains seven integers: k, n_1, n_2, n_3, t_1, t_2, t_3 (1 ≤ k ≤ 10^4; 1 ≤ n_1, n_2, n_3, t_1, t_2, t_3 ≤ 1000).

-----Output-----

Print one integer — smallest number of minutes to do all your laundry.

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

Output
15

Input
8 4 3 2 10 5 2

Output
32

-----Note-----

In the first example there's one instance of each machine, each taking 5 minutes to complete. You have only one piece of laundry, so it takes 15 minutes to process it.

In the second example you start washing first two pieces at moment 0. If you start the third piece of laundry immediately, then by the time it is dried, there will be no folding machine available, so you have to wait, and start washing third piece at moment 2. Similarly, you can't start washing next piece until moment 5, since otherwise there will be no dryer available, when it is washed. Start time for each of the eight pieces of laundry is 0, 0, 2, 5, 10, 10, 12 and 15 minutes respectively. The last piece of laundry will be ready after 15 + 10 + 5 + 2 = 32 minutes.

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

class step(object):
    timer = []
    def __init__(self, name, machin_num, step_time):
        self.machin_num = machin_num
        self.step_time = step_time
        self.name = name

    def step_input(self, cloth_num, t):
        '''
        if cloth_num + len(self.timer) > self.machin_num:
            excloth = cloth_num + len(self.timer) - self.machin_num
            print('%s error excloth is %d' %(self.name , excloth))
            return 'error'
        else:
            for new_cloth in range(cloth_num):
                self.timer.append(t)
            #print(self.timer)
        '''
        for new_cloth in range(cloth_num):
                self.timer.append(t)

    def step_run(self, t):
        tmptimer = [each_timer for each_timer in self.timer if t - each_timer < self.step_time]
        #next_num = len(self.timer) - len(tmptimer)
        self.timer = tmptimer
        #if len(self.timer) == 0:
            #print('%s in %d is empty' %(self.name, t))
            #pass
        #print('%d: %s timer:\n%s \n' %(t, self.name, self.timer))
        #print('%d: %s timer: %d \n' %(t, self.name, next_num))
        #return next_num

    def checkstate(self, pre_t):
        running_machine = len(self.timer)
        #output = 0
        for each_timer in range(running_machine):
            if pre_t - self.timer[each_timer] >= self.step_time:
                running_machine -= 1
                #output += 1
        return self.machin_num - running_machine

def main():
    p, n1, n2, n3, t1, t2, t3 = list(map(int, input().split()))
    '''
    p = 8
    n1 = 4
    n2 = 3
    n3 = 2
    t1 = 10
    t2 = 5
    t3 = 2
    '''
    step1 = step('step1', n1, t1)
    step2 = step('step2', n2, t2)
    step3 = step('step3', n3, t3)

    t = 0
    #cp = 0
    while True:
        pre_num1 = step1.checkstate(t)
        pre_num2 = step2.checkstate(t + t1)
        pre_num3 = step3.checkstate(t + t1 + t2)
        step1_input = min(pre_num1, pre_num2, pre_num3)
        p -= step1_input
       ...


I found an interesting problem on https://codeforces.com/problemset/problem/453/A:
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.

The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability $\frac{1}{m}$. Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times.

-----Input-----

A single line contains two integers m and n (1 ≤ m, n ≤ 10^5).

-----Output-----

Output a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn't exceed 10 ^{ - 4}.

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

Output
3.500000000000

Input
6 3

Output
4.958333333333

Input
2 2

Output
1.750000000000

-----Note-----

Consider the third test example. If you've made two tosses:  You can get 1 in the first toss, and 2 in the second. Maximum equals to 2.  You can get 1 in the first toss, and 1 in the second. Maximum equals to 1.  You can get 2 in the first toss, and 1 in the second. Maximum equals to 2.  You can get 2 in the first toss, and 2 in the second. Maximum equals to 2.

The probability of each outcome is 0.25, that is expectation equals to: $(2 + 1 + 2 + 2) \cdot 0.25 = \frac{7}{4}$

You can read about expectation using the following link: http://en.wikipedia.org/wiki/Expected_value

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

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

ans = 0
for x in range(1, m + 1):
    ans += x * ((x / m)**n - ((x - 1)/m)**n)
print('%0.9f' % ans)


I found an interesting problem on https://codeforces.com/problemset/problem/454/A:
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n × n matrix with a diamond inscribed into it.

You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.

-----Input-----

The only line contains an integer n (3 ≤ n ≤ 101; n is odd).

-----Output-----

Output a crystal of size n.

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

Output
*D*
DDD
*D*

Input
5

Output
**D**
*DDD*
DDDDD
*DDD*
**D**

Input
7

Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***

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

n = int(input())

for i in range(n):
    for j in range(n):
        if min(i, n - 1 - i) + min(j, n - 1 - j) < n // 2:
            print('*', end = '')
        else:
            print('D', end = '')
    print()


I found an interesting problem on https://codeforces.com/problemset/problem/454/B:
One day, Twilight Sparkle is interested in how to sort a sequence of integers a_1, a_2, ..., a_{n} in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a_1, a_2, ..., a_{n} → a_{n}, a_1, a_2, ..., a_{n} - 1.

Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?

-----Input-----

The first line contains an integer n (2 ≤ n ≤ 10^5). The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5).

-----Output-----

If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.

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

Output
1

Input
3
1 3 2

Output
-1

Input
2
1 2

Output
0

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

def is_sorted(a):
    for i in range(1, len(a)):
        if a[i - 1] > a[i]:
            return False
    return True

def solve():
    n = int(input())
    a = list(map(int, input().split()))
    if is_sorted(a):
        return 0
    for i in range(1, len(a)):
        if a[i - 1] > a[i]:
            if is_sorted(a[i:] + a[:i]):
                return n - i
            else:
                return -1

print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/455/A:
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.

Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it a_{k}) and delete it, at that all elements equal to a_{k} + 1 and a_{k} - 1 also must be deleted from the sequence. That step brings a_{k} points to the player.

Alex is a perfectionist, so he decided to get as many points as possible. Help him.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) that shows how many numbers are in Alex's sequence.

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

-----Output-----

Print a single integer — the maximum number of points that Alex can earn.

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

Output
2

Input
3
1 2 3

Output
4

Input
9
1 2 1 3 2 2 2 2 3

Output
10

-----Note-----

Consider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points.

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

3

import sys

def compress(l):
    x = l[0]
    cnt = 1
    c = []
    for i in range(1, len(l)):
        if l[i] == x:
            cnt += 1
        else:
            c.append((x, cnt))
            x = l[i]
            cnt = 1
    c.append((x, cnt))
    return c

def __starting_point():
    n = int(sys.stdin.readline())
    a = [int(x) for x in sys.stdin.readline().split()]
    a.sort()
    a = compress(a)
    dp = [0, a[0][0] * a[0][1]]
    for i in range(1, len(a)):
        x, c = a[i]
        px = a[i-1][0]
        dp.append(max(dp[-1], x*c + (dp[-1] if x > px + 1 else dp[-2])))
    print(max(dp))

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/456/A:
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.

Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist.

-----Input-----

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

Next n lines contain two integers each, a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n), where a_{i} is the price of the i-th laptop, and b_{i} is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality).

All a_{i} are distinct. All b_{i} are distinct.

-----Output-----

If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes).

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

Output
Happy Alex

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

n = int(input())
arr = []
for i in range(n):
	a,b = map(int, input().split(' '))
	arr.append((a,b))
arr = sorted(arr)
for i in range(n-1):
	if(arr[i][1]>arr[i+1][1]):
		print("Happy Alex")
		break
else:
	print("Poor Alex")


I found an interesting problem on https://codeforces.com/problemset/problem/456/B:
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:(1^{n} + 2^{n} + 3^{n} + 4^{n}) mod 5

for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).

-----Input-----

The single line contains a single integer n (0 ≤ n ≤ 10^10^5). The number doesn't contain any leading zeroes.

-----Output-----

Print the value of the expression without leading zeros.

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

Output
4

Input
124356983594583453458888889

Output
0

-----Note-----

Operation x mod y means taking remainder after division x by y.

Note to the first sample:

[Image]

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/457/A:
Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number $q = \frac{\sqrt{5} + 1}{2}$, in particular that q^2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a_0a_1...a_{n} equals to $\sum_{i = 0}^{n} a_{i} \cdot q^{n - i}$.

Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.

Given two numbers written in golden system notation, determine which of them has larger decimal value.

-----Input-----

Input consists of two lines — one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.

-----Output-----

Print ">" if the first number is larger, "<" if it is smaller and "=" if they are equal.

-----Examples-----
Input
1000
111

Output
<

Input
00100
11

Output
=

Input
110
101

Output
>

-----Note-----

In the first example first number equals to $((\sqrt{5} + 1) / 2)^{3} \approx 1.618033988^{3} \approx 4.236$, while second number is approximately 1.618033988^2 + 1.618033988 + 1 ≈ 5.236, which is clearly a bigger number.

In the second example numbers are equal. Each of them is  ≈ 2.618.

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

u = v = 0
a, b = input(), input()
n, m = len(a), len(b)
if n > m: b = '0' * (n - m) + b
else: a = '0' * (m - n) + a
for i in range(max(n, m)):
    u, v = v + u, u + int(a[i]) - int(b[i])
    if u > 1:
        print('>')
        return
    elif u < -1:
        print('<')
        return
d = 2 * v + u
if u == v == 0: print('=')
elif u >= 0 and d >= 0: print('>')
elif u <= 0 and d <= 0: print('<')
else: print('>' if (u * u > v * (v + u)) ^ (u < 0) else '<')


I found an interesting problem on https://codeforces.com/problemset/problem/457/B:
Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.

Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting of m partitions. Partition with index i has a_{i} rows from A. Similarly, second cluster containing table B has n partitions, i-th one having b_{i} rows from B.

In one network operation she can copy one row from any partition to any other partition. At the end, for each row from A and each row from B there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.

-----Input-----

First line contains two integer numbers, m and n (1 ≤ m, n ≤ 10^5). Second line contains description of the first cluster with m space separated integers, a_{i} (1 ≤ a_{i} ≤ 10^9). Similarly, third line describes second cluster with n space separated integers, b_{i} (1 ≤ b_{i} ≤ 10^9).

-----Output-----

Print one integer — minimal number of copy operations.

-----Examples-----
Input
2 2
2 6
3 100

Output
11

Input
2 3
10 10
1 1 1

Output
6

-----Note-----

In the first example it makes sense to move all the rows to the second partition of the second cluster which is achieved in 2 + 6 + 3 = 11 operations

In the second example Piegirl can copy each row from B to the both partitions of the first cluster which needs 2·3 = 6 copy operations.

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

n, m = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort(reverse=True)
B.sort(reverse=True)
sumA = sum(A)
sumB = sum(B)
ansA = sumB
ansB = sumA

for i in range(1, n):
    ansA += min(A[i],sumB)
for i in range(1, m):
    ansB += min(B[i], sumA)
print(min(ansA,ansB))


I found an interesting problem on https://codeforces.com/problemset/problem/459/A:
Pashmak has fallen in love with an attractive girl called Parmida since one year ago...

Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.

-----Input-----

The first line contains four space-separated x_1, y_1, x_2, y_2 ( - 100 ≤ x_1, y_1, x_2, y_2 ≤ 100) integers, where x_1 and y_1 are coordinates of the first tree and x_2 and y_2 are coordinates of the second tree. It's guaranteed that the given points are distinct.

-----Output-----

If there is no solution to the problem, print -1. Otherwise print four space-separated integers x_3, y_3, x_4, y_4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them.

Note that x_3, y_3, x_4, y_4 must be in the range ( - 1000 ≤ x_3, y_3, x_4, y_4 ≤ 1000).

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

Output
1 0 1 1

Input
0 0 1 1

Output
0 1 1 0

Input
0 0 1 2

Output
-1

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

x1, y1, x2, y2 = map(int, input().split())
#diagonal
if x1 != x2 and y1 != y2:
    if abs(x1 - x2) == abs(y1 - y2):
        print(x1, y2, x2, y1)
    else:
        print(-1)
#same side
elif x1 == x2:
    aux = abs(y2 - y1)
    print(x1 + aux, y1, x1 + aux, y2)
elif y1 == y2:
    aux = abs(x2 - x1)
    print(x1, y1 + aux, x2, y1 + aux)


I found an interesting problem on https://codeforces.com/problemset/problem/459/B:
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number b_{i}. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!

Your task is to write a program which calculates two things:  The maximum beauty difference of flowers that Pashmak can give to Parmida.  The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.

-----Input-----

The first line of the input contains n (2 ≤ n ≤ 2·10^5). In the next line there are n space-separated integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^9).

-----Output-----

The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.

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

Output
1 1
Input
3
1 4 5

Output
4 1
Input
5
3 1 2 3 1

Output
2 4

-----Note-----

In the third sample the maximum beauty difference is 2 and there are 4 ways to do this:  choosing the first and the second flowers;  choosing the first and the fifth flowers;  choosing the fourth and the second flowers;  choosing the fourth and the fifth flowers.

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

import math
n = int(input())
f = list(map(int,input().split()))

f.sort()
diff = f[-1] - f[0]
a = f[0]
b = f[-1]

c1 = 1
c2 = 1
for i in range(1,n-1):
    if f[i] == a :
        c1 += 1
    elif f[i] == b:
        c2 += 1
#print(c1,c2)
if a==b :
    summ = 0
    for i in range(n-1,0,-1):
        summ += i

    print(diff,summ )
else:
    print(diff, c1*c2)


I found an interesting problem on https://codeforces.com/problemset/problem/459/C:
Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all d days.

Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.

-----Input-----

The first line of input contains three space-separated integers n, k, d (1 ≤ n, d ≤ 1000; 1 ≤ k ≤ 10^9).

-----Output-----

If there is no valid arrangement just print -1. Otherwise print d lines, in each of them print n integers. The j-th integer of the i-th line shows which bus the j-th student has to take on the i-th day. You can assume that the buses are numbered from 1 to k.

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

Output
1 1 2
1 2 1

Input
3 2 1

Output
-1

-----Note-----

Note that two students become close friends only if they share a bus each day. But the bus they share can differ from day to day.

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

n,k,d=list(map(int,input().split()))
if n>k**d:print((-1));return
K=1
for j in range(d):
    print(" ".join([str(i//K%k +1) for i in range(n)]))
    K*=k


I found an interesting problem on https://codeforces.com/problemset/problem/459/D:
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.

There is a sequence a that consists of n integers a_1, a_2, ..., a_{n}. Let's denote f(l, r, x) the number of indices k such that: l ≤ k ≤ r and a_{k} = x. His task is to calculate the number of pairs of indicies i, j (1 ≤ i < j ≤ n) such that f(1, i, a_{i}) > f(j, n, a_{j}).

Help Pashmak with the test.

-----Input-----

The first line of the input contains an integer n (1 ≤ n ≤ 10^6). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

Print a single integer — the answer to the problem.

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

Output
8

Input
3
1 1 1

Output
1

Input
5
1 2 3 4 5

Output
0

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

INF = 10 ** 10
# merge two sorted lists l and r
def merge(l, r):
    res = l + r

    i = j = k = 0
    while i < len(l) and j < len(r):
        if l[i] < r[j]:
            res[k] = l[i]
            k += 1
            i += 1
        else:
            res[k] = r[j]
            k += 1
            j += 1

    res[k:] = l[i:] + r[j:]
    return res

def solve(fl, fr, l, r):
    if l == r:
        return 0

    mid = (l + r) // 2
    # after calling solve(l, mid) and (mid + 1, r), fl and fr are sorted on these ranges
    res = solve(fl, fr, l, mid) + solve(fl, fr, mid + 1, r)

    # perform 2-pointers on 2 sorted lists
    i, j = l, mid + 1
    while i <= mid:
        while j <= r and fr[j] < fl[i]:
            j += 1
        res += j - mid - 1
        i += 1

    # merge 2 sorted lists
    fl[l: r + 1] = merge(fl[l: mid + 1], fl[mid + 1: r + 1])
    fr[l: r + 1] = merge(fr[l: mid + 1], fr[mid + 1: r + 1])
    return res

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

    fl, cnt = [], {}
    for x in a:
        cnt[x] = cnt.get(x, 0) + 1
        # fl[i] = f(0, i, a[i])
        fl.append(cnt[x])

    fr, cnt = [], {}
    for x in a[::-1]:
        cnt[x] = cnt.get(x, 0) + 1
        # fr[i] = f(i, n - 1, a[i])
        fr.append(cnt[x])
    fr = fr[::-1]

    print(solve(fl, fr, 0, n - 1))

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/459/E:
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.

You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.

Help Pashmak, print the number of edges in the required path.

-----Input-----

The first line contains two integers n, m (2 ≤ n ≤ 3·10^5; 1 ≤ m ≤ min(n·(n - 1), 3·10^5)). Then, m lines follows. The i-th line contains three space separated integers: u_{i}, v_{i}, w_{i} (1 ≤ u_{i}, v_{i} ≤ n; 1 ≤ w_{i} ≤ 10^5) which indicates that there's a directed edge with weight w_{i} from vertex u_{i} to vertex v_{i}.

It's guaranteed that the graph doesn't contain self-loops and multiple edges.

-----Output-----

Print a single integer — the answer to the problem.

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

Output
1

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

Output
3

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

Output
6

-----Note-----

In the first sample the maximum trail can be any of this trails: $1 \rightarrow 2,2 \rightarrow 3,3 \rightarrow 1$.

In the second sample the maximum trail is $1 \rightarrow 2 \rightarrow 3 \rightarrow 1$.

In the third sample the maximum trail is $1 \rightarrow 2 \rightarrow 5 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 6$.

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

from sys import *

a = list(map(int, stdin.read().split()))

n = a[0]
m = a[1]
inf = 10**5 + 1

g = [[] for i in range(inf)]

for i in range(2, len(a), 3):
	b, c, w = a[i:i + 3]
	g[w].append((c, b))
n += 1
s = [0] * n

for l in g:
	for i, k in [(i, s[j]) for i, j in l]:
		s[i] = max(s[i], k + 1)
print(max(s))


I found an interesting problem on https://codeforces.com/problemset/problem/460/A:
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?

-----Input-----

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

-----Output-----

Print a single integer — the answer to the problem.

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

Output
3

Input
9 3

Output
13

-----Note-----

In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two.

In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day.

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

n, m = map(int, input().split())
day = 1
while n > 0:
    n -= 1
    if day % m == 0:
        n += 1
    day += 1

print(day - 1)


I found an interesting problem on https://codeforces.com/problemset/problem/460/B:
Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment.

Find all integer solutions x (0 < x < 10^9) of the equation:x = b·s(x)^{a} + c,

where a, b, c are some predetermined constant values and function s(x) determines the sum of all digits in the decimal representation of number x.

The teacher gives this problem to Dima for each lesson. He changes only the parameters of the equation: a, b, c. Dima got sick of getting bad marks and he asks you to help him solve this challenging problem.

-----Input-----

The first line contains three space-separated integers: a, b, c (1 ≤ a ≤ 5; 1 ≤ b ≤ 10000;  - 10000 ≤ c ≤ 10000).

-----Output-----

Print integer n — the number of the solutions that you've found. Next print n integers in the increasing order — the solutions of the given equation. Print only integer solutions that are larger than zero and strictly less than 10^9.

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

Output
3
10 2008 13726
Input
1 2 -18

Output
0

Input
2 2 -1

Output
4
1 31 337 967

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

a, b, c = list(map(int, input().split()))
ans = []
for sum in range(1, 200):
    x = b * sum ** a + c
    if x <= 0 or x >= 10 ** 9:
        continue
    summ = 0
    for aa in str(x):
        summ += int(aa)
    if sum == summ:
        ans.append(x)
print(len(ans))
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/460/C:
Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted n flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions.

There are m days left to the birthday. The height of the i-th flower (assume that the flowers in the row are numbered from 1 to n from left to right) is equal to a_{i} at the moment. At each of the remaining m days the beaver can take a special watering and water w contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get?

-----Input-----

The first line contains space-separated integers n, m and w (1 ≤ w ≤ n ≤ 10^5; 1 ≤ m ≤ 10^5). The second line contains space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

Print a single integer — the maximum final height of the smallest flower.

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

Output
2

Input
2 5 1
5 8

Output
9

-----Note-----

In the first sample beaver can water the last 3 flowers at the first day. On the next day he may not to water flowers at all. In the end he will get the following heights: [2, 2, 2, 3, 2, 2]. The smallest flower has height equal to 2. It's impossible to get height 3 in this test.

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

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

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

from collections import Counter

import math
import sys

from itertools import permutations

import bisect

#print(bisect.bisect_right([1,2,3],2))
#print(bisect.bisect_left([1,2,3],2))

n,m,w=R()

a=L()

l=0
r=10**10

while l<r-1:
    mid=(l+r)//2
    b=[0]*n

    fl=True

    cur=0
    days=0
    for i in range(n):
        cur+=b[i]

        if a[i]+cur<mid:
            delta=mid-a[i]-cur
            days+=delta
            cur+=delta

            if i+w<n:
                b[i+w]-=delta

        if days>m:
            fl=False
            break

    if fl:
        l=mid
    else:
        r=mid

print(l)