I found an interesting problem on https://codeforces.com/problemset/problem/1038/F:
You are given a binary string $s$.

Find the number of distinct cyclical binary strings of length $n$ which contain $s$ as a substring.

The cyclical string $t$ contains $s$ as a substring if there is some cyclical shift of string $t$, such that $s$ is a substring of this cyclical shift of $t$.

For example, the cyclical string "000111" contains substrings "001", "01110" and "10", but doesn't contain "0110" and "10110".

Two cyclical strings are called different if they differ from each other as strings. For example, two different strings, which differ from each other by a cyclical shift, are still considered different cyclical strings.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 40$) — the length of the target string $t$.

The next line contains the string $s$ ($1 \le |s| \le n$) — the string which must be a substring of cyclical string $t$. String $s$ contains only characters '0' and '1'.

-----Output-----

Print the only integer — the number of distinct cyclical binary strings $t$, which contain $s$ as a substring.

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

Output
3
Input
4
1010

Output
2
Input
20
10101010101010

Output
962

-----Note-----

In the first example, there are three cyclical strings, which contain "0" — "00", "01" and "10".

In the second example, there are only two such strings — "1010", "0101".

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

n=int(input())
s=[c=='1' for c in input()]
m=len(s)
z=[[0,0]]
for c in s:
 ind = z[-1][c]
 z[-1][c] = len(z)
 z.append(z[ind][:])
assert(len(z) == m+1)
z[m][0] = z[m][1] = m # make it sticky

# how many things match directly
dp = [0 for _ in range(m+1)]
dp[0] = 1
for i in range(n):
 ndp = [0 for _ in range(m+1)]
 for i in range(m+1):
  ndp[z[i][0]] += dp[i]
  ndp[z[i][1]] += dp[i]
 dp = ndp
res = dp[m]

for k in range(1, m):
 s0 = 0
 for c in s[-k:]:
  s0 = z[s0][c]
 dp = [0 for _ in range(m+1)]
 dp[s0] = 1
 for i in range(n - k):
  ndp = [0 for _ in range(m+1)]
  for i in range(m+1):
   ndp[z[i][0]] += dp[i]
   ndp[z[i][1]] += dp[i]
  dp = ndp
 for s1 in range(m): # skip m
  v = dp[s1]
  for c in s[-k:]:
   if s1 == m: v = 0
   s1 = z[s1][c]
  if s1 == m: res += v
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1040/A:
A group of $n$ dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future.

On the day when the suits were to be bought, the director was told that the participants of the olympiad will be happy if the colors of the suits on the scene will form a palindrome. A palindrome is a sequence that is the same when read from left to right and when read from right to left. The director liked the idea, and she wants to buy suits so that the color of the leftmost dancer's suit is the same as the color of the rightmost dancer's suit, the 2nd left is the same as 2nd right, and so on.

The director knows how many burls it costs to buy a white suit, and how many burls to buy a black suit. You need to find out whether it is possible to buy suits to form a palindrome, and if it's possible, what's the minimal cost of doing so. Remember that dancers can not change positions, and due to bureaucratic reasons it is not allowed to buy new suits for the dancers who already have suits, even if it reduces the overall spending.

-----Input-----

The first line contains three integers $n$, $a$, and $b$ ($1 \leq n \leq 20$, $1 \leq a, b \leq 100$) — the number of dancers, the cost of a white suit, and the cost of a black suit.

The next line contains $n$ numbers $c_i$, $i$-th of which denotes the color of the suit of the $i$-th dancer. Number $0$ denotes the white color, $1$ — the black color, and $2$ denotes that a suit for this dancer is still to be bought.

-----Output-----

If it is not possible to form a palindrome without swapping dancers and buying new suits for those who have one, then output -1. Otherwise, output the minimal price to get the desired visual effect.

-----Examples-----
Input
5 100 1
0 1 2 1 2

Output
101

Input
3 10 12
1 2 0

Output
-1

Input
3 12 1
0 1...

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

import sys
f=sys.stdin
out=sys.stdout

n,a,b=map(int,f.readline().rstrip('\r\n').split())
c=list(map(int,f.readline().rstrip('\r\n').split()))
j=n-1
cost,flag=0,0
for i in range(n//2):
	if c[i]==c[j] and c[i]==2:
		cost+=(2*min(a,b))
	elif c[i]!=c[j] and c[i]==2:
		if c[j]==0:
			cost+=a
		else:
			cost+=b
	elif c[i]!=c[j] and c[j]==2:
		if c[i]==0:
			cost+=a
		else:
			cost+=b
	elif c[i]!=c[j]:
		flag=1
		break
	j-=1
if (n&1==1):
	if c[(n//2)]==2:
		cost+=min(a,b)
if(flag==1):
	out.write(str(-1)+"\n")
else:
	out.write(str(cost)+"\n")


I found an interesting problem on https://codeforces.com/problemset/problem/1040/B:
Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.

This time Miroslav laid out $n$ skewers parallel to each other, and enumerated them with consecutive integers from $1$ to $n$ in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number $i$, it leads to turning $k$ closest skewers from each side of the skewer $i$, that is, skewers number $i - k$, $i - k + 1$, ..., $i - 1$, $i + 1$, ..., $i + k - 1$, $i + k$ (if they exist).

For example, let $n = 6$ and $k = 1$. When Miroslav turns skewer number $3$, then skewers with numbers $2$, $3$, and $4$ will come up turned over. If after that he turns skewer number $1$, then skewers number $1$, $3$, and $4$ will be turned over, while skewer number $2$ will be in the initial position (because it is turned again).

As we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all $n$ skewers with the minimal possible number of actions. For example, for the above example $n = 6$ and $k = 1$, two turnings are sufficient: he can turn over skewers number $2$ and $5$.

Help Miroslav turn over all $n$ skewers.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \leq n \leq 1000$, $0 \leq k \leq 1000$) — the number of skewers and the number of skewers from each side that are turned in one step.

-----Output-----

The first line should contain integer $l$ — the minimum number of actions needed by Miroslav to turn over all $n$ skewers. After than print $l$ integers from $1$ to $n$ denoting the number of the skewer that is to be turned over at the corresponding step.

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

Output
2
1 6

Input
5 1

Output
2
1 4

-----Note-----

In the first example the first operation turns over skewers $1$, $2$ and $3$, the second operation turns over skewers $4$, $5$, $6$ and $7$.

In the second example it is also correct to turn...

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

n, k = map(int, input().split())
a = 1000000
af = []
for i in range(k+1):
    f = []
    for j in range(i+1, n+1, 2*k+1):
        f.append(j)
    if i+1 > n:
        break
    if f[-1]+k >= n:
        if a > len(f):
            a = len(f)
            af = f[:]
print(a)
print(*af)


I found an interesting problem on https://codeforces.com/problemset/problem/1041/A:
There was an electronic store heist last night.

All keyboards which were in the store yesterday were numbered in ascending order from some integer number $x$. For example, if $x = 4$ and there were $3$ keyboards in the store, then the devices had indices $4$, $5$ and $6$, and if $x = 10$ and there were $7$ of them then the keyboards had indices $10$, $11$, $12$, $13$, $14$, $15$ and $16$.

After the heist, only $n$ keyboards remain, and they have indices $a_1, a_2, \dots, a_n$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $x$ nor the number of keyboards in the store before the heist.

-----Input-----

The first line contains single integer $n$ $(1 \le n \le 1\,000)$ — the number of  keyboards in the store that remained after the heist.

The second line contains $n$ distinct integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^{9})$ — the indices of the remaining keyboards. The integers $a_i$ are given in arbitrary order and are pairwise distinct.

-----Output-----

Print the minimum possible number of keyboards that have been stolen if the staff remember neither $x$ nor the number of keyboards in the store before the heist.

-----Examples-----
Input
4
10 13 12 8

Output
2

Input
5
7 5 6 4 8

Output
0

-----Note-----

In the first example, if $x=8$ then minimum number of stolen keyboards is equal to $2$. The keyboards with indices $9$ and $11$ were stolen during the heist.

In the second example, if $x=4$ then nothing was stolen during the heist.

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

n = int(input())
a = list(map(int,input().split()))
a.sort()
ans = 0
for i in range(1,n):
    ans = ans+a[i]-a[i-1]-1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1041/B:
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than $a$ and screen height not greater than $b$. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is $w$, and the height of the screen is $h$, then the following condition should be met: $\frac{w}{h} = \frac{x}{y}$.

There are many different TV sets in the shop. Monocarp is sure that for any pair of positive integers $w$ and $h$ there is a TV set with screen width $w$ and height $h$ in the shop.

Monocarp isn't ready to choose the exact TV set he is going to buy. Firstly he wants to determine the optimal screen resolution. He has decided to try all possible variants of screen size. But he must count the number of pairs of positive integers $w$ and $h$, beforehand, such that $(w \le a)$, $(h \le b)$ and $(\frac{w}{h} = \frac{x}{y})$.

In other words, Monocarp wants to determine the number of TV sets having aspect ratio $\frac{x}{y}$, screen width not exceeding $a$, and screen height not exceeding $b$. Two TV sets are considered different if they have different screen width or different screen height.

-----Input-----

The first line contains four integers $a$, $b$, $x$, $y$ ($1 \le a, b, x, y \le 10^{18}$) — the constraints on the screen width and height, and on the aspect ratio.

-----Output-----

Print one integer — the number of different variants to choose TV screen width and screen height so that they meet the aforementioned constraints.

-----Examples-----
Input
17 15 5 3

Output
3

Input
14 16 7 22

Output
0

Input
4 2 6 4

Output
1

Input
1000000000000000000 1000000000000000000 999999866000004473 999999822000007597

Output
1000000063

-----Note-----

In the first example, there are $3$ possible variants: $(5, 3)$, $(10, 6)$, $(15, 9)$.

In the second example, there is no TV set meeting the constraints.

In the third example, there is only one variant: $(3, 2)$.

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

from math import gcd

a, b, x, y = map(int, input().split(' '))

g = gcd(x, y)

n1 = (a*g)//x
n2 = (b*g)//y

print(min(n1,n2))


I found an interesting problem on https://codeforces.com/problemset/problem/1041/C:
Recently Monocarp got a job. His working day lasts exactly $m$ minutes. During work, Monocarp wants to drink coffee at certain moments: there are $n$ minutes $a_1, a_2, \dots, a_n$, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute).

However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute $a_i$, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least $d$ minutes pass between any two coffee breaks. Monocarp also wants to take these $n$ coffee breaks in a minimum possible number of working days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than $d$ minutes pass between the end of any working day and the start of the following working day.

For each of the $n$ given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent.

-----Input-----

The first line contains three integers $n$, $m$, $d$ $(1 \le n \le 2\cdot10^{5}, n \le m \le 10^{9}, 1 \le d \le m)$ — the number of coffee breaks Monocarp wants to have, the length of each working day, and the minimum number of minutes between any two consecutive coffee breaks.

The second line contains $n$ distinct integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le m)$, where $a_i$ is some minute when Monocarp wants to have a coffee break.

-----Output-----

In the first line, write the minimum number of days required to make a coffee break in each of the $n$ given minutes.

In the second line, print $n$ space separated integers. The $i$-th of integers should be the index of the day during which Monocarp should have a coffee break at minute $a_i$. Days are numbered from $1$. If there are multiple optimal solutions, you may print any of them.

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

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

# -*- coding: utf-8 -*-

# Baqir Khan
# Software Engineer (Backend)

from sys import stdin

inp = stdin.readline

n, m, d = list(map(int, inp().split()))
a = [(int(minute), index) for index, minute in enumerate(inp().split())]
ans = [0] * n

a.sort()
ans[a[0][1]] = 1
max_cur_day = 1
j = 0
count = 1

for i in range(1, n):
    if a[i][0] - a[j][0] > d:
        ans[a[i][1]] = ans[a[j][1]]
        j += 1
    else:
        count += 1
        ans[a[i][1]] = count

print(count)
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1041/D:
A plane is flying at a constant height of $h$ meters above the ground surface. Let's consider that it is flying from the point $(-10^9, h)$ to the point $(10^9, h)$ parallel with $Ox$ axis.

A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only when the plane's coordinates are integers). After jumping from the plane, he will fly in the same direction as the plane, parallel to $Ox$ axis, covering a unit of distance every second. Naturally, he will also descend; thus his second coordinate will decrease by one unit every second.

There are ascending air flows on certain segments, each such segment is characterized by two numbers $x_1$ and $x_2$ ($x_1 < x_2$) representing its endpoints. No two segments share any common points. When the glider is inside one of such segments, he doesn't descend, so his second coordinate stays the same each second. The glider still flies along $Ox$ axis, covering one unit of distance every second.  [Image] If the glider jumps out at $1$, he will stop at $10$. Otherwise, if he jumps out at $2$, he will stop at $12$.

Determine the maximum distance along $Ox$ axis from the point where the glider's flight starts to the point where his flight ends if the glider can choose any integer coordinate to jump from the plane and start his flight. After touching the ground the glider stops altogether, so he cannot glide through an ascending airflow segment if his second coordinate is $0$.

-----Input-----

The first line contains two integers $n$ and $h$ $(1 \le n \le 2\cdot10^{5}, 1 \le h \le 10^{9})$ — the number of ascending air flow segments and the altitude at which the plane is flying, respectively.

Each of the next $n$ lines contains two integers $x_{i1}$ and $x_{i2}$ $(1 \le x_{i1} < x_{i2} \le 10^{9})$ — the endpoints of the $i$-th ascending air flow segment. No two segments intersect, and they are given in ascending order.

-----Output-----

Print one integer — the maximum distance along $Ox$ axis...

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

n, s = map(int, input().split())
mass = list()
arr = list()
past = -1
answer = 0

for i in range(n):
    l, r = map(int, input().split())
    mass.append(r - l)
    if past != -1:
        arr.append(l - past)
    past = r

l2 = 0

local = s
q = mass[0] + s
for j in range(n - 1):
    local -= arr[j]
    if local <= 0:
        l2 = j
        break
    q += mass[j + 1]
answer = q

if local <= 0:
    for i in range(1, n):
        local += arr[i - 1]
        q -= mass[i - 1]
        if local > 0:
            local += arr[l2]
            for j in range(l2, n - 1):
                local -= arr[j]
                if local <= 0:
                    break
                l2 += 1
                q += mass[j + 1]
        if q > answer:
            answer = q
        if local > 0:
            break

print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/1041/E:
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $1$ to $n$. For every edge $e$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $e$ (and only this edge) is erased from the tree.

Monocarp has given you a list of $n - 1$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.

-----Input-----

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

Each of the next $n-1$ lines contains two integers $a_i$ and $b_i$ each ($1 \le a_i < b_i \le n$) — the maximal indices of vertices in the components formed if the $i$-th edge is removed.

-----Output-----

If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).

Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $n - 1$ lines. Each of the last $n - 1$ lines should contain two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$) — vertices connected by an edge.

Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.

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

Output
YES
1 3
3 2
2 4

Input
3
1 3
1 3

Output
NO

Input
3
1 2
2 3

Output
NO

-----Note-----

Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.  [Image]

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

n = int(input())
V = []
for _ in range(n-1):
    a,b  = map(int, input().split())
    V.append(a)
    if b <n:
        print('NO')
        quit()
V.sort()
for i in range(n-1):
    if V[i]<=i:
        print("NO")
        quit()
used = [False]*(n+1)
tree = []
for i in range(n-1):
    v = V[i]
    if not used[v]:
        tree.append(v)
        used[v]=True
    else:
        for j in range(1,n+1):
            if not used[j]:
                tree.append(j)
                used[j] = True
                break
tree.append(n)
print("YES")
for i in range(n-1):
    print(tree[i],tree[i+1])


I found an interesting problem on https://codeforces.com/problemset/problem/1041/F:
You are given a tube which is reflective inside represented as two non-coinciding, but parallel to $Ox$ lines. Each line has some special integer points — positions of sensors on sides of the tube.

You are going to emit a laser ray in the tube. To do so, you have to choose two integer points $A$ and $B$ on the first and the second line respectively (coordinates can be negative): the point $A$ is responsible for the position of the laser, and the point $B$ — for the direction of the laser ray. The laser ray is a ray starting at $A$ and directed at $B$ which will reflect from the sides of the tube (it doesn't matter if there are any sensors at a reflection point or not). A sensor will only register the ray if the ray hits exactly at the position of the sensor. [Image] Examples of laser rays. Note that image contains two examples. The $3$ sensors (denoted by black bold points on the tube sides) will register the blue ray but only $2$ will register the red.

Calculate the maximum number of sensors which can register your ray if you choose points $A$ and $B$ on the first and the second lines respectively.

-----Input-----

The first line contains two integers $n$ and $y_1$ ($1 \le n \le 10^5$, $0 \le y_1 \le 10^9$) — number of sensors on the first line and its $y$ coordinate.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — $x$ coordinates of the sensors on the first line in the ascending order.

The third line contains two integers $m$ and $y_2$ ($1 \le m \le 10^5$, $y_1 < y_2 \le 10^9$) — number of sensors on the second line and its $y$ coordinate.

The fourth line contains $m$ integers $b_1, b_2, \ldots, b_m$ ($0 \le b_i \le 10^9$) — $x$ coordinates of the sensors on the second line in the ascending order.

-----Output-----

Print the only integer — the maximum number of sensors which can register the ray.

-----Example-----
Input
3 1
1 5 6
1 3
3

Output
3

-----Note-----

One of the solutions illustrated on the image by pair $A_2$ and $B_2$.

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

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

ans = 2

for i in range(31):
	step = (2 << i)
	half = (step >> 1)

	counts = dict()

	for x in a:
		rem = x % step
		count = counts.get(rem, 0)
		counts[rem] = count + 1

	for x in b:
		rem = (x + half) % step
		count = counts.get(rem, 0)
		counts[rem] = count + 1

	res = max(counts.values())
	ans = max(ans, res)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1042/A:
There are $n$ benches in the Berland Central park. It is known that $a_i$ people are currently sitting on the $i$-th bench. Another $m$ people are coming to the park and each of them is going to have a seat on some bench out of $n$ available.

Let $k$ be the maximum number of people sitting on one bench after additional $m$ people came to the park. Calculate the minimum possible $k$ and the maximum possible $k$.

Nobody leaves the taken seat during the whole process.

-----Input-----

The first line contains a single integer $n$ $(1 \le n \le 100)$ — the number of benches in the park.

The second line contains a single integer $m$ $(1 \le m \le 10\,000)$ — the number of people additionally coming to the park.

Each of the next $n$ lines contains a single integer $a_i$ $(1 \le a_i \le 100)$ — the initial number of people on the $i$-th bench.

-----Output-----

Print the minimum possible $k$ and the maximum possible $k$, where $k$ is the maximum number of people sitting on one bench after additional $m$ people came to the park.

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

Output
3 7

Input
1
10
5

Output
15 15

Input
3
6
1
6
5

Output
6 12

Input
3
7
1
6
5

Output
7 13

-----Note-----

In the first example, each of four benches is occupied by a single person. The minimum $k$ is $3$. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum $k$ is $7$. That requires all six new people to occupy the same bench.

The second example has its minimum $k$ equal to $15$ and maximum $k$ equal to $15$, as there is just a single bench in the park and all $10$ people will occupy it.

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

n=int(input())
m=int(input())
A=[int(input()) for i in range(n)]

A.sort()
ANS2=max(A)+m

while m!=0:
    x=min(A)
    i=0
    while i<n and m!=0:
        if A[i]==x:
            A[i]+=1
            i+=1
            m-=1
        else:
            break

    A.sort()

print(max(A),ANS2)


I found an interesting problem on https://codeforces.com/problemset/problem/1042/B:
Berland shop sells $n$ kinds of juices. Each juice has its price $c_i$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.

Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.

-----Input-----

The first line contains a single integer $n$ $(1 \le n \le 1\,000)$ — the number of juices.

Each of the next $n$ lines contains an integer $c_i$ $(1 \le c_i \le 100\,000)$ and a string $s_i$ — the price of the $i$-th juice and the vitamins it contains. String $s_i$ contains from $1$ to $3$ characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string $s_i$. The order of letters in strings $s_i$ is arbitrary.

-----Output-----

Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.

-----Examples-----
Input
4
5 C
6 B
16 BAC
4 A

Output
15

Input
2
10 AB
15 BA

Output
-1

Input
5
10 A
9 BC
11 CA
4 A
5 B

Output
13

Input
6
100 A
355 BCA
150 BC
160 AC
180 B
190 CA

Output
250

Input
2
5 BA
11 CB

Output
16

-----Note-----

In the first example Petya buys the first, the second and the fourth juice. He spends $5 + 6 + 4 = 15$ and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is $16$, which isn't optimal.

In the second example Petya can't obtain all three vitamins, as no juice contains vitamin "C".

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

n = int(input())
c = []
s = []
for _ in range(n):
    ln = input().split()
    c.append(int(ln[0]))
    s.append(str(ln[1]))
dp = [1e9 for _ in range(8)]
dp[0] = 0
for i in range(n):
    k = 0
    if 'A' in s[i]:
        k += 1
    if 'B' in s[i]:
        k += 2
    if 'C' in s[i]:
        k += 4
    for j in range(8):
        dp[j | k] = min(dp[j | k], dp[j] + c[i])
if dp[7] == 1e9:
    print(-1)
else:
    print(dp[7])


I found an interesting problem on https://codeforces.com/problemset/problem/1042/C:
You are given an array $a$ consisting of $n$ integers. You can perform the following operations with it:   Choose some positions $i$ and $j$ ($1 \le i, j \le n, i \ne j$), write the value of $a_i \cdot a_j$ into the $j$-th cell and remove the number from the $i$-th cell;  Choose some position $i$ and remove the number from the $i$-th cell (this operation can be performed no more than once and at any point of time, not necessarily in the beginning).

The number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations.

Your task is to perform exactly $n - 1$ operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print any sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print.

-----Input-----

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

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

-----Output-----

Print $n - 1$ lines. The $k$-th line should contain one of the two possible operations.

The operation of the first type should look like this: $1~ i_k~ j_k$, where $1$ is the type of operation, $i_k$ and $j_k$ are the positions of the chosen elements.

The operation of the second type should look like this: $2~ i_k$, where $2$ is the type of operation, $i_k$ is the position of the chosen element. Note that there should be no more than one such operation.

If there are multiple possible sequences of operations leading to the maximum number — print any of them.

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

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

Input
5
5 2 0 4 0

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

Input
2
2 -1

Output
2 2

Input
4
0 -10 0 0

Output
1 1 2
1 2 3
1 3 4

Input
4
0 0 0 0

Output
1 1 2
1 2...

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

from enum import Enum

class OperationType(Enum):
	Multiply = 1
	Remove = 2

class RemoveOperation:
	def __init__(self, index):
		self.type = OperationType.Remove
		self.index = index

	def __repr__(self):
		return "RemoveOperation({})".format(self.index)

class MultiplyOperation:
	def __init__(self, index_a, index_b):
		self.type = OperationType.Multiply
		self.index_a = index_a
		self.index_b = index_b

	def __repr__(self):
		return "MultiplyOperation({}, {})".format(self.index_a, self.index_b)

def multiply_remaining(removed, n):
	"""
	Removed should be list of 1-based indices
	"""
	operations = []
	keep_indices = set(range(1, n + 1)) - set(removed)
	previous = None
	for index in sorted(keep_indices):
		if previous is not None:
			operations.append(MultiplyOperation(previous, index))
		previous = index
	return operations

def multiply_everything(n):
	operations = []
	for i in range(1, n):
		operations.append(MultiplyOperation(i, i + 1))
	return operations

def remove_indices_and_multiply_remaining(removed, n):
	"""
	Removed should be a collection of 1-based indices
	"""
	operations = []
	keep_indices = set(range(1, n + 1)) - set(removed)
	previous = None
	for index in sorted(keep_indices):
		if previous is not None:
			operations.append(MultiplyOperation(previous, index))
		previous = index
	return operations

def find_zero_indices(xs):
	"""
	Returns sorted list of 1-based indices
	"""
	zero_indices = []
	for index, x, in enumerate(xs):
		if x == 0:
			zero_indices.append(index + 1)
	return zero_indices

def remove_indices_and_multiply_remaining(indices_to_remove, n):
	"""
	indices_to_remove should be a sorted list of 1-based indices
	"""
	# multiply together indices to remove and then actually remove last one
	operations = []
	previous = None
	for index in indices_to_remove:
		if previous is not None:
			operations.append(MultiplyOperation(previous, index))
		previous = index

	if len(indices_to_remove) < n:
		operations.append(RemoveOperation(previous))
		operations +=...


I found an interesting problem on https://codeforces.com/problemset/problem/1042/D:
Petya has an array $a$ consisting of $n$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.

Now he wonders what is the number of segments in his array with the sum less than $t$. Help Petya to calculate this number.

More formally, you are required to calculate the number of pairs $l, r$ ($l \le r$) such that $a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$.

-----Input-----

The first line contains two integers $n$ and $t$ ($1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$).

The second line contains a sequence of integers $a_1, a_2, \dots, a_n$ ($|a_{i}| \le 10^{9}$) — the description of Petya's array. Note that there might be negative, zero and positive elements.

-----Output-----

Print the number of segments in Petya's array with the sum of elements less than $t$.

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

Output
5

Input
3 0
-1 2 -3

Output
4

Input
4 -1
-2 1 -2 3

Output
3

-----Note-----

In the first example the following segments have sum less than $4$:  $[2, 2]$, sum of elements is $-1$  $[2, 3]$, sum of elements is $2$  $[3, 3]$, sum of elements is $3$  $[4, 5]$, sum of elements is $3$  $[5, 5]$, sum of elements is $-1$

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

import bisect
class BIT:
    def __init__(self, node_size):
        self._node = node_size+1
        self.bit = [0]*self._node

    def add(self, index, add_val):
        while index < self._node:
            self.bit[index] += add_val
            index += index & -index

    def sum(self, index):
        res = 0
        while index > 0:
            res += self.bit[index]
            index -= index & -index
        return res
n,t = map(int,input().split())
a = list(map(int,input().split()))
ru = [0] * (n+1)
ans = 0
for i in range(1,n+1):
  ru[i] = ru[i-1]+ a[i-1]
rus = sorted(ru)
bit = BIT(n+2)
for i in range(n+1):
  ru[i] = bisect.bisect_left(rus,ru[i])
for i in range(n+1):
  ind = bisect.bisect_left(rus,rus[ru[i]]-t+1)
  ans += bit.sum(n+2)-bit.sum(ind)
  bit.add(ru[i]+1,1)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1043/A:
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are $n$ students in the school. Each student has exactly $k$ votes and is obligated to use all of them. So Awruk knows that if a person gives $a_i$ votes for Elodreip, than he will get exactly $k - a_i$ votes from this person. Of course $0 \le k - a_i$ holds.

Awruk knows that if he loses his life is over. He has been speaking a lot with his friends and now he knows $a_1, a_2, \dots, a_n$ — how many votes for Elodreip each student wants to give. Now he wants to change the number $k$ to win the elections. Of course he knows that bigger $k$ means bigger chance that somebody may notice that he has changed something and then he will be disqualified.

So, Awruk knows $a_1, a_2, \dots, a_n$ — how many votes each student will give to his opponent. Help him select the smallest winning number $k$. In order to win, Awruk needs to get strictly more votes than Elodreip.

-----Input-----

The first line contains integer $n$ ($1 \le n \le 100$) — the number of students in the school.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 100$) — the number of votes each student gives to Elodreip.

-----Output-----

Output the smallest integer $k$ ($k \ge \max a_i$) which gives Awruk the victory. In order to win, Awruk needs to get strictly more votes than Elodreip.

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

Output
5
Input
5
2 2 3 2 2

Output
5

-----Note-----

In the first example, Elodreip gets $1 + 1 + 1 + 5 + 1 = 9$ votes. The smallest possible $k$ is $5$ (it surely can't be less due to the fourth person), and it leads to $4 + 4 + 4 + 0 + 4 = 16$ votes for Awruk, which is enough to win.

In the second example, Elodreip gets $11$ votes. If $k = 4$, Awruk gets $9$ votes and loses to Elodreip.

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

n = int(input())
a = list(map(int,input().split()))
s = sum(a)
for k in range(max(a), 999999):
    vote = sum(k-x for x in a)
    if vote > s: print(k); break


I found an interesting problem on https://codeforces.com/problemset/problem/1043/B:
Bajtek, known for his unusual gifts, recently got an integer array $x_0, x_1, \ldots, x_{k-1}$.

Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array $a$ of length $n + 1$. As a formal description of $a$ says, $a_0 = 0$ and for all other $i$ ($1 \le i \le n$) $a_i = x_{(i-1)\bmod k} + a_{i-1}$, where $p \bmod q$ denotes the remainder of division $p$ by $q$.

For example, if the $x = [1, 2, 3]$ and $n = 5$, then:  $a_0 = 0$,  $a_1 = x_{0\bmod 3}+a_0=x_0+0=1$,  $a_2 = x_{1\bmod 3}+a_1=x_1+1=3$,  $a_3 = x_{2\bmod 3}+a_2=x_2+3=6$,  $a_4 = x_{3\bmod 3}+a_3=x_0+6=7$,  $a_5 = x_{4\bmod 3}+a_4=x_1+7=9$.

So, if the $x = [1, 2, 3]$ and $n = 5$, then $a = [0, 1, 3, 6, 7, 9]$.

Now the boy hopes that he will be able to restore $x$ from $a$! Knowing that $1 \le k \le n$, help him and find all possible values of $k$ — possible lengths of the lost array.

-----Input-----

The first line contains exactly one integer $n$ ($1 \le n \le 1000$) — the length of the array $a$, excluding the element $a_0$.

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

Note that $a_0$ is always $0$ and is not given in the input.

-----Output-----

The first line of the output should contain one integer $l$ denoting the number of correct lengths of the lost array.

The second line of the output should contain $l$ integers — possible lengths of the lost array in increasing order.

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

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

Output
2
3 5
Input
3
1 5 3

Output
1
3

-----Note-----

In the first example, any $k$ is suitable, since $a$ is an arithmetic progression.

Possible arrays $x$:  $[1]$ $[1, 1]$ $[1, 1, 1]$ $[1, 1, 1, 1]$  $[1, 1, 1, 1, 1]$

In the second example, Bajtek's array can have three or five elements.

Possible arrays $x$:  $[1, 2, 2]$ $[1, 2, 2, 1, 2]$

For example, $k = 4$ is bad, since it leads to $6 +...

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

n = int(input())
a = list(map(int, input().split()))
a.insert(0,0)
l = []
for i in range(n):
	l.append(a[i + 1] - a[i])
r = []
for i in range(1,n+1):
	m = l[:i]
	j = 0
	k = i
	f = True
	while k<n:
		if m[j] == l[k]:
			j = (j+1)%i
			k += 1
		else:
			f = False
			break
	if f == True:
		r.append(i)
print(len(r))
print(' '.join(map(str,r)))


I found an interesting problem on https://codeforces.com/problemset/problem/1043/C:
IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting.

Today, when IA looked at the fridge, she noticed that the word formed by magnets is really messy. "It would look much better when I'll swap some of them!" — thought the girl — "but how to do it?". After a while, she got an idea. IA will look at all prefixes with lengths from $1$ to the length of the word and for each prefix she will either reverse this prefix or leave it as it is. She will consider the prefixes in the fixed order: from the shortest to the largest. She wants to get the lexicographically smallest possible word after she considers all prefixes. Can you help her, telling which prefixes should be chosen for reversing?

A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds: $a$ is a prefix of $b$, but $a \ne b$; in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.

-----Input-----

The first and the only line contains a string $s$ ($1 \le |s| \le 1000$), describing the initial string formed by magnets. The string $s$ consists only of characters 'a' and 'b'.

-----Output-----

Output exactly $|s|$ integers. If IA should reverse the $i$-th prefix (that is, the substring from $1$ to $i$), the $i$-th integer should be equal to $1$, and it should be equal to $0$ otherwise.

If there are multiple possible sequences leading to the optimal answer, print any of them.

-----Examples-----
Input
bbab

Output
0 1 1 0

Input
aaaaa

Output
1 0 0 0 1

-----Note-----

In the first example, IA can reverse the second and the third prefix and get a string "abbb". She cannot get better result, since it is also lexicographically smallest string obtainable by permuting characters of the initial string.

In the...

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

s = input()
arr_ans = [0] * len(s)
for i in range(1, len(s)):
    if s[i] == 'a':
        arr_ans[i - 1] = (arr_ans[i - 1] + 1) % 2
        arr_ans[i] += 1
print(*arr_ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1043/D:
Acingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked $m$ neighbours of Ada about clients who have visited her in that unlucky day. Let's number the clients from $1$ to $n$. Each neighbour's testimony is a permutation of these numbers, which describes the order in which clients have been seen by the asked neighbour.

However, some facts are very suspicious – how it is that, according to some of given permutations, some client has been seen in the morning, while in others he has been seen in the evening? "In the morning some of neighbours must have been sleeping!" — thinks Gawry — "and in the evening there's been too dark to see somebody's face...". Now he wants to delete some prefix and some suffix (both prefix and suffix can be empty) in each permutation, so that they'll be non-empty and equal to each other after that — some of the potential criminals may disappear, but the testimony won't stand in contradiction to each other.

In how many ways he can do it? Two ways are called different if the remaining common part is different.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 100\,000$, $1 \le m \le 10$) — the number of suspects and the number of asked neighbors.

Each of the next $m$ lines contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$). It is guaranteed that these integers form a correct permutation (that is, each number from $1$ to $n$ appears exactly once).

-----Output-----

Output a single integer denoting the number of ways to delete some prefix and some suffix of each permutation (possibly empty), such that the remaining parts will be equal and non-empty.

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

Output
4

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

Output
5

Input
2 2
1 2
2...

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

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

graph = [0] * n
_next = [True] * n
_next[n - 1] = False

def read_array():
    return list([x - 1 for x in list(map(int, input().split()))])

first = read_array()
iterable1 = list(range(n))
iterable2 = list(range(n - 1))
for i in iterable1:
    graph[first[i]] = i

for cnt in range(1, m):
    a = read_array()
    for i in range(n - 1):
        if graph[a[i]] + 1 != graph[a[i + 1]]:
            _next[graph[a[i]]] = False
    _next[graph[a[n - 1]]] = False

l = 0
ans = 0
for cnt in iterable1:
    l += 1
    if not _next[cnt]:
        ans += (l * (l + 1)) // 2
        l = 0

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1043/E:
Zibi is a competitive programming coach. There are $n$ competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.

Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).

We know that the $i$-th competitor will always have score $x_i$ when he codes the first task and $y_i$ when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.

Zibi wants all competitors to write a contest with each other. However, there are $m$ pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?

-----Input-----

The first line contains two integers $n$ and $m$ ($2 \le n \le 300\,000$, $0 \le m \le 300\,000$) — the number of participants and the number of pairs of people who will not write a contest together.

Each of the next $n$ lines contains two integers $x_i$ and $y_i$ ($-10^9 \le x_i, y_i \le 10^9$) — the scores which will the $i$-th competitor get on the first problem and on the second problem. It is guaranteed that...

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

import sys
input = sys.stdin.readline

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

s = sys.stdin.read()

i = 0
j = 1
inp = []
while i<len(s):
    while s[j]>='-':j+=1
    inp.append(int(s[i:j]))
    j+=1
    i=j

order = sorted(range(n),key=lambda i:inp[2*i]-inp[2*i+1])

score = [0]*n
val = sum(inp[1:2*n:2])
for ind in range(n):
    i = order[ind]

    # Do second problem together with order[:ind]
    # Do first problem together with order[ind:]
    score[i] += val + inp[2*i+1]*(ind-1) + inp[2*i]*(n-ind-1)
    val += inp[2*i]-inp[2*i+1]

for _ in range(m):
    u = inp[2*n+2*_]-1
    v = inp[2*n+2*_+1]-1
    s = min(inp[2*u]+inp[2*v+1],inp[2*v]+inp[2*u+1])
    score[u] -= s
    score[v] -= s

sys.stdout.write(' '.join(str(x) for x in score))


I found an interesting problem on https://codeforces.com/problemset/problem/1043/F:
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $n$ integers $a_i$.

It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $1$. Now Janusz wonders, for given sequence, how much elements should the player choose?

-----Input-----

The first line contains an only integer $n$ ($1 \le n \le 300\,000$) — the number of integers in the sequence.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 300\,000$).

-----Output-----

If there is no subset of the given sequence with gcd equal to $1$, output -1.

Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $1$.

-----Examples-----
Input
3
10 6 15

Output
3

Input
3
2 4 6

Output
-1

Input
7
30 60 21 42 70 15 30

Output
3

-----Note-----

In the first example, selecting a subset of all numbers gives a gcd of $1$ and for all smaller subsets the gcd is greater than $1$.

In the second example, for all subsets of numbers the gcd is at least $2$.

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

from sys import *

maxn = 3 * 10 ** 5 + 5
fre = [0] * maxn
divi = [0] * maxn
isprime = [0] * maxn
prime = []

def seive(n):
	for i in range(n):
		isprime[i] = True
	for i in range(2, n):
		if isprime[i] is True:
			prime.append(i)
		for j in range(1, n):
			if i * j >= n:
				break
			isprime[i * j] = False
			divi[i] += fre[i * j]

mobius = [0] * maxn

def calc_mobius(n):
	for i in range(1, n):
		mobius[i] = 1
	for p in prime:
		if p * p >= n:
			break
		x = p * p
		for j in range(x, n, x):
			mobius[j] = 0
	for p in prime:
		for j in range(p, n, p):
			mobius[j] *= -1

fact = [1] * 10

def calc_fact():
	fact[0] = 1
	for i in range(1, 10):
		fact[i] = i * fact[i - 1]

def nCr(n, r):
	if n < r:
		return 0
	if n is r:
		return 1
	pro = 1
	for i in range(r):
		pro *= (n - i)
	pro //= fact[r]
	return pro

def count_coprime(r):
	coprime = 0
	for d in range(1, maxn):
		ncr = nCr(divi[d], r)
		coprime += mobius[d] * ncr
	return coprime;

def __starting_point():
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().split()))
	for i in arr:
		if i is 1:
			print(1)
			return
		fre[i] += 1
	divi[1] = n
	seive(maxn)
	calc_mobius(maxn)
	calc_fact()
	for r in range(2, 10):
		coprime = count_coprime(r)
		if coprime > 0:
			print(r);return
	print(-1)
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1044/A:
On a chessboard with a width of $10^9$ and a height of $10^9$, the rows are numbered from bottom to top from $1$ to $10^9$, and the columns are numbered from left to right from $1$ to $10^9$. Therefore, for each cell of the chessboard you can assign the coordinates $(x,y)$, where $x$ is the column number and $y$ is the row number.

Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner — a cell with coordinates $(1,1)$. But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely — on the upper side of the field (that is, in any cell that is in the row with number $10^9$).

Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:   Vertical. Each of these is defined by one number $x$. Such spells create an infinite blocking line between the columns $x$ and $x+1$.  Horizontal. Each of these is defined by three numbers $x_1$, $x_2$, $y$. Such spells create a blocking segment that passes through the top side of the cells, which are in the row $y$ and in columns from $x_1$ to $x_2$ inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.

 [Image]

 An example of a chessboard.

Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell $(r_0,c_0)$ into the cell $(r_1,c_1)$ only under the condition that $r_1 = r_0$ or $c_1 = c_0$ and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).

Fortunately, the rook can remove spells, but for this it has to put tremendous...

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

def __starting_point():
    n, m = map(int, input().split())
    # for i in range(n):
        # sir = int(input())
    sir = [int(input()) for i in range(n)]
    sir.append(10**9)
    w = []
    b = 0
    mini = 999999
    nrSir = len(sir)

    for i in range(m):
        x, y, z = map(int, input().split())
        if x == 1:
            w.append(y)
    sir.sort()
    w.sort()
    nrW = len(w)
    for i in range(nrSir):
        while b < nrW and sir[i] > w[b]:
            b = b + 1
        if mini + b > nrW + i:
            mini = i - b + nrW
        if b == nrW:
            break
    print(mini)
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1046/C:
Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race.

Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next race. It's guaranteed that given astronaut will have unique number of points before the race.

-----Input-----

The first line contains two integer numbers $N$ ($1 \leq N \leq 200000$) representing number of F1 astronauts, and current position of astronaut $D$ ($1 \leq D \leq N$) you want to calculate best ranking for (no other competitor will have the same number of points before the race).

The second line contains $N$ integer numbers $S_k$ ($0 \leq S_k \leq 10^8$, $k=1...N$), separated by a single space, representing current ranking of astronauts. Points are sorted in non-increasing order.

The third line contains $N$ integer numbers $P_k$ ($0 \leq P_k \leq 10^8$, $k=1...N$), separated by a single space, representing point awards for the next race. Points are sorted in non-increasing order, so winner of the race gets the maximum number of points.

-----Output-----

Output contains one integer number — the best possible ranking for astronaut after the race. If multiple astronauts have the same score after the race, they all share the best ranking.

-----Example-----
Input
4 3
50 30 20 10
15 10 7 3

Output
2

-----Note-----

If the third ranked astronaut wins the race, he will have 35 points. He cannot take the leading position, but he can overtake the second position if the second ranked astronaut finishes the race at the last position.

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

a = input().split()
a = [int(i) for i in a]

b = input().split()
b = [int(i) for i in b]

c = input().split()
c = [int(i) for i in c]

cha = []

for i in range(0, a[1] - 1):
	cha.append(b[i] -b[a[1] - 1])

cao = []
for i in range(1, a[1]):
	cao.append(c[0] - c[-i])

dui = 0
cha.sort()
cao.sort()

i = 0
j = 0
while(j < a[1] - 1):
	if cha[i] <= cao[j]:
		dui += 1
		i += 1
		j += 1
	else:
		j += 1

print (a[1] - dui)


I found an interesting problem on https://codeforces.com/problemset/problem/1046/F:
After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.

These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet.

This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $x$ satoshi (1 bitcoin = $10^8$ satoshi). She can create new public address wallets for free and is willing to pay $f$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal.

-----Input-----

First line contains number $N$ ($1 \leq N \leq 200\,000$) representing total number of public addresses Alice has.

Next line contains $N$ integer numbers $a_i$ ($1 \leq a_i \leq 10^9$) separated by a single space, representing how many satoshi Alice has in her public addresses.

Last line contains two numbers $x$, $f$ ($1 \leq f < x \leq 10^9$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction.

-----Output-----

Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal.

-----Example-----
Input
3
13 7 6
6 2

Output
4

-----Note-----

Alice can make two transactions in a following way:

0. 13 7 6 (initial state)

1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)

2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)

Since cost per transaction is 2 satoshies, total fee is 4.

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

#JMD
#Nagendra Jha-4096
import sys
import bisect

#import fractions
#import numpy

###File Operations###
fileoperation=0
if(fileoperation):
    orig_stdout = sys.stdout
    orig_stdin = sys.stdin
    inputfile = open('W:/Competitive Programming/input.txt', 'r')
    outputfile = open('W:/Competitive Programming/output.txt', 'w')
    sys.stdin = inputfile
    sys.stdout = outputfile

###Defines...###
mod=1000000007

###FUF's...###
def nospace(l):
    ans=''.join(str(i) for i in l)
    return ans

def search(a, x):
    'Find rightmost value less than or equal to x'
    i = bisect.bisect_right(a, x)
    if(i==0):
        return -1
    return i-1

##### Main ####
n=int(input())
a=list(map(int, sys.stdin.readline().split(' ')))
x,f=map(int, sys.stdin.readline().split(' '))

ans=0

for aa in a:
    if(aa<=x):
        continue
    val=(aa-x)//(x+f)
    if(val*(x+f)<aa-x):
        val+=1
    ans+=val
print(f*ans)

#####File Operations#####
if(fileoperation):
    sys.stdout = orig_stdout
    sys.stdin = orig_stdin
    inputfile.close()
    outputfile.close()


I found an interesting problem on https://codeforces.com/problemset/problem/1047/A:
Little C loves number «3» very much. He loves all things about it.

Now he has a positive integer $n$. He wants to split $n$ into $3$ positive integers $a,b,c$, such that $a+b+c=n$ and none of the $3$ integers is a multiple of $3$. Help him to find a solution.

-----Input-----

A single line containing one integer $n$ ($3 \leq n \leq 10^9$) — the integer Little C has.

-----Output-----

Print $3$ positive integers $a,b,c$ in a single line, such that $a+b+c=n$ and none of them is a multiple of $3$.

It can be proved that there is at least one solution. If there are multiple solutions, print any of them.

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

Output
1 1 1
Input
233
Output
77 77 79

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

n = int(input())
if not (n - 2) % 3:
    print(1, 2, n - 3)
else:
    print(1, 1, n - 2)


I found an interesting problem on https://codeforces.com/problemset/problem/1047/B:
There are $n$ points on the plane, $(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$.

You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.

-----Input-----

First line contains one integer $n$ ($1 \leq n \leq 10^5$).

Each of the next $n$ lines contains two integers $x_i$ and $y_i$ ($1 \leq x_i,y_i \leq 10^9$).

-----Output-----

Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.

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

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

Output
4

-----Note-----

Illustration for the first example: [Image]

Illustration for the second example: [Image]

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

n = int(input())
res = -float('inf')
for _ in range(n):
    a,b = list(map(int,input().split()))
    res = max(res,a+b)
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1051/B:
You are given a set of all integers from $l$ to $r$ inclusive, $l < r$, $(r - l + 1) \le 3 \cdot 10^5$ and $(r - l)$ is always odd.

You want to split these numbers into exactly $\frac{r - l + 1}{2}$ pairs in such a way that for each pair $(i, j)$ the greatest common divisor of $i$ and $j$ is equal to $1$. Each number should appear in exactly one of the pairs.

Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.

-----Input-----

The only line contains two integers $l$ and $r$ ($1 \le l < r \le 10^{18}$, $r - l + 1 \le 3 \cdot 10^5$, $(r - l)$ is odd).

-----Output-----

If any solution exists, print "YES" in the first line. Each of the next $\frac{r - l + 1}{2}$ lines should contain some pair of integers. GCD of numbers in each pair should be equal to $1$. All $(r - l + 1)$ numbers should be pairwise distinct and should have values from $l$ to $r$ inclusive.

If there are multiple solutions, print any of them.

If there exists no solution, print "NO".

-----Example-----
Input
1 8

Output
YES
2 7
4 1
3 8
6 5

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

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

print('YES')
for i in range(a, b, 2):
    print(i, i + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1051/D:
You are given a grid, consisting of $2$ rows and $n$ columns. Each cell of this grid should be colored either black or white.

Two cells are considered neighbours if they have a common border and share the same color. Two cells $A$ and $B$ belong to the same component if they are neighbours, or if there is a neighbour of $A$ that belongs to the same component with $B$.

Let's call some bicoloring beautiful if it has exactly $k$ components.

Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo $998244353$.

-----Input-----

The only line contains two integers $n$ and $k$ ($1 \le n \le 1000$, $1 \le k \le 2n$) — the number of columns in a grid and the number of components required.

-----Output-----

Print a single integer — the number of beautiful bicolorings modulo $998244353$.

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

Output
12

Input
4 1

Output
2

Input
1 2

Output
2

-----Note-----

One of possible bicolorings in sample $1$: [Image]

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

n,k=map(int,input().split())
same=[0]*(k+1)
diff=[0]*(k+1)
same[1]=2
if k>1:
    diff[2]=2
for i in range(n-1):
    newsame=[0]*(k+1)
    newdiff=[0]*(k+1)
    for i in range(1,k+1):
        newsame[i]=(same[i]+same[i-1]+2*diff[i])%998244353
    for i in range(2,k+1):
        newdiff[i]=(2*same[i-1]+diff[i]+diff[i-2])%998244353
    same=newsame
    diff=newdiff
print((same[-1]+diff[-1])%998244353)


I found an interesting problem on https://codeforces.com/problemset/problem/1051/E:
Vasya owns three big integers — $a, l, r$. Let's define a partition of $x$ such a sequence of strings $s_1, s_2, \dots, s_k$ that $s_1 + s_2 + \dots + s_k = x$, where $+$ is a concatanation of strings. $s_i$ is the $i$-th element of the partition. For example, number $12345$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.

Let's call some partition of $a$ beautiful if each of its elements contains no leading zeros.

Vasya want to know the number of beautiful partitions of number $a$, which has each of $s_i$ satisfy the condition $l \le s_i \le r$. Note that the comparison is the integer comparison, not the string one.

Help Vasya to count the amount of partitions of number $a$ such that they match all the given requirements. The result can be rather big, so print it modulo $998244353$.

-----Input-----

The first line contains a single integer $a~(1 \le a \le 10^{1000000})$.

The second line contains a single integer $l~(0 \le l \le 10^{1000000})$.

The third line contains a single integer $r~(0 \le r \le 10^{1000000})$.

It is guaranteed that $l \le r$.

It is also guaranteed that numbers $a, l, r$ contain no leading zeros.

-----Output-----

Print a single integer — the amount of partitions of number $a$ such that they match all the given requirements modulo $998244353$.

-----Examples-----
Input
135
1
15

Output
2

Input
10000
0
9

Output
1

-----Note-----

In the first test case, there are two good partitions $13+5$ and $1+3+5$.

In the second test case, there is one good partition $1+0+0+0+0$.

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

def kmp(pat,text,t):
    s=pat+"?"+text;
    #z[i] es el tamaño del prefijo mas largo de, formado por una subcadena s[i:...]
    z=[0 for i in range(len(s))]
    L=0;R=0;n=len(s);
    for i in range(1,len(s)):
        if i>R:
            L=R=i
            while R<n and s[R-L]==s[R]:
                R+=1
            z[i]=R-L
            R-=1
        elif z[i-L]+i<=R:
            z[i]=z[i-L]
        else:
            L=i
            while R<n and s[R-L]==s[R]:
                R+=1
            z[i]=R-L
            R-=1
    for i in range(len(pat)+1,len(z)):
        dp[t][i-(len(pat)+1)]=z[i]%len(pat)
from sys import stdin
mod=998244353
a=stdin.readline().strip()
l=stdin.readline().strip()
r=stdin.readline().strip()
x=len(l)
y=len(r)
n=len(a)
dp=[[0 for i in range(len(a))]for j in range(2)]
ans=[0 for i in range(len(a)+1)]
ans[-1]=1
kmp(l,a,0)
kmp(r,a,1)
auxl=x-1
auxr=y-1
acum=[0 for i in range(n+2)]
acum[n]=1
for i in range(n-1,-1,-1):
    if a[i]=="0":
        if l[0]=="0":
            ans[i]=ans[i+1]
        acum[i]=(acum[i+1]+ans[i])%mod
        continue
    if auxl>=n:
        acum[i]=(acum[i+1]+ans[i])%mod
        continue
    if auxl!=auxr:
        if (auxl+i)<n and a[dp[0][i]+i]>=l[dp[0][i]]:
            ans[i]=(ans[i]+ans[i+auxl+1])%mod
        if (auxr+i)<n and a[dp[1][i]+i]<=r[dp[1][i]]:
            ans[i]=(ans[i]+ans[i+auxr+1])%mod
    else:
        if (auxl+i)<n and a[dp[0][i]+i]>=l[dp[0][i]] and a[dp[1][i]+i]<=r[dp[1][i]]:
            ans[i]=(ans[i]+ans[i+auxl+1])%mod
    lim1=auxl+i+2
    lim2=min(auxr+i+1,n+1)
    if lim1<lim2:
        ans[i]=(ans[i]+acum[lim1]-acum[lim2])%mod
    acum[i]=(acum[i+1]+ans[i])%mod
print(ans[0]%mod)


I found an interesting problem on https://codeforces.com/problemset/problem/1054/A:
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor $x$, Egor on the floor $y$ (not on the same floor with Masha).

The house has a staircase and an elevator. If Masha uses the stairs, it takes $t_1$ seconds for her to walk between adjacent floors (in each direction). The elevator passes between adjacent floors (in each way) in $t_2$ seconds. The elevator moves with doors closed. The elevator spends $t_3$ seconds to open or close the doors. We can assume that time is not spent on any action except moving between adjacent floors and waiting for the doors to open or close. If Masha uses the elevator, it immediately goes directly to the desired floor.

Coming out of the apartment on her floor, Masha noticed that the elevator is now on the floor $z$ and has closed doors. Now she has to choose whether to use the stairs or use the elevator.

If the time that Masha needs to get to the Egor's floor by the stairs is strictly less than the time it will take her using the elevator, then she will use the stairs, otherwise she will choose the elevator.

Help Mary to understand whether to use the elevator or the stairs.

-----Input-----

The only line contains six integers $x$, $y$, $z$, $t_1$, $t_2$, $t_3$ ($1 \leq x, y, z, t_1, t_2, t_3 \leq 1000$) — the floor Masha is at, the floor Masha wants to get to, the floor the elevator is located on, the time it takes Masha to pass between two floors by stairs, the time it takes the elevator to pass between two floors and the time it takes for the elevator to close or open the doors.

It is guaranteed that $x \ne y$.

-----Output-----

If the time it will take to use the elevator is not greater than the time it will take to use the stairs, print «YES» (without quotes), otherwise print «NO> (without quotes).

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

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

Output
YES
Input
1 6...

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

x,y,z,t1,t2,t3=list(map(int,input().strip().split()))
T1=abs(y-x)*t2+abs(z-x)*t2+t3*3
T2=abs(y-x)*t1
if (T1<=T2):
	print ("YES")
else:
	print ("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1054/B:
Initially Ildar has an empty array. He performs $n$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array.

The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset $[0, 2, 3]$ is $1$, while the mex of the multiset $[1, 2, 1]$ is $0$.

More formally, on the step $m$, when Ildar already has an array $a_1, a_2, \ldots, a_{m-1}$, he chooses some subset of indices $1 \leq i_1 < i_2 < \ldots < i_k < m$ (possibly, empty), where $0 \leq k < m$, and appends the $mex(a_{i_1}, a_{i_2}, \ldots a_{i_k})$ to the end of the array.

After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $a_1, a_2, \ldots, a_n$ the minimum step $t$ such that he has definitely made a mistake on at least one of the steps $1, 2, \ldots, t$, or determine that he could have obtained this array without mistakes.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 100\,000$) — the number of steps Ildar made.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 10^9$) — the array Ildar obtained.

-----Output-----

If Ildar could have chosen the subsets on each step in such a way that the resulting array is $a_1, a_2, \ldots, a_n$, print $-1$.

Otherwise print a single integer $t$ — the smallest index of a step such that a mistake was made on at least one step among steps $1, 2, \ldots, t$.

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

Output
-1
Input
3
1 0 1

Output
1
Input
4
0 1 2 239

Output
4

-----Note-----

In the first example it is possible that Ildar made no mistakes. Here is the process he could have followed.  $1$-st step. The initial array is empty. He can choose an empty subset and obtain $0$, because the mex of an empty set is $0$. Appending this value to the end he gets the array $[0]$.  $2$-nd step. The current array is $[0]$. He can choose a subset $[0]$...

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

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

i = 1
m = -1
ans = -1
for x in a:
    if x > m + 1:
        ans = i
        break
    else:
        i = i + 1
        m = max( m, x )

print( ans )


I found an interesting problem on https://codeforces.com/problemset/problem/1054/C:
There are $n$ children numbered from $1$ to $n$ in a kindergarten. Kindergarten teacher gave $a_i$ ($1 \leq a_i \leq n$) candies to the $i$-th child. Children were seated in a row in order from $1$ to $n$ from left to right and started eating candies.

While the $i$-th child was eating candies, he calculated two numbers $l_i$ and $r_i$ — the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively.

Formally, $l_i$ is the number of indices $j$ ($1 \leq j < i$), such that $a_i < a_j$ and $r_i$ is the number of indices $j$ ($i < j \leq n$), such that $a_i < a_j$.

Each child told to the kindergarten teacher the numbers $l_i$ and $r_i$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $l$ and $r$ determine whether she could have given the candies to the children such that all children correctly calculated their values $l_i$ and $r_i$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.

-----Input-----

On the first line there is a single integer $n$ ($1 \leq n \leq 1000$) — the number of children in the kindergarten.

On the next line there are $n$ integers $l_1, l_2, \ldots, l_n$ ($0 \leq l_i \leq n$), separated by spaces.

On the next line, there are $n$ integer numbers $r_1, r_2, \ldots, r_n$ ($0 \leq r_i \leq n$), separated by spaces.

-----Output-----

If there is no way to distribute the candies to the children so that all of them calculated their numbers correctly, print «NO» (without quotes).

Otherwise, print «YES» (without quotes) on the first line. On the next line, print $n$ integers $a_1, a_2, \ldots, a_n$, separated by spaces — the numbers of candies the children $1, 2, \ldots, n$ received, respectively. Note that some of these numbers can be equal, but all numbers should satisfy the condition $1 \leq a_i \leq n$. The number of children...

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

n=int(input())

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

a=[[l[i]+r[i],i] for i in range(n)]
a.sort()
#print(a)
candies=[0 for i in range(n)]

if(a[0][0] != 0):

    print('NO')
    return
else:
    candies[a[0][1]] = n - a[0][0]

for i in range(1,n):
    if(a[i][0] != a[i-1][0] and a[i][0]!=i):
        print('NO')
 #       print(i,a[i])
        return
  #  print(a[i][1],n-a[i][0],i)
    candies[a[i][1]] = n - a[i][0]
#print(candies)
for i in range(n):
    l1=0
    r1=0
    for j in range(i):
        if(candies[j]>candies[i]):
            l1+=1
    for j in range(i+1,n):
        if(candies[j]>candies[i]):
            r1+=1
 #   print(l1,r1)
    if(l1 != l[i] or r1 != r[i]):
        print('NO')
        return
print('YES')
print(*candies)


I found an interesting problem on https://codeforces.com/problemset/problem/1054/D:
At a break Vanya came to the class and saw an array of $n$ $k$-bit integers $a_1, a_2, \ldots, a_n$ on the board. An integer $x$ is called a $k$-bit integer if $0 \leq x \leq 2^k - 1$.

Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $i$ ($1 \leq i \leq n$) and replace the number $a_i$ with the number $\overline{a_i}$. We define $\overline{x}$ for a $k$-bit integer $x$ as the $k$-bit integer such that all its $k$ bits differ from the corresponding bits of $x$.

Vanya does not like the number $0$. Therefore, he likes such segments $[l, r]$ ($1 \leq l \leq r \leq n$) such that $a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$, where $\oplus$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \leq n \leq 200\,000$, $1 \leq k \leq 30$).

The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 2^k - 1$), separated by spaces — the array of $k$-bit integers.

-----Output-----

Print one integer — the maximum possible number of segments with XOR not equal to $0$ that can be obtained by making several (possibly $0$) operations described in the statement.

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

Output
5
Input
6 3
1 4 4 7 3 4

Output
19

-----Note-----

In the first example if Vasya does not perform any operations, he gets an array that has $5$ segments that Vanya likes. If he performs the operation with $i = 2$, he gets an array $[1, 0, 0]$, because $\overline{3} = 0$ when $k = 2$. This array has $3$ segments that Vanya likes. Also, to get an array with $5$ segments that Vanya likes, he can perform two operations with $i = 3$ and with $i = 2$. He then gets an array $[1, 0, 3]$. It can be proven that he can't obtain $6$ or more segments that...

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

n, k = [int(i) for i in input().split()]
d = dict()
d[0] = 1
x = 0
for i in [int(i) for i in input().split()]:
    x ^= i
    v = min(x, (1 << k) - x - 1)
    if v not in list(d.keys()):
        d[v] = 0
    d[v] += 1
ans = 0
for k, v in list(d.items()):
    c1 = v // 2
    c2 = v - c1
    ans += c1 * (c1 - 1) // 2 + c2 * (c2 - 1) // 2
print(n * (n - 1) // 2 + n - ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1055/A:
Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.

In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $n$ stations numbered from $1$ to $n$. Bob lives near the station with number $1$, while Alice lives near the station with number $s$. The metro line has two tracks. Trains on the first track go from the station $1$ to the station $n$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.

Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.

When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.

-----Input-----

The first line contains two integers $n$ and $s$ ($2 \le s \le n \le 1000$) — the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station $1$.

Next lines describe information about closed and open stations.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($a_i = 0$ or $a_i = 1$). If $a_i = 1$, then the $i$-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track.

The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($b_i = 0$ or $b_i = 1$). If $b_i = 1$, then the $i$-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second...

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

#
import collections, atexit, math, sys, bisect

sys.setrecursionlimit(1000000)
def getIntList():
    return list(map(int, input().split()))

try :
    #raise ModuleNotFoundError
    import numpy
    def dprint(*args, **kwargs):
        #print(*args, **kwargs, file=sys.stderr)
        # in python 3.4 **kwargs is invalid???
        print(*args,  file=sys.stderr)
    dprint('debug mode')
except Exception:
    def dprint(*args, **kwargs):
        pass

inId = 0
outId = 0
if inId>0:
    dprint('use input', inId)
    sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件
if outId>0:
    dprint('use output', outId)
    sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件
    atexit.register(lambda :sys.stdout.close())     #idle 中不会执行 atexit

N, S = getIntList()
z1 = getIntList()
z2 = getIntList()
#print(N)

if z1[0] ==0:
    print('NO')
    return

if z1[S-1] ==1:
    print('YES')
    return

if z2[S-1]==0:
    print('NO')
    return

for i in range(S-1, N):
    if z1[i] ==1 and z2[i]==1:
        print('YES')
        return

print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1055/B:
Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...

To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $l$ centimeters after haircut, where $l$ is her favorite number. Suppose, that the Alice's head is a straight line on which $n$ hairlines grow. Let's number them from $1$ to $n$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $l$, given that all hairlines on that segment had length strictly greater than $l$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.

Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types:  $0$ — Alice asks how much time the haircut would take if she would go to the hairdresser now.  $1$ $p$ $d$ — $p$-th hairline grows by $d$ centimeters.

Note, that in the request $0$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.

-----Input-----

The first line contains three integers $n$, $m$ and $l$ ($1 \le n, m \le 100\,000$, $1 \le l \le 10^9$) — the number of hairlines, the number of requests and the favorite number of Alice.

The second line contains $n$ integers $a_i$ ($1 \le a_i \le 10^9$) — the initial lengths of all hairlines of Alice.

Each of the following $m$ lines contains a request in the format described in the statement.

The request description starts with an integer $t_i$. If $t_i = 0$, then you need to find the time the haircut would take. Otherwise, $t_i = 1$ and in this moment one hairline grows. The rest of the line than contains two more integers: $p_i$ and $d_i$ ($1 \le p_i \le n$, $1 \le d_i \le 10^9$) — the number of the...

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

#!/usr/bin/env python3
import sys

def count_it():
    return len(''.join(list([' ' if x <= l else '1' for x in h])).split())

n, m, l = list([int(x) for x in sys.stdin.readline().split(' ')])
h = list([int(x) for x in sys.stdin.readline().split(' ')])
k = count_it()
for mi in range(m):
    request = sys.stdin.readline().split(' ')
    if len(request) == 1:
        print(k)
    else:
        r, p, d = list([int(x) for x in request])
        h[p - 1] += d
        if (h[p - 1] > l) and (h[p - 1] - d <= l):
            if n == 1:
                k += 1
            else:
                if (p - 1 == 0 and h[1] <= l) or (p == len(h) and h[p - 2] <= l) or (h[p - 2] <= l and h[p] <= l):
                    k += 1
                elif p - 1 != 0 and p != len(h) and h[p - 2] > l and h[p] > l:
                    k -= 1


I found an interesting problem on https://codeforces.com/problemset/problem/1055/C:
Bob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days $[l_a; r_a]$ are lucky, then there are some unlucky days: $[r_a + 1; l_a + t_a - 1]$, and then there are lucky days again: $[l_a + t_a; r_a + t_a]$ and so on. In other words, the day is lucky for Alice if it lies in the segment $[l_a + k t_a; r_a + k t_a]$ for some non-negative integer $k$.

The Bob's lucky day have similar structure, however the parameters of his sequence are different: $l_b$, $r_b$, $t_b$. So a day is a lucky for Bob if it lies in a segment $[l_b + k t_b; r_b + k t_b]$, for some non-negative integer $k$.

Alice and Bob want to participate in team competitions together and so they want to find out what is the largest possible number of consecutive days, which are lucky for both Alice and Bob.

-----Input-----

The first line contains three integers $l_a$, $r_a$, $t_a$ ($0 \le l_a \le r_a \le t_a - 1, 2 \le t_a \le 10^9$) and describes Alice's lucky days.

The second line contains three integers $l_b$, $r_b$, $t_b$ ($0 \le l_b \le r_b \le t_b - 1, 2 \le t_b \le 10^9$) and describes Bob's lucky days.

It is guaranteed that both Alice and Bob have some unlucky days.

-----Output-----

Print one integer: the maximum number of days in the row that are lucky for both Alice and Bob.

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

Output
2

Input
0 1 3
2 3 6

Output
1

-----Note-----

The graphs below correspond to the two sample tests and show the lucky and unlucky days of Alice and Bob as well as the possible solutions for these tests.

[Image]

[Image]

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

from sys import stdin, stdout
from math import sin, tan, cos, pi, atan2, sqrt, acos, atan, factorial

def gcd(a, b):
    if not b:
        return a
    else:
        return gcd(b, a % b)

def solution(la, ra, ta, lb, rb, tb):
    g = gcd(ta, tb)
    d = (lb - la) % g
    return min(ra - la + 1 - d, rb - lb + 1)

la, ra, ta = map(int, stdin.readline().split())
lb, rb, tb = map(int, stdin.readline().split())

ans = max(solution(la, ra, ta, lb, rb, tb), solution(lb, rb, tb, la, ra, ta))
stdout.write(str(max(0, ans)))


I found an interesting problem on https://codeforces.com/problemset/problem/1055/E:
You are a given a list of integers $a_1, a_2, \ldots, a_n$ and $s$ of its segments $[l_j; r_j]$ (where $1 \le l_j \le r_j \le n$).

You need to select exactly $m$ segments in such a way that the $k$-th order statistic of the multiset of $a_i$, where $i$ is contained in at least one segment, is the smallest possible. If it's impossible to select a set of $m$ segments in such a way that the multiset contains at least $k$ elements, print -1.

The $k$-th order statistic of a multiset is the value of the $k$-th element after sorting the multiset in non-descending order.

-----Input-----

The first line contains four integers $n$, $s$, $m$ and $k$ ($1 \le m \le s \le 1500$, $1 \le k \le n \le 1500$) — the size of the list, the number of segments, the number of segments to choose and the statistic number.

The second line contains $n$ integers $a_i$ ($1 \le a_i \le 10^9$) — the values of the numbers in the list.

Each of the next $s$ lines contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le n$) — the endpoints of the segments.

It is possible that some segments coincide.

-----Output-----

Print exactly one integer — the smallest possible $k$-th order statistic, or -1 if it's impossible to choose segments in a way that the multiset contains at least $k$ elements.

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

Output
2

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

Output
1

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

Output
-1

-----Note-----

In the first example, one possible solution is to choose the first and the third segment. Together they will cover three elements of the list (all, except for the third one). This way the $2$-nd order statistic for the covered elements is $2$.

[Image]

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

n, s, m, k = map(int, input().split())
a = list(map(int, input().split()))
nt = [-1 for i in range(n+1)]
for i in range(s):
	l, r  = map(int, input().split())
	l-=1
	for j in range(l, r):
		nt[j] = max(nt[j], r)

dp = [[0 for i in range(m+1)] for i in range(n+1)]
sum = [0 for i in range(n+1)]
def solve(mid):
	for i in range(n+1):
		for j in range(m+1):
			dp[i][j] = 0
	for i in range(n):
		if a[i] <= mid:
			sum[i+1] = 1
		else:
			sum[i+1] = 0
		sum[i+1] += sum[i]
	for i in range(0, n+1):
		for j in range(m+1):
			if i > 0:
				dp[i][j] = max(dp[i][j], dp[i-1][j])
			if nt[i] != -1 and j < m:
				dp[nt[i]][j+1] = max(dp[nt[i]][j+1], dp[i][j] + sum[nt[i]] - sum[i])
	return dp[n][m]

lo, hi, ans = 1, 10**9, -1
while lo <= hi:
	mid = (lo+hi)//2
	if(solve(mid) >= k):
		ans = mid
		hi = mid-1
	else:
		lo = mid+1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1056/A:
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.

During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?

-----Input-----

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

The next $n$ lines describe the stops. Each of them starts with a single integer $r$ ($1 \le r \le 100$) — the number of tram lines that stop there. $r$ distinct integers follow, each one between $1$ and $100$, inclusive, — the line numbers. They can be in arbitrary order.

It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.

-----Output-----

Print all tram lines that Arkady could be in, in arbitrary order.

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

Output
1 4

Input
5
1 1
10 10 9 8 7 100 5 4 3 99 1
5 1 2 3 4 5
5 4 1 3 2 5
4 10 1 5 3

Output
1

-----Note-----

Consider the first example. Arkady woke up three times. The first time he saw a stop with lines $1$, $4$, $6$. The second time he saw a stop with lines $1$, $4$. The third time he saw a stop with lines $10$, $5$, $6$, $4$ and $1$. He can be in a tram of one of two lines: $1$ or $4$.

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

#
import collections, atexit, math, sys, bisect

sys.setrecursionlimit(1000000)
def getIntList():
    return list(map(int, input().split()))

try :
    #raise ModuleNotFoundError
    import numpy
    def dprint(*args, **kwargs):
        #print(*args, **kwargs, file=sys.stderr)
        # in python 3.4 **kwargs is invalid???
        print(*args,  file=sys.stderr)
    dprint('debug mode')
except Exception:
    def dprint(*args, **kwargs):
        pass

inId = 0
outId = 0
if inId>0:
    dprint('use input', inId)
    sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件
if outId>0:
    dprint('use output', outId)
    sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件
    atexit.register(lambda :sys.stdout.close())     #idle 中不会执行 atexit

N, = getIntList()
#print(N)
s0 = set()
for i in range(N):
    za = getIntList()
    ss = set(za[1:])
    if len(s0) ==0:
        s0 = ss
    else:
        s0&= ss
for x in s0:
    print(x,end= ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/1056/B:
Arkady and his friends love playing checkers on an $n \times n$ field. The rows and the columns of the field are enumerated from $1$ to $n$.

The friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friends one set of candies per each cell of the field: the set of candies for cell $(i, j)$ will have exactly $(i^2 + j^2)$ candies of unique type.

There are $m$ friends who deserve the present. How many of these $n \times n$ sets of candies can be split equally into $m$ parts without cutting a candy into pieces? Note that each set has to be split independently since the types of candies in different sets are different.

-----Input-----

The only line contains two integers $n$ and $m$ ($1 \le n \le 10^9$, $1 \le m \le 1000$) — the size of the field and the number of parts to split the sets into.

-----Output-----

Print a single integer — the number of sets that can be split equally.

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

Output
1

Input
6 5

Output
13

Input
1000000000 1

Output
1000000000000000000

-----Note-----

In the first example, only the set for cell $(3, 3)$ can be split equally ($3^2 + 3^2 = 18$, which is divisible by $m=3$).

In the second example, the sets for the following cells can be divided equally:   $(1, 2)$ and $(2, 1)$, since $1^2 + 2^2 = 5$, which is divisible by $5$;  $(1, 3)$ and $(3, 1)$;  $(2, 4)$ and $(4, 2)$;  $(2, 6)$ and $(6, 2)$;  $(3, 4)$ and $(4, 3)$;  $(3, 6)$ and $(6, 3)$;  $(5, 5)$.

In the third example, sets in all cells can be divided equally, since $m = 1$.

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

a, b = map(int, input().split())
A = set()
A_ = set()
B_ = set()
A__ = {}
B__ = {}
calc = 0
for i in range(1, b + 1):
    for j in range(1, b + 1):
        if (i ** 2 + j ** 2) % b == 0:
            A.add((i % b, j % b))
            B_.add(j % b)
            A_.add(i % b)
for i in A_:
    A__[i] = a // b
    if a % b >= i and i != 0:
        A__[i] += 1
for i in B_:
    B__[i] = a // b
    if a % b >= i and i != 0:
        B__[i] += 1
for i in A:
    calc += A__[i[0]] * B__[i[1]]
print(calc)


I found an interesting problem on https://codeforces.com/problemset/problem/1056/D:
There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from $1$ to $n$, the junction $1$ is called the root.

A subtree of a junction $v$ is a set of junctions $u$ such that the path from $u$ to the root must pass through $v$. Note that $v$ itself is included in a subtree of $v$.

A leaf is such a junction that its subtree contains exactly one junction.

The New Year is coming, so Arkady wants to decorate the tree. He will put a light bulb of some color on each leaf junction and then count the number happy junctions. A happy junction is such a junction $t$ that all light bulbs in the subtree of $t$ have different colors.

Arkady is interested in the following question: for each $k$ from $1$ to $n$, what is the minimum number of different colors needed to make the number of happy junctions be greater than or equal to $k$?

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of junctions in the tree.

The second line contains $n - 1$ integers $p_2$, $p_3$, ..., $p_n$ ($1 \le p_i < i$), where $p_i$ means there is a branch between junctions $i$ and $p_i$. It is guaranteed that this set of branches forms a tree.

-----Output-----

Output $n$ integers. The $i$-th of them should be the minimum number of colors needed to make the number of happy junctions be at least $i$.

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

Output
1 1 2

Input
5
1 1 3 3

Output
1 1 1 2 3

-----Note-----

In the first example for $k = 1$ and $k = 2$ we can use only one color: the junctions $2$ and $3$ will be happy. For $k = 3$ you have to put the bulbs of different colors to make all the junctions happy.

In the second example for $k = 4$ you can, for example, put the bulbs of color $1$ in junctions $2$ and $4$, and a bulb of color $2$ into junction $5$. The happy junctions are the ones with indices $2$, $3$, $4$ and $5$ then.

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

n = int(input())
tr = {}
p = [int(s) for s in input().split()]
for i in range(n-1):
    if not tr.get(p[i]-1):
        tr[p[i]-1] = []
    tr[p[i]-1].append(i+1)
# print(tr)
lc = [-1 for i in range(n)]
def get_lc(i):
    if lc[i] == -1:
        if tr.get(i):
            lc[i] = 0
            for j in tr[i]:
                lc[i] += get_lc(j)
        else:
            lc[i] = 1
    return lc[i]
for i in range(n-1, -1, -1):
    get_lc(i)
print(*sorted(lc))


I found an interesting problem on https://codeforces.com/problemset/problem/1056/E:
One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal $s$ towards a faraway galaxy. Recently they've received a response $t$ which they believe to be a response from aliens! The scientists now want to check if the signal $t$ is similar to $s$.

The original signal $s$ was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal $t$, however, does not look as easy as $s$, but the scientists don't give up! They represented $t$ as a sequence of English letters and say that $t$ is similar to $s$ if you can replace all zeros in $s$ with some string $r_0$ and all ones in $s$ with some other string $r_1$ and obtain $t$. The strings $r_0$ and $r_1$ must be different and non-empty.

Please help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings $r_0$ and $r_1$) that transform $s$ to $t$.

-----Input-----

The first line contains a string $s$ ($2 \le |s| \le 10^5$) consisting of zeros and ones — the original signal.

The second line contains a string $t$ ($1 \le |t| \le 10^6$) consisting of lowercase English letters only — the received signal.

It is guaranteed, that the string $s$ contains at least one '0' and at least one '1'.

-----Output-----

Print a single integer — the number of pairs of strings $r_0$ and $r_1$ that transform $s$ to $t$.

In case there are no such pairs, print $0$.

-----Examples-----
Input
01
aaaaaa

Output
4

Input
001
kokokokotlin

Output
2

-----Note-----

In the first example, the possible pairs $(r_0, r_1)$ are as follows:  "a", "aaaaa"  "aa", "aaaa"  "aaaa", "aa"  "aaaaa", "a"

The pair "aaa", "aaa" is not allowed, since $r_0$ and $r_1$ must be different.

In the second example, the following pairs are possible:   "ko", "kokotlin"  "koko", "tlin"

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

def gethash(l,r):
	return (ha[r]-((ha[l]*p[r-l])%mod)+mod)%mod

def check(lenx,leny):
	ha_0=-1
	ha_1=-1
	j=0
	for i in range(m):
		if s[i]=="0":
			tmp=gethash(j,j+lenx)
			if ha_0==-1:
				ha_0=tmp
			elif ha_0!=tmp:
				return 0
			j+=lenx
		else:
			tmp=gethash(j,j+leny)
			if ha_1==-1:
				ha_1=tmp
			elif ha_1!=tmp:
				return 0
			j+=leny
	return ha_0!=ha_1

s=list(input())
t=list(input())
m=len(s)
n=len(t)

p=[1]
bas=2333
mod=(1<<50)-2
for i in range(1,n+1):
	p.append((p[i-1]*bas)%mod)
ha=[0]
for i in range(1,n+1):
	ha.append((ha[i-1]*bas+ord(t[i-1]))%mod)
cnt_0=0
cnt_1=0
for x in s:
	if x=="0":
		cnt_0+=1
	else:
		cnt_1+=1

ans=0
for i in range(1,n//cnt_0+1):#length of r_0
	j=n-cnt_0*i
	if j%cnt_1==0 and j!=0:
		j//=cnt_1
		ans+=check(i,j)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1057/A:
Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values $p_i$ — the index of the router to which the $i$-th router was connected after being purchased ($p_i < i$).

There are $n$ routers in Boogle in total now. Print the sequence of routers on the path from the first to the $n$-th router.

-----Input-----

The first line contains integer number $n$ ($2 \le n \le 200000$) — the number of the routers. The following line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i < i$), where $p_i$ is equal to index of the router to which the $i$-th was connected after purchase.

-----Output-----

Print the path from the $1$-st to the $n$-th router. It starts with $1$ and ends with $n$. All the elements in the path should be distinct.

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

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

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

Output
1 3 7

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

n = int ( input ())
a = [ 0 ] + list (map(int,input().split()))
z=[]
while n != 0:
    z +=[n]
    n = a [ n -1 ]
z.reverse()
for i in z:
    print(i,end=" ")