I found an interesting problem on https://codeforces.com/problemset/problem/1345/F:
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)

You have completed many programming projects. In fact, there are exactly $n$ types of programming projects, and you have completed $a_i$ projects of type $i$. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.

You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired:

$$ f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). $$

Here, $b_i$ denotes the number of projects of type $i$ you include in your résumé. Of course, you cannot include more projects than you have completed, so you require $0\le b_i \le a_i$ for all $i$.

Your résumé only has enough room for $k$ projects, and you will absolutely not be hired if your résumé has empty space, so you require $\sum\limits_{i=1}^n b_i=k$.

Find values for $b_1,\ldots, b_n$ that maximize the value of $f(b_1,\ldots,b_n)$ while satisfying the above two constraints.

-----Input-----

The first line contains two integers $n$ and $k$ ($1\le n\le 10^5$, $1\le k\le \sum\limits_{i=1}^n a_i$) — the number of types of programming projects and the résumé size, respectively.

The next line contains $n$ integers $a_1,\ldots,a_n$ ($1\le a_i\le 10^9$) — $a_i$ is equal to the number of completed projects of type $i$.

-----Output-----

In a single line, output $n$ integers $b_1,\ldots, b_n$ that achieve the maximum value of $f(b_1,\ldots,b_n)$, while satisfying the requirements $0\le b_i\le a_i$ and $\sum\limits_{i=1}^n b_i=k$. If there are multiple solutions, output any.

Note that you do not have to output the value $f(b_1,\ldots,b_n)$.

-----Examples-----
Input
10 32
1 2 3 4...

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

import sys
import heapq as hq

readline = sys.stdin.readline

ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))

eps = 10**-7

def solve():
    n, k = nm()
    a = nl()
    ans = [0]*n
    ok = 10**9; ng = -4*10**18
    while ok - ng > 1:
        mid = (ok + ng) // 2
        ck = 0
        for i in range(n):
            d =  9 - 12 * (mid + 1 - a[i])
            if d < 0:
                continue
            ck += min(a[i], int((3 + d**.5) / 6 + eps))
        # print(mid, ck)
        if ck > k:
            ng = mid
        else:
            ok = mid
    for i in range(n):
        d =  9 - 12 * (ok + 1 - a[i])
        if d < 0:
            continue
        ans[i] = min(a[i], int((3 + d**.5) / 6 + eps))
    # print(ans)
    rk = k - sum(ans)
    l = list()
    for i in range(n):
        if ans[i] < a[i]:
            hq.heappush(l, (-a[i] + 3 * ans[i]**2 - 3 * ans[i] + 1, i))
    for _ in range(rk):
        v, i = hq.heappop(l)
        ans[i] += 1
        if ans[i] < a[i]:
            hq.heappush(l, (-a[i] + 3 * ans[i]**2 - 3 * ans[i] + 1, i))
    print(*ans)
    return

solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1348/A:
Phoenix has $n$ coins with weights $2^1, 2^2, \dots, 2^n$. He knows that $n$ is even.

He wants to split the coins into two piles such that each pile has exactly $\frac{n}{2}$ coins and the difference of weights between the two piles is minimized. Formally, let $a$ denote the sum of weights in the first pile, and $b$ denote the sum of weights in the second pile. Help Phoenix minimize $|a-b|$, the absolute value of $a-b$.

-----Input-----

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

The first line of each test case contains an integer $n$ ($2 \le n \le 30$; $n$ is even) — the number of coins that Phoenix has.

-----Output-----

For each test case, output one integer — the minimum possible difference of weights between the two piles.

-----Example-----
Input
2
2
4

Output
2
6

-----Note-----

In the first test case, Phoenix has two coins with weights $2$ and $4$. No matter how he divides the coins, the difference will be $4-2=2$.

In the second test case, Phoenix has four coins of weight $2$, $4$, $8$, and $16$. It is optimal for Phoenix to place coins with weights $2$ and $16$ in one pile, and coins with weights $4$ and $8$ in another pile. The difference is $(2+16)-(4+8)=6$.

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

pot = [1] * 40
for i in range(1,40):
	pot[i] = 2 * pot[i-1]
q = int(input())
for riwe in range(q):
	n = int(input())
	wyn = pot[n]
	for i in range(n//2):
		j = n-1-i
		wyn -= pot[j]
	for i in range(1,n//2):
		wyn += pot[i]
	print(wyn)


I found an interesting problem on https://codeforces.com/problemset/problem/1348/C:
Phoenix has a string $s$ consisting of lowercase Latin letters. He wants to distribute all the letters of his string into $k$ non-empty strings $a_1, a_2, \dots, a_k$ such that every letter of $s$ goes to exactly one of the strings $a_i$. The strings $a_i$ do not need to be substrings of $s$. Phoenix can distribute letters of $s$ and rearrange the letters within each string $a_i$ however he wants.

For example, if $s = $ baba and $k=2$, Phoenix may distribute the letters of his string in many ways, such as:   ba and ba  a and abb  ab and ab  aa and bb

But these ways are invalid:   baa and ba  b and ba  baba and empty string ($a_i$ should be non-empty)

Phoenix wants to distribute the letters of his string $s$ into $k$ strings $a_1, a_2, \dots, a_k$ to minimize the lexicographically maximum string among them, i. e. minimize $max(a_1, a_2, \dots, a_k)$. Help him find the optimal distribution and print the minimal possible value of $max(a_1, a_2, \dots, a_k)$.

String $x$ is lexicographically less than string $y$ if either $x$ is a prefix of $y$ and $x \ne y$, or there exists an index $i$ ($1 \le i \le min(|x|, |y|))$ such that $x_i$ < $y_i$ and for every $j$ $(1 \le j < i)$ $x_j = y_j$. Here $|x|$ denotes the length of the string $x$.

-----Input-----

The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases. Each test case consists of two lines.

The first line of each test case consists of two integers $n$ and $k$ ($1 \le k \le n \le 10^5$) — the length of string $s$ and the number of non-empty strings, into which Phoenix wants to distribute letters of $s$, respectively.

The second line of each test case contains a string $s$ of length $n$ consisting only of lowercase Latin letters.

It is guaranteed that the sum of $n$ over all test cases is $\le 10^5$.

-----Output-----

Print $t$ answers — one per test case. The $i$-th answer should be the minimal possible value of $max(a_1, a_2, \dots, a_k)$ in the $i$-th test...

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

import sys
readline = sys.stdin.readline

T = int(readline())
Ans = [None]*T
for qu in range(T):
    N, K = map(int, readline().split())
    S = list(map(lambda x: ord(x)-97, readline().strip()))
    S.sort()
    if len(set(S[:K])) != 1:
        Ans[qu] = chr(97+S[K-1])
        continue
    L = len(set(S[K:]))
    if L == 1:
        res = [S[0]] + [S[K]]*(-((K-N)//K))
    else:
        res = [S[0]] + S[K:]
    Ans[qu] = ''.join(map(lambda x: chr(x+97), res))

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


I found an interesting problem on https://codeforces.com/problemset/problem/1348/D:
Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.

Initially, on day $1$, there is one bacterium with mass $1$.

Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass $m$ splits, it becomes two bacteria of mass $\frac{m}{2}$ each. For example, a bacterium of mass $3$ can split into two bacteria of mass $1.5$.

Also, every night, the mass of every bacteria will increase by one.

Phoenix is wondering if it is possible for the total mass of all the bacteria to be exactly $n$. If it is possible, he is interested in the way to obtain that mass using the minimum possible number of nights. Help him become the best scientist!

-----Input-----

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

The first line of each test case contains an integer $n$ ($2 \le n \le 10^9$) — the sum of bacteria masses that Phoenix is interested in.

-----Output-----

For each test case, if there is no way for the bacteria to exactly achieve total mass $n$, print -1. Otherwise, print two lines.

The first line should contain an integer $d$  — the minimum number of nights needed.

The next line should contain $d$ integers, with the $i$-th integer representing the number of bacteria that should split on the $i$-th day.

If there are multiple solutions, print any.

-----Example-----
Input
3
9
11
2

Output
3
1 0 2
3
1 1 2
1
0

-----Note-----

In the first test case, the following process results in bacteria with total mass $9$:   Day $1$: The bacterium with mass $1$ splits. There are now two bacteria with mass $0.5$ each.  Night $1$: All bacteria's mass increases by one. There are now two bacteria with mass $1.5$.  Day $2$: None split.  Night $2$: There are now two bacteria with mass $2.5$.  Day $3$: Both bacteria split. There are now four bacteria with mass $1.25$.  Night $3$: There are now four bacteria with mass $2.25$.  The total mass is $2.25+2.25+2.25+2.25=9$. It...

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

import math

def __starting_point():
    t = int(input())
    for numtests in range(t):
        n = int(input())
        d = math.floor(math.log(n, 2))
        if n == 2:
            print("1")
            print("0")
        elif n == 3:
            print("1")
            print("1")
        else:
            print(str(d))
            for i in range(d-2):
                print(str(int(2**(i))), end = " ")
            if n < int(3*(2**(d-1))):
                print(str(math.floor((n+1-2**d)/2)), end = " ")
                print(str((n+1)%2))
            else:
                print(str(int(2**(d-2))), end = " ")
                print(str(int(n+1-3*(2**(d-1)))))
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1348/E:
Phoenix is picking berries in his backyard. There are $n$ shrubs, and each shrub has $a_i$ red berries and $b_i$ blue berries.

Each basket can contain $k$ berries. But, Phoenix has decided that each basket may only contain berries from the same shrub or berries of the same color (red or blue). In other words, all berries in a basket must be from the same shrub or/and have the same color.

For example, if there are two shrubs with $5$ red and $2$ blue berries in the first shrub and $2$ red and $1$ blue berries in the second shrub then Phoenix can fill $2$ baskets of capacity $4$ completely:   the first basket will contain $3$ red and $1$ blue berries from the first shrub;  the second basket will contain the $2$ remaining red berries from the first shrub and $2$ red berries from the second shrub.

Help Phoenix determine the maximum number of baskets he can fill completely!

-----Input-----

The first line contains two integers $n$ and $k$ ($ 1\le n, k \le 500$) — the number of shrubs and the basket capacity, respectively.

The $i$-th of the next $n$ lines contain two integers $a_i$ and $b_i$ ($0 \le a_i, b_i \le 10^9$) — the number of red and blue berries in the $i$-th shrub, respectively.

-----Output-----

Output one integer — the maximum number of baskets that Phoenix can fill completely.

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

Output
2

Input
1 5
2 3

Output
1

Input
2 5
2 1
1 3

Output
0

Input
1 2
1000000000 1

Output
500000000

-----Note-----

The first example is described above.

In the second example, Phoenix can fill one basket fully using all the berries from the first (and only) shrub.

In the third example, Phoenix cannot fill any basket completely because there are less than $5$ berries in each shrub, less than $5$ total red berries, and less than $5$ total blue berries.

In the fourth example, Phoenix can put all the red berries into baskets, leaving an extra blue berry behind.

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

def check(k, aas, bs, a_rem, b_rem):
    if a_rem + b_rem < k:
        return False
    a_lo = k - b_rem
    a_hi = a_rem

    rems = set()
    rems.add(0)
    for a, b in zip(aas, bs):
        if a + b < k:
            continue
        for i in range(max(0, k - b), min(a, k) + 1):
            rem = i % k
            for j in list(rems):
                rems.add((j + rem) % k)
    for rem in rems:
        if rem >= a_lo and rem <= a_hi:
            return True
    return False

n, k = [int(x) for x in input().split()]
aas = []
bs = []
a_total = 0
b_total = 0
for i in range(n):
    a, b = [int(x) for x in input().split()]
    aas.append(a)
    bs.append(b)
    a_total += a
    b_total += b
ans = a_total // k + b_total // k
if check(k, aas, bs, a_total % k, b_total % k):
    print(ans + 1)
else:
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1349/B:
Slime has a sequence of positive integers $a_1, a_2, \ldots, a_n$.

In one operation Orac can choose an arbitrary subsegment $[l \ldots r]$ of this sequence and replace all values $a_l, a_{l + 1}, \ldots, a_r$ to the value of median of $\{a_l, a_{l + 1}, \ldots, a_r\}$.

In this problem, for the integer multiset $s$, the median of $s$ is equal to the $\lfloor \frac{|s|+1}{2}\rfloor$-th smallest number in it. For example, the median of $\{1,4,4,6,5\}$ is $4$, and the median of $\{1,7,5,8\}$ is $5$.

Slime wants Orac to make $a_1 = a_2 = \ldots = a_n = k$ using these operations.

Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.

-----Input-----

The first line of the input is a single integer $t$: the number of queries.

The first line of each query contains two integers $n\ (1\le n\le 100\,000)$ and $k\ (1\le k\le 10^9)$, the second line contains $n$ positive integers $a_1,a_2,\dots,a_n\ (1\le a_i\le 10^9)$

The total sum of $n$ is at most $100\,000$.

-----Output-----

The output should contain $t$ lines. The $i$-th line should be equal to 'yes' if it is possible to make all integers $k$ in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase.

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

Output
no
yes
yes
no
yes

-----Note-----

In the first query, Orac can't turn all elements into $3$.

In the second query, $a_1=6$ is already satisfied.

In the third query, Orac can select the complete array and turn all elements into $2$.

In the fourth query, Orac can't turn all elements into $3$.

In the fifth query, Orac can select $[1,6]$ at first and then select $[2,10]$.

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

import sys
input = sys.stdin.readline

Q = int(input())
Query = []
for _ in range(Q):
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    Query.append((N, K, A))

for N, K, A in Query:
    Inds = []
    exists = False
    for i, a in enumerate(A):
        if a == K: exists = True
        if a >= K:
            Inds.append(i)

    if not exists:
        ok = False
    elif N == 1:
        ok = True
    else:
        ok = False
        for ind in Inds:
            if ind < N-1 and A[ind+1] >= A[ind]:
                ok = True
            elif ind > 0 and A[ind-1] >= A[ind]:
                ok = True
            elif ind > 1 and A[ind-2] >= A[ind]:
                ok = True
            elif ind < N-2 and A[ind+2] >= A[ind]:
                ok = True
    print("yes" if ok else "no")


I found an interesting problem on https://codeforces.com/problemset/problem/1350/A:
Orac is studying number theory, and he is interested in the properties of divisors.

For two positive integers $a$ and $b$, $a$ is a divisor of $b$ if and only if there exists an integer $c$, such that $a\cdot c=b$.

For $n \ge 2$, we will denote as $f(n)$ the smallest positive divisor of $n$, except $1$.

For example, $f(7)=7,f(10)=2,f(35)=5$.

For the fixed integer $n$, Orac decided to add $f(n)$ to $n$.

For example, if he had an integer $n=5$, the new value of $n$ will be equal to $10$. And if he had an integer $n=6$, $n$ will be changed to $8$.

Orac loved it so much, so he decided to repeat this operation several times.

Now, for two positive integers $n$ and $k$, Orac asked you to add $f(n)$ to $n$ exactly $k$ times (note that $n$ will change after each operation, so $f(n)$ may change too) and tell him the final value of $n$.

For example, if Orac gives you $n=5$ and $k=2$, at first you should add $f(5)=5$ to $n=5$, so your new value of $n$ will be equal to $n=10$, after that, you should add $f(10)=2$ to $10$, so your new (and the final!) value of $n$ will be equal to $12$.

Orac may ask you these queries many times.

-----Input-----

The first line of the input is a single integer $t\ (1\le t\le 100)$: the number of times that Orac will ask you.

Each of the next $t$ lines contains two positive integers $n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$, corresponding to a query by Orac.

It is guaranteed that the total sum of $n$ is at most $10^6$.

-----Output-----

Print $t$ lines, the $i$-th of them should contain the final value of $n$ in the $i$-th query by Orac.

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

Output
10
12
12

-----Note-----

In the first query, $n=5$ and $k=1$. The divisors of $5$ are $1$ and $5$, the smallest one except $1$ is $5$. Therefore, the only operation adds $f(5)=5$ to $5$, and the result is $10$.

In the second query, $n=8$ and $k=2$. The divisors of $8$ are $1,2,4,8$, where the smallest one except $1$ is $2$, then after one operation $8$ turns into $8+(f(8)=2)=10$. The divisors...

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

t=int(input())
for _ in range(t):
    n,k=list(map(int,input().split()))
    if n%2==0:
        print(n+2*k)
    else:
        i=2
        while 1>0:
            if n%i==0:
                break
            i=i+1
        n=n+i
        k=k-1
        print(n+2*k)


I found an interesting problem on https://codeforces.com/problemset/problem/1350/B:
There are $n$ models in the shop numbered from $1$ to $n$, with sizes $s_1, s_2, \ldots, s_n$.

Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).

Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices $i_j$ and $i_{j+1}$ (note that $i_j < i_{j+1}$, because Orac arranged them properly), $i_{j+1}$ is divisible by $i_j$ and $s_{i_j} < s_{i_{j+1}}$.

For example, for $6$ models with sizes $\{3, 6, 7, 7, 7, 7\}$, he can buy models with indices $1$, $2$, and $6$, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful.

Orac wants to know the maximum number of models that he can buy, and he may ask you these queries many times.

-----Input-----

The first line contains one integer $t\ (1 \le t\le 100)$: the number of queries.

Each query contains two lines. The first line contains one integer $n\ (1\le n\le 100\,000)$: the number of models in the shop, and the second line contains $n$ integers $s_1,\dots,s_n\ (1\le s_i\le 10^9)$: the sizes of models.

It is guaranteed that the total sum of $n$ is at most $100\,000$.

-----Output-----

Print $t$ lines, the $i$-th of them should contain the maximum number of models that Orac can buy for the $i$-th query.

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

Output
2
3
1
1

-----Note-----

In the first query, for example, Orac can buy models with indices $2$ and $4$, the arrangement will be beautiful because $4$ is divisible by $2$ and $6$ is more than $3$. By enumerating, we can easily find that there are no beautiful arrangements with more than two models.

In the second query, Orac can buy models with indices $1$, $3$, and $6$. By enumerating, we can easily find that there are no beautiful arrangements with more than three models.

In the third query, there are no beautiful arrangements with more than one model.

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

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


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

-----Input-----

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

Each test case is given as a line of two integers $a$ and $b$ ($-1000 \le a, b \le 1000$).

-----Output-----

Print $t$ integers — the required numbers $a+b$.

-----Example-----
Input
4
1 5
314 15
-99 99
123 987

Output
6
329
0
1110

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

t=int(input())
for i in range(t):
    a,b=map(int,input().split())
    print(a+b)


I found an interesting problem on https://codeforces.com/problemset/problem/1352/A:
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $1$ to $9$ (inclusive) are round.

For example, the following numbers are round: $4000$, $1$, $9$, $800$, $90$. The following numbers are not round: $110$, $707$, $222$, $1001$.

You are given a positive integer $n$ ($1 \le n \le 10^4$). Represent the number $n$ as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number $n$ as a sum of the least number of terms, each of which is a round number.

-----Input-----

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

Each test case is a line containing an integer $n$ ($1 \le n \le 10^4$).

-----Output-----

Print $t$ answers to the test cases. Each answer must begin with an integer $k$ — the minimum number of summands. Next, $k$ terms must follow, each of which is a round number, and their sum is $n$. The terms can be printed in any order. If there are several answers, print any of them.

-----Example-----
Input
5
5009
7
9876
10000
10

Output
2
5000 9
1
7
4
800 70 6 9000
1
10000
1
10

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

def sol():
    x=int(input())
    res=[]
    pw=0
    while x>0:
        p=x%10
        if p>0:
            d=p*(10**pw)
            res.append(d)
        pw+=1
        x//=10

    print(len(res))
    print(*res)

for n in range(int(input())):
    sol()


I found an interesting problem on https://codeforces.com/problemset/problem/1352/B:
You are given two positive integers $n$ ($1 \le n \le 10^9$) and $k$ ($1 \le k \le 100$). Represent the number $n$ as the sum of $k$ positive integers of the same parity (have the same remainder when divided by $2$).

In other words, find $a_1, a_2, \ldots, a_k$ such that all $a_i>0$, $n = a_1 + a_2 + \ldots + a_k$ and either all $a_i$ are even or all $a_i$ are odd at the same time.

If such a representation does not exist, then report it.

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases in the input. Next, $t$ test cases are given, one per line.

Each test case is two positive integers $n$ ($1 \le n \le 10^9$) and $k$ ($1 \le k \le 100$).

-----Output-----

For each test case print:

  YES and the required values $a_i$, if the answer exists (if there are several answers, print any of them);  NO if the answer does not exist.

The letters in the words YES and NO can be printed in any case.

-----Example-----
Input
8
10 3
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9

Output
YES
4 2 4
YES
55 5 5 35
NO
NO
YES
1 1 1 1 1 1 1 1
NO
YES
3 1 1
YES
111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120

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

t = int(input())
for _ in range(t):
    n, k = list(map(int, input().split()))
    ans = []
    if n % 2 == 0:
        if k % 2 == 0:
            for i in range(k-1):
                ans.append(1)
                n -= 1
            ans.append(n)

        else:
            for i in range(k-1):
                ans.append(2)
                n -= 2
            ans.append(n)

    else:
        if k % 2 == 0:
            ans.append(-1)
        else:
            for i in range(k-1):
                ans.append(1)
                n -= 1
            ans.append(n)
    if min(ans) <= 0:
        print("NO")
    else:
        print("YES")
        print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1352/C:
You are given two positive integers $n$ and $k$. Print the $k$-th positive integer that is not divisible by $n$.

For example, if $n=3$, and $k=7$, then all numbers that are not divisible by $3$ are: $1, 2, 4, 5, 7, 8, 10, 11, 13 \dots$. The $7$-th number among them is $10$.

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases in the input. Next, $t$ test cases are given, one per line.

Each test case is two positive integers $n$ ($2 \le n \le 10^9$) and $k$ ($1 \le k \le 10^9$).

-----Output-----

For each test case print the $k$-th positive integer that is not divisible by $n$.

-----Example-----
Input
6
3 7
4 12
2 1000000000
7 97
1000000000 1000000000
2 1

Output
10
15
1999999999
113
1000000001
1

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

for t in range(int(input())):
    n, k = list(map(int, input().split()))
    if k % (n - 1) == 0:
        print(k // (n - 1) * n - 1)
    else:
        print(k // (n - 1) * n + k % (n - 1))


I found an interesting problem on https://codeforces.com/problemset/problem/1352/D:
There are $n$ candies in a row, they are numbered from left to right from $1$ to $n$. The size of the $i$-th candy is $a_i$.

Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.

The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).

Alice makes the first move. During the first move, she will eat $1$ candy (its size is $a_1$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.

On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.

For example, if $n=11$ and $a=[3,1,4,1,5,9,2,6,5,3,5]$, then:  move 1: Alice eats one candy of size $3$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3,5]$.  move 2: Alice ate $3$ on the previous move, which means Bob must eat $4$ or more. Bob eats one candy of size $5$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3]$.  move 3: Bob ate $5$ on the previous move, which means Alice must eat $6$ or more. Alice eats three candies with the total size of $1+4+1=6$ and the sequence of candies becomes $[5,9,2,6,5,3]$.  move 4: Alice ate $6$ on the previous move, which means Bob must eat $7$ or more. Bob eats two candies with the total size of $3+5=8$ and the sequence of candies becomes $[5,9,2,6]$.  move 5: Bob...

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

from _collections import deque

for _ in range(int(input())):
    n = int(input())
    ar = list(map(int, input().split()))
    ar = deque(ar)
    turn = 0
    a, b = 0, 0
    num2 = 0
    x = 0
    while ar:
        if turn == 0:
            num1 = 0
            while ar and num1 <= num2:
                num1 += ar[0]
                ar.popleft()
            a += num1
            num2 = num1
            turn = 1
        else:
            num1 = 0
            while ar and num1 <= num2:
                num1 += ar[-1]
                ar.pop()
            b += num1
            num2 = num1
            turn = 0
        x += 1
    print(x, a, b)


I found an interesting problem on https://codeforces.com/problemset/problem/1352/E:
Pay attention to the non-standard memory limit in this problem.

In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.

The array $a=[a_1, a_2, \ldots, a_n]$ ($1 \le a_i \le n$) is given. Its element $a_i$ is called special if there exists a pair of indices $l$ and $r$ ($1 \le l < r \le n$) such that $a_i = a_l + a_{l+1} + \ldots + a_r$. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).

Print the number of special elements of the given array $a$.

For example, if $n=9$ and $a=[3,1,4,1,5,9,2,6,5]$, then the answer is $5$:  $a_3=4$ is a special element, since $a_3=4=a_1+a_2=3+1$;  $a_5=5$ is a special element, since $a_5=5=a_2+a_3=1+4$;  $a_6=9$ is a special element, since $a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$;  $a_8=6$ is a special element, since $a_8=6=a_2+a_3+a_4=1+4+1$;  $a_9=5$ is a special element, since $a_9=5=a_2+a_3=1+4$.

Please note that some of the elements of the array $a$ may be equal — if several elements are equal and special, then all of them should be counted in the answer.

-----Input-----

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

Each test case is given in two lines. The first line contains an integer $n$ ($1 \le n \le 8000$) — the length of the array $a$. The second line contains integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$).

It is guaranteed that the sum of the values of $n$ for all test cases in the input does not exceed $8000$.

-----Output-----

Print $t$ numbers — the number of special elements for each of the given arrays.

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

Output
5
1
0
4
0

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

t = int(input())
for _ in range(t):
    n = int(input())
    s = list(map(int, input().split()))
    p = max(s)
    dict = {}
    for i in range(n):
        count = s[i]
        for j in range(i+1, n):
            count += s[j]
            dict[count] = 1
            if count >= p:
                break
    ans = 0
    for i in range(n):
        if dict.get(s[i]) is not None:
            ans += 1
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1352/G:
A permutation of length $n$ is an array $p=[p_1,p_2,\dots,p_n]$, which contains every integer from $1$ to $n$ (inclusive) and, moreover, each number appears exactly once. For example, $p=[3,1,4,2,5]$ is a permutation of length $5$.

For a given number $n$ ($n \ge 2$), find a permutation $p$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $2$ and $4$, inclusive. Formally, find such permutation $p$ that $2 \le |p_i - p_{i+1}| \le 4$ for each $i$ ($1 \le i < n$).

Print any such permutation for the given integer $n$ or determine that it does not exist.

-----Input-----

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

Each test case is described by a single line containing an integer $n$ ($2 \le n \le 1000$).

-----Output-----

Print $t$ lines. Print a permutation that meets the given requirements. If there are several such permutations, then print any of them. If no such permutation exists, print -1.

-----Example-----
Input
6
10
2
4
6
7
13

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

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

T = int(input())
for _ in range(T):
    n = int(input())
    if n <= 3:
        print(-1)
    else:
        left = []
        for i in range(1, n + 1, 2):
            left.append(i)
        right = []
        right.append(4)
        right.append(2)
        for i in range(6, n + 1, 2):
            right.append(i)
        right.reverse()

        for i in left:
            right.append(i)

        for i in right:
            print(i, end = " ")
        print("")


I found an interesting problem on https://codeforces.com/problemset/problem/1353/A:
You are given two integers $n$ and $m$. You have to construct the array $a$ of length $n$ consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly $m$ and the value $\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$ is the maximum possible. Recall that $|x|$ is the absolute value of $x$.

In other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array $a=[1, 3, 2, 5, 5, 0]$ then the value above for this array is $|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$. Note that this example doesn't show the optimal answer but it shows how the required value for some array is calculated.

You have to answer $t$ independent test cases.

-----Input-----

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

The only line of the test case contains two integers $n$ and $m$ ($1 \le n, m \le 10^9$) — the length of the array and its sum correspondingly.

-----Output-----

For each test case, print the answer — the maximum possible value of $\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$ for the array $a$ consisting of $n$ non-negative integers with the sum $m$.

-----Example-----
Input
5
1 100
2 2
5 5
2 1000000000
1000000000 1000000000

Output
0
2
10
1000000000
2000000000

-----Note-----

In the first test case of the example, the only possible array is $[100]$ and the answer is obviously $0$.

In the second test case of the example, one of the possible arrays is $[2, 0]$ and the answer is $|2-0| = 2$.

In the third test case of the example, one of the possible arrays is $[0, 2, 0, 3, 0]$ and the answer is $|0-2| + |2-0| + |0-3| + |3-0| = 10$.

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

q = int(input())
for _ in range(q):
	n,m = map(int,input().split())
	if n > 2:
		print(2*m)
	else:
		if n == 1:
			print(0)
		else:
			print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/1353/B:
You are given two arrays $a$ and $b$ both consisting of $n$ positive (greater than zero) integers. You are also given an integer $k$.

In one move, you can choose two indices $i$ and $j$ ($1 \le i, j \le n$) and swap $a_i$ and $b_j$ (i.e. $a_i$ becomes $b_j$ and vice versa). Note that $i$ and $j$ can be equal or different (in particular, swap $a_2$ with $b_2$ or swap $a_3$ and $b_9$ both are acceptable moves).

Your task is to find the maximum possible sum you can obtain in the array $a$ if you can do no more than (i.e. at most) $k$ such moves (swaps).

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 200$) — 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 30; 0 \le k \le n$) — the number of elements in $a$ and $b$ and the maximum number of moves you can do. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 30$), where $a_i$ is the $i$-th element of $a$. The third line of the test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 30$), where $b_i$ is the $i$-th element of $b$.

-----Output-----

For each test case, print the answer — the maximum possible sum you can obtain in the array $a$ if you can do no more than (i.e. at most) $k$ swaps.

-----Example-----
Input
5
2 1
1 2
3 4
5 5
5 5 6 6 5
1 2 5 4 3
5 3
1 2 3 4 5
10 9 10 10 9
4 0
2 2 4 3
2 4 2 3
4 4
1 2 2 1
4 4 5 4

Output
6
27
39
11
17

-----Note-----

In the first test case of the example, you can swap $a_1 = 1$ and $b_2 = 4$, so $a=[4, 2]$ and $b=[3, 1]$.

In the second test case of the example, you don't need to swap anything.

In the third test case of the example, you can swap $a_1 = 1$ and $b_1 = 10$, $a_3 = 3$ and $b_3 = 10$ and $a_2 = 2$ and $b_4 = 10$, so $a=[10, 10, 10, 4, 5]$ and $b=[1, 9, 3, 2, 9]$.

In the fourth test case of the example, you cannot swap anything.

In the fifth test case of the example, you can...

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

for _ in range(int(input())):
    n, k = [int(x) for x in input().split()]
    a = sorted([int(x) for x in input().split()])
    b = sorted([int(x) for x in input().split()], reverse=True)
    for i in range(k):
        if a[i] < b[i]:
            a[i], b[i] = b[i], a[i]
    print(sum(a))


I found an interesting problem on https://codeforces.com/problemset/problem/1353/C:
You are given a board of size $n \times n$, where $n$ is odd (not divisible by $2$). Initially, each cell of the board contains one figure.

In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $(i, j)$ you can move the figure to cells:   $(i - 1, j - 1)$;  $(i - 1, j)$;  $(i - 1, j + 1)$;  $(i, j - 1)$;  $(i, j + 1)$;  $(i + 1, j - 1)$;  $(i + 1, j)$;  $(i + 1, j + 1)$;

Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.

Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $n^2-1$ cells should contain $0$ figures and one cell should contain $n^2$ figures).

You have to answer $t$ independent test cases.

-----Input-----

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

The only line of the test case contains one integer $n$ ($1 \le n < 5 \cdot 10^5$) — the size of the board. It is guaranteed that $n$ is odd (not divisible by $2$).

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

-----Output-----

For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.

-----Example-----
Input
3
1
5
499993

Output
0
40
41664916690999888

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

N = 5*(10**5)+1
dp = [0 for i in range(N)]
dp[1] = 0
for i in range(3,N,2):
	dp[i] = dp[i-2]+8*(i//2)*(i//2)
t = int(input())
for y in range(t):
	n = int(input())
	print(dp[n])


I found an interesting problem on https://codeforces.com/problemset/problem/1354/A:
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $a$ minutes to feel refreshed.

Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in $b$ minutes.

Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than $a$ minutes in total, then he sets his alarm to go off in $c$ minutes after it is reset and spends $d$ minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.

If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another $c$ minutes and tries to fall asleep for $d$ minutes again.

You just want to find out when will Polycarp get out of his bed or report that it will never happen.

Please check out the notes for some explanations of the example.

-----Input-----

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

The only line of each testcase contains four integers $a, b, c, d$ ($1 \le a, b, c, d \le 10^9$) — the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.

-----Output-----

For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.

-----Example-----
Input
7
10 3 6 4
11 3 6 4
5 9 4 10
6 5 2 3
1 1 1 1
3947465 47342 338129 123123
234123843 13 361451236 361451000

Output
27
27
9
-1
1
6471793
358578060125049

-----Note-----

In the first testcase Polycarp wakes up after $3$ minutes. He only rested for $3$ minutes out of $10$ minutes he needed. So after that he sets his alarm to go off in $6$ minutes and spends $4$ minutes falling asleep. Thus, he rests for $2$ more minutes, totaling in $3+2=5$ minutes of sleep. Then he repeats the procedure three more times and ends up with $11$...

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

#JMD
#Nagendra Jha-4096

import sys
import math

#import fractions
#import numpy

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

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

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

##### Main ####
t=int(input())
for tt in range(t):
    #n=int(input())
    a,b,c,d= map(int, sys.stdin.readline().split(' '))
    if a<=b:
        print(b)
        continue
    diff = c-d

    if diff<=0:
        print(-1)
        continue
    else:
        rem=a-b
        slept=b
        v = (rem//diff)
        if v*diff<rem:
            v+=1
        slept+=(v*c)
        print(slept)
    #a=list(map(int,sys.stdin.readline().split(' ')))

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


I found an interesting problem on https://codeforces.com/problemset/problem/1354/B:
You are given a string $s$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $s$ such that it contains each of these three characters at least once.

A contiguous substring of string $s$ is a string that can be obtained from $s$ by removing some (possibly zero) characters from the beginning of $s$ and some (possibly zero) characters from the end of $s$.

-----Input-----

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

Each test case consists of one line containing the string $s$ ($1 \le |s| \le 200000$). It is guaranteed that each character of $s$ is either 1, 2, or 3.

The sum of lengths of all strings in all test cases does not exceed $200000$.

-----Output-----

For each test case, print one integer — the length of the shortest contiguous substring of $s$ containing all three types of characters at least once. If there is no such substring, print $0$ instead.

-----Example-----
Input
7
123
12222133333332
112233
332211
12121212
333333
31121

Output
3
3
4
4
0
0
4

-----Note-----

Consider the example test:

In the first test case, the substring 123 can be used.

In the second test case, the substring 213 can be used.

In the third test case, the substring 1223 can be used.

In the fourth test case, the substring 3221 can be used.

In the fifth test case, there is no character 3 in $s$.

In the sixth test case, there is no character 1 in $s$.

In the seventh test case, the substring 3112 can be used.

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

import sys
input = sys.stdin.readline

t = int(input())
out = []

for _ in range(t):
    s = input().strip()
    n = len(s)
    best = n + 1
    last1 = -best
    last2 = -best
    last3 = -best
    for i in range(n):
        c = s[i]
        if c == '1':
            last1 = i
        elif c == '2':
            last2 = i
        else:
            last3 = i
        curr = i - min(last1, last2, last3) + 1
        best = min(best, curr)
    if best <= n:
        out.append(best)
    else:
        out.append(0)
print(*out, sep = '\n')


I found an interesting problem on https://codeforces.com/problemset/problem/1354/E:
You are given an undirected graph without self-loops or multiple edges which consists of $n$ vertices and $m$ edges. Also you are given three integers $n_1$, $n_2$ and $n_3$.

Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:   Each vertex should be labeled by exactly one number 1, 2 or 3;  The total number of vertices with label 1 should be equal to $n_1$;  The total number of vertices with label 2 should be equal to $n_2$;  The total number of vertices with label 3 should be equal to $n_3$;  $|col_u - col_v| = 1$ for each edge $(u, v)$, where $col_x$ is the label of vertex $x$.

If there are multiple valid labelings, print any of them.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 5000$; $0 \le m \le 10^5$) — the number of vertices and edges in the graph.

The second line contains three integers $n_1$, $n_2$ and $n_3$ ($0 \le n_1, n_2, n_3 \le n$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $n_1 + n_2 + n_3 = n$.

Next $m$ lines contan description of edges: the $i$-th line contains two integers $u_i$, $v_i$ ($1 \le u_i, v_i \le n$; $u_i \neq v_i$) — the vertices the $i$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.

-----Output-----

If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $n$ consisting of 1, 2 and 3. The $i$-th letter should be equal to the label of the $i$-th vertex.

If there is no valid labeling, print "NO" (without quotes).

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

Output
YES
112323

Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5

Output
NO

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

n,m=map(int,input().split())
x,y,z=map(int,input().split())
edge=[[]for _ in range(n)]
for _ in range(m):
  a,b=map(int,input().split())
  a-=1
  b-=1
  edge[a].append(b)
  edge[b].append(a)
color=[0]*n
def bfs(v,c):
  color[v]=c
  h=w=0
  if c==1:h=1
  else:w=1
  for i in edge[v]:
    if color[i]==c:return [False,h,w]
    elif color[i]==0:
      f,hh,ww=bfs(i,-c)
      h+=hh
      w+=ww
      if not f:return [False,h,w]
  return [True,h,w]
q=[]
for i in range(n):
  if color[i]==0:
    f,h,w=bfs(i,1)
    if not f:print("NO");return
    q.append([i,min(h,w),max(h,w)-min(h,w),1-2*(h<w)])
yy=y
for _,i,__,___ in q:yy-=i
if yy<0:print("NO");return
dp=[(yy+1)*[0]for _ in range(len(q)+1)]
dp[0][0]=1
for i in range(len(q)):
  _,__,ii,___=q[i]
  for j in range(yy+1):dp[i+1][j]=dp[i][j]
  for j in range(yy+1):
    if ii+j>yy:break
    dp[i+1][ii+j]|=dp[i][j]
if dp[-1][-1]==0:print("NO");return
k=yy
qq=[]
for i in range(len(q),0,-1):
  if dp[i][k]==dp[i-1][k]:qq.append((q[i-1][0],-q[i-1][3]))
  else:
    qq.append((q[i-1][0],q[i-1][3]))
    k-=q[i-1][2]
color=[0]*n
visited=set()
for i,c in qq:
  stack=[i]
  visited.add(i)
  color[i]=c
  for j in stack:
    for k in edge[j]:
      if k in visited:continue
      visited.add(k)
      color[k]=-color[j]
      stack.append(k)
for i in range(n):
  if color[i]==1:color[i]="2"
  elif x:color[i]="1";x-=1
  else:color[i]="3"
print("YES")
print("".join(color))


I found an interesting problem on https://codeforces.com/problemset/problem/1355/C:
Like any unknown mathematician, Yuri has favourite numbers: $A$, $B$, $C$, and $D$, where $A \leq B \leq C \leq D$. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides $x$, $y$, and $z$ exist, such that $A \leq x \leq B \leq y \leq C \leq z \leq D$ holds?

Yuri is preparing problems for a new contest now, so he is very busy. That's why he asked you to calculate the number of triangles with described property.

The triangle is called non-degenerate if and only if its vertices are not collinear.

-----Input-----

The first line contains four integers: $A$, $B$, $C$ and $D$ ($1 \leq A \leq B \leq C \leq D \leq 5 \cdot 10^5$) — Yuri's favourite numbers.

-----Output-----

Print the number of non-degenerate triangles with integer sides $x$, $y$, and $z$ such that the inequality $A \leq x \leq B \leq y \leq C \leq z \leq D$ holds.

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

Output
4

Input
1 2 2 5

Output
3

Input
500000 500000 500000 500000

Output
1

-----Note-----

In the first example Yuri can make up triangles with sides $(1, 3, 3)$, $(2, 2, 3)$, $(2, 3, 3)$ and $(2, 3, 4)$.

In the second example Yuri can make up triangles with sides $(1, 2, 2)$, $(2, 2, 2)$ and $(2, 2, 3)$.

In the third example Yuri can make up only one equilateral triangle with sides equal to $5 \cdot 10^5$.

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

A, B, C, D = [int(i) for i in input().split()]

count_ymz = [None for i in range(D-B + 1)]
for i in range(len(count_ymz)):
	count_ymz[i] = min(C, D-i) - max(C-i, B) + 1

pre_count_ymz = [None for i in range(len(count_ymz))]
pre_count_ymz[0] = count_ymz[0]
for i in range(1, len(count_ymz)):
	pre_count_ymz[i] = pre_count_ymz[i-1] + count_ymz[i]
ans = 0
for x in range(A, B+1):
	if x > D-B + 1:
		ans += pre_count_ymz[-1]
	else:
		ans += pre_count_ymz[x-1]

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1355/E:
You have to restore the wall. The wall consists of $N$ pillars of bricks, the height of the $i$-th pillar is initially equal to $h_{i}$, the height is measured in number of bricks. After the restoration all the $N$ pillars should have equal heights.

You are allowed the following operations: put a brick on top of one pillar, the cost of this operation is $A$; remove a brick from the top of one non-empty pillar, the cost of this operation is $R$; move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is $M$.

You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes $0$.

What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?

-----Input-----

The first line of input contains four integers $N$, $A$, $R$, $M$ ($1 \le N \le 10^{5}$, $0 \le A, R, M \le 10^{4}$) — the number of pillars and the costs of operations.

The second line contains $N$ integers $h_{i}$ ($0 \le h_{i} \le 10^{9}$) — initial heights of pillars.

-----Output-----

Print one integer — the minimal cost of restoration.

-----Examples-----
Input
3 1 100 100
1 3 8

Output
12

Input
3 100 1 100
1 3 8

Output
9

Input
3 100 100 1
1 3 8

Output
4

Input
5 1 2 4
5 5 3 6 5

Output
4

Input
5 1 2 2
5 5 3 6 5

Output
3

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

def read_int():
    return int(input())

def read_ints():
    return list(map(int, input().split(' ')))

n, a, r, m = read_ints()
h = list(read_ints())
h.sort()
lo = h[0]
hi = h[-1]
s = [0]
for i in h:
    s.append(s[-1] + i)
ans = int(1e20)
for i in range(n):
    target = h[i]
    inc = i * target - s[i]
    dec = s[n] - s[i + 1] - (n - i - 1) * target
    plan_a = inc * a + dec * r
    plan_b = (inc - dec) * a + dec * \
        m if inc >= dec else inc * m + (dec - inc) * r
    ans = min(ans, min(plan_a, plan_b))
avg = s[n] // n
for target in range(max(0, avg - 1), avg + 2):
    inc = 0
    dec = 0
    for i in h:
        if i > target:
            dec += i - target
        else:
            inc += target - i
    plan_a = inc * a + dec * r
    plan_b = (inc - dec) * a + dec * \
        m if inc >= dec else inc * m + (dec - inc) * r
    ans = min(ans, min(plan_a, plan_b))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1358/A:
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.

The park is a rectangular table with $n$ rows and $m$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $1$. For example, park with $n=m=2$ has $12$ streets.

You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park).

 [Image] The park sizes are: $n=4$, $m=5$. The lighted squares are marked yellow. Please note that all streets have length $1$. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit.

Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.

-----Input-----

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

Each test case is a line containing two integers $n$, $m$ ($1 \le n, m \le 10^4$) — park sizes.

-----Output-----

Print $t$ answers to the test cases. Each answer must be a single integer — the minimum number of lanterns that are required to light all the squares.

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

Output
1
2
2
5
8

-----Note-----

Possible optimal arrangement of the lanterns for the $2$-nd test case of input data example: [Image]

Possible optimal arrangement of the lanterns for the $3$-rd test case of input data example: [Image]

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

t = int(input())

for _ in range(t):
    n, m = [int(x) for x in input().split()]
    print((n*m + 1)//2)


I found an interesting problem on https://codeforces.com/problemset/problem/1358/B:
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.

She has $n$ friends who are also grannies (Maria is not included in this number). The $i$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $a_i$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $i$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $a_i$.

Grannies gather in the courtyard like that.  Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $1$). All the remaining $n$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $a_i$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $i$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $a_i$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance.

Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!

Consider an example: if $n=6$ and $a=[1,5,4,5,1,9]$, then:  at the first step Maria can call grannies with numbers $1$ and $5$, each of them will see two grannies at the moment of going out into the yard (note that $a_1=1 \le 2$ and $a_5=1 \le 2$);  at the...

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

t = int(input())
while t > 0 :
    t -= 1
    n = int(input())
    a = [int(i) for i in input().split()]
    a.sort()
    ans = 1
    for i in range(n) :
        if a[i] <= i + 1 :
            ans = i + 2
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1358/C:
During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows:

 [Image]  The cell with coordinates $(x, y)$ is at the intersection of $x$-th row and $y$-th column. Upper left cell $(1,1)$ contains an integer $1$.

The developers of the SUM function don't sleep either. Because of the boredom, they teamed up with the developers of the RAND function, so they added the ability to calculate the sum on an arbitrary path from one cell to another, moving down or right. Formally, from the cell $(x,y)$ in one step you can move to the cell $(x+1, y)$ or $(x, y+1)$.

After another Dinwows update, Levian started to study "Celex-2021" (because he wants to be an accountant!). After filling in the table with the GAZ-GIZ function, he asked you to calculate the quantity of possible different amounts on the path from a given cell $(x_1, y_1)$ to another given cell $(x_2, y_2$), if you can only move one cell down or right.

Formally, consider all the paths from the cell $(x_1, y_1)$ to cell $(x_2, y_2)$ such that each next cell in the path is located either to the down or to the right of the previous one. Calculate the number of different sums of elements for all such paths.

-----Input-----

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

Each of the following $t$ lines contains four natural numbers $x_1$, $y_1$, $x_2$, $y_2$ ($1 \le x_1 \le x_2 \le 10^9$, $1 \le y_1 \le y_2 \le 10^9$) — coordinates of the start and the end cells.

-----Output-----

For each test case, in a separate line, print the number of possible different sums on the way from the start cell to the end cell.

-----Example-----
Input
4
1 1 2 2
1 2 2 4
179 1 179 100000
5 7 5 7

Output
2
3
1
1

-----Note-----

In the first test case there are two possible sums: $1+2+5=8$ and $1+3+5=9$. [Image]

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

t=int(input())
while t>0 :
    x1,y1,x2,y2=map(int,input().split())
    print((x2-x1)*(y2-y1)+1)
    t-=1


I found an interesting problem on https://codeforces.com/problemset/problem/1358/D:
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha.

You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly $x$ days and that's the exact number of days you will spend visiting your friend. You will spend exactly $x$ consecutive (successive) days visiting Coronavirus-chan.

They use a very unusual calendar in Naha: there are $n$ months in a year, $i$-th month lasts exactly $d_i$ days. Days in the $i$-th month are numbered from $1$ to $d_i$. There are no leap years in Naha.

The mood of Coronavirus-chan (and, accordingly, her desire to hug you) depends on the number of the day in a month. In particular, you get $j$ hugs if you visit Coronavirus-chan on the $j$-th day of the month.

You know about this feature of your friend and want to plan your trip to get as many hugs as possible (and then maybe you can win the heart of Coronavirus-chan).

Please note that your trip should not necessarily begin and end in the same year.

-----Input-----

The first line of input contains two integers $n$ and $x$ ($1 \le n \le 2 \cdot 10^5$) — the number of months in the year and the number of days you can spend with your friend.

The second line contains $n$ integers $d_1, d_2, \ldots, d_n$, $d_i$ is the number of days in the $i$-th month ($1 \le d_i \le 10^6$).

It is guaranteed that $1 \le x \le d_1 + d_2 + \ldots + d_n$.

-----Output-----

Print one integer — the maximum number of hugs that you can get from Coronavirus-chan during the best vacation in your life.

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

Output
5
Input
3 6
3 3 3

Output
12
Input
5 6
4 2 3 1 3

Output
15

-----Note-----

In the first test case, the numbers of the days in a year are (indices of days in a corresponding month) $\{1,1,2,3,1\}$. Coronavirus-chan will hug you the most if you come on the third day of the year: $2+3=5$ hugs.

In the second test case, the numbers of the days are...

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

from bisect import *
n, x = list(map(int, input().split()))
d = list(map(int, input().split()))
d.extend(d)

date_acc = [0]
tot_acc = [0]
for i in range(n*2):
    date_acc.append(date_acc[i]+d[i])
    tot_acc.append(tot_acc[i]+(d[i]*(d[i]+1))//2)

ans = 0
for i in range(n+1, 2*n+1):
    now = date_acc[i]
    start_i = bisect_left(date_acc, now-x)
    start = date_acc[start_i]
    remain = x - (now - start)
    temp = tot_acc[i] - tot_acc[start_i]
    temp += (remain*(2*d[start_i-1]-remain+1))//2
    ans = max(ans, temp)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1359/A:
The game of Berland poker is played with a deck of $n$ cards, $m$ of which are jokers. $k$ players play this game ($n$ is divisible by $k$).

At the beginning of the game, each player takes $\frac{n}{k}$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $x - y$, where $x$ is the number of jokers in the winner's hand, and $y$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $0$ points.

Here are some examples:  $n = 8$, $m = 3$, $k = 2$. If one player gets $3$ jokers and $1$ plain card, and another player gets $0$ jokers and $4$ plain cards, then the first player is the winner and gets $3 - 0 = 3$ points;  $n = 4$, $m = 2$, $k = 4$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $0$ points;  $n = 9$, $m = 6$, $k = 3$. If the first player gets $3$ jokers, the second player gets $1$ joker and $2$ plain cards, and the third player gets $2$ jokers and $1$ plain card, then the first player is the winner, and he gets $3 - 2 = 1$ point;  $n = 42$, $m = 0$, $k = 7$. Since there are no jokers, everyone gets $0$ jokers, everyone is a winner, and everyone gets $0$ points.

Given $n$, $m$ and $k$, calculate the maximum number of points a player can get for winning the game.

-----Input-----

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

Then the test cases follow. Each test case contains three integers $n$, $m$ and $k$ ($2 \le n \le 50$, $0 \le m \le n$, $2 \le k \le n$, $k$ is a divisors of $n$).

-----Output-----

For each test case, print one integer — the maximum number of points a player can get for winning the game.

-----Example-----
Input
4
8 3 2
4 2 4
9 6 3
42 0 7

Output
3
0
1
0

-----Note-----

Test cases of the example are described in the statement.

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

import sys

input = sys.stdin.readline
flush = sys.stdout.flush

for _ in range(int(input())):
    n, m, k = list(map(int, input().split()))
    if m >= n // k:
        a = n // k
        m -= a
        b = m // (k - 1) + 1 - (m % (k - 1) == 0)
        print(a - b)
        continue
    else:
        print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/1359/B:
You might have remembered Theatre square from the problem 1A. Now it's finally getting repaved.

The square still has a rectangular shape of $n \times m$ meters. However, the picture is about to get more complicated now. Let $a_{i,j}$ be the $j$-th square in the $i$-th row of the pavement.

You are given the picture of the squares:  if $a_{i,j} = $ "*", then the $j$-th square in the $i$-th row should be black;  if $a_{i,j} = $ ".", then the $j$-th square in the $i$-th row should be white.

The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles:  $1 \times 1$ tiles — each tile costs $x$ burles and covers exactly $1$ square;  $1 \times 2$ tiles — each tile costs $y$ burles and covers exactly $2$ adjacent squares of the same row. Note that you are not allowed to rotate these tiles or cut them into $1 \times 1$ tiles.

You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.

What is the smallest total price of the tiles needed to cover all the white squares?

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 500$) — the number of testcases. Then the description of $t$ testcases follow.

The first line of each testcase contains four integers $n$, $m$, $x$ and $y$ ($1 \le n \le 100$; $1 \le m \le 1000$; $1 \le x, y \le 1000$) — the size of the Theatre square, the price of the $1 \times 1$ tile and the price of the $1 \times 2$ tile.

Each of the next $n$ lines contains $m$ characters. The $j$-th character in the $i$-th line is $a_{i,j}$. If $a_{i,j} = $ "*", then the $j$-th square in the $i$-th row should be black, and if $a_{i,j} = $ ".", then the $j$-th square in the $i$-th row should be white.

It's guaranteed that the sum of $n \times m$ over all testcases doesn't exceed $10^5$.

-----Output-----

For each testcase print a single integer — the smallest total price of the tiles needed to cover all the white squares in burles.

-----Example-----
Input
4
1 1 10...

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

def solv():
    x,y,on,tw=map(int,input().split())
    ans=0
    for n in range(x):
        s=input()
        tot=0
        for n in s:
            if n=='.':
                tot+=1
            else:
                a=tot*on
                b=(tot//2)*tw+(tot%2)*on
                ans+=min(a,b)
                tot=0
        a=tot*on
        b=(tot//2)*tw+(tot%2)*on
        ans+=min(a,b)
    print(ans)

for n in range(int(input())):
    solv()


I found an interesting problem on https://codeforces.com/problemset/problem/1359/C:
There are two infinite sources of water:  hot water of temperature $h$;  cold water of temperature $c$ ($c < h$).

You perform the following procedure of alternating moves:  take one cup of the hot water and pour it into an infinitely deep barrel;  take one cup of the cold water and pour it into an infinitely deep barrel;  take one cup of the hot water $\dots$  and so on $\dots$

Note that you always start with the cup of hot water.

The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.

You want to achieve a temperature as close as possible to $t$. So if the temperature in the barrel is $t_b$, then the absolute difference of $t_b$ and $t$ ($|t_b - t|$) should be as small as possible.

How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $t$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.

-----Input-----

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

Each of the next $T$ lines contains three integers $h$, $c$ and $t$ ($1 \le c < h \le 10^6$; $c \le t \le h$) — the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.

-----Output-----

For each testcase print a single positive integer — the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $t$.

-----Example-----
Input
3
30 10 20
41 15 30
18 13 18

Output
2
7
1

-----Note-----

In the first testcase the temperature after $2$ poured cups: $1$ hot and $1$ cold is exactly $20$. So that is the closest we can achieve.

In the second testcase the temperature after $7$ poured cups: $4$ hot and $3$ cold is about $29.857$. Pouring more water won't get us closer to $t$ than that.

In the third testcase the temperature after $1$ poured cup: $1$ hot is $18$. That's exactly equal to $t$.

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

import sys

input = sys.stdin.readline
flush = sys.stdout.flush

for _ in range(int(input())):
    h, c, t = list(map(int, input().split()))
    m = h + c >> 1
    if t <= m:
        print(2)
        continue
    a = (h - t) // (2*t - h - c)
    b = a + 1
    print(2*a + 1 if 2*t*(2*a+1)*(2*b+1) >= (2*b+1)*((a+1)*h+a*c)+(2*a+1)*((b+1)*h+b*c) else 2 * b + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1359/D:
Alice and Bob are playing yet another card game. This time the rules are the following. There are $n$ cards lying in a row in front of them. The $i$-th card has value $a_i$.

First, Alice chooses a non-empty consecutive segment of cards $[l; r]$ ($l \le r$). After that Bob removes a single card $j$ from that segment $(l \le j \le r)$. The score of the game is the total value of the remaining cards on the segment $(a_l + a_{l + 1} + \dots + a_{j - 1} + a_{j + 1} + \dots + a_{r - 1} + a_r)$. In particular, if Alice chooses a segment with just one element, then the score after Bob removes the only card is $0$.

Alice wants to make the score as big as possible. Bob takes such a card that the score is as small as possible.

What segment should Alice choose so that the score is maximum possible? Output the maximum score.

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($-30 \le a_i \le 30$) — the values on the cards.

-----Output-----

Print a single integer — the final score of the game.

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

Output
6

Input
8
5 2 5 3 -30 -30 6 9

Output
10

Input
3
-10 6 -15

Output
0

-----Note-----

In the first example Alice chooses a segment $[1;5]$ — the entire row of cards. Bob removes card $3$ with the value $10$ from the segment. Thus, the final score is $5 + (-2) + (-1) + 4 = 6$.

In the second example Alice chooses a segment $[1;4]$, so that Bob removes either card $1$ or $3$ with the value $5$, making the answer $5 + 2 + 3 = 10$.

In the third example Alice can choose any of the segments of length $1$: $[1;1]$, $[2;2]$ or $[3;3]$. Bob removes the only card, so the score is $0$. If Alice chooses some other segment then the answer will be less than $0$.

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

from bisect import bisect_left as lower_bound, bisect_right as upper_bound
from sys import stdin, stdout
from collections import defaultdict

N = 10**5 + 7

minn = [0 for _ in range(2*N)]
maxx = [0 for _ in range(2*N)]

def build(p, n):
    for i in range(n):
        maxx[n+i] = p[i]
        minn[n+i] = p[i]

    for i in range(n-1, 0, -1):
        maxx[i] = max(maxx[i<<1], maxx[i<<1|1])
        minn[i] = min(minn[i<<1], minn[i<<1|1])

def query(l, r, n):
    l += n
    r += n

    retminn, retmaxx = float('inf'), -float('inf')

    while l < r:
        if l&1:
            retminn = min(retminn, minn[l])
            retmaxx = max(retmaxx, maxx[l])
            l += 1

        if r&1:
            r -= 1
            retminn = min(retminn, minn[r])
            retmaxx = max(retmaxx, maxx[r])

        l >>= 1
        r >>= 1

    return retminn, retmaxx

def main():
    n = int(input())
    a = list(map(int, input().strip().split()))

    left = [-1]*n
    right = [n]*n

    p = [a[i] for i in range(n)]
    for i in range(1, n): p[i] += p[i-1]

    build(p, n)

    st = [0]
    for i in range(1, n):
        while st and a[st[-1]] <= a[i]: st.pop()

        if st: left[i] = st[-1]
        st.append(i)

    st = [n-1]
    for i in range(n-2, -1, -1):
        while st and a[st[-1]] < a[i]: st.pop()

        if st: right[i] = st[-1]
        st.append(i)

    #print(left, right, p)
    #

    if max(a) <= 0:
        print(0)
        return None

    ret = -float('inf')

    for i in range(n):
        l, r = left[i], right[i]

        _, rmaxx = query(i, r, n)
        lminn, _ = query(max(0, l), i, n)

        if l < 0: lminn = min(lminn, 0)

        s = rmaxx - lminn
        #print(i, s, a[i], l, r)

        ret = max(ret, s-a[i])

    print(ret)

def __starting_point(): main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1359/E:
We define $x \bmod y$ as the remainder of division of $x$ by $y$ ($\%$ operator in C++ or Java, mod operator in Pascal).

Let's call an array of positive integers $[a_1, a_2, \dots, a_k]$ stable if for every permutation $p$ of integers from $1$ to $k$, and for every non-negative integer $x$, the following condition is met:

 $ (((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k = (((x \bmod a_{p_1}) \bmod a_{p_2}) \dots \bmod a_{p_{k - 1}}) \bmod a_{p_k} $

That is, for each non-negative integer $x$, the value of $(((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k$ does not change if we reorder the elements of the array $a$.

For two given integers $n$ and $k$, calculate the number of stable arrays $[a_1, a_2, \dots, a_k]$ such that $1 \le a_1 < a_2 < \dots < a_k \le n$.

-----Input-----

The only line contains two integers $n$ and $k$ ($1 \le n, k \le 5 \cdot 10^5$).

-----Output-----

Print one integer — the number of stable arrays $[a_1, a_2, \dots, a_k]$ such that $1 \le a_1 < a_2 < \dots < a_k \le n$. Since the answer may be large, print it modulo $998244353$.

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

Output
16

Input
3 7

Output
0

Input
1337 42

Output
95147305

Input
1 1

Output
1

Input
500000 1

Output
500000

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

def modfac(n, MOD):

    f = 1
    factorials = [1]
    for m in range(1, n + 1):
        f *= m
        f %= MOD
        factorials.append(f)
    inv = pow(f, MOD - 2, MOD)
    invs = [1] * (n + 1)
    invs[n] = inv
    for m in range(n, 1, -1):
        inv *= m
        inv %= MOD
        invs[m - 1] = inv
    return factorials, invs

def modnCr(n,r,mod,fac,inv):
    return fac[n] * inv[n-r] * inv[r] % mod

n,k = map(int,input().split())
mod = 998244353
fac,inv = modfac(n+10,mod)
ans = 0

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

    rem = n // i - 1
    if rem >= k-1:
        ans += modnCr(rem,k-1,mod,fac,inv)
        ans %= mod

print (ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1360/C:
We call two numbers $x$ and $y$ similar if they have the same parity (the same remainder when divided by $2$), or if $|x-y|=1$. For example, in each of the pairs $(2, 6)$, $(4, 3)$, $(11, 7)$, the numbers are similar to each other, and in the pairs $(1, 4)$, $(3, 12)$, they are not.

You are given an array $a$ of $n$ ($n$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.

For example, for the array $a = [11, 14, 16, 12]$, there is a partition into pairs $(11, 12)$ and $(14, 16)$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.

-----Input-----

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

Each test case consists of two lines.

The first line contains an even positive integer $n$ ($2 \le n \le 50$) — length of array $a$.

The second line contains $n$ positive integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$).

-----Output-----

For each test case print:  YES if the such a partition exists,  NO otherwise.

The letters in the words YES and NO can be displayed in any case.

-----Example-----
Input
7
4
11 14 16 12
2
1 8
4
1 1 1 1
4
1 2 5 6
2
12 13
6
1 6 3 10 5 8
6
1 12 3 10 5 8

Output
YES
NO
YES
YES
YES
YES
NO

-----Note-----

The first test case was explained in the statement.

In the second test case, the two given numbers are not similar.

In the third test case, any partition is suitable.

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

def read_int():
    return int(input())

def read_ints():
    return list(map(int, input().split(' ')))

t = read_int()
for case_num in range(t):
    n = read_int()
    a = list(read_ints())
    cnt = [0 for i in range(101)]
    even = 0
    for ai in a:
        cnt[ai] += 1
        if ai % 2 == 0:
            even += 1
    odd = n - even
    if even % 2 == 0:
        print('YES')
    else:
        ok = False
        for i in range(1, 100):
            if cnt[i] > 0 and cnt[i + 1] > 0:
                ok = True
                break
        print('YES' if ok else 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1360/D:
Polycarp wants to buy exactly $n$ shovels. The shop sells packages with shovels. The store has $k$ types of packages: the package of the $i$-th type consists of exactly $i$ shovels ($1 \le i \le k$). The store has an infinite number of packages of each type.

Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $n$ shovels?

For example, if $n=8$ and $k=7$, then Polycarp will buy $2$ packages of $4$ shovels.

Help Polycarp find the minimum number of packages that he needs to buy, given that he:   will buy exactly $n$ shovels in total;  the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $1$ to $k$, inclusive.

-----Input-----

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

Each test case consists of two positive integers $n$ ($1 \le n \le 10^9$) and $k$ ($1 \le k \le 10^9$) — the number of shovels and the number of types of packages.

-----Output-----

Print $t$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.

-----Example-----
Input
5
8 7
8 1
6 10
999999733 999999732
999999733 999999733

Output
2
8
1
999999733
1

-----Note-----

The answer to the first test case was explained in the statement.

In the second test case, there is only one way to buy $8$ shovels — $8$ packages of one shovel.

In the third test case, you need to buy a $1$ package of $6$ shovels.

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

import bisect
t=int(input())
for you in range(t):
    l=input().split()
    n=int(l[0])
    k=int(l[1])
    lfi=[]
    i=1
    maxa=1
    while(i*i<=n):
        if(n%i==0):
            lfi.append(i)
            if(i>maxa and i<=k):
                maxa=i
            if(i!=n//i):
                lfi.append(n//i)
                if(n//i>maxa and n//i<=k):
                    maxa=n//i
        i+=1
    print(n//maxa)


I found an interesting problem on https://codeforces.com/problemset/problem/1362/A:
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can multiply or divide your number by $2$, $4$ or $8$, and division is only allowed if the number is divisible by the chosen divisor.

Formally, if the register contains a positive integer $x$, in one operation it can be replaced by one of the following:   $x \cdot 2$  $x \cdot 4$  $x \cdot 8$  $x / 2$, if $x$ is divisible by $2$  $x / 4$, if $x$ is divisible by $4$  $x / 8$, if $x$ is divisible by $8$

For example, if $x = 6$, in one operation it can be replaced by $12$, $24$, $48$ or $3$. Value $6$ isn't divisible by $4$ or $8$, so there're only four variants of replacement.

Now Johnny wonders how many operations he needs to perform if he puts $a$ in the register and wants to get $b$ at the end.

-----Input-----

The input consists of multiple test cases. The first line contains an integer $t$ ($1 \leq t \leq 1000$) — the number of test cases. The following $t$ lines contain a description of test cases.

The first and only line in each test case contains integers $a$ and $b$ ($1 \leq a, b \leq 10^{18}$) — the initial and target value of the variable, respectively.

-----Output-----

Output $t$ lines, each line should contain one integer denoting the minimum number of operations Johnny needs to perform. If Johnny cannot get $b$ at the end, then write $-1$.

-----Example-----
Input
10
10 5
11 44
17 21
1 1
96 3
2 128
1001 1100611139403776
1000000000000000000 1000000000000000000
7 1
10 8

Output
1
1
-1
0
2
2
14
0
-1
-1

-----Note-----

In the first test case, Johnny can reach $5$ from $10$ by using the shift to the right by one (i.e. divide by $2$).

In the second test case, Johnny can reach $44$ from $11$ by using the shift to the left by two (i.e. multiply by $4$).

In the third test case, it...

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

for i in range(int(input())):
    a,b=map(int,input().split())
    m=0
    l=0
    while a%2==0:
        a//=2
        m+=1
    while b%2==0:
        b//=2
        l+=1
    if b!=a:
        print(-1)
    else:
        u=abs(l-m)
        if u%3!=0:
            print(u//3+1)
        else:
            print(u//3)


I found an interesting problem on https://codeforces.com/problemset/problem/1362/C:
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.

The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of $5 = 101_2$ and $14 = 1110_2$ equals to $3$, since $0101$ and $1110$ differ in $3$ positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.

Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from $0$ to $n$. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.

-----Input-----

The input consists of multiple test cases. The first line contains one integer $t$ ($1 \leq t \leq 10\,000$) — the number of test cases. The following $t$ lines contain a description of test cases.

The first and only line in each test case contains a single integer $n$ ($1 \leq n \leq 10^{18})$.

-----Output-----

Output $t$ lines. For each test case, you should output a single line with one integer — the unfairness of the contest if the rating sequence equals to $0$, $1$, ..., $n - 1$, $n$.

-----Example-----
Input
5
5
7
11
1
2000000000000

Output
8
11
19
1
3999999999987

-----Note-----

For $n = 5$ we calculate unfairness of the following sequence (numbers from $0$ to $5$ written in binary with extra leading zeroes, so they all have the same length):   $000$  $001$  $010$  $011$  $100$ ...

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

t = int(input())
for _ in range(t):
	n = int(input())
	n += 1
	res = 0
	for i in range(60,-1,-1):
		temp = 1<<i
		if temp <= n:
			temp1 = n//temp
			if n%temp != 0:
				temp1 += 1
			res += temp1 - 1
	print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1362/D:
Today Johnny wants to increase his contribution. His plan assumes writing $n$ blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.

There are $n$ different topics, numbered from $1$ to $n$ sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most $n - 1$ neighbors.

For example, if already written neighbors of the current blog have topics number $1$, $3$, $1$, $5$, and $2$, Johnny will choose the topic number $4$ for the current blog, because topics number $1$, $2$ and $3$ are already covered by neighbors and topic number $4$ isn't covered.

As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?

-----Input-----

The first line contains two integers $n$ $(1 \leq n \leq 5 \cdot 10^5)$ and $m$ $(0 \leq m \leq 5 \cdot 10^5)$ — the number of blogs and references, respectively.

Each of the following $m$ lines contains two integers $a$ and $b$ ($a \neq b$; $1 \leq a, b \leq n$), which mean that there is a reference between blogs $a$ and $b$. It's guaranteed that the graph doesn't contain multiple edges.

The last line contains $n$ integers $t_1, t_2, \ldots, t_n$, $i$-th of them denotes desired topic number of the $i$-th blog ($1...

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

import io,os
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
from collections import deque

def solve(n,m,Edges,T):
    if n==1:
        if T[0]==1:
            return [1]
        return [-1]
    L=[]
    for i,t in enumerate(T):
        L.append((t,i))
    L.sort()
    Visited=[False]*n
    Ans=[]
    for num,fr in L:
        Visited[fr]=True
        s=set()
        for to in Edges[fr]:
            if Visited[to]:
                if T[to]==num:
                    return [-1]
                s.add(T[to])
        if len(s)!=num-1:
            return [-1]
        Ans.append(fr+1)
    return Ans

def main():
    n,m=map(int,input().split())
    Edges=[[] for _ in range(n)]
    for _ in range(m):
        a,b=map(lambda x: int(x)-1,input().split())
        Edges[a].append(b)
        Edges[b].append(a)
    T=list(map(int,input().split()))
    Ans=solve(n,m,Edges,T)
    sys.stdout.write(' '.join(map(str,Ans))+'\n')

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1363/A:
Shubham has an array $a$ of size $n$, and wants to select exactly $x$ elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.

Tell him whether he can do so.

-----Input-----

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

The first line of each test case contains two integers $n$ and $x$ $(1 \le x \le n \le 1000)$ — the length of the array and the number of elements you need to choose.

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

-----Output-----

For each test case, print "Yes" or "No" depending on whether it is possible to choose $x$ elements such that their sum is odd.

You may print every letter in any case you want.

-----Example-----
Input
5
1 1
999
1 1
1000
2 1
51 50
2 2
51 50
3 3
101 102 103

Output
Yes
No
Yes
Yes
No

-----Note-----

For $1$st case: We must select element $999$, and the sum is odd.

For $2$nd case: We must select element $1000$, so overall sum is not odd.

For $3$rd case: We can select element $51$.

For $4$th case: We must select both elements $50$ and $51$  — so overall sum is odd.

For $5$th case: We must select all elements  — but overall sum is not odd.

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

T = int(input())

for _ in range(T):
    n,x = map(int,input().split())
    a = list(map(int,input().split()))
    p,q = 0,0
    for i in a:
        if i % 2 == 0:
            p += 1
        else:
            q += 1
    ok = False
    for i in range(p + 1):
        j = x - i
        if j < 0 or j > q:
            continue
        if j % 2 == 1:
            ok = True
            break
    if ok:
        print('Yes')
    else:
        print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/1363/B:
Shubham has a binary string $s$. A binary string is a string containing only characters "0" and "1".

He can perform the following operation on the string any amount of times:   Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.

A string is called good if it does not contain "010" or "101" as a subsequence  — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.

What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.

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

-----Input-----

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

Each of the next $t$ lines contains a binary string $s$ $(1 \le |s| \le 1000)$.

-----Output-----

For every string, output the minimum number of operations required to make it good.

-----Example-----
Input
7
001
100
101
010
0
1
001100

Output
0
0
1
1
0
0
2

-----Note-----

In test cases $1$, $2$, $5$, $6$ no operations are required since they are already good strings.

For the $3$rd test case: "001" can be achieved by flipping the first character  — and is one of the possible ways to get a good string.

For the $4$th test case: "000" can be achieved by flipping the second character  — and is one of the possible ways to get a good string.

For the $7$th test case: "000000" can be achieved by flipping the third and fourth characters  — and is one of the possible ways to get a good string.

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

q = int(input())
for ii in range(q):
	s = input()
	n = len(s)
	wyn = 5298528589245892
	wyn = min(wyn, s.count('0'))
	wyn = min(wyn, s.count('1'))
	#00001111
	cyk = s.count('0')
	for i in range(n):
		if s[i] == '1':
			cyk +=1
		else:
			cyk -= 1
		wyn = min(wyn,cyk)
	cyk = s.count('1')
	for i in range(n):
		if s[i] == '0':
			cyk += 1
		else:
			cyk -= 1
		wyn = min(wyn,cyk)
	print(wyn)


I found an interesting problem on https://codeforces.com/problemset/problem/1363/C:
Ayush and Ashish play a game on an unrooted tree consisting of $n$ nodes numbered $1$ to $n$. Players make the following move in turns:   Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to $1$.

A tree is a connected undirected graph without cycles.

There is a special node numbered $x$. The player who removes this node wins the game.

Ayush moves first. Determine the winner of the game if each player plays optimally.

-----Input-----

The first line of the input contains a single integer $t$ $(1 \leq t \leq 10)$ — the number of testcases. The description of the test cases follows.

The first line of each testcase contains two integers $n$ and $x$ $(1\leq n \leq 1000, 1 \leq x \leq n)$ — the number of nodes in the tree and the special node respectively.

Each of the next $n-1$ lines contain two integers $u$, $v$ $(1 \leq u, v \leq n, \text{ } u \ne v)$, meaning that there is an edge between nodes $u$ and $v$ in the tree.

-----Output-----

For every test case, if Ayush wins the game, print "Ayush", otherwise print "Ashish" (without quotes).

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

Output
Ashish

Input
1
3 2
1 2
1 3

Output
Ayush

-----Note-----

For the $1$st test case, Ayush can only remove node $2$ or $3$, after which node $1$ becomes a leaf node and Ashish can remove it in his turn.

For the $2$nd test case, Ayush can remove node $2$ in the first move itself.

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,x = map(int,input().split())
  ab = [list(map(int,input().split())) for i in range(n-1)]
  graph = [[] for i in range(n+1)]
  for a,b in ab:
    graph[a].append(b)
    graph[b].append(a)
  if len(graph[x]) == 1 or n == 1:
    print("Ayush")
    continue
  if n%2:
    print("Ashish")
  else:
    print("Ayush")


I found an interesting problem on https://codeforces.com/problemset/problem/1363/E:
Ashish has a tree consisting of $n$ nodes numbered $1$ to $n$ rooted at node $1$. The $i$-th node in the tree has a cost $a_i$, and binary digit $b_i$ is written in it. He wants to have binary digit $c_i$ written in the $i$-th node in the end.

To achieve this, he can perform the following operation any number of times:   Select any $k$ nodes from the subtree of any node $u$, and shuffle the digits in these nodes as he wishes, incurring a cost of $k \cdot a_u$. Here, he can choose $k$ ranging from $1$ to the size of the subtree of $u$.

He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.

Help him find the minimum total cost he needs to spend so that after all the operations, every node $u$ has digit $c_u$ written in it, or determine that it is impossible.

-----Input-----

First line contains a single integer $n$ $(1 \le n \le 2 \cdot 10^5)$ denoting the number of nodes in the tree.

$i$-th line of the next $n$ lines contains 3 space-separated integers $a_i$, $b_i$, $c_i$ $(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$  — the cost of the $i$-th node, its initial digit and its goal digit.

Each of the next $n - 1$ lines contain two integers $u$, $v$ $(1 \leq u, v \leq n, \text{ } u \ne v)$, meaning that there is an edge between nodes $u$ and $v$ in the tree.

-----Output-----

Print the minimum total cost to make every node reach its target digit, and $-1$ if it is impossible.

-----Examples-----
Input
5
1 0 1
20 1 0
300 0 1
4000 0 0
50000 1 0
1 2
2 3
2 4
1 5

Output
4
Input
5
10000 0 1
2000 1 0
300 0 1
40 0 0
1 1 0
1 2
2 3
2 4
1 5

Output
24000
Input
2
109 0 1
205 0 1
1 2

Output
-1

-----Note-----

The tree corresponding to samples $1$ and $2$ are: [Image]

In sample $1$, we can choose node $1$ and $k = 4$ for a cost of $4 \cdot 1$ = $4$ and select nodes ${1, 2, 3, 5}$, shuffle their digits and get the desired digits in every node.

In sample $2$, we can choose node $1$ and $k = 2$ for a cost of $10000 \cdot 2$, select nodes ${1, 5}$ and...

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

import sys
input = sys.stdin.readline
n = int(input())
cbc = [list(map(int,input().split())) for i in range(n)]
ab = [list(map(int,input().split())) for i in range(n-1)]
graph = [[] for i in range(n+1)]
if n == 1:
  if cbc[0][1] != cbc[0][2]:
    print(-1)
  else:
    print(0)
  return
deg = [0]*(n+1)
for a,b in ab:
  graph[a].append(b)
  graph[b].append(a)
  deg[a] += 1
  deg[b] += 1
deg[1] += 1
stack = [1]
par = [0]*(n+1)
par[1] = -1
leaf = []
while stack:
  x = stack.pop()
  if x != 1 and len(graph[x]) == 1:
    leaf.append(x)
  for y in graph[x]:
    if par[y]:
      continue
    par[y] = x
    cbc[y-1][0] = min(cbc[y-1][0],cbc[x-1][0])
    stack.append(y)
dp = [[0,0] for i in range(n+1)]
ans = 0
while leaf:
  x = leaf.pop()
  p = par[x]
  if cbc[x-1][1] != cbc[x-1][2]:
    if cbc[x-1][1] == 1:
      dp[x][0] += 1
    else:
      dp[x][1] += 1
  if min(dp[x][0],dp[x][1]):
    if dp[x][0] > dp[x][1]:
      dp[x][0] -= dp[x][1]
      ans += cbc[x-1][0]*dp[x][1]*2
      dp[x][1] = 0
    else:
      dp[x][1] -= dp[x][0]
      ans += cbc[x-1][0]*dp[x][0]*2
      dp[x][0] = 0
  dp[p][0] += dp[x][0]
  dp[p][1] += dp[x][1]
  deg[p] -= 1
  if deg[p] == 1:
    leaf.append(p)
if dp[1][0] != dp[1][1]:
  print(-1)
else:
  print(ans)