I found an interesting problem on https://codeforces.com/problemset/problem/723/E:
There are n cities and m two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads.

The road minister decided to make a reform in Berland and to orient all roads in the country, i.e. to make each road one-way. The minister wants to maximize the number of cities, for which the number of roads that begins in the city equals to the number of roads that ends in it.

-----Input-----

The first line contains a positive integer t (1 ≤ t ≤ 200) — the number of testsets in the input.

Each of the testsets is given in the following way. The first line contains two integers n and m (1 ≤ n ≤ 200, 0 ≤ m ≤ n·(n - 1) / 2) — the number of cities and the number of roads in Berland.

The next m lines contain the description of roads in Berland. Each line contains two integers u and v (1 ≤ u, v ≤ n) — the cities the corresponding road connects. It's guaranteed that there are no self-loops and multiple roads. It is possible that there is no way along roads between a pair of cities.

It is guaranteed that the total number of cities in all testset of input data doesn't exceed 200.

Pay attention that for hacks, you can only use tests consisting of one testset, so t should be equal to one.

-----Output-----

For each testset print the maximum number of such cities that the number of roads that begins in the city, is equal to the number of roads that ends in it.

In the next m lines print oriented roads. First print the number of the city where the road begins and then the number of the city where the road ends. If there are several answers, print any of them. It is allowed to print roads in each test in arbitrary order. Each road should be printed exactly once.

-----Example-----
Input
2
5 5
2 1
4 5
2 3
1 3
3 5
7 2
3 7
4 2

Output
3
1 3
3 5
5 4
3 2
2 1
3
2 4
3 7

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

import sys
from collections import defaultdict

rlines = sys.stdin.readlines()
lines = (l.strip() for l in rlines)

def eucycle(n,m,adj):
	dir_edges = []
	us = list(adj.keys())
	for u in us:
		while adj[u]:
			v0 = u
			v1 = adj[v0].pop()
			adj[v1].remove(v0)
			dir_edges.append((v0, v1))
			while v1 != u:
				v0 = v1
				v1 = adj[v0].pop()
				adj[v1].remove(v0)
				dir_edges.append((v0, v1))
	return dir_edges

def solve(n,m,edges):
	adj = defaultdict(set)
	for u, v in edges:
		adj[u].add(v)
		adj[v].add(u)

	odds = set(u for u in adj if len(adj[u])%2==1)

	for odd in odds:
 		adj[odd].add(n+1)
 		adj[n+1].add(odd)
	total = n - len(odds)
	dir_edges = eucycle(n+1, m, adj)
	return total, dir_edges

t = int(next(lines))

for ti in range(t):
	n,m = [int(s) for s in next(lines).split()]
	edges = []
	for ei in range(m):
		u,v = [int(s) for s in next(lines).split()]
		edges.append((u,v))
	total, ans = solve(n,m,edges)
	print(total)
	print('\n'.join(str(u)+ ' '+ str(v) for u, v in ans if u != n+1 and v!= n+1))


I found an interesting problem on https://codeforces.com/problemset/problem/724/A:
You are given names of two days of the week.

Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong to one year.

In this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. The number of days in months during any non-leap year is: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31.

Names of the days of the week are given with lowercase English letters: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".

-----Input-----

The input consists of two lines, each of them containing the name of exactly one day of the week. It's guaranteed that each string in the input is from the set "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".

-----Output-----

Print "YES" (without quotes) if such situation is possible during some non-leap year. Otherwise, print "NO" (without quotes).

-----Examples-----
Input
monday
tuesday

Output
NO

Input
sunday
sunday

Output
YES

Input
saturday
tuesday

Output
YES

-----Note-----

In the second sample, one can consider February 1 and March 1 of year 2015. Both these days were Sundays.

In the third sample, one can consider July 1 and August 1 of year 2017. First of these two days is Saturday, while the second one is Tuesday.

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

names = {"monday":0, "tuesday":1, "wednesday":2, "thursday":3, "friday":4, "saturday":5, "sunday":6,}

a = names[input().strip()]
b = names[input().strip()]

if (a == b) or ((a + 2) % 7 == b) or ((a + 3) % 7 == b):
	print("YES")
else:
	print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/724/B:
You are given a table consisting of n rows and m columns.

Numbers in each row form a permutation of integers from 1 to m.

You are allowed to pick two elements in one row and swap them, but no more than once for each row. Also, no more than once you are allowed to pick two columns and swap them. Thus, you are allowed to perform from 0 to n + 1 actions in total. Operations can be performed in any order.

You have to check whether it's possible to obtain the identity permutation 1, 2, ..., m in each row. In other words, check if one can perform some of the operation following the given rules and make each row sorted in increasing order.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 20) — the number of rows and the number of columns in the given table.

Each of next n lines contains m integers — elements of the table. It's guaranteed that numbers in each line form a permutation of integers from 1 to m.

-----Output-----

If there is a way to obtain the identity permutation in each row by following the given rules, print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).

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

Output
YES

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

Output
NO

Input
3 6
2 1 3 4 5 6
1 2 4 3 5 6
1 2 3 4 6 5

Output
YES

-----Note-----

In the first sample, one can act in the following way:   Swap second and third columns. Now the table is 1 2 3 4 1 4 3 2  In the second row, swap the second and the fourth elements. Now the table is 1 2 3 4 1 2 3 4

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

import sys

def swapC(c1, c2):
    for r in range(n):
        swap(r, c1, c2)

def swap(r, c1, c2):
    nums[r][c1], nums[r][c2] = nums[r][c2], nums[r][c1]

def checkRow(r):
    bad = []
    for i in range(m):
        if nums[r][i] != i:
            bad.append(i)
    if len(bad) == 0:
        return True
    if len(bad) != 2:
        return False
    x0, x1 = nums[r][bad[0]], nums[r][bad[1]]
    return bad[0] == x1 and bad[1] == x0

def checkAll():
    for r in range(n):
        if not checkRow(r):
            return False
    return True

n, m = map(int, input().split())
nums = [list(map(lambda x: int(x) - 1, input().split())) for i in range(n)]

flag = False
for c1 in range(m):
    for c2 in range(c1, m):
        swapC(c1, c2)
        if checkAll():
            print("YES")
            flag = True
            break
        swapC(c1, c2)
    if flag:
        break
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/725/A:
In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 or i + 1 > n, the ball falls from the game field.

Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.

-----Output-----

Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.

-----Examples-----
Input
4
<<><

Output
2
Input
5
>>>>>

Output
5
Input
4
>><<

Output
0

-----Note-----

In the first sample, the ball will fall from the field if starts at position 1 or position 2.

In the second sample, any starting position will result in the ball falling from the field.

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

n = int(input())
s = input()
l = 0
ans = 0
while l < len(s) and s[l] == '<':
    ans += 1
    l += 1

r = n - 1
while r >= 0 and s[r] == '>':
    ans += 1
    r -= 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/725/B:
A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats 'd', 'e' and 'f' are located to the right. Seats 'a' and 'f' are located near the windows, while seats 'c' and 'd' are located near the aisle.  [Image]

It's lunch time and two flight attendants have just started to serve food. They move from the first rows to the tail, always maintaining a distance of two rows from each other because of the food trolley. Thus, at the beginning the first attendant serves row 1 while the second attendant serves row 3. When both rows are done they move one row forward: the first attendant serves row 2 while the second attendant serves row 4. Then they move three rows forward and the first attendant serves row 5 while the second attendant serves row 7. Then they move one row forward again and so on.

Flight attendants work with the same speed: it takes exactly 1 second to serve one passenger and 1 second to move one row forward. Each attendant first serves the passengers on the seats to the right of the aisle and then serves passengers on the seats to the left of the aisle (if one looks in the direction of the cockpit). Moreover, they always serve passengers in order from the window to the aisle. Thus, the first passenger to receive food in each row is located in seat 'f', and the last one — in seat 'c'. Assume that all seats are occupied.

Vasya has seat s in row n and wants to know how many seconds will pass before he gets his lunch.

-----Input-----

The only line of input contains a description of Vasya's seat in the format ns, where n (1 ≤ n ≤ 10^18) is the index of the row and s is the seat in this row, denoted as letter from 'a' to 'f'. The index of the row and the seat are not separated by a space.

-----Output-----

Print one integer — the number of...

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/725/C:
Let’s define a grid to be a set of tiles with 2 rows and 13 columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid: ABCDEFGHIJKLM

NOPQRSTUVWXYZ

We say that two tiles are adjacent if they share a side or a corner. In the example grid above, the tile with the letter 'A' is adjacent only to the tiles with letters 'B', 'N', and 'O'. A tile is not adjacent to itself.

A sequence of tiles is called a path if each tile in the sequence is adjacent to the tile which follows it (except for the last tile in the sequence, which of course has no successor). In this example, "ABC" is a path, and so is "KXWIHIJK". "MAB" is not a path because 'M' is not adjacent to 'A'. A single tile can be used more than once by a path (though the tile cannot occupy two consecutive places in the path because no tile is adjacent to itself).

You’re given a string s which consists of 27 upper-case English letters. Each English letter occurs at least once in s. Find a grid that contains a path whose tiles, viewed in the order that the path visits them, form the string s. If there’s no solution, print "Impossible" (without the quotes).

-----Input-----

The only line of the input contains the string s, consisting of 27 upper-case English letters. Each English letter occurs at least once in s.

-----Output-----

Output two lines, each consisting of 13 upper-case English characters, representing the rows of the grid. If there are multiple solutions, print any of them. If there is no solution print "Impossible".

-----Examples-----
Input
ABCDEFGHIJKLMNOPQRSGTUVWXYZ

Output
YXWVUTGHIJKLM
ZABCDEFSRQPON

Input
BUVTYZFQSNRIWOXXGJLKACPEMDH

Output
Impossible

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/725/D:
One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed.

You should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings.

A contest has just finished. There are n teams, numbered 1 through n. The i-th team has t_{i} balloons and weight w_{i}. It's guaranteed that t_{i} doesn't exceed w_{i} so nobody floats initially.

Limak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has.

What is the best place Limak can get?

-----Input-----

The first line of the standard input contains one integer n (2 ≤ n ≤ 300 000) — the number of teams.

The i-th of n following lines contains two integers t_{i} and w_{i} (0 ≤ t_{i} ≤ w_{i} ≤ 10^18) — respectively the number of balloons and the weight of the i-th team. Limak is a member of the first team.

-----Output-----

Print one integer denoting the best place Limak can get.

-----Examples-----
Input
8
20 1000
32 37
40 1000
45 50
16 16
16 16
14 1000
2 1000

Output
3

Input
7
4 4
4 4
4 4
4 4
4 4
4 4
5 5

Output
2

Input
7
14000000003 1000000000000000000
81000000000 88000000000
5000000000 7000000000
15000000000 39000000000
46000000000 51000000000
0 1000000000
0 0

Output
2

-----Note-----

In...

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

'''input
8
20 1000
32 37
40 1000
45 50
16 16
16 16
14 1000
2 1000
'''
import heapq
from bisect import bisect

inf = 10**18 + 2

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

def ri():
    return int(input())

def bin_search(arr, pred, lo=0, hi = None):
    if hi is None:
        hi = len(arr)
    while lo < hi :
        mid = (lo+hi) // 2
        if pred(arr[mid]):
            hi = mid
        else:
            lo = mid + 1
    return lo

n = ri()
score, _ = rints()

teams = []
for _ in range(n-1):
    t, w = rints()
    teams.append((w-t + 1, t, w))

teams.sort(key = lambda x : x[1])
# print(teams)

def solve(score):
    idx = bin_search(teams, lambda x : x[1] > score)
    best = pos = len(teams) - idx + 1
    # print(teams[idx:], pos)

    ahead = teams[idx:]
    behind = teams[:idx]
    heapq.heapify(ahead)
    # print(ahead)

    while ahead and score >= ahead[0][0]:
        score -= heapq.heappop(ahead)[0]
        pos -= 1
        while behind and behind[-1][1] > score:
            heapq.heappush(ahead, behind.pop())
            pos += 1
        # print(score, pos)
        best = min(best, pos)

    return best

print(solve(score))


I found an interesting problem on https://codeforces.com/problemset/problem/727/A:
Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations:  multiply the current number by 2 (that is, replace the number x by 2·x);  append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1).

You need to help Vasily to transform the number a into the number b using only the operations described above, or find that it is impossible.

Note that in this task you are not required to minimize the number of operations. It suffices to find any way to transform a into b.

-----Input-----

The first line contains two positive integers a and b (1 ≤ a < b ≤ 10^9) — the number which Vasily has and the number he wants to have.

-----Output-----

If there is no way to get b from a, print "NO" (without quotes).

Otherwise print three lines. On the first line print "YES" (without quotes). The second line should contain single integer k — the length of the transformation sequence. On the third line print the sequence of transformations x_1, x_2, ..., x_{k}, where:  x_1 should be equal to a,  x_{k} should be equal to b,  x_{i} should be obtained from x_{i} - 1 using any of two described operations (1 < i ≤ k).

If there are multiple answers, print any of them.

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

Output
YES
5
2 4 8 81 162

Input
4 42

Output
NO

Input
100 40021

Output
YES
5
100 200 2001 4002 40021

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

a, b = [int(x) for x in input().split()]
ans = [b]
while b > a:
    if b % 2 == 1 and str(b)[-1] != '1':
        print("NO")
        break
    if b % 2 == 1 and str(b)[-1] == '1':
        b = b // 10
        ans.append(b)
        continue
    if b % 2 == 0:
        b = b // 2
        ans.append(b)
        continue
else:
    if b != a:
        print("NO")
    else:
        print("YES")
        print(len(ans))
        for i in range(len(ans)):
            print(ans[len(ans) - i - 1], end = " ")


I found an interesting problem on https://codeforces.com/problemset/problem/727/B:
Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "name_1price_1name_2price_2...name_{n}price_{n}", where name_{i} (name of the i-th purchase) is a non-empty string of length not more than 10, consisting of lowercase English letters, and price_{i} (the price of the i-th purchase) is a non-empty string, consisting of digits and dots (decimal points). It is possible that purchases with equal names have different prices.

The price of each purchase is written in the following format. If the price is an integer number of dollars then cents are not written.

Otherwise, after the number of dollars a dot (decimal point) is written followed by cents in a two-digit format (if number of cents is between 1 and 9 inclusively, there is a leading zero).

Also, every three digits (from less significant to the most) in dollars are separated by dot (decimal point). No extra leading zeroes are allowed. The price always starts with a digit and ends with a digit.

For example:  "234", "1.544", "149.431.10", "0.99" and "123.05" are valid prices,  ".333", "3.33.11", "12.00", ".33", "0.1234" and "1.2" are not valid.

Write a program that will find the total price of all purchases in the given bill.

-----Input-----

The only line of the input contains a non-empty string s with length not greater than 1000 — the content of the bill.

It is guaranteed that the bill meets the format described above. It is guaranteed that each price in the bill is not less than one cent and not greater than 10^6 dollars.

-----Output-----

Print the total price exactly in the same format as prices given in the input.

-----Examples-----
Input
chipsy48.32televizor12.390

Output
12.438.32

Input
a1b2c3.38

Output
6.38

Input
aa0.01t0.03

Output
0.04

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

import sys, math
s = input()
gg = 0
i = 0
dbl = 0
while i < len(s):
    if 'a' <= s[i] <= 'z':
        i += 1
        continue
    h = '000'
    while i < len(s) and  not 'a' <= s[i] <= 'z':
        h += s[i]
        i += 1
    ans = ''
    if h[-3] == '.':
        dbl += int(h[-2:])
        h = h[:-3]
    for z in h:
        if z != '.':
            ans += z
    gg += int(ans)
#print(gg, dbl)
dd = []
gg += dbl // 100
dbl = dbl % 100
gg = gg
if dbl != 0:
    dbl = str(dbl)
    while len(dbl) < 2:
        dbl = '0' + dbl
    dd.append(dbl)
#print(dd)
if gg == 0:
    dd.append(0)
while gg != 0:
    dd.append(str(gg % 1000))
    if (gg >= 1000):
        while len(dd[-1]) < 3:
            dd[-1] = '0' + dd[-1]
    gg //= 1000
dd.reverse()
print(*dd, sep = '.')


I found an interesting problem on https://codeforces.com/problemset/problem/727/D:
The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.

During the registration, the organizers asked each of the n participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.

Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size:   the size he wanted, if he specified one size;  any of the two neibouring sizes, if he specified two sizes.

If it is possible, the program should find any valid distribution of the t-shirts.

-----Input-----

The first line of the input contains six non-negative integers — the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100 000.

The second line contains positive integer n (1 ≤ n ≤ 100 000) — the number of participants.

The following n lines contain the sizes specified by the participants, one line per participant. The i-th line contains information provided by the i-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring.

-----Output-----

If it is not possible to present a t-shirt to each participant, print «NO» (without quotes).

Otherwise, print n + 1 lines. In the first line print «YES» (without quotes). In the following n lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input.

If there are...

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

d = {}
d["S"] = 0
d["M"] = 1
d["L"] = 2
d["XL"] = 3
d["XXL"] = 4
d["XXXL"] = 5

cnt = [int(t) for t in input().split()]
n = int(input())
ind = [i for i in range(n)]
p = []
for i in range(n):
    p.append(input().split(','))
ind.sort(key=lambda x:[d[p[x][0]], len(p[x])])
ans = {}
for i in ind:
    cur = p[i]
    if cnt[d[cur[0]]] != 0:
        ans[i] = cur[0]
        cnt[d[cur[0]]] -= 1
    elif len(cur) == 2 and cnt[d[cur[1]]] != 0:
        ans[i] = cur[1]
        cnt[d[cur[1]]] -= 1
    else:
        print("NO")
        return
print("YES")
for i in list(ans.keys()):
    print(ans[i])


I found an interesting problem on https://codeforces.com/problemset/problem/729/A:
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.

There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.

The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.

To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.

Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!

-----Input-----

The first line contains a positive integer n (1 ≤ n ≤ 100) — the length of the interview.

The second line contains the string s of length n, consisting of lowercase English letters.

-----Output-----

Print the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences.

-----Examples-----
Input
7
aogogob

Output
a***b

Input
13
ogogmgogogogo

Output
***gmg***

Input
9
ogoogoogo

Output
*********

-----Note-----

The first sample contains one filler word ogogo, so the interview for printing is "a***b".

The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***".

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

n = int(input())
s = input()
i = 0
ans = ''
while i < n:
    if i <= n - 3 and s[i:i + 3] == 'ogo':
        j = i + 3
        while j < n - 1:
            if s[j] == 'g' and s[j + 1] == 'o':
                j += 2
            else:
                break
        ans += '***'
        i = j
    else:
        ans += s[i]
        i += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/729/B:
Theater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.

You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.

A position is good if two conditions hold:   there is no actor in the cell the spotlight is placed to;  there is at least one actor in the direction the spotlight projects.

Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.

-----Input-----

The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the plan.

The next n lines contain m integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.

-----Output-----

Print one integer — the number of good positions for placing the spotlight.

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

Output
9

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

Output
20

-----Note-----

In the first example the following positions are good:  the (1, 1) cell and right direction;  the (1, 1) cell and down direction;  the (1, 3) cell and left direction;  the (1, 3) cell and down direction;  the (1, 4) cell and left direction;  the (2, 2) cell and left direction;  the (2, 2) cell and up direction;  the (2, 2) and right direction;  the (2, 4) cell and left direction.

Therefore, there are 9 good positions in this example.

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

def f(s):
    l, r = s.find('1'), s.rfind('1')
    if l == -1:
        return 0
    else:
        return l + len(s) - r - 1 + 2 * sum(s[i] == '0' for i in range(l + 1, r))
n, m = map(int, input().split())
a = [''.join(input().split()) for i in range(n)]
r = sum(f(s) for s in a)
c = sum(f(''.join(a[i][j] for i in range(n))) for j in range(m))
print(r + c)


I found an interesting problem on https://codeforces.com/problemset/problem/729/C:
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.

There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.

There are n cars in the rental service, i-th of them is characterized with two integers c_{i} and v_{i} — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity v_{i}. All cars are completely fueled at the car rental service.

Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.

Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.

-----Input-----

The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·10^5, 1 ≤ k ≤ 2·10^5, 2 ≤ s ≤ 10^9, 1 ≤ t ≤ 2·10^9) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts.

Each of the next n lines contains two positive integers c_{i} and v_{i} (1 ≤ c_{i}, v_{i} ≤ 10^9) — the price of the i-th car and its fuel tank capacity.

The next line contains k distinct integers g_1, g_2, ..., g_{k} (1 ≤ g_{i} ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.

-----Output-----

Print the minimum rent price of an appropriate car,...

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

# Question B. Road to Cinema
import sys

def roadToCinema(V, S, T, stations): # O(M)
    """
    V       : volume of fuel tank
    S       : total distance
    T       : time limit
    stations: fuel stations' locations

    rtype   : boolean, whether this aircraft can travel within the time limit
    """
    m = len(stations)
    t = 0
    stations.append(S) # destination
    prev = 0
    for cur in stations:
        dis = cur - prev
        # let Sa, Sb as the distance of accelerated mode/ normal mode respectively
        # then the task is:
        #  min t = (Sa + 2 * Sb)
        # s.t. Sa + Sb = dis
        #      2 * Sa + Sb <= V

        if dis > V:
            # Sa <= V - dis < 0
            return False
        else:
            # t = Sa + 2Sb = 3(Sa + Sb) - (2Sa + Sb)
            #   >= 3 * dis - V
            # on the other hand, Sb is non-negative
            # Sb = t - dis
            t += max(dis * 3 - V, dis)

        if t > T:
            return False

        prev = cur

    return True

def binSearch(S, T, stations): # O(logS * M)
    """
    to find the least tank volume to enable the aircraft to complete the journey
    the fastest way is to complete the whole journey with the speed of 2km/min, at 2L/km
    V <= 2S
    """
    l = 0
    r = S * 2

    if T < S:
        return float("inf")

    while l + 1 < r:
        m = l + (r - l) // 2
        if roadToCinema(m, S, T, stations) == True:
            r = m
        else:
            l = m

    return r

def __starting_point(): # O(logS * M + N)

    line = sys.stdin.readline()
    [N, M, S, T] = list(map(int, line.split(" ")))

    aircrafts = []
    for i in range(N):
        [c, v] = list(map(int, sys.stdin.readline().split(" ")))
        aircrafts.append([c, v])

    stations = list(map(int, sys.stdin.readline().split(" ")))
    stations.sort()

    minVolume = binSearch(S, T, stations)

    if minVolume == float("inf"):
        # no aircraft can complete the journey
        print(-1)
    else:
        res = float("inf")
  ...


I found an interesting problem on https://codeforces.com/problemset/problem/729/D:
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.

Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").

Galya has already made k shots, all of them were misses.

Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.

It is guaranteed that there is at least one valid ships placement.

-----Input-----

The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·10^5, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made.

The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.

-----Output-----

In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.

In the second line print the cells Galya should shoot at.

Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left.

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

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

Output
2
4 2

Input
13 3 2 3
1000000010001

Output
2
7 11

-----Note-----

There is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.

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

n,a,b,k=list(map(int,input().split()))
A=input()
B=A.split('1')
C=[]
l=1

for i in B:
    if len(i)>=b:
        for j in range(b-1,len(i),b):
            C.append(j+l)
    l+=len(i)+1
C=C[:len(C)-a+1]
print(len(C))
print(' '.join(list(map(str,C))))


I found an interesting problem on https://codeforces.com/problemset/problem/729/E:
There are n workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior.

There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate superior, the immediate superior of the his immediate superior, and so on. For example, if there are three workers in the company, from which the first is the chief, the second worker's immediate superior is the first, the third worker's immediate superior is the second, then the third worker has two superiors, one of them is immediate and one not immediate. The chief is a superior to all the workers except himself.

Some of the workers were in a hurry and made a mistake. You are to find the minimum number of workers that could make a mistake.

-----Input-----

The first line contains two positive integers n and s (1 ≤ n ≤ 2·10^5, 1 ≤ s ≤ n) — the number of workers and the id of the chief.

The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ n - 1), where a_{i} is the number of superiors (not only immediate) the worker with id i reported about.

-----Output-----

Print the minimum number of workers that could make a mistake.

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

Output
1

Input
5 3
1 0 0 4 1

Output
2

-----Note-----

In the first example it is possible that only the first worker made a mistake. Then:   the immediate superior of the first worker is the second worker,  the immediate superior of the third worker is the first worker,  the second worker is the chief.

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

""" This is a solution to the problem Subordinates on codeforces.com

    There is a DAG with n nodes, pointing towards the root, without further constraints.
    Given: for each node, a number signifying the count of (direct and indirect) predecessors, and the ID of root s.
    Some of these counts might be wrong. Give the minimum amount of wrong counts.

    For details, see
    http://codeforces.com/problemset/problem/729/E
"""

#Idea: count = level of DAG. Check constraints: root has 0 predecessors, level 0 has only one count, each level to the last has be > 0

from sys import stdin

#lines = open("input.txt", 'r').readlines()
lines = stdin.readlines()

n, s = map(int, lines[0].split())
counts = list(map(int, lines[1].split()))

totalwrong = 0
if counts[s-1] > 0: # root has to be 0
    totalwrong += 1
    counts[s-1] = 0

maxlevel = max(counts)
# count number of nodes on levels
levelcount = [0] * (max(counts) + 1)

for c in counts:
    levelcount[c] += 1

curwrong = levelcount[0] - 1 # only one root
levelcount[0] = 1
totalwrong += curwrong

curlevel = 0
while curlevel <= maxlevel:
    lc = levelcount[curlevel]
    if lc == 0:         # a mistake
        if curwrong > 0: # still mistakes available, just use them to fill
            curwrong -= 1
            levelcount[curlevel] = 1
        else: # else fill from last level
            levelcount[maxlevel] -= 1
            levelcount[curlevel] = 1
            totalwrong += 1
            while levelcount[maxlevel] == 0:
                maxlevel -= 1       # as levelcount[curlevel] = 1, this aborts at some point
    curlevel += 1
print(totalwrong)


I found an interesting problem on https://codeforces.com/problemset/problem/730/A:
A group of n friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the i-th friend is r_{i}.

The friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team consisting of all n friends. So the friends are faced with the problem: how to make all their ratings equal.

One way to change ratings is to willingly lose in some matches. Friends can form a party consisting of two to five (but not more than n) friends and play a match in the game. When the party loses, the rating of each of its members decreases by 1. A rating can't become negative, so r_{i} = 0 doesn't change after losing.

The friends can take part in multiple matches, each time making a party from any subset of friends (but remember about constraints on party size: from 2 to 5 members).

The friends want to make their ratings equal but as high as possible.

Help the friends develop a strategy of losing the matches so that all their ratings become equal and the resulting rating is maximum possible.

-----Input-----

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

The second line contains n non-negative integers r_1, r_2, ..., r_{n} (0 ≤ r_{i} ≤ 100), where r_{i} is the initial rating of the i-th friend.

-----Output-----

In the first line, print a single integer R — the final rating of each of the friends.

In the second line, print integer t — the number of matches the friends have to play. Each of the following t lines should contain n characters '0' or '1', where the j-th character of the i-th line is equal to:

  '0', if friend j should not play in match i,  '1', if friend j should play in match i.

Each line should contain between two and five characters '1', inclusive.

The value t should not exceed 10^4, it is guaranteed that such solution exists.

Remember that you shouldn't minimize the value t, but you should maximize R. If there are multiple...

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

n = int(input())
L = list(map(int, input().split()))
ans = 0
M = []
while max(L) != min(L):
    ans += 1
    k = max(L)
    if L.count(k) == 3:
        s = ''
        for i in range(len(L)):
            if L[i] == k:
                s += '1'
                L[i] -= 1
            else:
                s += '0'
        M.append(s)
    else:
        max_1 = 0
        max_2 = 1
        if L[max_1] < L[max_2]:
            max_1, max_2 = max_2, max_1
        for i in range(2, n):
            if L[i] > L[max_1]:
                max_2, max_1 = max_1, i
            elif L[i] > L[max_2]:
                max_2 = i
        s = ''
        for i in range(n):
            if i == max_1 or i == max_2:
                s += '1'
            else:
                s += '0'
        M.append(s)
        L[max_1] -= 1
        if L[max_1] < 0:
            L[max_1] = 0
        L[max_2] -= 1
        if L[max_2] < 0:
            L[max_2] = 0
print(max(L))
print(ans)
for i in M:
    print(i)


I found an interesting problem on https://codeforces.com/problemset/problem/730/H:
Polycarp is a beginner programmer. He is studying how to use a command line.

Polycarp faced the following problem. There are n files in a directory and he needs to delete some of them. Polycarp wants to run a single delete command with filename pattern as an argument. All the files to be deleted should match the pattern and all other files shouldn't match the pattern.

Polycarp doesn't know about an asterisk '*', the only special character he knows is a question mark '?' which matches any single character. All other characters in the pattern match themselves only.

Formally, a pattern matches a filename if and only if they have equal lengths and all characters in the corresponding positions are equal except when the character in the pattern is '?', in which case the corresponding filename character does not matter.

For example, the filename pattern "a?ba?":  matches filenames "aabaa", "abba.", "a.ba9" and "a.ba.";  does not match filenames "aaba", "abaab", "aabaaa" and "aabaa.".

Help Polycarp find a pattern which matches files to be deleted and only them or report if there is no such pattern.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 100) — the total number of files and the number of files to be deleted.

The following n lines contain filenames, single filename per line. All filenames are non-empty strings containing only lowercase English letters, digits and dots ('.'). The length of each filename doesn't exceed 100. It is guaranteed that all filenames are distinct.

The last line of the input contains m distinct integer numbers in ascending order a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ n) — indices of files to be deleted. All files are indexed from 1 to n in order of their appearance in the input.

-----Output-----

If the required pattern exists, print "Yes" in the first line of the output. The second line should contain the required pattern. If there are multiple solutions, print any of them.

If the required pattern doesn't exist, print the only line...

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

import collections

Input=input().split()
n=int(Input[0])
m=int(Input[1])
listfile=[]

for i in range(n):
    listfile.append(input())

listdet=list(map(int, input().split()))
listfile1=[]

valid = 0
for i in range(len(listdet)):
    if i==0:
        valid = len(listfile[listdet[i]-1])
    elif len(listfile[listdet[i]-1]) != valid:
        valid = -1
        break
    listfile1.append(listfile[listdet[i]-1])

result=''
if valid == -1:
    print("No")
else:
    temp=''
    for i in range(len(listfile1[0])):
        for j in range(len(listfile1)):
            if j==0:
                temp = listfile1[j][i]
            if listfile1[j][i] != temp:
                result+="?"
                break
            elif j == len(listfile1)-1:
                result+= listfile1[j][i]

    count=0
    for i in range(len(listfile)):
        if len(listfile[i]) == len(result) and (i+1 not in listdet):
            for j in range(len(listfile1[0])):
                if listfile[i][j] != result[j] and result[j] != "?":
                    count+=1
                    break
        elif len(listfile[i])!= len(result) and (i+1 not in listdet):
            count+=1

    if count == n-m:
        if result == "?"*len(listfile1):
            print("No")
        else:
            print("Yes")
            print(result)
    else:
        print("No")


I found an interesting problem on https://codeforces.com/problemset/problem/730/I:
There are n students at Berland State University. Every student has two skills, each measured as a number: a_{i} — the programming skill and b_{i} — the sports skill.

It is announced that an Olympiad in programming and sports will be held soon. That's why Berland State University should choose two teams: one to take part in the programming track and one to take part in the sports track.

There should be exactly p students in the programming team and exactly s students in the sports team. A student can't be a member of both teams.

The university management considers that the strength of the university on the Olympiad is equal to the sum of two values: the programming team strength and the sports team strength. The strength of a team is the sum of skills of its members in the corresponding area, so the strength of the programming team is the sum of all a_{i} and the strength of the sports team is the sum of all b_{i} over corresponding team members.

Help Berland State University to compose two teams to maximize the total strength of the university on the Olympiad.

-----Input-----

The first line contains three positive integer numbers n, p and s (2 ≤ n ≤ 3000, p + s ≤ n) — the number of students, the size of the programming team and the size of the sports team.

The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 3000), where a_{i} is the programming skill of the i-th student.

The third line contains n positive integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 3000), where b_{i} is the sports skill of the i-th student.

-----Output-----

In the first line, print the the maximum strength of the university on the Olympiad. In the second line, print p numbers — the members of the programming team. In the third line, print s numbers — the members of the sports team.

The students are numbered from 1 to n as they are given in the input. All numbers printed in the second and in the third lines should be distinct and can be printed in arbitrary order.

If there are multiple solutions, print...

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

#!/usr/bin/env python3
from itertools import accumulate
from heapq import heappop, heappush

def top(ppl_indices, vals, start):
    Q = []
    res = [0 for i in range(len(ppl_indices))]
    for k, idx in enumerate(ppl_indices):
        heappush(Q, -vals[idx])
        if k >= start:
            res[k] = res[k-1] - heappop(Q)

    return res

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

conversion_gain = [y - x for x, y in zip(a, b)]

ordered_by_a = sorted(zip(a, list(range(n))), reverse=True)
prefix_sums_a = list(accumulate([x for x, y in ordered_by_a]))
conversions = top([idx for val, idx in ordered_by_a], conversion_gain, a_size)
rest_of_bs = list(reversed(top([idx for val, idx in reversed(ordered_by_a[a_size:])],
                               b, n - a_size - b_size))) + [0]

sol, top_k = max([(prefix_a + convert + add_bs, idx)
                  for idx, (prefix_a, convert, add_bs)
                  in enumerate(zip(prefix_sums_a[a_size-1:a_size+b_size],
                                   conversions[a_size-1:a_size+b_size],
                                   rest_of_bs))])
top_k += a_size

conversion_ordered_by_a = [(conversion_gain[idx], idx) for val, idx in ordered_by_a]
conversion_sorted = sorted(conversion_ordered_by_a[:top_k], reverse=True)
converted = [idx for val, idx in conversion_sorted[:top_k-a_size]]
team_a = list(set(idx for val, idx in ordered_by_a[:top_k]) - set(converted))

b_ordered_by_a = [(b[idx], idx) for val, idx in ordered_by_a]
b_sorted = sorted(b_ordered_by_a[top_k:], reverse=True)
team_b = converted + [idx for val, idx in b_sorted[:(a_size+b_size) - top_k]]

print(sol)
print(" ".join(str(idx+1) for idx in team_a))
print(" ".join(str(idx+1) for idx in team_b))


I found an interesting problem on https://codeforces.com/problemset/problem/730/J:
Nick has n bottles of soda left after his birthday. Each bottle is described by two values: remaining amount of soda a_{i} and bottle volume b_{i} (a_{i} ≤ b_{i}).

Nick has decided to pour all remaining soda into minimal number of bottles, moreover he has to do it as soon as possible. Nick spends x seconds to pour x units of soda from one bottle to another.

Nick asks you to help him to determine k — the minimal number of bottles to store all remaining soda and t — the minimal time to pour soda into k bottles. A bottle can't store more soda than its volume. All remaining soda should be saved.

-----Input-----

The first line contains positive integer n (1 ≤ n ≤ 100) — the number of bottles.

The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100), where a_{i} is the amount of soda remaining in the i-th bottle.

The third line contains n positive integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 100), where b_{i} is the volume of the i-th bottle.

It is guaranteed that a_{i} ≤ b_{i} for any i.

-----Output-----

The only line should contain two integers k and t, where k is the minimal number of bottles that can store all the soda and t is the minimal time to pour the soda into k bottles.

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

Output
2 6

Input
2
1 1
100 100

Output
1 1

Input
5
10 30 5 6 24
10 41 7 8 24

Output
3 11

-----Note-----

In the first example Nick can pour soda from the first bottle to the second bottle. It will take 3 seconds. After it the second bottle will contain 3 + 3 = 6 units of soda. Then he can pour soda from the fourth bottle to the second bottle and to the third bottle: one unit to the second and two units to the third. It will take 1 + 2 = 3 seconds. So, all the soda will be in two bottles and he will spend 3 + 3 = 6 seconds to do it.

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

f = lambda: list(map(int, input().split()))
n = int(input())
a, b = f(), f()

d = [[None] * 10001 for i in range(n)]

def g(i, s):
    if s <= 0: return (0, s)
    if i == n: return (1e7, 0)

    if not d[i][s]:
        x, y = g(i + 1, s - b[i])
        d[i][s] = min(g(i + 1, s), (x + 1, y + b[i] - a[i]))
    return d[i][s]

x, y = g(0, sum(a))
print(x, y)


I found an interesting problem on https://codeforces.com/problemset/problem/731/A:
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.

Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture: [Image]

After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.

Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.

-----Input-----

The only line of input contains the name of some exhibit — the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.

-----Output-----

Print one integer — the minimum number of rotations of the wheel, required to print the name given in the input.

-----Examples-----
Input
zeus

Output
18

Input
map

Output
35

Input
ares

Output
34

-----Note-----

  [Image]

To print the string from the first sample it would be optimal to perform the following sequence of rotations:   from 'a' to 'z' (1 rotation counterclockwise),  from 'z' to 'e' (5 clockwise rotations),  from 'e' to 'u' (10 rotations counterclockwise),  from 'u' to 's' (2 counterclockwise rotations).  In total, 1 + 5 + 10 + 2 = 18 rotations are required.

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

#!/usr/bin/env python3

SEQ = 'abcdefghijklmnopqrstuvwxyz'

def dist(a, b):
  a = ord(a) - ord('a')
  b = ord(b) - ord('a')
  d = abs(a - b)
  return min(d, 26 - d)

def __starting_point():
  seq = input()
  pos = 'a'
  r = 0
  for c in seq:
    r += dist(pos, c)
    pos = c
  print(r)

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/731/B:
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.

Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be a_{i} teams on the i-th day.

There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total).

As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.

Sereja wants to order exactly a_{i} pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n.

-----Input-----

The first line of input contains a single integer n (1 ≤ n ≤ 200 000) — the number of training sessions.

The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10 000) — the number of teams that will be present on each of the days.

-----Output-----

If there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print "YES" (without quotes) in the only line of output. Otherwise, print "NO" (without quotes).

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

Output
YES

Input
3
1 0 1

Output
NO

-----Note-----

In the first...

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

from sys import stdin

n = int(stdin.readline())

a = [int(x) for x in stdin.readline().split()]

pizza_free_today = False

result = 'NO'

for teams in a:
    if pizza_free_today:
        teams -= 1
        pizza_free_today = False
    if teams < 0:
        break
    if teams % 2 == 0:
        pass
    else:
        pizza_free_today = True
else:
    if not pizza_free_today:
        result = 'YES'

print(result)


I found an interesting problem on https://codeforces.com/problemset/problem/731/C:
Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes.

Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's n socks is assigned a unique integer from 1 to n. Thus, the only thing his mother had to do was to write down two integers l_{i} and r_{i} for each of the days — the indices of socks to wear on the day i (obviously, l_{i} stands for the left foot and r_{i} for the right). Each sock is painted in one of k colors.

When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses k jars with the paint — one for each of k colors.

Arseniy wants to repaint some of the socks in such a way, that for each of m days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.

The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of m days.

-----Input-----

The first line of input contains three integers n, m and k (2 ≤ n ≤ 200 000, 0 ≤ m ≤ 200 000, 1 ≤ k ≤ 200 000) — the number of socks, the number of days and the number of available colors respectively.

The second line contain n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ k) — current colors of Arseniy's socks.

Each of the following m lines contains two integers...

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

from collections import Counter, defaultdict

class DSU:
	def __init__(self, n):
		self.parents = [i for i in range(n)]
		self.rank = [0 for i in range(n)]

	def find_parent(self, a):
		if a == self.parents[a]:
			return a
		else:
			b = self.find_parent(self.parents[a])
			self.parents[a] = b
			return b

	def join_sets(self, a, b):
		a = self.find_parent(a)
		b = self.find_parent(b)
		if a != b:
			if self.rank[a] < self.rank[b]:
				a, b = b, a
			self.parents[b] = a
			if self.rank[a] == self.rank[b]:
				self.rank[a] += 1

n, m, k = map(int, input().split(' '))
dsu = DSU(n)
colors = list(map(int, input().split(' ')))
for _ in range(m):
	a, b = map(int, input().split(' '))
	a, b = a-1, b-1
	dsu.join_sets(a, b)
cur_colors = defaultdict(Counter)
for i in range(n):
	cur_colors[dsu.find_parent(i)][colors[i]] += 1
ans = 0
for color_counter in cur_colors.values():
	ans += sum(color_counter.values()) - color_counter.most_common(1)[0][1]

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/731/E:
Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.

The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.

One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move.

Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.

Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.

-----Input-----

The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall.

The second line contains n integers a_1, a_2, ..., a_{n} ( - 10 000 ≤ a_{i} ≤ 10 000) — the numbers on stickers in order from left to right.

-----Output-----

Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally.

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

Output
14

Input
4
1 -7 -2 3

Output
-3

-----Note-----

In the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.

In the second sample, the optimal sequence...

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

n = int(input())
raw = input().split()
d = []
prev = 0
for i in range(n):
    di = int(raw[i])
    di += prev
    d.append(di)
    prev = di
i = n - 2
cur = d[n - 1]
while i > 0:
    cur = max(cur, d[i] - cur)
    i -= 1

print(cur)


I found an interesting problem on https://codeforces.com/problemset/problem/731/F:
Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.

There are n video cards in the shop, the power of the i-th video card is equal to integer value a_{i}. As Vlad wants to be sure the new game will work he wants to buy not one, but several video cards and unite their powers using the cutting-edge technology. To use this technology one of the cards is chosen as the leading one and other video cards are attached to it as secondary. For this new technology to work it's required that the power of each of the secondary video cards is divisible by the power of the leading video card. In order to achieve that the power of any secondary video card can be reduced to any integer value less or equal than the current power. However, the power of the leading video card should remain unchanged, i.e. it can't be reduced.

Vlad has an infinite amount of money so he can buy any set of video cards. Help him determine which video cards he should buy such that after picking the leading video card and may be reducing some powers of others to make them work together he will get the maximum total value of video power.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of video cards in the shop.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 200 000) — powers of video cards.

-----Output-----

The only line of the output should contain one integer value — the maximum possible total power of video cards working together.

-----Examples-----
Input
4
3 2 15 9

Output
27

Input
4
8 2 2 7

Output
18

-----Note-----

In the first sample, it would be optimal to buy video cards with powers 3, 15 and 9. The video card with power 3 should be chosen as the leading one and all other video cards will be compatible with it. Thus, the total power would be 3 + 15 + 9 = 27. If he buys...

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

n = int(input())
s = list(map(int, input().split()))
h = max(s)
ss = [0] * (h + 1)
for i in s:
    ss[i] += 1
f, x = [0] * h, 0
for j in reversed(ss):
    x += j
    f.append(x)
f.reverse()
res = []
for i, x in enumerate(ss):
    if x:
        summ, x = 0, f[i]
        for j in range(i, h + 1, i):
            o = f[j + i]
            summ += (x - o) * j
            x = o
        res.append(summ)
print(max(res))


I found an interesting problem on https://codeforces.com/problemset/problem/732/A:
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.

In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ≤ 9).

What is the minimum number of shovels Polycarp has to buy so that he can pay for the purchase without any change? It is obvious that he can pay for 10 shovels without any change (by paying the requied amount of 10-burle coins and not using the coin of r burles). But perhaps he can buy fewer shovels and pay without any change. Note that Polycarp should buy at least one shovel.

-----Input-----

The single line of input contains two integers k and r (1 ≤ k ≤ 1000, 1 ≤ r ≤ 9) — the price of one shovel and the denomination of the coin in Polycarp's pocket that is different from "10-burle coins".

Remember that he has an unlimited number of coins in the denomination of 10, that is, Polycarp has enough money to buy any number of shovels.

-----Output-----

Print the required minimum number of shovels Polycarp has to buy so that he can pay for them without any change.

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

Output
9

Input
237 7

Output
1

Input
15 2

Output
2

-----Note-----

In the first example Polycarp can buy 9 shovels and pay 9·117 = 1053 burles. Indeed, he can pay this sum by using 10-burle coins and one 3-burle coin. He can't buy fewer shovels without any change.

In the second example it is enough for Polycarp to buy one shovel.

In the third example Polycarp should buy two shovels and pay 2·15 = 30 burles. It is obvious that he can pay this sum without any change.

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

k,r=list(map(int,input().split()))
for i in range(1,11):
    if (k*i)%10==r or (k*i)%10==0:
        print(i)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/732/B:
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.

Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.

Polycarp analysed all his affairs over the next n days and made a sequence of n integers a_1, a_2, ..., a_{n}, where a_{i} is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).

Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.

Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b_1, b_2, ..., b_{n} (b_{i} ≥ a_{i}), where b_{i} means the total number of walks with the dog on the i-th day.

-----Input-----

The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.

The second line contains integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.

-----Output-----

In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.

In the second line print n integers b_1, b_2, ..., b_{n}, where b_{i} — the total number of walks on the i-th day according to the found solutions (a_{i} ≤ b_{i} for all i from 1 to n). If there are multiple solutions, print any of them.

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

Output
4
2 3 2

Input
3 1
0 0...

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

N,K = ( int(x) for x in input().split() )
walklist = [int(x) for x in input().split()]
cost = 0
for i in range(1,N):
	if walklist[i] + walklist[i-1] < K:
		cost += K - (walklist[i] + walklist[i-1])
		walklist[i] = K - walklist[i-1]

print(cost)
print(" ".join([str(x) for x in walklist]))


I found an interesting problem on https://codeforces.com/problemset/problem/732/C:
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation!

Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all.

Vasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived.

According to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.

-----Input-----

The only line contains three integers b, d and s (0 ≤ b, d, s ≤ 10^18,  b + d + s ≥ 1) — the number of breakfasts, dinners and suppers which Vasiliy had during his vacation in the sanatorium.

-----Output-----

Print single integer — the minimum possible number of meals which Vasiliy could have missed during his vacation.

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

Output
1

Input
1 0 0

Output
0

Input
1 1 1

Output
0

Input
1000000000000000000 0 1000000000000000000

Output
999999999999999999

-----Note-----

In the first sample, Vasiliy could have missed one supper, for example, in case he have arrived before breakfast, have been in the sanatorium for two days (including the day of arrival)...

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

from collections import defaultdict
import sys, os, math

def __starting_point():
    #n, m = list(map(int, input().split()))
    b, d, s = map(int, input().split())
    ans = 0
    if b > d and b > s:
        ans = (b - 1) * 3 + 1 - d - b - s
    elif d > b and d > s:
        ans = (d - 2) * 3 + 4 - d - b - s
    elif s > d and s > b:
        ans = (s - 1) * 3 + 1 - d - b - s
    elif s == d == b:
        ans = 0
    elif d == b:
        ans = (b - 1) * 3 + 2 - d - b - s
    elif b == s:
        ans = (b - 1) * 3 + 2 - d - b - s
    else:
        ans = (d - 1) * 3 + 2 - d - b - s
    print(ans)
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/732/D:
Vasiliy has an exam period which will continue for n days. He has to pass exams on m subjects. Subjects are numbered from 1 to m.

About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day.

On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest.

About each subject Vasiliy know a number a_{i} — the number of days he should prepare to pass the exam number i. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during a_{i} days for the exam number i. He can mix the order of preparation for exams in any way.

Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of days in the exam period and the number of subjects.

The second line contains n integers d_1, d_2, ..., d_{n} (0 ≤ d_{i} ≤ m), where d_{i} is the number of subject, the exam of which can be passed on the day number i. If d_{i} equals 0, it is not allowed to pass any exams on the day number i.

The third line contains m positive integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^5), where a_{i} is the number of days that are needed to prepare before passing the exam on the subject i.

-----Output-----

Print one integer — the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1.

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

Output
5

Input
10 3
0 0 1 2 3 0 2 0 1 2
1 1 4

Output
9

Input
5 1
1 1 1 1 1
5

Output
-1

-----Note-----

In the first example Vasiliy can behave as follows. On the first and the second day he can prepare for the exam number 1 and pass it on the fifth day, prepare for the exam number 2 on the third day and pass it on the fourth day.

In...

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

from collections import deque

def main():
    n, m = list(map(int, input().split()))
    test = list(map(int, input().split()))
    prepare = list(map(int, input().split()))
    least_days = sum(prepare) + m

    if least_days > len(test):
        print(-1)
        return
    index = list()
    for p in range(m + 1):
        index.append(deque())
    for t in range(len(test)):
        if test[t] == 0:
            continue
        index[test[t]].append(t)
        if t >= least_days - 1:
            index[0].append(t)
    if deque([]) in index:
        print(-1)
        return
    min_index = max(list([x.popleft() for x in index[1:]]))
    min_index = max(least_days - 1, min_index)
    for x in index[0]:
        if x >= min_index:
            print(x + 1)
            break

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/733/A:
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of his jump.

Formally, consider that at the begginning the Grasshopper is located directly in front of the leftmost character of the string. His goal is to reach the position right after the rightmost character of the string. In one jump the Grasshopper could jump to the right any distance from 1 to the value of his jump ability. [Image] The picture corresponds to the first example.

The following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'.

-----Input-----

The first line contains non-empty string consisting of capital English letters. It is guaranteed that the length of the string does not exceed 100.

-----Output-----

Print single integer a — the minimum jump ability of the Grasshopper (in the number of symbols) that is needed to overcome the given string, jumping only on vowels.

-----Examples-----
Input
ABABBBACFEYUKOTT

Output
4
Input
AAA

Output
1

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

#!/usr/bin/env python3

from   functools import reduce
from   operator  import add
import re

def main():
    try:
        while True:
            print(reduce(max, (len(m.group()) for m in re.finditer(r"[^AEIOUY]+", input())), 0) + 1)

    except EOFError:
        pass

main()


I found an interesting problem on https://codeforces.com/problemset/problem/733/B:
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.

There will be n columns participating in the parade, the i-th column consists of l_{i} soldiers, who start to march from left leg, and r_{i} soldiers, who start to march from right leg.

The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.

No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values l_{i} and r_{i}.

Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.

-----Input-----

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

The next n lines contain the pairs of integers l_{i} and r_{i} (1 ≤ l_{i}, r_{i} ≤ 500) — the number of soldiers in the i-th column which start to march from the left or the right leg respectively.

-----Output-----

Print single integer k — the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached.

Consider that columns are numbered from 1 to n in the order they are given in the input data.

If there are several answers, print any of them.

-----Examples-----
Input
3
5 6
8 9
10...

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

n = int(input())
a = [0] * n
R = 0
L = 0
for i in range(n):
    a[i] = list(map(int, input().split()))
    R += a[i][1]
    L += a[i][0]

m = abs(L - R)
ans = 0
for i in range(n):
    b = abs((L - a[i][0] + a[i][1]) - (R - a[i][1] + a[i][0]))
    if b > m:
        ans = i + 1
        m = b

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/733/C:
There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.

Soon, monsters became hungry and began to eat each other.

One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight a_{i}.

For example, if weights are [1, 2, 2, 2, 1, 2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are:  the first monster can't eat the second monster because a_1 = 1 is not greater than a_2 = 2;  the second monster can't eat the third monster because a_2 = 2 is not greater than a_3 = 2;  the second monster can't eat the fifth monster because they are not neighbors;  the second monster can eat the first monster, the queue will be transformed to [3, 2, 2, 1, 2].

After some time, someone said a good joke and all monsters recovered. At that moment there were k (k ≤ n) monsters in the queue, the j-th of which had weight b_{j}. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last.

You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 500) — the number of monsters in the initial...

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

import sys

a = [0,]
b = [0,]
ans1 = []
ans2 = []
n = int(input())
s = input()
nums = s.split()
for i in range(0, n):
    a.append(int(nums[i]))

k = int(input())
s = input()
nums = s.split()
for i in range(0, k):
    b.append(int(nums[i]))

def f(x, y, z):
    #print(x,y,z)
    pos1 = x
    pos2 = x
    if x == y:
        return 1
    for i in range(x, y + 1):
        if a[i] > a[pos1]:
            pos1 = i
        if a[i] >= a[pos2]:
            pos2 = i
    for i in range(x, y):
        if a[i] == a[pos2]:
            if a[i + 1] < a[i]:
                pos2 = i
    for i in range(x + 1, y + 1):
        if a[i] == a[pos1]:
            if a[i - 1] < a[i]:
                pos1 = i
    if pos1 != x or a[pos1] > a[pos1 + 1]:
        for i in range(0, pos1 - x):
            ans1.append(pos1 - x + z - i)
            ans2.append('L')
        for i in range(0, y - pos1):
            ans1.append(z)
            ans2.append('R')
    elif pos2 != y or a[pos2] > a[pos2 - 1]:
        for i in range(0, y - pos2):
            ans1.append(pos2 - x + z)
            ans2.append('R')
        for i in range(0, pos2 - x):
            ans1.append(pos2 - x + z - i)
            ans2.append('L')
    else:
        return 0

    return 1

lasti = 0
j = 1
sum = 0
for i in range(1, n+1):
    if j > k:
        print('NO')
        return
    sum += a[i]
    #print(i, sum, j)
    if sum > b[j]:
        print('NO')
        return
    if sum == b[j]:
        if f(lasti + 1, i, j) == 0:
            print('NO')
            return
        lasti = i
        j += 1
        sum = 0

if j <= k:
    print('NO')
    return

print('YES')
for i in range(0, len(ans1)):
    print(ans1[i], ans2[i])


I found an interesting problem on https://codeforces.com/problemset/problem/733/D:
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere.

Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are a_{i}, b_{i} and c_{i}. He can take no more than two stones and present them to Kostya.

If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way.

Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.

-----Input-----

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

n lines follow, in the i-th of which there are three integers a_{i}, b_{i} and c_{i} (1 ≤ a_{i}, b_{i}, c_{i} ≤ 10^9) — the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.

-----Output-----

In the first line print k (1 ≤ k ≤ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to n — the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data.

You can print the stones in arbitrary order. If there are several answers print any of them.

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

Output
1
1

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

Output
2
1 5

-----Note-----

In the first example we can connect the pairs of stones:  2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1  2 and 5, the size of the...

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

def main():
    from collections import defaultdict
    d, m = defaultdict(list), 0
    for i in range(1, int(input()) + 1):
        a, b, c = sorted(map(int, input().split()))
        d[b, c].append((a, i))
    for (a, b), l in list(d.items()):
        if len(l) > 1:
            l.sort()
            c, i = l[-1]
            x, j = l[-2]
            c += x
        else:
            c, i = l[0]
            j = 0
        if a > m < c:
            m, res = a if a < c else c, (i, j)
    print(("2\n%d %d" % res) if res[1] else ("1\n%d" % res[0]))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/733/E:
The academic year has just begun, but lessons and olympiads have already occupied all the free time. It is not a surprise that today Olga fell asleep on the Literature. She had a dream in which she was on a stairs.

The stairs consists of n steps. The steps are numbered from bottom to top, it means that the lowest step has number 1, and the highest step has number n. Above each of them there is a pointer with the direction (up or down) Olga should move from this step. As soon as Olga goes to the next step, the direction of the pointer (above the step she leaves) changes. It means that the direction "up" changes to "down", the direction "down"  —  to the direction "up".

Olga always moves to the next step in the direction which is shown on the pointer above the step.

If Olga moves beyond the stairs, she will fall and wake up. Moving beyond the stairs is a moving down from the first step or moving up from the last one (it means the n-th) step.

In one second Olga moves one step up or down according to the direction of the pointer which is located above the step on which Olga had been at the beginning of the second.

For each step find the duration of the dream if Olga was at this step at the beginning of the dream.

Olga's fall also takes one second, so if she was on the first step and went down, she would wake up in the next second.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 10^6) — the number of steps on the stairs.

The second line contains a string s with the length n — it denotes the initial direction of pointers on the stairs. The i-th character of string s denotes the direction of the pointer above i-th step, and is either 'U' (it means that this pointer is directed up), or 'D' (it means this pointed is directed down).

The pointers are given in order from bottom to top.

-----Output-----

Print n numbers, the i-th of which is equal either to the duration of Olga's dream or to  - 1 if Olga never goes beyond the stairs, if in the beginning of sleep she was on the i-th...

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

n=int(input())
string = input()
q1,q2,B,C=[],[],[],[]
A=0
for i in range(n):
    if string[i] == "D":
        q1.append(i)
    else:
        q2.append(n-1-i)

for i in range(len(q1)):
    A+=(q1[i]-i)*2+1
    B.append(A)

A=0
temp = []
for i in range(len(q2)):
    A+=(q2[len(q2)-1-i]-i)*2+1
    C.append(A)
C.reverse()

B=list(map(str,B+C))
print(" ".join(B))


I found an interesting problem on https://codeforces.com/problemset/problem/734/A:
Anton likes to play chess, and so does his friend Danik.

Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.

Now Anton wonders, who won more games, he or Danik? Help him determine this.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played.

The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.

-----Output-----

If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output.

If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output.

If Anton and Danik won the same number of games, print "Friendship" (without quotes).

-----Examples-----
Input
6
ADAAAA

Output
Anton

Input
7
DDDAADA

Output
Danik

Input
6
DADADA

Output
Friendship

-----Note-----

In the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton".

In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".

In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".

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

n = int(input())
s = input()
if s.count('A') > s.count('D'):
    print('Anton')
elif s.count('A') < s.count('D'):
    print('Danik')
else:
    print('Friendship')


I found an interesting problem on https://codeforces.com/problemset/problem/734/B:
Recently Anton found a box with digits in his room. There are k_2 digits 2, k_3 digits 3, k_5 digits 5 and k_6 digits 6.

Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task!

Each digit can be used no more than once, i.e. the composed integers should contain no more than k_2 digits 2, k_3 digits 3 and so on. Of course, unused digits are not counted in the sum.

-----Input-----

The only line of the input contains four integers k_2, k_3, k_5 and k_6 — the number of digits 2, 3, 5 and 6 respectively (0 ≤ k_2, k_3, k_5, k_6 ≤ 5·10^6).

-----Output-----

Print one integer — maximum possible sum of Anton's favorite integers that can be composed using digits from the box.

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

Output
800

Input
1 1 1 1

Output
256

-----Note-----

In the first sample, there are five digits 2, one digit 3, three digits 5 and four digits 6. Anton can compose three integers 256 and one integer 32 to achieve the value 256 + 256 + 256 + 32 = 800. Note, that there is one unused integer 2 and one unused integer 6. They are not counted in the answer.

In the second sample, the optimal answer is to create on integer 256, thus the answer is 256.

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/734/C:
Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions.

Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions.  Spells of this type speed up the preparation time of one potion. There are m spells of this type, the i-th of them costs b_{i} manapoints and changes the preparation time of each potion to a_{i} instead of x.  Spells of this type immediately prepare some number of potions. There are k such spells, the i-th of them costs d_{i} manapoints and instantly create c_{i} potions.

Anton can use no more than one spell of the first type and no more than one spell of the second type, and the total number of manapoints spent should not exceed s. Consider that all spells are used instantly and right before Anton starts to prepare potions.

Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least n potions.

-----Input-----

The first line of the input contains three integers n, m, k (1 ≤ n ≤ 2·10^9, 1 ≤ m, k ≤ 2·10^5) — the number of potions, Anton has to make, the number of spells of the first type and the number of spells of the second type.

The second line of the input contains two integers x and s (2 ≤ x ≤ 2·10^9, 1 ≤ s ≤ 2·10^9) — the initial number of seconds required to prepare one potion and the number of manapoints Anton can use.

The third line contains m integers a_{i} (1 ≤ a_{i} < x) — the number of seconds it will take to prepare one potion if the i-th spell of the first type is used.

The fourth line contains m integers b_{i} (1 ≤ b_{i} ≤ 2·10^9) — the number of manapoints to use the i-th spell of the first type.

There are k integers c_{i} (1 ≤ c_{i} ≤ n) in the fifth line — the number of potions that will be immediately created if the i-th spell of the second type is used. It's guaranteed that c_{i} are not...

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

n,m,k = list(map(int,input().split()))
x,s = list(map(int,input().split()))
a_time = list(map(int,input().split()))
a_cost = list(map(int,input().split()))
b_num = list(map(int,input().split()))
b_cost = list(map(int,input().split()))

def binary_search(manapoints):
    nonlocal  k,b_cost
    l = 0;  r = k-1;  pos = -1
    while (l <= r):
        mid = int((l+r)/2)
        if (b_cost[mid] <= manapoints):
            l = mid+1;  pos = mid;
        else :
            r = mid-1
    return pos
res = n*x
pos = binary_search(s)
if (pos >= 0):  res = min(res,(n-b_num[pos])*x);
for i in range(m):
    if (a_cost[i] > s): continue;
    rest = s-a_cost[i]
    pos = binary_search(rest)
    if (pos >= 0):  res = min(res,(n-b_num[pos])*a_time[i])
    else : res = min(res,n*a_time[i])
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/734/D:
Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead.

The first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help.

Consider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move.

Help Anton and write the program that for the given position determines whether the white king is in check.

Remainder, on how do chess pieces move:   Bishop moves any number of cells diagonally, but it can't "leap" over the occupied cells.  Rook moves any number of cells horizontally or vertically, but it also can't "leap" over the occupied cells.  Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't "leap".

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of black pieces.

The second line contains two integers x_0 and y_0 ( - 10^9 ≤ x_0, y_0 ≤ 10^9) — coordinates of the white king.

Then follow n lines, each of them contains a character and two integers x_{i} and y_{i} ( - 10^9 ≤ x_{i}, y_{i} ≤ 10^9) — type of the i-th piece and its position. Character 'B' stands for the bishop, 'R' for the rook and 'Q' for the queen. It's guaranteed that no two pieces occupy the same position.

-----Output-----

The only line of the output should contains "YES" (without quotes) if the white king is in check and "NO" (without quotes) otherwise.

-----Examples-----
Input
2
4 2
R 1 1
B 1 5

Output
YES

Input
2
4 2
R 3 3
B 1 5

Output
NO

-----Note-----

Picture for the first sample:  [Image]  White king is in check, because the black bishop can reach the cell with the white king in one move....

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

n = int(input())
x0, y0 = map(int, input().split())
Nord = 10 ** 9 + 1
fNord = '-'
East = 10 ** 9 + 1
fEast = '-'
South = -10 ** 9 - 1
fSouth = '-'
West = -10 ** 9 - 1
fWest = '-'

NE = 10 ** 9 + 1
fNE = '-'
NW = 10 ** 9 + 1
fNW = '-'
SE = -10 ** 9 - 1
fSE = '-'
SW = -10 ** 9 - 1
fSW = '-'

for i in range(n):
    f, x, y = input().split()
    x = int(x)
    y = int(y)
    if x == x0:
        if y0 < y < Nord:
            fNord = f
            Nord = y
        elif y0 > y > South:
            fSouth = f
            South = y
    if y == y0:
        if x0 < x < East:
            fEast = f
            East = x
        elif x0 > x > West:
            fWest = f
            West = x

    if x + y == x0 + y0:
        if y0 < y < NW:
            fNW = f
            NW = y
        elif y0 > y > SE:
            fSE = f
            SE = y
    if x - y == x0 - y0:
        if y0 < y < NE:
            fNE = f
            NE = y
        elif y0 > y > SW:
            fSW = f
            SW = y
ans  = False
if fSW == 'Q' or fSE == 'Q' or fNW == 'Q' or fNE == 'Q':
    ans = True
if fNord == 'Q' or fSouth == 'Q' or fWest == 'Q' or fEast == 'Q':
    ans = True
if fSW == 'B' or fSE == 'B' or fNW == 'B' or fNE == 'B':
    ans = True
if fNord == 'R' or fSouth == 'R' or fWest == 'R' or fEast == 'R':
    ans = True

#print(fSW, fSE, fNW, fNE)
#print(fNord, fSouth, fWest, fEast)
print('YES' if ans else 'NO')