I found an interesting problem on https://codeforces.com/problemset/problem/1221/E:
Alice and Bob play a game. Initially they have a string $s_1, s_2, \dots, s_n$, consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must select a substing of length $a$, and Bob must select a substring of length $b$. It is guaranteed that $a > b$.

For example, if $s =$ ...X.. and $a = 3$, $b = 2$, then after Alice's move string can turn only into XXXX... And if it's Bob's turn and the string $s =$ ...X.., then after Bob's move the string can turn into XX.X.., .XXX.. or ...XXX.

Whoever is unable to make a move, loses. You have to determine who wins if they both play optimally.

You have to answer $q$ independent queries.

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 3 \cdot 10^5$) — the number of queries.

The first line of each query contains two integers $a$ and $b$ ($1 \le b < a \le 3 \cdot 10^5$).

The second line of each query contains the string $s$ ($1 \le |s| \le 3 \cdot 10^5$), consisting of only characters . and X.

It is guaranteed that sum of all $|s|$ over all queries not exceed $3 \cdot 10^5$.

-----Output-----

For each test case print YES if Alice can win and NO otherwise.

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

-----Example-----
Input
3
3 2
XX......XX...X
4 2
X...X.X..X
5 3
.......X..X

Output
YES
NO
YES

-----Note-----

In the first query Alice can select substring $s_3 \dots s_5$. After that $s$ turns into XXXXX...XX...X. After that, no matter what move Bob makes, Alice can make the move (this will be her second move), but Bob can't make his second move.

In the second query Alice can not win because she cannot even make one move.

In the third query Alice can choose substring $s_2 \dots s_6$. After that $s$ turns into .XXXXX.X..X, and Bob can't make a move after that.

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

import os, sys

# zeilen = [l.strip() for l in sys.stdin.readlines()]

q = int(sys.stdin.readline().strip())

for _ in range(q):
  a, b = list(map(int, sys.stdin.readline().strip().split()))
  word = sys.stdin.readline().strip()
  gaps = sorted([len(gap) for gap in word.split('X') if len(gap)>= b])
  if len(gaps) == 0:
    print('NO')
  elif gaps[0] < a:
    print('NO')
  elif len(gaps) > 1 and gaps[-2] >= 2*b:
    print('NO')
  elif gaps[-1] < 2*b: # no problematic, need only count
    print('YES' if (len(gaps) % 2) else 'NO')
  else: # exactly one problematic gap
    p = gaps[-1]
    if (len(gaps) % 2): # A tries to make this gap into zero or two
      if p <= (a + 2*b - 2): # short enough for 0
        print('YES')
      elif p < 3*a: # we have to try two
        print('NO') # not long enough
      elif p > (a + 4*b - 2): # too long
        print('NO')
      else:
        print('YES')
    else: # A tries to make this gap into one
      if p < 2*a: # too short
        print('NO')
      elif p > (a + 3*b - 2):# too long
        print('NO')
      else:
        print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/1223/A:
Let's denote correct match equation (we will denote it as CME) an equation $a + b = c$ there all integers $a$, $b$ and $c$ are greater than zero.

For example, equations $2 + 2 = 4$ (||+||=||||) and $1 + 2 = 3$ (|+||=|||) are CME but equations $1 + 2 = 4$ (|+||=||||), $2 + 2 = 3$ (||+||=|||), and $0 + 1 = 1$ (+|=|) are not.

Now, you have $n$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!

For example, if $n = 2$, you can buy two matches and assemble |+|=||, and if $n = 5$ you can buy one match and assemble ||+|=|||.  [Image]

Calculate the minimum number of matches which you have to buy for assembling CME.

Note, that you have to answer $q$ independent queries.

-----Input-----

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

The only line of each query contains one integer $n$ ($2 \le n \le 10^9$) — the number of matches.

-----Output-----

For each test case print one integer in single line — the minimum number of matches which you have to buy for assembling CME.

-----Example-----
Input
4
2
5
8
11

Output
2
1
0
1

-----Note-----

The first and second queries are explained in the statement.

In the third query, you can assemble $1 + 3 = 4$ (|+|||=||||) without buying matches.

In the fourth query, buy one match and assemble $2 + 4 = 6$ (||+||||=||||||).

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

n = int(input())
for i in range(n):
    p=int(input())
    if p ==2:
        print(2)
    else:
        print(p%2)


I found an interesting problem on https://codeforces.com/problemset/problem/1223/C:
You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!

You have $n$ tickets to sell. The price of the $i$-th ticket is $p_i$. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them to the order you chose:  The $x\%$ of the price of each the $a$-th sold ticket ($a$-th, $2a$-th, $3a$-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources.  The $y\%$ of the price of each the $b$-th sold ticket ($b$-th, $2b$-th, $3b$-th and so on) in the order you chose is aimed for pollution abatement.

If the ticket is in both programs then the $(x + y) \%$ are used for environmental activities. Also, it's known that all prices are multiples of $100$, so there is no need in any rounding.

For example, if you'd like to sell tickets with prices $[400, 100, 300, 200]$ and the cinema pays $10\%$ of each $2$-nd sold ticket and $20\%$ of each $3$-rd sold ticket, then arranging them in order $[100, 200, 300, 400]$ will lead to contribution equal to $100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120$. But arranging them in order $[100, 300, 400, 200]$ will lead to $100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130$.

Nature can't wait, so you decided to change the order of tickets in such a way, so that the total contribution to programs will reach at least $k$ in minimum number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least $k$.

-----Input-----

The first line contains a single integer $q$ ($1 \le q \le 100$) — the number of independent queries. Each query consists of $5$ lines.

The first line of each query contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of tickets.

The...

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

from math import gcd
def check(m):
    nonlocal p, k, x, a, y, b
    ans  = 0
    kx = m // a
    ky = m // b
    kxy = m // (a * b // gcd(a, b))
    kx -= kxy
    ky -= kxy
    for i in range(kxy):
        ans += p[i] * (x + y) // 100
        #print(p[i], end = ' ')
    if x >= y:
        for i in range(kxy, kxy + kx):
            ans += p[i] * x // 100
            #print(p[i],end = ' ')

        for i in range(kxy + kx, kxy + kx + ky):
            ans += p[i] * y // 100
            #print(p[i],end = ' ')
    else:
        for i in range(kxy, kxy + ky):
            ans += p[i] * y // 100
    #        print(p[i],end = ' ')

        for i in range(kxy + ky, kxy + kx + ky):
            ans += p[i] * x // 100
     #       print(p[i],end = ' ')
    #print("!!!!")
    #print('III', ans, m)
    return ans

p = []
for i in range(int(input())):
    n = int(input())
    p = sorted(map(int, input().split()), reverse=True)
    x, a = list(map(int, input().split()))
    y, b = list(map(int, input().split()))
    k = int(input())
    l = 0
    r = n
    if check(n) < k:
        print(-1)
        #print()
        continue
    else:
        while r - l > 1:
            m = (r + l) // 2
            if check(m) >= k:
                r =  m
            else:
                l = m
        print(r)
        #print()


I found an interesting problem on https://codeforces.com/problemset/problem/1225/A:
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation $a + 1 = b$ with positive integers $a$ and $b$, but Kolya forgot the numbers $a$ and $b$. He does, however, remember that the first (leftmost) digit of $a$ was $d_a$, and the first (leftmost) digit of $b$ was $d_b$.

Can you reconstruct any equation $a + 1 = b$ that satisfies this property? It may be possible that Kolya misremembers the digits, and there is no suitable equation, in which case report so.

-----Input-----

The only line contains two space-separated digits $d_a$ and $d_b$ ($1 \leq d_a, d_b \leq 9$).

-----Output-----

If there is no equation $a + 1 = b$ with positive integers $a$ and $b$ such that the first digit of $a$ is $d_a$, and the first digit of $b$ is $d_b$, print a single number $-1$.

Otherwise, print any suitable $a$ and $b$ that both are positive and do not exceed $10^9$. It is guaranteed that if a solution exists, there also exists a solution with both numbers not exceeding $10^9$.

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

Output
199 200

Input
4 4

Output
412 413

Input
5 7

Output
-1

Input
6 2

Output
-1

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

a, b = map(int, input().split())
if b - a == 1:
    print(a, b)
elif a == b:
    print(a, '0 ', b, '1', sep='')
elif b == 1 and a == 9:
    print(9, 10)
else:
    print('-1')


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

The BerTV channel every day broadcasts one episode of one of the $k$ TV shows. You know the schedule for the next $n$ days: a sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the show, the episode of which will be shown in $i$-th day.

The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.

How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $d$ ($1 \le d \le n$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $d$ consecutive days in which all episodes belong to the purchased shows.

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 100$) — the number of test cases in the input. Then $t$ test case descriptions follow.

The first line of each test case contains three integers $n, k$ and $d$ ($1 \le n \le 100$, $1 \le k \le 100$, $1 \le d \le n$). The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the show that is broadcasted on the $i$-th day.

It is guaranteed that the sum of the values of $n$ for all test cases in the input does not exceed $100$.

-----Output-----

Print $t$ integers — the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $d$ consecutive days. Please note that it is permissible that you will be able to watch more than $d$ days in a row.

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

Output
2
1
4
5

-----Note-----

In the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $1$ and on...

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

for i in range(int(input())):
    n, k, d = map(int, input().split())
    a = list(map(int, input().split()))
    ans = d
    for day in range(n - d + 1):
        ans = min(ans, len(set(a[day:day + d])))
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1225/C:
Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer $p$ (which may be positive, negative, or zero). To combine their tastes, they invented $p$-binary numbers of the form $2^x + p$, where $x$ is a non-negative integer.

For example, some $-9$-binary ("minus nine" binary) numbers are: $-8$ (minus eight), $7$ and $1015$ ($-8=2^0-9$, $7=2^4-9$, $1015=2^{10}-9$).

The boys now use $p$-binary numbers to represent everything. They now face a problem: given a positive integer $n$, what's the smallest number of $p$-binary numbers (not necessarily distinct) they need to represent $n$ as their sum? It may be possible that representation is impossible altogether. Help them solve this problem.

For example, if $p=0$ we can represent $7$ as $2^0 + 2^1 + 2^2$.

And if $p=-9$ we can represent $7$ as one number $(2^4-9)$.

Note that negative $p$-binary numbers are allowed to be in the sum (see the Notes section for an example).

-----Input-----

The only line contains two integers $n$ and $p$ ($1 \leq n \leq 10^9$, $-1000 \leq p \leq 1000$).

-----Output-----

If it is impossible to represent $n$ as the sum of any number of $p$-binary numbers, print a single integer $-1$. Otherwise, print the smallest possible number of summands.

-----Examples-----
Input
24 0

Output
2

Input
24 1

Output
3

Input
24 -1

Output
4

Input
4 -7

Output
2

Input
1 1

Output
-1

-----Note-----

$0$-binary numbers are just regular binary powers, thus in the first sample case we can represent $24 = (2^4 + 0) + (2^3 + 0)$.

In the second sample case, we can represent $24 = (2^4 + 1) + (2^2 + 1) + (2^0 + 1)$.

In the third sample case, we can represent $24 = (2^4 - 1) + (2^2 - 1) + (2^2 - 1) + (2^2 - 1)$. Note that repeated summands are allowed.

In the fourth sample case, we can represent $4 = (2^4 - 7) + (2^1 - 7)$. Note that the second summand is negative, which is allowed.

In the fifth sample case, no representation is possible.

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

n, p = map(int, input().split())
if n == 0:
    print(0)
else:
    if p >= n:
        print(-1)
    else:
        i = 0
        while 1:
            n -= p
            if n <= 0:
                print(-1)
                break
            i += 1
            s = str(bin(n))
            k = 0
            for j in s:
                if j == '1':
                    k += 1
            if k <= i and n >= i:
                print(i)
                break


I found an interesting problem on https://codeforces.com/problemset/problem/1225/D:
You are given $n$ positive integers $a_1, \ldots, a_n$, and an integer $k \geq 2$. Count the number of pairs $i, j$ such that $1 \leq i < j \leq n$, and there exists an integer $x$ such that $a_i \cdot a_j = x^k$.

-----Input-----

The first line contains two integers $n$ and $k$ ($2 \leq n \leq 10^5$, $2 \leq k \leq 100$).

The second line contains $n$ integers $a_1, \ldots, a_n$ ($1 \leq a_i \leq 10^5$).

-----Output-----

Print a single integer — the number of suitable pairs.

-----Example-----
Input
6 3
1 3 9 8 24 1

Output
5

-----Note-----

In the sample case, the suitable pairs are: $a_1 \cdot a_4 = 8 = 2^3$; $a_1 \cdot a_6 = 1 = 1^3$; $a_2 \cdot a_3 = 27 = 3^3$; $a_3 \cdot a_5 = 216 = 6^3$; $a_4 \cdot a_6 = 8 = 2^3$.

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

def f(n):
    Ans = []
    d = 2
    while d * d <= n:
        if n % d == 0:
            Ans.append(d)
            n //= d
        else:
            d += 1
    if n > 1:
        Ans.append(n)
    return Ans

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

m = {}
c = 0
for i in arr:
    r = {}
    d = 2
    while d * d <= i:
        if i % d == 0:
            r[d] = (r.get(d, 0) + 1) % k
            i //= d
        else:
            d += 1
    if i > 1:
        r[i] = (r.get(i, 0) + 1) % k
    r = tuple([x for x in list(r.items()) if x[1]])
    r2 = tuple([(x[0], k - x[1]) for x in r])
    c += m.get(r2, 0)
    m[r] = m.get(r, 0) + 1
print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/1227/A:
Your math teacher gave you the following problem:

There are $n$ segments on the $x$-axis, $[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$. The segment $[l; r]$ includes the bounds, i.e. it is a set of such $x$ that $l \le x \le r$. The length of the segment $[l; r]$ is equal to $r - l$.

Two segments $[a; b]$ and $[c; d]$ have a common point (intersect) if there exists $x$ that $a \leq x \leq b$ and $c \leq x \leq d$. For example, $[2; 5]$ and $[3; 10]$ have a common point, but $[5; 6]$ and $[1; 4]$ don't have.

You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $n$ segments.

In other words, you need to find a segment $[a; b]$, such that $[a; b]$ and every $[l_i; r_i]$ have a common point for each $i$, and $b-a$ is minimal.

-----Input-----

The first line contains integer number $t$ ($1 \le t \le 100$) — the number of test cases in the input. Then $t$ test cases follow.

The first line of each test case contains one integer $n$ ($1 \le n \le 10^{5}$) — the number of segments. The following $n$ lines contain segment descriptions: the $i$-th of them contains two integers $l_i,r_i$ ($1 \le l_i \le r_i \le 10^{9}$).

The sum of all values $n$ over all the test cases in the input doesn't exceed $10^5$.

-----Output-----

For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.

-----Example-----
Input
4
3
4 5
5 9
7 7
5
11 19
4 17
16 16
3 12
14 17
1
1 10
1
1 1

Output
2
4
0
0

-----Note-----

In the first test case of the example, we can choose the segment $[5;7]$ as the answer. It is the shortest segment that has at least one common point with all given segments.

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

t = int(input())
for i in range(t):
	n = int(input())
	leviy_otr = [10000000000,10000000000]
	pryavi_otr = [-10000000000,-10000000000]
	for j in range(n):
		a = input().split()
		a = [int(a[0]), int(a[1])]
		if leviy_otr[1] > a[1]:
			leviy_otr = a
		if pryavi_otr[0] < a[0]:
			pryavi_otr = a
	print (max(0, pryavi_otr[0] - leviy_otr[1]))


I found an interesting problem on https://codeforces.com/problemset/problem/1227/D1:
This is the easier version of the problem. In this version $1 \le n, m \le 100$. You can hack this problem only if you solve and lock both problems.

You are given a sequence of integers $a=[a_1,a_2,\dots,a_n]$ of length $n$. Its subsequence is obtained by removing zero or more elements from the sequence $a$ (they do not necessarily go consecutively). For example, for the sequence $a=[11,20,11,33,11,20,11]$:

  $[11,20,11,33,11,20,11]$, $[11,20,11,33,11,20]$, $[11,11,11,11]$, $[20]$, $[33,20]$ are subsequences (these are just some of the long list);  $[40]$, $[33,33]$, $[33,20,20]$, $[20,20,11,11]$ are not subsequences.

Suppose that an additional non-negative integer $k$ ($1 \le k \le n$) is given, then the subsequence is called optimal if:

  it has a length of $k$ and the sum of its elements is the maximum possible among all subsequences of length $k$;  and among all subsequences of length $k$ that satisfy the previous item, it is lexicographically minimal.

Recall that the sequence $b=[b_1, b_2, \dots, b_k]$ is lexicographically smaller than the sequence $c=[c_1, c_2, \dots, c_k]$ if the first element (from the left) in which they differ less in the sequence $b$ than in $c$. Formally: there exists $t$ ($1 \le t \le k$) such that $b_1=c_1$, $b_2=c_2$, ..., $b_{t-1}=c_{t-1}$ and at the same time $b_t<c_t$. For example:

  $[10, 20, 20]$ lexicographically less than $[10, 21, 1]$,  $[7, 99, 99]$ is lexicographically less than $[10, 21, 1]$,  $[10, 21, 0]$ is lexicographically less than $[10, 21, 1]$.

You are given a sequence of $a=[a_1,a_2,\dots,a_n]$ and $m$ requests, each consisting of two numbers $k_j$ and $pos_j$ ($1 \le k \le n$, $1 \le pos_j \le k_j$). For each query, print the value that is in the index $pos_j$ of the optimal subsequence of the given sequence $a$ for $k=k_j$.

For example, if $n=4$, $a=[10,20,30,20]$, $k_j=2$, then the optimal subsequence is $[20,30]$ — it is the minimum lexicographically among all subsequences of length $2$ with the maximum total sum of items. Thus, the answer to...

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

n = int(input())
data = list(map(int, input().split()))
m = int(input())
for _ in range(m):
    k, pos = list(map(int, input().split()))
    s = data[:]
    ans = []
    for i in range(k):
        x = s.index(max(s))
        ans.append(x)
        s[x] = -1
    ans.sort()
    print(data[ans[pos - 1]])


I found an interesting problem on https://codeforces.com/problemset/problem/1227/D2:
This is the harder version of the problem. In this version, $1 \le n, m \le 2\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.

You are given a sequence of integers $a=[a_1,a_2,\dots,a_n]$ of length $n$. Its subsequence is obtained by removing zero or more elements from the sequence $a$ (they do not necessarily go consecutively). For example, for the sequence $a=[11,20,11,33,11,20,11]$:  $[11,20,11,33,11,20,11]$, $[11,20,11,33,11,20]$, $[11,11,11,11]$, $[20]$, $[33,20]$ are subsequences (these are just some of the long list);  $[40]$, $[33,33]$, $[33,20,20]$, $[20,20,11,11]$ are not subsequences.

Suppose that an additional non-negative integer $k$ ($1 \le k \le n$) is given, then the subsequence is called optimal if:  it has a length of $k$ and the sum of its elements is the maximum possible among all subsequences of length $k$;  and among all subsequences of length $k$ that satisfy the previous item, it is lexicographically minimal.

Recall that the sequence $b=[b_1, b_2, \dots, b_k]$ is lexicographically smaller than the sequence $c=[c_1, c_2, \dots, c_k]$ if the first element (from the left) in which they differ less in the sequence $b$ than in $c$. Formally: there exists $t$ ($1 \le t \le k$) such that $b_1=c_1$, $b_2=c_2$, ..., $b_{t-1}=c_{t-1}$ and at the same time $b_t<c_t$. For example:  $[10, 20, 20]$ lexicographically less than $[10, 21, 1]$,  $[7, 99, 99]$ is lexicographically less than $[10, 21, 1]$,  $[10, 21, 0]$ is lexicographically less than $[10, 21, 1]$.

You are given a sequence of $a=[a_1,a_2,\dots,a_n]$ and $m$ requests, each consisting of two numbers $k_j$ and $pos_j$ ($1 \le k \le n$, $1 \le pos_j \le k_j$). For each query, print the value that is in the index $pos_j$ of the optimal subsequence of the given sequence $a$ for $k=k_j$.

For example, if $n=4$, $a=[10,20,30,20]$, $k_j=2$, then the optimal subsequence is $[20,30]$ — it is the minimum lexicographically among all subsequences of length $2$ with...

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

import sys

class TreeNode:
    def __init__(self, k, v):
        self.key = k
        self.value = v
        self.left = None
        self.right = None
        self.parent = None
        self.height = 1
        self.num_left = 1
        self.num_total = 1

class AvlTree:

    def __init__(self):
        self._tree = None

    def add(self, k, v):
        if not self._tree:
            self._tree = TreeNode(k, v)
            return
        node = self._add(k, v)
        if node:
            self._rebalance(node)

    def _add(self, k, v):
        node = self._tree
        while node:
            if k < node.key:
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(k, v)
                    node.left.parent = node
                    return node.left
            elif node.key < k:
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(k, v)
                    node.right.parent = node
                    return node.right
            else:
                node.value = v
                return

    @staticmethod
    def get_height(x):
        return x.height if x else 0

    @staticmethod
    def get_num_total(x):
        return x.num_total if x else 0

    def _rebalance(self, node):

        n = node
        while n:
            lh = self.get_height(n.left)
            rh = self.get_height(n.right)
            n.height = max(lh, rh) + 1
            balance_factor = lh - rh
            n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
            n.num_left = 1 + self.get_num_total(n.left)

            if balance_factor > 1:
                if self.get_height(n.left.left) < self.get_height(n.left.right):
                    self._rotate_left(n.left)
                self._rotate_right(n)
            elif balance_factor < -1:
                if self.get_height(n.right.right) < self.get_height(n.right.left):
                   ...


I found an interesting problem on https://codeforces.com/problemset/problem/1227/F1:
Your program fails again. This time it gets "Wrong answer on test 233".

This is the easier version of the problem. In this version $1 \le n \le 2000$. You can hack this problem only if you solve and lock both problems.

The problem is about a test containing $n$ one-choice-questions. Each of the questions contains $k$ options, and only one of them is correct. The answer to the $i$-th question is $h_{i}$, and if your answer of the question $i$ is $h_{i}$, you earn $1$ point, otherwise, you earn $0$ points for this question. The values $h_1, h_2, \dots, h_n$ are known to you in this problem.

However, you have a mistake in your program. It moves the answer clockwise! Consider all the $n$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.

Formally, the mistake moves the answer for the question $i$ to the question $i \bmod n + 1$. So it moves the answer for the question $1$ to question $2$, the answer for the question $2$ to the question $3$, ..., the answer for the question $n$ to the question $1$.

We call all the $n$ answers together an answer suit. There are $k^n$ possible answer suits in total.

You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $1$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $998\,244\,353$.

For example, if $n = 5$, and your answer suit is $a=[1,2,3,4,5]$, it will submitted as $a'=[5,1,2,3,4]$ because of a mistake. If the correct answer suit is $h=[5,2,2,3,4]$, the answer suit $a$ earns $1$ point and the answer suite $a'$ earns $4$ points. Since $4 > 1$, the answer suit $a=[1,2,3,4,5]$ should be counted.

-----Input-----

The first line contains two integers $n$, $k$ ($1 \le n \le 2000$, $1 \le k \le 10^9$) — the number of questions and the number of possible answers to each question.

The following line contains $n$ integers $h_1, h_2, \dots, h_n$, ($1 \le h_{i} \le k)$ — answers to...

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

M=998244353
class Factorial:
    def __init__(self,n):
        self.f=f=[0]*(n+1)
        f[0]=b=1
        for i in range(1,n+1):f[i]=b=b*i%M
        self.inv=inv=[0]*(n+1)
        inv[n]=b=pow(self.f[n],M-2,M)
        for i in range(n,0,-1):inv[i-1]=b=b*i%M
    def factorial(self,i):
        return self.f[i]
    def ifactorial(self,i):
        return self.inv[i]
    def comb(self,n,k):
        if n>=k:return self.f[n]*self.inv[n-k]*self.inv[k]%M
        else:return 0
def main():
    n,k,*h=map(int,open(0).read().split())
    m=sum(i!=j for i,j in zip(h,h[1:]+h[:1]))
    comb=Factorial(m).comb
    print((pow(k,m,M)-sum(comb(m,i)*comb(m-i,i)*pow(k-2,m-i-i,M)for i in range(m//2+1)))*pow(k,n-m,M)*pow(2,M-2,M)%M)
main()


I found an interesting problem on https://codeforces.com/problemset/problem/1227/F2:
Your program fails again. This time it gets "Wrong answer on test 233".

This is the harder version of the problem. In this version, $1 \le n \le 2\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.

The problem is to finish $n$ one-choice-questions. Each of the questions contains $k$ options, and only one of them is correct. The answer to the $i$-th question is $h_{i}$, and if your answer of the question $i$ is $h_{i}$, you earn $1$ point, otherwise, you earn $0$ points for this question. The values $h_1, h_2, \dots, h_n$ are known to you in this problem.

However, you have a mistake in your program. It moves the answer clockwise! Consider all the $n$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.

Formally, the mistake moves the answer for the question $i$ to the question $i \bmod n + 1$. So it moves the answer for the question $1$ to question $2$, the answer for the question $2$ to the question $3$, ..., the answer for the question $n$ to the question $1$.

We call all the $n$ answers together an answer suit. There are $k^n$ possible answer suits in total.

You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $1$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $998\,244\,353$.

For example, if $n = 5$, and your answer suit is $a=[1,2,3,4,5]$, it will submitted as $a'=[5,1,2,3,4]$ because of a mistake. If the correct answer suit is $h=[5,2,2,3,4]$, the answer suit $a$ earns $1$ point and the answer suite $a'$ earns $4$ points. Since $4 > 1$, the answer suit $a=[1,2,3,4,5]$ should be counted.

-----Input-----

The first line contains two integers $n$, $k$ ($1 \le n \le 2\cdot10^5$, $1 \le k \le 10^9$) — the number of questions and the number of possible answers to each question.

The following line contains $n$ integers $h_1, h_2,...

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

def main():
    M=998244353
    n,k,*h=map(int,open(0).read().split())
    m=sum(i!=j for i,j in zip(h,h[1:]+h[:1]))
    f=[0]*(m+1)
    f[0]=b=1
    for i in range(1,m+1):f[i]=b=b*i%M
    inv=[0]*(m+1)
    inv[m]=b=pow(f[m],M-2,M)
    for i in range(m,0,-1):inv[i-1]=b=b*i%M
    comb=lambda n,k:f[n]*inv[n-k]*inv[k]%M
    print((pow(k,m,M)-sum(comb(m,i)*comb(m-i,i)*pow(k-2,m-i-i,M)for i in range(m//2+1)))*pow(k,n-m,M)*pow(2,M-2,M)%M)
main()


I found an interesting problem on https://codeforces.com/problemset/problem/1228/A:
You have two integers $l$ and $r$. Find an integer $x$ which satisfies the conditions below:

  $l \le x \le r$.  All digits of $x$ are different.

If there are multiple answers, print any of them.

-----Input-----

The first line contains two integers $l$ and $r$ ($1 \le l \le r \le 10^{5}$).

-----Output-----

If an answer exists, print any of them. Otherwise, print $-1$.

-----Examples-----
Input
121 130

Output
123

Input
98766 100000

Output
-1

-----Note-----

In the first example, $123$ is one of the possible answers. However, $121$ can't be the answer, because there are multiple $1$s on different digits.

In the second example, there is no valid answer.

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

l, r = list(map(int, input().split()))
for i in range(l, r + 1):
    if len(set(str(i))) == len(str(i)):
        print(i)
        break
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1228/B:
Suppose there is a $h \times w$ grid consisting of empty or full cells. Let's make some definitions:

  $r_{i}$ is the number of consecutive full cells connected to the left side in the $i$-th row ($1 \le i \le h$). In particular, $r_i=0$ if the leftmost cell of the $i$-th row is empty.  $c_{j}$ is the number of consecutive full cells connected to the top end in the $j$-th column ($1 \le j \le w$). In particular, $c_j=0$ if the topmost cell of the $j$-th column is empty.

In other words, the $i$-th row starts exactly with $r_i$ full cells. Similarly, the $j$-th column starts exactly with $c_j$ full cells.

 [Image] These are the $r$ and $c$ values of some $3 \times 4$ grid. Black cells are full and white cells are empty.

You have values of $r$ and $c$. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of $r$ and $c$. Since the answer can be very large, find the answer modulo $1000000007\,(10^{9} + 7)$. In other words, find the remainder after division of the answer by $1000000007\,(10^{9} + 7)$.

-----Input-----

The first line contains two integers $h$ and $w$ ($1 \le h, w \le 10^{3}$) — the height and width of the grid.

The second line contains $h$ integers $r_{1}, r_{2}, \ldots, r_{h}$ ($0 \le r_{i} \le w$) — the values of $r$.

The third line contains $w$ integers $c_{1}, c_{2}, \ldots, c_{w}$ ($0 \le c_{j} \le h$) — the values of $c$.

-----Output-----

Print the answer modulo $1000000007\,(10^{9} + 7)$.

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

Output
2

Input
1 1
0
1

Output
0

Input
19 16
16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12
6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4

Output
797922655

-----Note-----

In the first example, this is the other possible case.

 [Image]

In the second example, it's impossible to make a grid to satisfy such $r$, $c$ values.

In the third example, make sure to print answer modulo $(10^9 + 7)$.

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

rows, cols = list(map(int, input().split()))

a = [[-1] * cols for _ in range(rows)]

r = list(map(int, input().split()))
c = list(map(int, input().split()))

# print(np.matrix(a))

for row in range(rows):
  for col in range(r[row]):
    a[row][col] = 1

  if(r[row] < cols):
    a[row][r[row]] = 0

# print(np.matrix(a))

for col in range(cols):
  for row in range(c[col]):
    a[row][col] = 1

  if(c[col] < rows):
    a[c[col]][col] = 0

# print(np.matrix(a))

isSol = True

for row in range(rows):
  for col in range(r[row]):
    if a[row][col] != 1 :
      isSol = False

  if(r[row] < cols):
    if a[row][r[row]] != 0:
      isSol = False

for col in range(cols):
  for row in range(c[col]):
    if(a[row][col] != 1):
      isSol = False

  if(c[col] < rows):
    if (a[c[col]][col] != 0):
      isSol = False

if(isSol):
  sol = 1

  for row in a:
    for i in row:
      if(i == -1):
        sol = (sol * 2) % 1000000007

  print(sol)
else:
  print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/1228/C:
Let's introduce some definitions that will be needed later.

Let $prime(x)$ be the set of prime divisors of $x$. For example, $prime(140) = \{ 2, 5, 7 \}$, $prime(169) = \{ 13 \}$.

Let $g(x, p)$ be the maximum possible integer $p^k$ where $k$ is an integer such that $x$ is divisible by $p^k$. For example:  $g(45, 3) = 9$ ($45$ is divisible by $3^2=9$ but not divisible by $3^3=27$),  $g(63, 7) = 7$ ($63$ is divisible by $7^1=7$ but not divisible by $7^2=49$).

Let $f(x, y)$ be the product of $g(y, p)$ for all $p$ in $prime(x)$. For example:  $f(30, 70) = g(70, 2) \cdot g(70, 3) \cdot g(70, 5) = 2^1 \cdot 3^0 \cdot 5^1 = 10$,  $f(525, 63) = g(63, 3) \cdot g(63, 5) \cdot g(63, 7) = 3^2 \cdot 5^0 \cdot 7^1 = 63$.

You have integers $x$ and $n$. Calculate $f(x, 1) \cdot f(x, 2) \cdot \ldots \cdot f(x, n) \bmod{(10^{9} + 7)}$.

-----Input-----

The only line contains integers $x$ and $n$ ($2 \le x \le 10^{9}$, $1 \le n \le 10^{18}$) — the numbers used in formula.

-----Output-----

Print the answer.

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

Output
2

Input
20190929 1605

Output
363165664

Input
947 987654321987654321

Output
593574252

-----Note-----

In the first example, $f(10, 1) = g(1, 2) \cdot g(1, 5) = 1$, $f(10, 2) = g(2, 2) \cdot g(2, 5) = 2$.

In the second example, actual value of formula is approximately $1.597 \cdot 10^{171}$. Make sure you print the answer modulo $(10^{9} + 7)$.

In the third example, be careful about overflow issue.

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

from math import floor,sqrt
def pp(a,b,c):
	r = 1
	a%=c
	while(b):
		if b&1:
			r = (r*a) % c
		b>>=1
		a=(a*a)%c
	return r

n,x=[int(i)for i in input().split()]
d=n
l=[]
h=floor(sqrt(d))
MOD = (1000000007)
if(d%2==0):
	l+=[2];
	while d%2==0:d//=2;
for i in range(3,h+1,2):
	if(d%i==0):
		l+=[i]
	while(d%i==0):d//=i;

if d > 2: l+=[d]
ans = 1
for i in l:
	f = i
	s = 0
	while f <= x:
		s += x//f
		f *= i
	ans = (ans*pp(i,s,MOD))% MOD
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1228/D:
You have a simple undirected graph consisting of $n$ vertices and $m$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.

Let's make a definition.

Let $v_1$ and $v_2$ be two some nonempty subsets of vertices that do not intersect. Let $f(v_{1}, v_{2})$ be true if and only if all the conditions are satisfied:  There are no edges with both endpoints in vertex set $v_1$.  There are no edges with both endpoints in vertex set $v_2$.  For every two vertices $x$ and $y$ such that $x$ is in $v_1$ and $y$ is in $v_2$, there is an edge between $x$ and $y$.

Create three vertex sets ($v_{1}$, $v_{2}$, $v_{3}$) which satisfy the conditions below;  All vertex sets should not be empty.  Each vertex should be assigned to only one vertex set.  $f(v_{1}, v_{2})$, $f(v_{2}, v_{3})$, $f(v_{3}, v_{1})$ are all true.

Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.

-----Input-----

The first line contains two integers $n$ and $m$ ($3 \le n \le 10^{5}$, $0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$) — the number of vertices and edges in the graph.

The $i$-th of the next $m$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$) — it means there is an edge between $a_{i}$ and $b_{i}$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.

-----Output-----

If the answer exists, print $n$ integers. $i$-th integer means the vertex set number (from $1$ to $3$) of $i$-th vertex. Otherwise, print $-1$.

If there are multiple answers, print any.

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

Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4

Output
-1

-----Note-----

In the first example, if $v_{1} = \{ 1 \}$, $v_{2} = \{ 2, 3 \}$, and $v_{3} = \{ 4, 5, 6 \}$ then vertex sets will satisfy all conditions. But you can assign vertices to...

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

n,m=list(map(int,input().split()))
EE=[]
if m<3:
  print(-1)
else:
  edge = [[] for i in range(n)]
  a,b=list(map(int,input().split()))
  edge[a-1].append(b-1)
  edge[b-1].append(a-1)
  EE.append([a-1,b-1])

  for i in range(m-1):
    x,y=list(map(int,input().split()))
    edge[x-1].append(y-1)
    edge[y-1].append(x-1)
    EE.append([x-1,y-1])
  c=0
  for i in range(n):
    if a-1 in edge[i] and b-1 in edge[i]:
      c=i+1
      break
  if c==0:
    print(-1)
  else:
    Ans=[0]*n
    Ans[a-1]=1
    Ans[b-1]=2
    Ans[c-1]=3
    flg=True
    C=[1]*3
    for i in range(n):
      if Ans[i]!=0:
        continue
      else:
        E=edge[i]
        if a-1 in E and b-1 in E and c-1 not in E:
          Ans[i]=3
          C[2]+=1
        elif a-1 in E and b-1 not in E and c-1 in E:
          Ans[i]=2
          C[1]+=1
        elif a-1 not in E and b-1 in E and c-1 in E:
          Ans[i]=1
          C[0]+=1
        else:
          print(-1)
          flg=False
          break
    if flg:
      T=[0]*3
      for x,y in EE:
        xx,yy=Ans[x],Ans[y]
        if xx==yy:
          print(-1)
          flg=False
          break
        elif xx==1 and yy==2:
          T[0]+=1
        elif xx==2 and yy==1:
          T[0]+=1
        elif xx==1 and yy==3:
          T[1]+=1
        elif xx==3 and yy==1:
          T[1]+=1
        else:
          T[2]+=1
    if flg:
      if T[0]==C[0]*C[1] and T[1]==C[0]*C[2] and T[2]==C[1]*C[2]:
        print(*Ans)
      else:
        print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1228/E:
You have $n \times n$ square grid and an integer $k$. Put an integer in each cell while satisfying the conditions below.  All numbers in the grid should be between $1$ and $k$ inclusive.  Minimum number of the $i$-th row is $1$ ($1 \le i \le n$).  Minimum number of the $j$-th column is $1$ ($1 \le j \le n$).

Find the number of ways to put integers in the grid. Since the answer can be very large, find the answer modulo $(10^{9} + 7)$. [Image] These are the examples of valid and invalid grid when $n=k=2$.

-----Input-----

The only line contains two integers $n$ and $k$ ($1 \le n \le 250$, $1 \le k \le 10^{9}$).

-----Output-----

Print the answer modulo $(10^{9} + 7)$.

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

Output
7

Input
123 456789

Output
689974806

-----Note-----

In the first example, following $7$ cases are possible. [Image]

In the second example, make sure you print the answer modulo $(10^{9} + 7)$.

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

fa = [1]
m = 251
P = 10**9+7
for i in range(1, m+1): fa.append(fa[-1] * i % P)
fainv = [pow(fa[m], P-2, P)]
for i in range(1, m+1)[::-1]: fainv.append(fainv[-1] * i % P)
fainv = fainv[::-1]
def C(a, b): return fa[a] * fainv[a-b] * fainv[b] % P

N, K = list(map(int, input().split()))
poK = [1]
for i in range(251): poK.append(poK[-1] * K % P)
poK1 = [1]
for i in range(251): poK1.append(poK1[-1] * (K-1) % P)

dpC = [[C(i, j) for j in range(i+1)] for i in range(N+1)]
dpCpoK = [[C(i, j) * poK[j] % P for j in range(i+1)] for i in range(N+1)]

DP = [[0] * (N+1) for _ in range(N+1)]
DP[0][0] = 1
for i in range(1, N+1):
    for j in range(1, N+1):
        for k in range(j+1):
            if k < j:
                DP[i][j] = (DP[i][j] + DP[i-1][k] * dpCpoK[j][k]) % P
            else:
                DP[i][j] = (DP[i][j] + DP[i-1][k] * dpC[j][k] % P * (poK[k] - poK1[k])) % P
    for j in range(1, N+1):
        DP[i][j] = DP[i][j] * poK1[N-j] % P

print(DP[N][N])


I found an interesting problem on https://codeforces.com/problemset/problem/1228/F:
You have an integer $n$. Let's define following tree generation as McDic's generation:  Make a complete and full binary tree of $2^{n} - 1$ vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes.  Select a non-root vertex $v$ from that binary tree.  Remove $v$ from tree and make new edges between $v$'s parent and $v$'s direct children. If $v$ has no children, then no new edges will be made.

You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree.

-----Input-----

The first line contains integer $n$ ($2 \le n \le 17$).

The $i$-th of the next $2^{n} - 3$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le 2^{n} - 2$) — meaning there is an edge between $a_{i}$ and $b_{i}$. It is guaranteed that the given edges form a tree.

-----Output-----

Print two lines.

In the first line, print a single integer — the number of answers. If given tree cannot be made by McDic's generation, then print $0$.

In the second line, print all possible answers in ascending order, separated by spaces. If the given tree cannot be made by McDic's generation, then don't print anything.

-----Examples-----
Input
4
1 2
1 3
2 4
2 5
3 6
3 13
3 14
4 7
4 8
5 9
5 10
6 11
6 12

Output
1
3

Input
2
1 2

Output
2
1 2

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

Output
0

-----Note-----

In the first example, $3$ is the only possible answer. $8$

In the second example, there are $2$ possible answers. [Image]

In the third example, the tree can't be generated by McDic's generation.

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

3

import array
import math
import os
import sys

DEBUG = 'DEBUG' in os.environ

def inp():
    return sys.stdin.readline().rstrip()

def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)

def solve(N, M, G):
    if N == 2:
        return [0, 1]

    degv = [set() for _ in range(5)]
    for i in range(M):
        d = len(G[i])
        if d == 0 or d >= 5:
            return []
        degv[d].add(i)

    layer_vcount = 1 << (N - 1)
    vs = degv[1]
    levels = [0] * M
    ans = []
    for level in range(1, N):
        #dprint('level', level, [x for x in levels])
        #dprint('vs', vs)
        #dprint('layer_vcount', layer_vcount)

        if len(vs) not in (layer_vcount - 1, layer_vcount):
            return []
        if len(vs) == layer_vcount - 1:
            if ans:
                return []
            if level == 1:
                sp_deg_off = -1
            else:
                sp_deg_off = 1
        else:
            sp_deg_off = 0
        #dprint('sp_deg_off', sp_deg_off)

        ndeg = 3 if level < N - 1 else 2
        us = set()
        ss = set()

        for v in vs:
            #dprint('v', v)
            levels[v] = level
            p = None
            for u in G[v]:
                if levels[u] == 0:
                    if p is not None:
                        return []
                    p = u
                    break
            #dprint('  p', p)
            if p is None:
                return []
            deg = len(G[p])
            #dprint('  deg', deg)

            if deg == ndeg:
                us.add(p)
            elif deg == ndeg + sp_deg_off:
                ss.add(p)
            elif sp_deg_off == 0 and deg == ndeg + 1:
                ss.add(p)
            else:
                return []

        #dprint('us', us)
        #dprint('ss', ss)

        if sp_deg_off != 0:
            if len(ss) != 1:
                return []
            (sp,) = list(ss)
            ans = [sp]
            us.add(sp)

        if sp_deg_off ==...


I found an interesting problem on https://codeforces.com/problemset/problem/1230/A:
Dawid has four bags of candies. The $i$-th of them contains $a_i$ candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?

Note, that you can't keep bags for yourself or throw them away, each bag should be given to one of the friends.

-----Input-----

The only line contains four integers $a_1$, $a_2$, $a_3$ and $a_4$ ($1 \leq a_i \leq 100$) — the numbers of candies in each bag.

-----Output-----

Output YES if it's possible to give the bags to Dawid's friends so that both friends receive the same amount of candies, or NO otherwise. Each character can be printed in any case (either uppercase or lowercase).

-----Examples-----
Input
1 7 11 5

Output
YES

Input
7 3 2 5

Output
NO

-----Note-----

In the first sample test, Dawid can give the first and the third bag to the first friend, and the second and the fourth bag to the second friend. This way, each friend will receive $12$ candies.

In the second sample test, it's impossible to distribute the bags.

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

a,b,c,d = map(lambda x:int(x),input().split())

step1 = [0]
step2 = []
step3 = []
step4 = []
step5 = []

for x in step1:
    step2.append(x+a)
    step2.append(x-a)
for x in step2:
    step3.append(x+b)
    step3.append(x-b)
for x in step3:
    step4.append(x+c)
    step4.append(x-c)
for x in step4:
    step5.append(x+d)
    step5.append(x-d)
print("YES" if 0 in step5 else "NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1230/B:
Ania has a large integer $S$. Its decimal representation has length $n$ and doesn't contain any leading zeroes. Ania is allowed to change at most $k$ digits of $S$. She wants to do it in such a way that $S$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \leq n \leq 200\,000$, $0 \leq k \leq n$) — the number of digits in the decimal representation of $S$ and the maximum allowed number of changed digits.

The second line contains the integer $S$. It's guaranteed that $S$ has exactly $n$ digits and doesn't contain any leading zeroes.

-----Output-----

Output the minimal possible value of $S$ which Ania can end with. Note that the resulting integer should also have $n$ digits.

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

Output
10028

Input
3 2
102

Output
100

Input
1 1
1

Output
0

-----Note-----

A number has leading zeroes if it consists of at least two digits and its first digit is $0$. For example, numbers $00$, $00069$ and $0101$ have leading zeroes, while $0$, $3000$ and $1010$ don't have leading zeroes.

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

import sys
input = lambda: sys.stdin.readline().strip()

n, k = list(map(int, input().split()))
S = list(input())
if n==1 and k==1: print(0)
elif k==0: print(''.join(S))
else:
    cnt = 0
    if S[0]!='1':
        S[0] = '1'
        cnt+=1
    for i in range(1, n):
        if cnt==k: break
        if S[i]!='0':
            S[i] = '0'
            cnt+=1
    print(''.join(S))


I found an interesting problem on https://codeforces.com/problemset/problem/1231/C:
In this problem, a $n \times m$ rectangular matrix $a$ is called increasing if, for each row of $i$, when go from left to right, the values strictly increase (that is, $a_{i,1}<a_{i,2}<\dots<a_{i,m}$) and for each column $j$, when go from top to bottom, the values strictly increase (that is, $a_{1,j}<a_{2,j}<\dots<a_{n,j}$).

In a given matrix of non-negative integers, it is necessary to replace each value of $0$ with some positive integer so that the resulting matrix is increasing and the sum of its elements is maximum, or find that it is impossible.

It is guaranteed that in a given value matrix all values of $0$ are contained only in internal cells (that is, not in the first or last row and not in the first or last column).

-----Input-----

The first line contains integers $n$ and $m$ ($3 \le n, m \le 500$) — the number of rows and columns in the given matrix $a$.

The following lines contain $m$ each of non-negative integers — the values in the corresponding row of the given matrix: $a_{i,1}, a_{i,2}, \dots, a_{i,m}$ ($0 \le a_{i,j} \le 8000$).

It is guaranteed that for all $a_{i,j}=0$, $1 < i < n$ and $1 < j < m$ are true.

-----Output-----

If it is possible to replace all zeros with positive numbers so that the matrix is increasing, print the maximum possible sum of matrix elements. Otherwise, print -1.

-----Examples-----
Input
4 5
1 3 5 6 7
3 0 7 0 9
5 0 0 0 10
8 9 10 11 12

Output
144

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

Output
30

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

Output
-1

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

Output
-1

-----Note-----

In the first example, the resulting matrix is as follows:

1 3 5 6 7

3 6 7 8 9

5 7 8 9 10

8 9 10 11 12

In the second example, the value $3$ must be put in the middle cell.

In the third example, the desired resultant matrix does not exist.

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

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

matrix = [list(map(int, input().split())) for _ in range(n)]
res = 0

for i in range(n-2, 0, -1):
    for j in range(m-1, 0, -1):
        if matrix[i][j] == 0:
            mn = min(matrix[i + 1][j], matrix[i][j + 1])
            if mn != 1:
                matrix[i][j] = mn - 1
            else:
                res = -1
                break
    if res == -1:
        break
else:
    for i in range(n):
        if [matrix[i][j] for j in range(m-1) if matrix[i][j] >= matrix[i][j+1]]:
            res = -1
            break
    else:
        for j in range(m):
            if [matrix[i][j] for i in range(n-1) if matrix[i][j] >= matrix[i+1][j]]:
                res = -1
                break
        else:
            res = sum((sum(matrix[i]) for i in range(n)))

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1231/E:
The problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out.

You are given two strings $s$ and $t$ of the same length $n$. Their characters are numbered from $1$ to $n$ from left to right (i.e. from the beginning to the end).

In a single move you can do the following sequence of actions:

  choose any valid index $i$ ($1 \le i \le n$),  move the $i$-th character of $s$ from its position to the beginning of the string or move the $i$-th character of $s$ from its position to the end of the string.

Note, that the moves don't change the length of the string $s$. You can apply a move only to the string $s$.

For example, if $s=$"test" in one move you can obtain:

  if $i=1$ and you move to the beginning, then the result is "test" (the string doesn't change),  if $i=2$ and you move to the beginning, then the result is "etst",  if $i=3$ and you move to the beginning, then the result is "stet",  if $i=4$ and you move to the beginning, then the result is "ttes",  if $i=1$ and you move to the end, then the result is "estt",  if $i=2$ and you move to the end, then the result is "tste",  if $i=3$ and you move to the end, then the result is "tets",  if $i=4$ and you move to the end, then the result is "test" (the string doesn't change).

You want to make the string $s$ equal to the string $t$. What is the minimum number of moves you need? If it is impossible to transform $s$ to $t$, print -1.

-----Input-----

The first line contains integer $q$ ($1 \le q \le 100$) — the number of independent test cases in the input.

Each test case is given in three lines. The first line of a test case contains $n$ ($1 \le n \le 100$) — the length of the strings $s$ and $t$. The second line contains $s$, the third line contains $t$. Both strings $s$ and $t$ have length $n$ and contain only lowercase Latin letters.

There are no constraints on the sum of $n$ in the test (i.e. the input with $q=100$ and...

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

from collections import Counter
def cal(n,s,t):
    if(Counter(s)!=Counter(t)):
        return -1
    ans=0
    for i in range(n):
        k=0
        for j in range(i,n):
            while k<n and s[k] != t[j]:
                k+=1
            if k==n:
                break
            k+=1
            ans=max(ans,j-i+1)
    return n-ans

for _ in range(int(input())):
    n=int(input())
    s,t=input(),input()
    print(cal(n,s,t))


I found an interesting problem on https://codeforces.com/problemset/problem/1234/A:
You are both a shop keeper and a shop assistant at a small nearby shop. You have $n$ goods, the $i$-th good costs $a_i$ coins.

You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all $n$ goods you have.

However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all $n$ goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.

On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one.

So you need to find the minimum possible equal price of all $n$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.

You have to answer $q$ independent queries.

-----Input-----

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

The first line of the query contains one integer $n$ ($1 \le n \le 100)$ — the number of goods. The second line of the query contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^7$), where $a_i$ is the price of the $i$-th good.

-----Output-----

For each query, print the answer for it — the minimum possible equal price of all $n$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.

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

Output
3
2
1

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

#
# Yet I'm feeling like
# 	There is no better place than right by your side
# 		I had a little taste
# 			And I'll only spoil the party anyway
# 				'Cause all the girls are looking fine
# 					But you're the only one on my mind

import sys
# import re
inf = float("inf")
# sys.setrecursionlimit(1000000)

# abc='abcdefghijklmnopqrstuvwxyz'
# abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod,MOD=1000000007,998244353
# vow=['a','e','i','o','u']
# dx,dy=[-1,1,0,0,-1,1,-1,1],[0,0,1,-1,1,1,-1,-1]

# from functools import reduce
# from collections import deque, Counter, OrderedDict,defaultdict
# from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
from math import ceil,floor,log,sqrt,factorial,pow,pi,gcd,log10,atan,tan
# from bisect import bisect_left,bisect_right,insort_left
# import numpy as np
# import queue
# from copy import deepcopy
# import random
# import operator

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

T=int(input())
while T:
    n=int(input())
    Arr=get_array()
    s=sum(Arr)
    ans = ceil(s/n)
    print(ans)
    T-=1


I found an interesting problem on https://codeforces.com/problemset/problem/1234/B1:
The only difference between easy and hard versions are constraints on $n$ and $k$.

You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $0$).

Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.

You (suddenly!) have the ability to see the future. You know that during the day you will receive $n$ messages, the $i$-th message will be received from the friend with ID $id_i$ ($1 \le id_i \le 10^9$).

If you receive a message from $id_i$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.

Otherwise (i.e. if there is no conversation with $id_i$ on the screen):  Firstly, if the number of conversations displayed on the screen is $k$, the last conversation (which has the position $k$) is removed from the screen.  Now the number of conversations on the screen is guaranteed to be less than $k$ and the conversation with the friend $id_i$ is not displayed on the screen.  The conversation with the friend $id_i$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down.

Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $n$ messages.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 200)$ — the number of messages and the number of conversations your smartphone can show.

The second line of the input contains $n$ integers $id_1, id_2, \dots, id_n$ ($1 \le id_i \le 10^9$), where $id_i$ is the ID of the friend which sends you the $i$-th...

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

from collections import deque
n,k=map(int,input().split())
d=deque()
s=set()
for i in map(int,input().split()):
  if i in s:continue
  d.appendleft(i);s.add(i)
  if len(d)>k:s.discard(d.pop())
print(len(d))
print(*d)


I found an interesting problem on https://codeforces.com/problemset/problem/1234/B2:
The only difference between easy and hard versions are constraints on $n$ and $k$.

You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $0$).

Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.

You (suddenly!) have the ability to see the future. You know that during the day you will receive $n$ messages, the $i$-th message will be received from the friend with ID $id_i$ ($1 \le id_i \le 10^9$).

If you receive a message from $id_i$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.

Otherwise (i.e. if there is no conversation with $id_i$ on the screen):

  Firstly, if the number of conversations displayed on the screen is $k$, the last conversation (which has the position $k$) is removed from the screen.  Now the number of conversations on the screen is guaranteed to be less than $k$ and the conversation with the friend $id_i$ is not displayed on the screen.  The conversation with the friend $id_i$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down.

Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $n$ messages.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 2 \cdot 10^5)$ — the number of messages and the number of conversations your smartphone can show.

The second line of the input contains $n$ integers $id_1, id_2, \dots, id_n$ ($1 \le id_i \le 10^9$), where $id_i$ is the ID of the friend which sends you the $i$-th...

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

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

lt = dict()
timer = 0
for Id in a :
    if Id not in lt :
        lt[Id] = -k
    cur_time = lt[Id]
    if cur_time <= timer - k :
        timer += 1
        lt[Id] = timer

screen = list(lt.items())
screen.sort(key=(lambda t: -t[1]))
# print(screen)
screen = screen[:min(n, k)]
print(len(screen))
for v in screen :
    print(v[0], end=' ')
print()


I found an interesting problem on https://codeforces.com/problemset/problem/1234/D:
You are given a string $s$ consisting of lowercase Latin letters and $q$ queries for this string.

Recall that the substring $s[l; r]$ of the string $s$ is the string $s_l s_{l + 1} \dots s_r$. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".

There are two types of queries:   $1~ pos~ c$ ($1 \le pos \le |s|$, $c$ is lowercase Latin letter): replace $s_{pos}$ with $c$ (set $s_{pos} := c$);  $2~ l~ r$ ($1 \le l \le r \le |s|$): calculate the number of distinct characters in the substring $s[l; r]$.

-----Input-----

The first line of the input contains one string $s$ consisting of no more than $10^5$ lowercase Latin letters.

The second line of the input contains one integer $q$ ($1 \le q \le 10^5$) — the number of queries.

The next $q$ lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.

-----Output-----

For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.

-----Examples-----
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7

Output
3
1
2

Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11

Output
5
2
5
2
6

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

import math
import bisect
from functools import reduce
import sys
from collections import defaultdict
input=sys.stdin.readline
def inn():
    return int(input())

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

MOD = 10**9+7
INF = inf = 10**18+5

s = list(input().strip())
n = len(s)
t = [[0]*26 for i in range(2*n)]

for i in range(n):
    t[i+n][ord(s[i])-97] = 1

def build():
    for i in range(n-1, 0, -1):
        for j in range(26):
            t[i][j] = t[i<<1][j] + t[i<<1|1][j]

def modify(p, val):
    t[p+n][ord(s[p])-97] = 0
    t[p+n][ord(val)-97] = 1
    s[p] = val
    p = p+n
    while p>1:
        for i in range(26):
            t[p>>1][i] = t[p][i] + t[p^1][i]
        p >>= 1

def query(l, r):
    res = [0]*26
    l += n
    r += n
    while l<r:
        if l&1:
            for i in range(26):
                res[i] += t[l][i]
            l += 1
        if r&1:
            r -= 1
            for i in range(26):
                res[i] += t[r][i]
        l >>= 1
        r >>= 1
    return res

build()

for q in range(inn()):
    tp, l, r = input().split()
    tp = int(tp)
    l = int(l)
    if tp==1:
        modify(l-1, r)
    elif tp==2:
        r = int(r)
        res = query(l-1, r)
        c = len([i for i in range(26) if res[i]>0])
        print(c)
    # print(t)


I found an interesting problem on https://codeforces.com/problemset/problem/1234/E:
Let's define $p_i(n)$ as the following permutation: $[i, 1, 2, \dots, i - 1, i + 1, \dots, n]$. This means that the $i$-th permutation is almost identity (i.e. which maps every element to itself) permutation but the element $i$ is on the first position. Examples:  $p_1(4) = [1, 2, 3, 4]$;  $p_2(4) = [2, 1, 3, 4]$;  $p_3(4) = [3, 1, 2, 4]$;  $p_4(4) = [4, 1, 2, 3]$.

You are given an array $x_1, x_2, \dots, x_m$ ($1 \le x_i \le n$).

Let $pos(p, val)$ be the position of the element $val$ in $p$. So, $pos(p_1(4), 3) = 3, pos(p_2(4), 2) = 1, pos(p_4(4), 4) = 1$.

Let's define a function $f(p) = \sum\limits_{i=1}^{m - 1} |pos(p, x_i) - pos(p, x_{i + 1})|$, where $|val|$ is the absolute value of $val$. This function means the sum of distances between adjacent elements of $x$ in $p$.

Your task is to calculate $f(p_1(n)), f(p_2(n)), \dots, f(p_n(n))$.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($2 \le n, m \le 2 \cdot 10^5$) — the number of elements in each permutation and the number of elements in $x$.

The second line of the input contains $m$ integers ($m$, not $n$) $x_1, x_2, \dots, x_m$ ($1 \le x_i \le n$), where $x_i$ is the $i$-th element of $x$. Elements of $x$ can repeat and appear in arbitrary order.

-----Output-----

Print $n$ integers: $f(p_1(n)), f(p_2(n)), \dots, f(p_n(n))$.

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

Output
3 4 6 5

Input
5 5
2 1 5 3 5

Output
9 8 12 6 8

Input
2 10
1 2 1 1 2 2 2 2 2 2

Output
3 3

-----Note-----

Consider the first example:

$x = [1, 2, 3, 4]$, so  for the permutation $p_1(4) = [1, 2, 3, 4]$ the answer is $|1 - 2| + |2 - 3| + |3 - 4| = 3$;  for the permutation $p_2(4) = [2, 1, 3, 4]$ the answer is $|2 - 1| + |1 - 3| + |3 - 4| = 4$;  for the permutation $p_3(4) = [3, 1, 2, 4]$ the answer is $|2 - 3| + |3 - 1| + |1 - 4| = 6$;  for the permutation $p_4(4) = [4, 1, 2, 3]$ the answer is $|2 - 3| + |3 - 4| + |4 - 1| = 5$.

Consider the second example:

$x = [2, 1, 5, 3, 5]$, so  for the permutation $p_1(5) = [1, 2, 3, 4, 5]$ the...

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

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

left = [0] * (n + 1)
left_sum = left[:]
right = left[:]
cross = left[:]
rang = left[:]
ans = left[:n]
total = 0

for i in range(1, m):
    p = a[i - 1]
    q = a[i]
    if p == q:
        continue
    if q < p:
        p, q = q, p
    total += q - p
    rang[p] += 1
    rang[q - 1] -= 1
    right[p] += 1
    left[q] += 1
    left_sum[q] += q - p

start = 0
for i in range(n):
    cross[i] = start
    start += rang[i]

ans[0] = total
for i in range(2, n + 1):
    ans[i - 1] = total - cross[i] + left[i] * i - 2 * left_sum[i] + (i - 1) * right[i]
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1236/A:
Alice is playing with some stones.

Now there are three numbered heaps of stones. The first of them contains $a$ stones, the second of them contains $b$ stones and the third of them contains $c$ stones.

Each time she can do one of two operations:  take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones);  take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones).

She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $0$ stones. Can you help her?

-----Input-----

The first line contains one integer $t$ ($1 \leq t \leq 100$)  — the number of test cases. Next $t$ lines describe test cases in the following format:

Line contains three non-negative integers $a$, $b$ and $c$, separated by spaces ($0 \leq a,b,c \leq 100$) — the number of stones in the first, the second and the third heap, respectively.

In hacks it is allowed to use only one test case in the input, so $t = 1$ should be satisfied.

-----Output-----

Print $t$ lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer  — the maximum possible number of stones that Alice can take after making some operations.

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

Output
9
0
6

-----Note-----

For the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is $9$. It is impossible to make some operations to take more than $9$ stones, so the answer is $9$.

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

import sys
readline = sys.stdin.readline

N = int(readline())

Ans = [None]*N
for qu in range(N):
    A, B, C = map(int, readline().split())
    res = 0
    for a in range(A+1):
        if 2*a > B:
            break
        cnt = 3*a
        t = B - 2*a
        t = min(t, C//2)
        cnt += 3*t
        res = max(res, cnt)
    Ans[qu] = res

print('\n'.join(map(str, Ans)))


I found an interesting problem on https://codeforces.com/problemset/problem/1236/B:
Alice got many presents these days. So she decided to pack them into boxes and send them to her friends.

There are $n$ kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different kinds are distinguishable). The number of presents of each kind, that Alice has is very big, so we can consider Alice has an infinite number of gifts of each kind.

Also, there are $m$ boxes. All of them are for different people, so they are pairwise distinct (consider that the names of $m$ friends are written on the boxes). For example, putting the first kind of present into the first box but not into the second box, is different from putting the first kind of present into the second box but not into the first box.

Alice wants to pack presents with the following rules:  She won't pack more than one present of each kind into the same box, so each box should contain presents of different kinds (i.e. each box contains a subset of $n$ kinds, empty boxes are allowed);  For each kind at least one present should be packed into some box.

Now Alice wants to know how many different ways to pack the presents exists. Please, help her and calculate this number. Since the answer can be huge, output it by modulo $10^9+7$.

See examples and their notes for clarification.

-----Input-----

The first line contains two integers $n$ and $m$, separated by spaces ($1 \leq n,m \leq 10^9$) — the number of kinds of presents and the number of boxes that Alice has.

-----Output-----

Print one integer  — the number of ways to pack the presents with Alice's rules, calculated by modulo $10^9+7$

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

Output
7
Input
2 2

Output
9

-----Note-----

In the first example, there are seven ways to pack presents:

$\{1\}\{\}\{\}$

$\{\}\{1\}\{\}$

$\{\}\{\}\{1\}$

$\{1\}\{1\}\{\}$

$\{\}\{1\}\{1\}$

$\{1\}\{\}\{1\}$

$\{1\}\{1\}\{1\}$

In the second example there are nine ways to pack...

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

# Contest: Codeforces Round #593 (Div. 2) (https://codeforces.com/contest/1236)
# Problem: B: Alice and the List of Presents (https://codeforces.com/contest/1236/problem/B)

def rint():
    return int(input())

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

M = 10**9 + 7
n, m = rints()
print(pow((pow(2, m, M) + M - 1) % M, n, M))


I found an interesting problem on https://codeforces.com/problemset/problem/1237/A:
Another Codeforces Round has just finished! It has gathered $n$ participants, and according to the results, the expected rating change of participant $i$ is $a_i$. These rating changes are perfectly balanced — their sum is equal to $0$.

Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.

There are two conditions though:   For each participant $i$, their modified rating change $b_i$ must be integer, and as close to $\frac{a_i}{2}$ as possible. It means that either $b_i = \lfloor \frac{a_i}{2} \rfloor$ or $b_i = \lceil \frac{a_i}{2} \rceil$. In particular, if $a_i$ is even, $b_i = \frac{a_i}{2}$. Here $\lfloor x \rfloor$ denotes rounding down to the largest integer not greater than $x$, and $\lceil x \rceil$ denotes rounding up to the smallest integer not smaller than $x$.  The modified rating changes must be perfectly balanced — their sum must be equal to $0$.

Can you help with that?

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 13\,845$), denoting the number of participants.

Each of the next $n$ lines contains a single integer $a_i$ ($-336 \le a_i \le 1164$), denoting the rating change of the $i$-th participant.

The sum of all $a_i$ is equal to $0$.

-----Output-----

Output $n$ integers $b_i$, each denoting the modified rating change of the $i$-th participant in order of input.

For any $i$, it must be true that either $b_i = \lfloor \frac{a_i}{2} \rfloor$ or $b_i = \lceil \frac{a_i}{2} \rceil$. The sum of all $b_i$ must be equal to $0$.

If there are multiple solutions, print any. We can show that a solution exists for any valid input.

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

Output
5
-2
-3

Input
7
-7
-29
0
3
24
-29
38

Output
-3
-15
0
2
12
-15
19

-----Note-----

In the first example, $b_1 = 5$, $b_2 = -3$ and $b_3 = -2$ is another correct solution.

In the second example there are $6$ possible solutions, one of them is shown in the example output.

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

N = int(input())

A = []
for _ in range(N):
    A.append(int(input()))
odd_count = 0
for a in A:
    if a % 2 == 0:
        print(a//2)
    else:
        if odd_count % 2 == 0:
            print((a+1)//2)
        else:
            print((a-1)//2)
        odd_count+=1


I found an interesting problem on https://codeforces.com/problemset/problem/1237/B:
Consider a tunnel on a one-way road. During a particular day, $n$ cars numbered from $1$ to $n$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.

A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.

Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.

Traffic regulations prohibit overtaking inside the tunnel. If car $i$ overtakes any other car $j$ inside the tunnel, car $i$ must be fined. However, each car can be fined at most once.

Formally, let's say that car $i$ definitely overtook car $j$ if car $i$ entered the tunnel later than car $j$ and exited the tunnel earlier than car $j$. Then, car $i$ must be fined if and only if it definitely overtook at least one other car.

Find the number of cars that must be fined.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 10^5$), denoting the number of cars.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$), denoting the ids of cars in order of entering the tunnel. All $a_i$ are pairwise distinct.

The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le n$), denoting the ids of cars in order of exiting the tunnel. All $b_i$ are pairwise distinct.

-----Output-----

Output the number of cars to be fined.

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

Output
2

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

Output
6

Input
2
1 2
1 2

Output
0

-----Note-----

The first example is depicted below:

[Image]

Car $2$ definitely overtook car $5$, while car $4$ definitely overtook cars $1$, $2$, $3$ and $5$. Cars $2$ and $4$ must be fined.

In the second example car $5$ was definitely overtaken by all other cars.

In the third example no car must be fined.

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

n = int(input())

a = list(map(int, input().split()))
dictt = {}
for x in range(n):
    dictt[a[x]] = x
# print(dictt)
b = list(map(int, input().split()))
bb = []
for x in b:
    bb.append(dictt[x])
# print(bb)
bb.reverse()
# work with bb
fines = 0
smallest = bb[0]
largest = bb[0]
for i in range(1, n):
    if bb[i] > smallest:
        fines += 1
        # print(f"xx{i}")
    if bb[i] > largest:
        largest = bb[i]
    if bb[i] < smallest:
        smallest = bb[i]
print(fines)


I found an interesting problem on https://codeforces.com/problemset/problem/1237/C1:
This is an easier version of the problem. In this version, $n \le 2000$.

There are $n$ distinct points in three-dimensional space numbered from $1$ to $n$. The $i$-th point has coordinates $(x_i, y_i, z_i)$. The number of points $n$ is even.

You'd like to remove all $n$ points using a sequence of $\frac{n}{2}$ snaps. In one snap, you can remove any two points $a$ and $b$ that have not been removed yet and form a perfectly balanced pair. A pair of points $a$ and $b$ is perfectly balanced if no other point $c$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $a$ and $b$.

Formally, point $c$ lies within the axis-aligned minimum bounding box of points $a$ and $b$ if and only if $\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$, $\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$, and $\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$. Note that the bounding box might be degenerate.

Find a way to remove all points in $\frac{n}{2}$ snaps.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 2000$; $n$ is even), denoting the number of points.

Each of the next $n$ lines contains three integers $x_i$, $y_i$, $z_i$ ($-10^8 \le x_i, y_i, z_i \le 10^8$), denoting the coordinates of the $i$-th point.

No two points coincide.

-----Output-----

Output $\frac{n}{2}$ pairs of integers $a_i, b_i$ ($1 \le a_i, b_i \le n$), denoting the indices of points removed on snap $i$. Every integer between $1$ and $n$, inclusive, must appear in your output exactly once.

We can show that it is always possible to remove all points. If there are many solutions, output any of them.

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

Output
3 6
5 1
2 4

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

Output
4 5
1 6
2 7
3 8

-----Note-----

In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on $z = 0$ plane). Note that order of removing matters: for example, points...

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/1237/C2:
This is a harder version of the problem. In this version, $n \le 50\,000$.

There are $n$ distinct points in three-dimensional space numbered from $1$ to $n$. The $i$-th point has coordinates $(x_i, y_i, z_i)$. The number of points $n$ is even.

You'd like to remove all $n$ points using a sequence of $\frac{n}{2}$ snaps. In one snap, you can remove any two points $a$ and $b$ that have not been removed yet and form a perfectly balanced pair. A pair of points $a$ and $b$ is perfectly balanced if no other point $c$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $a$ and $b$.

Formally, point $c$ lies within the axis-aligned minimum bounding box of points $a$ and $b$ if and only if $\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$, $\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$, and $\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$. Note that the bounding box might be degenerate.

Find a way to remove all points in $\frac{n}{2}$ snaps.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 50\,000$; $n$ is even), denoting the number of points.

Each of the next $n$ lines contains three integers $x_i$, $y_i$, $z_i$ ($-10^8 \le x_i, y_i, z_i \le 10^8$), denoting the coordinates of the $i$-th point.

No two points coincide.

-----Output-----

Output $\frac{n}{2}$ pairs of integers $a_i, b_i$ ($1 \le a_i, b_i \le n$), denoting the indices of points removed on snap $i$. Every integer between $1$ and $n$, inclusive, must appear in your output exactly once.

We can show that it is always possible to remove all points. If there are many solutions, output any of them.

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

Output
3 6
5 1
2 4

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

Output
4 5
1 6
2 7
3 8

-----Note-----

In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on $z = 0$ plane). Note that order of removing matters: for example,...

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

from sys import stdin,stdout
n=int(stdin.readline())
l=[]
for i in range(n):
    x=list(map(int,stdin.readline().split()))
    l.append([x,i+1])
l.sort()
#print(l)
deleted=[0]*n
for i in range(n-1):
    if deleted[i]:
        continue
    if l[i][0][0]==l[i+1][0][0] and l[i][0][1]==l[i+1][0][1]:
        print(l[i][1],l[i+1][1])
        deleted[i]=deleted[i+1]=1
remaining=[]
for i in range(n):
    if deleted[i]==0:
        remaining.append(l[i])
del deleted
n=len(remaining)
deleted=[0]*n
for i in range(n-1):
    if deleted[i]:
        continue
    if remaining[i][0][0]==remaining[i+1][0][0]:
        print(remaining[i][1],remaining[i+1][1])
        deleted[i]=deleted[i+1]=1
last=[]
for i in range(n):
    if deleted[i]==0:
        last.append(remaining[i])
for i in range(0,len(last),2):
    print(last[i][1],last[i+1][1])


I found an interesting problem on https://codeforces.com/problemset/problem/1237/D:
Your favorite music streaming platform has formed a perfectly balanced playlist exclusively for you. The playlist consists of $n$ tracks numbered from $1$ to $n$. The playlist is automatic and cyclic: whenever track $i$ finishes playing, track $i+1$ starts playing automatically; after track $n$ goes track $1$.

For each track $i$, you have estimated its coolness $a_i$. The higher $a_i$ is, the cooler track $i$ is.

Every morning, you choose a track. The playlist then starts playing from this track in its usual cyclic fashion. At any moment, you remember the maximum coolness $x$ of already played tracks. Once you hear that a track with coolness strictly less than $\frac{x}{2}$ (no rounding) starts playing, you turn off the music immediately to keep yourself in a good mood.

For each track $i$, find out how many tracks you will listen to before turning off the music if you start your morning with track $i$, or determine that you will never turn the music off. Note that if you listen to the same track several times, every time must be counted.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 10^5$), denoting the number of tracks in the playlist.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$), denoting coolnesses of the tracks.

-----Output-----

Output $n$ integers $c_1, c_2, \ldots, c_n$, where $c_i$ is either the number of tracks you will listen to if you start listening from track $i$ or $-1$ if you will be listening to music indefinitely.

-----Examples-----
Input
4
11 5 2 7

Output
1 1 3 2

Input
4
3 2 5 3

Output
5 4 3 6

Input
3
4 3 6

Output
-1 -1 -1

-----Note-----

In the first example, here is what will happen if you start with...   track $1$: listen to track $1$, stop as $a_2 < \frac{a_1}{2}$.  track $2$: listen to track $2$, stop as $a_3 < \frac{a_2}{2}$.  track $3$: listen to track $3$, listen to track $4$, listen to track $1$, stop as $a_2 < \frac{\max(a_3, a_4, a_1)}{2}$.  track $4$: listen to track $4$, listen to track $1$,...

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

NN = 18
MI = [1<<100] * ((1<<NN+1)-1)

def update(x):
    i = (1<<NN) - 1 + x
    MI[i] = x
    while True:
        i = (i-1) // 2
        MI[i] = min(MI[2*i+1], MI[2*i+2])
        if i == 0:
            break

def rangemin(a, b):
    l = a + (1<<NN)
    r = b + (1<<NN)
    mi = 1<<100
    while l < r:
        if l%2:
            mi = min(mi, MI[l-1])
            l += 1
        if r%2:
            r -= 1
            mi = min(mi, MI[r-1])
        l >>= 1
        r >>= 1
    return mi

N = int(input())
A = [int(a) for a in input().split()]
B = sorted([(A[i], i) for i in range(N)])
i = 0 # large
j = 0 # small
X = [1<<20] * (2*N)
while i < N:
    while 2 * B[j][0] < B[i][0]:
        update(B[j][1])
        update(B[j][1]+N)
        j += 1
    X[B[i][1]] = rangemin(B[i][1], B[i][1]+N)
    X[B[i][1]+N] = X[B[i][1]] + N
    i += 1
for i in range(2*N-1)[::-1]:
    X[i] = min(X[i], X[i+1])
for i in range(N):
    X[i] -= i
X = [a if a < (1<<20) else -1 for a in X[:N]]
print(*X)


I found an interesting problem on https://codeforces.com/problemset/problem/1237/E:
Recall that a binary search tree is a rooted binary tree, whose nodes each store a key and each have at most two distinguished subtrees, left and right. The key in each node must be greater than any key stored in the left subtree, and less than any key stored in the right subtree.

The depth of a vertex is the number of edges on the simple path from the vertex to the root. In particular, the depth of the root is $0$.

Let's call a binary search tree perfectly balanced if there doesn't exist a binary search tree with the same number of vertices that has a strictly smaller sum of depths of its vertices.

Let's call a binary search tree with integer keys striped if both of the following conditions are satisfied for every vertex $v$:   If $v$ has a left subtree whose root is $u$, then the parity of the key of $v$ is different from the parity of the key of $u$.  If $v$ has a right subtree whose root is $w$, then the parity of the key of $v$ is the same as the parity of the key of $w$.

You are given a single integer $n$. Find the number of perfectly balanced striped binary search trees with $n$ vertices that have distinct integer keys between $1$ and $n$, inclusive. Output this number modulo $998\,244\,353$.

-----Input-----

The only line contains a single integer $n$ ($1 \le n \le 10^6$), denoting the required number of vertices.

-----Output-----

Output the number of perfectly balanced striped binary search trees with $n$ vertices and distinct integer keys between $1$ and $n$, inclusive, modulo $998\,244\,353$.

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

Output
1

Input
3

Output
0

-----Note-----

In the first example, this is the only tree that satisfies the conditions: $\left. \begin{array}{l}{\text{perfectly balanced}} \\{\text{striped}} \\{\text{binary search tree}} \end{array} \right.$

In the second example, here are various trees that don't satisfy some condition: [Image]

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

n = int(input())
exist = list()
exist.append(1)
exist.append(2)
exist.append(4)
exist.append(5)
prev1 = 4
prev2 = 5
while prev2 < n:
    t1 = 1 + 2*(max(prev1, prev2) - (min(prev1, prev2) + 1) % 2)
    t2 = 1 + (max(prev1, prev2) - (min(prev1, prev2) + 1) % 2) + (max(prev1, prev2) - (min(prev1, prev2)) % 2)
    prev1 = t1
    prev2 = t2
    exist.append(prev1)
    exist.append(prev2)
if n in exist:
    print(1)
else:
    print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/1238/A:
You are given two integers $x$ and $y$ (it is guaranteed that $x > y$). You may choose any prime integer $p$ and subtract it any number of times from $x$. Is it possible to make $x$ equal to $y$?

Recall that a prime number is a positive integer that has exactly two positive divisors: $1$ and this integer itself. The sequence of prime numbers starts with $2$, $3$, $5$, $7$, $11$.

Your program should solve $t$ independent test cases.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases.

Then $t$ lines follow, each describing a test case. Each line contains two integers $x$ and $y$ ($1 \le y < x \le 10^{18}$).

-----Output-----

For each test case, print YES if it is possible to choose a prime number $p$ and subtract it any number of times from $x$ so that $x$ becomes equal to $y$. Otherwise, print NO.

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).

-----Example-----
Input
4
100 98
42 32
1000000000000000000 1
41 40

Output
YES
YES
YES
NO

-----Note-----

In the first test of the example you may choose $p = 2$ and subtract it once.

In the second test of the example you may choose $p = 5$ and subtract it twice. Note that you cannot choose $p = 7$, subtract it, then choose $p = 3$ and subtract it again.

In the third test of the example you may choose $p = 3$ and subtract it $333333333333333333$ times.

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

import math
from collections import deque, defaultdict
from sys import stdin, stdout
input = stdin.readline
# print = stdout.write
listin = lambda : list(map(int, input().split()))
mapin = lambda : map(int, input().split())
for _ in range(int(input())):
    n, m = map(int, input().split())
    if n-m == 1:
        print("NO")
    else:
        print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1238/B:
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters.

The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let's assume that the point $x = 0$ is where these parts meet.

The right part of the corridor is filled with $n$ monsters — for each monster, its initial coordinate $x_i$ is given (and since all monsters are in the right part, every $x_i$ is positive).

The left part of the corridor is filled with crusher traps. If some monster enters the left part of the corridor or the origin (so, its current coordinate becomes less than or equal to $0$), it gets instantly killed by a trap.

The main weapon Ivan uses to kill the monsters is the Phoenix Rod. It can launch a missile that explodes upon impact, obliterating every monster caught in the explosion and throwing all other monsters away from the epicenter. Formally, suppose that Ivan launches a missile so that it explodes in the point $c$. Then every monster is either killed by explosion or pushed away. Let some monster's current coordinate be $y$, then:

  if $c = y$, then the monster is killed;  if $y < c$, then the monster is pushed $r$ units to the left, so its current coordinate becomes $y - r$;  if $y > c$, then the monster is pushed $r$ units to the right, so its current coordinate becomes $y + r$.

Ivan is going to kill the monsters as follows: choose some integer point $d$ and launch a missile into that point, then wait until it explodes and all the monsters which are pushed to the left part of the corridor are killed by crusher traps, then, if at least one monster is still alive, choose another integer point (probably the one that was already used) and launch a missile there, and so on.

What is the minimum number of missiles Ivan has to launch in order to kill all of the monsters? You may assume that every time Ivan fires the Phoenix Rod, he...

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

import sys
input = sys.stdin.readline

q=int(input())

for testcases in range(q):
    n,r=list(map(int,input().split()))
    E=list(map(int,input().split()))

    E.append(0)

    E=sorted(set(E))

    for i in range(1,n+1):
        if E[-i-1]<=r*i:
            print(i)
            break


I found an interesting problem on https://codeforces.com/problemset/problem/1238/C:
You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height $h$, and there is a moving platform on each height $x$ from $1$ to $h$.

Each platform is either hidden inside the cliff or moved out. At first, there are $n$ moved out platforms on heights $p_1, p_2, \dots, p_n$. The platform on height $h$ is moved out (and the character is initially standing there).

If you character is standing on some moved out platform on height $x$, then he can pull a special lever, which switches the state of two platforms: on height $x$ and $x - 1$. In other words, the platform you are currently standing on will hide in the cliff and the platform one unit below will change it state: it will hide if it was moved out or move out if it was hidden. In the second case, you will safely land on it. Note that this is the only way to move from one platform to another.

Your character is quite fragile, so it can safely fall from the height no more than $2$. In other words falling from the platform $x$ to platform $x - 2$ is okay, but falling from $x$ to $x - 3$ (or lower) is certain death.

Sometimes it's not possible to come down from the cliff, but you can always buy (for donate currency) several magic crystals. Each magic crystal can be used to change the state of any single platform (except platform on height $h$, which is unaffected by the crystals). After being used, the crystal disappears.

What is the minimum number of magic crystal you need to buy to safely land on the $0$ ground level?

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 100$) — the number of queries. Each query contains two lines and is independent of all other queries.

The first line of each query contains two integers $h$ and $n$ ($1 \le h \le 10^9$, $1 \le n \le \min(h, 2 \cdot 10^5)$) — the height of the cliff and the number of moved out platforms.

The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($h = p_1 > p_2 > \dots > p_n \ge...

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

import sys
import math
from collections import defaultdict
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : list(map(int, input().split()))
def write(*args, sep="\n"):
  for i in args:
    sys.stdout.write("{}".format(i) + sep)
INF = float('inf')
MOD = int(1e9 + 7)

for q in range(int(input())):
  h, n = read()
  arr = list(read()) + [0]

  if n == 1:
    write(0)
    continue

  ans = 0

  cur = h
  for i in range(1, n):
    if cur == arr[i]:
      continue
    else:
      if arr[i + 1] == arr[i] - 1:
        cur = arr[i] - 1
      else:
        ans += 1

  write(ans)