I found an interesting problem on https://codeforces.com/problemset/problem/1373/B:
Alica and Bob are playing a game.

Initially they have a binary string $s$ consisting of only characters 0 and 1.

Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string $s$ and delete them. For example, if $s = 1011001$ then the following moves are possible:   delete $s_1$ and $s_2$: $\textbf{10}11001 \rightarrow 11001$;  delete $s_2$ and $s_3$: $1\textbf{01}1001 \rightarrow 11001$;  delete $s_4$ and $s_5$: $101\textbf{10}01 \rightarrow 10101$;  delete $s_6$ and $s_7$: $10110\textbf{01} \rightarrow 10110$.

If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.

-----Input-----

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

Only line of each test case contains one string $s$ ($1 \le |s| \le 100$), consisting of only characters 0 and 1.

-----Output-----

For each test case print answer in the single line.

If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register.

-----Example-----
Input
3
01
1111
0011

Output
DA
NET
NET

-----Note-----

In the first test case after Alice's move string $s$ become empty and Bob can not make any move.

In the second test case Alice can not make any move initially.

In the third test case after Alice's move string $s$ turn into $01$. Then, after Bob's move string $s$ become empty and Alice can not make any move.

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

from sys import exit,stdin,stderr
def rl():
    return [int(w) for w in stdin.readline().split()]

T, = rl()
for _ in range(T):
    s = input().rstrip()
    c0 = len([c for c in s if c == '0'])
    c1 = len([c for c in s if c == '1'])
    print(['NET', 'DA'][min(c0, c1) & 1])


I found an interesting problem on https://codeforces.com/problemset/problem/1373/C:
You are given a string $s$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0

for init = 0 to inf

    cur = init

    ok = true

    for i = 1 to |s|

        res = res + 1

        if s[i] == '+'

            cur = cur + 1

        else

            cur = cur - 1

        if cur < 0

            ok = false

            break

    if ok

        break

Note that the $inf$ denotes infinity, and the characters of the string are numbered from $1$ to $|s|$.

You have to calculate the value of the $res$ after the process ends.

-----Input-----

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

The only lines of each test case contains string $s$ ($1 \le |s| \le 10^6$) consisting only of characters + and -.

It's guaranteed that sum of $|s|$ over all test cases doesn't exceed $10^6$.

-----Output-----

For each test case print one integer — the value of the $res$ after the process ends.

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

Output
7
9
6

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

for _ in range(int(input())):
    ar = list(input())
    kek = 0
    lol = 0
    for i in range(len(ar)):
        if ar[i] == '-':
            kek += 1
        else:
            kek -= 1
        if kek > lol:
            lol = kek
    fifi = [-1] * lol
    cur = 0
    for i in range(len(ar)):
        if ar[i] == '-':
            cur += 1
            if cur > 0 and fifi[cur - 1] == -1:
                fifi[cur - 1] = i + 1
        else:
            cur -= 1
    ans = 0
    for elem in fifi:
        ans += elem
    print(len(ar) + ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1373/D:
You are given an array $a$ consisting of $n$ integers. Indices of the array start from zero (i. e. the first element is $a_0$, the second one is $a_1$, and so on).

You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of $a$ with borders $l$ and $r$ is $a[l; r] = a_l, a_{l + 1}, \dots, a_{r}$.

Your task is to reverse such a subarray that the sum of elements on even positions of the resulting array is maximized (i. e. the sum of elements $a_0, a_2, \dots, a_{2k}$ for integer $k = \lfloor\frac{n-1}{2}\rfloor$ should be maximum possible).

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $a$. The second line of the test case contains $n$ integers $a_0, a_1, \dots, a_{n-1}$ ($1 \le a_i \le 10^9$), where $a_i$ is the $i$-th element of $a$.

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

-----Output-----

For each test case, print the answer on the separate line — the maximum possible sum of elements on even positions after reversing at most one subarray (continuous subsegment) of $a$.

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

Output
26
5
37
5

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

import math
import sys
from itertools import permutations
input = sys.stdin.readline

t=int(input())
for i in range(t):
    n=int(input())
    arr=list(map(int,input().split()))

    ans=0
    for j in range(n):
        if j%2==0:
            ans+=arr[j]

    arr1=[]
    for j in range(1,n,2):
        arr1.append(arr[j]-arr[j-1])

    msf=0
    meh=0
    for j in range(len(arr1)):
        meh+=arr1[j]
        if msf<=meh:
            msf=meh
        if meh<0:
            meh=0
    cur1=ans+msf

    arr2=[]
    for j in range(2,n,2):
        arr2.append(arr[j-1]-arr[j])

    msf=0
    meh=0
    for j in range(len(arr2)):
        meh+=arr2[j]
        if msf<=meh:
            msf=meh
        if meh<0:
            meh=0
    cur2=ans+msf
    # print(cur1,cur2)
    print(max(cur1,cur2))


I found an interesting problem on https://codeforces.com/problemset/problem/1373/E:
Let $f(x)$ be the sum of digits of a decimal number $x$.

Find the smallest non-negative integer $x$ such that $f(x) + f(x + 1) + \dots + f(x + k) = n$.

-----Input-----

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

Each test case consists of one line containing two integers $n$ and $k$ ($1 \le n \le 150$, $0 \le k \le 9$).

-----Output-----

For each test case, print one integer without leading zeroes. If there is no such $x$ that $f(x) + f(x + 1) + \dots + f(x + k) = n$, print $-1$; otherwise, print the minimum $x$ meeting that constraint.

-----Example-----
Input
7
1 0
1 1
42 7
13 7
99 1
99 0
99 2

Output
1
0
4
-1
599998
99999999999
7997

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

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

def get(n, k):
    ans = 0
    for i in range(k+1):
        ans += f(n+i)
    return ans

t = int(input())
for tmp in range(t):
    w, k = map(int, input().split())

    ans = -1
    for last in range(10):
        c9 = 0
        while last + c9 * 9 <= w:
            st = '9' * c9 + str(last)
            stx = int(st)
            h = get(stx, k)
            if h <= w and (w - h) % (k + 1) == 0:
                ost = (w - h) // (k + 1)

                pref = ''
                while ost > 0:
                    if ost >= 9:

                        if len(pref) == 0:
                            pref += '8'
                            ost -= 8
                        else:
                            pref += '9'
                            ost -= 9

                    else:
                        pref += str(ost)
                        break
                pref = pref[::-1]

                s = pref + '9' * c9 + str(last)
                x = int(s)

                if get(x, k) == w:
                    if ans == -1 or x < ans:
                        ans = x

            c9 += 1

    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1373/F:
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and $n$ cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the $i$-th city contains $a_i$ households that require a connection.

The government designed a plan to build $n$ network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the $i$-th network station will provide service only for the $i$-th and the $(i + 1)$-th city (the $n$-th station is connected to the $n$-th and the $1$-st city).

All network stations have capacities: the $i$-th station can provide the connection to at most $b_i$ households.

Now the government asks you to check can the designed stations meet the needs of all cities or not — that is, is it possible to assign each household a network station so that each network station $i$ provides the connection to at most $b_i$ households.

-----Input-----

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

The first line of each test case contains the single integer $n$ ($2 \le n \le 10^6$) — the number of cities and stations.

The second line of each test case contains $n$ integers ($1 \le a_i \le 10^9$) — the number of households in the $i$-th city.

The third line of each test case contains $n$ integers ($1 \le b_i \le 10^9$) — the capacities of the designed stations.

It's guaranteed that the sum of $n$ over test cases doesn't exceed $10^6$.

-----Output-----

For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).

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

Output
YES
YES
NO
YES
YES

-----Note-----

In the first test case:   the first network station can provide $2$ connections to the first city and $1$ connection to the second city;  the...

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

T = int(input())
while T > 0:
    n = int(input())
    households = list(map(int, input().split()))
    stations = list(map(int, input().split()))
    l, r = 0, min(households[0],stations[0])
    ans = False
    while l <= r:
        mid = (l+r)//2
        left = households[0]-mid
        now = stations[0]-mid
        short = False
        for i in range(1,n):
            now = min(now, households[i])
            if now+stations[i] < households[i]:
                r = mid-1
                short = True
                break
            now = now+stations[i]-households[i]
        if short is True:
            continue
        if now >= left:
            ans = True
            break
        l = mid+1
    if ans:
        print('YES')
    else:
        print('NO')

    T -= 1


I found an interesting problem on https://codeforces.com/problemset/problem/1373/G:
You are given a chessboard consisting of $n$ rows and $n$ columns. Rows are numbered from bottom to top from $1$ to $n$. Columns are numbered from left to right from $1$ to $n$. The cell at the intersection of the $x$-th column and the $y$-th row is denoted as $(x, y)$. Furthermore, the $k$-th column is a special column.

Initially, the board is empty. There are $m$ changes to the board. During the $i$-th change one pawn is added or removed from the board. The current board is good if we can move all pawns to the special column by the followings rules:  Pawn in the cell $(x, y)$ can be moved to the cell $(x, y + 1)$, $(x - 1, y + 1)$ or $(x + 1, y + 1)$;  You can make as many such moves as you like;  Pawns can not be moved outside the chessboard;  Each cell can not contain more than one pawn.

The current board may not always be good. To fix it, you can add new rows to the board. New rows are added at the top, i. e. they will have numbers $n+1, n+2, n+3, \dots$.

After each of $m$ changes, print one integer — the minimum number of rows which you have to add to make the board good.

-----Input-----

The first line contains three integers $n$, $k$ and $m$ ($1 \le n, m \le 2 \cdot 10^5; 1 \le k \le n$) — the size of the board, the index of the special column and the number of changes respectively.

Then $m$ lines follow. The $i$-th line contains two integers $x$ and $y$ ($1 \le x, y \le n$) — the index of the column and the index of the row respectively. If there is no pawn in the cell $(x, y)$, then you add a pawn to this cell, otherwise — you remove the pawn from this cell.

-----Output-----

After each change print one integer — the minimum number of rows which you have to add to make the board good.

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

Output
0
1
2
2
1

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

import collections
import math
n, k, m = [int(i) for i in input().split()]
l = math.ceil((math.log(2*n) / math.log(2)))
p = 2 ** l
# print(p)
memo = [0] * (2 * p)
allres = [0] * (2 * p)

exist = set()
for _i in range(m):
    x, y = [int(i) for i in input().split()]
    l = abs(x - k) + y
    index = l + p
    if (x, y) in exist:
        exist.remove((x, y))
        while index != 0:
            memo[index] -= 1
            index = index // 2
    else:
        exist.add((x, y))
        while index != 0:
            memo[index] += 1
            index = index // 2
    index = (l + p) // 2
    allres[l+p] = l + memo[l + p] - 1
    if memo[l + p] == 0:
        allres[l+p] = 0
    while index != 0:
        allres[index] = max(allres[index * 2] + memo[index * 2 + 1], allres[index * 2 + 1])
        index = index // 2
    # print('i', _i + 1, exist, allres, memo)

    print(max(allres[1] - n, 0))


I found an interesting problem on https://codeforces.com/problemset/problem/1374/A:
You are given three integers $x, y$ and $n$. Your task is to find the maximum integer $k$ such that $0 \le k \le n$ that $k \bmod x = y$, where $\bmod$ is modulo operation. Many programming languages use percent operator % to implement it.

In other words, with given $x, y$ and $n$ you need to find the maximum possible integer from $0$ to $n$ that has the remainder $y$ modulo $x$.

You have to answer $t$ independent test cases. It is guaranteed that such $k$ exists for each test case.

-----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 contain test cases.

The only line of the test case contains three integers $x, y$ and $n$ ($2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$).

It can be shown that such $k$ always exists under the given constraints.

-----Output-----

For each test case, print the answer — maximum non-negative integer $k$ such that $0 \le k \le n$ and $k \bmod x = y$. It is guaranteed that the answer always exists.

-----Example-----
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999

Output
12339
0
15
54306
999999995
185
999999998

-----Note-----

In the first test case of the example, the answer is $12339 = 7 \cdot 1762 + 5$ (thus, $12339 \bmod 7 = 5$). It is obvious that there is no greater integer not exceeding $12345$ which has the remainder $5$ modulo $7$.

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

ntest = int(input())
for testcase in range(ntest):
    x, y, n = list(map(int, input().split()))
    t = (n - y) // x * x + y
    print(t)


I found an interesting problem on https://codeforces.com/problemset/problem/1374/B:
You are given an integer $n$. In one move, you can either multiply $n$ by two or divide $n$ by $6$ (if it is divisible by $6$ without the remainder).

Your task is to find the minimum number of moves needed to obtain $1$ from $n$ or determine if it's impossible to do that.

You have to answer $t$ independent test cases.

-----Input-----

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

The only line of the test case contains one integer $n$ ($1 \le n \le 10^9$).

-----Output-----

For each test case, print the answer — the minimum number of moves needed to obtain $1$ from $n$ if it's possible to do that or -1 if it's impossible to obtain $1$ from $n$.

-----Example-----
Input
7
1
2
3
12
12345
15116544
387420489

Output
0
-1
2
-1
-1
12
36

-----Note-----

Consider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $15116544$:

  Divide by $6$ and get $2519424$;  divide by $6$ and get $419904$;  divide by $6$ and get $69984$;  divide by $6$ and get $11664$;  multiply by $2$ and get $23328$;  divide by $6$ and get $3888$;  divide by $6$ and get $648$;  divide by $6$ and get $108$;  multiply by $2$ and get $216$;  divide by $6$ and get $36$;  divide by $6$ and get $6$;  divide by $6$ and get $1$.

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

import sys
input = sys.stdin.readline

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

    TWO=0
    THREE=0

    while n%2==0:
        TWO+=1
        n//=2

    while n%3==0:
        THREE+=1
        n//=3

    if n!=1:
        print(-1)
    else:
        if TWO>THREE:
            print(-1)
        else:
            print(THREE-TWO+THREE)


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

Initially, you have an integer $x = 0$. During one move, you can do one of the following two operations:  Choose exactly one $i$ from $1$ to $n$ and increase $a_i$ by $x$ ($a_i := a_i + x$), then increase $x$ by $1$ ($x := x + 1$).  Just increase $x$ by $1$ ($x := x + 1$).

The first operation can be applied no more than once to each $i$ from $1$ to $n$.

Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by $k$ (the value $k$ is given).

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9$) — the length of $a$ and the required divisior. The second line of the test case 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$.

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

-----Output-----

For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by $k$.

-----Example-----
Input
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8

Output
6
18
0
227
8

-----Note-----

Consider the first test case of the example:  $x=0$, $a = [1, 2, 1, 3]$. Just increase $x$;  $x=1$, $a = [1, 2, 1, 3]$. Add $x$ to the second element and increase $x$;  $x=2$, $a = [1, 3, 1, 3]$. Add $x$ to the third element and increase $x$;  $x=3$, $a = [1, 3, 3, 3]$. Add $x$ to the fourth element and increase $x$;  $x=4$, $a = [1, 3, 3, 6]$. Just increase $x$;  $x=5$, $a = [1, 3, 3, 6]$. Add $x$ to the first element and increase $x$;  $x=6$, $a = [6, 3, 3, 6]$. We obtained the required array.

Note...

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

from collections import deque
import sys
def inp():
    return sys.stdin.readline().strip()
for _ in range(int(inp())):
    n,k=list(map(int,inp().split()))
    a=list(map(int,inp().split()))
    d={}
    f=0
    mx=-1
    for i in a:
        if i%k==0:
            continue
        if i%k not in d:
            d[i%k]=0
        d[i%k]+=1
        if f<d[i%k]:
            f=d[i%k]
            mx=i%k
        elif f==d[i%k]:
            mx=min(mx,i%k)
    if mx==-1:
        print(0)
        continue
    print((f-1)*k+(k-mx)+1)


I found an interesting problem on https://codeforces.com/problemset/problem/1374/E1:
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.

Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster.

There are $n$ books in the family library. The $i$-th book is described by three integers: $t_i$ — the amount of time Alice and Bob need to spend to read it, $a_i$ (equals $1$ if Alice likes the $i$-th book and $0$ if not), and $b_i$ (equals $1$ if Bob likes the $i$-th book and $0$ if not).

So they need to choose some books from the given $n$ books in such a way that:

  Alice likes at least $k$ books from the chosen set and Bob likes at least $k$ books from the chosen set;  the total reading time of these books is minimized (they are children and want to play and joy as soon a possible).

The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of $t_i$ over all books that are in the chosen set.

Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$).

The next $n$ lines contain descriptions of books, one description per line: the $i$-th line contains three integers $t_i$, $a_i$ and $b_i$ ($1 \le t_i \le 10^4$, $0 \le a_i, b_i \le 1$), where:

  $t_i$ — the amount of time required for reading the $i$-th book;  $a_i$ equals $1$ if Alice likes the $i$-th book and $0$ otherwise;  $b_i$ equals $1$ if Bob likes the $i$-th book and $0$ otherwise.

-----Output-----

If there is no solution, print only one integer -1. Otherwise print one integer $T$ — the minimum total reading time of the suitable set of books.

-----Examples-----
Input
8 4
7 1 1
2 1 1
4 0 1
8 1 1
1 0 1
1 1 1
1...

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

import sys
n,k=map(int,input().split())
bothlike=[]
alike=[]
blike=[]
for i in range(n):
  t,a,b=map(int,input().split())
  if a==1 and b==1:
    bothlike.append(t)
  if a==1 and b==0:
    alike.append(t)
  if a==0 and b==1:
    blike.append(t)
if len(alike)+len(bothlike)<k or len(blike)+len(bothlike)<k:
  print(-1)
  return
alike.sort()
blike.sort()
bothlike.sort()
asum=[0]
current=0
for i in range(len(alike)):
  current+=alike[i]
  asum.append(current)
bsum=[0]
current=0
for i in range(len(blike)):
  current+=blike[i]
  bsum.append(current)
bothcurrent=0
ans=10**18
alen=len(alike)
blen=len(blike)
bothlen=len(bothlike)
for i in range(bothlen+1):
  if i>0:
    bothcurrent+=bothlike[i-1]
  if i>k:
    break

  if k-i>alen or k-i>blen:
    continue
  ans=min(ans,asum[k-i]+bsum[k-i]+bothcurrent)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1374/E2:
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.

Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read exactly $m$ books before all entertainments. Alice and Bob will read each book together to end this exercise faster.

There are $n$ books in the family library. The $i$-th book is described by three integers: $t_i$ — the amount of time Alice and Bob need to spend to read it, $a_i$ (equals $1$ if Alice likes the $i$-th book and $0$ if not), and $b_i$ (equals $1$ if Bob likes the $i$-th book and $0$ if not).

So they need to choose exactly $m$ books from the given $n$ books in such a way that:  Alice likes at least $k$ books from the chosen set and Bob likes at least $k$ books from the chosen set;  the total reading time of these $m$ books is minimized (they are children and want to play and joy as soon a possible).

The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of $t_i$ over all books that are in the chosen set.

Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.

-----Input-----

The first line of the input contains three integers $n$, $m$ and $k$ ($1 \le k \le m \le n \le 2 \cdot 10^5$).

The next $n$ lines contain descriptions of books, one description per line: the $i$-th line contains three integers $t_i$, $a_i$ and $b_i$ ($1 \le t_i \le 10^4$, $0 \le a_i, b_i \le 1$), where:  $t_i$ — the amount of time required for reading the $i$-th book;  $a_i$ equals $1$ if Alice likes the $i$-th book and $0$ otherwise;  $b_i$ equals $1$ if Bob likes the $i$-th book and $0$ otherwise.

-----Output-----

If there is no solution, print only one integer -1.

If the solution exists, print $T$ in the first line — the minimum total reading time of the suitable set of books. In the second line print $m$...

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

# input = raw_input
# range = xrange
import sys
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0

seg = [0]*200000

def offset(x):
	return x + 100000
def encode(x, y):
	return x*200002 + y
def decode(x):
	return x//200002, x%200002

def upd(node, L, R, pos, val):
	while L < R:
		seg[node] += val
		seg[offset(node)] += val*pos
		if L+1 == R:
			break

		M = (L+R)//2
		node <<= 1
		if pos < M:
			R = M
		else:
			L = M
			node += 1

def query(node, L, R, k):
	ret = 0
	while L < R:
		if k == 0:
			return ret
		if seg[node] == k:
			return ret + seg[offset(node)]
		if L+1 == R:
			return ret + k*L

		M = (L+R)//2
		node <<= 1
		if seg[node] >= k:
			R = M
		else:
			ret += seg[offset(node)]
			k -= seg[node]
			L = M
			node += 1

	return ret

n, m, k = inp[ii:ii+3]; ii += 3
A, B, both, neither = [], [], [], []
for i in range(n):
	t, a, b = inp[ii:ii+3]; ii += 3
	if a == 0 and b == 0:
		neither.append(encode(t, i+1))
	if a == 1 and b == 0:
		A.append(encode(t, i+1))
	if a == 0 and b == 1:
		B.append(encode(t, i+1))
	if a == 1 and b == 1:
		both.append(encode(t, i+1))
	upd(1, 0, 10001, t, 1)

A.sort(); B.sort(); both.sort()
p1 = min(k, len(both))
p2 = k - p1
if 2*k - p1 > m or p2 > min(len(A), len(B)):
	print(-1)
	return

sum, ans, ch = 0, 2**31, p1
for i in range(p1):
	sum += both[i]//200002
	upd(1, 0, 10001, both[i]//200002, -1)
for i in range(p2):
	sum += A[i]//200002 + B[i]//200002
	upd(1, 0, 10001, A[i]//200002, -1)
	upd(1, 0, 10001, B[i]//200002, -1)

ans = query(1, 0, 10001, m-2*k+p1) + sum

while p1 > 0:
	if p2 == min(len(A), len(B)):
		break
	upd(1, 0, 10001, A[p2]//200002, -1); sum += A[p2]//200002
	upd(1, 0, 10001, B[p2]//200002, -1); sum += B[p2]//200002
	upd(1, 0, 10001, both[p1-1]//200002, 1); sum -= both[p1-1]//200002
	p2 += 1
	p1 -= 1
	if m - 2*k + p1 < 0:
		break
	Q = query(1, 0, 10001, m-2*k+p1)
	if ans > sum + Q:
		ans = sum + Q
		ch = p1

print(ans)
ind = [both[i]%200002 for i in range(ch)] + [A[i]%200002 for i in range(k-ch)] + [B[i]%200002 for i in range(k-ch)]
st = neither +...


I found an interesting problem on https://codeforces.com/problemset/problem/1375/E:
Madeline has an array $a$ of $n$ integers. A pair $(u, v)$ of integers forms an inversion in $a$ if:

  $1 \le u < v \le n$.  $a_u > a_v$.

Madeline recently found a magical paper, which allows her to write two indices $u$ and $v$ and swap the values $a_u$ and $a_v$. Being bored, she decided to write a list of pairs $(u_i, v_i)$ with the following conditions:

  all the pairs in the list are distinct and form an inversion in $a$.  all the pairs that form an inversion in $a$ are in the list.  Starting from the given array, if you swap the values at indices $u_1$ and $v_1$, then the values at indices $u_2$ and $v_2$ and so on, then after all pairs are processed, the array $a$ will be sorted in non-decreasing order.

Construct such a list or determine that no such list exists. If there are multiple possible answers, you may find any of them.

-----Input-----

The first line of the input contains a single integer $n$ ($1 \le n \le 1000$) — the length of the array.

Next line contains $n$ integers $a_1,a_2,...,a_n$ $(1 \le a_i \le 10^9)$  — elements of the array.

-----Output-----

Print -1 if no such list exists. Otherwise in the first line you should print a single integer $m$ ($0 \le m \le \dfrac{n(n-1)}{2}$) — number of pairs in the list.

The $i$-th of the following $m$ lines should contain two integers $u_i, v_i$ ($1 \le u_i < v_i\le n$).

If there are multiple possible answers, you may find any of them.

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

Output
2
1 3
1 2

Input
4
1 8 1 6

Output
2
2 4
2 3

Input
5
1 1 1 2 2

Output
0

-----Note-----

In the first sample test case the array will change in this order $[3,1,2] \rightarrow [2,1,3] \rightarrow [1,2,3]$.

In the second sample test case it will be $[1,8,1,6] \rightarrow [1,6,1,8] \rightarrow [1,1,6,8]$.

In the third sample test case the array is already sorted.

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

n = int(input())
a = list(map(int,input().split()))
inv = []
for i in range(1,n):
	for j in range(i):
		if a[i] < a[j]:inv.append((i,-a[j],-j))
inv.sort(reverse=True)
r = list(range(len(inv)))
if r is not None:
	print(len(r))
	for z in r:v, _, u = inv[z];u = -u;print(u+1,v+1)
else:
	print("wut")


I found an interesting problem on https://codeforces.com/problemset/problem/1375/G:
You are given a tree with $n$ vertices. You are allowed to modify the structure of the tree through the following multi-step operation:  Choose three vertices $a$, $b$, and $c$ such that $b$ is adjacent to both $a$ and $c$.  For every vertex $d$ other than $b$ that is adjacent to $a$, remove the edge connecting $d$ and $a$ and add the edge connecting $d$ and $c$.  Delete the edge connecting $a$ and $b$ and add the edge connecting $a$ and $c$.

As an example, consider the following tree: [Image]

The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices $2$, $4$, and $5$: [Image]

It can be proven that after each operation, the resulting graph is still a tree.

Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree $n - 1$, called its center, and $n - 1$ vertices of degree $1$.

-----Input-----

The first line contains an integer $n$ ($3 \le n \le 2 \cdot 10^5$)  — the number of vertices in the tree.

The $i$-th of the following $n - 1$ lines contains two integers $u_i$ and $v_i$ ($1 \le u_i, v_i \le n$, $u_i \neq v_i$) denoting that there exists an edge connecting vertices $u_i$ and $v_i$. It is guaranteed that the given edges form a tree.

-----Output-----

Print a single integer  — the minimum number of operations needed to transform the tree into a star.

It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most $10^{18}$ operations.

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

Output
1

Input
4
2 4
4 1
3 4

Output
0

-----Note-----

The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex $5$ by applying a single operation to vertices $2$, $4$, and $5$.

In the second test case, the given tree is already a star with the center at vertex $4$, so no operations have to be performed.

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

import sys

sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

n=II()
to=[[] for _ in range(n)]
for _ in range(n-1):
    u,v=MI1()
    to[u].append(v)
    to[v].append(u)
dp=[0]*n
ch=[0]*n
stack=[(0,-1)]
first=[True]*n
while stack:
    u,pu=stack.pop()
    if first[u]:
        first[u]=False
        stack.append((u,pu))
        for v in to[u]:
            if v==pu:continue
            stack.append((v,u))
    else:
        for v in to[u]:
            if v==pu:continue
            ch[u]+=1+dp[v]
            dp[u]+=ch[v]
#print(dp)
#print(ch)

stack=[(0,-1)]
while stack:
    u,pu=stack.pop()
    for v in to[u]:
        if v==pu:continue
        dpvu=dp[u]-ch[v]
        chvu=ch[u]-dp[v]-1
        dp[v]+=chvu
        ch[v]+=dpvu+1
        stack.append((v,u))
#print(dp)
#print(ch)

print(min(dp))


I found an interesting problem on https://codeforces.com/problemset/problem/1379/C:
Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her exactly $n$ flowers.

Vladimir went to a flower shop, and he was amazed to see that there are $m$ types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers to maximize the happiness of his wife. He knows that after receiving the first flower of the $i$-th type happiness of his wife increases by $a_i$ and after receiving each consecutive flower of this type her happiness increases by $b_i$. That is, if among the chosen flowers there are $x_i > 0$ flowers of type $i$, his wife gets $a_i + (x_i - 1) \cdot b_i$ additional happiness (and if there are no flowers of type $i$, she gets nothing for this particular type).

Please help Vladimir to choose exactly $n$ flowers to maximize the total happiness of his wife.

-----Input-----

The first line contains the only integer $t$ ($1 \leq t \leq 10\,000$), the number of test cases. It is followed by $t$ descriptions of the test cases.

Each test case description starts with two integers $n$ and $m$ ($1 \le n \le 10^9$, $1 \le m \le 100\,000$), the number of flowers Vladimir needs to choose and the number of types of available flowers.

The following $m$ lines describe the types of flowers: each line contains integers $a_i$ and $b_i$ ($0 \le a_i, b_i \le 10^9$) for $i$-th available type of flowers.

The test cases are separated by a blank line. It is guaranteed that the sum of values $m$ among all test cases does not exceed $100\,000$.

-----Output-----

For each test case output a single integer: the maximum total happiness of Vladimir's wife after choosing exactly $n$ flowers optimally.

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

5 3
5 2
4 2
3 1

Output
14
16

-----Note-----

In the first example case Vladimir can pick 1 flower of the first type and 3 flowers of the second type, in this case the total happiness equals $5 + (1 + 2 \cdot 4) = 14$.

In the second example Vladimir can pick 2 flowers of...

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

import sys
input = sys.stdin.readline
for f in range(int(input())):
    n,m=map(int,input().split())
    a=[0]*m
    b=[0]*m
    acop=[0]*m
    bcop=[0]*m
    for i in range(m):
        a[i],b[i]=map(int,input().split())
        acop[i]=a[i]
        bcop[i]=[b[i],i]
    acop.sort(reverse=True)
    bcop.sort(reverse=True)
    mx=0
    i=0
    su=0
    for j in range(m):
        bi=bcop[j][0]
        ii=bcop[j][1]
        ai=a[ii]
        while i<m and acop[i]>bi:
            su+=acop[i]
            i+=1
        maxi=ai
        if i<n:
            maxi+=su
            if i+1<n:
                maxi+=(n-i-1)*bi
            if ai>bi:
                maxi+=bi
                maxi-=ai
            mx=max(maxi,mx)
    if n<=m:
        sun=0
        for i in range(n):
            sun+=acop[i]
        mx=max(mx,sun)
    print(mx)
    blank=input()


I found an interesting problem on https://codeforces.com/problemset/problem/1379/D:
There are many freight trains departing from Kirnes planet every day. One day on that planet consists of $h$ hours, and each hour consists of $m$ minutes, where $m$ is an even number. Currently, there are $n$ freight trains, and they depart every day at the same time: $i$-th train departs at $h_i$ hours and $m_i$ minutes.

The government decided to add passenger trams as well: they plan to add a regular tram service with half-hour intervals. It means that the first tram of the day must depart at $0$ hours and $t$ minutes, where $0 \le t < {m \over 2}$, the second tram departs $m \over 2$ minutes after the first one and so on. This schedule allows exactly two passenger trams per hour, which is a great improvement.

To allow passengers to board the tram safely, the tram must arrive $k$ minutes before. During the time when passengers are boarding the tram, no freight train can depart from the planet. However, freight trains are allowed to depart at the very moment when the boarding starts, as well as at the moment when the passenger tram departs. Note that, if the first passenger tram departs at $0$ hours and $t$ minutes, where $t < k$, then the freight trains can not depart during the last $k - t$ minutes of the day.

 $O$ A schematic picture of the correct way to run passenger trams. Here $h=2$ (therefore, the number of passenger trams is $2h=4$), the number of freight trains is $n=6$. The passenger trams are marked in red (note that the spaces between them are the same). The freight trains are marked in blue. Time segments of length $k$ before each passenger tram are highlighted in red. Note that there are no freight trains inside these segments.

Unfortunately, it might not be possible to satisfy the requirements of the government without canceling some of the freight trains. Please help the government find the optimal value of $t$ to minimize the number of canceled freight trains in case all passenger trams depart according to schedule.

-----Input-----

The first line of input contains four integers $n$,...

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

import sys
import re

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

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	n, h, m, k = mints()
	m //= 2
	a = [0]*n
	e = [None]*(2*n+2)
	c = 0
	for i in range(n):
		hh, mm = mints()
		x = mm % m
		a[i] = mm
		e[2*i] = ((x+k)%m, -1, i)
		e[2*i+1] = ((x+1)%m, 1, i)
		if (x+1)%m > (x+k)%m:
			c += 1
	e[2*n] = (0,0,0)
	e[2*n+1] = (m-1,0,0)
	#print(e)
	e.sort()
	p = -1
	r = (int(1e9),0)
	#print(e)
	for x, t, id in e:
		#print(x,t,id,c)
		if p != x and p != -1:
			r = min(r, (c, p))
		p = x
		c += t
	r = min(r, (c, p))
	print(*r)
	p = r[1]
	for i in range(n):
		mm = a[i]
		x = (mm-p) % m
		if (x+1)%m > (x+k)%m and (x+k)%m != 0 \
		or (x+1)%m < (x+k)%m and (x+1)%m == 0:
			print(i+1,end=' ')

#for i in range(mint()):
solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1380/D:
There are $n$ warriors in a row. The power of the $i$-th warrior is $a_i$. All powers are pairwise distinct.

You have two types of spells which you may cast:   Fireball: you spend $x$ mana and destroy exactly $k$ consecutive warriors;  Berserk: you spend $y$ mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power.

For example, let the powers of warriors be $[2, 3, 7, 8, 11, 5, 4]$, and $k = 3$. If you cast Berserk on warriors with powers $8$ and $11$, the resulting sequence of powers becomes $[2, 3, 7, 11, 5, 4]$. Then, for example, if you cast Fireball on consecutive warriors with powers $[7, 11, 5]$, the resulting sequence of powers becomes $[2, 3, 4]$.

You want to turn the current sequence of warriors powers $a_1, a_2, \dots, a_n$ into $b_1, b_2, \dots, b_m$. Calculate the minimum amount of mana you need to spend on it.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the length of sequence $a$ and the length of sequence $b$ respectively.

The second line contains three integers $x, k, y$ ($1 \le x, y, \le 10^9; 1 \le k \le n$) — the cost of fireball, the range of fireball and the cost of berserk respectively.

The third line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$). It is guaranteed that all integers $a_i$ are pairwise distinct.

The fourth line contains $m$ integers $b_1, b_2, \dots, b_m$ ($1 \le b_i \le n$). It is guaranteed that all integers $b_i$ are pairwise distinct.

-----Output-----

Print the minimum amount of mana for turning the sequnce $a_1, a_2, \dots, a_n$ into $b_1, b_2, \dots, b_m$, or $-1$ if it is impossible.

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

Output
8

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

Output
-1

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

Output
0

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

__MULTITEST = False

## solve
def isSubseq(a, b):
    ptr = 0
    lenB = len(b)
    for x in a:
        if b[ptr] == x:
            ptr += 1
            if ptr == lenB:
                return True
    return False

def solve():
    n, m = map(int, input().split())
    x, k, y = map(int, input().split())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))

    ## check
    if not isSubseq(a, b):
        print(-1)
    else:
        a.insert(0, -1); a.append(-2);
        b.insert(0, -1); b.append(-2);

        lenA = len(a)
        lenB = len(b)

        #print(a, b)

        ans = 0

        pa1 = 0; pa2 = 1;
        pb = 0;
        while pb + 1 < lenB:
            ## find surrounded seg in a that has border is b[pb] and b[pb+1]
            maxOfSeg = -3

            #print(pb, pa1, pa2)

            while a[pa1] != b[pb]:
                pa1 += 1
            pa2 = pa1 + 1
            while a[pa2] != b[pb+1]:
                maxOfSeg = max(maxOfSeg, a[pa2])
                pa2 += 1

            ## solve that seg
            segLen = pa2 - pa1 - 1
            if segLen >= k:
                if x > y * k:
                    if a[pa1] < maxOfSeg and a[pa2] < maxOfSeg:
                        ans += (x + (segLen - k) * y)
                    else:
                        ans += (segLen * y)
                else:
                    ans += (segLen // k) * x + (segLen % k) * y
            else:
                if a[pa1] < maxOfSeg and a[pa2] < maxOfSeg:
                    print(-1)
                    return
                else:
                    ans += segLen * y

            ## after solve, increment pointers
            pb += 1
            pa1 = pa2
        print(ans)

## main
def __starting_point():
    t = (int(input()) if __MULTITEST else 1)
    for tt in range(t):
        try:
            solve();
        except IndexError:
            print("-1")
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1380/E:
You have a set of $n$ discs, the $i$-th disc has radius $i$. Initially, these discs are split among $m$ towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top.

You would like to assemble one tower containing all of those discs. To do so, you may choose two different towers $i$ and $j$ (each containing at least one disc), take several (possibly all) top discs from the tower $i$ and put them on top of the tower $j$ in the same order, as long as the top disc of tower $j$ is bigger than each of the discs you move. You may perform this operation any number of times.

For example, if you have two towers containing discs $[6, 4, 2, 1]$ and $[8, 7, 5, 3]$ (in order from bottom to top), there are only two possible operations:

  move disc $1$ from the first tower to the second tower, so the towers are $[6, 4, 2]$ and $[8, 7, 5, 3, 1]$;  move discs $[2, 1]$ from the first tower to the second tower, so the towers are $[6, 4]$ and $[8, 7, 5, 3, 2, 1]$.

Let the difficulty of some set of towers be the minimum number of operations required to assemble one tower containing all of the discs. For example, the difficulty of the set of towers $[[3, 1], [2]]$ is $2$: you may move the disc $1$ to the second tower, and then move both discs from the second tower to the first tower.

You are given $m - 1$ queries. Each query is denoted by two numbers $a_i$ and $b_i$, and means "merge the towers $a_i$ and $b_i$" (that is, take all discs from these two towers and assemble a new tower containing all of them in descending order of their radii from top to bottom). The resulting tower gets index $a_i$.

For each $k \in [0, m - 1]$, calculate the difficulty of the set of towers after the first $k$ queries are performed.

-----Input-----

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

The second line contains $n$ integers $t_1$, $t_2$, ...,...

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

import sys
input = sys.stdin.readline
n,m = map(int,input().split())
a = list(map(int,input().split()))
s = [set() for i in range(m+1)]
u = [-1]*(m+1)

for i in range(n):
    s[a[i]].add(i+1)

def find(x):
    if u[x] <= 0:
        return x
    else:
        u[x] = find(u[x])
        return u[x]

count = 0
for i in range(n-1):
    if a[i] != a[i+1]:
        count += 1
ans = [count]

for i in range(1,m):
    x,y = map(int,input().split())
    x = find(x)
    y = find(y)
    if len(s[x]) < len(s[y]):
        x,y = y,x
    for j in s[y]:
        if j-1 in s[x]:
            count -= 1
        if j+1 in s[x]:
            count -= 1
    ans.append(count)
    s[x] |= s[y]
    u[y] = x

for i in ans:
    print(i)


I found an interesting problem on https://codeforces.com/problemset/problem/1380/G:
You are creating a level for a video game. The level consists of $n$ rooms placed in a circle. The rooms are numbered $1$ through $n$. Each room contains exactly one exit: completing the $j$-th room allows you to go the $(j+1)$-th room (and completing the $n$-th room allows you to go the $1$-st room).

You are given the description of the multiset of $n$ chests: the $i$-th chest has treasure value $c_i$.

Each chest can be of one of two types:   regular chest — when a player enters a room with this chest, he grabs the treasure and proceeds to the next room;  mimic chest — when a player enters a room with this chest, the chest eats him alive, and he loses.

The player starts in a random room with each room having an equal probability of being chosen. The players earnings is equal to the total value of treasure chests he'd collected before he lost.

You are allowed to choose the order the chests go into the rooms. For each $k$ from $1$ to $n$ place the chests into the rooms in such a way that:

  each room contains exactly one chest;  exactly $k$ chests are mimics;  the expected value of players earnings is minimum possible.

Please note that for each $k$ the placement is chosen independently.

It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$. Report the values of $P \cdot Q^{-1} \pmod {998244353}$.

-----Input-----

The first contains a single integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the number of rooms and the number of chests.

The second line contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le 10^6$) — the treasure values of each chest.

-----Output-----

Print $n$ integers — the $k$ -th value should be equal to the minimum possible expected value of players earnings if the chests are placed into the rooms in some order and exactly $k$ of the chests are mimics.

It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$. Report the values of $P \cdot Q^{-1} \pmod...

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

from sys import stdin

def inverse(a,mod):
    return pow(a,mod-2,mod)

n = int(stdin.readline())
c = list(map(int,stdin.readline().split()))

mod = 998244353
c.sort()
d = [0]
for i in range(n):
    d.append(d[-1] + c[i])

inv = inverse( n , mod )
ans = []

for k in range(1,n+1):

    now = 0

    ni = n-k
    cnt = 1
    while ni > k:
        now += cnt * (d[ni]-d[ni-k])
        cnt += 1
        ni -= k
    now += cnt * d[ni]
    ans.append(now * inv % mod)

print (*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1382/A:
You are given two arrays of integers $a_1,\ldots,a_n$ and $b_1,\ldots,b_m$.

Your task is to find a non-empty array $c_1,\ldots,c_k$ that is a subsequence of $a_1,\ldots,a_n$, and also a subsequence of $b_1,\ldots,b_m$. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.

A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero) elements. For example, $[3,1]$ is a subsequence of $[3,2,1]$ and $[4,3,1]$, but not a subsequence of $[1,3,3,7]$ and $[3,10,4]$.

-----Input-----

The first line contains a single integer $t$ ($1\le t\le 1000$)  — the number of test cases. Next $3t$ lines contain descriptions of test cases.

The first line of each test case contains two integers $n$ and $m$ ($1\le n,m\le 1000$)  — the lengths of the two arrays.

The second line of each test case contains $n$ integers $a_1,\ldots,a_n$ ($1\le a_i\le 1000$)  — the elements of the first array.

The third line of each test case contains $m$ integers $b_1,\ldots,b_m$ ($1\le b_i\le 1000$)  — the elements of the second array.

It is guaranteed that the sum of $n$ and the sum of $m$ across all test cases does not exceed $1000$ ($\sum\limits_{i=1}^t n_i, \sum\limits_{i=1}^t m_i\le 1000$).

-----Output-----

For each test case, output "YES" if a solution exists, or "NO" otherwise.

If the answer is "YES", on the next line output an integer $k$ ($1\le k\le 1000$)  — the length of the array, followed by $k$ integers $c_1,\ldots,c_k$ ($1\le c_i\le 1000$)  — the elements of the array.

If there are multiple solutions with the smallest possible $k$, output any.

-----Example-----
Input
5
4 5
10 8 6 4
1 2 3 4 5
1 1
3
3
1 1
3
2
5 3
1000 2 2 2 3
3 1 5
5 5
1 2 3 4 5
1 2 3 4 5

Output
YES
1 4
YES
1 3
NO
YES
1 3
YES
1 2

-----Note-----

In the first test case, $[4]$ is a subsequence of $[10, 8, 6, 4]$ and $[1, 2, 3, 4, 5]$. This array has...

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

import random

def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)

def lcm(a, b):
    return (a * b) / gcd(a, b)

for _ in range(int(input())):
    n,m=list(map(int,input().split()))
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    f=-1
    a.sort()
    b.sort()
    d={}
    for i in a:
        d[i]=1
    for i in b:
        if i in d:
            f=i
    if (f==-1):
        print('NO')
    else:
        print('YES')
        print(1,f)


I found an interesting problem on https://codeforces.com/problemset/problem/1382/B:
There are $n$ piles of stones, where the $i$-th pile has $a_i$ stones. Two people play a game, where they take alternating turns removing stones.

In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game.

-----Input-----

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

The first line of each test case contains a single integer $n$ ($1\le n\le 10^5$)  — the number of piles.

The second line of each test case contains $n$ integers $a_1,\ldots,a_n$ ($1\le a_i\le 10^9$)  — $a_i$ is equal to the number of stones in the $i$-th pile.

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

-----Output-----

For each test case, if the player who makes the first move will win, output "First". Otherwise, output "Second".

-----Example-----
Input
7
3
2 5 4
8
1 1 1 1 1 1 1 1
6
1 2 3 4 5 6
6
1 1 2 1 2 2
1
1000000000
5
1 2 2 1 1
3
1 1 1

Output
First
Second
Second
First
First
Second
First

-----Note-----

In the first test case, the first player will win the game. His winning strategy is:   The first player should take the stones from the first pile. He will take $1$ stone. The numbers of stones in piles will be $[1, 5, 4]$.  The second player should take the stones from the first pile. He will take $1$ stone because he can't take any other number of stones. The numbers of stones in piles will be $[0, 5, 4]$.  The first player should take the stones from the second pile because the first pile is empty. He will take $4$ stones. The numbers of stones in piles will be $[0, 1, 4]$.  The second player should take the stones from the second pile because the first pile is empty. He will take $1$ stone because he can't take any other number of stones. The...

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

import sys
input=sys.stdin.readline
t=int(input())
for _ in range(t):
    n=int(input())
    arr=list(map(int,input().split()))
    ones=0
    for i in arr:
        if i==1:
            ones+=1
        else:
            break
    if(ones<n):
        if(ones%2==0):
            print("First")
        else:
            print("Second")
    else:
        if(ones%2==1):
            print("First")
        else:
            print("Second")


I found an interesting problem on https://codeforces.com/problemset/problem/1384/A:
The length of the longest common prefix of two strings $s = s_1 s_2 \ldots s_n$ and $t = t_1 t_2 \ldots t_m$ is defined as the maximum integer $k$ ($0 \le k \le min(n,m)$) such that $s_1 s_2 \ldots s_k$ equals $t_1 t_2 \ldots t_k$.

Koa the Koala initially has $n+1$ strings $s_1, s_2, \dots, s_{n+1}$.

For each $i$ ($1 \le i \le n$) she calculated $a_i$ — the length of the longest common prefix of $s_i$ and $s_{i+1}$.

Several days later Koa found these numbers, but she couldn't remember the strings.

So Koa would like to find some strings $s_1, s_2, \dots, s_{n+1}$ which would have generated numbers $a_1, a_2, \dots, a_n$. Can you help her?

If there are many answers print any. We can show that answer always exists for the given constraints.

-----Input-----

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

The first line of each test case contains a single integer $n$ ($1 \le n \le 100$) — the number of elements in the list $a$.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 50$) — the elements of $a$.

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

-----Output-----

For each test case:

Output $n+1$ lines. In the $i$-th line print string $s_i$ ($1 \le |s_i| \le 200$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $s_i$ and $s_{i+1}$ has to be equal to $a_i$.

If there are many answers print any. We can show that answer always exists for the given constraints.

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

Output
aeren
ari
arousal
around
ari
monogon
monogamy
monthly
kevinvu
kuroni
kurioni
korone
anton
loves
adhoc
problems

-----Note-----

In the $1$-st test case one of the possible answers is $s = [aeren, ari, arousal, around, ari]$.

Lengths of longest common prefixes are:  Between $\color{red}{a}eren$ and $\color{red}{a}ri$ $\rightarrow 1$  Between...

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

for _ in range(int(input())):
    _ = int(input())
    *arr, = list(map(int, input().split()))
    max_len = max(arr) + 1
    ans = ['a'] * max_len
    print(''.join(ans))
    for n in arr:
        if ans[n] == 'a':
            ans[n] = 'b'
        else:
            ans[n] = 'a'
        print(''.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1384/B1:
The only difference between easy and hard versions is on constraints. In this version constraints are lower. You can make hacks only if all versions of the problem are solved.

Koa the Koala is at the beach!

The beach consists (from left to right) of a shore, $n+1$ meters of sea and an island at $n+1$ meters from the shore.

She measured the depth of the sea at $1, 2, \dots, n$ meters from the shore and saved them in array $d$. $d_i$ denotes the depth of the sea at $i$ meters from the shore for $1 \le i \le n$.

Like any beach this one has tide, the intensity of the tide is measured by parameter $k$ and affects all depths from the beginning at time $t=0$ in the following way:

  For a total of $k$ seconds, each second, tide increases all depths by $1$.

  Then, for a total of $k$ seconds, each second, tide decreases all depths by $1$.

  This process repeats again and again (ie. depths increase for $k$ seconds then decrease for $k$ seconds and so on ...).

Formally, let's define $0$-indexed array $p = [0, 1, 2, \ldots, k - 2, k - 1, k, k - 1, k - 2, \ldots, 2, 1]$ of length $2k$. At time $t$ ($0 \le t$) depth at $i$ meters from the shore equals $d_i + p[t \bmod 2k]$ ($t \bmod 2k$ denotes the remainder of the division of $t$ by $2k$). Note that the changes occur instantaneously after each second, see the notes for better understanding.

At time $t=0$ Koa is standing at the shore and wants to get to the island. Suppose that at some time $t$ ($0 \le t$) she is at $x$ ($0 \le x \le n$) meters from the shore:

  In one second Koa can swim $1$ meter further from the shore ($x$ changes to $x+1$) or not swim at all ($x$ stays the same), in both cases $t$ changes to $t+1$.

  As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed $l$ at integer points of time (or she will drown). More formally, if Koa is at $x$ ($1 \le x \le n$) meters from the shore at the moment $t$ (for some integer $t\ge 0$), the depth of the sea at this point  — $d_x + p[t \bmod 2k]$  — can't exceed $l$. In other...

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

inp = lambda : map(int, input().split())
t = int(input())
for _ in range(t):
    n, k, l = inp()
    d = list(inp())
    remain = [i for i in range((-1) * (k - 1), 0)] + [i for i in range(k + 1)]
    f = True
    for i in range(n):
        #print(remain)
        f = False
        new_remain = []
        for j in range(len(remain)):
            temp = (remain[j] + 1)
            if temp > k:
                temp = - k + 1
            if abs(temp) + d[i] <= l:
                f = True
                new_remain.append(temp)
        if not f:
            print("No")
            break
        remain = []
        flag = False if k + d[i] > l else True
        for j in range(1 - k, k + 1):
            if j in new_remain:
                flag = True
            if abs(j) + d[i] <= l and flag:
                remain.append(j)
            if abs(j) + d[i] > l:
                flag = False

    if f:
        print("Yes")


I found an interesting problem on https://codeforces.com/problemset/problem/1384/B2:
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.

Koa the Koala is at the beach!

The beach consists (from left to right) of a shore, $n+1$ meters of sea and an island at $n+1$ meters from the shore.

She measured the depth of the sea at $1, 2, \dots, n$ meters from the shore and saved them in array $d$. $d_i$ denotes the depth of the sea at $i$ meters from the shore for $1 \le i \le n$.

Like any beach this one has tide, the intensity of the tide is measured by parameter $k$ and affects all depths from the beginning at time $t=0$ in the following way:

  For a total of $k$ seconds, each second, tide increases all depths by $1$.

  Then, for a total of $k$ seconds, each second, tide decreases all depths by $1$.

  This process repeats again and again (ie. depths increase for $k$ seconds then decrease for $k$ seconds and so on ...).

Formally, let's define $0$-indexed array $p = [0, 1, 2, \ldots, k - 2, k - 1, k, k - 1, k - 2, \ldots, 2, 1]$ of length $2k$. At time $t$ ($0 \le t$) depth at $i$ meters from the shore equals $d_i + p[t \bmod 2k]$ ($t \bmod 2k$ denotes the remainder of the division of $t$ by $2k$). Note that the changes occur instantaneously after each second, see the notes for better understanding.

At time $t=0$ Koa is standing at the shore and wants to get to the island. Suppose that at some time $t$ ($0 \le t$) she is at $x$ ($0 \le x \le n$) meters from the shore:

  In one second Koa can swim $1$ meter further from the shore ($x$ changes to $x+1$) or not swim at all ($x$ stays the same), in both cases $t$ changes to $t+1$.

  As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed $l$ at integer points of time (or she will drown). More formally, if Koa is at $x$ ($1 \le x \le n$) meters from the shore at the moment $t$ (for some integer $t\ge 0$), the depth of the sea at this point  — $d_x + p[t \bmod 2k]$  — can't exceed $l$. In other...

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

import math
######################################################
# ps template
def mi(): return list(map(int, input().split()))
def ii(): return int(input())
def li(): return list(map(int, input().split()))
def si(): return input().split()

#######################################################
t = ii()
for _ in range(t):
    n, k, l = mi()
    a = li()
    dp = [ -1 for i in range(n)]
    ans = True
    rev = False
    if a[0]+k<=l:
        dp[0] = 'F'
    elif a[0]<=l:
        dp[0] = l - a[0]
        if dp[0] > 0:
            rev = True
        else:
            rev = False
    else:
        dp[0] = -1
    for i in range(1,n):
        if dp[i-1]==-1 or a[i]>l:
            ans = False
            break
        if a[i]+k<=l:
            dp[i] = 'F'
        elif dp[i-1]=='F':
            dp[i] = l - a[i]
            if dp[i]>0:
                rev = True
            else:
                rev = False
        elif rev:
            if l-a[i]<=dp[i-1]-1:
                dp[i] = l - a[i]
                if dp[i]>0:
                    rev = True
                else:
                    rev = False
            else:
                dp[i] = dp[i-1] - 1
                if dp[i]>0:
                    rev = True
                else:
                    rev = False
        elif dp[i-1]+1+a[i]<=l:
            dp[i] = dp[i-1]+1
            if dp[i] == k:
                rev= True
        else:
            ans = False
            break
    #print(dp)
    if ans and dp[n-1]!=-1:
        print("Yes")
    else:
        print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/1385/A:
You are given three positive (i.e. strictly greater than zero) integers $x$, $y$ and $z$.

Your task is to find positive integers $a$, $b$ and $c$ such that $x = \max(a, b)$, $y = \max(a, c)$ and $z = \max(b, c)$, or determine that it is impossible to find such $a$, $b$ and $c$.

You have to answer $t$ independent test cases. Print required $a$, $b$ and $c$ in any (arbitrary) order.

-----Input-----

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

The only line of the test case contains three integers $x$, $y$, and $z$ ($1 \le x, y, z \le 10^9$).

-----Output-----

For each test case, print the answer:  "NO" in the only line of the output if a solution doesn't exist;  or "YES" in the first line and any valid triple of positive integers $a$, $b$ and $c$ ($1 \le a, b, c \le 10^9$) in the second line. You can print $a$, $b$ and $c$ in any order.

-----Example-----
Input
5
3 2 3
100 100 100
50 49 49
10 30 20
1 1000000000 1000000000

Output
YES
3 2 1
YES
100 100 100
NO
NO
YES
1 1 1000000000

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

t=int(input())
for _ in range(t):
  a=list(map(int,input().split()))
  a.sort()
  if a[1]==a[2]:
    print('YES')
    ans=[]
    ans.append(str(a[1]))
    ans.append(str(a[0]))
    ans.append(str(a[0]))
    print(' '.join(ans))
  else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1388/A:
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.

Recently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer $x$ as nearly prime if it can be represented as $p \cdot q$, where $1 < p < q$ and $p$ and $q$ are prime numbers. For example, integers $6$ and $10$ are nearly primes (since $2 \cdot 3 = 6$ and $2 \cdot 5 = 10$), but integers $1$, $3$, $4$, $16$, $17$ or $44$ are not.

Captain Flint guessed an integer $n$ and asked you: can you represent it as the sum of $4$ different positive integers where at least $3$ of them should be nearly prime.

Uncle Bogdan easily solved the task and joined the crew. Can you do the same?

-----Input-----

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

Next $t$ lines contain test cases — one per line. The first and only line of each test case contains the single integer $n$ $(1 \le n \le 2 \cdot 10^5)$ — the number Flint guessed.

-----Output-----

For each test case print:   YES and $4$ different positive integers such that at least $3$ of them are nearly prime and their sum is equal to $n$ (if there are multiple answers print any of them);  NO if there is no way to represent $n$ as the sum of $4$ different positive integers where at least $3$ of them are nearly prime.  You can print each character of YES or NO in any case.

-----Example-----
Input
7
7
23
31
36
44
100
258

Output
NO
NO
YES
14 10 6 1
YES
5 6 10 15
YES
6 7 10 21
YES
2 10 33 55
YES
10 21 221 6

-----Note-----

In the first and second test cases, it can be proven that there are no four different positive integers such that at least three of them are nearly prime.

In the third test case, $n=31=2 \cdot 7 + 2 \cdot 5 + 2 \cdot 3 + 1$: integers $14$, $10$, $6$ are nearly prime.

In...

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


I found an interesting problem on https://codeforces.com/problemset/problem/1388/B:
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.

In the beginning, uncle Bogdan wrote on a board a positive integer $x$ consisting of $n$ digits. After that, he wiped out $x$ and wrote integer $k$ instead, which was the concatenation of binary representations of digits $x$ consists of (without leading zeroes). For example, let $x = 729$, then $k = 111101001$ (since $7 = 111$, $2 = 10$, $9 = 1001$).

After some time, uncle Bogdan understood that he doesn't know what to do with $k$ and asked Denis to help. Denis decided to wipe last $n$ digits of $k$ and named the new number as $r$.

As a result, Denis proposed to find such integer $x$ of length $n$ that $r$ (as number) is maximum possible. If there are multiple valid $x$ then Denis is interested in the minimum one.

All crew members, including captain Flint himself, easily solved the task. All, except cabin boy Kostya, who was too drunk to think straight. But what about you?

Note: in this task, we compare integers ($x$ or $k$) as numbers (despite what representations they are written in), so $729 < 1999$ or $111 < 1000$.

-----Input-----

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

Next $t$ lines contain test cases — one per test case. The one and only line of each test case contains the single integer $n$ ($1 \le n \le 10^5$) — the length of the integer $x$ you need to find.

It's guaranteed that the sum of $n$ from all test cases doesn't exceed $2 \cdot 10^5$.

-----Output-----

For each test case, print the minimum integer $x$ of length $n$ such that obtained by Denis number $r$ is maximum possible.

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

Output
8
998

-----Note-----

In the second test case (with $n = 3$), if uncle Bogdan had $x = 998$ then...

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

# for _ in range(1):
for _ in range(int(input())):
    # a, b = map(int, input().split())
    n = int(input())
    # arr = list(map(int, input().split()))
    # s = input()
    x = (n + 3) // 4
    y = n - x
    print(y * '9' + x * '8')


I found an interesting problem on https://codeforces.com/problemset/problem/1388/C:
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.

There are $n$ cities and $n−1$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $1$ to $n$ and the city $1$ is a capital. In other words, the country has a tree structure.

There are $m$ citizens living in the country. A $p_i$ people live in the $i$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths.

Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.

Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $i$-th city calculates a happiness index $h_i$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.

Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.

Uncle Bogdan successfully solved the problem. Can you do the same?

More formally, You need to check: "Is it possible that, after all people return home, for each city $i$ the happiness index will be equal exactly to $h_i$".

-----Input-----

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

The first line of each test case contains two integers $n$ and $m$ ($1 \le n \le 10^5$; $0 \le m \le 10^9$) — the number of cities and citizens.

The second line of each test case...

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

import sys
input = sys.stdin.readline
T = int(input())

for testcase in range(1,T+1):
    n,m = map(int,input().split())
    p = tuple(map(int,input().split()))
    h = tuple(map(int,input().split()))

    a = [0]*n
    b = [0]*n

    edge = [[] for i in range(n)]
    for _ in range(n-1):
        x,y = map(int,input().split())
        edge[x-1].append(y-1)
        edge[y-1].append(x-1)

    par = [-1]*n
    tank = [0]
    order = []
    while tank:
        now = tank.pop()
        order.append(now)
        for e in edge[now]:
            if par[now] != e:
                par[e] = now
                tank.append(e)
    flag = True
    for e in order[::-1]:
        if (a[e]-b[e]-p[e] <= h[e] <= a[e]+b[e]+p[e]) and (h[e]+a[e]+b[e]+p[e])%2 == 0:
            if e != 0:
                a[par[e]] += (h[e]+a[e]+b[e]+p[e])//2
                b[par[e]] += (h[e]+a[e]+b[e]+p[e])//2 - h[e]
        else:
            flag = False
            break
    if flag:
        print("YES")
    else:
        print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1388/D:
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...

There are two arrays $a$ and $b$ of length $n$. Initially, an $ans$ is equal to $0$ and the following operation is defined:   Choose position $i$ ($1 \le i \le n$);  Add $a_i$ to $ans$;  If $b_i \neq -1$ then add $a_i$ to $a_{b_i}$.

What is the maximum $ans$ you can get by performing the operation on each $i$ ($1 \le i \le n$) exactly once?

Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.

-----Input-----

The first line contains the integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of arrays $a$ and $b$.

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

The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le n$ or $b_i = -1$).

Additional constraint: it's guaranteed that for any $i$ ($1 \le i \le n$) the sequence $b_i, b_{b_i}, b_{b_{b_i}}, \ldots$ is not cyclic, in other words it will always end with $-1$.

-----Output-----

In the first line, print the maximum $ans$ you can get.

In the second line, print the order of operations: $n$ different integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$). The $p_i$ is the position which should be chosen at the $i$-th step. If there are multiple orders, print any of them.

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

Output
10
1 2 3

Input
2
-1 100
2 -1

Output
99
2 1

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

Output
-9
3 5 6 1 9 4 10 7 8 2

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

n=int(input())
val=list(map(int,input().split()))
b=list(map(int,input().split()))
neig=[0]*n
for i in range(n):
    neig[i]=[0]
inedges=[0]*n
for i in range(n):
    if b[i]!=-1:
        neig[i][0]+=1
        neig[i].append(b[i]-1)
        inedges[b[i]-1]+=1
ans=0
beg=[]
en=[]
tod=[]
for i in range(n):
    if inedges[i]==0:
        tod.append(i)
while len(tod)>0:
    x=tod.pop()
    ans+=val[x]
    if val[x]>0:
        beg.append(x+1)
    else:
        en.append(x+1)
    if neig[x][0]==1:
        inedges[neig[x][1]]-=1
        if inedges[neig[x][1]]==0:
            tod.append(neig[x][1])
        if val[x]>0:
            val[neig[x][1]]+=val[x]
print(ans)
print(*beg,end=" ")
en.reverse()
print(*en)


I found an interesting problem on https://codeforces.com/problemset/problem/1389/A:
Let $LCM(x, y)$ be the minimum positive integer that is divisible by both $x$ and $y$. For example, $LCM(13, 37) = 481$, $LCM(9, 6) = 18$.

You are given two integers $l$ and $r$. Find two integers $x$ and $y$ such that $l \le x < y \le r$ and $l \le LCM(x, y) \le r$.

-----Input-----

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

Each test case is represented by one line containing two integers $l$ and $r$ ($1 \le l < r \le 10^9$).

-----Output-----

For each test case, print two integers:

  if it is impossible to find integers $x$ and $y$ meeting the constraints in the statement, print two integers equal to $-1$;  otherwise, print the values of $x$ and $y$ (if there are multiple valid answers, you may print any of them).

-----Example-----
Input
4
1 1337
13 69
2 4
88 89

Output
6 7
14 21
2 4
-1 -1

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

for _ in range(int(input())):
    l,r = list(map(int,input().split()))
    if l*2 > r:
        print(-1, -1)
    else:
        print(l,l*2)


I found an interesting problem on https://codeforces.com/problemset/problem/1389/B:
You are given an array $a_1, a_2, \dots, a_n$, consisting of $n$ positive integers.

Initially you are standing at index $1$ and have a score equal to $a_1$. You can perform two kinds of moves:   move right — go from your current index $x$ to $x+1$ and add $a_{x+1}$ to your score. This move can only be performed if $x<n$.  move left — go from your current index $x$ to $x-1$ and add $a_{x-1}$ to your score. This move can only be performed if $x>1$. Also, you can't perform two or more moves to the left in a row.

You want to perform exactly $k$ moves. Also, there should be no more than $z$ moves to the left among them.

What is the maximum score you can achieve?

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases.

The first line of each testcase contains three integers $n, k$ and $z$ ($2 \le n \le 10^5$, $1 \le k \le n - 1$, $0 \le z \le min(5, k)$) — the number of elements in the array, the total number of moves you should perform and the maximum number of moves to the left you can perform.

The second line of each testcase contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^4$) — the given array.

The sum of $n$ over all testcases does not exceed $3 \cdot 10^5$.

-----Output-----

Print $t$ integers — for each testcase output the maximum score you can achieve if you make exactly $k$ moves in total, no more than $z$ of them are to the left and there are no two or more moves to the left in a row.

-----Example-----
Input
4
5 4 0
1 5 4 3 2
5 4 1
1 5 4 3 2
5 4 4
10 20 30 40 50
10 7 3
4 6 8 2 9 9 7 4 10 9

Output
15
19
150
56

-----Note-----

In the first testcase you are not allowed to move left at all. So you make four moves to the right and obtain the score $a_1 + a_2 + a_3 + a_4 + a_5$.

In the second example you can move one time to the left. So we can follow these moves: right, right, left, right. The score will be $a_1 + a_2 + a_3 + a_2 + a_3$.

In the third example you can move four times to the left but it's not optimal anyway,...

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

t = int(input())

for _ in range(t):
    n, k, z = [int(x) for x in input().split()]
    a = [int(x) for x in input().split()]

    best = -1
    best_pair = -1
    acc = a[0]
    used = 1

    for (prev, cur) in zip(a[:-1], a[1:]):
        used += 1

        if prev + cur > best_pair:
            best_pair = prev + cur

        acc += cur

        #print(f"Now k={k}, used={used}, z={z}")
        if (k - used + 2)//2 <= z and used <= k + 1:
            #print("Allowed at (prev, cur) =", (prev, cur))
            score = acc + (((k+1) - used)//2 * best_pair) + ((k+1 - used) % 2) * prev
            if score > best:
                #print(f"used={used}, (prev, cur) = {(prev, cur)}, best = {score}")
                best = score
    print(best)


I found an interesting problem on https://codeforces.com/problemset/problem/1389/C:
Let's call left cyclic shift of some string $t_1 t_2 t_3 \dots t_{n - 1} t_n$ as string $t_2 t_3 \dots t_{n - 1} t_n t_1$.

Analogically, let's call right cyclic shift of string $t$ as string $t_n t_1 t_2 t_3 \dots t_{n - 1}$.

Let's say string $t$ is good if its left cyclic shift is equal to its right cyclic shift.

You are given string $s$ which consists of digits 0–9.

What is the minimum number of characters you need to erase from $s$ to make it good?

-----Input-----

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

Next $t$ lines contains test cases — one per line. The first and only line of each test case contains string $s$ ($2 \le |s| \le 2 \cdot 10^5$). Each character $s_i$ is digit 0–9.

It's guaranteed that the total length of strings doesn't exceed $2 \cdot 10^5$.

-----Output-----

For each test case, print the minimum number of characters you need to erase from $s$ to make it good.

-----Example-----
Input
3
95831
100120013
252525252525

Output
3
5
0

-----Note-----

In the first test case, you can erase any $3$ characters, for example, the $1$-st, the $3$-rd, and the $4$-th. You'll get string 51 and it is good.

In the second test case, we can erase all characters except 0: the remaining string is 0000 and it's good.

In the third test case, the given string $s$ is already good.

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

import math
import sys
input = sys.stdin.readline

T = int(input())

for t in range(T):
    s = input()[:-1]

    answer = math.inf
    for n1 in range(10):
        sn1 = str(n1)
        for n2 in range(10):
            sn2 = str(n2)
            lookn1 = True
            current = 0
            for c in s:
                if c == sn1 and lookn1:
                    lookn1 = False
                    current += 1
                elif c == sn2 and not lookn1:
                    lookn1 = True
                    current += 1
            if current % 2 and n1 != n2:
                current -= 1

            answer = min(answer, len(s)-current)

    print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/1389/D:
You are given two lists of segments $[al_1, ar_1], [al_2, ar_2], \dots, [al_n, ar_n]$ and $[bl_1, br_1], [bl_2, br_2], \dots, [bl_n, br_n]$.

Initially, all segments $[al_i, ar_i]$ are equal to $[l_1, r_1]$ and all segments $[bl_i, br_i]$ are equal to $[l_2, r_2]$.

In one step, you can choose one segment (either from the first or from the second list) and extend it by $1$. In other words, suppose you've chosen segment $[x, y]$ then you can transform it either into $[x - 1, y]$ or into $[x, y + 1]$.

Let's define a total intersection $I$ as the sum of lengths of intersections of the corresponding pairs of segments, i.e. $\sum\limits_{i=1}^{n}{\text{intersection_length}([al_i, ar_i], [bl_i, br_i])}$. Empty intersection has length $0$ and length of a segment $[x, y]$ is equal to $y - x$.

What is the minimum number of steps you need to make $I$ greater or equal to $k$?

-----Input-----

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

The first line of each test case contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$; $1 \le k \le 10^9$) — the length of lists and the minimum required total intersection.

The second line of each test case contains two integers $l_1$ and $r_1$ ($1 \le l_1 \le r_1 \le 10^9$) — the segment all $[al_i, ar_i]$ are equal to initially.

The third line of each test case contains two integers $l_2$ and $r_2$ ($1 \le l_2 \le r_2 \le 10^9$) — the segment all $[bl_i, br_i]$ are equal to initially.

It's guaranteed that the sum of $n$ doesn't exceed $2 \cdot 10^5$.

-----Output-----

Print $t$ integers — one per test case. For each test case, print the minimum number of step you need to make $I$ greater or equal to $k$.

-----Example-----
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8

Output
7
2000000000
0

-----Note-----

In the first test case, we can achieve total intersection $5$, for example, using next strategy:   make $[al_1, ar_1]$ from $[1, 2]$ to $[1, 4]$ in $2$ steps;  make $[al_2, ar_2]$ from...

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

def inter(l1, r1, l2, r2):
    l = max(l1,l2)
    r = min(r1,r2)
    return max(r - l, 0)
def solve():
    n, k = map(int,input().split())
    al, ar = map(int,input().split())
    bl, br = map(int,input().split())
    res = inter(al,ar,bl,br) * n
    goodt = max(ar, br) - min(al,bl) - inter(al,ar,bl,br)
    minhodi = 1000000000000
    hodi = 0
    to_soed = max(0, max(al,bl) - min(ar, br))
    if res >= k:
        print(0)
        return 0
    for i in range(n):
        hodi += to_soed
        ineed = k - res
        if goodt >= ineed:
            hodi += ineed
            minhodi = min(minhodi, hodi)
            break
        hodi += goodt
        res += goodt
        minhodi = min(hodi + (k - res) * 2, minhodi)
    print(minhodi)
for i in range(int(input())):
    solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1391/A:
A permutation of length $n$ 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).

For a positive integer $n$, we call a permutation $p$ of length $n$ good if the following condition holds for every pair $i$ and $j$ ($1 \le i \le j \le n$) —   $(p_i \text{ OR } p_{i+1} \text{ OR } \ldots \text{ OR } p_{j-1} \text{ OR } p_{j}) \ge j-i+1$, where $\text{OR}$ denotes the bitwise OR operation.

In other words, a permutation $p$ is good if for every subarray of $p$, the $\text{OR}$ of all elements in it is not less than the number of elements in that subarray.

Given a positive integer $n$, output any good permutation of length $n$. We can show that for the given constraints such a permutation always exists.

-----Input-----

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

The first and only line of every test case contains a single integer $n$ ($1 \le n \le 100$).

-----Output-----

For every test, output any good permutation of length $n$ on a separate line.

-----Example-----
Input
3
1
3
7

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

-----Note-----

For $n = 3$, $[3,1,2]$ is a good permutation. Some of the subarrays are listed below.   $3\text{ OR }1 = 3 \geq 2$ $(i = 1,j = 2)$  $3\text{ OR }1\text{ OR }2 = 3 \geq 3$ $(i = 1,j = 3)$  $1\text{ OR }2 = 3 \geq 2$ $(i = 2,j = 3)$  $1 \geq 1$ $(i = 2,j = 2)$

Similarly, you can verify that $[4,3,5,2,7,1,6]$ is also good.

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

from sys import stdin
input = stdin.readline

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

    for x in range(1, n + 1):
        print(x, end = ' ')

    print()


I found an interesting problem on https://codeforces.com/problemset/problem/1391/B:
Consider a conveyor belt represented using a grid consisting of $n$ rows and $m$ columns. The cell in the $i$-th row from the top and the $j$-th column from the left is labelled $(i,j)$.

Every cell, except $(n,m)$, has a direction R (Right) or D (Down) assigned to it. If the cell $(i,j)$ is assigned direction R, any luggage kept on that will move to the cell $(i,j+1)$. Similarly, if the cell $(i,j)$ is assigned direction D, any luggage kept on that will move to the cell $(i+1,j)$. If at any moment, the luggage moves out of the grid, it is considered to be lost.

There is a counter at the cell $(n,m)$ from where all luggage is picked. A conveyor belt is called functional if and only if any luggage reaches the counter regardless of which cell it is placed in initially. More formally, for every cell $(i,j)$, any luggage placed in this cell should eventually end up in the cell $(n,m)$.

This may not hold initially; you are, however, allowed to change the directions of some cells to make the conveyor belt functional. Please determine the minimum amount of cells you have to change.

Please note that it is always possible to make any conveyor belt functional by changing the directions of some set of cells.

-----Input-----

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

The first line of each test case contains two integers $n, m$ ($1 \le n \le 100$, $1 \le m \le 100$)  — the number of rows and columns, respectively.

The following $n$ lines each contain $m$ characters. The $j$-th character in the $i$-th line, $a_{i,j}$ is the initial direction of the cell $(i, j)$. Please note that $a_{n,m}=$ C.

-----Output-----

For each case, output in a new line the minimum number of cells that you have to change to make the conveyor belt functional.

-----Example-----
Input
4
3 3
RRD
DDR
RRC
1 4
DDDC
6 9
RDDDDDRRR
RRDDRRDDD
RRDRDRRDR
DDDDRDDRR
DRRDRDDDR
DDRDRRDDC
1 1
C

Output
1
3
9
0

-----Note-----

In the...

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

a=int(input())
for i in range(a):
    x,y=list(map(int,input().split()))
    ans=[]
    for i in range(x):
        s=input()
        ans.append(s[-1])

    print(s.count('D')+ans.count('R'))


I found an interesting problem on https://codeforces.com/problemset/problem/1391/C:
A permutation of length $n$ 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).

Consider a permutation $p$ of length $n$, we build a graph of size $n$ using it as follows:   For every $1 \leq i \leq n$, find the largest $j$ such that $1 \leq j < i$ and $p_j > p_i$, and add an undirected edge between node $i$ and node $j$  For every $1 \leq i \leq n$, find the smallest $j$ such that $i < j \leq n$ and $p_j > p_i$, and add an undirected edge between node $i$ and node $j$

In cases where no such $j$ exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.

For clarity, consider as an example $n = 4$, and $p = [3,1,4,2]$; here, the edges of the graph are $(1,3),(2,1),(2,3),(4,3)$.

A permutation $p$ is cyclic if the graph built using $p$ has at least one simple cycle.

Given $n$, find the number of cyclic permutations of length $n$. Since the number may be very large, output it modulo $10^9+7$.

Please refer to the Notes section for the formal definition of a simple cycle

-----Input-----

The first and only line contains a single integer $n$ ($3 \le n \le 10^6$).

-----Output-----

Output a single integer $0 \leq x < 10^9+7$, the number of cyclic permutations of length $n$ modulo $10^9+7$.

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

Output
16
Input
583291

Output
135712853

-----Note-----

There are $16$ cyclic permutations for $n = 4$. $[4,2,1,3]$ is one such permutation, having a cycle of length four: $4 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 4$.

Nodes $v_1$, $v_2$, $\ldots$, $v_k$ form a simple cycle if the following conditions hold:   $k \geq 3$.  $v_i \neq v_j$ for any pair of indices $i$ and $j$. ($1 \leq i < j \leq k$)  $v_i$ and $v_{i+1}$ share an edge for all $i$ ($1 \leq i < k$), and $v_1$ and $v_k$ share an edge.

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

import sys
input = sys.stdin.readline

N = int(input())

MOD = 10**9 + 7

start = 1
to_remove = 1
for i in range(1, N+1):
    start = (start * i) % MOD
    if i > 1:
        to_remove = (to_remove * 2) % MOD
    # print(start, to_remove)
res = (start - to_remove) % MOD
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1391/D:
A binary matrix is called good if every even length square sub-matrix has an odd number of ones.

Given a binary matrix $a$ consisting of $n$ rows and $m$ columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all.

All the terms above have their usual meanings — refer to the Notes section for their formal definitions.

-----Input-----

The first line of input contains two integers $n$ and $m$ ($1 \leq n \leq m \leq 10^6$ and $n\cdot m \leq 10^6$)  — the number of rows and columns in $a$, respectively.

The following $n$ lines each contain $m$ characters, each of which is one of 0 and 1. If the $j$-th character on the $i$-th line is 1, then $a_{i,j} = 1$. Similarly, if the $j$-th character on the $i$-th line is 0, then $a_{i,j} = 0$.

-----Output-----

Output the minimum number of cells you need to change to make $a$ good, or output $-1$ if it's not possible at all.

-----Examples-----
Input
3 3
101
001
110

Output
2
Input
7 15
000100001010010
100111010110001
101101111100100
010000111111010
111010010100001
000011001111101
111111011010011

Output
-1

-----Note-----

In the first case, changing $a_{1,1}$ to $0$ and $a_{2,2}$ to $1$ is enough.

You can verify that there is no way to make the matrix in the second case good.

Some definitions —   A binary matrix is one in which every element is either $1$ or $0$.  A sub-matrix is described by $4$ parameters — $r_1$, $r_2$, $c_1$, and $c_2$; here, $1 \leq r_1 \leq r_2 \leq n$ and $1 \leq c_1 \leq c_2 \leq m$.  This sub-matrix contains all elements $a_{i,j}$ that satisfy both $r_1 \leq i \leq r_2$ and $c_1 \leq j \leq c_2$.  A sub-matrix is, further, called an even length square if $r_2-r_1 = c_2-c_1$ and $r_2-r_1+1$ is divisible by $2$.

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

import sys
input = sys.stdin.readline

n, m = list(map(int, input().split()))
l = []
for _ in range(n):
    l.append(input().strip())

def witch(s):
    out = 0
    if s[0] != s[1]:
        out += 2
    if s[1] != s[2]:
        out += 1
    return out

if n >= 4 and m >= 4:
    print(-1)
else:
    if n < m:
        n, m = m, n
        l = [''.join([l[j][i] for j in range(m)]) for i in range(n)]
    if m == 1:
        print(0)
    elif m == 2:
        even = 0
        odd = 0
        first = l.pop(0)
        if first == '00' or first == '11':
            odd += 1
        else:
            even += 1
        for nex in l:
            if nex == '00' or nex == '11':
                odd, even = even + 1, odd
            else:
                odd, even = even, odd + 1
        print(min(even, odd))
    elif m == 3:
        #ee, eo, oe, oo = [0, 0, 0 ,0]
        ll = [0, 0, 0, 0]
        for nex in l:
            ll.reverse()
            ll[witch(nex)] += 1
        print(n - max(ll))


I found an interesting problem on https://codeforces.com/problemset/problem/1392/A:
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!

A password is an array $a$ of $n$ positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index $i$ such that $1 \leq i < n$ and $a_{i} \neq a_{i+1}$, delete both $a_i$ and $a_{i+1}$ from the array and put $a_{i}+a_{i+1}$ in their place.

For example, for array $[7, 4, 3, 7]$ you can choose $i = 2$ and the array will become $[7, 4+3, 7] = [7, 7, 7]$. Note that in this array you can't apply this operation anymore.

Notice that one operation will decrease the size of the password by $1$. What is the shortest possible length of the password after some number (possibly $0$) of operations?

-----Input-----

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

The first line of each test case contains an integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the length of the password.

The second line of each test case contains $n$ integers $a_{1},a_{2},\dots,a_{n}$ ($1 \leq a_{i} \leq 10^9$) — the initial contents of your password.

The sum of $n$ over all test cases will not exceed $2 \cdot 10^5$.

-----Output-----

For each password, print one integer: the shortest possible length of the password after some number of operations.

-----Example-----
Input
2
4
2 1 3 1
2
420 420

Output
1
2

-----Note-----

In the first test case, you can do the following to achieve a length of $1$:

Pick $i=2$ to get $[2, 4, 1]$

Pick $i=1$ to get $[6, 1]$

Pick $i=1$ to get $[7]$

In the second test case, you can't perform any operations because there is no valid $i$ that satisfies the requirements mentioned above.

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

import sys
input = sys.stdin.readline
for f in range(int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    iseq=True
    for i in range(1,n):
        if a[i]!=a[i-1]:
            iseq=False
    if iseq:
        print(n)
    else:
        print(1)


I found an interesting problem on https://codeforces.com/problemset/problem/1392/B:
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:

You are given an array $a$ of $n$ integers. You are also given an integer $k$. Lord Omkar wants you to do $k$ operations with this array.

Define one operation as the following:   Set $d$ to be the maximum value of your array.  For every $i$ from $1$ to $n$, replace $a_{i}$ with $d-a_{i}$.

The goal is to predict the contents in the array after $k$ operations. Please help Ray determine what the final sequence will look like!

-----Input-----

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

The first line of each test case contains two integers $n$ and $k$ ($1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^{18}$) – the length of your array and the number of operations to perform.

The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ $(-10^9 \leq a_{i} \leq 10^9)$ – the initial contents of your array.

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

-----Output-----

For each case, print the final version of array $a$ after $k$ operations described above.

-----Example-----
Input
3
2 1
-199 192
5 19
5 -1 4 2 0
1 2
69

Output
391 0
0 6 1 3 5
0

-----Note-----

In the first test case the array changes as follows:

Initially, the array is $[-199, 192]$. $d = 192$.

After the operation, the array becomes $[d-(-199), d-192] = [391, 0]$.

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

input=__import__('sys').stdin.readline
for _ in range(int(input())):
    n,k=map(int,input().split())
    s=list(map(int,input().split()))
    for _ in range((k+1)%2+1):
        f=max(s)
        for i in range(n):s[i]=f-s[i]
    print(*s)