I found an interesting problem on https://codeforces.com/problemset/problem/1140/E:
Let's denote that some array $b$ is bad if it contains a subarray $b_l, b_{l+1}, \dots, b_{r}$ of odd length more than $1$ ($l < r$ and $r - l + 1$ is odd) such that $\forall i \in \{0, 1, \dots, r - l\}$ $b_{l + i} = b_{r - i}$.

If an array is not bad, it is good.

Now you are given an array $a_1, a_2, \dots, a_n$. Some elements are replaced by $-1$. Calculate the number of good arrays you can obtain by replacing each $-1$ with some integer from $1$ to $k$.

Since the answer can be large, print it modulo $998244353$.

-----Input-----

The first line contains two integers $n$ and $k$ ($2 \le n, k \le 2 \cdot 10^5$) — the length of array $a$ and the size of "alphabet", i. e., the upper bound on the numbers you may use to replace $-1$.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($a_i = -1$ or $1 \le a_i \le k$) — the array $a$.

-----Output-----

Print one integer — the number of good arrays you can get, modulo $998244353$.

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

Output
9

Input
5 2
1 -1 -1 1 2

Output
0

Input
5 3
1 -1 -1 1 2

Output
2

Input
4 200000
-1 -1 12345 -1

Output
735945883

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

3.7

import sys

mod = 998244353

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

ub = [0 for i in range(n)]
b = [[0, 0] for i in range(n)]
ub[0] = 1
b[0] = [0, 1]
for i in range(1, n):
    ub[i] = ub[i - 1] * (k - 1) % mod
    sb = b[i - 1][0] + b[i - 1][1] * (k - 1) % mod
    if sb >= mod:
        sb -= mod
    for j in range(2):
        b[i][j] = sb - b[i - 1][j]
        if b[i][j] < 0:
            b[i][j] += mod

ans = 1
for arr in [a[::2], a[1::2]]:

    for i in range(1, len(arr)):
        if (arr[i] != -1) and (arr[i] == arr[i - 1]):
            print(0)
            return

    cur = -1
    for i, x in enumerate(arr):
        if x == -1:
            continue
        cnt = i - cur - 1
        if cnt > 0:
            if cur == -1:
                ans = (ans * ub[cnt - 1] * (k - 1)) % mod
            else:
                s = b[cnt - 1][0] + b[cnt - 1][1] * (k - 1) % mod
                if s >= mod:
                    s -= mod
                if x == arr[cur]:
                    s -= b[cnt - 1][0]
                else:
                    s -= b[cnt - 1][1]
                if s < 0:
                    s += mod
                ans = ans * s % mod
        cur = i
    if cur == -1:
        ans = (ans * ub[len(arr) - 1] * k) % mod
    elif cur < len(arr) - 1:
        cnt = len(arr) - cur - 1
        s = b[cnt - 1][0] + b[cnt - 1][1] * (k - 1) % mod
        if s >= mod:
            s -= mod
        ans = ans * s % mod

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1141/A:
Polycarp plays "Game 23". Initially he has a number $n$ and his goal is to transform it to $m$. In one move, he can multiply $n$ by $2$ or multiply $n$ by $3$. He can perform any number of moves.

Print the number of moves needed to transform $n$ to $m$. Print -1 if it is impossible to do so.

It is easy to prove that any way to transform $n$ to $m$ contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).

-----Input-----

The only line of the input contains two integers $n$ and $m$ ($1 \le n \le m \le 5\cdot10^8$).

-----Output-----

Print the number of moves to transform $n$ to $m$, or -1 if there is no solution.

-----Examples-----
Input
120 51840

Output
7

Input
42 42

Output
0

Input
48 72

Output
-1

-----Note-----

In the first example, the possible sequence of moves is: $120 \rightarrow 240 \rightarrow 720 \rightarrow 1440 \rightarrow 4320 \rightarrow 12960 \rightarrow 25920 \rightarrow 51840.$ The are $7$ steps in total.

In the second example, no moves are needed. Thus, the answer is $0$.

In the third example, it is impossible to transform $48$ to $72$.

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

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

if m % n != 0:
    print(-1)
else:
    x = m // n
    k = 0
    while x % 2 == 0:
        x //= 2
        k += 1
    while x % 3 == 0:
        x //= 3
        k += 1
    if x == 1:
        print(k)
    else:
        print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1141/B:
Each day in Berland consists of $n$ hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence $a_1, a_2, \dots, a_n$ (each $a_i$ is either $0$ or $1$), where $a_i=0$ if Polycarp works during the $i$-th hour of the day and $a_i=1$ if Polycarp rests during the $i$-th hour of the day.

Days go one after another endlessly and Polycarp uses the same schedule for each day.

What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.

-----Input-----

The first line contains $n$ ($1 \le n \le 2\cdot10^5$) — number of hours per day.

The second line contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 1$), where $a_i=0$ if the $i$-th hour in a day is working and $a_i=1$ if the $i$-th hour is resting. It is guaranteed that $a_i=0$ for at least one $i$.

-----Output-----

Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.

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

Output
2

Input
6
0 1 0 1 1 0

Output
2

Input
7
1 0 1 1 1 0 1

Output
3

Input
3
0 0 0

Output
0

-----Note-----

In the first example, the maximal rest starts in last hour and goes to the first hour of the next day.

In the second example, Polycarp has maximal rest from the $4$-th to the $5$-th hour.

In the third example, Polycarp has maximal rest from the $3$-rd to the $5$-th hour.

In the fourth example, Polycarp has no rest at all.

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

# # Soru 1
#
# nm = list(map(int, input().split()))
# n = nm[0]
# m = nm[1]
#
# if int(m/n) != m/n:
#     print(-1)
# elif m/n == 1:
#     print(0)
# else:
#     x = m//n
#     count = 0
#     while x%2 == 0:
#         x = x//2
#         count += 1
#     while x%3 == 0:
#         x = x//3
#         count += 1
#     if x != 1:
#         print(-1)
#     else:
#         print(count)
# Soru 2
n = int(input())
lst = list(map(int, input().split()))
lst = lst + lst
count = 0
large = 0
for i in lst:
    if i == 1:
        count += 1
    else:
        if count > large:
            large = count
        count = 0
print(large)


I found an interesting problem on https://codeforces.com/problemset/problem/1141/C:
An array of integers $p_1, p_2, \dots, p_n$ is called a permutation if it contains each number from $1$ to $n$ exactly once. For example, the following arrays are permutations: $[3, 1, 2]$, $[1]$, $[1, 2, 3, 4, 5]$ and $[4, 3, 1, 2]$. The following arrays are not permutations: $[2]$, $[1, 1]$, $[2, 3, 4]$.

Polycarp invented a really cool permutation $p_1, p_2, \dots, p_n$ of length $n$. It is very disappointing, but he forgot this permutation. He only remembers the array $q_1, q_2, \dots, q_{n-1}$ of length $n-1$, where $q_i=p_{i+1}-p_i$.

Given $n$ and $q=q_1, q_2, \dots, q_{n-1}$, help Polycarp restore the invented permutation.

-----Input-----

The first line contains the integer $n$ ($2 \le n \le 2\cdot10^5$) — the length of the permutation to restore. The second line contains $n-1$ integers $q_1, q_2, \dots, q_{n-1}$ ($-n < q_i < n$).

-----Output-----

Print the integer -1 if there is no such permutation of length $n$ which corresponds to the given array $q$. Otherwise, if it exists, print $p_1, p_2, \dots, p_n$. Print any such permutation if there are many of them.

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

Output
3 1 2
Input
5
1 1 1 1

Output
1 2 3 4 5
Input
4
-1 2 2

Output
-1

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

ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(mi())

n = ii()
a = li()
b = [0]
for x in a:
    b.append(b[-1] + x)
mn = min(b)
b = [x - mn + 1 for x in b]
if sorted(b) == list(range(1, n + 1)):
    print(*b)
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1141/D:
There are $n$ left boots and $n$ right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings $l$ and $r$, both of length $n$. The character $l_i$ stands for the color of the $i$-th left boot and the character $r_i$ stands for the color of the $i$-th right boot.

A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.

For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').

Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.

Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.

-----Input-----

The first line contains $n$ ($1 \le n \le 150000$), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).

The second line contains the string $l$ of length $n$. It contains only lowercase Latin letters or question marks. The $i$-th character stands for the color of the $i$-th left boot.

The third line contains the string $r$ of length $n$. It contains only lowercase Latin letters or question marks. The $i$-th character stands for the color of the $i$-th right boot.

-----Output-----

Print $k$ — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.

The following $k$ lines should contain pairs $a_j, b_j$ ($1 \le a_j, b_j \le n$). The $j$-th of these lines should contain the index $a_j$ of the left boot in the $j$-th pair and index $b_j$ of the right boot in the $j$-th pair. All the numbers $a_j$ should be distinct (unique), all the numbers $b_j$...

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

n = int(input())

left = [[] for _ in range(27)]
right = [[] for _ in range(27)]

for i, c in enumerate(input().strip()):
    if c == '?':
        left[26].append(i + 1)
    else:
        left[ord(c) - ord('a')].append(i + 1)
for i, c in enumerate(input().strip()):
    if c == '?':
        right[26].append(i + 1)
    else:
        right[ord(c) - ord('a')].append(i + 1)

result = []
for i in range(26):
    count = min(len(left[i]), len(right[i]))
    for j in range(count):
        result.append((left[i][j], right[i][j]))

i = 0
left_q = 0
while True:
    if left_q == len(left[26]) or i == 26:
        break
    for j in range(len(left[i]), len(right[i])):
        result.append((left[26][left_q], right[i][j]))
        left_q += 1
        if left_q == len(left[26]):
            break
    i += 1

i = 0
right_q = 0
while True:
    if right_q == len(right[26]) or i == 26:
        break
    for j in range(len(right[i]), len(left[i])):
        result.append((left[i][j], right[26][right_q]))
        right_q += 1
        if right_q == len(right[26]):
            break
    i += 1

while left_q < len(left[26]) and right_q < len(right[26]):
    result.append((left[26][left_q], right[26][right_q]))
    left_q += 1
    right_q += 1

print(len(result))
for i, j in result:
    print(i, j)


I found an interesting problem on https://codeforces.com/problemset/problem/1141/E:
A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly $n$ minutes. After a round ends, the next round starts immediately. This is repeated over and over again.

Each round has the same scenario. It is described by a sequence of $n$ numbers: $d_1, d_2, \dots, d_n$ ($-10^6 \le d_i \le 10^6$). The $i$-th element means that monster's hp (hit points) changes by the value $d_i$ during the $i$-th minute of each round. Formally, if before the $i$-th minute of a round the monster's hp is $h$, then after the $i$-th minute it changes to $h := h + d_i$.

The monster's initial hp is $H$. It means that before the battle the monster has $H$ hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to $0$. Print -1 if the battle continues infinitely.

-----Input-----

The first line contains two integers $H$ and $n$ ($1 \le H \le 10^{12}$, $1 \le n \le 2\cdot10^5$). The second line contains the sequence of integers $d_1, d_2, \dots, d_n$ ($-10^6 \le d_i \le 10^6$), where $d_i$ is the value to change monster's hp in the $i$-th minute of a round.

-----Output-----

Print -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer $k$ such that $k$ is the first minute after which the monster is dead.

-----Examples-----
Input
1000 6
-100 -200 -300 125 77 -4

Output
9

Input
1000000000000 5
-1 0 0 0 0

Output
4999999999996

Input
10 4
-3 -6 5 4

Output
-1

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

H, n = list(map(int, input().split()))
ds = [int(x) for x in input().split()]

h = H
mn = 0
for i, d in enumerate(ds):
    h += d
    mn = min(mn, h - H)
    if h <= 0:
        print(i + 1)
        break
else:
    sd = sum(ds)
    if sd >= 0:
        print(-1)
    else:
        sd = -sd
        # print(mn, sd)
        repeat = (H + mn) // sd
        h = H - repeat * sd
        # print(repeat, h)
        for i, d in enumerate(ds):
            h += d
            if h <= 0:
                print(repeat * n + i + 1)
                break
        else:
            for i, d in enumerate(ds):
                h += d
                if h <= 0:
                    print(repeat * n + i + 1 + n)
                    break


I found an interesting problem on https://codeforces.com/problemset/problem/1141/F1:
This problem is given in two editions, which differ exclusively in the constraints on the number $n$.

You are given an array of integers $a[1], a[2], \dots, a[n].$ A block is a sequence of contiguous (consecutive) elements $a[l], a[l+1], \dots, a[r]$ ($1 \le l \le r \le n$). Thus, a block is defined by a pair of indices $(l, r)$.

Find a set of blocks $(l_1, r_1), (l_2, r_2), \dots, (l_k, r_k)$ such that:

  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks $(l_i, r_i)$ and $(l_j, r_j$) where $i \neq j$ either $r_i < l_j$ or $r_j < l_i$.  For each block the sum of its elements is the same. Formally, $$a[l_1]+a[l_1+1]+\dots+a[r_1]=a[l_2]+a[l_2+1]+\dots+a[r_2]=$$ $$\dots =$$ $$a[l_k]+a[l_k+1]+\dots+a[r_k].$$  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks $(l_1', r_1'), (l_2', r_2'), \dots, (l_{k'}', r_{k'}')$ satisfying the above two requirements with $k' > k$.

 $\left. \begin{array}{|l|l|l|l|l|l|} \hline 4 & {1} & {2} & {2} & {1} & {5} & {3} \\ \hline \end{array} \right.$ The picture corresponds to the first example. Blue boxes illustrate blocks.

Write a program to find such a set of blocks.

-----Input-----

The first line contains integer $n$ ($1 \le n \le 50$) — the length of the given array. The second line contains the sequence of elements $a[1], a[2], \dots, a[n]$ ($-10^5 \le a_i \le 10^5$).

-----Output-----

In the first line print the integer $k$ ($1 \le k \le n$). The following $k$ lines should contain blocks, one per line. In each line print a pair of indices $l_i, r_i$ ($1 \le l_i \le r_i \le n$) — the bounds of the $i$-th block. You can print blocks in any order. If there are multiple answers, print any of them.

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

Output
3
7 7
2 3
4 5

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

Output
2
3 4
1 1

Input
4
1 1 1 1

Output
4
4 4
1 1
2 2
3 3

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

franxx = int(input())

life = input()
life = life.split()

darling = {}

for i in range(0, franxx):
	tmp = 0
	for j in range(i, franxx):
		tmp += int(life[j])
		darling[tmp] = (franxx, 0)

for i in range(franxx, 0, -1):
	tmp = 0
	for j in range(i - 1, franxx):
		tmp += int(life[j])
		if (darling[tmp][0] > j):
			darling[tmp] = (i - 1, 1 + darling[tmp][1])

oh_pay = "I love my darling"

for i in range(0, franxx):
	tmp = 0
	for j in range(i, franxx):
		tmp += int(life[j])
		if (oh_pay == "I love my darling" or darling[tmp][1] > darling[oh_pay][1]):
			oh_pay = tmp

print(darling[oh_pay][1])
darling[oh_pay] = (franxx, 0)

for i in range(franxx, 0, -1):
	tmp = 0
	for j in range(i - 1, franxx):
		tmp += int(life[j])
		if (tmp != oh_pay):
			continue;
		if (darling[oh_pay][0] > j):
			print(i, j + 1)
			darling[oh_pay] = (i - 1, 1 + darling[oh_pay][1])


I found an interesting problem on https://codeforces.com/problemset/problem/1141/F2:
This problem is given in two editions, which differ exclusively in the constraints on the number $n$.

You are given an array of integers $a[1], a[2], \dots, a[n].$ A block is a sequence of contiguous (consecutive) elements $a[l], a[l+1], \dots, a[r]$ ($1 \le l \le r \le n$). Thus, a block is defined by a pair of indices $(l, r)$.

Find a set of blocks $(l_1, r_1), (l_2, r_2), \dots, (l_k, r_k)$ such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks $(l_i, r_i)$ and $(l_j, r_j$) where $i \neq j$ either $r_i < l_j$ or $r_j < l_i$.  For each block the sum of its elements is the same. Formally, $$a[l_1]+a[l_1+1]+\dots+a[r_1]=a[l_2]+a[l_2+1]+\dots+a[r_2]=$$ $$\dots =$$ $$a[l_k]+a[l_k+1]+\dots+a[r_k].$$  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks $(l_1', r_1'), (l_2', r_2'), \dots, (l_{k'}', r_{k'}')$ satisfying the above two requirements with $k' > k$.  $\left. \begin{array}{|l|l|l|l|l|l|} \hline 4 & {1} & {2} & {2} & {1} & {5} & {3} \\ \hline \end{array} \right.$ The picture corresponds to the first example. Blue boxes illustrate blocks.

Write a program to find such a set of blocks.

-----Input-----

The first line contains integer $n$ ($1 \le n \le 1500$) — the length of the given array. The second line contains the sequence of elements $a[1], a[2], \dots, a[n]$ ($-10^5 \le a_i \le 10^5$).

-----Output-----

In the first line print the integer $k$ ($1 \le k \le n$). The following $k$ lines should contain blocks, one per line. In each line print a pair of indices $l_i, r_i$ ($1 \le l_i \le r_i \le n$) — the bounds of the $i$-th block. You can print blocks in any order. If there are multiple answers, print any of them.

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

Output
3
7 7
2 3
4 5

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

Output
2
3 4
1 1

Input
4
1 1 1 1

Output
4
4 4
1 1
2 2
3 3

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

from itertools import accumulate

n = int(input())
arr = list(map(int, input().split()))
arr_sums = [0] + list(accumulate(arr))

blocks = {}
for i in range(1, n+1):
    for j in range(i):
        total = arr_sums[i] - arr_sums[j]
        if total not in blocks:
            blocks[total] = [(j+1, i)]
        else:
            if blocks[total][-1][1] < j+1:
                blocks[total].append((j+1, i))

max_block = sorted([(i, len(x)) for i, x in list(blocks.items())], key=lambda y: (-y[1], y[0]))
print(max_block[0][1])
for item in blocks[max_block[0][0]]:
    print(item[0], item[1])


I found an interesting problem on https://codeforces.com/problemset/problem/1141/G:
Treeland consists of $n$ cities and $n-1$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.

There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.

The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $k$ and the number of companies taking part in the privatization is minimal.

Choose the number of companies $r$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $k$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $r$ that there is such assignment to companies from $1$ to $r$ that the number of cities which are not good doesn't exceed $k$. [Image] The picture illustrates the first example ($n=6, k=2$). The answer contains $r=2$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $3$) is not good. The number of such vertices (just one) doesn't exceed $k=2$. It is impossible to have at most $k=2$ not good cities in case of one company.

-----Input-----

The first line contains two integers $n$ and $k$ ($2 \le n \le 200000, 0 \le k \le n - 1$) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.

The following $n-1$ lines contain roads, one road per line. Each line contains a pair of integers $x_i$, $y_i$ ($1 \le x_i, y_i \le n$), where $x_i$, $y_i$ are cities...

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

import sys
from collections import deque

def norm_edge(i, j):
    return (i, j) if i < j else (j, i)

inpt = sys.stdin.read().split('\n')
n, k = list(map(int, inpt[0].split()))
edges = []
for edge_str in inpt[1:n]:
    i, j = tuple([int(x) - 1 for x in edge_str.split()])

    edges.append(norm_edge(i, j))

degree = [0 for _ in range(n)]
neigh = [[] for _ in range(n)]
for i, j in edges:
    degree[i] += 1
    degree[j] += 1
    neigh[i].append(j)
    neigh[j].append(i)

r = sorted(degree)[-(k + 1)]
print(r)

visited = set()
color = {}

q = deque([0])
visited = set([0])
while len(q) > 0:
    i = q.popleft()

    used_color = None
    for j in neigh[i]:
        if j not in visited:
            visited.add(j)
            q.append(j)
        e = norm_edge(i, j)
        if used_color is None and e in color:
            used_color = color[e]
    next_color = 0
    for j in neigh[i]:
        e = norm_edge(i, j)
        if e in color:
            continue

        if next_color == used_color:
            next_color += 1
        color[e] = next_color % r if next_color >= r else next_color
        next_color += 1

print(' '.join([str(color[e] + 1) for e in edges]))

# for i in range(n):
#     print("Node", i)
#     for j in neigh[i]:
#         e = norm_edge(i, j)
#         print("    ", e, color[e])


I found an interesting problem on https://codeforces.com/problemset/problem/1142/A:
Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through $n \cdot k$ cities. The cities are numerated from $1$ to $n \cdot k$, the distance between the neighboring cities is exactly $1$ km.

Sergey does not like beetles, he loves burgers. Fortunately for him, there are $n$ fast food restaurants on the circle, they are located in the $1$-st, the $(k + 1)$-st, the $(2k + 1)$-st, and so on, the $((n-1)k + 1)$-st cities, i.e. the distance between the neighboring cities with fast food restaurants is $k$ km.

Sergey began his journey at some city $s$ and traveled along the circle, making stops at cities each $l$ km ($l > 0$), until he stopped in $s$ once again. Sergey then forgot numbers $s$ and $l$, but he remembers that the distance from the city $s$ to the nearest fast food restaurant was $a$ km, and the distance from the city he stopped at after traveling the first $l$ km from $s$ to the nearest fast food restaurant was $b$ km. Sergey always traveled in the same direction along the circle, but when he calculated distances to the restaurants, he considered both directions.

Now Sergey is interested in two integers. The first integer $x$ is the minimum number of stops (excluding the first) Sergey could have done before returning to $s$. The second integer $y$ is the maximum number of stops (excluding the first) Sergey could have done before returning to $s$.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le n, k \le 100\,000$) — the number of fast food restaurants on the circle and the distance between the neighboring restaurants, respectively.

The second line contains two integers $a$ and $b$ ($0 \le a, b \le \frac{k}{2}$) — the distances to the nearest fast food restaurants from the initial city and from the city Sergey made the first stop at, respectively.

-----Output-----

Print the two integers $x$ and $y$.

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

Output
1 6

Input
3 2
0 0

Output
1 3

Input
1 10
5 3

Output
5 5

-----Note-----

In the first...

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

def gcd(a,b):
    while b!=0:
        t=int(a)
        a=int(b)
        b=t%a
    return int(a)
from sys import stdin
n,k=list(map(int,stdin.readline().strip().split()))
a,b=list(map(int,stdin.readline().strip().split()))
mx=-10**20
mn=-mx
for i in range(n):
    nk=(k*i)

    l1=(-a)%(n*k)
    l2=(nk-b)%(n*k)
    l=0

    if l2>l1:
        l=l2-l1
    elif l2<l1:
        l=n*k-l1+l2
    if l==0:
        l=n*k
    if True:

        mn=min(mn,n*k/gcd(n*k,l))
        mx=max(mx,n*k/gcd(n*k,l))
    l1=(a)%(n*k)
    l2=(nk+b)%(n*k)
    l=0
    if l2>l1:
        l=l2-l1
    elif l2<l1:
        l=n*k-l1+l2
    if l==0:
        l=n*k
    if True:

        mn=min(mn,n*k/gcd(n*k,l))
        mx=max(mx,n*k/gcd(n*k,l))

    l1=(-a)%(n*k)
    l2=(nk+b)%(n*k)
    l=0
    if l2>l1:
        l=l2-l1
    elif l2<l1:
        l=n*k-l1+l2
    if l==0:
        l=n*k
    if True:

        mn=min(mn,n*k/gcd(n*k,l))
        mx=max(mx,n*k/gcd(n*k,l))

    l1=(a)%(n*k)
    l2=(nk-b)%(n*k)
    l=0
    if l2>l1:
        l=l2-l1
    elif l2<l1:
        l=n*k-l1+l2
    if l==0:
        l=n*k
    if True:

        mn=min(mn,n*k/gcd(n*k,l))
        mx=max(mx,n*k/gcd(n*k,l))

print(int(mn),int(mx))


I found an interesting problem on https://codeforces.com/problemset/problem/1143/A:
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.

There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $k$ such that Mr. Black can exit the house after opening the first $k$ doors.

We have to note that Mr. Black opened each door at most once, and in the end all doors became open.

-----Input-----

The first line contains integer $n$ ($2 \le n \le 200\,000$) — the number of doors.

The next line contains $n$ integers: the sequence in which Mr. Black opened the doors. The $i$-th of these integers is equal to $0$ in case the $i$-th opened door is located in the left exit, and it is equal to $1$ in case it is in the right exit.

It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.

-----Output-----

Print the smallest integer $k$ such that after Mr. Black opened the first $k$ doors, he was able to exit the house.

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

Output
3

Input
4
1 0 0 1

Output
3

-----Note-----

In the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.

When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the...

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

n = int(input())

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

left, right = a.count(0), a.count(1)

l, r = 0, 0
for i in range(n):
    if a[i] == 0:
        l += 1
    else:
        r += 1
    if l == left or r == right:
        print(i + 1)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/1143/B:
Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper.

Help Kurt find the maximum possible product of digits among all integers from $1$ to $n$.

-----Input-----

The only input line contains the integer $n$ ($1 \le n \le 2\cdot10^9$).

-----Output-----

Print the maximum product of digits among all integers from $1$ to $n$.

-----Examples-----
Input
390

Output
216

Input
7

Output
7

Input
1000000000

Output
387420489

-----Note-----

In the first example the maximum product is achieved for $389$ (the product of digits is $3\cdot8\cdot9=216$).

In the second example the maximum product is achieved for $7$ (the product of digits is $7$).

In the third example the maximum product is achieved for $999999999$ (the product of digits is $9^9=387420489$).

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

s = input()
def chuj(st,le):
	if le == 1:
		return int(st)
	return max(max((int(st[0])-1),1) * 9**(le-1), int(st[0]) * chuj(st[1:], le - 1))
print(chuj(s,len(s)))


I found an interesting problem on https://codeforces.com/problemset/problem/1143/C:
You are given a rooted tree with vertices numerated from $1$ to $n$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.

Ancestors of the vertex $i$ are all vertices on the path from the root to the vertex $i$, except the vertex $i$ itself. The parent of the vertex $i$ is the nearest to the vertex $i$ ancestor of $i$. Each vertex is a child of its parent. In the given tree the parent of the vertex $i$ is the vertex $p_i$. For the root, the value $p_i$ is $-1$.

 [Image] An example of a tree with $n=8$, the root is vertex $5$. The parent of the vertex $2$ is vertex $3$, the parent of the vertex $1$ is vertex $5$. The ancestors of the vertex $6$ are vertices $4$ and $5$, the ancestors of the vertex $7$ are vertices $8$, $3$ and $5$

You noticed that some vertices do not respect others. In particular, if $c_i = 1$, then the vertex $i$ does not respect any of its ancestors, and if $c_i = 0$, it respects all of them.

You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $v$, all children of $v$ become connected with the parent of $v$.

 [Image] An example of deletion of the vertex $7$.

Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.

-----Input-----

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

The next $n$ lines describe the tree: the $i$-th line contains two integers $p_i$ and $c_i$ ($1 \le p_i \le n$, $0 \le c_i \le 1$), where $p_i$ is the parent of the vertex $i$, and $c_i = 0$, if the vertex $i$ respects its parents, and $c_i = 1$, if the vertex $i$ does not respect any of its parents. The root of the tree has $-1$ instead of the parent index, also,...

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

n = int(input())
parent = [-1]*n
isresp = [1]*n
for i in range(n):
	p, r = list(map(int, input().split()))
	p -= 1
	if r == 0:
		isresp[i] = 0
		if p>=0:
			isresp[p] = 0
nore = []
for i in range(n):
	if isresp[i] == 1:
		nore.append(i+1)
if not nore:
	print(-1)
else:
	print(" ".join(map(str, nore)))


I found an interesting problem on https://codeforces.com/problemset/problem/1144/A:
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are not adjacent.

Formally, consider positions of all letters in the string in the alphabet. These positions should form contiguous segment, i.e. they should come one by one without any gaps. And all letters in the string should be distinct (duplicates are not allowed).

You are given a sequence of strings. For each string, if it is diverse, print "Yes". Otherwise, print "No".

-----Input-----

The first line contains integer $n$ ($1 \le n \le 100$), denoting the number of strings to process. The following $n$ lines contains strings, one string per line. Each string contains only lowercase Latin letters, its length is between $1$ and $100$, inclusive.

-----Output-----

Print $n$ lines, one line per a string in the input. The line should contain "Yes" if the corresponding string is diverse and "No" if the corresponding string is not diverse. You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.

-----Example-----
Input
8
fced
xyz
r
dabcef
az
aa
bad
babc

Output
Yes
Yes
Yes
Yes
No
No
No
No

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

n=int(input())
for i in range(n):
    s = ''.join(sorted(input()))
    ans = True
    for i in range(1, len(s)):
        if ord(s[i]) - ord(s[i - 1]) != 1: ans = False
    if ans: print('Yes')
    else: print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/1144/B:
Polycarp has an array $a$ consisting of $n$ integers.

He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains $n-1$ elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.

Formally:   If it is the first move, he chooses any element and deletes it;  If it is the second or any next move:   if the last deleted element was odd, Polycarp chooses any even element and deletes it;  if the last deleted element was even, Polycarp chooses any odd element and deletes it.   If after some move Polycarp cannot make a move, the game ends.

Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.

Help Polycarp find this value.

-----Input-----

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

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

-----Output-----

Print one integer — the minimum possible sum of non-deleted elements of the array after end of the game.

-----Examples-----
Input
5
1 5 7 8 2

Output
0

Input
6
5 1 2 4 6 3

Output
0

Input
2
1000000 1000000

Output
1000000

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

import sys

input = sys.stdin.readline

n = int(input())

evens = []
odds = []

for i in map(int, input().split()):
    if i % 2 == 0:
        evens.append(i)
    else:
        odds.append(i)

evens.sort(reverse = True)
odds.sort(reverse = True)

if len(evens) > len(odds):
    print(sum(evens[len(odds)+1:]))
elif len(odds) > len(evens):
    print(sum(odds[len(evens)+1:]))
else:
    print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/1144/C:
Two integer sequences existed initially — one of them was strictly increasing, and the other one — strictly decreasing.

Strictly increasing sequence is a sequence of integers $[x_1 < x_2 < \dots < x_k]$. And strictly decreasing sequence is a sequence of integers $[y_1 > y_2 > \dots > y_l]$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.

They were merged into one sequence $a$. After that sequence $a$ got shuffled. For example, some of the possible resulting sequences $a$ for an increasing sequence $[1, 3, 4]$ and a decreasing sequence $[10, 4, 2]$ are sequences $[1, 2, 3, 4, 4, 10]$ or $[4, 2, 1, 10, 4, 3]$.

This shuffled sequence $a$ is given in the input.

Your task is to find any two suitable initial sequences. One of them should be strictly increasing and the other one — strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.

If there is a contradiction in the input and it is impossible to split the given sequence $a$ to increasing and decreasing sequences, print "NO".

-----Input-----

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

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

-----Output-----

If there is a contradiction in the input and it is impossible to split the given sequence $a$ to increasing and decreasing sequences, print "NO" in the first line.

Otherwise print "YES" in the first line and any two suitable sequences. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.

In the second line print $n_i$ — the number of elements in the strictly increasing sequence. $n_i$ can be zero, in this case the increasing sequence is empty.

In the third line print $n_i$ integers $inc_1, inc_2, \dots, inc_{n_i}$ in...

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

n = int(input())
a = list(map(int, input().split()))
inc = set([])
dec = set([])
for i in a:
    if i not in inc:
        inc.add(i)
    elif i not in dec:
        dec.add(i)
    else:
        print("NO")
        return
inc = list(inc)
dec = list(dec)
inc.sort(reverse = True)
dec.sort()
print("YES")
print(len(dec))
print(*dec)
print(len(inc))
print(*inc)


I found an interesting problem on https://codeforces.com/problemset/problem/1144/D:
You are given an array $a$ consisting of $n$ integers. You can perform the following operations arbitrary number of times (possibly, zero):

  Choose a pair of indices $(i, j)$ such that $|i-j|=1$ (indices $i$ and $j$ are adjacent) and set $a_i := a_i + |a_i - a_j|$;  Choose a pair of indices $(i, j)$ such that $|i-j|=1$ (indices $i$ and $j$ are adjacent) and set $a_i := a_i - |a_i - a_j|$.

The value $|x|$ means the absolute value of $x$. For example, $|4| = 4$, $|-3| = 3$.

Your task is to find the minimum number of operations required to obtain the array of equal elements and print the order of operations to do it.

It is guaranteed that you always can obtain the array of equal elements using such operations.

Note that after each operation each element of the current array should not exceed $10^{18}$ by absolute value.

-----Input-----

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

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

-----Output-----

In the first line print one integer $k$ — the minimum number of operations required to obtain the array of equal elements.

In the next $k$ lines print operations itself. The $p$-th operation should be printed as a triple of integers $(t_p, i_p, j_p)$, where $t_p$ is either $1$ or $2$ ($1$ means that you perform the operation of the first type, and $2$ means that you perform the operation of the second type), and $i_p$ and $j_p$ are indices of adjacent elements of the array such that $1 \le i_p, j_p \le n$, $|i_p - j_p| = 1$. See the examples for better understanding.

Note that after each operation each element of the current array should not exceed $10^{18}$ by absolute value.

If there are many possible answers, you can print any.

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

Output
2
1 2 3
1 1 2

Input
3
2 8 10

Output
2
2 2 1
2 3 2

Input
4
1 1 1 1

Output
0

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

from collections import defaultdict as ddict

n = int(input())
a = list(map(int, input().split()))
count = ddict(list)
main_key = 0
max_len = 0

for i, it in enumerate(a):
    count[it].append(i)
for k in count:
    if len(count[k]) > max_len:
        max_len = len(count[k])
        main_key = count[k][0]
if max_len == n:
    print(0)
    return

ans = list()
for i in range(main_key-1, -1, -1):
    if a[i] == a[main_key]: continue
    if a[i] > a[main_key]: ans.append((2, i+1, i+2))
    else: ans.append((1, i+1, i+2))

for i in range(main_key+1, n):
    if a[i] == a[main_key]: continue
    if a[i] > a[main_key]: ans.append((2, i+1, i))
    else: ans.append((1, i+1, i))

print(len(ans))
for it in ans:
    print('%d %d %d'%(it))


I found an interesting problem on https://codeforces.com/problemset/problem/1144/E:
You are given two strings $s$ and $t$, both consisting of exactly $k$ lowercase Latin letters, $s$ is lexicographically less than $t$.

Let's consider list of all strings consisting of exactly $k$ lowercase Latin letters, lexicographically not less than $s$ and not greater than $t$ (including $s$ and $t$) in lexicographical order. For example, for $k=2$, $s=$"az" and $t=$"bf" the list will be ["az", "ba", "bb", "bc", "bd", "be", "bf"].

Your task is to print the median (the middle element) of this list. For the example above this will be "bc".

It is guaranteed that there is an odd number of strings lexicographically not less than $s$ and not greater than $t$.

-----Input-----

The first line of the input contains one integer $k$ ($1 \le k \le 2 \cdot 10^5$) — the length of strings.

The second line of the input contains one string $s$ consisting of exactly $k$ lowercase Latin letters.

The third line of the input contains one string $t$ consisting of exactly $k$ lowercase Latin letters.

It is guaranteed that $s$ is lexicographically less than $t$.

It is guaranteed that there is an odd number of strings lexicographically not less than $s$ and not greater than $t$.

-----Output-----

Print one string consisting exactly of $k$ lowercase Latin letters — the median (the middle element) of list of strings of length $k$ lexicographically not less than $s$ and not greater than $t$.

-----Examples-----
Input
2
az
bf

Output
bc

Input
5
afogk
asdji

Output
alvuw

Input
6
nijfvj
tvqhwp

Output
qoztvz

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

N = int(input())
s = input()
t = input()

def stoi(s):
    return ord(s)-97
def itos(i):
    return chr(97+i)

def stoL(s):
    L = []
    for ss in s:
        L.append(stoi(ss))
    return L

A = stoL(s)
B = stoL(t)
C = [A[i]+B[i] for i in range(N)]
for i in range(1, N)[::-1]:
    if C[i] >= 26:
        C[i] -= 26
        C[i-1] += 1

t = 0
for i in range(N):
    if C[i] % 2:
        C[i] = (C[i]+t-1) // 2
        t = 26
    else:
        C[i] = (C[i]+t) // 2
        t = 0

u = ""
for c in C:
    u += itos(c)
print(u)


I found an interesting problem on https://codeforces.com/problemset/problem/1144/F:
You are given a connected undirected graph consisting of $n$ vertices and $m$ edges. There are no self-loops or multiple edges in the given graph.

You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges).

-----Input-----

The first line contains two integer numbers $n$ and $m$ ($2 \le n \le 2 \cdot 10^5$, $n - 1 \le m \le 2 \cdot 10^5$) — the number of vertices and edges, respectively.

The following $m$ lines contain edges: edge $i$ is given as a pair of vertices $u_i$, $v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$). There are no multiple edges in the given graph, i. e. for each pair ($u_i, v_i$) there are no other pairs ($u_i, v_i$) and ($v_i, u_i$) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph).

-----Output-----

If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line.

Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length $m$. The $i$-th element of this string should be '0' if the $i$-th edge of the graph should be directed from $u_i$ to $v_i$, and '1' otherwise. Edges are numbered in the order they are given in the input.

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

Output
YES
10100

-----Note-----

The picture corresponding to the first example: [Image]

And one of possible answers: $\text{of}$

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

import sys

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

n, m = map(int, input().split())
give = [False] * (n + 1)
take = [False] * (n + 1)
edge = dict()
inputs = []
for i in range(n):
    edge[i+1] = []
for i in range(m):
    u, v = map(int, input().split())
    inputs.append((u, v))
    edge[u].append(v)
    edge[v].append(u)
check = [False] * (n + 1)
queue = [1]
front = 0
while front < len(queue):
    u = queue[front]
    check[u] = True
    for v in edge[u]:
        if check[v]:
            continue
        queue.append(v)
        if (give[u] and give[v]) or (take[u] and take[v]):
            print('NO')
            return
        if (give[u] and take[v]) or (take[u] and give[v]):
            continue
        if give[u]:
            take[v] = True
            continue
        if take[u]:
            give[v] = True
            continue
        if give[v]:
            take[u] = True
            continue
        if take[v]:
            give[u] = True
            continue
        give[u] = True
        take[v] = True
    front += 1
print('YES')
for u, v in inputs:
    if give[u] and take[v]:
        print(1, end="")
    else:
        print(0, end="")
print()


I found an interesting problem on https://codeforces.com/problemset/problem/1144/G:
Two integer sequences existed initially, one of them was strictly increasing, and another one — strictly decreasing.

Strictly increasing sequence is a sequence of integers $[x_1 < x_2 < \dots < x_k]$. And strictly decreasing sequence is a sequence of integers $[y_1 > y_2 > \dots > y_l]$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.

Elements of increasing sequence were inserted between elements of the decreasing one (and, possibly, before its first element and after its last element) without changing the order. For example, sequences $[1, 3, 4]$ and $[10, 4, 2]$ can produce the following resulting sequences: $[10, \textbf{1}, \textbf{3}, 4, 2, \textbf{4}]$, $[\textbf{1}, \textbf{3}, \textbf{4}, 10, 4, 2]$. The following sequence cannot be the result of these insertions: $[\textbf{1}, 10, \textbf{4}, 4, \textbf{3}, 2]$ because the order of elements in the increasing sequence was changed.

Let the obtained sequence be $a$. This sequence $a$ is given in the input. Your task is to find any two suitable initial sequences. One of them should be strictly increasing, and another one — strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.

If there is a contradiction in the input and it is impossible to split the given sequence $a$ into one increasing sequence and one decreasing sequence, print "NO".

-----Input-----

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

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

-----Output-----

If there is a contradiction in the input and it is impossible to split the given sequence $a$ into one increasing sequence and one decreasing sequence, print "NO" in the first line.

Otherwise print "YES" in the first line. In the second line, print a sequence of $n$...

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

n, a = int(input()), list(map(int, input().split())) + [0, ]

ans, inc, dec = [0] * n, -1, 1e7
for i in range(n):
	if inc < a[i] < dec:
		if a[i] < a[i + 1]:
			inc = a[i]
		else:
			dec = a[i]
			ans[i] = 1
	elif inc < a[i]:
		inc = a[i]
	elif dec > a[i]:
		dec = a[i]
		ans[i] = 1
	else:
		print('NO')
		break
else:
	print('YES')
	print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1145/A:
Thanos sort is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.

Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort?

*Infinity Gauntlet required.

-----Input-----

The first line of input contains a single number $n$ ($1 \le n \le 16$) — the size of the array. $n$ is guaranteed to be a power of 2.

The second line of input contains $n$ space-separated integers $a_i$ ($1 \le a_i \le 100$) — the elements of the array.

-----Output-----

Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order.

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

Output
4

Input
8
11 12 1 2 13 14 3 4

Output
2

Input
4
7 6 5 4

Output
1

-----Note-----

In the first example the array is already sorted, so no finger snaps are required.

In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array.

In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction.

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

def is_sorted(lst):
    it = lst[0]
    for i in range(1, len(lst)):
        if lst[i] < it:
            return False
        it = lst[i]
    return True

def do(lst):
    if is_sorted(lst):
        return len(lst)

    v1 = do(lst[:len(lst) // 2])
    v2 = do(lst[len(lst) // 2:])

    return max(v1, v2)

N = int(input())

A = list(map(int, input().split()))
print(do(A))


I found an interesting problem on https://codeforces.com/problemset/problem/1145/B:
-----Input-----

The input contains a single integer $a$ ($1 \le a \le 99$).

-----Output-----

Output "YES" or "NO".

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

Output
YES

Input
13

Output
NO

Input
24

Output
NO

Input
46

Output
YES

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

n = int(input())
s = {1, 7, 9, 10, 11}
if n < 12:
	if n in s:
		print("NO")
	else:
		print("YES")
elif 12 < n < 30:
	print("NO")
elif 69 < n < 80:
	print("NO")
elif 89 < n:
	print("NO")
else:
	if n % 10 not in {1, 7, 9}:
		print("YES")
	else: print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1145/C:
[Image]

-----Input-----

The input contains a single integer $a$ ($0 \le a \le 15$).

-----Output-----

Output a single integer.

-----Example-----
Input
3

Output
13

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


I found an interesting problem on https://codeforces.com/problemset/problem/1145/D:
From "ftying rats" to urban saniwation workers - can synthetic biology tronsform how we think of pigeons?

The upiquitous pigeon has long been viewed as vermin - spleading disease, scavenging through trush, and defecating in populous urban spases. Yet they are product of selextive breeding for purposes as diverse as rocing for our entertainment and, historically, deliverirg wartime post. Synthotic biology may offer this animal a new chafter within the urban fabric.

Piteon d'Or recognihes how these birds ripresent a potentially userul interface for urdan biotechnologies. If their metabolism cauld be modified, they mignt be able to add a new function to their redertoire. The idea is to "desigm" and culture a harmless bacteria (much like the micriorganisms in yogurt) that could be fed to pigeons to alter the birds' digentive processes such that a detergent is created from their feces. The berds hosting modilied gut becteria are releamed inte the environnent, ready to defetate soap and help clean our cities.

-----Input-----

The first line of input data contains a single integer $n$ ($5 \le n \le 10$).

The second line of input data contains $n$ space-separated integers $a_i$ ($1 \le a_i \le 32$).

-----Output-----

Output a single integer.

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

Output
4

-----Note-----

We did not proofread this statement at all.

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

# twoplusxorofthirdandminelement

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

third = xs[2]
min_ = min(xs)
print(2 + (third ^ min_))


I found an interesting problem on https://codeforces.com/problemset/problem/1145/F:
-----Input-----

The input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive.

-----Output-----

Output "YES" or "NO".

-----Examples-----
Input
NEAT

Output
YES

Input
WORD

Output
NO

Input
CODER

Output
NO

Input
APRILFOOL

Output
NO

Input
AI

Output
YES

Input
JUROR

Output
YES

Input
YES

Output
NO

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

n=input()
s='AEFHIKLMNTVWXYZ'
t='BCDGJOPQRSU'
f1=0
f2=0
for i in s:
	if i in n:f1=1
for i in t:
	if i in n:f2=1
if f1+f2==1:print('YES')
else:print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1146/A:
Alice has a string $s$. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not.

Alice can erase some characters from her string $s$. She would like to know what is the longest string remaining after erasing some characters (possibly zero) to get a good string. It is guaranteed that the string has at least one "a" in it, so the answer always exists.

-----Input-----

The first line contains a string $s$ ($1 \leq |s| \leq 50$) consisting of lowercase English letters. It is guaranteed that there is at least one "a" in $s$.

-----Output-----

Print a single integer, the length of the longest good string that Alice can get after erasing some characters from $s$.

-----Examples-----
Input
xaxxxxa

Output
3

Input
aaabaa

Output
6

-----Note-----

In the first example, it's enough to erase any four of the "x"s. The answer is $3$ since that is the maximum number of characters that can remain.

In the second example, we don't need to erase any characters.

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

from collections import Counter
S = input()
SC = Counter(S)
a = SC['a']
print(min(len(S), 2*a-1))


I found an interesting problem on https://codeforces.com/problemset/problem/1146/B:
Bob has a string $s$ consisting of lowercase English letters. He defines $s'$ to be the string after removing all "a" characters from $s$ (keeping all other characters in the same order). He then generates a new string $t$ by concatenating $s$ and $s'$. In other words, $t=s+s'$ (look at notes for an example).

You are given a string $t$. Your task is to find some $s$ that Bob could have used to generate $t$. It can be shown that if an answer exists, it will be unique.

-----Input-----

The first line of input contains a string $t$ ($1 \leq |t| \leq 10^5$) consisting of lowercase English letters.

-----Output-----

Print a string $s$ that could have generated $t$. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters).

-----Examples-----
Input
aaaaa

Output
aaaaa

Input
aacaababc

Output
:(

Input
ababacacbbcc

Output
ababacac

Input
baba

Output
:(

-----Note-----

In the first example, we have $s = $ "aaaaa", and $s' = $ "".

In the second example, no such $s$ can work that will generate the given $t$.

In the third example, we have $s = $ "ababacac", and $s' = $ "bbcc", and $t = s + s' = $ "ababacacbbcc".

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

def solve():
    s = input()

    a = ""

    for x in s:
        if x != 'a':
            a += x

    if len(a) == 0:
        print (s)
        return

    n = len(a)//2

    if 'a' in s[len(s)-n:]:
        print (":(")
        return

    print (s[:len(s)-n] if a[:n] == a[n:] else ":(")

def __starting_point():
    solve()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1146/D:
A frog is initially at position $0$ on the number line. The frog has two positive integers $a$ and $b$. From a position $k$, it can either jump to position $k+a$ or $k-b$.

Let $f(x)$ be the number of distinct integers the frog can reach if it never jumps on an integer outside the interval $[0, x]$. The frog doesn't need to visit all these integers in one trip, that is, an integer is counted if the frog can somehow reach it if it starts from $0$.

Given an integer $m$, find $\sum_{i=0}^{m} f(i)$. That is, find the sum of all $f(i)$ for $i$ from $0$ to $m$.

-----Input-----

The first line contains three integers $m, a, b$ ($1 \leq m \leq 10^9, 1 \leq a,b \leq 10^5$).

-----Output-----

Print a single integer, the desired sum.

-----Examples-----
Input
7 5 3

Output
19

Input
1000000000 1 2019

Output
500000001500000001

Input
100 100000 1

Output
101

Input
6 4 5

Output
10

-----Note-----

In the first example, we must find $f(0)+f(1)+\ldots+f(7)$. We have $f(0) = 1, f(1) = 1, f(2) = 1, f(3) = 1, f(4) = 1, f(5) = 3, f(6) = 3, f(7) = 8$. The sum of these values is $19$.

In the second example, we have $f(i) = i+1$, so we want to find $\sum_{i=0}^{10^9} i+1$.

In the third example, the frog can't make any jumps in any case.

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

import math
m,a,b=list(map(int,(input().split())))
vis=[-1]*(a+b+5)
now=0
maxd=0
while True:
    vis[now]=maxd
    #print(now,maxd)
    if now>=b:
        now-=b
    else:
        now+=a
    if now==0:
        break
    maxd=max(maxd,now)
ans=0
#for i in range(0,a+b):
    #print(vis[i])
for i in range(0,a+b):
    if vis[i]!=-1:
        ans+=max(0,m-vis[i]+1)
rest=m-(a+b)+1
if m>=a+b:
    g=math.gcd(a,b)
    tmp=(rest//g)*g
    fir=rest-tmp
    lst=rest
    cnt=tmp//g+1
    ans+=(fir+lst)*cnt//2
print(int(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1146/E:
You are given an array of $n$ integers $a_1, a_2, \ldots, a_n$.

You will perform $q$ operations. In the $i$-th operation, you have a symbol $s_i$ which is either "<" or ">" and a number $x_i$.

You make a new array $b$ such that $b_j = -a_j$ if $a_j s_i x_i$ and $b_j = a_j$ otherwise (i.e. if $s_i$ is '>', then all $a_j > x_i$ will be flipped). After doing all these replacements, $a$ is set to be $b$.

You want to know what your final array looks like after all operations.

-----Input-----

The first line contains two integers $n,q$ ($1 \leq n,q \leq 10^5$) — the number of integers and the number of queries.

The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($-10^5 \leq a_i \leq 10^5$) — the numbers.

Each of the next $q$ lines contains a character and an integer $s_i, x_i$. ($s_i \in \{<, >\}, -10^5 \leq x_i \leq 10^5$) – the queries.

-----Output-----

Print $n$ integers $c_1, c_2, \ldots, c_n$ representing the array after all operations.

-----Examples-----
Input
11 3
-5 -4 -3 -2 -1 0 1 2 3 4 5
> 2
> -4
< 5

Output
5 4 -3 -2 -1 0 1 2 -3 4 5

Input
5 5
0 1 -2 -1 2
< -2
< -1
< 0
< 1
< 2

Output
0 -1 2 -1 2

-----Note-----

In the first example, the array goes through the following changes:   Initial: $[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]$  $> 2$: $[-5, -4, -3, -2, -1, 0, 1, 2, -3, -4, -5]$  $> -4$: $[-5, -4, 3, 2, 1, 0, -1, -2, 3, -4, -5]$  $< 5$: $[5, 4, -3, -2, -1, 0, 1, 2, -3, 4, 5]$

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

import sys
N, Q = map(int, input().split())
A = list(map(int, input().split()))
Sign = [0]*(3+10**5)
SX = [tuple(sys.stdin.readline().split()) for _ in range(Q)]
mini = 3 + 10**5
Sign = [0]*(3+10**5)
keep = 1
for (s, x) in SX[::-1]:
    x = int(x)
    ax = abs(x) + int((s == '>') ^ (x < 0))
    sin = 1 if s == '<' else -1
    if mini > ax:
        t = sin*keep
        for i in range(mini-1, ax-1, -1):
            Sign[i] = t
        mini = ax
    keep *= (2*(s == '>') - 1) * (2*(0 < x) - 1)
Ans = [None]*N
for i, a in enumerate(A):
    s = Sign[abs(a)]
    if s == 0:
        s = (2*(a > 0) - 1)*keep
    Ans[i] = s*abs(a)
print(*Ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1147/A:
Alice and Bob are playing a game on a line with $n$ cells. There are $n$ cells labeled from $1$ through $n$. For each $i$ from $1$ to $n-1$, cells $i$ and $i+1$ are adjacent.

Alice initially has a token on some cell on the line, and Bob tries to guess where it is.

Bob guesses a sequence of line cell numbers $x_1, x_2, \ldots, x_k$ in order. In the $i$-th question, Bob asks Alice if her token is currently on cell $x_i$. That is, Alice can answer either "YES" or "NO" to each Bob's question.

At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.

Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.

You are given $n$ and Bob's questions $x_1, \ldots, x_k$. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.

Let $(a,b)$ denote a scenario where Alice starts at cell $a$ and ends at cell $b$. Two scenarios $(a_i, b_i)$ and $(a_j, b_j)$ are different if $a_i \neq a_j$ or $b_i \neq b_j$.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \leq n,k \leq 10^5$) — the number of cells and the number of questions Bob asked.

The second line contains $k$ integers $x_1, x_2, \ldots, x_k$ ($1 \leq x_i \leq n$) — Bob's questions.

-----Output-----

Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.

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

Output
9

Input
4 8
1 2 3 4 4 3 2 1

Output
0

Input
100000 1
42

Output
299997

-----Note-----

The notation $(i,j)$ denotes a scenario where Alice starts at cell $i$ and ends at cell $j$.

In the first example, the valid scenarios are $(1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5)$. For example, $(3,4)$ is valid since Alice can start at cell $3$, stay there for...

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

def solve():
	n,k = map(int,input().split())
	x = list(map(int,input().split()))
	fpos = [k for i in range(n+1)]
	lpos = [-1 for i in range(n+1)]
	for i in range(1,k+1):
		lpos[x[i-1]] = i
	for i in range(k,0,-1):
		fpos[x[i-1]] = i
	ans = 0
	for i in range(1,n+1):
		if lpos[i] == -1:
			ans+=1
	# print(ans)
	for i in range(1,n):
		if fpos[i] >= lpos[i+1]:
			ans += 1
		if fpos[i+1] >= lpos[i]:
			ans += 1

		# print(i,i+1,ans)
	print(ans)

def __starting_point():
	solve()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1147/B:
Inaka has a disc, the circumference of which is $n$ units. The circumference is equally divided by $n$ points numbered clockwise from $1$ to $n$, such that points $i$ and $i + 1$ ($1 \leq i < n$) are adjacent, and so are points $n$ and $1$.

There are $m$ straight segments on the disc, the endpoints of which are all among the aforementioned $n$ points.

Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $k$ ($1 \leq k < n$), such that if all segments are rotated clockwise around the center of the circle by $k$ units, the new image will be the same as the original one.

-----Input-----

The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 100\,000$, $1 \leq m \leq 200\,000$) — the number of points and the number of segments, respectively.

The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$) that describe a segment connecting points $a_i$ and $b_i$.

It is guaranteed that no segments coincide.

-----Output-----

Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).

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

-----Examples-----
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3

Output
Yes

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

Output
Yes

Input
10 3
1 2
3 2
7 2

Output
No

Input
10 2
1 6
2 7

Output
Yes

-----Note-----

The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $120$ degrees around the center.

 [Image]

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

import math

class CodeforcesTask1147BSolution:
    def __init__(self):
        self.result = ''
        self.n_m = []
        self.points = []

    def read_input(self):
        self.n_m = [int(x) for x in input().split(" ")]
        for x in range(self.n_m[1]):
            self.points.append([int(y) for y in input().split(" ")])

    def process_task(self):
        can = False
        segm = {}
        for point in self.points:
            segm["{0}_{1}".format(*point)] = True
            segm["{1}_{0}".format(*point)] = True
        for k in range(1, self.n_m[0]):
            if not self.n_m[0] % k:
                #print(k)
                do = True
                for p in self.points:
                    a, b = (p[0] + k) % self.n_m[0], (p[1] + k) % self.n_m[0]
                    if not a:
                        a = self.n_m[0]
                    if not b:
                        b = self.n_m[0]
                    if not "{0}_{1}".format(a, b) in segm:
                        do = False
                        break
                if do:
                    can = do
                    break
        self.result = "Yes" if can else "No"

    def get_result(self):
        return self.result

def __starting_point():
    Solution = CodeforcesTask1147BSolution()
    Solution.read_input()
    Solution.process_task()
    print(Solution.get_result())

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1147/C:
Alice and Bob are playing a game with $n$ piles of stones. It is guaranteed that $n$ is an even number. The $i$-th pile has $a_i$ stones.

Alice and Bob will play a game alternating turns with Alice going first.

On a player's turn, they must choose exactly $\frac{n}{2}$ nonempty piles and independently remove a positive number of stones from each of the chosen piles. They can remove a different number of stones from the piles in a single turn. The first player unable to make a move loses (when there are less than $\frac{n}{2}$ nonempty piles).

Given the starting configuration, determine who will win the game.

-----Input-----

The first line contains one integer $n$ ($2 \leq n \leq 50$) — the number of piles. It is guaranteed that $n$ is an even number.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 50$) — the number of stones in the piles.

-----Output-----

Print a single string "Alice" if Alice wins; otherwise, print "Bob" (without double quotes).

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

Output
Bob

Input
4
3 1 4 1

Output
Alice

-----Note-----

In the first example, each player can only remove stones from one pile ($\frac{2}{2}=1$). Alice loses, since Bob can copy whatever Alice does on the other pile, so Alice will run out of moves first.

In the second example, Alice can remove $2$ stones from the first pile and $3$ stones from the third pile on her first move to guarantee a win.

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

def judge(i):
    return "Bob" if cnt[i]>n//2 else "Alice"
n=int(input())
a=list(map(int,input().split()))
cnt=[0 for i in range(51)]
for i in a:
    cnt[i]+=1
print(judge(min(a)))


I found an interesting problem on https://codeforces.com/problemset/problem/1148/A:
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.

You have $a$ strings "a", $b$ strings "b" and $c$ strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.

What is the length of the longest good string you can obtain this way?

-----Input-----

The first line contains three positive integers $a$, $b$, $c$ ($1 \leq a, b, c \leq 10^9$) — the number of strings "a", "b" and "ab" respectively.

-----Output-----

Print a single number — the maximum possible length of the good string you can obtain.

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

Output
4

Input
2 1 2

Output
7

Input
3 5 2

Output
11

Input
2 2 1

Output
6

Input
1000000000 1000000000 1000000000

Output
4000000000

-----Note-----

In the first example the optimal string is "baba".

In the second example the optimal string is "abababa".

In the third example the optimal string is "bababababab".

In the fourth example the optimal string is "ababab".

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

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)

def main():
    a,b,c = LI()
    r = min(a,b) * 2
    if a != b:
        r += 1

    return r + c * 2

print(main())


I found an interesting problem on https://codeforces.com/problemset/problem/1148/B:
Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.

There are $n$ flights from A to B, they depart at time moments $a_1$, $a_2$, $a_3$, ..., $a_n$ and arrive at B $t_a$ moments later.

There are $m$ flights from B to C, they depart at time moments $b_1$, $b_2$, $b_3$, ..., $b_m$ and arrive at C $t_b$ moments later.

The connection time is negligible, so one can use the $i$-th flight from A to B and the $j$-th flight from B to C if and only if $b_j \ge a_i + t_a$.

You can cancel at most $k$ flights. If you cancel a flight, Arkady can not use it.

Arkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel $k$ flights. If you can cancel $k$ or less flights in such a way that it is not possible to reach C at all, print $-1$.

-----Input-----

The first line contains five integers $n$, $m$, $t_a$, $t_b$ and $k$ ($1 \le n, m \le 2 \cdot 10^5$, $1 \le k \le n + m$, $1 \le t_a, t_b \le 10^9$) — the number of flights from A to B, the number of flights from B to C, the flight time from A to B, the flight time from B to C and the number of flights you can cancel, respectively.

The second line contains $n$ distinct integers in increasing order $a_1$, $a_2$, $a_3$, ..., $a_n$ ($1 \le a_1 < a_2 < \ldots < a_n \le 10^9$) — the times the flights from A to B depart.

The third line contains $m$ distinct integers in increasing order $b_1$, $b_2$, $b_3$, ..., $b_m$ ($1 \le b_1 < b_2 < \ldots < b_m \le 10^9$) — the times the flights from B to C depart.

-----Output-----

If you can cancel $k$ or less flights in such a way that it is not possible to reach C at all, print $-1$.

Otherwise print the earliest time Arkady can arrive at C if you cancel $k$ flights in such a way that maximizes this time.

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

Output
11

Input
2 2 4 4 2
1 10
10...

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

from bisect import bisect_left as bl
n, m, t1, t2, k = list(map(int, input().split()))
A = [int(a) for a in input().split()]
B = [int(a)-t1 for a in input().split()]

if min(n, m) <= k:
    print(-1)
else:
    ma = -1
    for i in range(k+1):
        x = bl(B, A[i]) + k - i
        if x >= m:
            print(-1)
            break
        ma = max(ma, B[x]+t1+t2)
    else:
        print(ma)


I found an interesting problem on https://codeforces.com/problemset/problem/1148/C:
You are given a permutation $p$ of integers from $1$ to $n$, where $n$ is an even number.

Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type:   take two indices $i$ and $j$ such that $2 \cdot |i - j| \geq n$ and swap $p_i$ and $p_j$.

There is no need to minimize the number of operations, however you should use no more than $5 \cdot n$ operations. One can show that it is always possible to do that.

-----Input-----

The first line contains a single integer $n$ ($2 \leq n \leq 3 \cdot 10^5$, $n$ is even) — the length of the permutation.

The second line contains $n$ distinct integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$) — the given permutation.

-----Output-----

On the first line print $m$ ($0 \le m \le 5 \cdot n$) — the number of swaps to perform.

Each of the following $m$ lines should contain integers $a_i, b_i$ ($1 \le a_i, b_i \le n$, $|a_i - b_i| \ge \frac{n}{2}$) — the indices that should be swapped in the corresponding swap.

Note that there is no need to minimize the number of operations. We can show that an answer always exists.

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

Output
1
1 2
Input
4
3 4 1 2

Output
4
1 4
1 4
1 3
2 4

Input
6
2 5 3 1 4 6

Output
3
1 5
2 5
1 4

-----Note-----

In the first example, when one swap elements on positions $1$ and $2$, the array becomes sorted.

In the second example, pay attention that there is no need to minimize number of swaps.

In the third example, after swapping elements on positions $1$ and $5$ the array becomes: $[4, 5, 3, 1, 2, 6]$. After swapping elements on positions $2$ and $5$ the array becomes $[4, 2, 3, 1, 5, 6]$ and finally after swapping elements on positions $1$ and $4$ the array becomes sorted: $[1, 2, 3, 4, 5, 6]$.

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

n=int(input())
a=[0]  + list(map(int,input().split()))
d={}
b=[]
for i in range(1,n+1):
    d[a[i]]=i
m=0
for i in range(1,n+1):
    ele=a[i]
    if ele!=i and abs(i-d[i])*2>=n:
        m+=1
        b.append([i,d[i]])
        a[i]=i
        a[d[i]]=ele
        d[ele]=d[i]
        d[i]=i

        # print("a")
    elif ele!=i and abs(i-d[i])*2<n and i<=n//2 and 2*(d[i]-1)>=n:
        m+=5
        b.append([1,d[i]])
        b.append([1,n])
        b.append([i,n])
        b.append([1,n])
        b.append([1,d[i]])
        a[i]=i
        a[d[i]]=ele

        d[ele]=d[i]
        d[i]=i
        # print("b")
    elif ele!=i and abs(i-d[i])*2<n and i<=n//2 and 2*(d[i]-1)<n:
        m+=3
        b.append([n,d[i]])
        b.append([i,n])
        b.append([n,d[i]])
        a[i]=i
        a[d[i]]=ele

        d[ele]=d[i]
        d[i]=i
        # print("b")

    elif ele!=i and abs(i-d[i])*2<n:
        m+=3
        b.append([1,d[i]])
        b.append([i,1])
        b.append([1,d[i]])
        a[i]=i
        a[d[i]]=ele
        d[ele]=d[i]
        d[i]=i
        # print("c")
    # print(d,a)
print(m)
for i in b:
    print(*i)

# print(a)


I found an interesting problem on https://codeforces.com/problemset/problem/1148/D:
You are given $n$ pairs of integers $(a_1, b_1), (a_2, b_2), \ldots, (a_n, b_n)$. All of the integers in the pairs are distinct and are in the range from $1$ to $2 \cdot n$ inclusive.

Let's call a sequence of integers $x_1, x_2, \ldots, x_{2k}$ good if either   $x_1 < x_2 > x_3 < \ldots < x_{2k-2} > x_{2k-1} < x_{2k}$, or  $x_1 > x_2 < x_3 > \ldots > x_{2k-2} < x_{2k-1} > x_{2k}$.

You need to choose a subset of distinct indices $i_1, i_2, \ldots, i_t$ and their order in a way that if you write down all numbers from the pairs in a single sequence (the sequence would be $a_{i_1}, b_{i_1}, a_{i_2}, b_{i_2}, \ldots, a_{i_t}, b_{i_t}$), this sequence is good.

What is the largest subset of indices you can choose? You also need to construct the corresponding index sequence $i_1, i_2, \ldots, i_t$.

-----Input-----

The first line contains single integer $n$ ($2 \leq n \leq 3 \cdot 10^5$) — the number of pairs.

Each of the next $n$ lines contain two numbers — $a_i$ and $b_i$ ($1 \le a_i, b_i \le 2 \cdot n$) — the elements of the pairs.

It is guaranteed that all integers in the pairs are distinct, that is, every integer from $1$ to $2 \cdot n$ is mentioned exactly once.

-----Output-----

In the first line print a single integer $t$ — the number of pairs in the answer.

Then print $t$ distinct integers $i_1, i_2, \ldots, i_t$ — the indexes of pairs in the corresponding order.

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

Output
3
1 5 3

Input
3
5 4
3 2
6 1

Output
3
3 2 1

-----Note-----

The final sequence in the first example is $1 < 7 > 3 < 5 > 2 < 10$.

The final sequence in the second example is $6 > 1 < 3 > 2 < 5 > 4$.

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

# https://codeforces.com/contest/1148/problem/D
n = int(input())

d = {}
d['+'] = []
d['-'] = []

for _ in range(n):
    a, b = list(map(int, input().split()))
    if a < b:
        d['+'].append([b, _])
    else:
        d['-'].append([b, _])

d['+'] = sorted(d['+'], key = lambda x: x[0], reverse=True)
d['-'] = sorted(d['-'], key = lambda x: x[0])

s = ''
if len(d['+']) > len(d['-']):
    print(len(d['+']))
    for x in d['+']:
        s+=str(x[1]+1) +  ' '
else:
    print(len(d['-']))
    for x in d['-']:
        s+=str(x[1]+1) +  ' '

print(s)

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


I found an interesting problem on https://codeforces.com/problemset/problem/1150/A:
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market!

In the morning, there are $n$ opportunities to buy shares. The $i$-th of them allows to buy as many shares as you want, each at the price of $s_i$ bourles.

In the evening, there are $m$ opportunities to sell shares. The $i$-th of them allows to sell as many shares as you want, each at the price of $b_i$ bourles. You can't sell more shares than you have.

It's morning now and you possess $r$ bourles and no shares.

What is the maximum number of bourles you can hold after the evening?

-----Input-----

The first line of the input contains three integers $n, m, r$ ($1 \leq n \leq 30$, $1 \leq m \leq 30$, $1 \leq r \leq 1000$) — the number of ways to buy the shares on the market, the number of ways to sell the shares on the market, and the number of bourles you hold now.

The next line contains $n$ integers $s_1, s_2, \dots, s_n$ ($1 \leq s_i \leq 1000$); $s_i$ indicates the opportunity to buy shares at the price of $s_i$ bourles.

The following line contains $m$ integers $b_1, b_2, \dots, b_m$ ($1 \leq b_i \leq 1000$); $b_i$ indicates the opportunity to sell shares at the price of $b_i$ bourles.

-----Output-----

Output a single integer — the maximum number of bourles you can hold after the evening.

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

Output
26

Input
2 2 50
5 7
4 2

Output
50

-----Note-----

In the first example test, you have $11$ bourles in the morning. It's optimal to buy $5$ shares of a stock at the price of $2$ bourles in the morning, and then to sell all of them at the price of $5$ bourles in the evening. It's easy to verify that you'll have $26$ bourles after the evening.

In the second example test, it's optimal not to take any action.

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

n, m, r = list(map(int, input().split()))
a = min(list(map(int, input().split())))
b = max(list(map(int, input().split())))
print(max(r, (r//a)*(b-a)+r))


I found an interesting problem on https://codeforces.com/problemset/problem/1150/B:
One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile:  [Image]  By the pieces lay a large square wooden board. The board is divided into $n^2$ cells arranged into $n$ rows and $n$ columns. Some of the cells are already occupied by single tiles stuck to it. The remaining cells are free.

Alice started wondering whether she could fill the board completely using the pieces she had found. Of course, each piece has to cover exactly five distinct cells of the board, no two pieces can overlap and every piece should fit in the board entirely, without some parts laying outside the board borders. The board however was too large for Alice to do the tiling by hand. Can you help determine if it's possible to fully tile the board?

-----Input-----

The first line of the input contains a single integer $n$ ($3 \leq n \leq 50$) — the size of the board.

The following $n$ lines describe the board. The $i$-th line ($1 \leq i \leq n$) contains a single string of length $n$. Its $j$-th character ($1 \leq j \leq n$) is equal to "." if the cell in the $i$-th row and the $j$-th column is free; it is equal to "#" if it's occupied.

You can assume that the board contains at least one free cell.

-----Output-----

Output YES if the board can be tiled by Alice's pieces, or NO otherwise. You can print each letter in any case (upper or lower).

-----Examples-----
Input
3
#.#
...
#.#

Output
YES

Input
4
##.#
#...
####
##.#

Output
NO

Input
5
#.###
....#
#....
###.#
#####

Output
YES

Input
5
#.###
....#
#....
....#
#..##

Output
NO

-----Note-----

The following sketches show the example boards and their tilings if such tilings exist:  [Image]

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

# Please DON'T hack me! TY!
import sys

class Main:
    def __init__(self):
        self.buff = None
        self.index = 0

    def __next__(self):
        if self.buff is None or self.index == len(self.buff):
            self.buff = self.next_line()
            self.index = 0
        val = self.buff[self.index]
        self.index += 1
        return val

    def next_line(self, _map=str):
        return list(map(_map, sys.stdin.readline().split()))

    def next_int(self):
        return int(next(self))

    def solve(self):
        n = self.next_int()
        ss = [[s for s in next(self)] for _ in range(0, n)]
        for i in range(0, n):
            for j in range(0, n):
                if ss[i][j] == '.':
                    if j == 0 or j == n - 1 or i >= n - 2:
                        print('NO')
                        return
                    if ss[i + 1][j - 1] != '.' or ss[i + 1][j] != '.' or ss[i + 1][j + 1] != '.' or ss[i + 2][j] != '.':
                        print('NO')
                        return
                    ss[i + 1][j - 1] = '#'
                    ss[i + 1][j] = '#'
                    ss[i + 1][j + 1] = '#'
                    ss[i + 2][j] = '#'
        print('YES')

def __starting_point():
    Main().solve()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1151/A:
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".

Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string $s$ consisting of uppercase letters and length of at least $4$, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string $s$ with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".

Help Maxim solve the problem that the teacher gave him.

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

-----Input-----

The first line contains a single integer $n$ ($4 \leq n \leq 50$) — the length of the string $s$.

The second line contains the string $s$, consisting of exactly $n$ uppercase letters of the Latin alphabet.

-----Output-----

Output the minimum number of operations that need to be applied to the string $s$ so that the genome appears as a substring in it.

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

Output
2
Input
5
ZDATG

Output
5
Input
6
AFBAKC

Output
16

-----Note-----

In the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring.

In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.

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

n=int(input())
s=input()
g='ACTG'
m = 10000000
for i in range(n - 3):
	t = 0
	for j in range(4):
		k = abs(ord(s[i + j]) - ord(g[j]))
		t += min(k, 26 - k)
	m = min(m, t)
print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/1151/B:
Student Dima from Kremland has a matrix $a$ of size $n \times m$ filled with non-negative integers.

He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him!

Formally, he wants to choose an integers sequence $c_1, c_2, \ldots, c_n$ ($1 \leq c_j \leq m$) so that the inequality $a_{1, c_1} \oplus a_{2, c_2} \oplus \ldots \oplus a_{n, c_n} > 0$ holds, where $a_{i, j}$ is the matrix element from the $i$-th row and the $j$-th column.

Here $x \oplus y$ denotes the bitwise XOR operation of integers $x$ and $y$.

-----Input-----

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

Each of the next $n$ lines contains $m$ integers: the $j$-th integer in the $i$-th line is the $j$-th element of the $i$-th row of the matrix $a$, i.e. $a_{i, j}$ ($0 \leq a_{i, j} \leq 1023$).

-----Output-----

If there is no way to choose one integer from each row so that their bitwise exclusive OR is strictly greater than zero, print "NIE".

Otherwise print "TAK" in the first line, in the next line print $n$ integers $c_1, c_2, \ldots c_n$ ($1 \leq c_j \leq m$), so that the inequality $a_{1, c_1} \oplus a_{2, c_2} \oplus \ldots \oplus a_{n, c_n} > 0$ holds.

If there is more than one possible answer, you may output any.

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

Output
NIE

Input
2 3
7 7 7
7 7 10

Output
TAK
1 3

-----Note-----

In the first example, all the numbers in the matrix are $0$, so it is impossible to select one number in each row of the table so that their bitwise exclusive OR is strictly greater than zero.

In the second example, the selected numbers are $7$ (the first number in the first line) and $10$ (the third number in the second line), $7 \oplus 10 = 13$, $13$ is more than $0$, so the answer is found.

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

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

def xor(arr):
    t = 0
    for a in arr:
        t = t^a
    return t

a = []
win = False
j = 0
for i in range(n):
    tmp = [int(t) for t in input().split()]
    if len(set(tmp)) > 1:
        win = True
        j = i
    a.append(tmp)
if not win:
    if xor([t[0] for t in a]) == 0:
        print('NIE')
    else:
        print('TAK')
        print(' '.join(['1']*n))
else:
    print('TAK')
    if xor([t[0] for t in a]) != 0:
        print(' '.join(['1']*n))
    else:
        ans = ['1']*n
        k = 1
        while a[j][k] == a[j][0]:
            k += 1
        ans[j] = str(k + 1)
        print(' '.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1151/C:
Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.

Consider two infinite sets of numbers. The first set consists of odd positive numbers ($1, 3, 5, 7, \ldots$), and the second set consists of even positive numbers ($2, 4, 6, 8, \ldots$). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage — the first two numbers from the second set, on the third stage — the next four numbers from the first set, on the fourth — the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out two times more numbers than at the previous one, and also changes the set from which these numbers are written out to another.

The ten first written numbers: $1, 2, 4, 3, 5, 7, 9, 6, 8, 10$. Let's number the numbers written, starting with one.

The task is to find the sum of numbers with numbers from $l$ to $r$ for given integers $l$ and $r$. The answer may be big, so you need to find the remainder of the division by $1000000007$ ($10^9+7$).

Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem.

-----Input-----

The first line contains two integers $l$ and $r$ ($1 \leq l \leq r \leq 10^{18}$) — the range in which you need to find the sum.

-----Output-----

Print a single integer — the answer modulo $1000000007$ ($10^9+7$).

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

Output
7
Input
5 14

Output
105
Input
88005553535 99999999999

Output
761141116

-----Note-----

In the first example, the answer is the sum of the first three numbers written out ($1 + 2 + 4 = 7$).

In the second example, the numbers with numbers from $5$ to $14$: $5, 7, 9, 6, 8, 10, 12, 14, 16, 18$. Their sum is $105$.

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

MOD = 1000000007
def evensum(n):
    n //= 2
    return (n*(n+1))%MOD
def oddsum(n):
    a = (n*(n+1))//2
    a %= MOD
    a -= evensum(n-1)
    a %= MOD
    return a
def cs(n):
    i = 0
    cn = 1
    tot = 0
    so = -1
    se = 0
    while tot < n:
        cur = min(cn, n-tot)
        if i % 2 == 0:
            so += 2*cur
        else:
            se += 2*cur
        cn *= 2
        tot += cur
        i += 1
    ans = 0
    if se > 0: ans += evensum(se)
    if so > -1: ans += oddsum(so)
    ans %= MOD
    return ans
L, R = list(map(int, input().split()))
ans = cs(R)
if L>1: ans -= cs(L-1)
ans %= MOD
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1151/D:
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of $n$ high school students numbered from $1$ to $n$. Initially, each student $i$ is on position $i$. Each student $i$ is characterized by two numbers — $a_i$ and $b_i$. Dissatisfaction of the person $i$ equals the product of $a_i$ by the number of people standing to the left of his position, add the product $b_i$ by the number of people standing to the right of his position. Formally, the dissatisfaction of the student $i$, which is on the position $j$, equals $a_i \cdot (j-1) + b_i \cdot (n-j)$.

The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.

Although Stas is able to solve such problems, this was not given to him. He turned for help to you.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the number of people in the queue.

Each of the following $n$ lines contains two integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq 10^8$) — the characteristic of the student $i$, initially on the position $i$.

-----Output-----

Output one integer — minimum total dissatisfaction which can be achieved by rearranging people in the queue.

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

Output
12
Input
4
2 4
3 3
7 1
2 3

Output
25
Input
10
5 10
12 4
31 45
20 55
30 17
29 30
41 32
7 1
5 5
3 15

Output
1423

-----Note-----

In the first example it is optimal to put people in this order: ($3, 1, 2$). The first person is in the position of $2$, then his dissatisfaction will be equal to $4 \cdot 1+2 \cdot 1=6$. The second person is in the position of $3$, his dissatisfaction will be equal to $2 \cdot 2+3 \cdot 0=4$. The third person is in the position of $1$, his dissatisfaction will be equal to $6 \cdot 0+1 \cdot 2=2$. The total dissatisfaction will be $12$.

In the second example, you need to put people in this order: ($3, 2, 4, 1$). The total dissatisfaction will be $25$.

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

n = int(input())

pos = []
neg = []

res = 0
for i in range(n):
    a,b = list(map(int,input().split()))
    if a > b:
        pos.append([a, b])
    elif a < b:
        neg.append([a, b])
    else:
        res += (n - 1) * a

pos.sort(key=lambda l: -abs(l[0] - l[1]))
neg.sort(key=lambda l: -abs(l[0] - l[1]))

def f(i, l):
    return l[0] * (i - 1) + l[1] * (n - i)

for i in range(len(pos)):
    res += f(i + 1, pos[i])

for i in range(len(neg)):
    res += f(n - i, neg[i])

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1151/E:
The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of $n$ vertices. Each vertex $i$ has its own value $a_i$. All vertices are connected in series by edges. Formally, for every $1 \leq i < n$ there is an edge between the vertices of $i$ and $i+1$.

Denote the function $f(l, r)$, which takes two integers $l$ and $r$ ($l \leq r$):

    We leave in the tree only vertices whose values range from $l$ to $r$.    The value of the function will be the number of connected components in the new graph.

Your task is to calculate the following sum: $$\sum_{l=1}^{n} \sum_{r=l}^{n} f(l, r) $$

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq n$) — the values of the vertices.

-----Output-----

Print one number — the answer to the problem.

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

Output
7
Input
4
2 1 1 3

Output
11
Input
10
1 5 2 5 5 3 10 6 5 1

Output
104

-----Note-----

In the first example, the function values will be as follows:   $f(1, 1)=1$ (there is only a vertex with the number $2$, which forms one component)  $f(1, 2)=1$ (there are vertices $1$ and $2$ that form one component)  $f(1, 3)=1$ (all vertices remain, one component is obtained)  $f(2, 2)=1$ (only vertex number $1$)  $f(2, 3)=2$ (there are vertices $1$ and $3$ that form two components)  $f(3, 3)=1$ (only vertex $3$)  Totally out $7$.

In the second example, the function values will be as follows:   $f(1, 1)=1$  $f(1, 2)=1$  $f(1, 3)=1$  $f(1, 4)=1$  $f(2, 2)=1$  $f(2, 3)=2$  $f(2, 4)=2$  $f(3, 3)=1$  $f(3, 4)=1$  $f(4, 4)=0$ (there is no vertex left, so the number of components is $0$)  Totally out $11$.

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

# AC
import sys

class Main:
    def __init__(self):
        self.buff = None
        self.index = 0

    def __next__(self):
        if self.buff is None or self.index == len(self.buff):
            self.buff = sys.stdin.readline().split()
            self.index = 0
        val = self.buff[self.index]
        self.index += 1
        return val

    def next_int(self):
        return int(next(self))

    def solve(self):
        n = self.next_int()
        x = [self.next_int() for _ in range(0, n)]
        ans = 0
        for i in range(0, n):
            ans += x[i] * (n - x[i] + 1)
            if i > 0:
                ans -= min(x[i], x[i - 1]) * (n - max(x[i], x[i - 1]) + 1)
        print(ans)

def __starting_point():
    Main().solve()

__starting_point()