I found an interesting problem on https://codeforces.com/problemset/problem/1108/B:
Recently you have received two positive integer numbers $x$ and $y$. You forgot them, but you remembered a shuffled list containing all divisors of $x$ (including $1$ and $x$) and all divisors of $y$ (including $1$ and $y$). If $d$ is a divisor of both numbers $x$ and $y$ at the same time, there are two occurrences of $d$ in the list.

For example, if $x=4$ and $y=6$ then the given list can be any permutation of the list $[1, 2, 4, 1, 2, 3, 6]$. Some of the possible lists are: $[1, 1, 2, 4, 6, 3, 2]$, $[4, 6, 1, 1, 2, 3, 2]$ or $[1, 6, 3, 2, 4, 1, 2]$.

Your problem is to restore suitable positive integer numbers $x$ and $y$ that would yield the same list of divisors (possibly in different order).

It is guaranteed that the answer exists, i.e. the given list of divisors corresponds to some positive integers $x$ and $y$.

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 128$) — the number of divisors of $x$ and $y$.

The second line of the input contains $n$ integers $d_1, d_2, \dots, d_n$ ($1 \le d_i \le 10^4$), where $d_i$ is either divisor of $x$ or divisor of $y$. If a number is divisor of both numbers $x$ and $y$ then there are two copies of this number in the list.

-----Output-----

Print two positive integer numbers $x$ and $y$ — such numbers that merged list of their divisors is the permutation of the given list of integers. It is guaranteed that the answer exists.

-----Example-----
Input
10
10 2 8 1 2 4 1 20 4 5

Output
20 8

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

n = int(input())
a = list(map(int, input().split()))
x = max(a)
b = []
for i in range(1, x + 1) :
    if x % i == 0 :
        b.append(i)

for i in range(len(b)) :
    a.remove(b[i])

print(x, max(a))


I found an interesting problem on https://codeforces.com/problemset/problem/1108/C:
You have a garland consisting of $n$ lamps. Each lamp is colored red, green or blue. The color of the $i$-th lamp is $s_i$ ('R', 'G' and 'B' — colors of lamps in the garland).

You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.

A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is $t$, then for each $i, j$ such that $t_i = t_j$ should be satisfied $|i-j|~ mod~ 3 = 0$. The value $|x|$ means absolute value of $x$, the operation $x~ mod~ y$ means remainder of $x$ when divided by $y$.

For example, the following garlands are nice: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not nice: "RR", "RGBG".

Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of lamps.

The second line of the input contains the string $s$ consisting of $n$ characters 'R', 'G' and 'B' — colors of lamps in the garland.

-----Output-----

In the first line of the output print one integer $r$ — the minimum number of recolors needed to obtain a nice garland from the given one.

In the second line of the output print one string $t$ of length $n$ — a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.

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

Output
1
GRB

Input
7
RGBGRBB

Output
3
RGBRGBR

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

# -*- coding: utf-8 -*-
# @Time    : 2019/1/23 22:56
# @Author  : LunaFire
# @Email   : gilgemesh2012@gmail.com
# @File    : C. Nice Garland.py

def main():
    n = int(input())
    s = input()

    patterns = ['RGB', 'RBG', 'BGR', 'BRG', 'GRB', 'GBR']

    recolor_count = n + 1
    nice_pattern = None
    for p in patterns:
        curr_count = 0
        for i in range(n):
            if s[i] != p[i % 3]:
                curr_count += 1
        if curr_count < recolor_count:
            recolor_count = curr_count
            nice_pattern = p

    print(recolor_count)
    for i in range(n):
        print(nice_pattern[i % 3], end='')
    print()

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1108/D:
You have a garland consisting of $n$ lamps. Each lamp is colored red, green or blue. The color of the $i$-th lamp is $s_i$ ('R', 'G' and 'B' — colors of lamps in the garland).

You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.

A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is $1$) have distinct colors.

In other words, if the obtained garland is $t$ then for each $i$ from $1$ to $n-1$ the condition $t_i \ne t_{i + 1}$ should be satisfied.

Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of lamps.

The second line of the input contains the string $s$ consisting of $n$ characters 'R', 'G' and 'B' — colors of lamps in the garland.

-----Output-----

In the first line of the output print one integer $r$ — the minimum number of recolors needed to obtain a diverse garland from the given one.

In the second line of the output print one string $t$ of length $n$ — a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.

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

Output
2
RBGRGBRGR

Input
8
BBBGBRRR

Output
2
BRBGBRGR

Input
13
BBRRRRGGGGGRR

Output
6
BGRBRBGBGBGRG

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

import itertools
n = int(input())
s = list(input())
count = 0
values = {(l, r): next(iter(set("RGB") - {l, r})) for l, r in itertools.product("RGB", repeat=2)}
ranges = []
start = None
for i in range(1, n):
    if s[i - 1] == s[i]:
        if start is None:
            start = i - 1
    elif start is not None:
        ranges.append((start, i))
        start = None
if start is not None:
    ranges.append((start, n))

for r in ranges:
    for i in range(r[0] + 1, r[1], 2):
        l = s[i - 1]
        r = s[(i + 1) % n]
        s[i] = values[l, r]
        count += 1

print(count)
print("".join(s))


I found an interesting problem on https://codeforces.com/problemset/problem/1108/E1:
The only difference between easy and hard versions is a number of elements in the array.

You are given an array $a$ consisting of $n$ integers. The value of the $i$-th element of the array is $a_i$.

You are also given a set of $m$ segments. The $j$-th segment is $[l_j; r_j]$, where $1 \le l_j \le r_j \le n$.

You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $a = [0, 0, 0, 0, 0]$ and the given segments are $[1; 3]$ and $[2; 4]$ then you can choose both of them and the array will become $b = [-1, -2, -2, -1, 0]$.

You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $a$ and obtain the array $b$ then the value $\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$ will be maximum possible.

Note that you can choose the empty set.

If there are multiple answers, you can print any.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n \le 300, 0 \le m \le 300$) — the length of the array $a$ and the number of segments, respectively.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^6 \le a_i \le 10^6$), where $a_i$ is the value of the $i$-th element of the array $a$.

The next $m$ lines are contain two integers each. The $j$-th of them contains two integers $l_j$ and $r_j$ ($1 \le l_j \le r_j \le n$), where $l_j$ and $r_j$ are the ends of the $j$-th segment.

-----Output-----

In the first line of the output print one integer $d$ — the maximum possible value $\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$ if $b$ is the array obtained by applying some subset of the given segments to the array $a$.

In the second line of the output print one integer $q$ ($0 \le q \le m$) — the number of segments you apply.

In the third line...

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

n, m = list(map(int, input().split()))
A = list(map(int, input().split()))
lst = []
for i in range(m):
    a, b = list(map(int, input().split()))
    lst.append([a, b])
answer = 0
answer_1 = []
for i in range(n):
    B = A.copy()
    kek = []
    for j in range(m):
        a, b = lst[j][0], lst[j][1]
        if a <= i + 1 <= b:
            kek.append(j + 1)
            for q in range(a - 1, b):
                B[q] -= 1
    elem = max(B)
    if answer < elem - B[i]:
        answer = elem - B[i]
        answer_1 = kek.copy()
print(answer)
print(len(answer_1))
print(' '.join(map(str, answer_1)))


I found an interesting problem on https://codeforces.com/problemset/problem/1108/E2:
The only difference between easy and hard versions is a number of elements in the array.

You are given an array $a$ consisting of $n$ integers. The value of the $i$-th element of the array is $a_i$.

You are also given a set of $m$ segments. The $j$-th segment is $[l_j; r_j]$, where $1 \le l_j \le r_j \le n$.

You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $a = [0, 0, 0, 0, 0]$ and the given segments are $[1; 3]$ and $[2; 4]$ then you can choose both of them and the array will become $b = [-1, -2, -2, -1, 0]$.

You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $a$ and obtain the array $b$ then the value $\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$ will be maximum possible.

Note that you can choose the empty set.

If there are multiple answers, you can print any.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n \le 10^5, 0 \le m \le 300$) — the length of the array $a$ and the number of segments, respectively.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^6 \le a_i \le 10^6$), where $a_i$ is the value of the $i$-th element of the array $a$.

The next $m$ lines are contain two integers each. The $j$-th of them contains two integers $l_j$ and $r_j$ ($1 \le l_j \le r_j \le n$), where $l_j$ and $r_j$ are the ends of the $j$-th segment.

-----Output-----

In the first line of the output print one integer $d$ — the maximum possible value $\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$ if $b$ is the array obtained by applying some subset of the given segments to the array $a$.

In the second line of the output print one integer $q$ ($0 \le q \le m$) — the number of segments you apply.

In the third line...

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

import sys
import copy
input = sys.stdin.readline

n,m=map(int,input().split())
A=list(map(int,input().split()))

LR=[list(map(int,input().split())) for i in range(m)]

MLIST=[]
for l,r in LR:
    MLIST.append(l)
    MLIST.append(r)

MLIST=list(set(MLIST))
MLIST.sort()
MLIST.append(10**9)

MDICT=dict()
MLEN=len(MLIST)
for i in range(MLEN):
    MDICT[MLIST[i]]=i

MINUSLIST=[[0]*(MLEN*2-1) for i in range(MLEN)]

for l,r in LR:
    for j in range(MDICT[l],MDICT[r]+1):
        for k in range(MDICT[l]*2+1,MDICT[r]*2+2):
            MINUSLIST[j][k]+=1

#print(MLIST)
#print(MINUSLIST)

A_m=[[float("inf"),-float("inf")] for i in range(MLEN*2-1)]

if MLIST[0]!=1:
    A_m[0]=[min(A[:MLIST[0]-1]),max(A[:MLIST[0]-1])]
#if MLIST[MLEN-2]!=n:
#    A_m[MLEN*2-2]=[min(A[MLIST[MLEN-2]:]),max(A[MLIST[MLEN-2]:])]

for i in range(MLEN-1):
    x=MLIST[i]-1
    y=MLIST[i+1]-1

    A_m[2*i+1]=[A[x],A[x]]
    if x+1!=y and x!=n-1:
        A_m[2*i+2]=[min(A[x+1:y]),max(A[x+1:y])]

def MINUS(A,B):
    MIN=float("inf")
    MAX=-float("inf")

    for i in range(MLEN*2-1):
        if MIN>A[i][0]-B[i]:
            MIN=A[i][0]-B[i]
        if MAX<A[i][1]-B[i]:
            MAX=A[i][1]-B[i]

    return MAX-MIN

ANSLIST=[0]*MLEN

for i in range(MLEN):
    ANSLIST[i]=MINUS(A_m,MINUSLIST[i])

print(max(ANSLIST))
target=MLIST[ANSLIST.index(max(ANSLIST))]

AN=[]
for i in range(m):
    z,w=LR[i]
    if z<=target<=w:
        AN.append(i+1)

print(len(AN))
for a in AN:
    print(a,end=" ")


I found an interesting problem on https://codeforces.com/problemset/problem/1108/F:
You are given an undirected weighted connected graph with $n$ vertices and $m$ edges without loops and multiple edges.

The $i$-th edge is $e_i = (u_i, v_i, w_i)$; the distance between vertices $u_i$ and $v_i$ along the edge $e_i$ is $w_i$ ($1 \le w_i$). The graph is connected, i. e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph.

A minimum spanning tree (MST) in case of positive weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges).

You can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by $1$. You can increase the weight of each edge multiple (possibly, zero) times.

Suppose that the initial MST cost is $k$. Your problem is to increase weights of some edges with minimum possible number of operations in such a way that the cost of MST in the obtained graph remains $k$, but MST is unique (it means that there is only one way to choose MST in the obtained graph).

Your problem is to calculate the minimum number of operations required to do it.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5$) — the number of vertices and the number of edges in the initial graph.

The next $m$ lines contain three integers each. The $i$-th line contains the description of the $i$-th edge $e_i$. It is denoted by three integers $u_i, v_i$ and $w_i$ ($1 \le u_i, v_i \le n, u_i \ne v_i, 1 \le w \le 10^9$), where $u_i$ and $v_i$ are vertices connected by the $i$-th edge and $w_i$ is the weight of this edge.

It is guaranteed that the given graph doesn't contain loops and multiple edges (i.e. for each $i$ from $1$ to $m$ $u_i \ne v_i$ and for each unordered pair of vertices $(u, v)$ there is at most one edge connecting this pair of vertices). It is also guaranteed...

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

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

l = []
for i in range(m):
	a,b,c = map(int,input().split())
	l.append((c,a,b))
l.sort()
f = [i for i in range(n+1)]
c=[1]*(n+1)
def r(a):
    if a!=f[a]:
        f[a]=r(f[a])
    return f[a]
def union(x,y):
    if x==y:
        return
    if c[x]<c[y]:
        f[x]=y
    else:
        if c[x]==c[y]:
            c[x]=c[x]+1
        f[y]=x

cnt = 0
i=0
while i < m:
    j = i
    while j < m and l[j][0] == l[i][0]:
        j=j+1
    num=0
    for k in range(i,j):
        x=r(l[k][1])
        y=r(l[k][2])
        if x!=y:
            num=num+1
    for k in range(i,j):
        x = r(l[k][1])
        y = r(l[k][2])
        if x != y:
            union(x,y)
            num = num -1
    cnt=cnt+num
    i=j
print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/1110/A:
You are given an integer $n$ ($n \ge 0$) represented with $k$ digits in base (radix) $b$. So,

$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$

For example, if $b=17, k=3$ and $a=[11, 15, 7]$ then $n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$.

Determine whether $n$ is even or odd.

-----Input-----

The first line contains two integers $b$ and $k$ ($2\le b\le 100$, $1\le k\le 10^5$) — the base of the number and the number of digits.

The second line contains $k$ integers $a_1, a_2, \ldots, a_k$ ($0\le a_i < b$) — the digits of $n$.

The representation of $n$ contains no unnecessary leading zero. That is, $a_1$ can be equal to $0$ only if $k = 1$.

-----Output-----

Print "even" if $n$ is even, otherwise print "odd".

You can print each letter in any case (upper or lower).

-----Examples-----
Input
13 3
3 2 7

Output
even

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

Output
odd

Input
99 5
32 92 85 74 4

Output
odd

Input
2 2
1 0

Output
even

-----Note-----

In the first example, $n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$, which is even.

In the second example, $n = 123456789$ is odd.

In the third example, $n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$ is odd.

In the fourth example $n = 2$.

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

b, k = list(map(int, input().split()))
a = list(map(int, input().split()))
ans = 0;
for i in range(k):
  if i == k - 1:
    ans ^= a[i] % 2;
  else:
    ans ^= (a[i] % 2) * (b % 2)
print('even' if ans == 0 else 'odd')


I found an interesting problem on https://codeforces.com/problemset/problem/1110/B:
You have a long stick, consisting of $m$ segments enumerated from $1$ to $m$. Each segment is $1$ centimeter long. Sadly, some segments are broken and need to be repaired.

You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length $t$ placed at some position $s$ will cover segments $s, s+1, \ldots, s+t-1$.

You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.

Time is money, so you want to cut at most $k$ continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?

-----Input-----

The first line contains three integers $n$, $m$ and $k$ ($1 \le n \le 10^5$, $n \le m \le 10^9$, $1 \le k \le n$) — the number of broken segments, the length of the stick and the maximum number of pieces you can use.

The second line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le m$) — the positions of the broken segments. These integers are given in increasing order, that is, $b_1 < b_2 < \ldots < b_n$.

-----Output-----

Print the minimum total length of the pieces.

-----Examples-----
Input
4 100 2
20 30 75 80

Output
17

Input
5 100 3
1 2 4 60 87

Output
6

-----Note-----

In the first example, you can use a piece of length $11$ to cover the broken segments $20$ and $30$, and another piece of length $6$ to cover $75$ and $80$, for a total length of $17$.

In the second example, you can use a piece of length $4$ to cover broken segments $1$, $2$ and $4$, and two pieces of length $1$ to cover broken segments $60$ and $87$.

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

n,m,k=map(int,input().split())
x=[*map(int,input().split())]
diff=[]
for i in range(n-1):
    diff.append([x[i+1]-x[i]-1,i])
diff.sort(reverse=True)

ori=x[-1]-x[0]+1
for i in range(k-1):
    ori-=diff[i][0]
print(ori)


I found an interesting problem on https://codeforces.com/problemset/problem/1110/C:
Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.

Suppose you are given a positive integer $a$. You want to choose some integer $b$ from $1$ to $a - 1$ inclusive in such a way that the greatest common divisor (GCD) of integers $a \oplus b$ and $a \> \& \> b$ is as large as possible. In other words, you'd like to compute the following function:

$$f(a) = \max_{0 < b < a}{gcd(a \oplus b, a \> \& \> b)}.$$

Here $\oplus$ denotes the bitwise XOR operation, and $\&$ denotes the bitwise AND operation.

The greatest common divisor of two integers $x$ and $y$ is the largest integer $g$ such that both $x$ and $y$ are divided by $g$ without remainder.

You are given $q$ integers $a_1, a_2, \ldots, a_q$. For each of these integers compute the largest possible value of the greatest common divisor (when $b$ is chosen optimally).

-----Input-----

The first line contains an integer $q$ ($1 \le q \le 10^3$) — the number of integers you need to compute the answer for.

After that $q$ integers are given, one per line: $a_1, a_2, \ldots, a_q$ ($2 \le a_i \le 2^{25} - 1$) — the integers you need to compute the answer for.

-----Output-----

For each integer, print the answer in the same order as the integers are given in input.

-----Example-----
Input
3
2
3
5

Output
3
1
7

-----Note-----

For the first integer the optimal choice is $b = 1$, then $a \oplus b = 3$, $a \> \& \> b = 0$, and the greatest common divisor of $3$ and $0$ is $3$.

For the second integer one optimal choice is $b = 2$, then $a \oplus b = 1$, $a \> \& \> b = 2$, and the greatest common divisor of $1$ and $2$ is $1$.

For the third integer the optimal choice is $b = 2$, then $a \oplus b = 7$, $a \> \& \> b = 0$, and the greatest common divisor of $7$ and $0$ is $7$.

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

from math import sqrt
q = int(input())
for _ in range(q):
	a = int(input())
	bi = format(a, 'b')
	if bi.count("0") == 0:
		for i in range(2, int(sqrt(a))+1):
			if a%i == 0:
				print(a//i)
				break
		else:
			print(1)
	else:
		print(pow(2, len(bi)) - 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1110/E:
Grigory has $n$ magic stones, conveniently numbered from $1$ to $n$. The charge of the $i$-th stone is equal to $c_i$.

Sometimes Grigory gets bored and selects some inner stone (that is, some stone with index $i$, where $2 \le i \le n - 1$), and after that synchronizes it with neighboring stones. After that, the chosen stone loses its own charge, but acquires the charges from neighboring stones. In other words, its charge $c_i$ changes to $c_i' = c_{i + 1} + c_{i - 1} - c_i$.

Andrew, Grigory's friend, also has $n$ stones with charges $t_i$. Grigory is curious, whether there exists a sequence of zero or more synchronization operations, which transforms charges of Grigory's stones into charges of corresponding Andrew's stones, that is, changes $c_i$ into $t_i$ for all $i$?

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 10^5$) — the number of magic stones.

The second line contains integers $c_1, c_2, \ldots, c_n$ ($0 \le c_i \le 2 \cdot 10^9$) — the charges of Grigory's stones.

The second line contains integers $t_1, t_2, \ldots, t_n$ ($0 \le t_i \le 2 \cdot 10^9$) — the charges of Andrew's stones.

-----Output-----

If there exists a (possibly empty) sequence of synchronization operations, which changes all charges to the required ones, print "Yes".

Otherwise, print "No".

-----Examples-----
Input
4
7 2 4 12
7 15 10 12

Output
Yes

Input
3
4 4 4
1 2 3

Output
No

-----Note-----

In the first example, we can perform the following synchronizations ($1$-indexed):  First, synchronize the third stone $[7, 2, \mathbf{4}, 12] \rightarrow [7, 2, \mathbf{10}, 12]$.  Then synchronize the second stone: $[7, \mathbf{2}, 10, 12] \rightarrow [7, \mathbf{15}, 10, 12]$.

In the second example, any operation with the second stone will not change its charge.

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

def __starting_point():
    n = int(input())
    c = input().split()
    t = input().split()
    for i in range(n):
        c[i] = int(c[i])
        t[i] = int(t[i])

    d = [0 for i in range(n-1)]
    s = [0 for i in range(n-1)]
    for i in range(n-1):
        d[i] = c[i+1]-c[i]
        s[i] = t[i+1]-t[i]
    d.sort()
    s.sort()

    index = 0
    same = True
    while(same and index < n-1):
        if d[index] == s[index]:
            index += 1
        else:
            same = False

    if not c[0] == t[0]:
        same = False
    if not c[n-1] == t[n-1]:
        same = False

    if same:
        print("Yes")
    else:
        print("No")

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1111/A:
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name $s$ can transform to another superhero with name $t$ if $s$ can be made equal to $t$ by changing any vowel in $s$ to any other vowel and any consonant in $s$ to any other consonant. Multiple changes can be made.

In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.

Given the names of two superheroes, determine if the superhero with name $s$ can be transformed to the Superhero with name $t$.

-----Input-----

The first line contains the string $s$ having length between $1$ and $1000$, inclusive.

The second line contains the string $t$ having length between $1$ and $1000$, inclusive.

Both strings $s$ and $t$ are guaranteed to be different and consist of lowercase English letters only.

-----Output-----

Output "Yes" (without quotes) if the superhero with name $s$ can be transformed to the superhero with name $t$ and "No" (without quotes) otherwise.

You can print each letter in any case (upper or lower).

-----Examples-----
Input
a
u

Output
Yes

Input
abc
ukm

Output
Yes

Input
akm
ua

Output
No

-----Note-----

In the first sample, since both 'a' and 'u' are vowels, it is possible to convert string $s$ to $t$.

In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string $s$ to $t$.

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

s = input().strip()
t = input().strip()
ok = 0
vow = 'aeiou'
if len(s) == len(t):
    ok = 1
    for a, b in zip(s, t):
        if (a in vow) ^ (b in vow):
            ok = 0
            break
print('Yes' if ok else 'No')


I found an interesting problem on https://codeforces.com/problemset/problem/1111/B:
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.

Initially, there are $n$ superheroes in avengers team having powers $a_1, a_2, \ldots, a_n$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $1$. They can do at most $m$ operations. Also, on a particular superhero at most $k$ operations can be done.

Can you help the avengers team to maximize the average power of their crew?

-----Input-----

The first line contains three integers $n$, $k$ and $m$ ($1 \le n \le 10^{5}$, $1 \le k \le 10^{5}$, $1 \le m \le 10^{7}$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^{6}$) — the initial powers of the superheroes in the cast of avengers.

-----Output-----

Output a single number — the maximum final average power.

Your answer is considered correct if its absolute or relative error does not exceed $10^{-6}$.

Formally, let your answer be $a$, and the jury's answer be $b$. Your answer is accepted if and only if $\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$.

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

Output
11.00000000000000000000

Input
4 2 6
1 3 2 3

Output
5.00000000000000000000

-----Note-----

In the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.

In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $2$ each.

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

n,k,m = list(map(int,input().split()))
ai = list(map(int,input().split()))
ai.sort()
n2 = n
num = sum(ai)
ans = 0.0
i = 0
while n2 > 0 and m > -1:
    num2 = (num + min(m,n2 * k)) / n2
    ans = max(ans,num2)
    num -= ai[i]
    i += 1
    n2 -= 1
    m -= 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1111/C:
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.

Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $2$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:   if the current length is at least $2$, divide the base into $2$ equal halves and destroy them separately, or  burn the current base. If it contains no avenger in it, it takes $A$ amount of power, otherwise it takes his $B \cdot n_a \cdot l$ amount of power, where $n_a$ is the number of avengers and $l$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.

-----Input-----

The first line contains four integers $n$, $k$, $A$ and $B$ ($1 \leq n \leq 30$, $1 \leq k \leq 10^5$, $1 \leq A,B \leq 10^4$), where $2^n$ is the length of the base, $k$ is the number of avengers and $A$ and $B$ are the constants explained in the question.

The second line contains $k$ integers $a_{1}, a_{2}, a_{3}, \ldots, a_{k}$ ($1 \leq a_{i} \leq 2^n$), where $a_{i}$ represents the position of avenger in the base.

-----Output-----

Output one integer — the minimum power needed to destroy the avengers base.

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

Output
6

Input
3 2 1 2
1 7

Output
8

-----Note-----

Consider the first example.

One option for Thanos is to burn the whole base $1-4$ with power $2 \cdot 2 \cdot 4 = 16$.

Otherwise he can divide the base into two parts $1-2$ and $3-4$.

For base $1-2$, he can either burn it with power $2 \cdot 1 \cdot 2 = 4$ or divide it into $2$ parts $1-1$ and $2-2$.

For base $1-1$, he can burn it with power $2 \cdot 1 \cdot 1 = 2$. For $2-2$, he can destroy it with power $1$, as there are no avengers. So, the total power for destroying $1-2$ is $2 + 1 = 3$, which is less than $4$.

Similarly, he needs $3$ power to destroy...

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

def inint():
    return int(input())
def mp():
    return list(map(int,input().split()))
from bisect import bisect,bisect_left

def sol(i,j):
    works=bisect(a,j)-bisect_left(a,i)
    if works==0:return A
    if i==j:return B*works
    m=(i+j)>>1
    return min(B*(j-i+1)*works,sol(i,m)+sol(m+1,j))

n,k,A,B=mp()
a=list(mp())
a.sort()
#print(a)
print(sol(1,2**n))


I found an interesting problem on https://codeforces.com/problemset/problem/1112/A:
Everybody knows that the $m$-coder Tournament will happen soon. $m$ schools participate in the tournament, and only one student from each school participates.

There are a total of $n$ students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate.

Arkady is a hacker who wants to have $k$ Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too.

You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that $k$ Chosen Ones would be selected by the Technogoblet.

-----Input-----

The first line contains three integers $n$, $m$ and $k$ ($1 \le n \le 100$, $1 \le m, k \le n$) — the total number of students, the number of schools and the number of the Chosen Ones.

The second line contains $n$ different integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$), where $p_i$ denotes the power of $i$-th student. The bigger the power, the stronger the student.

The third line contains $n$ integers $s_1, s_2, \ldots, s_n$ ($1 \le s_i \le m$), where $s_i$ denotes the school the $i$-th student goes to. At least one student studies in each of the schools.

The fourth line contains $k$ different integers $c_1, c_2, \ldots, c_k$ ($1 \le c_i \le n$)  — the id's of the Chosen Ones.

-----Output-----

Output a single integer  — the minimal number of schools to be made up by Arkady so that $k$ Chosen Ones would be selected by the Technogoblet.

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

Output
1

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

Output
2

-----Note-----

In the first...

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

n, m, k = list(map(int, input().split()))
p = list(map(int, input().split()))
s = list(map(int, input().split()))
good = list(map(int, input().split()))
is_good = [0] * n
for el in good:
	is_good[el - 1] = 1
sch = [[] for i in range(m + 1)]
for i in range(n):
	sch[s[i]].append((p[i], i))
cnt = 0
for el in sch:
	el.sort(reverse=True)
	for i in el[1:]:
		cnt += is_good[i[1]]
print(cnt)

# sorted(i * i for i in range(n))


I found an interesting problem on https://codeforces.com/problemset/problem/1112/B:
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.

There are $n$ solutions, the $i$-th of them should be tested on $a_i$ tests, testing one solution on one test takes $1$ second. The solutions are judged in the order from $1$ to $n$. There are $k$ testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.

At any time moment $t$ when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id $i$, then it is being tested on the first test from time moment $t$ till time moment $t + 1$, then on the second test till time moment $t + 2$ and so on. This solution is fully tested at time moment $t + a_i$, and after that the testing process immediately starts testing another solution.

Consider some time moment, let there be exactly $m$ fully tested solutions by this moment. There is a caption "System testing: $d$%" on the page with solutions, where $d$ is calculated as

$$d = round\left(100\cdot\frac{m}{n}\right),$$

where $round(x) = \lfloor{x + 0.5}\rfloor$ is a function which maps every real to the nearest integer.

Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test $q$, and the caption says "System testing: $q$%". Find the number of interesting solutions.

Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.

-----Input-----

The first line contains two positive integers $n$ and $k$ ($1 \le n \le 1000$, $1 \le k \le 100$) standing for the number of submissions and the number of testing processes respectively.

The second line contains $n$ positive integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 150$), where $a_i$ is equal to the...

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()))
p = [[0, 0, 0] for i in range(k)]
j = 0
m = 0
ans = [0] * n
flag = True
while flag:
    flag = False
    t = 0
    for i in range(k):
        p[i][0] += 1
        if p[i][0] == int(m / n * 100 + 0.5):
            ans[p[i][2]] = 1
        if p[i][0] >= p[i][1]:
            if p[i][1] != 0:
                t += 1
            if j >= n:
                p[i] = [0, 0, 0]
            else:
                p[i][0] = 0
                p[i][1] = a[j]
                p[i][2] = j
                j += 1
        if p[i][1] != 0:
            flag = True
    m += t
print(sum(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1112/C:
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly $k$ flowers.

The work material for the wreaths for all $n$ citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence $a_1$, $a_2$, ..., $a_m$, where $a_i$ is an integer that denotes the type of flower at the position $i$. This year the liana is very long ($m \ge n \cdot k$), and that means every citizen will get a wreath.

Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts $k$ flowers from the beginning of the liana, then another $k$ flowers and so on. Each such piece of $k$ flowers is called a workpiece. The machine works until there are less than $k$ flowers on the liana.

Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, $k$ flowers must contain flowers of types $b_1$, $b_2$, ..., $b_s$, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.

Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least $n$ workpieces?

-----Input-----

The first line contains four integers $m$, $k$, $n$ and $s$ ($1 \le n, k, m \le 5 \cdot 10^5$, $k \cdot n \le m$, $1 \le s \le k$): the number of flowers on the liana, the number of flowers in one wreath,...

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

n, k, m, s = map(int, input().split())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
need = len(c)
rez = n - m * k
kek = [0 for i in range(500007)]
cur_kek = [0 for i in range(500007)]
for i in c:
    kek[i] += 1
r = 0
if (rez == 0):
    lol = need
    for i in range(0, n, k):
        for j in range(i, i + k):
            if kek[a[j]] > cur_kek[a[j]]:
                need -= 1
            cur_kek[a[j]] += 1
        if (need == 0):
            print(0)
            break
        for j in range(i, i + k):
            cur_kek[a[j]] = 0
    else:
        print(-1)
    return
meshayut = 0 if kek[a[0]] else 1
if kek[a[0]]:
    need -= 1
cur_kek[a[0]] += 1
ans = []
for l in range(n):
    while need > 0 and r < n - 1:
        r += 1
        if (kek[a[r]] > cur_kek[a[r]]):
            need -= 1
            cur_kek[a[r]] += 1
        else:
            cur_kek[a[r]] += 1
            meshayut += 1
        #print(r, need)
    need_to_cut = l % k
    cur = r - l + 1
    razn = cur - k
    #print(l, r, need_to_cut, razn, meshayut, cur, need)
    #print(need, razn + need_to_cut, rez, meshayut + not_useful, razn + need_to_cut)
    if (need == 0 and razn + need_to_cut <= rez and meshayut >= razn):
        rezhem = razn
        for j in range(l - need_to_cut, l):
            ans.append(j + 1)
        for j in range(l, r + 1):
            if kek[a[j]]:
                kek[a[j]] -= 1
            elif rezhem:
                ans.append(j + 1)
                rezhem -= 1
        print(len(ans))
        print(' '.join(map(str, ans)))
        break
    if (kek[a[l]]):
        if cur_kek[a[l]] > kek[a[l]]:
            meshayut -= 1
        else:
            need += 1
    else:
        meshayut -= 1
    cur_kek[a[l]] -= 1
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1113/A:
Sasha is a very happy guy, that's why he is always on the move. There are $n$ cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from $1$ to $n$ in increasing order. The distance between any two adjacent cities is equal to $1$ kilometer. Since all roads in the country are directed, it's possible to reach the city $y$ from the city $x$ only if $x < y$.

Once Sasha decided to go on a trip around the country and to visit all $n$ cities. He will move with the help of his car, Cheetah-2677. The tank capacity of this model is $v$ liters, and it spends exactly $1$ liter of fuel for $1$ kilometer of the way. At the beginning of the journey, the tank is empty. Sasha is located in the city with the number $1$ and wants to get to the city with the number $n$. There is a gas station in each city. In the $i$-th city, the price of $1$ liter of fuel is $i$ dollars. It is obvious that at any moment of time, the tank can contain at most $v$ liters of fuel.

Sasha doesn't like to waste money, that's why he wants to know what is the minimum amount of money is needed to finish the trip if he can buy fuel in any city he wants. Help him to figure it out!

-----Input-----

The first line contains two integers $n$ and $v$ ($2 \le n \le 100$, $1 \le v \le 100$)  — the number of cities in the country and the capacity of the tank.

-----Output-----

Print one integer — the minimum amount of money that is needed to finish the trip.

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

Output
4

Input
7 6

Output
6

-----Note-----

In the first example, Sasha can buy $2$ liters for $2$ dollars ($1$ dollar per liter) in the first city, drive to the second city, spend $1$ liter of fuel on it, then buy $1$ liter for $2$ dollars in the second city and then drive to the $4$-th city. Therefore, the answer is $1+1+2=4$.

In the second example, the capacity of the tank allows to fill the tank completely in the first city, and drive to the last city without stops in other cities.

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

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#

"""
"""

from operator import itemgetter

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

if v >= n-1:
    ans = n-1
else:
    ans = v + ((2+(2+n-v-2))*(n-v-1))//2
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1113/B:
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $n$ machines, and the power of the $i$-th machine is $a_i$.

This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer $x$, then choose one machine and reduce the power of its machine by $x$ times, and at the same time increase the power of one another machine by $x$ times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices $i$ and $j$, and one integer $x$ such that $x$ is a divisor of $a_i$, and change powers as following: $a_i = \frac{a_i}{x}$, $a_j = a_j \cdot x$

Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 5 \cdot 10^4$) — the number of machines.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 100$) — the powers of the machines.

-----Output-----

Print one integer — minimum total power.

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

Output
14

Input
4
4 2 4 4

Output
14

Input
5
2 4 2 3 7

Output
18

-----Note-----

In the first example, the farmer can reduce the power of the $4$-th machine by $2$ times, and increase the power of the $1$-st machine by $2$ times, then the powers will be: $[2, 2, 3, 2, 5]$.

In the second example, the farmer can reduce the power of the $3$-rd machine by $2$ times, and increase the power of the $2$-nd machine by $2$ times. At the same time, the farmer can leave is be as it is and the total power won't change.

In the third example, it is optimal to leave it be as it is.

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

list_int_input = lambda inp: list(map(int, inp.split()))
int_input = lambda inp: int(inp)
string_to_list_input = lambda inp: list(inp)

n=int(input())
lst=list(map(int,input().split()))
minn=min(lst)
summ=sum(lst)
sum1=summ
val=-1
for i in range(50,1,-1):
    for j in lst:
        if j%i==0:
            val=i
            sum1=min(summ-minn-j+int(j/i)+(i*minn),sum1)
print(sum1)


I found an interesting problem on https://codeforces.com/problemset/problem/1114/A:
The Duck song

For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.

Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen: Andrew, Dmitry and Michal should eat at least $x$, $y$ and $z$ grapes, respectively. Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only. On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes. Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.

Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with $a$ green grapes, $b$ purple grapes and $c$ black grapes.

However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?

It is not required to distribute all the grapes, so it's possible that some of them will remain unused.

-----Input-----

The first line contains three integers $x$, $y$ and $z$ ($1 \le x, y, z \le 10^5$) — the number of grapes Andrew, Dmitry and Michal want to eat.

The second line contains three integers $a$, $b$, $c$ ($1 \le a, b, c \le 10^5$) — the number of green, purple and black grapes in the box.

-----Output-----

If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".

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

Output
YES

Input
5 1 1
4 3 2

Output
NO

-----Note-----

In the first example, there is only one possible distribution:

Andrew should take $1$ green grape, Dmitry should take $3$ remaining green grapes and $3$ purple grapes, and Michal will take $2$ out of $3$ available black...

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

x, y, z = list(map(int, input().split()))
a, b, c = list(map(int, input().split()))
if a >= x and a+b >= x+y and a+b+c >= x+y+z:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1114/B:
An array $b$ is called to be a subarray of $a$ if it forms a continuous subsequence of $a$, that is, if it is equal to $a_l$, $a_{l + 1}$, $\ldots$, $a_r$ for some $l, r$.

Suppose $m$ is some known constant. For any array, having $m$ or more elements, let's define it's beauty as the sum of $m$ largest elements of that array. For example:   For array $x = [4, 3, 1, 5, 2]$ and $m = 3$, the $3$ largest elements of $x$ are $5$, $4$ and $3$, so the beauty of $x$ is $5 + 4 + 3 = 12$.

 For array $x = [10, 10, 10]$ and $m = 2$, the beauty of $x$ is $10 + 10 = 20$.

You are given an array $a_1, a_2, \ldots, a_n$, the value of the said constant $m$ and an integer $k$. Your need to split the array $a$ into exactly $k$ subarrays such that:

  Each element from $a$ belongs to exactly one subarray.

 Each subarray has at least $m$ elements.

 The sum of all beauties of $k$ subarrays is maximum possible.

-----Input-----

The first line contains three integers $n$, $m$ and $k$ ($2 \le n \le 2 \cdot 10^5$, $1 \le m$, $2 \le k$, $m \cdot k \le n$) — the number of elements in $a$, the constant $m$ in the definition of beauty and the number of subarrays to split to.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($-10^9 \le a_i \le 10^9$).

-----Output-----

In the first line, print the maximum possible sum of the beauties of the subarrays in the optimal partition.

In the second line, print $k-1$ integers $p_1, p_2, \ldots, p_{k-1}$ ($1 \le p_1 < p_2 < \ldots < p_{k-1} < n$) representing the partition of the array, in which:

 All elements with indices from $1$ to $p_1$ belong to the first subarray.

 All elements with indices from $p_1 + 1$ to $p_2$ belong to the second subarray.

 $\ldots$.

 All elements with indices from $p_{k-1} + 1$ to $n$ belong to the last, $k$-th subarray.

If there are several optimal partitions, print any of them.

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

Output
21
3 5
Input
6 1 4
4 1 3 2 2 3

Output
12
1 3 5
Input
2 1 2
-1000000000 1000000000

Output
0
1...

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

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

B=list(enumerate(A))
B.sort(key=lambda x:x[1])
B.reverse()

LIST=[0]*n
ANS=0

for i in range(m*k):
    LIST[B[i][0]]=1
    ANS+=B[i][1]

ANSLIST=[]
count=0
for i in range(n):
    if LIST[i]==1:
        count+=1

    if count==m:
        ANSLIST.append(i+1)
        count=0

print(ANS)
for a in ANSLIST[:-1]:
    print(a,end=" ")


I found an interesting problem on https://codeforces.com/problemset/problem/1114/C:
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.

Aki is fond of numbers, especially those with trailing zeros. For example, the number $9200$ has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.

However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.

Given two integers $n$ and $b$ (in decimal notation), your task is to calculate the number of trailing zero digits in the $b$-ary (in the base/radix of $b$) representation of $n\,!$ (factorial of $n$).

-----Input-----

The only line of the input contains two integers $n$ and $b$ ($1 \le n \le 10^{18}$, $2 \le b \le 10^{12}$).

-----Output-----

Print an only integer — the number of trailing zero digits in the $b$-ary representation of $n!$

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

Output
1

Input
38 11

Output
3

Input
5 2

Output
3

Input
5 10

Output
1

-----Note-----

In the first example, $6!_{(10)} = 720_{(10)} = 880_{(9)}$.

In the third and fourth example, $5!_{(10)} = 120_{(10)} = 1111000_{(2)}$.

The representation of the number $x$ in the $b$-ary base is $d_1, d_2, \ldots, d_k$ if $x = d_1 b^{k - 1} + d_2 b^{k - 2} + \ldots + d_k b^0$, where $d_i$ are integers and $0 \le d_i \le b - 1$. For example, the number $720$ from the first example is represented as $880_{(9)}$ since $720 = 8 \cdot 9^2 + 8 \cdot 9 + 0 \cdot 1$.

You can read more about bases here.

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

def factorial_1(n: int):
    for i in range(2, n+1):
        if i > n**0.5:
            return n
        elif n % i == 0:
            return i

def factorial_2(n: int):
    res = dict()
    while n > 1:
        f_now = factorial_1(n)
        n //= f_now
        res[f_now] = res.get(f_now, 0) + 1
    return res

n, k = map(int, input().split())
f_k, x = factorial_2(k), float('inf')
for key, val in f_k.items():
    qua_f, pow_ = 0, key
    while pow_ <= n:
        qua_f += n//pow_
        pow_ *= key
    x = min(x, qua_f//val)
print(x)


I found an interesting problem on https://codeforces.com/problemset/problem/1114/D:
You are given a line of $n$ colored squares in a row, numbered from $1$ to $n$ from left to right. The $i$-th square initially has the color $c_i$.

Let's say, that two squares $i$ and $j$ belong to the same connected component if $c_i = c_j$, and $c_i = c_k$ for all $k$ satisfying $i < k < j$. In other words, all squares on the segment from $i$ to $j$ should have the same color.

For example, the line $[3, 3, 3]$ has $1$ connected component, while the line $[5, 2, 4, 4]$ has $3$ connected components.

The game "flood fill" is played on the given line as follows:   At the start of the game you pick any starting square (this is not counted as a turn).  Then, in each game turn, change the color of the connected component containing the starting square to any other color.

Find the minimum number of turns needed for the entire line to be changed into a single color.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 5000$) — the number of squares.

The second line contains integers $c_1, c_2, \ldots, c_n$ ($1 \le c_i \le 5000$) — the initial colors of the squares.

-----Output-----

Print a single integer — the minimum number of the turns needed.

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

Output
2

Input
8
4 5 2 2 1 3 5 5

Output
4

Input
1
4

Output
0

-----Note-----

In the first example, a possible way to achieve an optimal answer is to pick square with index $2$ as the starting square and then play as follows:  $[5, 2, 2, 1]$  $[5, 5, 5, 1]$  $[1, 1, 1, 1]$

In the second example, a possible way to achieve an optimal answer is to pick square with index $5$ as the starting square and then perform recoloring into colors $2, 3, 5, 4$ in that order.

In the third example, the line already consists of one color only.

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

a=int(input())
b = [int(x) for x in input().split()]
c = [b[0]]
for i in b[1:]:
    if i!=c[-1]:
        c.append(i)
a=len(c)

dpa = []
dpb = [0] * (a+1)
for i in range(2,a+1):
    dp=[]
    for j in range(a-i+1):
        if c[j] == c[j+i-1]:
            dp.append(min(dpb[j], dpb[j+1], dpa[j+1])+1)
        else:
            dp.append(min(dpb[j], dpb[j+1])+1)
    dpa, dpb = dpb, dp
print(dpb[0])


I found an interesting problem on https://codeforces.com/problemset/problem/1117/A:
You are given array $a_1, a_2, \dots, a_n$. Find the subsegment $a_l, a_{l+1}, \dots, a_r$ ($1 \le l \le r \le n$) with maximum arithmetic mean $\frac{1}{r - l + 1}\sum\limits_{i=l}^{r}{a_i}$ (in floating-point numbers, i.e. without any rounding).

If there are many such subsegments find the longest one.

-----Input-----

The first line contains single integer $n$ ($1 \le n \le 10^5$) — length of the array $a$.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the array $a$.

-----Output-----

Print the single integer — the length of the longest subsegment with maximum possible arithmetic mean.

-----Example-----
Input
5
6 1 6 6 0

Output
2

-----Note-----

The subsegment $[3, 4]$ is the longest among all subsegments with maximum arithmetic mean.

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

n=int(input())
a=list(map(int,input().split()))
mx=max(a)
cnt=0
ans=0
for i in range(n):
    if a[i]==mx:
        cnt+=1
    else:
        ans=max(ans,cnt)
        cnt=0
ans=max(ans,cnt)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1117/B:
There are $n$ emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The $i$-th emote increases the opponent's happiness by $a_i$ units (we all know that emotes in this game are used to make opponents happy).

You have time to use some emotes only $m$ times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than $k$ times in a row (otherwise the opponent will think that you're trolling him).

Note that two emotes $i$ and $j$ ($i \ne j$) such that $a_i = a_j$ are considered different.

You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.

-----Input-----

The first line of the input contains three integers $n, m$ and $k$ ($2 \le n \le 2 \cdot 10^5$, $1 \le k \le m \le 2 \cdot 10^9$) — the number of emotes, the number of times you can use emotes and the maximum number of times you may use the same emote in a row.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is value of the happiness of the $i$-th emote.

-----Output-----

Print one integer — the maximum opponent's happiness if you use emotes in a way satisfying the problem statement.

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

Output
54

Input
3 1000000000 1
1000000000 987654321 1000000000

Output
1000000000000000000

-----Note-----

In the first example you may use emotes in the following sequence: $4, 4, 5, 4, 4, 5, 4, 4, 5$.

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

N, M, K = map(int, input().split())
A = [int(a) for a in input().split()]
A = sorted(A)

m1 = A[-1]
m2 = A[-2]

a = M // (K+1)
b = M % (K+1)

print(a*(m1*K+m2)+m1*b)


I found an interesting problem on https://codeforces.com/problemset/problem/1117/C:
You a captain of a ship. Initially you are standing in a point $(x_1, y_1)$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $(x_2, y_2)$.

You know the weather forecast — the string $s$ of length $n$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $s_1$, the second day — $s_2$, the $n$-th day — $s_n$ and $(n+1)$-th day — $s_1$ again and so on.

Ship coordinates change the following way:  if wind blows the direction U, then the ship moves from $(x, y)$ to $(x, y + 1)$;  if wind blows the direction D, then the ship moves from $(x, y)$ to $(x, y - 1)$;  if wind blows the direction L, then the ship moves from $(x, y)$ to $(x - 1, y)$;  if wind blows the direction R, then the ship moves from $(x, y)$ to $(x + 1, y)$.

The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $(x, y)$ it will move to the point $(x - 1, y + 1)$, and if it goes the direction U, then it will move to the point $(x, y + 2)$.

You task is to determine the minimal number of days required for the ship to reach the point $(x_2, y_2)$.

-----Input-----

The first line contains two integers $x_1, y_1$ ($0 \le x_1, y_1 \le 10^9$) — the initial coordinates of the ship.

The second line contains two integers $x_2, y_2$ ($0 \le x_2, y_2 \le 10^9$) — the coordinates of the destination point.

It is guaranteed that the initial coordinates and destination point coordinates are different.

The third line contains a single integer $n$ ($1 \le n \le 10^5$) — the length of the string $s$.

The fourth line contains the string $s$ itself, consisting only of letters U, D, L and...

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

x1,y1 = [int(i) for i in input().split()]
x2,y2 = [int(i) for i in input().split()]

n = int(input())
s = input()

def dst(x1,y1,x2,y2):
    return abs(x2-x1) + abs(y2-y1)

d = dst(x1,y1,x2,y2)

dx=dy=0
ss = []
for i in range(n):
    if s[i] == 'U':
        dy += 1
    elif s[i] == 'D':
        dy -= 1
    elif s[i] == 'R':
        dx += 1
    else:
        dx -=1
    ss.append((dx, dy))

l = 1
r = 10**18

def check(m):
    c = m // n
    x = x1 + dx*c
    y = y1 + dy*c
    r = m % n
    if r != 0:
        x += ss[r-1][0]
        y += ss[r-1][1]
    d = dst(x2,y2,x,y)
    if d <= m:
        return True
    return False

ans = 10**19
while r >= l:
    m = int((r+l) // 2)
    if check(m):
        ans = min(ans, m)
        r = m - 1
    else:
        l = m + 1

if ans == 10**19:
    print(-1)
else:
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1117/D:
Reziba has many magic gems. Each magic gem can be split into $M$ normal gems. The amount of space each magic (and normal) gem takes is $1$ unit. A normal gem cannot be split.

Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is $N$ units. If a magic gem is chosen and split, it takes $M$ units of space (since it is split into $M$ gems); if a magic gem is not split, it takes $1$ unit.

How many different configurations of the resulting set of gems can Reziba have, such that the total amount of space taken is $N$ units? Print the answer modulo $1000000007$ ($10^9+7$). Two configurations are considered different if the number of magic gems Reziba takes to form them differs, or the indices of gems Reziba has to split differ.

-----Input-----

The input contains a single line consisting of $2$ integers $N$ and $M$ ($1 \le N \le 10^{18}$, $2 \le M \le 100$).

-----Output-----

Print one integer, the total number of configurations of the resulting set of gems, given that the total amount of space taken is $N$ units. Print the answer modulo $1000000007$ ($10^9+7$).

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

Output
5

Input
3 2

Output
3

-----Note-----

In the first example each magic gem can split into $2$ normal gems, and we know that the total amount of gems are $4$.

Let $1$ denote a magic gem, and $0$ denote a normal gem.

The total configurations you can have is:   $1 1 1 1$ (None of the gems split);  $0 0 1 1$ (First magic gem splits into $2$ normal gems);  $1 0 0 1$ (Second magic gem splits into $2$ normal gems);  $1 1 0 0$ (Third magic gem splits into $2$ normal gems);  $0 0 0 0$ (First and second magic gems split into total $4$ normal gems).

Hence, answer is $5$.

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

import sys

MOD = 10**9+7

# Polymod
def polymod(P,Q):
    assert(Q[-1]==1)
    n = len(Q)
    while len(P)>=n:
        p = P[-1]
        for i in range(n):
            P[-i-1] -= p*Q[-i-1]
        assert(P[-1]==0)
        P.pop()
    return P

def polyprod(P,Q):
    n = len(P)
    m = len(Q)
    W = [0]*(n+m-1)
    for i in range(n):
        for j in range(m):
            W[i+j]+=P[i]*Q[j]
    return [w%MOD for w in W]

# Calc A^m * B
def power(A,B,m,mult):
    if m == 0:
        return B
    while m>1:
        if m%2==1:
            B = mult(A,B)
        A = mult(A,A)
        m//=2
    return mult(A,B)

def calc_nth_term(init,linear_coeff,n):
    def mult(A,B):
        return polymod(polyprod(A,B),linear_coeff)

    ans = power([0,1],[1],n,mult)
    return sum(ans[i]*init[i] for i in range(len(ans)))

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

linear_rec = [0]*(m+1)
linear_rec[0] = -1
linear_rec[m-1] = -1
linear_rec[m] = 1

print(calc_nth_term([1]*m,linear_rec,n)%MOD)


I found an interesting problem on https://codeforces.com/problemset/problem/1118/A:
Polycarp wants to cook a soup. To do it, he needs to buy exactly $n$ liters of water.

There are only two types of water bottles in the nearby shop — $1$-liter bottles and $2$-liter bottles. There are infinitely many bottles of these two types in the shop.

The bottle of the first type costs $a$ burles and the bottle of the second type costs $b$ burles correspondingly.

Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly $n$ liters of water in the nearby shop if the bottle of the first type costs $a$ burles and the bottle of the second type costs $b$ burles.

You also have to answer $q$ independent queries.

-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 500$) — the number of queries.

The next $n$ lines contain queries. The $i$-th query is given as three space-separated integers $n_i$, $a_i$ and $b_i$ ($1 \le n_i \le 10^{12}, 1 \le a_i, b_i \le 1000$) — how many liters Polycarp needs in the $i$-th query, the cost (in burles) of the bottle of the first type in the $i$-th query and the cost (in burles) of the bottle of the second type in the $i$-th query, respectively.

-----Output-----

Print $q$ integers. The $i$-th integer should be equal to the minimum amount of money (in burles) Polycarp needs to buy exactly $n_i$ liters of water in the nearby shop if the bottle of the first type costs $a_i$ burles and the bottle of the second type costs $b_i$ burles.

-----Example-----
Input
4
10 1 3
7 3 2
1 1000 1
1000000000000 42 88

Output
10
9
1000
42000000000000

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

n = int(input())
for i in range(n):
    lit, one, two = map(int, input().split())
    if two > one * 2:
        print(one * lit)
    else:
        print(two * (lit // 2) + one * (lit % 2))


I found an interesting problem on https://codeforces.com/problemset/problem/1118/B:
Tanya has $n$ candies numbered from $1$ to $n$. The $i$-th candy has the weight $a_i$.

She plans to eat exactly $n-1$ candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.

Your task is to find the number of such candies $i$ (let's call these candies good) that if dad gets the $i$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one.

For example, $n=4$ and weights are $[1, 4, 3, 3]$. Consider all possible cases to give a candy to dad:  Tanya gives the $1$-st candy to dad ($a_1=1$), the remaining candies are $[4, 3, 3]$. She will eat $a_2=4$ in the first day, $a_3=3$ in the second day, $a_4=3$ in the third day. So in odd days she will eat $4+3=7$ and in even days she will eat $3$. Since $7 \ne 3$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $2$-nd candy to dad ($a_2=4$), the remaining candies are $[1, 3, 3]$. She will eat $a_1=1$ in the first day, $a_3=3$ in the second day, $a_4=3$ in the third day. So in odd days she will eat $1+3=4$ and in even days she will eat $3$. Since $4 \ne 3$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $3$-rd candy to dad ($a_3=3$), the remaining candies are $[1, 4, 3]$. She will eat $a_1=1$ in the first day, $a_2=4$ in the second day, $a_4=3$ in the third day. So in odd days she will eat $1+3=4$ and in even days she will eat $4$. Since $4 = 4$ this case should be counted to the answer (this candy is good).  Tanya gives the $4$-th candy to dad ($a_4=3$), the remaining candies are $[1, 4, 3]$. She will eat $a_1=1$ in the first day, $a_2=4$ in the second day, $a_3=3$ in the third day. So in odd days she will eat $1+3=4$ and in even days she will eat $4$. Since $4 = 4$ this case should be counted to the answer (this candy is good).

In total...

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/1118/C:
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.

For example, the following matrices are palindromic: $\left[ \begin{array}{l l l}{1} & {3} & {1} \\{3} & {1} & {3} \\{1} & {3} & {1} \end{array} \right] \quad \left[ \begin{array}{l l l l}{1} & {2} & {2} & {1} \\{8} & {2} & {2} & {8} \\{8} & {2} & {2} & {8} \\{1} & {2} & {2} & {1} \end{array} \right]$

The following matrices are not palindromic because they change after the order of rows is reversed: $\left[ \begin{array}{l l l}{1} & {3} & {1} \\{3} & {1} & {3} \\{2} & {3} & {2} \end{array} \right] \rightarrow \left[ \begin{array}{l l l}{2} & {3} & {2} \\{3} & {1} & {3} \\{1} & {3} & {1} \end{array} \right] \quad \left[ \begin{array}{l l l l}{1} & {8} & {8} & {9} \\{2} & {4} & {3} & {2} \\{1} & {3} & {4} & {1} \\{9} & {8} & {8} & {1} \end{array} \right] \rightarrow \left[ \begin{array}{l l l l}{9} & {8} & {8} & {1} \\{1} & {3} & {4} & {1} \\{2} & {4} & {3} & {2} \\{1} & {8} & {8} & {9} \end{array} \right]$

The following matrices are not palindromic because they change after the order of columns is reversed: $\left[ \begin{array}{l l l}{1} & {3} & {2} \\{3} & {1} & {3} \\{1} & {3} & {2} \end{array} \right] \rightarrow \left[ \begin{array}{l l l}{2} & {3} & {1} \\{3} & {1} & {3} \\{2} & {3} & {1} \end{array} \right] \quad \left[ \begin{array}{l l l l}{1} & {2} & {1} & {9} \\{8} & {4} & {3} & {8} \\{8} & {3} & {4} & {8} \\{9} & {2} & {1} & {1} \end{array} \right] \rightarrow \left[ \begin{array}{l l l l}{9} & {1} & {2} & {1} \\{8} & {3} & {4} & {8} \\{8} & {4} & {3} & {8} \\{1} & {1} & {2} & {9} \end{array} \right]$

You are given $n^2$ integers. Put them into a matrix of $n$ rows and $n$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".

-----Input-----

The...

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

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

c=[0]*1001

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

sym=0
sin=0

for i in range (1001):
	sym+=(c[i]//4)
	if(c[i]%2==1):
		sin+=1

if(n%2==0 and sym==((n*n)//4)):
	mat= [([0]*(n//2)) for i in range (n//2)]
	ar=[]
	for i in range (1001):
		while(c[i]>=4):
			ar.append(i)
			c[i]-=4

	k=0
	for i in range (n//2):
		for j in range (n//2):
			mat[i][j]=ar[k]
			k+=1

	newm=[([0]*n) for i in range (n)]
	for i in range (n//2):
		for j in range (n//2):
			newm[i][j]=mat[i][j]
			newm[n-i-1][j]=mat[i][j]
			newm[n-i-1][n-j-1]=mat[i][j]
			newm[i][n-j-1]=mat[i][j]

	print("YES")
	for i in range (n):
		for j in range (n):
			print(newm[i][j],end=" ")
		print()

elif(n%2==1 and (((sym>=(((n//2) *(n//2)) ) ) and (sin==1)))):
	mat= [([0]*(n//2)) for i in range (n//2)]
	ar=[]
	for i in range (1001):
		while(c[i]>=4):
			ar.append(i)
			c[i]-=4

	k=0
	for i in range (n//2):
		for j in range (n//2):
			mat[i][j]=ar[k]
			ar.pop(k)

	newm=[([0]*n) for i in range (n)]
	for i in range (n//2):
		for j in range (n//2):
			newm[i][j]=mat[i][j]
			newm[n-i-1][j]=mat[i][j]
			newm[n-i-1][n-j-1]=mat[i][j]
			newm[i][n-j-1]=mat[i][j]

	na=len(ar)
	ar2=[]
	for i in range (na):
		ar2.append(ar[i])
		ar2.append(ar[i])

	for i in range (1001):
		while(c[i]>=2):
			ar2.append(i)
			c[i]-=2

	#print(ar)
	for i in range (n//2):
		newm[n//2 ][i]=ar2[0]
		newm[n//2 ][n-i-1]=ar2[0]
		ar2.pop(0)
		newm[i][n//2 ]=ar2[0]
		newm[n-i-1][n//2 ]=ar2[0]
		ar2.pop(0)

	for i in range (1001):
		if(c[i]==1):
			newm[n//2][n//2]=i

	print("YES")
	for i in range (n):
		for j in range (n):
			print(newm[i][j],end=" ")
		print()

else:
	print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1118/D1:
The only difference between easy and hard versions is the constraints.

Polycarp has to write a coursework. The coursework consists of $m$ pages.

Polycarp also has $n$ cups of coffee. The coffee in the $i$-th cup has $a_i$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).

Surely, courseworks are not usually being written in a single day (in a perfect world of Berland, at least). Some of them require multiple days of hard work.

Let's consider some day of Polycarp's work. Consider Polycarp drinks $k$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $a_{i_1}, a_{i_2}, \dots, a_{i_k}$. Then the first cup he drinks gives him energy to write $a_{i_1}$ pages of coursework, the second cup gives him energy to write $max(0, a_{i_2} - 1)$ pages, the third cup gives him energy to write $max(0, a_{i_3} - 2)$ pages, ..., the $k$-th cup gives him energy to write $max(0, a_{i_k} - k + 1)$ pages.

If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.

Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n \le 100$, $1 \le m \le 10^4$) — the number of cups of coffee and the number of pages in the coursework.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the caffeine dosage of coffee in the $i$-th cup.

-----Output-----

If it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.

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

Output
4

Input
7 10
1 3 4 2 1 4 2

Output
2

Input
5 15
5 5 5 5 5

Output
1

Input
5 16
5 5 5 5 5

Output
2

Input
5...

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

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

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

l.sort(reverse = True)

left = 1
right = n

def check(k,m):
  if m > 0:
    lef = 0
    z = 0
    for i in range(n):
      m -= max(0, l[i]-lef)
      z += 1
      if z == k:
        z = 0
        lef += 1
  if m <= 0:
    return 1
  else:
    return 0

res = []

while left <= right:
  mid = int((left+right)/2)
  if check(mid, m):
    res.append(mid)
    right = mid - 1
  else:
    left = mid + 1
if len(res) > 0:
  print(min(res))
else:
  print("-1")

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

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

s = sum(l)
ans = 0

def find(x):
  su = 0
  days = 0
  z = 0

  for i in l:
    su += max(0, i-z)
    days += 1
    if days == x:
      days = 0
      z += 1
  if su < m:
    return 0
  return x

def binary(left, right):
  nonlocal ans
  mid = int((left+right)/2)
  r = find(mid)
  if right == left:
    ans = r
  elif left == right - 1:
    if r:
      ans = r
    else:
      binary(r, r)
  else:
    if r:
      binary(left, mid)
    else:
      binary(mid, right)

if s < m:
  print("-1")
elif s == m:
  print(n)
else:
  l.sort(reverse = True)
  binary(1,n)
  print(ans)
print(ans)
"""


I found an interesting problem on https://codeforces.com/problemset/problem/1118/D2:
The only difference between easy and hard versions is the constraints.

Polycarp has to write a coursework. The coursework consists of $m$ pages.

Polycarp also has $n$ cups of coffee. The coffee in the $i$-th cup Polycarp has $a_i$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).

Surely, courseworks are not being written in a single day (in a perfect world of Berland, at least).

Let's consider some day of Polycarp's work. Consider Polycarp drinks $k$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $a_{i_1}, a_{i_2}, \dots, a_{i_k}$. Then the first cup he drinks gives him energy to write $a_{i_1}$ pages of coursework, the second cup gives him energy to write $max(0, a_{i_2} - 1)$ pages, the third cup gives him energy to write $max(0, a_{i_3} - 2)$ pages, ..., the $k$-th cup gives him energy to write $max(0, a_{i_k} - k + 1)$ pages.

If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.

Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $1 \le m \le 10^9$) — the number of cups of coffee and the number of pages in the coursework.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the caffeine dosage of coffee in the $i$-th cup.

-----Output-----

If it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.

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

Output
4

Input
7 10
1 3 4 2 1 4 2

Output
2

Input
5 15
5 5 5 5 5

Output
1

Input
5 16
5 5 5 5 5

Output
2

Input
5 26
5 5 5 5...

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

n, m = list(map(int, input().split()))
l = list(map(int, input().split()))
l.sort(reverse=True)
ans = []
def bin(s):
    tmp = [[] for k in range(s)]
    cur = s
    tr = 0
    for i in range(n):
        if (cur == s):
            cur = 0
        tmp[cur].append(l[i])
        cur += 1
    for i in range(s):
        for k in range(len(tmp[i])):
            tr += max(tmp[i][k] - k, 0)
    if tr >= m:
        return 1
    else:
        return 0
uk2 = n
uk1 = 1
while (uk2 - uk1 > 1):
    if bin((uk2 + uk1) // 2):
        uk2 = (uk2 + uk1) // 2
    else:
        uk1 = (uk2 + uk1) // 2
if bin(uk1):
    print(uk1)
elif bin(uk2):
    print(uk2)
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1118/E:
The king of Berland organizes a ball! $n$ pair are invited to the ball, they are numbered from $1$ to $n$. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from $1$ to $k$, inclusive.

Let $b_i$ be the color of the man's costume and $g_i$ be the color of the woman's costume in the $i$-th pair. You have to choose a color for each dancer's costume (i.e. values $b_1, b_2, \dots, b_n$ and $g_1, g_2, \dots g_n$) in such a way that:  for every $i$: $b_i$ and $g_i$ are integers between $1$ and $k$, inclusive;  there are no two completely identical pairs, i.e. no two indices $i, j$ ($i \ne j$) such that $b_i = b_j$ and $g_i = g_j$ at the same time;  there is no pair such that the color of the man's costume is the same as the color of the woman's costume in this pair, i.e. $b_i \ne g_i$ for every $i$;  for each two consecutive (adjacent) pairs both man's costume colors and woman's costume colors differ, i.e. for every $i$ from $1$ to $n-1$ the conditions $b_i \ne b_{i + 1}$ and $g_i \ne g_{i + 1}$ hold.

Let's take a look at the examples of bad and good color choosing (for $n=4$ and $k=3$, man is the first in a pair and woman is the second):

Bad color choosing:   $(1, 2)$, $(2, 3)$, $(3, 2)$, $(1, 2)$ — contradiction with the second rule (there are equal pairs);  $(2, 3)$, $(1, 1)$, $(3, 2)$, $(1, 3)$ — contradiction with the third rule (there is a pair with costumes of the same color);  $(1, 2)$, $(2, 3)$, $(1, 3)$, $(2, 1)$ — contradiction with the fourth rule (there are two consecutive pairs such that colors of costumes of men/women are the same).

Good color choosing:   $(1, 2)$, $(2, 1)$, $(1, 3)$, $(3, 1)$;  $(1, 2)$, $(3, 1)$, $(2, 3)$, $(3, 2)$;  $(3, 1)$, $(1, 2)$, $(2, 3)$, $(3, 2)$.

You have to find any suitable color choosing or say that no suitable choosing exists.

-----Input-----

The only line of the input contains two integers $n$ and $k$ ($2 \le n, k \le 2 \cdot 10^5$) — the number of...

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

import sys
n,k=list(map(int,input().split()))
c=0
if k*(k-1) < n:
 print('NO')
else:
 print('YES')
 for i in range(k-1):
  for j in range(k):
   c+=1
   if c>n:return
   print(1+j,1+(j+i+1)%k)


I found an interesting problem on https://codeforces.com/problemset/problem/1118/F1:
You are given an undirected tree of $n$ vertices.

Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.

You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.

How many nice edges are there in the given tree?

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the number of vertices in the tree.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2$) — the colors of the vertices. $a_i = 1$ means that vertex $i$ is colored red, $a_i = 2$ means that vertex $i$ is colored blue and $a_i = 0$ means that vertex $i$ is uncolored.

The $i$-th of the next $n - 1$ lines contains two integers $v_i$ and $u_i$ ($1 \le v_i, u_i \le n$, $v_i \ne u_i$) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.

-----Output-----

Print a single integer — the number of nice edges in the given tree.

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

Output
1

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

Output
4

Input
3
1 1 2
2 3
1 3

Output
0

-----Note-----

Here is the tree from the first example: [Image]

The only nice edge is edge $(2, 4)$. Removing it makes the tree fall apart into components $\{4\}$ and $\{1, 2, 3, 5\}$. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices.

Here is the tree from the second example: [Image]

Every edge is nice in it.

Here is the tree from the third example: [Image]

Edge $(1, 3)$ splits the into components $\{1\}$ and $\{3, 2\}$, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge $(2, 3)$ splits the into components $\{1, 3\}$ and $\{2\}$, the former...

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

import sys
input=sys.stdin.readline
n = int(input())
a = [int(t) for t in input().split(' ')]
mx = [[] for _ in range(n)]
for i in range(n-1):
    v1, v2 = list(map(int,input().split()))
    mx[v1-1].append(v2-1)
    mx[v2-1].append(v1-1)
count = [[0, 0] for _ in range(n)]
total = [a.count(1), a.count(2)]
answer = 0
OBSERVE = 0
CHECK = 1
stack = [(OBSERVE, 0, -1)]
while len(stack):
    #print(stack,count)
    state, vertex, parent = stack.pop()
    if state == OBSERVE:
        stack.append((CHECK, vertex, parent))
        for child in mx[vertex]:
            #print(nv,v,from_)
            if child != parent:
                stack.append((OBSERVE, child, vertex))
    else:
        for child in mx[vertex]:
            if child != parent:
                #print(child,parent,count)
                if count[child][0] == total[0] and count[child][1] == 0 or count[child][1] == total[1] and count[child][0] == 0:
                    answer += 1
                count[vertex][0] += count[child][0]
                count[vertex][1] += count[child][1]

        if a[vertex] != 0:
            #print(count)
            count[vertex][a[vertex]-1] += 1
            #print(count)

print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/1119/A:
Ilya lives in a beautiful city of Chordalsk.

There are $n$ houses on the street Ilya lives, they are numerated from $1$ to $n$ from left to right; the distance between every two neighboring houses is equal to $1$ unit. The neighboring houses are $1$ and $2$, $2$ and $3$, ..., $n-1$ and $n$. The houses $n$ and $1$ are not neighboring.

The houses are colored in colors $c_1, c_2, \ldots, c_n$ so that the $i$-th house is colored in the color $c_i$. Everyone knows that Chordalsk is not boring, so there are at least two houses colored in different colors.

Ilya wants to select two houses $i$ and $j$ so that $1 \leq i < j \leq n$, and they have different colors: $c_i \neq c_j$. He will then walk from the house $i$ to the house $j$ the distance of $(j-i)$ units.

Ilya loves long walks, so he wants to choose the houses so that the distance between them is the maximum possible.

Help Ilya, find this maximum possible distance.

-----Input-----

The first line contains a single integer $n$ ($3 \leq n \leq 300\,000$) — the number of cities on the street.

The second line contains $n$ integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq n$) — the colors of the houses.

It is guaranteed that there is at least one pair of indices $i$ and $j$ so that $1 \leq i < j \leq n$ and $c_i \neq c_j$.

-----Output-----

Print a single integer — the maximum possible distance Ilya can walk.

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

Output
4

Input
3
1 2 1

Output
1

Input
7
1 1 3 1 1 1 1

Output
4

-----Note-----

In the first example the optimal way is to walk from the first house to the last one, where Ilya can walk the distance of $5-1 = 4$ units.

In the second example the optimal way is to either walk from the first house to the second or from the second to the third. Both these ways have the distance of $1$ unit.

In the third example the optimal way is to walk from the third house to the last one, where Ilya can walk the distance of $7-3 = 4$ units.

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

def mp():
    return map(int, input().split())

n = int(input())
a = list(mp())

ans = 1
for i in range(1, n):
    if a[i] != a[0]:
        ans = i
a = a[::-1]
for i in range(1, n):
    if a[i] != a[0]:
        ans = max(ans, i)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1119/B:
Alyona has recently bought a miniature fridge that can be represented as a matrix with $h$ rows and $2$ columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part.

 [Image] An example of a fridge with $h = 7$ and two shelves. The shelves are shown in black. The picture corresponds to the first example.

Alyona has $n$ bottles of milk that she wants to put in the fridge. The $i$-th bottle is $a_i$ cells tall and $1$ cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can not put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.

Alyona is interested in the largest integer $k$ such that she can put bottles $1$, $2$, ..., $k$ in the fridge at the same time. Find this largest $k$.

-----Input-----

The first line contains two integers $n$ and $h$ ($1 \le n \le 10^3$, $1 \le h \le 10^9$) — the number of bottles and the height of the fridge.

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le h$) — the heights of the bottles.

-----Output-----

Print the single integer $k$ — the maximum integer such that Alyona can put the bottles $1$, $2$, ..., $k$ in the fridge at the same time. If Alyona can put all bottles in the fridge, print $n$. It is easy to see that Alyona can always put at least one bottle in the fridge.

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

Output
3

Input
10 10
9 1 1 1 1 1 1 1 1 1

Output
4

Input
5 10
3 1 4 2 4

Output
5

-----Note-----

One of optimal locations in the first example is shown on the picture in the statement.

One of optimal locations in the second example is shown on the picture below.

 [Image]

One of optimal locations in the third example is shown on the picture below.

 [Image]

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

n,h=map(int,input().split())
l=list(map(int,input().split()))
ans=0
for i in range(n):
         curr=0
         ls=sorted(l[:i+1])
         for j in range(i,-1,-2):
                  curr+=ls[j]
         if(curr>h):
                  break
         else:
                  ans=i
print(ans+1)


I found an interesting problem on https://codeforces.com/problemset/problem/1119/C:
Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task.

You are given two matrices $A$ and $B$ of size $n \times m$, each of which consists of $0$ and $1$ only. You can apply the following operation to the matrix $A$ arbitrary number of times: take any submatrix of the matrix $A$ that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain $0$, will be replaced by $1$, and all corners of the submatrix that contain $1$, will be replaced by $0$). You have to answer whether you can obtain the matrix $B$ from the matrix $A$. [Image] An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow.

Ramesses don't want to perform these operations by himself, so he asks you to answer this question.

A submatrix of matrix $M$ is a matrix which consist of all elements which come from one of the rows with indices $x_1, x_1+1, \ldots, x_2$ of matrix $M$ and one of the columns with indices $y_1, y_1+1, \ldots, y_2$ of matrix $M$, where $x_1, x_2, y_1, y_2$ are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$, where the cell $(i,j)$ denotes the cell on the intersection of the $i$-th row and the $j$-th column.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \leq n, m \leq 500$) — the number of rows and the number of columns in matrices $A$ and $B$.

Each of the next $n$ lines contain $m$ integers: the $j$-th integer in the $i$-th line is the $j$-th element of the $i$-th row of the matrix $A$ ($0 \leq A_{ij} \leq 1$).

Each of the next $n$ lines contain $m$ integers: the $j$-th integer in the $i$-th line is the $j$-th element of the $i$-th row of the...

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

N,M = list(map(int,input().split()))
A = [list(map(int,input().split())) for i in range(N)]
B = [list(map(int,input().split())) for i in range(N)]

if N==1 or M==1:
    print('Yes' if A==B else 'No')
    return

D = []
for arow,brow in zip(A,B):
    D.append([abs(a-b) for a,b in zip(arow,brow)])

for i in range(N-1):
    ds = [j for j in range(M) if D[i][j]]
    if len(ds)%2:
        print('No')
        return
    for j in ds:
        D[i+1][j] = 1 - D[i+1][j]
print('No' if any(D[-1]) else 'Yes')


I found an interesting problem on https://codeforces.com/problemset/problem/1119/D:
Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day.

In return, the fleas made a bigger ukulele for her: it has $n$ strings, and each string has $(10^{18} + 1)$ frets numerated from $0$ to $10^{18}$. The fleas use the array $s_1, s_2, \ldots, s_n$ to describe the ukulele's tuning, that is, the pitch of the $j$-th fret on the $i$-th string is the integer $s_i + j$.

Miyako is about to leave the kingdom, but the fleas hope that Miyako will answer some last questions for them.

Each question is in the form of: "How many different pitches are there, if we consider frets between $l$ and $r$ (inclusive) on all strings?"

Miyako is about to visit the cricket kingdom and has no time to answer all the questions. Please help her with this task!

Formally, you are given a matrix with $n$ rows and $(10^{18}+1)$ columns, where the cell in the $i$-th row and $j$-th column ($0 \le j \le 10^{18}$) contains the integer $s_i + j$. You are to answer $q$ queries, in the $k$-th query you have to answer the number of distinct integers in the matrix from the $l_k$-th to the $r_k$-th columns, inclusive.

-----Input-----

The first line contains an integer $n$ ($1 \leq n \leq 100\,000$) — the number of strings.

The second line contains $n$ integers $s_1, s_2, \ldots, s_n$ ($0 \leq s_i \leq 10^{18}$) — the tuning of the ukulele.

The third line contains an integer $q$ ($1 \leq q \leq 100\,000$) — the number of questions.

The $k$-th among the following $q$ lines contains two integers $l_k$，$r_k$ ($0 \leq l_k \leq r_k \leq 10^{18}$) — a question from the fleas.

-----Output-----

Output one number for each question, separated by spaces — the number of different pitches.

-----Examples-----
Input
6
3 1 4 1 5 9
3
7 7
0 2
8 17

Output
5 10 18

Input
2
1 500000000000000000
2
1000000000000000000 1000000000000000000
0 1000000000000000000

Output
2 1500000000000000000

-----Note-----

For the first example, the pitches on the $6$ strings are as...

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

def main():
    from bisect import bisect
    from itertools import accumulate, chain
    from sys import stdin, stdout

    input = stdin.readline
    input()
    s = sorted(set(map(int, input().split())))
    n = len(s)
    inp = sorted((a - b for (a, b) in zip(s[1:], s)))
    acc = tuple(chain(accumulate(inp), (0,)))
    for _ in range(int(input())):
        l_, r = list(map(int, input().split()))
        d = r + 1 - l_
        i = bisect(inp, d)
        stdout.write(f'{acc[i - 1] + (n - i) * d} ')

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1119/E:
Pavel has several sticks with lengths equal to powers of two.

He has $a_0$ sticks of length $2^0 = 1$, $a_1$ sticks of length $2^1 = 2$, ..., $a_{n-1}$ sticks of length $2^{n-1}$.

Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.

It is forbidden to break sticks, and each triangle should consist of exactly three sticks.

Find the maximum possible number of triangles.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 300\,000$) — the number of different lengths of sticks.

The second line contains $n$ integers $a_0$, $a_1$, ..., $a_{n-1}$ ($1 \leq a_i \leq 10^9$), where $a_i$ is the number of sticks with the length equal to $2^i$.

-----Output-----

Print a single integer — the maximum possible number of non-degenerate triangles that Pavel can make.

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

Output
3

Input
3
1 1 1

Output
0

Input
3
3 3 3

Output
3

-----Note-----

In the first example, Pavel can, for example, make this set of triangles (the lengths of the sides of the triangles are listed): $(2^0, 2^4, 2^4)$, $(2^1, 2^3, 2^3)$, $(2^1, 2^2, 2^2)$.

In the second example, Pavel cannot make a single triangle.

In the third example, Pavel can, for example, create this set of triangles (the lengths of the sides of the triangles are listed): $(2^0, 2^0, 2^0)$, $(2^1, 2^1, 2^1)$, $(2^2, 2^2, 2^2)$.

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

n, ans, last = int(input()), 0, 0
a = list(map(int, input().split()))
for i in range(len(a)):
    while last > 0 and a[i] >= 2:
        ans += 1
        a[i] -= 2
        last -= 1
    ans += a[i] // 3
    last += a[i] % 3
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1120/C:
Suppose you are given a string $s$ of length $n$ consisting of lowercase English letters. You need to compress it using the smallest possible number of coins.

To compress the string, you have to represent $s$ as a concatenation of several non-empty strings: $s = t_{1} t_{2} \ldots t_{k}$. The $i$-th of these strings should be encoded with one of the two ways:  if $|t_{i}| = 1$, meaning that the current string consists of a single character, you can encode it paying $a$ coins;  if $t_{i}$ is a substring of $t_{1} t_{2} \ldots t_{i - 1}$, then you can encode it paying $b$ coins.

A string $x$ is a substring of a string $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

So your task is to calculate the minimum possible number of coins you need to spend in order to compress the given string $s$.

-----Input-----

The first line contains three positive integers, separated by spaces: $n$, $a$ and $b$ ($1 \leq n, a, b \leq 5000$) — the length of the string, the cost to compress a one-character string and the cost to compress a string that appeared before.

The second line contains a single string $s$, consisting of $n$ lowercase English letters.

-----Output-----

Output a single integer — the smallest possible number of coins you need to spend to compress $s$.

-----Examples-----
Input
3 3 1
aba

Output
7

Input
4 1 1
abcd

Output
4

Input
4 10 1
aaaa

Output
12

-----Note-----

In the first sample case, you can set $t_{1} =$ 'a', $t_{2} =$ 'b', $t_{3} =$ 'a' and pay $3 + 3 + 1 = 7$ coins, since $t_{3}$ is a substring of $t_{1}t_{2}$.

In the second sample, you just need to compress every character by itself.

In the third sample, you set $t_{1} = t_{2} =$ 'a', $t_{3} =$ 'aa' and pay $10 + 1 + 1 = 12$ coins, since $t_{2}$ is a substring of $t_{1}$ and $t_{3}$ is a substring of $t_{1} t_{2}$.

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

def f(x):
    z=[0 for i in range(len(x))]
    l=0
    r=0
    for i in range(1,len(x)):
        if i<=r:
            z[i]=min(z[i-l],r-i+1)
        while i+z[i]<len(x) and x[z[i]]==x[i+z[i]]:
            z[i]+=1
        if i+z[i]-1>r:
            l,r=i,i+z[i]-1
    return z
a=list(map(int,input('').split()))
n,a,b=a[0],a[1],a[2]
s=input('')
dp=[0 for i in range(n)]
dp[0]=a
for i in range(1,n):
    t=s[:i+1]
    dp[i]=dp[i-1]+a
    q=f(t[::-1])
    maxs=[0 for j in range(i+1)]
    maxs[0]=q[i]
    for j in range(1,i):
        maxs[j]=max(maxs[j-1],q[i-j])
    for j in range(i):
        if maxs[j]>=i-j:
            dp[i]=min(dp[i],dp[j]+b)
print(dp[len(dp)-1])