I found an interesting problem on https://codeforces.com/problemset/problem/1151/F:
A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her.

Given an array $a$ of length $n$, consisting only of the numbers $0$ and $1$, and the number $k$. Exactly $k$ times the following happens:   Two numbers $i$ and $j$ are chosen equiprobable such that ($1 \leq i < j \leq n$).  The numbers in the $i$ and $j$ positions are swapped.

Sonya's task is to find the probability that after all the operations are completed, the $a$ array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem.

It can be shown that the desired probability is either $0$ or it can be represented as $\dfrac{P}{Q}$, where $P$ and $Q$ are coprime integers and $Q \not\equiv 0~\pmod {10^9+7}$.

-----Input-----

The first line contains two integers $n$ and $k$ ($2 \leq n \leq 100, 1 \leq k \leq 10^9$) — the length of the array $a$ and the number of operations.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 1$) — the description of the array $a$.

-----Output-----

If the desired probability is $0$, print $0$, otherwise print the value $P \cdot Q^{-1}$ $\pmod {10^9+7}$, where $P$ and $Q$ are defined above.

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

Output
333333336
Input
5 1
1 1 1 0 0

Output
0
Input
6 4
1 0 0 1 1 0

Output
968493834

-----Note-----

In the first example, all possible variants of the final array $a$, after applying exactly two operations: $(0, 1, 0)$, $(0, 0, 1)$, $(1, 0, 0)$, $(1, 0, 0)$, $(0, 1, 0)$, $(0, 0, 1)$, $(0, 0, 1)$, $(1, 0, 0)$, $(0, 1, 0)$. Therefore, the answer is $\dfrac{3}{9}=\dfrac{1}{3}$.

In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is $0$.

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

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

"""Codeforces Round #553 (Div. 2)

Problem F. Sonya and Informatics

:author:         Kitchen Tong
:mail:    kctong529@gmail.com

Please feel free to contact me if you have any question
regarding the implementation below.
"""

__version__ = '1.8'
__date__ = '2019-04-21'

import sys

def binom_dp():
    dp = [[-1 for j in range(110)] for i in range(110)]
    def calculate(n, k):
        if n < k:
            return 0
        if n == k or k == 0:
            return 1
        if dp[n][k] > 0:
            return dp[n][k]
        else:
            dp[n][k] = calculate(n-1, k-1) + calculate(n-1, k)
        return dp[n][k]
    return calculate

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

def multiply(A, B, mod):
    if not hasattr(B[0], '__len__'):
        C = [sum(aij * B[j] % mod for j, aij in enumerate(ai)) for ai in A]
    else:
        C = [[0 for col in range(len(B[0]))] for row in range(len(A))]
        len_A = len(A)
        len_B = len(B)
        for row in range(len_A):
            if sum(A[row]) == 0:
                continue
            for col in range(len_B):
                C[row][col] = sum(A[row][k] * B[k][col]
                                  for k in range(len_B)) % mod
    return C

def memoize(func):
    memo = {}
    def wrapper(*args):
        M, n, mod = args
        if n not in memo:
            memo[n] = func(M, n, mod)
        return memo[n]
    return wrapper

@memoize
def matrix_pow(M, n, mod):
    # print(f'n is {n}')
    if n == 2:
        return multiply(M, M, mod)
    if n == 1:
        return M
    sub_M = matrix_pow(M, n//2, mod)
    if n % 2 == 0:
        return multiply(sub_M, sub_M, mod)
    return multiply(sub_M, matrix_pow(M, n - n//2, mod), mod)

def solve(n, k, a, binom, mod):
    ones =...


I found an interesting problem on https://codeforces.com/problemset/problem/1152/A:
On a random day, Neko found $n$ treasure chests and $m$ keys. The $i$-th chest has an integer $a_i$ written on it and the $j$-th key has an integer $b_j$ on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.

The $j$-th key can be used to unlock the $i$-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, $a_i + b_j \equiv 1 \pmod{2}$. One key can be used to open at most one chest, and one chest can be opened at most once.

Find the maximum number of chests Neko can open.

-----Input-----

The first line contains integers $n$ and $m$ ($1 \leq n, m \leq 10^5$) — the number of chests and the number of keys.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the numbers written on the treasure chests.

The third line contains $m$ integers $b_1, b_2, \ldots, b_m$ ($1 \leq b_i \leq 10^9$) — the numbers written on the keys.

-----Output-----

Print the maximum number of chests you can open.

-----Examples-----
Input
5 4
9 14 6 2 11
8 4 7 20

Output
3
Input
5 1
2 4 6 8 10
5

Output
1
Input
1 4
10
20 30 40 50

Output
0

-----Note-----

In the first example, one possible way to unlock $3$ chests is as follows:

  Use first key to unlock the fifth chest,  Use third key to unlock the second chest,  Use fourth key to unlock the first chest.

In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).

In the third example, no key can unlock the given chest.

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

n,m=map(int,input().split())
a=[int(s) for s in input().split()]
b=[int(s) for s in input().split()]
cnt=0
cnt1=0
for i in range(n):
    if a[i]%2==0:
        cnt+=1
for i in range(m):
    if b[i]%2==0:
        cnt1+=1
print(min(cnt,m-cnt1)+min(cnt1,n-cnt))


I found an interesting problem on https://codeforces.com/problemset/problem/1152/B:
Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.

Assume that we have a cat with a number $x$. A perfect longcat is a cat with a number equal $2^m - 1$ for some non-negative integer $m$. For example, the numbers $0$, $1$, $3$, $7$, $15$ and so on are suitable for the perfect longcats.

In the Cat Furrier Transform, the following operations can be performed on $x$:  (Operation A): you select any non-negative integer $n$ and replace $x$ with $x \oplus (2^n - 1)$, with $\oplus$ being a bitwise XOR operator. (Operation B): replace $x$ with $x + 1$.

The first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B.

Neko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most $40$ operations. Can you help Neko writing a transformation plan?

Note that it is not required to minimize the number of operations. You just need to use no more than $40$ operations.

-----Input-----

The only line contains a single integer $x$ ($1 \le x \le 10^6$).

-----Output-----

The first line should contain a single integer $t$ ($0 \le t \le 40$) — the number of operations to apply.

Then for each odd-numbered operation print the corresponding number $n_i$ in it. That is, print $\lceil \frac{t}{2} \rceil$ integers $n_i$ ($0 \le n_i \le 30$), denoting the replacement $x$ with $x \oplus (2^{n_i} - 1)$ in the corresponding step.

If there are multiple possible answers, you can print any of them. It is possible to show, that there is at least one answer in the constraints of this problem.

-----Examples-----
Input
39

Output
4
5 3
Input
1

Output
0

Input
7

Output
0

-----Note-----

In the first test, one of the...

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

x = int(input())

ans = []

cnt = 0

while x & (x + 1) != 0:
    bn = str(bin(x)[2:])
    cnt += 1

    ret = -1
    for i in range(len(bn)):
        if bn[i] == '0':
            ret = i
            break

    if ret == -1:
        break

    x ^= 2 ** (len(bn) - ret) - 1
    ans.append(len(bn) - ret)

    if x & (x + 1) == 0:
        break

    x += 1
    cnt += 1

print(cnt)
if len(ans) > 0:
    print(' '.join(str(el) for el in ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1152/C:
Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.

Neko has two integers $a$ and $b$. His goal is to find a non-negative integer $k$ such that the least common multiple of $a+k$ and $b+k$ is the smallest possible. If there are multiple optimal integers $k$, he needs to choose the smallest one.

Given his mathematical talent, Neko had no trouble getting Wrong Answer on this problem. Can you help him solve it?

-----Input-----

The only line contains two integers $a$ and $b$ ($1 \le a, b \le 10^9$).

-----Output-----

Print the smallest non-negative integer $k$ ($k \ge 0$) such that the lowest common multiple of $a+k$ and $b+k$ is the smallest possible.

If there are many possible integers $k$ giving the same value of the least common multiple, print the smallest one.

-----Examples-----
Input
6 10

Output
2
Input
21 31

Output
9
Input
5 10

Output
0

-----Note-----

In the first test, one should choose $k = 2$, as the least common multiple of $6 + 2$ and $10 + 2$ is $24$, which is the smallest least common multiple possible.

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

are, bre = list(map(int,input().split()))

def plottt(xre,yre):

	if (xre == 0):

		return yre

	if (yre == 0):

		return xre

	if (yre > xre):

		yre,xre = xre,yre

	return plottt(xre%yre, yre)

if (are > bre):

	are, bre = bre, are

kre = bre - are

plkiyer = []

ire = 1

while( ire**2<=kre):

	if( kre % ire == 0):

		plkiyer.append(ire)

		plkiyer.append(kre // ire)

	ire+= 1

plotttd = are*bre / plottt(are,bre)

result = 0

for dre in plkiyer:

	aare = are - (are % dre) + dre

	bbre = bre - (bre % dre) + dre

	if (aare*bbre // plottt(aare,bbre) <= plotttd):

		if( aare*bbre // plottt(aare,bbre) == plotttd):

			result = min(dre-(are%dre),result)

		else:

			plotttd = aare*bbre // plottt(aare,bbre)

			result = dre - (are%dre)

print(result)


I found an interesting problem on https://codeforces.com/problemset/problem/1152/D:
Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys...

It took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of weird things, including a trie of all correct bracket sequences of length $2n$.

The definition of correct bracket sequence is as follows:  The empty sequence is a correct bracket sequence,  If $s$ is a correct bracket sequence, then $(\,s\,)$ is a correct bracket sequence,  If $s$ and $t$ are a correct bracket sequence, then $st$ is also a correct bracket sequence.

For example, the strings "(())", "()()" form a correct bracket sequence, while ")(" and "((" not.

Aki then came up with an interesting problem: What is the size of the maximum matching (the largest set of edges such that there are no two edges with a common vertex) in this trie? Since the answer can be quite large, print it modulo $10^9 + 7$.

-----Input-----

The only line contains a single integer $n$ ($1 \le n \le 1000$).

-----Output-----

Print exactly one integer — the size of the maximum matching in the trie. Since the answer can be quite large, print it modulo $10^9 + 7$.

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

Output
1

Input
2

Output
3

Input
3

Output
9

-----Note-----

The pictures below illustrate tries in the first two examples (for clarity, the round brackets are replaced with angle brackets). The maximum matching is highlighted with blue. [Image] [Image]

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


I found an interesting problem on https://codeforces.com/problemset/problem/1152/E:
A permutation of length $k$ is a sequence of $k$ integers from $1$ to $k$ containing each integer exactly once. For example, the sequence $[3, 1, 2]$ is a permutation of length $3$.

When Neko was five, he thought of an array $a$ of $n$ positive integers and a permutation $p$ of length $n - 1$. Then, he performed the following:

  Constructed an array $b$ of length $n-1$, where $b_i = \min(a_i, a_{i+1})$.  Constructed an array $c$ of length $n-1$, where $c_i = \max(a_i, a_{i+1})$.  Constructed an array $b'$ of length $n-1$, where $b'_i = b_{p_i}$.  Constructed an array $c'$ of length $n-1$, where $c'_i = c_{p_i}$.

For example, if the array $a$ was $[3, 4, 6, 5, 7]$ and permutation $p$ was $[2, 4, 1, 3]$, then Neko would have constructed the following arrays:

  $b = [3, 4, 5, 5]$  $c = [4, 6, 6, 7]$  $b' = [4, 5, 3, 5]$  $c' = [6, 7, 4, 6]$

Then, he wrote two arrays $b'$ and $c'$ on a piece of paper and forgot about it. 14 years later, when he was cleaning up his room, he discovered this old piece of paper with two arrays $b'$ and $c'$ written on it. However he can't remember the array $a$ and permutation $p$ he used.

In case Neko made a mistake and there is no array $a$ and permutation $p$ resulting in such $b'$ and $c'$, print -1. Otherwise, help him recover any possible array $a$.

-----Input-----

The first line contains an integer $n$ ($2 \leq n \leq 10^5$) — the number of elements in array $a$.

The second line contains $n-1$ integers $b'_1, b'_2, \ldots, b'_{n-1}$ ($1 \leq b'_i \leq 10^9$).

The third line contains $n-1$ integers $c'_1, c'_2, \ldots, c'_{n-1}$ ($1 \leq c'_i \leq 10^9$).

-----Output-----

If Neko made a mistake and there is no array $a$ and a permutation $p$ leading to the $b'$ and $c'$, print -1. Otherwise, print $n$ positive integers $a_i$ ($1 \le a_i \le 10^9$), denoting the elements of the array $a$.

If there are multiple possible solutions, print any of them.

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

Output
3 4 6 5 7

Input
3
2 4
3 2

Output
-1

Input
8
2 3 1 1 2 4...

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

from collections import defaultdict, Counter
N = int(input())
B = list(map(int, input().split()))
C = list(map(int, input().split()))
Edge = defaultdict(list)
Edc = defaultdict(int)
for b, c in zip(B, C):
    if b > c:
        print(-1)
        return
    Edge[b].append(c)
    Edc[(b, c)] += 1
    if b != c:
        Edge[c].append(b)
Deg = Counter(B + C)
eul = 0
st = []
for k, v in list(Deg.items()):
    if v % 2:
        eul += 1
        st.append(k)
s, e = B[0], B[0]
if eul and eul != 2:
    print(-1)
    return
if eul:
    s, e = st[0], st[1]
ans = [s]
while True:
    vn = ans[-1]
    while True:
        vf = Edge[vn][-1]
        if Deg[vf] != 0 and Edc[(vn, vf) if vn < vf else (vf, vn)]:
            break
        Edge[vn].pop()
    vf = Edge[vn].pop()
    Deg[vn] -= 1
    Deg[vf] -= 1
    Edc[(vn, vf) if vn < vf else (vf, vn)] -= 1
    ans.append(vf)
    if not Deg[vf]:
        break
loop = defaultdict(list)
for a in ans:
    if Deg[a]:
        loopa = [a]
        while Deg[a]:
            vn = loopa[-1]
            while True:
                vf = Edge[vn][-1]
                if Deg[vf] != 0 and Edc[(vn, vf) if vn < vf else (vf, vn)]:
                    break
                Edge[vn].pop()
            vf = Edge[vn].pop()
            Deg[vn] -= 1
            Deg[vf] -= 1
            Edc[(vn, vf) if vn < vf else (vf, vn)] -= 1
            loopa.append(vf)
            if not Deg[vf]:
                break
        loop[a] = loopa
Ans = []
for a in ans:
    if loop[a]:
        Ans.extend(loop[a])
        loop[a] = []
    else:
        Ans.append(a)
if len(Ans) != N:
    print(-1)
    return
print(*Ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1153/A:
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.

Serval will go to the bus station at time $t$, and there are $n$ bus routes which stop at this station. For the $i$-th bus route, the first bus arrives at time $s_i$ minutes, and each bus of this route comes $d_i$ minutes later than the previous one.

As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.

-----Input-----

The first line contains two space-separated integers $n$ and $t$ ($1\leq n\leq 100$, $1\leq t\leq 10^5$) — the number of bus routes and the time Serval goes to the station.

Each of the next $n$ lines contains two space-separated integers $s_i$ and $d_i$ ($1\leq s_i,d_i\leq 10^5$) — the time when the first bus of this route arrives and the interval between two buses of this route.

-----Output-----

Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.

-----Examples-----
Input
2 2
6 4
9 5

Output
1

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

Output
3

Input
3 7
2 2
2 3
2 4

Output
1

-----Note-----

In the first example, the first bus of the first route arrives at time $6$, and the first bus of the second route arrives at time $9$, so the first route is the answer.

In the second example, a bus of the third route arrives at time $5$, so it is the answer.

In the third example, buses of the first route come at times $2$, $4$, $6$, $8$, and so fourth, buses of the second route come at times $2$, $5$, $8$, and so fourth and buses of the third route come at times $2$, $6$, $10$, and so on, so $1$ and $2$ are...

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

import sys
from math import ceil

input = sys.stdin.readline

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

choose = []

for i in range(1, n+1):
    a, b = map(int, input().split())
    if a < t:
        a += ceil((t-a)/b) * b

    choose.append((a-t, i))
choose.sort()

print(choose[0][1])


I found an interesting problem on https://codeforces.com/problemset/problem/1153/B:
Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.

He has a special interest to create difficult problems for others to solve. This time, with many $1 \times 1 \times 1$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $n \times m$ matrix, such that in each cell $(i,j)$, there are $h_{i,j}$ bricks standing on the top of each other.

However, Serval doesn't give you any $h_{i,j}$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $m$ columns, and in the $i$-th of them, the height is the maximum of $h_{1,i},h_{2,i},\dots,h_{n,i}$. It is similar for the left view, where there are $n$ columns. And in the top view, there is an $n \times m$ matrix $t_{i,j}$, where $t_{i,j}$ is $0$ or $1$. If $t_{i,j}$ equals $1$, that means $h_{i,j}>0$, otherwise, $h_{i,j}=0$.

However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?

-----Input-----

The first line contains three positive space-separated integers $n, m, h$ ($1\leq n, m, h \leq 100$) — the length, width and height.

The second line contains $m$ non-negative space-separated integers $a_1,a_2,\dots,a_m$, where $a_i$ is the height in the $i$-th column from left to right of the front view ($0\leq a_i \leq h$).

The third line contains $n$ non-negative space-separated integers $b_1,b_2,\dots,b_n$ ($0\leq b_j \leq h$), where $b_j$ is the height in the $j$-th column from left to right of the left view.

Each of the following $n$ lines contains $m$ numbers, each is $0$ or $1$, representing the top view, where $j$-th number of $i$-th row is $1$ if $h_{i, j}>0$, and $0$ otherwise.

It is guaranteed that there is at least one structure...

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

n,m,h=[int(i) for i in input().split()]
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
c=[[int(i) for i in input().split()] for j in range(n)]

for i in range(n):
    target = b[i]
    for j in range(m):
        if c[i][j]==0: continue
        if a[j] < target: continue
        c[i][j] = target
for j in range(m):
    target = a[j]
    for i in range(n):
        if c[i][j]==0: continue
        if b[i] < target: continue
        c[i][j] = target
for row in c:
    for col in row:
        print(col,end=' ')
    print()


I found an interesting problem on https://codeforces.com/problemset/problem/1153/C:
Serval soon said goodbye to Japari kindergarten, and began his life in Japari Primary School.

In his favorite math class, the teacher taught him the following interesting definitions.

A parenthesis sequence is a string, containing only characters "(" and ")".

A correct parenthesis sequence is a parenthesis sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, parenthesis sequences "()()", "(())" are correct (the resulting expressions are: "(1+1)+(1+1)", "((1+1)+1)"), while ")(" and ")" are not. Note that the empty string is a correct parenthesis sequence by definition.

We define that $|s|$ as the length of string $s$. A strict prefix $s[1\dots l]$ $(1\leq l< |s|)$ of a string $s = s_1s_2\dots s_{|s|}$ is string $s_1s_2\dots s_l$. Note that the empty string and the whole string are not strict prefixes of any string by the definition.

Having learned these definitions, he comes up with a new problem. He writes down a string $s$ containing only characters "(", ")" and "?". And what he is going to do, is to replace each of the "?" in $s$ independently by one of "(" and ")" to make all strict prefixes of the new sequence not a correct parenthesis sequence, while the new sequence should be a correct parenthesis sequence.

After all, he is just a primary school student so this problem is too hard for him to solve. As his best friend, can you help him to replace the question marks? If there are many solutions, any of them is acceptable.

-----Input-----

The first line contains a single integer $|s|$ ($1\leq |s|\leq 3 \cdot 10^5$), the length of the string.

The second line contains a string $s$, containing only "(", ")" and "?".

-----Output-----

A single line contains a string representing the answer.

If there are many solutions, any of them is acceptable.

If there is no answer, print a single line containing ":(" (without the...

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

#!/usr/bin/env python3
import sys

def rint():
    return list(map(int, sys.stdin.readline().split()))
#lines = stdin.readlines()

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

o = s.count('(')
c = s.count(')')
ans = []
cnt = 0

ok = 0
for i in range(n):
    ans.append(s[i])

oc = o - c
if oc > 0:
    for i in range(n-1, -1, -1):
        if oc == 0:
            break
        if ans[i] =='?':
            ans[i] = ')'
            oc -= 1
    if oc !=0:
        print(':(')
        return
#print(ans)
qc = n - o - c - (o-c)
#print(qc)
if qc%2:
    print(':(')
    return

q = 0
for i in range(n):
    if q == qc:
        break
    if ans[i] == '?':
        if q < qc//2:
            ans[i] = '('
        else:
            ans[i] = ')'
        q += 1
#print(ans)
cnt = 0
for i in range(n):
    if ans[i] == '(':
        cnt += 1
    elif ans[i] == ')':
        cnt -= 1
    if cnt <= 0 and i != n-1:
        print(':(')
        return
#print(cnt)
if cnt != 0:
    print(':(')
    return
print(''.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1153/D:
Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before.

As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.

A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a node $v$ is the last different from $v$ vertex on the path from the root to the vertex $v$. Children of vertex $v$ are all nodes for which $v$ is the parent. A vertex is a leaf if it has no children.

The rooted tree Serval owns has $n$ nodes, node $1$ is the root. Serval will write some numbers into all nodes of the tree. However, there are some restrictions. Each of the nodes except leaves has an operation $\max$ or $\min$ written in it, indicating that the number in this node should be equal to the maximum or minimum of all the numbers in its sons, respectively.

Assume that there are $k$ leaves in the tree. Serval wants to put integers $1, 2, \ldots, k$ to the $k$ leaves (each number should be used exactly once). He loves large numbers, so he wants to maximize the number in the root. As his best friend, can you help him?

-----Input-----

The first line contains an integer $n$ ($2 \leq n \leq 3\cdot 10^5$), the size of the tree.

The second line contains $n$ integers, the $i$-th of them represents the operation in the node $i$. $0$ represents $\min$ and $1$ represents $\max$. If the node is a leaf, there is still a number of $0$ or $1$, but you can ignore it.

The third line contains $n-1$ integers $f_2, f_3, \ldots, f_n$ ($1 \leq f_i \leq i-1$), where $f_i$ represents the parent of the node $i$.

-----Output-----

Output one integer — the maximum possible number in the root of the tree.

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

Output
1

Input
5
1 0 1 0 1
1 1 1 1

Output
4

Input
8
1 0 0 1 0 1 1 0
1 1 2 2 3 3 3

Output
4

Input
9
1 1 0 0 1 0 1 0 1
1 1 2 2 3 3 4 4

Output
5

-----Note-----

Pictures below explain the examples. The numbers written...

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

import sys,threading
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)

def main():
    n = int(input().strip())
    son_tree = dict()
    min_max = [0] + [int(i) for i in input().strip().split()]
    for child, parent in enumerate(map(int,input().strip().split()),2):
        if parent not in son_tree:
            son_tree[parent] = [child]
        else:
            son_tree[parent].append(child)
    leaf_ctr = 0
    dp = [0 for i in range(n+1)]
    for i in range(1,n+1):
        if i not in son_tree:
            leaf_ctr += 1
            dp[i] = 1

    visited = set()
    def dfs(node):
        if node not in visited:
            visited.add(node)
            if node not in son_tree:
                return 1
            if min_max[node]:
                for i in son_tree[node]:
                    dfs(i)
                dp[node] = min(dp[k] for k in son_tree[node])
                return 0
            else:
                for i in son_tree[node]:
                    dfs(i)
                dp[node] = sum(dp[k] for k in son_tree[node])
                return 0
    dfs(1)
    print(leaf_ctr - dp[1]+1)
def __starting_point():
    t = threading.Thread(target=main)
    t.start()
    t.join()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1154/A:
Polycarp has guessed three positive integers $a$, $b$ and $c$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $a+b$, $a+c$, $b+c$ and $a+b+c$.

You have to guess three numbers $a$, $b$ and $c$ using given numbers. Print three guessed integers in any order.

Pay attention that some given numbers $a$, $b$ and $c$ can be equal (it is also possible that $a=b=c$).

-----Input-----

The only line of the input contains four positive integers $x_1, x_2, x_3, x_4$ ($2 \le x_i \le 10^9$) — numbers written on a board in random order. It is guaranteed that the answer exists for the given number $x_1, x_2, x_3, x_4$.

-----Output-----

Print such positive integers $a$, $b$ and $c$ that four numbers written on a board are values $a+b$, $a+c$, $b+c$ and $a+b+c$ written in some order. Print $a$, $b$ and $c$ in any order. If there are several answers, you can print any. It is guaranteed that the answer exists.

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

Output
2 1 3

Input
40 40 40 60

Output
20 20 20

Input
201 101 101 200

Output
1 100 100

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


I found an interesting problem on https://codeforces.com/problemset/problem/1154/B:
You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ integers.

You can choose any non-negative integer $D$ (i.e. $D \ge 0$), and for each $a_i$ you can:

  add $D$ (only once), i. e. perform $a_i := a_i + D$, or  subtract $D$ (only once), i. e. perform $a_i := a_i - D$, or  leave the value of $a_i$ unchanged.

It is possible that after an operation the value $a_i$ becomes negative.

Your goal is to choose such minimum non-negative integer $D$ and perform changes in such a way, that all $a_i$ are equal (i.e. $a_1=a_2=\dots=a_n$).

Print the required $D$ or, if it is impossible to choose such value $D$, print -1.

For example, for array $[2, 8]$ the value $D=3$ is minimum possible because you can obtain the array $[5, 5]$ if you will add $D$ to $2$ and subtract $D$ from $8$. And for array $[1, 4, 7, 7]$ the value $D=3$ is also minimum possible. You can add it to $1$ and subtract it from $7$ and obtain the array $[4, 4, 4, 4]$.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 100$) — the number of elements in $a$.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$) — the sequence $a$.

-----Output-----

Print one integer — the minimum non-negative integer value $D$ such that if you add this value to some $a_i$, subtract this value from some $a_i$ and leave some $a_i$ without changes, all obtained values become equal.

If it is impossible to choose such value $D$, print -1.

-----Examples-----
Input
6
1 4 4 7 4 1

Output
3

Input
5
2 2 5 2 5

Output
3

Input
4
1 3 3 7

Output
-1

Input
2
2 8

Output
3

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

n = int(input())
a = [int(x) for x in input().split()]
b = sorted(set(a))

if len(b) == 1:
    print(0)
elif len(b) == 2:
    b.sort()
    if sum(b) % 2 == 0:
        print((b[1] - b[0])//2)
    else:
        print(b[1] - b[0])
elif len(b) == 3:
    b.sort()
    if b[0] + b[2] == 2*b[1]:
        print(b[1] - b[0])
    else:
        print(-1)
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1154/C:
Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:  on Mondays, Thursdays and Sundays he eats fish food;  on Tuesdays and Saturdays he eats rabbit stew;  on other days of week he eats chicken stake.

Polycarp plans to go on a trip and already packed his backpack. His backpack contains:  $a$ daily rations of fish food;  $b$ daily rations of rabbit stew;  $c$ daily rations of chicken stakes.

Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.

-----Input-----

The first line of the input contains three positive integers $a$, $b$ and $c$ ($1 \le a, b, c \le 7\cdot10^8$) — the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly.

-----Output-----

Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.

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

Output
4

Input
3 2 2

Output
7

Input
1 100 1

Output
3

Input
30 20 10

Output
39

-----Note-----

In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday — rabbit stew and during Wednesday — chicken stake. So, after four days of the trip all food will be eaten.

In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack.

In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be $99$ portions of rabbit stew in a backpack, can cannot eat anything in fourth day...

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

a, b, c = list(map(int, input().split()))
weeks = min(a//3, b//2, c//2)
a -= weeks * 3
b -= weeks * 2
c -= weeks * 2

days = ["f", "r", "c", "f", "c", "r", "f"]
ans = 0

for i in range(7):
    day = i
    anstemp = 0
    A = a
    B = b
    C = c
    for j in range(50):
        if days[day] == "f":
            if A > 0:
                A -= 1
                day += 1
                anstemp += 1
            else:
                break
        elif days[day] == "r":
            if B > 0:
                B -= 1
                day += 1
                anstemp += 1
            else:
                break
        else:
            if C > 0:
                C -= 1
                day += 1
                anstemp += 1
        if day == 7:
            day = 0
    ans = max(anstemp, ans)

ans += weeks * 7
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1154/D:
There is a robot staying at $X=0$ on the $Ox$ axis. He has to walk to $X=n$. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.

The $i$-th segment of the path (from $X=i-1$ to $X=i$) can be exposed to sunlight or not. The array $s$ denotes which segments are exposed to sunlight: if segment $i$ is exposed, then $s_i = 1$, otherwise $s_i = 0$.

The robot has one battery of capacity $b$ and one accumulator of capacity $a$. For each segment, you should choose which type of energy storage robot will use to go to the next point (it can be either battery or accumulator). If the robot goes using the battery, the current charge of the battery is decreased by one (the robot can't use the battery if its charge is zero). And if the robot goes using the accumulator, the current charge of the accumulator is decreased by one (and the robot also can't use the accumulator if its charge is zero).

If the current segment is exposed to sunlight and the robot goes through it using the battery, the charge of the accumulator increases by one (of course, its charge can't become higher than it's maximum capacity).

If accumulator is used to pass some segment, its charge decreases by 1 no matter if the segment is exposed or not.

You understand that it is not always possible to walk to $X=n$. You want your robot to go as far as possible. Find the maximum number of segments of distance the robot can pass if you control him optimally.

-----Input-----

The first line of the input contains three integers $n, b, a$ ($1 \le n, b, a \le 2 \cdot 10^5$) — the robot's destination point, the battery capacity and the accumulator capacity, respectively.

The second line of the input contains $n$ integers $s_1, s_2, \dots, s_n$ ($0 \le s_i \le 1$), where $s_i$ is $1$ if the $i$-th segment of distance is exposed to sunlight, and $0$ otherwise.

-----Output-----

Print one integer — the maximum number of segments the robot can pass if you control him...

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

n, mb, ma = [int(i) for i in input().split()]
l = [int(i) for i in input().split()]

a, b = ma, mb
for i in range(n):
    if a + b == 0:
        print(i)
        return
    elif a != ma and b > 0 and l[i] == 1:
        b -= 1
        a += 1
    elif a > 0:
        a -= 1
    else:
        b -= 1
print(n)


I found an interesting problem on https://codeforces.com/problemset/problem/1154/E:
There are $n$ students standing in a row. Two coaches are forming two teams — the first coach chooses the first team and the second coach chooses the second team.

The $i$-th student has integer programming skill $a_i$. All programming skills are distinct and between $1$ and $n$, inclusive.

Firstly, the first coach will choose the student with maximum programming skill among all students not taken into any team, and $k$ closest students to the left of him and $k$ closest students to the right of him (if there are less than $k$ students to the left or to the right, all of them will be chosen). All students that are chosen leave the row and join the first team. Secondly, the second coach will make the same move (but all students chosen by him join the second team). Then again the first coach will make such move, and so on. This repeats until the row becomes empty (i. e. the process ends when each student becomes to some team).

Your problem is to determine which students will be taken into the first team and which students will be taken into the second team.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the number of students and the value determining the range of chosen students during each move, respectively.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the programming skill of the $i$-th student. It is guaranteed that all programming skills are distinct.

-----Output-----

Print a string of $n$ characters; $i$-th character should be 1 if $i$-th student joins the first team, or 2 otherwise.

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

Output
11111

Input
5 1
2 1 3 5 4

Output
22111

Input
7 1
7 2 1 3 5 4 6

Output
1121122

Input
5 1
2 4 5 3 1

Output
21112

-----Note-----

In the first example the first coach chooses the student on a position $3$, and the row becomes empty (all students join the first team).

In the second example the first coach chooses the student on...

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

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

ranked = list([x[1] for x in sorted([(-x[1], x[0]) for x in enumerate(row)])])

prev = list(range(-1, n - 1))
nxt = list(range(1, n + 1))
teams = [0] * n
current = 1
total = 0

for i in ranked:
    if total > n:
        break

    if not teams[i]:
        teams[i] = current
        took = 1

        # walk left
        count = k
        left = prev[i]
        while count > 0 and left != -1:
            teams[left] = current
            left = prev[left]
            took += 1
            count -= 1

        # walk right
        count = k
        right = nxt[i]
        while count > 0 and right != n:
            teams[right] = current
            right = nxt[right]
            took += 1
            count -= 1

        if left != -1:
            nxt[left] = right

        if right != n:
            prev[right] = left

        total += took
        current = 2 if current == 1 else 1

print(''.join(map(str, teams)))


I found an interesting problem on https://codeforces.com/problemset/problem/1154/F:
There are $n$ shovels in the nearby shop. The $i$-th shovel costs $a_i$ bourles.

Misha has to buy exactly $k$ shovels. Each shovel can be bought no more than once.

Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.

There are also $m$ special offers in the shop. The $j$-th of them is given as a pair $(x_j, y_j)$, and it means that if Misha buys exactly $x_j$ shovels during one purchase then $y_j$ most cheapest of them are for free (i.e. he will not pay for $y_j$ most cheapest shovels during the current purchase).

Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).

Your task is to calculate the minimum cost of buying $k$ shovels, if Misha buys them optimally.

-----Input-----

The first line of the input contains three integers $n, m$ and $k$ ($1 \le n, m \le 2 \cdot 10^5, 1 \le k \le min(n, 2000)$) — the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2 \cdot 10^5$), where $a_i$ is the cost of the $i$-th shovel.

The next $m$ lines contain special offers. The $j$-th of them is given as a pair of integers $(x_i, y_i)$ ($1 \le y_i \le x_i \le n$) and means that if Misha buys exactly $x_i$ shovels during some purchase, then he can take $y_i$ most cheapest of them for free.

-----Output-----

Print one integer — the minimum cost of buying $k$ shovels if Misha buys them optimally.

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

Output
7

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

Output
17

Input
5 1 4
2 5 7 4 6
5 4

Output
17

-----Note-----

In the first example Misha can buy shovels on positions $1$ and $4$ (both with costs $2$) during the first purchase and get one of them for free using the first or the third...

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

# http://codeforces.com/contest/1154/problem/F
# Explain: https://codeforces.com/blog/entry/66586?locale=en
from collections import defaultdict

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

n, m, k = input2int()
cost = list(input2int())
cost = sorted(cost)[:k]
# cost.reverse()
# print(cost)

preSum = defaultdict(int)
for i in range(k):
    preSum[i] = preSum[i - 1] + cost[i]
preSum[k] = preSum[k - 1]
# print(preSum)

offer = []
for i in range(m):
    x, y = input2int()
    if x <= k:
        offer.append((x, y))

# print(offer)

dp = defaultdict(lambda: int(1e9))
dp[0] = 0

for i in range(k + 1):
    if i < k:
        dp[i + 1] = min(dp[i] + cost[i], dp[i + 1])
    for _ in offer:
        x, y = _
        # print("i: {}, x: {}, y: {}".format(i, x, y))
        if i + x > k:
            continue
        # print('sum: {}'.format(preSum[i + x] - preSum[i + y]))
        dp[i + x] = min(dp[i + x], dp[i] + preSum[i + x - 1] - preSum[i + y - 1])
        # print(dp)

# print(dp)
print(dp[k])


I found an interesting problem on https://codeforces.com/problemset/problem/1154/G:
You are given an array $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$.

Your problem is to find such pair of indices $i, j$ ($1 \le i < j \le n$) that $lcm(a_i, a_j)$ is minimum possible.

$lcm(x, y)$ is the least common multiple of $x$ and $y$ (minimum positive number such that both $x$ and $y$ are divisors of this number).

-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 10^6$) — the number of elements in $a$.

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

-----Output-----

Print two integers $i$ and $j$ ($1 \le i < j \le n$) such that the value of $lcm(a_i, a_j)$ is minimum among all valid pairs $i, j$. If there are multiple answers, you can print any.

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

Output
1 2

Input
5
5 2 11 3 7

Output
2 4

Input
6
2 5 10 1 10 2

Output
1 4

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

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

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

    MAX = 10**7 + 1
    res = MAX * MAX

    #MAX_P = int(math.sqrt(MAX))
    MAX_P = 3163

    primes = []
    p = 2
    sieve = [True] * (MAX_P+1)
    while p < MAX_P:
        if sieve[p]:
            primes.append(p)
            k = 2
            while k * p < MAX_P:
                sieve[k * p] = False
                k += 1
        p += 1

    np = len(primes)
    cand1 = {}
    cand2 = {}
    ind1 = {}
    ind2 = {}

    res = MAX * MAX
    for index in range(n):
        val = a[index]
        if val >= res:
            continue

        divisors = [1]
        p = 0
        while val > 0 and p < np:
            while val % primes[p] == 0:
                divisors += [d * primes[p] for d in divisors]
                val //= primes[p]
            p += 1
        if val > 1:
            divisors += [d * val for d in divisors]

        for d in set(divisors):
            if d not in cand1:
                cand1[d] = a[index]
                ind1[d] = index
            else:
                if d not in cand2:
                    if a[index] < cand1[d]:
                        cand2[d] = cand1[d]
                        ind2[d] = ind1[d]
                        cand1[d] = a[index]
                        ind1[d] = index
                    else:
                        cand2[d] = a[index]
                        ind2[d] = index
                else:
                    if a[index] < cand1[d]:
                        cand2[d] = cand1[d]
                        ind2[d] = ind1[d]
                        cand1[d] = a[index]
                        ind1[d] = index
                    elif a[index] < cand2[d]:
                        cand2[d] = a[index]
                        ind2[d] = index
                    else:
                        continue
                if res > cand1[d] // d * cand2[d]:
                    x, y = ind1[d], ind2[d]
             ...


I found an interesting problem on https://codeforces.com/problemset/problem/1155/A:
You are given a string $s$ consisting of $n$ lowercase Latin letters.

Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position $3$ and ends in position $6$), but "aa" or "d" aren't substrings of this string. So the substring of the string $s$ from position $l$ to position $r$ is $s[l; r] = s_l s_{l + 1} \dots s_r$.

You have to choose exactly one of the substrings of the given string and reverse it (i. e. make $s[l; r] = s_r s_{r - 1} \dots s_l$) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.

If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring.

String $x$ is lexicographically less than string $y$, if either $x$ is a prefix of $y$ (and $x \ne y$), or there exists such $i$ ($1 \le i \le min(|x|, |y|)$), that $x_i < y_i$, and for any $j$ ($1 \le j < i$) $x_j = y_j$. Here $|a|$ denotes the length of the string $a$. The lexicographic comparison of strings is implemented by operator < in modern programming languages.

-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the length of $s$.

The second line of the input contains the string $s$ of length $n$ consisting only of lowercase Latin letters.

-----Output-----

If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices $l$ and $r$ ($1 \le l < r \le n$) denoting the substring you have to reverse. If there are multiple answers, you can print any.

-----Examples-----
Input
7
abacaba

Output
YES
2 5

Input
6
aabcfg

Output
NO

-----Note-----

In the first testcase the resulting string is "aacabba".

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

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

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

l = -1
for i in range(n - 1):
    if s[i] > s[i + 1]:
        l = i + 1
        break
if [i for i in s] == sorted([i for i in s]):
    print('NO')
else:
    print('YES')
    print(l, l + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1155/B:
A telephone number is a sequence of exactly $11$ digits such that its first digit is 8.

Vasya and Petya are playing a game. Initially they have a string $s$ of length $n$ ($n$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $s$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.

You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).

-----Input-----

The first line contains one integer $n$ ($13 \le n < 10^5$, $n$ is odd) — the length of string $s$.

The second line contains the string $s$ ($|s| = n$) consisting only of decimal digits.

-----Output-----

If Vasya has a strategy that guarantees him victory, print YES.

Otherwise print NO.

-----Examples-----
Input
13
8380011223344

Output
YES

Input
15
807345619350641

Output
NO

-----Note-----

In the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.

In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.

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

input()
s=input()
not8=[i for i, c in enumerate(s) if c!='8']
is8=[i for i, c in enumerate(s) if c=='8']

n=len(s)
moves=(n-11)//2

if moves >= len(not8):
    print('YES')
    raise SystemExit(0)
if moves >= len(is8):
    print('NO')
    raise SystemExit(0)

not8 = not8[moves:]
is8 = is8[moves:]

# print(not8, is8)

if is8[0] < not8[0]:
    print('YES')
    raise SystemExit(0)
else:
    print('NO')
    raise SystemExit(0)


I found an interesting problem on https://codeforces.com/problemset/problem/1155/C:
Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the $i$-th of them will start during the $x_i$-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes $x_1, x_2, \dots, x_n$, so he will be awake during each of these minutes (note that it does not matter if his alarm clock will ring during any other minute).

Ivan can choose two properties for the alarm clock — the first minute it will ring (let's denote it as $y$) and the interval between two consecutive signals (let's denote it by $p$). After the clock is set, it will ring during minutes $y, y + p, y + 2p, y + 3p$ and so on.

Ivan can choose any minute as the first one, but he cannot choose any arbitrary value of $p$. He has to pick it among the given values $p_1, p_2, \dots, p_m$ (his phone does not support any other options for this setting).

So Ivan has to choose the first minute $y$ when the alarm clock should start ringing and the interval between two consecutive signals $p_j$ in such a way that it will ring during all given minutes $x_1, x_2, \dots, x_n$ (and it does not matter if his alarm clock will ring in any other minutes).

Your task is to tell the first minute $y$ and the index $j$ such that if Ivan sets his alarm clock with properties $y$ and $p_j$ it will ring during all given minutes $x_1, x_2, \dots, x_n$ or say that it is impossible to choose such values of the given properties. If there are multiple answers, you can print any.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($2 \le n \le 3 \cdot 10^5, 1 \le m \le 3 \cdot 10^5$) — the number of events and the number of possible settings for the interval between signals.

The second line of the input contains $n$ integers $x_1, x_2, \dots, x_n$ ($1 \le x_i \le 10^{18}$), where $x_i$ is the minute when $i$-th event starts. It is guaranteed that all $x_i$ are given in increasing order (i. e. the condition $x_1 < x_2 < \dots <...

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

n, m = list(map(int, input().split()))
u = list(map(int, input().split()))
p = list(map(int, input().split()))
for i in range(1, n):
    u[i] -= u[0]
h = u[0]
u[0] = 0
def gsd(a, b):
    a, b = max(a, b), min(a, b)
    if b == 0:
        return a
    return gsd(b, a % b)
for i in range(1, n):
    u[i] = gsd(u[i], u[i - 1])
for i in range(m):
    if u[-1] % p[i] == 0:
        print("YES")
        print(h, i + 1)
        return
print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1155/D:
You are given an array $a$ consisting of $n$ integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.

You may choose at most one consecutive subarray of $a$ and multiply all values contained in this subarray by $x$. You want to maximize the beauty of array after applying at most one such operation.

-----Input-----

The first line contains two integers $n$ and $x$ ($1 \le n \le 3 \cdot 10^5, -100 \le x \le 100$) — the length of array $a$ and the integer $x$ respectively.

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

-----Output-----

Print one integer — the maximum possible beauty of array $a$ after multiplying all values belonging to some consecutive subarray $x$.

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

Output
22

Input
12 -3
1 3 3 7 1 3 3 7 1 3 3 7

Output
42

Input
5 10
-1 -2 -3 -4 -5

Output
0

-----Note-----

In the first test case we need to multiply the subarray [-2, 1, -6], and the array becomes [-3, 8, 4, -2, 12] with beauty 22 ([-3, 8, 4, -2, 12]).

In the second test case we don't need to multiply any subarray at all.

In the third test case no matter which subarray we multiply, the beauty of array will be equal to 0.

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()))
def factiry(arr,mul):
    curMax,mulMax,gloMax,cur = 0,0,0,0
    for i in range(n):
        curMax=max(arr[i]+curMax,0)
        mulMax = max(mulMax+(arr[i]*mul),curMax)
        cur = max(cur+arr[i],mulMax)
        gloMax = max(gloMax,cur)
    return (gloMax)
total = factiry(a,m)
print(total)


I found an interesting problem on https://codeforces.com/problemset/problem/1156/A:
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.

Future students will be asked just a single question. They are given a sequence of integer numbers $a_1, a_2, \dots, a_n$, each number is from $1$ to $3$ and $a_i \ne a_{i + 1}$ for each valid $i$. The $i$-th number represents a type of the $i$-th figure:

  circle;  isosceles triangle with the length of height equal to the length of base;  square.

The figures of the given sequence are placed somewhere on a Cartesian plane in such a way that:

  $(i + 1)$-th figure is inscribed into the $i$-th one;  each triangle base is parallel to OX;  the triangle is oriented in such a way that the vertex opposite to its base is at the top;  each square sides are parallel to the axes;  for each $i$ from $2$ to $n$ figure $i$ has the maximum possible length of side for triangle and square and maximum radius for circle.

Note that the construction is unique for some fixed position and size of just the first figure.

The task is to calculate the number of distinct points (not necessarily with integer coordinates) where figures touch. The trick is, however, that the number is sometimes infinite. But that won't make the task difficult for you, will it?

So can you pass the math test and enroll into Berland State University?

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 100$) — the number of figures.

The second line contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 3$, $a_i \ne a_{i + 1}$) — types of the figures.

-----Output-----

The first line should contain either the word "Infinite" if the number of distinct points where figures touch is infinite or "Finite" otherwise.

If the number is finite than print it in the second line. It's guaranteed that the number fits into 32-bit integer type.

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

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

def solve(l):
    helper = {
        1: {
            2: 3,
            3: 4
        },
        2: {
            1: 3,
            3: float('inf')
        },
        3: {
            1: 4,
            2: float('inf')
        }
    }
    p_i, a_i = 0, 1
    pp_i = -1
    ppre = None
    res = 0
    while a_i < len(l):
        if a_i > 1:
            pp_i += 1
            ppre = l[pp_i]
        pre, aft = l[p_i], l[a_i]
        res += helper[pre][aft]
        if res == float('inf'):
            return False, None
        if ppre is not None and (ppre, pre, aft) == (3, 1, 2):
            res -= 1
        p_i += 1
        a_i += 1
    return True, res

def __starting_point():
    _ = input()
    l = [int(x) for x in input().split()]
    is_finite, res = solve(l)
    if is_finite:
        print('Finite')
        print(res)
    else:
        print('Infinite')

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1156/B:
You are given a string, consisting of lowercase Latin letters.

A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions $(1, 2)$ — "ab" and $(2, 3)$ — "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.

Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.

If there are multiple answers, print any of them.

You also have to answer $T$ separate queries.

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 100$) — the number of queries.

Each of the next $T$ lines contains string $s$ $(1 \le |s| \le 100)$ — the string for the next query. It is guaranteed that it contains only lowercase Latin letters.

Note that in hacks you have to set $T = 1$.

-----Output-----

Print $T$ lines. The $i$-th line should contain the answer to the $i$-th query.

If the answer for the $i$-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.

If there are multiple answers, print any of them.

Otherwise print "No answer" for that query.

-----Example-----
Input
4
abcd
gg
codeforces
abaca

Output
cadb
gg
codfoerces
No answer

-----Note-----

In the first example answer "bdac" is also correct.

The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.

There are lots of valid answers for the third example.

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

from collections import Counter
import string

def valid(o):
    for x, y in zip(o, o[1:]):
        if abs(ord(x) - ord(y)) == 1:
            return False

    return True

def create(c, o):
    res = []
    for x in o:
        for j in range(c[x]):
            res.append(x)
    return res

T = int(input())
for _ in range(T):
    c = Counter(input())
    o = []
    o1 = string.ascii_lowercase[1::2] + string.ascii_lowercase[::2]
    o2 = string.ascii_lowercase[::2] + string.ascii_lowercase[1::2]

    s1 = create(c, o1)
    s2 = create(c, o2)

    if valid(s1):
        print(''.join(s1))
    elif valid(s2):
        print(''.join(s2))
    else:
        print('No answer')


I found an interesting problem on https://codeforces.com/problemset/problem/1156/C:
You are given a set of points $x_1$, $x_2$, ..., $x_n$ on the number line.

Two points $i$ and $j$ can be matched with each other if the following conditions hold:  neither $i$ nor $j$ is matched with any other point;  $|x_i - x_j| \ge z$.

What is the maximum number of pairs of points you can match with each other?

-----Input-----

The first line contains two integers $n$ and $z$ ($2 \le n \le 2 \cdot 10^5$, $1 \le z \le 10^9$) — the number of points and the constraint on the distance between matched points, respectively.

The second line contains $n$ integers $x_1$, $x_2$, ..., $x_n$ ($1 \le x_i \le 10^9$).

-----Output-----

Print one integer — the maximum number of pairs of points you can match with each other.

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

Output
2

Input
5 5
10 9 5 8 7

Output
1

-----Note-----

In the first example, you may match point $1$ with point $2$ ($|3 - 1| \ge 2$), and point $3$ with point $4$ ($|7 - 3| \ge 2$).

In the second example, you may match point $1$ with point $3$ ($|5 - 10| \ge 5$).

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

n, z = list(map(int, input().split()))
l = list(map(int, input().split()))
l = sorted(l)
wyn = 0
maly = 0
duzy = n // 2
zaj = [0] * n
while duzy < n:
	while maly < n:
		if zaj[maly] == 1:
			maly += 1
		else:
			break
	if l[duzy] - l[maly] >= z and zaj[duzy] == 0 and zaj[maly] == 0:
		wyn += 1
		maly += 1
		zaj[maly - 1] = 1
		zaj[duzy] = 1
	duzy += 1
print(wyn)


I found an interesting problem on https://codeforces.com/problemset/problem/1156/D:
You are given a tree (an undirected connected acyclic graph) consisting of $n$ vertices and $n - 1$ edges. A number is written on each edge, each number is either $0$ (let's call such edges $0$-edges) or $1$ (those are $1$-edges).

Let's call an ordered pair of vertices $(x, y)$ ($x \ne y$) valid if, while traversing the simple path from $x$ to $y$, we never go through a $0$-edge after going through a $1$-edge. Your task is to calculate the number of valid pairs in the tree.

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 200000$) — the number of vertices in the tree.

Then $n - 1$ lines follow, each denoting an edge of the tree. Each edge is represented by three integers $x_i$, $y_i$ and $c_i$ ($1 \le x_i, y_i \le n$, $0 \le c_i \le 1$, $x_i \ne y_i$) — the vertices connected by this edge and the number written on it, respectively.

It is guaranteed that the given edges form a tree.

-----Output-----

Print one integer — the number of valid pairs of vertices.

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

Output
34

-----Note-----

The picture corresponding to the first example:

[Image]

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

mod = 1000000007
eps = 10**-9

def main():
    import sys
    from collections import deque
    input = sys.stdin.readline

    class UnionFind():
        def __init__(self, n):
            self.n = n
            self.root = [-1] * (n + 1)
            self.rnk = [0] * (n + 1)

        def find_root(self, x):
            while self.root[x] >= 0:
                x = self.root[x]
            return x

        def unite(self, x, y):
            x = self.find_root(x)
            y = self.find_root(y)
            if x == y:
                return
            elif self.rnk[x] > self.rnk[y]:
                self.root[x] += self.root[y]
                self.root[y] = x
            else:
                self.root[y] += self.root[x]
                self.root[x] = y
                if self.rnk[x] == self.rnk[y]:
                    self.rnk[y] += 1

        def isSameGroup(self, x, y):
            return self.find_root(x) == self.find_root(y)

        def size(self, x):
            return -self.root[self.find_root(x)]

    N = int(input())
    adj = [[] for _ in range(N+1)]
    UF0 = UnionFind(N+1)
    UF1 = UnionFind(N+1)
    for _ in range(N-1):
        a, b, c = list(map(int, input().split()))
        adj[a].append((b, c))
        adj[b].append((a, c))
        if c == 0:
            UF0.unite(a, b)
        else:
            UF1.unite(a, b)

    ans = 0
    roots = set()
    for v in range(1, N+1):
        r = UF1.find_root(v)
        if r not in roots:
            roots.add(r)
            s = -UF1.root[r]
            ans += s * (s-1)
    #print(ans)

    roots = set()
    for v in range(1, N+1):
        r = UF0.find_root(v)
        if r not in roots:
            roots.add(r)
            s = -UF0.root[r]
            ans += s * (s-1)
    #print(ans)

    for v in range(1, N+1):
        W = 0
        B = 0
        flg0 = 0
        flg1 = 0
        for u, c in adj[v]:
            if flg0 and flg1:
                break
            if c == 0:
                if flg0:
                    continue
                W +=...


I found an interesting problem on https://codeforces.com/problemset/problem/1156/E:
You are given a permutation $p$ of $n$ integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once).

Let's call some subsegment $p[l, r]$ of this permutation special if $p_l + p_r = \max \limits_{i = l}^{r} p_i$. Please calculate the number of special subsegments.

-----Input-----

The first line contains one integer $n$ ($3 \le n \le 2 \cdot 10^5$).

The second line contains $n$ integers $p_1$, $p_2$, ..., $p_n$ ($1 \le p_i \le n$). All these integers are pairwise distinct.

-----Output-----

Print the number of special subsegments of the given permutation.

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

Output
2

Input
3
1 3 2

Output
1

-----Note-----

Special subsegments in the first example are $[1, 5]$ and $[1, 3]$.

The only special subsegment in the second example is $[1, 3]$.

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

n=int(input())
ns=[int(x) for x in input().split()]
# n=200000
# ns=[x+1 for x in range(n)]

"""
st=[[ns[i]]for i in range(n)]
for l in range(1,20):
    for i in range(0,n+10,2**l):
        if i+2**(l-1)<len(st):
            st[i].append(max(st[i][-1],st[i+2**(l-1)][-1]))
def get_sum(l,r):
    ans,i=st[l][0],1
    while l+2**i<=r and i<len(st[l]):
        ans=st[l][i]
        i+=1
    rr=l+2**(i-1)-1
    if rr>=r:
        return ans
    else:
        return max(ans,get_sum(rr+1,r))
"""
# print(time.time()-tm)
# import random as rd
#
# n=10000
# s=set()
# ns=[]
# for i in range(n):
#     s.add(i+1)
# for i in range(n):
#     x=rd.sample(s,1)
#     ns.append(x[0])
#     s.remove(x[0])
# print(ns)
# quit()
# ns=[5, 8, 4, 1, 6, 7, 2, 3]
# n=len(ns)

maxx=max(ns)+10
lst=[None]*n
nxt=[None]*n
tmp=[(-1,maxx)]
mp=[False]*n
wh=[None]*(n+1)
for i in range(n):
    c=ns[i]
    while tmp[-1][1]<=c:
        tmp.pop()
    lst[i]=tmp[-1][0]
    tmp.append((i,c))
tmp=[(n,maxx)]
for i in range(n):
    i=n-i-1
    c=ns[i]
    while tmp[-1][1]<=c:
        tmp.pop()
    nxt[i]=tmp[-1][0]
    tmp.append((i,c))
lm={}
for i in range(n):
    lm[(lst[i]+1,nxt[i]-1)]=ns[i]
# print(lm)

for i in range(n):
    wh[ns[i]]=i

def check(i,m,lm):
    f=ns[m]-ns[i]
    f=wh[f]
    if lm[0]<=f<=lm[1]:
        return True
    return False
# print(wh)
ans=0
rec=[(0,n-1)]

def get():
    if len(rec)==0:
        return False
    l,r=rec.pop()
    if r-l+1<=2:
        return True
    nonlocal ans
    x=lm[(l,r)]
    lc=wh[x]
    if lc<(l+r)//2:
        for i in range(l,lc):
            c=ns[i]
            c=ns[lc]-c
            c=wh[c]
            if lc<=c<=r:
                ans+=1
    else:
        for i in range(lc+1,r+1):
            c=ns[i]
            c=ns[lc]-c
            c=wh[c]
            if l<=c<=lc:
                ans+=1
    rec.append((l,lc-1))
    rec.append((lc+1,r))
while len(rec)>0:
    get()
print(ans)
quit()

get(0,n-1)
print(ans)
quit()

x=n
while x>=1:
    lc=wh[x]
    mp[lc]=True
    l,r=lc-1,lc+1
    while l>lst[lc] and...


I found an interesting problem on https://codeforces.com/problemset/problem/1156/G:
Let's analyze a program written on some strange programming language. The variables in this language have names consisting of $1$ to $4$ characters, and each character is a lowercase or an uppercase Latin letter, or a digit. There is an extra constraint that the first character should not be a digit.

There are four types of operations in the program, each denoted by one of the characters: $, ^, # or &.

Each line of the program has one of the following formats:   <lvalue>=<rvalue>, where <lvalue> and <rvalue> are valid variable names;  <lvalue>=<arg1><op><arg2>, where <lvalue>, <arg1> and <arg2> are valid variable names, and <op> is an operation character.

The program is executed line-by-line, and the result of execution is stored in a variable having the name res. If res is never assigned in the program, then the result will be equal to the value of res before running the program.

Two programs are called equivalent if no matter which operations do characters $, ^, # and & denote (but, obviously, performing the same operation on the same arguments gives the same result) and which values do variables have before execution of program, the value of res after running the first program is equal to the value of res after running the second program (the programs are executed independently).

You are given a program consisting of $n$ lines. Your task is to write a program consisting of minimum possible number of lines that is equivalent to the program you are given.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 1000$) — the number of lines in the program.

Then $n$ lines follow — the program itself. Each line corresponds to the format described in the statement and has no extra whitespaces.

-----Output-----

In the first line print $k$ — the minimum number of lines in the equivalent program.

Then print $k$ lines without any whitespaces — an equivalent program having exactly $k$ lines, in the same format it is described in the...

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

#!/usr/bin/env python3

import sys
sys.setrecursionlimit(65536)

vars, reserved = {}, set()
rules, irules, R = [], {}, 0

def wwj():
	n__ = 0
	def dak():
		nonlocal n__
		while 'a' + str(n__) in reserved:
			n__ += 1
		n__ += 1
		return 'a' + str(n__ - 1)
	return dak

next_var = wwj()

L = int(input())
for i in range(L):
	k, v = input().split('=')
	if v.isidentifier():
		if v in vars:
			vars[k] = vars[v]
		else:
			vars[k] = v
			reserved.add(v)
	else:
		j = [i for i in range(len(v)) if not v[i].isalnum()][0]
		v1, op, v2 = vars.get(v[:j], v[:j]), v[j], vars.get(v[j + 1:], v[j + 1:])
		r = (op, v1, v2)
		if r not in irules:
			rules.append(r)
			irules[r] = R
			R += 1
		vars[k] = irules[r]

if vars.get('res', 'res') == 'res':
	print(0)
	return

resolve = {}
output = []

def interprete(v, name = None):
	if isinstance(v, str):
		return v
	if v in resolve:
		return resolve[v]
	op, v1, v2 = rules[v]
	u1, u2 = interprete(v1), interprete(v2)
	if name is None:
		name = next_var()
	resolve[v] = name
	output.append('{}={}{}{}'.format(name, u1, op, u2))
	return name

R = interprete(vars['res'], 'res')
if R != 'res':
	output.append('res={}'.format(R))

print(len(output), '\n'.join(output), sep = '\n')


I found an interesting problem on https://codeforces.com/problemset/problem/1157/A:
Let's denote a function $f(x)$ in such a way: we add $1$ to $x$, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,   $f(599) = 6$: $599 + 1 = 600 \rightarrow 60 \rightarrow 6$;  $f(7) = 8$: $7 + 1 = 8$;  $f(9) = 1$: $9 + 1 = 10 \rightarrow 1$;  $f(10099) = 101$: $10099 + 1 = 10100 \rightarrow 1010 \rightarrow 101$.

We say that some number $y$ is reachable from $x$ if we can apply function $f$ to $x$ some (possibly zero) times so that we get $y$ as a result. For example, $102$ is reachable from $10098$ because $f(f(f(10098))) = f(f(10099)) = f(101) = 102$; and any number is reachable from itself.

You are given a number $n$; your task is to count how many different numbers are reachable from $n$.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 10^9$).

-----Output-----

Print one integer: the number of different numbers that are reachable from $n$.

-----Examples-----
Input
1098

Output
20

Input
10

Output
19

-----Note-----

The numbers that are reachable from $1098$ are:

$1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1098, 1099$.

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

from collections import defaultdict
n = int(input())
d = defaultdict(int)
c = 1
d[n] = 1
while True:
    n = n+1
    while n%10==0:
        n= n/10

    if d[n]==1:
        break
    else:
        d[n]=1
        c+=1

print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/1157/B:
You are given a long decimal number $a$ consisting of $n$ digits from $1$ to $9$. You also have a function $f$ that maps every digit from $1$ to $9$ to some (possibly the same) digit from $1$ to $9$.

You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in $a$, and replace each digit $x$ from this segment with $f(x)$. For example, if $a = 1337$, $f(1) = 1$, $f(3) = 5$, $f(7) = 3$, and you choose the segment consisting of three rightmost digits, you get $1553$ as the result.

What is the maximum possible number you can obtain applying this operation no more than once?

-----Input-----

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

The second line contains a string of $n$ characters, denoting the number $a$. Each character is a decimal digit from $1$ to $9$.

The third line contains exactly $9$ integers $f(1)$, $f(2)$, ..., $f(9)$ ($1 \le f(i) \le 9$).

-----Output-----

Print the maximum number you can get after applying the operation described in the statement no more than once.

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

Output
1557

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

Output
99999

Input
2
33
1 1 1 1 1 1 1 1 1

Output
33

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

#	!/usr/bin/env python3
#	encoding: UTF-8
#	Modified: <26/Apr/2019 08:18:47 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT),Gwalior

# ///==========Libraries, Constants and Functions=============///

import sys

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return map(int, sys.stdin.readline().split())

def input(): return sys.stdin.readline().strip()

# ///==========MAIN=============///

def main():
    n = int(input())
    a = list(input())
    f = get_array()
    flag = False
    for i in range(n):
        x = int(a[i])
        if (x < f[x - 1]):
            flag = True
            a[i] = f[x - 1]
        else:
            if flag == True and x > f[x - 1]:
                break
    print(*a, sep='')

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1157/C1:
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).

You are given a sequence $a$ consisting of $n$ integers. All these integers are distinct, each value from $1$ to $n$ appears in the sequence exactly once.

You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).

For example, for the sequence $[2, 1, 5, 4, 3]$ the answer is $4$ (you take $2$ and the sequence becomes $[1, 5, 4, 3]$, then you take the rightmost element $3$ and the sequence becomes $[1, 5, 4]$, then you take $4$ and the sequence becomes $[1, 5]$ and then you take $5$ and the sequence becomes $[1]$, the obtained increasing sequence is $[2, 3, 4, 5]$).

-----Input-----

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

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the $i$-th element of $a$. All these integers are pairwise distinct.

-----Output-----

In the first line of the output print $k$ — the maximum number of elements in a strictly increasing sequence you can obtain.

In the second line print a string $s$ of length $k$, where the $j$-th character of this string $s_j$ should be 'L' if you take the leftmost element during the $j$-th move and 'R' otherwise. If there are multiple answers, you can print any.

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

Output
4
LRRR

Input
7
1 3 5 6 7 4 2

Output
7
LRLRLLL

Input
3
1 2 3

Output
3
LLL

Input
4
1 2 4 3

Output
4
LLRL

-----Note-----

The first example is described in the problem statement.

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

from collections import *

n = int(input())

M = deque(list(map(int, input().split())))

ans = []
last = None
while len(M) > 0:
    if ans == []:
        if M[-1] <= M[0]:
            ans += ['R']
            last = M[-1]
            M.pop()
        else:
            ans += ['L']
            last = M[0]
            M.popleft()
    else:
        if M[-1] <= last and M[0] <= last:
            break

        if M[-1] <= last:
            ans += ["L"]
            last = M[0]
            M.popleft()
            continue

        if M[0] <= last:
            ans += ['R']
            last = M[-1]
            M.pop()
            continue

        if M[0] <= M[-1]:
            ans += ["L"]
            last = M[0]
            M.popleft()
        elif M[-1] <= M[0]:
            ans += ["R"]
            last = M[-1]
            M.pop()

print(len(ans))
print("".join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1157/C2:
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).

You are given a sequence $a$ consisting of $n$ integers.

You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).

For example, for the sequence $[1, 2, 4, 3, 2]$ the answer is $4$ (you take $1$ and the sequence becomes $[2, 4, 3, 2]$, then you take the rightmost element $2$ and the sequence becomes $[2, 4, 3]$, then you take $3$ and the sequence becomes $[2, 4]$ and then you take $4$ and the sequence becomes $[2]$, the obtained increasing sequence is $[1, 2, 3, 4]$).

-----Input-----

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

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

-----Output-----

In the first line of the output print $k$ — the maximum number of elements in a strictly increasing sequence you can obtain.

In the second line print a string $s$ of length $k$, where the $j$-th character of this string $s_j$ should be 'L' if you take the leftmost element during the $j$-th move and 'R' otherwise. If there are multiple answers, you can print any.

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

Output
4
LRRR

Input
7
1 3 5 6 5 4 2

Output
6
LRLRRR

Input
3
2 2 2

Output
1
R

Input
4
1 2 4 3

Output
4
LLRR

-----Note-----

The first example is described in the problem statement.

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

def search(l, r, pr):
	posl = ""
	fl = True
	while l <= r:
		if sp[l] < sp[r]:
			if sp[l] > pr:
				pr = sp[l]
				l += 1
				posl += "L"
			elif sp[r] > pr:
				pr = sp[r]
				r -= 1
				posl += "R"
			else:
				fl = False
		elif sp[l] > sp[r]:
			if sp[r] > pr:
				pr = sp[r]
				r -= 1
				posl += "R"
			elif sp[l] > pr:
				pr = sp[l]
				l += 1
				posl += "L"
			else:
				fl = False
		else:
			if sp[l] > pr:
				fst = search(l + 1, r, sp[l]) + "L"
				sec = search(l, r - 1, sp[r]) + "R"
				if len(sec) > len(fst):
					posl += sec
				else:
					posl += fst
			fl = False
		if not fl:
			break
	return posl

n = int(input())
sp = list(map(int, input().split()))
pr = 0
posl = ""
l = 0
r = n - 1
new = search(l, r, 0)
print(len(new))
print(new)


I found an interesting problem on https://codeforces.com/problemset/problem/1157/D:
Polycarp has to solve exactly $n$ problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in $k$ days. It means that Polycarp has exactly $k$ days for training!

Polycarp doesn't want to procrastinate, so he wants to solve at least one problem during each of $k$ days. He also doesn't want to overwork, so if he solves $x$ problems during some day, he should solve no more than $2x$ problems during the next day. And, at last, he wants to improve his skill, so if he solves $x$ problems during some day, he should solve at least $x+1$ problem during the next day.

More formally: let $[a_1, a_2, \dots, a_k]$ be the array of numbers of problems solved by Polycarp. The $i$-th element of this array is the number of problems Polycarp solves during the $i$-th day of his training. Then the following conditions must be satisfied:   sum of all $a_i$ for $i$ from $1$ to $k$ should be $n$;  $a_i$ should be greater than zero for each $i$ from $1$ to $k$;  the condition $a_i < a_{i + 1} \le 2 a_i$ should be satisfied for each $i$ from $1$ to $k-1$.

Your problem is to find any array $a$ of length $k$ satisfying the conditions above or say that it is impossible to do it.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n \le 10^9, 1 \le k \le 10^5$) — the number of problems Polycarp wants to solve and the number of days Polycarp wants to train.

-----Output-----

If it is impossible to find any array $a$ of length $k$ satisfying Polycarp's rules of training, print "NO" in the first line.

Otherwise print "YES" in the first line, then print $k$ integers $a_1, a_2, \dots, a_k$ in the second line, where $a_i$ should be the number of problems Polycarp should solve during the $i$-th day. If there are multiple answers, you can print any.

-----Examples-----
Input
26 6

Output
YES
1 2 4 5 6 8

Input
8 3

Output
NO

Input
1 1

Output
YES
1

Input
9 4

Output
NO

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

x,y=list(map(int,input().split()))
if(x==8 and y==3):
    print('NO')
    return
if(x==4 and y==2):
    print('NO')
    return

z=[]
leftover=0
day=0
mini=((y*(y+1)))//2
if(mini>x):
    print('NO')
    return
elif(mini==x):
    for i in range(y):
        z.append(i+1)
else:
    leftover=x-mini
    day=leftover//y
    for i in range(y):
        z.append(i+1+day)
    leftover=leftover%y
    while(-1*leftover!=0):
        z[-1*leftover]=z[-1*leftover]+1
        leftover=leftover-1

for i in range(len(z)-1):
    if(z[i+1]>2*z[i]):
        z[i+1]=z[i+1]-1
        z[-1]=z[-1]+1
print('YES')
print(' '.join(map(str,z)))


I found an interesting problem on https://codeforces.com/problemset/problem/1157/E:
You are given two arrays $a$ and $b$, both of length $n$. All elements of both arrays are from $0$ to $n-1$.

You can reorder elements of the array $b$ (if you want, you may leave the order of elements as it is). After that, let array $c$ be the array of length $n$, the $i$-th element of this array is $c_i = (a_i + b_i) \% n$, where $x \% y$ is $x$ modulo $y$.

Your task is to reorder elements of the array $b$ to obtain the lexicographically minimum possible array $c$.

Array $x$ of length $n$ is lexicographically less than array $y$ of length $n$, if there exists such $i$ ($1 \le i \le n$), that $x_i < y_i$, and for any $j$ ($1 \le j < i$) $x_j = y_j$.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of elements in $a$, $b$ and $c$.

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

The third line of the input contains $n$ integers $b_1, b_2, \dots, b_n$ ($0 \le b_i < n$), where $b_i$ is the $i$-th element of $b$.

-----Output-----

Print the lexicographically minimum possible array $c$. Recall that your task is to reorder elements of the array $b$ and obtain the lexicographically minimum possible array $c$, where the $i$-th element of $c$ is $c_i = (a_i + b_i) \% n$.

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

Output
1 0 0 2

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

Output
0 0 0 1 0 2 4

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

from collections import Counter
n=int(input())
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
d=Counter(b)
ans=[]
e=list(range(1,n))+[0]
for i in a:
    v=(n-i)%n
    while d[v]==0:
        if d[e[v]]==0:
            e[v]=e[e[v]]
        v=e[v]
    d[v]-=1
    ans.append((i+v)%n)
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1157/F:
There are $n$ people in a row. The height of the $i$-th person is $a_i$. You can choose any subset of these people and try to arrange them into a balanced circle.

A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than $1$. For example, let heights of chosen people be $[a_{i_1}, a_{i_2}, \dots, a_{i_k}]$, where $k$ is the number of people you choose. Then the condition $|a_{i_j} - a_{i_{j + 1}}| \le 1$ should be satisfied for all $j$ from $1$ to $k-1$ and the condition $|a_{i_1} - a_{i_k}| \le 1$ should be also satisfied. $|x|$ means the absolute value of $x$. It is obvious that the circle consisting of one person is balanced.

Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.

-----Input-----

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

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2 \cdot 10^5$), where $a_i$ is the height of the $i$-th person.

-----Output-----

In the first line of the output print $k$ — the number of people in the maximum balanced circle.

In the second line print $k$ integers $res_1, res_2, \dots, res_k$, where $res_j$ is the height of the $j$-th person in the maximum balanced circle. The condition $|res_{j} - res_{j + 1}| \le 1$ should be satisfied for all $j$ from $1$ to $k-1$ and the condition $|res_{1} - res_{k}| \le 1$ should be also satisfied.

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

Output
5
2 1 1 2 3

Input
5
3 7 5 1 5

Output
2
5 5

Input
3
5 1 4

Output
2
4 5

Input
7
2 2 3 2 1 2 2

Output
7
1 2 2 2 2 3 2

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

def solve():
    n = int(input())
    a = sorted(map(int, input().split()))
    ans = (1, 0)
    cur = [a[0]]
    for i in range(1, n):
        if a[i] - a[i - 1] > 1:
            ans = max(ans, (len(cur), i - 1))
            cur.clear()
        elif a[i - 1] < a[i] and (i == n - 1 or a[i] < a[i + 1]):
            cur.append(a[i])
            ans = max(ans, (len(cur), i))
            cur.clear()
        cur.append(a[i])
    ans = max(ans, (len(cur), n - 1))
    print(ans[0])
    ans1 = []
    ans2 = []
    for i in a[ans[1]-ans[0]+1:ans[1]+1]:
        if not ans1 or ans1[-1] != i:
            ans1.append(i)
        else:
            ans2.append(i)
    print(*(ans1 + ans2[::-1]))

for _ in range(1):
    solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1157/G:
You are given a binary matrix $a$ of size $n \times m$. A binary matrix is a matrix where each element is either $0$ or $1$.

You may perform some (possibly zero) operations with this matrix. During each operation you can inverse the row of this matrix or a column of this matrix. Formally, inverting a row is changing all values in this row to the opposite ($0$ to $1$, $1$ to $0$). Inverting a column is changing all values in this column to the opposite.

Your task is to sort the initial matrix by some sequence of such operations. The matrix is considered sorted if the array $[a_{1, 1}, a_{1, 2}, \dots, a_{1, m}, a_{2, 1}, a_{2, 2}, \dots, a_{2, m}, \dots, a_{n, m - 1}, a_{n, m}]$ is sorted in non-descending order.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 200$) — the number of rows and the number of columns in the matrix.

The next $n$ lines contain $m$ integers each. The $j$-th element in the $i$-th line is $a_{i, j}$ ($0 \le a_{i, j} \le 1$) — the element of $a$ at position $(i, j)$.

-----Output-----

If it is impossible to obtain a sorted matrix, print "NO" in the first line.

Otherwise print "YES" in the first line. In the second line print a string $r$ of length $n$. The $i$-th character $r_i$ of this string should be '1' if the $i$-th row of the matrix is inverted and '0' otherwise. In the third line print a string $c$ of length $m$. The $j$-th character $c_j$ of this string should be '1' if the $j$-th column of the matrix is inverted and '0' otherwise. If there are multiple answers, you can print any.

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

Output
YES
00
10

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

Output
YES
010
0000

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

Output
NO

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

import sys
input = sys.stdin.readline

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

for i in range(m):
    #一行目をi-1まで0にする

    ANSR=[0]*n
    ANSC=[0]*m

    for j in range(i):
        if A[0][j]==1:
            ANSC[j]=1

    for j in range(i,m):
        if A[0][j]==0:
            ANSC[j]=1

    for r in range(1,n):
        B=set()
        for c in range(m):
            if ANSC[c]==0:
                B.add(A[r][c])
            else:
                B.add(1-A[r][c])

        if len(B)>=2:
            break
        if max(B)==0:
            ANSR[r]=1

    else:
        print("YES")
        print("".join(map(str,ANSR)))
        print("".join(map(str,ANSC)))
        return

ANSR=[0]*n
ANSC=[0]*m

for j in range(m):
    if A[0][j]==1:
        ANSC[j]=1

flag=0
for r in range(1,n):
    if flag==0:
        B=[]
        for c in range(m):
            if ANSC[c]==0:
                B.append(A[r][c])
            else:
                B.append(1-A[r][c])

        if max(B)==0:
            continue
        elif min(B)==1:
            ANSR[r]=1
            continue
        else:
            OI=B.index(1)
            if min(B[OI:])==1:
                flag=1
                continue

            OO=B.index(0)
            if max(B[OO:])==0:
                flag=1
                ANSR[r]=1
                continue

            else:
                print("NO")
                return

    else:

        B=set()
        for c in range(m):
            if ANSC[c]==0:
                B.add(A[r][c])
            else:
                B.add(1-A[r][c])

        if len(B)>=2:
            break
        if max(B)==0:
            ANSR[r]=1

else:
    print("YES")
    print("".join(map(str,ANSR)))
    print("".join(map(str,ANSC)))
    return

print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1158/B:
Let $s$ be some string consisting of symbols "0" or "1". Let's call a string $t$ a substring of string $s$, if there exists such number $1 \leq l \leq |s| - |t| + 1$ that $t = s_l s_{l+1} \ldots s_{l + |t| - 1}$. Let's call a substring $t$ of string $s$ unique, if there exist only one such $l$.

For example, let $s = $"1010111". A string $t = $"010" is an unique substring of $s$, because $l = 2$ is the only one suitable number. But, for example $t = $"10" isn't a unique substring of $s$, because $l = 1$ and $l = 3$ are suitable. And for example $t =$"00" at all isn't a substring of $s$, because there is no suitable $l$.

Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols "0" and "1", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him.

You are given $2$ positive integers $n$ and $k$, such that $(n \bmod 2) = (k \bmod 2)$, where $(x \bmod 2)$ is operation of taking remainder of $x$ by dividing on $2$. Find any string $s$ consisting of $n$ symbols "0" or "1", such that the length of its minimal unique substring is equal to $k$.

-----Input-----

The first line contains two integers $n$ and $k$, separated by spaces ($1 \leq k \leq n \leq 100\,000$, $(k \bmod 2) = (n \bmod 2)$).

-----Output-----

Print a string $s$ of length $n$, consisting of symbols "0" and "1". Minimal length of the unique substring of $s$ should be equal to $k$. You can find any suitable string. It is guaranteed, that there exists at least one such string.

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

Output
1111
Input
5 3

Output
01010
Input
7 3

Output
1011011

-----Note-----

In the first test, it's easy to see, that the only unique substring of string $s = $"1111" is all string $s$, which has length $4$.

In the second test a string $s = $"01010" has minimal unique substring $t =$"101", which has length $3$.

In the third test a string $s = $"1011011" has minimal unique substring $t...

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/1159/A:
Vasya has a pile, that consists of some number of stones. $n$ times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.

You are given $n$ operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.

-----Input-----

The first line contains one positive integer $n$ — the number of operations, that have been made by Vasya ($1 \leq n \leq 100$).

The next line contains the string $s$, consisting of $n$ symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on $i$-th operation, $s_i$ is equal to "-" (without quotes), if added, $s_i$ is equal to "+" (without quotes).

-----Output-----

Print one integer — the minimal possible number of stones that can be in the pile after these $n$ operations.

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

Output
0
Input
4
++++

Output
4
Input
2
-+

Output
1
Input
5
++-++

Output
3

-----Note-----

In the first test, if Vasya had $3$ stones in the pile at the beginning, after making operations the number of stones will be equal to $0$. It is impossible to have less number of piles, so the answer is $0$. Please notice, that the number of stones at the beginning can't be less, than $3$, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).

In the second test, if Vasya had $0$ stones in the pile at the beginning, after making operations the number of stones will be equal to $4$. It is impossible to have less number of piles because after making $4$ operations the number of stones in the pile increases on $4$ stones. So, the answer is $4$.

In the third test, if Vasya had $1$ stone in the pile at the beginning, after making operations the number of stones will be equal to $1$. It can be proved, that it is impossible to have less number of stones after making the operations.

In the fourth test, if Vasya had $0$ stones in the pile at the...

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

def go():
    n = int(input())
    a = [i for i in input()]
    x = 0
    for i in a:
        if i == '-':
            x = max(0, x - 1)
        else:
            x += 1
    return x

print(go())