I found an interesting problem on https://codeforces.com/problemset/problem/1328/B:
For the given integer $n$ ($n > 2$) let's write down all the strings of length $n$ which contain $n-2$ letters 'a' and two letters 'b' in lexicographical (alphabetical) order.

Recall that the string $s$ of length $n$ is lexicographically less than string $t$ of length $n$, if there exists such $i$ ($1 \le i \le n$), that $s_i < t_i$, and for any $j$ ($1 \le j < i$) $s_j = t_j$. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.

For example, if $n=5$ the strings are (the order does matter):  aaabb  aabab  aabba  abaab  ababa  abbaa  baaab  baaba  babaa  bbaaa

It is easy to show that such a list of strings will contain exactly $\frac{n \cdot (n-1)}{2}$ strings.

You are given $n$ ($n > 2$) and $k$ ($1 \le k \le \frac{n \cdot (n-1)}{2}$). Print the $k$-th string from the list.

-----Input-----

The input contains one or more test cases.

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

Each test case is written on the the separate line containing two integers $n$ and $k$ ($3 \le n \le 10^5, 1 \le k \le \min(2\cdot10^9, \frac{n \cdot (n-1)}{2})$.

The sum of values $n$ over all test cases in the test doesn't exceed $10^5$.

-----Output-----

For each test case print the $k$-th string from the list of all described above strings of length $n$. Strings in the list are sorted lexicographically (alphabetically).

-----Example-----
Input
7
5 1
5 2
5 8
5 10
3 1
3 2
20 100

Output
aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa

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

import math
t = int(input())
for i in range(t):
    n,k = list(map(int,input().split(" ")))
    k-=1 #zero-index
    m = int((1+math.sqrt(1+8*k))/2)
    tri = int(m*(m-1)/2)
    s = k-tri
    #print(m)
    #print(s)
    s = "a"*(n-m-1)+"b"+"a"*(m-s-1)+"b"+"a"*s
    print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1328/E:
You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is a vertex number $1$.

A tree is a connected undirected graph with $n-1$ edges.

You are given $m$ queries. The $i$-th query consists of the set of $k_i$ distinct vertices $v_i[1], v_i[2], \dots, v_i[k_i]$. Your task is to say if there is a path from the root to some vertex $u$ such that each of the given $k$ vertices is either belongs to this path or has the distance $1$ to some vertex of this path.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($2 \le n \le 2 \cdot 10^5$, $1 \le m \le 2 \cdot 10^5$) — the number of vertices in the tree and the number of queries.

Each of the next $n-1$ lines describes an edge of the tree. Edge $i$ is denoted by two integers $u_i$ and $v_i$, the labels of vertices it connects $(1 \le u_i, v_i \le n, u_i \ne v_i$).

It is guaranteed that the given edges form a tree.

The next $m$ lines describe queries. The $i$-th line describes the $i$-th query and starts with the integer $k_i$ ($1 \le k_i \le n$) — the number of vertices in the current query. Then $k_i$ integers follow: $v_i[1], v_i[2], \dots, v_i[k_i]$ ($1 \le v_i[j] \le n$), where $v_i[j]$ is the $j$-th vertex of the $i$-th query.

It is guaranteed that all vertices in a single query are distinct.

It is guaranteed that the sum of $k_i$ does not exceed $2 \cdot 10^5$ ($\sum\limits_{i=1}^{m} k_i \le 2 \cdot 10^5$).

-----Output-----

For each query, print the answer — "YES", if there is a path from the root to some vertex $u$ such that each of the given $k$ vertices is either belongs to this path or has the distance $1$ to some vertex of this path and "NO" otherwise.

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

Output
YES
YES
YES
YES
NO
NO

-----Note-----

The picture corresponding to the example:

[Image]

Consider the queries.

The first query is $[3, 8, 9, 10]$. The answer is "YES" as you can choose the path...

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

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

N, M = list(map(int, input().split()))
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = list(map(int, input().split()))
    x -= 1
    y -= 1
    X[x].append(y)
    X[y].append(x)

P = [-1] * N
DE = [0] * N

def EulerTour(n, X, i0 = 0):
    Q = [~i0, i0]
    ct = -1
    ET = []
    ET1 = [0] * n
    ET2 = [0] * n
    de = -1
    while Q:
        i = Q.pop()
        if i < 0:
            ET2[~i] = ct
            de -= 1
            continue
        if i >= 0:
            ET.append(i)
            ct += 1
            if ET1[i] == 0: ET1[i] = ct
            de += 1
            DE[i] = de
        for a in X[i][::-1]:
            if a != P[i]:
                P[a] = i
                for k in range(len(X[a])):
                    if X[a][k] == i:
                        del X[a][k]
                        break
                Q.append(~a)
                Q.append(a)
    return (ET, ET1, ET2)

ET, ET1, ET2 = EulerTour(N, X, 0)

for _ in range(M):
    A = [max(P[int(a) - 1], 0) for a in input().split()][1:]
    mad = -1
    for a in A:
        if DE[a] > mad:
            mad = DE[a]
            maa = a
    e = ET1[maa]
    for a in A:
        if not (ET1[a] <= e <= ET2[a]):
            print("NO")
            break
    else:
        print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1328/F:
You are given the array $a$ consisting of $n$ elements and the integer $k \le n$.

You want to obtain at least $k$ equal elements in the array $a$. In one move, you can make one of the following two operations:

  Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of $a$ is $mn$ then you choose such index $i$ that $a_i = mn$ and set $a_i := a_i + 1$);  take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of $a$ is $mx$ then you choose such index $i$ that $a_i = mx$ and set $a_i := a_i - 1$).

Your task is to calculate the minimum number of moves required to obtain at least $k$ equal elements in the array.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the number of elements in $a$ and the required number of equal elements.

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

-----Output-----

Print one integer — the minimum number of moves required to obtain at least $k$ equal elements in the array.

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

Output
3

Input
7 5
3 3 2 1 1 1 3

Output
4

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

#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,k = LI()
    a = LI()
    a.sort()
    d = defaultdict(lambda : 0)
    c = defaultdict(lambda : 0)
    s = [0]
    for i in a:
        d[i] += i
        c[i] += 1
        s.append(s[-1]+i)
    ans = float("inf")
    p = -1
    for i in a:
        if i == p:
            continue
        if k <= c[i]:
            ans = 0
            break
        l,r = bisect.bisect_left(a,i),bisect.bisect_right(a,i)
        m = r
        if m >= k:
            ns = l*(i-1)-s[l]
            su = ns+k-c[i]
            if su < ans:
                ans = su
        m = n-l
        if m >= k:
            ns = s[n]-s[r]-(n-r)*(i+1)
            su = ns+k-c[i]
            if su < ans:
                ans = su
        ns = s[n]-s[r]-(n-r)*(i+1)+l*(i-1)-s[l]
        su = ns+k-c[i]
        if su < ans:
            ans = su
        p = i
    print(ans)
    return

#Solve
def __starting_point():
    solve()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1330/A:
Dreamoon is a big fan of the Codeforces contests.

One day, he claimed that he will collect all the places from $1$ to $54$ after two more rated contests. It's amazing!

Based on this, you come up with the following problem:

There is a person who participated in $n$ Codeforces rounds. His place in the first round is $a_1$, his place in the second round is $a_2$, ..., his place in the $n$-th round is $a_n$.

You are given a positive non-zero integer $x$.

Please, find the largest $v$ such that this person can collect all the places from $1$ to $v$ after $x$ more rated contests.

In other words, you need to find the largest $v$, such that it is possible, that after $x$ more rated contests, for each $1 \leq i \leq v$, there will exist a contest where this person took the $i$-th place.

For example, if $n=6$, $x=2$ and $a=[3,1,1,5,7,10]$ then answer is $v=5$, because if on the next two contest he will take places $2$ and $4$, then he will collect all places from $1$ to $5$, so it is possible to get $v=5$.

-----Input-----

The first line contains an integer $t$ ($1 \leq t \leq 5$) denoting the number of test cases in the input.

Each test case contains two lines. The first line contains two integers $n, x$ ($1 \leq n, x \leq 100$). The second line contains $n$ positive non-zero integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 100$).

-----Output-----

For each test case print one line containing the largest $v$, such that it is possible that after $x$ other contests, for each $1 \leq i \leq v$, there will exist a contest where this person took the $i$-th place.

-----Example-----
Input
5
6 2
3 1 1 5 7 10
1 100
100
11 1
1 1 1 1 1 1 1 1 1 1 1
1 1
1
4 57
80 60 40 20

Output
5
101
2
2
60

-----Note-----

The first test case is described in the statement.

In the second test case, the person has one hundred future contests, so he can take place $1,2,\ldots,99$ and place $101$ on them in some order, to collect places $1,2,\ldots,101$.

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

import io, sys, atexit, os
import math as ma
from decimal import Decimal as dec
from itertools import permutations
from itertools import combinations

def li():
    return list(map(int, sys.stdin.readline().split()))

def num():
    return list(map(int, sys.stdin.readline().split()))

def nu():
    return int(input())

def find_gcd(x, y):
    while (y):
        x, y = y, x % y
    return x

def lcm(x, y):
    gg = find_gcd(x, y)
    return (x * y // gg)

mm = 1000000007

def solve():
    t = nu()
    for tt in range(t):
        n,x=num()
        a=li()
        s=set(a)
        cc=1
        while(x!=0):
            if(cc in s):
                cc+=1
                continue
            x-=1
            s.add(cc)
            cc+=1
        cc=1
        pp=0
        while(cc in s):
            pp+=1
            cc+=1
        print(pp)

def __starting_point():
    solve()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1331/B:
There was once young lass called Mary,

Whose jokes were occasionally scary.

On this April's Fool

Fixed limerick rules

Allowed her to trip the unwary.

Can she fill all the lines

To work at all times?

On juggling the words

Right around two-thirds

She nearly ran out of rhymes.

-----Input-----

The input contains a single integer $a$ ($4 \le a \le 998$). Not every integer in the range is a valid input for the problem; you are guaranteed that the input will be a valid integer.

-----Output-----

Output a single number.

-----Examples-----
Input
35

Output
57

Input
57

Output
319

Input
391

Output
1723

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

def main():
    import sys
    input = sys.stdin.readline

    def PrimeDecomposition(N):
        ret = {}
        n = int(N ** 0.5)
        for d in range(2, n + 1):
            while N % d == 0:
                if d not in ret:
                    ret[d] = 1
                else:
                    ret[d] += 1
                N //= d
            if N == 1:
                break
        if N != 1:
            ret[N] = 1
        return ret

    N = int(input())
    prime = PrimeDecomposition(N)
    ans = []
    for p in prime:
        for _ in range(prime[p]):
            ans.append(p)
    ans.sort()
    print(''.join(map(str, ans)))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1331/C:
-----Input-----

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

-----Output-----

Output a single number.

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

Output
2

Input
5

Output
24

Input
35

Output
50

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


I found an interesting problem on https://codeforces.com/problemset/problem/1331/D:
-----Input-----

The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.

-----Output-----

Output a single integer.

-----Examples-----
Input
A278832

Output
0

Input
A089956

Output
0

Input
A089957

Output
1

Input
A144045

Output
1

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

#!/usr/bin/env python3

a = input()
print(int(a[-1]) % 2)


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

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

-----Output-----

Output "YES" or "NO".

-----Examples-----
Input
GENIUS

Output
YES

Input
DOCTOR

Output
NO

Input
IRENE

Output
YES

Input
MARY

Output
NO

Input
SMARTPHONE

Output
NO

Input
REVOLVER

Output
YES

Input
HOLMES

Output
NO

Input
WATSON

Output
YES

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


I found an interesting problem on https://codeforces.com/problemset/problem/1332/A:
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat!

Initially, Alice's cat is located in a cell $(x,y)$ of an infinite grid. According to Alice's theory, cat needs to move:   exactly $a$ steps left: from $(u,v)$ to $(u-1,v)$;  exactly $b$ steps right: from $(u,v)$ to $(u+1,v)$;  exactly $c$ steps down: from $(u,v)$ to $(u,v-1)$;  exactly $d$ steps up: from $(u,v)$ to $(u,v+1)$.

Note that the moves can be performed in an arbitrary order. For example, if the cat has to move $1$ step left, $3$ steps right and $2$ steps down, then the walk right, down, left, right, right, down is valid.

Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is always in the area $[x_1,x_2]\times [y_1,y_2]$, i.e. for every cat's position $(u,v)$ of a walk $x_1 \le u \le x_2$ and $y_1 \le v \le y_2$ holds.

Also, note that the cat can visit the same cell multiple times.

Can you help Alice find out if there exists a walk satisfying her wishes?

Formally, the walk should contain exactly $a+b+c+d$ unit moves ($a$ to the left, $b$ to the right, $c$ to the down, $d$ to the up). Alice can do the moves in any order. Her current position $(u, v)$ should always satisfy the constraints: $x_1 \le u \le x_2$, $y_1 \le v \le y_2$. The staring point is $(x, y)$.

You are required to answer $t$ test cases independently.

-----Input-----

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

The first line of each test case contains four integers $a$, $b$, $c$, $d$ ($0 \le a,b,c,d \le 10^8$, $a+b+c+d \ge 1$).

The second line of the test case contains six integers $x$, $y$, $x_1$, $y_1$, $x_2$, $y_2$ ($-10^8 \le x_1\le x \le x_2 \le 10^8$, $-10^8 \le y_1 \le y \le y_2 \le 10^8$).

-----Output-----

For each test case, output "YES" in a separate line, if there exists a walk satisfying her wishes. Otherwise, output "NO" in a separate line.

You can print each letter in any case (upper or...

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

from math import *
for t in range(int(input())):
    a, b, c, d = map(int, input().split())
    x, y, x1, y1, x2, y2 = map(int, input().split())
    x += b - a
    y += d - c
    if (x < x1 or x > x2 or y < y1 or y > y2):
        print("No")
        continue
    if x1 == x2 and x1 == x and (a != 0 or b != 0):
        print("No")
        continue
    if y1 == y2 and y1 == y and (c != 0 or d != 0):
        print("No")
        continue
    print("Yes")


I found an interesting problem on https://codeforces.com/problemset/problem/1332/E:
Alice has got addicted to a game called Sirtet recently.

In Sirtet, player is given an $n \times m$ grid. Initially $a_{i,j}$ cubes are stacked up in the cell $(i,j)$. Two cells are called adjacent if they share a side. Player can perform the following operations:   stack up one cube in two adjacent cells;  stack up two cubes in one cell.

Cubes mentioned above are identical in height.

Here is an illustration of the game. States on the right are obtained by performing one of the above operations on the state on the left, and grey cubes are added due to the operation. [Image]

Player's goal is to make the height of all cells the same (i.e. so that each cell has the same number of cubes in it) using above operations.

Alice, however, has found out that on some starting grids she may never reach the goal no matter what strategy she uses. Thus, she is wondering the number of initial grids such that   $L \le a_{i,j} \le R$ for all $1 \le i \le n$, $1 \le j \le m$;  player can reach the goal using above operations.

Please help Alice with it. Notice that the answer might be large, please output the desired value modulo $998,244,353$.

-----Input-----

The only line contains four integers $n$, $m$, $L$ and $R$ ($1\le n,m,L,R \le 10^9$, $L \le R$, $n \cdot m \ge 2$).

-----Output-----

Output one integer, representing the desired answer modulo $998,244,353$.

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

Output
1

Input
1 2 1 2

Output
2

-----Note-----

In the first sample, the only initial grid that satisfies the requirements is $a_{1,1}=a_{2,1}=a_{1,2}=a_{2,2}=1$. Thus the answer should be $1$.

In the second sample, initial grids that satisfy the requirements are $a_{1,1}=a_{1,2}=1$ and $a_{1,1}=a_{1,2}=2$. Thus the answer should be $2$.

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

n, m, L, R = list(map(int, input().split()))
mod = 998244353
if n * m % 2 == 1:
    print(pow(R - L + 1, n * m, mod))
else:
    val = pow(R - L + 1, n * m, mod)
    if pow(R - L + 1, n * m, 2) == 0:
        print(val * pow(2, mod - 2, mod) % mod)
    else:
        print(((val - 1) * pow(2, mod - 2, mod) + 1) % mod)


I found an interesting problem on https://codeforces.com/problemset/problem/1332/F:
Eric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.

Given a graph $G=(V,E)$, an independent set is a subset of vertices $V' \subset V$ such that for every pair $u,v \in V'$, $(u,v) \not \in E$ (i.e. no edge in $E$ connects two vertices from $V'$).

An edge-induced subgraph consists of a subset of edges $E' \subset E$ and all the vertices in the original graph that are incident on at least one edge in the subgraph.

Given $E' \subset E$, denote $G[E']$ the edge-induced subgraph such that $E'$ is the edge set of the subgraph. Here is an illustration of those definitions: [Image]

In order to help his students get familiar with those definitions, he leaves the following problem as an exercise:

Given a tree $G=(V,E)$, calculate the sum of $w(H)$ over all except null edge-induced subgraph $H$ of $G$, where $w(H)$ is the number of independent sets in $H$. Formally, calculate $\sum \limits_{\emptyset \not= E' \subset E} w(G[E'])$.

Show Eric that you are smarter than his students by providing the correct answer as quickly as possible. Note that the answer might be large, you should output the answer modulo $998,244,353$.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 3 \cdot 10^5$), representing the number of vertices of the graph $G$.

Each of the following $n-1$ lines contains two integers $u$ and $v$ ($1 \le u,v \le n$, $u \not= v$), describing edges of the given tree.

It is guaranteed that the given edges form a tree.

-----Output-----

Output one integer, representing the desired value modulo $998,244,353$.

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

Output
3

Input
3
1 2
3 2

Output
11

-----Note-----

For the second example, all independent sets are listed below. $\vdots : \vdots : \vdots$

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

import sys
readline = sys.stdin.readline

def parorder(Edge, p):
    N = len(Edge)
    par = [0]*N
    par[p] = -1
    stack = [p]
    order = []
    visited = set([p])
    ast = stack.append
    apo = order.append
    while stack:
        vn = stack.pop()
        apo(vn)
        for vf in Edge[vn]:
            if vf in visited:
                continue
            visited.add(vf)
            par[vf] = vn
            ast(vf)
    return par, order

def getcld(p):
    res = [[] for _ in range(len(p))]
    for i, v in enumerate(p[1:], 1):
        res[v].append(i)
    return res

N = int(readline())
MOD = 998244353
Edge = [[] for _ in range(N)]
for _ in range(N-1):
    a, b = map(int, readline().split())
    a -= 1
    b -= 1
    Edge[a].append(b)
    Edge[b].append(a)

P, L = parorder(Edge, 0)
C = getcld(P)

dp = [[1, 1, 0, 0, 1] for _ in range(N)]
for p in L[::-1]:
    if not C[p]:
        continue
    res = 1
    res2 = 1
    res3 = 1
    for ci in C[p]:
        res = (res*(dp[ci][2] + dp[ci][3] + dp[ci][4])) % MOD
        res2 = (res2*(dp[ci][1] + dp[ci][2] + 2*dp[ci][3] + dp[ci][4])) % MOD
        res3 = (res3*(sum(dp[ci]) + dp[ci][2] + dp[ci][3])) % MOD
    dp[p][0] = res
    dp[p][1] = res
    dp[p][2] = (res2 - res)%MOD
    dp[p][3] = (res3 - res)%MOD
    dp[p][4] = res
print((dp[0][2] + dp[0][3] + dp[0][4] - 1) %MOD)


I found an interesting problem on https://codeforces.com/problemset/problem/1333/A:
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.

Artem wants to paint an $n \times m$ board. Each cell of the board should be colored in white or black.

Lets $B$ be the number of black cells that have at least one white neighbor adjacent by the side. Let $W$ be the number of white cells that have at least one black neighbor adjacent by the side. A coloring is called good if $B = W + 1$.

The first coloring shown below has $B=5$ and $W=4$ (all cells have at least one neighbor with the opposite color). However, the second coloring is not good as it has $B=4$, $W=4$ (only the bottom right cell doesn't have a neighbor with the opposite color). [Image]

Please, help Medina to find any good coloring. It's guaranteed that under given constraints the solution always exists. If there are several solutions, output any of them.

-----Input-----

Each test contains multiple test cases.

The first line contains the number of test cases $t$ ($1 \le t \le 20$). Each of the next $t$ lines contains two integers $n, m$ ($2 \le n,m \le 100$) — the number of rows and the number of columns in the grid.

-----Output-----

For each test case print $n$ lines, each of length $m$, where $i$-th line is the $i$-th row of your colored matrix (cell labeled with 'B' means that the cell is black, and 'W' means white). Do not use quotes.

It's guaranteed that under given constraints the solution always exists.

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

Output
BW
WB
BB
BWB
BWW
BWB

-----Note-----

In the first testcase, $B=3$, $W=2$.

In the second testcase, $B=5$, $W=4$. You can see the coloring in the statement.

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

t=int(input())
for _ in range(t):
    n,m=list(map(int,input().split()))
    ar=[['B']*m for i in range(n)]
    ar[0][0]='W'
    for x in ar:
        s=""
        for y in x:
            s+=y
        print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1333/C:
Eugene likes working with arrays. And today he needs your help in solving one challenging task.

An array $c$ is a subarray of an array $b$ if $c$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array $[-1, 2, -3]$ is good, as all arrays $[-1]$, $[-1, 2]$, $[-1, 2, -3]$, $[2]$, $[2, -3]$, $[-3]$ have nonzero sums of elements. However, array $[-1, 2, -1, -3]$ isn't good, as his subarray $[-1, 2, -1]$ has sum of elements equal to $0$.

Help Eugene to calculate the number of nonempty good subarrays of a given array $a$.

-----Input-----

The first line of the input contains a single integer $n$ ($1 \le n \le 2 \times 10^5$)  — the length of array $a$.

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

-----Output-----

Output a single integer  — the number of good subarrays of $a$.

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

Output
5

Input
3
41 -41 41

Output
3

-----Note-----

In the first sample, the following subarrays are good: $[1]$, $[1, 2]$, $[2]$, $[2, -3]$, $[-3]$. However, the subarray $[1, 2, -3]$ isn't good, as its subarray $[1, 2, -3]$ has sum of elements equal to $0$.

In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray $[41, -41, 41]$ isn't good, as its subarray $[41, -41]$ has sum of elements equal to $0$.

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

n=int(input())
a=list(int(i) for i in input().split())
p=[0]*(n+1)
for i in range(0,n) :
	p[i+1]+=p[i]+a[i]
ok=dict()
ans,l=0,0
for i in range(n+1) :
	if p[i] in ok :
		ok[p[i]]+=1
	else :
		ok[p[i]]=1
	while ok[p[i]]>1:
		ok[p[l]]-=1
		l+=1
	ans+=(i-l+1)
print(ans-n-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1333/D:
There are $n$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.

Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.

You are given the number $n$, the initial arrangement of children and the number $k$. You have to find a way for the children to act if they want to finish the process in exactly $k$ seconds. More formally, for each of the $k$ moves, you need to output the numbers of the children who turn left during this move.

For instance, for the configuration shown below and $k = 2$ children can do the following steps:  [Image]  At the beginning, two pairs make move: $(1, 2)$ and $(3, 4)$. After that, we receive the following configuration:  [Image]  At the second move pair $(2, 3)$ makes the move. The final configuration is reached. Good job.  [Image]

It is guaranteed that if the solution exists, it takes not more than $n^2$ "headturns".

-----Input-----

The first line of input contains two integers $n$ and $k$ ($2 \le n \le 3000$, $1 \le k \le 3000000$)  — the number of children and required number of moves.

The next line contains a string of length $n$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.

-----Output-----

If there is no solution, print a single line with number $-1$.

Otherwise, output $k$ lines. Each line has to start with a number $n_i$ ($1\le n_i \le \frac{n}{2}$)  — the number of pairs of children, who...

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

n,k=map(int,input().split())
a=list(input())
ans,cnt=list(list()),0
while True :
	cur=list()
	for i in range(n-1) :
		if a[i]=='R' and a[i+1]=='L' :
			cur.append(i)
			cnt+=1
	if len(cur)>0:
		ans.append(cur.copy())
		for i in cur :
			a[i],a[i+1]=a[i+1],a[i]
	else :
		break
if len(ans)>k or cnt<k:
	print(-1)
else :
	lst=list()
	dumb=k-len(ans)
	w,p=0,0
	while dumb>0 :
		lst.append("1 "+str(ans[w][p]+1)+"\n")
		dumb-=1
		p+=1
		if p==len(ans[w]) :
			p=0
			w+=1
			dumb+=1
	while w<len(ans) :
		lst.append(str(len(ans[w])-p)+" ")
		while p<len(ans[w]) :
			lst.append(str(ans[w][p]+1)+" ")
			p+=1
		lst.append("\n")
		w+=1
		p=0
	print("".join(lst))


I found an interesting problem on https://codeforces.com/problemset/problem/1333/E:
Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!

Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The queen walks in all directions vertically and diagonally at any distance. You can see the examples below. [Image]

To reach the goal, Egor should research the next topic:

There is an $N \times N$ board. Each cell of the board has a number from $1$ to $N ^ 2$ in it and numbers in all cells are distinct.

In the beginning, some chess figure stands in the cell with the number $1$. Note that this cell is already considered as visited. After that every move is determined by the following rules:   Among all not visited yet cells to which the figure can get in one move, it goes to the cell that has minimal number. If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of $1$ vun. If all cells are already visited, the process is stopped.

Egor should find an $N \times N$ board on which the rook pays strictly less vuns than the queen during the round with this numbering. Help him to find such $N \times N$ numbered board, or tell that it doesn't exist.

-----Input-----

The only line contains one integer $N$  — the size of the board, $1\le N \le 500$.

-----Output-----

The output should contain $N$ lines.

In $i$-th line output $N$ numbers  — numbers on the $i$-th row of the board. All numbers from $1$ to $N \times N$ must be used exactly once.

On your board rook must pay strictly less vuns than the queen.

If there are no solutions, print $-1$.

If there are several solutions, you can output any of them.

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

Output
-1
Input
4

Output
4 3 6 12
7 5 9 15
14 1 11 10
13 8 16 2

-----Note-----

In case we have...

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


I found an interesting problem on https://codeforces.com/problemset/problem/1333/F:
Kate has a set $S$ of $n$ integers $\{1, \dots, n\} $.

She thinks that imperfection of a subset $M \subseteq S$ is equal to the maximum of $gcd(a, b)$ over all pairs $(a, b)$ such that both $a$ and $b$ are in $M$ and $a \neq b$.

Kate is a very neat girl and for each $k \in \{2, \dots, n\}$ she wants to find a subset that has the smallest imperfection among all subsets in $S$ of size $k$. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size $k$, will name it $I_k$.

Please, help Kate to find $I_2$, $I_3$, ..., $I_n$.

-----Input-----

The first and only line in the input consists of only one integer $n$ ($2\le n \le 5 \cdot 10^5$)  — the size of the given set $S$.

-----Output-----

Output contains only one line that includes $n - 1$ integers: $I_2$, $I_3$, ..., $I_n$.

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

Output
1
Input
3

Output
1 1

-----Note-----

First sample: answer is 1, because $gcd(1, 2) = 1$.

Second sample: there are subsets of $S$ with sizes $2, 3$ with imperfection equal to 1. For example, $\{2,3\}$ and $\{1, 2, 3\}$.

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

n = int(input())
l = []
for i in range(n + 1):
    l.append(0)
for i in range(2, n + 1):
    for j in range(i * 2, n + 1, i):
        l[j] = i
l.sort()
for i in range(2, n + 1):
    if l[i] == 0:
        print(1, end=" ")
    else:
        print(l[i], end=" ")


I found an interesting problem on https://codeforces.com/problemset/problem/1334/A:
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.

All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by $1$. If he manages to finish the level successfully then the number of clears increases by $1$ as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).

Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.

So he peeked at the stats $n$ times and wrote down $n$ pairs of integers — $(p_1, c_1), (p_2, c_2), \dots, (p_n, c_n)$, where $p_i$ is the number of plays at the $i$-th moment of time and $c_i$ is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).

Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.

Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.

Help him to check the correctness of his records.

For your convenience you have to answer multiple independent test cases.

-----Input-----

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

The first line of each test case contains a single integer $n$ ($1 \le n \le 100$) — the number of moments of time Polycarp peeked at the stats.

Each of the next $n$ lines contains two integers $p_i$ and $c_i$ ($0 \le p_i, c_i \le 1000$) — the number of plays and the number of clears of the level at the...

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

from collections import *
import sys
try: inp = raw_input
except: inp = input
def err(s):
    sys.stderr.write('{}\n'.format(s))

def ni():
    return int(inp())

def nl():
    return [int(_) for _ in inp().split()]

T = ni()
for _ in range(T):
    N = ni()
    lp, lc = 0, 0
    fail = False
    for _ in range(N):
        p, c = nl()
        dp = p - lp
        dc = c - lc
        lp, lc = p, c
        if dp < dc or dc < 0:
            fail = True
    if fail:
        print('NO')
    else:
        print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/1334/B:
Many years ago Berland was a small country where only $n$ people lived. Each person had some savings: the $i$-th one had $a_i$ burles.

The government considered a person as wealthy if he had at least $x$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that:   the government chooses some subset of people (maybe all of them);  the government takes all savings from the chosen people and redistributes the savings among the chosen people equally.

For example, consider the savings as list $[5, 1, 2, 1]$: if the government chose the $1$-st and the $3$-rd persons then it, at first, will take all $5 + 2 = 7$ burles and after that will return $3.5$ burles to the chosen people. As a result, the savings will become $[3.5, 1, 3.5, 1]$.

A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.

-----Input-----

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

Next $2T$ lines contain the test cases — two lines per test case. The first line contains two integers $n$ and $x$ ($1 \le n \le 10^5$, $1 \le x \le 10^9$) — the number of people and the minimum amount of money to be considered as wealthy.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the initial savings of each person.

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

-----Output-----

Print $T$ integers — one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms.

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

Output
2
4
0
3

-----Note-----

The first test case is described in the statement.

In the second test case, the government, for example, could carry out two reforms: $[\underline{11}, \underline{9}, 11, 9] \rightarrow [10, 10,...

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

for ahfiuyh in range(int(input())):
    n, x = list(map(int,input().split()))
    a = list(map(int,input().split()))
    a.sort(reverse = True)
    s = 0
    cc = 0
    f = True
    for i in range(n):
        cc += 1
        s += a[i]
        if s // cc < x:
            print(i)
            f= False
            break
    if f:print(n)


I found an interesting problem on https://codeforces.com/problemset/problem/1334/D:
You are given a complete directed graph $K_n$ with $n$ vertices: each pair of vertices $u \neq v$ in $K_n$ have both directed edges $(u, v)$ and $(v, u)$; there are no self-loops.

You should find such a cycle in $K_n$ that visits every directed edge exactly once (allowing for revisiting vertices).

We can write such cycle as a list of $n(n - 1) + 1$ vertices $v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$ — a visiting order, where each $(v_i, v_{i + 1})$ occurs exactly once.

Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.

Since the answer can be too large print its $[l, r]$ segment, in other words, $v_l, v_{l + 1}, \dots, v_r$.

-----Input-----

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

Next $T$ lines contain test cases — one per line. The first and only line of each test case contains three integers $n$, $l$ and $r$ ($2 \le n \le 10^5$, $1 \le l \le r \le n(n - 1) + 1$, $r - l + 1 \le 10^5$) — the number of vertices in $K_n$, and segment of the cycle to print.

It's guaranteed that the total sum of $n$ doesn't exceed $10^5$ and the total sum of $r - l + 1$ doesn't exceed $10^5$.

-----Output-----

For each test case print the segment $v_l, v_{l + 1}, \dots, v_r$ of the lexicographically smallest cycle that visits every edge exactly once.

-----Example-----
Input
3
2 1 3
3 3 6
99995 9998900031 9998900031

Output
1 2 1
1 3 2 3
1

-----Note-----

In the second test case, the lexicographically minimum cycle looks like: $1, 2, 1, 3, 2, 3, 1$.

In the third test case, it's quite obvious that the cycle should start and end in vertex $1$.

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

t = int(input())
for case_num in range(t):
    n, l, r = list(map(int, input().split(' ')))
    if l == n * (n-1) + 1:
        print(1)
        continue
    total = 0
    unvisited = n - 1
    while total < l:
        total += unvisited * 2
        unvisited -= 1
    unvisited += 1
    total -= unvisited * 2
    current = n - unvisited
    nxt = current + 1
    ans = []
    while total < r:
        total += 1
        now = current if total % 2 == 1 else nxt
        if now == nxt:
            nxt += 1
            if nxt > n:
                current += 1
                nxt = current + 1
                if current == n:
                    current = 1
        if total >= l:
            ans.append(now)
    print(' '.join(map(str, ans)))


I found an interesting problem on https://codeforces.com/problemset/problem/1334/E:
You are given a positive integer $D$. Let's build the following graph from it:   each vertex is a divisor of $D$ (not necessarily prime, $1$ and $D$ itself are also included);  two vertices $x$ and $y$ ($x > y$) have an undirected edge between them if $x$ is divisible by $y$ and $\frac x y$ is a prime;  the weight of an edge is the number of divisors of $x$ that are not divisors of $y$.

For example, here is the graph for $D=12$:  [Image]

Edge $(4,12)$ has weight $3$ because $12$ has divisors $[1,2,3,4,6,12]$ and $4$ has divisors $[1,2,4]$. Thus, there are $3$ divisors of $12$ that are not divisors of $4$ — $[3,6,12]$.

There is no edge between $3$ and $2$ because $3$ is not divisible by $2$. There is no edge between $12$ and $3$ because $\frac{12}{3}=4$ is not a prime.

Let the length of the path between some vertices $v$ and $u$ in the graph be the total weight of edges on it. For example, path $[(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)]$ has length $1+2+2+3+1+2=11$. The empty path has length $0$.

So the shortest path between two vertices $v$ and $u$ is the path that has the minimal possible length.

Two paths $a$ and $b$ are different if there is either a different number of edges in them or there is a position $i$ such that $a_i$ and $b_i$ are different edges.

You are given $q$ queries of the following form:   $v$ $u$ — calculate the number of the shortest paths between vertices $v$ and $u$.

The answer for each query might be large so print it modulo $998244353$.

-----Input-----

The first line contains a single integer $D$ ($1 \le D \le 10^{15}$) — the number the graph is built from.

The second line contains a single integer $q$ ($1 \le q \le 3 \cdot 10^5$) — the number of queries.

Each of the next $q$ lines contains two integers $v$ and $u$ ($1 \le v, u \le D$). It is guaranteed that $D$ is divisible by both $v$ and $u$ (both $v$ and $u$ are divisors of $D$).

-----Output-----

Print $q$ integers — for each query output the number of the shortest paths between the two given vertices...

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

def main():
    import sys
    input=sys.stdin.readline
    mod=998244353
    N=10**5+3
    fac=[1]*(N+1)
    for i in range(1,N+1):
        fac[i]=fac[i-1]*i%mod
    inv_fac=[1]*(N+1)
    inv_fac[N]=pow(fac[N],mod-2,mod)
    for i in range(N-1,0,-1):
        inv_fac[i]=inv_fac[i+1]*(i+1)%mod
    D=int(input())
    A=[]
    for i in range(2,int(D**.5)+1):
        c=0
        while D%i==0:
            D//=i
            c+=1
        if c!=0:
        	A.append(i)
    if D>=2:
        A.append(D)
    l=len(A)
    q=int(input())
    for _ in range(q):
        u,v=map(int,input().split())
        l1=[0]*l
        l2=[0]*l
        l3=[0]*l
        for i in range(l):
            while u%A[i]==0:
                l1[i]+=1
                u//=A[i]
            while v%A[i]==0:
                l2[i]+=1
                v//=A[i]
            l3[i]=l1[i]-l2[i]
        ans1=1
        ans2=1
        s1=0
        s2=0
        for i in range(l):
            if l3[i]>=0:
                ans1=ans1*inv_fac[l3[i]]%mod
                s1+=l3[i]
            else:
                ans2=ans2*inv_fac[-l3[i]]%mod
                s2-=l3[i]
        ans1=ans1*fac[s1]%mod
        ans2=ans2*fac[s2]%mod
        print(ans1*ans2%mod)
def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1335/A:
There are two sisters Alice and Betty. You have $n$ candies. You want to distribute these $n$ candies between two sisters in such a way that:  Alice will get $a$ ($a > 0$) candies;  Betty will get $b$ ($b > 0$) candies;  each sister will get some integer number of candies;  Alice will get a greater amount of candies than Betty (i.e. $a > b$);  all the candies will be given to one of two sisters (i.e. $a+b=n$).

Your task is to calculate the number of ways to distribute exactly $n$ candies between sisters in a way described above. Candies are indistinguishable.

Formally, find the number of ways to represent $n$ as the sum of $n=a+b$, where $a$ and $b$ are positive integers and $a>b$.

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 a test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^9$) — the number of candies you have.

-----Output-----

For each test case, print the answer — the number of ways to distribute exactly $n$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $0$.

-----Example-----
Input
6
7
1
2
3
2000000000
763243547

Output
3
0
0
1
999999999
381621773

-----Note-----

For the test case of the example, the $3$ possible ways to distribute candies are:  $a=6$, $b=1$;  $a=5$, $b=2$;  $a=4$, $b=3$.

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

import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy

ORDA = 97
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return [int(i) for i in input().split()]
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def revn(n): return str(n)[::-1]
def dd(): return collections.defaultdict(int)
def ddl(): return collections.defaultdict(list)
def sieve(n):
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r
def divs(n, start=1):
    r = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if (n % i == 0):
            if (n / i == i):
                r.append(i)
            else:
                r.extend([i, n // i])
    return r
def divn(n, primes):
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t
def prime(n):
    if n == 2: return True
    if n % 2 == 0 or n <= 1: return False
    sqr = int(math.sqrt(n)) + 1
    for d in range(3, sqr, 2):
        if n % d == 0: return False
    return True
def convn(number, base):
    newnumber = 0
    while number > 0:
        newnumber += number % base
        number //= base
    return newnumber
def cdiv(n, k): return n // k + (n % k != 0)

for i in range(ii()):
    n = ii()
    if n & 1:
        print(n // 2)
    else:
        print(n // 2 - 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1335/B:
You are given three positive integers $n$, $a$ and $b$. You have to construct a string $s$ of length $n$ consisting of lowercase Latin letters such that each substring of length $a$ has exactly $b$ distinct letters. It is guaranteed that the answer exists.

You have to answer $t$ independent test cases.

Recall that the substring $s[l \dots r]$ is the string $s_l, s_{l+1}, \dots, s_{r}$ and its length is $r - l + 1$. In this problem you are only interested in substrings of length $a$.

-----Input-----

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

The only line of a test case contains three space-separated integers $n$, $a$ and $b$ ($1 \le a \le n \le 2000, 1 \le b \le \min(26, a)$), where $n$ is the length of the required string, $a$ is the length of a substring and $b$ is the required number of distinct letters in each substring of length $a$.

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

-----Output-----

For each test case, print the answer — such a string $s$ of length $n$ consisting of lowercase Latin letters that each substring of length $a$ has exactly $b$ distinct letters. If there are multiple valid answers, print any of them. It is guaranteed that the answer exists.

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

Output
tleelte
qwerty
vvvvvv
abcde

-----Note-----

In the first test case of the example, consider all the substrings of length $5$:  "tleel": it contains $3$ distinct (unique) letters,  "leelt": it contains $3$ distinct (unique) letters,  "eelte": it contains $3$ distinct (unique) letters.

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

t = int(input(''))
c = []
for i in range(97,123,1):
    c.append(chr(i))
for _ in range(t):
    n,a,b = list(map(int,input('').split(' ')))
    s = ''
    for i in range(n):
        s = s+c[i%b]
    print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1335/C:
You have $n$ students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the $i$-th student skill is denoted by an integer $a_i$ (different students can have the same skills).

So, about the teams. Firstly, these two teams should have the same size. Two more constraints:  The first team should consist of students with distinct skills (i.e. all skills in the first team are unique).  The second team should consist of students with the same skills (i.e. all skills in the second team are equal).

Note that it is permissible that some student of the first team has the same skill as a student of the second team.

Consider some examples (skills are given):  $[1, 2, 3]$, $[4, 4]$ is not a good pair of teams because sizes should be the same;  $[1, 1, 2]$, $[3, 3, 3]$ is not a good pair of teams because the first team should not contain students with the same skills;  $[1, 2, 3]$, $[3, 4, 4]$ is not a good pair of teams because the second team should contain students with the same skills;  $[1, 2, 3]$, $[3, 3, 3]$ is a good pair of teams;  $[5]$, $[6]$ is a good pair of teams.

Your task is to find the maximum possible size $x$ for which it is possible to compose a valid pair of teams, where each team size is $x$ (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.

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 first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of students. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the skill of the $i$-th student. Different students can have the same skills.

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

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

t=int(input())
while t:
    n=int(input())
    a=list(map(int,input().split()))
    ls=[0 for i in range(n+1)]
    for i in range(n):
        ls[a[i]]+=1
    dis=len(set(a))
    sam=max(ls)
    print(max(min(dis-1,sam),min(dis,sam-1)))
    t-=1


I found an interesting problem on https://codeforces.com/problemset/problem/1335/D:
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.

The picture showing the correct sudoku solution:

[Image]

Blocks are bordered with bold black color.

Your task is to change at most $9$ elements of this field (i.e. choose some $1 \le i, j \le 9$ and change the number at the position $(i, j)$ to any other number in range $[1; 9]$) to make it anti-sudoku. The anti-sudoku is the $9 \times 9$ field, in which:  Any number in this field is in range $[1; 9]$;  each row contains at least two equal elements;  each column contains at least two equal elements;  each $3 \times 3$ block (you can read what is the block in the link above) contains at least two equal elements.

It is guaranteed that the answer exists.

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.

Each test case consists of $9$ lines, each line consists of $9$ characters from $1$ to $9$ without any whitespaces — the correct solution of the sudoku puzzle.

-----Output-----

For each test case, print the answer — the initial field with at most $9$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.

-----Example-----
Input
1
154873296
386592714
729641835
863725149
975314628
412968357
631457982
598236471
247189563

Output
154873396
336592714
729645835
863725145
979314628
412958357
631457992
998236471
247789563

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

for _ in range(int(input())):
    a = [0]*9
    for i in range(9):
        a[i] = list(input())
        a[i][a[i].index('2')] = '1'
        print(''.join(a[i]))


I found an interesting problem on https://codeforces.com/problemset/problem/1337/A:
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.

These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now she is solving the following problem.[Image]

You are given four positive integers $a$, $b$, $c$, $d$, such that $a \leq b \leq c \leq d$.

Your task is to find three integers $x$, $y$, $z$, satisfying the following conditions: $a \leq x \leq b$. $b \leq y \leq c$. $c \leq z \leq d$. There exists a triangle with a positive non-zero area and the lengths of its three sides are $x$, $y$, and $z$.

Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?

-----Input-----

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

The next $t$ lines describe test cases. Each test case is given as four space-separated integers $a$, $b$, $c$, $d$ ($1 \leq a \leq b \leq c \leq d \leq 10^9$).

-----Output-----

For each test case, print three integers $x$, $y$, $z$  — the integers you found satisfying the conditions given in the statement.

It is guaranteed that the answer always exists. If there are multiple answers, print any.

-----Example-----
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810

Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810

-----Note-----

One of the possible solutions to the first test case:

[Image]

One of the possible solutions to the second test case:

[Image]

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

from sys import stdin
input = stdin.readline

for _ in range(int(input())):
    a, b, c, d = map(int, input().split())
    print(b, c, c)


I found an interesting problem on https://codeforces.com/problemset/problem/1337/B:
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.

One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.[Image]

The dragon has a hit point of $x$ initially. When its hit point goes to $0$ or under $0$, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells.  Void Absorption

Assume that the dragon's current hit point is $h$, after casting this spell its hit point will become $\left\lfloor \frac{h}{2} \right\rfloor + 10$. Here $\left\lfloor \frac{h}{2} \right\rfloor$ denotes $h$ divided by two, rounded down. Lightning Strike

This spell will decrease the dragon's hit point by $10$. Assume that the dragon's current hit point is $h$, after casting this spell its hit point will be lowered to $h-10$.

Due to some reasons Kana can only cast no more than $n$ Void Absorptions and $m$ Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.

-----Input-----

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

The next $t$ lines describe test cases. For each test case the only line contains three integers $x$, $n$, $m$ ($1\le x \le 10^5$, $0\le n,m\le30$)  — the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.

-----Output-----

If it is possible to defeat the dragon, print "YES" (without quotes). Otherwise, print "NO" (without quotes).

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

-----Example-----
Input
7
100 3 4
189 3 4
64 2 3
63 2 3
30 27 7
10 9 1
69117 21 2

Output
YES
NO
NO
YES
YES
YES
YES

-----Note-----

One possible casting sequence of the first test case is shown below: Void Absorption $\left\lfloor...

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

def main():
    x, n, m = list(map(int, input().split()))
    while x > 20 and n > 0:
        n -= 1
        x = x//2 + 10
    if x > m * 10:
        print("NO")
    else:
        print("YES")

def __starting_point():
    t = int(input())
    for i in range(t):
        main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1337/E:
Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. [Image]

Kaavi has a string $T$ of length $m$ and all the strings with the prefix $T$ are magic spells. Kaavi also has a string $S$ of length $n$ and an empty string $A$.

During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: Delete the first character of $S$ and add it at the front of $A$. Delete the first character of $S$ and add it at the back of $A$.

Kaavi can perform no more than $n$ operations. To finish the divination, she wants to know the number of different operation sequences to make $A$ a magic spell (i.e. with the prefix $T$). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo $998\,244\,353$.

Two operation sequences are considered different if they are different in length or there exists an $i$ that their $i$-th operation is different.

A substring is a contiguous sequence of characters within a string. A prefix of a string $S$ is a substring of $S$ that occurs at the beginning of $S$.

-----Input-----

The first line contains a string $S$ of length $n$ ($1 \leq n \leq 3000$).

The second line contains a string $T$ of length $m$ ($1 \leq m \leq n$).

Both strings contain only lowercase Latin letters.

-----Output-----

The output contains only one integer  — the answer modulo $998\,244\,353$.

-----Examples-----
Input
abab
ba

Output
12
Input
defineintlonglong
signedmain

Output
0
Input
rotator
rotator

Output
4
Input
cacdcdbbbb
bdcaccdbbb

Output
24

-----Note-----

The first test:

$\text{baba abab bbaa baab baab}$

The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of $A$, although the results are the same, they are considered as...

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

import sys
readline = sys.stdin.readline

S = input()
T = '*' + input()
n, m = len(S), len(T)
mod = 998244353
dp = [[0]*(n+5) for _ in range(n+5)]
for i in range(n+1):
    dp[i][i+1] = 1

for i, c in enumerate(S, start=1):
    for l, r in zip(list(range(0, n+1)), list(range(i, n+2))):
        if l >= m or 0 < l and T[l] == c:
            dp[l-1][r] += dp[l][r] % mod
        if r >= m or T[r] == c:
            dp[l][r+1] += dp[l][r] % mod

print(sum(dp[0][m:]) % mod)


I found an interesting problem on https://codeforces.com/problemset/problem/1339/A:
You have integer $n$. Calculate how many ways are there to fully cover belt-like area of $4n-2$ triangles with diamond shapes.

Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it.

$2$ coverings are different if some $2$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.

Please look at pictures below for better understanding.

 $\theta$ On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill.

[Image] These are the figures of the area you want to fill for $n = 1, 2, 3, 4$.

You have to answer $t$ independent test cases.

-----Input-----

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

Each of the next $t$ lines contains a single integer $n$ ($1 \le n \le 10^{9}$).

-----Output-----

For each test case, print the number of ways to fully cover belt-like area of $4n-2$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $10^{18}$.

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

Output
2
1

-----Note-----

In the first test case, there are the following $2$ ways to fill the area:

 [Image]

In the second test case, there is a unique way to fill the area:

 [Image]

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

for i in range(int(input())):
    # arr = list(map(int,input().split()))
    am = int(input())
    print(am)


I found an interesting problem on https://codeforces.com/problemset/problem/1339/B:
You have array of $n$ numbers $a_{1}, a_{2}, \ldots, a_{n}$.

Rearrange these numbers to satisfy $|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$, where $|x|$ denotes absolute value of $x$. It's always possible to find such rearrangement.

Note that all numbers in $a$ are not necessarily different. In other words, some numbers of $a$ may be same.

You have to answer independent $t$ test cases.

-----Input-----

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

The first line of each test case contains single integer $n$ ($3 \le n \le 10^{5}$) — the length of array $a$. It is guaranteed that the sum of values of $n$ over all test cases in the input does not exceed $10^{5}$.

The second line of each test case contains $n$ integers $a_{1}, a_{2}, \ldots, a_{n}$ ($-10^{9} \le a_{i} \le 10^{9}$).

-----Output-----

For each test case, print the rearranged version of array $a$ which satisfies given condition. If there are multiple valid rearrangements, print any of them.

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

Output
5 5 4 6 8 -2
1 2 4 8

-----Note-----

In the first test case, after given rearrangement, $|a_{1} - a_{2}| = 0 \le |a_{2} - a_{3}| = 1 \le |a_{3} - a_{4}| = 2 \le |a_{4} - a_{5}| = 2 \le |a_{5} - a_{6}| = 10$. There are other possible answers like "5 4 5 6 -2 8".

In the second test case, after given rearrangement, $|a_{1} - a_{2}| = 1 \le |a_{2} - a_{3}| = 2 \le |a_{3} - a_{4}| = 4$. There are other possible answers like "2 4 8 1".

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 = int(input())
    A = list(map(int, input().split()))
    Query.append((N, A))

for N, A in Query:
    A.sort()
    l = 0
    r = N-1
    ans = []
    for i in range(N):
        if i%2 == 0:
            ans.append(str(A[l]))
            l += 1
        else:
            ans.append(str(A[r]))
            r -= 1
    print(" ".join(ans[::-1]))


I found an interesting problem on https://codeforces.com/problemset/problem/1341/A:
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.

In total, Nastya dropped $n$ grains. Nastya read that each grain weighs some integer number of grams from $a - b$ to $a + b$, inclusive (numbers $a$ and $b$ are known), and the whole package of $n$ grains weighs from $c - d$ to $c + d$ grams, inclusive (numbers $c$ and $d$ are known). The weight of the package is the sum of the weights of all $n$ grains in it.

Help Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the $i$-th grain weighs some integer number $x_i$ $(a - b \leq x_i \leq a + b)$, and in total they weigh from $c - d$ to $c + d$, inclusive ($c - d \leq \sum\limits_{i=1}^{n}{x_i} \leq c + d$).

-----Input-----

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

The next $t$ lines contain descriptions of the test cases, each line contains $5$ integers: $n$ $(1 \leq n \leq 1000)$  — the number of grains that Nastya counted and $a, b, c, d$ $(0 \leq b < a \leq 1000, 0 \leq d < c \leq 1000)$  — numbers that determine the possible weight of one grain of rice (from $a - b$ to $a + b$) and the possible total weight of the package (from $c - d$ to $c + d$).

-----Output-----

For each test case given in the input print "Yes", if the information about the weights is not inconsistent, and print "No" if $n$ grains with masses from $a - b$ to $a + b$ cannot make a package with a total mass from $c - d$ to $c + d$.

-----Example-----
Input
5
7 20 3 101 18
11 11 10 234 2
8 9 7 250 122
19 41 21 321 10
3 10 8 6 1

Output
Yes
No
Yes
No
Yes

-----Note-----

In the first test case of the example, we can assume that each grain weighs $17$ grams, and a pack $119$ grams, then really Nastya could collect the whole pack.

In the third test case of the example, we can assume that each grain weighs $16$ grams,...

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

t = int(input())

for _ in range(t):
    n, a, b, c, d = list(map(int, input().split()))

    mg = n * (a - b)
    Mg = n * (a + b)
    mp = c - d
    Mp = c + d

    if mg <= Mp and Mg >= mp:
        print("Yes")
    else:
        print("No")


I found an interesting problem on https://codeforces.com/problemset/problem/1341/D:
Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer.

The poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of $7$ segments, which can be turned on or off to display different numbers. The picture shows how all $10$ decimal digits are displayed:

 [Image]

After the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke exactly $k$ segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly $k$ sticks (which are off now)?

It is allowed that the number includes leading zeros.

-----Input-----

The first line contains integer $n$ $(1 \leq n \leq 2000)$  — the number of digits on scoreboard and $k$ $(0 \leq k \leq 2000)$  — the number of segments that stopped working.

The next $n$ lines contain one binary string of length $7$, the $i$-th of which encodes the $i$-th digit of the scoreboard.

Each digit on the scoreboard consists of $7$ segments. We number them, as in the picture below, and let the $i$-th place of the binary string be $0$ if the $i$-th stick is not glowing and $1$ if it is glowing. Then a binary string of length $7$ will specify which segments are glowing now.

 [Image]

Thus, the sequences "1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" encode in sequence all digits from $0$ to $9$ inclusive.

-----Output-----

Output a single number consisting of $n$ digits  — the maximum number that can be obtained if you turn...

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

class Solution:
    def __init__(self):
        self.n, self.k = list(map(int, input().split()))
        self.s = [input() for i in range(0, self.n)]
        self.state = [
            (119, 6),
            (36, 2),
            (93, 5),
            (109, 5),
            (46, 4),
            (107, 5),
            (123, 6),
            (37, 3),
            (127, 7),
            (111, 6),
        ]
        self.p = []
        self.dp = [[False for j in range(0, self.k + 1)] for i in range(0, self.n)]

    def solve(self):
        for a in self.s:
            state = int(a[::-1], 2)
            stick = a.count("1")
            v = []
            for i, (dState, dStick) in enumerate(self.state):
                if dState & state == state:
                    v.append((i, dStick - stick))
            self.p.append(v)

        for i in range(self.n - 1, -1, -1):
            for j, stick in self.p[i]:
                if i == self.n - 1:
                    if stick <= self.k:
                        self.dp[i][stick] = True
                else:
                    for d in range(stick, self.k + 1):
                        self.dp[i][d] |= self.dp[i + 1][d - stick]
        if not self.dp[0][self.k]:
            return "-1"

        result = ""

        for i, v in enumerate(self.p):
            for j, stick in v[::-1]:
                ok = (self.k == stick) if i == self.n - 1 else (self.k >= stick and self.dp[i + 1][self.k - stick])
                if ok:
                    self.k -= stick
                    result += str(j)
                    break
        return result

print(Solution().solve())


I found an interesting problem on https://codeforces.com/problemset/problem/1341/E:
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.

On the way from Denis's house to the girl's house is a road of $n$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.

Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $g$ seconds green, and then $r$ seconds red, then again $g$ seconds green and so on.

Formally, the road can be represented as a segment $[0, n]$. Initially, Denis is at point $0$. His task is to get to point $n$ in the shortest possible time.

He knows many different integers $d_1, d_2, \ldots, d_m$, where $0 \leq d_i \leq n$  — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.

Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:  He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $\pm 1$ in $1$ second. While doing so, he must always stay inside the segment $[0, n]$.  He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $+1$ and he walked on a safety island, then he can change his position by $\pm 1$. Otherwise, he can change his position only by $+1$. Similarly, if in the previous second he changed his position by $-1$, on a safety island he can change position by $\pm 1$, and at any other point by $-1$.  At the moment when the red light is on, the boy must be on one of the...

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

import collections

n,m=map(int,input().split())
arr=list(map(int,input().split()))
arr=sorted(arr)
g,r=map(int,input().split())
q=collections.deque()
q.append((0,0,0))
checked=[[-1]*(g) for _ in range(m)]
checked[0][0]=0
while len(q)!=0:
  v,t,cnt=q.popleft()
  if v!=m-1:
    cost1=arr[v+1]-arr[v]
    if t+cost1<=g:
      if checked[v+1][(t+cost1)%g]==-1:
        if t+cost1<g:
          q.appendleft((v+1,t+cost1,cnt))
          checked[v+1][t+cost1]=cnt
        else:
          q.append((v+1,0,cnt+1))
          checked[v+1][0]=cnt+1
  if v!=0:
    cost2=arr[v]-arr[v-1]
    if t+cost2<=g:
      if checked[v-1][(t+cost2)%g]==-1:
        if t+cost2<g:
          q.appendleft((v-1,t+cost2,cnt))
          checked[v-1][t+cost2]=cnt
        else:
          q.append((v-1,0,cnt+1))
          checked[v-1][0]=cnt+1
ans=10**18
for i in range(m):
  for j in range(g):
    if checked[i][j]==-1:
      continue
    else:
      if j+n-arr[i]<=g:
        ans=min(ans,checked[i][j]*(g+r)+j+n-arr[i])
if ans==10**18:
  print(-1)
else:
  print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1342/A:
You are given two integers $x$ and $y$. You can perform two types of operations:   Pay $a$ dollars and increase or decrease any of these integers by $1$. For example, if $x = 0$ and $y = 7$ there are four possible outcomes after this operation:   $x = 0$, $y = 6$;  $x = 0$, $y = 8$;  $x = -1$, $y = 7$;  $x = 1$, $y = 7$.

  Pay $b$ dollars and increase or decrease both integers by $1$. For example, if $x = 0$ and $y = 7$ there are two possible outcomes after this operation:   $x = -1$, $y = 6$;  $x = 1$, $y = 8$.

Your goal is to make both given integers equal zero simultaneously, i.e. $x = y = 0$. There are no other requirements. In particular, it is possible to move from $x=1$, $y=0$ to $x=y=0$.

Calculate the minimum amount of dollars you have to spend on it.

-----Input-----

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

The first line of each test case contains two integers $x$ and $y$ ($0 \le x, y \le 10^9$).

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

-----Output-----

For each test case print one integer — the minimum amount of dollars you have to spend.

-----Example-----
Input
2
1 3
391 555
0 0
9 4

Output
1337
0

-----Note-----

In the first test case you can perform the following sequence of operations: first, second, first. This way you spend $391 + 555 + 391 = 1337$ dollars.

In the second test case both integers are equal to zero initially, so you dont' have to spend money.

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

for _ in range(int(input())):
    x, y = list(map(int, input().split()))
    a, b = list(map(int, input().split()))
    ans = a * abs(x - y)
    if a * 2 < b:
        ans += min(x, y) * a * 2
    else:
        ans += min(x, y) * b
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1342/B:
Let's say string $s$ has period $k$ if $s_i = s_{i + k}$ for all $i$ from $1$ to $|s| - k$ ($|s|$ means length of string $s$) and $k$ is the minimum positive integer with this property.

Some examples of a period: for $s$="0101" the period is $k=2$, for $s$="0000" the period is $k=1$, for $s$="010" the period is $k=2$, for $s$="0011" the period is $k=4$.

You are given string $t$ consisting only of 0's and 1's and you need to find such string $s$ that:  String $s$ consists only of 0's and 1's;  The length of $s$ doesn't exceed $2 \cdot |t|$;  String $t$ is a subsequence of string $s$;  String $s$ has smallest possible period among all strings that meet conditions 1—3.

Let us recall that $t$ is a subsequence of $s$ if $t$ can be derived from $s$ by deleting zero or more elements (any) without changing the order of the remaining elements. For example, $t$="011" is a subsequence of $s$="10101".

-----Input-----

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

Next $T$ lines contain test cases — one per line. Each line contains string $t$ ($1 \le |t| \le 100$) consisting only of 0's and 1's.

-----Output-----

Print one string for each test case — string $s$ you needed to find. If there are multiple solutions print any one of them.

-----Example-----
Input
4
00
01
111
110

Output
00
01
11111
1010

-----Note-----

In the first and second test cases, $s = t$ since it's already one of the optimal solutions. Answers have periods equal to $1$ and $2$, respectively.

In the third test case, there are shorter optimal solutions, but it's okay since we don't need to minimize the string $s$. String $s$ has period equal to $1$.

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):
    a = input()
    n = len(a)
    one = 0
    for c in a:
        if c == '1':
            one += 1
    if one == 0 or one == n:
        print(a)
    else:
        print(''.join(['01' for i in range(n)]))


I found an interesting problem on https://codeforces.com/problemset/problem/1342/C:
You are given two integers $a$ and $b$, and $q$ queries. The $i$-th query consists of two numbers $l_i$ and $r_i$, and the answer to it is the number of integers $x$ such that $l_i \le x \le r_i$, and $((x \bmod a) \bmod b) \ne ((x \bmod b) \bmod a)$. Calculate the answer for each query.

Recall that $y \bmod z$ is the remainder of the division of $y$ by $z$. For example, $5 \bmod 3 = 2$, $7 \bmod 8 = 7$, $9 \bmod 4 = 1$, $9 \bmod 9 = 0$.

-----Input-----

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

The first line of each test case contains three integers $a$, $b$ and $q$ ($1 \le a, b \le 200$; $1 \le q \le 500$).

Then $q$ lines follow, each containing two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le 10^{18}$) for the corresponding query.

-----Output-----

For each test case, print $q$ integers — the answers to the queries of this test case in the order they appear.

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

Output
0 0 0 2 4
0 91

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

from sys import stdin
input = stdin.readline
t = int(input())
for _ in range(t):
	a,b,q = map(int,input().split())
	przyg = [0] * (a*b)
	for i in range(a*b):
		if (i%a)%b != (i%b)%a:
			przyg[i] = 1
	cyk = sum(przyg)
	pref = [0]*(a*b)
	pref[0] = przyg[0]
	for i in range(1,a*b):
		pref[i] = pref[i-1] + przyg[i]
	for query in range(q):
		l,r = map(int,input().split())
		ll = l%(a*b)
		rr = r%(a*b)
		wynik = cyk * (r//(a*b) - l//(a*b))
		wynik += pref[rr]
		if ll > 0:
			wynik -= pref[ll-1]
		if query < q-1:
			print(wynik, end = " ")
		else:
			print(wynik)


I found an interesting problem on https://codeforces.com/problemset/problem/1342/D:
So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem!

Initially, each test in that problem is just an array. The maximum size of an array is $k$. For simplicity, the contents of arrays don't matter. You have $n$ tests — the $i$-th test is an array of size $m_i$ ($1 \le m_i \le k$).

Your coordinator asks you to distribute all of your arrays into multiple testcases. Each testcase can include multiple arrays. However, each testcase should include no more than $c_1$ arrays of size greater than or equal to $1$ ($\ge 1$), no more than $c_2$ arrays of size greater than or equal to $2$, $\dots$, no more than $c_k$ arrays of size greater than or equal to $k$. Also, $c_1 \ge c_2 \ge \dots \ge c_k$.

So now your goal is to create the new testcases in such a way that:   each of the initial arrays appears in exactly one testcase;  for each testcase the given conditions hold;  the number of testcases is minimum possible.

Print the minimum possible number of testcases you can achieve and the sizes of arrays included in each testcase.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le n, k \le 2 \cdot 10^5$) — the number of initial tests and the limit for the size of each array.

The second line contains $n$ integers $m_1, m_2, \dots, m_n$ ($1 \le m_i \le k$) — the sizes of the arrays in the original tests.

The third line contains $k$ integers $c_1, c_2, \dots, c_k$ ($n \ge c_1 \ge c_2 \ge \dots \ge c_k \ge 1$); $c_i$ is the maximum number of arrays of size greater than or equal to $i$ you can have in a single testcase.

-----Output-----

In the first line print a single integer $ans$ ($1 \le ans \le n$) — the minimum number of testcases you can achieve.

Each of the next $ans$ lines should contain the description of a testcase in the following format:

$t$ $a_1$ $a_2$ $\dots$ $a_{t}$ ($1 \le t\le n$) — the testcase...

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

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

m = list(map(int,input().split()))
c = list(map(int,input().split()))

mi = []
for i in range(n):
    mi.append([m[i],i])
mi.sort()
mi.reverse()

ans = [[]]

for loop in range(n):

    now,ind = mi[loop]

    l = -1
    r = len(ans)

    while r-l != 1:

        mid = (l+r)//2
        if len(ans[mid]) < c[now-1]:
            r = mid
        else:
            l = mid

    if r == len(ans):
        ans.append([now])
    else:
        ans[r].append(now)

print(len(ans))
for i in ans:
    print(len(i),*i)


I found an interesting problem on https://codeforces.com/problemset/problem/1342/E:
Calculate the number of ways to place $n$ rooks on $n \times n$ chessboard so that both following conditions are met:

  each empty cell is under attack;  exactly $k$ pairs of rooks attack each other.

An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two rooks attack each other if they share the same row or column, and there are no other rooks between them. For example, there are only two pairs of rooks that attack each other in the following picture:

 [Image] One of the ways to place the rooks for $n = 3$ and $k = 2$

Two ways to place the rooks are considered different if there exists at least one cell which is empty in one of the ways but contains a rook in another way.

The answer might be large, so print it modulo $998244353$.

-----Input-----

The only line of the input contains two integers $n$ and $k$ ($1 \le n \le 200000$; $0 \le k \le \frac{n(n - 1)}{2}$).

-----Output-----

Print one integer — the number of ways to place the rooks, taken modulo $998244353$.

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

Output
6

Input
3 3

Output
0

Input
4 0

Output
24

Input
1337 42

Output
807905441

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

class Combination:
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        f = 1
        self.fac = fac = [f]
        for i in range(1, n_max+1):
            f = f * i % mod
            fac.append(f)
        f = pow(f, mod-2, mod)
        self.facinv = facinv = [f]
        for i in range(n_max, 0, -1):
            f = f * i % mod
            facinv.append(f)
        facinv.reverse()

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def C(self, n, r):
        if not 0 <= r <= n: return 0
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def P(self, n, r):
        if not 0 <= r <= n: return 0
        return self.fac[n] * self.facinv[n-r] % self.mod

    def H(self, n, r):
        if (n == 0 and r > 0) or r < 0: return 0
        return self.fac[n+r-1] * self.facinv[r] % self.mod * self.facinv[n-1] % self.mod

    def rising_factorial(self, n, r):
        return self.fac[n+r-1] * self.facinv[n-1] % self.mod

    def stirling_first(self, n, k):
        if n == k: return 1
        if k == 0: return 0
        return (self.stirling_first(n-1, k-1) + (n-1)*self.stirling_first(n-1, k)) % self.mod

    def stirling_second(self, n, k):
        if n == k: return 1
        return self.facinv[k] * sum((-1)**(k-m) * self.C(k, m) * pow(m, n, self.mod) for m in range(1, k+1)) % self.mod

    def balls_and_boxes_3(self, n, k):
        return sum((-1)**(k-m) * self.C(k, m) * pow(m, n, self.mod) for m in range(1, k+1)) % self.mod

    def bernoulli(self, n):
        if n == 0: return 1
        if n % 2 and n >= 3: return 0
        return (- pow(n+1, self.mod-2, self.mod) * sum(self.C(n+1, k) * self.bernoulli(k) % self.mod for k in range(n))) % self.mod

    def faulhaber(self, k, n):
        return pow(k+1, self.mod-2, self.mod) * sum(self.C(k+1, j) * self.bernoulli(j) % self.mod * pow(n, k-j+1, self.mod) % self.mod for j in range(k+1)) % self.mod

    def lah(self, n, k):
        return self.C(n-1,...


I found an interesting problem on https://codeforces.com/problemset/problem/1343/A:
Recently Vova found $n$ candy wrappers. He remembers that he bought $x$ candies during the first day, $2x$ candies during the second day, $4x$ candies during the third day, $\dots$, $2^{k-1} x$ candies during the $k$-th day. But there is an issue: Vova remembers neither $x$ nor $k$ but he is sure that $x$ and $k$ are positive integers and $k > 1$.

Vova will be satisfied if you tell him any positive integer $x$ so there is an integer $k>1$ that $x + 2x + 4x + \dots + 2^{k-1} x = n$. It is guaranteed that at least one solution exists. Note that $k > 1$.

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 one integer $n$ ($3 \le n \le 10^9$) — the number of candy wrappers Vova found. It is guaranteed that there is some positive integer $x$ and integer $k>1$ that $x + 2x + 4x + \dots + 2^{k-1} x = n$.

-----Output-----

Print one integer — any positive integer value of $x$ so there is an integer $k>1$ that $x + 2x + 4x + \dots + 2^{k-1} x = n$.

-----Example-----
Input
7
3
6
7
21
28
999999999
999999984

Output
1
2
1
7
4
333333333
333333328

-----Note-----

In the first test case of the example, one of the possible answers is $x=1, k=2$. Then $1 \cdot 1 + 2 \cdot 1$ equals $n=3$.

In the second test case of the example, one of the possible answers is $x=2, k=2$. Then $1 \cdot 2 + 2 \cdot 2$ equals $n=6$.

In the third test case of the example, one of the possible answers is $x=1, k=3$. Then $1 \cdot 1 + 2 \cdot 1 + 4 \cdot 1$ equals $n=7$.

In the fourth test case of the example, one of the possible answers is $x=7, k=2$. Then $1 \cdot 7 + 2 \cdot 7$ equals $n=21$.

In the fifth test case of the example, one of the possible answers is $x=4, k=3$. Then $1 \cdot 4 + 2 \cdot 4 + 4 \cdot 4$ equals $n=28$.

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

def solve():
    n = int(input())
    t = 2
    while True:
        k = 2**t - 1
        if n % k == 0:
            return n // k
        t += 1

#----
t = int(input())
for case in range(t):
    print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/1343/B:
You are given a positive integer $n$, it is guaranteed that $n$ is even (i.e. divisible by $2$).

You want to construct the array $a$ of length $n$ such that:   The first $\frac{n}{2}$ elements of $a$ are even (divisible by $2$);  the second $\frac{n}{2}$ elements of $a$ are odd (not divisible by $2$);  all elements of $a$ are distinct and positive;  the sum of the first half equals to the sum of the second half ($\sum\limits_{i=1}^{\frac{n}{2}} a_i = \sum\limits_{i=\frac{n}{2} + 1}^{n} a_i$).

If there are multiple answers, you can print any. It is not guaranteed that the answer exists.

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 one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the length of the array. It is guaranteed that that $n$ is even (i.e. divisible by $2$).

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

-----Output-----

For each test case, print the answer — "NO" (without quotes), if there is no suitable answer for the given test case or "YES" in the first line and any suitable array $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) satisfying conditions from the problem statement on the second line.

-----Example-----
Input
5
2
4
6
8
10

Output
NO
YES
2 4 1 5
NO
YES
2 4 6 8 1 3 5 11
NO

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

from math import *

for zz in range(int(input())):
    n = int(input())
    if n % 4 != 0:
        print('NO')
    else:
        print('YES')
        a = []
        cs = 0
        ce = 2
        for i in range(n//2):
            a.append(ce)
            cs += ce
            ce += 2
        ce = 1
        for i in range(n//2, n - 1):
            a.append(ce)
            cs -= ce
            ce += 2
        a.append(cs)
        print(*a)


I found an interesting problem on https://codeforces.com/problemset/problem/1343/C:
Recall that the sequence $b$ is a a subsequence of the sequence $a$ if $b$ can be derived from $a$ by removing zero or more elements without changing the order of the remaining elements. For example, if $a=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.

You are given a sequence $a$ consisting of $n$ positive and negative elements (there is no zeros in the sequence).

Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.

In other words, if the maximum length of alternating subsequence is $k$ then your task is to find the maximum sum of elements of some alternating subsequence of length $k$.

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 first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of elements in $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9, a_i \ne 0$), where $a_i$ is the $i$-th element of $a$.

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

-----Output-----

For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $a$.

-----Example-----
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000

Output
2
-1
6
-2999999997

-----Note-----

In the first test case of the example, one of the possible answers is $[1, 2, \underline{3}, \underline{-1}, -2]$.

In the second...

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

for _ in range(int(input())):
    n=int(input())
    l=list(map(int,input().split()))
    a=[]
    lis=[]
    prevsign=-1
    if l[0]>0:
        prevsign=1
    else:
        prevsign=0
    i=0
    for i in l:
        if (i>0 and prevsign==1) or (i<0 and prevsign==0):
            lis.append(i)
        else:
            if prevsign==1:
                a.append(max(lis))
                lis=[]
                lis.append(i)
                prevsign=0
            else:
                a.append(max(lis))
                lis=[]
                lis.append(i)
                prevsign=1

    if prevsign==1:
        a.append(max(lis))
        lis=[]
        lis.append(i)
        prevsign=0
    else:
        a.append(max(lis))
        lis=[]
        lis.append(i)
        prevsign=1
    print(sum(a))


I found an interesting problem on https://codeforces.com/problemset/problem/1344/B:
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.

There is an $n\times m$ grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.

An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.

Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.

  There is at least one south magnet in every row and every column.  If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.  If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.

Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).

-----Input-----

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

The next $n$ lines describe the coloring. The $i$-th of these lines contains a string of length $m$, where the $j$-th character denotes the color of the cell in row $i$ and column $j$. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.

-----Output-----

Output a single integer, the minimum possible...

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

from collections import deque
import sys
def input():
	return sys.stdin.readline()[:-1]
n, m = map(int, input().split())
s = ["." * (m+2)] +  ["." + input() + "." for _ in range(n)] + ["." * (m+2)]
ok = True
num = 0
n_zero = 0
for i in range(1, n+1):
	p = s[i].count("#")
	num += p
	if p == 0:
		n_zero += 1

m_zero = 0
for j in range(1, m+1):
	for i in range(1, n+1):
		if s[i][j] == "#":
			break
	else:
		m_zero += 1

if n_zero * m_zero == 0 and n_zero + m_zero > 0:
	print(-1)
	return
if num == 0:
	print(0)
	return

for i in range(n+2):
	already = False
	for j in range(1, m+2):
		if already and s[i][j] == "#":
			ok = False
			break
		elif s[i][j-1] == "#" and s[i][j] == ".":
			already = True
	if not ok:
		break

for j in range(m+2):
	already = False
	for i in range(1, n+2):
		if already and s[i][j] == "#":
			ok = False
			break
		elif s[i-1][j] == "#" and s[i][j] == ".":
			already = True
	if not ok:
		break

if not ok:
	print(-1)
	return

cnt = 0
visited = [[False for _ in range(m+2)] for _ in range(n+2)]
DI = [1, 0, -1, 0]
DJ = [0, 1, 0, -1]

def bfs(x, y):
	q = deque([x*(m+2)+y])
	while q:
		l = q.popleft()
		i, j = l//(m+2), l%(m+2)
		for di, dj in zip(DI, DJ):
			if s[i+di][j+dj] == "#" and visited[i+di][j+dj] == False:
				visited[i+di][j+dj] = True
				q.append((i+di)*(m+2) + j+dj)
	return

for i in range(n+2):
	for j in range(m+2):
		if s[i][j] == "#" and visited[i][j] == False:
			cnt += 1
			visited[i][j] = True
			bfs(i, j)

print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/1345/B:
A card pyramid of height $1$ is constructed by resting two cards against each other. For $h>1$, a card pyramid of height $h$ is constructed by placing a card pyramid of height $h-1$ onto a base. A base consists of $h$ pyramids of height $1$, and $h-1$ cards on top. For example, card pyramids of heights $1$, $2$, and $3$ look as follows: $\wedge A A$

You start with $n$ cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?

-----Input-----

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

Each test case contains a single integer $n$ ($1\le n\le 10^9$) — the number of cards.

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

-----Output-----

For each test case output a single integer — the number of pyramids you will have constructed in the end.

-----Example-----
Input
5
3
14
15
24
1

Output
1
2
1
3
0

-----Note-----

In the first test, you construct a pyramid of height $1$ with $2$ cards. There is $1$ card remaining, which is not enough to build a pyramid.

In the second test, you build two pyramids, each of height $2$, with no cards remaining.

In the third test, you build one pyramid of height $3$, with no cards remaining.

In the fourth test, you build one pyramid of height $3$ with $9$ cards remaining. Then you build a pyramid of height $2$ with $2$ cards remaining. Then you build a final pyramid of height $1$ with no cards remaining.

In the fifth test, one card is not enough to build any pyramids.

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

import math as m
def func(a):
    return int((m.sqrt(24*a+1)-1)//6)

t=int(input())
for _ in range(t):
    n=int(input())
    c=0
    while n>1:
        a=func(n)
        n=n-(3*a*a+a)//2
        c=c+1
    print(c)