I found an interesting problem on https://codeforces.com/problemset/problem/1272/A:
Three friends are going to meet each other. Initially, the first friend stays at the position $x = a$, the second friend stays at the position $x = b$ and the third friend stays at the position $x = c$ on the coordinate axis $Ox$.

In one minute each friend independently from other friends can change the position $x$ by $1$ to the left or by $1$ to the right (i.e. set $x := x - 1$ or $x := x + 1$) or even don't change it.

Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let $a'$, $b'$ and $c'$ be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is $|a' - b'| + |a' - c'| + |b' - c'|$, where $|x|$ is the absolute value of $x$.

Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.

You have to answer $q$ independent test cases.

-----Input-----

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

The next $q$ lines describe test cases. The $i$-th test case is given as three integers $a, b$ and $c$ ($1 \le a, b, c \le 10^9$) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.

-----Output-----

For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.

-----Example-----
Input
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6

Output
0
36
0
0
1999999994
1999999994
2
4

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

test = int(input())
for _ in range(test):
    ans = 10**10
    a,b,c = map(int,input().split())
    for i in range(-1,2):
        for j in range(-1,2):
            for k in range(-1,2):
                ta = a+i
                tb = b+j
                tc = c+k
                ans = min(ans,abs(ta-tb)+abs(tb-tc)+abs(ta-tc))
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1272/C:
Recently, Norge found a string $s = s_1 s_2 \ldots s_n$ consisting of $n$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $s$. Yes, all $\frac{n (n + 1)}{2}$ of them!

A substring of $s$ is a non-empty string $x = s[a \ldots b] = s_{a} s_{a + 1} \ldots s_{b}$ ($1 \leq a \leq b \leq n$). For example, "auto" and "ton" are substrings of "automaton".

Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $k$ Latin letters $c_1, c_2, \ldots, c_k$ out of $26$.

After that, Norge became interested in how many substrings of the string $s$ he could still type using his broken keyboard. Help him to find this number.

-----Input-----

The first line contains two space-separated integers $n$ and $k$ ($1 \leq n \leq 2 \cdot 10^5$, $1 \leq k \leq 26$) — the length of the string $s$ and the number of Latin letters still available on the keyboard.

The second line contains the string $s$ consisting of exactly $n$ lowercase Latin letters.

The third line contains $k$ space-separated distinct lowercase Latin letters $c_1, c_2, \ldots, c_k$ — the letters still available on the keyboard.

-----Output-----

Print a single number — the number of substrings of $s$ that can be typed using only available letters $c_1, c_2, \ldots, c_k$.

-----Examples-----
Input
7 2
abacaba
a b

Output
12

Input
10 3
sadfaasdda
f a d

Output
21

Input
7 1
aaaaaaa
b

Output
0

-----Note-----

In the first example Norge can print substrings $s[1\ldots2]$, $s[2\ldots3]$, $s[1\ldots3]$, $s[1\ldots1]$, $s[2\ldots2]$, $s[3\ldots3]$, $s[5\ldots6]$, $s[6\ldots7]$, $s[5\ldots7]$, $s[5\ldots5]$, $s[6\ldots6]$, $s[7\ldots7]$.

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

from math import *
import os, sys
from io import BytesIO

#input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, k = list(map(int, input().split()))
s = input()
a = set(input().split())
n += 1
can1 = [0] *  n
can2 = [0] *  n
n -= 1
ans = 0
for i in range(n):
    if s[i] in a:
        can1[i + 1] = can1[i] + 1
    ans += can1[i + 1]
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1272/D:
You are given an array $a$ consisting of $n$ integers.

You can remove at most one element from this array. Thus, the final length of the array is $n-1$ or $n$.

Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.

Recall that the contiguous subarray $a$ with indices from $l$ to $r$ is $a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$. The subarray $a[l \dots r]$ is called strictly increasing if $a_l < a_{l+1} < \dots < a_r$.

-----Input-----

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

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

-----Output-----

Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $a$ after removing at most one element.

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

Output
4

Input
2
1 2

Output
2

Input
7
6 5 4 3 2 4 3

Output
2

-----Note-----

In the first example, you can delete $a_3=5$. Then the resulting array will be equal to $[1, 2, 3, 4]$ and the length of its largest increasing subarray will be equal to $4$.

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

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

cur = 0
l = [0] * n
m = [0] * n

for i in range(1, n + 1):
    if a[i] > a[i - 1]:
        cur += 1
    else:
        cur = 1
    l[i - 1] = cur

cur = n - 1
num = l[cur]
while cur >= 0:
    m[cur] = num
    if l[cur] == 1:
        num = l[cur - 1]
    cur -= 1

res = max(m)
a = a[1:]

for i in range(1, n - 1):
    if l[i - 1] + 2 != l[i + 1] and a[i - 1] < a[i + 1]:
        res = max(res, m[i - 1] + m[i + 1] - 1)

print(res)

# print(l)
# print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/1272/E:
You are given an array $a$ consisting of $n$ integers. In one move, you can jump from the position $i$ to the position $i - a_i$ (if $1 \le i - a_i$) or to the position $i + a_i$ (if $i + a_i \le n$).

For each position $i$ from $1$ to $n$ you want to know the minimum the number of moves required to reach any position $j$ such that $a_j$ has the opposite parity from $a_i$ (i.e. if $a_i$ is odd then $a_j$ has to be even and vice versa).

-----Input-----

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

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

-----Output-----

Print $n$ integers $d_1, d_2, \dots, d_n$, where $d_i$ is the minimum the number of moves required to reach any position $j$ such that $a_j$ has the opposite parity from $a_i$ (i.e. if $a_i$ is odd then $a_j$ has to be even and vice versa) or -1 if it is impossible to reach such a position.

-----Example-----
Input
10
4 5 7 6 7 5 4 4 6 4

Output
1 1 1 2 -1 1 1 3 1 1

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

import sys
from itertools import chain, permutations

n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split(' ')))

result = [-1 for _ in a]
jumps_to = [[] for _ in a]

for i in range(len(a)):
	left = i - a[i]
	right = i + a[i]
	if left >= 0:
		jumps_to[left].append(i)
		if (a[left] % 2) != (a[i] % 2):
			result[i] = 1
	if right < n:
		jumps_to[right].append(i)
		if (a[right] % 2) != (a[i] % 2):
			result[i] = 1

queue = []
queue_ptr = 0
for i in range(n):
	if result[i] == 1:
		queue.append(i)

while queue_ptr < len(queue):
	current = queue[queue_ptr]
	for to in jumps_to[current]:
		if result[to] == -1 or result[to] > result[current] + 1:
			queue.append(to)
			result[to] = result[current] + 1
	queue_ptr += 1

#print(jumps_to)

print(" ".join(map(str, result)))


I found an interesting problem on https://codeforces.com/problemset/problem/1276/C:
You are given $n$ integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the $n$ numbers may not be chosen.

A rectangle (rectangular matrix) is called beautiful if in each row and in each column all values are different.

What is the largest (by the total number of cells) beautiful rectangle you can construct? Print the rectangle itself.

-----Input-----

The first line contains $n$ ($1 \le n \le 4\cdot10^5$). The second line contains $n$ integers ($1 \le a_i \le 10^9$).

-----Output-----

In the first line print $x$ ($1 \le x \le n$) — the total number of cells of the required maximum beautiful rectangle. In the second line print $p$ and $q$ ($p \cdot q=x$): its sizes. In the next $p$ lines print the required rectangle itself. If there are several answers, print any.

-----Examples-----
Input
12
3 1 4 1 5 9 2 6 5 3 5 8

Output
12
3 4
1 2 3 5
3 1 5 4
5 6 8 9

Input
5
1 1 1 1 1

Output
1
1 1
1

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()))

from collections import Counter

C=Counter(A)

import math

MAXV=max(max(C.values()),int(math.sqrt(n)))

VCOUNT=[0]*(MAXV+1)

for v in list(C.values()):
    VCOUNT[v]+=1

SUM=n

from itertools import accumulate

ACC=list(accumulate(VCOUNT[::-1]))[::-1]

ANS=0

for i in range(MAXV,0,-1):
    if SUM//i>=i:
        if ANS<i*(SUM//i):
            ANS=i*(SUM//i)
            ANSX=i,(SUM//i)

    SUM-=ACC[i]

print(ANS)

X,Y=ANSX[0],ANSX[1]
print(X,Y)

A=[[0]*Y for i in range(X)]

i=0
j=0
nowj=0
colored=0
same=0
LIST=list(C.most_common())
ind=0

while colored<ANS:
    A[i][j],MAX=LIST[ind]
    colored+=1
    i+=1
    j=(j+1)%Y
    if i==X:
        i=0
        nowj+=1
        j=nowj
    same+=1

    if same==min(X,MAX):
        ind+=1
        same=0

for a in A:
    sys.stdout.write(" ".join(map(str,a))+"\n")


I found an interesting problem on https://codeforces.com/problemset/problem/1278/A:
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.

Polycarp decided to store the hash of the password, generated by the following algorithm:  take the password $p$, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain $p'$ ($p'$ can still be equal to $p$);  generate two random strings, consisting of lowercase Latin letters, $s_1$ and $s_2$ (any of these strings can be empty);  the resulting hash $h = s_1 + p' + s_2$, where addition is string concatenation.

For example, let the password $p =$ "abacaba". Then $p'$ can be equal to "aabcaab". Random strings $s1 =$ "zyx" and $s2 =$ "kjh". Then $h =$ "zyxaabcaabkjh".

Note that no letters could be deleted or added to $p$ to obtain $p'$, only the order could be changed.

Now Polycarp asks you to help him to implement the password check module. Given the password $p$ and the hash $h$, check that $h$ can be the hash for the password $p$.

Your program should answer $t$ independent test cases.

-----Input-----

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

The first line of each test case contains a non-empty string $p$, consisting of lowercase Latin letters. The length of $p$ does not exceed $100$.

The second line of each test case contains a non-empty string $h$, consisting of lowercase Latin letters. The length of $h$ does not exceed $100$.

-----Output-----

For each test case print the answer to it — "YES" if the given hash $h$ could be obtained from the given password $p$ or "NO" otherwise.

-----Example-----
Input
5
abacaba
zyxaabcaabkjh
onetwothree
threetwoone
one
zzonneyy
one
none
twenty
ten

Output
YES
YES
NO
YES
NO

-----Note-----

The first test case is explained in the statement.

In the second test case both $s_1$ and $s_2$ are empty and $p'=$ "threetwoone" is $p$ shuffled.

In the third test case the hash could not be obtained from the password.

In the fourth test case...

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

t = int(input())
for _  in range(t):
    w = input()
    h = input()
    works = False
    for i in range(len(h)):
        ls = [h[x] if x < len(h) else "" for x in range(i, i + len(w))]
        if sorted(ls) == sorted(w):
            works = True
            break
    if works:
        print("YES")
    else:
        print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1278/B:
You are given two integers $a$ and $b$. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by $1$; during the second operation you choose one of these numbers and increase it by $2$, and so on. You choose the number of these operations yourself.

For example, if $a = 1$ and $b = 3$, you can perform the following sequence of three operations:   add $1$ to $a$, then $a = 2$ and $b = 3$;  add $2$ to $b$, then $a = 2$ and $b = 5$;  add $3$ to $a$, then $a = 5$ and $b = 5$.

Calculate the minimum number of operations required to make $a$ and $b$ equal.

-----Input-----

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

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

-----Output-----

For each test case print one integer — the minimum numbers of operations required to make $a$ and $b$ equal.

-----Example-----
Input
3
1 3
11 11
30 20

Output
3
0
4

-----Note-----

First test case considered in the statement.

In the second test case integers $a$ and $b$ are already equal, so you don't need to perform any operations.

In the third test case you have to apply the first, the second, the third and the fourth operation to $b$ ($b$ turns into $20 + 1 + 2 + 3 + 4 = 30$).

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

from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 +10 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase

#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
show_flg=True

t=I()
for _ in range(t):
    ans=0
    a,b=LI()
    if a>b:
        a,b=b,a
    if a==b:
        print(0)
        continue

    nb=max(int((2*(b-a))**0.5)-3,0)

    for i in range(nb,nb*2+100):
        #show(a+i*(i-1)//2,b , (a+i*(i-1)//2-b)%2,i)
        if a+i*(i+1)//2>=b and (a+i*(i+1)//2-b)%2==0:
            print(i)

            break

    #print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1278/D:
As the name of the task implies, you are asked to do some work with segments and trees.

Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices.

You are given $n$ segments $[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$, $l_i < r_i$ for every $i$. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends.

Let's generate a graph with $n$ vertices from these segments. Vertices $v$ and $u$ are connected by an edge if and only if segments $[l_v, r_v]$ and $[l_u, r_u]$ intersect and neither of it lies fully inside the other one.

For example, pairs $([1, 3], [2, 4])$ and $([5, 10], [3, 7])$ will induce the edges but pairs $([1, 2], [3, 4])$ and $([5, 7], [3, 10])$ will not.

Determine if the resulting graph is a tree or not.

-----Input-----

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

The $i$-th of the next $n$ lines contain the description of the $i$-th segment — two integers $l_i$ and $r_i$ ($1 \le l_i < r_i \le 2n$).

It is guaranteed that all segments borders are pairwise distinct.

-----Output-----

Print "YES" if the resulting graph is a tree and "NO" otherwise.

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

Output
YES

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

Output
NO

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

Output
NO

-----Note-----

The graph corresponding to the first example:

[Image]

The graph corresponding to the second example:

[Image]

The graph corresponding to the third example:

[Image]

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

import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

class BIT_RSQ():
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+2)

    def add(self, i, v):
        while i <= self.n:
            self.data[i] += v
            i += i & -i

    def sum(self, i):
        ret = 0
        while(i > 0):
            ret += self.data[i]
            i -= i & -i
        return ret

    def query(self, l, r):
        return self.sum(r) - self.sum(l-1)

    def lowerBound(self, w):
        if w <= 0: return 0
        x, k = 0, 2**self.n.bit_length()
        while k:
            if x+k <= self.n and self.data[x+k] < w:
                w -= self.data[x+k]
                x += k
            k >>= 1
        return x + 1

n = int(input())
edges = [0]*(2*n)
c = [0]*(2*n)
BIT = BIT_RSQ(2*n)

uf = [-1]*n
def root(x):
    if uf[x] < 0:
        return x
    uf[x] = root(uf[x])
    return uf[x]
def unite(x,y):
    rx, ry = root(x), root(y)
    if rx == ry:
        return False
    if uf[rx] > uf[ry]:
        rx, ry = ry, rx
    uf[rx] += uf[ry]
    uf[ry] = rx
    return True

for i in range(n):
    a,b = list(map(int, input().split()))
    a,b = a-1,b-1
    c[a] = c[b] = i
    edges[a] = b
    edges[b] = b

for i in reversed(list(range(2*n))):
    j = edges[i]
    if j == i:
        BIT.add(j+1, 1)
    else:
        BIT.add(j+1, -1)
        cnt = BIT.sum(j+1)
        while cnt:
            k = BIT.lowerBound(cnt)
            if not unite(c[j], c[k-1]):
                print("NO")
                return
            cnt -= 1
if sum(i<0 for i in uf) == 1:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1279/A:
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.

The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!

For example, if you provide $3$ red, $3$ green and $3$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.

However, if you provide, say, $1$ red, $10$ green and $2$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.

So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of sets of lamps Polycarp has bought.

Each of the next $t$ lines contains three integers $r$, $g$ and $b$ ($1 \le r, g, b \le 10^9$) — the number of red, green and blue lamps in the set, respectively.

-----Output-----

Print $t$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.

-----Example-----
Input
3
3 3 3
1 10 2
2 1 1

Output
Yes
No
Yes

-----Note-----

The first two sets are desribed in the statement.

The third set produces garland "RBRG", for example.

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

t = int(input())
for i in range(t):
    a, b, c= sorted([int(x) for x in input().split()])
    if a + b < c - 1:
        print("No")
    else:
        print("Yes")


I found an interesting problem on https://codeforces.com/problemset/problem/1279/B:
New Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus.

Vasya's verse contains $n$ parts. It takes $a_i$ seconds to recite the $i$-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes $a_1$ seconds, secondly — the part which takes $a_2$ seconds, and so on. After reciting the verse, Vasya will get the number of presents equal to the number of parts he fully recited.

Vasya can skip at most one part of the verse while reciting it (if he skips more than one part, then Santa will definitely notice it).

Santa will listen to Vasya's verse for no more than $s$ seconds. For example, if $s = 10$, $a = [100, 9, 1, 1]$, and Vasya skips the first part of verse, then he gets two presents.

Note that it is possible to recite the whole verse (if there is enough time).

Determine which part Vasya needs to skip to obtain the maximum possible number of gifts. If Vasya shouldn't skip anything, print 0. If there are multiple answers, print any of them.

You have to process $t$ test cases.

-----Input-----

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

The first line of each test case contains two integers $n$ and $s$ ($1 \le n \le 10^5, 1 \le s \le 10^9$) — the number of parts in the verse and the maximum number of seconds Santa will listen to Vasya, respectively.

The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the time it takes to recite each part of the verse.

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

-----Output-----

For each test case print one integer — the number of the part that Vasya needs to skip to obtain the maximum number of gifts. If Vasya shouldn't skip any parts, print 0.

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

Output
2
1
0

-----Note-----

In the first test case if Vasya skips the second part then he gets three gifts.

In the second test...

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

t=int(input())
for i in range(t):
    n,s=list(map(int,input().split()))
    a=list(map(int,input().split()))
    mx,sm,mxi=0,0,0
    k=True
    for ii in range(len(a)):
        i=a[ii]
        sm+=i
        if i > mx:
            mx,mxi=i,ii
        if sm>s:
            break
    else:
        k=False
    if k==False:
        print(0)
    else:
        sm-=mx
        ad=0
        for ij in range(ii,len(a)):
            j=a[ij]
            ad+=1
            sm+=i
            if sm>s:
                break
        if ad==0:
            print(0)
        else:
            print(mxi+1)


I found an interesting problem on https://codeforces.com/problemset/problem/1279/D:
Santa Claus has received letters from $n$ different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the $i$-th kid asked Santa to give them one of $k_i$ different items as a present. Some items could have been asked by multiple kids.

Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:

  choose one kid $x$ equiprobably among all $n$ kids;  choose some item $y$ equiprobably among all $k_x$ items kid $x$ wants;  choose a kid $z$ who will receive the present equipropably among all $n$ kids (this choice is independent of choosing $x$ and $y$); the resulting triple $(x, y, z)$ is called the decision of the Bot.

If kid $z$ listed item $y$ as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.

Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 10^6$) — the number of kids who wrote their letters to Santa.

Then $n$ lines follow, the $i$-th of them contains a list of items wanted by the $i$-th kid in the following format: $k_i$ $a_{i, 1}$ $a_{i, 2}$ ... $a_{i, k_i}$ ($1 \le k_i, a_{i, j} \le 10^6$), where $k_i$ is the number of items wanted by the $i$-th kid, and $a_{i, j}$ are the items themselves. No item is contained in the same list more than once.

It is guaranteed that $\sum \limits_{i = 1}^{n} k_i \le 10^6$.

-----Output-----

Print the probatility that the Bot produces a valid decision as follows:

Let this probability be represented as an irreducible fraction $\frac{x}{y}$. You have to print $x \cdot y^{-1} \mod 998244353$, where $y^{-1}$ is the inverse element of $y$ modulo $998244353$ (such integer that...

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

import sys
from collections import Counter
mod = 998244353

n = int(input())
div_n = pow(n, mod-2, mod)
wants = []
cnt = Counter()
for a in (list(map(int, l.split())) for l in sys.stdin):
    wants.append(a[1:])
    cnt.update(a[1:])

ans = 0

for i in range(n):
    prob = div_n * pow(len(wants[i]), mod-2, mod) * div_n % mod
    for x in wants[i]:
        ans = (ans + prob * cnt[x]) % mod

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1280/F:
You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a $2 \times (2k + 1)$ rectangular grid. The alien has $4k + 1$ distinct organs, numbered $1$ to $4k + 1$.

In healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for $k = 4$: [Image]

Here, the E represents empty space.

In general, the first row contains organs $1$ to $2k + 1$ (in that order from left to right), and the second row contains organs $2k + 2$ to $4k + 1$ (in that order from left to right) and then empty space right after.

Your patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things:  You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space;  You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) only if the empty space is on the leftmost column, rightmost column or in the centermost column. Again, you do this by sliding the organ in question to the empty space.

Your job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all $4k + 1$ internal organs of your patient in the correct cells. If it is impossible to do so, you must say so.

-----Input-----

The first line of input contains a single integer $t$ ($1 \le t \le 4$) denoting the number of test cases. The next lines contain...

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

def flatten(grid):
    k = len(grid[0]) // 2
    seek = list(range(2*k + 2)) + list(range(2*k + 2, 4*k + 2))[::-1]
    return [seek[v] for v in grid[0] + grid[1][::-1] if v]

def solve(grid):
    grid = list(map(list, grid))
    k = len(grid[0]) // 2
    flat = flatten(grid)

    m = {
        'L': 'l'*2*k + 'u' + 'r'*2*k + 'd',
        'R': 'u' + 'l'*2*k + 'd' + 'r'*2*k,
        'C': 'l'*k + 'u' + 'r'*k + 'd',
        'D': 'CC' + 'R'*(2*k + 1) + 'CC' + 'R'*(2*k + 2),
        'F': 'R'*(k - 1) + 'DD' + 'R'*(2*k + 1) + 'D' + 'L'*2*k + 'DD' + 'L'*k,
        'G': 'FF',
    }

    [(i, j)] = [(i, j) for i in range(2) for j in range(2*k + 1) if grid[i][j] == 0]
    st = 'r'*(2*k - j) + 'd'*(1 - i)

    for v in range(2, 4*k + 2):
        ct = flat.index(v)

        if ct >= 2:
            st += 'L'*(ct - 2) + 'GR'*(ct - 2) + 'G'
            flat = flat[ct - 1: ct + 1] + flat[:ct - 1] + flat[ct + 1:]

        if ct >= 1:
            st += 'G'
            flat = flat[1:3] + flat[:1] + flat[3:]

        st += 'L'
        flat = flat[1:] + flat[:1]

    if flat[0] == 1: return st, m

def main():
    def get_line():
        return [0 if x == 'E' else int(x) for x in input().split()]

    for cas in range(int(input())):
        k = int(input())
        grid = [get_line() for i in range(2)]
        assert all(len(row) == 2*k + 1 for row in grid)
        res = solve(grid)
        if res is None:
            print('SURGERY FAILED')
        else:
            print('SURGERY COMPLETE')
            st, m = res
            print(st)
            for shortcut in list(m.items()): print(*shortcut)
            print('DONE')

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1281/A:
We just discovered a new data structure in our research group: a suffix three!

It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.

It's super simple, 100% accurate, and doesn't involve advanced machine learning algorithms.

Let us tell you how it works.

  If a sentence ends with "po" the language is Filipino.  If a sentence ends with "desu" or "masu" the language is Japanese.  If a sentence ends with "mnida" the language is Korean.

Given this, we need you to implement a suffix three that can differentiate Filipino, Japanese, and Korean.

Oh, did I say three suffixes? I meant four.

-----Input-----

The first line of input contains a single integer $t$ ($1 \leq t \leq 30$) denoting the number of test cases. The next lines contain descriptions of the test cases.

Each test case consists of a single line containing a single string denoting the sentence. Spaces are represented as underscores (the symbol "_") for ease of reading. The sentence has at least $1$ and at most $1000$ characters, and consists only of lowercase English letters and underscores. The sentence has no leading or trailing underscores and no two consecutive underscores. It is guaranteed that the sentence ends with one of the four suffixes mentioned above.

-----Output-----

For each test case, print a single line containing either "FILIPINO", "JAPANESE", or "KOREAN" (all in uppercase, without quotes), depending on the detected language.

-----Example-----
Input
8
kamusta_po
genki_desu
ohayou_gozaimasu
annyeong_hashimnida
hajime_no_ippo
bensamu_no_sentou_houhou_ga_okama_kenpo
ang_halaman_doon_ay_sarisari_singkamasu
si_roy_mustang_ay_namamasu

Output
FILIPINO
JAPANESE
JAPANESE
KOREAN
FILIPINO
FILIPINO
JAPANESE
JAPANESE

-----Note-----

The first sentence ends with "po", so it is written in Filipino.

The second and third sentences end with "desu" and "masu", so they are written in Japanese.

The fourth sentence ends with...

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

t = int(input())
while t:
    s = input()
    if s[-2] == 'p' and s[-1] == 'o':
        print("FILIPINO")
    else:
        if s[-4:] == "desu" or s[-4:] == "masu":
            print("JAPANESE")
        else:
            print("KOREAN")
    t -= 1


I found an interesting problem on https://codeforces.com/problemset/problem/1281/E:
Welcome! Everything is fine.

You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.

You have a list of $k$ pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the $2k$ people into one of the $2k$ houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.

Of course, in the neighborhood, it is possible to visit friends. There are $2k - 1$ roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.

The truth is, these $k$ pairs of people are actually soulmates. We index them from $1$ to $k$. We denote by $f(i)$ the amount of time it takes for the $i$-th pair of soulmates to go to each other's houses.

As we have said before, you will need to assign each of the $2k$ people into one of the $2k$ houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:  The first mission, from The Good Place, is to assign the people into the houses such that the sum of $f(i)$ over all pairs $i$ is minimized. Let's define this minimized sum as $G$. This makes sure that soulmates can easily and efficiently visit each other;  The second mission, from The Bad Place, is to assign the people into the houses such that the sum of $f(i)$ over all pairs $i$ is maximized. Let's define this maximized sum as $B$. This makes sure that soulmates will have a difficult time to visit each other.

What are the values of $G$ and $B$?

-----Input-----

The first line of input contains a single integer $t$ ($1 \le t \le 500$) denoting the number of...

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

import sys

# inf = open('input.txt', 'r')
# reader = (map(int, line.split()) for line in inf)
reader = (list(map(int, line.split())) for line in sys.stdin)

def minmaxPairs(g, costDict, n):
    G = B = 0
    s = 1
    stack = [s]
    traversal = []
    visited = [False] * (n + 1)
    subtreeSize = [1 for _ in range(n + 1)]
    while stack:
        v = stack.pop()
        if not visited[v]:
            visited[v] = True
            for to in g[v]:
                if not visited[to]:
                    stack.append(v)
                    stack.append(to)
        else:
            to = traversal[-1]
            if (v, to) in costDict:
                cost = costDict[(v, to)]
            else:
                cost = costDict[(to, v)]
            toSize = subtreeSize[to]
            subtreeSize[v] += toSize
            minComp = min(toSize, n - toSize)
            G += (minComp % 2) * cost
            B += minComp * cost
        traversal.append(v)
    return G, B

t, = next(reader)
for _ in range(t):
    k, = next(reader)
    n = 2 * k
    g = [[] for i in range(n + 1)]
    costDict = {}
    for i in range(n - 1):
        v, to, cost = next(reader)
        costDict[(v, to)] = cost
        g[v].append(to)
        g[to].append(v)
    G, B = minmaxPairs(g, costDict, n)
    print(G, B)

# inf.close()


I found an interesting problem on https://codeforces.com/problemset/problem/1282/B1:
This is the easy version of this problem. The only difference is the constraint on $k$ — the number of gifts in the offer. In this version: $k=2$.

Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "$k$ of goods for the price of one" is held in store. Remember, that in this problem $k=2$.

Using this offer, Vasya can buy exactly $k$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.

More formally, for each good, its price is determined by $a_i$ — the number of coins it costs. Initially, Vasya has $p$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:  Vasya can buy one good with the index $i$ if he currently has enough coins (i.e $p \ge a_i$). After buying this good, the number of Vasya's coins will decrease by $a_i$, (i.e it becomes $p := p - a_i$).  Vasya can buy a good with the index $i$, and also choose exactly $k-1$ goods, the price of which does not exceed $a_i$, if he currently has enough coins (i.e $p \ge a_i$). Thus, he buys all these $k$ goods, and his number of coins decreases by $a_i$ (i.e it becomes $p := p - a_i$).

Please note that each good can be bought no more than once.

For example, if the store now has $n=5$ goods worth $a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$, respectively, $k=2$, and Vasya has $6$ coins, then he can buy $3$ goods. A good with the index $1$ will be bought by Vasya without using the offer and he will pay $2$ coins. Goods with the indices $2$ and $3$ Vasya will buy using the offer and he will pay $4$ coins. It can be proved that Vasya can not buy more goods with six coins.

Help Vasya to find out the maximum number of goods he can buy.

-----Input-----

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

The next lines contain a description of $t$ test...

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

import sys

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

T = int(input())

def solve(n,p,k,goods):
    i = 0
    ans = 0
    while i < n:
        if i<n-1 and goods[i+1]<=p:
            ans+=2
            p-=goods[i+1]
            i+=2
        elif goods[i]<=p:
            ans+=1
            break
        else:
            i+=1
    return ans

for _ in range(T):
    n,p,k = list(map(int, input().split()))
    goods = list(map(int, input().split()))
    goods.sort()

    ans = solve(n,p,k,goods)
    if goods[0]<=p and n>=2:
        ans = max(ans, solve(n-1,p-goods[0], k, goods[1:])+1)
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1282/B2:
This is the hard version of this problem. The only difference is the constraint on $k$ — the number of gifts in the offer. In this version: $2 \le k \le n$.

Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "$k$ of goods for the price of one" is held in store.

Using this offer, Vasya can buy exactly $k$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.

More formally, for each good, its price is determined by $a_i$ — the number of coins it costs. Initially, Vasya has $p$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:

  Vasya can buy one good with the index $i$ if he currently has enough coins (i.e $p \ge a_i$). After buying this good, the number of Vasya's coins will decrease by $a_i$, (i.e it becomes $p := p - a_i$).  Vasya can buy a good with the index $i$, and also choose exactly $k-1$ goods, the price of which does not exceed $a_i$, if he currently has enough coins (i.e $p \ge a_i$). Thus, he buys all these $k$ goods, and his number of coins decreases by $a_i$ (i.e it becomes $p := p - a_i$).

Please note that each good can be bought no more than once.

For example, if the store now has $n=5$ goods worth $a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$, respectively, $k=2$, and Vasya has $6$ coins, then he can buy $3$ goods. A good with the index $1$ will be bought by Vasya without using the offer and he will pay $2$ coins. Goods with the indices $2$ and $3$ Vasya will buy using the offer and he will pay $4$ coins. It can be proved that Vasya can not buy more goods with six coins.

Help Vasya to find out the maximum number of goods he can buy.

-----Input-----

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

The next lines contain a description of $t$ test cases.

The first line of...

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

import os
from io import BytesIO

# input = BytesIO(os.read(0, os.fstat(0).st_size)).readline

def check(x, p):
    i = x - 1
    while i > -1 and a[i] <= p:
        p -= a[i]
        if i >= k - 1:
            i -= k
        else:
            i -= 1
    return i <= -1

for _ in range(int(input())):
    n, p, k = map(int, input().split())
    a = sorted(map(int, input().split()))
    dp = [1000000000] * (n + 1)
    dp[0] = 0
    ans = 0
    for i in range(1, n + 1):
        dp[i] = dp[i - 1] + a[i - 1]
        if i - k + 1 >= 0:
            dp[i] = min(dp[i], dp[i - k] + a[i - 1])
        if dp[i] <= p:
            ans = i
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1283/A:
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $h$ hours and $m$ minutes, where $0 \le hh < 24$ and $0 \le mm < 60$. We use 24-hour time format!

Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows $0$ hours and $0$ minutes.

You have to answer $t$ independent test cases.

-----Input-----

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

The following $t$ lines describe test cases. The $i$-th line contains the time as two integers $h$ and $m$ ($0 \le h < 24$, $0 \le m < 60$). It is guaranteed that this time is not a midnight, i.e. the following two conditions can't be met at the same time: $h=0$ and $m=0$. It is guaranteed that both $h$ and $m$ are given without leading zeros.

-----Output-----

For each test case, print the answer on it — the number of minutes before the New Year.

-----Example-----
Input
5
23 55
23 0
0 1
4 20
23 59

Output
5
60
1439
1180
1

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

t = int(input())
for i in range(t):
	n, s = list(map(int, input().split()))
	print(24 * 60 - n * 60 - s)


I found an interesting problem on https://codeforces.com/problemset/problem/1283/B:
Santa has $n$ candies and he wants to gift them to $k$ kids. He wants to divide as many candies as possible between all $k$ kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.

Suppose the kid who recieves the minimum number of candies has $a$ candies and the kid who recieves the maximum number of candies has $b$ candies. Then Santa will be satisfied, if the both conditions are met at the same time:

  $b - a \le 1$ (it means $b = a$ or $b = a + 1$);  the number of kids who has $a+1$ candies (note that $a+1$ not necessarily equals $b$) does not exceed $\lfloor\frac{k}{2}\rfloor$ (less than or equal to $\lfloor\frac{k}{2}\rfloor$).

$\lfloor\frac{k}{2}\rfloor$ is $k$ divided by $2$ and rounded down to the nearest integer. For example, if $k=5$ then $\lfloor\frac{k}{2}\rfloor=\lfloor\frac{5}{2}\rfloor=2$.

Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.

You have to answer $t$ independent test cases.

-----Input-----

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

The next $t$ lines describe test cases. The $i$-th test case contains two integers $n$ and $k$ ($1 \le n, k \le 10^9$) — the number of candies and the number of kids.

-----Output-----

For each test case print the answer on it — the maximum number of candies Santa can give to kids so that he will be satisfied.

-----Example-----
Input
5
5 2
19 4
12 7
6 2
100000 50010

Output
5
18
10
6
75015

-----Note-----

In the first test case, Santa can give $3$ and $2$ candies to kids. There $a=2, b=3,a+1=3$.

In the second test case, Santa can give $5, 5, 4$ and $4$ candies. There $a=4,b=5,a+1=5$. The answer cannot be greater because then the number of kids with $5$ candies will be $3$.

In the third test case, Santa can distribute candies in the following way: $[1, 2, 2, 1, 1, 2, 1]$. There $a=1,b=2,a+1=2$. He cannot distribute two remaining candies in a way to be satisfied.

In the fourth...

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

for _ in range(int(input())):
    n,k = list(map(int, input().split()))
    ans = (n//k)*k + min(k//2,n%k)
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1283/C:
There are $n$ friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.

For each friend the value $f_i$ is known: it is either $f_i = 0$ if the $i$-th friend doesn't know whom he wants to give the gift to or $1 \le f_i \le n$ if the $i$-th friend wants to give the gift to the friend $f_i$.

You want to fill in the unknown values ($f_i = 0$) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.

If there are several answers, you can print any.

-----Input-----

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

The second line of the input contains $n$ integers $f_1, f_2, \dots, f_n$ ($0 \le f_i \le n$, $f_i \ne i$, all $f_i \ne 0$ are distinct), where $f_i$ is the either $f_i = 0$ if the $i$-th friend doesn't know whom he wants to give the gift to or $1 \le f_i \le n$ if the $i$-th friend wants to give the gift to the friend $f_i$. It is also guaranteed that there is at least two values $f_i = 0$.

-----Output-----

Print $n$ integers $nf_1, nf_2, \dots, nf_n$, where $nf_i$ should be equal to $f_i$ if $f_i \ne 0$ or the number of friend whom the $i$-th friend wants to give the gift to. All values $nf_i$ should be distinct, $nf_i$ cannot be equal to $i$. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself.

If there are several answers, you can print any.

-----Examples-----
Input
5
5 0 0 2 4

Output
5 3 1 2 4

Input
7
7 0 0 1 4 0 6

Output
7 3 2 1 4 5 6

Input
7
7 4 0 3 0 5 1

Output
7 4 2 3 6 5 1

Input
5
2 1 0 0 0

Output
2 1 4 5 3

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

n = int(input())
f = list(map(int, input().split()))
give = set(i for i in range(n))
get = set(i for i in range(n))
for i in range(n):
    if f[i] > 0:
        give.remove(i)
        get.remove(f[i]-1)
givel = list(give)
for x in givel:
    if x in get:
        give.remove(x)
        for j in get:
            if j == x:
                continue
            f[x] = j+1
            break
        get.remove(j)
givel = list(give)
for x in give:
    for j in get:
        f[x] = j+1
        break
    get.remove(j)
print(' '.join(map(str, f)))


I found an interesting problem on https://codeforces.com/problemset/problem/1283/D:
There are $n$ Christmas trees on an infinite number line. The $i$-th tree grows at the position $x_i$. All $x_i$ are guaranteed to be distinct.

Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.

There are $m$ people who want to celebrate Christmas. Let $y_1, y_2, \dots, y_m$ be the positions of people (note that all values $x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$ should be distinct and all $y_j$ should be integer). You want to find such an arrangement of people that the value $\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$ is the minimum possible (in other words, the sum of distances to the nearest Christmas tree for all people should be minimized).

In other words, let $d_j$ be the distance from the $j$-th human to the nearest Christmas tree ($d_j = \min\limits_{i=1}^{n} |y_j - x_i|$). Then you need to choose such positions $y_1, y_2, \dots, y_m$ that $\sum\limits_{j=1}^{m} d_j$ is the minimum possible.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the number of Christmas trees and the number of people.

The second line of the input contains $n$ integers $x_1, x_2, \dots, x_n$ ($-10^9 \le x_i \le 10^9$), where $x_i$ is the position of the $i$-th Christmas tree. It is guaranteed that all $x_i$ are distinct.

-----Output-----

In the first line print one integer $res$ — the minimum possible value of $\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$ (in other words, the sum of distances to the nearest Christmas tree for all people).

In the second line print $m$ integers $y_1, y_2, \dots, y_m$ ($-2 \cdot 10^9 \le y_j \le 2 \cdot 10^9$), where $y_j$ is the position of the $j$-th human. All $y_j$ should be distinct and all values $x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$ should be distinct.

If there are multiple answers, print any of them.

-----Examples-----
Input
2 6
1 5

Output
8
-1 2 6 4 0 3

Input
3 5
0 3...

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

import heapq,bisect

def main():
    n,m = map(int,input().split())
    trees = list(map(int,input().split()))
    trees.sort()

    ans = []
    distance = 0
    heap = []
    visited = set()
    for i in trees:
        visited.add(i)

    for i in trees:
        if i+1 not in visited:
            heapq.heappush(heap,(1,i+1))
        if i-1 not in visited:
            heapq.heappush(heap,(1,i-1))

    while heap:
        curr = heapq.heappop(heap)
        if curr[1] not in visited:
            distance += curr[0]
            ans.append(curr[1])
            visited.add(curr[1])
            if len(ans) == m:
                break

            if curr[1]+1 not in visited:
                index = bisect.bisect(trees,curr[1]+1)
                min_dist = float('inf')
                if index < len(trees):
                    min_dist = min(min_dist,trees[index]-curr[1]-1)
                if index-1 >= 0:
                    min_dist = min(min_dist,curr[1]+1-trees[index-1])

                heapq.heappush(heap,(min_dist,curr[1]+1))

            if curr[1]-1 not in visited:
                index = bisect.bisect(trees,curr[1]-1)
                min_dist = float('inf')
                if index < len(trees):
                    min_dist = min(min_dist,trees[index]-curr[1]+1)
                if index-1 >= 0:
                    min_dist = min(min_dist,curr[1]-1-trees[index-1])

                heapq.heappush(heap,(min_dist,curr[1]-1))

    print(distance)
    for i in ans:
        print(i,end = ' ')

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1283/E:
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...

$n$ friends live in a city which can be represented as a number line. The $i$-th friend lives in a house with an integer coordinate $x_i$. The $i$-th friend can come celebrate the New Year to the house with coordinate $x_i-1$, $x_i+1$ or stay at $x_i$. Each friend is allowed to move no more than once.

For all friends $1 \le x_i \le n$ holds, however, they can come to houses with coordinates $0$ and $n+1$ (if their houses are at $1$ or $n$, respectively).

For example, let the initial positions be $x = [1, 2, 4, 4]$. The final ones then can be $[1, 3, 3, 4]$, $[0, 2, 3, 3]$, $[2, 2, 5, 5]$, $[2, 1, 3, 5]$ and so on. The number of occupied houses is the number of distinct positions among the final ones.

So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?

-----Input-----

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

The second line contains $n$ integers $x_1, x_2, \dots, x_n$ ($1 \le x_i \le n$) — the coordinates of the houses of the friends.

-----Output-----

Print two integers — the minimum and the maximum possible number of occupied houses after all moves are performed.

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

Output
2 4

Input
9
1 1 8 8 8 4 4 4 4

Output
3 8

Input
7
4 3 7 1 4 3 3

Output
3 6

-----Note-----

In the first example friends can go to $[2, 2, 3, 3]$. So friend $1$ goes to $x_1+1$, friend $2$ stays at his house $x_2$, friend $3$ goes to $x_3-1$ and friend $4$ goes to $x_4-1$. $[1, 1, 3, 3]$, $[2, 2, 3, 3]$ or $[2, 2, 4, 4]$ are also all valid options to obtain $2$ occupied houses.

For the maximum number of occupied houses friends can go to $[1, 2, 3, 4]$ or to $[0, 2, 4, 5]$, for example.

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

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

ls.sort()
minh = set()
maxh = set()

for e in ls:
    if e-1 not in maxh:
        maxh.add(e-1)
    elif e not in maxh:
        maxh.add(e)
    else:
        maxh.add(e+1)

    if e-1 not in minh and e not in minh and e+1 not in minh:
        minh.add(e+1)

print(len(minh), len(maxh))


I found an interesting problem on https://codeforces.com/problemset/problem/1284/A:
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.

There are two sequences of $n$ strings $s_1, s_2, s_3, \ldots, s_{n}$ and $m$ strings $t_1, t_2, t_3, \ldots, t_{m}$. These strings contain only lowercase letters. There might be duplicates among these strings.

Let's call a concatenation of strings $x$ and $y$ as the string that is obtained by writing down strings $x$ and $y$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".

The year 1 has a name which is the concatenation of the two strings $s_1$ and $t_1$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.

For example, if $n = 3, m = 4, s = ${"a", "b", "c"}, $t =$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. [Image]

You are given two sequences of strings of size $n$ and $m$ and also $q$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?

-----Input-----

The first line contains two integers $n, m$ ($1 \le n, m \le 20$).

The next line contains $n$ strings $s_1, s_2, \ldots, s_{n}$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $1$ and at most $10$.

The next line contains $m$ strings $t_1, t_2, \ldots, t_{m}$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $1$ and at most $10$.

Among the given $n + m$ strings may be duplicates (that is, they are not necessarily all different).

The next line...

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

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

for _ in range(int(input())):
    y = int(input()) - 1
    print(s[y % n] + t[y % m])


I found an interesting problem on https://codeforces.com/problemset/problem/1284/C:
Recall that the permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).

A sequence $a$ is a subsegment of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as $[l, r]$, where $l, r$ are two integers with $1 \le l \le r \le n$. This indicates the subsegment where $l-1$ elements from the beginning and $n-r$ elements from the end are deleted from the sequence.

For a permutation $p_1, p_2, \ldots, p_n$, we define a framed segment as a subsegment $[l,r]$ where $\max\{p_l, p_{l+1}, \dots, p_r\} - \min\{p_l, p_{l+1}, \dots, p_r\} = r - l$. For example, for the permutation $(6, 7, 1, 8, 5, 3, 2, 4)$ some of its framed segments are: $[1, 2], [5, 8], [6, 7], [3, 3], [8, 8]$. In particular, a subsegment $[i,i]$ is always a framed segments for any $i$ between $1$ and $n$, inclusive.

We define the happiness of a permutation $p$ as the number of pairs $(l, r)$ such that $1 \le l \le r \le n$, and $[l, r]$ is a framed segment. For example, the permutation $[3, 1, 2]$ has happiness $5$: all segments except $[1, 2]$ are framed segments.

Given integers $n$ and $m$, Jongwon wants to compute the sum of happiness for all permutations of length $n$, modulo the prime number $m$. Note that there exist $n!$ (factorial of $n$) different permutations of length $n$.

-----Input-----

The only line contains two integers $n$ and $m$ ($1 \le n \le 250\,000$, $10^8 \le m \le 10^9$, $m$ is prime).

-----Output-----

Print $r$ ($0 \le r < m$), the sum of happiness for all permutations of length $n$, modulo a prime number $m$.

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

Output
1

Input
2 993244853

Output
6

Input
3 993244853

Output
32

Input
2019...

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

input = __import__('sys').stdin.readline
MIS = lambda: map(int,input().split())

n, MOD = MIS()
ans = 0
fac = [1]
for i in range(1, n+2): fac.append(fac[-1] * i % MOD)
for d in range(1, n+1):
    ans+= (n-d+1)**2 * fac[d] * fac[n-d]
    ans%= MOD
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1285/A:
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position $x = 0$. Mezo starts sending $n$ commands to Zoma. There are two possible commands:  'L' (Left) sets the position $x: =x - 1$;  'R' (Right) sets the position $x: =x + 1$.

Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position $x$ doesn't change and Mezo simply proceeds to the next command.

For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully):   "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position $0$;  "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position $0$ as well;  "LRLR" — Zoma moves to the left, then to the left again and ends up in position $-2$.

Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.

-----Input-----

The first line contains $n$ $(1 \le n \le 10^5)$ — the number of commands Mezo sends.

The second line contains a string $s$ of $n$ commands, each either 'L' (Left) or 'R' (Right).

-----Output-----

Print one integer — the number of different positions Zoma may end up at.

-----Example-----
Input
4
LRLR

Output
5

-----Note-----

In the example, Zoma may end up anywhere between $-2$ and $2$.

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

n = int(input())
a = input()
print(n + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1285/B:
Today, Yasser and Adel are at the shop buying cupcakes. There are $n$ cupcake types, arranged from $1$ to $n$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $i$ is an integer $a_i$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.

Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.

On the other hand, Adel will choose some segment $[l, r]$ $(1 \le l \le r \le n)$ that does not include all of cupcakes (he can't choose $[l, r] = [1, n]$) and buy exactly one cupcake of each of types $l, l + 1, \dots, r$.

After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.

For example, let the tastinesses of the cupcakes be $[7, 4, -1]$. Yasser will buy all of them, the total tastiness will be $7 + 4 - 1 = 10$. Adel can choose segments $[7], [4], [-1], [7, 4]$ or $[4, -1]$, their total tastinesses are $7, 4, -1, 11$ and $3$, respectively. Adel can choose segment with tastiness $11$, and as $10$ is not strictly greater than $11$, Yasser won't be happy :(

Find out if Yasser will be happy after visiting the shop.

-----Input-----

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

The first line of each test case contains $n$ ($2 \le n \le 10^5$).

The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$), where $a_i$ represents the tastiness of the $i$-th type of cupcake.

It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.

-----Output-----

For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's...

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

test = int(input())
for z in range(test):
    amount = int(input())
    numb = list(map(int, input().split()))
    all = sum(numb)
    happy = True
    summ = 0
    for i in range(amount - 1):
        summ += numb[i]
        if summ <= 0:
            happy = False
            break
    if (not happy):
        print('NO')
        continue
    else:
        summ = 0
        for i in range(amount - 1, 0, -1):
            summ += numb[i]
            if summ <= 0:
                happy = False
                break
        if not happy:
            print('NO')
            continue
    print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1285/C:
Today, Osama gave Fadi an integer $X$, and Fadi was wondering about the minimum possible value of $max(a, b)$ such that $LCM(a, b)$ equals $X$. Both $a$ and $b$ should be positive integers.

$LCM(a, b)$ is the smallest positive integer that is divisible by both $a$ and $b$. For example, $LCM(6, 8) = 24$, $LCM(4, 12) = 12$, $LCM(2, 3) = 6$.

Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?

-----Input-----

The first and only line contains an integer $X$ ($1 \le X \le 10^{12}$).

-----Output-----

Print two positive integers, $a$ and $b$, such that the value of $max(a, b)$ is minimum possible and $LCM(a, b)$ equals $X$. If there are several possible such pairs, you can print any.

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

Output
1 2

Input
6

Output
2 3

Input
4

Output
1 4

Input
1

Output
1 1

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

import sys
input = sys.stdin.readline

x=int(input())
y=x
ANS=x+1
AX=[0,0]

import math
L=int(math.sqrt(x))

FACT=dict()

for i in range(2,L+2):
    while x%i==0:
        FACT[i]=FACT.get(i,0)+1
        x=x//i

if x!=1:
    FACT[x]=FACT.get(x,0)+1
x=y
LEN=len(FACT)
LIST=list(FACT.keys())
for i in range(1<<LEN):
    sc=1
    for j in range(LEN):
        if i & (1<<j) !=0:
            sc*=LIST[j]**FACT[LIST[j]]

    if ANS>max(sc,x//sc):
        ANS=max(sc,x//sc)
        AX=[sc,x//sc]

print(*AX)


I found an interesting problem on https://codeforces.com/problemset/problem/1285/D:
Today, as a friendship gift, Bakry gave Badawy $n$ integers $a_1, a_2, \dots, a_n$ and challenged him to choose an integer $X$ such that the value $\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$ is minimum possible, where $\oplus$ denotes the bitwise XOR operation.

As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$.

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2^{30}-1$).

-----Output-----

Print one integer — the minimum possible value of $\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$.

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

Output
2

Input
2
1 5

Output
4

-----Note-----

In the first sample, we can choose $X = 3$.

In the second sample, we can choose $X = 5$.

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

n = int(input())
seq = sorted(list(map(int, input().split())))

#Left (inc), Right(exc), bit to check, value to add
queue = [(0,n,30,0)]
best = 2 ** 30
while queue:
    l, r, b, v = queue.pop()
    if b >= 0:
        mask = 1 << b

        if not mask & seq[l] and mask & seq[r - 1]:
            for i in range(l, r):
                if mask & seq[i]:
                    queue.append((l,i,b - 1, v + mask))
                    queue.append((i,r,b - 1, v + mask))
                    break
        else:
            queue.append((l, r, b - 1, v))
    else:
        best = min(best, v)

print(best)


I found an interesting problem on https://codeforces.com/problemset/problem/1285/E:
There are $n$ segments on a $Ox$ axis $[l_1, r_1]$, $[l_2, r_2]$, ..., $[l_n, r_n]$. Segment $[l, r]$ covers all points from $l$ to $r$ inclusive, so all $x$ such that $l \le x \le r$.

Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is $l_i=r_i$ is possible.

Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:  if $n=3$ and there are segments $[3, 6]$, $[100, 100]$, $[5, 8]$ then their union is $2$ segments: $[3, 8]$ and $[100, 100]$;  if $n=5$ and there are segments $[1, 2]$, $[2, 3]$, $[4, 5]$, $[4, 6]$, $[6, 6]$ then their union is $2$ segments: $[1, 3]$ and $[4, 6]$.

Obviously, a union is a set of pairwise non-intersecting segments.

You are asked to erase exactly one segment of the given $n$ so that the number of segments in the union of the rest $n-1$ segments is maximum possible.

For example, if $n=4$ and there are segments $[1, 4]$, $[2, 3]$, $[3, 6]$, $[5, 7]$, then:  erasing the first segment will lead to $[2, 3]$, $[3, 6]$, $[5, 7]$ remaining, which have $1$ segment in their union;  erasing the second segment will lead to $[1, 4]$, $[3, 6]$, $[5, 7]$ remaining, which have $1$ segment in their union;  erasing the third segment will lead to $[1, 4]$, $[2, 3]$, $[5, 7]$ remaining, which have $2$ segments in their union;  erasing the fourth segment will lead to $[1, 4]$, $[2, 3]$, $[3, 6]$ remaining, which have $1$ segment in their union.

Thus, you are required to erase the third segment to get answer $2$.

Write a program that will find the maximum number of segments in the union of $n-1$ segments if you erase any of the given $n$ segments.

Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly $n-1$ segments.

-----Input-----

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

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

from sys import stdin
input = stdin.readline
q = int(input())
for rwere in range(q):
	n = int(input())
	seg = []
	pts = []
	for i in range(n):
		pocz, kon = map(int,input().split())
		seg.append([2*pocz, 2*kon])
		pts.append(2*kon+1)
	p,k = map(list,zip(*seg))
	pts += (p + k)
	pts.sort()
	ind = -1
	while True:
		if pts[ind] == pts[-1]:
			ind -= 1
		else:
			break
	ind += 1
	pts = pts[:ind]
	mapa = {}
	val = 0
	mapa[pts[0]] = val
	for i in range(1, len(pts)):
		if pts[i] != pts[i-1]:
			val += 1
		mapa[pts[i]] = val
	val += 1
	for i in range(n):
		seg[i] = [mapa[seg[i][0]], mapa[seg[i][1]]]
	seg.sort()
	dupa = [0] * (val+1)
	for s in seg:
		dupa[s[0]] += 1
		dupa[s[1] + 1] -= 1
	cov = [0] * val
	cov[0] = dupa[0]
	for i in range(1, val):
		cov[i] = cov[i-1] + dupa[i]
	przyn = [0] * val
	cur = seg[0][0]
	label = 1
	for i in range(n):
		kon = seg[i][1]
		if cur <= kon:
			for j in range(cur, kon + 1):
				przyn[j] = label
			label += 1
			cur = kon + 1
	final = [(przyn[i] if cov[i] == 1 else (-1 if cov[i] == 0 else 0)) for i in range(val)]
	baza = final.count(-1) + 1
	final = [-1] + final + [-1]
	val += 2
	if max(final) <= 0:
		print(baza)
	else:
		comp = {}
		comp[0] = -100000000000
		for i in final:
			if i > 0:
				comp[i] = 0
		for i in range(1, val - 1):
			if final[i] > 0 and final[i] != final[i-1]:
				comp[final[i]] += 1
			if final[i-1] == -1:
				comp[final[i]] -= 1
			if final[i+1] == -1:
				comp[final[i]] -= 1
		best = -10000000000000
		for i in comp:
			best = max(best, comp[i])
		if max(final) == n:
			print(baza + best)
		else:
			print(max(baza + best, baza))


I found an interesting problem on https://codeforces.com/problemset/problem/1285/F:
Given an array $a$, consisting of $n$ integers, find:

$$\max\limits_{1 \le i < j \le n} LCM(a_i,a_j),$$

where $LCM(x, y)$ is the smallest positive integer that is divisible by both $x$ and $y$. For example, $LCM(6, 8) = 24$, $LCM(4, 12) = 12$, $LCM(2, 3) = 6$.

-----Input-----

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

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

-----Output-----

Print one integer, the maximum value of the least common multiple of two elements in the array $a$.

-----Examples-----
Input
3
13 35 77

Output
1001
Input
6
1 2 4 8 16 32

Output
32

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

import math
N = 10**5 + 10
u = [-1]*N
divi = [ [] for i in range(N) ]
pd = [ [] for i in range(N) ]
mark = [0]*N

def precalc():
    for i in range(1,N) :
        for j in range(i,N,i) :
            divi[j].append(i)

    for i in range(2,N) :
        if mark[i] == 1 :
            continue
        for j in range(i,N,i) :
            pd[j].append(i)
            mark[j] = 1

    for i in range(1,N) :
        for prm in pd[i] :
            time = 0
            _i = i
            while _i % prm == 0 :
                time += 1
                _i /= prm
            if time > 1 :
                u[i] = 0
                continue
        if u[i] == -1 :
            if len(pd[i]) & 1 :
                u[i] = -1
            else :
                u[i] = 1

has = [False]*N
cnt = [0]*N

def has_coprime(n):
    ret = 0
    for d in divi[n] :
        ret += u[d] * cnt[d]
    return ret

def update(n,val) :
    for d in divi[n] :
        cnt[d] += val

def solve(n) :
    li = list(map(int,input().split()))
    ans = 0
    for i in range(n) :
        if has[li[i]] :
            ans = max(ans,li[i])
        has[li[i]] = True

    for g in range(1,N) :
        st = []
        for num in reversed(list(range(1,N//g + 1))) :
            if num*g > N-1 or not has[num*g]  :
                continue
            how_many = has_coprime(num)

            while how_many > 0 :
                #print(how_many)
                now = st.pop()
                if math.gcd(now,num) == 1 :
                    ans = max(ans,num*now*g)
                    how_many -= 1
                update(now,-1)
            st.append(num)
            update(num,1)
        while st :
            update(st.pop(),-1)

    print(ans)

precalc()

while True :
    try :
        n = int(input())
        solve(n)
    except EOFError:
        break


I found an interesting problem on https://codeforces.com/problemset/problem/1286/A:
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of $n$ light bulbs in a single row. Each bulb has a number from $1$ to $n$ (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.[Image]

Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by $2$). For example, the complexity of 1 4 2 3 5 is $2$ and the complexity of 1 3 5 7 6 4 2 is $1$.

No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 100$) — the number of light bulbs on the garland.

The second line contains $n$ integers $p_1,\ p_2,\ \ldots,\ p_n$ ($0 \le p_i \le n$) — the number on the $i$-th bulb, or $0$ if it was removed.

-----Output-----

Output a single number — the minimum complexity of the garland.

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

Output
2

Input
7
1 0 0 5 0 0 2

Output
1

-----Note-----

In the first example, one should place light bulbs as 1 5 4 2 3. In that case, the complexity would be equal to 2, because only $(5, 4)$ and $(2, 3)$ are the pairs of adjacent bulbs that have different parity.

In the second case, one of the correct answers is 1 7 3 5 6 4 2.

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

import sys
readline = sys.stdin.readline

N = int(readline())
S = list(map(int, readline().split()))
S = [0 if s == 0 else 1 if s & 1 else -1 for s in S]

odd = -(-N//2)
even = N//2
for s in S:
    if s:
        if s == 1:
            odd -= 1
        else:
            even -= 1

inf = 10**9
dpe = [[inf]*(odd+1) for _ in range(even+1)]
dpo = [[inf]*(odd+1) for _ in range(even+1)]
dpe[0][0] = 0
dpo[0][0] = 0

for i in range(N):
    dp2e = [[inf]*(odd+1) for _ in range(even+1)]
    dp2o = [[inf]*(odd+1) for _ in range(even+1)]
    s = S[i]
    for e in range(even+1):
        for o in range(odd+1):
            if s == 1:
                dp2o[e][o] = min(dp2o[e][o], dpo[e][o], 1+dpe[e][o])
            elif s == -1:
                dp2e[e][o] = min(dp2e[e][o], dpe[e][o], 1+dpo[e][o])
            else:
                if o < odd:
                    dp2o[e][o+1] = min(dp2o[e][o+1], dpo[e][o], 1+dpe[e][o])
                if e < even:
                    dp2e[e+1][o] = min(dp2e[e+1][o], dpe[e][o], 1+dpo[e][o])
    dpe = [d[:] for d in dp2e]
    dpo = [d[:] for d in dp2o]

print(min(dpe[even][odd], dpo[even][odd]))


I found an interesting problem on https://codeforces.com/problemset/problem/1287/A:
It's a walking tour day in SIS.Winter, so $t$ groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.

Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":   "A" corresponds to an angry student  "P" corresponds to a patient student

Such string describes the row from the last to the first student.

Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index $i$ in the string describing a group then they will throw a snowball at the student that corresponds to the character with index $i+1$ (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.

[Image]

Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.

Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.

-----Input-----

The first line contains a single integer $t$ — the number of groups of students ($1 \le t \le 100$). The following $2t$ lines contain descriptions of groups of students.

The description of the group starts with an integer $k_i$ ($1 \le k_i \le 100$) — the number of students in the group, followed by a string $s_i$, consisting of $k_i$ letters "A" and "P", which describes the $i$-th group of students.

-----Output-----

For every group output single integer — the last moment a student becomes angry.

-----Examples-----
Input
1
4
PPAP

Output
1

Input
3
12
APPAPPPAPPPP
3
AAP
3
PPA

Output
4
1
0

-----Note-----

In the first test, after $1$ minute the state of...

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

t=int(input())
for i in range(t):
    k=int(input())
    a=input()
    maxlen=0
    cl=-1
    for i in a:

        if i=="A":
            cl=0
        elif cl!=-1:
            cl+=1
            maxlen=max(cl,maxlen)
    print(max(maxlen,0))


I found an interesting problem on https://codeforces.com/problemset/problem/1287/B:
Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.

[Image]

Polina came up with a new game called "Hyperset". In her game, there are $n$ cards with $k$ features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with $k = 4$.

Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.

Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.

-----Input-----

The first line of each test contains two integers $n$ and $k$ ($1 \le n \le 1500$, $1 \le k \le 30$) — number of cards and number of features.

Each of the following $n$ lines contains a card description: a string consisting of $k$ letters "S", "E", "T". The $i$-th character of this string decribes the $i$-th feature of that card. All cards are distinct.

-----Output-----

Output a single integer — the number of ways to choose three cards that form a set.

-----Examples-----
Input
3 3
SET
ETS
TSE

Output
1
Input
3 4
SETE
ETSE
TSES

Output
0
Input
5 4
SETT
TEST
EEET
ESTE
STES

Output
2

-----Note-----

In the third example test, these two triples of cards are sets:  "SETT", "TEST", "EEET"  "TEST", "ESTE", "STES"

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

def calc(a,b):
	if a=="S":
		if b=="E":
			return "T"
		elif b=="S":
			return "S"
		else:
			return "E"
	elif a=="E":
		if b=="E":
			return "E"
		elif b=="S":
			return "T"
		else:
			return "S"
	else:
		if b=="E":
			return "S"
		elif b=="S":
			return "E"
		else:
			return "T"

n,k=map(int,input().split())
d={}
l=[]
done={}
for i in range(n):
	a=input()
	d[a]=1
	l.append(a)
if n<=2:
	print (0)
	return
ans=0
for i in range(n):
	for j in range(i+1,n):
		reqd=""
		for m in range(k):
			reqd+=(calc(l[i][m],l[j][m]))
		if reqd in d:
			#print (l[i],l[j],reqd)
			if (l[i],l[j],reqd) not in done and (l[i],reqd,l[j]) not in done and (l[j],l[i],reqd) not in done and (l[j],reqd,l[i]) not in done and (reqd,l[j],l[i]) not in done and (reqd,l[i],l[j]) not in done:
				done[(l[i],l[j],reqd)]=1
				ans+=1

print (ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1288/A:
Adilbek was assigned to a special project. For Adilbek it means that he has $n$ days to run a special program and provide its results. But there is a problem: the program needs to run for $d$ days to calculate the results.

Fortunately, Adilbek can optimize the program. If he spends $x$ ($x$ is a non-negative integer) days optimizing the program, he will make the program run in $\left\lceil \frac{d}{x + 1} \right\rceil$ days ($\left\lceil a \right\rceil$ is the ceiling function: $\left\lceil 2.4 \right\rceil = 3$, $\left\lceil 2 \right\rceil = 2$). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to $x + \left\lceil \frac{d}{x + 1} \right\rceil$.

Will Adilbek be able to provide the generated results in no more than $n$ days?

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 50$) — the number of test cases.

The next $T$ lines contain test cases – one per line. Each line contains two integers $n$ and $d$ ($1 \le n \le 10^9$, $1 \le d \le 10^9$) — the number of days before the deadline and the number of days the program runs.

-----Output-----

Print $T$ answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in $n$ days or NO (case insensitive) otherwise.

-----Example-----
Input
3
1 1
4 5
5 11

Output
YES
YES
NO

-----Note-----

In the first test case, Adilbek decides not to optimize the program at all, since $d \le n$.

In the second test case, Adilbek can spend $1$ day optimizing the program and it will run $\left\lceil \frac{5}{2} \right\rceil = 3$ days. In total, he will spend $4$ days and will fit in the limit.

In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program $2$ days, it'll still work $\left\lceil \frac{11}{2+1} \right\rceil = 4$ days.

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

import math

def inp(dtype=str, strip=True):
    s = input()
    res = [dtype(p) for p in s.split()]
    res = res[0] if len(res) == 1 and strip else res
    return res

def problem1():
    t = inp(int)
    for _ in range(t):
        n, d = inp(int)
        res = False
        sq = math.floor(math.sqrt(d))
        for x in range(max(sq - 1000, 0), min(sq + 1000, n)):
            if x + math.ceil(d / (x + 1)) <= n:
                res = True
                break
        if res:
            print('YES')
        else:
            print('NO')

def problem2():
    pass

def problem3():
    pass

def problem4():
    pass

def problem5():
    pass

def problem6():
    pass

def __starting_point():
    # problem6()
    # problem5()
    # problem4()
    # problem3()
    # problem2()
    problem1()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1288/B:
You are given two integers $A$ and $B$, calculate the number of pairs $(a, b)$ such that $1 \le a \le A$, $1 \le b \le B$, and the equation $a \cdot b + a + b = conc(a, b)$ is true; $conc(a, b)$ is the concatenation of $a$ and $b$ (for example, $conc(12, 23) = 1223$, $conc(100, 11) = 10011$). $a$ and $b$ should not contain leading zeroes.

-----Input-----

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

Each test case contains two integers $A$ and $B$ $(1 \le A, B \le 10^9)$.

-----Output-----

Print one integer — the number of pairs $(a, b)$ such that $1 \le a \le A$, $1 \le b \le B$, and the equation $a \cdot b + a + b = conc(a, b)$ is true.

-----Example-----
Input
3
1 11
4 2
191 31415926

Output
1
0
1337

-----Note-----

There is only one suitable pair in the first test case: $a = 1$, $b = 9$ ($1 + 9 + 1 \cdot 9 = 19$).

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

t = int(input())

s = [10 ** i - 1 for i in range(1, 18)]

for _ in range(t):
    a, b = map(int, input().split())
    c = 0
    for i in s:
        if i <= b:
            c += 1
        else:
            break
    print(a * c)


I found an interesting problem on https://codeforces.com/problemset/problem/1288/C:
You are given two integers $n$ and $m$. Calculate the number of pairs of arrays $(a, b)$ such that:

  the length of both arrays is equal to $m$;  each element of each array is an integer between $1$ and $n$ (inclusive);  $a_i \le b_i$ for any index $i$ from $1$ to $m$;  array $a$ is sorted in non-descending order;  array $b$ is sorted in non-ascending order.

As the result can be very large, you should print it modulo $10^9+7$.

-----Input-----

The only line contains two integers $n$ and $m$ ($1 \le n \le 1000$, $1 \le m \le 10$).

-----Output-----

Print one integer – the number of arrays $a$ and $b$ satisfying the conditions described above modulo $10^9+7$.

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

Output
5

Input
10 1

Output
55

Input
723 9

Output
157557417

-----Note-----

In the first test there are $5$ suitable arrays:   $a = [1, 1], b = [2, 2]$;  $a = [1, 2], b = [2, 2]$;  $a = [2, 2], b = [2, 2]$;  $a = [1, 1], b = [2, 1]$;  $a = [1, 1], b = [1, 1]$.

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

import sys
readline = sys.stdin.readline

MOD = 10**9+7

N, M = map(int, readline().split())

dp = [0] + [1]*N

for _ in range(2*M):
    dp2 = dp[:]
    for i in range(1, N+1):
        dp2[i] = (dp2[i]+dp2[i-1])%MOD
    dp = dp2[:]
print(dp[N])


I found an interesting problem on https://codeforces.com/problemset/problem/1288/E:
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has $n$ friends, numbered from $1$ to $n$.

Recall that a permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array.

So his recent chat list can be represented with a permutation $p$ of size $n$. $p_1$ is the most recent friend Polycarp talked to, $p_2$ is the second most recent and so on.

Initially, Polycarp's recent chat list $p$ looks like $1, 2, \dots, n$ (in other words, it is an identity permutation).

After that he receives $m$ messages, the $j$-th message comes from the friend $a_j$. And that causes friend $a_j$ to move to the first position in a permutation, shifting everyone between the first position and the current position of $a_j$ by $1$. Note that if the friend $a_j$ is in the first position already then nothing happens.

For example, let the recent chat list be $p = [4, 1, 5, 3, 2]$:   if he gets messaged by friend $3$, then $p$ becomes $[3, 4, 1, 5, 2]$;  if he gets messaged by friend $4$, then $p$ doesn't change $[4, 1, 5, 3, 2]$;  if he gets messaged by friend $2$, then $p$ becomes $[2, 4, 1, 5, 3]$.

For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 3 \cdot 10^5$) — the number of Polycarp's friends and the number of received messages, respectively.

The second line contains $m$ integers $a_1, a_2, \dots, a_m$ ($1 \le a_i \le n$) — the descriptions of the received messages.

-----Output-----

Print $n$ pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.

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

Output
1 3
2 5
1 4
1 5
1 5

Input
4 3
1 2 4

Output
1 3
1 2
3 4
1 4

-----Note-----

In the first example, Polycarp's recent chat...

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

#!usr/bin/env python3
import sys
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
mod = 1000000007

def solve():
    def add(i,x):
        while i < len(bit):
            bit[i] += x
            i += i&-i
    def sum(i):
        res = 0
        while i > 0:
            res += bit[i]
            i -= i&-i
        return res
    n,m = LI()
    a = LI()
    bit = [0]*(n+m+2)
    MIN = [i+1 for i in range(n)]
    MAX = [i+1 for i in range(n)]
    f = [i+m+1 for i in range(n)]
    for i in range(n):
        add(f[i],1)
    M = m
    for i in range(m):
        ai = a[i]-1
        MIN[ai] = 1
        index = sum(f[ai])
        if MAX[ai] < index:
            MAX[ai] = index
        add(M,1)
        add(f[ai],-1)
        f[ai] = M
        M -= 1
    for i in range(n):
        index = sum(f[i])
        if MAX[i] < index:
            MAX[i] = index
    for i in range(n):
        print(MIN[i],MAX[i])
    return

#Solve
def __starting_point():
    solve()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1292/B:
THE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - Perspectives

With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.

The space can be considered a 2D plane, with an infinite number of data nodes, indexed from $0$, with their coordinates defined as follows:  The coordinates of the $0$-th node is $(x_0, y_0)$  For $i > 0$, the coordinates of $i$-th node is $(a_x \cdot x_{i-1} + b_x, a_y \cdot y_{i-1} + b_y)$

Initially Aroma stands at the point $(x_s, y_s)$. She can stay in OS space for at most $t$ seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point $(x_s, y_s)$ to warp home.

While within the OS space, Aroma can do the following actions:  From the point $(x, y)$, Aroma can move to one of the following points: $(x-1, y)$, $(x+1, y)$, $(x, y-1)$ or $(x, y+1)$. This action requires $1$ second.  If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs $0$ seconds. Of course, each data node can be collected at most once.

Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within $t$ seconds?

-----Input-----

The first line contains integers $x_0$, $y_0$, $a_x$, $a_y$, $b_x$, $b_y$ ($1 \leq x_0, y_0 \leq 10^{16}$, $2 \leq a_x, a_y \leq 100$, $0 \leq b_x, b_y \leq 10^{16}$), which define the coordinates of the data nodes.

The second line contains integers $x_s$, $y_s$, $t$ ($1 \leq x_s, y_s, t \leq 10^{16}$) – the initial Aroma's coordinates and the amount of time available.

-----Output-----

Print a single integer — the maximum number of data nodes Aroma can collect within $t$ seconds.

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

Output
3
Input
1 1 2 3 1 0
15 27 26

Output
2
Input
1 1 2 3 1 0
2 2 1

Output
0

-----Note-----

In all three examples, the coordinates of the first $5$ data nodes are $(1, 1)$, $(3, 3)$, $(7,...

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

import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

x0, y0, ax, ay, bx, by = list(map(int, input().split()))
xs, ys, t = list(map(int, input().split()))

p = [(x0, y0)]
d = [0]
m = 100
for i in range(m):
    x,y = p[-1]
    nx = ax*x + bx
    ny = ay*y + by
    nd = abs(nx-x) + abs(ny-y)
    d.append(d[-1]+nd)
    p.append((nx, ny))

ans = 0
for i in range(m):
    x,y = p[i]
    init_d = abs(x-xs) + abs(y-ys)
    if init_d > t:
        continue
    tmp = 1
    rem = t-init_d
    left = -1
    right = i
    while right-left > 1:
        mid = (right+left)//2
        if d[i]-d[mid] <= rem:
            right = mid
        else:
            left = mid
    tmp += i-right
    ans = max(ans, tmp)
    tmp = 1
    left = i
    right = m
    while right-left > 1:
        mid = (right+left)//2
        if d[mid]-d[i] <= rem:
            left = mid
        else:
            right = mid
    tmp += left - i
    ans = max(ans, tmp)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1292/D:
Æsir - CHAOS Æsir - V.

"Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.

The time right now...... 00:01:12......

It's time."

The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.

The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers ($1, 2, 3, \ldots$). The node with a number $x$ ($x > 1$), is directly connected with a node with number $\frac{x}{f(x)}$, with $f(x)$ being the lowest prime divisor of $x$.

Vanessa's mind is divided into $n$ fragments. Due to more than 500 years of coma, the fragments have been scattered: the $i$-th fragment is now located at the node with a number $k_i!$ (a factorial of $k_i$).

To maximize the chance of successful awakening, Ivy decides to place the samples in a node $P$, so that the total length of paths from each fragment to $P$ is smallest possible. If there are multiple fragments located at the same node, the path from that node to $P$ needs to be counted multiple times.

In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.

But for a mere human like you, is this still possible?

For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node $P$.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 10^6$) — number of fragments of Vanessa's mind.

The second line contains $n$ integers: $k_1, k_2, \ldots, k_n$ ($0 \le k_i \le 5000$), denoting the nodes where fragments of Vanessa's mind are located: the $i$-th fragment is at the node with a number $k_i!$.

-----Output-----

Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node $P$).

As a reminder, if there are multiple fragments at the same node, the distance from...

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

from sys import stdin, stdout

prime = list()
factor = list()
count = list()
dist = list()
N = 0

def find_prime():
    nonlocal prime
    for i in range(2, 5010):
        is_prime = True
        for j in prime:
            if i % j == 0:
                is_prime = False
                break
        if is_prime is True:
            prime.append(i)

def calculate_factor(max):
    nonlocal prime
    nonlocal factor
    nonlocal dist
    factor = [[0 for x in range(len(prime))] for y in range(5010)]
    dist = [0] * (max+1)
    d = 0
    for i in range(1, max+1):
        temp = i
        factor[i] = list(factor[i-1])
        for j,x in enumerate(prime):
            while temp % x == 0:
                factor[i][j] +=1
                temp = temp / x
                d += 1
            if temp == 1:
                dist[i] = d
                break

def dynamic_count():
    nonlocal count
    for i in range (1,len(count)):
        count[i] += count[i-1]

def moving(i, left, right, d, current_factor):
    nonlocal count
    nonlocal prime
    nonlocal factor
    nonlocal N
    while (factor[left][i] == factor[right][i]):
        d += ((2 * (count[right] - count[left-1])) - N) * (factor[right][i] - current_factor[i])
        current_factor[i] = factor[right][i]
        i -= 1
        if i < 0:
            return d
    d += ((2 * (count[right] - count[left-1])) - N) * (factor[left][i] - current_factor[i])
    current_factor[i] = factor[left][i]

    temp_left = right
    while temp_left >= left:
        if (factor[temp_left-1][i] != factor[right][i] or temp_left == left ) and count[right] - count[temp_left-1] > int(N/2):
            if (temp_left > left):
                d += ((2 * (count[temp_left-1] - count[left-1]))) * (factor[left][i] - current_factor[i])
            return moving(i, temp_left, right, d, current_factor)
        elif factor[temp_left-1][i] != factor[right][i]:
            i -= 1
            right = temp_left - 1
            if i < 0:
                return d
       ...