I found an interesting problem on https://codeforces.com/problemset/problem/1408/B:
You are given a non-decreasing array of non-negative integers $a_1, a_2, \ldots, a_n$. Also you are given a positive integer $k$.

You want to find $m$ non-decreasing arrays of non-negative integers $b_1, b_2, \ldots, b_m$, such that:  The size of $b_i$ is equal to $n$ for all $1 \leq i \leq m$.  For all $1 \leq j \leq n$, $a_j = b_{1, j} + b_{2, j} + \ldots + b_{m, j}$. In the other word, array $a$ is the sum of arrays $b_i$.  The number of different elements in the array $b_i$ is at most $k$ for all $1 \leq i \leq m$.

Find the minimum possible value of $m$, or report that there is no possible $m$.

-----Input-----

The first line contains one integer $t$ ($1 \leq t \leq 100$): the number of test cases.

The first line of each test case contains two integers $n$, $k$ ($1 \leq n \leq 100$, $1 \leq k \leq n$).

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_1 \leq a_2 \leq \ldots \leq a_n \leq 100$, $a_n > 0$).

-----Output-----

For each test case print a single integer: the minimum possible value of $m$. If there is no such $m$, print $-1$.

-----Example-----
Input
6
4 1
0 0 0 1
3 1
3 3 3
11 3
0 1 2 2 3 3 3 4 4 4 4
5 3
1 2 3 4 5
9 4
2 2 3 5 7 11 13 13 17
10 7
0 1 1 2 3 3 4 5 5 6

Output
-1
1
2
2
2
1

-----Note-----

In the first test case, there is no possible $m$, because all elements of all arrays should be equal to $0$. But in this case, it is impossible to get $a_4 = 1$ as the sum of zeros.

In the second test case, we can take $b_1 = [3, 3, 3]$. $1$ is the smallest possible value of $m$.

In the third test case, we can take $b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]$ and $b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]$. It's easy to see, that $a_i = b_{1, i} + b_{2, i}$ for all $i$ and the number of different elements in $b_1$ and in $b_2$ is equal to $3$ (so it is at most $3$). It can be proven that $2$ is the smallest possible value of $m$.

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

from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *
import sys
'''
@lru_cache(None)
def fact(x):
    if x<2:
        return 1
    return fact(x-1)*x

@lru_cache(None)
def per(i,j):
    return fact(i)//fact(i-j)

@lru_cache(None)
def com(i,j):
    return per(i,j)//fact(j)

def linc(f,t,l,r):
    while l<r:
        mid=(l+r)//2
        if t>f(mid):
            l=mid+1
        else:
            r=mid
    return l

def rinc(f,t,l,r):
    while l<r:
        mid=(l+r+1)//2
        if t<f(mid):
            r=mid-1
        else:
            l=mid
    return l

def ldec(f,t,l,r):
    while l<r:
        mid=(l+r)//2
        if t<f(mid):
            l=mid+1
        else:
            r=mid
    return l

def rdec(f,t,l,r):
    while l<r:
        mid=(l+r+1)//2
        if t>f(mid):
            r=mid-1
        else:
            l=mid
    return l

def isprime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False
    return True

def power2(n):
    while not n&1:
        n>>=1
    return n==1
'''
'''
import time
s=time.time()
e=time.time()
print(e-s)
'''

t=int(input())
for i in range(t):
    n,k=list(map(int,input().split()))
    #n=int(input())
    a=set(map(int,input().split()))
    n=len(a)
    if n==1:
        ans=1
    else:
        if k==1:
            ans=-1
        else:
            ans=ceil((n-1)/(k-1))
    print(ans)
'''
n,m=map(int,input().split())
graph=defaultdict(dict)
for i in range(m):
    u,v,w=map(int,input().split())
    graph[u][v]=w
    graph[v][u]=w
def dij(u,v):
    graph[u][v]*=2
    graph[v][u]*=2
    d={}
    d[1]=0
    for i in range(2,n+1):
        d[i]=inf
    remain=set(range(2,n+1))
    for i in graph[1]:
        d[i]=graph[1][i]
    while remain:
        k=min(remain,key=lambda x: d[x])
        remain.remove(k)
        for i in remain:
            if i in graph[k]:
                d[i]=min(d[i],d[k]+graph[k][i])
    graph[u][v]//=2
   ...


I found an interesting problem on https://codeforces.com/problemset/problem/1408/D:
There are $n$ robbers at coordinates $(a_1, b_1)$, $(a_2, b_2)$, ..., $(a_n, b_n)$ and $m$ searchlight at coordinates $(c_1, d_1)$, $(c_2, d_2)$, ..., $(c_m, d_m)$.

In one move you can move each robber to the right (increase $a_i$ of each robber by one) or move each robber up (increase $b_i$ of each robber by one). Note that you should either increase all $a_i$ or all $b_i$, you can't increase $a_i$ for some points and $b_i$ for some other points.

Searchlight $j$ can see a robber $i$ if $a_i \leq c_j$ and $b_i \leq d_j$.

A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair $i,j$ such that searchlight $j$ can see a robber $i$).

What is the minimum number of moves you need to perform to reach a safe configuration?

-----Input-----

The first line of input contains two integers $n$ and $m$ ($1 \leq n, m \leq 2000$): the number of robbers and the number of searchlight.

Each of the next $n$ lines contains two integers $a_i$, $b_i$ ($0 \leq a_i, b_i \leq 10^6$), coordinates of robbers.

Each of the next $m$ lines contains two integers $c_i$, $d_i$ ($0 \leq c_i, d_i \leq 10^6$), coordinates of searchlights.

-----Output-----

Print one integer: the minimum number of moves you need to perform to reach a safe configuration.

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

Output
3

Input
2 3
1 6
6 1
10 1
1 10
7 7

Output
4

Input
1 2
0 0
0 0
0 0

Output
1

Input
7 3
0 8
3 8
2 7
0 10
5 5
7 0
3 5
6 6
3 11
11 5

Output
6

-----Note-----

In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates $(3, 0)$.

The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates $(2, 3)$ and $3 > 2$.

In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates $(3, 8)$, $(8, 3)$.

It's easy the see that the configuration of the robbers is safe.

It can be proved that you can't reach a safe...

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

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

N, M = list(map(int, input().split()))
X = []
for _ in range(N):
    a, b = list(map(int, input().split()))
    X.append((a, b))
Y = []
for _ in range(M):
    c, d = list(map(int, input().split()))
    c, d = c, d+1
    Y.append((c, d))
Y.sort(key = lambda x: -x[0])

Z = [0] * 1001001
for a, b in X:
    for c, d in Y:
        if c >= a:
            Z[c-a] = max(Z[c-a], d - b)

ans = 1 << 30
ma = 0
for i in range(1001000)[::-1]:
    ma = max(ma, Z[i])
    ans = min(ans, ma + i)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1408/F:
You are given an integer $n$.

You should find a list of pairs $(x_1, y_1)$, $(x_2, y_2)$, ..., $(x_q, y_q)$ ($1 \leq x_i, y_i \leq n$) satisfying the following condition.

Let's consider some function $f: \mathbb{N} \times \mathbb{N} \to \mathbb{N}$ (we define $\mathbb{N}$ as the set of positive integers). In other words, $f$ is a function that returns a positive integer for a pair of positive integers.

Let's make an array $a_1, a_2, \ldots, a_n$, where $a_i = i$ initially.

You will perform $q$ operations, in $i$-th of them you will:   assign $t = f(a_{x_i}, a_{y_i})$ ($t$ is a temporary variable, it is used only for the next two assignments);  assign $a_{x_i} = t$;  assign $a_{y_i} = t$.

In other words, you need to simultaneously change $a_{x_i}$ and $a_{y_i}$ to $f(a_{x_i}, a_{y_i})$. Note that during this process $f(p, q)$ is always the same for a fixed pair of $p$ and $q$.

In the end, there should be at most two different numbers in the array $a$.

It should be true for any function $f$.

Find any possible list of pairs. The number of pairs should not exceed $5 \cdot 10^5$.

-----Input-----

The single line contains a single integer $n$ ($1 \leq n \leq 15\,000$).

-----Output-----

In the first line print $q$ ($0 \leq q \leq 5 \cdot 10^5$) — the number of pairs.

In each of the next $q$ lines print two integers. In the $i$-th line print $x_i$, $y_i$ ($1 \leq x_i, y_i \leq n$).

The condition described in the statement should be satisfied.

If there exists multiple answers you can print any of them.

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

Output
1
1 2

Input
4

Output
2
1 2
3 4

-----Note-----

In the first example, after performing the only operation the array $a$ will be $[f(a_1, a_2), f(a_1, a_2), a_3]$. It will always have at most two different numbers.

In the second example, after performing two operations the array $a$ will be $[f(a_1, a_2), f(a_1, a_2), f(a_3, a_4), f(a_3, a_4)]$. It will always have at most two different numbers.

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

n = int(input())

def f(x, a):
    if x == 2:
        return [(a, a+1)]
    else:
        s = []
        for i in range(x // 2):
            s += [(a + i, a + i + x // 2)]
        return f(x // 2, a) + f(x // 2, x // 2 + a) + s

if n == 0 or n == 1:
    print(0)
else:
    x = 1
    for i in range(1, n):

        if 2 * x > n:
            break
        x *= 2
    s1 = f(x, 1)
    s2 = f(x, n - x + 1)
    print(len(s1) + len(s2))
    for i in range(len(s1)):
        print(s1[i][0], s1[i][1])
    for i in range(len(s2)):
        print(s2[i][0], s2[i][1])


I found an interesting problem on https://codeforces.com/problemset/problem/1409/A:
You are given two integers $a$ and $b$.

In one move, you can choose some integer $k$ from $1$ to $10$ and add it to $a$ or subtract it from $a$. In other words, you choose an integer $k \in [1; 10]$ and perform $a := a + k$ or $a := a - k$. You may use different values of $k$ in different moves.

Your task is to find the minimum number of moves required to obtain $b$ from $a$.

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.

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

-----Output-----

For each test case, print the answer: the minimum number of moves required to obtain $b$ from $a$.

-----Example-----
Input
6
5 5
13 42
18 4
1337 420
123456789 1000000000
100500 9000

Output
0
3
2
92
87654322
9150

-----Note-----

In the first test case of the example, you don't need to do anything.

In the second test case of the example, the following sequence of moves can be applied: $13 \rightarrow 23 \rightarrow 32 \rightarrow 42$ (add $10$, add $9$, add $10$).

In the third test case of the example, the following sequence of moves can be applied: $18 \rightarrow 10 \rightarrow 4$ (subtract $8$, subtract $6$).

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

import math
from collections import deque
from sys import stdin, stdout
from string import ascii_letters
import sys
letters = ascii_letters
input = stdin.readline
#print = stdout.write

for i in range(int(input())):
#for i in range(1):
    a, b = list(map(int, input().split()))
    print(abs(a - b) // 10 + (1 if abs(a - b) % 10 != 0 else 0))


I found an interesting problem on https://codeforces.com/problemset/problem/1409/B:
You are given four integers $a$, $b$, $x$ and $y$. Initially, $a \ge x$ and $b \ge y$. You can do the following operation no more than $n$ times:

  Choose either $a$ or $b$ and decrease it by one. However, as a result of this operation, value of $a$ cannot become less than $x$, and value of $b$ cannot become less than $y$.

Your task is to find the minimum possible product of $a$ and $b$ ($a \cdot b$) you can achieve by applying the given operation no more than $n$ times.

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.

The only line of the test case contains five integers $a$, $b$, $x$, $y$ and $n$ ($1 \le a, b, x, y, n \le 10^9$). Additional constraint on the input: $a \ge x$ and $b \ge y$ always holds.

-----Output-----

For each test case, print one integer: the minimum possible product of $a$ and $b$ ($a \cdot b$) you can achieve by applying the given operation no more than $n$ times.

-----Example-----
Input
7
10 10 8 5 3
12 8 8 7 2
12343 43 4543 39 123212
1000000000 1000000000 1 1 1
1000000000 1000000000 1 1 1000000000
10 11 2 1 5
10 11 9 1 10

Output
70
77
177177
999999999000000000
999999999
55
10

-----Note-----

In the first test case of the example, you need to decrease $b$ three times and obtain $10 \cdot 7 = 70$.

In the second test case of the example, you need to decrease $a$ one time, $b$ one time and obtain $11 \cdot 7 = 77$.

In the sixth test case of the example, you need to decrease $a$ five times and obtain $5 \cdot 11 = 55$.

In the seventh test case of the example, you need to decrease $b$ ten times and obtain $10 \cdot 1 = 10$.

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

for i in range(int(input())):
	a, b, x, y, n = (int(j) for j in input().split())
	ans = 10 ** 18

	d1 = a - x
	d2 = b - y
	if (d1 > n):
		ans = min(ans, (a - n) * b)
	elif (d1 + d2 > n):
		ans = min(ans, x * (b - n + d1))
	else:
		ans = min(ans, x * y)

	x, y = y, x
	a, b = b, a

	d1 = a - x
	d2 = b - y
	if (d1 > n):
		ans = min(ans, (a - n) * b)
	elif (d1 + d2 > n):
		ans = min(ans, x * (b - n + d1))
	else:
		ans = min(ans, x * y)

	print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1409/C:
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array:

  The array consists of $n$ distinct positive (greater than $0$) integers.  The array contains two elements $x$ and $y$ (these elements are known for you) such that $x < y$.  If you sort the array in increasing order (such that $a_1 < a_2 < \ldots < a_n$), differences between all adjacent (consecutive) elements are equal (i.e. $a_2 - a_1 = a_3 - a_2 = \ldots = a_n - a_{n-1})$.

It can be proven that such an array always exists under the constraints given below.

Among all possible arrays that satisfy the given conditions, we ask you to restore one which has the minimum possible maximum element. In other words, you have to minimize $\max(a_1, a_2, \dots, a_n)$.

You have to answer $t$ independent test cases.

-----Input-----

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

The only line of the test case contains three integers $n$, $x$ and $y$ ($2 \le n \le 50$; $1 \le x < y \le 50$) — the length of the array and two elements that are present in the array, respectively.

-----Output-----

For each test case, print the answer: $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the $i$-th element of the required array. If there are several answers, you can print any (it also means that the order of elements doesn't matter).

It can be proven that such an array always exists under the given constraints.

-----Example-----
Input
5
2 1 49
5 20 50
6 20 50
5 3 8
9 13 22

Output
1 49
20 40 30 50 10
26 32 20 38 44 50
8 23 18 13 3
1 10 13 4 19 22 25 16 7

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

from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop,heapify
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline

from itertools import accumulate
from functools import lru_cache

M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]

def check(diff, x, y, n):
    s = set()
    i = y
    while n and i > 0:
        s.add(i)
        i -= diff
        n -= 1
    i = y + diff
    while n:
        n -= 1
        s.add(i)
        i += diff

    return -1 if x not in s else max(s)

for _ in range(val()):
    n, x, y = li()

    diff = factors(y - x)

    for i in range(1, y - x + 1):
        ans = check(i, x, y, n)
        if ans != -1:
            diff = i
            break

    l = []
    while n:
        l.append(ans)
        n -= 1
        ans -= diff
    print(*l)


I found an interesting problem on https://codeforces.com/problemset/problem/1409/D:
You are given a positive integer $n$. In one move, you can increase $n$ by one (i.e. make $n := n + 1$). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of $n$ be less than or equal to $s$.

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.

The only line of the test case contains two integers $n$ and $s$ ($1 \le n \le 10^{18}$; $1 \le s \le 162$).

-----Output-----

For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of $n$ be less than or equal to $s$.

-----Example-----
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1

Output
8
0
500
2128012501878
899999999999999999

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

# d-decrease-the-sum-of-digits.yml

def dsum(x):
    res = 0
    while x:
        res += x % 10
        x //= 10
    return res

for _ in range(int(input())):
    n, s = list(map(int, input().split()))
    # print(f'init: n={n}, s={s}')

    p = 1
    ans = 0
    csum = dsum(n)
    # its=10
    while csum > s:
        # print(f'n={n}')
        add = 10 * p - n % (10 * p)
        if add == 10 * p: add = 0
        ans += add
        n += add
        csum = dsum(n)
        p *= 10
        # print(f'n={n},p={p},csum={csum},add={add}')

        # its-=1
        # assert its

    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1409/E:
There are $n$ points on a plane. The $i$-th point has coordinates $(x_i, y_i)$. You have two horizontal platforms, both of length $k$. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same $y$-coordinate) and have integer borders. If the left border of the platform is $(x, y)$ then the right border is $(x + k, y)$ and all points between borders (including borders) belong to the platform.

Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same $y$-coordinate.

When you place both platforms on a plane, all points start falling down decreasing their $y$-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.

Your task is to find the maximum number of points you can save if you place both platforms optimally.

You have to answer $t$ independent test cases.

For better understanding, please read the Note section below to see a picture for the first test case.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$; $1 \le k \le 10^9$) — the number of points and the length of each platform, respectively. The second line of the test case contains $n$ integers $x_1, x_2, \dots, x_n$ ($1 \le x_i \le 10^9$), where $x_i$ is $x$-coordinate of the $i$-th point. The third line of the input contains $n$ integers $y_1, y_2, \dots, y_n$ ($1 \le y_i \le 10^9$), where $y_i$ is $y$-coordinate of the $i$-th point. All points are distinct (there is no pair $1 \le i < j \le n$ such that $x_i = x_j$ and $y_i = y_j$).

It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).

-----Output-----

For each test case, print the answer: the maximum number of points you can save if you place both platforms...

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

import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
# from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var): sys.stdout.write(' '.join(map(str, var)) + '\n')
def out(var): sys.stdout.write(str(var) + '\n')
from decimal import Decimal
# from fractions import Fraction
# sys.setrecursionlimit(100000)
mod = int(1e9) + 7
INF=2**32

def cal(n):
    ans=0
    while n:
        ans+=n%10
        n//=10
    return ans

for t in range(int(data())):
   n,k=mdata()
   ans=1
   X=sorted(mdata())
   Y=mdata()
   q=deque()
   d=dd(int)
   m=0
   for i in range(n):
        while q and X[i]-k>q[0]:
            m=max(m,d[q.popleft()])
        q.append(X[i])
        d[X[i]]=len(q)
        ans=max(ans,m+len(q))
   out(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1413/A:
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are $T$ rooms there. Every room has a door into it, each door can be described by the number $n$ of seals on it and their integer energies $a_1$, $a_2$, ..., $a_n$. All energies $a_i$ are nonzero and do not exceed $100$ by absolute value. Also, $n$ is even.

In order to open a door, Naruto must find such $n$ seals with integer energies $b_1$, $b_2$, ..., $b_n$ that the following equality holds: $a_{1} \cdot b_{1} + a_{2} \cdot b_{2} + ... + a_{n} \cdot b_{n} = 0$. All $b_i$ must be nonzero as well as $a_i$ are, and also must not exceed $100$ by absolute value. Please find required seals for every room there.

-----Input-----

The first line contains the only integer $T$ ($1 \leq T \leq 1000$) standing for the number of rooms in the Orochimaru's lair. The other lines contain descriptions of the doors.

Each description starts with the line containing the only even integer $n$ ($2 \leq n \leq 100$) denoting the number of seals.

The following line contains the space separated sequence of nonzero integers $a_1$, $a_2$, ..., $a_n$ ($|a_{i}| \leq 100$, $a_{i} \neq 0$) denoting the energies of seals.

-----Output-----

For each door print a space separated sequence of nonzero integers $b_1$, $b_2$, ..., $b_n$ ($|b_{i}| \leq 100$, $b_{i} \neq 0$) denoting the seals that can open the door. If there are multiple valid answers, print any. It can be proven that at least one answer always exists.

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

Output
-100 1
1 1 1 -1

-----Note-----

For the first door Naruto can use energies $[-100, 1]$. The required equality does indeed hold: $1 \cdot (-100) + 100 \cdot 1 = 0$.

For the second door Naruto can use, for example, energies $[1, 1, 1, -1]$. The required equality also holds: $1 \cdot 1 + 2 \cdot 1 + 3 \cdot 1 + 6 \cdot (-1) = 0$.

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

t = int(input())
for j in range(t):
    n = int(input())
    ans = []
    s = list(map(int, input().split()))
    for i in range(n):
        if i % 2 == 0:
            ans.append(-s[i + 1])
            ans.append(s[i])
    print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1413/C:
After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has $6$ strings and an infinite number of frets numbered from $1$. Fretting the fret number $j$ on the $i$-th string produces the note $a_{i} + j$.

Tayuya wants to play a melody of $n$ notes. Each note can be played on different string-fret combination. The easiness of performance depends on the difference between the maximal and the minimal indices of used frets. The less this difference is, the easier it is to perform the technique. Please determine the minimal possible difference.

For example, if $a = [1, 1, 2, 2, 3, 3]$, and the sequence of notes is $4, 11, 11, 12, 12, 13, 13$ (corresponding to the second example), we can play the first note on the first string, and all the other notes on the sixth string. Then the maximal fret will be $10$, the minimal one will be $3$, and the answer is $10 - 3 = 7$, as shown on the picture. [Image]

-----Input-----

The first line contains $6$ space-separated numbers $a_{1}$, $a_{2}$, ..., $a_{6}$ ($1 \leq a_{i} \leq 10^{9}$) which describe the Tayuya's strings.

The second line contains the only integer $n$ ($1 \leq n \leq 100\,000$) standing for the number of notes in the melody.

The third line consists of $n$ integers $b_{1}$, $b_{2}$, ..., $b_{n}$ ($1 \leq b_{i} \leq 10^{9}$), separated by space. They describe the notes to be played. It's guaranteed that $b_i > a_j$ for all $1\leq i\leq n$ and $1\leq j\leq 6$, in other words, you can play each note on any string.

-----Output-----

Print the minimal possible difference of the maximal and the minimal indices of used frets.

-----Examples-----
Input
1 4 100 10 30 5
6
101 104 105 110 130 200

Output
0

Input
1 1 2 2 3 3
7
13 4 11 12 11 13 12

Output
7

-----Note-----

In the first sample test it is optimal to play the first note on the first string, the second note on the second string, the third note on the sixth string, the fourth note on the fourth string, the fifth note on the fifth string,...

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

a=list(map(int,input().split()));n=int(input());s=list(map(int,input().split()));b=[]
for i in range(n):
	for j in a:b.append((s[i]-j)*n+i)
b=sorted(b);cs={};i=j=0;ans=10**18
cs[b[0]%n]=cs.get(b[0]%n,0)+1;z=len(b)
while j<z:
	while j+1<z and len(cs)<n:j+=1;cs[b[j]%n]=cs.get(b[j]%n,0)+1
	while len(cs)==n:
		ans=min(ans,b[j]//n-b[i]//n)
		cs[b[i]%n]-=1
		if cs[b[i]%n]==0:cs.pop(b[i]%n)
		i+=1
	if j+1==z:break
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1413/D:
Tenten runs a weapon shop for ninjas. Today she is willing to sell $n$ shurikens which cost $1$, $2$, ..., $n$ ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.

Tenten keeps a record for all events, and she ends up with a list of the following types of records:

  + means that she placed another shuriken on the showcase;  - x means that the shuriken of price $x$ was bought.

Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!

-----Input-----

The first line contains the only integer $n$ ($1\leq n\leq 10^5$) standing for the number of shurikens.

The following $2n$ lines describe the events in the format described above. It's guaranteed that there are exactly $n$ events of the first type, and each price from $1$ to $n$ occurs exactly once in the events of the second type.

-----Output-----

If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".

In the first case the second line must contain $n$ space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.

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

Output
YES
4 2 3 1

Input
1
- 1
+

Output
NO

Input
3
+
+
+
- 2
- 1
- 3

Output
NO

-----Note-----

In the first example Tenten first placed shurikens with prices $4$ and $2$. After this a customer came in and bought the cheapest shuriken which costed $2$. Next, Tenten added a shuriken with price $3$ on the showcase to the already placed...

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

from collections import defaultdict as _defaultdict
import sys as _sys

def main():
    n, = _read_ints()
    events = _read_events(2 * n)
    try:
        result = restore_shurikens_order(events, n)
    except ValueError:
        print("NO")
    else:
        print("YES")
        print(*result)

def _read_events(events_n):
    for i_event in range(events_n):
        event_type, *event_args = _read_line().split(' ')
        if event_type == '+':
            assert len(event_args) == 0
            event = (PLACE_SHURIKEN_ID,)
        else:
            assert event_type == '-'
            assert len(event_args) == 1
            event = (BUY_SHURIKEN_ID, int(event_args[0]))
        yield event

PLACE_SHURIKEN_ID = 0
BUY_SHURIKEN_ID = 1

def restore_shurikens_order(events, shurikens_n):
    result = [None] * shurikens_n

    limits_tree = [0] * (shurikens_n + 1 + 1)
    limits_counter = _defaultdict(int)
    sources_by_limits = [[] for limit in range(shurikens_n+1)]

    next_placement_index = 0

    for event in events:

        if event[0] == PLACE_SHURIKEN_ID:
            limit = 1
            _fenwick_add(limits_tree, limit, 1)
            sources_by_limits[limit].append(next_placement_index)
            limits_counter[limit] += 1
            next_placement_index += 1

        else:
            assert event[0] == BUY_SHURIKEN_ID
            item_to_buy = event[1]
            if _fenwick_prefix_sum(limits_tree, item_to_buy) == 0:
                raise ValueError("unable to restore shurikens order")

            limits_can_be_removed_n = _fenwick_prefix_sum(limits_tree, item_to_buy)

            min_limit_to_remove = 1
            max_limit_to_remove = item_to_buy
            while min_limit_to_remove != max_limit_to_remove:
                mid_limit_to_remove = (min_limit_to_remove + max_limit_to_remove) >> 1
                if limits_can_be_removed_n \
                        - _fenwick_prefix_sum(limits_tree, mid_limit_to_remove) == 0:
                 ...


I found an interesting problem on https://codeforces.com/problemset/problem/1413/E:
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal $a$ instant damage to him, and then heal that enemy $b$ health points at the end of every second, for exactly $c$ seconds, starting one second after the ability is used. That means that if the ability is used at time $t$, the enemy's health decreases by $a$ at time $t$, and then increases by $b$ at time points $t + 1$, $t + 2$, ..., $t + c$ due to this ability.

The ability has a cooldown of $d$ seconds, i. e. if Meka-Naruto uses it at time moment $t$, next time he can use it is the time $t + d$. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.

The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under $k$ spells gets $k\cdot b$ amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.

Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every $d$ seconds). The enemy is killed if their health points become $0$ or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?

-----Input-----

The first line contains an integer $t$ ($1\leq t\leq 10^5$) standing for the number of testcases.

Each test case is described with one line containing four numbers $a$, $b$, $c$ and $d$ ($1\leq a, b, c, d\leq 10^6$) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.

-----Output-----

For each testcase in a separate line print $-1$ if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.

-----Example-----
Input
7
1 1 1 1
2 2 2...

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

import sys

# sys.stdin = open('in.txt')

s = sys.stdin.read().split()
p = 0

def getSm(k, a, b, c, d):
    return (k + 1) * a - (k * (k + 1) >> 1) * b * d

t = int(s[p])
p += 1

res = []

for _ in range(t):
    a = int(s[p])
    p += 1
    b = int(s[p])
    p += 1
    c = int(s[p])
    p += 1
    d = int(s[p])
    p += 1
    if a - b * c > 0:
        res.append(-1)
    elif d >= c:
        res.append(a)
    else:
        dn = 0
        up = int(1e6) + 1
        while up - dn > 1:
            md = (up + dn) >> 1
            if getSm(md, a, b, c, d) < getSm(md + 1, a, b, c, d):
                dn = md
            else:
                up = md
        ans = max(a, getSm(dn, a, b, c, d), getSm(up, a, b, c, d))
        res.append(ans)

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


I found an interesting problem on https://codeforces.com/problemset/problem/1418/D:
Vova decided to clean his room. The room can be represented as the coordinate axis $OX$. There are $n$ piles of trash in the room, coordinate of the $i$-th pile is the integer $p_i$. All piles have different coordinates.

Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $x$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $x$ and move all piles from $x$ to $x+1$ or $x-1$ using his broom. Note that he can't choose how many piles he will move.

Also, there are two types of queries:

  $0$ $x$ — remove a pile of trash from the coordinate $x$. It is guaranteed that there is a pile in the coordinate $x$ at this moment.  $1$ $x$ — add a pile of trash to the coordinate $x$. It is guaranteed that there is no pile in the coordinate $x$ at this moment.

Note that it is possible that there are zero piles of trash in the room at some moment.

Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.

For better understanding, please read the Notes section below to see an explanation for the first example.

-----Input-----

The first line of the input contains two integers $n$ and $q$ ($1 \le n, q \le 10^5$) — the number of piles in the room before all queries and the number of queries, respectively.

The second line of the input contains $n$ distinct integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le 10^9$), where $p_i$ is the coordinate of the $i$-th pile.

The next $q$ lines describe queries. The $i$-th query is described with two integers $t_i$ and $x_i$ ($0 \le t_i \le 1; 1 \le x_i \le 10^9$), where $t_i$ is $0$ if you need to remove a pile from the coordinate...

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

class SortedList:
    def __init__(self, iterable=[], _load=200):
        """Initialize sorted list instance."""
        values = sorted(iterable)
        self._len = _len = len(values)
        self._load = _load
        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
        self._list_lens = [len(_list) for _list in _lists]
        self._mins = [_list[0] for _list in _lists]
        self._fen_tree = []
        self._rebuild = True

    def _fen_build(self):
        """Build a fenwick tree instance."""
        self._fen_tree[:] = self._list_lens
        _fen_tree = self._fen_tree
        for i in range(len(_fen_tree)):
            if i | i + 1 < len(_fen_tree):
                _fen_tree[i | i + 1] += _fen_tree[i]
        self._rebuild = False

    def _fen_update(self, index, value):
        """Update `fen_tree[index] += value`."""
        if not self._rebuild:
            _fen_tree = self._fen_tree
            while index < len(_fen_tree):
                _fen_tree[index] += value
                index |= index + 1

    def _fen_query(self, end):
        """Return `sum(_fen_tree[:end])`."""
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        x = 0
        while end:
            x += _fen_tree[end - 1]
            end &= end - 1
        return x

    def _fen_findkth(self, k):
        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
        _list_lens = self._list_lens
        if k < _list_lens[0]:
            return 0, k
        if k >= self._len - _list_lens[-1]:
            return len(_list_lens) - 1, k + _list_lens[-1] - self._len
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        idx = -1
        for d in reversed(list(range(len(_fen_tree).bit_length()))):
            right_idx = idx + (1 << d)
            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
                idx = right_idx
                k -=...


I found an interesting problem on https://codeforces.com/problemset/problem/1418/E:
You are playing a computer game. In this game, you have to fight $n$ monsters.

To defend from monsters, you need a shield. Each shield has two parameters: its current durability $a$ and its defence rating $b$. Each monster has only one parameter: its strength $d$.

When you fight a monster with strength $d$ while having a shield with current durability $a$ and defence $b$, there are three possible outcomes:  if $a = 0$, then you receive $d$ damage;  if $a > 0$ and $d \ge b$, you receive no damage, but the current durability of the shield decreases by $1$;  if $a > 0$ and $d < b$, nothing happens.

The $i$-th monster has strength $d_i$, and you will fight each of the monsters exactly once, in some random order (all $n!$ orders are equiprobable). You have to consider $m$ different shields, the $i$-th shield has initial durability $a_i$ and defence rating $b_i$. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given $n$ monsters in random order.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the number of monsters and the number of shields, respectively.

The second line contains $n$ integers $d_1$, $d_2$, ..., $d_n$ ($1 \le d_i \le 10^9$), where $d_i$ is the strength of the $i$-th monster.

Then $m$ lines follow, the $i$-th of them contains two integers $a_i$ and $b_i$ ($1 \le a_i \le n$; $1 \le b_i \le 10^9$) — the description of the $i$-th shield.

-----Output-----

Print $m$ integers, where the $i$-th integer represents the expected damage you receive with the $i$-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction $\dfrac{x}{y}$, where $y$ is coprime with $998244353$. You have to print the value of $x \cdot y^{-1} \bmod 998244353$, where $y^{-1}$ is the inverse element for $y$ ($y \cdot y^{-1} \bmod 998244353 = 1$).

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

Output
665496237
1

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

Output
0
8
665496236

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

import sys,bisect
r=lambda:map(int,sys.stdin.readline().split())
M=998244353
def f(b):return pow(b,M-2,M)
n,m=r()
d=sorted(r())
p=[0]
for v in d:p+=[p[-1]+v]
for _ in range(m):a,b=r();i=bisect.bisect_left(d,b);v=n-i; print([(p[i]*a*f(v+v*v)-p[-1]*(a*f(v)-1))%M,0][a>v])


I found an interesting problem on https://codeforces.com/problemset/problem/1419/A:
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $t$ matches of a digit game...

In each of $t$ matches of the digit game, a positive integer is generated. It consists of $n$ digits. The digits of this integer are numerated from $1$ to $n$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.

Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.

It can be proved, that before the end of the match (for every initial integer with $n$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.

For each of $t$ matches find out, which agent wins, if both of them want to win and play optimally.

-----Input-----

First line of input contains an integer $t$ $(1 \le t \le 100)$  — the number of matches.

The first line of each match description contains an integer $n$ $(1 \le n \le 10^3)$  — the number of digits of the generated number.

The second line of each match description contains an $n$-digit positive integer without leading zeros.

-----Output-----

For each match print $1$, if Raze wins, and $2$, if Breach wins.

-----Example-----
Input
4
1
2
1
3
3
102
4
2069

Output
2
1
1
2

-----Note-----

In the first match no one can make a turn, the only digit left is $2$, it's even, so Breach wins.

In the second match the only digit left is $3$, it's odd, so Raze wins.

In the third match Raze can mark the last digit, after that Breach can only mark $0$. $1$ will be the last digit left, it's odd, so Raze wins.

In the fourth match no matter...

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

def a(l):
    odd = 0
    even = 0
    for x in l:
        if x % 2 == 1:
            odd += 1
        else:
            even += 1
    return (odd, even)

T = int(input())
for _ in range(T):
    n = int(input())
    l = list(map(int, list(input())))
    odds = l[::2]
    evens = l[1::2]
    if n % 2 == 1:
        x,y = a(odds)
        print(1 if x > 0 else 2)
    else:
        x,y = a(evens)
        print(2 if y > 0 else 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1419/C:
A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).

Killjoy's account is already infected and has a rating equal to $x$. Its rating is constant. There are $n$ accounts except hers, numbered from $1$ to $n$. The $i$-th account's initial rating is $a_i$. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.

Contests are regularly held on Codeforces. In each contest, any of these $n$ accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.

Find out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.

It can be proven that all accounts can be infected in some finite number of contests.

-----Input-----

The first line contains a single integer $t$ $(1 \le t \le 100)$ — the number of test cases. The next $2t$ lines contain the descriptions of all test cases.

The first line of each test case contains two integers $n$ and $x$ ($2 \le n \le 10^3$, $-4000 \le x \le 4000$) — the number of accounts on Codeforces and the rating of Killjoy's account.

The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ $(-4000 \le a_i \le 4000)$ — the ratings of other accounts.

-----Output-----

For each test case output the minimal number of contests needed to infect all accounts.

-----Example-----
Input
3
2 69
68 70
6 4
4 4 4 4 4 4
9 38
-21 83 50 -59 -77 15 -71 -78 20

Output
1
0
2

-----Note-----

In the first test case it's possible to make...

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

T = int(input())
for _ in range(T):
    N, X = list(map(int, input().split()))
    A = [int(a) for a in input().split()]
    if A.count(X) == N:
        print(0)
    elif sum(A) == N * X or A.count(X) > 0:
        print(1)
    else:
        print(2)


I found an interesting problem on https://codeforces.com/problemset/problem/1419/D1:
This is the easy version of the problem. The difference between the versions is that in the easy version all prices $a_i$ are different. You can make hacks if and only if you solved both versions of the problem.

Today is Sage's birthday, and she will go shopping to buy ice spheres. All $n$ ice spheres are placed in a row and they are numbered from $1$ to $n$ from left to right. Each ice sphere has a positive integer price. In this version all prices are different.

An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.

You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.

-----Input-----

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

The second line contains $n$ different integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^9)$ — the prices of ice spheres.

-----Output-----

In the first line print the maximum number of ice spheres that Sage can buy.

In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.

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

Output
2
3 1 4 2 5

-----Note-----

In the example it's not possible to place ice spheres in any order so that Sage would buy $3$ of them. If the ice spheres are placed like this $(3, 1, 4, 2, 5)$, then Sage will buy two spheres: one for $1$ and one for $2$, because they are cheap.

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

n = int(input())
u = sorted(list(map(int, input().split())))
print((n - 1) // 2)
ans = []
ind = 0
for i in range((n - 1) // 2, n):
    ans.append(u[i])
    if ind == (n - 1) // 2:
        continue
    ans.append(u[ind])
    ind += 1
print(' '.join(map(str, ans)))


I found an interesting problem on https://codeforces.com/problemset/problem/1419/D2:
This is the hard version of the problem. The difference between the versions is that in the easy version all prices $a_i$ are different. You can make hacks if and only if you solved both versions of the problem.

Today is Sage's birthday, and she will go shopping to buy ice spheres. All $n$ ice spheres are placed in a row and they are numbered from $1$ to $n$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.

An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.

You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^9)$ — the prices of ice spheres.

-----Output-----

In the first line print the maximum number of ice spheres that Sage can buy.

In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.

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

Output
3
3 1 4 2 4 2 5

-----Note-----

In the sample it's not possible to place the ice spheres in any order so that Sage would buy $4$ of them. If the spheres are placed in the order $(3, 1, 4, 2, 4, 2, 5)$, then Sage will buy one sphere for $1$ and two spheres for $2$ each.

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

import sys
input = sys.stdin.readline

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

res = [0] * n
a = sorted(a, reverse=True)
ai = 0

for i in range(0, n, 2):
    res[i] = a[ai]
    ai += 1
if n % 2 == 0:
    res[-1] = a[ai]
    ai += 1
for i in range(1, n - 1, 2):
    res[i] = a[ai]
    ai += 1

ans = 0
for i in range(n):
    if not(i - 1 >= 0 and i + 1 < n):
        continue
    if res[i] < res[i - 1] and res[i] < res[i + 1]:
        ans += 1
print(ans)
print(*res)


I found an interesting problem on https://codeforces.com/problemset/problem/1419/F:
There are $n$ detachments on the surface, numbered from $1$ to $n$, the $i$-th detachment is placed in a point with coordinates $(x_i, y_i)$. All detachments are placed in different points.

Brimstone should visit each detachment at least once. You can choose the detachment where Brimstone starts.

To move from one detachment to another he should first choose one of four directions of movement (up, right, left or down) and then start moving with the constant speed of one unit interval in a second until he comes to a detachment. After he reaches an arbitrary detachment, he can repeat the same process.

Each $t$ seconds an orbital strike covers the whole surface, so at that moment Brimstone should be in a point where some detachment is located. He can stay with any detachment as long as needed.

Brimstone is a good commander, that's why he can create at most one detachment and place it in any empty point with integer coordinates he wants before his trip. Keep in mind that Brimstone will need to visit this detachment, too.

Help Brimstone and find such minimal $t$ that it is possible to check each detachment. If there is no such $t$ report about it.

-----Input-----

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

In each of the next $n$ lines there is a pair of integers $x_i$, $y_i$ $(|x_i|, |y_i| \le 10^9)$ — the coordinates of $i$-th detachment.

It is guaranteed that all points are different.

-----Output-----

Output such minimal integer $t$ that it is possible to check all the detachments adding at most one new detachment.

If there is no such $t$, print $-1$.

-----Examples-----
Input
4
100 0
0 100
-100 0
0 -100

Output
100
Input
7
0 2
1 0
-3 0
0 -2
-1 -1
-1 -3
-2 -3

Output
-1
Input
5
0 0
0 -1
3 0
-2 0
-2 1

Output
2
Input
5
0 0
2 0
0 -1
-2 0
-2 1

Output
2

-----Note-----

In the first test it is possible to place a detachment in $(0, 0)$, so that it is possible to check all the detachments for $t = 100$. It can be proven that it is impossible to check...

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

# import numpy as npy
import functools
import math

n=int(input())
x=[0 for i in range(n+2)]
y=[0 for i in range(n+2)]
adj=[[] for i in range(n+2)]
idx=[]
idy=[]
for i in range(n):
    x[i],y[i]=map(int,input().split())
    idx.append(i)
    idy.append(i)

def cmpx(a,b):
    if x[a]!=x[b]:
        if x[a]<x[b]:
            return -1
        else:
            return 1
    if y[a]!=y[b]:
        if y[a]<y[b]:
            return -1
        else:
            return 1
    return 0

def cmpy(a,b):
    if y[a]!=y[b]:
        if y[a]<y[b]:
            return -1
        else:
            return 1
    if x[a]!=x[b]:
        if x[a]<x[b]:
            return -1
        else:
            return 1
    return 0

idx=sorted(idx,key=functools.cmp_to_key(cmpx))
idy=sorted(idy,key=functools.cmp_to_key(cmpy))

# print(idx)
# print(idy)

def disx(a,b):
    if x[a]!=x[b]:
        return 1e18
    return y[b]-y[a]

def disy(a,b):
    if y[a]!=y[b]:
        return 1e18
    return x[b]-x[a]

l=0
r=2000000000
ans=-1

while l<=r:
    # print(l,r)
    mid=(l+r)//2
    for i in range(n):
        adj[i]=[]
    for i in range(n-1):
        if disx(idx[i],idx[i+1])<=mid:
            adj[idx[i]].append(idx[i+1])
            adj[idx[i+1]].append(idx[i])
            # print(idx[i],idx[i+1])
        if disy(idy[i],idy[i+1])<=mid:
            adj[idy[i]].append(idy[i+1])
            adj[idy[i+1]].append(idy[i])
            # print(idy[i],idy[i+1])
    col=[0 for i in range(n)]
    cur=0
    def dfs(x):
        col[x]=cur
        for i in range(len(adj[x])):
            if col[adj[x][i]]==0:
                dfs(adj[x][i])
    for i in range(n):
        if col[i]==0:
            cur=cur+1
            dfs(i)
    ok=0
    if cur>4:
        ok=0
    if cur==1:
        ok=1
    if cur==2:
        for i in range(n):
            for j in range(i+1,n):
                if (col[i]!=col[j]):
                    d1=abs(x[i]-x[j])
                    d2=abs(y[i]-y[j])
                    if d1==0 or d2==0:
                        if d1+d2<=2*mid:
     ...


I found an interesting problem on https://codeforces.com/problemset/problem/1420/A:
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?

Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it!

Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent — cubes.

For completing the chamber Wheatley needs $n$ cubes. $i$-th cube has a volume $a_i$.

Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each $i>1$, $a_{i-1} \le a_i$ must hold.

To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any $i>1$ you can exchange cubes on positions $i-1$ and $i$.

But there is a problem: Wheatley is very impatient. If Wheatley needs more than $\frac{n \cdot (n-1)}{2}-1$ exchange operations, he won't do this boring work.

Wheatly wants to know: can cubes be sorted under this conditions?

-----Input-----

Each test contains multiple test cases.

The first line contains one positive integer $t$ ($1 \le t \le 1000$), denoting the number of test cases. Description of the test cases follows.

The first line of each test case contains one positive integer $n$ ($2 \le n \le 5 \cdot 10^4$) — number of cubes.

The second line contains $n$ positive integers $a_i$ ($1 \le a_i \le 10^9$) — volumes of cubes.

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.

-----Output-----

For each test case, print a word in a single line: "YES" (without quotation marks) if the cubes can be sorted and "NO" (without quotation marks) otherwise.

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

Output
YES
YES
NO

-----Note-----

In the first test case it is possible to sort all the cubes in $7$ exchanges.

In the second test case the cubes are already sorted.

In the third test case we can make $0$...

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

t=int(input())
for you in range(t):
    n=int(input())
    l=input().split()
    li=[int(i) for i in l]
    poss=1
    for i in range(n-1):
        if(li[i]>li[i+1]):
            continue
        poss=0
        break
    if(poss):
        print("NO")
    else:
        print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1420/B:
"You must lift the dam. With a lever. I will give it to you.

You must block the canal. With a rock. I will not give the rock to you."

Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.

Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.

You are given a positive integer $n$, and an array $a$ of positive integers. The task is to calculate the number of such pairs $(i,j)$ that $i<j$ and $a_i$ $\&$ $a_j \ge a_i \oplus a_j$, where $\&$ denotes the bitwise AND operation, and $\oplus$ denotes the bitwise XOR operation.

Danik has solved this task. But can you solve it?

-----Input-----

Each test contains multiple test cases.

The first line contains one positive integer $t$ ($1 \le t \le 10$) denoting the number of test cases. Description of the test cases follows.

The first line of each test case contains one positive integer $n$ ($1 \le n \le 10^5$) — length of the array.

The second line contains $n$ positive integers $a_i$ ($1 \le a_i \le 10^9$) — elements of the array.

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.

-----Output-----

For every test case print one non-negative integer — the answer to the problem.

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

Output
1
3
2
0
0

-----Note-----

In the first test case there is only one pair: $(4,7)$: for it $4$ $\&$ $7 = 4$, and $4 \oplus 7 = 3$.

In the second test case all pairs are good.

In the third test case there are two pairs: $(6,5)$ and $(2,3)$.

In the fourth test case there are no good pairs.

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

t = int(input())

for _ in range(t):
    n = int(input())

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

    counts = [0] * 32
    for x in a:
        counts[len(bin(x))-2] += 1

    total = 0
    for count in counts:
        total += count * (count-1) // 2
    print(total)


I found an interesting problem on https://codeforces.com/problemset/problem/1420/C2:
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.

Pikachu is a cute and friendly pokémon living in the wild pikachu herd.

But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.

First, Andrew counted all the pokémon — there were exactly $n$ pikachu. The strength of the $i$-th pokémon is equal to $a_i$, and all these numbers are distinct.

As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $b$ from $k$ indices such that $1 \le b_1 < b_2 < \dots < b_k \le n$, and his army will consist of pokémons with forces $a_{b_1}, a_{b_2}, \dots, a_{b_k}$.

The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$.

Andrew is experimenting with pokémon order. He performs $q$ operations. In $i$-th operation Andrew swaps $l_i$-th and $r_i$-th pokémon.

Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.

Help Andrew and the pokémon, or team R will realize their tricky plan!

-----Input-----

Each test contains multiple test cases.

The first line contains one positive integer $t$ ($1 \le t \le 10^3$) denoting the number of test cases. Description of the test cases follows.

The first line of each test case contains two integers $n$ and $q$ ($1 \le n \le 3 \cdot 10^5, 0 \le q \le 3 \cdot 10^5$) denoting the number of pokémon and number of operations respectively.

The second line contains $n$ distinct positive integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) denoting the strengths of the pokémon.

$i$-th of the last $q$ lines contains two positive integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le n$)...

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

from sys import stdin

tt = int(stdin.readline())
pls = []

for loop in range(tt):

    n,q = list(map(int,stdin.readline().split()))
    a   = list(map(int,stdin.readline().split()))
    a = [0] + a + [0]

    lis = [0] * len(a)

    ans = 0
    for i in range(1,len(a)-1):
        if a[i-1] < a[i] and a[i] > a[i+1]:
            lis[i] = 1
            ans += a[i]
        elif a[i-1] > a[i] and a[i] < a[i+1]:
            lis[i] = -1
            ans -= a[i]

    pls.append(ans)

    for loop in range(q):

        l,r = list(map(int,stdin.readline().split()))
        if l == r:
            pls.append(ans)
            continue
        ch = {}
        ch[l-1] = 0
        ch[l] = 0
        ch[l+1] = 0
        ch[r-1] = 0
        ch[r] = 0
        ch[r+1] = 0

        for i in ch:
            ans -= a[i] * lis[i]

        a[l],a[r] = a[r],a[l]

        for i in ch:
            if i == 0 or i == len(a)-1:
                pass
            elif a[i-1] < a[i] and a[i] > a[i+1]:
                lis[i] = 1
                ans += a[i]
            elif a[i-1] > a[i] and a[i] < a[i+1]:
                lis[i] = -1
                ans -= a[i]
            else:
                lis[i] = 0
        pls.append(ans)

print("\n".join(map(str,pls)))


I found an interesting problem on https://codeforces.com/problemset/problem/1420/D:
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened.

Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door.

There are $n$ lamps with Spirit Tree's light. Sein knows the time of turning on and off for the $i$-th lamp — $l_i$ and $r_i$ respectively. To open the door you have to choose $k$ lamps in such a way that there will be a moment of time when they all will be turned on.

While Sein decides which of the $k$ lamps to pick, Ori is interested: how many ways there are to pick such $k$ lamps that the door will open? It may happen that Sein may be wrong and there are no such $k$ lamps. The answer might be large, so print it modulo $998\,244\,353$.

-----Input-----

First line contains two integers $n$ and $k$ ($1 \le n \le 3 \cdot 10^5$, $1 \le k \le n$) — total number of lamps and the number of lamps that must be turned on simultaneously.

Next $n$ lines contain two integers $l_i$ ans $r_i$ ($1 \le l_i \le r_i \le 10^9$) — period of time when $i$-th lamp is turned on.

-----Output-----

Print one integer — the answer to the task modulo $998\,244\,353$.

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

Output
9
Input
3 1
1 1
2 2
3 3

Output
3
Input
3 2
1 1
2 2
3 3

Output
0
Input
3 3
1 3
2 3
3 3

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

Output
7

-----Note-----

In first test case there are nine sets of $k$ lamps: $(1, 2, 3)$, $(1, 2, 4)$, $(1, 2, 5)$, $(1, 2, 6)$, $(1, 3, 6)$, $(1, 4, 6)$, $(2, 3, 6)$, $(2, 4, 6)$, $(2, 6, 7)$.

In second test case $k=1$, so the answer is 3.

In third test case there are no such pairs of lamps.

In forth test case all lamps are turned on in a time $3$, so the answer is 1.

In fifth test case there are seven sets of $k$ lamps: $(1, 2)$, $(1, 3)$, $(2, 3)$, $(2, 4)$, $(3, 4)$, $(3, 5)$, $(4, 5)$.

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

import sys
input = sys.stdin.readline

MOD = 998_244_353
N = 3 * 10 ** 5 + 10

fact = [0 for _ in range(N)]
invfact = [0 for _ in range(N)]
fact[0] = 1
for i in range(1, N):
    fact[i] = fact[i - 1] * i % MOD

invfact[N - 1] = pow(fact[N - 1], MOD - 2, MOD)

for i in range(N - 2, -1, -1):
    invfact[i] = invfact[i + 1] * (i + 1) % MOD
def nCk(n, k):
    if k < 0 or n < k:
        return 0
    else:
        return fact[n] * invfact[k] * invfact[n - k] % MOD

def main():
    n, k = map(int, input().split())
    l_s = []
    r_s = []
    for _ in range(n):
        l, r = map(int, input().split())
        l_s.append(l)
        r_s.append(r)
    l_s.sort()
    r_s.sort()
    l_pos = 0
    r_pos = 0
    total = 0
    ans = 0
    while 1:
        if l_s[l_pos] <= r_s[r_pos]:
            total += 1
            l_pos += 1
            if total >= k:
                ans += nCk(total - 1, k - 1)
                ans %= MOD
            if l_pos == n:
                break
        else:
            total -= 1
            r_pos += 1

    print(ans)

"""
for _ in range(int(input())):
    main()
"""
main()


I found an interesting problem on https://codeforces.com/problemset/problem/1420/E:
A lighthouse keeper Peter commands an army of $n$ battle lemmings. He ordered his army to stand in a line and numbered the lemmings from $1$ to $n$ from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield.

The more protected Peter's army is, the better. To calculate the protection of the army, he finds the number of protected pairs of lemmings, that is such pairs that both lemmings in the pair don't hold a shield, but there is a lemming with a shield between them.

Now it's time to prepare for defence and increase the protection of the army. To do this, Peter can give orders. He chooses a lemming with a shield and gives him one of the two orders:   give the shield to the left neighbor if it exists and doesn't have a shield;  give the shield to the right neighbor if it exists and doesn't have a shield.

In one second Peter can give exactly one order.

It's not clear how much time Peter has before the defence. So he decided to determine the maximal value of army protection for each $k$ from $0$ to $\frac{n(n-1)}2$, if he gives no more that $k$ orders. Help Peter to calculate it!

-----Input-----

First line contains a single integer $n$ ($1 \le n \le 80$), the number of lemmings in Peter's army.

Second line contains $n$ integers $a_i$ ($0 \le a_i \le 1$). If $a_i = 1$, then the $i$-th lemming has a shield, otherwise $a_i = 0$.

-----Output-----

Print $\frac{n(n-1)}2 + 1$ numbers, the greatest possible protection after no more than $0, 1, \dots, \frac{n(n-1)}2$ orders.

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

Output
0 2 3 3 3 3 3 3 3 3 3

Input
12
0 0 0 0 1 1 1 1 0 1 1 0

Output
9 12 13 14 14 14 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15

-----Note-----

Consider the first example.

The protection is initially equal to zero, because for each pair of lemmings without shields there is no lemmings with shield.

In one second...

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

# import numpy as npy
# idx=sorted(idx,key=functools.cmp_to_key(cmpx))
import bisect
import array
import functools
import math

n=int(input())
a=array.array('i',map(int,input().split()))
s=0
q=[]
q.append(0)
for i in range(n):
    if a[i]==1:
        q.append(i+1)
        s=s+1
q.append(n+1)
m=n*(n-1)//2
f=[[10000000 for i in range(82)] for i in range(3500)]
f[0][0]=0
for i in range(1,s+2):
    rlim=n+1-(s+1-i)
    g=[[10000000 for i in range(82)] for i in range(3500)]
    for j in range(i-1,rlim+1):
        for S in range(m+1):
            if (f[S][j]<1000000):
                for k in range(j+1,rlim+1):
                    nv=f[S][j]+(k-j-1)*(k-j-2)//2
                    nS=S+abs(k-q[i])
                    g[nS][k]=min(g[nS][k],nv)
    f=g
mn=0
for i in range(m+1):
    mn=max(mn,(n-s)*(n-s-1)//2-f[i][n+1])
    print(mn,end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/1421/B:
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.

Roger Waters has a square grid of size $n\times n$ and he wants to traverse his grid from the upper left ($1,1$) corner to the lower right corner ($n,n$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($1,1$) and ($n,n$) every cell has a value $0$ or $1$ in it.

Before starting his traversal he will pick either a $0$ or a $1$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($1,1$) and ($n,n$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($1,1$) takes value the letter 'S' and the cell ($n,n$) takes value the letter 'F'.

For example, in the first example test case, he can go from ($1, 1$) to ($n, n$) by using the zeroes on this path: ($1, 1$), ($2, 1$), ($2, 2$), ($2, 3$), ($3, 3$), ($3, 4$), ($4, 4$)

The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $0$ to $1$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells.  Note that you cannot invert cells $(1, 1)$ and $(n, n)$.

We can show that there always exists a solution for the given constraints.

Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($n,n$) no matter what digit he picks.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 50$). Description of the test cases follows.

The first line of each test case contains one integers $n$ ($3 \le n \le 200$).

The following $n$ lines of each test case contain the binary grid, square ($1, 1$)...

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/1421/C:
Ringo found a string $s$ of length $n$ in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string $s$ into a palindrome by applying two types of operations to the string.

The first operation allows him to choose $i$ ($2 \le i \le n-1$) and to append the substring $s_2s_3 \ldots s_i$ ($i - 1$ characters) reversed to the front of $s$.

The second operation allows him to choose $i$ ($2 \le i \le n-1$) and to append the substring $s_i s_{i + 1}\ldots s_{n - 1}$ ($n - i$ characters) reversed to the end of $s$.

Note that characters in the string in this problem are indexed from $1$.

For example suppose $s=$abcdef. If he performs the first operation with $i=3$ then he appends cb to the front of $s$ and the result will be cbabcdef. Performing the second operation on the resulted string with $i=5$ will yield cbabcdefedc.

Your task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) at most $30$ times. The length of the resulting palindrome must not exceed $10^6$

It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.

-----Input-----

The only line contains the string $S$ ($3 \le |s| \le 10^5$) of lowercase letters from the English alphabet.

-----Output-----

The first line should contain $k$ ($0\le k \le 30$)  — the number of operations performed.

Each of the following $k$ lines should describe an operation in form L i or R i. $L$ represents the first operation, $R$ represents the second operation, $i$ represents the index chosen.

The length of the resulting palindrome must not exceed $10^6$.

-----Examples-----
Input
abac

Output
2
R 2
R 5

Input
acccc

Output
2
L 4
L 2

Input
hannah

Output
0

-----Note-----

For the first example the following operations are...

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

n = len(input())
print(3)
print("R", n-1)
print("L", n)
print("L", 2)


I found an interesting problem on https://codeforces.com/problemset/problem/1421/D:
Lindsey Buckingham told Stevie Nicks "Go your own way". Nicks is now sad and wants to go away as quickly as possible, but she lives in a 2D hexagonal world.

Consider a hexagonal tiling of the plane as on the picture below. [Image]

Nicks wishes to go from the cell marked $(0, 0)$ to a certain cell given by the coordinates. She may go from a hexagon to any of its six neighbors you want, but there is a cost associated with each of them. The costs depend only on the direction in which you travel. Going from $(0, 0)$ to $(1, 1)$ will take the exact same cost as going from $(-2, -1)$ to $(-1, 0)$. The costs are given in the input in the order $c_1$, $c_2$, $c_3$, $c_4$, $c_5$, $c_6$ as in the picture below. [Image]

Print the smallest cost of a path from the origin which has coordinates $(0, 0)$ to the given cell.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^{4}$). Description of the test cases follows.

The first line of each test case contains two integers $x$ and $y$ ($-10^{9} \le x, y \le 10^{9}$) representing the coordinates of the target hexagon.

The second line of each test case contains six integers $c_1$, $c_2$, $c_3$, $c_4$, $c_5$, $c_6$ ($1 \le c_1, c_2, c_3, c_4, c_5, c_6 \le 10^{9}$) representing the six costs of the making one step in a particular direction (refer to the picture above to see which edge is for each value).

-----Output-----

For each testcase output the smallest cost of a path from the origin to the given cell.

-----Example-----
Input
2
-3 1
1 3 5 7 9 11
1000000000 1000000000
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Output
18
1000000000000000000

-----Note-----

The picture below shows the solution for the first sample. The cost $18$ is reached by taking $c_3$ 3 times and $c_2$ once, amounting to $5+5+5+3=18$. [Image]

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

import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod=10**9+7

for t in range(int(data())):
    y,x=mdata()
    c=mdata()
    if x>=0 and y>=0:
        out(min(c[1]*x+c[5]*y,c[0]*min(x,y)+c[1]*(x-min(x,y))+c[5]*(y-min(x,y)),c[0]*max(x,y)+c[4]*(max(x,y)-x)+c[2]*(max(x,y)-y)))
    elif x>0 and y<0:
        y=abs(y)
        out(min(c[1] * x + c[2] * y,c[0]*x+c[2]*(x+y),c[3]*y+c[1]*(x+y)))
    elif x<0 and y>0:
        x=abs(x)
        out(min(c[4] * x + c[5] * y,c[3]*x+c[5]*(x+y),c[0]*y+c[4]*(x+y)))
    else:
        x=abs(x)
        y=abs(y)
        out(min(c[4] * x + c[2] * y, c[3] * min(x, y) + c[4] * (x - min(x, y)) + c[2] * (y - min(x, y)),
                c[3] * max(x, y) + c[1] * (max(x, y) - x) + c[5] * (max(x, y) - y)))


I found an interesting problem on https://codeforces.com/problemset/problem/1421/E:
While playing yet another strategy game, Mans has recruited $n$ Swedish heroes, whose powers which can be represented as an array $a$.

Unfortunately, not all of those mighty heroes were created as capable as he wanted, so that he decided to do something about it. In order to accomplish his goal, he can pick two consecutive heroes, with powers $a_i$ and $a_{i+1}$, remove them and insert a hero with power $-(a_i+a_{i+1})$ back in the same position.

For example if the array contains the elements $[5, 6, 7, 8]$, he can pick $6$ and $7$ and get $[5, -(6+7), 8] = [5, -13, 8]$.

After he will perform this operation $n-1$ times, Mans will end up having only one hero. He wants his power to be as big as possible. What's the largest possible power he can achieve?

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 200000$).

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

-----Output-----

Print the largest possible power he can achieve after $n-1$ operations.

-----Examples-----
Input
4
5 6 7 8

Output
26

Input
5
4 -5 9 -2 1

Output
15

-----Note-----

Suitable list of operations for the first sample:

$[5, 6, 7, 8] \rightarrow [-11, 7, 8] \rightarrow [-11, -15] \rightarrow [26]$

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

from heapq import nsmallest
from math import inf as _inf
import sys as _sys

def main():
    n, = _read_ints()
    a = tuple(_read_ints())
    result = find_max_power_can_make(a)
    print(result)

def _read_line():
    result = _sys.stdin.readline()
    assert result[-1] == "\n"
    return result[:-1]

def _read_ints():
    return list(map(int, _read_line().split()))

def find_max_power_can_make(heroes_powers):
    heroes_powers = tuple(heroes_powers)
    assert heroes_powers

    abs_powers_sum = sum(map(abs, heroes_powers))

    if len(heroes_powers) <= 9:
        return _compute_using_brute_force(heroes_powers)

    zeros_n = heroes_powers.count(0)
    if zeros_n >= 2:
        return abs_powers_sum
    assert zeros_n <= 1

    n = len(heroes_powers)
    if n % 3 == 1 % 3:
        can_invert_mod_3 = 0
    elif n % 3 == 2 % 3:
        can_invert_mod_3 = 2
    else:
        assert n % 3 == 3 % 3
        can_invert_mod_3 = 1

    result = -_inf

    for is_zero_positive in (False, True):

        if zeros_n == 0 or is_zero_positive:
            signs = [1 if x >= 0 else -1 for x in heroes_powers]
        else:
            signs = [1 if x > 0 else -1 for x in heroes_powers]

        negative_n = signs.count(-1)
        have_pair_of_same = any(signs[i] == signs[i + 1] for i in range(len(signs) - 1))
        is_trivial = not (not have_pair_of_same and negative_n % 3 == can_invert_mod_3)

        if is_trivial:
            if negative_n % 3 == can_invert_mod_3:
                result = max(result, abs_powers_sum)
                continue
            negative_to_inverse_1 = negative_n
            while negative_to_inverse_1 % 3 != can_invert_mod_3:
                negative_to_inverse_1 -= 1
            negative_to_inverse_2 = negative_to_inverse_1 + 3
        else:
            negative_to_inverse_1 = negative_n - 3
            negative_to_inverse_2 = negative_n + 3
            min_pos = max(
                heroes_powers,
                key=lambda x: (x >= 0 if...


I found an interesting problem on https://codeforces.com/problemset/problem/1422/A:
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $a$, $b$, and $c$. Now he needs to find out some possible integer length $d$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $a$, $b$, $c$, and $d$. Help Yura, find any possible length of the fourth side.

A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.

-----Input-----

The first line contains a single integer $t$ — the number of test cases ($1 \le t \le 1000$). The next $t$ lines describe the test cases.

Each line contains three integers $a$, $b$, and $c$ — the lengths of the three fence segments ($1 \le a, b, c \le 10^9$).

-----Output-----

For each test case print a single integer $d$ — the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.

-----Example-----
Input
2
1 2 3
12 34 56

Output
4
42

-----Note-----

We can build a quadrilateral with sides $1$, $2$, $3$, $4$.

We can build a quadrilateral with sides $12$, $34$, $56$, $42$.

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

import sys
input = sys.stdin.readline
def print(val):
    sys.stdout.write(str(val) + '\n')
def prog():
    for _ in range(int(input())):
        a = list(map(int,input().split()))
        print(sum(a) - 1)
prog()


I found an interesting problem on https://codeforces.com/problemset/problem/1422/B:
A matrix of size $n \times m$ is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers $(a_1, a_2, \dots , a_k)$ is a palindrome, if for any integer $i$ ($1 \le i \le k$) the equality $a_i = a_{k - i + 1}$ holds.

Sasha owns a matrix $a$ of size $n \times m$. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.

Help him!

-----Input-----

The first line contains a single integer $t$ — the number of test cases ($1 \le t \le 10$). The $t$ tests follow.

The first line of each test contains two integers $n$ and $m$ ($1 \le n, m \le 100$) — the size of the matrix.

Each of the next $n$ lines contains $m$ integers $a_{i, j}$ ($0 \le a_{i, j} \le 10^9$) — the elements of the matrix.

-----Output-----

For each test output the smallest number of operations required to make the matrix nice.

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

Output
8
42

-----Note-----

In the first test case we can, for example, obtain the following nice matrix in $8$ operations:

2 2

4 4

4 4

2 2

In the second test case we can, for example, obtain the following nice matrix in $42$ operations:

5 6 6 5

6 6 6 6

5 6 6 5

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

import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict

# available on Google, not available on Codeforces
# import numpy as np
# import scipy

def solve(grid, h, w):  # fix inputs here
    console("----- solving ------")
    console(grid)

    lst = []

    for i,row in enumerate(grid):
        for j,cell in enumerate(row):
            lst.append([
                grid[h-i-1][w-j-1],
                grid[h-i-1][j],
                grid[i][w-j-1],
                grid[i][j],
            ])

    res = 0
    for vals in lst:
        vals = sorted(vals)
        median = (vals[1] + vals[2]) // 2
        for v in vals:
            res += abs(v-median)
    # return a string (i.e. not a list or matrix)
    return res//4

def console(*args):  # the judge will not read these print statement
    # print('\033[36m', *args, '\033[0m', file=sys.stderr)
    return

# fast read all
# sys.stdin.readlines()

for case_num in range(int(input())):
    # read line as a string
    # strr = input()

    # read line as an integer
    # k = int(input())

    # read one line and parse each word as a string
    # lst = input().split()

    # read one line and parse each word as an integer
    nrows, w = list(map(int,input().split()))

    # read matrix and parse as integers (after reading read nrows)
    # lst = list(map(int,input().split()))
    # nrows = lst[0]  # index containing information, please change
    grid = []
    for _ in range(nrows):
        grid.append(list(map(int,input().split())))

    res = solve(grid, h=nrows, w=w)  # please change

    # Google - case number required
    # print("Case #{}: {}".format(case_num+1, res))

    # Codeforces - no case number required
    print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1422/C:
Sometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price $n$, Vova removes a non-empty substring of (consecutive) digits from the price, the remaining digits close the gap, and the resulting integer is the price.

For example, is Sasha names $1213121$, Vova can remove the substring $1312$, and the result is $121$.

It is allowed for result to contain leading zeros. If Vova removes all digits, the price is considered to be $0$.

Sasha wants to come up with some constraints so that Vova can't just remove all digits, but he needs some arguments supporting the constraints. To start with, he wants to compute the sum of all possible resulting prices after Vova's move.

Help Sasha to compute this sum. Since the answer can be very large, print it modulo $10^9 + 7$.

-----Input-----

The first and only line contains a single integer $n$ ($1 \le n < 10^{10^5}$).

-----Output-----

In the only line print the required sum modulo $10^9 + 7$.

-----Examples-----
Input
107

Output
42

Input
100500100500

Output
428101984

-----Note-----

Consider the first example.

Vova can choose to remove $1$, $0$, $7$, $10$, $07$, or $107$. The results are $07$, $17$, $10$, $7$, $1$, $0$. Their sum is $42$.

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

s = [int(c) for c in input()][::-1]
n = len(s)

mod = 1000000007
def inv(x):
    return pow(x, mod - 2, mod)
teninv = inv(10)

P = [0]
p = 1
for x in s:
    P.append((P[-1] + x*p) % mod)
    p = p*10 % mod

Q = [0]
for i in range(n+1):
    Q.append((Q[-1] + P[i]*pow(teninv, i, mod))%mod)

s = 0
for l in range(n):
    first = P[l] - P[0]
    s += (n - l)*first % mod
    s += P[n] * inv(9) % mod * (1 - inv(pow(10, n-l, mod))) % mod
    d = Q[n+1] - Q[l+1]

    s = (s - d*inv(pow(teninv,l,mod))%mod) % mod
print(s%mod)


I found an interesting problem on https://codeforces.com/problemset/problem/1422/D:
Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.

Let's represent the city as an area of $n \times n$ square blocks. Yura needs to move from the block with coordinates $(s_x,s_y)$ to the block with coordinates $(f_x,f_y)$. In one minute Yura can move to any neighboring by side block; in other words, he can move in four directions. Also, there are $m$ instant-movement locations in the city. Their coordinates are known to you and Yura. Yura can move to an instant-movement location in no time if he is located in a block with the same coordinate $x$ or with the same coordinate $y$ as the location.

Help Yura to find the smallest time needed to get home.

-----Input-----

The first line contains two integers $n$ and $m$ — the size of the city and the number of instant-movement locations ($1 \le n \le 10^9$, $0 \le m \le 10^5$).

The next line contains four integers $s_x$ $s_y$ $f_x$ $f_y$ — the coordinates of Yura's initial position and the coordinates of his home ($ 1 \le s_x, s_y, f_x, f_y \le n$).

Each of the next $m$ lines contains two integers $x_i$ $y_i$ — coordinates of the $i$-th instant-movement location ($1 \le x_i, y_i \le n$).

-----Output-----

In the only line print the minimum time required to get home.

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

Output
5

Input
84 5
67 59 41 2
39 56
7 2
15 3
74 18
22 7

Output
42

-----Note-----

In the first example Yura needs to reach $(5, 5)$ from $(1, 1)$. He can do that in $5$ minutes by first using the second instant-movement location (because its $y$ coordinate is equal to Yura's $y$ coordinate), and then walking $(4, 1) \to (4, 2) \to (4, 3) \to (5, 3) \to (5, 4) \to (5, 5)$.

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

import sys, io, os
import math
import heapq as hq
import random
from collections import defaultdict

# available on Google, not available on Codeforces
# import numpy as np
# import scipy

import sys
from os import path

def console(*args):  # the judge will not read these print statement
    # print('\033[36m', *args, '\033[0m', file=sys.stderr)
    pass

# if Codeforces environment
if path.exists('input.txt'):
    sys.stdin = open("input.txt","r")
    sys.stdout = open("output.txt","w")

    def console(*args):
        pass

inp = sys.stdin.readlines()
# inp = io.BytesIO(os.read(0,os.fstat(0).st_size)).readlines()

def solve(*args):
    console("----- solving ------")
    console(*args)
    console("----- ------- ------")
    return solve_(*args)

def solve_(grid,sx,sy,ex,ey):  # fix inputs here
    console("----- solving ------")
    # console(grid,sx,sy,ex,ey)

    minres = abs(sx-ex) + abs(sy-ey)
    console(minres)
    if grid == []:
        return minres

    d = defaultdict(list)
    grid = [(i,x,y) for i,(x,y) in enumerate(grid)]

    # x-order
    grid = sorted(grid, key=lambda x: x[1])
    for (i1,x1,y1),(i2,x2,y2) in zip(grid, grid[1:]):
        d[i1].append((i2,x2-x1))
        d[i2].append((i1,x2-x1))

    grid = sorted(grid, key=lambda x: x[2])
    for (i1,x1,y1),(i2,x2,y2) in zip(grid, grid[1:]):
        d[i1].append((i2,y2-y1))
        d[i2].append((i1,y2-y1))

    for i,x,y in grid:
        # start to x-axis
        d[-2].append((i,abs(x-sx)))

        # start to y-axis
        d[-2].append((i,abs(y-sy)))

        # point to destination
        d[i].append((-1, abs(x-ex) + abs(y-ey)))

    d[-1] = []
    console(list(d.keys()))

    idxs = {k:i for i,k in enumerate(d.keys())}
    G = [[] for _ in range(len(idxs))]

    for e,vrr in list(d.items()):
        for v,cost in vrr:
            G[idxs[e]].append((idxs[v],cost))

    return min(minres, dijkstra_with_preprocessing(d, -2, -1))

def dijkstra_with_preprocessing(map_from_node_to_nodes_and_costs, source, target):
    d =...


I found an interesting problem on https://codeforces.com/problemset/problem/1422/E:
Some time ago Lesha found an entertaining string $s$ consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows.

Lesha chooses an arbitrary (possibly zero) number of pairs on positions $(i, i + 1)$ in such a way that the following conditions are satisfied:   for each pair $(i, i + 1)$ the inequality $0 \le i < |s| - 1$ holds;  for each pair $(i, i + 1)$ the equality $s_i = s_{i + 1}$ holds;  there is no index that is contained in more than one pair.  After that Lesha removes all characters on indexes contained in these pairs and the algorithm is over.

Lesha is interested in the lexicographically smallest strings he can obtain by applying the algorithm to the suffixes of the given string.

-----Input-----

The only line contains the string $s$ ($1 \le |s| \le 10^5$) — the initial string consisting of lowercase English letters only.

-----Output-----

In $|s|$ lines print the lengths of the answers and the answers themselves, starting with the answer for the longest suffix. The output can be large, so, when some answer is longer than $10$ characters, instead print the first $5$ characters, then "...", then the last $2$ characters of the answer.

-----Examples-----
Input
abcdd

Output
3 abc
2 bc
1 c
0
1 d

Input
abbcdddeaaffdfouurtytwoo

Output
18 abbcd...tw
17 bbcdd...tw
16 bcddd...tw
15 cddde...tw
14 dddea...tw
13 ddeaa...tw
12 deaad...tw
11 eaadf...tw
10 aadfortytw
9 adfortytw
8 dfortytw
9 fdfortytw
8 dfortytw
7 fortytw
6 ortytw
5 rtytw
6 urtytw
5 rtytw
4 tytw
3 ytw
2 tw
1 w
0
1 o

-----Note-----

Consider the first example.

  The longest suffix is the whole string "abcdd". Choosing one pair $(4, 5)$, Lesha obtains "abc".  The next longest suffix is "bcdd". Choosing one pair $(3, 4)$, we obtain "bc".  The next longest suffix is "cdd". Choosing one pair $(2, 3)$, we obtain "c".  The next longest suffix is "dd". Choosing one pair $(1, 2)$, we obtain "" (an empty string).  The last suffix is the string...

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

s = input()
n = len(s)
res = ['',s[-1]]
l = [1]
flag = True
last = ['']
for i in range(n-2,-1,-1):
    tmp = res[-1]
    if flag and s[i]==tmp[0] and s[i]>last[-1]:
        res.append(res[-2])
        l.append(l[-1]-1)
        flag = False
        if l[-1]>0 and res[-1][0]!=s[i]:
            last.pop()
    else:
        l.append(l[-1]+1)
        tmp = s[i]+tmp
        flag = True
        if len(tmp)>10:
            res.append(tmp[:5]+'...'+tmp[-2:])
        else:
            res.append(tmp)
        if len(res[-1])>1 and res[-1][0]!=res[-1][1]:
            last.append(res[-1][1])
res.pop(0)
for i in range(n-1,-1,-1):
    print(l[i],res[i])


I found an interesting problem on https://codeforces.com/problemset/problem/1424/G:
During one of the space missions, humans have found an evidence of previous life at one of the planets. They were lucky enough to find a book with birth and death years of each individual that had been living at this planet. What's interesting is that these years are in the range $(1, 10^9)$! Therefore, the planet was named Longlifer.

In order to learn more about Longlifer's previous population, scientists need to determine the year with maximum number of individuals that were alive, as well as the number of alive individuals in that year. Your task is to help scientists solve this problem!

-----Input-----

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

Each of the following $n$ lines contain two integers $b$ and $d$ ($1 \le b \lt d \le 10^9$) representing birth and death year (respectively) of each individual.

-----Output-----

Print two integer numbers separated by blank character, $y$  — the year with a maximum number of people alive and $k$  — the number of people alive in year $y$.

In the case of multiple possible solutions, print the solution with minimum year.

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

Output
2 2

Input
4
3 4
4 5
4 6
8 10

Output
4 2

-----Note-----

You can assume that an individual living from $b$ to $d$ has been born at the beginning of $b$ and died at the beginning of $d$, and therefore living for $d$ - $b$ years.

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

from sys import stdin

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

n = int(input())
birth_arr = []
death_arr = []
for i in range(n):
    b, d = list(map(int, input().split()))
    birth_arr.append(b)
    death_arr.append(d)

birth_arr = sorted(birth_arr)
death_arr = sorted(death_arr)

num_ppl = len(birth_arr)
curr = 0
curr_year = 0
max_year = None
max_ppl = 0
b_pointer = 0
d_pointer = 0

while b_pointer < num_ppl:
    if birth_arr[b_pointer] < death_arr[d_pointer]:
        curr += 1
        curr_year = birth_arr[b_pointer]
        if curr > max_ppl:
            max_year = curr_year
            max_ppl = curr
        b_pointer += 1
    elif birth_arr[b_pointer] == death_arr[d_pointer]:
        curr_year = birth_arr[b_pointer]
        b_pointer += 1
        d_pointer += 1
    else:
        curr -= 1
        curr_year = death_arr[d_pointer]
        d_pointer += 1

print(f"{max_year} {max_ppl}")


I found an interesting problem on https://codeforces.com/problemset/problem/1424/M:
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.

After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.

Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.

-----Input-----

First-line contains two integers: $n$ and $k$ ($1 \le n, k \le 10^3$) — the number of pages that scientists have found and the number of words present at each page. Following $n$ groups contain a line with a single integer $p_i$ ($0 \le n \lt 10^3$) — the number of $i$-th page, as well as $k$ lines, each line containing one of the strings (up to $100$ characters) written on the page numbered $p_i$.

-----Output-----

Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.

-----Example-----
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb

Output
acb

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

from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import defaultdict
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readline

M = mod = 10**9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]

graph = defaultdict(set)

n, k = li()
l = []
allwords = set()
for i in range(n):
    p = val()
    l1 = []
    for j in range(k):l1.append(st())

    allwords |= set(l1[-1])
    l.append([p, l1[:]])

l.sort(key = lambda x:x[0])
l = [i[1] for i in l]
if n == k == 1:
    print(''.join(set(l[0][0])))
    return

ingraph = defaultdict(int)

def match(a, b):
    for j in range(min(len(a), len(b))):
        if a[j] == b[j]:continue
        elif b[j] in graph[a[j]]:return
        else:
            graph[a[j]].add(b[j])
            ingraph[b[j]] += 1
            return
    if len(a) > len(b):
        print('IMPOSSIBLE')
        return

finl = []
for i in l:finl.extend(i)
l = finl

# for i in l:print(i)

for i in range(1, len(l)):
    match(l[i - 1], l[i])

# print(graph)
# print(ingraph)

if min([ingraph[j] for j in graph]) != 0:
    print('IMPOSSIBLE')
    return

ans = ''

d = deque()

for j in graph:
    if ingraph[j] == 0:
        d.append(j)

while d:
    node = d.popleft()
    ans += node

    for j in graph[node]:
        ingraph[j] -= 1
        if not ingraph[j]:d.append(j)

if len(ans) != len(allwords):
    print('IMPOSSIBLE')
    return
print(ans)