I found an interesting problem on https://codeforces.com/problemset/problem/461/A:
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:  Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.  Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.

After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 3·10^5). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — the initial group that is given to Toastman.

-----Output-----

Print a single integer — the largest possible score.

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

Output
26

Input
1
10

Output
10

-----Note-----

Consider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions.

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

n=int(input())
lis=input().split()
for i in range(n):
    lis[i]=int(lis[i])
lis.sort()
m=max(lis)
s=0
for i in range(len(lis)):
   s+=lis[i]*(i+2)
print(s-m)


I found an interesting problem on https://codeforces.com/problemset/problem/462/A:
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?

Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.

-----Output-----

Print "YES" or "NO" (without the quotes) depending on the answer to the problem.

-----Examples-----
Input
3
xxo
xox
oxx

Output
YES

Input
4
xxxo
xoxo
oxox
xxxx

Output
NO

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

n = int(input())

b = [input() for _ in range(n)]
ans = True
for i in range(n):
    for j in range(n):
        ans &= len([1 for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)] if 0 <= i + di < n and 0 <= j + dj < n and b[i + di][j + dj] == 'o']) % 2 == 0
print('YES' if ans else 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/462/B:
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.

Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?

-----Input-----

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 10^5). The next line contains n uppercase letters without spaces — the i-th letter describes the i-th card of the Appleman.

-----Output-----

Print a single integer – the answer to the problem.

-----Examples-----
Input
15 10
DZFDFZDFDDDDDDF

Output
82

Input
6 4
YJSNPI

Output
4

-----Note-----

In the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.

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

temp = input().split()
N, K = int(temp[0]), int(temp[1])
s = input()
d = dict()
for c in s:
    d[c] = d.get(c, 0) + 1

sum = 0
while (K > 0):
    m = '-'
    for k, v in list(d.items()):
        if d.get(m, 0) < v:
            m = k

    if K > d[m]:
        sum += d[m] * d[m]
        K -= d[m]
    else:
        sum += K * K
        K = 0
    d[m] = 0
print (sum)


I found an interesting problem on https://codeforces.com/problemset/problem/463/A:
Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.

Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).

Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change.

-----Input-----

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

The i-th of the next n lines contains two integers x_{i}, y_{i} (1 ≤ x_{i} ≤ 100; 0 ≤ y_{i} < 100), where x_{i} represents the number of dollars and y_{i} the number of cents needed in order to buy the i-th type of sugar.

-----Output-----

Print a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.

-----Examples-----
Input
5 10
3 90
12 0
9 70
5 50
7 0

Output
50

Input
5 5
10 10
20 20
30 30
40 40
50 50

Output
-1

-----Note-----

In the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change.

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

import itertools
import math
import random

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

    return tmp

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

n, s = list(map(int, input().split(' ')))
array = [list(map(int, input().split(' '))) for i in range(n)]

res = -100;
for i in range(n):
    if array[i][0]+array[i][1]/100 <= s:
        sdacha = 100 - array[i][1]
        if array[i][1]== 0:
            sdacha = 0
        if sdacha>res:
            res = sdacha

if res == -100:
    print(-1)
else:
    print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/463/B:
Caisa solved the problem with the sugar and now he is on the way back to home.

Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height h_{i}. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k + 1). When the player have made such a move, its energy increases by h_{k} - h_{k} + 1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time.

Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5). The next line contains n integers h_1, h_2, ..., h_{n} (1  ≤  h_{i}  ≤  10^5) representing the heights of the pylons.

-----Output-----

Print a single number representing the minimum number of dollars paid by Caisa.

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

Output
4

Input
3
4 4 4

Output
4

-----Note-----

In the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon.

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

n = int(input())

heights = input()
splitted = heights.split(' ')
splitted.reverse()
splitted.append('0')
splitted.reverse()

energy = 0
dollars = 0

for i in range(0, len(splitted) - 1):
    h = int(splitted[i])
    hplus = int(splitted[i + 1])

    diff = hplus - h

    if diff > energy:
        dollars += (diff - energy)
        energy = 0
    else:
        energy -= diff

print(dollars)


I found an interesting problem on https://codeforces.com/problemset/problem/463/C:
Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.

He has a n × n chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number x written on it, if this cell is attacked by one of the bishops Gargari will get x dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.

We assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 2000). Each of the next n lines contains n integers a_{ij} (0 ≤ a_{ij} ≤ 10^9) — description of the chessboard.

-----Output-----

On the first line print the maximal number of dollars Gargari will get. On the next line print four integers: x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_2 ≤ n), where x_{i} is the number of the row where the i-th bishop should be placed, y_{i} is the number of the column where the i-th bishop should be placed. Consider rows are numbered from 1 to n from top to bottom, and columns are numbered from 1 to n from left to right.

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

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

Output
12
2 2 3 2

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

from sys import stdin
input = stdin.buffer.readline
I = lambda : list(map(int,input().split()))

n,=I()
l=[]
for i in range(n):
	l.append(I())
d={};su={};s=0;an=[1,1,2,1]
for i in range(n):
	for j in range(n):
		d[i-j]=d.get(i-j,0)+l[i][j]
		su[i+j]=su.get(i+j,0)+l[i][j]
x=0;y=0
for i in range(n):
	for j in range(n):
		p=d[i-j]+su[i+j]-l[i][j]
		if (i+j)%2:
			if p>x:
				an[0],an[1]=i+1,j+1
				x=p
		else:
			if p>y:
				an[2],an[3]=i+1,j+1
				y=p
s=x+y
print(s)
print(*an)


I found an interesting problem on https://codeforces.com/problemset/problem/463/D:
Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?

You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 1000; 2 ≤ k ≤ 5). Each of the next k lines contains integers 1, 2, ..., n in some order — description of the current permutation.

-----Output-----

Print the length of the longest common subsequence.

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

Output
3

-----Note-----

The answer for the first test sample is subsequence [1, 2, 3].

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

#   ==========     //\\       //||     ||====//||
#       ||        //  \\        ||     ||   // ||
#       ||       //====\\       ||     ||  //  ||
#       ||      //      \\      ||     || //   ||
#   ========== //        \\  ========  ||//====||
#  code

def solve():
    n, k = map(int, input().split())
    c = [ [-1 for i in range(n + 1)] for i in range(k)]
    dp = [0 for i in range(n + 1)]
    a = []

    for i in range(k):
        b = list(map(int, input().split()))
        for j, v in enumerate(b):
            c[i][v] = j
        a.append(b)

    for i in range(n):
        curpos = a[0][i]
        dp[i] = 1
        for j in range(i):
            prevpos = a[0][j]
            ok = True
            for p in range(k):
                if c[p][curpos] < c[p][prevpos]:
                    ok = False
                    break
            if ok:
                dp[i] = max(dp[i], dp[j] + 1)
    print(max(dp))
    return

def main():
    t = 1
    # t = int(input())
    for _ in range(t):
        solve()

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/464/A:
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.

Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.

-----Input-----

The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).

-----Output-----

If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).

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

Output
NO

Input
3 4
cba

Output
cbd

Input
4 4
abcd

Output
abda

-----Note-----

String s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s_1 = t_1, ..., s_{i} = t_{i}, s_{i} + 1 > t_{i} + 1.

The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.

A palindrome is a string that reads the same forward or reversed.

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

def trans(c):
  return chr(ord(c) + 1)
n, p = list(map(int, input().split()))
s = list(input())
s[n-1] = trans(s[n-1]) #increment the last char
i = n - 1
while i >= 0 and i < n:
  if ord(s[i]) >= ord('a') + p:
    s[i] = 'a'  #overflow make a
    i -= 1
    s[i] = trans(s[i])# to make lexo larger ...inc the prev char #eg bc becomes ca for p=3
  elif i > 0 and s[i] == s[i-1] or i > 1 and s[i] == s[i-2]:
    s[i] = trans(s[i]) # a pal substring is present..inc
  else:
    i += 1# good good..go on
else:
  print("NO" if i < 0 else "".join(s))
  #if i became n ,,we are done
  #else wwe have no ans


I found an interesting problem on https://codeforces.com/problemset/problem/464/B:
Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — coordinates of cube's vertex (a single line contains coordinates of a single vertex, each vertex is written exactly once), put the paper on the table and left. While Peter was away, his little brother Nick decided to play with the numbers on the paper. In one operation Nick could swap some numbers inside a single line (Nick didn't swap numbers from distinct lines). Nick could have performed any number of such operations.

When Peter returned and found out about Nick's mischief, he started recollecting the original coordinates. Help Peter restore the original position of the points or else state that this is impossible and the numbers were initially recorded incorrectly.

-----Input-----

Each of the eight lines contains three space-separated integers — the numbers written on the piece of paper after Nick's mischief. All numbers do not exceed 10^6 in their absolute value.

-----Output-----

If there is a way to restore the cube, then print in the first line "YES". In each of the next eight lines print three integers — the restored coordinates of the points. The numbers in the i-th output line must be a permutation of the numbers in i-th input line. The numbers should represent the vertices of a cube with non-zero length of a side. If there are multiple possible ways, print any of them.

If there is no valid way, print "NO" (without the quotes) in the first line. Do not print anything else.

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

Output
YES
0 0 0
0 0 1
0 1 0
1 0 0
0 1 1
1 0 1
1 1 0
1 1 1

Input
0 0 0
0 0 0
0 0 0
0 0 0
1 1 1
1 1 1
1 1 1
1 1 1

Output
NO

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

import itertools
from itertools import permutations as perm
import copy

def getPerm(it, index):
	if index == 0:
		return it
	elif index == 1:
		return [it[0], it[2], it[1]]
	elif index == 2:
		return [it[1], it[0], it[2]]
	elif index == 3:
		return [it[1], it[2], it[0]]
	elif index == 4:
		return [it[2], it[0], it[1]]
	elif index == 5:
		return [it[2], it[1], it[0]]

def distance(coord1, coord2):
	return ((coord2[0] - coord1[0])**2 + (coord2[1] - coord1[1])**2 + (coord2[2] - coord1[2])**2)

dists = ([0]*6)*7

pointList =  [[int(x) for x in input().split()] for y in range(0, 8)]

p0 = pointList[0]

for x in range(0, 7):
	y = 0
	for pt in perm(pointList[x + 1], 3):
		# print(pt, p0)
		dists[x*6 + y] = distance(p0, pt)
		# print(dists)
		y += 1

# print(pointList)
# print(dists)
done = False
final = None

def same(it1, it2):
	# print(it1, it2)
	if list(it1) == list(it2):
		return True
	return False

def checkNotSame(indicesSoFar, newIndex):
	nonlocal pointList
	ptToComp = getPerm(pointList[len(indicesSoFar) + 1], newIndex)
	for c in range(len(indicesSoFar)):
		if same(getPerm(pointList[c + 1], indicesSoFar[c]), ptToComp):
			# print(getPerm(pointList[c + 1], indicesSoFar[c]), getPerm(pointList[len(indicesSoFar)], newIndex), False)
			return False
	return True

def checkCompatible(a, b):
	if a == b or a*2 == b or a == 2*b or a*3 == b or a ==3*b or 2*a == 3*b or 3*a== 2*b:
		return True
	return False

def getSeven(distList, soFar, index):
	nonlocal done
	nonlocal final
	if done == True:
		return
	if index == 7:
		# for h in range(0,7):
		# 	print(getPerm(pointList[h+1], soFar[h]), end=" ")
		# print()
		# for i in range(0,7):
		# 	print(dists[i*6+soFar[i]], end=" ")
		# print()
		# print(soFar)
		distsSoFar = [dists[i*6+soFar[i]] for i in range(0, 7)]
		# print(distsSoFar)
		lowest = min(distsSoFar)
		lows = 0
		twos = 0
		threes = 0
		for a in range(0, 7):
			if distsSoFar[a] == lowest:
				lows += 1
			elif distsSoFar[a] == lowest*2:
				twos += 1
			elif distsSoFar[a] == lowest*3:
				threes += 1
		if lows...


I found an interesting problem on https://codeforces.com/problemset/problem/465/A:
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.

Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.

Sergey wrote certain values of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of bits in the cell.

The second line contains a string consisting of n characters — the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.

-----Output-----

Print a single integer — the number of bits in the cell which change their state after we add 1 to the cell.

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

Output
3

Input
4
1111

Output
4

-----Note-----

In the first sample the cell ends up with value 0010, in the second sample — with 0000.

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

N = int(input())
S = input()[::-1]
x = int(S, 2) + 1
Sp = bin(x)[2:].zfill(N)[-N:]
print(sum(a != b for a, b in zip(S, Sp)))


I found an interesting problem on https://codeforces.com/problemset/problem/465/B:
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.

Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations: Move from the list of letters to the content of any single letter. Return to the list of letters from single letter viewing mode. In single letter viewing mode, move to the next or to the previous letter in the list. You cannot move from the first letter to the previous one or from the last letter to the next one.

The program cannot delete the letters from the list or rearrange them.

Alexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. What minimum number of operations does Alexey need to perform to read all unread letters?

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of letters in the mailbox.

The second line contains n space-separated integers (zeros and ones) — the state of the letter list. The i-th number equals either 1, if the i-th number is unread, or 0, if the i-th letter is read.

-----Output-----

Print a single number — the minimum number of operations needed to make all the letters read.

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

Output
3

Input
5
1 1 0 0 1

Output
4

Input
2
0 0

Output
0

-----Note-----

In the first sample Alexey needs three operations to cope with the task: open the second letter, move to the third one, move to the fourth one.

In the second sample the action plan: open the first letter, move to the second letter, return to the list, open the fifth letter.

In the third sample all letters are already read.

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

#!/usr/bin/env python3

def main():
    n = input()
    letters = list(input().split(' '))
    idx = list()
    for i in range(len(letters)):
        if letters[i] == '1':
            idx.append(i)
    m = len(idx)
    if m == 0:
        print(0)
        return
    res = 1
    for i in range(1, m):
        res += min(2, idx[i] - idx[i - 1])
    print(res)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/466/A:
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of money she will have to spend to make n rides?

-----Input-----

The single line contains four space-separated integers n, m, a, b (1 ≤ n, m, a, b ≤ 1000) — the number of rides Ann has planned, the number of rides covered by the m ride ticket, the price of a one ride ticket and the price of an m ride ticket.

-----Output-----

Print a single integer — the minimum sum in rubles that Ann will need to spend.

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

Output
6

Input
5 2 2 3

Output
8

-----Note-----

In the first sample one of the optimal solutions is: each time buy a one ride ticket. There are other optimal solutions. For example, buy three m ride tickets.

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

__author__ = 'sonerik'

import sys

inp = sys.stdin
# inp = open("a.txt")

all_drives, abon_drives, ord_price, abon_price = map(int, inp.readline().strip().split())

# print(all_drives, abon_drives, one_price, abon_price)

one_abon_price = abon_price / abon_drives

# print(one_abon_price, ord_price)

if one_abon_price < ord_price:  # abonement is better
    abons = all_drives // abon_drives
    ords = all_drives % abon_drives

    if abon_price < ords*ord_price:
        abons += 1
        ords = 0

    print(abons*abon_price + ords*ord_price)
else:
    print(all_drives*ord_price)


I found an interesting problem on https://codeforces.com/problemset/problem/466/B:
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a × b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.

-----Input-----

The first line contains three space-separated integers n, a and b (1 ≤ n, a, b ≤ 10^9) — the number of students and the sizes of the room.

-----Output-----

Print three integers s, a_1 and b_1 (a ≤ a_1; b ≤ b_1) — the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.

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

Output
18
3 6

Input
2 4 4

Output
16
4 4

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

import math
n, a, b = list(map(int, input().split()))
s = 6*n
if a*b >= s:
    print(a*b)
    print(a, b)
else:
    aa, bb = a, b
    area = float('inf')
    _a = 0
    for i in range(min(math.ceil(s**0.5), s // max(a, b)), min(a, b)-1, -1):
        _b = math.ceil(s/i)
        _s = _b * i
        if _s <= area:
            area, _a = _s, i
            if _s == s:
                break
    print(area)
    _b = area//_a
    if not (aa <= _a and bb <= _b):
        _a, _b = _b, _a
    print(_a, _b)


I found an interesting problem on https://codeforces.com/problemset/problem/466/C:
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.

More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that $\sum_{k = 1}^{i - 1} a_{k} = \sum_{k = i}^{j} a_{k} = \sum_{k = j + 1}^{n} a_{k}$.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 5·10^5), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≤  10^9) — the elements of array a.

-----Output-----

Print a single integer — the number of ways to split the array into three parts with the same sum.

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

Output
2

Input
4
0 1 -1 0

Output
1

Input
2
4 1

Output
0

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

n = int(input())
a = list(map(int, input().split()))
b = [a[0]]
for i in a[1:]:
    b.append(b[-1] + i)
d = [a[-1]]
for i in a[:-1][::-1]:
    d.append(d[-1] + i)
d = d[::-1]
c = [0] * n
s = b[n - 1]

if b[0] * 3 == s:
    c[0] = 1
for i in range(1, n):
    if b[i] * 3 == s:
        c[i] = c[i - 1] + 1
    else:
        c[i] = c[i - 1]

ans = 0
for i in range(2, n):
    if d[i] * 3 == s:
        ans = ans + c[i - 2]

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/466/D:
Peter has a sequence of integers a_1, a_2, ..., a_{n}. Peter wants all numbers in the sequence to equal h. He can perform the operation of "adding one on the segment [l, r]": add one to all elements of the sequence with indices from l to r (inclusive). At that, Peter never chooses any element as the beginning of the segment twice. Similarly, Peter never chooses any element as the end of the segment twice. In other words, for any two segments [l_1, r_1] and [l_2, r_2], where Peter added one, the following inequalities hold: l_1 ≠ l_2 and r_1 ≠ r_2.

How many distinct ways are there to make all numbers in the sequence equal h? Print this number of ways modulo 1000000007 (10^9 + 7). Two ways are considered distinct if one of them has a segment that isn't in the other way.

-----Input-----

The first line contains two integers n, h (1 ≤ n, h ≤ 2000). The next line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 2000).

-----Output-----

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

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

Output
4

Input
5 1
1 1 1 1 1

Output
1

Input
4 3
3 2 1 1

Output
0

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

f = lambda: map(int, input().split())
n, h = f()
s, i = 1, 0
for j in f():
    j = h - j
    if j < 0 or abs(j - i) > 1: print(0);return
    if j <= i: s = s * (j + 1) % 1000000007
    i = j
print(0 if i > 1 else s)


I found an interesting problem on https://codeforces.com/problemset/problem/466/E:
There are n employees working in company "X" (let's number them from 1 to n for convenience). Initially the employees didn't have any relationships among each other. On each of m next days one of the following events took place:  either employee y became the boss of employee x (at that, employee x didn't have a boss before);  or employee x gets a packet of documents and signs them; then he gives the packet to his boss. The boss signs the documents and gives them to his boss and so on (the last person to sign the documents sends them to the archive);  or comes a request of type "determine whether employee x signs certain documents".

Your task is to write a program that will, given the events, answer the queries of the described type. At that, it is guaranteed that throughout the whole working time the company didn't have cyclic dependencies.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of employees and the number of events.

Each of the next m lines contains the description of one event (the events are given in the chronological order). The first number of the line determines the type of event t (1 ≤ t ≤ 3).   If t = 1, then next follow two integers x and y (1 ≤ x, y ≤ n) — numbers of the company employees. It is guaranteed that employee x doesn't have the boss currently.  If t = 2, then next follow integer x (1 ≤ x ≤ n) — the number of the employee who got a document packet.  If t = 3, then next follow two integers x and i (1 ≤ x ≤ n; 1 ≤ i ≤ [number of packets that have already been given]) — the employee and the number of the document packet for which you need to find out information. The document packets are numbered started from 1 in the chronological order.

It is guaranteed that the input has at least one query of the third type.

-----Output-----

For each query of the third type print "YES" if the employee signed the document package and "NO" otherwise. Print all the words without the quotes.

-----Examples-----
Input
4 9
1 4 3
2 4
3 3 1
1 2 3
2...

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

n, m = map(int, input().split())
ev = [tuple(map(int, input().split())) for _ in range(m)]

g = [[] for _ in range(n + 1)]
qry = [[] for _ in range(m + 1)]
roots = set(range(1, n + 1))
qcnt = 0
for e in ev:
	if e[0] == 1:
		g[e[2]].append(e[1])
		roots.remove(e[1])
	elif e[0] == 3:
		qry[e[2]].append((qcnt, e[1]))
		qcnt += 1

tin, tout = [0] * (n + 1), [0] * (n + 1)
st = [(u, 0) for u in roots]
time = 0
while st:
	u, w = st.pop()
	if w:
		tout[u] = time
		continue
	time += 1
	tin[u] = time
	st.append((u, 1))
	for v in g[u]:
		st.append((v, 0))

p = list(range(n + 1))
def find(x):
	if x != p[x]:
		p[x] = find(p[x])
	return p[x]

pcnt = 0
ans = [None] * qcnt
for e in ev:
	if e[0] == 1:
		p[find(e[1])] = find(e[2])
	elif e[0] == 2:
		pcnt += 1
		for qid, x in qry[pcnt]:
			ans[qid] = 'YES' if find(e[1]) == find(x) and tin[x] <= tin[e[1]] <= tout[x] else 'NO'

print(*ans, sep='\n')


I found an interesting problem on https://codeforces.com/problemset/problem/467/A:
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.

George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has p_{i} people living in it and the room can accommodate q_{i} people in total (p_{i} ≤ q_{i}). Your task is to count how many rooms has free place for both George and Alex.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of rooms.

The i-th of the next n lines contains two integers p_{i} and q_{i} (0 ≤ p_{i} ≤ q_{i} ≤ 100) — the number of people who already live in the i-th room and the room's capacity.

-----Output-----

Print a single integer — the number of rooms where George and Alex can move in.

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

Output
0

Input
3
1 10
0 10
10 10

Output
2

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

n = int(input())
ans = 0
for i in range(n):
    a, b = map(int, input().split())
    if b - a >= 2:
        ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/467/B:
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3».

The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each player has an army. Army of the i-th player can be described by non-negative integer x_{i}. Consider binary representation of x_{i}: if the j-th bit of number x_{i} equal to one, then the army of the i-th player has soldiers of the j-th type.

Fedor is the (m + 1)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.

-----Input-----

The first line contains three integers n, m, k (1 ≤ k ≤ n ≤ 20; 1 ≤ m ≤ 1000).

The i-th of the next (m + 1) lines contains a single integer x_{i} (1 ≤ x_{i} ≤ 2^{n} - 1), that describes the i-th player's army. We remind you that Fedor is the (m + 1)-th player.

-----Output-----

Print a single integer — the number of Fedor's potential friends.

-----Examples-----
Input
7 3 1
8
5
111
17

Output
0

Input
3 3 3
1
2
3
4

Output
3

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

n, m, k = map(int, input().split())
a = list([])
for i in range(m + 1):
    l = int(input())
    a.append(l)
ans = 0
for i in range(m):
    bi = a[i] ^ a[m]
    s = bin(bi)
    r = 0
    j = 2
    while r <= k and j < len(s):
        if s[j] == '1':
            r += 1
        j += 1
    if r <= k:
        ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/467/C:
The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.

Given a sequence of n integers p_1, p_2, ..., p_{n}. You are to choose k pairs of integers:

 [l_1, r_1], [l_2, r_2], ..., [l_{k}, r_{k}] (1 ≤ l_1 ≤ r_1 < l_2 ≤ r_2 < ... < l_{k} ≤ r_{k} ≤ n; r_{i} - l_{i} + 1 = m),

in such a way that the value of sum $\sum_{i = 1}^{k} \sum_{j = l_{i}}^{r_{i}} p_{j}$ is maximal possible. Help George to cope with the task.

-----Input-----

The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p_1, p_2, ..., p_{n} (0 ≤ p_{i} ≤ 10^9).

-----Output-----

Print an integer in a single line — the maximum possible value of sum.

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

Output
9

Input
7 1 3
2 10 7 18 5 33 0

Output
61

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

from sys import stdin, setrecursionlimit
from collections import *
import threading

def arr_inp(n):
    if n == 1:
        return [int(x) for x in stdin.readline().split()]
    elif n == 2:
        return [float(x) for x in stdin.readline().split()]
    else:
        return list(stdin.readline()[:-1])

def dp(i, num):
    if num > k:
        return -float('inf')
    if i >= n - m + 1:
        return 0
    if mem[i, num] != -1:
        return mem[i, num]

    mem[i, num] = max(dp(i + 1, num), cum[i] + dp(i + m, num + 1))
    return mem[i, num]

def main():
    ans = 0
    if m == 1:
        print(sum(sorted(a)[n - k:]))
    else:
        for i in range(n - m + 1):
            ans = max(ans, dp(i, 0))

        print(ans)

def __starting_point():
    n, m, k = arr_inp(1)
    a = arr_inp(1)
    mem, cum = defaultdict(lambda: -1), [sum(a[i:i + m]) for i in range(n - m + 1)]
    setrecursionlimit(50000)
    threading.stack_size(102400000)
    thread = threading.Thread(target=main)
    thread.start()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/467/D:
After you had helped Fedor to find friends in the «Call of Soldiers 3» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all. Now Fedor is going to change the essay using the synonym dictionary of the English language.

Fedor does not want to change the meaning of the essay. So the only change he would do: change a word from essay to one of its synonyms, basing on a replacement rule from the dictionary. Fedor may perform this operation any number of times.

As a result, Fedor wants to get an essay which contains as little letters «R» (the case doesn't matter) as possible. If there are multiple essays with minimum number of «R»s he wants to get the one with minimum length (length of essay is the sum of the lengths of all the words in it). Help Fedor get the required essay.

Please note that in this problem the case of letters doesn't matter. For example, if the synonym dictionary says that word cat can be replaced with word DOG, then it is allowed to replace the word Cat with the word doG.

-----Input-----

The first line contains a single integer m (1 ≤ m ≤ 10^5) — the number of words in the initial essay. The second line contains words of the essay. The words are separated by a single space. It is guaranteed that the total length of the words won't exceed 10^5 characters.

The next line contains a single integer n (0 ≤ n ≤ 10^5) — the number of pairs of words in synonym dictionary. The i-th of the next n lines contains two space-separated non-empty words x_{i} and y_{i}. They mean that word x_{i} can be replaced with word y_{i} (but not vise versa). It is guaranteed that the total length of all pairs of synonyms doesn't exceed 5·10^5 characters.

All the words at input can only consist of uppercase and lowercase letters of the English alphabet.

-----Output-----

Print two integers — the minimum number of letters...

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

from collections import defaultdict

input()
index = {}
stat = lambda word: (word.count('r'),
    len(word), index.setdefault(word, len(index)))
essay = list(map(stat, input().lower().split()))
queue = essay[:]

syn = defaultdict(list)
for i in range(int(input())):
  word, rep = list(map(stat, input().lower().split()))
  syn[rep[2]].append(word[2])
  queue.append(rep)
queue.sort(reverse=True)
best = {}
while queue:
  n_r, length, word = queue.pop()
  if word in best:
    continue
  best[word] = n_r, length
  for rep in syn[word]:
    if rep not in best:
      queue.append((n_r, length, rep))
sum_n_r, sum_len = 0, 0
for n_r, length in [best[w[2]] for w in essay]:
  sum_n_r += n_r
  sum_len += length
print(sum_n_r, sum_len)


I found an interesting problem on https://codeforces.com/problemset/problem/469/A:
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.

Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?

-----Input-----

The first line contains a single integer n (1 ≤  n ≤ 100).

The next line contains an integer p (0 ≤ p ≤ n) at first, then follows p distinct integers a_1, a_2, ..., a_{p} (1 ≤ a_{i} ≤ n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.

-----Output-----

If they can pass all the levels, print "I become the guy.". If it's impossible, print "Oh, my keyboard!" (without the quotes).

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

Output
I become the guy.

Input
4
3 1 2 3
2 2 3

Output
Oh, my keyboard!

-----Note-----

In the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.

In the second sample, no one can pass level 4.

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

n = int(input())
a = [0] * (n + 1)
f = 1
x = list(map(int, input().split()))
for i in range(1, len(x)):
    a[x[i]] = 1
y = list(map(int, input().split()))
for i in range(1, len(y)):
    a[y[i]] = 1
for i in range(1, n + 1):
    if not a[i]:
        f = 0
print('I become the guy.' if f else 'Oh, my keyboard!')


I found an interesting problem on https://codeforces.com/problemset/problem/469/B:
Little X and Little Z are good friends. They always chat online. But both of them have schedules.

Little Z has fixed schedule. He always online at any moment of time between a_1 and b_1, between a_2 and b_2, ..., between a_{p} and b_{p} (all borders inclusive). But the schedule of Little X is quite strange, it depends on the time when he gets up. If he gets up at time 0, he will be online at any moment of time between c_1 and d_1, between c_2 and d_2, ..., between c_{q} and d_{q} (all borders inclusive). But if he gets up at time t, these segments will be shifted by t. They become [c_{i} + t, d_{i} + t] (for all i).

If at a moment of time, both Little X and Little Z are online simultaneosly, they can chat online happily. You know that Little X can get up at an integer moment of time between l and r (both borders inclusive). Also you know that Little X wants to get up at the moment of time, that is suitable for chatting with Little Z (they must have at least one common moment of time in schedules). How many integer moments of time from the segment [l, r] suit for that?

-----Input-----

The first line contains four space-separated integers p, q, l, r (1 ≤  p, q ≤ 50; 0 ≤ l ≤ r ≤ 1000).

Each of the next p lines contains two space-separated integers a_{i}, b_{i} (0 ≤ a_{i} < b_{i} ≤ 1000). Each of the next q lines contains two space-separated integers c_{j}, d_{j} (0 ≤ c_{j} < d_{j} ≤ 1000).

It's guaranteed that b_{i} < a_{i} + 1 and d_{j} < c_{j} + 1 for all valid i and j.

-----Output-----

Output a single integer — the number of moments of time from the segment [l, r] which suit for online conversation.

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

Output
3

Input
2 3 0 20
15 17
23 26
1 4
7 11
15 17

Output
20

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

p,q,l,r = tuple(map(int, input().split(' ')))
IP = [False]*1001
IQ = [False]*1001
for i in range(p):
    a,b = tuple(map(int, input().split(' ')))
    IP[a:b+1] = [True]*(b-a+1)

for i in range(q):
    a,b = tuple(map(int, input().split(' ')))
    IQ[a:b+1]=[True]*(b-a+1)

li = []
li= [1 for i in range(l,r+1) if any([True for j in range(1001-i) if IP[i+j] and IQ[j] ]) ]

print(sum(li))


I found an interesting problem on https://codeforces.com/problemset/problem/472/B:
One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.

Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have n people standing on the first floor, the i-th person wants to go to the f_{i}-th floor. Unfortunately, there is only one elevator and its capacity equal to k (that is at most k people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs |a - b| seconds to move from the a-th floor to the b-th floor (we don't count the time the people need to get on and off the elevator).

What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor?

-----Input-----

The first line contains two integers n and k (1 ≤ n, k ≤ 2000) — the number of people and the maximal capacity of the elevator.

The next line contains n integers: f_1, f_2, ..., f_{n} (2 ≤ f_{i} ≤ 2000), where f_{i} denotes the target floor of the i-th person.

-----Output-----

Output a single integer — the minimal time needed to achieve the goal.

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

Output
8

Input
4 2
50 100 50 100

Output
296

Input
10 3
2 2 2 2 2 2 2 2 2 2

Output
8

-----Note-----

In first sample, an optimal solution is:   The elevator takes up person #1 and person #2.  It goes to the 2nd floor.  Both people go out of the elevator.  The elevator goes back to the 1st floor.  Then the elevator takes up person #3.  And it goes to the 2nd floor.  It picks up person #2.  Then it goes to the 3rd floor.  Person #2 goes out.  Then it goes to the 4th floor, where person #3 goes out.  The elevator goes back to the 1st floor.

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

n, k = map(int,input().split())
f = list(map(int,input().split()))
f.sort(reverse = True)
ans = 0
places = 0
for fl in f:
    places += 1
    if places == 1:
        ans += 2 * (fl - 1)
    if places == k:
        places = 0
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/472/C:
A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.

Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordinary sorting problem, but we can make it more interesting by adding nondeterministic element. There are n people, each person will use either his/her first name or last name as a handle. Can the lexicographical order of the handles be exactly equal to the given permutation p?

More formally, if we denote the handle of the i-th person as h_{i}, then the following condition must hold: $\forall i, j(i < j) : h_{p_{i}} < h_{p_{j}}$.

-----Input-----

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

The next n lines each contains two strings. The i-th line contains strings f_{i} and s_{i} (1 ≤ |f_{i}|, |s_{i}| ≤ 50) — the first name and last name of the i-th person. Each string consists only of lowercase English letters. All of the given 2n strings will be distinct.

The next line contains n distinct integers: p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n).

-----Output-----

If it is possible, output "YES", otherwise output "NO".

-----Examples-----
Input
3
gennady korotkevich
petr mitrichev
gaoyuan chen
1 2 3

Output
NO

Input
3
gennady korotkevich
petr mitrichev
gaoyuan chen
3 1 2

Output
YES

Input
2
galileo galilei
nicolaus copernicus
2 1

Output
YES

Input
10
rean schwarzer
fei claussell
alisa reinford
eliot craig
laura arseid
jusis albarea
machias regnitz
sara valestin
emma millstein
gaius worzel
1 2 3 4 5 6 7 8 9 10

Output
NO

Input
10
rean schwarzer
fei claussell
alisa reinford
eliot craig
laura arseid
jusis albarea
machias regnitz
sara valestin
emma millstein
gaius worzel
2 4 9 6 5 7 1 3 8 10

Output
YES

-----Note-----

In example 1 and 2, we have 3 people: tourist, Petr and me (cgy4ever). You can see that whatever handle is chosen, I must be the first, then tourist...

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

# 472 C

a = int(input())
l = []
l1 = []
for i in range(a):
    l.append('')
for i in range(a):
    lol = input().split()
    l1.append([lol[0],lol[1]])
l2 = input().split()

for i in range(a):
    l[i] = l1[int(l2[i])-1]
m = ''
work = "YES"
for i in range(a):
    if min(l[i]) >= m:
        m = min(l[i])
    elif max(l[i]) >= m:
        m = max(l[i])
    else:
        work = "NO"
        break

print(work)


I found an interesting problem on https://codeforces.com/problemset/problem/474/A:
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:

qwertyuiop

asdfghjkl;

zxcvbnm,./

Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input).

We have a sequence of characters he has typed and we want to find the original message.

-----Input-----

First line of the input contains one letter describing direction of shifting ('L' or 'R' respectively for left or right).

Second line contains a sequence of characters written by Mole. The size of this sequence will be no more than 100. Sequence contains only symbols that appear on Mole's keyboard. It doesn't contain spaces as there is no space on Mole's keyboard.

It is guaranteed that even though Mole hands are moved, he is still pressing buttons on keyboard and not hitting outside it.

-----Output-----

Print a line that contains the original message.

-----Examples-----
Input
R
s;;upimrrfod;pbr

Output
allyouneedislove

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

x=input()
y=input()

a='qwertyuiop'+'asdfghjkl;'+'zxcvbnm,./'

if x=='R':
    for i in range(len(y)):
        t=a.index(y[i])
        print(a[t-1],end="")
if x=='L':
    for i in range(len(y)):
        t=a.index(y[i])
        print(a[t+1],end="")


I found an interesting problem on https://codeforces.com/problemset/problem/474/C:
Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.

Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (x_{i}, y_{i}) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.

Each mole i has a home placed at the position (a_{i}, b_{i}). Moving this mole one time means rotating his position point (x_{i}, y_{i}) 90 degrees counter-clockwise around it's home point (a_{i}, b_{i}).

A regiment is compact only if the position points of the 4 moles form a square with non-zero area.

Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 100), the number of regiments.

The next 4n lines contain 4 integers x_{i}, y_{i}, a_{i}, b_{i} ( - 10^4 ≤ x_{i}, y_{i}, a_{i}, b_{i} ≤ 10^4).

-----Output-----

Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print "-1" (without quotes).

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

Output
1
-1
3
3

-----Note-----

In the first regiment we can move once the second or the third mole.

We can't make the second regiment compact.

In the third regiment, from the last 3 moles we can move once one and twice another one.

In the fourth regiment, we can move twice the first mole and once the third mole.

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

def r(t): t[0], t[1] = t[2] + t[3] - t[1], t[3] + t[0] - t[2]
f = range(4)
g = lambda u, v: (u[0] - v[0]) ** 2 + (u[1] - v[1]) ** 2
h = [(i, j) for i in f for j in f if i < j]
for i in range(int(input())):
    p = [list(map(int, input().split())) for j in f]
    s = 13
    for a in f:
        for b in f:
            for c in f:
                for d in f:
                    t = sorted(g(p[u], p[v]) for u, v in h)
                    if 0 != t[4] == t[5] == 2 * t[0] == 2 * t[3]: s = min(s, a + b + c + d)
                    r(p[3])
                r(p[2])
            r(p[1])
        r(p[0])
    print(s if s < 13 else -1)


I found an interesting problem on https://codeforces.com/problemset/problem/474/D:
We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.

But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size k.

Now Marmot wonders in how many ways he can eat between a and b flowers. As the number of ways could be very large, print it modulo 1000000007 (10^9 + 7).

-----Input-----

Input contains several test cases.

The first line contains two integers t and k (1 ≤ t, k ≤ 10^5), where t represents the number of test cases.

The next t lines contain two integers a_{i} and b_{i} (1 ≤ a_{i} ≤ b_{i} ≤ 10^5), describing the i-th test.

-----Output-----

Print t lines to the standard output. The i-th line should contain the number of ways in which Marmot can eat between a_{i} and b_{i} flowers at dinner modulo 1000000007 (10^9 + 7).

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

Output
6
5
5

-----Note-----  For K = 2 and length 1 Marmot can eat (R).  For K = 2 and length 2 Marmot can eat (RR) and (WW).  For K = 2 and length 3 Marmot can eat (RRR), (RWW) and (WWR).  For K = 2 and length 4 Marmot can eat, for example, (WWWW) or (RWWR), but for example he can't eat (WWWR).

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

from sys import stdin, stdout

lines = list([_f for _f in stdin.read().split('\n') if _f])

def parseline(line):
	return list(map(int, line.split()))

lines = list(map(parseline, lines))
t, k = lines[0]

assert len(lines) >= t + 1

max_flowers = 10 ** 5
modulo = 10 ** 9 + 7

A = [0] * (1 + max_flowers)
A[0] = 1
A_sum = [0] * (1 + max_flowers)

for i in range(1, 1 + max_flowers):
	Ai_m_k = A[i-k] if i >= k else 0
	A[i] = (A[i-1] + Ai_m_k) % modulo
	A_sum[i] = (A_sum[i-1] + A[i]) % modulo

def tests():
	for i in range(1, t + 1):
		yield lines[i]

for a, b in tests():
	print((A_sum[b] - A_sum[a-1]) % modulo)


I found an interesting problem on https://codeforces.com/problemset/problem/475/A:
The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows.  [Image]

The event coordinator has a list of k participants who should be picked up at the airport. When a participant gets on the bus, he will sit in the last row with an empty seat. If there is more than one empty seat in that row, he will take the leftmost one.

In order to keep track of the people who are on the bus, the event coordinator needs a figure showing which seats are going to be taken by k participants. Your task is to draw the figure representing occupied seats.

-----Input-----

The only line of input contains integer k, (0 ≤ k ≤ 34), denoting the number of participants.

-----Output-----

Print the figure of a bus with k passengers as described in sample tests. Character '#' denotes an empty seat, while 'O' denotes a taken seat. 'D' is the bus driver and other characters in the output are for the purpose of beautifying the figure. Strictly follow the sample test cases output format. Print exactly six lines. Do not output extra space or other characters.

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

Output
+------------------------+
|O.O.O.#.#.#.#.#.#.#.#.|D|)
|O.O.O.#.#.#.#.#.#.#.#.|.|
|O.......................|
|O.O.#.#.#.#.#.#.#.#.#.|.|)
+------------------------+

Input
20

Output
+------------------------+
|O.O.O.O.O.O.O.#.#.#.#.|D|)
|O.O.O.O.O.O.#.#.#.#.#.|.|
|O.......................|
|O.O.O.O.O.O.#.#.#.#.#.|.|)
+------------------------+

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/475/B:
Imagine a city with n horizontal streets crossing m vertical streets, forming an (n - 1) × (m - 1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traffic moves only from north to south or only from south to north in each vertical street. It is possible to enter a horizontal street from a vertical street, or vice versa, at their intersection.

 [Image]

The mayor has received some street direction patterns. Your task is to check whether it is possible to reach any junction from any other junction in the proposed street direction pattern.

-----Input-----

The first line of input contains two integers n and m, (2 ≤ n, m ≤ 20), denoting the number of horizontal streets and the number of vertical streets.

The second line contains a string of length n, made of characters '<' and '>', denoting direction of each horizontal street. If the i-th character is equal to '<', the street is directed from east to west otherwise, the street is directed from west to east. Streets are listed in order from north to south.

The third line contains a string of length m, made of characters '^' and 'v', denoting direction of each vertical street. If the i-th character is equal to '^', the street is directed from south to north, otherwise the street is directed from north to south. Streets are listed in order from west to east.

-----Output-----

If the given pattern meets the mayor's criteria, print a single line containing "YES", otherwise print a single line containing "NO".

-----Examples-----
Input
3 3
><>
v^v

Output
NO

Input
4 6
<><>
v^v^v^

Output
YES

-----Note-----

The figure above shows street directions in the second sample test case.

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/475/D:
Given a sequence of integers a_1, ..., a_{n} and q queries x_1, ..., x_{q} on it. For each query x_{i} you have to count the number of pairs (l, r) such that 1 ≤ l ≤ r ≤ n and gcd(a_{l}, a_{l} + 1, ..., a_{r}) = x_{i}.

$\operatorname{gcd}(v_{1}, v_{2}, \ldots, v_{n})$ is a greatest common divisor of v_1, v_2, ..., v_{n}, that is equal to a largest positive integer that divides all v_{i}.

-----Input-----

The first line of the input contains integer n, (1 ≤ n ≤ 10^5), denoting the length of the sequence. The next line contains n space separated integers a_1, ..., a_{n}, (1 ≤ a_{i} ≤ 10^9).

The third line of the input contains integer q, (1 ≤ q ≤ 3 × 10^5), denoting the number of queries. Then follows q lines, each contain an integer x_{i}, (1 ≤ x_{i} ≤ 10^9).

-----Output-----

For each query print the result in a separate line.

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

Output
1
2
2
0
1

Input
7
10 20 3 15 1000 60 16
10
1
2
3
4
5
6
10
20
60
1000

Output
14
0
2
2
2
0
2
2
1
1

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

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

n = int(input())
arr = list(map(int, input().rstrip().split(" ")))
q = int(input())

d = defaultdict(lambda : 0)

current = defaultdict(lambda : 0)

for i in range(n):
    newCurrent = defaultdict(lambda : 0)
    newCurrent[arr[i]] += 1
    for key, value in current.items():
        g = math.gcd(arr[i], key)
        newCurrent[g] += value

    for key, value in newCurrent.items():
        d[key] += value

    current = newCurrent

for _ in range(q):
    x = int(input())
    print(d[x])


I found an interesting problem on https://codeforces.com/problemset/problem/476/A:
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.

What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?

-----Input-----

The single line contains two space separated integers n, m (0 < n ≤ 10000, 1 < m ≤ 10).

-----Output-----

Print a single integer — the minimal number of moves being a multiple of m. If there is no way he can climb satisfying condition print  - 1 instead.

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

Output
6

Input
3 5

Output
-1

-----Note-----

For the first sample, Dreamoon could climb in 6 moves with following sequence of steps: {2, 2, 2, 2, 1, 1}.

For the second sample, there are only three valid sequence of steps {2, 1}, {1, 2}, {1, 1, 1} with 2, 2, and 3 steps respectively. All these numbers are not multiples of 5.

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

n, m = list(map(int, input().split()))
Min = (n + 1) // 2;
while Min <= n and Min % m != 0:
	Min += 1;
if Min <= n:
	print(Min)
else:
	print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/476/B:
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.

Each command is one of the following two types:   Go 1 unit towards the positive direction, denoted as '+'  Go 1 unit towards the negative direction, denoted as '-'

But the Wi-Fi condition is so poor that Dreamoon's smartphone reports some of the commands can't be recognized and Dreamoon knows that some of them might even be wrong though successfully recognized. Dreamoon decides to follow every recognized command and toss a fair coin to decide those unrecognized ones (that means, he moves to the 1 unit to the negative or positive direction with the same probability 0.5).

You are given an original list of commands sent by Drazil and list received by Dreamoon. What is the probability that Dreamoon ends in the position originally supposed to be final by Drazil's commands?

-----Input-----

The first line contains a string s_1 — the commands Drazil sends to Dreamoon, this string consists of only the characters in the set {'+', '-'}.

The second line contains a string s_2 — the commands Dreamoon's smartphone recognizes, this string consists of only the characters in the set {'+', '-', '?'}. '?' denotes an unrecognized command.

Lengths of two strings are equal and do not exceed 10.

-----Output-----

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

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

Output
1.000000000000

Input
+-+-
+-??

Output
0.500000000000

Input
+++
??-

Output
0.000000000000

-----Note-----

For the first sample, both s_1 and s_2 will lead Dreamoon to finish at the same position  + 1.

For the second sample, s_1 will lead Dreamoon to finish at position 0, while there are four possibilites for s_2: {"+-++", "+-+-", "+--+", "+---"} with ending position {+2, 0, 0, -2} respectively. So there are 2 correct cases out of 4, so the...

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

import math

#input

s1=str(input())
s2=str(input())

#variables
sum1=0
sum2=0
steps=0

def prob(x,y):
	if x>y:
		return 0
	elif y==0:
		if x==0:
			return 1
		else:
			return 0
	else:
		return (prob(x-1,y-1)+prob(x+1,y-1))/2

#main
for i in range(len(s1)):
	if s1[i]=='+':
		sum1+=1
	if s1[i]=='-':
		sum1-=1
	if s2[i]=='+':
		sum2+=1
	if s2[i]=='-':
		sum2-=1
	if s2[i]=='?':
		steps+=1

end=sum2-sum1

print(prob(end,steps))


I found an interesting problem on https://codeforces.com/problemset/problem/476/D:
Dreamoon likes to play with sets, integers and $gcd$. $\operatorname{gcd}(a, b)$ is defined as the largest positive integer that divides both a and b.

Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements s_{i}, s_{j} from S, $\operatorname{gcd}(s_{i}, s_{j}) = k$.

Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.

-----Input-----

The single line of the input contains two space separated integers n, k (1 ≤ n ≤ 10 000, 1 ≤ k ≤ 100).

-----Output-----

On the first line print a single integer — the minimal possible m.

On each of the next n lines print four space separated integers representing the i-th set.

Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.

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

Output
5
1 2 3 5

Input
2 2

Output
22
2 4 6 22
14 18 10 16

-----Note-----

For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since $\operatorname{gcd}(2,4) = 2 \neq 1$.

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

k = 0
i = 1
a = []
while k <10000:
	b = []
	b.append(i)
	b.append(i+1)
	b.append(i+2)
	b.append(i+4)
	i += 6
	a.append(b)
	k += 1
n, k = tuple(map(int, input().split()))
print(a[n-1][3]*k)
for i in range(0, n):
	print(a[i][0]*k, a[i][1]*k, a[i][2]*k, a[i][3]*k)


I found an interesting problem on https://codeforces.com/problemset/problem/476/E:
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates $\operatorname{occ}(s^{\prime}, p)$ that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.

More formally, let's define $\operatorname{ans}(x)$ as maximum value of $\operatorname{occ}(s^{\prime}, p)$ over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know $\operatorname{ans}(x)$ for all x from 0 to |s| where |s| denotes the length of string s.

-----Input-----

The first line of the input contains the string s (1 ≤ |s| ≤ 2 000).

The second line of the input contains the string p (1 ≤ |p| ≤ 500).

Both strings will only consist of lower case English letters.

-----Output-----

Print |s| + 1 space-separated integers in a single line representing the $\operatorname{ans}(x)$ for all x from 0 to |s|.

-----Examples-----
Input
aaaaa
aa

Output
2 2 1 1 0 0

Input
axbaxxb
ab

Output
0 1 1 2 1 1 0 0

-----Note-----

For the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}.

For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}.

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

s, p = input(), input()
n, m = len(s) + 1, len(p)
d = [[0] * n for t in range(n)]
for x in range(1, n):
    i, j = x, m
    while i and j:
        j -= s[i - 1] == p[j - 1]
        i -= 1
    if not j:
        for y in range(i + 1): d[x][y + x - i - m] = d[i][y] + 1
    for y in range(x): d[x][y] = max(d[x][y], d[x - 1][y])
print(*d[-1])


I found an interesting problem on https://codeforces.com/problemset/problem/478/A:
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player.

Your task is to write a program that can, given the number of coins each player has at the end of the game, determine the size b of the initial bet or find out that such outcome of the game cannot be obtained for any positive number of coins b in the initial bet.

-----Input-----

The input consists of a single line containing five integers c_1, c_2, c_3, c_4 and c_5 — the number of coins that the first, second, third, fourth and fifth players respectively have at the end of the game (0 ≤ c_1, c_2, c_3, c_4, c_5 ≤ 100).

-----Output-----

Print the only line containing a single positive integer b — the number of coins in the initial bet of each player. If there is no such value of b, then print the only value "-1" (quotes for clarity).

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

Output
3

Input
4 5 9 2 1

Output
-1

-----Note-----

In the first sample the following sequence of operations is possible:  One coin is passed from the fourth player to the second player;  One coin is passed from the fourth player to the fifth player;  One coin is passed from the first player to the third player;  One coin is passed from the fourth player to the second player.

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

a,b,c,d,e=map(int,input().split())
sum=a+b+c+d+e

if sum>0 and sum%5==0:
    print(sum//5)
else: print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/478/B:
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.

Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition.

-----Input-----

The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 10^9) — the number of participants and the number of teams respectively.

-----Output-----

The only line of the output should contain two integers k_{min} and k_{max} — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively.

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

Output
10 10

Input
3 2

Output
1 1

Input
6 3

Output
3 6

-----Note-----

In the first sample all the participants get into one team, so there will be exactly ten pairs of friends.

In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one.

In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people.

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

n, m = map(int, input().split())
if n == m:
    print(0, 0)
elif n == m+1:
    print(1, 1)
else:
    p = n-m+1
    maxi = p*(p-1)//2
    d = n//m
    if d == 1:
        mini = n - m
    else:
        if n % m:
            d += 1
            remain = d*m-n
            mini = (d-1)*(d-2)//2*remain
            remain = n - remain*(d-1)
            remain //= d
            mini += d*(d-1)//2*remain
        else:
            mini = d*(d-1)//2*m
    print(mini, maxi)


I found an interesting problem on https://codeforces.com/problemset/problem/478/C:
You have r red, g green and b blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number t of tables can be decorated if we know number of balloons of each color?

Your task is to write a program that for given values r, g and b will find the maximum number t of tables, that can be decorated in the required manner.

-----Input-----

The single line contains three integers r, g and b (0 ≤ r, g, b ≤ 2·10^9) — the number of red, green and blue baloons respectively. The numbers are separated by exactly one space.

-----Output-----

Print a single integer t — the maximum number of tables that can be decorated in the required manner.

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

Output
4

Input
1 1 1

Output
1

Input
2 3 3

Output
2

-----Note-----

In the first sample you can decorate the tables with the following balloon sets: "rgg", "gbb", "brr", "rrg", where "r", "g" and "b" represent the red, green and blue balls, respectively.

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

"""
Codeforces Contest 273 Div 2 Problem C

Author  : chaotic_iak
Language: Python 3.3.4
"""

def main():
    a = read()
    a.sort()
    res = 0
    if a[1]-a[0] <= a[2]-a[1]:
        res += a[1]-a[0]
        a[1] -= res
        a[2] -= 2*res
        if 4*a[0] <= a[2]:
            print(res + 2*a[0])
            return
        else:
            n = (a[2] - a[0]) // 3
            res += 2*n
            a[0] -= n
            a[1] -= n
            a[2] -= 4*n
            if 0 < a[0] == a[2] - 2:
                res += 1
                a[0] -= 1
                a[2] -= 2
            print(res + a[0])
            return
    else:
        res += a[2]-a[1]
        a[1] -= res
        a[2] -= 2*res
        n = (a[1] - a[0]) // 3
        res += 2*n
        a[1] -= 3*n
        a[2] -= 3*n
        if a[1] == a[0]+2:
            res += 1
            a[1] -= 2
            a[2] -= 1
        print(res + a[0])
        return

################################### NON-SOLUTION STUFF BELOW

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 list(map(int, inputs.split()))

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

import itertools
write(main())


I found an interesting problem on https://codeforces.com/problemset/problem/479/A:
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets:  1+2*3=7  1*(2+3)=5  1*2*3=6  (1+2)*3=9

Note that you can insert operation signs only between a and b, and between b and c, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2.

It's easy to see that the maximum value that you can obtain is 9.

Your task is: given a, b and c print the maximum value that you can get.

-----Input-----

The input contains three integers a, b and c, each on a single line (1 ≤ a, b, c ≤ 10).

-----Output-----

Print the maximum value of the expression that you can obtain.

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

Output
9

Input
2
10
3

Output
60

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

a = int(input())
b = int(input())
c = int(input())
if a == 1:
    print(max((a + b) * c, a + b + c))
elif b == 1:
    print(max([(a + b) * c, a * (b + c), a + b + c]))
elif c == 1:
    print(max(a * (b + c), a + b + c))
else:
    print(a * b * c)


I found an interesting problem on https://codeforces.com/problemset/problem/479/B:
As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of a_{i} cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2).

The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time.

Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task.

-----Input-----

The first line contains two space-separated positive integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000) — the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers a_{i} (1 ≤ a_{i} ≤ 10^4) — the towers' initial heights.

-----Output-----

In the first line print two space-separated non-negative integers s and m (m ≤ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that.

In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i ≠ j). Note that in the process of performing operations the heights of some towers can become equal to zero.

If...

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

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

inst = max(t) - min(t)
i = 0
steps = []

while inst > 0 and i < k:
    imax = t.index(max(t))
    imin = t.index(min(t))
    steps.append(imax+1)
    steps.append(imin+1)

    t[imax] -= 1
    t[imin] += 1
    inst = max(t) - min(t)
    i += 1

print(inst, i)
for i in range(0, len(steps), 2):
    print(steps[i], steps[i+1])


I found an interesting problem on https://codeforces.com/problemset/problem/479/C:
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.

According to the schedule, a student can take the exam for the i-th subject on the day number a_{i}. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day b_{i} (b_{i} < a_{i}). Thus, Valera can take an exam for the i-th subject either on day a_{i}, or on day b_{i}. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number a_{i}.

Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.

-----Input-----

The first line contains a single positive integer n (1 ≤ n ≤ 5000) — the number of exams Valera will take.

Each of the next n lines contains two positive space-separated integers a_{i} and b_{i} (1 ≤ b_{i} < a_{i} ≤ 10^9) — the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly.

-----Output-----

Print a single integer — the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date.

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

Output
2

Input
3
6 1
5 2
4 3

Output
6

-----Note-----

In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher...

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

import math
import random
import itertools
import collections
import sys
import time
import fractions
import os
import functools
import bisect

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

def contains(l, elem):
    index = bisect.bisect_left(l, elem)
    if index < len(l):
        return l[index] == elem
    return False

n = int(input())

array = []
for i in range(n):
    array.append(list(map(int, input().split(' '))))

array = sorted(array, key = lambda x:x[0]*100+x[1])
currentDate = 0

#print(array)

for i in range(len(array)):
    if array[i][0]>=currentDate and array[i][1]>=currentDate:
        currentDate = min(array[i][0], array[i][1])
    else:
        if array[i][0]>currentDate:
            currentDate = array[i][0]
        else:
            if array[i][1]>currentDate:
                currentDate = array[i][1]
    #print(currentDate)

print(currentDate)

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


I found an interesting problem on https://codeforces.com/problemset/problem/479/D:
Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler!

However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a_1, a_2, ..., a_{n}, where a_{i} denotes the distance of the i-th mark from the origin (a_1 = 0, a_{n} = l).

Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1 ≤ i ≤ j ≤ n), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, a_{j} - a_{i} = d).

Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (x < y) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y.

Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.

-----Input-----

The first line contains four positive space-separated integers n, l, x, y (2 ≤ n ≤ 10^5, 2 ≤ l ≤ 10^9, 1 ≤ x < y ≤ l) — the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly.

The second line contains a sequence of n integers a_1, a_2, ..., a_{n} (0 = a_1 < a_2 < ... < a_{n} = l), where a_{i} shows the distance from the i-th mark to the origin.

-----Output-----

In the first line print a single non-negative integer v —...

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

#Adapted from code of hatsuyuki15 in this contest
n, l, x, y = list(map(int, input().split()))
a = set(map(int, input().split()))
boy = False
girl = False
one = False
where = -1
for i in a:
    if i + x in a:
        boy = True
    if i + y in a:
        girl = True
    if i - x > 0 and i - x + y in a:
        one = True
        where = i - x
    if i + x < l and i + x - y in a:
        one = True
        where = i + x
    if i + x + y in a:
        one = True
        where = i + x
    if i - x - y in a:
        one = True
        where = i - x

if boy and girl:
    print(0)
if boy and not girl:
    print(1)
    print(y)
if girl and not boy:
    print(1)
    print(x)
if not boy and not girl:
    if one:
        print(1)
        print(where)
    if not one:
        print(2)
        print(x, y)


I found an interesting problem on https://codeforces.com/problemset/problem/483/A:
Your friend has recently learned about coprime numbers. A pair of numbers {a, b} is called coprime if the maximum number that divides both a and b is equal to one.

Your friend often comes up with different statements. He has recently supposed that if the pair (a, b) is coprime and the pair (b, c) is coprime, then the pair (a, c) is coprime.

You want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers (a, b, c), for which the statement is false, and the numbers meet the condition l ≤ a < b < c ≤ r.

More specifically, you need to find three numbers (a, b, c), such that l ≤ a < b < c ≤ r, pairs (a, b) and (b, c) are coprime, and pair (a, c) is not coprime.

-----Input-----

The single line contains two positive space-separated integers l, r (1 ≤ l ≤ r ≤ 10^18; r - l ≤ 50).

-----Output-----

Print three positive space-separated integers a, b, c — three distinct numbers (a, b, c) that form the counterexample. If there are several solutions, you are allowed to print any of them. The numbers must be printed in ascending order.

If the counterexample does not exist, print the single number -1.

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

Output
2 3 4

Input
10 11

Output
-1

Input
900000000000000009 900000000000000029

Output
900000000000000009 900000000000000010 900000000000000021

-----Note-----

In the first sample pair (2, 4) is not coprime and pairs (2, 3) and (3, 4) are.

In the second sample you cannot form a group of three distinct integers, so the answer is -1.

In the third sample it is easy to see that numbers 900000000000000009 and 900000000000000021 are divisible by three.

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

def nod(x, y):
    while min(x, y) > 0 and x != y:
        if x > y:
            x = x % y
        else:
            y = y % x
    return max(x, y)
def is_me_right(left, right):
    for a in range(l, r - 1):
        for b in range(a + 1, r):
            for c in range(b + 1, r + 1):
                if (nod(a, b) == 1) and (nod(b, c) == 1) and (nod(a, c) != 1):
                    return True, a, b, c
    return False, 1, 1, 1
l, r = list(map(int, input().split()))
imr, a, b, c = is_me_right(l, r)
if imr:
    print(a, b, c)
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/483/B:
You have two friends. You want to present each of them several positive integers. You want to present cnt_1 numbers to the first friend and cnt_2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.

In addition, the first friend does not like the numbers that are divisible without remainder by prime number x. The second one does not like the numbers that are divisible without remainder by prime number y. Of course, you're not going to present your friends numbers they don't like.

Your task is to find such minimum number v, that you can form presents using numbers from a set 1, 2, ..., v. Of course you may choose not to present some numbers at all.

A positive integer number greater than 1 is called prime if it has no positive divisors other than 1 and itself.

-----Input-----

The only line contains four positive integers cnt_1, cnt_2, x, y (1 ≤ cnt_1, cnt_2 < 10^9; cnt_1 + cnt_2 ≤ 10^9; 2 ≤ x < y ≤ 3·10^4) — the numbers that are described in the statement. It is guaranteed that numbers x, y are prime.

-----Output-----

Print a single integer — the answer to the problem.

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

Output
5

Input
1 3 2 3

Output
4

-----Note-----

In the first sample you give the set of numbers {1, 3, 5} to the first friend and the set of numbers {2} to the second friend. Note that if you give set {1, 3, 5} to the first friend, then we cannot give any of the numbers 1, 3, 5 to the second friend.

In the second sample you give the set of numbers {3} to the first friend, and the set of numbers {1, 2, 4} to the second friend. Thus, the answer to the problem is 4.

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

def valid(n1, n2, p1, p2, mid):
    x = mid - mid//p1
    y = mid - mid//p2
    rem = mid - mid//(p1*p2)
    return x < n1 or y < n2 or rem < n1+n2

def binary_search(n1, n2, p1, p2):
    l, r = 0, 1<<61
    while (l <= r):
        mid = l+r >> 1
        if (valid(n1, n2, p1, p2, mid)):
            l = mid+1
        else:
            r = mid-1
    return l

def main():
    n1, n2, p1, p2 = map(int, input().split())
    print(binary_search(n1, n2, p1, p2))

main()


I found an interesting problem on https://codeforces.com/problemset/problem/485/A:
One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were x details in the factory storage, then by the end of the day the factory has to produce $x \operatorname{mod} m$ (remainder after dividing x by m) more details. Unfortunately, no customer has ever bought any mythical detail, so all the details produced stay on the factory.

The board of directors are worried that the production by the given plan may eventually stop (that means that there will be а moment when the current number of details on the factory is divisible by m).

Given the number of details a on the first day and number m check if the production stops at some moment.

-----Input-----

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

-----Output-----

Print "Yes" (without quotes) if the production will eventually stop, otherwise print "No".

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

Output
No

Input
3 6

Output
Yes

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

ip=list(int(n) for n in input().split())
import math
a=ip[0]
m=ip[1]
a%=m
af=[a]
x=1;k=1;count=0;countlimit=int(math.floor(math.log(m,2)))
while (k==1):
	a=((a+a%m)%m)
	if a==0:
		print("Yes")
		k=0
	else:
		for check in af:
			if a==check:
				print("No")
				k=0
	if	count<=countlimit:
			af.append(a)
			count+=1
return


I found an interesting problem on https://codeforces.com/problemset/problem/485/B:
Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems.

Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. The map contains mines with valuable resources, located at some points with integer coordinates. The sizes of mines are relatively small, i.e. they can be treated as points. The city should be built in such a way that all the mines are inside or on the border of the city square.

Building a city takes large amount of money depending on the size of the city, so you have to build the city with the minimum area. Given the positions of the mines find the minimum possible area of the city.

-----Input-----

The first line of the input contains number n — the number of mines on the map (2 ≤ n ≤ 1000). Each of the next n lines contains a pair of integers x_{i} and y_{i} — the coordinates of the corresponding mine ( - 10^9 ≤ x_{i}, y_{i} ≤ 10^9). All points are pairwise distinct.

-----Output-----

Print the minimum area of the city that can cover all the mines with valuable resources.

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

Output
4

Input
2
0 0
0 3

Output
9

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

#!/bin/env python3
n=int(input())
x,y=input().split(' ')
x,y=int(x),int(y)
min_y=y
max_y=y
min_x=x
max_x=x

for x in range(n-1):
    x,y=input().split(' ')
    x,y=int(x),int(y)
    if x>max_x:
        max_x=x
    if x<min_x:
        min_x=x
    if y>max_y:
        max_y=y
    if y<min_y:
        min_y=y

print(max((max_y-min_y),(max_x-min_x))**2)


I found an interesting problem on https://codeforces.com/problemset/problem/486/A:
For a positive integer n let's define a function f:

f(n) =  - 1 + 2 - 3 + .. + ( - 1)^{n}n

Your task is to calculate f(n) for a given integer n.

-----Input-----

The single line contains the positive integer n (1 ≤ n ≤ 10^15).

-----Output-----

Print f(n) in a single line.

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

Output
2

Input
5

Output
-3

-----Note-----

f(4) =  - 1 + 2 - 3 + 4 = 2

f(5) =  - 1 + 2 - 3 + 4 - 5 =  - 3

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

n = int(input())
summ = 0
if n % 2 == 0:
    summ = n // 2
else:
    summ = -(n // 2 + 1)
print(summ)


I found an interesting problem on https://codeforces.com/problemset/problem/486/B:
Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner:

$a_{1} OR a_{2} OR \ldots OR a_{k}$ where $a_{i} \in \{0,1 \}$ is equal to 1 if some a_{i} = 1, otherwise it is equal to 0.

Nam has a matrix A consisting of m rows and n columns. The rows are numbered from 1 to m, columns are numbered from 1 to n. Element at row i (1 ≤ i ≤ m) and column j (1 ≤ j ≤ n) is denoted as A_{ij}. All elements of A are either 0 or 1. From matrix A, Nam creates another matrix B of the same size using formula:

[Image].

(B_{ij} is OR of all elements in row i and column j of matrix A)

Nam gives you matrix B and challenges you to guess matrix A. Although Nam is smart, he could probably make a mistake while calculating matrix B, since size of A can be large.

-----Input-----

The first line contains two integer m and n (1 ≤ m, n ≤ 100), number of rows and number of columns of matrices respectively.

The next m lines each contain n integers separated by spaces describing rows of matrix B (each element of B is either 0 or 1).

-----Output-----

In the first line, print "NO" if Nam has made a mistake when calculating B, otherwise print "YES". If the first line is "YES", then also print m rows consisting of n integers representing matrix A that can produce given matrix B. If there are several solutions print any one.

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

Output
NO

Input
2 3
1 1 1
1 1 1

Output
YES
1 1 1
1 1 1

Input
2 3
0 1 0
1 1 1

Output
YES
0 0 0
0 1 0

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

def main():
    n, m = map(int, input().split())
    l = tuple(tuple(map(int, input().split())) for _ in range(n))
    res = [[1] * m for _ in range(n)]
    for y, row in enumerate(l):
        for x, f in enumerate(row):
            if not f:
                res[y] = [0] * m
                for rr in res:
                    rr[x] = 0
    for y, row in enumerate(l):
        for x, f in enumerate(row):
            if f:
                if not (any(res[y]) or any(rr[x] for rr in res)):
                    print('NO')
                    return
    print('YES')
    for rr in res:
        print(*rr)

def __starting_point():
    main()
__starting_point()