I found an interesting problem on https://codeforces.com/problemset/problem/802/A:
Your search for Heidi is over – you finally found her at a library, dressed up as a human. In fact, she has spent so much time there that she now runs the place! Her job is to buy books and keep them at the library so that people can borrow and read them. There are n different books, numbered 1 through n.

We will look at the library's operation during n consecutive days. Heidi knows in advance that on the i-th day (1 ≤ i ≤ n) precisely one person will come to the library, request to borrow the book a_{i}, read it in a few hours, and return the book later on the same day.

Heidi desperately wants to please all her guests, so she will make sure to always have the book a_{i} available in the library on the i-th day. During the night before the i-th day, she has the option of going to the bookstore (which operates at nights to avoid competition with the library) and buying any book for the price of 1 CHF. Of course, if she already has a book at the library, she does not need to buy it again. Initially, the library contains no books.

There is a problem, though. The capacity of the library is k – this means that at any time, there can be at most k books at the library. If buying a new book would cause Heidi to have more than k books, she must first get rid of some book that she already has, in order to make room for the new book. If she later needs a book that she got rid of, she will need to buy that book again.

You are given k and the sequence of requests for books a_1, a_2, ..., a_{n}. What is the minimum cost (in CHF) of buying new books to satisfy all the requests?

-----Input-----

The first line of input will contain two integers n and k (1 ≤ n, k ≤ 80). The second line will contain n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) – the sequence of book requests.

-----Output-----

On a single line print the minimum cost of buying books at the store so as to satisfy all requests.

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

Output
2

Input
4 1
1 2 2 1

Output
3

Input
4 2
1 2 3...

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

n, k = [int(x) for x in input().split()]
requests = [int(x) for x in input().split()]

req_list = {}

def find_last(bucket):
    last_book = None
    last_date = None
    nonlocal req_list
    i = 0
    for item in bucket:
        #print(item, req_list)
        if last_book is None:
            last_book = item
            if len(req_list[item]) < 1:
                last_date = float('inf')
                return item, i
            else:
                last_date = req_list[item][0]
            index = i
        elif len(req_list[item]) >= 1 and req_list[item][0] > last_date:
            last_book = item
            last_date = req_list[item][0]
            index = i
        elif len(req_list[item]) < 1 and last_date < float('inf'):
            return item, i
        i += 1
    return last_book, index

def update_reqlist(book):
    nonlocal req_list
    req_list[book] = req_list[book][1:]

for i in range(n):
    if requests[i] in req_list:
        req_list[requests[i]].append(i)
    else:
        req_list[requests[i]] = [i]

bucket = []
bucket_size = 0
cost = 0
for book in requests:
    if book in bucket:
        update_reqlist(book)
        continue
    if bucket_size < k:
        bucket.append(book)
        bucket_size += 1
        cost += 1
        update_reqlist(book)
    else:
        last_book, index = find_last(bucket)
        if len(bucket) > 1:
            bucket.pop(index)
        else:
            bucket = []
        bucket.append(book)
        update_reqlist(book)
        cost += 1
    #print(bucket, req_list)

#print(req_list)
print(cost)


I found an interesting problem on https://codeforces.com/problemset/problem/802/B:
Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences.

-----Input-----

Same as the easy version, but the limits have changed: 1 ≤ n, k ≤ 400 000.

-----Output-----

Same as the easy version.

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

Output
2

Input
4 1
1 2 2 1

Output
3

Input
4 2
1 2 3 1

Output
3

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

# https://codeforces.com/problemset/problem/802/B
import heapq

n, k  = map(int, input().split())
a     = list(map(int, input().split()))
d     = {}
pos   = {}
Q     = []
cnt   = 0

for i, x in enumerate(a):
    if x not in pos:
        pos[x] = []
    pos[x].append(i)

for i, x in enumerate(a):

    if x not in d:
        cnt += 1

        if len(d) == k:
            pos_, x_ = heapq.heappop(Q)
            del d[x_]
        d[x] = 1

    pos[x].pop(0)

    if len(pos[x]) > 0:
        heapq.heappush(Q, (-pos[x][0], x))
    else:
        heapq.heappush(Q, (-float('inf'), x))

print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/802/G:
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...

-----Input-----

The first and only line of input contains a single nonempty string s of length at most 1000 composed of lowercase letters (a-z).

-----Output-----

Output YES if the string s contains heidi as a subsequence and NO otherwise.

-----Examples-----
Input
abcheaibcdi

Output
YES
Input
hiedi

Output
NO

-----Note-----

A string s contains another string p as a subsequence if it is possible to delete some characters from s and obtain p.

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

def lcs(a,b):
    lena=len(a)
    lenb=len(b)
    c=[[0 for i in range(lenb+1)] for j in range(lena+1)]
    for i in range(lena):
        for j in range(lenb):
            if a[i]==b[j]:
                c[i+1][j+1]=c[i][j]+1
            elif c[i+1][j]>c[i][j+1]:
                c[i+1][j+1]=c[i+1][j]
            else:
                c[i+1][j+1]=c[i][j+1]
    return c

a=input()
b='heidi'
s1 = lcs(a,b)
if s1[-1][5] == 5:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/802/J:
Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to deliver the same message to yet another friend (that the recipient has in common with Heidi), and so on.

Heidi believes that her friends want to avoid awkward situations, so she will not be made to visit the same person (including Jenny) twice. She also knows how much it costs to travel between any two of her friends who know each other. She wants to know: what is the maximal amount of money she will waste on travel if it really is a prank?

Heidi's n friends are labeled 0 through n - 1, and their network of connections forms a tree. In other words, every two of her friends a, b know each other, possibly indirectly (there is a sequence of friends starting from a and ending on b and such that each two consecutive friends in the sequence know each other directly), and there are exactly n - 1 pairs of friends who know each other directly.

Jenny is given the number 0.

-----Input-----

The first line of the input contains the number of friends n (3 ≤ n ≤ 100). The next n - 1 lines each contain three space-separated integers u, v and c (0 ≤ u, v ≤ n - 1, 1 ≤ c ≤ 10^4), meaning that u and v are friends (know each other directly) and the cost for travelling between u and v is c.

It is guaranteed that the social network of the input forms a tree.

-----Output-----

Output a single integer – the maximum sum of costs.

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

Output
5

Input
6
1 2 3
0 2 100
1 4 2
0 3 7
3 5 10

Output
105

Input
11
1 0 1664
2 0 881
3 2 4670
4 2 1555
5 1 1870
6 2 1265
7 2 288
8 7 2266
9 2 1536
10 6 3378

Output
5551

-----Note-----

In the second example, the worst-case scenario goes like this: Jenny sends Heidi to the friend labeled by number 2 (incurring a cost of 100), then...

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

# Author: S Mahesh Raju
# Username: maheshraju2020
# Created on: 25/09/2020 01:47:42

from sys import stdin, stdout, setrecursionlimit
import heapq
from math import gcd, ceil, sqrt
from collections import Counter, deque
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations
ii1 = lambda: int(stdin.readline().strip())
is1 = lambda: stdin.readline().strip()
iia = lambda: list(map(int, stdin.readline().strip().split()))
isa = lambda: stdin.readline().strip().split()
setrecursionlimit(100000)
mod = 1000000007

def getAns(d):
    queue = [[0, 0]]
    seen = set()
    res = float("-inf")
    while len(queue):
        cur, cost = queue.pop()
        if cur not in seen:
            seen.add(cur)
            res = max(res, cost)
            for a, b in d.get(cur, []):
                queue.append([a, b + cost])
    return res

n = ii1()
d = {}
for i in range(n - 1):
    a, b, cost = iia()
    d.setdefault(a, []).append([b, cost])
    d.setdefault(b, []).append([a, cost])
print(getAns(d))


I found an interesting problem on https://codeforces.com/problemset/problem/802/M:
The marmots have prepared a very easy problem for this year's HC^2 – this one. It involves numbers n, k and a sequence of n positive integers a_1, a_2, ..., a_{n}. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal.

However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!

-----Input-----

The first line of the input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 2200). The second line contains n space-separated integers a_1, ..., a_{n} (1 ≤ a_{i} ≤ 10^4).

-----Output-----

Output one number.

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

Output
5
Input
10 3
16 8 2 4 512 256 32 128 64 1

Output
7
Input
5 1
20 10 50 30 46

Output
10
Input
6 6
6 6 6 6 6 6

Output
36
Input
1 1
100

Output
100

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/802/N:
The marmots need to prepare k problems for HC^2 over n days. Each problem, once prepared, also has to be printed.

The preparation of a problem on day i (at most one per day) costs a_{i} CHF, and the printing of a problem on day i (also at most one per day) costs b_{i} CHF. Of course, a problem cannot be printed before it has been prepared (but doing both on the same day is fine).

What is the minimum cost of preparation and printing?

-----Input-----

The first line of input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 2200). The second line contains n space-separated integers a_1, ..., a_{n} ($1 \leq a_{i} \leq 10^{9}$) — the preparation costs. The third line contains n space-separated integers b_1, ..., b_{n} ($1 \leq b_{i} \leq 10^{9}$) — the printing costs.

-----Output-----

Output the minimum cost of preparation and printing k problems — that is, the minimum possible sum a_{i}_1 + a_{i}_2 + ... + a_{i}_{k} + b_{j}_1 + b_{j}_2 + ... + b_{j}_{k}, where 1 ≤ i_1 < i_2 < ... < i_{k} ≤ n, 1 ≤ j_1 < j_2 < ... < j_{k} ≤ n and i_1 ≤ j_1, i_2 ≤ j_2, ..., i_{k} ≤ j_{k}.

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

Output
32

-----Note-----

In the sample testcase, one optimum solution is to prepare the first problem on day 1 and print it on day 1, prepare the second problem on day 2 and print it on day 4, prepare the third problem on day 3 and print it on day 5, and prepare the fourth problem on day 6 and print it on day 8.

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

from itertools import count
from collections import deque
from heapq import heappop, heappush

class Edge(object):
    __slots__ = ('x', 'y', 'cap', 'cost', 'inv')
    def __repr__(self):
        return f'{self.x}-->{self.y} ({self.cap} , {self.cost})'

class MCFP(list):
    inf = float('inf')

    def add(G, x, y, cap, cost):
        G.extend(([] for i in range(max(0,max(x,y)+1-len(G)))))
        e = Edge()
        e.x=x ; e.y=y; e.cap=cap; e.cost=cost
        z = Edge()
        z.x=y ; z.y=x; z.cap=0; z.cost=-cost
        e.inv=z ; z.inv=e
        G[x].append(e)
        G[y].append(z)

    def solve(G, src, tgt, flowStop=float('inf')):
        n = len(G)
        flowVal = flowCost = 0
        phi, prev, dist = [0]*n, [None]*n, [G.inf]*n
        for it in count():
            G.shortest(src, phi, prev, dist, tgt)
            if prev[tgt]==None:
                break
            p = list(G.backward(tgt, src, prev))
            z = min(e.cap for e in p)
            for e in p: e.cap -= z ; e.inv.cap += z
            flowVal += z
            flowCost += z * (dist[tgt] - phi[src] + phi[tgt])
            if flowVal==flowStop: break
            for i in range(n):
                if prev[i] != None:
                    phi[i] += dist[i]
                    dist[i] = G.inf
        #print(it)
        return flowVal, flowCost

    def backward(G, x, src, prev):
        while x!=src: e = prev[x] ; yield e ; x = e.x

    def shortest_(G, src, phi, prev, dist, tgt):
        prev[tgt] = None
        dist[src] = 0
        Q = [(dist[src], src)]
        k = 0
        while Q:
            k += 1
            d, x = heappop(Q)
            if dist[x]!=d: continue
            for e in G[x]:
                if e.cap <= 0: continue
                dy = dist[x] + phi[x] + e.cost - phi[e.y]
                if dy < dist[e.y]:
                    dist[e.y] = dy
                    prev[e.y] = e
                    heappush(Q, (dy, e.y))
        print(k)
        return

    def shortest(G, src, phi, prev, dist, tgt):
       ...


I found an interesting problem on https://codeforces.com/problemset/problem/803/A:
You are given matrix with n rows and n columns filled with zeroes. You should put k ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.

One matrix is lexicographically greater than the other if the first different number in the first different row from the top in the first matrix is greater than the corresponding number in the second one.

If there exists no such matrix then output -1.

-----Input-----

The first line consists of two numbers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 10^6).

-----Output-----

If the answer exists then output resulting matrix. Otherwise output -1.

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

Output
1 0
0 0

Input
3 2

Output
1 0 0
0 1 0
0 0 0

Input
2 5

Output
-1

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

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

if n * n < k:
    print(-1)
else:
    arr = [[0 for _ in range(n)] for _ in range(n)]
    cnt = 0
    for i in range(n):
        if cnt < k:
            arr[i][i] = 1
            cnt += 1
        for j in range(i + 1, n):
            if cnt <= k - 2:
                arr[i][j] = 1
                arr[j][i] = 1
                cnt += 2
    for r in arr:
        print(' '.join(map(str, r)))


I found an interesting problem on https://codeforces.com/problemset/problem/803/B:
You are given the array of integer numbers a_0, a_1, ..., a_{n} - 1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 2·10^5) — length of the array a. The second line contains integer elements of the array separated by single spaces ( - 10^9 ≤ a_{i} ≤ 10^9).

-----Output-----

Print the sequence d_0, d_1, ..., d_{n} - 1, where d_{i} is the difference of indices between i and nearest j such that a_{j} = 0. It is possible that i = j.

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

Output
2 1 0 1 0 0 1 2 3
Input
5
0 1 2 3 4

Output
0 1 2 3 4
Input
7
5 6 0 1 -2 3 4

Output
2 1 0 1 2 3 4

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

import sys
import math
n = int(input())
a = list(map(int, input().split()))
ans = [n for i in range(n)]
lind = -n
for i in range(n):
    if a[i] == 0:
        lind = i
    ans[i] = min(ans[i], abs(i - lind))
lind = -n
for i in range(n - 1, -1, -1):
    if a[i] == 0:
        lind = i
    ans[i] = min(ans[i], abs(i - lind))
for  i in range(n):
    print(ans[i], end  = " " )


I found an interesting problem on https://codeforces.com/problemset/problem/803/C:
You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a_1, a_2, ..., a_{k}, that their sum is equal to n and greatest common divisor is maximal.

Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them.

If there is no possible sequence then output -1.

-----Input-----

The first line consists of two numbers n and k (1 ≤ n, k ≤ 10^10).

-----Output-----

If the answer exists then output k numbers — resulting sequence. Otherwise output -1. If there are multiple answers, print any of them.

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

Output
1 2 3

Input
8 2

Output
2 6

Input
5 3

Output
-1

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

str_params = input()
[n, k]= [int(s) for s in str_params.split(' ')]
parts = (1+k)/2*k
if parts<=n:
	nod = n/parts
	while (nod%1!=0)|(parts%1!=0):
		if nod<parts:
			if nod%1!=0:
				nod = int(nod)
			else:
				nod = nod-1
			parts = n/nod
		else:
			if parts%1!=0:
				parts = int(parts)+1
			else:
				parts = parts+1
			nod = n/parts
	numbers = [nod*(x+1) for x in range(k)]
	numbers[k-1] = n-(1+k-1)/2*(k-1)*nod

	if numbers[0]==0:
		print(-1)
	else:
		print(' '.join(map(str,list(map(int, numbers)))))
else:
	print(-1)

"""while (sum(numbers)<n):

	33/5 = 6.6
	33/11 = 3

	33/6 = 5.5

	24/10 = 2.4

i = 1
while (sum(numbers)<n) & (i<k):
	while sum(numbers)<n:
		numbers = [numbers[x]*i for x in range(k)]
		print (i, numbers)
		i = i+1
print (numbers)
if sum(numbers)>n:
	print (-1)
if sum(numbers)==n:
	print (' '.join(map(str,numbers)))"""


I found an interesting problem on https://codeforces.com/problemset/problem/803/D:
The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:

There are space-separated non-empty words of lowercase and uppercase Latin letters.

There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen.

It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word.

When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding.

The ad can occupy no more that k lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it.

You should write a program that will find minimal width of the ad.

-----Input-----

The first line contains number k (1 ≤ k ≤ 10^5).

The second line contains the text of the ad — non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 10^6 characters.

-----Output-----

Output minimal width of the ad.

-----Examples-----
Input
4
garage for sa-le

Output
7

Input
4
Edu-ca-tion-al Ro-unds are so fun

Output
10

-----Note-----

Here all spaces are replaced with dots.

In the first example one of possible results after all word wraps looks like this:

garage.

for.

sa-

le

The second example:

Edu-ca-

tion-al.

Ro-unds.

are.so.fun

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

import re
class Solution(object):
    def minWidth (self):
        k=int(input())
        s=input()
        words=re.split(' |-',s)
        l=[]
        for i in range(len(words)):
            l.append(len(words[i])+1)
        l[-1]-=1
        start=max(sum(l)//k,max(l))-1
        end=max(l)+sum(l)//k+1
        def can(pos):
            c=1
            cur=0
            for i in range(len(l)):
                cur+=l[i]
                if cur>pos:
                    c+=1
                    cur=l[i]
                    if c>k:
                        return False
            return True
        while (end-start>1):
            pos=(start+end)//2
            if can(pos):
                end=pos
            else:
                start=pos
        print(end)
sol=Solution()
sol.minWidth()


I found an interesting problem on https://codeforces.com/problemset/problem/803/F:
Let's call a non-empty sequence of positive integers a_1, a_2... a_{k} coprime if the greatest common divisor of all elements of this sequence is equal to 1.

Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 10^9 + 7.

Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].

-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 100000).

The second line contains n integer numbers a_1, a_2... a_{n} (1 ≤ a_{i} ≤ 100000).

-----Output-----

Print the number of coprime subsequences of a modulo 10^9 + 7.

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

Output
5

Input
4
1 1 1 1

Output
15

Input
7
1 3 5 15 3 105 35

Output
100

-----Note-----

In the first example coprime subsequences are:   1  1, 2  1, 3  1, 2, 3  2, 3

In the second example all subsequences are coprime.

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

fact=[1]
temp=1
MOD=10**9+7
for i in range(1,10**5+5):
    temp*=i
    temp%=MOD
    fact+=[temp]
def bino(a,b):
    up=fact[a]
    down=pow(fact[b]*fact[a-b],MOD-2,MOD)
    return (up*down)%MOD

def find(A):
    MOD=10**9+7

    dp=[0]*(10**5+2)
    for x in A:
        dp[x]+=1
    for i in range(2,len(dp)):
        for j in range(2,len(dp)):
            if i*j>len(dp)-1:
                break
            dp[i]+=dp[i*j]
    for i in range(2,len(dp)):
        dp[i]=(pow(2,dp[i],MOD)-1)%MOD

    for i in range(len(dp)-1,1,-1):
        for j in range(2,len(dp)):
            if i*j>=len(dp):
                break
            dp[i]-=dp[i*j]
            dp[i]%=MOD

    ans=0
    for i in range(2,len(dp)):
        ans+=dp[i]
        ans%=MOD

    return (pow(2,len(A),MOD)-ans-1)%MOD
input()
print(find(list(map(int,input().strip().split(' ')))))


I found an interesting problem on https://codeforces.com/problemset/problem/804/A:
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.

There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs $(i + j) \operatorname{mod}(n + 1)$ and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.

-----Input-----

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

-----Output-----

Print single integer: the minimum cost of tickets needed to visit all schools.

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

Output
0

Input
10

Output
4

-----Note-----

In the first example we can buy a ticket between the schools that costs $(1 + 2) \operatorname{mod}(2 + 1) = 0$.

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/804/E:
Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions (i, j), where i < j, exactly once. MoJaK doesn't like to upset Sajjad.

Given the permutation, determine whether it is possible to swap all pairs of positions so that the permutation stays the same. If it is possible find how to do that.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 1000) — the size of the permutation.

As the permutation is not important, you can consider a_{i} = i, where the permutation is a_1, a_2, ..., a_{n}.

-----Output-----

If it is not possible to swap all pairs of positions so that the permutation stays the same, print "NO",

Otherwise print "YES", then print $\frac{n(n - 1)}{2}$ lines: the i-th of these lines should contain two integers a and b (a < b) — the positions where the i-th swap is performed.

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

Output
NO

Input
1

Output
YES

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

n=int(input())
p=lambda a,b:print(a+1,b+1)
b=[0,1]
if n%4>1:
	print("NO")
else:
	print("YES")
	for i in range(n%4,n,4):
		for x in b:
			a=2*x
			for j in range(i):p(j,i+a)
			p(i+a,i+a+1)
			for j in range(i,0,-1):p(j-1,i+a+1)
		[p(i+y,i+(y^(3-x))) for x in b for y in b]


I found an interesting problem on https://codeforces.com/problemset/problem/805/B:
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.

He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 2·10^5) — the length of the string.

-----Output-----

Print the string that satisfies all the constraints.

If there are multiple answers, print any of them.

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

Output
aa

Input
3

Output
bba

-----Note-----

A palindrome is a sequence of characters which reads the same backward and forward.

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

import sys

fin = sys.stdin
fout = sys.stdout
n = int(fin.readline())
m = ['a', 'b']
s = ''
for i in range(n):
    s += m[(i // 2) % 2]
fout.write(s)


I found an interesting problem on https://codeforces.com/problemset/problem/807/A:
Is it rated?

Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.

Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.

It's known that if at least one participant's rating has changed, then the round was rated for sure.

It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.

In this problem, you should not make any other assumptions about the rating system.

Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants.

Each of the next n lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.

-----Output-----

If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".

-----Examples-----
Input
6
3060 3060
2194 2194
2876 2903
2624 2624
3007 2991
2884 2884

Output
rated

Input
4
1500 1500
1300 1300
1200 1200
1400 1400

Output
unrated

Input
5
3123 3123
2777 2777
2246 2246
2246 2246
1699 1699

Output
maybe

-----Note-----

In the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.

In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for...

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

n = int(input())
a=[[int(i) for i in input().split()] for i in range(n)]
ans = 'maybe'
for i in range(n):
    if a[i][0] != a[i][1]:
        ans = 'rated'
        break
else:
    for i in range(n-1):
        if a[i][0] < a[i+1][0]:
            ans = 'unrated'
            break
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/807/B:
Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt.

Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place p.

Now the elimination round of 8VC Venture Cup 2017 is being held. It has been announced that the Codecraft-17 T-shirt winners will be chosen as follows. Let s be the number of points of the winner of the elimination round of 8VC Venture Cup 2017. Then the following pseudocode will be executed:

i := (s div 50) mod 475

repeat 25 times:

    i := (i * 96 + 42) mod 475

    print (26 + i)

Here "div" is the integer division operator, "mod" is the modulo (the remainder of division) operator.

As the result of pseudocode execution, 25 integers between 26 and 500, inclusive, will be printed. These will be the numbers of places of the participants who get the Codecraft-17 T-shirts. It is guaranteed that the 25 printed integers will be pairwise distinct for any value of s.

You're in the lead of the elimination round of 8VC Venture Cup 2017, having x points. You believe that having at least y points in the current round will be enough for victory.

To change your final score, you can make any number of successful and unsuccessful hacks. A successful hack brings you 100 points, an unsuccessful one takes 50 points from you. It's difficult to do successful hacks, though.

You want to win the current round and, at the same time, ensure getting a Codecraft-17 T-shirt. What is the smallest number of successful hacks you have to do to achieve that?

-----Input-----

The only line contains three integers p, x and y (26 ≤ p ≤ 500; 1 ≤ y ≤ x ≤ 20000) — your place in Codecraft-17, your current score in the elimination round of 8VC Venture Cup 2017, and the smallest number of points you consider sufficient for winning the current round.

-----Output-----

Output a single integer — the smallest number of successful hacks you have to...

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

def main():
    p, x, y = list(map(int, input().split()))

    # 0 check
    xcopy = x
    while xcopy >= y:
        if p in choice(xcopy):
            print(0)
            return
        xcopy -= 50

    # + check
    i = 1
    while x <= 23800:
        if (p in choice(x + 100*i - 50)) or (p in choice(x + 100*i)):
            print(i)
            return
        i += 1

def choice(s):
    i = (s//50)%475

    res = []
    for n in range(25):
        i = (i*96 + 42) % 475
        res.append(26 + i)

    return res

def __starting_point():
    # nonlocal stime
    # stime = time.clock()
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/808/A:
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.

You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.

-----Input-----

The first line contains integer number n (1 ≤ n ≤ 10^9) — current year in Berland.

-----Output-----

Output amount of years from the current year to the next lucky one.

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

Output
1

Input
201

Output
99

Input
4000

Output
1000

-----Note-----

In the first example next lucky year is 5. In the second one — 300. In the third — 5000.

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

n = int(input())
ans = 0
prev = 0
N = n
while n:
	a = n%10
	n //= 10
	ans += 1
	prev = a
if ans==1:
	print(1)
else:
	print(((prev+1)*(10**(ans-1)))-N)


I found an interesting problem on https://codeforces.com/problemset/problem/808/B:
It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days!

When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a_1, a_2, ..., a_{n}, where a_{i} is the sleep time on the i-th day.

The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is $\frac{(3 + 4) +(4 + 7)}{2} = 9$.

You should write a program which will calculate average sleep times of Polycarp over all weeks.

-----Input-----

The first line contains two integer numbers n and k (1 ≤ k ≤ n ≤ 2·10^5).

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

-----Output-----

Output average sleeping time over all weeks.

The answer is considered to be correct if its absolute or relative error does not exceed 10^{ - 6}. In particular, it is enough to output real number with at least 6 digits after the decimal point.

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

Output
9.0000000000

Input
1 1
10

Output
10.0000000000

Input
8 2
1 2 4 100000 123 456 789 1

Output
28964.2857142857

-----Note-----

In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7.

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

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

    ans = 0

    for i in range(n):
        l = max(i - k + 1, 0)
        r = min(i, n - k)
        ans += a[i] * (r - l + 1)

    print("{:.12f}".format(ans / (n - k + 1)))

def __starting_point():
    # import sys
    # sys.stdin = open("in.txt")
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/808/C:
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a_1, a_2, ..., a_{n}. His teapot stores w milliliters of tea (w ≤ a_1 + a_2 + ... + a_{n}). Polycarp wants to pour tea in cups in such a way that:  Every cup will contain tea for at least half of its volume  Every cup will contain integer number of milliliters of tea  All the tea from the teapot will be poured into cups  All friends will be satisfied.

Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but a_{i} > a_{j}.

For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.

-----Input-----

The first line contains two integer numbers n and w (1 ≤ n ≤ 100, $1 \leq w \leq \sum_{i = 1}^{n} a_{i}$).

The second line contains n numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100).

-----Output-----

Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.

If it's impossible to pour all the tea and satisfy all conditions then output -1.

-----Examples-----
Input
2 10
8 7

Output
6 4

Input
4 4
1 1 1 1

Output
1 1 1 1

Input
3 10
9 8 10

Output
-1

-----Note-----

In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.

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

n, w = map(int, input().split())
a = list(map(int, input().split()))
s = 0
for i in range(n):
    s += (a[i] + 1) // 2
    a[i] = [a[i], i]
if s > w:
    print(-1)
else:
    res = [[(a[i][0] + 1) // 2, i] for i in range(n)]
    w -= s
    a.sort(reverse=True)
    i = 0
    while w > 0:
        res[a[i][1]][0] = min(a[i][0], res[a[i][1]][0] + w)
        w -= a[i][0] // 2
        i += 1
    for i in range(n):
        print(res[i][0], end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/808/D:
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).

Inserting an element in the same position he was erased from is also considered moving.

Can Vasya divide the array after choosing the right element to move and its new position?

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 100000) — the size of the array.

The second line contains n integers a_1, a_2... a_{n} (1 ≤ a_{i} ≤ 10^9) — the elements of the array.

-----Output-----

Print YES if Vasya can divide the array after moving one element. Otherwise print NO.

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

Output
YES

Input
5
1 2 3 4 5

Output
NO

Input
5
2 2 3 4 5

Output
YES

-----Note-----

In the first example Vasya can move the second element to the end of the array.

In the second example no move can make the division possible.

In the third example Vasya can move the fourth element by one position to the left.

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

def f(aa, s):
    d = {a: i for i, a in enumerate(aa)}
    for i, a in enumerate(aa):
        if s in d and i <= d[s]:
            return True
        s -= a
        if s <= 0:
            break
    return not s

n = int(input())
aa = list(map(int, input().split()))
s, res = sum(aa), False
if not s & 1 and n > 1:
    res = f(aa, s // 2)
    if not res:
        aa.reverse()
        res = f(aa, s // 2)
print(("NO", "YES")[res])


I found an interesting problem on https://codeforces.com/problemset/problem/808/E:
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.

This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight w_{i} and cost c_{i}. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.

Help Petya to determine maximum possible total cost.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.

Then n lines follow. ith line contains two integers w_{i} and c_{i} (1 ≤ w_{i} ≤ 3, 1 ≤ c_{i} ≤ 10^9) — the weight and the cost of ith souvenir.

-----Output-----

Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.

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

Output
0

Input
2 2
1 3
2 2

Output
3

Input
4 3
3 10
2 7
2 8
1 1

Output
10

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

n,m = map(int,input().split())
a = [[],[],[]]
for _ in range(n):
    x,y = map(int,input().split())
    a[x-1].append(y)

for i in range(3):
    a[i].sort(reverse=True)

a_one_odd = []
a_one_even = []
a_length = [len(a[i]) for i in range(3)]
for i in range(0,a_length[0]-1,2):
    a_one_even.append(a[0][i]+a[0][i+1])
for i in range(1,a_length[0]-1,2):
    a_one_odd.append(a[0][i]+a[0][i+1])
data_even = sorted(a_one_even+a[1],reverse=True)
data_odd = sorted(a_one_odd+a[1],reverse=True)

data_sum_even = [0]
for x in data_even:
    data_sum_even.append(data_sum_even[-1]+x)
data_sum_odd = [0]
for x in data_odd:
    data_sum_odd.append(data_sum_odd[-1]+x)

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

ans = 0
#print(data_sum_odd,data_sum_even,data_sum_three)
for k in range(a_length[2]+1):
    if m-3*k < 0:break
    now1,now2 = data_sum_three[k],data_sum_three[k]
    if (m-3*k)%2== 0:
        now1 += data_sum_even[min((m-3*k)//2,len(data_sum_even)-1)]
        if a_length[0] > 0 and m-3*k > 0:
            now2 += a[0][0]
        if (m-3*k)//2 >= 1:
            now2 += data_sum_odd[min((m-3*k)//2-1,len(data_sum_odd)-1)]
    else:
        now1 += data_sum_even[min((m-3*k)//2,len(data_sum_even)-1)]
        if a_length[0] > 0 and m-3*k > 0:
            now2 += a[0][0]
        now2 += data_sum_odd[min((m-3*k-1)//2,len(data_sum_odd)-1)]
    ans = max(ans,now1,now2)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/808/G:
Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.

Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.

He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work.

The anthem is the string s of no more than 10^5 small Latin letters and question marks. The most glorious victory is the string t of no more than 10^5 small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string t in string s is maximal.

Note that the occurrences of string t in s can overlap. Check the third example for clarification.

-----Input-----

The first line contains string of small Latin letters and question marks s (1 ≤ |s| ≤ 10^5).

The second line contains string of small Latin letters t (1 ≤ |t| ≤ 10^5).

Product of lengths of strings |s|·|t| won't exceed 10^7.

-----Output-----

Output the maximum number of occurrences of string t you can achieve by replacing all the question marks in string s with small Latin letters.

-----Examples-----
Input
winlose???winl???w??
win

Output
5

Input
glo?yto?e??an?
or

Output
3

Input
??c?????
abcab

Output
2

-----Note-----

In the first example the resulting string s is "winlosewinwinlwinwin"

In the second example the resulting string s is "glorytoreorand". The last letter of the string can be arbitrary.

In the third example occurrences of string t are overlapping. String s with maximal number of occurrences of t is "abcabcab".

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

t=input()
s=input()
n=len(s)
h=[0]*(n+1)
h[0]=0
j=0
fa=[0]*(n+1)
for i in range(2,n+1) :
    while j and s[i-1]!=s[j]:
        #j=fa[j-1];
        j=fa[j];
    if s[i-1]==s[j]:
        j+=1
    fa[i]=j;
#print(fa)
l=list()
j=fa[n]
while(j>0):
    l.append(j)
    j=fa[j]

tmp=t
t=s
s=tmp
n=len(s)
dp=[0]*(n)
m=[0]*n
'''if len(s)<len(t):
    print(0)'''

for i in range(len(t)-1,len(s)):
    can=True
    for j in range(len(t)):
        if s[i-len(t)+1+j]=='?':
            continue
        if s[i-len(t)+1+j]!=t[j]:
            can=False
            break
    if can:
        dp[i]=1
        for d in l:
            d=len(t)-d
            dp[i]=max(dp[i],1+dp[i-d])
        if i-len(t)>=0:
            dp[i]=max(dp[i],m[i-len(t)]+1)
    m[i]=max(m[i-1],dp[i])
print(m[-1])


I found an interesting problem on https://codeforces.com/problemset/problem/809/A:
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.

Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point x_{i}. Moreover the coordinates of all computers are distinct.

Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.

Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression $\sum_{a \subseteq A, a \neq \varnothing} F(a)$. Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, $F(a) = \operatorname{max}_{i, j \in a}|x_{i} - x_{j}|$. Since the required sum can be quite large Noora asks to find it modulo 10^9 + 7.

Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 3·10^5) denoting the number of hacked computers.

The second line contains n integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^9) denoting the coordinates of hacked computers. It is guaranteed that all x_{i} are distinct.

-----Output-----

Print a single integer — the required sum modulo 10^9 + 7.

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

Output
3

Input
3
4 3 1

Output
9

-----Note-----

There are three non-empty subsets in the first...

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

import sys
import math

MOD = int(1e9 + 7)
line = lambda: list(map(int, input().split()))

def solve():
    n = int(input())
    x = [x for x in line()]
    x.sort()
    p2 = []
    p2.append(1)
    for i in range(1, n):
        p2.append(p2[i - 1] * 2 % MOD)
    ans = 0
    for i in range(n):
        ans += x[i] * (p2[i] - p2[n - i - 1] + MOD)
        ans %= MOD
    print(ans)

def main():
    solve()
    return

main()


I found an interesting problem on https://codeforces.com/problemset/problem/810/A:
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one.

In school, where Noora is studying, teachers are putting down marks to the online class register, which are integers from 1 to k. The worst mark is 1, the best is k. Mark that is going to the certificate, is calculated as an average of all the marks, rounded to the closest integer. If several answers are possible, rounding up is produced. For example, 7.3 is rounded to 7, but 7.5 and 7.8784 — to 8.

For instance, if Noora has marks [8, 9], then the mark to the certificate is 9, because the average is equal to 8.5 and rounded to 9, but if the marks are [8, 8, 9], Noora will have graduation certificate with 8.

To graduate with «A» certificate, Noora has to have mark k.

Noora got n marks in register this year. However, she is afraid that her marks are not enough to get final mark k. Noora decided to ask for help in the internet, where hacker Leha immediately responded to her request. He is ready to hack class register for Noora and to add Noora any number of additional marks from 1 to k. At the same time, Leha want his hack be unseen to everyone, so he decided to add as less as possible additional marks. Please help Leha to calculate the minimal number of marks he has to add, so that final Noora's mark will become equal to k.

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 100) denoting the number of marks, received by Noora and the value of highest possible mark.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ k) denoting marks received by Noora before Leha's hack.

-----Output-----

Print a single integer — minimal number of additional marks, that Leha has to add in order to change Noora's final mark to k.

-----Examples-----
Input
2 10
8 9

Output
4
Input
3 5
4 4 4

Output
3

-----Note-----

Consider the first example...

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

n,k = map(int, input().split())
a = list(map(int, input().split()))
sm = sum(a)
l,r = -1, 10 ** 20
def check(m):
    return round((sm + k * m) / (n + m) + 0.000001) >= k
while r - l > 1:
    m = (l + r) // 2
    if check(m):
        r = m
    else:
        l = m
print(r)


I found an interesting problem on https://codeforces.com/problemset/problem/810/B:
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.

Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day k_{i} products will be put up for sale and exactly l_{i} clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.

For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale k_{i} products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·k_{i} products. Consequently, there is an opportunity to sell two times more products on days of sell-out.

Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.

-----Input-----

The first line contains two integers n and f (1 ≤ n ≤ 10^5, 0 ≤ f ≤ n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out.

Each line of the following n subsequent lines contains two integers k_{i}, l_{i} (0 ≤ k_{i}, l_{i} ≤ 10^9) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.

-----Output-----

Print a single integer denoting the maximal number of products that shop can sell.

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

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

#!/usr/bin/env python

import sys

n, f = list(map(int, sys.stdin.readline().split()))
increments = []
without_increments = 0
for __ in range(n):
    prod, cust = list(map(int, sys.stdin.readline().split()))
    increments.append(max(0, min(prod * 2, cust) - prod))
    #print(increments)
    without_increments += min(prod, cust)
    #print( without_increments )
print(without_increments + sum(sorted(increments, reverse=True)[:f]))


I found an interesting problem on https://codeforces.com/problemset/problem/811/A:
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.

More formally, the guys take turns giving each other one candy more than they received in the previous turn.

This continued until the moment when one of them couldn’t give the right amount of candy. Candies, which guys got from each other, they don’t consider as their own. You need to know, who is the first who can’t give the right amount of candy.

-----Input-----

Single line of input data contains two space-separated integers a, b (1 ≤ a, b ≤ 10^9) — number of Vladik and Valera candies respectively.

-----Output-----

Pring a single line "Vladik’’ in case, if Vladik first who can’t give right amount of candy, or "Valera’’ otherwise.

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

Output
Valera

Input
7 6

Output
Vladik

-----Note-----

Illustration for first test case:

[Image]

Illustration for second test case:

[Image]

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

a, b = list(map(int, input().split()))
curr = 1
while True:
    if curr % 2 == 1:
        a -= curr
    if curr % 2 == 0:
        b -= curr
    curr += 1
    if a < 0:
        print("Vladik")
        return
    if b < 0:
        print("Valera")
        return


I found an interesting problem on https://codeforces.com/problemset/problem/811/B:
Vladik had started reading a complicated book about algorithms containing n pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation P = [p_1, p_2, ..., p_{n}], where p_{i} denotes the number of page that should be read i-th in turn.

Sometimes Vladik’s mom sorted some subsegment of permutation P from position l to position r inclusive, because she loves the order. For every of such sorting Vladik knows number x — what index of page in permutation he should read. He is wondered if the page, which he will read after sorting, has changed. In other words, has p_{x} changed? After every sorting Vladik return permutation to initial state, so you can assume that each sorting is independent from each other.

-----Input-----

First line contains two space-separated integers n, m (1 ≤ n, m ≤ 10^4) — length of permutation and number of times Vladik's mom sorted some subsegment of the book.

Second line contains n space-separated integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — permutation P. Note that elements in permutation are distinct.

Each of the next m lines contains three space-separated integers l_{i}, r_{i}, x_{i} (1 ≤ l_{i} ≤ x_{i} ≤ r_{i} ≤ n) — left and right borders of sorted subsegment in i-th sorting and position that is interesting to Vladik.

-----Output-----

For each mom’s sorting on it’s own line print "Yes", if page which is interesting to Vladik hasn't changed, or "No" otherwise.

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

Output
Yes
No
Yes
Yes
No

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

Output
Yes
No
Yes
No
Yes

-----Note-----

Explanation of first test case:   [1, 2, 3, 4, 5] — permutation after sorting, 3-rd element hasn’t changed, so answer is "Yes".  [3, 4, 5, 2, 1] — permutation after sorting, 1-st element has changed, so answer is "No".  [5, 2, 3, 4, 1] — permutation after sorting, 3-rd element hasn’t changed, so answer is "Yes".  [5, 4, 3, 2, 1] — permutation after sorting, 4-th...

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

##n = int(input())
##a = list(map(int, input().split()))
##print(' '.join(map(str, res)))

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

for i in range(m):
    [l, r, x] = list(map(int, input().split()))
    a = p[x-1]
    cnt = 0
    for j in range(l, r+1):
        if p[j-1] <= a:
            cnt += 1
    if cnt == x-l+1:
        print('Yes')
    else:
        print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/811/C:
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:

Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code a_{i} is known (the code of the city in which they are going to).

Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.

Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.

Total comfort of a train trip is equal to sum of comfort for each segment.

Help Vladik to know maximal possible total comfort.

-----Input-----

First line contains single integer n (1 ≤ n ≤ 5000) — number of people.

Second line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 5000), where a_{i} denotes code of the city to which i-th person is going.

-----Output-----

The output should contain a single integer — maximal possible total comfort.

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

Output
14

Input
9
5 1 3 1 5 2 4 2 5

Output
9

-----Note-----

In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14

In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.

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

"""
from
http://codeforces.com/contest/811/problem/C
"""
length = int(input())
array = [0] + [int(x) for x in input().split()]
dp = [0]*(length+1)
end = [0]*5001
start = [5001]*5001
vis = [0]*5001

for i in range(1,length+1):
    start[array[i]] = min(start[array[i]],i)
    end[array[i]] = max(end[array[i]],i)

for i in range(1, length + 1):
    dp[i] = dp[i-1]
    chk = [0] * 5001
    ll = i
    cur = 0
    for j in range(i,0,-1):
        ll = min(ll,start[array[j]])
        if end[array[j]] > i:break
        if chk[array[j]] == 0:
            cur = array[j] ^ cur
            chk[array[j]] = 1
        if ll == j:
            dp[i] = max(dp[i],dp[j-1]+cur)
print(dp[length])


I found an interesting problem on https://codeforces.com/problemset/problem/812/A:
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane getting into the intersection (l — left, s — straight, r — right) and a light p for a pedestrian crossing.  [Image]

An accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time.

Now, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible.

-----Input-----

The input consists of four lines with each line describing a road part given in a counter-clockwise order.

Each line contains four integers l, s, r, p — for the left, straight, right and pedestrian lights, respectively. The possible values are 0 for red light and 1 for green light.

-----Output-----

On a single line, print "YES" if an accident is possible, and "NO" otherwise.

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

Output
YES

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

Output
NO

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

Output
NO

-----Note-----

In the first example, some accidents are possible because cars of part 1 can hit pedestrians of parts 1 and 4. Also, cars of parts 2 and 3 can hit pedestrians of part 4.

In the second example, no car can pass the pedestrian crossing of part 4 which is the only green pedestrian light. So, no accident can occur.

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

p = [list(map(int, input().split())) for i in range(4)]
log = False
for i in range(4):
    if p[i][3] == 1 and (p[i - 1][2] + p[(i + 1) % 4][0] + p[(i + 2) % 4][1] + p[i][1] + p[i][0] + p[i][2] > 0):
        log = True
if log:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/812/B:
Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.

The building consists of n floors with stairs at the left and the right sides. Each floor has m rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with n rows and m + 2 columns, where the first and the last columns represent the stairs, and the m columns in the middle represent rooms.

Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights.

Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 15 and 1 ≤ m ≤ 100) — the number of floors and the number of rooms in each floor, respectively.

The next n lines contains the building description. Each line contains a binary string of length m + 2 representing a floor (the left stairs, then m rooms, then the right stairs) where 0 indicates that the light is off and 1 indicates that the light is on. The floors are listed from top to bottom, so that the last line represents the ground floor.

The first and last characters of each string represent the left and the right stairs, respectively, so they are always 0.

-----Output-----

Print a...

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

import sys
from itertools import accumulate
from operator import or_

inf = float('inf')

def solve():
    n, m = map(int, input().split())
    s = [[int(j) for j in input()] for i in range(n)][::-1]

    e = [any(si) for si in s]
    es = e[:] + [False]
    es = list(accumulate(es[::-1], or_))[::-1]

    if not es[0]:
        print(0)
    else:
        lim = 0

        for i in range(n + 1):
            if not es[i]:
                lim = i - 1
                break

        left, right = -1, inf

        for i in range(lim):
            if not e[i]:
                left, right = min(left + 1, right + m + 2), min(right + 1, left + m + 2)
            else:
                kr = rindex(s[i], 1)
                kl = s[i].index(1)
                left, right = min(left + 1 + 2*kr, right + m + 2), min(right + 1 + 2*(m + 1 - kl), left + m + 2)

        kr = rindex(s[lim], 1)
        kl = s[lim].index(1)

        ans = min(left + 1 + kr, right + m + 2 - kl)

        print(ans)

def rindex(arr, x):
    return len(arr) - 1 - arr[::-1].index(x)

def __starting_point():
    solve()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/812/C:
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost a_{i} Egyptian pounds. If Sagheer buys k items with indices x_1, x_2, ..., x_{k}, then the cost of item x_{j} is a_{x}_{j} + x_{j}·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k.

Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?

-----Input-----

The first line contains two integers n and S (1 ≤ n ≤ 10^5 and 1 ≤ S ≤ 10^9) — the number of souvenirs in the market and Sagheer's budget.

The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5) — the base costs of the souvenirs.

-----Output-----

On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs.

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

Output
2 11

Input
4 100
1 2 5 6

Output
4 54

Input
1 7
7

Output
0 0

-----Note-----

In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items.

In the second example, he can buy all items as they will cost him [5, 10, 17, 22].

In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it.

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

def func(c,k,s,n):
	nc=[]
	for i in range(n):
		nc.append(c[i]+(i+1)*(k+1))
	nc.sort()
	val=sum(nc[:k+1])
	if(val<=s):
		return val
	else:
		return -1

inp=input().split()
n=int(inp[0])
s=int(inp[1])
c=[]
val=input().split()
i=1
for v in val:
	c.append(int(v))
	i+=1
begin=0
end=n-1
flag=0
while(begin<=end):
	mid=(begin+end)//2
	if(func(c,mid,s,n)!=-1):
		if(mid==n-1):
			print(mid+1,func(c,mid,s,n))
			flag=1
			break
		if(func(c,mid+1,s,n)==-1):
			print(mid+1,func(c,mid,s,n))
			flag=1
			break
		else:
			begin=mid+1
	else:
		end=mid-1
if(flag==0):
	print("0 0")


I found an interesting problem on https://codeforces.com/problemset/problem/812/E:
Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has a_{i} apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).

Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.

In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things:  eat the apples, if the node is a leaf.  move the apples to one of the children, if the node is non-leaf.

Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v.

Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u, v) and (v, u) are considered to be the same pair.

-----Input-----

The first line will contain one integer n (2 ≤ n ≤ 10^5) — the number of nodes in the apple tree.

The second line will contain n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^7) — the number of apples on each node of the tree.

The third line will contain n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_{i} ≤ n) — the parent of each node of the tree. Node i has parent p_{i} (for 2 ≤ i ≤ n). Node 1 is the root of the tree.

It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.

-----Output-----

On a single line, print the number of different pairs of nodes (u, v), u ≠ v such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u, v) and (v, u) are considered to be the same pair.

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

Output
1

Input
3
1 2 3
1 1

Output
0

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

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

def coloring(i, ancestors, color):
    while i != 0 and color[ancestors[i - 1]] is None:
        color[ancestors[i - 1]] = not color[i]
        i = ancestors[i - 1]

def main():
    n = int(input())
    a = list(map(int, input().split()))
    ancestors = list([int(x) - 1 for x in input().split()])
    descendants = [[] for i in range(n)]
    for i in range(n - 1):
        descendants[ancestors[i]].append(i + 1)
    color = [None for i in range(n)]
    for i in range(n):
        if not descendants[i]:
            color[i] = True
            coloring(i, ancestors, color)
    reds = 0
    blues = 0
    xor = 0
    count_red = dict()
    count_blue = dict()
    for i in range(n):
        if color[i]:
            blues += 1
            xor ^= a[i]
            if str(a[i]) in count_blue:
                count_blue[str(a[i])] += 1
            else:
                count_blue[str(a[i])] = 1
        else:
            reds += 1
            if str(a[i]) in count_red:
                count_red[str(a[i])] += 1
            else:
                count_red[str(a[i])] = 1
    res = 0
    if xor == 0:
        res += (blues - 1) * blues // 2
        res += (reds - 1) * reds // 2
        for i in list(count_blue.items()):
            if i[0] in count_red:
                res += i[1] * count_red[i[0]]
    else:
        for i in list(count_blue.items()):
            if str(xor ^ int(i[0])) in count_red:
                res += i[1] * count_red[str(xor ^ int(i[0]))]
    print(res)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/813/A:
Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!

This contest consists of n problems, and Pasha solves ith problem in a_{i} time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. Pasha can send any number of solutions at the same moment.

Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during m time periods, jth period is represented by its starting moment l_{j} and ending moment r_{j}. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment T iff there exists a period x such that l_{x} ≤ T ≤ r_{x}.

Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have solutions to all problems submitted, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 1000) — the number of problems. The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^5) — the time Pasha needs to solve ith problem.

The third line contains one integer m (0 ≤ m ≤ 1000) — the number of periods of time when the website is working. Next m lines represent these periods. jth line contains two numbers l_{j} and r_{j} (1 ≤ l_{j} < r_{j} ≤ 10^5) — the starting and the ending moment of jth period.

It is guaranteed that the periods are not intersecting and are given in chronological order, so for every j > 1 the condition l_{j} > r_{j} - 1 is met.

-----Output-----

If Pasha can solve and submit all the problems before the end of the contest, print the minimal moment of time by which he can have all the solutions...

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

n = int(input())
a = list(map(int, input().split()))
ans = -1
s = sum(a)
m = int(input())
for _ in range(m):
    l, r = list(map(int, input().split()))
    if ans == -1:
        if l <= s <= r:
            ans = s
        elif s < l:
            ans = l

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/813/B:
Unlucky year in Berland is such a year that its number n can be represented as n = x^{a} + y^{b}, where a and b are non-negative integer numbers.

For example, if x = 2 and y = 3 then the years 4 and 17 are unlucky (4 = 2^0 + 3^1, 17 = 2^3 + 3^2 = 2^4 + 3^0) and year 18 isn't unlucky as there is no such representation for it.

Such interval of years that there are no unlucky years in it is called The Golden Age.

You should write a program which will find maximum length of The Golden Age which starts no earlier than the year l and ends no later than the year r. If all years in the interval [l, r] are unlucky then the answer is 0.

-----Input-----

The first line contains four integer numbers x, y, l and r (2 ≤ x, y ≤ 10^18, 1 ≤ l ≤ r ≤ 10^18).

-----Output-----

Print the maximum length of The Golden Age within the interval [l, r].

If all years in the interval [l, r] are unlucky then print 0.

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

Output
1

Input
3 5 10 22

Output
8

Input
2 3 3 5

Output
0

-----Note-----

In the first example the unlucky years are 2, 3, 4, 5, 7, 9 and 10. So maximum length of The Golden Age is achived in the intervals [1, 1], [6, 6] and [8, 8].

In the second example the longest Golden Age is the interval [15, 22].

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

x,y,l,r=list(map(int,input().split()))
b=set()
a=0
b.add(l-1)
b.add(r+1)
for i in range(100):
  xx=x**i
  if xx>r: break
  for j in range(100):
    rr=xx+(y**j)
    if rr>r: break
    if rr>=l:
      b.add(rr)
b=sorted(list(b))
for i in range(1,len(b)):
  a=max(a,b[i]-b[i-1]-1)
print(a)


I found an interesting problem on https://codeforces.com/problemset/problem/813/C:
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.

Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.

The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.

You should write a program which will determine how many moves will the game last.

-----Input-----

The first line contains two integer numbers n and x (2 ≤ n ≤ 2·10^5, 2 ≤ x ≤ n).

Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.

-----Output-----

Print the total number of moves Alice and Bob will make.

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

Output
4

Input
5 2
1 2
2 3
3 4
2 5

Output
6

-----Note-----

In the first example the tree looks like this:

 [Image]

The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:

B: stay at vertex 3

A: go to vertex 2

B: stay at vertex 3

A: go to vertex 3

In the second example the tree looks like this:

 [Image]

The moves in the optimal strategy are:

B: go to vertex 3

A: go to vertex 2

B: go to vertex 4

A: go to vertex 3

B: stay at vertex 4

A: go to vertex 4

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

from sys import stdin

#Clase nodo
class Node():
    def __init__(self,value=None,prox=None):
        self.value=value
        self.prox=prox
#Clase cola
class Queue:
    def __init__(self):
        self.first=None
        self.last=None
        self.count=0

    def Enqueue(self,value):
        new_node=Node(value)
        self.count+=1
        if self.first is None:
            self.last=self.first=new_node
        else:
            self.last.prox=new_node
            self.last=new_node

    def Dequeue(self):
        value=self.first.value
        self.count-=1
        self.first=self.first.prox
        return value

#Parser
def parser():
    return [int(x) for x in input().split(" ")]

#Algoritmo BFS
def BFS(s):
    if s==0:
        distance=distance_Alice
    else:
        distance=distance_Bob

    distance[s]=0
    q=Queue()
    q.Enqueue(s)
    while q.count>0:
        v=q.Dequeue()
        for u in adjacents_list[v]:
            if distance[u] == -1:
                distance[u]=distance[v]+1
                q.Enqueue(u)

#Recibiendo los valores de n y x
n,x=map(int, stdin.readline().split())

#Creando los arrays necesarios para la ejecucion de DFS
#visitados
distance_Alice=[-1 for i in range(n)]
distance_Bob=[-1 for i in range(n)]

#Armando el arbol
adjacents_list=[[] for i in range(n)]
for i in range(n-1):
    v1,v2=map(int, stdin.readline().split())
    adjacents_list[v1-1].append(v2-1)
    adjacents_list[v2-1].append(v1-1)

BFS(0)

BFS(x-1)

#Hallando el nodo mas alejado a Alice que puede alcanzar Bob antes que lo alcance Alice
max=0
for i in range(n):
    if max<distance_Alice[i] and distance_Bob[i]<distance_Alice[i]:
        max=distance_Alice[i]

print(max*2)


I found an interesting problem on https://codeforces.com/problemset/problem/813/D:
Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time!

Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal.

Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

Subsequence forms a melody when each two adjacent notes either differs by 1 or are congruent modulo 7.

You should write a program which will calculate maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.

-----Input-----

The first line contains one integer number n (2 ≤ n ≤ 5000).

The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5) — notes written on a sheet.

-----Output-----

Print maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.

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

Output
4

Input
6
62 22 60 61 48 49

Output
5

-----Note-----

In the first example subsequences [1, 2] and [4, 5] give length 4 in total.

In the second example subsequences [62, 48, 49] and [60, 61] give length 5 in total. If you choose subsequence [62, 61] in the first place then the second melody will have maximum length 2, that gives the result of 4, which is not maximal.

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

import sys

def solve():
    n = int(sys.stdin.readline())
    a = [0] + [int(i) for i in sys.stdin.readline().split()]

    dp = [[0]*(n + 1) for i in range(n + 1)]
    ans = 0

    maxnum = [0] * (10**5 + 2)
    maxmod = [0] * 7

    for y in range(n + 1):
        maxmod = [0] * 7

        for ai in a:
            maxnum[ai] = 0

        for i in range(y):
            maxmod[a[i] % 7] = max(maxmod[a[i] % 7], dp[i][y])
            maxnum[a[i]] = max(maxnum[a[i]], dp[i][y])

        for x in range(y + 1, n + 1):
            dp[x][y] = max(maxmod[a[x] % 7], maxnum[a[x] + 1], maxnum[a[x] - 1], dp[0][y]) + 1
            dp[y][x] = dp[x][y]
            maxmod[a[x] % 7] = max(maxmod[a[x] % 7], dp[x][y])
            maxnum[a[x]] = max(maxnum[a[x]], dp[x][y])
            ans = max(ans, dp[x][y])

    print(ans)

def __starting_point():
    solve()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/814/A:
A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed.

To get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long time, but now Kaiki provides an opportunity.

Hitagi's sequence a has a length of n. Lost elements in it are denoted by zeros. Kaiki provides another sequence b, whose length k equals the number of lost elements in a (i.e. the number of zeros). Hitagi is to replace each zero in a with an element from b so that each element in b should be used exactly once. Hitagi knows, however, that, apart from 0, no integer occurs in a and b more than once in total.

If the resulting sequence is not an increasing sequence, then it has the power to recover Hitagi from the oddity. You are to determine whether this is possible, or Kaiki's sequence is just another fake. In other words, you should detect whether it is possible to replace each zero in a with an integer from b so that each integer from b is used exactly once, and the resulting sequence is not increasing.

-----Input-----

The first line of input contains two space-separated positive integers n (2 ≤ n ≤ 100) and k (1 ≤ k ≤ n) — the lengths of sequence a and b respectively.

The second line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 200) — Hitagi's broken sequence with exactly k zero elements.

The third line contains k space-separated integers b_1, b_2, ..., b_{k} (1 ≤ b_{i} ≤ 200) — the elements to fill into Hitagi's sequence.

Input guarantees that apart from 0, no integer occurs in a and b more than once in total.

-----Output-----

Output "Yes" if it's possible to replace zeros in a with elements in b and make the resulting sequence not increasing, and "No" otherwise.

-----Examples-----
Input
4 2
11 0 0 14
5 4

Output
Yes

Input
6 1
2 3 0 8 9 10
5

Output
No

Input
4 1
8 94 0 4
89

Output
Yes

Input
7 7
0 0 0 0 0 0...

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

import sys

def main():
    n,k = map(int,sys.stdin.readline().split())

    a = list(map(int, sys.stdin.readline().split()))
    b = list(map(int, sys.stdin.readline().split()))
    b.sort(reverse=True)
    j = 0
    for i in range(n):
        if a[i] ==0:
            a[i] = b[j]
            j+=1

    p = a[0]
    for i in range(1,n):
        if a[i] <= p:
            print("Yes")
            return
        p = a[i]

    print("No")

main()


I found an interesting problem on https://codeforces.com/problemset/problem/814/B:
Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.

On that night, Sengoku constructed a permutation p_1, p_2, ..., p_{n} of integers from 1 to n inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with n meteorids, colours of which being integer sequences a_1, a_2, ..., a_{n} and b_1, b_2, ..., b_{n} respectively. Meteoroids' colours were also between 1 and n inclusive, and the two sequences were not identical, that is, at least one i (1 ≤ i ≤ n) exists, such that a_{i} ≠ b_{i} holds.

Well, she almost had it all — each of the sequences a and b matched exactly n - 1 elements in Sengoku's permutation. In other words, there is exactly one i (1 ≤ i ≤ n) such that a_{i} ≠ p_{i}, and exactly one j (1 ≤ j ≤ n) such that b_{j} ≠ p_{j}.

For now, Sengoku is able to recover the actual colour sequences a and b through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.

-----Input-----

The first line of input contains a positive integer n (2 ≤ n ≤ 1 000) — the length of Sengoku's permutation, being the length of both meteor outbursts at the same time.

The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — the sequence of colours in the first meteor outburst.

The third line contains n space-separated integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ n) — the sequence of colours in the second meteor outburst. At least one i (1 ≤ i ≤ n) exists, such that a_{i} ≠ b_{i} holds.

-----Output-----

Output n space-separated integers p_1, p_2, ..., p_{n}, denoting a possible permutation Sengoku could have had. If there are more than one possible answer, output any one of them.

Input guarantees that such permutation...

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

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

    ans_list = [-3 for i in range(n)]

    mismatch_count = 0
    ans_set = set([])
    for i in range(0, n):
        if a[i] == b[i]:
            ans_list[i] = a[i]
            ans_set.add(a[i])
        else:
            mismatch_count += 1
            ans_list[i] += mismatch_count

    one_to_n_set = set([i for i in range(1, n + 1)])
    add_set = one_to_n_set.difference(ans_set)
    if mismatch_count == 1:
        ans_list[ans_list.index(-2)] = add_set.pop()
    else:
        tmp1 = ans_list.index(-2)
        tmp2 = ans_list.index(-1)
        ele1 = add_set.pop()
        ele2 = add_set.pop()
        if ele1 == a[tmp1] and ele2 == b[tmp2]:
            ans_list[tmp1] = ele1
            ans_list[tmp2] = ele2
        elif ele1 == a[tmp2] and ele2 == b[tmp1]:
            ans_list[tmp2] = ele1
            ans_list[tmp1] = ele2
        elif ele2 == a[tmp1] and ele1 == b[tmp2]:
            ans_list[tmp1] = ele2
            ans_list[tmp2] = ele1
        elif ele2 == a[tmp2] and ele1 == b[tmp1]:
            ans_list[tmp2] = ele2
            ans_list[tmp1] = ele1

    for i in range(0, n):
        print(ans_list[i], end=' ')

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/814/C:
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!

Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour s_{i}, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.

For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.

But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer m_{i} and a lowercase letter c_{i}, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.

-----Input-----

The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland.

The second line contains n lowercase English letters s_1s_2... s_{n} as a string — the initial colours of paper pieces on the garland.

The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has.

The next q lines describe one plan each: the i-th among them contains an integer m_{i} (1 ≤ m_{i} ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter c_{i} — Koyomi's possible favourite colour.

-----Output-----

Output q lines: for...

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

import sys
input = sys.stdin.readline

n = int(input())
s = input()[:-1]
ans = [[-1]*(n+1) for _ in range(26)]

for c in range(26):
    for i in range(n):
        cnt = 0

        for j in range(i, n):
            if ord(s[j])-ord('a')!=c:
                cnt += 1

            ans[c][cnt] = max(ans[c][cnt], j-i+1)

for c in range(26):
    for i in range(1, n+1):
        ans[c][i] = max(ans[c][i], ans[c][i-1])

for _ in range(int(input())):
    m, c = input().split()
    print(ans[ord(c)-ord('a')][int(m)])


I found an interesting problem on https://codeforces.com/problemset/problem/814/D:
The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it?

The discotheque can be seen as an infinite xy-plane, in which there are a total of n dancers. Once someone starts moving around, they will move only inside their own movement range, which is a circular area C_{i} described by a center (x_{i}, y_{i}) and a radius r_{i}. No two ranges' borders have more than one common point, that is for every pair (i, j) (1 ≤ i < j ≤ n) either ranges C_{i} and C_{j} are disjoint, or one of them is a subset of the other. Note that it's possible that two ranges' borders share a single common point, but no two dancers have exactly the same ranges.

Tsukihi, being one of them, defines the spaciousness to be the area covered by an odd number of movement ranges of dancers who are moving. An example is shown below, with shaded regions representing the spaciousness if everyone moves at the same time. [Image]

But no one keeps moving for the whole night after all, so the whole night's time is divided into two halves — before midnight and after midnight. Every dancer moves around in one half, while sitting down with friends in the other. The spaciousness of two halves are calculated separately and their sum should, of course, be as large as possible. The following figure shows an optimal solution to the example above. [Image]

By different plans of who dances in the first half and who does in the other, different sums of spaciousness over two halves are achieved. You are to find the largest achievable value of this sum.

-----Input-----

The first line of input contains a positive integer n (1 ≤ n ≤ 1 000) — the number of dancers.

The following n lines each describes a dancer: the i-th line among them contains three space-separated integers x_{i}, y_{i} and r_{i} ( - 10^6 ≤ x_{i}, y_{i} ≤ 10^6, 1 ≤ r_{i} ≤ 10^6), describing a circular movement range centered at (x_{i}, y_{i}) with radius r_{i}.

-----Output-----

Output one decimal number — the largest...

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

from collections import namedtuple
from math import hypot, pi

def contains(fst, scd):
    return hypot(fst.x - scd.x, fst.y - scd.y) < fst.r

def area(circle):
    return pi * circle.r ** 2

def find_prev(side, circle):
    for prev in reversed(side):
        if contains(prev, circle):
            return prev

Circle = namedtuple('Circle', 'x y r')

n = int(input())
cs = []
for i in range(n):
    cs.append(Circle(*list(map(int, input().split()))))

cs = sorted(cs, key=lambda circle: -circle.r)
ans = 0.0
counts = dict()
left = []
right = []
for ind, cur in enumerate(cs):
    prev_left = find_prev(left, cur)
    prev_right = find_prev(right, cur)
    if prev_left is None:
        left.append(cur)
        counts[cur] = True
        ans += area(cur)
    elif prev_right is None:
        right.append(cur)
        counts[cur] = True
        ans += area(cur)
    elif counts[prev_left]:
        left.append(cur)
        counts[cur] = False
        ans -= area(cur)
    else:
        left.append(cur)
        counts[cur] = True
        ans += area(cur)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/815/A:
On the way to school, Karen became fixated on the puzzle game on her phone! [Image]

The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.

One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.

To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to g_{i}, j.

Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!

-----Input-----

The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively.

The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains g_{i}, j (0 ≤ g_{i}, j ≤ 500).

-----Output-----

If there is an error and it is actually not possible to beat the level, output a single integer -1.

Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level.

The next k lines should each contain one of the following, describing the moves in the order they must be done:  row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row".  col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column".

If there are multiple optimal solutions, output any one of them.

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

Output
4
row 1
row 1
col 4
row 3

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

Output
-1

Input
3 3
1 1 1
1 1 1
1 1 1

Output
3
row 1
row 2
row 3

-----Note-----

In the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: [Image]

In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.

In the...

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

#!/usr/bin/env pypy3

def all_zero(A):
    for row in A:
        for e in row:
            if e != 0: return False
    return True

n, m = input().split(' ')
n = int(n)
m = int(m)

A = []

for _ in range(n):
    row = input().split(' ')
    row = list(map(int, row))
    A += [row]

moves = []

# produce a zero

min_elem = min(min(row) for row in A)

if min_elem > 0:
    if m >= n:
        for x in range(n):
            moves += [f"row {x+1}"]*min_elem
    else:
        for y in range(m):
            moves += [f"col {y+1}"]*min_elem

    for x in range(n):
        for y in range(m):
            A[x][y] -= min_elem

pivot = None

for x in range(n):
    for y in range(m):
        if A[x][y] == 0:
            pivot = (x, y)
            break

assert(pivot is not None)

pivot_x, pivot_y = pivot

for x in range(n):
    if x == pivot_x: continue
    f = A[x][pivot_y]
    moves += [f"row {x+1}"]*f
    for y in range(m):
        A[x][y] -= f

for y in range(m):
    if y == pivot_y: continue
    f = A[pivot_x][y]
    moves += [f"col {y+1}"]*f
    for x in range(n):
        A[x][y] -= f

if not all_zero(A):
    print(-1)
else:
    print(len(moves))
    print('\n'.join(moves))


I found an interesting problem on https://codeforces.com/problemset/problem/816/A:
Karen is getting ready for a new school day!

 [Image]

It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.

What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?

Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.

-----Input-----

The first and only line of input contains a single string in the format hh:mm (00 ≤  hh  ≤ 23, 00 ≤  mm  ≤ 59).

-----Output-----

Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.

-----Examples-----
Input
05:39

Output
11

Input
13:31

Output
0

Input
23:59

Output
1

-----Note-----

In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.

In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.

In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.

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

# coding: utf-8

def is_parindrome(h, m):
    s = "{:02d}:{:02d}".format(h, m)
    return s == s[::-1]

def main():
    h, m = list(map(int, input().split(":")))
    c = 0
    while not is_parindrome(h, m):
        m += 1
        c += 1
        if m == 60:
            h += 1
            m = 0
            if h == 24:
                h = 0
    return c

print(main())